Skip to main content

orbit_atomic/
id.rs

1//! The address of a shared value, and the types a value can have.
2
3use std::fmt;
4use std::str::FromStr;
5
6use crate::{Error, Result};
7
8/// What the 64 bits of a value spell.
9#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
10#[repr(u8)]
11pub enum Kind {
12    I64 = 1,
13    U64 = 2,
14    F64 = 3,
15    Bool = 4,
16}
17
18impl Kind {
19    /// The name used in the text form of an id.
20    pub const fn name(self) -> &'static str {
21        match self {
22            Self::I64 => "i64",
23            Self::U64 => "u64",
24            Self::F64 => "f64",
25            Self::Bool => "bool",
26        }
27    }
28
29    pub(crate) const fn from_tag(tag: u8) -> Option<Self> {
30        match tag {
31            1 => Some(Self::I64),
32            2 => Some(Self::U64),
33            3 => Some(Self::F64),
34            4 => Some(Self::Bool),
35            _ => None,
36        }
37    }
38
39    fn from_name(name: &str) -> Option<Self> {
40        [Self::I64, Self::U64, Self::F64, Self::Bool]
41            .into_iter()
42            .find(|kind| kind.name() == name)
43    }
44}
45
46impl fmt::Display for Kind {
47    fn fmt(
48        &self,
49        f: &mut fmt::Formatter<'_>,
50    ) -> fmt::Result {
51        f.write_str(self.name())
52    }
53}
54
55pub(crate) const SLOT_BITS: u32 = 24;
56const SLOT_MASK: u64 = (1 << SLOT_BITS) - 1;
57
58/// The address of one shared value: `kind:8 | slot:24 | epoch:32`.
59///
60/// It is the only thing that travels between processes. Eight big-endian
61/// bytes through [`Self::to_bytes`], or `<kind>:<slot>:<epoch>` as text,
62/// such as `i64:12:3`. An id is valid in the table that minted it until
63/// that table is reset.
64#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
65pub struct OrbitalId(u64);
66
67impl OrbitalId {
68    pub(crate) const fn new(
69        kind: Kind,
70        slot: u32,
71        epoch: u32,
72    ) -> Self {
73        Self(
74            ((kind as u64) << 56)
75                | ((slot as u64 & SLOT_MASK) << 32)
76                | epoch as u64,
77        )
78    }
79
80    pub const fn kind(self) -> Kind {
81        // Every constructor refuses an unknown kind byte.
82        match Kind::from_tag((self.0 >> 56) as u8) {
83            Some(kind) => kind,
84            None => unreachable!(),
85        }
86    }
87
88    pub(crate) const fn slot(self) -> u32 {
89        ((self.0 >> 32) & SLOT_MASK) as u32
90    }
91
92    pub(crate) const fn epoch(self) -> u32 {
93        self.0 as u32
94    }
95
96    /// Big-endian: the kind is the first byte.
97    pub const fn to_bytes(self) -> [u8; 8] {
98        self.0.to_be_bytes()
99    }
100
101    /// The inverse of [`Self::to_bytes`]. An unknown kind byte is refused.
102    pub fn from_bytes(bytes: [u8; 8]) -> Result<Self> {
103        match Kind::from_tag(bytes[0]) {
104            Some(_) => Ok(Self(u64::from_be_bytes(bytes))),
105            None => Err(Error::UnknownKind(bytes[0])),
106        }
107    }
108}
109
110impl fmt::Display for OrbitalId {
111    fn fmt(
112        &self,
113        f: &mut fmt::Formatter<'_>,
114    ) -> fmt::Result {
115        write!(f, "{}:{}:{}", self.kind(), self.slot(), self.epoch())
116    }
117}
118
119impl FromStr for OrbitalId {
120    type Err = Error;
121
122    fn from_str(text: &str) -> Result<Self> {
123        let parse = || {
124            let mut parts = text.splitn(3, ':');
125            let kind = Kind::from_name(parts.next()?)?;
126            let slot: u32 = parts.next()?.parse().ok()?;
127            let epoch: u32 = parts.next()?.parse().ok()?;
128            (u64::from(slot) <= SLOT_MASK).then(|| Self::new(kind, slot, epoch))
129        };
130        parse().ok_or_else(|| Error::Malformed(text.into()))
131    }
132}
133
134mod sealed {
135    pub trait Sealed {}
136}
137
138/// A type one shared value can hold: `i64`, `u64`, `f64` or `bool`.
139///
140/// Sealed: the table stores 64 bits and a kind, and every write keeps
141/// those bits in the one form its kind allows.
142pub trait Primitive: sealed::Sealed + Copy + Send + Sync + 'static {
143    const KIND: Kind;
144
145    #[doc(hidden)]
146    fn into_word(self) -> u64;
147    #[doc(hidden)]
148    fn from_word(word: u64) -> Self;
149}
150
151impl sealed::Sealed for i64 {}
152impl Primitive for i64 {
153    const KIND: Kind = Kind::I64;
154
155    #[inline]
156    fn into_word(self) -> u64 {
157        self as u64
158    }
159
160    #[inline]
161    fn from_word(word: u64) -> Self {
162        word as i64
163    }
164}
165
166impl sealed::Sealed for u64 {}
167impl Primitive for u64 {
168    const KIND: Kind = Kind::U64;
169
170    #[inline]
171    fn into_word(self) -> u64 {
172        self
173    }
174
175    #[inline]
176    fn from_word(word: u64) -> Self {
177        word
178    }
179}
180
181impl sealed::Sealed for f64 {}
182impl Primitive for f64 {
183    const KIND: Kind = Kind::F64;
184
185    #[inline]
186    fn into_word(self) -> u64 {
187        self.to_bits()
188    }
189
190    #[inline]
191    fn from_word(word: u64) -> Self {
192        f64::from_bits(word)
193    }
194}
195
196impl sealed::Sealed for bool {}
197impl Primitive for bool {
198    const KIND: Kind = Kind::Bool;
199
200    #[inline]
201    fn into_word(self) -> u64 {
202        u64::from(self)
203    }
204
205    #[inline]
206    fn from_word(word: u64) -> Self {
207        word != 0
208    }
209}