#![deny(missing_docs)]
use core::cmp::Ordering;
use core::hash::Hash;
use core::hash::Hasher;
use std::borrow::Borrow;
use std::fmt;
use std::fmt::Debug;
use std::iter;
use std::mem;
use std::ops;
use std::slice;
use std::vec;
use self::Entry::Occupied;
use self::Entry::Vacant;
pub struct LinearMap<K, V> {
pub(crate) storage: Vec<(K, V)>,
}
impl<K, V> LinearMap<K, V> {
#[inline]
pub fn from_vec_unchecked(storage: Vec<(K, V)>) -> Self {
Self { storage }
}
}
impl<K: Eq, V> LinearMap<K, V> {
#[inline]
pub const fn new() -> Self {
Self { storage: vec![] }
}
#[inline]
pub fn with_capacity(capacity: usize) -> Self {
Self {
storage: Vec::with_capacity(capacity),
}
}
#[inline]
pub fn capacity(&self) -> usize {
self.storage.capacity()
}
#[inline]
pub fn reserve(&mut self, additional: usize) {
self.storage.reserve(additional);
}
#[inline]
pub fn reserve_exact(&mut self, additional: usize) {
self.storage.reserve_exact(additional);
}
#[inline]
pub fn shrink_to_fit(&mut self) {
self.storage.shrink_to_fit();
}
#[inline]
pub fn shrink_to(&mut self, min_capacity: usize) {
self.storage.shrink_to(min_capacity);
}
#[inline]
pub fn truncate(&mut self, len: usize) {
self.storage.truncate(len);
}
#[inline]
pub fn len(&self) -> usize {
self.storage.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.storage.is_empty()
}
#[inline]
pub fn clear(&mut self) {
self.storage.clear();
}
pub fn retain<F>(&mut self, mut keep_fn: F)
where
F: FnMut(&K, &mut V) -> bool,
{
let mut del = 0;
{
let v = &mut *self.storage;
for i in 0..v.len() {
if !keep_fn(&v[i].0, &mut v[i].1) {
del += 1;
} else if del > 0 {
v.swap(i - del, i);
}
}
}
if del > 0 {
let len = self.storage.len();
self.storage.truncate(len - del);
}
}
#[inline]
pub fn drain(&mut self) -> Drain<'_, K, V> {
Drain {
iter: self.storage.drain(..),
}
}
#[inline]
pub fn iter(&self) -> Iter<'_, K, V> {
Iter {
iter: self.storage.iter(),
}
}
#[inline]
pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
IterMut {
iter: self.storage.iter_mut(),
}
}
#[inline]
pub fn iter_full_unchecked_mut(&mut self) -> IterFullUncheckedMut<'_, K, V> {
IterFullUncheckedMut {
iter: self.storage.iter_mut(),
}
}
#[inline]
pub fn keys(&self) -> Keys<'_, K, V> {
Keys { iter: self.iter() }
}
#[inline]
pub fn values(&self) -> Values<'_, K, V> {
Values { iter: self.iter() }
}
#[inline]
pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
ValuesMut {
iter: self.storage.iter_mut(),
}
}
pub fn get<Q: ?Sized + Eq>(&self, key: &Q) -> Option<&V>
where
K: Borrow<Q>,
{
for (k, v) in self {
if key == k.borrow() {
return Some(v);
}
}
None
}
pub fn get_mut<Q: ?Sized + Eq>(&mut self, key: &Q) -> Option<&mut V>
where
K: Borrow<Q>,
{
for (k, v) in self {
if key == k.borrow() {
return Some(v);
}
}
None
}
#[inline]
pub fn get_index(&self, index: usize) -> Option<&(K, V)> {
self.storage.get(index)
}
#[inline]
pub fn get_index_mut(&mut self, index: usize) -> Option<(&K, &mut V)> {
let (k, v) = self.storage.get_mut(index)?;
Some((&*k, v))
}
#[inline]
pub fn contains_key<Q: ?Sized + Eq>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
{
self.get(key).is_some()
}
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
match self.entry(key) {
Occupied(mut e) => Some(e.insert(value)),
Vacant(e) => {
e.insert(value);
None
}
}
}
pub fn remove<Q: ?Sized + Eq>(&mut self, key: &Q) -> Option<V>
where
K: Borrow<Q>,
{
for i in 0..self.storage.len() {
if self.storage[i].0.borrow() == key {
return Some(self.storage.swap_remove(i).1);
}
}
None
}
pub fn shift_remove<Q: ?Sized + Eq>(&mut self, key: &Q) -> Option<V>
where
K: Borrow<Q>,
{
for i in 0..self.storage.len() {
if self.storage[i].0.borrow() == key {
return Some(self.storage.remove(i).1);
}
}
None
}
pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
match self.storage.iter().position(|(k, _)| key == *k) {
None => Vacant(VacantEntry { map: self, key }),
Some(index) => Occupied(OccupiedEntry { map: self, index }),
}
}
#[inline]
pub fn sort_keys(&mut self)
where
K: Ord,
{
self.storage.sort_unstable_by(|(k1, _), (k2, _)| k1.cmp(k2));
}
#[inline]
pub fn sort_by<F>(&mut self, mut cmp: F)
where
F: FnMut(&K, &V, &K, &V) -> Ordering,
{
self.storage
.sort_by(|(k1, v1), (k2, v2)| cmp(k1, v1, k2, v2));
}
#[inline]
pub fn sort_unstable_by<F>(&mut self, mut cmp: F)
where
F: FnMut(&K, &V, &K, &V) -> Ordering,
{
self.storage
.sort_unstable_by(|(k1, v1), (k2, v2)| cmp(k1, v1, k2, v2));
}
#[inline]
pub fn reverse(&mut self) {
self.storage.reverse();
}
#[inline]
pub fn as_slice(&self) -> &[(K, V)] {
&self.storage
}
}
impl<K: Clone, V: Clone> Clone for LinearMap<K, V> {
#[inline]
fn clone(&self) -> Self {
Self {
storage: self.storage.clone(),
}
}
#[inline]
fn clone_from(&mut self, other: &Self) {
self.storage.clone_from(&other.storage);
}
}
impl<K: Eq + Debug, V: Debug> Debug for LinearMap<K, V> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map().entries(self).finish()
}
}
impl<K: Eq, V> Default for LinearMap<K, V> {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl<K: Eq, V> Extend<(K, V)> for LinearMap<K, V> {
fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, key_values: I) {
for (key, value) in key_values {
self.insert(key, value);
}
}
}
impl<K: Eq, V> iter::FromIterator<(K, V)> for LinearMap<K, V> {
#[inline]
fn from_iter<I: IntoIterator<Item = (K, V)>>(key_values: I) -> Self {
let mut map = Self::new();
map.extend(key_values);
map
}
}
impl<'a, K: Eq + Borrow<Q>, V, Q: ?Sized + Eq> ops::Index<&'a Q> for LinearMap<K, V> {
type Output = V;
#[inline]
fn index(&self, key: &'a Q) -> &V {
self.get(key).expect("key not found")
}
}
impl<K: Eq, V: PartialEq> PartialEq for LinearMap<K, V> {
fn eq(&self, other: &Self) -> bool {
if self.len() != other.len() {
return false;
}
for (key, value) in self {
if other.get(key) != Some(value) {
return false;
}
}
true
}
}
impl<K: Eq, V: Eq> Eq for LinearMap<K, V> {}
impl<K, V> PartialOrd for LinearMap<K, V>
where
K: Eq + Ord,
V: Ord,
{
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<K, V> Ord for LinearMap<K, V>
where
K: Eq + Ord,
V: Ord,
{
fn cmp(&self, other: &Self) -> Ordering {
match self.len().cmp(&other.len()) {
Ordering::Less => return Ordering::Less,
Ordering::Greater => return Ordering::Greater,
Ordering::Equal => (),
}
let mut self_seq = self.storage.iter().collect::<Vec<_>>();
self_seq.sort_unstable_by_key(|(k, _v)| k); let mut other_seq = other.storage.iter().collect::<Vec<_>>();
other_seq.sort_unstable_by_key(|(k, _v)| k);
self_seq.into_iter().cmp(other_seq)
}
}
impl<K, V> Hash for LinearMap<K, V>
where
K: Hash,
V: Hash,
{
fn hash<H: Hasher>(&self, state: &mut H) {
let mut hash = 0u64;
for elt in self.storage.iter() {
let elt_hash = crate::hash_one_fixed(elt);
hash ^= elt_hash;
}
state.write_u64(hash);
}
}
impl<K: Eq, V> From<LinearMap<K, V>> for Vec<(K, V)> {
#[inline]
fn from(other: LinearMap<K, V>) -> Self {
other.storage
}
}
impl<K: Eq, V> From<Vec<(K, V)>> for LinearMap<K, V> {
#[inline]
fn from(other: Vec<(K, V)>) -> Self {
other.into_iter().collect()
}
}
impl<K: Eq + Clone, V: Clone, const N: usize> From<[(K, V); N]> for LinearMap<K, V> {
#[inline]
fn from(arr: [(K, V); N]) -> Self {
Self::from(arr.to_vec())
}
}
#[allow(missing_debug_implementations)]
pub struct OccupiedEntry<'a, K, V> {
map: &'a mut LinearMap<K, V>,
index: usize,
}
#[allow(missing_debug_implementations)]
pub struct VacantEntry<'a, K, V> {
map: &'a mut LinearMap<K, V>,
key: K,
}
#[allow(missing_debug_implementations)]
pub enum Entry<'a, K, V> {
Occupied(OccupiedEntry<'a, K, V>),
Vacant(VacantEntry<'a, K, V>),
}
impl<'a, K, V> Entry<'a, K, V> {
#[inline]
pub fn or_insert(self, default: V) -> &'a mut V {
match self {
Occupied(entry) => entry.into_mut(),
Vacant(entry) => entry.insert(default),
}
}
#[inline]
pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
match self {
Occupied(entry) => entry.into_mut(),
Vacant(entry) => entry.insert(default()),
}
}
#[inline]
pub fn and_modify<F>(self, f: F) -> Self
where
F: FnOnce(&mut V),
{
match self {
Occupied(mut entry) => {
f(entry.get_mut());
Occupied(entry)
}
Vacant(entry) => Vacant(entry),
}
}
}
impl<'a, K, V> OccupiedEntry<'a, K, V> {
#[inline]
pub fn get(&self) -> &V {
&self.map.storage[self.index].1
}
#[inline]
pub fn get_mut(&mut self) -> &mut V {
&mut self.map.storage[self.index].1
}
#[inline]
pub fn into_mut(self) -> &'a mut V {
&mut self.map.storage[self.index].1
}
#[inline]
pub fn insert(&mut self, value: V) -> V {
mem::replace(self.get_mut(), value)
}
#[inline]
pub fn remove(self) -> V {
self.map.storage.swap_remove(self.index).1
}
#[inline]
pub fn shift_remove(self) -> V {
self.map.storage.remove(self.index).1
}
}
impl<'a, K, V: Default> Entry<'a, K, V> {
#[inline]
pub fn or_default(self) -> &'a mut V {
match self {
Self::Occupied(e) => e.into_mut(),
Self::Vacant(e) => e.insert(V::default()),
}
}
}
impl<'a, K, V> VacantEntry<'a, K, V> {
#[inline]
pub fn insert(self, value: V) -> &'a mut V {
self.map.storage.push((self.key, value));
&mut self.map.storage.last_mut().unwrap().1
}
}
#[allow(missing_debug_implementations)]
pub struct IntoIter<K, V> {
iter: vec::IntoIter<(K, V)>,
}
impl<K, V> Iterator for IntoIter<K, V> {
type Item = (K, V);
#[inline]
fn next(&mut self) -> Option<(K, V)> {
self.iter.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
#[inline]
fn next_back(&mut self) -> Option<(K, V)> {
self.iter.next_back()
}
}
impl<K, V> ExactSizeIterator for IntoIter<K, V> {
#[inline]
fn len(&self) -> usize {
self.iter.len()
}
}
#[allow(missing_debug_implementations)]
pub struct Drain<'a, K, V> {
iter: vec::Drain<'a, (K, V)>,
}
#[allow(missing_debug_implementations)]
pub struct Iter<'a, K, V> {
iter: slice::Iter<'a, (K, V)>,
}
#[allow(missing_debug_implementations)]
pub struct IterMut<'a, K, V> {
iter: slice::IterMut<'a, (K, V)>,
}
#[allow(missing_debug_implementations)]
pub struct IterFullUncheckedMut<'a, K, V> {
iter: slice::IterMut<'a, (K, V)>,
}
#[allow(missing_debug_implementations)]
pub struct Keys<'a, K, V> {
iter: Iter<'a, K, V>,
}
#[allow(missing_debug_implementations)]
pub struct Values<'a, K, V> {
iter: Iter<'a, K, V>,
}
#[allow(missing_debug_implementations)]
pub struct ValuesMut<'a, K, V> {
iter: slice::IterMut<'a, (K, V)>,
}
macro_rules! impl_iter {
($typ:ty, $item:ty, $map:expr) => {
impl<'a, K, V> Iterator for $typ {
type Item = $item;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map($map)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<'a, K, V> DoubleEndedIterator for $typ {
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
self.iter.next_back().map($map)
}
}
impl<'a, K, V> ExactSizeIterator for $typ {
#[inline]
fn len(&self) -> usize {
self.iter.len()
}
}
};
}
impl_iter! {Drain<'a,K,V>, (K,V), |e| e }
impl_iter! {Iter<'a,K,V>, (&'a K, &'a V), |e| (&e.0, &e.1) }
impl_iter! {IterMut<'a,K,V>, (&'a K, &'a mut V), |e| (&e.0, &mut e.1) }
impl_iter! {IterFullUncheckedMut<'a,K,V>, (&'a mut K, &'a mut V), |e| (&mut e.0, &mut e.1) }
impl_iter! {Keys<'a,K,V>, &'a K, |e| e.0 }
impl_iter! {Values<'a,K,V>, &'a V, |e| e.1 }
impl_iter! {ValuesMut<'a,K,V>, &'a mut V, |e| &mut e.1 }
impl<K, V> Clone for Iter<'_, K, V> {
fn clone(&self) -> Self {
Iter {
iter: self.iter.clone(),
}
}
}
impl<K, V> Clone for Keys<'_, K, V> {
#[inline]
fn clone(&self) -> Self {
Keys {
iter: self.iter.clone(),
}
}
}
impl<K, V> Clone for Values<'_, K, V> {
#[inline]
fn clone(&self) -> Self {
Values {
iter: self.iter.clone(),
}
}
}
impl<K: Eq, V> IntoIterator for LinearMap<K, V> {
type Item = (K, V);
type IntoIter = IntoIter<K, V>;
#[inline]
fn into_iter(self) -> IntoIter<K, V> {
IntoIter {
iter: self.storage.into_iter(),
}
}
}
impl<'a, K: Eq, V> IntoIterator for &'a LinearMap<K, V> {
type Item = (&'a K, &'a V);
type IntoIter = Iter<'a, K, V>;
#[inline]
fn into_iter(self) -> Iter<'a, K, V> {
self.iter()
}
}
impl<'a, K: Eq, V> IntoIterator for &'a mut LinearMap<K, V> {
type Item = (&'a K, &'a mut V);
type IntoIter = IterMut<'a, K, V>;
#[inline]
fn into_iter(self) -> IterMut<'a, K, V> {
self.iter_mut()
}
}
#[allow(dead_code)]
fn assert_covariance() {
fn a<'a, K, V>(x: LinearMap<&'static K, &'static V>) -> LinearMap<&'a K, &'a V> {
x
}
fn b<'a, K, V>(x: IntoIter<&'static K, &'static V>) -> IntoIter<&'a K, &'a V> {
x
}
fn c<'i, 'a, K, V>(x: Iter<'i, &'static K, &'static V>) -> Iter<'i, &'a K, &'a V> {
x
}
fn d<'i, 'a, K, V>(x: Keys<'i, &'static K, &'static V>) -> Keys<'i, &'a K, &'a V> {
x
}
fn e<'i, 'a, K, V>(x: Values<'i, &'static K, &'static V>) -> Values<'i, &'a K, &'a V> {
x
}
}
#[cfg(feature = "serde")]
pub mod serde_as_map {
use super::*;
#[inline]
pub fn serialize<K, V, S>(map: &LinearMap<K, V>, serializer: S) -> Result<S::Ok, S::Error>
where
K: serde::Serialize + Hash + Eq,
V: serde::Serialize,
S: serde::Serializer,
{
use serde::ser::SerializeMap;
let mut ser_map = serializer.serialize_map(Some(map.len()))?;
for (k, v) in map {
ser_map.serialize_entry(k, v)?;
}
ser_map.end()
}
#[inline]
pub fn deserialize<'de, K, V, D>(deserializer: D) -> Result<LinearMap<K, V>, D::Error>
where
K: serde::Deserialize<'de> + Eq,
V: serde::Deserialize<'de>,
D: serde::Deserializer<'de>,
{
use core::marker::PhantomData;
use serde::de::MapAccess;
use serde::de::Visitor;
struct LinearMapVisitor<K, V>(PhantomData<(K, V)>);
impl<'de, K, V> Visitor<'de> for LinearMapVisitor<K, V>
where
K: serde::Deserialize<'de> + Eq,
V: serde::Deserialize<'de>,
{
type Value = LinearMap<K, V>;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("a map of (k, v) pairs")
}
fn visit_map<A>(self, mut access: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut map = LinearMap::with_capacity(access.size_hint().unwrap_or(0));
while let Some((k, v)) = access.next_entry::<K, V>()? {
map.insert(k, v);
}
Ok(map)
}
}
deserializer.deserialize_map(LinearMapVisitor::<K, V>(PhantomData))
}
}
#[cfg(feature = "serde")]
impl<K, V> serde::Serialize for LinearMap<K, V>
where
K: serde::Serialize + Eq,
V: serde::Serialize,
{
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.storage.serialize(serializer)
}
}
#[cfg(feature = "serde")]
impl<'de, K, V> serde::Deserialize<'de> for LinearMap<K, V>
where
K: serde::Deserialize<'de> + Eq,
V: serde::Deserialize<'de>,
{
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let storage = Vec::<(K, V)>::deserialize(deserializer)?;
Ok(Self { storage })
}
}
#[cfg(feature = "speedy")]
impl<'a, C, K, V> speedy::Readable<'a, C> for LinearMap<K, V>
where
C: speedy::Context,
K: speedy::Readable<'a, C>,
V: speedy::Readable<'a, C>,
{
#[inline]
fn read_from<R: speedy::Reader<'a, C>>(reader: &mut R) -> Result<Self, C::Error> {
let storage = Vec::<(K, V)>::read_from(reader)?;
Ok(Self { storage })
}
#[inline]
fn minimum_bytes_needed() -> usize {
Vec::<(K, V)>::minimum_bytes_needed()
}
}
#[cfg(feature = "speedy")]
impl<C, K, V> speedy::Writable<C> for LinearMap<K, V>
where
C: speedy::Context,
K: speedy::Writable<C>,
V: speedy::Writable<C>,
{
#[inline]
fn write_to<T: ?Sized + speedy::Writer<C>>(
&self,
writer: &mut T,
) -> Result<(), <C as speedy::Context>::Error> {
self.storage.write_to(writer)
}
#[inline]
fn bytes_needed(&self) -> Result<usize, <C as speedy::Context>::Error> {
self.storage.bytes_needed()
}
}