Skip to main content

slate_core/
id.rs

1//! Stable vector identifiers.
2
3use std::fmt;
4
5use serde::{Deserialize, Serialize};
6
7/// Stable identifier for a vector within an index.
8///
9/// A transparent newtype over `u64`. IDs are assigned densely from `0` at build
10/// time and remain valid across the soft-delete / buffered-insert update path,
11/// so an ID never refers to a different vector once issued.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
13#[repr(transparent)]
14#[serde(transparent)]
15pub struct VectorId(pub u64);
16
17impl VectorId {
18    /// Construct an identifier from its raw value.
19    #[inline]
20    pub const fn new(raw: u64) -> Self {
21        Self(raw)
22    }
23
24    /// Return the raw `u64` value.
25    #[inline]
26    pub const fn get(self) -> u64 {
27        self.0
28    }
29
30    /// Return the identifier as a `usize` index (for in-RAM array addressing).
31    #[inline]
32    pub const fn as_index(self) -> usize {
33        self.0 as usize
34    }
35}
36
37impl From<u64> for VectorId {
38    #[inline]
39    fn from(value: u64) -> Self {
40        Self(value)
41    }
42}
43
44impl From<usize> for VectorId {
45    #[inline]
46    fn from(value: usize) -> Self {
47        Self(value as u64)
48    }
49}
50
51impl From<VectorId> for u64 {
52    #[inline]
53    fn from(value: VectorId) -> Self {
54        value.0
55    }
56}
57
58impl From<VectorId> for usize {
59    #[inline]
60    fn from(value: VectorId) -> Self {
61        value.0 as usize
62    }
63}
64
65impl fmt::Display for VectorId {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        write!(f, "#{}", self.0)
68    }
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74
75    #[test]
76    fn roundtrips_through_integer_types() {
77        let id = VectorId::new(42);
78        assert_eq!(id.get(), 42);
79        assert_eq!(id.as_index(), 42usize);
80        assert_eq!(u64::from(id), 42);
81        assert_eq!(usize::from(id), 42usize);
82        assert_eq!(VectorId::from(42u64), id);
83        assert_eq!(VectorId::from(42usize), id);
84    }
85
86    #[test]
87    fn orders_and_displays() {
88        assert!(VectorId::new(1) < VectorId::new(2));
89        assert_eq!(VectorId::new(7).to_string(), "#7");
90    }
91}