use alloc::boxed::Box;
use alloc::vec::{IntoIter, Vec};
#[cfg(all(feature = "std", not(loom)))]
use core::cell::Cell;
use core::fmt;
use super::atomic::{AtomicU64, AtomicUsize, CachePadded, Ordering};
use super::lock::{ReadGuard, RwLock};
use crate::key::Key;
use crate::page::{DEFAULT_PAGE, Directory, Flat};
use crate::priority_queue::PagedPriorityQueue;
const SPLITMIX_INCREMENT: u64 = 0x9e37_79b9_7f4a_7c15;
fn splitmix64_finalizer(mut word: u64) -> u64 {
word = (word ^ (word >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
word = (word ^ (word >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
word ^ (word >> 31)
}
#[cfg(all(feature = "std", not(loom)))]
fn random_word() -> u64 {
static SEED: AtomicU64 = AtomicU64::new(0);
std::thread_local! {
static STATE: Cell<u64> = const { Cell::new(0) };
}
STATE.with(|state| {
let mut word = state.get();
if word == 0 {
let counter = SEED.fetch_add(SPLITMIX_INCREMENT, Ordering::Relaxed);
let address = core::ptr::from_ref(state).addr() as u64;
word = splitmix64_finalizer(counter.wrapping_add(address)).max(1);
}
word ^= word << 13;
word ^= word >> 7;
word ^= word << 17;
state.set(word);
word
})
}
fn default_shards() -> usize {
#[cfg(feature = "std")]
{
std::thread::available_parallelism()
.map_or(1, core::num::NonZeroUsize::get)
.saturating_mul(4)
.min(256)
}
#[cfg(not(feature = "std"))]
{
8
}
}
struct Shard<K, P, const PAGE: usize, D: Directory> {
queue: RwLock<PagedPriorityQueue<K, P, PAGE, D>>,
len: AtomicUsize,
}
struct UpdateLen<'a, K: Key, P, const PAGE: usize, D: Directory> {
queue: &'a mut PagedPriorityQueue<K, P, PAGE, D>,
len: &'a AtomicUsize,
}
impl<K: Key, P, const PAGE: usize, D: Directory> Drop for UpdateLen<'_, K, P, PAGE, D> {
fn drop(&mut self) {
self.len.store(self.queue.len(), Ordering::Relaxed);
}
}
impl<K: Key, P, const PAGE: usize, D: Directory> Shard<K, P, PAGE, D> {
fn update<R>(&self, f: impl FnOnce(&mut PagedPriorityQueue<K, P, PAGE, D>) -> R) -> R {
self.update_locked(&mut self.queue.write(), f)
}
fn update_locked<R>(
&self,
queue: &mut PagedPriorityQueue<K, P, PAGE, D>,
f: impl FnOnce(&mut PagedPriorityQueue<K, P, PAGE, D>) -> R,
) -> R {
let update = UpdateLen {
queue,
len: &self.len,
};
f(update.queue)
}
}
pub struct ConcurrentPriorityQueue<K, P, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
shards: Box<[CachePadded<Shard<K, P, PAGE, D>>]>,
#[cfg(any(not(feature = "std"), loom))]
random: AtomicU64,
}
impl<K: Key, P, const PAGE: usize, D: Directory> ConcurrentPriorityQueue<K, P, PAGE, D> {
pub fn new() -> Self {
Self::with_shards(default_shards())
}
pub fn with_shards(shards: usize) -> Self {
Self::with_shards_and_capacity(shards, 0)
}
pub fn with_shards_and_capacity(shards: usize, capacity: usize) -> Self {
assert!(
shards > 0,
"ConcurrentPriorityQueue requires at least one shard"
);
assert!(
PAGE > 0,
"ConcurrentPriorityQueue requires a nonzero page size"
);
let per_shard = capacity.div_ceil(shards);
Self {
shards: (0..shards)
.map(|_| {
CachePadded(Shard {
queue: RwLock::new(PagedPriorityQueue::with_capacity(per_shard)),
len: AtomicUsize::new(0),
})
})
.collect(),
#[cfg(any(not(feature = "std"), loom))]
random: AtomicU64::new(SPLITMIX_INCREMENT),
}
}
pub fn shards(&self) -> usize {
self.shards.len()
}
pub fn len(&self) -> usize {
self.shards
.iter()
.map(|shard| shard.0.len.load(Ordering::Relaxed))
.sum()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn allocated_pages(&self) -> usize {
self.read_shards()
.map(|queue| queue.allocated_pages())
.sum()
}
pub fn contains_key(&self, key: &K) -> bool {
self.shard(key).queue.read().contains_key(key)
}
pub fn priority(&self, key: &K) -> Option<P>
where
P: Clone,
{
self.with_priority(key, P::clone)
}
pub fn with_priority<R>(&self, key: &K, f: impl FnOnce(&P) -> R) -> Option<R> {
self.shard(key).queue.read().priority(key).map(f)
}
pub fn clear(&mut self) {
for CachePadded(shard) in self.shards.iter_mut() {
let update = UpdateLen {
queue: shard.queue.get_mut(),
len: &shard.len,
};
update.queue.clear();
}
}
pub fn shrink_to_fit(&mut self) {
for CachePadded(shard) in self.shards.iter_mut() {
shard.queue.get_mut().shrink_to_fit();
}
}
pub fn drain(&mut self) -> IntoIter<(K, P)> {
let mut entries = Vec::with_capacity(self.len());
for CachePadded(shard) in self.shards.iter_mut() {
entries.extend(shard.queue.get_mut().drain());
shard.len.store(0, Ordering::Relaxed);
}
entries.into_iter()
}
fn shard_of(&self, key: &K) -> usize {
(splitmix64_finalizer((key.index() / PAGE) as u64) % self.shards() as u64) as usize
}
fn shard(&self, key: &K) -> &Shard<K, P, PAGE, D> {
&self.shards[self.shard_of(key)].0
}
fn read_shards(
&self,
) -> impl Iterator<Item = ReadGuard<'_, PagedPriorityQueue<K, P, PAGE, D>>> {
self.shards.iter().map(|shard| shard.0.queue.read())
}
fn into_entries(self) -> impl Iterator<Item = (K, P)> {
self.shards
.into_vec()
.into_iter()
.flat_map(|shard| shard.0.queue.into_inner())
}
}
impl<K: Key, P: Ord, const PAGE: usize, D: Directory> ConcurrentPriorityQueue<K, P, PAGE, D> {
pub fn push(&self, key: K, priority: P) -> Option<P> {
self.shard(&key).update(|queue| queue.push(key, priority))
}
pub fn try_push(&self, key: K, priority: P) -> Result<Option<P>, (K, P)> {
self.shard(&key)
.update(|queue| queue.try_push(key, priority))
}
pub fn replace(&self, key: K, priority: P) -> Option<(K, P)> {
self.shard(&key)
.update(|queue| queue.replace(key, priority))
}
pub fn push_increase(&self, key: K, priority: P) -> bool {
self.shard(&key)
.update(|queue| queue.push_increase(key, priority))
}
pub fn push_decrease(&self, key: K, priority: P) -> bool {
self.shard(&key)
.update(|queue| queue.push_decrease(key, priority))
}
pub fn change_priority(&self, key: &K, priority: P) -> Option<P> {
self.shard(key)
.update(|queue| queue.change_priority(key, priority))
}
pub fn change_priority_with(&self, key: &K, change: impl FnOnce(&mut P)) -> bool {
self.shard(key)
.update(|queue| queue.change_priority_with(key, change))
}
pub fn remove(&self, key: &K) -> Option<(K, P)> {
self.shard(key).update(|queue| queue.remove(key))
}
pub fn pop(&self) -> Option<(K, P)> {
if self.shards() == 1 {
return self.shards[0].0.update(PagedPriorityQueue::pop);
}
let [a, b] = self.choose_shards();
if let Some(entry) = self.pop_pair(a.min(b), a.max(b)) {
return Some(entry);
}
let start = self.random_index(self.shards());
let found = self
.shard_indices_from(start)
.find_map(|index| self.shards[index].0.update(PagedPriorityQueue::pop));
#[cfg(all(test, loom))]
if found.is_some() {
SCAN_FOUND.store(true, core::sync::atomic::Ordering::Relaxed);
}
found
}
pub fn pop_exact(&self) -> Option<(K, P)> {
let mut queues: Vec<_> = self
.shards
.iter()
.map(|shard| shard.0.queue.write())
.collect();
let best = queues
.iter()
.enumerate()
.filter_map(|(index, queue)| queue.peek().map(|(_, priority)| (index, priority)))
.max_by(|(_, left), (_, right)| left.cmp(right))?
.0;
self.shards[best]
.0
.update_locked(&mut queues[best], PagedPriorityQueue::pop)
}
pub fn peek_exact(&self) -> Option<(K, P)>
where
P: Clone,
{
let queues: Vec<_> = self.read_shards().collect();
queues
.iter()
.filter_map(|queue| queue.peek())
.max_by(|(_, left), (_, right)| left.cmp(right))
.map(|(key, priority)| (*key, priority.clone()))
}
pub fn into_sorted_vec(self) -> Vec<(K, P)> {
let mut entries: Vec<_> = self.into_iter().collect();
entries.sort_unstable_by(|(_, left), (_, right)| left.cmp(right));
entries
}
pub fn into_queue(self) -> PagedPriorityQueue<K, P, PAGE, D> {
let mut queue = PagedPriorityQueue::with_capacity(self.len());
queue.extend(self.into_entries());
queue
}
pub fn snapshot(&self) -> PagedPriorityQueue<K, P, PAGE, D>
where
P: Clone,
{
let mut snapshot = PagedPriorityQueue::with_capacity(self.len());
for shard in self.read_shards() {
snapshot.extend(shard.iter().map(|(key, priority)| (*key, priority.clone())));
}
snapshot
}
fn random_index(&self, bound: usize) -> usize {
#[cfg(all(feature = "std", not(loom)))]
let word = random_word();
#[cfg(any(not(feature = "std"), loom))]
let word =
splitmix64_finalizer(self.random.fetch_add(SPLITMIX_INCREMENT, Ordering::Relaxed));
(word % bound as u64) as usize
}
fn shard_indices_from(&self, start: usize) -> impl Iterator<Item = usize> {
(start..self.shards()).chain(0..start)
}
fn choose_shards(&self) -> [usize; 2] {
let count = self.shards();
let first = self.random_index(count);
let second = self.random_index(count - 1);
let mut chosen = [first, second + usize::from(second >= first)];
let has_hint = |index: usize| self.shards[index].0.len.load(Ordering::Relaxed) != 0;
let mut hinted = chosen.map(has_hint);
for index in self.shard_indices_from(first) {
let Some(slot) = hinted.iter().position(|&nonempty| !nonempty) else {
break;
};
if !chosen.contains(&index) && has_hint(index) {
chosen[slot] = index;
hinted[slot] = true;
}
}
chosen
}
fn pop_pair(&self, lower: usize, higher: usize) -> Option<(K, P)> {
let left = &self.shards[lower].0;
let right = &self.shards[higher].0;
let mut left_queue = left.queue.write();
let mut right_queue = right.queue.write();
let left_top = left_queue.peek().map(|(_, priority)| priority);
let right_top = right_queue.peek().map(|(_, priority)| priority);
if left_top.cmp(&right_top).is_ge() {
left.update_locked(&mut left_queue, PagedPriorityQueue::pop)
} else {
right.update_locked(&mut right_queue, PagedPriorityQueue::pop)
}
}
}
impl<K: Key, P, const PAGE: usize, D: Directory> Default
for ConcurrentPriorityQueue<K, P, PAGE, D>
{
fn default() -> Self {
Self::new()
}
}
impl<K: Key, P: Ord + Clone, const PAGE: usize, D: Directory> Clone
for ConcurrentPriorityQueue<K, P, PAGE, D>
{
fn clone(&self) -> Self {
let mut cloned = Self::with_shards(self.shards());
cloned.extend(self.snapshot());
cloned
}
}
impl<K: Key + fmt::Debug, P: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
for ConcurrentPriorityQueue<K, P, PAGE, D>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut map = f.debug_map();
for shard in self.read_shards() {
map.entries(shard.iter());
}
map.finish()
}
}
impl<K: Key, P: Ord, const PAGE: usize, D: Directory> From<PagedPriorityQueue<K, P, PAGE, D>>
for ConcurrentPriorityQueue<K, P, PAGE, D>
{
fn from(queue: PagedPriorityQueue<K, P, PAGE, D>) -> Self {
queue.into_iter().collect()
}
}
impl<K: Key, P, const PAGE: usize, D: Directory> IntoIterator
for ConcurrentPriorityQueue<K, P, PAGE, D>
{
type Item = (K, P);
type IntoIter = IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
let mut entries = Vec::with_capacity(self.len());
entries.extend(self.into_entries());
entries.into_iter()
}
}
impl<K: Key, P: Ord, const PAGE: usize, D: Directory> Extend<(K, P)>
for ConcurrentPriorityQueue<K, P, PAGE, D>
{
fn extend<I: IntoIterator<Item = (K, P)>>(&mut self, iter: I) {
for (key, priority) in iter {
let index = self.shard_of(&key);
let shard = &mut self.shards[index].0;
let update = UpdateLen {
queue: shard.queue.get_mut(),
len: &shard.len,
};
update.queue.push(key, priority);
}
}
}
impl<K: Key, P: Ord, const PAGE: usize, D: Directory> FromIterator<(K, P)>
for ConcurrentPriorityQueue<K, P, PAGE, D>
{
fn from_iter<I: IntoIterator<Item = (K, P)>>(iter: I) -> Self {
let mut queue = Self::new();
queue.extend(iter);
queue
}
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::*;
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, SerializeSeq, Serializer};
impl<K: Key + Serialize, P: Serialize, const PAGE: usize, D: Directory> Serialize
for ConcurrentPriorityQueue<K, P, PAGE, D>
{
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut seq = serializer.serialize_seq(None)?;
for shard in self.read_shards() {
for entry in shard.iter() {
seq.serialize_element(&entry)?;
}
}
seq.end()
}
}
impl<'de, K: Key + Deserialize<'de>, P: Ord + Deserialize<'de>, const PAGE: usize, D: Directory>
Deserialize<'de> for ConcurrentPriorityQueue<K, P, PAGE, D>
{
fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
PagedPriorityQueue::deserialize(deserializer).map(Self::from)
}
}
}
#[cfg(all(test, loom))]
static SCAN_FOUND: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
#[cfg(all(test, loom))]
#[path = "loom_priority_queue.rs"]
mod loom_tests;