use hashbrown::HashMap; /// A set that automatically assigns a unique ID to every entry. /// /// # How unique? /// /// If you inserted a new entry every nanosecond, it would take more than /// 550_000 years to run out of indices. Realistically Orchid might insert a new /// entry every 10ms, so these 64-bit indices will probably outlast humanity. #[derive(Clone, Debug)] pub struct IdMap { next_id: u64, data: HashMap, } impl IdMap { /// Create a new empty set pub fn new() -> Self { Self { next_id: 0, data: HashMap::new() } } /// Insert an element with a new ID and return the ID pub fn insert(&mut self, t: T) -> u64 { let id = self.next_id; self.next_id += 1; (self.data.try_insert(id, t)).unwrap_or_else(|_| panic!("IdMap keys should be unique")); id } /// Remove the element with the given ID from the set. The ID will not be /// reused. pub fn remove(&mut self, id: u64) -> Option { self.data.remove(&id) } } impl Default for IdMap { fn default() -> Self { Self::new() } } #[cfg(test)] mod test { use super::IdMap; #[test] fn basic_test() { let mut map = IdMap::new(); let a = map.insert(1); let b = map.insert(2); assert_eq!(map.remove(a), Some(1)); assert_eq!(map.remove(a), None); assert_eq!(map.data.get(&b), Some(&2)); } }