1use crate::storage::{ArrayLayout, Capacity, Storage};
13use crate::collections::vec::{Drain, Vec};
14
15use core::fmt::{self, Debug, Formatter};
16use core::iter::{FromIterator, FusedIterator};
17#[allow(unused_imports)]
18use core::mem::MaybeUninit;
19use core::ops::{Deref, DerefMut};
20
21pub struct BinaryHeap<T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity = usize> {
32 a: Vec<T, S, I>,
33}
34
35pub struct PeekMut<'a, T: 'a + Ord, S: Storage<ArrayLayout<T>>, I: Capacity = usize> {
40 heap: &'a mut BinaryHeap<T, S, I>,
41}
42
43impl<T: Ord + Debug, S: Storage<ArrayLayout<T>>, I: Capacity> Debug for PeekMut<'_, T, S, I> {
44 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
45 f.debug_tuple("PeekMut").field(&self.heap.peek()).finish()
46 }
47}
48
49impl<T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity> Drop for PeekMut<'_, T, S, I> {
50 fn drop(&mut self) {
51 heapify(self.heap.a.as_mut_slice(), 0);
52 }
53}
54
55impl<T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity> Deref for PeekMut<'_, T, S, I> {
56 type Target = T;
57
58 fn deref(&self) -> &Self::Target {
59 debug_assert!(!self.heap.is_empty());
60 unsafe { self.heap.a.get_unchecked(0) }
61 }
62}
63
64impl<T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity> DerefMut for PeekMut<'_, T, S, I> {
65 fn deref_mut(&mut self) -> &mut Self::Target {
66 debug_assert!(!self.heap.is_empty());
67 unsafe { self.heap.a.get_unchecked_mut(0) }
68 }
69}
70
71impl<T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity> PeekMut<'_, T, S, I> {
72 pub fn pop(this: PeekMut<'_, T, S, I>) -> T {
74 debug_assert!(!this.heap.is_empty());
75 if let Some(value) = this.heap.pop() {
76 core::mem::forget(this);
77 value
78 } else {
79 unreachable!()
80 }
81 }
82}
83
84impl<T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity> From<S> for BinaryHeap<T, S, I> {
85 fn from(buf: S) -> Self {
90 BinaryHeap { a: Vec::from(buf) }
91 }
92}
93
94#[inline(always)]
101fn parent(i: usize) -> usize {
102 (i + 1) / 2 - 1
103}
104
105#[inline(always)]
106fn left(i: usize) -> usize {
107 2 * (i + 1) - 1
108}
109
110#[inline(always)]
111fn right(i: usize) -> usize {
112 2 * (i + 1)
113}
114
115fn heapify<T: Ord>(a: &mut [T], i: usize) {
116 let l = left(i);
117 let r = right(i);
118 let mut largest = if l < a.len() && a[l] > a[i] { l } else { i };
119 if r < a.len() && a[r] > a[largest] {
120 largest = r;
121 }
122 if largest != i {
123 a.swap(i, largest);
124 heapify(a, largest);
125 }
126}
127
128impl<T: Ord + Debug, S: Storage<ArrayLayout<T>>, I: Capacity> Debug for BinaryHeap<T, S, I> {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 f.debug_list().entries(self.iter()).finish()
131 }
132}
133
134impl<T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity> From<Vec<T, S, I>> for BinaryHeap<T, S, I> {
135 fn from(mut vec: Vec<T, S, I>) -> Self {
139 let a = vec.as_mut_slice();
140 for i in (0..(a.len() / 2)).rev() {
141 heapify(a, i);
142 }
143 BinaryHeap { a: vec }
144 }
145}
146
147impl<T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity> BinaryHeap<T, S, I> {
148 #[inline]
150 pub fn peek(&self) -> Option<&T> {
151 self.a.first()
152 }
153
154 #[inline]
178 pub fn peek_mut(&mut self) -> Option<PeekMut<T, S, I>> {
179 if self.is_empty() {
180 None
181 } else {
182 Some(PeekMut { heap: self })
183 }
184 }
185
186 pub fn pop(&mut self) -> Option<T> {
202 if self.is_empty() {
203 return None;
204 }
205
206 let result = self.a.swap_remove(I::from_usize(0));
207 heapify(self.a.as_mut_slice(), 0);
208 Some(result)
209 }
210
211 #[inline]
217 pub fn push(&mut self, item: T) {
218 #[cold]
219 #[inline(never)]
220 fn assert_failed() -> ! {
221 panic!("binary heap is already at capacity")
222 }
223
224 if self.try_push(item).is_err() {
225 assert_failed();
226 }
227 }
228
229 pub fn try_push(&mut self, item: T) -> Result<(), T> {
243 self.a.try_push(item)?;
244 let a = self.a.as_mut_slice();
245 let mut i = a.len() - 1;
246 while i > 0 && a[parent(i)] < a[i] {
247 a.swap(i, parent(i));
248 i = parent(i);
249 }
250 Ok(())
251 }
252
253 #[inline]
255 pub fn capacity(&self) -> usize {
256 self.a.capacity()
257 }
258
259 #[inline]
261 pub fn len(&self) -> usize {
262 self.a.len()
263 }
264
265 #[inline]
267 pub fn is_empty(&self) -> bool {
268 self.a.is_empty()
269 }
270
271 #[inline]
273 pub fn is_full(&self) -> bool {
274 self.a.is_full()
275 }
276
277 pub fn iter(&self) -> impl Iterator<Item = &T> {
279 self.a.iter()
280 }
281
282 #[inline]
301 pub fn drain(&mut self) -> Drain<'_, T, S, I> {
302 self.a.drain(..)
303 }
304
305 #[inline]
325 pub fn drain_sorted(&mut self) -> DrainSorted<'_, T, S, I> {
326 DrainSorted { heap: self }
327 }
328
329 #[inline]
331 pub fn clear(&mut self) {
332 self.a.clear();
333 }
334
335 #[inline]
337 pub fn into_vec(self) -> Vec<T, S, I> {
338 self.a
339 }
340
341 pub fn into_sorted_vec(self) -> Vec<T, S, I> {
352 let mut result = self.into_vec();
353 let a = result.as_mut_slice();
354 for i in (1..a.len()).rev() {
355 a.swap(0, i);
356 heapify(&mut a[..i], 0);
357 }
358 result
359 }
360
361 pub fn into_iter_sorted(self) -> IntoIterSorted<T, S, I> {
382 IntoIterSorted { heap: self }
383 }
384}
385
386impl<T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity> IntoIterator for BinaryHeap<T, S, I> {
387 type Item = T;
388 type IntoIter = <Vec<T, S, I> as IntoIterator>::IntoIter;
389 fn into_iter(self) -> Self::IntoIter {
390 self.a.into_iter()
391 }
392}
393
394impl<T1, T2: Ord, S: Storage<ArrayLayout<T2>>, I: Capacity> Extend<T1> for BinaryHeap<T2, S, I>
395where
396 Vec<T2, S, I>: Extend<T1>,
397{
398 fn extend<T: IntoIterator<Item = T1>>(&mut self, iter: T) {
399 self.a.extend(iter);
400 for i in (0..(self.a.len() / 2)).rev() {
401 heapify(self.a.as_mut_slice(), i);
402 }
403 }
404}
405
406impl<T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity> FromIterator<T> for BinaryHeap<T, S, I>
407where
408 Vec<T, S, I>: FromIterator<T>,
409{
410 fn from_iter<It: IntoIterator<Item = T>>(iter: It) -> Self {
415 let a = Vec::<T, S, I>::from_iter(iter);
416 Self::from(a)
417 }
418}
419
420pub struct DrainSorted<'a, T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity> {
425 heap: &'a mut BinaryHeap<T, S, I>,
426}
427
428impl<T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity> Iterator for DrainSorted<'_, T, S, I> {
429 type Item = T;
430
431 fn size_hint(&self) -> (usize, Option<usize>) {
432 let size = self.len();
433 (size, Some(size))
434 }
435
436 fn next(&mut self) -> Option<Self::Item> {
437 self.heap.pop()
438 }
439}
440
441impl<T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity> ExactSizeIterator for DrainSorted<'_, T, S, I> {}
442impl<T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity> FusedIterator for DrainSorted<'_, T, S, I> {}
443
444impl<T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity> Drop for DrainSorted<'_, T, S, I> {
445 fn drop(&mut self) {
446 self.for_each(drop);
447 }
448}
449
450#[derive(Debug)]
455pub struct IntoIterSorted<T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity> {
456 heap: BinaryHeap<T, S, I>,
457}
458
459impl<T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity> Iterator for IntoIterSorted<T, S, I> {
460 type Item = T;
461
462 #[inline]
463 fn size_hint(&self) -> (usize, Option<usize>) {
464 let size = self.heap.len();
465 (size, Some(size))
466 }
467
468 #[inline]
469 fn next(&mut self) -> Option<T> {
470 self.heap.pop()
471 }
472}
473
474impl<T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity> ExactSizeIterator for IntoIterSorted<T, S, I> {}
475impl<T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity> FusedIterator for IntoIterSorted<T, S, I> {}
476
477impl<T: Clone + Ord, S: Storage<ArrayLayout<T>>, I: Capacity> Clone for IntoIterSorted<T, S, I>
478where
479 BinaryHeap<T, S, I>: Clone,
480{
481 fn clone(&self) -> Self {
482 self.heap.clone().into_iter_sorted()
483 }
484}
485
486impl<T: Ord, S: Storage<ArrayLayout<T>>, I: Capacity> Drop for IntoIterSorted<T, S, I> {
487 fn drop(&mut self) {
488 self.for_each(drop);
489 }
490}
491
492#[cfg(feature = "alloc")]
493#[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))]
494impl<T: Copy + Ord, I: Capacity> crate::collections::AllocHeap<T, I> {
495 pub fn with_capacity(capacity: I) -> Self {
500 BinaryHeap {
501 a: Vec::with_capacity(capacity),
502 }
503 }
504}
505
506#[cfg(feature = "alloc")]
507#[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))]
508impl<T: Copy + Ord, I: Capacity> Clone for crate::collections::AllocHeap<T, I> {
509 fn clone(&self) -> Self {
510 BinaryHeap { a: self.a.clone() }
511 }
512}
513
514impl<T: Ord, I: Capacity, const C: usize> BinaryHeap<T, [MaybeUninit<T>; C], I> {
515 pub fn new() -> Self {
527 let a = Vec::new();
528 BinaryHeap { a }
529 }
530}
531
532impl<T: Ord, I: Capacity, const C: usize> Default for BinaryHeap<T, [MaybeUninit<T>; C], I> {
533 fn default() -> Self {
534 Self::new()
535 }
536}
537
538impl<T: Clone + Ord, I: Capacity, const C: usize> Clone for BinaryHeap<T, [MaybeUninit<T>; C], I> {
539 fn clone(&self) -> Self {
540 BinaryHeap { a: self.a.clone() }
541 }
542}
543
544#[cfg(test)]
545mod tests {
546 use super::*;
547
548 #[test]
549 fn tree_traversal_utilities() {
550 assert_eq!(left(0), 1);
551 assert_eq!(right(0), 2);
552 assert_eq!(parent(1), 0);
553 assert_eq!(parent(2), 0);
554
555 for i in 1..=1000 {
556 let l = left(i);
557 let r = right(i);
558 assert_eq!(l + 1, r);
559 assert_eq!(parent(l), i);
560 assert_eq!(parent(r), i);
561
562 let ll = left(l);
563 let lr = right(l);
564 let rl = left(r);
565 let rr = right(r);
566
567 assert_eq!(ll + 1, lr);
568 assert_eq!(rl + 1, rr);
569 assert_eq!(parent(parent(ll)), i);
570 assert_eq!(parent(parent(lr)), i);
571 assert_eq!(parent(parent(rl)), i);
572 assert_eq!(parent(parent(rr)), i);
573 }
574 }
575
576 #[test]
577 fn push_and_pop_randomized_inputs() {
578 use rand::{rngs::SmallRng, RngCore, SeedableRng};
579
580 let mut backing_region = [core::mem::MaybeUninit::<u32>::uninit(); 32];
581 let mut heap = crate::collections::SliceHeap::<_>::from(&mut backing_region[..]);
582
583 let mut rng = SmallRng::from_seed(crate::test_utils::RNG_SEED);
584
585 let mut newest = 0;
586 for _ in 0..32 {
587 newest = rng.next_u32();
588 heap.push(newest);
589 }
590
591 let mut prev = u32::max_value();
592 for _ in 0..1000 {
593 let x = heap.pop().unwrap();
594 assert!(x <= prev || x == newest);
595 prev = x;
596
597 newest = rng.next_u32();
598 heap.push(newest);
599 }
600 }
601
602 #[test]
603 fn iterators_take_and_drop_correctly() {
604 use core::cell::RefCell;
605
606 #[derive(Clone)]
607 struct Droppable<'a, 'b> {
608 value: usize,
609 log: &'a RefCell<crate::collections::SliceVec<'b, usize>>,
610 }
611
612 impl PartialEq for Droppable<'_, '_> {
613 fn eq(&self, rhs: &Self) -> bool {
614 self.value == rhs.value
615 }
616 }
617
618 impl Eq for Droppable<'_, '_> {}
619
620 impl PartialOrd for Droppable<'_, '_> {
621 fn partial_cmp(&self, rhs: &Self) -> Option<core::cmp::Ordering> {
622 Some(self.cmp(rhs))
623 }
624 }
625
626 impl Ord for Droppable<'_, '_> {
627 fn cmp(&self, rhs: &Self) -> core::cmp::Ordering {
628 self.value.cmp(&rhs.value)
629 }
630 }
631
632 impl Drop for Droppable<'_, '_> {
633 fn drop(&mut self) {
634 self.log.borrow_mut().push(self.value);
635 }
636 }
637
638 let mut backing_array = [MaybeUninit::<usize>::uninit(); 16];
639 let drop_log = RefCell::new(crate::collections::SliceVec::<_>::from(&mut backing_array[..]));
640
641 let mut backing_region = [
642 core::mem::MaybeUninit::<Droppable>::uninit(),
643 core::mem::MaybeUninit::<Droppable>::uninit(),
644 core::mem::MaybeUninit::<Droppable>::uninit(),
645 core::mem::MaybeUninit::<Droppable>::uninit(),
646 core::mem::MaybeUninit::<Droppable>::uninit(),
647 core::mem::MaybeUninit::<Droppable>::uninit(),
648 core::mem::MaybeUninit::<Droppable>::uninit(),
649 core::mem::MaybeUninit::<Droppable>::uninit(),
650 ];
651
652 let mut heap = crate::collections::SliceHeap::<Droppable>::from(&mut backing_region[..]);
653 for i in 1..=8 {
654 heap.push(Droppable {
655 value: i,
656 log: &drop_log,
657 });
658 }
659
660 let mut drain_iter = heap.drain_sorted();
661 assert_eq!(drain_iter.next().unwrap().value, 8);
662 assert_eq!(drain_iter.next().unwrap().value, 7);
663 assert_eq!(drop_log.borrow().len(), 2);
664
665 drop(drain_iter);
666 assert_eq!(drop_log.borrow().len(), 8);
667 assert_eq!(heap.len(), 0);
668
669 for i in 1..=8 {
670 heap.push(Droppable {
671 value: i,
672 log: &drop_log,
673 });
674 }
675
676 let mut into_iter = heap.into_iter_sorted();
677 assert_eq!(into_iter.next().unwrap().value, 8);
678 assert_eq!(into_iter.next().unwrap().value, 7);
679 assert_eq!(into_iter.next().unwrap().value, 6);
680 assert_eq!(drop_log.borrow().len(), 11);
681
682 drop(into_iter);
683 assert_eq!(drop_log.borrow().len(), 16);
684
685 assert_eq!(
686 drop_log.borrow().as_slice(),
687 &[8, 7, 6, 5, 4, 3, 2, 1, 8, 7, 6, 5, 4, 3, 2, 1]
688 );
689 }
690}