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