Skip to main content

cim_kit/
mrid.rs

1//! Master resource identifiers.
2//!
3//! IEC 61970-552 requires every CIM object to be identified by a UUID, serialized as
4//! `rdf:ID="_<uuid>"` and referenced as `rdf:resource="#_<uuid>"`, with model headers
5//! using the `urn:uuid:<uuid>` form. Real exchange files do not always comply, so an
6//! [`Mrid`] preserves any identifier verbatim while storing conforming ones compactly.
7
8use std::fmt;
9use std::hash::{Hash, Hasher};
10
11/// How an identifier was spelled in the document it came from.
12///
13/// "Is this a UUID" and "is it spelled as IEC 61970-552 requires" are different
14/// questions: `_1fa19c281c8f4e1eaad9e1cab70f923e` (from a published CGMES 2.4.15 boundary
15/// file) *is* a UUID with a `urn:uuid:` form; only its spelling deviates.
16#[derive(Clone, Copy, PartialEq, Eq, Debug)]
17pub enum MridForm {
18    /// The hyphenated `8-4-4-4-12` form IEC 61970-552 requires.
19    Uuid,
20    /// Thirty-two hex digits with no hyphens: a UUID value, non-conforming spelling.
21    Compact,
22    /// Not a UUID at all. Kept verbatim.
23    Opaque,
24}
25
26/// A master resource identifier.
27///
28/// Identifiers that denote a UUID are stored as 16 raw bytes together with the spelling
29/// they arrived in; anything else is kept as text. Either way the *decoration* CIM/XML
30/// puts around an identifier — a leading `#`, a leading `_`, a `urn:uuid:` prefix — is
31/// stripped on parse, so `_abc`, `#_abc` and `urn:uuid:abc` all denote the same object.
32///
33/// Non-conforming identifiers are stripped too, so `rdf:ID="_X"` and `rdf:resource="#_X"`
34/// still join.
35///
36/// # Spelling is remembered, identity is not spelled
37///
38/// Two `Mrid`s denoting the same UUID are equal, hash alike and order alike **whatever
39/// spelling they arrived in**. The spelling is kept only for re-export:
40/// [`Mrid::to_rdf_id`] echoes it, while [`Mrid::canonical`] and [`Mrid::to_urn`] always
41/// give the hyphenated form RFC 4122 defines.
42#[derive(Clone)]
43pub struct Mrid(Repr);
44
45#[derive(Clone)]
46enum Repr {
47    /// A UUID value, stored as raw bytes (align 1, keeping `Mrid` at 24 bytes) with the
48    /// spelling it was read in.
49    ///
50    /// The spelling records hyphenation and per-digit case (a bitmask, since the CGMES
51    /// 2.4.15 boundary set mixes case within one UUID: `_24C12434-E42B-497f-…`). The `u32`
52    /// fits in padding the other variant already forces.
53    Uuid {
54        bytes: [u8; 16],
55        /// Bit `i` set means hex digit `i` was written upper case.
56        case: u32,
57        compact: bool,
58    },
59    /// A non-conforming identifier, stripped of CIM/XML decoration.
60    Other(Box<str>),
61}
62
63/// Identity ignores the spelling: the same UUID written two ways is one object.
64///
65/// `Ord` keeps UUIDs before opaque identifiers and orders UUIDs by their bytes, which is
66/// what makes the writer's output order independent of how a producer spelled things.
67#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
68enum Key<'a> {
69    Uuid(&'a [u8; 16]),
70    Other(&'a str),
71}
72
73impl Mrid {
74    #[inline]
75    fn key(&self) -> Key<'_> {
76        match &self.0 {
77            Repr::Uuid { bytes, .. } => Key::Uuid(bytes),
78            Repr::Other(s) => Key::Other(s),
79        }
80    }
81
82    /// Parse an identifier in any of the forms CIM/XML uses.
83    ///
84    /// Accepts `<uuid>`, `_<uuid>`, `#_<uuid>`, `#<uuid>` and `urn:uuid:<uuid>` in either
85    /// the hyphenated or the compact spelling, as well as arbitrary strings (kept verbatim,
86    /// reported by [`Mrid::form`] as [`MridForm::Opaque`]).
87    ///
88    /// An **absolute IRI whose fragment is a UUID** (`http://host/doc#_<uuid>`, written
89    /// for cross-document references) denotes that UUID. A fragment that is not a UUID
90    /// leaves the whole string opaque.
91    pub fn parse(raw: &str) -> Mrid {
92        let core = strip_decoration(raw);
93        if let Some(m) = parse_uuid(core) {
94            return Mrid(m);
95        }
96        if let Some((_, fragment)) = core.rsplit_once('#')
97            && let Some(m) = parse_uuid(fragment.strip_prefix('_').unwrap_or(fragment))
98        {
99            return Mrid(m);
100        }
101        Mrid(Repr::Other(core.into()))
102    }
103
104    /// Build from raw UUID bytes, spelled the way IEC 61970-552 requires.
105    pub const fn from_uuid_bytes(bytes: [u8; 16]) -> Mrid {
106        Mrid(Repr::Uuid {
107            bytes,
108            case: 0,
109            compact: false,
110        })
111    }
112
113    /// The all-zero UUID, usable in a `const` or `static`.
114    pub const fn nil() -> Mrid {
115        Mrid::from_uuid_bytes([0u8; 16])
116    }
117
118    /// How this identifier was spelled.
119    pub fn form(&self) -> MridForm {
120        match &self.0 {
121            Repr::Uuid { compact: false, .. } => MridForm::Uuid,
122            Repr::Uuid { compact: true, .. } => MridForm::Compact,
123            Repr::Other(_) => MridForm::Opaque,
124        }
125    }
126
127    /// Whether this identifier denotes a UUID, in either spelling.
128    ///
129    /// This is the question the RDF writer asks, because a UUID has a `urn:uuid:` IRI
130    /// whether or not the document hyphenated it. Use [`Mrid::is_conforming`] for the
131    /// stricter question validation asks.
132    pub fn is_uuid(&self) -> bool {
133        matches!(self.0, Repr::Uuid { .. })
134    }
135
136    /// Whether this identifier is written exactly as IEC 61970-552 requires.
137    pub fn is_conforming(&self) -> bool {
138        self.form() == MridForm::Uuid
139    }
140
141    /// Raw UUID bytes, if this identifier denotes a UUID.
142    pub fn as_uuid_bytes(&self) -> Option<&[u8; 16]> {
143        match &self.0 {
144            Repr::Uuid { bytes, .. } => Some(bytes),
145            Repr::Other(_) => None,
146        }
147    }
148
149    /// Canonical lowercase hyphenated form without decoration, e.g. `70c4656c-f7a0-…`.
150    ///
151    /// Always the hyphenated spelling, whichever form the document used — this is the
152    /// identifier's canonical *name*, used for diagnostics and for `urn:uuid:` IRIs.
153    /// Non-conforming identifiers are returned verbatim.
154    pub fn canonical(&self) -> String {
155        match &self.0 {
156            Repr::Uuid { bytes, .. } => format_uuid(bytes, false, 0),
157            Repr::Other(s) => s.to_string(),
158        }
159    }
160
161    /// The identifier as the document spelled it, without decoration.
162    ///
163    /// Differs from [`Mrid::canonical`] for a UUID a producer wrote without hyphens or in
164    /// upper case — both of which the published CGMES 2.4.15 boundary sets do.
165    pub fn as_written(&self) -> String {
166        match &self.0 {
167            Repr::Uuid {
168                bytes,
169                case,
170                compact,
171            } => format_uuid(bytes, *compact, *case),
172            Repr::Other(s) => s.to_string(),
173        }
174    }
175
176    /// The `rdf:ID` form: a leading underscore, as mandated for locally defined objects.
177    ///
178    /// The underscore is added for non-UUID identifiers too, since an `NCName` may not
179    /// begin with a digit. The identifier keeps the spelling it was read with.
180    ///
181    /// Not every identifier this crate can hold has such a form: see [`Mrid::form_in_xml`].
182    pub fn to_rdf_id(&self) -> String {
183        format!("_{}", self.as_written())
184    }
185
186    /// Which RDF/XML serializations this identifier can carry.
187    ///
188    /// A UUID always answers [`IdentifierForm::Name`](crate::xml::IdentifierForm::Name).
189    /// A non-conforming identifier, kept verbatim (see [`MridForm`]), may be neither an
190    /// `NCName` nor an IRI: `rdf:ID="_http://host/EQ.xml#Sub1"` is well-formed XML but
191    /// invalid RDF/XML.
192    pub fn form_in_xml(&self) -> crate::xml::IdentifierForm {
193        match &self.0 {
194            // Every UUID, in either spelling, is a name once the underscore is added.
195            Repr::Uuid { .. } => crate::xml::IdentifierForm::Name,
196            Repr::Other(s) => crate::xml::identifier_form(s),
197        }
198    }
199
200    /// The `rdf:resource` form for a same-document reference: `#_<uuid>`.
201    pub fn to_rdf_resource(&self) -> String {
202        format!("#{}", self.to_rdf_id())
203    }
204
205    /// The value to write into `rdf:resource` or `rdf:about`, in a form RDF/XML accepts.
206    ///
207    /// Same as [`Mrid::to_rdf_resource`] for every name-form identifier (all conforming
208    /// input). An absolute-IRI identifier is written as itself, since `#_http://…#Sub1`
209    /// is not an IRI reference.
210    pub fn to_rdf_reference(&self) -> String {
211        match self.form_in_xml() {
212            crate::xml::IdentifierForm::Iri => self.as_written(),
213            // `Unwritable` has no valid form at all; the conventional one loses least and
214            // `Rule::UnserializableIdentifier` reports that it is not enough.
215            _ => self.to_rdf_resource(),
216        }
217    }
218
219    /// The `urn:uuid:` form used by `md:FullModel` identifiers and by RDF subjects.
220    ///
221    /// Always hyphenated (RFC 4122, RFC 8141). A non-UUID identifier is returned as-is.
222    pub fn to_urn(&self) -> String {
223        match &self.0 {
224            Repr::Uuid { bytes, .. } => format!("urn:uuid:{}", format_uuid(bytes, false, 0)),
225            Repr::Other(s) => s.to_string(),
226        }
227    }
228
229    /// Derive a name-based UUID (RFC 4122 version 5) from a namespace and a name.
230    ///
231    /// Deterministic: the same namespace and name always give the same identifier, with
232    /// no random source or extra dependency.
233    ///
234    /// ```
235    /// # use cim_kit::Mrid;
236    /// let ns = Mrid::parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8"); // RFC 4122 DNS namespace
237    /// let a = Mrid::new_v5(&ns, b"MicroGrid/EQ");
238    /// assert_eq!(a, Mrid::new_v5(&ns, b"MicroGrid/EQ"));
239    /// assert_ne!(a, Mrid::new_v5(&ns, b"MicroGrid/SSH"));
240    /// assert!(a.is_conforming());
241    /// ```
242    pub fn new_v5(namespace: &Mrid, name: &[u8]) -> Mrid {
243        let ns = namespace.as_uuid_bytes().copied().unwrap_or([0u8; 16]);
244        let mut h = Sha1::new();
245        h.update(&ns);
246        h.update(name);
247        let digest = h.finish();
248        let mut bytes = [0u8; 16];
249        bytes.copy_from_slice(&digest[..16]);
250        // Version 5, RFC 4122 variant.
251        bytes[6] = (bytes[6] & 0x0f) | 0x50;
252        bytes[8] = (bytes[8] & 0x3f) | 0x80;
253        Mrid::from_uuid_bytes(bytes)
254    }
255}
256
257impl PartialEq for Mrid {
258    fn eq(&self, other: &Self) -> bool {
259        self.key() == other.key()
260    }
261}
262impl Eq for Mrid {}
263
264impl Hash for Mrid {
265    fn hash<H: Hasher>(&self, state: &mut H) {
266        self.key().hash(state);
267    }
268}
269
270impl PartialOrd for Mrid {
271    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
272        Some(self.cmp(other))
273    }
274}
275
276impl Ord for Mrid {
277    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
278        self.key().cmp(&other.key())
279    }
280}
281
282/// Remove the decorations CIM/XML puts around identifiers.
283///
284/// Comparison is on bytes rather than on `str` slices: an identifier is arbitrary text
285/// from a possibly malformed document, and slicing it at a fixed byte index would panic
286/// whenever that index falls inside a multi-byte character.
287fn strip_decoration(raw: &str) -> &str {
288    const URN: &[u8] = b"urn:uuid:";
289    let s = raw.trim();
290    let s = s.strip_prefix('#').unwrap_or(s);
291    // `urn:uuid:` is case-insensitive per RFC 8141.
292    let s = match s.as_bytes().split_at_checked(URN.len()) {
293        Some((head, _)) if head.eq_ignore_ascii_case(URN) => &s[URN.len()..],
294        _ => s,
295    };
296    s.strip_prefix('_').unwrap_or(s)
297}
298
299/// Parse a UUID in either the hyphenated or the compact spelling, in either case.
300///
301/// Returns the raw bytes and how they were spelled, with case recorded per digit
302/// (published CGMES 2.4.15 files use both spellings and mixed case).
303fn parse_uuid(s: &str) -> Option<Repr> {
304    let b = s.as_bytes();
305    let compact = match b.len() {
306        36 => {
307            if b[8] != b'-' || b[13] != b'-' || b[18] != b'-' || b[23] != b'-' {
308                return None;
309            }
310            false
311        }
312        32 => true,
313        _ => return None,
314    };
315    let mut out = [0u8; 16];
316    let mut case = 0u32;
317    let mut oi = 0;
318    let mut digit = 0;
319    let mut i = 0;
320    while i < b.len() {
321        if b[i] == b'-' {
322            i += 1;
323            continue;
324        }
325        let hi = hex(b[i])?;
326        let lo = hex(*b.get(i + 1)?)?;
327        if b[i].is_ascii_uppercase() {
328            case |= 1 << digit;
329        }
330        if b[i + 1].is_ascii_uppercase() {
331            case |= 1 << (digit + 1);
332        }
333        out[oi] = (hi << 4) | lo;
334        oi += 1;
335        digit += 2;
336        i += 2;
337    }
338    (oi == 16).then_some(Repr::Uuid {
339        bytes: out,
340        case,
341        compact,
342    })
343}
344
345const fn hex(c: u8) -> Option<u8> {
346    match c {
347        b'0'..=b'9' => Some(c - b'0'),
348        b'a'..=b'f' => Some(c - b'a' + 10),
349        b'A'..=b'F' => Some(c - b'A' + 10),
350        _ => None,
351    }
352}
353
354/// Render sixteen bytes, hyphenated or not, with `case` deciding each digit.
355fn format_uuid(b: &[u8; 16], compact: bool, case: u32) -> String {
356    const LOWER: &[u8; 16] = b"0123456789abcdef";
357    const UPPER: &[u8; 16] = b"0123456789ABCDEF";
358    let mut s = String::with_capacity(36);
359    let mut digit = 0;
360    for (i, byte) in b.iter().enumerate() {
361        if !compact && matches!(i, 4 | 6 | 8 | 10) {
362            s.push('-');
363        }
364        for nibble in [byte >> 4, byte & 0x0f] {
365            let table = if case & (1 << digit) != 0 {
366                UPPER
367            } else {
368                LOWER
369            };
370            s.push(table[nibble as usize] as char);
371            digit += 1;
372        }
373    }
374    s
375}
376
377// ---------------------------------------------------------------------------
378// SHA-1, for name-based (version 5) UUIDs
379// ---------------------------------------------------------------------------
380
381/// SHA-1 (FIPS 180-4), used only to derive RFC 4122 version-5 UUIDs.
382///
383/// Vendored to keep a single mandatory dependency. Not for any other use: SHA-1 is broken
384/// for collision resistance.
385struct Sha1 {
386    state: [u32; 5],
387    buf: [u8; 64],
388    len: u64,
389}
390
391impl Sha1 {
392    fn new() -> Sha1 {
393        Sha1 {
394            state: [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0],
395            buf: [0u8; 64],
396            len: 0,
397        }
398    }
399
400    fn update(&mut self, mut data: &[u8]) {
401        let mut fill = (self.len % 64) as usize;
402        self.len += data.len() as u64;
403        while !data.is_empty() {
404            let n = data.len().min(64 - fill);
405            self.buf[fill..fill + n].copy_from_slice(&data[..n]);
406            fill += n;
407            data = &data[n..];
408            if fill == 64 {
409                let block = self.buf;
410                self.compress(&block);
411                fill = 0;
412            }
413        }
414    }
415
416    fn finish(mut self) -> [u8; 20] {
417        let bits = self.len * 8;
418        self.update(&[0x80]);
419        while self.len % 64 != 56 {
420            self.update(&[0]);
421        }
422        self.update(&bits.to_be_bytes());
423        let mut out = [0u8; 20];
424        for (i, w) in self.state.iter().enumerate() {
425            out[i * 4..i * 4 + 4].copy_from_slice(&w.to_be_bytes());
426        }
427        out
428    }
429
430    fn compress(&mut self, block: &[u8; 64]) {
431        let mut w = [0u32; 80];
432        for i in 0..16 {
433            w[i] = u32::from_be_bytes([
434                block[i * 4],
435                block[i * 4 + 1],
436                block[i * 4 + 2],
437                block[i * 4 + 3],
438            ]);
439        }
440        for i in 16..80 {
441            w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1);
442        }
443        let [mut a, mut b, mut c, mut d, mut e] = self.state;
444        for (i, wi) in w.iter().enumerate() {
445            let (f, k) = match i {
446                0..=19 => ((b & c) | (!b & d), 0x5A827999),
447                20..=39 => (b ^ c ^ d, 0x6ED9EBA1),
448                40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1BBCDC),
449                _ => (b ^ c ^ d, 0xCA62C1D6),
450            };
451            let t = a
452                .rotate_left(5)
453                .wrapping_add(f)
454                .wrapping_add(e)
455                .wrapping_add(k)
456                .wrapping_add(*wi);
457            e = d;
458            d = c;
459            c = b.rotate_left(30);
460            b = a;
461            a = t;
462        }
463        for (s, v) in self.state.iter_mut().zip([a, b, c, d, e]) {
464            *s = s.wrapping_add(v);
465        }
466    }
467}
468
469impl fmt::Display for Mrid {
470    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
471        f.write_str(&self.canonical())
472    }
473}
474
475impl fmt::Debug for Mrid {
476    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
477        write!(f, "Mrid({})", self.canonical())
478    }
479}
480
481impl From<&str> for Mrid {
482    fn from(s: &str) -> Mrid {
483        Mrid::parse(s)
484    }
485}
486
487#[cfg(test)]
488mod tests {
489    use super::*;
490
491    const CANON: &str = "70c4656c-f7a0-4319-98bb-84fb5e2e9b37";
492    const COMPACT: &str = "70c4656cf7a0431998bb84fb5e2e9b37";
493
494    #[test]
495    fn all_serialized_forms_are_the_same_identifier() {
496        let forms = [
497            CANON,
498            "_70c4656c-f7a0-4319-98bb-84fb5e2e9b37",
499            "#_70c4656c-f7a0-4319-98bb-84fb5e2e9b37",
500            "#70c4656c-f7a0-4319-98bb-84fb5e2e9b37",
501            "urn:uuid:70c4656c-f7a0-4319-98bb-84fb5e2e9b37",
502            "URN:UUID:70c4656c-f7a0-4319-98bb-84fb5e2e9b37",
503            // 61970-552 mandates lowercase, but uppercase occurs in the wild.
504            "_70C4656C-F7A0-4319-98BB-84FB5E2E9B37",
505        ];
506        for f in forms {
507            let m = Mrid::parse(f);
508            assert!(m.is_uuid(), "{f} should parse as a UUID");
509            assert!(m.is_conforming(), "{f} is written conformingly");
510            assert_eq!(m.canonical(), CANON, "{f}");
511            assert_eq!(m, Mrid::parse(CANON), "{f}");
512        }
513    }
514
515    #[test]
516    fn serialization_forms_round_trip() {
517        let m = Mrid::parse(CANON);
518        assert_eq!(m.to_rdf_id(), format!("_{CANON}"));
519        assert_eq!(m.to_rdf_resource(), format!("#_{CANON}"));
520        assert_eq!(m.to_urn(), format!("urn:uuid:{CANON}"));
521        assert_eq!(Mrid::parse(&m.to_rdf_resource()), m);
522    }
523
524    /// Published CGMES 2.4.15 files write UUIDs without hyphens. They are still UUIDs.
525    #[test]
526    fn a_compact_uuid_is_the_same_identifier_as_its_hyphenated_spelling() {
527        let compact = Mrid::parse("_1fa19c281c8f4e1eaad9e1cab70f923e");
528        let hyphenated = Mrid::parse("#_1fa19c28-1c8f-4e1e-aad9-e1cab70f923e");
529
530        // Same object: a boundary file and an equipment file referring to it must join.
531        assert_eq!(compact, hyphenated);
532        assert_eq!(
533            std::collections::HashSet::from([compact.clone(), hyphenated.clone()]).len(),
534            1
535        );
536
537        // Both denote a UUID, so both have a `urn:uuid:` IRI — which is what keeps them
538        // out of the blank-node path in the RDF writer.
539        assert!(compact.is_uuid());
540        assert_eq!(compact.to_urn(), hyphenated.to_urn());
541        assert_eq!(compact.canonical(), hyphenated.canonical());
542
543        // Only the spelling differs, and only the spelling is preserved on export.
544        assert_eq!(compact.form(), MridForm::Compact);
545        assert_eq!(hyphenated.form(), MridForm::Uuid);
546        assert!(!compact.is_conforming());
547        assert!(hyphenated.is_conforming());
548        assert_eq!(compact.to_rdf_id(), "_1fa19c281c8f4e1eaad9e1cab70f923e");
549        assert_eq!(
550            hyphenated.to_rdf_id(),
551            "_1fa19c28-1c8f-4e1e-aad9-e1cab70f923e"
552        );
553    }
554
555    /// The CGMES 2.4.15 boundary set writes upper-case UUIDs; export must keep the text,
556    /// which tools such as PowSyBl use as the identifier.
557    #[test]
558    fn an_uppercase_uuid_keeps_its_case_on_export_but_not_its_identity() {
559        const UPPER: &str = "1C405140-0F45-4534-9C90-F38F4905362C";
560        const LOWER: &str = "1c405140-0f45-4534-9c90-f38f4905362c";
561        let u = Mrid::parse(UPPER);
562        let l = Mrid::parse(LOWER);
563
564        // One object, whichever case it arrived in.
565        assert_eq!(u, l);
566        assert_eq!(
567            std::collections::HashSet::from([u.clone(), l.clone()]).len(),
568            1
569        );
570
571        // Written back as it came in, so re-export reproduces the document.
572        assert_eq!(u.as_written(), UPPER);
573        assert_eq!(u.to_rdf_id(), format!("_{UPPER}"));
574        assert_eq!(l.as_written(), LOWER);
575
576        // But the canonical name is always lower case, because RFC 4122 defines no other.
577        assert_eq!(u.canonical(), LOWER);
578        assert_eq!(u.to_urn(), format!("urn:uuid:{LOWER}"));
579        assert_eq!(u.to_urn(), l.to_urn());
580
581        // Upper case survives the compact spelling and the fragment path too.
582        let compact = Mrid::parse("_1C4051400F4545349C90F38F4905362C");
583        assert_eq!(compact, u);
584        assert_eq!(compact.as_written(), "1C4051400F4545349C90F38F4905362C");
585        assert_eq!(
586            Mrid::parse(&format!("http://host/EQ.xml#_{UPPER}")).as_written(),
587            UPPER
588        );
589
590        // Mixed case is not hypothetical: this identifier is from the published CGMES
591        // 2.4.15 boundary set, and the `497f` inside it is lower case while the rest is
592        // not. Per-digit fidelity is what this test exists for — a single upper/lower flag
593        // rewrites it, and rewriting it is what PowSyBl noticed.
594        const MIXED: &str = "24C12434-E42B-497f-928F-119C6AE92079";
595        let m = Mrid::parse(MIXED);
596        assert_eq!(m.as_written(), MIXED);
597        assert_eq!(m.canonical(), MIXED.to_ascii_lowercase());
598        assert_eq!(Mrid::parse(&m.to_rdf_id()), m);
599        assert_eq!(m, Mrid::parse(&MIXED.to_ascii_lowercase()));
600    }
601
602    /// The spelling rides in padding the pointer variant already forced, so remembering it
603    /// costs nothing per identifier — and a model holds one per object plus one per
604    /// reference, which is where a byte would have been felt.
605    #[test]
606    fn remembering_the_spelling_does_not_grow_an_identifier() {
607        assert!(
608            std::mem::size_of::<Mrid>() <= 24,
609            "Mrid grew to {} bytes",
610            std::mem::size_of::<Mrid>()
611        );
612    }
613
614    #[test]
615    fn compact_and_hyphenated_spellings_survive_a_round_trip_each() {
616        for raw in [CANON, COMPACT] {
617            let m = Mrid::parse(raw);
618            assert!(m.is_uuid(), "{raw}");
619            assert_eq!(m.as_written(), raw, "{raw}");
620            assert_eq!(Mrid::parse(&m.to_rdf_id()), m, "{raw}");
621            assert_eq!(Mrid::parse(&m.to_rdf_resource()), m, "{raw}");
622        }
623        assert_eq!(Mrid::parse(CANON), Mrid::parse(COMPACT));
624    }
625
626    /// Producers write cross-document references as absolute IRIs. The fragment is the
627    /// object; reading the whole IRI as opaque text dangles a reference against an object
628    /// that is present in the model.
629    #[test]
630    fn an_absolute_iri_denotes_the_uuid_in_its_fragment() {
631        for raw in [
632            "http://example.com/model#_70c4656c-f7a0-4319-98bb-84fb5e2e9b37",
633            "http://example.com/model#70c4656c-f7a0-4319-98bb-84fb5e2e9b37",
634            "file:///models/EQ.xml#_70c4656c-f7a0-4319-98bb-84fb5e2e9b37",
635        ] {
636            let m = Mrid::parse(raw);
637            assert!(m.is_uuid(), "{raw}");
638            assert_eq!(m, Mrid::parse(CANON), "{raw}");
639        }
640        // The compact spelling survives the fragment path too, and stays compact.
641        let compact = Mrid::parse(&format!("http://example.com/m#_{COMPACT}"));
642        assert_eq!(compact.form(), MridForm::Compact);
643        assert_eq!(compact, Mrid::parse(CANON));
644
645        // Nothing is invented: a fragment that is not a UUID leaves the identifier opaque,
646        // and so does a document IRI with no fragment at all.
647        for raw in [
648            "http://example.com/model#Substation",
649            "http://example.com/model",
650            "http://example.com/a#b#c",
651        ] {
652            assert!(!Mrid::parse(raw).is_uuid(), "{raw}");
653        }
654    }
655
656    #[test]
657    fn non_conforming_identifiers_keep_their_value_but_lose_decoration() {
658        for raw in ["not-a-uuid", "12345", "garbage"] {
659            let m = Mrid::parse(raw);
660            assert!(!m.is_uuid(), "{raw:?}");
661            assert_eq!(m.form(), MridForm::Opaque);
662            assert_eq!(m.canonical(), raw);
663            // Output uses the conforming form; re-reading gives the same identifier.
664            assert_eq!(m.to_rdf_id(), format!("_{raw}"));
665            assert_eq!(Mrid::parse(&m.to_rdf_id()), m);
666            assert_eq!(Mrid::parse(&m.to_rdf_resource()), m);
667        }
668    }
669
670    #[test]
671    fn non_ascii_identifiers_do_not_panic() {
672        // Decoration stripping must not slice a `str` at a fixed byte index: an
673        // identifier is arbitrary text from a possibly malformed document, and byte 9
674        // of these falls inside a multi-byte character.
675        for raw in [
676            "12345678é",
677            "urn:uuiδ:x",
678            "########é",
679            "é",
680            "ééééé",
681            "#_ééééé",
682            "urn:uuid:é",
683            // Exactly 32 bytes, but not 32 hex digits: the compact form's length test is
684            // in bytes, so what follows it must check each byte rather than assume.
685            "éééééééééééééééé",
686        ] {
687            let m = Mrid::parse(raw);
688            assert!(!m.is_uuid(), "{raw:?}");
689            // Whatever survives stripping must still round-trip through the wire forms.
690            assert_eq!(Mrid::parse(&m.to_rdf_id()), m, "{raw:?}");
691        }
692    }
693
694    #[test]
695    fn malformed_uuids_do_not_parse_as_uuid() {
696        for raw in [
697            "70c4656c-f7a0-4319-98bb-84fb5e2e9b3",   // too short
698            "70c4656c-f7a0-4319-98bb-84fb5e2e9b377", // too long
699            "70c4656cxf7a0-4319-98bb-84fb5e2e9b37",  // wrong separator
700            "70c4656c-f7a0-4319-98bb-84fb5e2e9bzz",  // non-hex
701            "70c4656cf7a0431998bb84fb5e2e9b3",       // 31 hex digits
702            "70c4656cf7a0431998bb84fb5e2e9bzz",      // 32 characters, not all hex
703        ] {
704            assert!(!Mrid::parse(raw).is_uuid(), "{raw}");
705        }
706    }
707
708    /// RFC 4122 §Appendix B publishes this vector for the DNS namespace and "www.example.org".
709    #[test]
710    fn version_5_uuids_match_the_published_test_vector() {
711        let dns = Mrid::parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8");
712        let m = Mrid::new_v5(&dns, b"www.example.org");
713        assert_eq!(m.canonical(), "74738ff5-5367-5958-9aee-98fffdcd1876");
714        assert!(m.is_conforming());
715        // Deterministic, and distinct for distinct names.
716        assert_eq!(m, Mrid::new_v5(&dns, b"www.example.org"));
717        assert_ne!(m, Mrid::new_v5(&dns, b"www.example.com"));
718    }
719
720    #[test]
721    fn sha1_matches_its_published_vectors() {
722        let hex = |d: [u8; 20]| d.iter().map(|b| format!("{b:02x}")).collect::<String>();
723        let mut h = Sha1::new();
724        assert_eq!(hex(h.finish()), "da39a3ee5e6b4b0d3255bfef95601890afd80709");
725        h = Sha1::new();
726        h.update(b"abc");
727        assert_eq!(hex(h.finish()), "a9993e364706816aba3e25717850c26c9cd0d89d");
728        // Multi-block, exercising the buffering path.
729        h = Sha1::new();
730        for _ in 0..1_000_000 {
731            h.update(b"a");
732        }
733        assert_eq!(hex(h.finish()), "34aa973cd4c4daa4f61eeb2bdbad27316534016f");
734    }
735}