use crate::utils::unlikely;
use crate::{DeferredMap, Key, identity::MapToken};
use std::{collections::TryReserveError, error::Error, fmt};
#[derive(Debug)]
pub enum SecondaryMapInsertError {
SentinelIndex,
IndexOutOfRange { index: u32 },
Allocation(TryReserveError),
}
impl fmt::Display for SecondaryMapInsertError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::SentinelIndex => {
f.write_str("SecondaryMap key index 0 is reserved for the primary map sentinel")
}
Self::IndexOutOfRange { index } => {
write!(f, "SecondaryMap key index {index} is out of range")
}
Self::Allocation(_) => f.write_str("failed to reserve SecondaryMap storage"),
}
}
}
impl Error for SecondaryMapInsertError {}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SecondaryMapBindError {
AssociationMismatch,
AlreadyBoundToAnotherMap,
}
impl fmt::Display for SecondaryMapBindError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::AssociationMismatch => f.write_str("SecondaryMap belongs to another primary map"),
Self::AlreadyBoundToAnotherMap => {
f.write_str("SecondaryMap is already bound to another map instance")
}
}
}
}
impl Error for SecondaryMapBindError {}
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct Slot<T> {
value: T,
generation: crate::Generation,
}
impl<T> Slot<T> {
#[inline(always)]
fn new(value: T, generation: crate::Generation) -> Self {
Self { value, generation }
}
#[inline(always)]
fn generation(&self) -> crate::Generation {
self.generation
}
}
#[derive(Clone)]
pub struct SecondaryMap<T, K: Key = crate::DefaultKey> {
slots: Vec<Option<Slot<T>>>,
num_elems: usize,
map_id: Option<u64>,
association_token: Option<MapToken>,
_marker: std::marker::PhantomData<K>,
}
impl<T, K: Key> Default for SecondaryMap<T, K> {
fn default() -> Self {
Self::new()
}
}
impl<T, K: Key> SecondaryMap<T, K> {
#[inline]
pub fn new() -> Self {
Self {
slots: Vec::new(),
num_elems: 0,
map_id: None,
association_token: None,
_marker: std::marker::PhantomData,
}
}
#[inline]
pub fn with_capacity(capacity: usize) -> Self {
Self {
slots: Vec::with_capacity(capacity),
num_elems: 0,
map_id: None,
association_token: None,
_marker: std::marker::PhantomData,
}
}
pub fn bind_to<M>(&mut self, map: &DeferredMap<M, K>) -> Result<(), SecondaryMapBindError> {
let map_id = map.map_id();
if let Some(current_id) = self.map_id
&& current_id != map_id
{
return Err(SecondaryMapBindError::AlreadyBoundToAnotherMap);
}
if let Some(current_token) = self.association_token
&& current_token != map.association_token()
{
return Err(SecondaryMapBindError::AssociationMismatch);
}
self.association_token = Some(map.association_token());
self.map_id = Some(map_id);
Ok(())
}
#[inline]
fn map_id_for_keys(&self) -> u64 {
match self.map_id {
Some(map_id) => map_id,
None => {
assert_eq!(
self.num_elems, 0,
"SecondaryMap must be bound to a DeferredMap before use"
);
0
}
}
}
pub fn insert(&mut self, key: K, value: T) -> Result<Option<T>, SecondaryMapInsertError> {
let map_id = self
.map_id
.expect("SecondaryMap must be bound to a DeferredMap before inserting");
assert_eq!(
map_id,
key.map_id(),
"Key used with wrong map instance in SecondaryMap"
);
let raw_index = key.index();
if raw_index == 0 {
return Err(SecondaryMapInsertError::SentinelIndex);
}
let generation = key.generation();
let index = usize::try_from(raw_index)
.map_err(|_| SecondaryMapInsertError::IndexOutOfRange { index: raw_index })?;
let required_len = index
.checked_add(1)
.ok_or(SecondaryMapInsertError::IndexOutOfRange { index: raw_index })?;
if required_len > self.slots.len() {
let required_additional = required_len - self.slots.len();
self.slots
.try_reserve(required_additional)
.map_err(SecondaryMapInsertError::Allocation)?;
self.slots.resize_with(required_len, || None);
}
let slot_opt = &mut self.slots[index];
match slot_opt {
Some(slot) => {
if slot.generation() == generation {
Ok(Some(std::mem::replace(&mut slot.value, value)))
} else if slot.generation() < generation {
let old_slot = slot_opt.replace(Slot::new(value, generation));
drop(old_slot);
Ok(None)
} else {
Ok(None)
}
}
None => {
*slot_opt = Some(Slot::new(value, generation));
self.num_elems += 1;
Ok(None)
}
}
}
pub fn remove(&mut self, key: K) -> Option<T> {
let map_id = self.map_id_for_keys();
self.map_id?;
assert_eq!(
map_id,
key.map_id(),
"Key used with wrong map instance in SecondaryMap"
);
let index = key.index();
let generation = key.generation();
let index = index as usize;
if unlikely(index >= self.slots.len()) {
return None;
}
let slot_opt = unsafe { self.slots.get_unchecked_mut(index) };
if let Some(slot) = slot_opt
&& slot.generation() == generation
{
self.num_elems -= 1;
return slot_opt.take().map(|s| s.value);
}
None
}
#[inline]
pub fn get(&self, key: K) -> Option<&T> {
let map_id = self.map_id_for_keys();
self.map_id?;
assert_eq!(
map_id,
key.map_id(),
"Key used with wrong map instance in SecondaryMap"
);
let index = key.index();
let generation = key.generation();
let index = index as usize;
if unlikely(index >= self.slots.len()) {
return None;
}
match unsafe { self.slots.get_unchecked(index) } {
Some(slot) if slot.generation() == generation => Some(&slot.value),
_ => None,
}
}
#[inline]
pub fn get_mut(&mut self, key: K) -> Option<&mut T> {
let map_id = self.map_id_for_keys();
self.map_id?;
assert_eq!(
map_id,
key.map_id(),
"Key used with wrong map instance in SecondaryMap"
);
let index = key.index();
let generation = key.generation();
let index = index as usize;
if unlikely(index >= self.slots.len()) {
return None;
}
match unsafe { self.slots.get_unchecked_mut(index) } {
Some(slot) if slot.generation() == generation => Some(&mut slot.value),
_ => None,
}
}
#[inline]
pub fn contains_key(&self, key: K) -> bool {
self.get(key).is_some()
}
#[inline]
pub fn len(&self) -> usize {
self.num_elems
}
#[inline]
pub fn is_empty(&self) -> bool {
self.num_elems == 0
}
#[inline]
pub fn capacity(&self) -> usize {
self.slots.capacity()
}
pub fn clear(&mut self) {
self.num_elems = 0;
self.map_id = None;
self.association_token = None;
let slots = self.slots.drain(..);
drop(slots);
}
pub fn retain<F>(&mut self, mut f: F)
where
F: FnMut(K, &mut T) -> bool,
{
let map_id = self.map_id_for_keys();
for (index, slot_opt) in self.slots.iter_mut().enumerate() {
if let Some(slot) = slot_opt {
let key = K::from_parts(index as u32, slot.generation, map_id);
if !f(key, &mut slot.value) {
let slot = slot_opt
.take()
.expect("SecondaryMap slot disappeared during retain");
self.num_elems -= 1;
let Slot { value, .. } = slot;
drop(value);
}
}
}
}
pub fn iter(&self) -> impl Iterator<Item = (K, &T)> {
let map_id = self.map_id_for_keys();
self.slots
.iter()
.enumerate()
.filter_map(move |(index, slot_opt)| {
slot_opt.as_ref().map(|slot| {
let key = K::from_parts(index as u32, slot.generation, map_id);
(key, &slot.value)
})
})
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = (K, &mut T)> {
let map_id = self.map_id_for_keys();
self.slots
.iter_mut()
.enumerate()
.filter_map(move |(index, slot_opt)| {
slot_opt.as_mut().map(|slot| {
let key = K::from_parts(index as u32, slot.generation, map_id);
(key, &mut slot.value)
})
})
}
}
#[cfg(feature = "serde")]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(tag = "state", content = "token", rename_all = "snake_case")]
enum SecondaryMapBinding {
Unbound,
Bound(MapToken),
}
#[cfg(feature = "serde")]
impl<T: serde::Serialize, K: Key> serde::Serialize for SecondaryMap<T, K> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
#[derive(serde::Serialize)]
struct SecondaryMapSerializeHelper<'a, T> {
slots: &'a [Option<Slot<T>>],
num_elems: u64,
binding: SecondaryMapBinding,
}
let helper = SecondaryMapSerializeHelper {
slots: &self.slots,
num_elems: self.num_elems as u64,
binding: match self.association_token {
Some(token) => SecondaryMapBinding::Bound(token),
None => SecondaryMapBinding::Unbound,
},
};
serde::Serialize::serialize(&helper, serializer)
}
}
#[cfg(feature = "serde")]
impl<'de, T: serde::Deserialize<'de>, K: Key> serde::Deserialize<'de> for SecondaryMap<T, K> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct SecondaryMapDeserializeHelper<T> {
slots: Vec<Option<Slot<T>>>,
num_elems: u64,
binding: SecondaryMapBinding,
}
let helper =
<SecondaryMapDeserializeHelper<T> as serde::Deserialize>::deserialize(deserializer)?;
let actual_num_elems = helper
.slots
.iter()
.try_fold(0_usize, |count, slot| {
if slot.is_some() {
count.checked_add(1)
} else {
Some(count)
}
})
.ok_or_else(|| serde::de::Error::custom("SecondaryMap element count overflow"))?;
if helper.slots.first().is_some_and(Option::is_some) {
return Err(serde::de::Error::custom(
"SecondaryMap cannot contain the primary map sentinel index",
));
}
let serialized_num_elems = usize::try_from(helper.num_elems).map_err(|_| {
serde::de::Error::custom("SecondaryMap element count exceeds platform limits")
})?;
if serialized_num_elems != actual_num_elems {
return Err(serde::de::Error::custom(
"SecondaryMap element count does not match occupied slots",
));
}
let association_token = match helper.binding {
SecondaryMapBinding::Unbound if actual_num_elems != 0 => {
return Err(serde::de::Error::custom(
"non-empty SecondaryMap must contain an association token",
));
}
SecondaryMapBinding::Unbound => None,
SecondaryMapBinding::Bound(token) => Some(token),
};
Ok(Self {
slots: helper.slots,
num_elems: actual_num_elems,
map_id: None,
association_token,
_marker: std::marker::PhantomData,
})
}
}
impl<T: fmt::Debug> fmt::Debug for SecondaryMap<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map().entries(self.iter()).finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::mem::size_of;
#[test]
fn test_slot_niche_optimization() {
assert_eq!(size_of::<Slot<u32>>(), 8);
assert_eq!(
size_of::<Option<Slot<u32>>>(),
8,
"Niche optimization failed for Slot<u32>"
);
assert_eq!(size_of::<Slot<u64>>(), 16);
assert_eq!(
size_of::<Option<Slot<u64>>>(),
16,
"Niche optimization failed for Slot<u64>"
);
}
}