diff --git a/.idea/Rust-Programming.iml b/.idea/Rust-Programming.iml index 4779fc9..7a15b19 100644 --- a/.idea/Rust-Programming.iml +++ b/.idea/Rust-Programming.iml @@ -6,9 +6,11 @@ + + diff --git a/container_type/src/main.rs b/container_type/src/main.rs index 9f416ad..8d171ea 100644 --- a/container_type/src/main.rs +++ b/container_type/src/main.rs @@ -17,15 +17,35 @@ use std::{vec::{IntoIter}, ops::Index, ops::IndexMut, println}; * Copyright (c) Sven Vogel */ +/// A vector based implementation of an associative map. +/// This strucutre maps a given key to a single value. +/// The type achives this by storing every pair of key/value pairs +/// in a single vector. +/// Thus for looking up a value takes a linear amount of time: O(n) in the worst case. +/// Adding a new value is a constant time operation since the map is not sorted in any +/// particular way. +/// Note that it is not possible to insert a new value with the same key. Instead the old value +/// associated with the already existing key will be replaced with the new value. +/// # Example +/// ```rust ignore +/// let mut map = HashishMap::new(); +/// +/// map.insert("abc", 99); +/// +/// map[&"abc"] += 1; +/// ``` pub struct HashishMap where K: Eq { vec: Vec<(K, V)> } impl HashishMap where K: Eq { + /// Create a new empty instance pub fn new() -> Self { Self { vec: vec![] } } + /// retrieve a reference to value associated with the specified key + /// if no such key exists in the map [`Option::None`] is returned pub fn get(&self, key: &K) -> Option<&V> { return match self.vec.iter().find(|(k, _)| *k == *key) { Some((_, v)) => Some(v), @@ -33,6 +53,8 @@ impl HashishMap where K: Eq { } } + /// retrieve a mutable reference to value associated with the specified key + /// if no such key exists in the map [`Option::None`] is returned pub fn get_mut(&mut self, key: &K) -> Option<&mut V> { return match self.vec.iter_mut().find(|(k, _)| *k == *key) { Some((_, v)) => Some(v), @@ -40,6 +62,9 @@ impl HashishMap where K: Eq { } } + /// insert a new value at the specified key. + /// Overrides the existing value if the key already exists. + /// The overriden value is discarded. pub fn insert(&mut self, key: K, value: V) { if let Some(val) = self.get_mut(&key) { *val = value; @@ -48,6 +73,8 @@ impl HashishMap where K: Eq { } } + /// Removes the key/value pair with the specified key from the map and return the value of the pair. + /// If no such pair can be found, [`Option::None`] is retuned pub fn remove(&mut self, key: &K) -> Option { // find a key matching the parameter and its according index. // remove the item at the found index from the vector and return its value @@ -68,7 +95,6 @@ impl Index for HashishMap where K: Eq { } } - impl IndexMut for HashishMap where K: Eq { fn index_mut(&mut self, index: K) -> &mut Self::Output { @@ -101,5 +127,4 @@ fn main() { for (k, v) in guter_stoff { println!("({k}, {:x})", v); } - } \ No newline at end of file