pub struct LinearMap<K, V>(/* private fields */);
Expand description
A linear key-value map backed by a Vec
.
This map performs O(n) lookups and inserts.
It is suitable only for small sets of keys which
must implement Eq
.
Internally stores key-value pairs in insertion order. Duplicate key inserts overwrite the previous value.
§Performance
Avoid using this for more than a few keys. All core operations are linear.
Implementations§
Source§impl<K: Eq, V> LinearMap<K, V>
impl<K: Eq, V> LinearMap<K, V>
Sourcepub fn with_capacity(capacity: usize) -> Self
pub fn with_capacity(capacity: usize) -> Self
Creates a new empty LinearMap
with a pre-allocated capacity.
Sourcepub fn get(&self, k: &K) -> Option<&V>
pub fn get(&self, k: &K) -> Option<&V>
Gets a reference to the value associated with the key, if it exists.
Returns Some(&V)
if found, or None
if not present.
This is an O(n) operation.
Sourcepub fn get_mut(&mut self, k: &K) -> Option<&mut V>
pub fn get_mut(&mut self, k: &K) -> Option<&mut V>
Gets a mutable reference to the value associated with the key, if it exists.
Returns Some(&mut V)
if found, or None
otherwise.
This is an O(n) operation.
Sourcepub fn insert(&mut self, k: K, v: V) -> Option<V>
pub fn insert(&mut self, k: K, v: V) -> Option<V>
Inserts a key-value pair into the map.
If the key exists, swaps the old value with the new one and returns the old value.
Otherwise, appends the new pair and returns None
.
This is an O(n) operation due to the linear search.
Sourcepub fn get_or_insert_with(&mut self, k: K, f: impl FnOnce() -> V) -> &mut V
pub fn get_or_insert_with(&mut self, k: K, f: impl FnOnce() -> V) -> &mut V
Returns a mutable reference to the value for the given key.
If the key exists, returns a mutable reference to the value. Otherwise, inserts a new value created by the provided closure and returns a reference to it.
This is an O(n) operation due to the key search.
Sourcepub fn values(&self) -> impl Iterator<Item = &V>
pub fn values(&self) -> impl Iterator<Item = &V>
Returns an iterator over the values in the map.
Values are yielded in insertion order.
Trait Implementations§
Source§impl<K: Eq, V> FromIterator<(K, V)> for LinearMap<K, V>
impl<K: Eq, V> FromIterator<(K, V)> for LinearMap<K, V>
Source§fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self
Builds a LinearMap
from an iterator of key-value pairs.
Later duplicates overwrite earlier entries.
This calls insert
in a loop, so is O(n^2)!!