heapless 0.9.4

`static` friendly data structures that don't require dynamic memory allocation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
//! A priority queue implemented with a binary heap.
//!
//! Insertion and popping the largest element have *O*(log n) time complexity.
//! Checking the smallest/largest element is *O*(1).

// TODO not yet implemented
// Converting a vector to a binary heap can be done in-place, and has *O*(n) complexity. A binary
// heap can also be converted to a sorted vector in-place, allowing it to be used for an
// *O*(n log n) in-place heapsort.

use core::{
    cmp::Ordering,
    fmt,
    marker::PhantomData,
    mem::{self, ManuallyDrop},
    ops::{Deref, DerefMut},
    ptr, slice,
};

#[cfg(feature = "zeroize")]
use zeroize::Zeroize;

use crate::vec::{OwnedVecStorage, Vec, VecInner, VecStorage, ViewVecStorage};

/// Min-heap
pub enum Min {}

/// Max-heap
pub enum Max {}

/// The binary heap kind: min-heap or max-heap
pub trait Kind: private::Sealed {
    #[doc(hidden)]
    fn ordering() -> Ordering;
}

impl Kind for Min {
    fn ordering() -> Ordering {
        Ordering::Less
    }
}

impl Kind for Max {
    fn ordering() -> Ordering {
        Ordering::Greater
    }
}

/// Sealed traits
mod private {
    pub trait Sealed {}
}

impl private::Sealed for Max {}
impl private::Sealed for Min {}

/// Base struct for [`BinaryHeap`] and [`BinaryHeapView`], generic over the [`VecStorage`].
///
/// In most cases you should use [`BinaryHeap`] or [`BinaryHeapView`] directly. Only use this
/// struct if you want to write code that's generic over both.
#[cfg_attr(
    feature = "zeroize",
    derive(Zeroize),
    zeroize(bound = "T: Zeroize, S: Zeroize")
)]
pub struct BinaryHeapInner<T, K, S: VecStorage<T> + ?Sized> {
    pub(crate) _kind: PhantomData<K>,
    pub(crate) data: VecInner<T, usize, S>,
}

/// A priority queue implemented with a binary heap.
///
/// This can be either a min-heap or a max-heap.
///
/// It is a logic error for an item to be modified in such a way that the item's ordering relative
/// to any other item, as determined by the `Ord` trait, changes while it is in the heap. This is
/// normally only possible through `Cell`, `RefCell`, global state, I/O, or unsafe code.
///
/// ```
/// use heapless::binary_heap::{BinaryHeap, Max};
///
/// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
///
/// // We can use peek to look at the next item in the heap. In this case,
/// // there's no items in there yet so we get None.
/// assert_eq!(heap.peek(), None);
///
/// // Let's add some scores...
/// heap.push(1).unwrap();
/// heap.push(5).unwrap();
/// heap.push(2).unwrap();
///
/// // Now peek shows the most important item in the heap.
/// assert_eq!(heap.peek(), Some(&5));
///
/// // We can check the length of a heap.
/// assert_eq!(heap.len(), 3);
///
/// // We can iterate over the items in the heap, although they are returned in
/// // a random order.
/// for x in &heap {
///     println!("{}", x);
/// }
///
/// // If we instead pop these scores, they should come back in order.
/// assert_eq!(heap.pop(), Some(5));
/// assert_eq!(heap.pop(), Some(2));
/// assert_eq!(heap.pop(), Some(1));
/// assert_eq!(heap.pop(), None);
///
/// // We can clear the heap of any remaining items.
/// heap.clear();
///
/// // The heap should now be empty.
/// assert!(heap.is_empty())
/// ```
pub type BinaryHeap<T, K, const N: usize> = BinaryHeapInner<T, K, OwnedVecStorage<T, N>>;

/// A priority queue implemented with a binary heap.
///
/// This can be either a min-heap or a max-heap.
///
/// It is a logic error for an item to be modified in such a way that the item's ordering relative
/// to any other item, as determined by the `Ord` trait, changes while it is in the heap. This is
/// normally only possible through `Cell`, `RefCell`, global state, I/O, or unsafe code.
///
/// ```
/// use heapless::binary_heap::{BinaryHeap, BinaryHeapView, Max};
///
/// let mut heap_buffer: BinaryHeap<_, Max, 8> = BinaryHeap::new();
/// let heap: &mut BinaryHeapView<_, Max> = &mut heap_buffer;
///
/// // We can use peek to look at the next item in the heap. In this case,
/// // there's no items in there yet so we get None.
/// assert_eq!(heap.peek(), None);
///
/// // Let's add some scores...
/// heap.push(1).unwrap();
/// heap.push(5).unwrap();
/// heap.push(2).unwrap();
///
/// // Now peek shows the most important item in the heap.
/// assert_eq!(heap.peek(), Some(&5));
///
/// // We can check the length of a heap.
/// assert_eq!(heap.len(), 3);
///
/// // We can iterate over the items in the heap, although they are returned in
/// // a random order.
/// for x in &*heap {
///     println!("{}", x);
/// }
///
/// // If we instead pop these scores, they should come back in order.
/// assert_eq!(heap.pop(), Some(5));
/// assert_eq!(heap.pop(), Some(2));
/// assert_eq!(heap.pop(), Some(1));
/// assert_eq!(heap.pop(), None);
///
/// // We can clear the heap of any remaining items.
/// heap.clear();
///
/// // The heap should now be empty.
/// assert!(heap.is_empty())
/// ```
pub type BinaryHeapView<T, K> = BinaryHeapInner<T, K, ViewVecStorage<T>>;

