Skip to main content

paged_collections/
priority_queue.rs

1//! [`PagedPriorityQueue`]: an indexed max-heap with a paged key index.
2//!
3//! The greatest priority is returned first. Use [`core::cmp::Reverse`] for a
4//! min-queue. Equal priorities have unspecified order. Keys and priorities
5//! occupy parallel contiguous arrays in heap order; a four-way heap keeps
6//! insertion, priority changes and removal to O(log n) comparisons.
7//!
8//! Lookups use [`PagedSparseSet`]'s paged index. With [`Flat`] they are O(1);
9//! [`Radix`](crate::page::Radix) and [`Tree`](crate::page::Tree) add their
10//! directory lookup costs to each index access. Only occupied key ranges
11//! allocate index pages.
12//!
13//! A slot holds one key. [`push`](PagedPriorityQueue::push) evicts another
14//! generation of that key; [`try_push`](PagedPriorityQueue::try_push) refuses
15//! it. Lookups always check the whole key, including its generation.
16//!
17//! # Panic safety and ordering
18//!
19//! If a priority comparison or a closure passed to
20//! [`change_priority_with`](PagedPriorityQueue::change_priority_with) panics,
21//! all remaining entries stay findable and paired with their priorities.
22//! A mutation already made remains made, but heap order may be broken, so
23//! subsequent maximum and sorted-order results are unspecified. Changing a
24//! stored priority's ordering through interior mutability is a logic error
25//! with the same consequence. These errors cannot cause undefined behaviour.
26//!
27//! ```
28//! use paged_collections::priority_queue::PagedPriorityQueue;
29//!
30//! let mut queue: PagedPriorityQueue<u32, i32> = PagedPriorityQueue::new();
31//! assert_eq!(queue.push(7, 10), None);
32//! assert_eq!(queue.push(3_000_000, 20), None);
33//! assert_eq!(queue.change_priority(&7, 30), Some(10));
34//! assert_eq!(queue.pop(), Some((7, 30)));
35//! assert_eq!(queue.pop(), Some((3_000_000, 20)));
36//! ```
37//!
38//! With the `rayon` feature, the shared parallel iterator is indexed and
39//! follows heap order.
40//!
41//! ```rust
42//! # #[cfg(feature = "rayon")] {
43//! use paged_collections::priority_queue::PagedPriorityQueue;
44//! use rayon::prelude::*;
45//!
46//! let mut queue: PagedPriorityQueue<u32, i32> = PagedPriorityQueue::new();
47//! queue.push(7, 10);
48//! queue.push(2, 20);
49//! assert_eq!(queue.par_iter().map(|(&k, &p)| (k, p)).collect::<Vec<_>>(), [(2, 20), (7, 10)]);
50//! # }
51//! ```
52
53use alloc::collections::TryReserveError;
54use alloc::vec::Vec;
55use core::fmt;
56use core::hash::{Hash, Hasher};
57use core::iter::{FusedIterator, Zip};
58use core::marker::PhantomData;
59use core::slice;
60
61use crate::hash::hash_unordered;
62use crate::key::Key;
63use crate::page::{DEFAULT_PAGE, Directory, Flat};
64use crate::paged_vec::capacity_overflow;
65use crate::sparse_set::{PagedSparseSet, Slot};
66
67const ARITY: usize = 4;
68
69/// An indexed max-priority queue with a paged index and dense heap storage.
70///
71/// `PAGE` is the non-zero number of index slots per page. `D` selects the
72/// directory: [`Flat`] (default), [`Radix`](crate::page::Radix), or
73/// [`Tree`](crate::page::Tree). See [`crate::page`]. At most `u32::MAX`
74/// entries can be stored. The greatest priority is at position zero; ties
75/// have unspecified order. See the [module docs](self) for panic safety.
76pub struct PagedPriorityQueue<K, P, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
77    // Invariants: equal lengths; priorities[i] belongs to keys.as_slice()[i].
78    // For i > 0, priorities[(i - 1) / ARITY] >= priorities[i], unless user
79    // code panicked or changed ordering through interior mutability.
80    keys: PagedSparseSet<K, PAGE, D>,
81    priorities: Vec<P>,
82}
83
84impl<K: Key, P, const PAGE: usize, D: Directory> PagedPriorityQueue<K, P, PAGE, D> {
85    /// Creates an empty queue without allocating.
86    pub fn new() -> Self {
87        Self {
88            keys: PagedSparseSet::new(),
89            priorities: Vec::new(),
90        }
91    }
92
93    /// Creates an empty queue with room for at least `capacity` entries in
94    /// its dense arrays. Index pages are allocated on demand.
95    pub fn with_capacity(capacity: usize) -> Self {
96        Self {
97            keys: PagedSparseSet::with_capacity(capacity),
98            priorities: Vec::with_capacity(capacity),
99        }
100    }
101
102    /// Number of entries in the queue.
103    pub fn len(&self) -> usize {
104        self.priorities.len()
105    }
106
107    /// Whether the queue has no entries.
108    pub fn is_empty(&self) -> bool {
109        self.priorities.is_empty()
110    }
111
112    /// Number of entries the dense arrays can hold without reallocating.
113    pub fn capacity(&self) -> usize {
114        self.keys.capacity().min(self.priorities.capacity())
115    }
116
117    /// Reserves room for at least `additional` more entries in both dense arrays.
118    pub fn reserve(&mut self, additional: usize) {
119        self.keys.reserve(additional);
120        self.priorities.reserve(additional);
121    }
122
123    /// Reserves room for at least `additional` more entries in both dense arrays.
124    ///
125    /// Returns an error if the capacity overflows or allocation fails. On
126    /// error the entries, capacity and array addresses are preserved.
127    ///
128    /// # Examples
129    ///
130    /// ```
131    /// use paged_collections::priority_queue::PagedPriorityQueue;
132    ///
133    /// let mut queue: PagedPriorityQueue<usize, i32> = PagedPriorityQueue::new();
134    /// queue.try_reserve(16).unwrap();
135    /// assert!(queue.capacity() >= 16);
136    /// ```
137    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
138        let needed = self
139            .len()
140            .checked_add(additional)
141            .ok_or_else(capacity_overflow)?;
142        if self.keys.capacity() >= needed {
143            return self.priorities.try_reserve(additional);
144        }
145        if self.priorities.capacity() >= needed {
146            return self.keys.try_reserve(additional);
147        }
148
149        // Stage the priority allocation so a key allocation failure leaves
150        // both original arrays in place. Moving priorities into the staged
151        // buffer cannot allocate or run user code.
152        let mut priorities = Vec::new();
153        priorities.try_reserve(needed)?;
154        self.keys.try_reserve(additional)?;
155        for priority in self.priorities.drain(..) {
156            priorities.push(priority);
157        }
158        self.priorities = priorities;
159        Ok(())
160    }
161
162    /// Shrinks the dense arrays and index directory. Frees every index page
163    /// if the queue is empty.
164    pub fn shrink_to_fit(&mut self) {
165        self.keys.shrink_to_fit();
166        self.priorities.shrink_to_fit();
167    }
168
169    /// Removes every entry, dropping its priority. Index pages and dense
170    /// capacity stay allocated for reuse.
171    pub fn clear(&mut self) {
172        // Vec::clear sets its length to zero before running P::drop. Clear
173        // the keys first, so even a panicking destructor leaves equal lengths.
174        self.keys.clear();
175        self.priorities.clear();
176    }
177
178    /// Number of allocated pages in the key index.
179    pub fn allocated_pages(&self) -> usize {
180        self.keys.allocated_pages()
181    }
182
183    /// The stored key and greatest priority, or `None` if empty.
184    pub fn peek(&self) -> Option<(&K, &P)> {
185        self.keys.as_slice().first().zip(self.priorities.first())
186    }
187
188    /// Whether the exact key is present, including its generation.
189    pub fn contains_key(&self, key: &K) -> bool {
190        self.keys.contains(*key)
191    }
192
193    /// The priority of the exact key, or `None` if absent.
194    pub fn priority(&self, key: &K) -> Option<&P> {
195        self.position(key).map(|pos| &self.priorities[pos])
196    }
197
198    /// Heap position of the exact key, or `None` if absent.
199    ///
200    /// Positions index both slices and can change on any heap mutation.
201    pub fn position(&self, key: &K) -> Option<usize> {
202        self.keys.position(*key)
203    }
204
205    /// Iterates over entries in heap order, which is otherwise unspecified.
206    pub fn iter(&self) -> Iter<'_, K, P> {
207        self.keys.iter().zip(self.priorities.iter())
208    }
209
210    /// Iterates over keys in heap order.
211    pub fn keys(&self) -> slice::Iter<'_, K> {
212        self.keys.iter()
213    }
214
215    /// Iterates over priorities in heap order.
216    pub fn priorities(&self) -> slice::Iter<'_, P> {
217        self.priorities.iter()
218    }
219
220    /// Keys in heap order; position zero has the greatest priority.
221    pub fn key_slice(&self) -> &[K] {
222        self.keys.as_slice()
223    }
224
225    /// Priorities in heap order, parallel to [`key_slice`](Self::key_slice).
226    pub fn priority_slice(&self) -> &[P] {
227        &self.priorities
228    }
229
230    /// Removes all entries eagerly and iterates over them in arbitrary order.
231    ///
232    /// Index pages and dense capacity are kept. Dropping the iterator drops
233    /// its remaining entries; forgetting it still leaves the queue empty.
234    /// The queue stays mutably borrowed until the iterator is released.
235    pub fn drain(&mut self) -> Drain<'_, K, P, PAGE, D> {
236        // Allocate before either length changes. All following pushes fit;
237        // copying keys and moving priorities runs no user code.
238        let mut entries = Vec::with_capacity(self.len());
239        for (key, priority) in self.keys.iter().copied().zip(self.priorities.drain(..)) {
240            entries.push((key, priority));
241        }
242        self.keys.clear();
243        Drain {
244            inner: entries.into_iter(),
245            _borrow: PhantomData,
246        }
247    }
248
249    /// Swaps complete entries without comparisons or allocation.
250    fn swap_positions(&mut self, a: usize, b: usize) {
251        self.keys.swap_positions(a, b);
252        self.priorities.swap(a, b);
253    }
254}
255
256impl<K: Key, P: Ord, const PAGE: usize, D: Directory> PagedPriorityQueue<K, P, PAGE, D> {
257    /// Inserts a key or updates its priority, returning the previous priority
258    /// of that same key. An equal stored key is kept.
259    ///
260    /// If another generation holds the slot, it is evicted and `None` is
261    /// returned. The replacement starts at the old entry's position and is
262    /// then sifted to restore heap order.
263    ///
264    /// # Panics
265    ///
266    /// Panics if a new entry would exceed `u32::MAX` entries, if storage
267    /// cannot be allocated, or if comparing priorities panics. Allocation
268    /// failure leaves entries unchanged; a comparison panic has the
269    /// guarantees described in the [module docs](self).
270    pub fn push(&mut self, key: K, priority: P) -> Option<P> {
271        if let Some(pos) = self.keys.occupant_pos(key.index()) {
272            let stored = self.keys.as_slice()[pos];
273            // Equality is user code too: finish it before changing either array.
274            let same = stored == key;
275            if !same {
276                self.keys.replace(key);
277            }
278            let old = core::mem::replace(&mut self.priorities[pos], priority);
279            self.repair(pos);
280            if same { Some(old) } else { None }
281        } else {
282            // Reserve priorities first: once insert appends the key, push
283            // cannot allocate or call user code, so lengths stay in step.
284            self.priorities.reserve(1);
285            self.keys.insert(key);
286            self.priorities.push(priority);
287            self.sift_up(self.len() - 1);
288            None
289        }
290    }
291
292    /// Inserts or updates as [`push`](Self::push), but returns the entry
293    /// previously in `key`'s slot, whether it was `key` itself or another
294    /// generation that is now evicted (as
295    /// [`PagedSparseMap::replace`](crate::sparse_map::PagedSparseMap::replace)).
296    ///
297    /// Unlike `push`, this stores `key` even when the old key is equal to it.
298    /// Panics under the same conditions as `push`.
299    ///
300    /// ```
301    /// use paged_collections::id_alloc::IdAllocator;
302    /// use paged_collections::priority_queue::PagedPriorityQueue;
303    ///
304    /// let mut ids = IdAllocator::new();
305    /// let old = ids.alloc();
306    /// ids.free(old);
307    /// let new = ids.alloc(); // same slot, next generation
308    /// let mut queue: PagedPriorityQueue<_, i32> = PagedPriorityQueue::new();
309    /// queue.push(old, 5);
310    /// assert_eq!(queue.replace(new, 7), Some((old, 5)));
311    /// assert_eq!(queue.replace(new, 9), Some((new, 7)));
312    /// assert_eq!(queue.pop(), Some((new, 9)));
313    /// ```
314    pub fn replace(&mut self, key: K, priority: P) -> Option<(K, P)> {
315        if let Some(pos) = self.keys.occupant_pos(key.index()) {
316            let old_key = self.keys.overwrite_at(pos, key);
317            let old = core::mem::replace(&mut self.priorities[pos], priority);
318            self.repair(pos);
319            Some((old_key, old))
320        } else {
321            self.priorities.reserve(1);
322            self.keys.insert(key);
323            self.priorities.push(priority);
324            self.sift_up(self.len() - 1);
325            None
326        }
327    }
328
329    /// Inserts or updates as [`push`](Self::push), but returns the supplied
330    /// pair unchanged if another generation holds the slot.
331    ///
332    /// Updating the same key is allowed and returns its previous priority.
333    /// Panics under the same conditions as `push`.
334    pub fn try_push(&mut self, key: K, priority: P) -> Result<Option<P>, (K, P)> {
335        if self
336            .keys
337            .occupant(key.index())
338            .is_some_and(|stored| *stored != key)
339        {
340            return Err((key, priority));
341        }
342        Ok(self.push(key, priority))
343    }
344
345    /// Inserts an absent key, or updates it only if `priority` is strictly
346    /// greater. Returns whether the queue changed.
347    ///
348    /// An absent generation evicts another generation as [`push`](Self::push)
349    /// does, regardless of the evicted priority. Panics as `push` does.
350    pub fn push_increase(&mut self, key: K, priority: P) -> bool {
351        if self.priority(&key).is_some_and(|old| priority <= *old) {
352            return false;
353        }
354        self.push(key, priority);
355        true
356    }
357
358    /// Inserts an absent key, or updates it only if `priority` is strictly
359    /// smaller. Returns whether the queue changed.
360    ///
361    /// An absent generation evicts another generation as [`push`](Self::push)
362    /// does, regardless of the evicted priority. Panics as `push` does.
363    pub fn push_decrease(&mut self, key: K, priority: P) -> bool {
364        if self.priority(&key).is_some_and(|old| priority >= *old) {
365            return false;
366        }
367        self.push(key, priority);
368        true
369    }
370
371    /// Changes the priority of a present key, returning its old priority.
372    /// Returns `None` without changing the queue if the exact key is absent.
373    ///
374    /// A comparison panic has the guarantees in the [module docs](self).
375    pub fn change_priority(&mut self, key: &K, priority: P) -> Option<P> {
376        let pos = self.position(key)?;
377        let old = core::mem::replace(&mut self.priorities[pos], priority);
378        self.repair(pos);
379        Some(old)
380    }
381
382    /// Calls `change` on a present key's priority and restores heap order.
383    /// Returns whether the exact key was present; an absent key does not
384    /// call the closure.
385    ///
386    /// If the closure or a comparison panics, its changes remain and heap
387    /// order may be broken, but entries stay findable and correctly paired.
388    pub fn change_priority_with(&mut self, key: &K, change: impl FnOnce(&mut P)) -> bool {
389        let Some(pos) = self.position(key) else {
390            return false;
391        };
392        change(&mut self.priorities[pos]);
393        self.repair(pos);
394        true
395    }
396
397    /// Removes and returns the entry with the greatest priority.
398    ///
399    /// Returns `None` if empty. If comparing priorities panics, the removed
400    /// entry is dropped and the remaining entries stay findable and paired,
401    /// though heap order may be broken.
402    pub fn pop(&mut self) -> Option<(K, P)> {
403        if self.is_empty() {
404            None
405        } else {
406            Some(self.remove_at(0))
407        }
408    }
409
410    /// Removes and returns the stored key and priority for the exact key.
411    ///
412    /// Returns `None` if absent. A comparison panic has the same guarantees
413    /// as [`pop`](Self::pop).
414    pub fn remove(&mut self, key: &K) -> Option<(K, P)> {
415        let pos = self.position(key)?;
416        Some(self.remove_at(pos))
417    }
418
419    fn remove_at(&mut self, pos: usize) -> (K, P) {
420        // Remove by position, not by key equality (user code): the key and
421        // priority arrays stay in step even if `K: Eq` misbehaves. Neither
422        // swap_remove can allocate or run P code.
423        let key = self.keys.remove_at(pos);
424        let priority = self.priorities.swap_remove(pos);
425        if pos < self.len() {
426            self.repair(pos);
427        }
428        (key, priority)
429    }
430
431    /// Consumes the queue into entries in ascending priority order.
432    /// Equal priorities have unspecified order.
433    pub fn into_sorted_vec(self) -> Vec<(K, P)> {
434        let mut entries: Vec<_> = self.into_sorted_iter().collect();
435        entries.reverse();
436        entries
437    }
438
439    /// Consumes the queue and repeatedly pops entries in descending priority
440    /// order. Equal priorities have unspecified order.
441    pub fn into_sorted_iter(self) -> IntoSortedIter<K, P, PAGE, D> {
442        IntoSortedIter { queue: self }
443    }
444
445    fn repair(&mut self, pos: usize) {
446        if pos > 0 && self.priorities[pos] > self.priorities[(pos - 1) / ARITY] {
447            self.sift_up(pos);
448        } else {
449            self.sift_down(pos);
450        }
451    }
452
453    fn sift_up(&mut self, mut pos: usize) {
454        while pos > 0 {
455            let parent = (pos - 1) / ARITY;
456            if self.priorities[parent] >= self.priorities[pos] {
457                break;
458            }
459            // Every completed swap restores pairing and the key index
460            // before the next comparison can panic.
461            self.swap_positions(parent, pos);
462            pos = parent;
463        }
464    }
465
466    fn sift_down(&mut self, mut pos: usize) {
467        // Checked arithmetic also handles a leaf near usize::MAX on 32-bit
468        // targets, where multiplying its position by ARITY could overflow.
469        while let Some(first) = pos.checked_mul(ARITY).and_then(|n| n.checked_add(1)) {
470            if first >= self.len() {
471                break;
472            }
473            let end = first.saturating_add(ARITY).min(self.len());
474            let mut greatest = first;
475            for child in first + 1..end {
476                if self.priorities[child] > self.priorities[greatest] {
477                    greatest = child;
478                }
479            }
480            if self.priorities[pos] >= self.priorities[greatest] {
481                break;
482            }
483            self.swap_positions(pos, greatest);
484            pos = greatest;
485        }
486    }
487
488    #[cfg(test)]
489    fn check(&self) {
490        assert_eq!(self.keys.len(), self.priorities.len());
491        for (pos, key) in self.keys.iter().enumerate() {
492            assert_eq!(self.position(key), Some(pos));
493            if pos > 0 {
494                assert!(self.priorities[(pos - 1) / ARITY] >= self.priorities[pos]);
495            }
496        }
497    }
498}
499
500impl<K: Key, P, const PAGE: usize, D: Directory> Default for PagedPriorityQueue<K, P, PAGE, D> {
501    fn default() -> Self {
502        Self::new()
503    }
504}
505
506impl<K: Key, P: Clone, const PAGE: usize, D: Directory> Clone for PagedPriorityQueue<K, P, PAGE, D>
507where
508    D::Store<Slot, PAGE>: Clone,
509{
510    fn clone(&self) -> Self {
511        Self {
512            keys: self.keys.clone(),
513            priorities: self.priorities.clone(),
514        }
515    }
516}
517
518impl<K: Key + fmt::Debug, P: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
519    for PagedPriorityQueue<K, P, PAGE, D>
520{
521    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
522        f.debug_map().entries(self.iter()).finish()
523    }
524}
525
526/// Compares priorities by exact key using [`priority`](PagedPriorityQueue::priority),
527/// across page sizes and directories. Equality ignores heap layout.
528impl<K: Key, P: PartialEq<Q>, Q, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
529    PartialEq<PagedPriorityQueue<K, Q, P2, D2>> for PagedPriorityQueue<K, P, PAGE, D>
530{
531    fn eq(&self, other: &PagedPriorityQueue<K, Q, P2, D2>) -> bool {
532        self.len() == other.len()
533            && self.iter().all(|(key, priority)| {
534                other
535                    .priority(key)
536                    .is_some_and(|other_priority| priority == other_priority)
537            })
538    }
539}
540
541/// Queue [`PartialEq`] is an equivalence relation when priorities implement [`Eq`].
542impl<K: Key, P: Eq, const PAGE: usize, D: Directory> Eq for PagedPriorityQueue<K, P, PAGE, D> {}
543
544/// Hashes the key-priority pairs in any order, consistent with [`PartialEq`].
545impl<K: Key + Hash, P: Hash, const PAGE: usize, D: Directory> Hash
546    for PagedPriorityQueue<K, P, PAGE, D>
547{
548    fn hash<H: Hasher>(&self, state: &mut H) {
549        hash_unordered(self.iter(), state);
550    }
551}
552
553/// Repeatedly pushes entries, so later entries in a slot win.
554impl<K: Key, P: Ord, const PAGE: usize, D: Directory> Extend<(K, P)>
555    for PagedPriorityQueue<K, P, PAGE, D>
556{
557    fn extend<I: IntoIterator<Item = (K, P)>>(&mut self, iter: I) {
558        for (key, priority) in iter {
559            self.push(key, priority);
560        }
561    }
562}
563
564impl<K: Key, P: Ord, const PAGE: usize, D: Directory> FromIterator<(K, P)>
565    for PagedPriorityQueue<K, P, PAGE, D>
566{
567    fn from_iter<I: IntoIterator<Item = (K, P)>>(iter: I) -> Self {
568        let mut queue = Self::new();
569        queue.extend(iter);
570        queue
571    }
572}
573
574impl<'a, K: Key, P, const PAGE: usize, D: Directory> IntoIterator
575    for &'a PagedPriorityQueue<K, P, PAGE, D>
576{
577    type Item = (&'a K, &'a P);
578    type IntoIter = Iter<'a, K, P>;
579
580    fn into_iter(self) -> Self::IntoIter {
581        self.iter()
582    }
583}
584
585impl<K: Key, P, const PAGE: usize, D: Directory> IntoIterator
586    for PagedPriorityQueue<K, P, PAGE, D>
587{
588    type Item = (K, P);
589    type IntoIter = IntoIter<K, P>;
590
591    fn into_iter(self) -> Self::IntoIter {
592        self.keys.into_iter().zip(self.priorities)
593    }
594}
595
596/// Borrowed iterator over entries in heap order, from
597/// [`iter`](PagedPriorityQueue::iter).
598pub type Iter<'a, K, P> = Zip<slice::Iter<'a, K>, slice::Iter<'a, P>>;
599
600/// Owning iterator over entries in arbitrary heap order.
601pub type IntoIter<K, P> = Zip<alloc::vec::IntoIter<K>, alloc::vec::IntoIter<P>>;
602
603/// Owning iterator over entries in descending priority order, from
604/// [`into_sorted_iter`](PagedPriorityQueue::into_sorted_iter).
605pub struct IntoSortedIter<K, P, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
606    queue: PagedPriorityQueue<K, P, PAGE, D>,
607}
608
609impl<K: Key, P: Ord, const PAGE: usize, D: Directory> Iterator for IntoSortedIter<K, P, PAGE, D> {
610    type Item = (K, P);
611
612    fn next(&mut self) -> Option<Self::Item> {
613        self.queue.pop()
614    }
615
616    fn size_hint(&self) -> (usize, Option<usize>) {
617        let len = self.queue.len();
618        (len, Some(len))
619    }
620}
621
622impl<K: Key, P: Ord, const PAGE: usize, D: Directory> ExactSizeIterator
623    for IntoSortedIter<K, P, PAGE, D>
624{
625}
626impl<K: Key, P: Ord, const PAGE: usize, D: Directory> FusedIterator
627    for IntoSortedIter<K, P, PAGE, D>
628{
629}
630
631/// Iterator over eagerly removed entries, from [`drain`](PagedPriorityQueue::drain).
632/// Dropping it drops any remaining entries; the queue is already empty.
633pub struct Drain<'a, K, P, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
634    inner: alloc::vec::IntoIter<(K, P)>,
635    _borrow: PhantomData<&'a mut PagedPriorityQueue<K, P, PAGE, D>>,
636}
637
638impl<K, P, const PAGE: usize, D: Directory> Iterator for Drain<'_, K, P, PAGE, D> {
639    type Item = (K, P);
640
641    fn next(&mut self) -> Option<Self::Item> {
642        self.inner.next()
643    }
644
645    fn size_hint(&self) -> (usize, Option<usize>) {
646        self.inner.size_hint()
647    }
648}
649
650impl<K, P, const PAGE: usize, D: Directory> DoubleEndedIterator for Drain<'_, K, P, PAGE, D> {
651    fn next_back(&mut self) -> Option<Self::Item> {
652        self.inner.next_back()
653    }
654}
655
656impl<K, P, const PAGE: usize, D: Directory> ExactSizeIterator for Drain<'_, K, P, PAGE, D> {}
657impl<K, P, const PAGE: usize, D: Directory> FusedIterator for Drain<'_, K, P, PAGE, D> {}
658
659#[cfg(feature = "rayon")]
660mod rayon_impl {
661    use super::*;
662    use rayon::prelude::*;
663
664    impl<'a, K: Key + Sync, P: Sync, const PAGE: usize, D: Directory> IntoParallelIterator
665        for &'a PagedPriorityQueue<K, P, PAGE, D>
666    {
667        type Item = (&'a K, &'a P);
668        type Iter = rayon::iter::Zip<rayon::slice::Iter<'a, K>, rayon::slice::Iter<'a, P>>;
669
670        fn into_par_iter(self) -> Self::Iter {
671            self.key_slice()
672                .par_iter()
673                .zip(self.priority_slice().par_iter())
674        }
675    }
676}
677
678#[cfg(feature = "serde")]
679mod serde_impl {
680    use super::*;
681    use serde::de::{Deserialize, Deserializer, SeqAccess, Visitor};
682    use serde::ser::{Serialize, Serializer};
683
684    /// Serializes as a sequence of `(key, priority)` pairs in heap order.
685    impl<K: Key + Serialize, P: Serialize, const PAGE: usize, D: Directory> Serialize
686        for PagedPriorityQueue<K, P, PAGE, D>
687    {
688        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
689            serializer.collect_seq(self.iter())
690        }
691    }
692
693    /// Deserializes pairs by repeated `push`, so later entries in a slot win.
694    /// Memory follows key indices: use Radix or Tree for widely spread keys.
695    impl<'de, K, P, const PAGE: usize, D> Deserialize<'de> for PagedPriorityQueue<K, P, PAGE, D>
696    where
697        K: Key + Deserialize<'de>,
698        P: Ord + Deserialize<'de>,
699        D: Directory,
700    {
701        fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
702            struct SeqVisitor<K, P, const PAGE: usize, D>(PhantomData<(K, P, D)>);
703
704            impl<'de, K, P, const PAGE: usize, D> Visitor<'de> for SeqVisitor<K, P, PAGE, D>
705            where
706                K: Key + Deserialize<'de>,
707                P: Ord + Deserialize<'de>,
708                D: Directory,
709            {
710                type Value = PagedPriorityQueue<K, P, PAGE, D>;
711
712                fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
713                    f.write_str("a sequence of key-priority pairs")
714                }
715
716                fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
717                    // Cap both entry count and bytes from an untrusted hint.
718                    let entry = core::mem::size_of::<K>().saturating_add(core::mem::size_of::<P>());
719                    let bytes = usize::try_from(1_u32 << 20).unwrap_or(usize::MAX);
720                    let cap = bytes.checked_div(entry).unwrap_or(usize::MAX).min(4096);
721                    let mut queue =
722                        PagedPriorityQueue::with_capacity(seq.size_hint().unwrap_or(0).min(cap));
723                    while let Some((key, priority)) = seq.next_element()? {
724                        queue.push(key, priority);
725                    }
726                    Ok(queue)
727                }
728            }
729
730            deserializer.deserialize_seq(SeqVisitor::<K, P, PAGE, D>(PhantomData))
731        }
732    }
733}
734
735#[cfg(test)]
736mod tests {
737    use super::*;
738    use core::cmp::Reverse;
739
740    #[test]
741    fn updates_remove_and_pop_restore_heap_order() {
742        let mut queue: PagedPriorityQueue<u16, i32, 4> = PagedPriorityQueue::new();
743        queue.check();
744        for key in 0..80 {
745            assert_eq!(queue.push(key, i32::from(key)), None);
746            queue.check();
747        }
748        assert_eq!(queue.push(3, 100), Some(3));
749        queue.check();
750        assert_eq!(queue.peek(), Some((&3, &100)));
751        assert_eq!(queue.try_push(3, -100), Ok(Some(100)));
752        queue.check();
753        assert_eq!(queue.change_priority(&1, 120), Some(1));
754        queue.check();
755        assert!(queue.change_priority_with(&1, |p| *p = -120));
756        queue.check();
757        assert_eq!(queue.change_priority(&100, 0), None);
758        queue.check();
759        assert!(!queue.change_priority_with(&100, |_| panic!("absent")));
760        queue.check();
761        // Remove from the middle, the end, and the root.
762        let middle = queue.key_slice()[queue.len() / 2];
763        assert_eq!(queue.remove(&middle).map(|e| e.0), Some(middle));
764        queue.check();
765        let last = *queue.key_slice().last().unwrap();
766        assert_eq!(queue.remove(&last).map(|e| e.0), Some(last));
767        queue.check();
768        assert_eq!(queue.remove(&100), None);
769        queue.check();
770        let mut previous = i32::MAX;
771        while let Some((_, priority)) = queue.pop() {
772            assert!(priority <= previous);
773            previous = priority;
774            queue.check();
775        }
776        assert_eq!(queue.pop(), None);
777        queue.check();
778    }
779
780    #[test]
781    fn strict_changes_ties_and_min_queue() {
782        let mut queue: PagedPriorityQueue<u16, i32, 1> = PagedPriorityQueue::new();
783        assert!(queue.push_increase(1, 10));
784        queue.check();
785        for priority in [9, 10] {
786            assert!(!queue.push_increase(1, priority));
787            queue.check();
788        }
789        assert!(queue.push_increase(1, 11));
790        queue.check();
791        for priority in [11, 12] {
792            assert!(!queue.push_decrease(1, priority));
793            queue.check();
794        }
795        assert!(queue.push_decrease(1, 10));
796        queue.check();
797        assert!(queue.push_decrease(2, 10));
798        queue.check();
799        assert_eq!(queue.clone().into_sorted_vec().len(), 2);
800        let mut min: PagedPriorityQueue<u16, Reverse<i32>> = PagedPriorityQueue::new();
801        for (key, value) in [(1, 10), (2, -2), (3, 10)] {
802            min.push(key, Reverse(value));
803            min.check();
804        }
805        assert_eq!(min.pop(), Some((2, Reverse(-2))));
806        min.check();
807    }
808
809    #[test]
810    fn iteration_sorting_and_eager_drain() {
811        let mut queue: PagedPriorityQueue<u16, i32, 4> = PagedPriorityQueue::default();
812        for entry in [(1, 5), (9, 2), (2, 5), (1, 7)] {
813            queue.extend([entry]);
814            queue.check();
815        }
816        assert_eq!(queue.len(), 3);
817        assert_eq!(queue.iter().len(), 3);
818        assert_eq!(queue.keys().copied().collect::<Vec<_>>(), queue.key_slice());
819        assert_eq!(
820            queue.priorities().copied().collect::<Vec<_>>(),
821            queue.priority_slice()
822        );
823        assert_eq!(
824            queue.iter().next_back(),
825            queue.key_slice().last().zip(queue.priority_slice().last())
826        );
827        let entries: Vec<_> = queue.iter().map(|(&k, &p)| (k, p)).collect();
828        assert_eq!(queue.clone().into_iter().collect::<Vec<_>>(), entries);
829        assert_eq!((&queue).into_iter().count(), 3);
830        assert_eq!(
831            queue
832                .clone()
833                .into_sorted_vec()
834                .iter()
835                .map(|e| e.1)
836                .collect::<Vec<_>>(),
837            [2, 5, 7]
838        );
839        let mut sorted = queue.clone().into_sorted_iter();
840        assert_eq!(sorted.len(), 3);
841        assert_eq!(sorted.next(), Some((1, 7)));
842        assert_eq!(sorted.len(), 2);
843        assert_eq!(sorted.by_ref().map(|e| e.1).collect::<Vec<_>>(), [5, 2]);
844        assert_eq!(sorted.next(), None);
845        let capacity = queue.capacity();
846        let pages = queue.allocated_pages();
847        let mut drain = queue.drain();
848        assert_eq!(drain.len(), 3);
849        assert_eq!(drain.next(), entries.first().copied());
850        assert_eq!(drain.next_back(), entries.last().copied());
851        drop(drain);
852        queue.check();
853        assert!(queue.is_empty());
854        assert_eq!(queue.capacity(), capacity);
855        assert_eq!(queue.allocated_pages(), pages);
856        queue.push(1, 1);
857        queue.check();
858        // Miri reports the deliberate leak; there, drop instead (removal
859        // is eager either way, which this test checks natively).
860        let drain = queue.drain();
861        if cfg!(miri) {
862            drop(drain);
863        } else {
864            core::mem::forget(drain);
865        }
866        queue.check();
867        assert!(queue.is_empty());
868        assert_eq!(queue.pop(), None);
869        queue.check();
870    }
871
872    #[test]
873    fn capacity_pages_and_non_ordered_priorities() {
874        let mut queue: PagedPriorityQueue<u16, i32, 4> = PagedPriorityQueue::with_capacity(5);
875        queue.check();
876        assert!(queue.capacity() >= 5);
877        assert_eq!(queue.allocated_pages(), 0);
878        for key in [1, 2, 40] {
879            queue.push(key, 0);
880            queue.check();
881        }
882        queue.reserve(20);
883        queue.check();
884        assert!(queue.capacity() >= 23);
885        assert_eq!(queue.allocated_pages(), 2);
886        let capacity = queue.capacity();
887        queue.clear();
888        queue.check();
889        assert_eq!(queue.capacity(), capacity);
890        assert_eq!(queue.allocated_pages(), 2);
891        for key in [1, 2, 40] {
892            assert!(!queue.contains_key(&key));
893        }
894        queue.push(40, 1);
895        queue.check();
896        assert!(!queue.contains_key(&1));
897        queue.shrink_to_fit();
898        queue.check();
899        assert_eq!(queue.allocated_pages(), 2);
900        queue.clear();
901        queue.check();
902        queue.shrink_to_fit();
903        queue.check();
904        assert_eq!(queue.allocated_pages(), 0);
905
906        // Construction, inspection, clearing and arbitrary iteration do not
907        // require P: Ord, even though heap mutations do.
908        let mut unordered: PagedPriorityQueue<u16, f32> = PagedPriorityQueue::new();
909        unordered.reserve(1);
910        assert_eq!(unordered.peek(), None);
911        assert_eq!(unordered.priority(&0), None);
912        assert_eq!(unordered.clone().into_iter().count(), 0);
913        assert_eq!(unordered.drain().count(), 0);
914        unordered.clear();
915        unordered.shrink_to_fit();
916        assert!(unordered.key_slice().is_empty());
917        assert!(unordered.priority_slice().is_empty());
918    }
919}