use alloc::collections::TryReserveError;
use alloc::vec::Vec;
use core::cmp::Ordering;
use core::fmt;
use core::iter::{FusedIterator, Zip};
use core::ops::Index;
use core::slice;
use crate::key::Key;
use crate::page::{DEFAULT_PAGE, Directory, Flat};
use crate::sparse_set::{PagedSparseSet, Slot};
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 {
let index = key.index();
let pos = match self.keys.occupant_pos(index) {
Some(pos) if self.keys.as_slice()[pos] == key => pos,
Some(pos) => {
let value = make();
self.keys.overwrite_at(pos, key);
drop(core::mem::replace(&mut self.values[pos], value));
pos
}
None => {
let value = make();
self.push_vacant(key, index, value)
}
};
&mut self.values[pos]
}
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 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, const PAGE: usize, D: Directory> PartialEq
for PagedSparseMap<K, V, PAGE, D>
{
fn eq(&self, other: &Self) -> bool {
self.len() == other.len()
&& self
.iter()
.all(|(&key, value)| other.get(key) == Some(value))
}
}
impl<K: Key, V: Eq, const PAGE: usize, D: Directory> Eq for PagedSparseMap<K, V, PAGE, D> {}
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)
);
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 = "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)]);
}
}