impl<T, K, const N: usize> BinaryHeap<T, K, N> {
    /* Constructors */
    /// Creates an empty `BinaryHeap` as a $K-heap.
    ///
    /// ```
    /// use heapless::binary_heap::{BinaryHeap, Max};
    ///
    /// // allocate the binary heap on the stack
    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
    /// heap.push(4).unwrap();
    ///
    /// // allocate the binary heap in a static variable
    /// static mut HEAP: BinaryHeap<i32, Max, 8> = BinaryHeap::new();
    /// ```
    pub const fn new() -> Self {
        Self {
            _kind: PhantomData,
            data: Vec::new(),
        }
    }
}

impl<T, K, const N: usize> BinaryHeap<T, K, N> {
    /// Returns the underlying `Vec<T,N>`. Order is arbitrary and time is *O*(1).
    pub fn into_vec(self) -> Vec<T, N, usize> {
        self.data
    }
}

impl<T, K, S: VecStorage<T>> BinaryHeapInner<T, K, S> {
    /// Get a reference to the `BinaryHeap`, erasing the `N` const-generic.
    pub fn as_view(&self) -> &BinaryHeapView<T, K> {
        S::as_binary_heap_view(self)
    }
    /// Get a mutable reference to the `BinaryHeap`, erasing the `N` const-generic.
    pub fn as_mut_view(&mut self) -> &mut BinaryHeapView<T, K> {
        S::as_binary_heap_view_mut(self)
    }
}

