1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
use std::fmt;
use std::num::NonZeroUsize;
/// An opaque identifier that is associated with AST items.
///
/// The default implementation for an identifier is empty, meaning it does not
/// hold any value, and attempting to perform lookups over it will fail with an
/// error indicating that it's empty with the string `Id(*)`.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct Id(NonZeroUsize);
impl Id {
/// Construct the initial (non-empty) id.
pub fn initial() -> Self {
Id(NonZeroUsize::new(1).unwrap())
}
/// Construct a new opaque identifier.
pub fn new(index: usize) -> Option<Id> {
NonZeroUsize::new(index).map(Self)
}
/// Get the next id.
pub fn next(self) -> Option<Id> {
let n = self.0.get().checked_add(1)?;
let n = NonZeroUsize::new(n)?;
Some(Self(n))
}
}
impl Default for Id {
fn default() -> Self {
Self::initial()
}
}
impl fmt::Debug for Id {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Id({})", self.0.get())
}
}