Skip to main content

vibe/cosmic/
cb_usri.rs

1//! Compact Binary USRI (CB-USRI) for zero-heap hot paths (OCS §13.2).
2//!
3//! 16-byte fixed-size binary representation of a USRI for use in
4//! Tier-1 hot paths, NQuin context fields, and GPU/WASM ABI.
5//!
6//! Layout (OCS §13.2):
7//! ```text
8//! Bits [0..55]   : 56-bit FNV-1a Hash of (realm_class : universe_id : branch_id : path)
9//! Bits [56..63]  : 8-bit Realm Class Index
10//! Bits [64..79]  : 16-bit Hierarchy Level & Nesting Depth Index (L_-2..L_12, Depth k)
11//! Bits [80..127] : 48-bit Anchor / Local Coordinate Hash
12//! ```
13//!
14//! Reference: OCS Specification v2.2.0 §13.2.
15
16use super::usri::RealmClass;
17use crate::value::Value;
18
19/// FNV-1a 64-bit hash.
20fn fnv1a_64(s: &str) -> u64 {
21    let mut h: u64 = 0xcbf29ce484222325;
22    for b in s.as_bytes() {
23        h ^= *b as u64;
24        h = h.wrapping_mul(0x100000001b3);
25    }
26    h
27}
28
29/// Hierarchy level index (OCS §3.1, §4, §5).
30///
31/// L_-2 through L_12, covering 61 orders of magnitude from
32/// Planck scale to cosmological horizons.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34pub enum HierarchyLevel {
35    LNeg2, // Sub-Planck / theoretical
36    LNeg1, // Planck scale
37    L0,    // Quantum field
38    L1,    // Nuclear subatomic
39    L2,    // Atomic / orbitals
40    L3,    // Macromolecular
41    L4,    // Cellular / tissue
42    L5,    // Celestial body / geodesy
43    L6,    // Terrestrial AR / local
44    L7,    // Planetary system
45    L8,    // Interstellar
46    L9,    // Galactic
47    L10,   // Galaxy cluster
48    L11,   // Supercluster
49    L12,   // Cosmological horizon
50}
51
52impl HierarchyLevel {
53    /// All 15 hierarchy levels from L_-2 through L_12 in ascending order.
54    pub const ALL: [Self; 15] = [
55        Self::LNeg2,
56        Self::LNeg1,
57        Self::L0,
58        Self::L1,
59        Self::L2,
60        Self::L3,
61        Self::L4,
62        Self::L5,
63        Self::L6,
64        Self::L7,
65        Self::L8,
66        Self::L9,
67        Self::L10,
68        Self::L11,
69        Self::L12,
70    ];
71
72    /// `u8` form.
73    pub fn as_u8(&self) -> u8 {
74        match self {
75            Self::LNeg2 => 0,
76            Self::LNeg1 => 1,
77            Self::L0 => 2,
78            Self::L1 => 3,
79            Self::L2 => 4,
80            Self::L3 => 5,
81            Self::L4 => 6,
82            Self::L5 => 7,
83            Self::L6 => 8,
84            Self::L7 => 9,
85            Self::L8 => 10,
86            Self::L9 => 11,
87            Self::L10 => 12,
88            Self::L11 => 13,
89            Self::L12 => 14,
90        }
91    }
92
93    /// Constructs from u8.
94    pub fn from_u8(v: u8) -> Option<Self> {
95        match v {
96            0 => Some(Self::LNeg2),
97            1 => Some(Self::LNeg1),
98            2 => Some(Self::L0),
99            3 => Some(Self::L1),
100            4 => Some(Self::L2),
101            5 => Some(Self::L3),
102            6 => Some(Self::L4),
103            7 => Some(Self::L5),
104            8 => Some(Self::L6),
105            9 => Some(Self::L7),
106            10 => Some(Self::L8),
107            11 => Some(Self::L9),
108            12 => Some(Self::L10),
109            13 => Some(Self::L11),
110            14 => Some(Self::L12),
111            _ => None,
112        }
113    }
114
115    /// Name.
116    pub fn name(&self) -> &'static str {
117        match self {
118            Self::LNeg2 => "L_-2",
119            Self::LNeg1 => "L_-1",
120            Self::L0 => "L_0",
121            Self::L1 => "L_1",
122            Self::L2 => "L_2",
123            Self::L3 => "L_3",
124            Self::L4 => "L_4",
125            Self::L5 => "L_5",
126            Self::L6 => "L_6",
127            Self::L7 => "L_7",
128            Self::L8 => "L_8",
129            Self::L9 => "L_9",
130            Self::L10 => "L_10",
131            Self::L11 => "L_11",
132            Self::L12 => "L_12",
133        }
134    }
135}
136
137/// Compact Binary USRI — 16-byte fixed-size (OCS §13.2).
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
139pub struct CompactBinaryUsri {
140    /// Bytes [0..7]: 56-bit path hash + 8-bit realm class
141    pub path_and_realm: u64,
142    /// Bytes [8..9]: 16-bit hierarchy level + nesting depth
143    pub level_and_depth: u16,
144    /// Bytes [10..15]: 48-bit anchor hash (stored as u64, upper 16 bits unused)
145    pub anchor_hash: u64,
146}
147
148impl CompactBinaryUsri {
149    /// Build a CB-USRI from components.
150    pub fn new(
151        realm_class: RealmClass,
152        path_hash: u64,
153        level: HierarchyLevel,
154        nesting_depth: u8,
155        anchor_hash: u64,
156    ) -> Self {
157        // Pack 56-bit path hash + 8-bit realm class into u64
158        let path_56 = path_hash & 0x00FF_FFFF_FFFF_FFFF;
159        let realm_8 = (realm_class.as_u8() as u64) << 56;
160        let path_and_realm = path_56 | realm_8;
161
162        // Pack 8-bit level + 8-bit depth into u16
163        let level_and_depth = ((level.as_u8() as u16) << 8) | (nesting_depth as u16 & 0xFF);
164
165        // Mask anchor to 48 bits
166        let anchor = anchor_hash & 0x0000_FFFF_FFFF_FFFF;
167
168        Self {
169            path_and_realm,
170            level_and_depth,
171            anchor_hash: anchor,
172        }
173    }
174
175    /// Extract the realm class.
176    pub fn realm_class(&self) -> u8 {
177        (self.path_and_realm >> 56) as u8
178    }
179
180    /// Extract the 56-bit path hash.
181    pub fn path_hash(&self) -> u64 {
182        self.path_and_realm & 0x00FF_FFFF_FFFF_FFFF
183    }
184
185    /// Extract the hierarchy level.
186    pub fn level(&self) -> u8 {
187        (self.level_and_depth >> 8) as u8
188    }
189
190    /// Extract the nesting depth.
191    pub fn nesting_depth(&self) -> u8 {
192        (self.level_and_depth & 0xFF) as u8
193    }
194
195    /// Extract the 48-bit anchor hash.
196    pub fn anchor_hash_48(&self) -> u64 {
197        self.anchor_hash & 0x0000_FFFF_FFFF_FFFF
198    }
199
200    /// Encode to 16 bytes (big-endian for deterministic ordering).
201    pub fn to_bytes(&self) -> [u8; 16] {
202        let mut bytes = [0u8; 16];
203        bytes[0..8].copy_from_slice(&self.path_and_realm.to_be_bytes());
204        bytes[8..10].copy_from_slice(&self.level_and_depth.to_be_bytes());
205        bytes[10..16].copy_from_slice(&self.anchor_hash.to_be_bytes()[2..8]);
206        bytes
207    }
208
209    /// Decode from 16 bytes.
210    pub fn from_bytes(bytes: &[u8; 16]) -> Self {
211        let path_and_realm = u64::from_be_bytes(bytes[0..8].try_into().unwrap());
212        let level_and_depth = u16::from_be_bytes(bytes[8..10].try_into().unwrap());
213        let mut anchor_bytes = [0u8; 8];
214        anchor_bytes[2..8].copy_from_slice(&bytes[10..16]);
215        let anchor_hash = u64::from_be_bytes(anchor_bytes);
216        Self {
217            path_and_realm,
218            level_and_depth,
219            anchor_hash,
220        }
221    }
222
223    /// Compute from a USRI string and level/depth/anchor info.
224    pub fn from_usri(
225        usri_str: &str,
226        realm_class: RealmClass,
227        level: HierarchyLevel,
228        nesting_depth: u8,
229        anchor: &str,
230    ) -> Self {
231        let path_hash = fnv1a_64(usri_str);
232        let anchor_hash = if anchor.is_empty() {
233            0
234        } else {
235            fnv1a_64(anchor)
236        };
237        Self::new(realm_class, path_hash, level, nesting_depth, anchor_hash)
238    }
239
240    /// Deterministically fold the 16-byte `CompactBinaryUsri` (`path_and_realm`,
241    /// `level_and_depth`, `anchor_hash`) into a zero-heap 60-bit token (`MSB = 0`,
242    /// distinct from `did:q42` topological pointers, with 56-bit scoped realm hash in
243    /// bits `[0..55]` and `SENSITIVITY_PUBLIC = 0` in bits `[56..63]`) for `NQuin.context`.
244    pub fn to_quin_context_token(&self) -> u64 {
245        let bytes = self.to_bytes();
246        let mut h: u64 = 0xcbf29ce484222325;
247        let mut i = 0;
248        while i < 16 {
249            h ^= bytes[i] as u64;
250            h = h.wrapping_mul(0x100000001b3);
251            i += 1;
252        }
253        h & 0x00FF_FFFF_FFFF_FFFF
254    }
255
256    /// Encode an `NQuin.context` word combining an 8-bit sensitivity class in `[56..63]`
257    /// with the 56-bit folded `CB-USRI` token in `[0..55]`.
258    pub fn to_quin_context_with_sensitivity(&self, sensitivity: u8) -> u64 {
259        ((sensitivity as u64) << 56) | self.to_quin_context_token()
260    }
261
262    /// Convert to a Value::Record for inspection.
263    pub fn to_value(&self) -> Value {
264        let mut rec = std::collections::BTreeMap::new();
265        rec.insert("realm_class".into(), Value::U64(self.realm_class() as u64));
266        rec.insert("path_hash".into(), Value::U64(self.path_hash()));
267        rec.insert("level".into(), Value::U64(self.level() as u64));
268        rec.insert(
269            "nesting_depth".into(),
270            Value::U64(self.nesting_depth() as u64),
271        );
272        rec.insert("anchor_hash".into(), Value::U64(self.anchor_hash_48()));
273        Value::Record(rec)
274    }
275}
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280
281    #[test]
282    fn cb_usri_pack_unpack() {
283        let cb = CompactBinaryUsri::new(
284            RealmClass::Physical,
285            0x1234_5678_9ABC,
286            HierarchyLevel::L5,
287            2,
288            0xDEAD_BEEF,
289        );
290        assert_eq!(cb.realm_class(), RealmClass::Physical.as_u8());
291        assert_eq!(cb.path_hash(), 0x1234_5678_9ABC);
292        assert_eq!(cb.level(), HierarchyLevel::L5.as_u8());
293        assert_eq!(cb.nesting_depth(), 2);
294        assert_eq!(cb.anchor_hash_48(), 0xDEAD_BEEF);
295    }
296
297    #[test]
298    fn cb_usri_bytes_round_trip() {
299        let cb = CompactBinaryUsri::new(
300            RealmClass::Fiction,
301            0x00FF_FFFF_FFFF_FFFF,
302            HierarchyLevel::L12,
303            3,
304            0xFFFF_FFFF_FFFF,
305        );
306        let bytes = cb.to_bytes();
307        let recovered = CompactBinaryUsri::from_bytes(&bytes);
308        assert_eq!(cb, recovered);
309    }
310
311    #[test]
312    fn cb_usri_from_usri_deterministic() {
313        let a = CompactBinaryUsri::from_usri(
314            "urn:omni:v1:physical:observable:standard:earth:wgs84",
315            RealmClass::Physical,
316            HierarchyLevel::L5,
317            0,
318            "geo(lat=37.8,lon=-122.4)",
319        );
320        let b = CompactBinaryUsri::from_usri(
321            "urn:omni:v1:physical:observable:standard:earth:wgs84",
322            RealmClass::Physical,
323            HierarchyLevel::L5,
324            0,
325            "geo(lat=37.8,lon=-122.4)",
326        );
327        assert_eq!(a, b, "same USRI should produce same CB-USRI");
328    }
329
330    #[test]
331    fn cb_usri_different_realms_differ() {
332        let physical = CompactBinaryUsri::from_usri(
333            "path",
334            RealmClass::Physical,
335            HierarchyLevel::L5,
336            0,
337            "anchor",
338        );
339        let fiction = CompactBinaryUsri::from_usri(
340            "path",
341            RealmClass::Fiction,
342            HierarchyLevel::L5,
343            0,
344            "anchor",
345        );
346        assert_ne!(physical, fiction);
347    }
348
349    #[test]
350    fn cb_usri_different_levels_differ() {
351        let l5 = CompactBinaryUsri::from_usri(
352            "path",
353            RealmClass::Physical,
354            HierarchyLevel::L5,
355            0,
356            "anchor",
357        );
358        let l6 = CompactBinaryUsri::from_usri(
359            "path",
360            RealmClass::Physical,
361            HierarchyLevel::L6,
362            0,
363            "anchor",
364        );
365        assert_ne!(l5, l6);
366    }
367
368    #[test]
369    fn hierarchy_level_round_trip() {
370        for level in [
371            HierarchyLevel::LNeg2,
372            HierarchyLevel::L0,
373            HierarchyLevel::L5,
374            HierarchyLevel::L12,
375        ] {
376            assert_eq!(HierarchyLevel::from_u8(level.as_u8()), Some(level));
377        }
378    }
379
380    #[test]
381    fn cb_usri_16_bytes() {
382        let cb = CompactBinaryUsri::new(RealmClass::Physical, 1, HierarchyLevel::L0, 0, 1);
383        assert_eq!(cb.to_bytes().len(), 16);
384    }
385
386    #[test]
387    fn cb_usri_to_value() {
388        let cb = CompactBinaryUsri::new(RealmClass::Physical, 42, HierarchyLevel::L5, 1, 99);
389        let v = cb.to_value();
390        match v {
391            Value::Record(r) => {
392                assert_eq!(r.get("realm_class"), Some(&Value::U64(0)));
393                assert_eq!(r.get("path_hash"), Some(&Value::U64(42)));
394                assert_eq!(r.get("level"), Some(&Value::U64(7))); // L5 = 7
395            }
396            _ => panic!("expected Record"),
397        }
398    }
399
400    #[test]
401    fn cb_usri_empty_anchor() {
402        let cb =
403            CompactBinaryUsri::from_usri("test", RealmClass::Physical, HierarchyLevel::L0, 0, "");
404        assert_eq!(cb.anchor_hash_48(), 0);
405        assert_eq!(HierarchyLevel::ALL.len(), 15);
406        for (idx, level) in HierarchyLevel::ALL.iter().copied().enumerate() {
407            assert_eq!(level.as_u8(), idx as u8);
408            assert_eq!(HierarchyLevel::from_u8(idx as u8), Some(level));
409            let cb_l = CompactBinaryUsri::from_usri(
410                "urn:omni:v1:physical:observable:standard:earth:wgs84",
411                RealmClass::Physical,
412                level,
413                idx as u8,
414                "geo(lat=-35.78,lon=148.29)",
415            );
416            let bytes = cb_l.to_bytes();
417            assert_eq!(CompactBinaryUsri::from_bytes(&bytes), cb_l);
418            let token = cb_l.to_quin_context_token();
419            assert_eq!(token & (1u64 << 63), 0, "MSB must be 0 (not a did:q42 pointer)");
420            assert_eq!(token & 0xF000_0000_0000_0000, 0, "must fit in 60-bit token");
421            assert_ne!(token, 0);
422        }
423    }
424}