Skip to main content

paged_collections/concurrent/
priority_queue.rs

1//! A sharded indexed max-priority queue.
2
3use alloc::boxed::Box;
4use alloc::vec::{IntoIter, Vec};
5#[cfg(all(feature = "std", not(loom)))]
6use core::cell::Cell;
7use core::fmt;
8
9use super::atomic::{AtomicU64, AtomicUsize, CachePadded, Ordering};
10use super::lock::{ReadGuard, RwLock};
11use crate::key::Key;
12use crate::page::{DEFAULT_PAGE, Directory, Flat};
13use crate::priority_queue::PagedPriorityQueue;
14
15const SPLITMIX_INCREMENT: u64 = 0x9e37_79b9_7f4a_7c15;
16
17fn splitmix64_finalizer(mut word: u64) -> u64 {
18    word = (word ^ (word >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
19    word = (word ^ (word >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
20    word ^ (word >> 31)
21}
22
23#[cfg(all(feature = "std", not(loom)))]
24fn random_word() -> u64 {
25    static SEED: AtomicU64 = AtomicU64::new(0);
26    std::thread_local! {
27        static STATE: Cell<u64> = const { Cell::new(0) };
28    }
29
30    STATE.with(|state| {
31        let mut word = state.get();
32        if word == 0 {
33            let counter = SEED.fetch_add(SPLITMIX_INCREMENT, Ordering::Relaxed);
34            let address = core::ptr::from_ref(state).addr() as u64;
35            word = splitmix64_finalizer(counter.wrapping_add(address)).max(1);
36        }
37        // xorshift64 with a nonzero state.
38        word ^= word << 13;
39        word ^= word >> 7;
40        word ^= word << 17;
41        state.set(word);
42        word
43    })
44}
45
46fn default_shards() -> usize {
47    #[cfg(feature = "std")]
48    {
49        std::thread::available_parallelism()
50            .map_or(1, core::num::NonZeroUsize::get)
51            .saturating_mul(4)
52            .min(256)
53    }
54    #[cfg(not(feature = "std"))]
55    {
56        8
57    }
58}
59
60struct Shard<K, P, const PAGE: usize, D: Directory> {
61    queue: RwLock<PagedPriorityQueue<K, P, PAGE, D>>,
62    len: AtomicUsize,
63}
64
65struct UpdateLen<'a, K: Key, P, const PAGE: usize, D: Directory> {
66    queue: &'a mut PagedPriorityQueue<K, P, PAGE, D>,
67    len: &'a AtomicUsize,
68}
69
70impl<K: Key, P, const PAGE: usize, D: Directory> Drop for UpdateLen<'_, K, P, PAGE, D> {
71    fn drop(&mut self) {
72        self.len.store(self.queue.len(), Ordering::Relaxed);
73    }
74}
75
76impl<K: Key, P, const PAGE: usize, D: Directory> Shard<K, P, PAGE, D> {
77    fn update<R>(&self, f: impl FnOnce(&mut PagedPriorityQueue<K, P, PAGE, D>) -> R) -> R {
78        self.update_locked(&mut self.queue.write(), f)
79    }
80
81    // Publish the length before releasing the caller's write lock, even if
82    // user code unwinds after changing membership.
83    fn update_locked<R>(
84        &self,
85        queue: &mut PagedPriorityQueue<K, P, PAGE, D>,
86        f: impl FnOnce(&mut PagedPriorityQueue<K, P, PAGE, D>) -> R,
87    ) -> R {
88        let update = UpdateLen {
89            queue,
90            len: &self.len,
91        };
92        f(update.queue)
93    }
94}
95
96/// A concurrent indexed max-priority queue with relaxed and exact removal.
97///
98/// Each shard wraps a [`PagedPriorityQueue`]. The key's index page determines
99/// its shard, keeping all generations of a slot together and allocating that
100/// index page in just one shard. `PAGE` must be nonzero. Workloads with fewer
101/// key pages than shards can distribute entries unevenly and reduce the
102/// effectiveness of relaxed popping. `D` selects the plain queue's directory.
103/// Each shard can hold at most `u32::MAX` entries.
104///
105/// [`pop`](Self::pop) returns the greatest of up to two sampled shard tops,
106/// with a fallback scan for nonempty shards. It has no rank guarantee with
107/// multiple shards. A key present throughout the call, with its insertion
108/// happening-before the call, prevents `None`. [`pop_exact`](Self::pop_exact)
109/// and [`peek_exact`](Self::peek_exact) select the global maximum. Ties have
110/// unspecified order.
111///
112/// # Locking and panics
113///
114/// Per-key operations lock one shard. Operations holding several shard locks
115/// at once acquire them in ascending shard order. Callbacks and user trait
116/// implementations such as `Ord`, `Clone`, `Debug` and `Serialize` run under
117/// shard locks and must avoid calling back into this queue, which can deadlock
118/// even on reads. The spin lock used without `std` permits writer starvation.
119///
120/// Locks ignore poisoning. If a priority comparison or a mutation callback
121/// panics, mutations already made remain in effect and all remaining entries
122/// stay findable with their priorities. Heap order may be broken in the
123/// modified shard, so subsequent maximum results may be unspecified.
124/// See [`PagedPriorityQueue`] for its panic guarantees.
125///
126/// ```
127/// use paged_collections::concurrent::ConcurrentPriorityQueue;
128///
129/// let queue = ConcurrentPriorityQueue::<u32, i32, 4>::with_shards(3);
130/// assert_eq!(queue.push(1, 10), None);
131/// assert_eq!(queue.push(5, 20), None);
132/// assert_eq!(queue.change_priority(&1, 30), Some(10));
133/// assert_eq!(queue.pop_exact(), Some((1, 30)));
134/// assert_eq!(queue.pop(), Some((5, 20)));
135/// assert_eq!(queue.pop(), None);
136/// ```
137pub struct ConcurrentPriorityQueue<K, P, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
138    shards: Box<[CachePadded<Shard<K, P, PAGE, D>>]>,
139    #[cfg(any(not(feature = "std"), loom))]
140    random: AtomicU64,
141}
142
143impl<K: Key, P, const PAGE: usize, D: Directory> ConcurrentPriorityQueue<K, P, PAGE, D> {
144    /// Creates an empty queue with the default shard count.
145    ///
146    /// With `std`, the count is four times the available parallelism, capped
147    /// at 256, or four if parallelism is unknown. Without `std` it is eight.
148    ///
149    /// # Panics
150    ///
151    /// Panics if `PAGE` is zero.
152    pub fn new() -> Self {
153        Self::with_shards(default_shards())
154    }
155
156    /// Creates an empty queue with `shards` shards.
157    ///
158    /// # Panics
159    ///
160    /// Panics if `shards` or `PAGE` is zero.
161    pub fn with_shards(shards: usize) -> Self {
162        Self::with_shards_and_capacity(shards, 0)
163    }
164
165    /// Creates an empty queue with dense capacity distributed across `shards`
166    /// shards, rounding up per shard. Index pages are allocated on demand.
167    ///
168    /// # Panics
169    ///
170    /// Panics if `shards` or `PAGE` is zero, or the capacity cannot be allocated.
171    pub fn with_shards_and_capacity(shards: usize, capacity: usize) -> Self {
172        assert!(
173            shards > 0,
174            "ConcurrentPriorityQueue requires at least one shard"
175        );
176        assert!(
177            PAGE > 0,
178            "ConcurrentPriorityQueue requires a nonzero page size"
179        );
180        let per_shard = capacity.div_ceil(shards);
181        Self {
182            shards: (0..shards)
183                .map(|_| {
184                    CachePadded(Shard {
185                        queue: RwLock::new(PagedPriorityQueue::with_capacity(per_shard)),
186                        len: AtomicUsize::new(0),
187                    })
188                })
189                .collect(),
190            #[cfg(any(not(feature = "std"), loom))]
191            random: AtomicU64::new(SPLITMIX_INCREMENT),
192        }
193    }
194
195    /// Returns the number of shards.
196    pub fn shards(&self) -> usize {
197        self.shards.len()
198    }
199
200    /// Returns the sum of shard lengths, exact when no write is in flight.
201    pub fn len(&self) -> usize {
202        self.shards
203            .iter()
204            .map(|shard| shard.0.len.load(Ordering::Relaxed))
205            .sum()
206    }
207
208    /// Returns whether the length hints report an empty queue.
209    ///
210    /// Like [`len`](Self::len), this is exact when no write is in flight.
211    pub fn is_empty(&self) -> bool {
212        self.len() == 0
213    }
214
215    /// Returns the total number of allocated index pages, reading one shard
216    /// at a time. The total is weakly consistent across shards.
217    pub fn allocated_pages(&self) -> usize {
218        self.read_shards()
219            .map(|queue| queue.allocated_pages())
220            .sum()
221    }
222
223    /// Looks up the exact key, including its generation, under a read lock.
224    pub fn contains_key(&self, key: &K) -> bool {
225        self.shard(key).queue.read().contains_key(key)
226    }
227
228    /// Clones the exact key's priority under a read lock, or returns `None`
229    /// if absent. The clone must avoid calling back into this queue.
230    pub fn priority(&self, key: &K) -> Option<P>
231    where
232        P: Clone,
233    {
234        self.with_priority(key, P::clone)
235    }
236
237    /// Calls `f` with the exact key's priority under a read lock.
238    ///
239    /// Returns `None` without calling `f` if absent. The callback must avoid
240    /// calling back into this queue.
241    pub fn with_priority<R>(&self, key: &K, f: impl FnOnce(&P) -> R) -> Option<R> {
242        self.shard(key).queue.read().priority(key).map(f)
243    }
244
245    /// Removes all entries, retaining index pages and dense capacity.
246    pub fn clear(&mut self) {
247        for CachePadded(shard) in self.shards.iter_mut() {
248            let update = UpdateLen {
249                queue: shard.queue.get_mut(),
250                len: &shard.len,
251            };
252            update.queue.clear();
253        }
254    }
255
256    /// Shrinks the dense arrays and directories, freeing index pages of
257    /// empty shards.
258    pub fn shrink_to_fit(&mut self) {
259        for CachePadded(shard) in self.shards.iter_mut() {
260            shard.queue.get_mut().shrink_to_fit();
261        }
262    }
263
264    /// Eagerly removes all entries and returns them in arbitrary order.
265    ///
266    /// Index pages and dense capacity stay allocated. Dropping the iterator
267    /// drops its remaining entries.
268    pub fn drain(&mut self) -> IntoIter<(K, P)> {
269        let mut entries = Vec::with_capacity(self.len());
270        for CachePadded(shard) in self.shards.iter_mut() {
271            entries.extend(shard.queue.get_mut().drain());
272            shard.len.store(0, Ordering::Relaxed);
273        }
274        entries.into_iter()
275    }
276
277    fn shard_of(&self, key: &K) -> usize {
278        (splitmix64_finalizer((key.index() / PAGE) as u64) % self.shards() as u64) as usize
279    }
280
281    fn shard(&self, key: &K) -> &Shard<K, P, PAGE, D> {
282        &self.shards[self.shard_of(key)].0
283    }
284
285    fn read_shards(
286        &self,
287    ) -> impl Iterator<Item = ReadGuard<'_, PagedPriorityQueue<K, P, PAGE, D>>> {
288        self.shards.iter().map(|shard| shard.0.queue.read())
289    }
290
291    fn into_entries(self) -> impl Iterator<Item = (K, P)> {
292        self.shards
293            .into_vec()
294            .into_iter()
295            .flat_map(|shard| shard.0.queue.into_inner())
296    }
297}
298
299impl<K: Key, P: Ord, const PAGE: usize, D: Directory> ConcurrentPriorityQueue<K, P, PAGE, D> {
300    /// Inserts a key or updates its priority under one shard write lock.
301    ///
302    /// Returns the previous priority of the same key, keeping the stored
303    /// key. Another generation occupying the slot is evicted and yields
304    /// `None`.
305    pub fn push(&self, key: K, priority: P) -> Option<P> {
306        self.shard(&key).update(|queue| queue.push(key, priority))
307    }
308
309    /// Inserts or updates under one shard write lock, refusing an occupied
310    /// slot held by another generation.
311    ///
312    /// Returns the previous priority on update, or the supplied pair on
313    /// refusal.
314    pub fn try_push(&self, key: K, priority: P) -> Result<Option<P>, (K, P)> {
315        self.shard(&key)
316            .update(|queue| queue.try_push(key, priority))
317    }
318
319    /// Stores the supplied key and priority under one shard write lock.
320    ///
321    /// Returns the former occupant of the slot, including an evicted
322    /// generation or an equal key.
323    pub fn replace(&self, key: K, priority: P) -> Option<(K, P)> {
324        self.shard(&key)
325            .update(|queue| queue.replace(key, priority))
326    }
327
328    /// Inserts an absent key or raises its priority if strictly greater,
329    /// returning whether the queue changed. An absent generation evicts the
330    /// slot's occupant as in [`push`](Self::push).
331    pub fn push_increase(&self, key: K, priority: P) -> bool {
332        self.shard(&key)
333            .update(|queue| queue.push_increase(key, priority))
334    }
335
336    /// Inserts an absent key or lowers its priority if strictly smaller,
337    /// returning whether the queue changed. An absent generation evicts the
338    /// slot's occupant as in [`push`](Self::push).
339    pub fn push_decrease(&self, key: K, priority: P) -> bool {
340        self.shard(&key)
341            .update(|queue| queue.push_decrease(key, priority))
342    }
343
344    /// Changes the priority of the exact key under a write lock, returning
345    /// its previous priority or `None` if absent.
346    pub fn change_priority(&self, key: &K, priority: P) -> Option<P> {
347        self.shard(key)
348            .update(|queue| queue.change_priority(key, priority))
349    }
350
351    /// Mutates the exact key's priority under a write lock and repairs heap
352    /// order. Returns whether the key was present.
353    ///
354    /// The callback runs only for a present key and must avoid calling back
355    /// into this queue. If it panics, its changes remain and heap order may
356    /// be broken.
357    pub fn change_priority_with(&self, key: &K, change: impl FnOnce(&mut P)) -> bool {
358        self.shard(key)
359            .update(|queue| queue.change_priority_with(key, change))
360    }
361
362    /// Removes and returns the stored pair for the exact key, or `None` if
363    /// absent, under one shard write lock.
364    pub fn remove(&self, key: &K) -> Option<(K, P)> {
365        self.shard(key).update(|queue| queue.remove(key))
366    }
367
368    /// Removes an entry using relaxed priority ordering.
369    ///
370    /// Samples two distinct shards, preferring nonzero length hints. Locks
371    /// both in ascending shard order and removes the greater top. If both
372    /// are empty, visits every shard once from a random start, locking one
373    /// at a time, and removes the first top it finds.
374    ///
375    /// With one shard this removes the maximum. With multiple shards there
376    /// is no rank guarantee. Rihani, Sanders and Dementiev (2015) report
377    /// empirical expected rank O(shards) for [MultiQueues].
378    ///
379    /// Returns `None` only if every shard was empty when visited. An entry
380    /// present throughout the call, with its insertion happening-before the
381    /// call, therefore prevents `None` because entries never migrate.
382    ///
383    /// [MultiQueues]: https://arxiv.org/abs/1411.1209
384    pub fn pop(&self) -> Option<(K, P)> {
385        if self.shards() == 1 {
386            return self.shards[0].0.update(PagedPriorityQueue::pop);
387        }
388
389        let [a, b] = self.choose_shards();
390        if let Some(entry) = self.pop_pair(a.min(b), a.max(b)) {
391            return Some(entry);
392        }
393
394        let start = self.random_index(self.shards());
395        let found = self
396            .shard_indices_from(start)
397            .find_map(|index| self.shards[index].0.update(PagedPriorityQueue::pop));
398        #[cfg(all(test, loom))]
399        if found.is_some() {
400            SCAN_FOUND.store(true, core::sync::atomic::Ordering::Relaxed);
401        }
402        found
403    }
404
405    /// Removes the global maximum, or returns `None` if empty.
406    ///
407    /// Acquires all shard write locks in ascending order. This operation
408    /// is linearizable.
409    pub fn pop_exact(&self) -> Option<(K, P)> {
410        let mut queues: Vec<_> = self
411            .shards
412            .iter()
413            .map(|shard| shard.0.queue.write())
414            .collect();
415        let best = queues
416            .iter()
417            .enumerate()
418            .filter_map(|(index, queue)| queue.peek().map(|(_, priority)| (index, priority)))
419            .max_by(|(_, left), (_, right)| left.cmp(right))?
420            .0;
421        self.shards[best]
422            .0
423            .update_locked(&mut queues[best], PagedPriorityQueue::pop)
424    }
425
426    /// Copies the key and clones the priority of the global maximum, or
427    /// returns `None` if empty.
428    ///
429    /// Acquires all shard read locks in ascending order for a linearizable
430    /// view. The priority's `Clone` must avoid calling back into this queue.
431    pub fn peek_exact(&self) -> Option<(K, P)>
432    where
433        P: Clone,
434    {
435        let queues: Vec<_> = self.read_shards().collect();
436        queues
437            .iter()
438            .filter_map(|queue| queue.peek())
439            .max_by(|(_, left), (_, right)| left.cmp(right))
440            .map(|(key, priority)| (*key, priority.clone()))
441    }
442
443    /// Consumes the queue into entries in ascending priority order.
444    pub fn into_sorted_vec(self) -> Vec<(K, P)> {
445        let mut entries: Vec<_> = self.into_iter().collect();
446        entries.sort_unstable_by(|(_, left), (_, right)| left.cmp(right));
447        entries
448    }
449
450    /// Consumes the queue and merges its entries into one plain queue.
451    ///
452    /// # Panics
453    ///
454    /// Panics if the entries exceed the plain queue's `u32::MAX` limit or
455    /// if comparing priorities panics.
456    pub fn into_queue(self) -> PagedPriorityQueue<K, P, PAGE, D> {
457        let mut queue = PagedPriorityQueue::with_capacity(self.len());
458        queue.extend(self.into_entries());
459        queue
460    }
461
462    /// Copies entries into a plain queue using one shard read lock at a time.
463    ///
464    /// The snapshot is consistent within each shard and weakly consistent
465    /// across shards. An entry that stays unchanged throughout the call
466    /// is included if its insertion happens-before the call. Priority
467    /// comparisons and clones must avoid calling back into this queue.
468    ///
469    /// # Panics
470    ///
471    /// Panics if the entries copied exceed the plain queue's `u32::MAX`
472    /// limit or if cloning or comparing priorities panics.
473    pub fn snapshot(&self) -> PagedPriorityQueue<K, P, PAGE, D>
474    where
475        P: Clone,
476    {
477        let mut snapshot = PagedPriorityQueue::with_capacity(self.len());
478        for shard in self.read_shards() {
479            snapshot.extend(shard.iter().map(|(key, priority)| (*key, priority.clone())));
480        }
481        snapshot
482    }
483
484    fn random_index(&self, bound: usize) -> usize {
485        #[cfg(all(feature = "std", not(loom)))]
486        let word = random_word();
487        #[cfg(any(not(feature = "std"), loom))]
488        let word =
489            splitmix64_finalizer(self.random.fetch_add(SPLITMIX_INCREMENT, Ordering::Relaxed));
490        (word % bound as u64) as usize
491    }
492
493    fn shard_indices_from(&self, start: usize) -> impl Iterator<Item = usize> {
494        (start..self.shards()).chain(0..start)
495    }
496
497    fn choose_shards(&self) -> [usize; 2] {
498        let count = self.shards();
499        let first = self.random_index(count);
500        let second = self.random_index(count - 1);
501        let mut chosen = [first, second + usize::from(second >= first)];
502        let has_hint = |index: usize| self.shards[index].0.len.load(Ordering::Relaxed) != 0;
503        let mut hinted = chosen.map(has_hint);
504
505        // Keep the random pair when both hints are nonzero. Otherwise try
506        // to replace the empty candidates in one pass, without locking.
507        for index in self.shard_indices_from(first) {
508            let Some(slot) = hinted.iter().position(|&nonempty| !nonempty) else {
509                break;
510            };
511            if !chosen.contains(&index) && has_hint(index) {
512                chosen[slot] = index;
513                hinted[slot] = true;
514            }
515        }
516        chosen
517    }
518
519    fn pop_pair(&self, lower: usize, higher: usize) -> Option<(K, P)> {
520        let left = &self.shards[lower].0;
521        let right = &self.shards[higher].0;
522        let mut left_queue = left.queue.write();
523        let mut right_queue = right.queue.write();
524        let left_top = left_queue.peek().map(|(_, priority)| priority);
525        let right_top = right_queue.peek().map(|(_, priority)| priority);
526        if left_top.cmp(&right_top).is_ge() {
527            left.update_locked(&mut left_queue, PagedPriorityQueue::pop)
528        } else {
529            right.update_locked(&mut right_queue, PagedPriorityQueue::pop)
530        }
531    }
532}
533
534impl<K: Key, P, const PAGE: usize, D: Directory> Default
535    for ConcurrentPriorityQueue<K, P, PAGE, D>
536{
537    fn default() -> Self {
538        Self::new()
539    }
540}
541
542/// Rebuilds the queue from a weakly consistent snapshot with the same shard
543/// count. See [`ConcurrentPriorityQueue::snapshot`] for locking.
544impl<K: Key, P: Ord + Clone, const PAGE: usize, D: Directory> Clone
545    for ConcurrentPriorityQueue<K, P, PAGE, D>
546{
547    fn clone(&self) -> Self {
548        let mut cloned = Self::with_shards(self.shards());
549        cloned.extend(self.snapshot());
550        cloned
551    }
552}
553
554/// Formats entries as a map using one shard read lock at a time, with the
555/// same consistency as [`ConcurrentPriorityQueue::snapshot`]. User formatting
556/// must avoid calling back into the queue.
557impl<K: Key + fmt::Debug, P: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
558    for ConcurrentPriorityQueue<K, P, PAGE, D>
559{
560    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
561        let mut map = f.debug_map();
562        for shard in self.read_shards() {
563            map.entries(shard.iter());
564        }
565        map.finish()
566    }
567}
568
569/// Moves a plain queue into the default number of shards by re-pushing its
570/// entries in O(n log n) time.
571impl<K: Key, P: Ord, const PAGE: usize, D: Directory> From<PagedPriorityQueue<K, P, PAGE, D>>
572    for ConcurrentPriorityQueue<K, P, PAGE, D>
573{
574    fn from(queue: PagedPriorityQueue<K, P, PAGE, D>) -> Self {
575        queue.into_iter().collect()
576    }
577}
578
579/// Consumes the queue and yields entries in arbitrary order.
580impl<K: Key, P, const PAGE: usize, D: Directory> IntoIterator
581    for ConcurrentPriorityQueue<K, P, PAGE, D>
582{
583    type Item = (K, P);
584    type IntoIter = IntoIter<Self::Item>;
585
586    fn into_iter(self) -> Self::IntoIter {
587        let mut entries = Vec::with_capacity(self.len());
588        entries.extend(self.into_entries());
589        entries.into_iter()
590    }
591}
592
593/// Pushes entries under exclusive access. Later entries in a slot win.
594impl<K: Key, P: Ord, const PAGE: usize, D: Directory> Extend<(K, P)>
595    for ConcurrentPriorityQueue<K, P, PAGE, D>
596{
597    fn extend<I: IntoIterator<Item = (K, P)>>(&mut self, iter: I) {
598        for (key, priority) in iter {
599            let index = self.shard_of(&key);
600            let shard = &mut self.shards[index].0;
601            let update = UpdateLen {
602                queue: shard.queue.get_mut(),
603                len: &shard.len,
604            };
605            update.queue.push(key, priority);
606        }
607    }
608}
609
610/// Collects entries into the default number of shards. Later entries in a
611/// slot win.
612impl<K: Key, P: Ord, const PAGE: usize, D: Directory> FromIterator<(K, P)>
613    for ConcurrentPriorityQueue<K, P, PAGE, D>
614{
615    fn from_iter<I: IntoIterator<Item = (K, P)>>(iter: I) -> Self {
616        let mut queue = Self::new();
617        queue.extend(iter);
618        queue
619    }
620}
621
622#[cfg(feature = "serde")]
623mod serde_impl {
624    use super::*;
625    use serde::de::{Deserialize, Deserializer};
626    use serde::ser::{Serialize, SerializeSeq, Serializer};
627
628    /// Serializes a sequence of key-priority pairs in the plain queue format,
629    /// holding one shard read lock at a time. User serialization must avoid
630    /// calling back into the queue.
631    ///
632    /// The length of the weakly consistent view is unknown upfront. For a
633    /// serializer that requires a sequence length, serialize
634    /// [`ConcurrentPriorityQueue::snapshot`] instead.
635    impl<K: Key + Serialize, P: Serialize, const PAGE: usize, D: Directory> Serialize
636        for ConcurrentPriorityQueue<K, P, PAGE, D>
637    {
638        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
639            let mut seq = serializer.serialize_seq(None)?;
640            for shard in self.read_shards() {
641                for entry in shard.iter() {
642                    seq.serialize_element(&entry)?;
643                }
644            }
645            seq.end()
646        }
647    }
648
649    /// Reads the plain queue format and redistributes entries into the
650    /// default number of shards.
651    impl<'de, K: Key + Deserialize<'de>, P: Ord + Deserialize<'de>, const PAGE: usize, D: Directory>
652        Deserialize<'de> for ConcurrentPriorityQueue<K, P, PAGE, D>
653    {
654        fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
655            PagedPriorityQueue::deserialize(deserializer).map(Self::from)
656        }
657    }
658}
659
660/// Set when `pop` finds an entry only in its fallback scan (a plain atomic
661/// outside the loom model): the scan model asserts it is reached.
662#[cfg(all(test, loom))]
663static SCAN_FOUND: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
664
665#[cfg(all(test, loom))]
666#[path = "loom_priority_queue.rs"]
667mod loom_tests;