MiniSet/MiniMap moved and renamed into SsoHashSet/SsoHashMap

It is a more descriptive name and with upcoming changes
there will be nothing "mini" about them.
This commit is contained in:
Valerii Lashmanov
2020-09-23 23:32:11 -05:00
parent 6f9a8a7f9b
commit 5c224a484d
10 changed files with 45 additions and 41 deletions

View File

@@ -0,0 +1,61 @@
use crate::fx::FxHashMap;
use arrayvec::ArrayVec;
use std::hash::Hash;
/// Small-storage-optimized implementation of a map
/// made specifically for caching results.
///
/// Stores elements in a small array up to a certain length
/// and switches to `HashMap` when that length is exceeded.
pub enum SsoHashMap<K, V> {
Array(ArrayVec<[(K, V); 8]>),
Map(FxHashMap<K, V>),
}
impl<K: Eq + Hash, V> SsoHashMap<K, V> {
/// Creates an empty `SsoHashMap`.
pub fn new() -> Self {
SsoHashMap::Array(ArrayVec::new())
}
/// Inserts or updates value in the map.
pub fn insert(&mut self, key: K, value: V) {
match self {
SsoHashMap::Array(array) => {
for pair in array.iter_mut() {
if pair.0 == key {
pair.1 = value;
return;
}
}
if let Err(error) = array.try_push((key, value)) {
let mut map: FxHashMap<K, V> = array.drain(..).collect();
let (key, value) = error.element();
map.insert(key, value);
*self = SsoHashMap::Map(map);
}
}
SsoHashMap::Map(map) => {
map.insert(key, value);
}
}
}
/// Return value by key if any.
pub fn get(&self, key: &K) -> Option<&V> {
match self {
SsoHashMap::Array(array) => {
for pair in array {
if pair.0 == *key {
return Some(&pair.1);
}
}
return None;
}
SsoHashMap::Map(map) => {
return map.get(key);
}
}
}
}