1use core::fmt;
5use std::collections::HashMap;
6use std::marker::PhantomData;
7use std::ops::{Index, IndexMut};
8use serde::{Deserialize, Serialize};
9
10pub trait Id: Copy + Clone + Eq + PartialEq + fmt::Debug + Into<u64> + From<u64> {
13 fn as_u64(&self) -> u64 {
15 (*self).into()
16 }
17
18 fn from_u64(val: u64) -> Self {
20 Self::from(val)
21 }
22}
23
24
25#[macro_export]
28macro_rules! new_id_type {
29 () => {};
31
32 (
34 $(#[$meta:meta])*
35 $vis:vis struct $name:ident;
36 $($rest:tt)*
37 ) => {
38 $(#[$meta])*
40 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41 $vis struct $name(pub u64);
42
43 impl From<u64> for $name {
44 #[inline]
45 fn from(val: u64) -> Self {
46 Self(val)
47 }
48 }
49
50 impl From<$name> for u64 {
51 #[inline]
52 fn from(id: $name) -> Self {
53 id.0
54 }
55 }
56
57 impl $crate::Id for $name {}
58
59 impl serde::Serialize for $name {
60 #[inline]
61 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
62 where
63 S: serde::Serializer,
64 {
65 self.0.serialize(serializer)
66 }
67 }
68
69 impl<'de> serde::Deserialize<'de> for $name {
70 #[inline]
71 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
72 where
73 D: serde::Deserializer<'de>,
74 {
75 let val = u64::deserialize(deserializer)?;
76 Ok(Self(val))
77 }
78 }
79
80 $crate::new_id_type!($($rest)*);
81 };
82}
83
84new_id_type!{
85 pub struct DefaultId;
86}
87
88
89#[derive(Debug, Clone)]
92#[derive(Serialize, Deserialize)]
93pub struct IdMap<K: Id, V> {
94 pub(crate) inner: HashMap<u64, V>, #[serde(skip)]
96 max_id: u64, #[serde(skip)]
98 _marker: PhantomData<K>,
99}
100
101impl<V> IdMap<DefaultId, V> {
102 pub fn new() -> Self { Self::with_id_capacity(0) }
104
105 pub fn with_capacity(capacity: usize) -> Self { Self::with_id_capacity(capacity) }
107}
108
109impl<K: Id, V> IdMap<K, V> {
110 pub fn with_id() -> Self {
112 Self {
113 inner: HashMap::new(),
114 max_id: 0,
115 _marker: PhantomData,
116 }
117 }
118
119 pub fn with_id_capacity(capacity: usize) -> Self {
121 Self {
122 inner: HashMap::with_capacity(capacity),
123 max_id: 0,
124 _marker: PhantomData,
125 }
126 }
127
128 pub fn insert(&mut self, value: V) -> K {
130 self.max_id += 1; let id_u64 = self.max_id;
132 self.inner.insert(id_u64, value); K::from_u64(id_u64) }
135
136
137 pub fn insert_with_id(&mut self, id: K, value: V) -> Option<V> {
141 let id_u64 = id.as_u64();
142 if id_u64 > self.max_id {
144 self.max_id = id_u64;
145 }
146 self.inner.insert(id_u64, value)
147 }
148
149 pub fn from_vec(values: Vec<V>) -> (Self, Vec<K>) {
152 let mut map = Self {
153 inner: HashMap::with_capacity(values.len()),
154 max_id: 0,
155 _marker: PhantomData,
156 };
157 let ids = values
158 .into_iter()
159 .map(|val| {
160 map.max_id += 1;
161 let id_u64 = map.max_id;
162 map.inner.insert(id_u64, val);
163 K::from_u64(id_u64)
164 })
165 .collect();
166 (map, ids)
167 }
168
169 pub fn insert_cyclic<F>(&mut self, f: F) -> K
172 where
173 F: FnOnce(K) -> V,
174 {
175 self.max_id += 1;
176 let new_id = K::from_u64(self.max_id);
177 let value = f(new_id);
178 self.inner.insert(self.max_id, value);
179 new_id
180 }
181
182 pub fn get(&self, id: K) -> Option<&V> {
184 self.inner.get(&id.as_u64())
185 }
186
187 pub fn get_mut(&mut self, id: K) -> Option<&mut V> {
189 self.inner.get_mut(&id.as_u64())
190 }
191
192 pub fn remove(&mut self, id: K) -> Option<V> {
194 self.inner.remove(&id.as_u64())
195 }
196
197 pub fn contains_id(&self, id: K) -> bool {
199 self.inner.contains_key(&id.as_u64())
200 }
201
202 pub fn max_id(&self) -> K {
204 K::from_u64(self.max_id)
205 }
206
207 pub fn len(&self) -> usize {
209 self.inner.len()
210 }
211
212 pub fn is_empty(&self) -> bool {
214 self.inner.is_empty()
215 }
216
217 pub fn clear(&mut self) {
219 self.inner.clear();
220 }
221}
222
223impl<K: Id, V> Index<K> for IdMap<K, V> {
225 type Output = V;
226
227 fn index(&self, id: K) -> &Self::Output {
228 self.get(id).expect("invalid IdMap id")
229 }
230}
231
232impl<K: Id, V> IndexMut<K> for IdMap<K, V> {
233 fn index_mut(&mut self, id: K) -> &mut Self::Output {
234 self.get_mut(id).expect("invalid IdMap id")
235 }
236}
237
238#[cfg(test)]
240mod tests {
241 use super::*;
242 use serde_json;
243
244 #[test]
246 fn test_default_id_auto_generate() {
247 let mut map = IdMap::new();
248
249 let id1 = map.insert("hello");
251 let id2 = map.insert("world");
252 let id3 = map.insert("rust");
253
254 assert_eq!(id1, DefaultId(1));
256 assert_eq!(id2, DefaultId(2));
257 assert_eq!(id3, DefaultId(3));
258
259 assert_eq!(map.get(id1), Some(&"hello"));
261 assert_eq!(map[id2], "world");
262 assert_eq!(map.max_id(), DefaultId(3));
263
264 map.remove(id2);
266 assert_eq!(map.max_id(), DefaultId(3));
267 let id4 = map.insert("new value");
268 assert_eq!(id4, DefaultId(4)); assert_eq!(map.len(), 3);
272 map.clear();
273 assert!(map.is_empty());
274 }
275
276 new_id_type! {
278 struct MyId;
279 }
280
281 #[test]
282 fn test_custom_id() {
283 let mut map = IdMap::<MyId, u32>::with_id();
284
285 let id1 = map.insert(42);
286 let id2 = map.insert(100);
287
288 assert_eq!(id1, MyId(1));
289 assert_eq!(id2, MyId(2));
290 assert_eq!(map.get(id1), Some(&42));
291
292 map.remove(id1);
294 assert!(!map.contains_id(id1));
295 }
296
297 #[test]
299 fn test_id_serde() {
300 let id = DefaultId(123456789);
302 let json = serde_json::to_string(&id).unwrap();
303 assert_eq!(json, "123456789"); let id2: DefaultId = serde_json::from_str(&json).unwrap();
305 assert_eq!(id2, id);
306
307 let my_id = MyId(987654321);
309 let json = serde_json::to_string(&my_id).unwrap();
310 let my_id2: MyId = serde_json::from_str(&json).unwrap();
311 assert_eq!(my_id2, my_id);
312 }
313}