use super::{
Entry, IdOrdItem, IntoIter, Iter, IterMut, OccupiedEntry, RefMut,
VacantEntry, tables::IdOrdMapTables,
};
use crate::{
errors::DuplicateItem,
internal::{ValidateChaos, ValidateCompact, ValidationError},
support::{
alloc::{Global, global_alloc},
borrow::DormantMutRef,
item_set::ItemSet,
map_hash::MapHash,
},
};
use alloc::collections::BTreeSet;
use core::{
fmt,
hash::{BuildHasher, Hash},
};
use equivalent::{Comparable, Equivalent};
#[derive(Clone)]
pub struct IdOrdMap<T> {
pub(super) items: ItemSet<T, Global>,
pub(super) tables: IdOrdMapTables,
}
impl<T: IdOrdItem> Default for IdOrdMap<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: IdOrdItem> IdOrdMap<T> {
#[inline]
pub const fn new() -> Self {
Self { items: ItemSet::new(), tables: IdOrdMapTables::new() }
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
items: ItemSet::with_capacity_in(capacity, global_alloc()),
tables: IdOrdMapTables::new(),
}
}
pub fn capacity(&self) -> usize {
self.items.capacity()
}
pub fn from_iter_unique<I: IntoIterator<Item = T>>(
iter: I,
) -> Result<Self, DuplicateItem<T>> {
let mut map = IdOrdMap::new();
for value in iter {
match map.entry(value.key()) {
Entry::Occupied(entry) => {
let duplicate = entry.remove();
return Err(DuplicateItem::__internal_new(
value,
vec![duplicate],
));
}
Entry::Vacant(entry) => {
entry.insert_ref(value);
}
}
}
Ok(map)
}
#[inline]
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
#[inline]
pub fn len(&self) -> usize {
self.items.len()
}
pub fn clear(&mut self) {
self.items.clear();
self.tables.key_to_item.clear();
}
pub fn reserve(&mut self, additional: usize) {
self.items.reserve(additional);
}
pub fn shrink_to_fit(&mut self) {
self.items.shrink_to_fit();
}
pub fn shrink_to(&mut self, min_capacity: usize) {
self.items.shrink_to(min_capacity);
}
#[inline]
pub fn iter(&self) -> Iter<'_, T> {
Iter::new(&self.items, &self.tables)
}
#[inline]
pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T>
where
T::Key<'a>: Hash,
{
IterMut::new(&mut self.items, &self.tables)
}
#[doc(hidden)]
pub fn validate(
&self,
compactness: ValidateCompact,
chaos: ValidateChaos,
) -> Result<(), ValidationError>
where
T: fmt::Debug,
{
self.items.validate(compactness)?;
self.tables.validate(self.len(), compactness)?;
for (&ix, item) in self.items.iter() {
let key = item.key();
let ix1 = match chaos {
ValidateChaos::Yes => {
self.linear_search_index(&key)
}
ValidateChaos::No => {
self.find_index(&key)
}
};
let Some(ix1) = ix1 else {
return Err(ValidationError::general(format!(
"item at index {ix} has no key1 index"
)));
};
if ix1 != ix {
return Err(ValidationError::General(format!(
"item at index {ix} has mismatched indexes: ix1: {ix1}",
)));
}
}
Ok(())
}
pub fn insert_unique(
&mut self,
value: T,
) -> Result<(), DuplicateItem<T, &T>> {
let _ = self.insert_unique_impl(value)?;
Ok(())
}
#[doc(alias = "insert")]
pub fn insert_overwrite(&mut self, value: T) -> Option<T> {
let duplicate = self.remove(&value.key());
if self.insert_unique(value).is_err() {
panic!("insert_unique failed after removing duplicates");
}
duplicate
}
pub fn contains_key<'a, Q>(&'a self, key: &Q) -> bool
where
Q: ?Sized + Comparable<T::Key<'a>>,
{
self.find_index(key).is_some()
}
pub fn get<'a, Q>(&'a self, key: &Q) -> Option<&'a T>
where
Q: ?Sized + Comparable<T::Key<'a>>,
{
self.find(key)
}
pub fn get_mut<'a, Q>(&'a mut self, key: &Q) -> Option<RefMut<'a, T>>
where
Q: ?Sized + Comparable<T::Key<'a>>,
T::Key<'a>: Hash,
{
let (dormant_map, index) = {
let (map, dormant_map) = DormantMutRef::new(self);
let index = map.find_index(key)?;
(dormant_map, index)
};
let awakened_map = unsafe { dormant_map.awaken() };
let item = &mut awakened_map.items[index];
let state = awakened_map.tables.state().clone();
let (hash, dormant) = {
let (item, dormant) = DormantMutRef::new(item);
let hash = awakened_map.tables.make_hash(item);
(hash, dormant)
};
let item = unsafe { dormant.awaken() };
Some(RefMut::new(state, hash, item))
}
pub fn remove<'a, Q>(&'a mut self, key: &Q) -> Option<T>
where
Q: ?Sized + Comparable<T::Key<'a>>,
{
let (dormant_map, remove_index) = {
let (map, dormant_map) = DormantMutRef::new(self);
let remove_index = map.find_index(key)?;
(dormant_map, remove_index)
};
let awakened_map = unsafe { dormant_map.awaken() };
awakened_map.remove_by_index(remove_index)
}
pub fn entry<'a>(&'a mut self, key: T::Key<'_>) -> Entry<'a, T> {
let (map, dormant_map) = DormantMutRef::new(self);
let key = T::upcast_key(key);
{
let index: Option<usize> = map
.tables
.key_to_item
.find_index(&key, |index| map.items[index].key());
if let Some(index) = index {
drop(key);
return Entry::Occupied(
unsafe { OccupiedEntry::new(dormant_map, index) },
);
}
}
Entry::Vacant(
unsafe { VacantEntry::new(dormant_map) },
)
}
#[inline]
pub fn first(&self) -> Option<&T> {
self.tables.key_to_item.first().map(|index| &self.items[index])
}
pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, T>> {
let index = self.tables.key_to_item.first()?;
let (_, dormant_map) = DormantMutRef::new(self);
Some(
unsafe { OccupiedEntry::new(dormant_map, index) },
)
}
pub fn pop_first(&mut self) -> Option<T> {
let index = self.tables.key_to_item.first()?;
self.remove_by_index(index)
}
#[inline]
pub fn last(&self) -> Option<&T> {
self.tables.key_to_item.last().map(|index| &self.items[index])
}
pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, T>> {
let index = self.tables.key_to_item.last()?;
let (_, dormant_map) = DormantMutRef::new(self);
Some(
unsafe { OccupiedEntry::new(dormant_map, index) },
)
}
pub fn pop_last(&mut self) -> Option<T> {
let index = self.tables.key_to_item.last()?;
self.remove_by_index(index)
}
pub fn retain<'a, F>(&'a mut self, mut f: F)
where
F: FnMut(RefMut<'a, T>) -> bool,
T::Key<'a>: Hash,
{
let hash_state = self.tables.state().clone();
let (_, mut dormant_items) = DormantMutRef::new(&mut self.items);
self.tables.key_to_item.retain(|index| {
let (item, dormant_items) = {
let items = unsafe { dormant_items.reborrow() };
let (items, dormant_items) = DormantMutRef::new(items);
let item: &'a mut T = items
.get_mut(index)
.expect("all indexes are present in self.items");
(item, dormant_items)
};
let (hash, dormant_item) = {
let (item, dormant_item): (&'a mut T, _) =
DormantMutRef::new(item);
let key = T::key(item);
let hash = hash_state.hash_one(key);
(MapHash::new(hash), dormant_item)
};
let retain = {
let item = unsafe { dormant_item.awaken() };
let ref_mut = RefMut::new(hash_state.clone(), hash, item);
f(ref_mut)
};
if retain {
true
} else {
let items = unsafe { dormant_items.awaken() };
items.remove(index);
false
}
});
}
fn find<'a, Q>(&'a self, k: &Q) -> Option<&'a T>
where
Q: ?Sized + Comparable<T::Key<'a>>,
{
self.find_index(k).map(|ix| &self.items[ix])
}
fn linear_search_index<'a, Q>(&'a self, k: &Q) -> Option<usize>
where
Q: ?Sized + Ord + Equivalent<T::Key<'a>>,
{
self.items.iter().find_map(|(index, item)| {
(k.equivalent(&item.key())).then_some(*index)
})
}
fn find_index<'a, Q>(&'a self, k: &Q) -> Option<usize>
where
Q: ?Sized + Comparable<T::Key<'a>>,
{
self.tables.key_to_item.find_index(k, |index| self.items[index].key())
}
pub(super) fn get_by_index(&self, index: usize) -> Option<&T> {
self.items.get(index)
}
pub(super) fn get_by_index_mut<'a>(
&'a mut self,
index: usize,
) -> Option<RefMut<'a, T>>
where
T::Key<'a>: Hash,
{
let state = self.tables.state().clone();
let (hash, dormant) = {
let item: &'a mut T = self.items.get_mut(index)?;
let (item, dormant) = DormantMutRef::new(item);
let hash = self.tables.make_hash(item);
(hash, dormant)
};
let item = unsafe { dormant.awaken() };
Some(RefMut::new(state, hash, item))
}
pub(super) fn insert_unique_impl(
&mut self,
value: T,
) -> Result<usize, DuplicateItem<T, &T>> {
let mut duplicates = BTreeSet::new();
let key = value.key();
if let Some(index) = self
.tables
.key_to_item
.find_index(&key, |index| self.items[index].key())
{
duplicates.insert(index);
}
if !duplicates.is_empty() {
drop(key);
return Err(DuplicateItem::__internal_new(
value,
duplicates.iter().map(|ix| &self.items[*ix]).collect(),
));
}
let next_index = self.items.next_index();
self.tables
.key_to_item
.insert(next_index, &key, |index| self.items[index].key());
drop(key);
self.items.insert_at_next_index(value);
Ok(next_index)
}
pub(super) fn remove_by_index(&mut self, remove_index: usize) -> Option<T> {
let value = self.items.remove(remove_index)?;
self.tables.key_to_item.remove(remove_index, value.key(), |index| {
if index == remove_index {
value.key()
} else {
self.items[index].key()
}
});
Some(value)
}
pub(super) fn replace_at_index(&mut self, index: usize, value: T) -> T {
let old_key =
self.get_by_index(index).expect("index is known to be valid").key();
if T::upcast_key(old_key) != value.key() {
panic!(
"must insert a value with \
the same key used to create the entry"
);
}
self.items.replace(index, value)
}
}
impl<'a, T: IdOrdItem> fmt::Debug for IdOrdMap<T>
where
T: fmt::Debug,
T::Key<'a>: fmt::Debug,
T: 'a,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut map = f.debug_map();
for item in self.iter() {
let key = item.key();
let key: T::Key<'a> =
unsafe { core::mem::transmute::<T::Key<'_>, T::Key<'a>>(key) };
map.entry(&key, &item);
}
map.finish()
}
}
impl<T: IdOrdItem + PartialEq> PartialEq for IdOrdMap<T> {
fn eq(&self, other: &Self) -> bool {
if self.items.len() != other.items.len() {
return false;
}
self.iter().zip(other.iter()).all(|(item1, item2)| {
item1 == item2
})
}
}
impl<T: IdOrdItem + Eq> Eq for IdOrdMap<T> {}
impl<T: IdOrdItem> Extend<T> for IdOrdMap<T> {
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
let iter = iter.into_iter();
let reserve = if self.is_empty() {
iter.size_hint().0
} else {
iter.size_hint().0.div_ceil(2)
};
self.reserve(reserve);
for item in iter {
self.insert_overwrite(item);
}
}
}
impl<'a, T: IdOrdItem> IntoIterator for &'a IdOrdMap<T> {
type Item = &'a T;
type IntoIter = Iter<'a, T>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a, T: IdOrdItem> IntoIterator for &'a mut IdOrdMap<T>
where
T::Key<'a>: Hash,
{
type Item = RefMut<'a, T>;
type IntoIter = IterMut<'a, T>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}
impl<T: IdOrdItem> IntoIterator for IdOrdMap<T> {
type Item = T;
type IntoIter = IntoIter<T>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
IntoIter::new(self.items, self.tables)
}
}
impl<T: IdOrdItem> FromIterator<T> for IdOrdMap<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut map = IdOrdMap::new();
for value in iter {
map.insert_overwrite(value);
}
map
}
}