impl<T, K, S: VecStorage<T> + ?Sized> BinaryHeapInner<T, K, S>
where
    T: Ord,
    K: Kind,
{
    /* Public API */
    /// Returns the capacity of the binary heap.
    pub fn capacity(&self) -> usize {
        self.data.capacity()
    }

    /// Drops all items from the binary heap.
    ///
    /// ```
    /// use heapless::binary_heap::{BinaryHeap, Max};
    ///
    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
    /// heap.push(1).unwrap();
    /// heap.push(3).unwrap();
    ///
    /// assert!(!heap.is_empty());
    ///
    /// heap.clear();
    ///
    /// assert!(heap.is_empty());
    /// ```
    pub fn clear(&mut self) {
        self.data.clear();
    }

    /// Returns the length of the binary heap.
    ///
    /// ```
    /// use heapless::binary_heap::{BinaryHeap, Max};
    ///
    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
    /// heap.push(1).unwrap();
    /// heap.push(3).unwrap();
    ///
    /// assert_eq!(heap.len(), 2);
    /// ```
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Checks if the binary heap is empty.
    ///
    /// ```
    /// use heapless::binary_heap::{BinaryHeap, Max};
    ///
    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
    ///
    /// assert!(heap.is_empty());
    ///
    /// heap.push(3).unwrap();
    /// heap.push(5).unwrap();
    /// heap.push(1).unwrap();
    ///
    /// assert!(!heap.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Checks if the binary heap is full.
    ///
    /// ```
    /// use heapless::binary_heap::{BinaryHeap, Max};
    ///
    /// let mut heap: BinaryHeap<_, Max, 4> = BinaryHeap::new();
    ///
    /// assert!(!heap.is_full());
    ///
    /// heap.push(1).unwrap();
    /// heap.push(2).unwrap();
    /// heap.push(3).unwrap();
    /// heap.push(4).unwrap();
    ///
    /// assert!(heap.is_full());
    /// ```
    pub fn is_full(&self) -> bool {
        self.len() == self.capacity()
    }

    /// Returns an iterator visiting all values in the underlying vector, in arbitrary order.
    ///
    /// ```
    /// use heapless::binary_heap::{BinaryHeap, Max};
    ///
    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
    /// heap.push(1).unwrap();
    /// heap.push(2).unwrap();
    /// heap.push(3).unwrap();
    /// heap.push(4).unwrap();
    ///
    /// // Print 1, 2, 3, 4 in arbitrary order
    /// for x in heap.iter() {
    ///     println!("{}", x);
    /// }
    /// ```
    pub fn iter(&self) -> slice::Iter<'_, T> {
        self.data.as_slice().iter()
    }

    /// Returns a mutable iterator visiting all values in the underlying vector, in arbitrary order.
    ///
    /// **WARNING** Mutating the items in the binary heap can leave the heap in an inconsistent
    /// state.
    pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
        self.data.as_mut_slice().iter_mut()
    }

    /// Returns the *top* (greatest if max-heap, smallest if min-heap) item in the binary heap, or
    /// None if it is empty.
    ///
    /// ```
    /// use heapless::binary_heap::{BinaryHeap, Max};
    ///
    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
    /// assert_eq!(heap.peek(), None);
    ///
    /// heap.push(1).unwrap();
    /// heap.push(5).unwrap();
    /// heap.push(2).unwrap();
    /// assert_eq!(heap.peek(), Some(&5));
    /// ```
    pub fn peek(&self) -> Option<&T> {
        self.data.as_slice().first()
    }

    /// Returns a mutable reference to the greatest item in the binary heap, or
    /// `None` if it is empty.
    ///
    /// Note: If the `PeekMut` value is leaked, the heap may be in an
    /// inconsistent state.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use heapless::binary_heap::{BinaryHeap, Max};
    ///
    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
    /// assert!(heap.peek_mut().is_none());
    ///
    /// heap.push(1);
    /// heap.push(5);
    /// heap.push(2);
    /// {
    ///     let mut val = heap.peek_mut().unwrap();
    ///     *val = 0;
    /// }
    ///
    /// assert_eq!(heap.peek(), Some(&2));
    /// ```
    pub fn peek_mut(&mut self) -> Option<PeekMutInner<'_, T, K, S>> {
        if self.is_empty() {
            return None;
        }
        // SAFETY: the heap has at least one item because of the previous condition.
        Some(unsafe { PeekMutInner::new(self) })
    }

    /// Removes the *top* (greatest if max-heap, smallest if min-heap) item from the binary heap and
    /// returns it, or None if it is empty.
    ///
    /// ```
    /// use heapless::binary_heap::{BinaryHeap, Max};
    ///
    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
    /// heap.push(1).unwrap();
    /// heap.push(3).unwrap();
    ///
    /// assert_eq!(heap.pop(), Some(3));
    /// assert_eq!(heap.pop(), Some(1));
    /// assert_eq!(heap.pop(), None);
    /// ```
    pub fn pop(&mut self) -> Option<T> {
        if self.is_empty() {
            return None;
        }
        // SAFETY: the heap has at least one item because of the previous condition.
        Some(unsafe { self.pop_unchecked() })
    }

    /// Removes the *top* (greatest if max-heap, smallest if min-heap) item from the binary heap and
    /// returns it, without checking if the binary heap is empty.
    ///
    /// # Safety
    ///
    /// The binary heap must not be empty.
    ///
    /// # Example
    ///
    /// ```
    /// use heapless::binary_heap::{BinaryHeap, Max};
    ///
    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
    /// heap.push(42)?;
    ///
    /// // SAFETY: We just pushed a number onto the heap, so it cannot be empty.
    /// let val = unsafe { heap.pop_unchecked() };
    /// assert_eq!(val, 42);
    /// # Ok::<(), u8>(())
    /// ```
    pub unsafe fn pop_unchecked(&mut self) -> T {
        // SAFETY: the binary heap is not empty, thus `0` is smaller than `self.len()`.
        unsafe { self.remove_unchecked(0) }
    }

    /// Retains only the elements specified by the predicate.
    ///
    /// The elements are visited in arbitrary order.
    ///
    /// # Examples
    ///
    /// ```
    /// use heapless::binary_heap::{BinaryHeap, Max};
    ///
    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
    /// heap.push(1).unwrap();
    /// heap.push(2).unwrap();
    /// heap.push(3).unwrap();
    /// heap.push(4).unwrap();
    ///
    /// heap.retain(|&x| x % 2 == 0);
    ///
    /// let mut iter = heap.iter();
    /// assert_eq!(iter.next(), Some(&4));
    /// assert_eq!(iter.next(), Some(&2));
    /// assert_eq!(iter.next(), None);
    /// ```
    pub fn retain<F>(&mut self, mut f: F)
    where
        F: FnMut(&T) -> bool,
    {
        let mut index = 0;
        while let Some(item) = self.data.get(index) {
            if f(item) {
                index += 1;
            } else {
                // SAFETY: `index` is valid because of the loop condition.
                unsafe { self.remove_unchecked(index) };
            }
        }
    }

    /// Pushes an item onto the binary heap.
    ///
    /// ```
    /// use heapless::binary_heap::{BinaryHeap, Max};
    ///
    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
    /// heap.push(3).unwrap();
    /// heap.push(5).unwrap();
    /// heap.push(1).unwrap();
    ///
    /// assert_eq!(heap.len(), 3);
    /// assert_eq!(heap.peek(), Some(&5));
    /// ```
    pub fn push(&mut self, item: T) -> Result<(), T> {
        if self.data.is_full() {
            return Err(item);
        }
        // SAFETY: the heap is not full because of the previous condition.
        unsafe { self.push_unchecked(item) }
        Ok(())
    }

    /// Pushes an item onto the binary heap without first checking if it's full.
    ///
    /// # Safety
    ///
    /// The binary heap must not be full.
    ///
    /// # Example
    ///
    /// ```
    /// use heapless::binary_heap::{BinaryHeap, Max};
    ///
    /// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
    ///
    /// // SAFETY: We just created an empty heap of size 8, so it cannot be full.
    /// unsafe { heap.push_unchecked(42) };
    /// assert_eq!(heap.len(), 1);
    /// assert_eq!(heap.peek(), Some(&42));
    /// ```
    pub unsafe fn push_unchecked(&mut self, item: T) {
        let old_len = self.len();
        // SAFETY: the function precondition guarantees that the heap is not full.
        unsafe { self.data.push_unchecked(item) };
        // SAFETY: `old_len` is now a valid index because a new item has been pushed.
        unsafe { self.sift_up(0, old_len) };
    }

    /* Private API */

    /// Removes and returns the element at position `index` within the inner vec.
    ///
    /// The elements are shifted to preserve the invariants of the binary heap.
    ///
    /// # Safety
    ///
    /// The length of the heap must be larger than `index`.
    unsafe fn remove_unchecked(&mut self, index: usize) -> T {
        debug_assert!(index < self.len());
        // SAFETY: the heap is not empty because of the precondition.
        let mut item = unsafe { self.data.pop_unchecked() };
        if let Some(item_to_remove) = self.data.get_mut(index) {
            mem::swap(&mut item, item_to_remove);
            // SAFETY: `index` is within the data slice because of the condition.
            unsafe { self.sift_down_to_bottom(index) };
        }
        item
    }

    /// Moves the element from `pos` down through the heap until it becomes a leaf,
    /// then sift up the element to meet the order invariant.
    ///
    /// # Safety
    ///
    /// `pos` must be within the data slice.
    unsafe fn sift_down_to_bottom(&mut self, mut pos: usize) {
        let end = self.len();
        let start = pos;
        // Scope to limit the lifetime of the hole.
        {
            // SAFETY: `pos` is within the data slice because of the function precondition.
            let mut hole = unsafe { Hole::new(self.data.as_mut_slice(), pos) };
            let mut child = 2 * pos + 1;
            while child < end {
                let right = child + 1;
                // SAFETY: `child` is within the data slice because it is lower than `end`.
                let child_val = unsafe { hole.get(child) };
                // Compares with the greater of the two children.
                // SAFETY: `right` is within the data slice because it is lower than `end`.
                if right < end && child_val.cmp(unsafe { hole.get(right) }) != K::ordering() {
                    child = right;
                }
                // SAFETY: `child` is within the data slice because it is lower than `end`.
                unsafe { hole.move_to(child) };
                child = 2 * hole.pos() + 1;
            }
            pos = hole.pos;
        }
        // Moves the element up to satisfy the order invariant.
        // SAFETY: `pos` is within the data slice because `hole` keeps track of a valid index.
        unsafe { self.sift_up(start, pos) };
    }

    /// Moves the element at `pos` up through the heap until either the order
    /// invariant is met or the `start` position is reached.
    ///
    /// # Safety
    ///
    /// `pos` must be within the data slice.
    unsafe fn sift_up(&mut self, start: usize, pos: usize) -> usize {
        // Take out the value at `pos` and create a hole.
        // SAFETY: `pos` is within the data slice because of the function precondition.
        let mut hole = unsafe { Hole::new(self.data.as_mut_slice(), pos) };

        while hole.pos() > start {
            let parent = (hole.pos() - 1) / 2;
            if hole.element().cmp(unsafe { hole.get(parent) }) != K::ordering() {
                break;
            }
            // SAFETY: `parent` is within the data slice because it is lower than `pos`.
            unsafe { hole.move_to(parent) };
        }
        hole.pos()
    }
}

