pub struct NumberKeyMap<V> { /* private fields */ }Expand description
A small, specialized hash map keyed by usize values.
It is optimized for zero-misses and so optimized for 99+% reading operations.
It is optimized for integer keys and expects an external invariant
that usize::MAX marks vacant slots.
§Example
use std::sync::{Mutex, RwLock};
use orengine_utils::NumberKeyMap;
static POOLS: RwLock<NumberKeyMap<Mutex<Vec<Box<[u8]>>>>> = RwLock::new(NumberKeyMap::new());
fn acquire_from_pool(size: usize) -> Box<[u8]> {
if let Some(v) = POOLS.read().unwrap().get(size) {
v.lock().unwrap().pop().unwrap_or_else(|| vec![0; size].into_boxed_slice())
} else {
vec![0; size].into_boxed_slice()
}
}
fn put_to_pool(buf: Box<[u8]>) {
let read_pool = POOLS.read().unwrap();
if let Some(v) = read_pool.get(buf.len()) {
v.lock().unwrap().push(buf);
return;
}
drop(read_pool);
let mut write_pool = POOLS.write().unwrap();
let res = write_pool.insert(buf.len(), Mutex::new(vec![buf]));
if let Err(mut v) = res {
let buf = v.get_mut().unwrap().pop().unwrap();
write_pool.get(buf.len()).unwrap().lock().unwrap().push(buf);
}
}Implementations§
Source§impl<V> NumberKeyMap<V>
impl<V> NumberKeyMap<V>
Sourcepub fn get(&self, key: usize) -> Option<&V>
pub fn get(&self, key: usize) -> Option<&V>
Retrieve a reference to a value stored under key, if present.
If the slot is occupied and contains the requested key, a reference to the value is returned.
§Panics
This function panics if key is equal to usize::MAX.
Sourcepub fn get_mut(&mut self, key: usize) -> Option<&mut V>
pub fn get_mut(&mut self, key: usize) -> Option<&mut V>
Retrieve a mutable reference to a value stored under key, if present.
If the slot is occupied and contains the requested key, a reference to the value is returned.
§Panics
This function panics if key is equal to usize::MAX.
Sourcepub fn remove(&mut self, key: usize) -> Option<V>
pub fn remove(&mut self, key: usize) -> Option<V>
Removes an item from the map and returns it if it exists.
§Panics
This function panics if key is equal to usize::MAX
Sourcepub fn clear_with(&mut self, func: impl Fn((usize, V)))
pub fn clear_with(&mut self, func: impl Fn((usize, V)))
Clears the NumberKeyMap with the provided function.
Sourcepub fn clear(&mut self)
pub fn clear(&mut self)
Clears the NumberKeyMap.