Skip to content

Commit 56213c1

Browse files
Implementation of Map for simple Vec<(_, _)>
Note it uses `swap_remove`.
1 parent 4b5d32d commit 56213c1

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

src/generic_containers.rs

+32
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
#![cfg(feature = "use_alloc")]
55

66
use alloc::collections::BTreeMap;
7+
use alloc::vec::Vec;
78
#[cfg(feature = "use_std")]
89
use core::hash::{BuildHasher, Hash};
910
#[cfg(feature = "use_std")]
@@ -60,3 +61,34 @@ where
6061
self.entry(key).or_default()
6162
}
6263
}
64+
65+
impl<K, V> Map for Vec<(K, V)>
66+
where
67+
K: Eq,
68+
{
69+
type Key = K;
70+
type Value = V;
71+
fn insert(&mut self, key: K, value: V) -> Option<V> {
72+
match self.iter_mut().find(|(k, _)| k == &key) {
73+
Some((_, v)) => Some(core::mem::replace(v, value)),
74+
None => {
75+
self.push((key, value));
76+
None
77+
}
78+
}
79+
}
80+
fn remove(&mut self, key: &K) -> Option<V> {
81+
let index = self.iter().position(|(k, _)| k == key)?;
82+
Some(self.swap_remove(index).1)
83+
}
84+
fn entry_or_default(&mut self, key: K) -> &mut V
85+
where
86+
V: Default,
87+
{
88+
let index = self.iter().position(|(k, _)| k == &key).unwrap_or_else(|| {
89+
self.push((key, V::default()));
90+
self.len() - 1
91+
});
92+
&mut self[index].1
93+
}
94+
}

0 commit comments

Comments
 (0)