1use 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 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 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
96pub 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 pub fn new() -> Self {
153 Self::with_shards(default_shards())
154 }
155
156 pub fn with_shards(shards: usize) -> Self {
162 Self::with_shards_and_capacity(shards, 0)
163 }
164
165 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 pub fn shards(&self) -> usize {
197 self.shards.len()
198 }
199
200 pub fn len(&self) -> usize {
202 self.shards
203 .iter()
204 .map(|shard| shard.0.len.load(Ordering::Relaxed))
205 .sum()
206 }
207
208 pub fn is_empty(&self) -> bool {
212 self.len() == 0
213 }
214
215 pub fn allocated_pages(&self) -> usize {
218 self.read_shards()
219 .map(|queue| queue.allocated_pages())
220 .sum()
221 }
222
223 pub fn contains_key(&self, key: &K) -> bool {
225 self.shard(key).queue.read().contains_key(key)
226 }
227
228 pub fn priority(&self, key: &K) -> Option<P>
231 where
232 P: Clone,
233 {
234 self.with_priority(key, P::clone)
235 }
236
237 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 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 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 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 pub fn push(&self, key: K, priority: P) -> Option<P> {
306 self.shard(&key).update(|queue| queue.push(key, priority))
307 }
308
309 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 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 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 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 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 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 pub fn remove(&self, key: &K) -> Option<(K, P)> {
365 self.shard(key).update(|queue| queue.remove(key))
366 }
367
368 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 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 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 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 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 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 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
542impl<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
554impl<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
569impl<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
579impl<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
593impl<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
610impl<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 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 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#[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;