/// Hole represents a hole in a slice i.e. an index without valid value
/// (because it was moved from or duplicated).
/// In drop, `Hole` will restore the slice by filling the hole
/// position with the value that was originally removed.
struct Hole<'a, T> {
    data: &'a mut [T],
    /// `elt` is always `Some` from new until drop.
    elt: ManuallyDrop<T>,
    pos: usize,
}

impl<'a, T> Hole<'a, T> {
    /// Create a new Hole at index `pos`.
    ///
    /// # Safety
    ///
    /// `pos` must be within the data slice.
    #[inline]
    unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
        debug_assert!(pos < data.len());
        let elt = ptr::read(data.get_unchecked(pos));
        Hole {
            data,
            elt: ManuallyDrop::new(elt),
            pos,
        }
    }

    #[inline]
    fn pos(&self) -> usize {
        self.pos
    }

    /// Returns a reference to the element removed.
    #[inline]
    fn element(&self) -> &T {
        &self.elt
    }

    /// Returns a reference to the element at `index`.
    ///
    /// # Safety
    ///
    /// `index` must be within the data slice and not equal to [`Self::pos`].
    #[inline]
    unsafe fn get(&self, index: usize) -> &T {
        debug_assert!(index != self.pos);
        debug_assert!(index < self.data.len());
        // SAFETY: `index` is valid because of the function precondition.
        unsafe { self.data.get_unchecked(index) }
    }

    /// Move hole to new location
    ///
    /// # Safety
    ///
    /// `index` must be within the data slice and not equal to [`Self::pos`].
    #[inline]
    unsafe fn move_to(&mut self, index: usize) {
        debug_assert!(index != self.pos);
        debug_assert!(index < self.data.len());
        let ptr = self.data.as_mut_ptr();
        let index_ptr: *const _ = ptr.add(index);
        let hole_ptr = ptr.add(self.pos);
        ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
        self.pos = index;
    }
}

