]>
Commit | Line | Data |
---|---|---|
1a4d82fc JJ |
1 | //! A priority queue implemented with a binary heap. |
2 | //! | |
3dfed10e XL |
3 | //! Insertion and popping the largest element have *O*(log(*n*)) time complexity. |
4 | //! Checking the largest element is *O*(1). Converting a vector to a binary heap | |
5 | //! can be done in-place, and has *O*(*n*) complexity. A binary heap can also be | |
6 | //! converted to a sorted vector in-place, allowing it to be used for an *O*(*n* \* log(*n*)) | |
ba9703b0 | 7 | //! in-place heapsort. |
1a4d82fc JJ |
8 | //! |
9 | //! # Examples | |
10 | //! | |
11 | //! This is a larger example that implements [Dijkstra's algorithm][dijkstra] | |
12 | //! to solve the [shortest path problem][sssp] on a [directed graph][dir_graph]. | |
cc61c64b | 13 | //! It shows how to use [`BinaryHeap`] with custom types. |
1a4d82fc | 14 | //! |
3dfed10e XL |
15 | //! [dijkstra]: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm |
16 | //! [sssp]: https://en.wikipedia.org/wiki/Shortest_path_problem | |
17 | //! [dir_graph]: https://en.wikipedia.org/wiki/Directed_graph | |
1a4d82fc JJ |
18 | //! |
19 | //! ``` | |
20 | //! use std::cmp::Ordering; | |
21 | //! use std::collections::BinaryHeap; | |
1a4d82fc | 22 | //! |
c34b1796 | 23 | //! #[derive(Copy, Clone, Eq, PartialEq)] |
1a4d82fc | 24 | //! struct State { |
85aaf69f SL |
25 | //! cost: usize, |
26 | //! position: usize, | |
1a4d82fc JJ |
27 | //! } |
28 | //! | |
29 | //! // The priority queue depends on `Ord`. | |
30 | //! // Explicitly implement the trait so the queue becomes a min-heap | |
31 | //! // instead of a max-heap. | |
32 | //! impl Ord for State { | |
1b1a35ee | 33 | //! fn cmp(&self, other: &Self) -> Ordering { |
7cac9316 XL |
34 | //! // Notice that the we flip the ordering on costs. |
35 | //! // In case of a tie we compare positions - this step is necessary | |
36 | //! // to make implementations of `PartialEq` and `Ord` consistent. | |
1a4d82fc | 37 | //! other.cost.cmp(&self.cost) |
7cac9316 | 38 | //! .then_with(|| self.position.cmp(&other.position)) |
1a4d82fc JJ |
39 | //! } |
40 | //! } | |
41 | //! | |
42 | //! // `PartialOrd` needs to be implemented as well. | |
43 | //! impl PartialOrd for State { | |
1b1a35ee | 44 | //! fn partial_cmp(&self, other: &Self) -> Option<Ordering> { |
1a4d82fc JJ |
45 | //! Some(self.cmp(other)) |
46 | //! } | |
47 | //! } | |
48 | //! | |
85aaf69f | 49 | //! // Each node is represented as an `usize`, for a shorter implementation. |
1a4d82fc | 50 | //! struct Edge { |
85aaf69f SL |
51 | //! node: usize, |
52 | //! cost: usize, | |
1a4d82fc JJ |
53 | //! } |
54 | //! | |
55 | //! // Dijkstra's shortest path algorithm. | |
56 | //! | |
57 | //! // Start at `start` and use `dist` to track the current shortest distance | |
58 | //! // to each node. This implementation isn't memory-efficient as it may leave duplicate | |
85aaf69f | 59 | //! // nodes in the queue. It also uses `usize::MAX` as a sentinel value, |
1a4d82fc | 60 | //! // for a simpler implementation. |
9cc50fc6 | 61 | //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> Option<usize> { |
1a4d82fc | 62 | //! // dist[node] = current shortest distance from `start` to `node` |
85aaf69f | 63 | //! let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect(); |
1a4d82fc JJ |
64 | //! |
65 | //! let mut heap = BinaryHeap::new(); | |
66 | //! | |
67 | //! // We're at `start`, with a zero cost | |
68 | //! dist[start] = 0; | |
69 | //! heap.push(State { cost: 0, position: start }); | |
70 | //! | |
71 | //! // Examine the frontier with lower cost nodes first (min-heap) | |
72 | //! while let Some(State { cost, position }) = heap.pop() { | |
73 | //! // Alternatively we could have continued to find all shortest paths | |
9cc50fc6 | 74 | //! if position == goal { return Some(cost); } |
1a4d82fc JJ |
75 | //! |
76 | //! // Important as we may have already found a better way | |
77 | //! if cost > dist[position] { continue; } | |
78 | //! | |
79 | //! // For each node we can reach, see if we can find a way with | |
80 | //! // a lower cost going through this node | |
62682a34 | 81 | //! for edge in &adj_list[position] { |
1a4d82fc JJ |
82 | //! let next = State { cost: cost + edge.cost, position: edge.node }; |
83 | //! | |
84 | //! // If so, add it to the frontier and continue | |
85 | //! if next.cost < dist[next.position] { | |
86 | //! heap.push(next); | |
87 | //! // Relaxation, we have now found a better way | |
88 | //! dist[next.position] = next.cost; | |
89 | //! } | |
90 | //! } | |
91 | //! } | |
92 | //! | |
93 | //! // Goal not reachable | |
9cc50fc6 | 94 | //! None |
1a4d82fc JJ |
95 | //! } |
96 | //! | |
97 | //! fn main() { | |
98 | //! // This is the directed graph we're going to use. | |
99 | //! // The node numbers correspond to the different states, | |
100 | //! // and the edge weights symbolize the cost of moving | |
101 | //! // from one node to another. | |
102 | //! // Note that the edges are one-way. | |
103 | //! // | |
104 | //! // 7 | |
105 | //! // +-----------------+ | |
106 | //! // | | | |
e9174d1e | 107 | //! // v 1 2 | 2 |
1a4d82fc JJ |
108 | //! // 0 -----> 1 -----> 3 ---> 4 |
109 | //! // | ^ ^ ^ | |
110 | //! // | | 1 | | | |
111 | //! // | | | 3 | 1 | |
112 | //! // +------> 2 -------+ | | |
113 | //! // 10 | | | |
114 | //! // +---------------+ | |
115 | //! // | |
116 | //! // The graph is represented as an adjacency list where each index, | |
117 | //! // corresponding to a node value, has a list of outgoing edges. | |
118 | //! // Chosen for its efficiency. | |
119 | //! let graph = vec![ | |
120 | //! // Node 0 | |
121 | //! vec![Edge { node: 2, cost: 10 }, | |
122 | //! Edge { node: 1, cost: 1 }], | |
123 | //! // Node 1 | |
124 | //! vec![Edge { node: 3, cost: 2 }], | |
125 | //! // Node 2 | |
126 | //! vec![Edge { node: 1, cost: 1 }, | |
127 | //! Edge { node: 3, cost: 3 }, | |
128 | //! Edge { node: 4, cost: 1 }], | |
129 | //! // Node 3 | |
130 | //! vec![Edge { node: 0, cost: 7 }, | |
131 | //! Edge { node: 4, cost: 2 }], | |
132 | //! // Node 4 | |
133 | //! vec![]]; | |
134 | //! | |
9cc50fc6 SL |
135 | //! assert_eq!(shortest_path(&graph, 0, 1), Some(1)); |
136 | //! assert_eq!(shortest_path(&graph, 0, 3), Some(3)); | |
137 | //! assert_eq!(shortest_path(&graph, 3, 0), Some(7)); | |
138 | //! assert_eq!(shortest_path(&graph, 0, 4), Some(5)); | |
139 | //! assert_eq!(shortest_path(&graph, 4, 0), None); | |
1a4d82fc JJ |
140 | //! } |
141 | //! ``` | |
142 | ||
143 | #![allow(missing_docs)] | |
85aaf69f | 144 | #![stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 145 | |
dfeec247 | 146 | use core::fmt; |
1b1a35ee XL |
147 | use core::iter::{FromIterator, FusedIterator, InPlaceIterable, SourceIter, TrustedLen}; |
148 | use core::mem::{self, swap, ManuallyDrop}; | |
dfeec247 | 149 | use core::ops::{Deref, DerefMut}; |
1a4d82fc JJ |
150 | use core::ptr; |
151 | ||
9fa01778 | 152 | use crate::slice; |
1b1a35ee | 153 | use crate::vec::{self, AsIntoIter, Vec}; |
1a4d82fc | 154 | |
a7813a04 XL |
155 | use super::SpecExtend; |
156 | ||
1a4d82fc JJ |
157 | /// A priority queue implemented with a binary heap. |
158 | /// | |
159 | /// This will be a max-heap. | |
c34b1796 AL |
160 | /// |
161 | /// It is a logic error for an item to be modified in such a way that the | |
162 | /// item's ordering relative to any other item, as determined by the `Ord` | |
163 | /// trait, changes while it is in the heap. This is normally only possible | |
164 | /// through `Cell`, `RefCell`, global state, I/O, or unsafe code. | |
54a0048b SL |
165 | /// |
166 | /// # Examples | |
167 | /// | |
168 | /// ``` | |
169 | /// use std::collections::BinaryHeap; | |
170 | /// | |
171 | /// // Type inference lets us omit an explicit type signature (which | |
172 | /// // would be `BinaryHeap<i32>` in this example). | |
173 | /// let mut heap = BinaryHeap::new(); | |
174 | /// | |
175 | /// // We can use peek to look at the next item in the heap. In this case, | |
176 | /// // there's no items in there yet so we get None. | |
177 | /// assert_eq!(heap.peek(), None); | |
178 | /// | |
179 | /// // Let's add some scores... | |
180 | /// heap.push(1); | |
181 | /// heap.push(5); | |
182 | /// heap.push(2); | |
183 | /// | |
184 | /// // Now peek shows the most important item in the heap. | |
185 | /// assert_eq!(heap.peek(), Some(&5)); | |
186 | /// | |
187 | /// // We can check the length of a heap. | |
188 | /// assert_eq!(heap.len(), 3); | |
189 | /// | |
190 | /// // We can iterate over the items in the heap, although they are returned in | |
191 | /// // a random order. | |
192 | /// for x in &heap { | |
193 | /// println!("{}", x); | |
194 | /// } | |
195 | /// | |
196 | /// // If we instead pop these scores, they should come back in order. | |
197 | /// assert_eq!(heap.pop(), Some(5)); | |
198 | /// assert_eq!(heap.pop(), Some(2)); | |
199 | /// assert_eq!(heap.pop(), Some(1)); | |
200 | /// assert_eq!(heap.pop(), None); | |
201 | /// | |
202 | /// // We can clear the heap of any remaining items. | |
203 | /// heap.clear(); | |
204 | /// | |
205 | /// // The heap should now be empty. | |
206 | /// assert!(heap.is_empty()) | |
207 | /// ``` | |
48663c56 XL |
208 | /// |
209 | /// ## Min-heap | |
210 | /// | |
211 | /// Either `std::cmp::Reverse` or a custom `Ord` implementation can be used to | |
212 | /// make `BinaryHeap` a min-heap. This makes `heap.pop()` return the smallest | |
213 | /// value instead of the greatest one. | |
214 | /// | |
215 | /// ``` | |
216 | /// use std::collections::BinaryHeap; | |
217 | /// use std::cmp::Reverse; | |
218 | /// | |
219 | /// let mut heap = BinaryHeap::new(); | |
220 | /// | |
221 | /// // Wrap values in `Reverse` | |
222 | /// heap.push(Reverse(1)); | |
223 | /// heap.push(Reverse(5)); | |
224 | /// heap.push(Reverse(2)); | |
225 | /// | |
226 | /// // If we pop these scores now, they should come back in the reverse order. | |
227 | /// assert_eq!(heap.pop(), Some(Reverse(1))); | |
228 | /// assert_eq!(heap.pop(), Some(Reverse(2))); | |
229 | /// assert_eq!(heap.pop(), Some(Reverse(5))); | |
230 | /// assert_eq!(heap.pop(), None); | |
231 | /// ``` | |
232 | /// | |
233 | /// # Time complexity | |
234 | /// | |
ba9703b0 XL |
235 | /// | [push] | [pop] | [peek]/[peek\_mut] | |
236 | /// |--------|-----------|--------------------| | |
3dfed10e | 237 | /// | O(1)~ | *O*(log(*n*)) | *O*(1) | |
48663c56 XL |
238 | /// |
239 | /// The value for `push` is an expected cost; the method documentation gives a | |
240 | /// more detailed analysis. | |
241 | /// | |
1b1a35ee XL |
242 | /// [push]: BinaryHeap::push |
243 | /// [pop]: BinaryHeap::pop | |
244 | /// [peek]: BinaryHeap::peek | |
245 | /// [peek\_mut]: BinaryHeap::peek_mut | |
85aaf69f | 246 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
247 | pub struct BinaryHeap<T> { |
248 | data: Vec<T>, | |
249 | } | |
250 | ||
cc61c64b XL |
251 | /// Structure wrapping a mutable reference to the greatest item on a |
252 | /// `BinaryHeap`. | |
3157f602 | 253 | /// |
cc61c64b XL |
254 | /// This `struct` is created by the [`peek_mut`] method on [`BinaryHeap`]. See |
255 | /// its documentation for more. | |
256 | /// | |
1b1a35ee | 257 | /// [`peek_mut`]: BinaryHeap::peek_mut |
5bcae85e | 258 | #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")] |
3157f602 | 259 | pub struct PeekMut<'a, T: 'a + Ord> { |
32a655c1 SL |
260 | heap: &'a mut BinaryHeap<T>, |
261 | sift: bool, | |
3157f602 XL |
262 | } |
263 | ||
8bb4bdeb | 264 | #[stable(feature = "collection_debug", since = "1.17.0")] |
9fa01778 XL |
265 | impl<T: Ord + fmt::Debug> fmt::Debug for PeekMut<'_, T> { |
266 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
dfeec247 | 267 | f.debug_tuple("PeekMut").field(&self.heap.data[0]).finish() |
8bb4bdeb XL |
268 | } |
269 | } | |
270 | ||
5bcae85e | 271 | #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")] |
9fa01778 | 272 | impl<T: Ord> Drop for PeekMut<'_, T> { |
3157f602 | 273 | fn drop(&mut self) { |
32a655c1 SL |
274 | if self.sift { |
275 | self.heap.sift_down(0); | |
276 | } | |
3157f602 XL |
277 | } |
278 | } | |
279 | ||
5bcae85e | 280 | #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")] |
9fa01778 | 281 | impl<T: Ord> Deref for PeekMut<'_, T> { |
3157f602 XL |
282 | type Target = T; |
283 | fn deref(&self) -> &T { | |
9fa01778 XL |
284 | debug_assert!(!self.heap.is_empty()); |
285 | // SAFE: PeekMut is only instantiated for non-empty heaps | |
286 | unsafe { self.heap.data.get_unchecked(0) } | |
3157f602 XL |
287 | } |
288 | } | |
289 | ||
5bcae85e | 290 | #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")] |
9fa01778 | 291 | impl<T: Ord> DerefMut for PeekMut<'_, T> { |
3157f602 | 292 | fn deref_mut(&mut self) -> &mut T { |
9fa01778 | 293 | debug_assert!(!self.heap.is_empty()); |
1b1a35ee | 294 | self.sift = true; |
9fa01778 XL |
295 | // SAFE: PeekMut is only instantiated for non-empty heaps |
296 | unsafe { self.heap.data.get_unchecked_mut(0) } | |
3157f602 XL |
297 | } |
298 | } | |
299 | ||
32a655c1 SL |
300 | impl<'a, T: Ord> PeekMut<'a, T> { |
301 | /// Removes the peeked value from the heap and returns it. | |
cc61c64b | 302 | #[stable(feature = "binary_heap_peek_mut_pop", since = "1.18.0")] |
32a655c1 SL |
303 | pub fn pop(mut this: PeekMut<'a, T>) -> T { |
304 | let value = this.heap.pop().unwrap(); | |
305 | this.sift = false; | |
306 | value | |
307 | } | |
308 | } | |
309 | ||
b039eaaf SL |
310 | #[stable(feature = "rust1", since = "1.0.0")] |
311 | impl<T: Clone> Clone for BinaryHeap<T> { | |
312 | fn clone(&self) -> Self { | |
313 | BinaryHeap { data: self.data.clone() } | |
314 | } | |
315 | ||
316 | fn clone_from(&mut self, source: &Self) { | |
317 | self.data.clone_from(&source.data); | |
318 | } | |
319 | } | |
320 | ||
85aaf69f | 321 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 322 | impl<T: Ord> Default for BinaryHeap<T> { |
9e0c209e | 323 | /// Creates an empty `BinaryHeap<T>`. |
1a4d82fc | 324 | #[inline] |
92a42be0 SL |
325 | fn default() -> BinaryHeap<T> { |
326 | BinaryHeap::new() | |
327 | } | |
1a4d82fc JJ |
328 | } |
329 | ||
e9174d1e | 330 | #[stable(feature = "binaryheap_debug", since = "1.4.0")] |
9fa01778 XL |
331 | impl<T: fmt::Debug> fmt::Debug for BinaryHeap<T> { |
332 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
e9174d1e SL |
333 | f.debug_list().entries(self.iter()).finish() |
334 | } | |
335 | } | |
336 | ||
1a4d82fc JJ |
337 | impl<T: Ord> BinaryHeap<T> { |
338 | /// Creates an empty `BinaryHeap` as a max-heap. | |
339 | /// | |
340 | /// # Examples | |
341 | /// | |
54a0048b SL |
342 | /// Basic usage: |
343 | /// | |
1a4d82fc JJ |
344 | /// ``` |
345 | /// use std::collections::BinaryHeap; | |
346 | /// let mut heap = BinaryHeap::new(); | |
85aaf69f | 347 | /// heap.push(4); |
1a4d82fc | 348 | /// ``` |
85aaf69f | 349 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
350 | pub fn new() -> BinaryHeap<T> { |
351 | BinaryHeap { data: vec![] } | |
352 | } | |
1a4d82fc JJ |
353 | |
354 | /// Creates an empty `BinaryHeap` with a specific capacity. | |
355 | /// This preallocates enough memory for `capacity` elements, | |
356 | /// so that the `BinaryHeap` does not have to be reallocated | |
357 | /// until it contains at least that many values. | |
358 | /// | |
359 | /// # Examples | |
360 | /// | |
54a0048b SL |
361 | /// Basic usage: |
362 | /// | |
1a4d82fc JJ |
363 | /// ``` |
364 | /// use std::collections::BinaryHeap; | |
365 | /// let mut heap = BinaryHeap::with_capacity(10); | |
85aaf69f | 366 | /// heap.push(4); |
1a4d82fc | 367 | /// ``` |
85aaf69f SL |
368 | #[stable(feature = "rust1", since = "1.0.0")] |
369 | pub fn with_capacity(capacity: usize) -> BinaryHeap<T> { | |
1a4d82fc JJ |
370 | BinaryHeap { data: Vec::with_capacity(capacity) } |
371 | } | |
372 | ||
3157f602 XL |
373 | /// Returns a mutable reference to the greatest item in the binary heap, or |
374 | /// `None` if it is empty. | |
375 | /// | |
376 | /// Note: If the `PeekMut` value is leaked, the heap may be in an | |
377 | /// inconsistent state. | |
378 | /// | |
379 | /// # Examples | |
380 | /// | |
381 | /// Basic usage: | |
382 | /// | |
383 | /// ``` | |
3157f602 XL |
384 | /// use std::collections::BinaryHeap; |
385 | /// let mut heap = BinaryHeap::new(); | |
386 | /// assert!(heap.peek_mut().is_none()); | |
387 | /// | |
388 | /// heap.push(1); | |
389 | /// heap.push(5); | |
390 | /// heap.push(2); | |
391 | /// { | |
392 | /// let mut val = heap.peek_mut().unwrap(); | |
393 | /// *val = 0; | |
394 | /// } | |
395 | /// assert_eq!(heap.peek(), Some(&2)); | |
396 | /// ``` | |
48663c56 XL |
397 | /// |
398 | /// # Time complexity | |
399 | /// | |
1b1a35ee XL |
400 | /// If the item is modified then the worst case time complexity is *O*(log(*n*)), |
401 | /// otherwise it's *O*(1). | |
5bcae85e | 402 | #[stable(feature = "binary_heap_peek_mut", since = "1.12.0")] |
9fa01778 | 403 | pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T>> { |
1b1a35ee | 404 | if self.is_empty() { None } else { Some(PeekMut { heap: self, sift: false }) } |
3157f602 XL |
405 | } |
406 | ||
1a4d82fc JJ |
407 | /// Removes the greatest item from the binary heap and returns it, or `None` if it |
408 | /// is empty. | |
409 | /// | |
410 | /// # Examples | |
411 | /// | |
54a0048b SL |
412 | /// Basic usage: |
413 | /// | |
1a4d82fc JJ |
414 | /// ``` |
415 | /// use std::collections::BinaryHeap; | |
b039eaaf | 416 | /// let mut heap = BinaryHeap::from(vec![1, 3]); |
1a4d82fc JJ |
417 | /// |
418 | /// assert_eq!(heap.pop(), Some(3)); | |
419 | /// assert_eq!(heap.pop(), Some(1)); | |
420 | /// assert_eq!(heap.pop(), None); | |
421 | /// ``` | |
48663c56 XL |
422 | /// |
423 | /// # Time complexity | |
424 | /// | |
3dfed10e | 425 | /// The worst case cost of `pop` on a heap containing *n* elements is *O*(log(*n*)). |
85aaf69f | 426 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
427 | pub fn pop(&mut self) -> Option<T> { |
428 | self.data.pop().map(|mut item| { | |
429 | if !self.is_empty() { | |
430 | swap(&mut item, &mut self.data[0]); | |
9cc50fc6 | 431 | self.sift_down_to_bottom(0); |
1a4d82fc JJ |
432 | } |
433 | item | |
434 | }) | |
435 | } | |
436 | ||
437 | /// Pushes an item onto the binary heap. | |
438 | /// | |
439 | /// # Examples | |
440 | /// | |
54a0048b SL |
441 | /// Basic usage: |
442 | /// | |
1a4d82fc JJ |
443 | /// ``` |
444 | /// use std::collections::BinaryHeap; | |
445 | /// let mut heap = BinaryHeap::new(); | |
85aaf69f | 446 | /// heap.push(3); |
1a4d82fc JJ |
447 | /// heap.push(5); |
448 | /// heap.push(1); | |
449 | /// | |
450 | /// assert_eq!(heap.len(), 3); | |
451 | /// assert_eq!(heap.peek(), Some(&5)); | |
452 | /// ``` | |
48663c56 XL |
453 | /// |
454 | /// # Time complexity | |
455 | /// | |
456 | /// The expected cost of `push`, averaged over every possible ordering of | |
457 | /// the elements being pushed, and over a sufficiently large number of | |
3dfed10e | 458 | /// pushes, is *O*(1). This is the most meaningful cost metric when pushing |
48663c56 XL |
459 | /// elements that are *not* already in any sorted pattern. |
460 | /// | |
461 | /// The time complexity degrades if elements are pushed in predominantly | |
462 | /// ascending order. In the worst case, elements are pushed in ascending | |
3dfed10e | 463 | /// sorted order and the amortized cost per push is *O*(log(*n*)) against a heap |
48663c56 XL |
464 | /// containing *n* elements. |
465 | /// | |
3dfed10e | 466 | /// The worst case cost of a *single* call to `push` is *O*(*n*). The worst case |
48663c56 XL |
467 | /// occurs when capacity is exhausted and needs a resize. The resize cost |
468 | /// has been amortized in the previous figures. | |
85aaf69f | 469 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
470 | pub fn push(&mut self, item: T) { |
471 | let old_len = self.len(); | |
472 | self.data.push(item); | |
473 | self.sift_up(0, old_len); | |
474 | } | |
475 | ||
1a4d82fc JJ |
476 | /// Consumes the `BinaryHeap` and returns a vector in sorted |
477 | /// (ascending) order. | |
478 | /// | |
479 | /// # Examples | |
480 | /// | |
54a0048b SL |
481 | /// Basic usage: |
482 | /// | |
1a4d82fc JJ |
483 | /// ``` |
484 | /// use std::collections::BinaryHeap; | |
485 | /// | |
b039eaaf | 486 | /// let mut heap = BinaryHeap::from(vec![1, 2, 4, 5, 7]); |
1a4d82fc JJ |
487 | /// heap.push(6); |
488 | /// heap.push(3); | |
489 | /// | |
490 | /// let vec = heap.into_sorted_vec(); | |
c34b1796 | 491 | /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]); |
1a4d82fc | 492 | /// ``` |
b039eaaf | 493 | #[stable(feature = "binary_heap_extras_15", since = "1.5.0")] |
1a4d82fc JJ |
494 | pub fn into_sorted_vec(mut self) -> Vec<T> { |
495 | let mut end = self.len(); | |
496 | while end > 1 { | |
497 | end -= 1; | |
29967ef6 XL |
498 | // SAFETY: `end` goes from `self.len() - 1` to 1 (both included), |
499 | // so it's always a valid index to access. | |
500 | // It is safe to access index 0 (i.e. `ptr`), because | |
501 | // 1 <= end < self.len(), which means self.len() >= 2. | |
502 | unsafe { | |
503 | let ptr = self.data.as_mut_ptr(); | |
504 | ptr::swap(ptr, ptr.add(end)); | |
505 | } | |
1a4d82fc JJ |
506 | self.sift_down_range(0, end); |
507 | } | |
508 | self.into_vec() | |
509 | } | |
510 | ||
511 | // The implementations of sift_up and sift_down use unsafe blocks in | |
512 | // order to move an element out of the vector (leaving behind a | |
d9579d0f AL |
513 | // hole), shift along the others and move the removed element back into the |
514 | // vector at the final location of the hole. | |
515 | // The `Hole` type is used to represent this, and make sure | |
516 | // the hole is filled back at the end of its scope, even on panic. | |
517 | // Using a hole reduces the constant factor compared to using swaps, | |
518 | // which involves twice as many moves. | |
32a655c1 | 519 | fn sift_up(&mut self, start: usize, pos: usize) -> usize { |
1a4d82fc | 520 | unsafe { |
d9579d0f AL |
521 | // Take out the value at `pos` and create a hole. |
522 | let mut hole = Hole::new(&mut self.data, pos); | |
1a4d82fc | 523 | |
d9579d0f AL |
524 | while hole.pos() > start { |
525 | let parent = (hole.pos() - 1) / 2; | |
92a42be0 SL |
526 | if hole.element() <= hole.get(parent) { |
527 | break; | |
528 | } | |
d9579d0f | 529 | hole.move_to(parent); |
1a4d82fc | 530 | } |
32a655c1 | 531 | hole.pos() |
1a4d82fc JJ |
532 | } |
533 | } | |
534 | ||
92a42be0 SL |
535 | /// Take an element at `pos` and move it down the heap, |
536 | /// while its children are larger. | |
537 | fn sift_down_range(&mut self, pos: usize, end: usize) { | |
1a4d82fc | 538 | unsafe { |
d9579d0f | 539 | let mut hole = Hole::new(&mut self.data, pos); |
1a4d82fc | 540 | let mut child = 2 * pos + 1; |
29967ef6 | 541 | while child < end - 1 { |
92a42be0 | 542 | // compare with the greater of the two children |
29967ef6 | 543 | child += (hole.get(child) <= hole.get(child + 1)) as usize; |
92a42be0 SL |
544 | // if we are already in order, stop. |
545 | if hole.element() >= hole.get(child) { | |
29967ef6 | 546 | return; |
92a42be0 | 547 | } |
d9579d0f AL |
548 | hole.move_to(child); |
549 | child = 2 * hole.pos() + 1; | |
1a4d82fc | 550 | } |
29967ef6 XL |
551 | if child == end - 1 && hole.element() < hole.get(child) { |
552 | hole.move_to(child); | |
553 | } | |
1a4d82fc JJ |
554 | } |
555 | } | |
556 | ||
85aaf69f | 557 | fn sift_down(&mut self, pos: usize) { |
1a4d82fc JJ |
558 | let len = self.len(); |
559 | self.sift_down_range(pos, len); | |
560 | } | |
561 | ||
9cc50fc6 SL |
562 | /// Take an element at `pos` and move it all the way down the heap, |
563 | /// then sift it up to its position. | |
564 | /// | |
565 | /// Note: This is faster when the element is known to be large / should | |
566 | /// be closer to the bottom. | |
567 | fn sift_down_to_bottom(&mut self, mut pos: usize) { | |
568 | let end = self.len(); | |
569 | let start = pos; | |
570 | unsafe { | |
571 | let mut hole = Hole::new(&mut self.data, pos); | |
572 | let mut child = 2 * pos + 1; | |
29967ef6 XL |
573 | while child < end - 1 { |
574 | child += (hole.get(child) <= hole.get(child + 1)) as usize; | |
9cc50fc6 SL |
575 | hole.move_to(child); |
576 | child = 2 * hole.pos() + 1; | |
577 | } | |
29967ef6 XL |
578 | if child == end - 1 { |
579 | hole.move_to(child); | |
580 | } | |
9cc50fc6 SL |
581 | pos = hole.pos; |
582 | } | |
583 | self.sift_up(start, pos); | |
584 | } | |
585 | ||
9fa01778 XL |
586 | fn rebuild(&mut self) { |
587 | let mut n = self.len() / 2; | |
588 | while n > 0 { | |
589 | n -= 1; | |
590 | self.sift_down(n); | |
591 | } | |
592 | } | |
593 | ||
594 | /// Moves all the elements of `other` into `self`, leaving `other` empty. | |
595 | /// | |
596 | /// # Examples | |
597 | /// | |
598 | /// Basic usage: | |
599 | /// | |
600 | /// ``` | |
601 | /// use std::collections::BinaryHeap; | |
602 | /// | |
603 | /// let v = vec![-10, 1, 2, 3, 3]; | |
604 | /// let mut a = BinaryHeap::from(v); | |
605 | /// | |
606 | /// let v = vec![-20, 5, 43]; | |
607 | /// let mut b = BinaryHeap::from(v); | |
608 | /// | |
609 | /// a.append(&mut b); | |
610 | /// | |
611 | /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]); | |
612 | /// assert!(b.is_empty()); | |
613 | /// ``` | |
614 | #[stable(feature = "binary_heap_append", since = "1.11.0")] | |
615 | pub fn append(&mut self, other: &mut Self) { | |
616 | if self.len() < other.len() { | |
617 | swap(self, other); | |
618 | } | |
619 | ||
620 | if other.is_empty() { | |
621 | return; | |
622 | } | |
623 | ||
624 | #[inline(always)] | |
625 | fn log2_fast(x: usize) -> usize { | |
1b1a35ee | 626 | (usize::BITS - x.leading_zeros() - 1) as usize |
9fa01778 XL |
627 | } |
628 | ||
629 | // `rebuild` takes O(len1 + len2) operations | |
630 | // and about 2 * (len1 + len2) comparisons in the worst case | |
ba9703b0 | 631 | // while `extend` takes O(len2 * log(len1)) operations |
9fa01778 XL |
632 | // and about 1 * len2 * log_2(len1) comparisons in the worst case, |
633 | // assuming len1 >= len2. | |
634 | #[inline] | |
635 | fn better_to_rebuild(len1: usize, len2: usize) -> bool { | |
636 | 2 * (len1 + len2) < len2 * log2_fast(len1) | |
637 | } | |
638 | ||
639 | if better_to_rebuild(self.len(), other.len()) { | |
640 | self.data.append(&mut other.data); | |
641 | self.rebuild(); | |
642 | } else { | |
643 | self.extend(other.drain()); | |
644 | } | |
645 | } | |
e74abb32 XL |
646 | |
647 | /// Returns an iterator which retrieves elements in heap order. | |
648 | /// The retrieved elements are removed from the original heap. | |
649 | /// The remaining elements will be removed on drop in heap order. | |
650 | /// | |
651 | /// Note: | |
3dfed10e | 652 | /// * `.drain_sorted()` is *O*(*n* \* log(*n*)); much slower than `.drain()`. |
e74abb32 XL |
653 | /// You should use the latter for most cases. |
654 | /// | |
655 | /// # Examples | |
656 | /// | |
657 | /// Basic usage: | |
658 | /// | |
659 | /// ``` | |
660 | /// #![feature(binary_heap_drain_sorted)] | |
661 | /// use std::collections::BinaryHeap; | |
662 | /// | |
663 | /// let mut heap = BinaryHeap::from(vec![1, 2, 3, 4, 5]); | |
664 | /// assert_eq!(heap.len(), 5); | |
665 | /// | |
666 | /// drop(heap.drain_sorted()); // removes all elements in heap order | |
667 | /// assert_eq!(heap.len(), 0); | |
668 | /// ``` | |
669 | #[inline] | |
670 | #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")] | |
671 | pub fn drain_sorted(&mut self) -> DrainSorted<'_, T> { | |
dfeec247 | 672 | DrainSorted { inner: self } |
e74abb32 | 673 | } |
f9f354fc XL |
674 | |
675 | /// Retains only the elements specified by the predicate. | |
676 | /// | |
677 | /// In other words, remove all elements `e` such that `f(&e)` returns | |
678 | /// `false`. The elements are visited in unsorted (and unspecified) order. | |
679 | /// | |
680 | /// # Examples | |
681 | /// | |
682 | /// Basic usage: | |
683 | /// | |
684 | /// ``` | |
685 | /// #![feature(binary_heap_retain)] | |
686 | /// use std::collections::BinaryHeap; | |
687 | /// | |
688 | /// let mut heap = BinaryHeap::from(vec![-10, -5, 1, 2, 4, 13]); | |
689 | /// | |
690 | /// heap.retain(|x| x % 2 == 0); // only keep even numbers | |
691 | /// | |
692 | /// assert_eq!(heap.into_sorted_vec(), [-10, 2, 4]) | |
693 | /// ``` | |
694 | #[unstable(feature = "binary_heap_retain", issue = "71503")] | |
695 | pub fn retain<F>(&mut self, f: F) | |
696 | where | |
697 | F: FnMut(&T) -> bool, | |
698 | { | |
699 | self.data.retain(f); | |
700 | self.rebuild(); | |
701 | } | |
9fa01778 XL |
702 | } |
703 | ||
704 | impl<T> BinaryHeap<T> { | |
705 | /// Returns an iterator visiting all values in the underlying vector, in | |
706 | /// arbitrary order. | |
707 | /// | |
708 | /// # Examples | |
709 | /// | |
710 | /// Basic usage: | |
711 | /// | |
712 | /// ``` | |
713 | /// use std::collections::BinaryHeap; | |
714 | /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]); | |
715 | /// | |
716 | /// // Print 1, 2, 3, 4 in arbitrary order | |
717 | /// for x in heap.iter() { | |
718 | /// println!("{}", x); | |
719 | /// } | |
720 | /// ``` | |
721 | #[stable(feature = "rust1", since = "1.0.0")] | |
722 | pub fn iter(&self) -> Iter<'_, T> { | |
723 | Iter { iter: self.data.iter() } | |
724 | } | |
725 | ||
e74abb32 XL |
726 | /// Returns an iterator which retrieves elements in heap order. |
727 | /// This method consumes the original heap. | |
728 | /// | |
729 | /// # Examples | |
730 | /// | |
731 | /// Basic usage: | |
732 | /// | |
733 | /// ``` | |
734 | /// #![feature(binary_heap_into_iter_sorted)] | |
735 | /// use std::collections::BinaryHeap; | |
736 | /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5]); | |
737 | /// | |
738 | /// assert_eq!(heap.into_iter_sorted().take(2).collect::<Vec<_>>(), vec![5, 4]); | |
739 | /// ``` | |
740 | #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")] | |
741 | pub fn into_iter_sorted(self) -> IntoIterSorted<T> { | |
dfeec247 | 742 | IntoIterSorted { inner: self } |
e74abb32 XL |
743 | } |
744 | ||
9fa01778 XL |
745 | /// Returns the greatest item in the binary heap, or `None` if it is empty. |
746 | /// | |
747 | /// # Examples | |
748 | /// | |
749 | /// Basic usage: | |
750 | /// | |
751 | /// ``` | |
752 | /// use std::collections::BinaryHeap; | |
753 | /// let mut heap = BinaryHeap::new(); | |
754 | /// assert_eq!(heap.peek(), None); | |
755 | /// | |
756 | /// heap.push(1); | |
757 | /// heap.push(5); | |
758 | /// heap.push(2); | |
759 | /// assert_eq!(heap.peek(), Some(&5)); | |
760 | /// | |
761 | /// ``` | |
48663c56 XL |
762 | /// |
763 | /// # Time complexity | |
764 | /// | |
3dfed10e | 765 | /// Cost is *O*(1) in the worst case. |
9fa01778 XL |
766 | #[stable(feature = "rust1", since = "1.0.0")] |
767 | pub fn peek(&self) -> Option<&T> { | |
768 | self.data.get(0) | |
769 | } | |
770 | ||
771 | /// Returns the number of elements the binary heap can hold without reallocating. | |
772 | /// | |
773 | /// # Examples | |
774 | /// | |
775 | /// Basic usage: | |
776 | /// | |
777 | /// ``` | |
778 | /// use std::collections::BinaryHeap; | |
779 | /// let mut heap = BinaryHeap::with_capacity(100); | |
780 | /// assert!(heap.capacity() >= 100); | |
781 | /// heap.push(4); | |
782 | /// ``` | |
783 | #[stable(feature = "rust1", since = "1.0.0")] | |
784 | pub fn capacity(&self) -> usize { | |
785 | self.data.capacity() | |
786 | } | |
787 | ||
788 | /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the | |
789 | /// given `BinaryHeap`. Does nothing if the capacity is already sufficient. | |
790 | /// | |
791 | /// Note that the allocator may give the collection more space than it requests. Therefore | |
792 | /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future | |
793 | /// insertions are expected. | |
794 | /// | |
795 | /// # Panics | |
796 | /// | |
797 | /// Panics if the new capacity overflows `usize`. | |
798 | /// | |
799 | /// # Examples | |
800 | /// | |
801 | /// Basic usage: | |
802 | /// | |
803 | /// ``` | |
804 | /// use std::collections::BinaryHeap; | |
805 | /// let mut heap = BinaryHeap::new(); | |
806 | /// heap.reserve_exact(100); | |
807 | /// assert!(heap.capacity() >= 100); | |
808 | /// heap.push(4); | |
809 | /// ``` | |
810 | /// | |
1b1a35ee | 811 | /// [`reserve`]: BinaryHeap::reserve |
9fa01778 XL |
812 | #[stable(feature = "rust1", since = "1.0.0")] |
813 | pub fn reserve_exact(&mut self, additional: usize) { | |
814 | self.data.reserve_exact(additional); | |
815 | } | |
816 | ||
817 | /// Reserves capacity for at least `additional` more elements to be inserted in the | |
818 | /// `BinaryHeap`. The collection may reserve more space to avoid frequent reallocations. | |
819 | /// | |
820 | /// # Panics | |
821 | /// | |
822 | /// Panics if the new capacity overflows `usize`. | |
823 | /// | |
824 | /// # Examples | |
825 | /// | |
826 | /// Basic usage: | |
827 | /// | |
828 | /// ``` | |
829 | /// use std::collections::BinaryHeap; | |
830 | /// let mut heap = BinaryHeap::new(); | |
831 | /// heap.reserve(100); | |
832 | /// assert!(heap.capacity() >= 100); | |
833 | /// heap.push(4); | |
834 | /// ``` | |
835 | #[stable(feature = "rust1", since = "1.0.0")] | |
836 | pub fn reserve(&mut self, additional: usize) { | |
837 | self.data.reserve(additional); | |
838 | } | |
839 | ||
840 | /// Discards as much additional capacity as possible. | |
841 | /// | |
842 | /// # Examples | |
843 | /// | |
844 | /// Basic usage: | |
845 | /// | |
846 | /// ``` | |
847 | /// use std::collections::BinaryHeap; | |
848 | /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100); | |
849 | /// | |
850 | /// assert!(heap.capacity() >= 100); | |
851 | /// heap.shrink_to_fit(); | |
852 | /// assert!(heap.capacity() == 0); | |
853 | /// ``` | |
854 | #[stable(feature = "rust1", since = "1.0.0")] | |
855 | pub fn shrink_to_fit(&mut self) { | |
856 | self.data.shrink_to_fit(); | |
857 | } | |
858 | ||
859 | /// Discards capacity with a lower bound. | |
860 | /// | |
861 | /// The capacity will remain at least as large as both the length | |
862 | /// and the supplied value. | |
863 | /// | |
864 | /// Panics if the current capacity is smaller than the supplied | |
865 | /// minimum capacity. | |
866 | /// | |
867 | /// # Examples | |
868 | /// | |
869 | /// ``` | |
870 | /// #![feature(shrink_to)] | |
871 | /// use std::collections::BinaryHeap; | |
872 | /// let mut heap: BinaryHeap<i32> = BinaryHeap::with_capacity(100); | |
873 | /// | |
874 | /// assert!(heap.capacity() >= 100); | |
875 | /// heap.shrink_to(10); | |
876 | /// assert!(heap.capacity() >= 10); | |
877 | /// ``` | |
878 | #[inline] | |
dfeec247 | 879 | #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")] |
9fa01778 XL |
880 | pub fn shrink_to(&mut self, min_capacity: usize) { |
881 | self.data.shrink_to(min_capacity) | |
882 | } | |
883 | ||
884 | /// Consumes the `BinaryHeap` and returns the underlying vector | |
885 | /// in arbitrary order. | |
886 | /// | |
887 | /// # Examples | |
888 | /// | |
889 | /// Basic usage: | |
890 | /// | |
891 | /// ``` | |
892 | /// use std::collections::BinaryHeap; | |
893 | /// let heap = BinaryHeap::from(vec![1, 2, 3, 4, 5, 6, 7]); | |
894 | /// let vec = heap.into_vec(); | |
895 | /// | |
896 | /// // Will print in some order | |
897 | /// for x in vec { | |
898 | /// println!("{}", x); | |
899 | /// } | |
900 | /// ``` | |
901 | #[stable(feature = "binary_heap_extras_15", since = "1.5.0")] | |
902 | pub fn into_vec(self) -> Vec<T> { | |
903 | self.into() | |
904 | } | |
905 | ||
1a4d82fc | 906 | /// Returns the length of the binary heap. |
54a0048b SL |
907 | /// |
908 | /// # Examples | |
909 | /// | |
910 | /// Basic usage: | |
911 | /// | |
912 | /// ``` | |
913 | /// use std::collections::BinaryHeap; | |
914 | /// let heap = BinaryHeap::from(vec![1, 3]); | |
915 | /// | |
916 | /// assert_eq!(heap.len(), 2); | |
917 | /// ``` | |
85aaf69f | 918 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
919 | pub fn len(&self) -> usize { |
920 | self.data.len() | |
921 | } | |
1a4d82fc JJ |
922 | |
923 | /// Checks if the binary heap is empty. | |
54a0048b SL |
924 | /// |
925 | /// # Examples | |
926 | /// | |
927 | /// Basic usage: | |
928 | /// | |
929 | /// ``` | |
930 | /// use std::collections::BinaryHeap; | |
931 | /// let mut heap = BinaryHeap::new(); | |
932 | /// | |
933 | /// assert!(heap.is_empty()); | |
934 | /// | |
935 | /// heap.push(3); | |
936 | /// heap.push(5); | |
937 | /// heap.push(1); | |
938 | /// | |
939 | /// assert!(!heap.is_empty()); | |
940 | /// ``` | |
85aaf69f | 941 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
942 | pub fn is_empty(&self) -> bool { |
943 | self.len() == 0 | |
944 | } | |
1a4d82fc JJ |
945 | |
946 | /// Clears the binary heap, returning an iterator over the removed elements. | |
c34b1796 AL |
947 | /// |
948 | /// The elements are removed in arbitrary order. | |
54a0048b SL |
949 | /// |
950 | /// # Examples | |
951 | /// | |
952 | /// Basic usage: | |
953 | /// | |
954 | /// ``` | |
955 | /// use std::collections::BinaryHeap; | |
956 | /// let mut heap = BinaryHeap::from(vec![1, 3]); | |
957 | /// | |
958 | /// assert!(!heap.is_empty()); | |
959 | /// | |
960 | /// for x in heap.drain() { | |
961 | /// println!("{}", x); | |
962 | /// } | |
963 | /// | |
964 | /// assert!(heap.is_empty()); | |
965 | /// ``` | |
1a4d82fc | 966 | #[inline] |
92a42be0 | 967 | #[stable(feature = "drain", since = "1.6.0")] |
9fa01778 | 968 | pub fn drain(&mut self) -> Drain<'_, T> { |
d9579d0f | 969 | Drain { iter: self.data.drain(..) } |
1a4d82fc JJ |
970 | } |
971 | ||
972 | /// Drops all items from the binary heap. | |
54a0048b SL |
973 | /// |
974 | /// # Examples | |
975 | /// | |
976 | /// Basic usage: | |
977 | /// | |
978 | /// ``` | |
979 | /// use std::collections::BinaryHeap; | |
980 | /// let mut heap = BinaryHeap::from(vec![1, 3]); | |
981 | /// | |
982 | /// assert!(!heap.is_empty()); | |
983 | /// | |
984 | /// heap.clear(); | |
985 | /// | |
986 | /// assert!(heap.is_empty()); | |
987 | /// ``` | |
85aaf69f | 988 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 SL |
989 | pub fn clear(&mut self) { |
990 | self.drain(); | |
991 | } | |
1a4d82fc JJ |
992 | } |
993 | ||
0731742a | 994 | /// Hole represents a hole in a slice i.e., an index without valid value |
d9579d0f AL |
995 | /// (because it was moved from or duplicated). |
996 | /// In drop, `Hole` will restore the slice by filling the hole | |
997 | /// position with the value that was originally removed. | |
998 | struct Hole<'a, T: 'a> { | |
999 | data: &'a mut [T], | |
83c7162d | 1000 | elt: ManuallyDrop<T>, |
d9579d0f AL |
1001 | pos: usize, |
1002 | } | |
1003 | ||
1004 | impl<'a, T> Hole<'a, T> { | |
9fa01778 | 1005 | /// Create a new `Hole` at index `pos`. |
9e0c209e SL |
1006 | /// |
1007 | /// Unsafe because pos must be within the data slice. | |
1008 | #[inline] | |
1009 | unsafe fn new(data: &'a mut [T], pos: usize) -> Self { | |
1010 | debug_assert!(pos < data.len()); | |
9fa01778 | 1011 | // SAFE: pos should be inside the slice |
f035d41b | 1012 | let elt = unsafe { ptr::read(data.get_unchecked(pos)) }; |
dfeec247 | 1013 | Hole { data, elt: ManuallyDrop::new(elt), pos } |
d9579d0f AL |
1014 | } |
1015 | ||
9e0c209e | 1016 | #[inline] |
92a42be0 SL |
1017 | fn pos(&self) -> usize { |
1018 | self.pos | |
1019 | } | |
d9579d0f | 1020 | |
cc61c64b | 1021 | /// Returns a reference to the element removed. |
9e0c209e | 1022 | #[inline] |
92a42be0 | 1023 | fn element(&self) -> &T { |
83c7162d | 1024 | &self.elt |
d9579d0f AL |
1025 | } |
1026 | ||
cc61c64b | 1027 | /// Returns a reference to the element at `index`. |
d9579d0f | 1028 | /// |
9e0c209e SL |
1029 | /// Unsafe because index must be within the data slice and not equal to pos. |
1030 | #[inline] | |
d9579d0f AL |
1031 | unsafe fn get(&self, index: usize) -> &T { |
1032 | debug_assert!(index != self.pos); | |
9e0c209e | 1033 | debug_assert!(index < self.data.len()); |
f035d41b | 1034 | unsafe { self.data.get_unchecked(index) } |
d9579d0f AL |
1035 | } |
1036 | ||
1037 | /// Move hole to new location | |
1038 | /// | |
9e0c209e SL |
1039 | /// Unsafe because index must be within the data slice and not equal to pos. |
1040 | #[inline] | |
d9579d0f AL |
1041 | unsafe fn move_to(&mut self, index: usize) { |
1042 | debug_assert!(index != self.pos); | |
9e0c209e | 1043 | debug_assert!(index < self.data.len()); |
f035d41b | 1044 | unsafe { |
29967ef6 XL |
1045 | let ptr = self.data.as_mut_ptr(); |
1046 | let index_ptr: *const _ = ptr.add(index); | |
1047 | let hole_ptr = ptr.add(self.pos); | |
f035d41b XL |
1048 | ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1); |
1049 | } | |
d9579d0f AL |
1050 | self.pos = index; |
1051 | } | |
1052 | } | |
1053 | ||
9fa01778 | 1054 | impl<T> Drop for Hole<'_, T> { |
9e0c209e | 1055 | #[inline] |
d9579d0f AL |
1056 | fn drop(&mut self) { |
1057 | // fill the hole again | |
1058 | unsafe { | |
1059 | let pos = self.pos; | |
83c7162d | 1060 | ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1); |
d9579d0f AL |
1061 | } |
1062 | } | |
1063 | } | |
1064 | ||
cc61c64b XL |
1065 | /// An iterator over the elements of a `BinaryHeap`. |
1066 | /// | |
1b1a35ee | 1067 | /// This `struct` is created by [`BinaryHeap::iter()`]. See its |
cc61c64b XL |
1068 | /// documentation for more. |
1069 | /// | |
1b1a35ee | 1070 | /// [`iter`]: BinaryHeap::iter |
85aaf69f | 1071 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 | 1072 | pub struct Iter<'a, T: 'a> { |
1a4d82fc JJ |
1073 | iter: slice::Iter<'a, T>, |
1074 | } | |
1075 | ||
8bb4bdeb | 1076 | #[stable(feature = "collection_debug", since = "1.17.0")] |
9fa01778 XL |
1077 | impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> { |
1078 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
dfeec247 | 1079 | f.debug_tuple("Iter").field(&self.iter.as_slice()).finish() |
8bb4bdeb XL |
1080 | } |
1081 | } | |
1082 | ||
ea8adc8c | 1083 | // FIXME(#26925) Remove in favor of `#[derive(Clone)]` |
85aaf69f | 1084 | #[stable(feature = "rust1", since = "1.0.0")] |
9fa01778 XL |
1085 | impl<T> Clone for Iter<'_, T> { |
1086 | fn clone(&self) -> Self { | |
1a4d82fc JJ |
1087 | Iter { iter: self.iter.clone() } |
1088 | } | |
1089 | } | |
1090 | ||
85aaf69f | 1091 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1092 | impl<'a, T> Iterator for Iter<'a, T> { |
1093 | type Item = &'a T; | |
1094 | ||
1095 | #[inline] | |
92a42be0 SL |
1096 | fn next(&mut self) -> Option<&'a T> { |
1097 | self.iter.next() | |
1098 | } | |
1a4d82fc JJ |
1099 | |
1100 | #[inline] | |
92a42be0 SL |
1101 | fn size_hint(&self) -> (usize, Option<usize>) { |
1102 | self.iter.size_hint() | |
1103 | } | |
416331ca XL |
1104 | |
1105 | #[inline] | |
1106 | fn last(self) -> Option<&'a T> { | |
1107 | self.iter.last() | |
1108 | } | |
1a4d82fc JJ |
1109 | } |
1110 | ||
85aaf69f | 1111 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1112 | impl<'a, T> DoubleEndedIterator for Iter<'a, T> { |
1113 | #[inline] | |
92a42be0 SL |
1114 | fn next_back(&mut self) -> Option<&'a T> { |
1115 | self.iter.next_back() | |
1116 | } | |
1a4d82fc JJ |
1117 | } |
1118 | ||
85aaf69f | 1119 | #[stable(feature = "rust1", since = "1.0.0")] |
9fa01778 | 1120 | impl<T> ExactSizeIterator for Iter<'_, T> { |
476ff2be SL |
1121 | fn is_empty(&self) -> bool { |
1122 | self.iter.is_empty() | |
1123 | } | |
1124 | } | |
1a4d82fc | 1125 | |
0531ce1d | 1126 | #[stable(feature = "fused", since = "1.26.0")] |
9fa01778 | 1127 | impl<T> FusedIterator for Iter<'_, T> {} |
9e0c209e | 1128 | |
cc61c64b XL |
1129 | /// An owning iterator over the elements of a `BinaryHeap`. |
1130 | /// | |
1b1a35ee | 1131 | /// This `struct` is created by [`BinaryHeap::into_iter()`] |
cc61c64b XL |
1132 | /// (provided by the `IntoIterator` trait). See its documentation for more. |
1133 | /// | |
1b1a35ee | 1134 | /// [`into_iter`]: BinaryHeap::into_iter |
85aaf69f | 1135 | #[stable(feature = "rust1", since = "1.0.0")] |
a7813a04 | 1136 | #[derive(Clone)] |
1a4d82fc JJ |
1137 | pub struct IntoIter<T> { |
1138 | iter: vec::IntoIter<T>, | |
1139 | } | |
1140 | ||
8bb4bdeb XL |
1141 | #[stable(feature = "collection_debug", since = "1.17.0")] |
1142 | impl<T: fmt::Debug> fmt::Debug for IntoIter<T> { | |
9fa01778 | 1143 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
dfeec247 | 1144 | f.debug_tuple("IntoIter").field(&self.iter.as_slice()).finish() |
8bb4bdeb XL |
1145 | } |
1146 | } | |
1147 | ||
85aaf69f | 1148 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1149 | impl<T> Iterator for IntoIter<T> { |
1150 | type Item = T; | |
1151 | ||
1152 | #[inline] | |
92a42be0 SL |
1153 | fn next(&mut self) -> Option<T> { |
1154 | self.iter.next() | |
1155 | } | |
1a4d82fc JJ |
1156 | |
1157 | #[inline] | |
92a42be0 SL |
1158 | fn size_hint(&self) -> (usize, Option<usize>) { |
1159 | self.iter.size_hint() | |
1160 | } | |
1a4d82fc JJ |
1161 | } |
1162 | ||
85aaf69f | 1163 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1164 | impl<T> DoubleEndedIterator for IntoIter<T> { |
1165 | #[inline] | |
92a42be0 SL |
1166 | fn next_back(&mut self) -> Option<T> { |
1167 | self.iter.next_back() | |
1168 | } | |
1a4d82fc JJ |
1169 | } |
1170 | ||
85aaf69f | 1171 | #[stable(feature = "rust1", since = "1.0.0")] |
476ff2be SL |
1172 | impl<T> ExactSizeIterator for IntoIter<T> { |
1173 | fn is_empty(&self) -> bool { | |
1174 | self.iter.is_empty() | |
1175 | } | |
1176 | } | |
1a4d82fc | 1177 | |
0531ce1d | 1178 | #[stable(feature = "fused", since = "1.26.0")] |
9e0c209e SL |
1179 | impl<T> FusedIterator for IntoIter<T> {} |
1180 | ||
1b1a35ee XL |
1181 | #[unstable(issue = "none", feature = "inplace_iteration")] |
1182 | unsafe impl<T> SourceIter for IntoIter<T> { | |
1183 | type Source = IntoIter<T>; | |
1184 | ||
1185 | #[inline] | |
1186 | unsafe fn as_inner(&mut self) -> &mut Self::Source { | |
1187 | self | |
1188 | } | |
1189 | } | |
1190 | ||
1191 | #[unstable(issue = "none", feature = "inplace_iteration")] | |
1192 | unsafe impl<I> InPlaceIterable for IntoIter<I> {} | |
1193 | ||
1194 | impl<I> AsIntoIter for IntoIter<I> { | |
1195 | type Item = I; | |
1196 | ||
1197 | fn as_into_iter(&mut self) -> &mut vec::IntoIter<Self::Item> { | |
1198 | &mut self.iter | |
1199 | } | |
1200 | } | |
1201 | ||
e74abb32 XL |
1202 | #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")] |
1203 | #[derive(Clone, Debug)] | |
1204 | pub struct IntoIterSorted<T> { | |
1205 | inner: BinaryHeap<T>, | |
1206 | } | |
1207 | ||
1208 | #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")] | |
1209 | impl<T: Ord> Iterator for IntoIterSorted<T> { | |
1210 | type Item = T; | |
1211 | ||
1212 | #[inline] | |
1213 | fn next(&mut self) -> Option<T> { | |
1214 | self.inner.pop() | |
1215 | } | |
1216 | ||
1217 | #[inline] | |
1218 | fn size_hint(&self) -> (usize, Option<usize>) { | |
1219 | let exact = self.inner.len(); | |
1220 | (exact, Some(exact)) | |
1221 | } | |
1222 | } | |
1223 | ||
1224 | #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")] | |
1225 | impl<T: Ord> ExactSizeIterator for IntoIterSorted<T> {} | |
1226 | ||
1227 | #[unstable(feature = "binary_heap_into_iter_sorted", issue = "59278")] | |
1228 | impl<T: Ord> FusedIterator for IntoIterSorted<T> {} | |
1229 | ||
1230 | #[unstable(feature = "trusted_len", issue = "37572")] | |
1231 | unsafe impl<T: Ord> TrustedLen for IntoIterSorted<T> {} | |
1232 | ||
cc61c64b XL |
1233 | /// A draining iterator over the elements of a `BinaryHeap`. |
1234 | /// | |
1b1a35ee | 1235 | /// This `struct` is created by [`BinaryHeap::drain()`]. See its |
cc61c64b XL |
1236 | /// documentation for more. |
1237 | /// | |
1b1a35ee | 1238 | /// [`drain`]: BinaryHeap::drain |
92a42be0 | 1239 | #[stable(feature = "drain", since = "1.6.0")] |
8bb4bdeb | 1240 | #[derive(Debug)] |
1a4d82fc JJ |
1241 | pub struct Drain<'a, T: 'a> { |
1242 | iter: vec::Drain<'a, T>, | |
1243 | } | |
1244 | ||
c30ab7b3 | 1245 | #[stable(feature = "drain", since = "1.6.0")] |
9fa01778 | 1246 | impl<T> Iterator for Drain<'_, T> { |
1a4d82fc JJ |
1247 | type Item = T; |
1248 | ||
1249 | #[inline] | |
92a42be0 SL |
1250 | fn next(&mut self) -> Option<T> { |
1251 | self.iter.next() | |
1252 | } | |
1a4d82fc JJ |
1253 | |
1254 | #[inline] | |
92a42be0 SL |
1255 | fn size_hint(&self) -> (usize, Option<usize>) { |
1256 | self.iter.size_hint() | |
1257 | } | |
1a4d82fc JJ |
1258 | } |
1259 | ||
c30ab7b3 | 1260 | #[stable(feature = "drain", since = "1.6.0")] |
9fa01778 | 1261 | impl<T> DoubleEndedIterator for Drain<'_, T> { |
1a4d82fc | 1262 | #[inline] |
92a42be0 SL |
1263 | fn next_back(&mut self) -> Option<T> { |
1264 | self.iter.next_back() | |
1265 | } | |
1a4d82fc JJ |
1266 | } |
1267 | ||
c30ab7b3 | 1268 | #[stable(feature = "drain", since = "1.6.0")] |
9fa01778 | 1269 | impl<T> ExactSizeIterator for Drain<'_, T> { |
476ff2be SL |
1270 | fn is_empty(&self) -> bool { |
1271 | self.iter.is_empty() | |
1272 | } | |
1273 | } | |
1a4d82fc | 1274 | |
0531ce1d | 1275 | #[stable(feature = "fused", since = "1.26.0")] |
9fa01778 | 1276 | impl<T> FusedIterator for Drain<'_, T> {} |
9e0c209e | 1277 | |
e74abb32 XL |
1278 | /// A draining iterator over the elements of a `BinaryHeap`. |
1279 | /// | |
1b1a35ee | 1280 | /// This `struct` is created by [`BinaryHeap::drain_sorted()`]. See its |
e74abb32 XL |
1281 | /// documentation for more. |
1282 | /// | |
1b1a35ee | 1283 | /// [`drain_sorted`]: BinaryHeap::drain_sorted |
e74abb32 XL |
1284 | #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")] |
1285 | #[derive(Debug)] | |
1286 | pub struct DrainSorted<'a, T: Ord> { | |
1287 | inner: &'a mut BinaryHeap<T>, | |
1288 | } | |
1289 | ||
1290 | #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")] | |
1291 | impl<'a, T: Ord> Drop for DrainSorted<'a, T> { | |
1292 | /// Removes heap elements in heap order. | |
1293 | fn drop(&mut self) { | |
74b04a01 XL |
1294 | struct DropGuard<'r, 'a, T: Ord>(&'r mut DrainSorted<'a, T>); |
1295 | ||
1296 | impl<'r, 'a, T: Ord> Drop for DropGuard<'r, 'a, T> { | |
1297 | fn drop(&mut self) { | |
f9f354fc | 1298 | while self.0.inner.pop().is_some() {} |
74b04a01 XL |
1299 | } |
1300 | } | |
1301 | ||
1302 | while let Some(item) = self.inner.pop() { | |
1303 | let guard = DropGuard(self); | |
1304 | drop(item); | |
1305 | mem::forget(guard); | |
1306 | } | |
e74abb32 XL |
1307 | } |
1308 | } | |
1309 | ||
1310 | #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")] | |
1311 | impl<T: Ord> Iterator for DrainSorted<'_, T> { | |
1312 | type Item = T; | |
1313 | ||
1314 | #[inline] | |
1315 | fn next(&mut self) -> Option<T> { | |
1316 | self.inner.pop() | |
1317 | } | |
1318 | ||
1319 | #[inline] | |
1320 | fn size_hint(&self) -> (usize, Option<usize>) { | |
1321 | let exact = self.inner.len(); | |
1322 | (exact, Some(exact)) | |
1323 | } | |
1324 | } | |
1325 | ||
1326 | #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")] | |
dfeec247 | 1327 | impl<T: Ord> ExactSizeIterator for DrainSorted<'_, T> {} |
e74abb32 XL |
1328 | |
1329 | #[unstable(feature = "binary_heap_drain_sorted", issue = "59278")] | |
1330 | impl<T: Ord> FusedIterator for DrainSorted<'_, T> {} | |
1331 | ||
1332 | #[unstable(feature = "trusted_len", issue = "37572")] | |
1333 | unsafe impl<T: Ord> TrustedLen for DrainSorted<'_, T> {} | |
1334 | ||
8bb4bdeb | 1335 | #[stable(feature = "binary_heap_extras_15", since = "1.5.0")] |
b039eaaf | 1336 | impl<T: Ord> From<Vec<T>> for BinaryHeap<T> { |
e1599b0c XL |
1337 | /// Converts a `Vec<T>` into a `BinaryHeap<T>`. |
1338 | /// | |
3dfed10e | 1339 | /// This conversion happens in-place, and has *O*(*n*) time complexity. |
b039eaaf SL |
1340 | fn from(vec: Vec<T>) -> BinaryHeap<T> { |
1341 | let mut heap = BinaryHeap { data: vec }; | |
a7813a04 | 1342 | heap.rebuild(); |
b039eaaf SL |
1343 | heap |
1344 | } | |
1345 | } | |
1346 | ||
8bb4bdeb | 1347 | #[stable(feature = "binary_heap_extras_15", since = "1.5.0")] |
b039eaaf | 1348 | impl<T> From<BinaryHeap<T>> for Vec<T> { |
1b1a35ee XL |
1349 | /// Converts a `BinaryHeap<T>` into a `Vec<T>`. |
1350 | /// | |
1351 | /// This conversion requires no data movement or allocation, and has | |
1352 | /// constant time complexity. | |
b039eaaf SL |
1353 | fn from(heap: BinaryHeap<T>) -> Vec<T> { |
1354 | heap.data | |
1355 | } | |
1356 | } | |
1357 | ||
85aaf69f | 1358 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 1359 | impl<T: Ord> FromIterator<T> for BinaryHeap<T> { |
92a42be0 | 1360 | fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> { |
b039eaaf | 1361 | BinaryHeap::from(iter.into_iter().collect::<Vec<_>>()) |
85aaf69f SL |
1362 | } |
1363 | } | |
1364 | ||
1365 | #[stable(feature = "rust1", since = "1.0.0")] | |
9fa01778 | 1366 | impl<T> IntoIterator for BinaryHeap<T> { |
85aaf69f SL |
1367 | type Item = T; |
1368 | type IntoIter = IntoIter<T>; | |
1369 | ||
9346a6ac AL |
1370 | /// Creates a consuming iterator, that is, one that moves each value out of |
1371 | /// the binary heap in arbitrary order. The binary heap cannot be used | |
1372 | /// after calling this. | |
1373 | /// | |
1374 | /// # Examples | |
1375 | /// | |
54a0048b SL |
1376 | /// Basic usage: |
1377 | /// | |
9346a6ac | 1378 | /// ``` |
9346a6ac | 1379 | /// use std::collections::BinaryHeap; |
b039eaaf | 1380 | /// let heap = BinaryHeap::from(vec![1, 2, 3, 4]); |
9346a6ac AL |
1381 | /// |
1382 | /// // Print 1, 2, 3, 4 in arbitrary order | |
1383 | /// for x in heap.into_iter() { | |
1384 | /// // x has type i32, not &i32 | |
1385 | /// println!("{}", x); | |
1386 | /// } | |
1387 | /// ``` | |
85aaf69f | 1388 | fn into_iter(self) -> IntoIter<T> { |
9346a6ac | 1389 | IntoIter { iter: self.data.into_iter() } |
85aaf69f SL |
1390 | } |
1391 | } | |
1392 | ||
1393 | #[stable(feature = "rust1", since = "1.0.0")] | |
9fa01778 | 1394 | impl<'a, T> IntoIterator for &'a BinaryHeap<T> { |
85aaf69f SL |
1395 | type Item = &'a T; |
1396 | type IntoIter = Iter<'a, T>; | |
1397 | ||
1398 | fn into_iter(self) -> Iter<'a, T> { | |
1399 | self.iter() | |
1a4d82fc JJ |
1400 | } |
1401 | } | |
1402 | ||
85aaf69f | 1403 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 1404 | impl<T: Ord> Extend<T> for BinaryHeap<T> { |
a7813a04 | 1405 | #[inline] |
54a0048b | 1406 | fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) { |
a7813a04 XL |
1407 | <Self as SpecExtend<I>>::spec_extend(self, iter); |
1408 | } | |
f9f354fc XL |
1409 | |
1410 | #[inline] | |
1411 | fn extend_one(&mut self, item: T) { | |
1412 | self.push(item); | |
1413 | } | |
1414 | ||
1415 | #[inline] | |
1416 | fn extend_reserve(&mut self, additional: usize) { | |
1417 | self.reserve(additional); | |
1418 | } | |
a7813a04 XL |
1419 | } |
1420 | ||
1421 | impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> { | |
1422 | default fn spec_extend(&mut self, iter: I) { | |
1423 | self.extend_desugared(iter.into_iter()); | |
1424 | } | |
1425 | } | |
1426 | ||
1427 | impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> { | |
1428 | fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) { | |
1429 | self.append(other); | |
1430 | } | |
1431 | } | |
1432 | ||
1433 | impl<T: Ord> BinaryHeap<T> { | |
1434 | fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) { | |
54a0048b SL |
1435 | let iterator = iter.into_iter(); |
1436 | let (lower, _) = iterator.size_hint(); | |
1a4d82fc JJ |
1437 | |
1438 | self.reserve(lower); | |
1439 | ||
532ac7d7 | 1440 | iterator.for_each(move |elem| self.push(elem)); |
1a4d82fc JJ |
1441 | } |
1442 | } | |
62682a34 SL |
1443 | |
1444 | #[stable(feature = "extend_ref", since = "1.2.0")] | |
1445 | impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> { | |
92a42be0 | 1446 | fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) { |
62682a34 SL |
1447 | self.extend(iter.into_iter().cloned()); |
1448 | } | |
f9f354fc XL |
1449 | |
1450 | #[inline] | |
1451 | fn extend_one(&mut self, &item: &'a T) { | |
1452 | self.push(item); | |
1453 | } | |
1454 | ||
1455 | #[inline] | |
1456 | fn extend_reserve(&mut self, additional: usize) { | |
1457 | self.reserve(additional); | |
1458 | } | |
62682a34 | 1459 | } |