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