Skip to main content

cim_kit/
schema.rs

1//! Runtime schema metadata.
2//!
3//! The generated code under [`crate::cgmes3`] fills in the static tables declared here.
4//! Everything else in the crate — reader, writer, validator, typed views — is written
5//! against this interface, so a new CIM vintage is a regeneration rather than a rewrite.
6
7use std::fmt;
8
9/// Set of profiles, as a bitmask over [`Schema::profiles`].
10///
11/// 64 bits rather than 32 because a profile set is not fixed at the eleven CGMES 3.0
12/// vocabularies. ENTSO-E publishes eighteen Network Code profiles in exactly the same
13/// RDFS form, and the generator treats a profile as data precisely so that those and
14/// bespoke ones can be added; twenty-nine published profiles leave no room for the
15/// custom profiles the design promises to accept.
16pub type ProfileMask = u64;
17
18macro_rules! id_type {
19    ($(#[$m:meta])* $name:ident) => {
20        $(#[$m])*
21        #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
22        pub struct $name(pub u16);
23
24        impl $name {
25            #[inline]
26            pub const fn index(self) -> usize {
27                self.0 as usize
28            }
29        }
30
31        impl fmt::Debug for $name {
32            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33                write!(f, concat!(stringify!($name), "({})"), self.0)
34            }
35        }
36    };
37}
38
39id_type!(
40    /// Index of a class in [`Schema::classes`].
41    ClassId
42);
43id_type!(
44    /// Index of an attribute or association in [`Schema::attributes`].
45    AttrId
46);
47id_type!(
48    /// Index of an enumeration in [`Schema::enums`].
49    EnumId
50);
51id_type!(
52    /// Index of an enumeration literal in [`Schema::enum_values`].
53    EnumValueId
54);
55id_type!(
56    /// Index of a CIM datatype in [`Schema::datatypes`].
57    DatatypeId
58);
59id_type!(
60    /// Index of a profile in [`Schema::profiles`].
61    ProfileId
62);
63id_type!(
64    /// Index of a namespace in [`Schema::namespaces`].
65    NsId
66);
67
68impl ProfileId {
69    /// How many profiles one schema may hold, which is [`ProfileMask`]'s width.
70    pub const MAX_PROFILES: usize = ProfileMask::BITS as usize;
71
72    /// This profile as a single-bit mask.
73    ///
74    /// # Panics
75    ///
76    /// If the profile index is at or beyond [`ProfileId::MAX_PROFILES`]. The alternative is
77    /// worse and is what a bare shift gives: Rust masks an over-wide shift in release
78    /// builds, so profile 64 would silently *alias* profile 0 — every filtering decision in
79    /// the writer, the differ and the RDF export would then quietly attribute one profile's
80    /// data to another. A schema this large is a generator defect rather than a caller's
81    /// mistake, and `schemas_fit_the_profile_mask` in `tests/schema.rs` makes it a test
82    /// failure before it can ever be a panic.
83    #[inline]
84    pub const fn mask(self) -> ProfileMask {
85        assert!(
86            (self.0 as usize) < ProfileId::MAX_PROFILES,
87            "profile index exceeds the width of ProfileMask; widen the type"
88        );
89        1 << self.0
90    }
91}
92
93/// A CIM primitive type (IEC 61970-301).
94#[derive(Clone, Copy, PartialEq, Eq, Debug)]
95pub enum Primitive {
96    String,
97    Integer,
98    Float,
99    Decimal,
100    Boolean,
101    Date,
102    DateTime,
103    MonthDay,
104    Time,
105    Duration,
106    Uri,
107}
108
109impl Primitive {
110    /// The XML Schema datatype IRI this primitive's values carry in RDF.
111    ///
112    /// CIM/XML exchanges no datatype information — every value is element text — so this
113    /// mapping is the only thing that can supply one, and it has to agree with the shapes
114    /// a consumer will validate against. It is taken from ENTSO-E's own published SHACL:
115    /// of the 3,137 `sh:datatype` constraints in the CGMES 3.0 shapes, 2,871 name
116    /// `xsd:float`, which is why CIM `Float` maps to `xsd:float` and not to the
117    /// `xsd:double` a 64-bit representation would suggest.
118    ///
119    /// [`Primitive::String`] returns the empty string: RDF 1.1 gives a literal with no
120    /// datatype the type `xsd:string` already, so writing one would be redundant.
121    pub const fn xsd_datatype(self) -> &'static str {
122        match self {
123            Primitive::String => "",
124            Primitive::Integer => "http://www.w3.org/2001/XMLSchema#integer",
125            Primitive::Float => "http://www.w3.org/2001/XMLSchema#float",
126            Primitive::Decimal => "http://www.w3.org/2001/XMLSchema#decimal",
127            Primitive::Boolean => "http://www.w3.org/2001/XMLSchema#boolean",
128            Primitive::Date => "http://www.w3.org/2001/XMLSchema#date",
129            Primitive::DateTime => "http://www.w3.org/2001/XMLSchema#dateTime",
130            Primitive::MonthDay => "http://www.w3.org/2001/XMLSchema#gMonthDay",
131            Primitive::Time => "http://www.w3.org/2001/XMLSchema#time",
132            Primitive::Duration => "http://www.w3.org/2001/XMLSchema#duration",
133            Primitive::Uri => "http://www.w3.org/2001/XMLSchema#anyURI",
134        }
135    }
136}
137
138/// Attribute cardinality as declared by `cims:multiplicity`.
139#[derive(Clone, Copy, PartialEq, Eq, Debug)]
140pub enum Mult {
141    /// `0..1`
142    Optional,
143    /// `1..1`
144    Required,
145    /// `0..n`
146    Many,
147    /// `1..n`
148    ManyRequired,
149    /// A bounded range such as `0..2`.
150    Bounded { min: u32, max: u32 },
151}
152
153impl Mult {
154    #[inline]
155    pub const fn is_many(self) -> bool {
156        matches!(self, Mult::Many | Mult::ManyRequired | Mult::Bounded { .. })
157    }
158    #[inline]
159    pub const fn is_required(self) -> bool {
160        match self {
161            Mult::Required | Mult::ManyRequired => true,
162            Mult::Bounded { min, .. } => min > 0,
163            Mult::Optional | Mult::Many => false,
164        }
165    }
166    #[inline]
167    pub const fn min(self) -> u32 {
168        match self {
169            Mult::Optional | Mult::Many => 0,
170            Mult::Required | Mult::ManyRequired => 1,
171            Mult::Bounded { min, .. } => min,
172        }
173    }
174    #[inline]
175    pub const fn max(self) -> u32 {
176        match self {
177            Mult::Optional | Mult::Required => 1,
178            Mult::Many | Mult::ManyRequired => u32::MAX,
179            Mult::Bounded { max, .. } => max,
180        }
181    }
182}
183
184/// What an attribute holds.
185#[derive(Clone, Copy, PartialEq, Eq, Debug)]
186pub enum AttrKind {
187    /// A plain primitive value.
188    Primitive(Primitive),
189    /// A unit-carrying CIM datatype such as `Resistance`; serialized as its primitive.
190    Datatype(DatatypeId),
191    /// An enumeration; serialized as `rdf:resource` pointing at `Enum.literal`.
192    Enumeration(EnumId),
193    /// A structured value with no identity of its own (`cims:stereotype Compound`).
194    ///
195    /// IEC 61970-552 gives compounds no `rdf:ID`, so they are written *inside* the
196    /// property element as `rdf:parseType="Resource"` rather than referenced. The
197    /// [`ClassId`] names the compound's type, whose attributes describe its fields.
198    Compound(ClassId),
199    /// A reference to another object; serialized as `rdf:resource` to its mRID.
200    Association {
201        target: ClassId,
202        /// The opposite role, when the schema declares `cims:inverseRoleName`.
203        inverse: Option<AttrId>,
204    },
205}
206
207#[derive(Debug)]
208pub struct NamespaceDef {
209    /// Namespace IRI including the trailing `#`.
210    pub iri: &'static str,
211    /// Conventional prefix used when writing, e.g. `cim`, `eu`.
212    pub prefix: &'static str,
213}
214
215#[derive(Debug)]
216pub struct ProfileDef {
217    /// Short keyword, e.g. `EQ`, `SSH`.
218    pub keyword: &'static str,
219    /// Canonical IRI, written as `md:Model.profile` on export.
220    pub version_iri: &'static str,
221    /// Further IRIs that also denote this profile when read.
222    ///
223    /// Published models name profiles by IRIs that changed between revisions, and some
224    /// profiles have more than one accepted form.
225    pub aliases: &'static [&'static str],
226    pub title: &'static str,
227}
228
229impl ProfileDef {
230    /// Whether `iri` denotes this profile, ignoring the trailing version segment.
231    pub fn matches_iri(&self, iri: &str) -> bool {
232        if self.version_iri == iri || self.aliases.contains(&iri) {
233            return true;
234        }
235        fn stem(s: &str) -> Option<&str> {
236            s.rsplit_once('/').map(|(a, _)| a)
237        }
238        let Some(want) = stem(iri) else { return false };
239        stem(self.version_iri) == Some(want) || self.aliases.iter().any(|a| stem(a) == Some(want))
240    }
241}
242
243#[derive(Debug)]
244pub struct ClassDef {
245    /// Local name, e.g. `ACLineSegment`.
246    pub name: &'static str,
247    pub ns: NsId,
248    /// Direct superclass, if any.
249    pub parent: Option<ClassId>,
250    /// Whether instances of this class may appear in an instance document.
251    pub concrete: bool,
252    /// Profiles whose vocabulary declares this class.
253    ///
254    /// This is declaration, not reach: an instance may still carry another profile's
255    /// data through an inherited attribute — a Steady State Hypothesis file sets
256    /// `Equipment.inService` on a `BusbarSection` that only the Equipment profile
257    /// declares. Use an object's stored values to decide what a profile export contains.
258    pub profiles: ProfileMask,
259    /// Profiles whose vocabulary *defines* this class rather than only referring to it.
260    ///
261    /// IEC 61970-552 distinguishes the file that introduces an object (`rdf:ID`) from a
262    /// file that adds to an object defined elsewhere (`rdf:about`), and the RDFS records
263    /// which is which by marking the latter with `cims:stereotype Description`. Steady
264    /// State Hypothesis marks every class it touches; State Variables marks only
265    /// `CsConverter` and `VsConverter`, which is why published SV files identify
266    /// `SvPowerFlow` with `rdf:ID`. [`IdStyle::Auto`](crate::writer::IdStyle::Auto) reads
267    /// this field.
268    pub defined_in: ProfileMask,
269    /// Profiles that declare this class `concrete`, i.e. may hold instances of it.
270    ///
271    /// Narrower than [`ClassDef::defined_in`], and deliberately so. `defined_in` answers
272    /// "did this file introduce the object", which decides `rdf:ID` versus `rdf:about` and
273    /// must tolerate published files that instantiate a class their own profile declares
274    /// abstract. `concrete_in` answers "may this profile hold such an instance at all",
275    /// which is what tells validation whether the file that would carry an object's
276    /// mandatory attributes is loaded.
277    pub concrete_in: ProfileMask,
278    pub deprecated: bool,
279    /// Whether this class is a compound value type without identity.
280    ///
281    /// Compounds are written inline inside the property that holds them and never carry
282    /// an `rdf:ID`, so they cannot appear as top-level objects.
283    pub compound: bool,
284    /// Attributes declared directly on this class.
285    pub own_attrs: &'static [AttrId],
286    /// Every attribute visible on this class, inherited ones first (root-first order).
287    pub all_attrs: &'static [AttrId],
288    /// Transitive superclasses, nearest parent first.
289    pub ancestors: &'static [ClassId],
290    /// This class and every class inheriting from it, in schema order.
291    pub descendants: &'static [ClassId],
292    pub doc: &'static str,
293}
294
295#[derive(Debug)]
296pub struct AttrDef {
297    /// Qualified local name as serialized, e.g. `ACLineSegment.r`.
298    pub name: &'static str,
299    /// Short name, e.g. `r`.
300    pub label: &'static str,
301    pub ns: NsId,
302    /// The class on which the attribute is declared.
303    pub owner: ClassId,
304    pub kind: AttrKind,
305    pub mult: Mult,
306    /// Profiles in which this attribute exists.
307    pub profiles: ProfileMask,
308    /// For associations, the profiles in which *this* side is the serialized one
309    /// (`cims:AssociationUsed = Yes`). Always equal to `profiles` for plain attributes.
310    pub used_in: ProfileMask,
311    pub deprecated: bool,
312    /// A value the schema pins via `cims:isFixed`.
313    pub fixed: Option<&'static str>,
314    pub doc: &'static str,
315}
316
317impl AttrDef {
318    /// Whether this attribute is written when serializing `profile`.
319    #[inline]
320    pub const fn is_serialized_in(&self, profile: ProfileId) -> bool {
321        self.used_in & profile.mask() != 0
322    }
323}
324
325#[derive(Debug)]
326pub struct EnumDef {
327    pub name: &'static str,
328    pub ns: NsId,
329    pub profiles: ProfileMask,
330    pub values: &'static [EnumValueId],
331    pub doc: &'static str,
332}
333
334#[derive(Debug)]
335pub struct EnumValueDef {
336    /// Qualified name as serialized, e.g. `PhaseCode.ABCN`.
337    pub name: &'static str,
338    /// Literal name, e.g. `ABCN`.
339    pub label: &'static str,
340    pub ns: NsId,
341    pub owner: EnumId,
342    pub doc: &'static str,
343}
344
345#[derive(Debug)]
346pub struct DatatypeDef {
347    pub name: &'static str,
348    pub ns: NsId,
349    /// The primitive actually serialized for this datatype.
350    pub value: Primitive,
351    /// Fixed `UnitSymbol`, e.g. `W` for `ActivePower`.
352    pub unit: Option<&'static str>,
353    /// Fixed `UnitMultiplier`, e.g. `M` (mega) for `ActivePower`.
354    pub multiplier: Option<&'static str>,
355    pub doc: &'static str,
356}
357
358/// A complete CIM schema vintage.
359pub struct Schema {
360    /// Vintage key, e.g. `cgmes3`.
361    pub vintage: &'static str,
362    pub namespaces: &'static [NamespaceDef],
363    pub profiles: &'static [ProfileDef],
364    pub classes: &'static [ClassDef],
365    pub attributes: &'static [AttrDef],
366    pub enums: &'static [EnumDef],
367    pub enum_values: &'static [EnumValueDef],
368    pub datatypes: &'static [DatatypeDef],
369    /// `(ns index, local name)` sorted, for binary-search lookup of classes.
370    pub class_index: &'static [(u16, &'static str, ClassId)],
371    /// `(ns index, qualified name)` sorted, for attribute lookup.
372    pub attr_index: &'static [(u16, &'static str, AttrId)],
373    /// `(ns index, qualified name)` sorted, for enum literal lookup.
374    pub enum_value_index: &'static [(u16, &'static str, EnumValueId)],
375}
376
377impl fmt::Debug for Schema {
378    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
379        f.debug_struct("Schema")
380            .field("vintage", &self.vintage)
381            .field("profiles", &self.profiles.len())
382            .field("classes", &self.classes.len())
383            .field("attributes", &self.attributes.len())
384            .finish()
385    }
386}
387
388impl Schema {
389    #[inline]
390    pub fn class(&self, id: ClassId) -> &'static ClassDef {
391        &self.classes[id.index()]
392    }
393    #[inline]
394    pub fn attr(&self, id: AttrId) -> &'static AttrDef {
395        &self.attributes[id.index()]
396    }
397    #[inline]
398    pub fn enumeration(&self, id: EnumId) -> &'static EnumDef {
399        &self.enums[id.index()]
400    }
401    #[inline]
402    pub fn enum_value(&self, id: EnumValueId) -> &'static EnumValueDef {
403        &self.enum_values[id.index()]
404    }
405    #[inline]
406    pub fn datatype(&self, id: DatatypeId) -> &'static DatatypeDef {
407        &self.datatypes[id.index()]
408    }
409    #[inline]
410    pub fn profile(&self, id: ProfileId) -> &'static ProfileDef {
411        &self.profiles[id.index()]
412    }
413    #[inline]
414    pub fn namespace(&self, id: NsId) -> &'static NamespaceDef {
415        &self.namespaces[id.index()]
416    }
417
418    pub fn ns_id(&self, iri: &str) -> Option<NsId> {
419        self.namespaces
420            .iter()
421            .position(|n| n.iri == iri)
422            .map(|i| NsId(i as u16))
423    }
424
425    pub fn profile_by_keyword(&self, keyword: &str) -> Option<ProfileId> {
426        self.profiles
427            .iter()
428            .position(|p| p.keyword.eq_ignore_ascii_case(keyword))
429            .map(|i| ProfileId(i as u16))
430    }
431
432    /// Resolve the `md:Model.profile` IRI written in an instance file header.
433    ///
434    /// The trailing version segment is ignored so that, for example, a file declaring
435    /// `.../CoreEquipment-EU/3.0` still resolves when the schema knows `/3.0`.
436    pub fn profile_by_iri(&self, iri: &str) -> Option<ProfileId> {
437        // Exact matches first, so an alias never shadows a profile's own IRI.
438        self.profiles
439            .iter()
440            .position(|p| p.version_iri == iri)
441            .or_else(|| self.profiles.iter().position(|p| p.aliases.contains(&iri)))
442            .or_else(|| self.profiles.iter().position(|p| p.matches_iri(iri)))
443            .map(|i| ProfileId(i as u16))
444    }
445
446    /// Look up a class by namespace IRI and local name.
447    pub fn find_class(&self, ns: &str, local: &str) -> Option<ClassId> {
448        let ns = self.ns_id(ns)?.0;
449        binary_search(self.class_index, ns, local)
450    }
451
452    /// Look up a class by local name in whichever namespace declares it.
453    ///
454    /// For tooling that must work across vintages without knowing their namespaces:
455    /// `Substation` lives in `CIM100` in CGMES 3.0 and in `cim16` in CGMES 2.4.15, and a
456    /// program that only wants to count substations should not have to spell either. Where
457    /// two namespaces declare the same local name — an extension shadowing a core class —
458    /// the first in namespace order wins, so [`Schema::find_class`] is the call to reach
459    /// for when the distinction matters.
460    pub fn class_by_name(&self, local: &str) -> Option<ClassId> {
461        self.class_index
462            .iter()
463            .find(|(_, name, _)| *name == local)
464            .map(|(_, _, id)| *id)
465    }
466
467    /// Look up an attribute by namespace IRI and qualified name (`Class.attr`).
468    pub fn find_attr(&self, ns: &str, qualified: &str) -> Option<AttrId> {
469        let ns = self.ns_id(ns)?.0;
470        binary_search(self.attr_index, ns, qualified)
471    }
472
473    /// Look up an enumeration literal by namespace IRI and qualified name.
474    pub fn find_enum_value(&self, ns: &str, qualified: &str) -> Option<EnumValueId> {
475        let ns = self.ns_id(ns)?.0;
476        binary_search(self.enum_value_index, ns, qualified)
477    }
478
479    /// Look up an enumeration literal by qualified name in any namespace.
480    ///
481    /// Exporters do misplace these: published CGMES 2.4.15 test models write the
482    /// ENTSO-E extension literal `LimitTypeKind.patl` under the `cim` namespace. The
483    /// qualified name is unambiguous on its own, so the value can still be recovered —
484    /// callers should report the namespace mismatch rather than accept it silently.
485    pub fn find_enum_value_any_ns(&self, qualified: &str) -> Option<EnumValueId> {
486        self.enum_value_index
487            .iter()
488            .find(|(_, name, _)| *name == qualified)
489            .map(|(_, _, id)| *id)
490    }
491
492    /// Whether `class` is `ancestor` or inherits from it.
493    pub fn is_a(&self, class: ClassId, ancestor: ClassId) -> bool {
494        class == ancestor || self.class(class).ancestors.contains(&ancestor)
495    }
496
497    /// Find an attribute visible on `class` by its short label.
498    ///
499    /// Searches the class and its ancestors, most-derived first.
500    pub fn attr_by_label(&self, class: ClassId, label: &str) -> Option<AttrId> {
501        self.class(class)
502            .all_attrs
503            .iter()
504            .rev()
505            .copied()
506            .find(|&a| self.attr(a).label == label)
507    }
508
509    /// The profiles a stored value belongs in — the single rule the writer and the
510    /// per-profile coverage report share, so the report cannot drift from the export.
511    ///
512    /// `provenance` is the profile mask recorded on the value when it was read (zero for
513    /// values set programmatically). It is *intersected* with the profiles that actually
514    /// declare the attribute, because one instance file routinely declares several
515    /// profiles: a CGMES 3.0 Equipment file commonly declares both `CoreEquipment` and
516    /// `ShortCircuit`, and without the intersection every value in it would be written to
517    /// both exports, duplicating the whole file.
518    ///
519    /// The intersection can be empty, because published files do set attributes their own
520    /// header does not declare — a CGMES 2.4.15 boundary file writes
521    /// `Terminal.ConnectivityNode`, which only the Equipment profile declares. When that
522    /// happens the value goes back where it came from: the data is evidence, the
523    /// vocabulary is a claim about it, and re-filing the value under a profile its source
524    /// does not serve would drop it from every export. [`validate`](mod@crate::validate)
525    /// reports the discrepancy as [`Rule::AttributeNotInProfile`](crate::Rule).
526    ///
527    /// Only a value with no provenance at all — one set programmatically — falls back to
528    /// the attribute's declaration, which is then the sole available answer.
529    pub fn effective_profiles(&self, attr: AttrId, provenance: ProfileMask) -> ProfileMask {
530        let declared = self.attr(attr).used_in;
531        match provenance & declared {
532            0 if provenance != 0 => provenance,
533            0 => declared,
534            narrowed => narrowed,
535        }
536    }
537
538    /// Whether a value's source file declared a profile that declares its attribute.
539    ///
540    /// False means the file under-declares its own content: it carries data belonging to
541    /// a profile its `md:Model.profile` does not name. Published models do this — the
542    /// `RealGrid` Equipment file carries ShortCircuit attributes while declaring only
543    /// `CoreEquipment` — so it is a warning about the header, not a reason to lose data.
544    pub fn declaration_covers(&self, attr: AttrId, provenance: ProfileMask) -> bool {
545        provenance == 0 || self.attr(attr).used_in & provenance != 0
546    }
547
548    /// How strongly a document declaring `namespaces` looks like this vintage.
549    ///
550    /// The number of this vintage's classes that live in namespaces the document declares.
551    ///
552    /// Weighted by class count rather than by namespace, because every namespace a schema
553    /// knows holds at least one class — the 61970-552 header vocabulary puts classes in
554    /// `md`, `dm` and even `rdf` — so presence alone discriminates nothing. Bulk does:
555    /// `CIM100#` holds 436 classes against `rdf`'s one, so a CGMES 2.4.15 document scores
556    /// 400 for 2.4.15 and 3 for 3.0.
557    pub fn match_score<'a>(&self, namespaces: impl IntoIterator<Item = &'a str>) -> usize {
558        let declared: Vec<&str> = namespaces.into_iter().collect();
559        let wanted: Vec<NsId> = self
560            .namespaces
561            .iter()
562            .enumerate()
563            .filter(|(_, n)| declared.contains(&n.iri))
564            .map(|(i, _)| NsId(i as u16))
565            .collect();
566        self.classes
567            .iter()
568            .filter(|c| wanted.contains(&c.ns))
569            .count()
570    }
571
572    /// The compiled-in vintage a document declaring `namespaces` belongs to.
573    ///
574    /// CIM/XML names its vocabulary in the document — `xmlns:cim="…/CIM100#"` for CGMES 3.0,
575    /// `"…/CIM-schema-cim16#"` for 2.4.15 — so the caller never has to guess, and guessing
576    /// wrong is expensive: reading a 2.4.15 file against the CGMES 3.0 tables resolves no
577    /// class at all and yields an empty model with one "unknown class" warning per element.
578    ///
579    /// Returns `None` when nothing in the document points at any compiled-in vintage, which
580    /// is the honest answer for a build without the matching feature.
581    ///
582    /// See [`reader::sniff`](crate::reader::sniff), which answers this from a document's
583    /// root element without parsing the rest.
584    pub fn detect<'a>(namespaces: impl IntoIterator<Item = &'a str>) -> Option<&'static Schema> {
585        let declared: Vec<&str> = namespaces.into_iter().collect();
586        crate::VINTAGES
587            .iter()
588            .map(|s| (s.match_score(declared.iter().copied()), *s))
589            .filter(|(score, _)| *score > 0)
590            .max_by_key(|(score, _)| *score)
591            .map(|(_, s)| s)
592    }
593
594    /// Every concrete class, useful for tooling that enumerates the model.
595    pub fn concrete_classes(&self) -> impl Iterator<Item = ClassId> + '_ {
596        self.classes
597            .iter()
598            .enumerate()
599            .filter(|(_, c)| c.concrete)
600            .map(|(i, _)| ClassId(i as u16))
601    }
602}
603
604fn binary_search<T: Copy>(
605    index: &'static [(u16, &'static str, T)],
606    ns: u16,
607    key: &str,
608) -> Option<T> {
609    index
610        .binary_search_by(|(n, k, _)| n.cmp(&ns).then_with(|| (*k).cmp(key)))
611        .ok()
612        .map(|i| index[i].2)
613}
614
615#[cfg(test)]
616mod tests {
617    use super::*;
618
619    #[test]
620    fn multiplicity_bounds() {
621        assert!(Mult::Required.is_required());
622        assert!(!Mult::Optional.is_required());
623        assert!(Mult::Many.is_many());
624        assert_eq!(Mult::Optional.max(), 1);
625        assert_eq!(Mult::Many.max(), u32::MAX);
626        assert_eq!(Mult::Bounded { min: 0, max: 2 }.max(), 2);
627        assert!(Mult::Bounded { min: 1, max: 2 }.is_required());
628    }
629
630    #[test]
631    fn profile_masks_are_distinct_bits() {
632        assert_eq!(ProfileId(0).mask(), 1);
633        assert_eq!(ProfileId(3).mask(), 8);
634    }
635}