use crate::{AsMutSlice, LinearMap};
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct VecMap<K: Eq, V: Sized + PartialEq> {
vector: Vec<(K, V)>,
}
impl<K: Eq, V: Sized + PartialEq> VecMap<K, V> {
pub fn new() -> VecMap<K, V> {
VecMap { vector: Vec::new() }
}
pub const unsafe fn from_vec_unchecked(vector: Vec<(K, V)>) -> VecMap<K, V> {
VecMap { vector }
}
pub fn len(&self) -> usize {
self.vector.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn with_capacity(capacity: usize) -> VecMap<K, V> {
VecMap {
vector: Vec::with_capacity(capacity),
}
}
pub fn remove(&mut self, key: &K) -> Option<V> {
self.remove_entry(key).map(|(_, v)| v)
}
pub fn remove_entry(&mut self, key: &K) -> Option<(K, V)> {
let idx = self
.vector
.iter()
.enumerate()
.find(|(_, (k, _))| k == key)
.map(|(i, _)| i)?;
Some(self.vector.remove(idx))
}
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
match self.vector.iter_mut().find(|(k, _)| *k == key) {
Some((_, v)) => Some(std::mem::replace(v, value)),
None => {
self.vector.push((key, value));
None
}
}
}
}
impl<K: Eq, V: Sized + PartialEq> LinearMap<K, V> for VecMap<K, V> {
type Backing = Vec<(K, V)>;
fn as_slice(&self) -> &[(K, V)] {
self.vector.as_slice()
}
fn into_inner(self) -> Self::Backing {
self.vector
}
}
impl<K: Eq, V: Sized + PartialEq> AsMutSlice<K, V> for VecMap<K, V> {
fn as_mut_slice(&mut self) -> &mut [(K, V)] {
self.vector.as_mut_slice()
}
}