1use 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#[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#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
27pub enum LinkPolicy {
28 Strict,
30 #[default]
36 Lenient,
37}
38
39#[derive(Debug)]
44pub struct Dataset {
45 schema: &'static Schema,
46 objects: Vec<Option<Object>>,
48 by_mrid: HashMap<Mrid, ObjectId>,
49 by_class: Vec<Vec<ObjectId>>,
53 class_slot: Vec<u32>,
57 headers: Vec<ModelHeader>,
58 by_source: Vec<Vec<ObjectId>>,
60 differences: Vec<DifferenceModel>,
61 applied: Vec<Mrid>,
64 superseded: Vec<Mrid>,
66 link_policy: LinkPolicy,
67 conflicts: Vec<MergeConflict>,
69 conflicts_dropped: usize,
71}
72
73#[derive(Clone, Debug)]
80pub struct MergeConflict {
81 pub object: Mrid,
82 pub attr: AttrId,
83 pub kept: Value,
85 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 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 #[inline]
130 pub fn headers(&self) -> &[ModelHeader] {
131 &self.headers
132 }
133
134 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 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 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 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 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 pub fn differences(&self) -> &[DifferenceModel] {
186 &self.differences
187 }
188
189 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 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 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 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 #[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 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 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 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 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 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 obj.merge_provenance(slot.attr, &slot.value, slot.profiles);
392 } else if many {
393 obj.push_slot(slot);
394 } else {
395 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 pub fn merge_conflicts(&self) -> &[MergeConflict] {
431 &self.conflicts
432 }
433
434 pub fn merge_conflicts_dropped(&self) -> usize {
436 self.conflicts_dropped
437 }
438
439 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 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 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 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 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 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 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 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 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 pub fn content_id(&self) -> Mrid {
567 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 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 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 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
641fn 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 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#[derive(Debug)]
688pub struct InverseIndex {
689 map: HashMap<Mrid, HashMap<AttrId, Vec<ObjectId>>>,
691}
692
693impl InverseIndex {
694 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 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 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 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 pub fn validate(&self) -> crate::error::Report {
754 crate::validate::validate(self)
755 }
756
757 pub fn validate_with(
759 &self,
760 options: &crate::validate::ValidateOptions,
761 ) -> crate::error::Report {
762 crate::validate::validate_with(self, options)
763 }
764}