/// Structure wrapping a mutable reference to the greatest item on a
/// `BinaryHeap`.
///
/// This `struct` is created by [`BinaryHeapInner::peek_mut`].
/// See its documentation for more.
pub struct PeekMutInner<'a, T, K, S>
where
    T: Ord,
    K: Kind,
    S: VecStorage<T> + ?Sized,
{
    /// Non-empty heap.
    heap: &'a mut BinaryHeapInner<T, K, S>,
    /// Does the peek item has been removed.
    /// The item can be removed using [`Self::pop`].
    removed: bool,
}
impl<'a, T, K, S> PeekMutInner<'a, T, K, S>
where
    T: Ord,
    K: Kind,
    S: VecStorage<T> + ?Sized,
{
    /// Creates a new instance that allows removing or mutating the first item of `heap`.
    ///
    /// # Safety
    ///
    /// The heap must not be empty.
    unsafe fn new(heap: &'a mut BinaryHeapInner<T, K, S>) -> Self {
        debug_assert!(!heap.is_empty());
        Self {
            heap,
            removed: false,
        }
    }
}

/// Structure wrapping a mutable reference to the greatest item on a
/// `BinaryHeap`.
///
/// This `struct` is created by [`BinaryHeap::peek_mut`].
/// See its documentation for more.
pub type PeekMut<'a, T, K, const N: usize> = PeekMutInner<'a, T, K, OwnedVecStorage<T, N>>;

/// Structure wrapping a mutable reference to the greatest item on a
/// `BinaryHeap`.
///
/// This `struct` is created by [`BinaryHeapView::peek_mut`].
/// See its documentation for more.
pub type PeekMutView<'a, T, K> = PeekMutInner<'a, T, K, ViewVecStorage<T>>;

impl<T, K, S> Drop for PeekMutInner<'_, T, K, S>
where
    T: Ord,
    K: Kind,
    S: VecStorage<T> + ?Sized,
{
    fn drop(&mut self) {
        if self.removed {
            return;
        }
        // SAFETY: the heap has at least one item because
        // `PeekMut` is only instantiated wiforth non-empty heaps and `removed` is still `false`.
        unsafe { self.heap.sift_down_to_bottom(0) };
    }
}

impl<T, K, S> Deref for PeekMutInner<'_, T, K, S>
where
    T: Ord,
    K: Kind,
    S: VecStorage<T> + ?Sized,
{
    type Target = T;
    fn deref(&self) -> &T {
        debug_assert!(!self.heap.is_empty());
        // SAFETY: `PeekMut` is only instantiated for non-empty heaps.
        unsafe { self.heap.data.as_slice().get_unchecked(0) }
    }
}

impl<T, K, S> DerefMut for PeekMutInner<'_, T, K, S>
where
    T: Ord,
    K: Kind,
    S: VecStorage<T> + ?Sized,
{
    fn deref_mut(&mut self) -> &mut T {
        debug_assert!(!self.heap.is_empty());
        // SAFE: PeekMut is only instantiated for non-empty heaps.
        unsafe { self.heap.data.as_mut_slice().get_unchecked_mut(0) }
    }
}

