|
| 1 | +#![deny(clippy::all)] |
| 2 | + |
| 3 | +use std::sync::OnceLock; |
| 4 | + |
| 5 | +/// An error indicating that the key wasn't given to the constructor. |
| 6 | +#[derive(Debug)] |
| 7 | +pub struct UnknownKey; |
| 8 | + |
| 9 | +/// A FixedMap is created with every key known at the start and cannot have |
| 10 | +/// value removed or written over. |
| 11 | +#[derive(Debug)] |
| 12 | +pub struct FixedMap<K, V> { |
| 13 | + inner: Vec<(K, OnceLock<V>)>, |
| 14 | +} |
| 15 | + |
| 16 | +impl<K: Ord, V> FixedMap<K, V> { |
| 17 | + pub fn new(keys: impl Iterator<Item = K>) -> Self { |
| 18 | + let mut inner = keys.map(|key| (key, OnceLock::new())).collect::<Vec<_>>(); |
| 19 | + inner.sort_by(|(k1, _), (k2, _)| k1.cmp(k2)); |
| 20 | + Self { inner } |
| 21 | + } |
| 22 | + |
| 23 | + /// Get a value for a key. |
| 24 | + /// |
| 25 | + /// Returns `None` if key hasn't had a value inserted yet. |
| 26 | + pub fn get(&self, key: &K) -> Result<Option<&V>, UnknownKey> { |
| 27 | + let item_index = self |
| 28 | + .inner |
| 29 | + .binary_search_by(|(k, _)| k.cmp(key)) |
| 30 | + .map_err(|_| UnknownKey)?; |
| 31 | + let (_, value) = &self.inner[item_index]; |
| 32 | + Ok(value.get()) |
| 33 | + } |
| 34 | + |
| 35 | + /// Insert a value for a key. |
| 36 | + /// |
| 37 | + /// There is no guarentee that the provided value will be the one returned. |
| 38 | + pub fn insert(&self, key: &K, value: V) -> Result<&V, UnknownKey> { |
| 39 | + let item_index = self |
| 40 | + .inner |
| 41 | + .binary_search_by(|(k, _)| k.cmp(key)) |
| 42 | + .map_err(|_| UnknownKey)?; |
| 43 | + let (_, value_slot) = &self.inner[item_index]; |
| 44 | + // We do not care about if this set was successful or if another call won out. |
| 45 | + // The end result is that we have a value for the key. |
| 46 | + let _ = value_slot.set(value); |
| 47 | + Ok(value_slot |
| 48 | + .get() |
| 49 | + .expect("OnceLock::set will always result in a value being present in the lock")) |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +impl<K: Clone, V: Clone> Clone for FixedMap<K, V> { |
| 54 | + fn clone(&self) -> Self { |
| 55 | + Self { |
| 56 | + inner: self.inner.clone(), |
| 57 | + } |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +impl<K: Ord, V> FromIterator<(K, Option<V>)> for FixedMap<K, V> { |
| 62 | + fn from_iter<T: IntoIterator<Item = (K, Option<V>)>>(iter: T) -> Self { |
| 63 | + let mut inner = iter |
| 64 | + .into_iter() |
| 65 | + .map(|(key, value)| { |
| 66 | + let value_slot = OnceLock::new(); |
| 67 | + if let Some(value) = value { |
| 68 | + value_slot |
| 69 | + .set(value) |
| 70 | + .map_err(|_| ()) |
| 71 | + .expect("nobody else has access to this lock yet"); |
| 72 | + } |
| 73 | + (key, value_slot) |
| 74 | + }) |
| 75 | + .collect::<Vec<_>>(); |
| 76 | + inner.sort_by(|(k1, _), (k2, _)| k1.cmp(k2)); |
| 77 | + Self { inner } |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +#[cfg(test)] |
| 82 | +mod test { |
| 83 | + use super::*; |
| 84 | + |
| 85 | + #[test] |
| 86 | + fn test_get() { |
| 87 | + let map: FixedMap<i32, ()> = FixedMap::new([3, 2, 1].iter().copied()); |
| 88 | + assert_eq!(map.get(&2).unwrap(), None); |
| 89 | + assert!(map.get(&4).is_err()); |
| 90 | + } |
| 91 | + |
| 92 | + #[test] |
| 93 | + fn test_set() { |
| 94 | + let map: FixedMap<i32, bool> = FixedMap::new([3, 2, 1].iter().copied()); |
| 95 | + assert!(map.insert(&4, true).is_err()); |
| 96 | + assert_eq!(map.insert(&2, true).unwrap(), &true); |
| 97 | + assert_eq!(map.insert(&2, false).unwrap(), &true); |
| 98 | + } |
| 99 | + |
| 100 | + #[test] |
| 101 | + fn test_contention() { |
| 102 | + let map: FixedMap<i32, bool> = FixedMap::new([3, 2, 1].iter().copied()); |
| 103 | + let results: Vec<_> = std::thread::scope(|scope| { |
| 104 | + let mut handles = vec![]; |
| 105 | + let map = ↦ |
| 106 | + for i in 0..16 { |
| 107 | + let is_even = i % 2 == 0; |
| 108 | + handles.push(scope.spawn(move || { |
| 109 | + let val = map.insert(&1, is_even).unwrap(); |
| 110 | + (val, *val) |
| 111 | + })); |
| 112 | + } |
| 113 | + handles.into_iter().map(|h| h.join().unwrap()).collect() |
| 114 | + }); |
| 115 | + |
| 116 | + for (val_ref, val) in results { |
| 117 | + assert_eq!(*val_ref, val, "all values should remain the same"); |
| 118 | + } |
| 119 | + } |
| 120 | +} |
0 commit comments