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/// A dataset is the unit of real-world exchange: CGMES splits one grid model across
42/// several profile files (EQ, SSH, TP, SV, ...) that describe the *same* objects. Loading
43/// them into one dataset merges each object's attributes across profiles.
44#[derive(Debug)]
45pub struct Dataset {
46 schema: &'static Schema,
47 /// `None` marks a removed slot, keeping [`ObjectId`]s stable.
48 objects: Vec<Option<Object>>,
49 by_mrid: HashMap<Mrid, ObjectId>,
50 /// Objects of exactly each class, indexed by [`ClassId`].
51 ///
52 /// A dense vector rather than a map: a schema has a few hundred classes, so the
53 /// per-class bucket is a direct index instead of a hash lookup on every iteration.
54 by_class: Vec<Vec<ObjectId>>,
55 /// Where each object sits inside its class bucket, indexed by [`ObjectId`].
56 ///
57 /// This is what keeps removing an object and moving it between classes O(1). Without
58 /// it both had to scan the bucket, so deleting every object of a class — an ordinary
59 /// way to filter a model — cost the square of their number, and so did loading a
60 /// Steady State Hypothesis file before its Equipment file, since every object it
61 /// carries as a generic `<cim:Equipment>` is then promoted to its real class.
62 class_slot: Vec<u32>,
63 headers: Vec<ModelHeader>,
64 /// Objects each loaded file contributed, indexed by header slot.
65 by_source: Vec<Vec<ObjectId>>,
66 differences: Vec<DifferenceModel>,
67 /// Identifiers of the change sets applied to this dataset, which count as loaded
68 /// models when the next change set names what it supersedes.
69 applied: Vec<Mrid>,
70 /// Models an applied change set superseded: no longer the state this dataset holds.
71 superseded: Vec<Mrid>,
72 link_policy: LinkPolicy,
73 /// Single-valued attributes two files gave different values for.
74 conflicts: Vec<MergeConflict>,
75 /// Conflicts beyond [`Dataset::MAX_CONFLICTS`], counted but not kept.
76 conflicts_dropped: usize,
77}
78
79/// Two files disagreeing about a single-valued attribute of one object.
80///
81/// Merging by mRID is what makes multi-profile assembly work, and for almost everything it
82/// is unambiguous: each file contributes attributes the others do not have, or repeats one
83/// with the same value. A *different* value for a single-valued attribute is neither — it
84/// is a defect in the model set, and one that has to be visible, because resolving it means
85/// discarding one of the two readings.
86///
87/// The last file read wins, so that a change file applied over a base model has the effect
88/// its author intended. Which one that is depends on load order; that the conflict happened
89/// does not, and is what [`Dataset::merge_conflicts`] reports.
90#[derive(Clone, Debug)]
91pub struct MergeConflict {
92 pub object: Mrid,
93 pub attr: AttrId,
94 /// The value now stored — the one the later file supplied.
95 pub kept: Value,
96 /// The value the earlier file supplied, which is no longer in the model.
97 pub discarded: Value,
98}
99
100impl Dataset {
101 pub fn new(schema: &'static Schema) -> Dataset {
102 Dataset {
103 schema,
104 objects: Vec::new(),
105 by_mrid: HashMap::new(),
106 by_class: vec![Vec::new(); schema.classes.len()],
107 class_slot: Vec::new(),
108 headers: Vec::new(),
109 by_source: Vec::new(),
110 differences: Vec::new(),
111 applied: Vec::new(),
112 superseded: Vec::new(),
113 link_policy: LinkPolicy::default(),
114 conflicts: Vec::new(),
115 conflicts_dropped: 0,
116 }
117 }
118
119 /// How many merge conflicts are retained before only their number is kept.
120 ///
121 /// A model set assembled from mismatched files can disagree about every object; the
122 /// cap keeps that from turning into memory proportional to the model.
123 pub const MAX_CONFLICTS: usize = 1000;
124
125 pub fn with_link_policy(mut self, policy: LinkPolicy) -> Dataset {
126 self.link_policy = policy;
127 self
128 }
129
130 #[inline]
131 pub fn schema(&self) -> &'static Schema {
132 self.schema
133 }
134
135 #[inline]
136 pub fn link_policy(&self) -> LinkPolicy {
137 self.link_policy
138 }
139
140 /// Headers of every file loaded into this dataset, in load order.
141 #[inline]
142 pub fn headers(&self) -> &[ModelHeader] {
143 &self.headers
144 }
145
146 /// Register a file's header and return the source slot its objects belong to.
147 ///
148 /// The reader calls this before storing a file's objects, so each object is recorded
149 /// against the file it came from and an export can reproduce that file set.
150 pub fn push_header(&mut self, header: ModelHeader) -> usize {
151 self.headers.push(header);
152 self.by_source.push(Vec::new());
153 self.headers.len() - 1
154 }
155
156 /// Replace the header in slot `index`, keeping the objects already recorded against it.
157 ///
158 /// A document that names itself only *after* its first object — legal XML, and not what
159 /// IEC 61970-552's layout suggests — claims a slot before its `md:FullModel` is read.
160 /// Pushing the real header afterwards would leave the file described twice and its
161 /// objects attached to the placeholder.
162 pub fn set_header(&mut self, index: usize, header: ModelHeader) {
163 if let Some(slot) = self.headers.get_mut(index) {
164 *slot = header;
165 }
166 }
167
168 /// Record that the file in header slot `source` contained `id`.
169 pub fn record_source(&mut self, source: usize, id: ObjectId) {
170 let Some(list) = self.by_source.get_mut(source) else {
171 return;
172 };
173 // One object element per file, so a repeat means the file described it twice.
174 if list.last() != Some(&id) {
175 list.push(id);
176 }
177 if let Some(Some(o)) = self.objects.get_mut(id.index()) {
178 o.from_file = true;
179 }
180 }
181
182 /// Objects the file in header slot `source` contributed, in the order it listed them.
183 ///
184 /// Profile provenance alone cannot say which *file* a value came from, and in a merged
185 /// common grid model that matters: two modelling authorities each contribute an
186 /// Equipment file, and writing the model back must put each authority's equipment in
187 /// its own file rather than the union in both.
188 ///
189 /// Objects since removed with [`Dataset::remove`] are skipped. The index is not
190 /// rebuilt on removal — an object appears in as many files as there are profiles
191 /// describing it, so cleaning it out would mean either a per-object source set or a
192 /// scan of every file's list — so the liveness check happens here instead, where it
193 /// costs one lookup per entry and cannot be forgotten by a caller.
194 pub fn objects_from(&self, source: usize) -> impl Iterator<Item = ObjectId> + '_ {
195 self.by_source
196 .get(source)
197 .map_or(&[][..], |v| v.as_slice())
198 .iter()
199 .copied()
200 .filter(move |&id| self.get(id).is_some())
201 }
202
203 /// Difference models read into this dataset, in load order.
204 ///
205 /// A difference is not applied on load — [`Dataset::apply_difference`] does that — but
206 /// it is kept so that a model set containing change files can be written back whole.
207 pub fn differences(&self) -> &[DifferenceModel] {
208 &self.differences
209 }
210
211 /// The model states this dataset holds now: its headers' identifiers, less every model
212 /// an applied change set superseded, plus the change sets applied. A difference file
213 /// merely *read* as part of a model set is not among them — it has not been applied —
214 /// and neither is a model a change set has replaced, which is why a second variant
215 /// computed against the same base is refused after the first.
216 pub fn model_ids(&self) -> impl Iterator<Item = &Mrid> + '_ {
217 self.headers
218 .iter()
219 .filter_map(|h| h.id.as_ref())
220 .filter(|id| !self.superseded.contains(id))
221 .chain(&self.applied)
222 }
223
224 pub(crate) fn record_applied(&mut self, id: Option<Mrid>, superseded: &[Mrid]) {
225 self.superseded.extend(superseded.iter().cloned());
226 self.applied.extend(id);
227 }
228
229 pub fn push_difference(&mut self, diff: DifferenceModel) {
230 self.differences.push(diff);
231 }
232
233 /// Profiles present across all loaded headers.
234 pub fn profiles(&self) -> ProfileMask {
235 self.headers.iter().fold(0, |acc, h| {
236 acc | h
237 .profiles
238 .iter()
239 .filter_map(|iri| self.schema.profile_by_iri(iri))
240 .fold(0, |a, p| a | p.mask())
241 })
242 }
243
244 /// Number of live objects.
245 pub fn len(&self) -> usize {
246 self.by_mrid.len()
247 }
248
249 pub fn is_empty(&self) -> bool {
250 self.by_mrid.is_empty()
251 }
252
253 #[inline]
254 pub fn get(&self, id: ObjectId) -> Option<&Object> {
255 self.objects.get(id.index())?.as_ref()
256 }
257
258 #[inline]
259 pub fn get_mut(&mut self, id: ObjectId) -> Option<&mut Object> {
260 self.objects.get_mut(id.index())?.as_mut()
261 }
262
263 pub fn find(&self, mrid: &Mrid) -> Option<ObjectId> {
264 self.by_mrid.get(mrid).copied()
265 }
266
267 pub fn by_mrid(&self, mrid: &Mrid) -> Option<&Object> {
268 self.find(mrid).and_then(|id| self.get(id))
269 }
270
271 /// Insert an object, or merge into the existing one with the same mRID.
272 ///
273 /// Merging is what makes multi-profile assembly work: when an SSH file describes an
274 /// object already known from EQ, its attributes are added rather than replacing the
275 /// object. A more specific class wins, since profiles may describe the same object
276 /// through a base class.
277 pub fn insert(&mut self, object: Object) -> ObjectId {
278 if let Some(&existing) = self.by_mrid.get(&object.mrid) {
279 self.merge_into(existing, object);
280 return existing;
281 }
282 let id = ObjectId(self.objects.len() as u32);
283 let class = object.class;
284 self.by_mrid.insert(object.mrid.clone(), id);
285 self.objects.push(Some(object));
286 self.class_slot.push(0);
287 self.attach_to_class(id, class);
288 id
289 }
290
291 /// Absorb another dataset: its objects, its file headers, which file each object came
292 /// from, and any change files it carries.
293 ///
294 /// The point is assembly that is not sequential. `load_files` reads one document after
295 /// another into one dataset because the merge has to happen somewhere, but reading is
296 /// the expensive half and it is embarrassingly parallel — a model set is a handful of
297 /// independent files. With this, each can be parsed into its own dataset on its own
298 /// thread and the results combined afterwards, and the outcome is the same model:
299 /// merging by mRID is what makes multi-profile assembly work, and it does not care
300 /// which dataset an object arrived in.
301 ///
302 // An example has to name a vintage, and a vintage is a feature. See `Dataset::view`.
303 #[cfg_attr(
304 feature = "cgmes3",
305 doc = r#"
306```no_run
307# use cim_kit::prelude::*;
308# use cim_kit::cgmes3::SCHEMA;
309# fn main() -> cim_kit::Result<()> {
310let mut model = Dataset::new(SCHEMA);
311for part in ["EQ.xml", "SSH.xml", "TP.xml", "SV.xml"]
312 .map(|f| Dataset::load(SCHEMA, [f]))
313{
314 model.merge(part?)?;
315}
316# Ok(()) }
317```
318"#
319 )]
320 ///
321 /// One order-dependence survives, and it is the same one `load_files` has: where two
322 /// files give a single-valued attribute two different values, the later merge wins and
323 /// the discarded reading is recorded as a [`MergeConflict`]. Conflicts `other`
324 /// recorded on its own are carried over rather than lost.
325 ///
326 /// Fails if the two datasets were built from different schema vintages, because their
327 /// [`AttrId`]s index different tables.
328 pub fn merge(&mut self, other: Dataset) -> Result<()> {
329 if !std::ptr::eq(self.schema, other.schema) {
330 return Err(Error::SchemaMismatch {
331 left: self.schema.vintage,
332 right: other.schema.vintage,
333 });
334 }
335 let base = self.headers.len();
336 for h in other.headers {
337 self.push_header(h);
338 }
339 for d in other.differences {
340 self.push_difference(d);
341 }
342 self.applied.extend(other.applied);
343 self.superseded.extend(other.superseded);
344
345 // `other`'s handles do not survive the move — its objects merge into whatever this
346 // dataset already holds under the same identifier — so the per-file index is
347 // rebuilt through a translation table rather than copied.
348 let mut moved: Vec<Option<ObjectId>> = vec![None; other.objects.len()];
349 for (i, slot) in other.objects.into_iter().enumerate() {
350 if let Some(o) = slot {
351 moved[i] = Some(self.insert(o));
352 }
353 }
354 for (i, ids) in other.by_source.into_iter().enumerate() {
355 for id in ids {
356 if let Some(new) = moved.get(id.index()).copied().flatten() {
357 self.record_source(base + i, new);
358 }
359 }
360 }
361
362 for c in other.conflicts {
363 self.record_conflict(c);
364 }
365 self.conflicts_dropped += other.conflicts_dropped;
366 Ok(())
367 }
368
369 /// Record `id` in `class`'s bucket, remembering where it landed.
370 fn attach_to_class(&mut self, id: ObjectId, class: ClassId) {
371 let Some(bucket) = self.by_class.get_mut(class.index()) else {
372 return;
373 };
374 self.class_slot[id.index()] = bucket.len() as u32;
375 bucket.push(id);
376 }
377
378 /// Take `id` out of `class`'s bucket in constant time.
379 ///
380 /// The last entry moves into the vacated slot, so its own recorded position has to be
381 /// corrected — the whole point of keeping the position rather than searching for it.
382 fn detach_from_class(&mut self, id: ObjectId, class: ClassId) {
383 let slot = self.class_slot[id.index()] as usize;
384 let Some(bucket) = self.by_class.get_mut(class.index()) else {
385 return;
386 };
387 debug_assert_eq!(bucket.get(slot), Some(&id), "class index out of step");
388 bucket.swap_remove(slot);
389 if let Some(&moved) = bucket.get(slot) {
390 self.class_slot[moved.index()] = slot as u32;
391 }
392 }
393
394 fn merge_into(&mut self, target: ObjectId, incoming: Object) {
395 let schema = self.schema;
396 let Some(old_class) = self.get(target).map(|o| o.class) else {
397 return;
398 };
399
400 // Prefer the most specific class: a profile may describe an object through a
401 // base class (e.g. SSH writing to `Terminal` where EQ knew a subclass).
402 let new_class = if schema.is_a(incoming.class, old_class) {
403 incoming.class
404 } else {
405 old_class
406 };
407 if new_class != old_class {
408 self.detach_from_class(target, old_class);
409 self.attach_to_class(target, new_class);
410 }
411
412 let mut conflicts: Vec<MergeConflict> = Vec::new();
413 let Some(obj) = self.objects[target.index()].as_mut() else {
414 return;
415 };
416 obj.set_class(new_class);
417 obj.mark_profile(incoming.profiles);
418 obj.from_file |= incoming.from_file;
419 for slot in incoming.values {
420 let many = schema.attr(slot.attr).mult.is_many();
421 let duplicate = obj
422 .get_all(slot.attr)
423 .iter()
424 .any(|existing| existing.value == slot.value);
425 if duplicate {
426 // The same value in two profiles: widen its provenance rather than
427 // storing it twice, so an export reproduces both files.
428 obj.merge_provenance(slot.attr, &slot.value, slot.profiles);
429 } else if many {
430 obj.push_slot(slot);
431 } else {
432 // Two files disagreeing on a single-valued attribute is a data error, and
433 // resolving it means throwing one of the two readings away — so it is
434 // recorded rather than swallowed. The newer value wins, which is what
435 // makes a change file applied over a base model do what its author meant.
436 // Provenance is unioned so both files still carry the attribute on export
437 // instead of one of them losing it.
438 let existing = obj.get_slot(slot.attr);
439 let inherited = existing.map_or(0, |s| s.profiles);
440 if let Some(old) = existing {
441 conflicts.push(MergeConflict {
442 object: obj.mrid().clone(),
443 attr: slot.attr,
444 kept: slot.value.clone(),
445 discarded: old.value.clone(),
446 });
447 }
448 let mut slot = slot;
449 slot.profiles |= inherited;
450 obj.set_slot(slot);
451 }
452 }
453 for c in conflicts {
454 self.record_conflict(c);
455 }
456 }
457
458 fn record_conflict(&mut self, conflict: MergeConflict) {
459 if self.conflicts.len() < Self::MAX_CONFLICTS {
460 self.conflicts.push(conflict);
461 } else {
462 self.conflicts_dropped += 1;
463 }
464 }
465
466 /// Single-valued attributes two loaded files gave different values for.
467 ///
468 /// Empty for a consistent model set. A non-empty result means the model this dataset
469 /// holds is not the union of its files: for each entry, one file's value was discarded.
470 /// [`validate`](mod@crate::validate) turns these into
471 /// [`Rule::ConflictingValue`](crate::Rule::ConflictingValue) diagnostics.
472 pub fn merge_conflicts(&self) -> &[MergeConflict] {
473 &self.conflicts
474 }
475
476 /// Conflicts that occurred beyond [`Dataset::MAX_CONFLICTS`] and were only counted.
477 pub fn merge_conflicts_dropped(&self) -> usize {
478 self.conflicts_dropped
479 }
480
481 /// Change an object's class, keeping the per-class index consistent, and return any
482 /// values the new class cannot carry.
483 ///
484 /// Used when a difference model reclassifies an object — IEC 61970-552 treats an
485 /// object's type as a statement like any other, and the published conformity change
486 /// sets replace a `LinearShuntCompensator` with a `NonlinearShuntCompensator` under one
487 /// identifier.
488 ///
489 /// **Values are shed, not kept.** Narrowing to a subclass sheds nothing, because a
490 /// subclass has every attribute its parent has. Moving sideways does:
491 /// `LinearShuntCompensator.bPerSection` has no meaning on a `NonlinearShuntCompensator`
492 /// and no place in one's instance file. Keeping such a value looks harmless and is not
493 /// — nothing afterwards would ever look at it, because the writer emits a class's own
494 /// attributes and validation checks a class's own attributes, so it would vanish
495 /// without a word on the next export. Handing it back makes the loss the caller's to
496 /// report, which is what [`Dataset::apply_difference`] does.
497 pub fn reclassify(&mut self, id: ObjectId, class: ClassId) -> Vec<crate::object::Slot> {
498 let schema = self.schema;
499 let Some(old) = self.get(id).map(|o| o.class()) else {
500 return Vec::new();
501 };
502 if old == class {
503 return Vec::new();
504 }
505 self.detach_from_class(id, old);
506 self.attach_to_class(id, class);
507 let Some(o) = self.objects[id.index()].as_mut() else {
508 return Vec::new();
509 };
510 o.set_class(class);
511 o.retain_slots(|slot| schema.is_a(class, schema.attr(slot.attr).owner))
512 }
513
514 /// Remove an object. Its [`ObjectId`] is never reused.
515 pub fn remove(&mut self, id: ObjectId) -> Option<Object> {
516 let obj = self.objects.get_mut(id.index())?.take()?;
517 self.by_mrid.remove(&obj.mrid);
518 self.detach_from_class(id, obj.class);
519 Some(obj)
520 }
521
522 /// Every live object.
523 pub fn iter(&self) -> impl Iterator<Item = (ObjectId, &Object)> + '_ {
524 self.objects
525 .iter()
526 .enumerate()
527 .filter_map(|(i, o)| Some((ObjectId(i as u32), o.as_ref()?)))
528 }
529
530 /// Objects of exactly `class`, excluding subclasses.
531 pub fn iter_exact(&self, class: ClassId) -> impl Iterator<Item = (ObjectId, &Object)> + '_ {
532 self.by_class
533 .get(class.index())
534 .map_or(&[][..], |v| v.as_slice())
535 .iter()
536 .filter_map(move |&id| self.get(id).map(|o| (id, o)))
537 }
538
539 /// Objects of `class` or any subclass — usually what callers want.
540 ///
541 /// Walks the per-class buckets of `class` and its descendants rather than scanning
542 /// the dataset, so asking for every `ACLineSegment` costs their number rather than
543 /// the model's. Order is unspecified but stable for a given load.
544 pub fn iter_class(&self, class: ClassId) -> impl Iterator<Item = (ObjectId, &Object)> + '_ {
545 self.schema
546 .class(class)
547 .descendants
548 .iter()
549 .flat_map(move |&c| self.iter_exact(c))
550 }
551
552 pub fn count_class(&self, class: ClassId) -> usize {
553 self.schema
554 .class(class)
555 .descendants
556 .iter()
557 .map(|c| self.by_class.get(c.index()).map_or(0, |v| v.len()))
558 .sum()
559 }
560
561 /// Resolve a single-valued association to the referenced object.
562 pub fn follow(&self, object: &Object, attr: AttrId) -> Option<&Object> {
563 let mrid = object.get(attr)?.as_reference()?;
564 self.by_mrid(mrid)
565 }
566
567 /// Resolve every value of a many-valued association.
568 ///
569 /// References that do not resolve are skipped; use
570 /// [`validate`](crate::validate::validate) to report them.
571 pub fn follow_all<'a>(
572 &'a self,
573 object: &'a Object,
574 attr: AttrId,
575 ) -> impl Iterator<Item = &'a Object> + 'a {
576 object
577 .get_all(attr)
578 .iter()
579 .filter_map(|s| s.value.as_reference())
580 .filter_map(move |m| self.by_mrid(m))
581 }
582
583 /// Objects whose association `attr` points at `target`.
584 ///
585 /// This walks the inverse of a stored association. Inverse roles are deliberately not
586 /// stored on both sides — IEC 61970-501 marks exactly one side of each association as
587 /// serialized — so this is computed. Build an [`InverseIndex`] when querying repeatedly.
588 pub fn referrers<'a>(
589 &'a self,
590 target: &'a Mrid,
591 attr: AttrId,
592 ) -> impl Iterator<Item = (ObjectId, &'a Object)> + 'a {
593 self.iter().filter(move |(_, o)| {
594 o.get_all(attr)
595 .iter()
596 .any(|s| s.value.as_reference() == Some(target))
597 })
598 }
599
600 /// The namespace under which this crate derives identifiers.
601 ///
602 /// A fixed version-4 UUID, so that a derived mRID cannot collide with one derived for
603 /// a different purpose, here or anywhere else.
604 pub const DERIVED_NS: Mrid = Mrid::from_uuid_bytes([
605 0x2b, 0x0f, 0x9a, 0x71, 0x2c, 0x8e, 0x4a, 0x2f, 0x9c, 0x1a, 0x3f, 0x7f, 0x9d, 0x4b, 0x6e,
606 0x10,
607 ]);
608
609 /// A UUID that identifies *what this model contains*.
610 ///
611 /// Exporting a model needs a `md:FullModel rdf:about`, and a model built
612 /// programmatically has none. A random one would make every export of an unchanged
613 /// model differ from the last, which defeats a deterministic writer; a fixed one would
614 /// give two unrelated models the same identifier, which is worse. Deriving it from the
615 /// content gives both properties: unchanged model, unchanged identifier; changed
616 /// model, changed identifier.
617 ///
618 /// The fingerprint covers the vintage and, for every object in mRID order, its
619 /// identifier, its class and every stored value. What it deliberately does not cover
620 /// is anything about the *files* — headers, per-file provenance, load order — because
621 /// two ways of packaging one model are still that model.
622 ///
623 /// It is not a cryptographic commitment and is not offered as one: it is derived with
624 /// SHA-1, which is broken for collision resistance, and identifies a model against
625 /// accident rather than against an adversary.
626 pub fn content_id(&self) -> Mrid {
627 // Objects in mRID order, so the result does not depend on load order, into one
628 // buffer built from raw bytes rather than rendered text — a nation-scale model is
629 // a quarter of a million objects and this should not allocate per object.
630 // Separators keep two different models from hashing alike by running together at
631 // the seams.
632 let mut ids: Vec<(&Mrid, ObjectId)> = self.iter().map(|(id, o)| (o.mrid(), id)).collect();
633 ids.sort_by(|a, b| a.0.cmp(b.0));
634
635 let mut buf: Vec<u8> = Vec::with_capacity(self.len() * 24 + 32);
636 buf.extend_from_slice(self.schema.vintage.as_bytes());
637 for (mrid, id) in ids {
638 buf.push(0x1e);
639 match mrid.as_uuid_bytes() {
640 Some(b) => buf.extend_from_slice(b),
641 None => buf.extend_from_slice(mrid.canonical().as_bytes()),
642 }
643 let Some(o) = self.get(id) else { continue };
644 buf.push(0x1f);
645 buf.extend_from_slice(&o.class().0.to_le_bytes());
646 for slot in o.slots() {
647 buf.extend_from_slice(&slot.attr.0.to_le_bytes());
648 fold_value(&mut buf, &slot.value);
649 }
650 }
651 Mrid::new_v5(&Self::DERIVED_NS, &buf)
652 }
653
654 /// Release unused capacity after bulk loading.
655 pub fn shrink_to_fit(&mut self) {
656 for o in self.objects.iter_mut().flatten() {
657 o.shrink();
658 }
659 self.objects.shrink_to_fit();
660 self.class_slot.shrink_to_fit();
661 self.by_mrid.shrink_to_fit();
662 for v in self.by_class.iter_mut() {
663 v.shrink_to_fit();
664 }
665 }
666
667 /// References that point at objects not present in the dataset.
668 pub fn dangling_references(&self) -> Vec<(ObjectId, AttrId, Mrid)> {
669 let mut out = Vec::new();
670 for (id, obj) in self.iter() {
671 for slot in obj.slots() {
672 if let Value::Reference(m) = &slot.value
673 && !self.by_mrid.contains_key(m)
674 {
675 out.push((id, slot.attr, m.clone()));
676 }
677 }
678 }
679 out
680 }
681
682 /// Fail if the link policy is [`LinkPolicy::Strict`] and references are unresolved.
683 pub fn check_links(&self) -> Result<()> {
684 if self.link_policy == LinkPolicy::Strict {
685 let dangling = self.dangling_references();
686 if !dangling.is_empty() {
687 let (id, attr, mrid) = &dangling[0];
688 let owner = self
689 .get(*id)
690 .map(|o| o.mrid().canonical())
691 .unwrap_or_default();
692 return Err(Error::DanglingReference {
693 object: owner,
694 attribute: self.schema.attr(*attr).name,
695 target: mrid.canonical(),
696 total: dangling.len(),
697 });
698 }
699 }
700 Ok(())
701 }
702}
703
704/// Append one value to a content fingerprint, in its stored rather than its printed form.
705///
706/// Each variant is tagged, so a text value cannot fold to the same bytes as a reference
707/// that happens to spell the same thing; floats go in by bit pattern, which is exact where
708/// a rendered form would depend on the formatter.
709fn fold_value(buf: &mut Vec<u8>, v: &Value) {
710 match v {
711 Value::Boolean(b) => buf.extend_from_slice(&[1, *b as u8]),
712 Value::Integer(i) => {
713 buf.push(2);
714 buf.extend_from_slice(&i.to_le_bytes());
715 }
716 Value::Float(f) => {
717 buf.push(3);
718 // The number, not its spelling: two models that differ only in how a producer
719 // formatted a float are the same model, and `Real`'s equality says so too.
720 buf.extend_from_slice(&f.get().to_bits().to_le_bytes());
721 }
722 Value::Text(s) => {
723 buf.push(4);
724 buf.extend_from_slice(&(s.len() as u64).to_le_bytes());
725 buf.extend_from_slice(s.as_bytes());
726 }
727 Value::Enum(e) => {
728 buf.push(5);
729 buf.extend_from_slice(&e.0.to_le_bytes());
730 }
731 Value::Reference(m) => {
732 buf.push(6);
733 match m.as_uuid_bytes() {
734 Some(b) => buf.extend_from_slice(b),
735 None => buf.extend_from_slice(m.canonical().as_bytes()),
736 }
737 }
738 Value::Compound(c) => {
739 buf.push(7);
740 buf.extend_from_slice(&c.class().0.to_le_bytes());
741 for (a, v) in c.values() {
742 buf.extend_from_slice(&a.0.to_le_bytes());
743 fold_value(buf, v);
744 }
745 }
746 }
747 buf.push(0x1d);
748}
749
750/// A precomputed index from referenced object to the objects that reference it.
751///
752/// Building this once turns repeated [`Dataset::referrers`] scans into hash lookups,
753/// which matters for traversals such as "all terminals of this equipment".
754#[derive(Debug)]
755pub struct InverseIndex {
756 /// Keyed by target first so a lookup borrows the identifier rather than cloning it.
757 map: HashMap<Mrid, HashMap<AttrId, Vec<ObjectId>>>,
758}
759
760impl InverseIndex {
761 /// Index every association in the dataset.
762 pub fn build(dataset: &Dataset) -> InverseIndex {
763 let mut map: HashMap<Mrid, HashMap<AttrId, Vec<ObjectId>>> = HashMap::new();
764 for (id, obj) in dataset.iter() {
765 for slot in obj.slots() {
766 if matches!(
767 dataset.schema().attr(slot.attr).kind,
768 AttrKind::Association { .. }
769 ) && let Value::Reference(m) = &slot.value
770 {
771 map.entry(m.clone())
772 .or_default()
773 .entry(slot.attr)
774 .or_default()
775 .push(id);
776 }
777 }
778 }
779 InverseIndex { map }
780 }
781
782 /// Objects whose `attr` points at `target`.
783 pub fn referrers(&self, attr: AttrId, target: &Mrid) -> &[ObjectId] {
784 self.map
785 .get(target)
786 .and_then(|m| m.get(&attr))
787 .map(|v| v.as_slice())
788 .unwrap_or(&[])
789 }
790
791 /// Every object referring to `target`, whichever association it uses.
792 pub fn all_referrers(&self, target: &Mrid) -> impl Iterator<Item = (AttrId, ObjectId)> + '_ {
793 self.map.get(target).into_iter().flat_map(|m| {
794 m.iter()
795 .flat_map(|(a, v)| v.iter().map(move |id| (*a, *id)))
796 })
797 }
798
799 /// Resolve the inverse of `attr` — the role declared by `cims:inverseRoleName` —
800 /// for `target`, following whichever side the schema actually serializes.
801 pub fn inverse_of<'a>(
802 &'a self,
803 schema: &Schema,
804 attr: AttrId,
805 target: &Mrid,
806 ) -> &'a [ObjectId] {
807 match schema.attr(attr).kind {
808 AttrKind::Association {
809 inverse: Some(inv), ..
810 } => self.referrers(inv, target),
811 _ => &[],
812 }
813 }
814}
815
816impl Dataset {
817 /// Validate with the default checks.
818 ///
819 /// Shorthand for [`validate::validate`](crate::validate::validate).
820 pub fn validate(&self) -> crate::error::Report {
821 crate::validate::validate(self)
822 }
823
824 /// Validate with explicit options.
825 pub fn validate_with(
826 &self,
827 options: &crate::validate::ValidateOptions,
828 ) -> crate::error::Report {
829 crate::validate::validate_with(self, options)
830 }
831}