impl<T, K, S> PeekMutInner<'_, T, K, S>
where
    T: Ord,
    K: Kind,
    S: VecStorage<T> + ?Sized,
{
    /// Removes the peeked value from the heap and returns it.
    pub fn pop(mut this: Self) -> T {
        // SAFE: PeekMut is only instantiated for non-empty heaps.
        let value = unsafe { this.heap.pop_unchecked() };
        this.removed = true;
        value
    }
}

impl<T> Drop for Hole<'_, T> {
    #[inline]
    fn drop(&mut self) {
        // fill the hole again
        unsafe {
            let pos = self.pos;
            ptr::write(self.data.get_unchecked_mut(pos), ptr::read(&*self.elt));
        }
    }
}

impl<T, K, const N: usize> Default for BinaryHeap<T, K, N>
where
    T: Ord,
    K: Kind,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<T, K, const N: usize> Clone for BinaryHeap<T, K, N>
where
    K: Kind,
    T: Ord + Clone,
{
    fn clone(&self) -> Self {
        Self {
            _kind: self._kind,
            data: self.data.clone(),
        }
    }
}

impl<T, K, S> fmt::Debug for BinaryHeapInner<T, K, S>
where
    K: Kind,
    T: Ord + fmt::Debug,
    S: VecStorage<T> + ?Sized,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.iter()).finish()
    }
}

