ifc_lite_core/
guid.rs

1// SPDX-License-Identifier: MPL-2.0
2//! The IfcGloballyUniqueId (22-char GlobalId) home: alphabet, validators, the
3//! leading-GlobalId reader and the two deterministic minters.
4//!
5//! Two notions on purpose, NOT interchangeable (#7777): [`is_global_id_shaped`]
6//! (length + alphabet) decides whether a token is RECOGNISED as a GlobalId, so
7//! the merge sees every collision real files produce (some exporters write a
8//! first character outside `0..=3`); [`is_valid_global_id`] additionally
9//! enforces the 128-bit packing rule and gates what we WRITE or trust
10//! (appearance). Strictness must never decide whether a collision is seen.
11
12/// buildingSMART base64 alphabet (64 chars) used by IfcGloballyUniqueId.
13pub const ALPHABET: &[u8; 64] =
14    b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_$";
15
16/// A GlobalId is the first attribute, so it always starts well inside this many
17/// bytes of a STEP line; the scan never looks further.
18const LEADING_WINDOW: usize = 128;
19
20/// True for a 22-char token drawn entirely from [`ALPHABET`]
21/// (`^[0-9A-Za-z_$]{22}$`). Does not check the first-character range.
22pub fn is_global_id_shaped(s: &str) -> bool {
23    s.len() == 22 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'$')
24}
25
26/// [`is_global_id_shaped`] plus the spec rule that the first character carries
27/// only 2 bits (`'0'..='3'`), since 22 chars hold `2 + 21 * 6 = 128` bits.
28pub fn is_valid_global_id(s: &str) -> bool {
29    is_global_id_shaped(s) && (b'0'..=b'3').contains(&s.as_bytes()[0])
30}
31
32/// The first `'...'` string of a STEP entity line, when it is GlobalId-shaped.
33/// Only the first 128 bytes are inspected. Rootedness (whether the entity type
34/// has a GlobalId at all) is the caller's decision.
35pub fn leading_global_id(line: &[u8]) -> Option<&str> {
36    let window = &line[..line.len().min(LEADING_WINDOW)];
37    let open = window.iter().position(|&b| b == b'(')?;
38    let mut i = open + 1;
39    while i < window.len() && window[i].is_ascii_whitespace() {
40        i += 1;
41    }
42    if i >= window.len() || window[i] != b'\'' {
43        return None;
44    }
45    let start = i + 1;
46    let close = window[start..].iter().position(|&b| b == b'\'')? + start;
47    let inner = std::str::from_utf8(&window[start..close]).ok()?;
48    is_global_id_shaped(inner).then_some(inner)
49}
50
51/// Rendered-line reader used by the merge's collision bookkeeping: the first
52/// `'...'` after the first `(`, anywhere in the text (no window), when it is
53/// GlobalId-SHAPED. Deliberately the lenient [`is_global_id_shaped`] test, not
54/// [`is_valid_global_id`]: whether a collision is SEEN must never depend on
55/// validity, or two entities sharing a non-conforming id are silently kept.
56pub fn read_leading_global_id(text: &str) -> Option<&str> {
57    let span = rendered_first_string(text)?;
58    let inner = &text[span.clone()];
59    is_global_id_shaped(inner).then_some(inner)
60}
61
62/// `text` with the string read by [`read_leading_global_id`]'s scan replaced by
63/// `new_guid`; unchanged when the line has no quoted first attribute.
64pub fn replace_rendered_global_id(text: &str, new_guid: &str) -> String {
65    let Some(span) = rendered_first_string(text) else {
66        return text.to_string();
67    };
68    let mut out = String::with_capacity(text.len() + new_guid.len());
69    out.push_str(&text[..span.start]);
70    out.push_str(new_guid);
71    out.push_str(&text[span.end..]);
72    out
73}
74
75fn rendered_first_string(text: &str) -> Option<std::ops::Range<usize>> {
76    let b = text.as_bytes();
77    let open = b.iter().position(|&c| c == b'(')?;
78    let q1 = b[open..].iter().position(|&c| c == b'\'')? + open;
79    let q2 = b[q1 + 1..].iter().position(|&c| c == b'\'')? + q1 + 1;
80    Some(q1 + 1..q2)
81}
82
83/// Deterministic 22-char GlobalId from an arbitrary seed. A faithful port of
84/// `@ifc-lite/parser`'s `deterministicGlobalId` (four independent 32-bit rolling
85/// hashes cross-mixed into a 128-bit state, stamped MSB-first as `2 + 21*6`
86/// bits), pinned by `rust/export/tests/fixtures/deterministic_global_id_vectors.json`.
87///
88/// The input is iterated as UTF-16 code units to match JavaScript's `charCodeAt`.
89pub fn deterministic(seed: &str) -> String {
90    encode(hash128(seed))
91}
92
93/// The 128-bit state [`deterministic`] encodes, exposed so a caller that needs
94/// the bits (to derive further ids from them) gets the same hash rather than a
95/// second one.
96pub fn hash128(seed: &str) -> u128 {
97    let mut h0: u32 = 0x811c_9dc5;
98    let mut h1: u32 = 0x9e37_79b9;
99    let mut h2: u32 = 0x6c07_8965;
100    let mut h3: u32 = 0xb529_7a4d;
101    for unit in seed.encode_utf16() {
102        let c = unit as u32;
103        h0 = (h0 ^ c).wrapping_mul(0x0100_0193);
104        h1 = (h1 ^ c ^ (h1 >> 11)).wrapping_mul(0x85eb_ca6b);
105        h2 = h2.wrapping_add(c).wrapping_add(h2 >> 7).wrapping_mul(0xc2b2_ae35);
106        h3 = (h3 ^ ((c << 3) | (c >> 5)) ^ (h3 >> 13)).wrapping_mul(0x27d4_eb2f);
107    }
108    let mix = |x: u32, y: u32| -> u32 {
109        ((x ^ y).wrapping_add((x >> 7) | (y << 25))).wrapping_mul(0x85eb_ca6b)
110    };
111    let m0 = mix(h0, h2);
112    let m1 = mix(h1, h3);
113    let m2 = mix(h2, m1);
114    let m3 = mix(h3, m0);
115    (u128::from(m0) << 96) | (u128::from(m1) << 64) | (u128::from(m2) << 32) | u128::from(m3)
116}
117
118/// Encode 128 bits as an IfcGloballyUniqueId: 22 characters of [`ALPHABET`],
119/// read MSB-first. 22 x 6 = 132 bits is four more than a GUID holds, so the
120/// FIRST character carries only the top 2 bits (`0`..`3`) and each of the
121/// other 21 carries 6. That split is the IFC convention, not RFC 4648 base64:
122/// a different alphabet order, no padding, and no byte alignment.
123pub fn encode(bits: u128) -> String {
124    let mut out = String::with_capacity(22);
125    out.push(ALPHABET[(bits >> 126) as usize] as char);
126    for i in 0..21 {
127        let shift = 120 - 6 * i;
128        out.push(ALPHABET[((bits >> shift) & 0x3f) as usize] as char);
129    }
130    out
131}
132
133/// The 128 bits a GlobalId encodes: the inverse of [`encode`], or `None` when
134/// `s` is not [`is_valid_global_id`] (a first character past `'3'` would need
135/// a 129th bit). A GlobalId is a compressed GUID, so these bits are the GUID a
136/// tool that expands GlobalIds (IfcOpenShell's `guid.expand`) prints.
137pub fn decode_bits(s: &str) -> Option<u128> {
138    if !is_valid_global_id(s) {
139        return None;
140    }
141    s.bytes().try_fold(0u128, |acc, b| {
142        let digit = ALPHABET.iter().position(|&a| a == b)?;
143        Some((acc << 6) | digit as u128)
144    })
145}
146
147/// Deterministic 22-char GlobalId-shaped placeholder derived from an express id
148/// (right-aligned base-64 of `id + 0x1000_0000`, zero-padded). Intentionally
149/// NOT the TypeScript mint: schema conversion pins this divergence
150/// (`schema_convert_tests.rs`).
151pub fn placeholder(id: u32) -> String {
152    let mut n = id as u64 + 0x1000_0000;
153    let mut s = [b'0'; 22];
154    let mut i = 22;
155    while i > 0 && n > 0 {
156        i -= 1;
157        s[i] = ALPHABET[(n % 64) as usize];
158        n /= 64;
159    }
160    s.iter().map(|&b| b as char).collect()
161}
162
163#[cfg(test)]
164#[path = "guid_tests.rs"]
165mod tests;
166