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