Skip to main content

safe_bump/
idx.rs

1use std::marker::PhantomData;
2
3/// Stable index into an [`Arena`](crate::Arena) or
4/// [`SharedArena`](crate::SharedArena).
5///
6/// Obtained from [`Arena::alloc`](crate::Arena::alloc) or
7/// [`SharedArena::alloc`](crate::SharedArena::alloc). Implements [`Copy`],
8/// so it can be freely duplicated and stored in data structures.
9///
10/// Valid as long as the arena has not been reset or rolled back past
11/// this index.
12///
13/// # Panics
14///
15/// Indexing with a stale `Idx` (after rollback/reset) panics with
16/// an out-of-bounds error.
17pub struct Idx<T> {
18    index: usize,
19    _marker: PhantomData<T>,
20}
21
22impl<T> Idx<T> {
23    /// Returns the raw index value.
24    #[must_use]
25    pub const fn into_raw(self) -> usize {
26        self.index
27    }
28
29    /// Creates an index from a raw value.
30    ///
31    /// The caller must ensure the index is valid for the target arena.
32    #[must_use]
33    pub const fn from_raw(index: usize) -> Self {
34        Self {
35            index,
36            _marker: PhantomData,
37        }
38    }
39}
40
41impl<T> Clone for Idx<T> {
42    fn clone(&self) -> Self {
43        *self
44    }
45}
46
47impl<T> Copy for Idx<T> {}
48
49impl<T> PartialEq for Idx<T> {
50    fn eq(&self, other: &Self) -> bool {
51        self.index == other.index
52    }
53}
54
55impl<T> Eq for Idx<T> {}
56
57impl<T> std::hash::Hash for Idx<T> {
58    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
59        self.index.hash(state);
60    }
61}
62
63impl<T> std::fmt::Debug for Idx<T> {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        write!(f, "Idx({})", self.index)
66    }
67}
68
69impl<T> PartialOrd for Idx<T> {
70    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
71        Some(self.cmp(other))
72    }
73}
74
75impl<T> Ord for Idx<T> {
76    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
77        self.index.cmp(&other.index)
78    }
79}