egglog_numeric_id/
lib.rs

1//! A crate with utilities for working with numeric Ids.
2use std::{
3    fmt::{self, Debug},
4    hash::Hash,
5    marker::PhantomData,
6    ops,
7};
8
9#[cfg(test)]
10mod tests;
11
12/// A trait describing "newtypes" that wrap an integer.
13pub trait NumericId: Copy + Clone + PartialEq + Eq + PartialOrd + Ord + Hash + Send + Sync {
14    type Rep;
15    type Atomic;
16    fn new(val: Self::Rep) -> Self;
17    fn from_usize(index: usize) -> Self;
18    fn index(self) -> usize;
19    fn rep(self) -> Self::Rep;
20    fn inc(self) -> Self {
21        Self::from_usize(self.index() + 1)
22    }
23}
24
25/// A [`NumericId`] whose in-memory representation may be accessed atomically.
26///
27/// # Safety
28///
29/// The ID must have the same size, byte representation, and set of valid bit
30/// patterns as both `Self::Rep` and `Self::Atomic`. (The atomic type may require
31/// stricter alignment; code creating an atomic view must check that separately.)
32/// It must therefore be sound to reinterpret a sufficiently aligned initialized
33/// slice of IDs as a slice of atomic integers, provided that atomic and
34/// non-atomic accesses do not overlap.
35pub unsafe trait AtomicNumericId: NumericId {}
36
37// SAFETY: `usize` and `AtomicUsize` have the same size, byte representation,
38// and valid bit patterns.
39unsafe impl AtomicNumericId for usize {}
40
41impl NumericId for usize {
42    type Rep = usize;
43    type Atomic = std::sync::atomic::AtomicUsize;
44    fn new(val: usize) -> Self {
45        val
46    }
47    fn from_usize(index: usize) -> Self {
48        index
49    }
50
51    fn rep(self) -> usize {
52        self
53    }
54
55    fn index(self) -> usize {
56        self
57    }
58}
59
60/// A mapping from a [`NumericId`] to some value.
61///
62/// This mapping is _dense_: it stores a flat array indexed by `K::index()`,
63/// with no hashing. For sparse mappings, use a HashMap.
64#[derive(PartialEq, Eq, Hash)]
65pub struct DenseIdMap<K, V> {
66    data: Vec<Option<V>>,
67    _marker: PhantomData<K>,
68}
69
70impl<K, V: Clone> Clone for DenseIdMap<K, V> {
71    fn clone(&self) -> Self {
72        Self {
73            data: self.data.clone(),
74            _marker: PhantomData,
75        }
76    }
77
78    fn clone_from(&mut self, source: &Self) {
79        self.data.clone_from(&source.data);
80    }
81}
82
83impl<K: NumericId + Debug, V: Debug> Debug for DenseIdMap<K, V> {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        let mut map = f.debug_map();
86        for (k, v) in self.iter() {
87            map.entry(&k, v);
88        }
89        map.finish()
90    }
91}
92
93impl<K, V> Default for DenseIdMap<K, V> {
94    fn default() -> Self {
95        Self {
96            data: Vec::new(),
97            _marker: PhantomData,
98        }
99    }
100}
101
102impl<K: NumericId, V> DenseIdMap<K, V> {
103    /// Create an empty map with space for `n` entries pre-allocated.
104    pub fn with_capacity(n: usize) -> Self {
105        let mut res = Self::new();
106        res.reserve_space(K::from_usize(n.saturating_sub(1)));
107        res
108    }
109
110    /// Create an empty map.
111    pub fn new() -> Self {
112        Self::default()
113    }
114
115    /// Clear the table's contents.
116    pub fn clear(&mut self) {
117        self.data.clear();
118    }
119
120    /// Get the current capacity for the table.
121    pub fn capacity(&self) -> usize {
122        self.data.capacity()
123    }
124
125    /// Get the number of ids currently indexed by the table (including "null"
126    /// entries). This is a less useful version of "length" in other containers.
127    pub fn n_ids(&self) -> usize {
128        self.data.len()
129    }
130
131    /// Insert the given mapping into the table.
132    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
133        self.reserve_space(key);
134        self.data[key.index()].replace(value)
135    }
136
137    /// Get the key that would be returned by the next call to [`DenseIdMap::push`].
138    pub fn next_id(&self) -> K {
139        K::from_usize(self.data.len())
140    }
141
142    /// Add the given mapping to the table, returning the key corresponding to
143    /// [`DenseIdMap::n_ids`].
144    pub fn push(&mut self, val: V) -> K {
145        let res = self.next_id();
146        self.data.push(Some(val));
147        res
148    }
149
150    /// Test whether `key` is set in this map.
151    pub fn contains_key(&self, key: K) -> bool {
152        self.data.get(key.index()).is_some_and(Option::is_some)
153    }
154
155    /// Get the current mapping for `key` in the table.
156    pub fn get(&self, key: K) -> Option<&V> {
157        self.data.get(key.index())?.as_ref()
158    }
159
160    /// Get a mutable reference to the current mapping for `key` in the table.
161    pub fn get_mut(&mut self, key: K) -> Option<&mut V> {
162        self.reserve_space(key);
163        self.data.get_mut(key.index())?.as_mut()
164    }
165
166    /// Extract the value mapped to by `key` from the table.
167    ///
168    /// # Panics
169    /// This method panics if `key` is not in the table.
170    pub fn unwrap_val(&mut self, key: K) -> V {
171        self.reserve_space(key);
172        self.data.get_mut(key.index()).unwrap().take().unwrap()
173    }
174
175    /// Extract the value mapped to by `key` from the table, if it is present.
176    pub fn take(&mut self, key: K) -> Option<V> {
177        self.reserve_space(key);
178        self.data.get_mut(key.index()).unwrap().take()
179    }
180
181    /// Get the current mapping for `key` in the table, or insert the value
182    /// returned by `f` and return a mutable reference to it.
183    pub fn get_or_insert(&mut self, key: K, f: impl FnOnce() -> V) -> &mut V {
184        self.reserve_space(key);
185        self.data[key.index()].get_or_insert_with(f)
186    }
187
188    pub fn raw(&self) -> &[Option<V>] {
189        &self.data
190    }
191
192    pub fn raw_mut(&mut self) -> &mut [Option<V>] {
193        &mut self.data
194    }
195
196    pub fn iter(&self) -> impl Iterator<Item = (K, &V)> {
197        self.data
198            .iter()
199            .enumerate()
200            .filter_map(|(i, v)| Some((K::from_usize(i), v.as_ref()?)))
201    }
202
203    pub fn iter_mut(&mut self) -> impl Iterator<Item = (K, &mut V)> {
204        self.data
205            .iter_mut()
206            .enumerate()
207            .filter_map(|(i, v)| Some((K::from_usize(i), v.as_mut()?)))
208    }
209
210    #[allow(clippy::should_implement_trait)]
211    pub fn into_iter(self) -> impl Iterator<Item = (K, V)> {
212        self.data
213            .into_iter()
214            .enumerate()
215            .filter_map(|(i, v)| Some((K::from_usize(i), v?)))
216    }
217
218    /// Reserve space up to the given key in the table.
219    pub fn reserve_space(&mut self, key: K) {
220        let index = key.index();
221        if index >= self.data.len() {
222            self.data.resize_with(index + 1, || None);
223        }
224    }
225
226    pub fn drain(&mut self) -> impl Iterator<Item = (K, V)> + '_ {
227        // To avoid the need to write down the return type.
228        self.data
229            .drain(..)
230            .enumerate()
231            .filter_map(|(i, v)| Some((K::from_usize(i), v?)))
232    }
233
234    pub fn retain(&mut self, mut f: impl FnMut(K, &V) -> bool) {
235        for (i, v) in self.data.iter_mut().enumerate() {
236            if let Some(inner) = v
237                && !f(K::from_usize(i), inner)
238            {
239                *v = None;
240            }
241        }
242    }
243
244    pub fn len(&self) -> usize {
245        self.data.iter().filter(|v| v.is_some()).count()
246    }
247
248    pub fn is_empty(&self) -> bool {
249        self.data.iter().all(|v| v.is_none())
250    }
251}
252
253impl<K: NumericId, V> ops::Index<K> for DenseIdMap<K, V> {
254    type Output = V;
255
256    fn index(&self, key: K) -> &Self::Output {
257        self.get(key).unwrap()
258    }
259}
260
261impl<K: NumericId, V> ops::IndexMut<K> for DenseIdMap<K, V> {
262    fn index_mut(&mut self, key: K) -> &mut Self::Output {
263        self.get_mut(key).unwrap()
264    }
265}
266
267impl<K: NumericId, V: Default> DenseIdMap<K, V> {
268    pub fn get_or_default(&mut self, key: K) -> &mut V {
269        self.get_or_insert(key, V::default)
270    }
271}
272
273impl<K: NumericId, V: Clone> FromIterator<(K, V)> for DenseIdMap<K, V> {
274    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
275        let mut res = DenseIdMap::new();
276        for (k, v) in iter {
277            res.insert(k, v);
278        }
279        res
280    }
281}
282
283#[derive(Debug)]
284pub struct IdVec<K, V> {
285    data: Vec<V>,
286    _marker: std::marker::PhantomData<K>,
287}
288
289impl<K, V> IdVec<K, V> {
290    pub fn clear(&mut self) {
291        self.data.clear();
292    }
293    pub fn len(&self) -> usize {
294        self.data.len()
295    }
296    pub fn capacity(&self) -> usize {
297        self.data.capacity()
298    }
299}
300
301impl<K, V> Default for IdVec<K, V> {
302    fn default() -> IdVec<K, V> {
303        IdVec {
304            data: Default::default(),
305            _marker: std::marker::PhantomData,
306        }
307    }
308}
309
310impl<K, V: Clone> Clone for IdVec<K, V> {
311    fn clone(&self) -> Self {
312        IdVec {
313            data: self.data.clone(),
314            _marker: std::marker::PhantomData,
315        }
316    }
317
318    fn clone_from(&mut self, source: &Self) {
319        self.data.clone_from(&source.data);
320    }
321}
322
323/// Like a [`DenseIdMap`], but supports freeing (and reusing) slots.
324#[derive(Clone)]
325pub struct DenseIdMapWithReuse<K, V> {
326    data: DenseIdMap<K, V>,
327    free: Vec<K>,
328}
329
330impl<K, V> Default for DenseIdMapWithReuse<K, V> {
331    fn default() -> Self {
332        Self {
333            data: Default::default(),
334            free: Default::default(),
335        }
336    }
337}
338
339impl<K: NumericId, V> DenseIdMapWithReuse<K, V> {
340    /// Reserve a slot in the map for use later with [`DenseIdMapWithReuse::insert`].
341    pub fn reserve_slot(&mut self) -> K {
342        match self.free.pop() {
343            Some(res) => res,
344            None => {
345                let res = self.data.next_id();
346                self.data.reserve_space(res);
347                res
348            }
349        }
350    }
351
352    /// Insert the given mapping into the table. You probably
353    /// want to use [`DenseIdMapWithReuse::push`] instead, unless you need to use
354    /// the key to build the value, in which case you can
355    /// use [`DenseIdMapWithReuse::reserve_slot`] to get the key for this method.
356    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
357        self.data.insert(key, value)
358    }
359
360    /// Add the given value to the table.
361    pub fn push(&mut self, value: V) -> K {
362        let res = self.reserve_slot();
363        self.insert(res, value);
364        res
365    }
366
367    /// Remove the given key from the table, if it is present.
368    pub fn take(&mut self, id: K) -> Option<V> {
369        let res = self.data.take(id);
370        if res.is_some() {
371            self.free.push(id);
372        }
373        res
374    }
375}
376
377impl<K: NumericId, V> std::ops::Index<K> for DenseIdMapWithReuse<K, V> {
378    type Output = V;
379    fn index(&self, key: K) -> &V {
380        &self.data[key]
381    }
382}
383
384impl<K: NumericId, V> std::ops::IndexMut<K> for DenseIdMapWithReuse<K, V> {
385    fn index_mut(&mut self, key: K) -> &mut V {
386        &mut self.data[key]
387    }
388}
389
390impl<K: NumericId, V> IdVec<K, V> {
391    pub fn with_capacity(cap: usize) -> IdVec<K, V> {
392        IdVec {
393            data: Vec::with_capacity(cap),
394            _marker: std::marker::PhantomData,
395        }
396    }
397
398    pub fn push(&mut self, elt: V) -> K {
399        let res = K::from_usize(self.data.len());
400        self.data.push(elt);
401        res
402    }
403
404    pub fn resize_with(&mut self, size: usize, init: impl FnMut() -> V) {
405        self.data.resize_with(size, init)
406    }
407
408    pub fn is_empty(&self) -> bool {
409        self.data.is_empty()
410    }
411
412    pub fn values(&self) -> impl Iterator<Item = &V> {
413        self.data.iter()
414    }
415
416    pub fn iter(&self) -> impl Iterator<Item = (K, &V)> {
417        self.data
418            .iter()
419            .enumerate()
420            .map(|(i, v)| (K::from_usize(i), v))
421    }
422    pub fn iter_mut(&mut self) -> impl Iterator<Item = (K, &mut V)> {
423        self.data
424            .iter_mut()
425            .enumerate()
426            .map(|(i, v)| (K::from_usize(i), v))
427    }
428    pub fn drain(&mut self) -> impl Iterator<Item = (K, V)> + '_ {
429        self.data
430            .drain(..)
431            .enumerate()
432            .map(|(i, v)| (K::from_usize(i), v))
433    }
434    pub fn get(&self, key: K) -> Option<&V> {
435        self.data.get(key.index())
436    }
437
438    pub fn as_mut_slice(&mut self) -> &mut [V] {
439        &mut self.data
440    }
441}
442
443impl<K: NumericId, V> ops::Index<K> for IdVec<K, V> {
444    type Output = V;
445
446    fn index(&self, key: K) -> &Self::Output {
447        &self.data[key.index()]
448    }
449}
450
451impl<K: NumericId, V> ops::IndexMut<K> for IdVec<K, V> {
452    fn index_mut(&mut self, key: K) -> &mut Self::Output {
453        &mut self.data[key.index()]
454    }
455}
456
457#[macro_export]
458#[doc(hidden)]
459macro_rules! atomic_of {
460    (usize) => {
461        std::sync::atomic::AtomicUsize
462    };
463    (u8) => {
464        std::sync::atomic::AtomicU8
465    };
466    (u16) => {
467        std::sync::atomic::AtomicU16
468    };
469    (u32) => {
470        std::sync::atomic::AtomicU32
471    };
472    (u64) => {
473        std::sync::atomic::AtomicU64
474    };
475}
476
477#[macro_export]
478macro_rules! define_id {
479    ($v:vis $name:ident, $repr:tt) => { define_id!($v $name, $repr, "", pretty ""); };
480    ($v:vis $name:ident, $repr:tt, $doc:tt) => { define_id!($v $name, $repr, $doc, pretty ""); };
481    ($v:vis $name:ident, $repr:tt, pretty $pretty_name:expr) => { define_id!($v $name, $repr, "", pretty $pretty_name); };
482    ($v:vis $name:ident, $repr:tt, $doc:tt, pretty $pretty_name:tt) => {
483        #[derive(Copy, Clone)]
484        #[repr(transparent)]
485        #[doc = $doc]
486        $v struct $name {
487            rep: $repr,
488        }
489
490        impl PartialEq for $name {
491            fn eq(&self, other: &Self) -> bool {
492                self.rep == other.rep
493            }
494        }
495
496        impl Eq for $name {}
497
498        impl PartialOrd for $name {
499            fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
500                Some(self.cmp(other))
501            }
502        }
503
504        impl Ord for $name {
505            fn cmp(&self, other: &Self) -> std::cmp::Ordering {
506                self.rep.cmp(&other.rep)
507            }
508        }
509
510        impl std::hash::Hash for $name {
511            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
512                self.rep.hash(state);
513            }
514        }
515
516        impl $name {
517            #[allow(unused)]
518            $v const fn new_const(id: $repr) -> Self {
519                $name {
520                    rep: id,
521                }
522            }
523
524            #[allow(unused)]
525            $v fn range(low: Self, high: Self) -> impl Iterator<Item = Self> {
526                use $crate::NumericId;
527                (low.rep..high.rep).map(|i| $name::new(i))
528            }
529
530        }
531
532        impl $crate::NumericId for $name {
533            type Rep = $repr;
534            type Atomic = $crate::atomic_of!($repr);
535            fn new(id: $repr) -> Self {
536                Self::new_const(id)
537            }
538            fn from_usize(index: usize) -> Self {
539                assert!(<$repr>::MAX as usize >= index,
540                    "overflowing id type {} (represented as {}) with index {}", stringify!($name), stringify!($repr), index);
541                $name::new(index as $repr)
542            }
543            /// return the inner representation of id as usize
544            fn index(self) -> usize {
545                self.rep as usize
546            }
547            /// return the inner representation of id.
548            fn rep(self) -> $repr {
549                self.rep
550            }
551        }
552
553        // SAFETY: this ID is `repr(transparent)` over its integer
554        // representation, and `Atomic` is the corresponding atomic integer.
555        unsafe impl $crate::AtomicNumericId for $name {}
556
557        impl std::fmt::Debug for $name {
558            fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
559                let name = if $pretty_name.is_empty() {
560                    stringify!($name).to_string()
561                } else {
562                    $pretty_name.to_string()
563                };
564                write!(fmt, "{}({:?})", name, self.rep)
565            }
566        }
567    };
568}