Skip to main content

cim_kit/
dataset.rs

1//! The dataset: a set of CIM objects assembled from one or more instance files.
2
3use std::collections::HashMap;
4
5use crate::error::{Error, Result};
6use crate::header::{DifferenceModel, ModelHeader};
7use crate::mrid::Mrid;
8use crate::object::Object;
9use crate::schema::{AttrId, AttrKind, ClassId, ProfileMask, Schema};
10use crate::value::Value;
11
12/// Handle to an object inside a [`Dataset`].
13///
14/// Stable for the lifetime of the dataset unless [`Dataset::remove`] is called.
15#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
16pub struct ObjectId(pub u32);
17
18impl ObjectId {
19    #[inline]
20    pub const fn index(self) -> usize {
21        self.0 as usize
22    }
23}
24
25/// How to treat references that do not resolve within the dataset.
26#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
27pub enum LinkPolicy {
28    /// Unresolved references are an error. Appropriate for a fully assembled model.
29    Strict,
30    /// Unresolved references are reported as diagnostics and otherwise tolerated.
31    ///
32    /// This is the default because real exchanges are routinely partial: a Steady State
33    /// Hypothesis file references equipment defined in a separate Equipment file, and a
34    /// model may legitimately be read before its boundary set is loaded.
35    #[default]
36    Lenient,
37}
38
39/// A set of CIM objects together with the headers of the files that produced them.
40///
41/// CGMES splits one grid model across profile files (EQ, SSH, TP, SV, ...) that describe
42/// the *same* objects; loading them into one dataset merges attributes by mRID.
43#[derive(Debug)]
44pub struct Dataset {
45    schema: &'static Schema,
46    /// `None` marks a removed slot, keeping [`ObjectId`]s stable.
47    objects: Vec<Option<Object>>,
48    by_mrid: HashMap<Mrid, ObjectId>,
49    /// Objects of exactly each class, indexed by [`ClassId`].
50    ///
51    /// Indexed by class: a schema has a few hundred classes, so no hash lookup.
52    by_class: Vec<Vec<ObjectId>>,
53    /// Where each object sits inside its class bucket, indexed by [`ObjectId`].
54    ///
55    /// Keeps removal and reclassification O(1) instead of a bucket scan.
56    class_slot: Vec<u32>,
57    headers: Vec<ModelHeader>,
58    /// Objects each loaded file contributed, indexed by header slot.
59    by_source: Vec<Vec<ObjectId>>,
60    differences: Vec<DifferenceModel>,
61    /// Identifiers of the change sets applied to this dataset, which count as loaded
62    /// models when the next change set names what it supersedes.
63    applied: Vec<Mrid>,
64    /// Models an applied change set superseded: no longer the state this dataset holds.
65    superseded: Vec<Mrid>,
66    link_policy: LinkPolicy,
67    /// Single-valued attributes two files gave different values for.
68    conflicts: Vec<MergeConflict>,
69    /// Conflicts beyond [`Dataset::MAX_CONFLICTS`], counted but not kept.
70    conflicts_dropped: usize,
71}
72
73/// Two files disagreeing about a single-valued attribute of one object.
74///
75/// A defect in the model set: merging keeps one reading and discards the other. The last
76/// file read wins (so a change file over a base model behaves as intended); which one
77/// that is depends on load order, but that a conflict happened does not.
78/// [`Dataset::merge_conflicts`] lists them.
79#[derive(Clone, Debug)]
80pub struct MergeConflict {
81    pub object: Mrid,
82    pub attr: AttrId,
83    /// The value now stored — the one the later file supplied.
84    pub kept: Value,
85    /// The value the earlier file supplied, which is no longer in the model.
86    pub discarded: Value,
87}
88
89impl Dataset {
90    pub fn new(schema: &'static Schema) -> Dataset {
91        Dataset {
92            schema,
93            objects: Vec::new(),
94            by_mrid: HashMap::new(),
95            by_class: vec![Vec::new(); schema.classes.len()],
96            class_slot: Vec::new(),
97            headers: Vec::new(),
98            by_source: Vec::new(),
99            differences: Vec::new(),
100            applied: Vec::new(),
101            superseded: Vec::new(),
102            link_policy: LinkPolicy::default(),
103            conflicts: Vec::new(),
104            conflicts_dropped: 0,
105        }
106    }
107
108    /// How many merge conflicts are retained before only their number is kept.
109    ///
110    /// Bounds memory when mismatched files disagree about every object.
111    pub const MAX_CONFLICTS: usize = 1000;
112
113    pub fn with_link_policy(mut self, policy: LinkPolicy) -> Dataset {
114        self.link_policy = policy;
115        self
116    }
117
118    #[inline]
119    pub fn schema(&self) -> &'static Schema {
120        self.schema
121    }
122
123    #[inline]
124    pub fn link_policy(&self) -> LinkPolicy {
125        self.link_policy
126    }
127
128    /// Headers of every file loaded into this dataset, in load order.
129    #[inline]
130    pub fn headers(&self) -> &[ModelHeader] {
131        &self.headers
132    }
133
134    /// Register a file's header and return the source slot its objects belong to.
135    ///
136    /// Called before a file's objects are stored, so each is recorded against its file.
137    pub fn push_header(&mut self, header: ModelHeader) -> usize {
138        self.headers.push(header);
139        self.by_source.push(Vec::new());
140        self.headers.len() - 1
141    }
142
143    /// Replace the header in slot `index`, keeping the objects already recorded against it.
144    ///
145    /// Used when a document's `md:FullModel` follows its first object, which has already
146    /// claimed a placeholder slot.
147    pub fn set_header(&mut self, index: usize, header: ModelHeader) {
148        if let Some(slot) = self.headers.get_mut(index) {
149            *slot = header;
150        }
151    }
152
153    /// Record that the file in header slot `source` contained `id`.
154    pub fn record_source(&mut self, source: usize, id: ObjectId) {
155        let Some(list) = self.by_source.get_mut(source) else {
156            return;
157        };
158        // One object element per file, so a repeat means the file described it twice.
159        if list.last() != Some(&id) {
160            list.push(id);
161        }
162        if let Some(Some(o)) = self.objects.get_mut(id.index()) {
163            o.from_file = true;
164        }
165    }
166
167    /// Objects the file in header slot `source` contributed, in the order it listed them.
168    ///
169    /// Needed where profile provenance is not enough, e.g. a merged model with one
170    /// Equipment file per modelling authority. Objects since removed with
171    /// [`Dataset::remove`] are skipped (checked here, not on removal).
172    pub fn objects_from(&self, source: usize) -> impl Iterator<Item = ObjectId> + '_ {
173        self.by_source
174            .get(source)
175            .map_or(&[][..], |v| v.as_slice())
176            .iter()
177            .copied()
178            .filter(move |&id| self.get(id).is_some())
179    }
180
181    /// Difference models read into this dataset, in load order.
182    ///
183    /// Not applied on load ([`Dataset::apply_difference`] does that); kept so a model set
184    /// with change files can be written back whole.
185    pub fn differences(&self) -> &[DifferenceModel] {
186        &self.differences
187    }
188
189    /// The model states this dataset holds now: its headers' identifiers, less every model
190    /// an applied change set superseded, plus the change sets applied. A difference file
191    /// only read, not applied, is not among them.
192    pub fn model_ids(&self) -> impl Iterator<Item = &Mrid> + '_ {
193        self.headers
194            .iter()
195            .filter_map(|h| h.id.as_ref())
196            .filter(|id| !self.superseded.contains(id))
197            .chain(&self.applied)
198    }
199
200    pub(crate) fn record_applied(&mut self, id: Option<Mrid>, superseded: &[Mrid]) {
201        self.superseded.extend(superseded.iter().cloned());
202        self.applied.extend(id);
203    }
204
205    pub fn push_difference(&mut self, diff: DifferenceModel) {
206        self.differences.push(diff);
207    }
208
209    /// Profiles present across all loaded headers.
210    pub fn profiles(&self) -> ProfileMask {
211        self.headers.iter().fold(0, |acc, h| {
212            acc | h
213                .profiles
214                .iter()
215                .filter_map(|iri| self.schema.profile_by_iri(iri))
216                .fold(0, |a, p| a | p.mask())
217        })
218    }
219
220    /// Number of live objects.
221    pub fn len(&self) -> usize {
222        self.by_mrid.len()
223    }
224
225    pub fn is_empty(&self) -> bool {
226        self.by_mrid.is_empty()
227    }
228
229    #[inline]
230    pub fn get(&self, id: ObjectId) -> Option<&Object> {
231        self.objects.get(id.index())?.as_ref()
232    }
233
234    #[inline]
235    pub fn get_mut(&mut self, id: ObjectId) -> Option<&mut Object> {
236        self.objects.get_mut(id.index())?.as_mut()
237    }
238
239    pub fn find(&self, mrid: &Mrid) -> Option<ObjectId> {
240        self.by_mrid.get(mrid).copied()
241    }
242
243    pub fn by_mrid(&self, mrid: &Mrid) -> Option<&Object> {
244        self.find(mrid).and_then(|id| self.get(id))
245    }
246
247    /// Insert an object, or merge into the existing one with the same mRID.
248    ///
249    /// Attributes are added to the existing object, not replacing it. The more specific
250    /// class wins, since profiles may describe an object through a base class.
251    pub fn insert(&mut self, object: Object) -> ObjectId {
252        if let Some(&existing) = self.by_mrid.get(&object.mrid) {
253            self.merge_into(existing, object);
254            return existing;
255        }
256        let id = ObjectId(self.objects.len() as u32);
257        let class = object.class;
258        self.by_mrid.insert(object.mrid.clone(), id);
259        self.objects.push(Some(object));
260        self.class_slot.push(0);
261        self.attach_to_class(id, class);
262        id
263    }
264
265    /// Absorb another dataset: its objects, its file headers, which file each object came
266    /// from, and any change files it carries.
267    ///
268    /// Lets files be parsed in parallel, one dataset each, and combined afterwards into
269    /// the same model a sequential load produces.
270    ///
271    #[cfg_attr(
272        feature = "cgmes3",
273        doc = r#"
274```no_run
275# use cim_kit::prelude::*;
276# use cim_kit::cgmes3::SCHEMA;
277# fn main() -> cim_kit::Result<()> {
278let mut model = Dataset::new(SCHEMA);
279for part in ["EQ.xml", "SSH.xml", "TP.xml", "SV.xml"]
280    .map(|f| Dataset::load(SCHEMA, [f]))
281{
282    model.merge(part?)?;
283}
284# Ok(()) }
285```
286"#
287    )]
288    ///
289    /// As with `load_files`, a conflicting single-valued attribute takes the later value
290    /// and is recorded as a [`MergeConflict`]; conflicts `other` recorded are carried over.
291    ///
292    /// Fails if the two datasets were built from different schema vintages.
293    pub fn merge(&mut self, other: Dataset) -> Result<()> {
294        if !std::ptr::eq(self.schema, other.schema) {
295            return Err(Error::SchemaMismatch {
296                left: self.schema.vintage,
297                right: other.schema.vintage,
298            });
299        }
300        let base = self.headers.len();
301        for h in other.headers {
302            self.push_header(h);
303        }
304        for d in other.differences {
305            self.push_difference(d);
306        }
307        self.applied.extend(other.applied);
308        self.superseded.extend(other.superseded);
309
310        // `other`'s handles do not survive merging, so the per-file index is rebuilt
311        // through a translation table.
312        let mut moved: Vec<Option<ObjectId>> = vec![None; other.objects.len()];
313        for (i, slot) in other.objects.into_iter().enumerate() {
314            if let Some(o) = slot {
315                moved[i] = Some(self.insert(o));
316            }
317        }
318        for (i, ids) in other.by_source.into_iter().enumerate() {
319            for id in ids {
320                if let Some(new) = moved.get(id.index()).copied().flatten() {
321                    self.record_source(base + i, new);
322                }
323            }
324        }
325
326        for c in other.conflicts {
327            self.record_conflict(c);
328        }
329        self.conflicts_dropped += other.conflicts_dropped;
330        Ok(())
331    }
332
333    /// Record `id` in `class`'s bucket, remembering where it landed.
334    fn attach_to_class(&mut self, id: ObjectId, class: ClassId) {
335        let Some(bucket) = self.by_class.get_mut(class.index()) else {
336            return;
337        };
338        self.class_slot[id.index()] = bucket.len() as u32;
339        bucket.push(id);
340    }
341
342    /// Take `id` out of `class`'s bucket in constant time.
343    ///
344    /// The last entry moves into the vacated slot and its recorded position is updated.
345    fn detach_from_class(&mut self, id: ObjectId, class: ClassId) {
346        let slot = self.class_slot[id.index()] as usize;
347        let Some(bucket) = self.by_class.get_mut(class.index()) else {
348            return;
349        };
350        debug_assert_eq!(bucket.get(slot), Some(&id), "class index out of step");
351        bucket.swap_remove(slot);
352        if let Some(&moved) = bucket.get(slot) {
353            self.class_slot[moved.index()] = slot as u32;
354        }
355    }
356
357    fn merge_into(&mut self, target: ObjectId, incoming: Object) {
358        let schema = self.schema;
359        let Some(old_class) = self.get(target).map(|o| o.class) else {
360            return;
361        };
362
363        // Prefer the most specific class: a profile may describe an object through a
364        // base class (e.g. SSH writing to `Terminal` where EQ knew a subclass).
365        let new_class = if schema.is_a(incoming.class, old_class) {
366            incoming.class
367        } else {
368            old_class
369        };
370        if new_class != old_class {
371            self.detach_from_class(target, old_class);
372            self.attach_to_class(target, new_class);
373        }
374
375        let mut conflicts: Vec<MergeConflict> = Vec::new();
376        let Some(obj) = self.objects[target.index()].as_mut() else {
377            return;
378        };
379        obj.set_class(new_class);
380        obj.mark_profile(incoming.profiles);
381        obj.from_file |= incoming.from_file;
382        for slot in incoming.values {
383            let many = schema.attr(slot.attr).mult.is_many();
384            let duplicate = obj
385                .get_all(slot.attr)
386                .iter()
387                .any(|existing| existing.value == slot.value);
388            if duplicate {
389                // The same value in two profiles: widen its provenance rather than
390                // storing it twice, so an export reproduces both files.
391                obj.merge_provenance(slot.attr, &slot.value, slot.profiles);
392            } else if many {
393                obj.push_slot(slot);
394            } else {
395                // A conflict: the newer value wins and is recorded. Provenance is unioned
396                // so both files still carry the attribute on export.
397                let existing = obj.get_slot(slot.attr);
398                let inherited = existing.map_or(0, |s| s.profiles);
399                if let Some(old) = existing {
400                    conflicts.push(MergeConflict {
401                        object: obj.mrid().clone(),
402                        attr: slot.attr,
403                        kept: slot.value.clone(),
404                        discarded: old.value.clone(),
405                    });
406                }
407                let mut slot = slot;
408                slot.profiles |= inherited;
409                obj.set_slot(slot);
410            }
411        }
412        for c in conflicts {
413            self.record_conflict(c);
414        }
415    }
416
417    fn record_conflict(&mut self, conflict: MergeConflict) {
418        if self.conflicts.len() < Self::MAX_CONFLICTS {
419            self.conflicts.push(conflict);
420        } else {
421            self.conflicts_dropped += 1;
422        }
423    }
424
425    /// Single-valued attributes two loaded files gave different values for.
426    ///
427    /// Empty for a consistent model set; each entry is a discarded value.
428    /// [`validate`](mod@crate::validate) turns these into
429    /// [`Rule::ConflictingValue`](crate::Rule::ConflictingValue) diagnostics.
430    pub fn merge_conflicts(&self) -> &[MergeConflict] {
431        &self.conflicts
432    }
433
434    /// Conflicts that occurred beyond [`Dataset::MAX_CONFLICTS`] and were only counted.
435    pub fn merge_conflicts_dropped(&self) -> usize {
436        self.conflicts_dropped
437    }
438
439    /// Change an object's class, keeping the per-class index consistent, and return any
440    /// values the new class cannot carry.
441    ///
442    /// Used when a difference model reclassifies an object (IEC 61970-552).
443    ///
444    /// **Values are shed, not kept.** Narrowing to a subclass sheds nothing; moving sideways
445    /// sheds attributes the new class lacks (e.g. `LinearShuntCompensator.bPerSection` on
446    /// a `NonlinearShuntCompensator`), since writer and validation would never see them.
447    /// They are returned so the caller can report the loss.
448    pub fn reclassify(&mut self, id: ObjectId, class: ClassId) -> Vec<crate::object::Slot> {
449        let schema = self.schema;
450        let Some(old) = self.get(id).map(|o| o.class()) else {
451            return Vec::new();
452        };
453        if old == class {
454            return Vec::new();
455        }
456        self.detach_from_class(id, old);
457        self.attach_to_class(id, class);
458        let Some(o) = self.objects[id.index()].as_mut() else {
459            return Vec::new();
460        };
461        o.set_class(class);
462        o.retain_slots(|slot| schema.is_a(class, schema.attr(slot.attr).owner))
463    }
464
465    /// Remove an object. Its [`ObjectId`] is never reused.
466    pub fn remove(&mut self, id: ObjectId) -> Option<Object> {
467        let obj = self.objects.get_mut(id.index())?.take()?;
468        self.by_mrid.remove(&obj.mrid);
469        self.detach_from_class(id, obj.class);
470        Some(obj)
471    }
472
473    /// Every live object.
474    pub fn iter(&self) -> impl Iterator<Item = (ObjectId, &Object)> + '_ {
475        self.objects
476            .iter()
477            .enumerate()
478            .filter_map(|(i, o)| Some((ObjectId(i as u32), o.as_ref()?)))
479    }
480
481    /// Objects of exactly `class`, excluding subclasses.
482    pub fn iter_exact(&self, class: ClassId) -> impl Iterator<Item = (ObjectId, &Object)> + '_ {
483        self.by_class
484            .get(class.index())
485            .map_or(&[][..], |v| v.as_slice())
486            .iter()
487            .filter_map(move |&id| self.get(id).map(|o| (id, o)))
488    }
489
490    /// Objects of `class` or any subclass — usually what callers want.
491    ///
492    /// Walks per-class buckets, so the cost is the number of matches, not the model size.
493    /// Order is unspecified but stable for a given load.
494    pub fn iter_class(&self, class: ClassId) -> impl Iterator<Item = (ObjectId, &Object)> + '_ {
495        self.schema
496            .class(class)
497            .descendants
498            .iter()
499            .flat_map(move |&c| self.iter_exact(c))
500    }
501
502    pub fn count_class(&self, class: ClassId) -> usize {
503        self.schema
504            .class(class)
505            .descendants
506            .iter()
507            .map(|c| self.by_class.get(c.index()).map_or(0, |v| v.len()))
508            .sum()
509    }
510
511    /// Resolve a single-valued association to the referenced object.
512    pub fn follow(&self, object: &Object, attr: AttrId) -> Option<&Object> {
513        let mrid = object.get(attr)?.as_reference()?;
514        self.by_mrid(mrid)
515    }
516
517    /// Resolve every value of a many-valued association.
518    ///
519    /// References that do not resolve are skipped; use
520    /// [`validate`](crate::validate::validate) to report them.
521    pub fn follow_all<'a>(
522        &'a self,
523        object: &'a Object,
524        attr: AttrId,
525    ) -> impl Iterator<Item = &'a Object> + 'a {
526        object
527            .get_all(attr)
528            .iter()
529            .filter_map(|s| s.value.as_reference())
530            .filter_map(move |m| self.by_mrid(m))
531    }
532
533    /// Objects whose association `attr` points at `target`.
534    ///
535    /// Computed, since only one side of each association is serialized (IEC 61970-501).
536    /// Build an [`InverseIndex`] when querying repeatedly.
537    pub fn referrers<'a>(
538        &'a self,
539        target: &'a Mrid,
540        attr: AttrId,
541    ) -> impl Iterator<Item = (ObjectId, &'a Object)> + 'a {
542        self.iter().filter(move |(_, o)| {
543            o.get_all(attr)
544                .iter()
545                .any(|s| s.value.as_reference() == Some(target))
546        })
547    }
548
549    /// The namespace under which this crate derives identifiers.
550    ///
551    /// A fixed version-4 UUID, so derived mRIDs cannot collide with those derived elsewhere.
552    pub const DERIVED_NS: Mrid = Mrid::from_uuid_bytes([
553        0x2b, 0x0f, 0x9a, 0x71, 0x2c, 0x8e, 0x4a, 0x2f, 0x9c, 0x1a, 0x3f, 0x7f, 0x9d, 0x4b, 0x6e,
554        0x10,
555    ]);
556
557    /// A UUID that identifies *what this model contains*.
558    ///
559    /// Used as `md:FullModel rdf:about` when exporting a model that has none: unchanged
560    /// content gives an unchanged identifier, so exports stay deterministic.
561    ///
562    /// Covers the vintage and, per object in mRID order, its identifier, class and stored
563    /// values; not headers, per-file provenance or load order.
564    ///
565    /// Derived with SHA-1: guards against accident, not an adversary.
566    pub fn content_id(&self) -> Mrid {
567        // mRID order, raw bytes into one buffer (no per-object allocation), with
568        // separators so adjacent fields cannot run together.
569        let mut ids: Vec<(&Mrid, ObjectId)> = self.iter().map(|(id, o)| (o.mrid(), id)).collect();
570        ids.sort_by(|a, b| a.0.cmp(b.0));
571
572        let mut buf: Vec<u8> = Vec::with_capacity(self.len() * 24 + 32);
573        buf.extend_from_slice(self.schema.vintage.as_bytes());
574        for (mrid, id) in ids {
575            buf.push(0x1e);
576            match mrid.as_uuid_bytes() {
577                Some(b) => buf.extend_from_slice(b),
578                None => buf.extend_from_slice(mrid.canonical().as_bytes()),
579            }
580            let Some(o) = self.get(id) else { continue };
581            buf.push(0x1f);
582            buf.extend_from_slice(&o.class().0.to_le_bytes());
583            for slot in o.slots() {
584                buf.extend_from_slice(&slot.attr.0.to_le_bytes());
585                fold_value(&mut buf, &slot.value);
586            }
587        }
588        Mrid::new_v5(&Self::DERIVED_NS, &buf)
589    }
590
591    /// Release unused capacity after bulk loading.
592    pub fn shrink_to_fit(&mut self) {
593        for o in self.objects.iter_mut().flatten() {
594            o.shrink();
595        }
596        self.objects.shrink_to_fit();
597        self.class_slot.shrink_to_fit();
598        self.by_mrid.shrink_to_fit();
599        for v in self.by_class.iter_mut() {
600            v.shrink_to_fit();
601        }
602    }
603
604    /// References that point at objects not present in the dataset.
605    pub fn dangling_references(&self) -> Vec<(ObjectId, AttrId, Mrid)> {
606        let mut out = Vec::new();
607        for (id, obj) in self.iter() {
608            for slot in obj.slots() {
609                if let Value::Reference(m) = &slot.value
610                    && !self.by_mrid.contains_key(m)
611                {
612                    out.push((id, slot.attr, m.clone()));
613                }
614            }
615        }
616        out
617    }
618
619    /// Fail if the link policy is [`LinkPolicy::Strict`] and references are unresolved.
620    pub fn check_links(&self) -> Result<()> {
621        if self.link_policy == LinkPolicy::Strict {
622            let dangling = self.dangling_references();
623            if !dangling.is_empty() {
624                let (id, attr, mrid) = &dangling[0];
625                let owner = self
626                    .get(*id)
627                    .map(|o| o.mrid().canonical())
628                    .unwrap_or_default();
629                return Err(Error::DanglingReference {
630                    object: owner,
631                    attribute: self.schema.attr(*attr).name,
632                    target: mrid.canonical(),
633                    total: dangling.len(),
634                });
635            }
636        }
637        Ok(())
638    }
639}
640
641/// Append one value to a content fingerprint, in its stored rather than its printed form.
642///
643/// Each variant is tagged, so text cannot collide with a reference of the same spelling.
644fn fold_value(buf: &mut Vec<u8>, v: &Value) {
645    match v {
646        Value::Boolean(b) => buf.extend_from_slice(&[1, *b as u8]),
647        Value::Integer(i) => {
648            buf.push(2);
649            buf.extend_from_slice(&i.to_le_bytes());
650        }
651        Value::Float(f) => {
652            buf.push(3);
653            // The number, not its spelling, matching `Real`'s equality.
654            buf.extend_from_slice(&f.get().to_bits().to_le_bytes());
655        }
656        Value::Text(s) => {
657            buf.push(4);
658            buf.extend_from_slice(&(s.len() as u64).to_le_bytes());
659            buf.extend_from_slice(s.as_bytes());
660        }
661        Value::Enum(e) => {
662            buf.push(5);
663            buf.extend_from_slice(&e.0.to_le_bytes());
664        }
665        Value::Reference(m) => {
666            buf.push(6);
667            match m.as_uuid_bytes() {
668                Some(b) => buf.extend_from_slice(b),
669                None => buf.extend_from_slice(m.canonical().as_bytes()),
670            }
671        }
672        Value::Compound(c) => {
673            buf.push(7);
674            buf.extend_from_slice(&c.class().0.to_le_bytes());
675            for (a, v) in c.values() {
676                buf.extend_from_slice(&a.0.to_le_bytes());
677                fold_value(buf, v);
678            }
679        }
680    }
681    buf.push(0x1d);
682}
683
684/// A precomputed index from referenced object to the objects that reference it.
685///
686/// Turns repeated [`Dataset::referrers`] scans into hash lookups.
687#[derive(Debug)]
688pub struct InverseIndex {
689    /// Keyed by target first so a lookup borrows the identifier rather than cloning it.
690    map: HashMap<Mrid, HashMap<AttrId, Vec<ObjectId>>>,
691}
692
693impl InverseIndex {
694    /// Index every association in the dataset.
695    pub fn build(dataset: &Dataset) -> InverseIndex {
696        let mut map: HashMap<Mrid, HashMap<AttrId, Vec<ObjectId>>> = HashMap::new();
697        for (id, obj) in dataset.iter() {
698            for slot in obj.slots() {
699                if matches!(
700                    dataset.schema().attr(slot.attr).kind,
701                    AttrKind::Association { .. }
702                ) && let Value::Reference(m) = &slot.value
703                {
704                    map.entry(m.clone())
705                        .or_default()
706                        .entry(slot.attr)
707                        .or_default()
708                        .push(id);
709                }
710            }
711        }
712        InverseIndex { map }
713    }
714
715    /// Objects whose `attr` points at `target`.
716    pub fn referrers(&self, attr: AttrId, target: &Mrid) -> &[ObjectId] {
717        self.map
718            .get(target)
719            .and_then(|m| m.get(&attr))
720            .map(|v| v.as_slice())
721            .unwrap_or(&[])
722    }
723
724    /// Every object referring to `target`, whichever association it uses.
725    pub fn all_referrers(&self, target: &Mrid) -> impl Iterator<Item = (AttrId, ObjectId)> + '_ {
726        self.map.get(target).into_iter().flat_map(|m| {
727            m.iter()
728                .flat_map(|(a, v)| v.iter().map(move |id| (*a, *id)))
729        })
730    }
731
732    /// Resolve the inverse of `attr` — the role declared by `cims:inverseRoleName` —
733    /// for `target`, following whichever side the schema actually serializes.
734    pub fn inverse_of<'a>(
735        &'a self,
736        schema: &Schema,
737        attr: AttrId,
738        target: &Mrid,
739    ) -> &'a [ObjectId] {
740        match schema.attr(attr).kind {
741            AttrKind::Association {
742                inverse: Some(inv), ..
743            } => self.referrers(inv, target),
744            _ => &[],
745        }
746    }
747}
748
749impl Dataset {
750    /// Validate with the default checks.
751    ///
752    /// Shorthand for [`validate::validate`](crate::validate::validate).
753    pub fn validate(&self) -> crate::error::Report {
754        crate::validate::validate(self)
755    }
756
757    /// Validate with explicit options.
758    pub fn validate_with(
759        &self,
760        options: &crate::validate::ValidateOptions,
761    ) -> crate::error::Report {
762        crate::validate::validate_with(self, options)
763    }
764}