use core::{marker::PhantomData, mem};
use alloc::vec::Vec;
use crate::allocator::{Allocator, DefaultAllocator};
#[derive(Debug)]
#[must_use]
pub enum Entry<'a, K, V, A: Allocator = DefaultAllocator> {
Occupied(OccupiedEntry<'a, K, V, A>),
Vacant(VacantEntry<'a, K, V, A>),
}
impl<'a, K, V, A: Allocator> Entry<'a, K, V, A> {
#[must_use]
#[inline]
pub fn key(&self) -> &K {
match self {
Entry::Occupied(occupied) => occupied.key(),
Entry::Vacant(vacant) => vacant.key(),
}
}
#[must_use]
#[inline]
pub fn or_insert(self, default: V) -> &'a mut V {
match self {
Entry::Occupied(occupied) => occupied.get_mut(),
Entry::Vacant(vacant) => vacant.insert(default),
}
}
}
#[allow(clippy::module_name_repetitions)]
#[derive(Debug)]
#[must_use]
pub struct OccupiedEntry<'a, K, V, A: Allocator = DefaultAllocator> {
#[cfg(feature = "allocator_api")]
pub(crate) vec: &'a mut Vec<(K, V), A>,
#[cfg(not(feature = "allocator_api"))]
pub(crate) vec: &'a mut Vec<(K, V)>,
pub(crate) phantom: PhantomData<A>,
pub(crate) index: usize,
pub(crate) key: K,
}
impl<'a, K, V, A: Allocator> OccupiedEntry<'a, K, V, A> {
#[must_use]
#[inline]
pub fn key(&self) -> &K {
&self.key
}
#[must_use]
#[inline]
pub fn get(self) -> &'a V {
let (_key, value) = self.vec.get(self.index).expect("Index out of bounds!");
value
}
#[must_use]
#[inline]
pub fn get_mut(self) -> &'a mut V {
let (_key, value) = self.vec.get_mut(self.index).expect("Index out of bounds!");
value
}
#[must_use]
#[inline]
pub fn remove_entry(self) -> (K, V) {
self.vec.swap_remove(self.index)
}
#[must_use]
#[inline]
pub fn remove(self) -> V {
let (_key, value) = self.vec.swap_remove(self.index);
value
}
#[must_use]
#[inline]
pub fn insert(&mut self, neuer_value: V) -> V {
let (_key, value) = self.vec.get_mut(self.index).expect("Index out of bounds!");
mem::replace(value, neuer_value)
}
}
#[allow(clippy::module_name_repetitions)]
#[derive(Debug)]
#[must_use]
pub struct VacantEntry<'a, K, V, A: Allocator = DefaultAllocator> {
#[cfg(feature = "allocator_api")]
pub(crate) vec: &'a mut Vec<(K, V), A>,
#[cfg(not(feature = "allocator_api"))]
pub(crate) vec: &'a mut Vec<(K, V)>,
pub(crate) phantom: PhantomData<A>,
pub(crate) key: K,
}
impl<'a, K, V, A: Allocator> VacantEntry<'a, K, V, A> {
#[must_use]
#[inline]
pub fn key(&self) -> &K {
&self.key
}
#[must_use]
#[inline]
pub fn insert(self, value: V) -> &'a mut V {
self.vec.push((self.key, value));
let (_key, inserted_value) = self.vec.last_mut().expect("Element has just been added!");
inserted_value
}
}