made no_alloc map (untested)

This commit is contained in:
Andy Killorin 2024-12-05 16:38:54 -05:00
parent a8973025d5
commit 6aca7422eb
Signed by: ank
GPG key ID: 23F9463ECB67FE8C

58
outside/src/arraymap.rs Normal file
View file

@ -0,0 +1,58 @@
/// no_std, no_alloc map
pub struct ArrayMap<const N: usize, K,V> {
keys: [Option<K>; N],
values: [Option<V>; N],
index: usize,
}
impl<const N: usize, K, V> ArrayMap<N, K, V> where K: Eq {
pub fn new() -> Self {
Self { keys: [const { None };N], values: [const { None };N], index: 0 }
}
pub fn insert(&mut self, key: K, value: V) {
match self.keys[..self.index].iter().enumerate()
.find(|k| k.1.as_ref().is_some_and(|v| *v == key)) {
Some((index, _)) => {
self.keys[index] = Some(key);
self.values[index] = Some(value);
},
None => {
self.keys[self.index] = Some(key);
self.values[self.index] = Some(value);
self.index += 1;
if self.index > N {
self.index = 0;
log::error!("arraymap is full, overwriting");
}
},
}
}
pub fn get(&self, key: K) -> Option<&V> {
match self.keys[..self.index].iter().enumerate()
.find(|k| k.1.as_ref().is_some_and(|v| *v == key)) {
Some((index, _)) => {
self.values[index].as_ref()
},
None => {
None
},
}
}
}
#[cfg(test)]
mod test {
use super::ArrayMap;
fn get() {
let mut map: ArrayMap<2, i32, &str> = ArrayMap::new();
map.insert(3, "fogey");
map.insert(4, "bogey");
assert_eq!(map.get(3), Some(&"fogey"));
assert_eq!(map.get(5), None);
}
}