use alloc::boxed::Box;
use core::fmt;
use core::mem;
use core::num::NonZeroU32;
use core::ops::{Bound, RangeBounds};
use core::slice;
use super::atomic::{AtomicU64, Ordering};
use super::count::StripedLen;
use super::directory::{PageIter, SharedDirectory, SharedPages};
use crate::direct_map::PagedDirectMap;
use crate::id_alloc::Id;
use crate::page::{DEFAULT_PAGE, Flat};
struct Page {
slots: Box<[AtomicU64]>,
}
struct Words<const PAGE: usize, D: SharedDirectory> {
pages: D::Pages<Page>,
len: StripedLen,
}
unsafe impl<const PAGE: usize, D: SharedDirectory> Send for Words<PAGE, D> {}
unsafe impl<const PAGE: usize, D: SharedDirectory> Sync for Words<PAGE, D> {}
impl<const PAGE: usize, D: SharedDirectory> Words<PAGE, D> {
fn valid_page_capacity() -> bool {
PAGE > 0 && PAGE <= isize::MAX as usize / mem::size_of::<AtomicU64>()
}
fn new(name: &str) -> Self {
assert!(Self::valid_page_capacity(), "{name}: invalid page capacity");
Self {
pages: D::Pages::<Page>::new(),
len: StripedLen::new(),
}
}
fn slot(&self, index: usize) -> Option<&AtomicU64> {
self.pages
.get(D::Pages::<Page>::page_number::<PAGE>(index)?)
.map(|page| &page.slots[index % PAGE])
}
fn ensure_slot(&self, index: usize, name: &str) -> &AtomicU64 {
let number = D::Pages::<Page>::page_number::<PAGE>(index)
.unwrap_or_else(|| panic!("{name}: key index exceeds direct spine range"));
let page = self.pages.get_or_insert_with(number, || {
Box::new(Page {
slots: (0..PAGE).map(|_| AtomicU64::new(0)).collect(),
})
});
&page.slots[index % PAGE]
}
fn load(&self, index: usize) -> u64 {
self.slot(index)
.map_or(0, |slot| slot.load(Ordering::Acquire))
}
fn count_change(&self, index: usize, old: u64, new: u64) {
match (old == 0, new == 0) {
(true, false) => self.len.increment(index / PAGE),
(false, true) => self.len.decrement(index / PAGE),
_ => {}
}
}
fn len(&self) -> usize {
self.len.get()
}
fn swap(&self, index: usize, new: u64, name: &str) -> u64 {
let slot = if new == 0 {
let Some(slot) = self.slot(index) else {
return 0;
};
slot
} else {
self.ensure_slot(index, name)
};
let old = slot.swap(new, Ordering::AcqRel);
self.count_change(index, old, new);
old
}
fn try_insert(&self, index: usize, new: u64, name: &str) -> Result<(), u64> {
let slot = self.ensure_slot(index, name);
match slot.compare_exchange(0, new, Ordering::AcqRel, Ordering::Acquire) {
Ok(old) => {
self.count_change(index, old, new);
Ok(())
}
Err(actual) => Err(actual),
}
}
fn update(
&self,
index: usize,
name: &str,
install: bool,
mut f: impl FnMut(u64) -> Option<u64>,
) -> Result<u64, u64> {
let mut slot = if install {
Some(self.ensure_slot(index, name))
} else {
self.slot(index)
};
let mut old = slot.map_or(0, |slot| slot.load(Ordering::Acquire));
loop {
let Some(new) = f(old) else {
return Err(old);
};
let target = match slot {
Some(slot) => slot,
None => {
let found = if new == 0 {
self.slot(index)
} else {
Some(self.ensure_slot(index, name))
};
let Some(found) = found else {
return Ok(0);
};
slot = Some(found);
found
}
};
match target.compare_exchange(old, new, Ordering::AcqRel, Ordering::Acquire) {
Ok(previous) => {
self.count_change(index, previous, new);
return Ok(previous);
}
Err(actual) => old = actual,
}
}
}
fn range(&self, start: usize, end: usize) -> WordsIter<'_, PAGE> {
WordsIter {
pages: self.pages.iter(),
slots: slice::Iter::default().enumerate(),
base: 0,
start,
end,
}
}
fn shrink_to_fit(&mut self) {
self.pages.retain(|_, page| {
page.slots
.iter()
.any(|slot| slot.load(Ordering::Relaxed) != 0)
});
}
fn clear(&mut self) {
for (_, page) in self.pages.iter_mut() {
for slot in page.slots.iter() {
slot.store(0, Ordering::Relaxed);
}
}
self.len.reset();
}
fn reset(&mut self) {
self.pages.clear();
self.len.reset();
}
}
struct WordsIter<'a, const PAGE: usize> {
pages: PageIter<'a, Page>,
slots: core::iter::Enumerate<slice::Iter<'a, AtomicU64>>,
base: usize,
start: usize,
end: usize,
}
impl<const PAGE: usize> Iterator for WordsIter<'_, PAGE> {
type Item = (usize, u64);
fn next(&mut self) -> Option<Self::Item> {
while self.start <= self.end {
for (offset, slot) in self.slots.by_ref() {
let word = slot.load(Ordering::Acquire);
if word != 0 {
return Some((self.base + offset, word));
}
}
let (number, page) = self.pages.next()?;
if number < self.start / PAGE {
continue;
}
if number > self.end / PAGE {
self.start = 1;
self.end = 0;
return None;
}
let first = if number == self.start / PAGE {
self.start % PAGE
} else {
0
};
let last = if number == self.end / PAGE {
self.end % PAGE + 1
} else {
PAGE
};
self.base = number * PAGE + first;
self.slots = page.slots[first..last].iter().enumerate();
}
None
}
}
fn index_bounds(keys: impl RangeBounds<usize>) -> (usize, usize) {
let start = match keys.start_bound() {
Bound::Included(&index) => index,
Bound::Excluded(&index) => match index.checked_add(1) {
Some(index) => index,
None => return (1, 0),
},
Bound::Unbounded => 0,
};
let end = match keys.end_bound() {
Bound::Included(&index) => index,
Bound::Excluded(&index) => match index.checked_sub(1) {
Some(index) => index,
None => return (1, 0),
},
Bound::Unbounded => usize::MAX,
};
(start, end)
}
fn encode_direct(value: u64) -> u64 {
value
.checked_add(1)
.expect("AtomicDirectMap: u64::MAX cannot be stored")
}
fn decode_direct(word: u64) -> Option<u64> {
word.checked_sub(1)
}
pub struct AtomicDirectMap<const PAGE: usize = DEFAULT_PAGE, D: SharedDirectory = Flat> {
words: Words<PAGE, D>,
}
impl<const PAGE: usize, D: SharedDirectory> AtomicDirectMap<PAGE, D> {
pub const PAGE_SIZE: usize = PAGE;
pub const MAX_VALUE: u64 = u64::MAX - 1;
pub fn new() -> Self {
Self {
words: Words::new("AtomicDirectMap"),
}
}
pub fn len(&self) -> usize {
self.words.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn allocated_pages(&self) -> usize {
self.words.pages.iter().count()
}
pub fn get(&self, key: usize) -> Option<u64> {
decode_direct(self.words.load(key))
}
pub fn contains_key(&self, key: usize) -> bool {
self.get(key).is_some()
}
pub fn insert(&self, key: usize, value: u64) -> Option<u64> {
decode_direct(
self.words
.swap(key, encode_direct(value), "AtomicDirectMap"),
)
}
pub fn try_insert(&self, key: usize, value: u64) -> Result<(), u64> {
self.words
.try_insert(key, encode_direct(value), "AtomicDirectMap")
.map_err(|word| decode_direct(word).unwrap())
}
pub fn remove(&self, key: usize) -> Option<u64> {
decode_direct(self.words.swap(key, 0, "AtomicDirectMap"))
}
pub fn compare_exchange(
&self,
key: usize,
current: Option<u64>,
new: Option<u64>,
) -> Result<Option<u64>, Option<u64>> {
let word = new.map_or(0, encode_direct);
self.words
.update(key, "AtomicDirectMap", new.is_some(), |old| {
(decode_direct(old) == current).then_some(word)
})
.map(decode_direct)
.map_err(decode_direct)
}
pub fn fetch_update(
&self,
key: usize,
mut f: impl FnMut(Option<u64>) -> Option<Option<u64>>,
) -> Result<Option<u64>, Option<u64>> {
self.words
.update(key, "AtomicDirectMap", false, |old| {
f(decode_direct(old)).map(|new| new.map_or(0, encode_direct))
})
.map(decode_direct)
.map_err(decode_direct)
}
pub fn iter(&self) -> AtomicDirectMapIter<'_, PAGE> {
AtomicDirectMapIter {
inner: self.words.range(0, usize::MAX),
}
}
pub fn range(&self, keys: impl RangeBounds<usize>) -> impl Iterator<Item = (usize, u64)> {
let (start, end) = index_bounds(keys);
self.words
.range(start, end)
.map(|(key, word)| (key, word - 1))
}
pub fn shrink_to_fit(&mut self) {
self.words.shrink_to_fit();
}
pub fn clear(&mut self) {
self.words.clear();
}
pub fn snapshot(&self) -> PagedDirectMap<usize, u64, PAGE, D> {
self.iter().collect()
}
pub fn into_inner(self) -> PagedDirectMap<usize, u64, PAGE, D> {
self.iter().collect()
}
pub fn reset(&mut self) {
self.words.reset();
}
}
fn encode_id(id: Id, value: u32) -> u64 {
(u64::from(id.generation().get()) << 32) | u64::from(value)
}
fn decode_id(index: u32, word: u64) -> Option<(Id, u32)> {
let generation = NonZeroU32::new((word >> 32) as u32)?;
Some((Id::new(index, generation), word as u32))
}
fn id_value(id: Id, word: u64) -> Option<u32> {
((word >> 32) as u32 == id.generation().get()).then_some(word as u32)
}
fn id_update(id: Id, old: u64, new: Option<u32>) -> u64 {
match new {
Some(value) => encode_id(id, value),
None if id_value(id, old).is_some() => 0,
None => old,
}
}
pub struct AtomicIdMap<const PAGE: usize = DEFAULT_PAGE> {
words: Words<PAGE, Flat>,
}
impl<const PAGE: usize> AtomicIdMap<PAGE> {
pub const PAGE_SIZE: usize = PAGE;
pub fn new() -> Self {
Self {
words: Words::new("AtomicIdMap"),
}
}
pub fn len(&self) -> usize {
self.words.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn allocated_pages(&self) -> usize {
self.words.pages.iter().count()
}
pub fn get(&self, id: Id) -> Option<u32> {
id_value(id, self.words.load(id.index() as usize))
}
pub fn contains_key(&self, id: Id) -> bool {
self.get(id).is_some()
}
pub fn occupant(&self, index: u32) -> Option<(Id, u32)> {
decode_id(index, self.words.load(index as usize))
}
pub fn insert(&self, id: Id, value: u32) -> Option<u32> {
self.replace(id, value).map(|(_, value)| value)
}
pub fn replace(&self, id: Id, value: u32) -> Option<(Id, u32)> {
let old = self
.words
.swap(id.index() as usize, encode_id(id, value), "AtomicIdMap");
decode_id(id.index(), old)
}
pub fn try_insert(&self, id: Id, value: u32) -> Result<(), (Id, u32)> {
self.words
.try_insert(id.index() as usize, encode_id(id, value), "AtomicIdMap")
.map_err(|word| decode_id(id.index(), word).unwrap())
}
pub fn remove(&self, id: Id) -> Option<u32> {
self.words
.update(id.index() as usize, "AtomicIdMap", false, |old| {
id_value(id, old).map(|_| 0)
})
.ok()
.and_then(|old| id_value(id, old))
}
pub fn remove_occupant(&self, index: u32) -> Option<(Id, u32)> {
decode_id(index, self.words.swap(index as usize, 0, "AtomicIdMap"))
}
pub fn compare_exchange(
&self,
id: Id,
current: Option<u32>,
new: Option<u32>,
) -> Result<Option<u32>, Option<u32>> {
self.words
.update(id.index() as usize, "AtomicIdMap", new.is_some(), |old| {
(id_value(id, old) == current).then(|| id_update(id, old, new))
})
.map(|old| id_value(id, old))
.map_err(|actual| id_value(id, actual))
}
pub fn fetch_update(
&self,
id: Id,
mut f: impl FnMut(Option<u32>) -> Option<Option<u32>>,
) -> Result<Option<u32>, Option<u32>> {
self.words
.update(id.index() as usize, "AtomicIdMap", false, |old| {
f(id_value(id, old)).map(|new| id_update(id, old, new))
})
.map(|old| id_value(id, old))
.map_err(|actual| id_value(id, actual))
}
pub fn iter(&self) -> AtomicIdMapIter<'_, PAGE> {
AtomicIdMapIter {
inner: self.words.range(0, usize::MAX),
}
}
pub fn range(&self, indices: impl RangeBounds<u32>) -> impl Iterator<Item = (Id, u32)> {
let bounds = (
indices.start_bound().map(|&index| index as usize),
indices.end_bound().map(|&index| index as usize),
);
let (start, end) = index_bounds(bounds);
self.words
.range(start, end)
.filter_map(|(index, word)| decode_id(index as u32, word))
}
pub fn shrink_to_fit(&mut self) {
self.words.shrink_to_fit();
}
pub fn clear(&mut self) {
self.words.clear();
}
pub fn reset(&mut self) {
self.words.reset();
}
}
impl<'a, const PAGE: usize, D: SharedDirectory> IntoIterator for &'a AtomicDirectMap<PAGE, D> {
type Item = (usize, u64);
type IntoIter = AtomicDirectMapIter<'a, PAGE>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a, const PAGE: usize> IntoIterator for &'a AtomicIdMap<PAGE> {
type Item = (Id, u32);
type IntoIter = AtomicIdMapIter<'a, PAGE>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct AtomicDirectMapIter<'a, const PAGE: usize = DEFAULT_PAGE> {
inner: WordsIter<'a, PAGE>,
}
impl<const PAGE: usize> Iterator for AtomicDirectMapIter<'_, PAGE> {
type Item = (usize, u64);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|(key, word)| (key, word - 1))
}
}
impl<const PAGE: usize> fmt::Debug for AtomicDirectMapIter<'_, PAGE> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AtomicDirectMapIter")
.finish_non_exhaustive()
}
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct AtomicIdMapIter<'a, const PAGE: usize = DEFAULT_PAGE> {
inner: WordsIter<'a, PAGE>,
}
impl<const PAGE: usize> Iterator for AtomicIdMapIter<'_, PAGE> {
type Item = (Id, u32);
fn next(&mut self) -> Option<Self::Item> {
self.inner
.find_map(|(index, word)| decode_id(index as u32, word))
}
}
impl<const PAGE: usize> fmt::Debug for AtomicIdMapIter<'_, PAGE> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AtomicIdMapIter").finish_non_exhaustive()
}
}
impl<const PAGE: usize, D: SharedDirectory> Clone for AtomicDirectMap<PAGE, D> {
fn clone(&self) -> Self {
Self::from(self.snapshot())
}
}
impl<const PAGE: usize, D: SharedDirectory> Default for AtomicDirectMap<PAGE, D> {
fn default() -> Self {
Self::new()
}
}
impl<const PAGE: usize, D: SharedDirectory> fmt::Debug for AtomicDirectMap<PAGE, D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map().entries(self.iter()).finish()
}
}
impl<const PAGE: usize, D: SharedDirectory> FromIterator<(usize, u64)>
for AtomicDirectMap<PAGE, D>
{
fn from_iter<T: IntoIterator<Item = (usize, u64)>>(iter: T) -> Self {
let mut map = Self::new();
map.extend(iter);
map
}
}
impl<const PAGE: usize, D: SharedDirectory> Extend<(usize, u64)> for AtomicDirectMap<PAGE, D> {
fn extend<T: IntoIterator<Item = (usize, u64)>>(&mut self, iter: T) {
for (key, value) in iter {
self.insert(key, value);
}
}
}
impl<const PAGE: usize, D: SharedDirectory> From<PagedDirectMap<usize, u64, PAGE, D>>
for AtomicDirectMap<PAGE, D>
{
fn from(map: PagedDirectMap<usize, u64, PAGE, D>) -> Self {
map.into_iter().collect()
}
}
impl<const PAGE: usize> Clone for AtomicIdMap<PAGE> {
fn clone(&self) -> Self {
self.iter().collect()
}
}
impl<const PAGE: usize> Default for AtomicIdMap<PAGE> {
fn default() -> Self {
Self::new()
}
}
impl<const PAGE: usize> fmt::Debug for AtomicIdMap<PAGE> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map().entries(self.iter()).finish()
}
}
impl<const PAGE: usize> FromIterator<(Id, u32)> for AtomicIdMap<PAGE> {
fn from_iter<T: IntoIterator<Item = (Id, u32)>>(iter: T) -> Self {
let mut map = Self::new();
map.extend(iter);
map
}
}
impl<const PAGE: usize> Extend<(Id, u32)> for AtomicIdMap<PAGE> {
fn extend<T: IntoIterator<Item = (Id, u32)>>(&mut self, iter: T) {
for (id, value) in iter {
self.insert(id, value);
}
}
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::*;
use crate::concurrent::serde::deserialize_map;
use alloc::vec::Vec;
use serde::de::{Deserialize, Deserializer, Error};
use serde::ser::{Serialize, Serializer};
impl<const PAGE: usize, D: SharedDirectory> Serialize for AtomicDirectMap<PAGE, D> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_map(self.iter().collect::<Vec<_>>())
}
}
impl<'de, const PAGE: usize, D: SharedDirectory> Deserialize<'de> for AtomicDirectMap<PAGE, D> {
fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
if !Words::<PAGE, D>::valid_page_capacity() {
return Err(De::Error::custom("AtomicDirectMap: invalid page capacity"));
}
deserialize_map(deserializer, Self::new(), |map, index, value| {
if value > Self::MAX_VALUE {
return Err("AtomicDirectMap: u64::MAX cannot be stored");
}
if D::Pages::<Page>::page_number::<PAGE>(index).is_none() {
return Err("AtomicDirectMap: key index exceeds direct spine range");
}
map.insert(index, value);
Ok(())
})
}
}
impl<const PAGE: usize> Serialize for AtomicIdMap<PAGE> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_map(self.iter().collect::<Vec<_>>())
}
}
impl<'de, const PAGE: usize> Deserialize<'de> for AtomicIdMap<PAGE> {
fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
if !Words::<PAGE, Flat>::valid_page_capacity() {
return Err(De::Error::custom("AtomicIdMap: invalid page capacity"));
}
deserialize_map(deserializer, Self::new(), |map, id: Id, value| {
if <Flat as SharedDirectory>::Pages::<Page>::page_number::<PAGE>(id.index() as usize)
.is_none()
{
return Err("AtomicIdMap: id index exceeds direct spine range");
}
map.insert(id, value);
Ok(())
})
}
}
}