impl<'a, T, K, S> IntoIterator for &'a BinaryHeapInner<T, K, S>
where
    K: Kind,
    T: Ord,
    S: VecStorage<T> + ?Sized,
{
    type Item = &'a T;
    type IntoIter = slice::Iter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

#[cfg(test)]
mod tests {
    use static_assertions::assert_not_impl_any;

    use super::{BinaryHeap, BinaryHeapView, Max, Min};

    // Ensure a `BinaryHeap` containing `!Send` values stays `!Send` itself.
    assert_not_impl_any!(BinaryHeap<*const (), Max, 4>: Send);
    assert_not_impl_any!(BinaryHeap<*const (), Min, 4>: Send);

    #[test]
    fn static_new() {
        static mut _B: BinaryHeap<i32, Min, 16> = BinaryHeap::new();
    }

    #[test]
    fn drop() {
        droppable!();

        {
            let mut v: BinaryHeap<Droppable, Max, 2> = BinaryHeap::new();
            v.push(Droppable::new()).ok().unwrap();
            v.push(Droppable::new()).ok().unwrap();
            v.pop().unwrap();
        }

        assert_eq!(Droppable::count(), 0);

        {
            let mut v: BinaryHeap<Droppable, Max, 2> = BinaryHeap::new();
            v.push(Droppable::new()).ok().unwrap();
            v.push(Droppable::new()).ok().unwrap();
        }

        assert_eq!(Droppable::count(), 0);

        {
            let mut v: BinaryHeap<Droppable, Min, 2> = BinaryHeap::new();
            v.push(Droppable::new()).ok().unwrap();
            v.push(Droppable::new()).ok().unwrap();
            v.pop().unwrap();
        }

        assert_eq!(Droppable::count(), 0);

        {
            let mut v: BinaryHeap<Droppable, Min, 2> = BinaryHeap::new();
            v.push(Droppable::new()).ok().unwrap();
            v.push(Droppable::new()).ok().unwrap();
        }

        assert_eq!(Droppable::count(), 0);
    }

    #[test]
    fn into_vec() {
        droppable!();

        let mut h: BinaryHeap<Droppable, Max, 2> = BinaryHeap::new();
        h.push(Droppable::new()).ok().unwrap();
        h.push(Droppable::new()).ok().unwrap();
        h.pop().unwrap();

        assert_eq!(Droppable::count(), 1);

        let v = h.into_vec();

        assert_eq!(Droppable::count(), 1);

        core::mem::drop(v);

        assert_eq!(Droppable::count(), 0);
    }

    #[test]
    fn min() {
        let mut heap = BinaryHeap::<_, Min, 16>::new();
        heap.push(1).unwrap();
        heap.push(2).unwrap();
        heap.push(3).unwrap();
        heap.push(17).unwrap();
        heap.push(19).unwrap();
        heap.push(36).unwrap();
        heap.push(7).unwrap();
        heap.push(25).unwrap();
        heap.push(100).unwrap();

        assert_eq!(
            heap.iter().cloned().collect::<Vec<_>>(),
            [1, 2, 3, 17, 19, 36, 7, 25, 100]
        );

        assert_eq!(heap.pop(), Some(1));

        assert_eq!(
            heap.iter().cloned().collect::<Vec<_>>(),
            [2, 17, 3, 25, 19, 36, 7, 100]
        );

        assert_eq!(heap.pop(), Some(2));
        assert_eq!(heap.pop(), Some(3));
        assert_eq!(heap.pop(), Some(7));
        assert_eq!(heap.pop(), Some(17));
        assert_eq!(heap.pop(), Some(19));
        assert_eq!(heap.pop(), Some(25));
        assert_eq!(heap.pop(), Some(36));
        assert_eq!(heap.pop(), Some(100));
        assert_eq!(heap.pop(), None);

        assert!(heap.peek_mut().is_none());

        heap.push(1).unwrap();
        heap.push(2).unwrap();
        heap.push(10).unwrap();

        {
            let mut val = heap.peek_mut().unwrap();
            *val = 7;
        }

        assert_eq!(heap.pop(), Some(2));
        assert_eq!(heap.pop(), Some(7));
        assert_eq!(heap.pop(), Some(10));
        assert_eq!(heap.pop(), None);
    }

    #[test]
    fn max() {
        let mut heap = BinaryHeap::<_, Max, 16>::new();
        heap.push(1).unwrap();
        heap.push(2).unwrap();
        heap.push(3).unwrap();
        heap.push(17).unwrap();
        heap.push(19).unwrap();
        heap.push(36).unwrap();
        heap.push(7).unwrap();
        heap.push(25).unwrap();
        heap.push(100).unwrap();

        assert_eq!(
            heap.iter().cloned().collect::<Vec<_>>(),
            [100, 36, 19, 25, 3, 2, 7, 1, 17]
        );

        assert_eq!(heap.pop(), Some(100));

        assert_eq!(
            heap.iter().cloned().collect::<Vec<_>>(),
            [36, 25, 19, 17, 3, 2, 7, 1]
        );

        assert_eq!(heap.pop(), Some(36));
        assert_eq!(heap.pop(), Some(25));
        assert_eq!(heap.pop(), Some(19));
        assert_eq!(heap.pop(), Some(17));
        assert_eq!(heap.pop(), Some(7));
        assert_eq!(heap.pop(), Some(3));
        assert_eq!(heap.pop(), Some(2));
        assert_eq!(heap.pop(), Some(1));
        assert_eq!(heap.pop(), None);

        assert!(heap.peek_mut().is_none());

        heap.push(1).unwrap();
        heap.push(9).unwrap();
        heap.push(10).unwrap();

        {
            let mut val = heap.peek_mut().unwrap();
            *val = 7;
        }

        assert_eq!(heap.pop(), Some(9));
        assert_eq!(heap.pop(), Some(7));
        assert_eq!(heap.pop(), Some(1));
        assert_eq!(heap.pop(), None);
    }

    #[test]
    fn peek_mut() {
        let mut heap = BinaryHeap::<_, Max, 16>::new();
        heap.push(1).unwrap();
        heap.push(2).unwrap();
        heap.push(3).unwrap();
        heap.push(17).unwrap();
        heap.push(19).unwrap();
        heap.push(36).unwrap();
        heap.push(7).unwrap();
        heap.push(25).unwrap();
        heap.push(100).unwrap();

        {
            let mut val = heap.peek_mut().unwrap();
            *val = 22;
        }

        {
            let mut val = heap.peek_mut().unwrap();
            *val = 9;
        }

        assert_eq!(heap.pop(), Some(25));
        assert_eq!(heap.pop(), Some(22));
        assert_eq!(heap.pop(), Some(19));
        assert_eq!(heap.pop(), Some(17));
        assert_eq!(heap.pop(), Some(9));
        assert_eq!(heap.pop(), Some(7));
        assert_eq!(heap.pop(), Some(3));
        assert_eq!(heap.pop(), Some(2));
        assert_eq!(heap.pop(), Some(1));
        assert_eq!(heap.pop(), None);
    }

    #[test]
    fn retain() {
        let mut heap = BinaryHeap::<_, Max, 8>::new();
        heap.retain(|_: &i32| true);
        heap.retain(|_: &i32| false);
        assert_eq!(heap.len(), 0);

        let mut heap = BinaryHeap::<_, Max, 8>::new();
        heap.push(1).unwrap();
        heap.push(2).unwrap();
        heap.push(3).unwrap();
        heap.retain(|&e| e != 1);
        assert_eq!(heap.pop(), Some(3));
        assert_eq!(heap.pop(), Some(2));
        assert_eq!(heap.pop(), None);

        let mut heap = BinaryHeap::<_, Max, 8>::new();
        heap.push(1).unwrap();
        heap.push(2).unwrap();
        heap.push(3).unwrap();
        heap.retain(|&e| e != 3);
        assert_eq!(heap.pop(), Some(2));
        assert_eq!(heap.pop(), Some(1));
        assert_eq!(heap.pop(), None);

        let mut heap = BinaryHeap::<_, Max, 8>::new();
        heap.push(1).unwrap();
        heap.push(2).unwrap();
        heap.push(3).unwrap();
        heap.retain(|&e| e != 2);
        assert_eq!(heap.pop(), Some(3));
        assert_eq!(heap.pop(), Some(1));
        assert_eq!(heap.pop(), None);

        let mut heap = BinaryHeap::<_, Max, 16>::new();
        heap.push(1).unwrap();
        heap.push(2).unwrap();
        heap.push(3).unwrap();
        heap.push(17).unwrap();
        heap.push(19).unwrap();
        heap.push(36).unwrap();
        heap.push(7).unwrap();
        heap.push(25).unwrap();
        heap.push(100).unwrap();
        heap.retain(|&x| x % 2 == 0);

        assert_eq!(heap.pop(), Some(100));
        assert_eq!(heap.pop(), Some(36));
        assert_eq!(heap.pop(), Some(2));
        assert_eq!(heap.pop(), None);

        let mut heap = BinaryHeap::<_, Max, 16>::new();
        heap.push(1).unwrap();
        heap.push(2).unwrap();
        heap.push(3).unwrap();
        heap.push(17).unwrap();
        heap.push(19).unwrap();
        heap.push(36).unwrap();
        heap.push(7).unwrap();
        heap.push(25).unwrap();
        heap.push(100).unwrap();
        heap.retain(|&x| x % 2 != 0);

        assert_eq!(heap.pop(), Some(25));
        assert_eq!(heap.pop(), Some(19));
        assert_eq!(heap.pop(), Some(17));
        assert_eq!(heap.pop(), Some(7));
        assert_eq!(heap.pop(), Some(3));
        assert_eq!(heap.pop(), Some(1));
        assert_eq!(heap.pop(), None);
    }

    #[test]
    fn remove_unchecked() {
        // This test depends on private APIs.

        let mut heap = BinaryHeap::<_, Max, 16>::new();
        heap.push(1).unwrap();
        heap.push(2).unwrap();
        heap.push(3).unwrap();
        heap.push(17).unwrap();
        heap.push(19).unwrap();
        heap.push(36).unwrap();
        heap.push(7).unwrap();
        heap.push(25).unwrap();
        heap.push(100).unwrap();

        assert_eq!(
            heap.iter()
                .copied()
                .collect::<crate::vec::Vec::<i32, 16>>()
                .as_slice(),
            &[100, 36, 19, 25, 3, 2, 7, 1, 17],
        );

        unsafe {
            heap.remove_unchecked(1);
        }
        assert_eq!(
            heap.iter()
                .copied()
                .collect::<crate::vec::Vec::<i32, 16>>()
                .as_slice(),
            &[100, 25, 19, 17, 3, 2, 7, 1],
        );

        unsafe {
            heap.remove_unchecked(2);
        }
        assert_eq!(
            heap.iter()
                .copied()
                .collect::<crate::vec::Vec::<i32, 16>>()
                .as_slice(),
            &[100, 25, 7, 17, 3, 2, 1],
        );

        unsafe {
            heap.remove_unchecked(3);
        }
        assert_eq!(
            heap.iter()
                .copied()
                .collect::<crate::vec::Vec::<i32, 16>>()
                .as_slice(),
            &[100, 25, 7, 1, 3, 2],
        );

        unsafe {
            heap.remove_unchecked(5);
        }
        assert_eq!(
            heap.iter()
                .copied()
                .collect::<crate::vec::Vec::<i32, 16>>()
                .as_slice(),
            &[100, 25, 7, 1, 3],
        );

        unsafe {
            heap.remove_unchecked(0);
        }
        assert_eq!(
            heap.iter()
                .copied()
                .collect::<crate::vec::Vec::<i32, 16>>()
                .as_slice(),
            &[25, 3, 7, 1],
        );
    }

    #[test]
    #[cfg(feature = "zeroize")]
    fn test_binary_heap_zeroize() {
        use zeroize::Zeroize;

        let mut heap = BinaryHeap::<u8, Max, 8>::new();
        for i in 0..8 {
            heap.push(i).unwrap();
        }

        assert_eq!(heap.len(), 8);
        assert_eq!(heap.peek(), Some(&7));

        // zeroized using Vec's implementation
        heap.zeroize();
        assert_eq!(heap.len(), 0);
    }

    fn _test_variance<'a: 'b, 'b>(x: BinaryHeap<&'a (), Max, 42>) -> BinaryHeap<&'b (), Max, 42> {
        x
    }
    fn _test_variance_view<'a: 'b, 'b, 'c>(
        x: &'c BinaryHeapView<&'a (), Max>,
    ) -> &'c BinaryHeapView<&'b (), Max> {
        x
    }
}