fugue_db/
id.rs

1use std::marker::PhantomData;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
4#[derive(serde::Serialize, serde::Deserialize)]
5#[repr(transparent)]
6/// Upper 32 bit: parent
7/// Lower 32 bit: index
8/// All 1: invalid
9pub struct Id<T>(u64, PhantomData<T>);
10
11impl<T> From<u32> for Id<T> {
12    fn from(value: u32) -> Self {
13        Self(value as i32 as i64 as u64, PhantomData)
14    }
15}
16
17impl<T> From<u64> for Id<T> {
18    fn from(value: u64) -> Self {
19        Self(value, PhantomData)
20    }
21}
22
23impl<T> From<usize> for Id<T> {
24    fn from(value: usize) -> Self {
25        Self(value as u64, PhantomData)
26    }
27}
28
29impl<T> Id<T> {
30    pub const fn invalid() -> Id<T> {
31        Id(0xffffffff_ffffffff, PhantomData)
32    }
33
34    pub const fn is_invalid(&self) -> bool {
35        self.0 == 0xffffffff_ffffffff
36    }
37
38    pub const fn parent(&self) -> usize {
39        (self.0 >> 32) as usize
40    }
41
42    pub const fn index(&self) -> usize {
43        (self.0 & 0xffffffff) as usize
44    }
45
46    pub const fn value(&self) -> u64 {
47        self.0
48    }
49}