use alloc::collections::TryReserveError;
use alloc::vec::Vec;
use core::cmp::Ordering;
use core::fmt;
use core::hash::{Hash, Hasher};
use core::iter::{FusedIterator, Zip};
use core::ops::{Index, RangeBounds};
use core::slice;
use crate::hash::hash_unordered;
use crate::key::Key;
use crate::page::{DEFAULT_PAGE, Directory, Flat};
use crate::sparse_set::{self, PagedSparseSet, Positions, Slot, index_bounds};
pub struct PagedSparseMap<K, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
keys: PagedSparseSet<K, PAGE, D>,
values: Vec<V>,
}
impl<K: Key, V, const PAGE: usize, D: Directory> PagedSparseMap<K, V, PAGE, D> {
pub const PAGE_SIZE: usize = PAGE;
pub fn new() -> Self {
Self {
keys: PagedSparseSet::new(),
values: Vec::new(),
}
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
keys: PagedSparseSet::with_capacity(capacity),
values: Vec::with_capacity(capacity),
}
}
#[inline]
pub fn len(&self) -> usize {
self.values.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
#[inline]
pub fn capacity(&self) -> usize {
self.keys.capacity().min(self.values.capacity())
}
#[inline]
pub fn allocated_pages(&self) -> usize {
self.keys.allocated_pages()
}
pub fn reserve(&mut self, additional: usize) {
self.keys.reserve(additional);
self.values.reserve(additional);
}
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.keys.try_reserve(additional)?;
self.values.try_reserve(additional)
}
#[inline]
pub fn as_set(&self) -> &PagedSparseSet<K, PAGE, D> {
&self.keys
}
#[inline]
pub fn position(&self, key: K) -> Option<usize> {
self.keys.position(key)
}
#[inline]
pub fn contains_key(&self, key: K) -> bool {
self.keys.contains(key)
}
#[inline]
pub fn get(&self, key: K) -> Option<&V> {
self.position(key).map(|pos| &self.values[pos])
}
#[inline]
pub fn get_mut(&mut self, key: K) -> Option<&mut V> {
self.position(key).map(|pos| &mut self.values[pos])
}
#[inline]
pub fn get_key_value(&self, key: K) -> Option<(&K, &V)> {
self.position(key).map(|pos| self.entry_at(pos))
}
#[inline]
pub fn occupant(&self, index: usize) -> Option<(&K, &V)> {
self.keys.occupant_pos(index).map(|pos| self.entry_at(pos))
}
#[inline]
pub fn occupant_mut(&mut self, index: usize) -> Option<(&K, &mut V)> {
let pos = self.keys.occupant_pos(index)?;
Some((&self.keys.as_slice()[pos], &mut self.values[pos]))
}
#[inline]
fn entry_at(&self, pos: usize) -> (&K, &V) {
(&self.keys.as_slice()[pos], &self.values[pos])
}
fn push_vacant(&mut self, key: K, index: usize, value: V) -> usize {
self.values.reserve(1);
self.keys.insert_vacant(key, index);
self.values.push(value);
self.values.len() - 1
}
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
let index = key.index();
match self.keys.occupant_pos(index) {
Some(pos) => {
if self.keys.as_slice()[pos] != key {
self.keys.overwrite_at(pos, key);
}
Some(core::mem::replace(&mut self.values[pos], value))
}
None => {
self.push_vacant(key, index, value);
None
}
}
}
pub fn replace(&mut self, key: K, value: V) -> Option<(K, V)> {
let index = key.index();
match self.keys.occupant_pos(index) {
Some(pos) => {
let old_key = self.keys.overwrite_at(pos, key);
let old_value = core::mem::replace(&mut self.values[pos], value);
Some((old_key, old_value))
}
None => {
self.push_vacant(key, index, value);
None
}
}
}
pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, V> {
let index = key.index();
if self.keys.occupant_pos(index).is_some() {
return Err(value);
}
let pos = self.push_vacant(key, index, value);
Ok(&mut self.values[pos])
}
pub fn get_or_insert_with(&mut self, key: K, make: impl FnOnce() -> V) -> &mut V {
self.entry(key).or_insert_with(make)
}
pub fn entry(&mut self, key: K) -> Entry<'_, K, V, PAGE, D> {
let index = key.index();
let occupant = self.keys.occupant_pos(index);
match occupant {
Some(pos) if self.keys.as_slice()[pos] == key => {
Entry::Occupied(OccupiedEntry { map: self, pos })
}
_ => Entry::Vacant(VacantEntry {
map: self,
key,
index,
occupant,
}),
}
}
fn remove_at(&mut self, pos: usize) -> (K, V) {
let key = self.keys.remove_at(pos);
let value = self.values.swap_remove(pos);
(key, value)
}
pub fn remove(&mut self, key: K) -> Option<V> {
self.remove_entry(key).map(|(_, value)| value)
}
pub fn remove_entry(&mut self, key: K) -> Option<(K, V)> {
self.position(key).map(|pos| self.remove_at(pos))
}
pub fn remove_occupant(&mut self, index: usize) -> Option<(K, V)> {
self.keys.occupant_pos(index).map(|pos| self.remove_at(pos))
}
pub fn retain(&mut self, mut keep: impl FnMut(&K, &mut V) -> bool) {
let mut pos = 0;
while pos < self.values.len() {
let key = self.keys.as_slice()[pos];
if keep(&key, &mut self.values[pos]) {
pos += 1;
} else {
self.remove_at(pos);
}
}
}
pub fn clear(&mut self) {
self.keys.clear();
self.values.clear();
}
pub fn reset(&mut self) {
self.keys.clear();
self.values.clear();
self.keys.free_pages();
}
pub fn shrink_to_fit(&mut self) {
self.keys.shrink_to_fit();
self.values.shrink_to_fit();
}
#[inline]
pub fn key_slice(&self) -> &[K] {
self.keys.as_slice()
}
#[inline]
pub fn value_slice(&self) -> &[V] {
&self.values
}
#[inline]
pub fn value_slice_mut(&mut self) -> &mut [V] {
&mut self.values
}
#[inline]
pub fn keys(&self) -> slice::Iter<'_, K> {
self.keys.iter()
}
#[inline]
pub fn values(&self) -> slice::Iter<'_, V> {
self.values.iter()
}
#[inline]
pub fn values_mut(&mut self) -> slice::IterMut<'_, V> {
self.values.iter_mut()
}
#[inline]
pub fn iter(&self) -> Iter<'_, K, V> {
Iter(self.keys.iter().zip(self.values.iter()))
}
#[inline]
pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
IterMut(self.keys.iter().zip(self.values.iter_mut()))
}
pub fn drain(&mut self) -> Drain<'_, K, V> {
Drain(self.keys.drain().zip(self.values.drain(..)))
}
pub fn extract_if<F: FnMut(&K, &mut V) -> bool>(
&mut self,
pred: F,
) -> ExtractIf<'_, K, V, F, PAGE, D> {
ExtractIf {
map: self,
pos: 0,
pred,
}
}
pub fn get_disjoint_mut<const N: usize>(&mut self, keys: [K; N]) -> [Option<&mut V>; N] {
let mut order = [(0, 0); N];
let mut n = 0;
for (i, &key) in keys.iter().enumerate() {
if let Some(pos) = self.position(key) {
order[n] = (pos, i);
n += 1;
}
}
let order = &mut order[..n];
order.sort_unstable();
for pair in order.windows(2) {
assert!(
pair[0].0 != pair[1].0,
"PagedSparseMap::get_disjoint_mut: key at positions {} and {} given twice",
pair[0].1,
pair[1].1
);
}
let mut out = [const { None }; N];
let mut rest: &mut [V] = &mut self.values;
let mut start = 0;
for &(pos, i) in order.iter() {
let (_, tail) = core::mem::take(&mut rest).split_at_mut(pos - start);
let (value, tail) = tail
.split_first_mut()
.expect("positions are inside the dense array");
out[i] = Some(value);
rest = tail;
start = pos + 1;
}
out
}
pub fn range(&self, keys: impl RangeBounds<K>) -> Range<'_, K, V, PAGE, D> {
self.range_of(&index_bounds(&keys))
}
fn range_of(&self, indices: &impl RangeBounds<usize>) -> Range<'_, K, V, PAGE, D> {
Range {
positions: self.keys.positions(indices),
values: &self.values,
}
}
pub fn first_key_value(&self) -> Option<(&K, &V)> {
self.range_of(&..).next()
}
pub fn last_key_value(&self) -> Option<(&K, &V)> {
self.range_of(&..).next_back()
}
pub fn next_occupant(&self, index: usize) -> Option<(&K, &V)> {
self.range_of(&(index..)).next()
}
pub fn prev_occupant(&self, index: usize) -> Option<(&K, &V)> {
self.range_of(&(..=index)).next_back()
}
pub fn pop_first(&mut self) -> Option<(K, V)> {
let pos = self.keys.positions(&..).next()?;
Some(self.remove_at(pos))
}
pub fn pop_last(&mut self) -> Option<(K, V)> {
let pos = self.keys.positions(&..).next_back()?;
Some(self.remove_at(pos))
}
pub fn into_keys(self) -> alloc::vec::IntoIter<K> {
self.keys.into_iter()
}
pub fn into_values(self) -> alloc::vec::IntoIter<V> {
self.values.into_iter()
}
fn reorder_by(&mut self, order: impl FnOnce(&mut [usize], &[K], &[V])) {
let mut perm: Vec<usize> = (0..self.len()).collect();
order(&mut perm, self.keys.as_slice(), &self.values);
let values = &mut self.values;
self.keys
.reorder_dense(|keys| permute(&mut perm, keys, values));
}
pub fn sort_by(&mut self, mut compare: impl FnMut((&K, &V), (&K, &V)) -> Ordering) {
self.reorder_by(|perm, keys, values| {
perm.sort_by(|&a, &b| compare((&keys[a], &values[a]), (&keys[b], &values[b])));
});
}
pub fn sort_by_key<T: Ord>(&mut self, mut f: impl FnMut(&K, &V) -> T) {
self.reorder_by(|perm, keys, values| {
perm.sort_by_key(|&i| f(&keys[i], &values[i]));
});
}
pub fn sort_by_cached_key<T: Ord>(&mut self, mut f: impl FnMut(&K, &V) -> T) {
self.reorder_by(|perm, keys, values| {
perm.sort_by_cached_key(|&i| f(&keys[i], &values[i]));
});
}
pub fn sort_keys(&mut self)
where
K: Ord,
{
self.reorder_by(|perm, keys, _| perm.sort_by_key(|&i| keys[i]));
}
pub fn binary_search_key(&self, key: &K) -> Result<usize, usize>
where
K: Ord,
{
self.keys.as_slice().binary_search(key)
}
pub fn binary_search_by(
&self,
mut compare: impl FnMut(&K, &V) -> Ordering,
) -> Result<usize, usize> {
let (keys, values) = (self.keys.as_slice(), &self.values);
let mut size = keys.len();
let mut base = 0;
while size > 0 {
let half = size / 2;
let mid = base + half;
match compare(&keys[mid], &values[mid]) {
Ordering::Less => {
base = mid + 1;
size -= half + 1;
}
Ordering::Greater => size = half,
Ordering::Equal => return Ok(mid),
}
}
Err(base)
}
pub fn partition_point(&self, mut pred: impl FnMut(&K, &V) -> bool) -> usize {
self.binary_search_by(|key, value| {
if pred(key, value) {
Ordering::Less
} else {
Ordering::Greater
}
})
.unwrap_or_else(|pos| pos)
}
pub fn sort_unstable_by(&mut self, mut compare: impl FnMut((&K, &V), (&K, &V)) -> Ordering) {
self.reorder_by(|perm, keys, values| {
perm.sort_unstable_by(|&a, &b| compare((&keys[a], &values[a]), (&keys[b], &values[b])));
});
}
pub fn sort_unstable_by_key<T: Ord>(&mut self, mut f: impl FnMut(&K, &V) -> T) {
self.reorder_by(|perm, keys, values| {
perm.sort_unstable_by_key(|&i| f(&keys[i], &values[i]));
});
}
pub fn sort_unstable_keys(&mut self)
where
K: Ord,
{
self.reorder_by(|perm, keys, _| perm.sort_unstable_by_key(|&i| keys[i]));
}
}
fn permute<K, V>(perm: &mut [usize], keys: &mut [K], values: &mut [V]) {
debug_assert!(perm.len() == keys.len() && perm.len() == values.len());
for start in 0..perm.len() {
let mut cur = start;
while perm[cur] != start {
let next = perm[cur];
keys.swap(cur, next);
values.swap(cur, next);
perm[cur] = cur;
cur = next;
}
perm[cur] = cur;
}
}
impl<K: Key, V, const PAGE: usize, D: Directory> Default for PagedSparseMap<K, V, PAGE, D> {
fn default() -> Self {
Self::new()
}
}
impl<K: Key, V: Clone, const PAGE: usize, D: Directory> Clone for PagedSparseMap<K, V, PAGE, D>
where
D::Store<Slot, PAGE>: Clone,
{
fn clone(&self) -> Self {
Self {
keys: self.keys.clone(),
values: self.values.clone(),
}
}
}
impl<K: Key + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
for PagedSparseMap<K, V, PAGE, D>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map().entries(self.iter()).finish()
}
}
impl<K: Key, V: PartialEq<W>, W, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
PartialEq<PagedSparseMap<K, W, P2, D2>> for PagedSparseMap<K, V, PAGE, D>
{
fn eq(&self, other: &PagedSparseMap<K, W, P2, D2>) -> bool {
self.len() == other.len()
&& self.iter().all(|(&key, value)| {
other
.get(key)
.is_some_and(|other_value| value == other_value)
})
}
}
impl<K: Key, V: Eq, const PAGE: usize, D: Directory> Eq for PagedSparseMap<K, V, PAGE, D> {}
impl<K: Key + Hash, V: Hash, const PAGE: usize, D: Directory> Hash
for PagedSparseMap<K, V, PAGE, D>
{
fn hash<H: Hasher>(&self, state: &mut H) {
hash_unordered(self.iter(), state);
}
}
impl<K: Key, V, const PAGE: usize, D: Directory> Index<K> for PagedSparseMap<K, V, PAGE, D> {
type Output = V;
fn index(&self, key: K) -> &V {
self.get(key).expect("key not in PagedSparseMap")
}
}
impl<K: Key, V, const PAGE: usize, D: Directory> Extend<(K, V)> for PagedSparseMap<K, V, PAGE, D> {
fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
for (key, value) in iter {
self.insert(key, value);
}
}
}
impl<'a, K: Key + 'a, V: Copy + 'a, const PAGE: usize, D: Directory> Extend<(&'a K, &'a V)>
for PagedSparseMap<K, V, PAGE, D>
{
fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
}
}
impl<K: Key, V, const PAGE: usize, D: Directory> FromIterator<(K, V)>
for PagedSparseMap<K, V, PAGE, D>
{
fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
let mut map = Self::new();
map.extend(iter);
map
}
}
impl<'a, K: Key, V, const PAGE: usize, D: Directory> IntoIterator
for &'a PagedSparseMap<K, V, PAGE, D>
{
type Item = (&'a K, &'a V);
type IntoIter = Iter<'a, K, V>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a, K: Key, V, const PAGE: usize, D: Directory> IntoIterator
for &'a mut PagedSparseMap<K, V, PAGE, D>
{
type Item = (&'a K, &'a mut V);
type IntoIter = IterMut<'a, K, V>;
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}
impl<K: Key, V, const PAGE: usize, D: Directory> IntoIterator for PagedSparseMap<K, V, PAGE, D> {
type Item = (K, V);
type IntoIter = IntoIter<K, V>;
fn into_iter(self) -> Self::IntoIter {
IntoIter(self.keys.into_iter().zip(self.values))
}
}
macro_rules! zip_iterator {
($(#[$doc:meta])* $name:ident<$($lt:lifetime,)? $k:ident, $v:ident>, $inner:ty, $item:ty) => {
$(#[$doc])*
#[derive(Debug)]
pub struct $name<$($lt,)? $k, $v>($inner);
impl<$($lt,)? $k, $v> Iterator for $name<$($lt,)? $k, $v> {
type Item = $item;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl<$($lt,)? $k, $v> DoubleEndedIterator for $name<$($lt,)? $k, $v> {
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
self.0.next_back()
}
}
impl<$($lt,)? $k, $v> ExactSizeIterator for $name<$($lt,)? $k, $v> {}
impl<$($lt,)? $k, $v> FusedIterator for $name<$($lt,)? $k, $v> {}
};
}
zip_iterator!(
Iter<'a, K, V>,
Zip<slice::Iter<'a, K>, slice::Iter<'a, V>>,
(&'a K, &'a V)
);
zip_iterator!(
IterMut<'a, K, V>,
Zip<slice::Iter<'a, K>, slice::IterMut<'a, V>>,
(&'a K, &'a mut V)
);
zip_iterator!(
IntoIter<K, V>,
Zip<alloc::vec::IntoIter<K>, alloc::vec::IntoIter<V>>,
(K, V)
);
zip_iterator!(
Drain<'a, K, V>,
Zip<sparse_set::Drain<'a, K>, alloc::vec::Drain<'a, V>>,
(K, V)
);
pub struct Range<'a, K, V, const PAGE: usize = DEFAULT_PAGE, D: Directory + 'a = Flat> {
positions: Positions<'a, K, PAGE, D>,
values: &'a [V],
}
impl<'a, K: Key, V, const PAGE: usize, D: Directory + 'a> Iterator for Range<'a, K, V, PAGE, D> {
type Item = (&'a K, &'a V);
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let pos = self.positions.next()?;
Some((&self.positions.dense()[pos], &self.values[pos]))
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.positions.size_hint()
}
}
impl<'a, K: Key, V, const PAGE: usize, D: Directory + 'a> DoubleEndedIterator
for Range<'a, K, V, PAGE, D>
{
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
let pos = self.positions.next_back()?;
Some((&self.positions.dense()[pos], &self.values[pos]))
}
}
impl<'a, K: Key, V, const PAGE: usize, D: Directory + 'a> FusedIterator
for Range<'a, K, V, PAGE, D>
{
}
impl<'a, K, V, const PAGE: usize, D: Directory + 'a> Clone for Range<'a, K, V, PAGE, D> {
fn clone(&self) -> Self {
Self {
positions: self.positions.clone(),
values: self.values,
}
}
}
impl<'a, K: Key + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory + 'a> fmt::Debug
for Range<'a, K, V, PAGE, D>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
pub enum Entry<'a, K: Key, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
Occupied(OccupiedEntry<'a, K, V, PAGE, D>),
Vacant(VacantEntry<'a, K, V, PAGE, D>),
}
pub struct OccupiedEntry<'a, K: Key, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
map: &'a mut PagedSparseMap<K, V, PAGE, D>,
pos: usize,
}
pub struct VacantEntry<'a, K: Key, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
map: &'a mut PagedSparseMap<K, V, PAGE, D>,
key: K,
index: usize,
occupant: Option<usize>,
}
impl<'a, K: Key, V, const PAGE: usize, D: Directory> Entry<'a, K, V, PAGE, D> {
#[inline]
pub fn key(&self) -> &K {
match self {
Entry::Occupied(entry) => entry.key(),
Entry::Vacant(entry) => entry.key(),
}
}
#[inline]
pub fn or_insert(self, default: V) -> &'a mut V {
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(default),
}
}
#[inline]
pub fn or_insert_with(self, make: impl FnOnce() -> V) -> &'a mut V {
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(make()),
}
}
#[inline]
pub fn or_insert_with_key(self, make: impl FnOnce(&K) -> V) -> &'a mut V {
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => {
let value = make(entry.key());
entry.insert(value)
}
}
}
#[inline]
pub fn or_default(self) -> &'a mut V
where
V: Default,
{
self.or_insert_with(V::default)
}
#[inline]
pub fn and_modify(mut self, f: impl FnOnce(&mut V)) -> Self {
if let Entry::Occupied(entry) = &mut self {
f(entry.get_mut());
}
self
}
#[inline]
pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, PAGE, D> {
match self {
Entry::Occupied(mut entry) => {
entry.insert(value);
entry
}
Entry::Vacant(entry) => entry.insert_entry(value),
}
}
}
impl<'a, K: Key, V, const PAGE: usize, D: Directory> OccupiedEntry<'a, K, V, PAGE, D> {
#[inline]
pub fn key(&self) -> &K {
&self.map.keys.as_slice()[self.pos]
}
#[inline]
pub fn get(&self) -> &V {
&self.map.values[self.pos]
}
#[inline]
pub fn get_mut(&mut self) -> &mut V {
&mut self.map.values[self.pos]
}
#[inline]
pub fn into_mut(self) -> &'a mut V {
&mut self.map.values[self.pos]
}
#[inline]
pub fn insert(&mut self, value: V) -> V {
core::mem::replace(self.get_mut(), value)
}
#[inline]
pub fn remove(self) -> V {
self.remove_entry().1
}
pub fn remove_entry(self) -> (K, V) {
self.map.remove_at(self.pos)
}
}
impl<'a, K: Key, V, const PAGE: usize, D: Directory> VacantEntry<'a, K, V, PAGE, D> {
#[inline]
pub fn key(&self) -> &K {
&self.key
}
#[inline]
pub fn into_key(self) -> K {
self.key
}
#[inline]
pub fn insert(self, value: V) -> &'a mut V {
self.insert_entry(value).into_mut()
}
fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, PAGE, D> {
let Self {
map,
key,
index,
occupant,
} = self;
let pos = match occupant {
Some(pos) => {
map.keys.overwrite_at(pos, key);
drop(core::mem::replace(&mut map.values[pos], value));
pos
}
None => map.push_vacant(key, index, value),
};
OccupiedEntry { map, pos }
}
}
impl<K: Key + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
for Entry<'_, K, V, PAGE, D>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Entry::Occupied(entry) => f.debug_tuple("Occupied").field(entry).finish(),
Entry::Vacant(entry) => f.debug_tuple("Vacant").field(entry).finish(),
}
}
}
impl<K: Key + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
for OccupiedEntry<'_, K, V, PAGE, D>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OccupiedEntry")
.field("key", self.key())
.field("value", self.get())
.finish()
}
}
impl<K: Key + fmt::Debug, V, const PAGE: usize, D: Directory> fmt::Debug
for VacantEntry<'_, K, V, PAGE, D>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("VacantEntry")
.field("key", self.key())
.finish()
}
}
pub struct ExtractIf<'a, K, V, F, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
map: &'a mut PagedSparseMap<K, V, PAGE, D>,
pos: usize,
pred: F,
}
impl<K: Key, V, F: FnMut(&K, &mut V) -> bool, const PAGE: usize, D: Directory> Iterator
for ExtractIf<'_, K, V, F, PAGE, D>
{
type Item = (K, V);
fn next(&mut self) -> Option<(K, V)> {
while self.pos < self.map.values.len() {
let pos = self.pos;
let key = self.map.keys.as_slice()[pos];
self.pos += 1;
if (self.pred)(&key, &mut self.map.values[pos]) {
self.pos = pos;
return Some(self.map.remove_at(pos));
}
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some(self.map.values.len() - self.pos))
}
}
impl<K: Key, V, F: FnMut(&K, &mut V) -> bool, const PAGE: usize, D: Directory> FusedIterator
for ExtractIf<'_, K, V, F, PAGE, D>
{
}
impl<K: Key + fmt::Debug, V: fmt::Debug, F, const PAGE: usize, D: Directory> fmt::Debug
for ExtractIf<'_, K, V, F, PAGE, D>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let pos = self.pos;
f.debug_struct("ExtractIf")
.field("untested_keys", &&self.map.keys.as_slice()[pos..])
.field("untested_values", &&self.map.values[pos..])
.finish_non_exhaustive()
}
}
impl<K, V> Clone for Iter<'_, K, V> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<K: Clone, V: Clone> Clone for IntoIter<K, V> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
#[cfg(feature = "rayon")]
mod rayon_impl {
use super::*;
use rayon::iter::Zip;
use rayon::prelude::*;
use rayon::slice::{Iter, IterMut};
impl<K: Key, V, const PAGE: usize, D: Directory> PagedSparseMap<K, V, PAGE, D> {
pub fn par_keys(&self) -> Iter<'_, K>
where
K: Sync,
{
self.key_slice().par_iter()
}
pub fn par_values(&self) -> Iter<'_, V>
where
V: Sync,
{
self.value_slice().par_iter()
}
pub fn par_values_mut(&mut self) -> IterMut<'_, V>
where
V: Send,
{
self.value_slice_mut().par_iter_mut()
}
}
impl<'a, K: Key + Sync, V: Sync, const PAGE: usize, D: Directory> IntoParallelIterator
for &'a PagedSparseMap<K, V, PAGE, D>
{
type Item = (&'a K, &'a V);
type Iter = Zip<Iter<'a, K>, Iter<'a, V>>;
fn into_par_iter(self) -> Self::Iter {
self.par_keys().zip(self.par_values())
}
}
impl<'a, K: Key + Sync, V: Send, const PAGE: usize, D: Directory> IntoParallelIterator
for &'a mut PagedSparseMap<K, V, PAGE, D>
{
type Item = (&'a K, &'a mut V);
type Iter = Zip<Iter<'a, K>, IterMut<'a, V>>;
fn into_par_iter(self) -> Self::Iter {
self.keys
.as_slice()
.par_iter()
.zip(self.values.par_iter_mut())
}
}
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::*;
use core::marker::PhantomData;
use serde::de::{Deserialize, Deserializer, MapAccess, Visitor};
use serde::ser::{Serialize, Serializer};
fn max_prealloc<K, V>() -> usize {
let entry = core::mem::size_of::<K>() + core::mem::size_of::<V>();
usize::try_from(1_u32 << 20)
.unwrap_or(usize::MAX)
.checked_div(entry)
.unwrap_or(usize::MAX)
.min(4096)
}
impl<K: Key + Serialize, V: Serialize, const PAGE: usize, D: Directory> Serialize
for PagedSparseMap<K, V, PAGE, D>
{
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_map(self.iter())
}
}
impl<'de, K, V, const PAGE: usize, D> Deserialize<'de> for PagedSparseMap<K, V, PAGE, D>
where
K: Key + Deserialize<'de>,
V: Deserialize<'de>,
D: Directory,
{
fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
struct MapVisitor<K, V, const PAGE: usize, D>(PhantomData<(K, V, D)>);
impl<'de, K, V, const PAGE: usize, D> Visitor<'de> for MapVisitor<K, V, PAGE, D>
where
K: Key + Deserialize<'de>,
V: Deserialize<'de>,
D: Directory,
{
type Value = PagedSparseMap<K, V, PAGE, D>;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a map of keys to values")
}
fn visit_map<A: MapAccess<'de>>(
self,
mut access: A,
) -> Result<Self::Value, A::Error> {
let hint = access.size_hint().unwrap_or(0).min(max_prealloc::<K, V>());
let mut map = PagedSparseMap::with_capacity(hint);
while let Some((key, value)) = access.next_entry()? {
map.insert(key, value);
}
Ok(map)
}
}
deserializer.deserialize_map(MapVisitor::<K, V, PAGE, D>(PhantomData))
}
}
}
#[cfg(all(test, any(target_pointer_width = "32", target_pointer_width = "64")))]
mod tests {
use super::*;
use alloc::string::{String, ToString};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct Gen(u32);
impl Key for Gen {
fn index(self) -> usize {
(self.0 & 0xffff) as usize
}
}
fn assert_parallel<K: Key + fmt::Debug, V, const PAGE: usize, D: Directory>(
map: &PagedSparseMap<K, V, PAGE, D>,
) {
assert_eq!(map.key_slice().len(), map.value_slice().len());
for (pos, &key) in map.key_slice().iter().enumerate() {
assert_eq!(map.position(key), Some(pos), "{key:?}");
}
}
#[test]
fn remove_moves_last_entry_with_its_value() {
let mut map: PagedSparseMap<u32, char, 4> = [(1, 'a'), (2, 'b'), (3, 'c'), (40, 'd')]
.into_iter()
.collect();
assert_eq!(map.remove(1), Some('a'));
assert_eq!(map.key_slice(), &[40, 2, 3]);
assert_eq!(map.value_slice(), &['d', 'b', 'c']);
assert_eq!(map.remove(1), None);
assert_eq!(map.remove_entry(3), Some((3, 'c')));
assert_eq!(map[40], 'd');
assert_parallel(&map);
}
#[test]
fn insert_updates_in_place() {
let mut map: PagedSparseMap<u32, u32> = (0..5).map(|k| (k, k * 10)).collect();
assert_eq!(map.insert(2, 99), Some(20));
assert_eq!(map.position(2), Some(2));
assert_eq!(map.value_slice(), &[0, 10, 99, 30, 40]);
*map.get_mut(4).unwrap() += 1;
assert_eq!(map.get(4), Some(&41));
}
#[derive(Clone, Copy, Debug)]
struct Tagged {
id: u32,
tag: u8,
}
impl PartialEq for Tagged {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for Tagged {}
impl Key for Tagged {
fn index(self) -> usize {
self.id as usize
}
}
#[test]
fn insert_keeps_an_equal_stored_key_and_replace_does_not() {
let mut map: PagedSparseMap<Tagged, u8> = PagedSparseMap::new();
map.insert(Tagged { id: 3, tag: 1 }, 10);
assert_eq!(map.insert(Tagged { id: 3, tag: 2 }, 20), Some(10));
assert_eq!(map.key_slice()[0].tag, 1);
let (old, _) = map.replace(Tagged { id: 3, tag: 3 }, 30).unwrap();
assert_eq!(old.tag, 1);
assert_eq!(map.key_slice()[0].tag, 3);
assert_eq!(map.clone().into_keys().next().map(|k| k.tag), Some(3));
assert_eq!(map.into_values().collect::<Vec<_>>(), [30]);
}
#[test]
fn generations_by_method() {
let old = Gen(7);
let new = Gen(7 | 1 << 16);
let mut map: PagedSparseMap<Gen, &str> = PagedSparseMap::new();
assert_eq!(map.try_insert(old, "old").copied(), Ok("old"));
assert_eq!(map.try_insert(new, "new"), Err("new"));
assert_eq!(map.try_insert(old, "again"), Err("again"));
assert_eq!(map.get(new), None);
assert_eq!(map.occupant(7), Some((&old, &"old")));
assert_eq!(map.replace(new, "new"), Some((old, "old")));
assert_eq!(map.get(old), None);
assert_eq!(map.insert(old, "back"), Some("new"));
assert_eq!(map.get_or_insert_with(new, || "made"), &"made");
assert_eq!(map.get_or_insert_with(new, || unreachable!()), &"made");
assert_eq!(map.len(), 1);
assert_eq!(map.remove(old), None);
if let Some((_, v)) = map.occupant_mut(7) {
*v = "edited";
}
assert_eq!(map.remove_occupant(7), Some((new, "edited")));
assert!(map.is_empty());
}
#[test]
fn clear_is_lazy_but_correct() {
let mut map: PagedSparseMap<u32, String, 4> = (0..10).map(|k| (k, k.to_string())).collect();
map.clear();
assert!(map.is_empty());
assert_eq!(map.allocated_pages(), 3);
assert!((0..10).all(|k| !map.contains_key(k)));
map.insert(9, "nine".into());
assert_eq!(map.get(0), None);
assert_eq!(map.position(9), Some(0));
map.reset();
assert_eq!(map.allocated_pages(), 0);
}
#[test]
fn retain_and_sort_move_values_with_keys() {
let mut map: PagedSparseMap<u32, u32, 8> = [9, 3, 7, 1, 8, 2]
.into_iter()
.map(|k| (k, k * 100))
.collect();
map.retain(|&k, v| {
*v += 1;
k % 3 != 0
});
map.sort_unstable_keys();
assert_eq!(map.key_slice(), &[1, 2, 7, 8]);
assert_eq!(map.value_slice(), &[101, 201, 701, 801]);
assert_parallel(&map);
map.sort_unstable_by(|(_, a), (_, b)| b.cmp(a));
assert_eq!(map.key_slice(), &[8, 7, 2, 1]);
map.sort_unstable_by_key(|&k, _| k % 7);
assert_eq!(map.key_slice(), &[7, 8, 1, 2]);
assert_eq!(map.value_slice(), &[701, 801, 101, 201]);
assert_parallel(&map);
}
#[test]
fn stable_sorts_keep_ties_in_order_and_searches_find_positions() {
let mut map: PagedSparseMap<u32, u32, 4> = [(5, 1), (9, 0), (2, 1), (7, 0), (40, 1)]
.into_iter()
.collect();
map.sort_by_key(|_, &v| v);
assert_eq!(map.key_slice(), &[9, 7, 5, 2, 40]);
assert_eq!(map.value_slice(), &[0, 0, 1, 1, 1]);
assert_parallel(&map);
assert_eq!(map.partition_point(|_, &v| v == 0), 2);
assert_eq!(map.partition_point(|_, _| true), 5);
assert_eq!(map.partition_point(|_, _| false), 0);
map.sort_by(|(a, _), (b, _)| (a % 2).cmp(&(b % 2)));
assert_eq!(map.key_slice(), &[2, 40, 9, 7, 5]);
let mut calls = 0;
map.sort_by_cached_key(|&k, _| {
calls += 1;
k / 10
});
assert_eq!(calls, 5);
assert_eq!(map.key_slice(), &[2, 9, 7, 5, 40]);
assert_parallel(&map);
map.sort_keys();
assert_eq!(map.key_slice(), &[2, 5, 7, 9, 40]);
assert_eq!(map.value_slice(), &[1, 1, 0, 0, 1]);
assert_parallel(&map);
assert_eq!(map.binary_search_key(&7), Ok(2));
assert_eq!(map.binary_search_key(&0), Err(0));
assert_eq!(map.binary_search_key(&8), Err(3));
assert_eq!(map.binary_search_key(&41), Err(5));
for (pos, &key) in map.key_slice().iter().enumerate() {
assert_eq!(map.binary_search_by(|k, _| k.cmp(&key)), Ok(pos));
}
assert_eq!(map.binary_search_by(|k, _| k.cmp(&6)), Err(2));
let empty: PagedSparseMap<u32, u32> = PagedSparseMap::new();
assert_eq!(empty.binary_search_key(&1), Err(0));
assert_eq!(empty.partition_point(|_, _| true), 0);
}
#[test]
fn permute_handles_every_permutation_of_four() {
for a in 0..4 {
for b in 0..4 {
for c in 0..4 {
for d in 0..4 {
let p = [a, b, c, d];
if (0..4).any(|i| !p.contains(&i)) {
continue;
}
let mut perm = p;
let mut keys = [10, 11, 12, 13];
let mut values = ['a', 'b', 'c', 'd'];
permute(&mut perm, &mut keys, &mut values);
assert_eq!(keys, p.map(|i| 10 + i), "{p:?}");
assert_eq!(values, p.map(|i| ['a', 'b', 'c', 'd'][i]), "{p:?}");
assert_eq!(perm, [0, 1, 2, 3]);
}
}
}
}
}
#[test]
fn equality_and_iterators() {
let a: PagedSparseMap<u32, i32> = [(1, -1), (2, -2)].into_iter().collect();
let mut b: PagedSparseMap<u32, i32> = [(2, -2), (1, -1)].into_iter().collect();
assert_eq!(a, b);
for (_, v) in &mut b {
*v *= 2;
}
assert_ne!(a, b);
assert_eq!(b.iter().rev().collect::<Vec<_>>(), [(&1, &-2), (&2, &-4)]);
assert_eq!(b.iter().len(), 2);
assert_eq!(b.into_iter().collect::<Vec<_>>(), [(2, -4), (1, -2)]);
}
}