Deep-Dive System Documentation
Standard Collections: Heap Containers
To hold dynamic sequences or keyed maps, Rust utilizes Vec and HashMap.
1. Vector (Vec<T>)
A contiguous, dynamically growable array allocated on the heap.
- Stack Overhead: 24 bytes (pointer to heap array, capacity size, current length).
- Performance: Direct array indexing is $O(1)$. Reallocates/doubles capacity when out of bounds.
let mut key_list = vec![0x41, 0x42];
key_list.push(0x43); // Contiguous growth
2. Hash Map (HashMap<K, V>)
A collection storing key-value associations.
- Hashing Security: By default, Rust's
HashMapuses SipHash 1-3 to prevent Hash DoS (Denial of Service) attacks. - Performance: Fast average insertions and lookups.
use std::collections::HashMap;
let mut shortcut_registry = HashMap::new();
shortcut_registry.insert(0x41, "TriggerActionA");
Optimization Trick
If the collection sizes are known in advance, initialize them using with_capacity() to skip multiple dynamic heap reallocations.
Useful Methods: Vec
.push(&mut self, value: T)
Appends an element to the back of the vector, dynamically allocating more heap space if required.
let mut v = vec![1, 2];
v.push(3);
assert_eq!(v, [1, 2, 3]);
.pop(&mut self) -> Option<T>
Removes the last element from a vector and returns it, or None if it is empty.
let mut v = vec![1, 2];
assert_eq!(v.pop(), Some(2));
assert_eq!(v.pop(), Some(1));
assert_eq!(v.pop(), None);
.insert(&mut self, index: usize, element: T)
Inserts an element at position index within the vector, shifting all elements after it to the right. $O(n)$ operation.
let mut v = vec![1, 3];
v.insert(1, 2);
assert_eq!(v, [1, 2, 3]);
Useful Methods: HashMap<K, V>
.insert(&mut self, k: K, v: V) -> Option<V>
Inserts a key-value pair into the map. If the map did not have this key present, None is returned. If it did, the value is updated and the old value is returned.
use std::collections::HashMap;
let mut map = HashMap::new();
assert_eq!(map.insert("a", 1), None);
assert_eq!(map.insert("a", 2), Some(1));
.get(&self, k: &Q) -> Option<&V>
Returns a reference to the value corresponding to the key.
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
assert_eq!(map.get("a"), Some(&1));
assert_eq!(map.get("b"), None);
.remove(&mut self, k: &Q) -> Option<V>
Removes a key from the map, returning the value at the key if the key was previously in the map.
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
assert_eq!(map.remove("a"), Some(1));
assert_eq!(map.remove("a"), None);
.entry(&mut self, key: K) -> Entry<'_, K, V>
Gets the corresponding entry in the map for in-place manipulation. Perfect for counting or updating map values efficiently.
use std::collections::HashMap;
let mut counts = HashMap::new();
counts.entry("words").and_modify(|e| *e += 1).or_insert(1);
assert_eq!(counts.get("words"), Some(&1));
Quick Reference Guide
let mut v = Vec::new();
v.push(1);
let mut m = HashMap::new();
m.insert("key", 1);