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 self.insert_new(object)
257 }
258
259 pub(crate) fn insert_new(&mut self, object: Object) -> ObjectId {
261 debug_assert!(!self.by_mrid.contains_key(&object.mrid));
262 let id = ObjectId(self.objects.len() as u32);
263 let class = object.class;
264 self.by_mrid.insert(object.mrid.clone(), id);
265 self.objects.push(Some(object));
266 self.class_slot.push(0);
267 self.attach_to_class(id, class);
268 id
269 }
270
271 #[cfg_attr(
278 feature = "cgmes3",
279 doc = r#"
280```no_run
281# use cim_kit::prelude::*;
282# use cim_kit::cgmes3::SCHEMA;
283# fn main() -> cim_kit::Result<()> {
284let mut model = Dataset::new(SCHEMA);
285for part in ["EQ.xml", "SSH.xml", "TP.xml", "SV.xml"]
286 .map(|f| Dataset::load(SCHEMA, [f]))
287{
288 model.merge(part?)?;
289}
290# Ok(()) }
291```
292"#
293 )]
294 pub fn merge(&mut self, other: Dataset) -> Result<()> {
300 if !std::ptr::eq(self.schema, other.schema) {
301 return Err(Error::SchemaMismatch {
302 left: self.schema.vintage,
303 right: other.schema.vintage,
304 });
305 }
306 let base = self.headers.len();
307 for h in other.headers {
308 self.push_header(h);
309 }
310 for d in other.differences {
311 self.push_difference(d);
312 }
313 self.applied.extend(other.applied);
314 self.superseded.extend(other.superseded);
315
316 let mut moved: Vec<Option<ObjectId>> = vec![None; other.objects.len()];
319 for (i, slot) in other.objects.into_iter().enumerate() {
320 if let Some(o) = slot {
321 moved[i] = Some(self.insert(o));
322 }
323 }
324 for (i, ids) in other.by_source.into_iter().enumerate() {
325 for id in ids {
326 if let Some(new) = moved.get(id.index()).copied().flatten() {
327 self.record_source(base + i, new);
328 }
329 }
330 }
331
332 for c in other.conflicts {
333 self.record_conflict(c);
334 }
335 self.conflicts_dropped += other.conflicts_dropped;
336 Ok(())
337 }
338
339 fn attach_to_class(&mut self, id: ObjectId, class: ClassId) {
341 let Some(bucket) = self.by_class.get_mut(class.index()) else {
342 return;
343 };
344 self.class_slot[id.index()] = bucket.len() as u32;
345 bucket.push(id);
346 }
347
348 fn detach_from_class(&mut self, id: ObjectId, class: ClassId) {
352 let slot = self.class_slot[id.index()] as usize;
353 let Some(bucket) = self.by_class.get_mut(class.index()) else {
354 return;
355 };
356 debug_assert_eq!(bucket.get(slot), Some(&id), "class index out of step");
357 bucket.swap_remove(slot);
358 if let Some(&moved) = bucket.get(slot) {
359 self.class_slot[moved.index()] = slot as u32;
360 }
361 }
362
363 fn merge_into(&mut self, target: ObjectId, incoming: Object) {
364 for c in self.absorb(target, incoming) {
365 self.record_conflict(c);
366 }
367 }
368
369 pub(crate) fn absorb(&mut self, target: ObjectId, incoming: Object) -> Vec<MergeConflict> {
371 let schema = self.schema;
372 let Some(obj) = self.objects[target.index()].as_mut() else {
373 return Vec::new();
374 };
375 let old_class = obj.class;
376 let conflicts = obj.absorb(incoming, schema);
377 let new_class = obj.class;
378 if new_class != old_class {
379 self.detach_from_class(target, old_class);
380 self.attach_to_class(target, new_class);
381 }
382 conflicts
383 }
384
385 pub(crate) fn slot_count(&self) -> usize {
387 self.objects.len()
388 }
389
390 pub(crate) fn record_conflict(&mut self, conflict: MergeConflict) {
391 if self.conflicts.len() < Self::MAX_CONFLICTS {
392 self.conflicts.push(conflict);
393 } else {
394 self.conflicts_dropped += 1;
395 }
396 }
397
398 pub fn merge_conflicts(&self) -> &[MergeConflict] {
405 &self.conflicts
406 }
407
408 pub fn merge_conflicts_dropped(&self) -> usize {
410 self.conflicts_dropped
411 }
412
413 pub fn reclassify(&mut self, id: ObjectId, class: ClassId) -> Vec<crate::object::Slot> {
423 let schema = self.schema;
424 let Some(old) = self.get(id).map(|o| o.class()) else {
425 return Vec::new();
426 };
427 if old == class {
428 return Vec::new();
429 }
430 self.detach_from_class(id, old);
431 self.attach_to_class(id, class);
432 let Some(o) = self.objects[id.index()].as_mut() else {
433 return Vec::new();
434 };
435 o.set_class(class);
436 o.retain_slots(|slot| schema.is_a(class, schema.attr(slot.attr).owner))
437 }
438
439 pub fn remove(&mut self, id: ObjectId) -> Option<Object> {
441 let obj = self.objects.get_mut(id.index())?.take()?;
442 self.by_mrid.remove(&obj.mrid);
443 self.detach_from_class(id, obj.class);
444 Some(obj)
445 }
446
447 pub fn iter(&self) -> impl Iterator<Item = (ObjectId, &Object)> + '_ {
449 self.objects
450 .iter()
451 .enumerate()
452 .filter_map(|(i, o)| Some((ObjectId(i as u32), o.as_ref()?)))
453 }
454
455 pub fn iter_exact(&self, class: ClassId) -> impl Iterator<Item = (ObjectId, &Object)> + '_ {
457 self.by_class
458 .get(class.index())
459 .map_or(&[][..], |v| v.as_slice())
460 .iter()
461 .filter_map(move |&id| self.get(id).map(|o| (id, o)))
462 }
463
464 pub fn iter_class(&self, class: ClassId) -> impl Iterator<Item = (ObjectId, &Object)> + '_ {
469 self.schema
470 .class(class)
471 .descendants
472 .iter()
473 .flat_map(move |&c| self.iter_exact(c))
474 }
475
476 pub fn count_class(&self, class: ClassId) -> usize {
477 self.schema
478 .class(class)
479 .descendants
480 .iter()
481 .map(|c| self.by_class.get(c.index()).map_or(0, |v| v.len()))
482 .sum()
483 }
484
485 pub fn follow(&self, object: &Object, attr: AttrId) -> Option<&Object> {
487 let mrid = object.get(attr)?.as_reference()?;
488 self.by_mrid(mrid)
489 }
490
491 pub fn follow_all<'a>(
496 &'a self,
497 object: &'a Object,
498 attr: AttrId,
499 ) -> impl Iterator<Item = &'a Object> + 'a {
500 object
501 .get_all(attr)
502 .iter()
503 .filter_map(|s| s.value.as_reference())
504 .filter_map(move |m| self.by_mrid(m))
505 }
506
507 pub fn referrers<'a>(
512 &'a self,
513 target: &'a Mrid,
514 attr: AttrId,
515 ) -> impl Iterator<Item = (ObjectId, &'a Object)> + 'a {
516 self.iter().filter(move |(_, o)| {
517 o.get_all(attr)
518 .iter()
519 .any(|s| s.value.as_reference() == Some(target))
520 })
521 }
522
523 pub const DERIVED_NS: Mrid = Mrid::from_uuid_bytes([
527 0x2b, 0x0f, 0x9a, 0x71, 0x2c, 0x8e, 0x4a, 0x2f, 0x9c, 0x1a, 0x3f, 0x7f, 0x9d, 0x4b, 0x6e,
528 0x10,
529 ]);
530
531 pub fn content_id(&self) -> Mrid {
541 let mut ids: Vec<(&Mrid, ObjectId)> = self.iter().map(|(id, o)| (o.mrid(), id)).collect();
544 ids.sort_by(|a, b| a.0.cmp(b.0));
545
546 let mut buf: Vec<u8> = Vec::with_capacity(self.len() * 24 + 32);
547 buf.extend_from_slice(self.schema.vintage.as_bytes());
548 for (mrid, id) in ids {
549 buf.push(0x1e);
550 match mrid.as_uuid_bytes() {
551 Some(b) => buf.extend_from_slice(b),
552 None => buf.extend_from_slice(mrid.canonical().as_bytes()),
553 }
554 let Some(o) = self.get(id) else { continue };
555 buf.push(0x1f);
556 buf.extend_from_slice(&o.class().0.to_le_bytes());
557 for slot in o.slots() {
558 buf.extend_from_slice(&slot.attr.0.to_le_bytes());
559 fold_value(&mut buf, &slot.value);
560 }
561 }
562 Mrid::new_v5(&Self::DERIVED_NS, &buf)
563 }
564
565 pub fn shrink_to_fit(&mut self) {
567 for o in self.objects.iter_mut().flatten() {
568 o.shrink();
569 }
570 self.objects.shrink_to_fit();
571 self.class_slot.shrink_to_fit();
572 self.by_mrid.shrink_to_fit();
573 for v in self.by_class.iter_mut() {
574 v.shrink_to_fit();
575 }
576 }
577
578 pub fn dangling_references(&self) -> Vec<(ObjectId, AttrId, Mrid)> {
580 let mut out = Vec::new();
581 for (id, obj) in self.iter() {
582 for slot in obj.slots() {
583 if let Value::Reference(m) = &slot.value
584 && !self.by_mrid.contains_key(m)
585 {
586 out.push((id, slot.attr, m.clone()));
587 }
588 }
589 }
590 out
591 }
592
593 pub fn check_links(&self) -> Result<()> {
595 if self.link_policy == LinkPolicy::Strict {
596 let dangling = self.dangling_references();
597 if !dangling.is_empty() {
598 let (id, attr, mrid) = &dangling[0];
599 let owner = self
600 .get(*id)
601 .map(|o| o.mrid().canonical())
602 .unwrap_or_default();
603 return Err(Error::DanglingReference {
604 object: owner,
605 attribute: self.schema.attr(*attr).name,
606 target: mrid.canonical(),
607 total: dangling.len(),
608 });
609 }
610 }
611 Ok(())
612 }
613}
614
615fn fold_value(buf: &mut Vec<u8>, v: &Value) {
619 match v {
620 Value::Boolean(b) => buf.extend_from_slice(&[1, *b as u8]),
621 Value::Integer(i) => {
622 buf.push(2);
623 buf.extend_from_slice(&i.to_le_bytes());
624 }
625 Value::Float(f) => {
626 buf.push(3);
627 buf.extend_from_slice(&f.get().to_bits().to_le_bytes());
629 }
630 Value::Text(s) => {
631 buf.push(4);
632 buf.extend_from_slice(&(s.len() as u64).to_le_bytes());
633 buf.extend_from_slice(s.as_bytes());
634 }
635 Value::Enum(e) => {
636 buf.push(5);
637 buf.extend_from_slice(&e.0.to_le_bytes());
638 }
639 Value::Reference(m) => {
640 buf.push(6);
641 match m.as_uuid_bytes() {
642 Some(b) => buf.extend_from_slice(b),
643 None => buf.extend_from_slice(m.canonical().as_bytes()),
644 }
645 }
646 Value::Compound(c) => {
647 buf.push(7);
648 buf.extend_from_slice(&c.class().0.to_le_bytes());
649 for (a, v) in c.values() {
650 buf.extend_from_slice(&a.0.to_le_bytes());
651 fold_value(buf, v);
652 }
653 }
654 }
655 buf.push(0x1d);
656}
657
658#[derive(Debug)]
662pub struct InverseIndex {
663 map: HashMap<Mrid, HashMap<AttrId, Vec<ObjectId>>>,
665}
666
667impl InverseIndex {
668 pub fn build(dataset: &Dataset) -> InverseIndex {
670 let mut map: HashMap<Mrid, HashMap<AttrId, Vec<ObjectId>>> = HashMap::new();
671 for (id, obj) in dataset.iter() {
672 for slot in obj.slots() {
673 if matches!(
674 dataset.schema().attr(slot.attr).kind,
675 AttrKind::Association { .. }
676 ) && let Value::Reference(m) = &slot.value
677 {
678 map.entry(m.clone())
679 .or_default()
680 .entry(slot.attr)
681 .or_default()
682 .push(id);
683 }
684 }
685 }
686 InverseIndex { map }
687 }
688
689 pub fn referrers(&self, attr: AttrId, target: &Mrid) -> &[ObjectId] {
691 self.map
692 .get(target)
693 .and_then(|m| m.get(&attr))
694 .map(|v| v.as_slice())
695 .unwrap_or(&[])
696 }
697
698 pub fn all_referrers(&self, target: &Mrid) -> impl Iterator<Item = (AttrId, ObjectId)> + '_ {
700 self.map.get(target).into_iter().flat_map(|m| {
701 m.iter()
702 .flat_map(|(a, v)| v.iter().map(move |id| (*a, *id)))
703 })
704 }
705
706 pub fn inverse_of<'a>(
709 &'a self,
710 schema: &Schema,
711 attr: AttrId,
712 target: &Mrid,
713 ) -> &'a [ObjectId] {
714 match schema.attr(attr).kind {
715 AttrKind::Association {
716 inverse: Some(inv), ..
717 } => self.referrers(inv, target),
718 _ => &[],
719 }
720 }
721}
722
723impl Dataset {
724 pub fn validate(&self) -> crate::error::Report {
728 crate::validate::validate(self)
729 }
730
731 pub fn validate_with(
733 &self,
734 options: &crate::validate::ValidateOptions,
735 ) -> crate::error::Report {
736 crate::validate::validate_with(self, options)
737 }
738}