Skip to main content

nodedb_types/id/
tenant.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Tenant identifier.
4
5use std::fmt;
6
7use serde::{Deserialize, Serialize};
8
9/// Identifies a tenant. All data is tenant-scoped by construction.
10#[derive(
11    Debug,
12    Clone,
13    Copy,
14    PartialEq,
15    Eq,
16    Hash,
17    Serialize,
18    Deserialize,
19    zerompk::ToMessagePack,
20    zerompk::FromMessagePack,
21    rkyv::Archive,
22    rkyv::Serialize,
23    rkyv::Deserialize,
24)]
25pub struct TenantId(u64);
26
27impl TenantId {
28    pub const fn new(id: u64) -> Self {
29        Self(id)
30    }
31
32    pub const fn as_u64(self) -> u64 {
33        self.0
34    }
35}
36
37impl From<u64> for TenantId {
38    fn from(id: u64) -> Self {
39        Self(id)
40    }
41}
42
43impl fmt::Display for TenantId {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        write!(f, "tenant:{}", self.0)
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52
53    #[test]
54    fn tenant_id_display() {
55        let t = TenantId::new(42);
56        assert_eq!(t.to_string(), "tenant:42");
57        assert_eq!(t.as_u64(), 42);
58    }
59
60    #[test]
61    fn tenant_id_above_u32_max_roundtrip() {
62        let large = u32::MAX as u64 + 1;
63        let t = TenantId::new(large);
64        assert_eq!(t.as_u64(), large);
65        assert_eq!(t.to_string(), format!("tenant:{large}"));
66    }
67
68    #[test]
69    fn tenant_id_from_u64() {
70        let t: TenantId = TenantId::from(4_294_967_296u64);
71        assert_eq!(t.as_u64(), 4_294_967_296u64);
72    }
73
74    #[test]
75    fn serde_roundtrip() {
76        let tid = TenantId::new(7);
77        let json = sonic_rs::to_string(&tid).unwrap();
78        let decoded: TenantId = sonic_rs::from_str(&json).unwrap();
79        assert_eq!(tid, decoded);
80    }
81
82    #[test]
83    fn serde_roundtrip_above_u32_max() {
84        let tid = TenantId::new(u32::MAX as u64 + 1);
85        let json = sonic_rs::to_string(&tid).unwrap();
86        let decoded: TenantId = sonic_rs::from_str(&json).unwrap();
87        assert_eq!(tid, decoded);
88    }
89}