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