Skip to main content

cim_kit/
object.rs

1//! Objects: the storage unit of a CIM model.
2
3use crate::dataset::MergeConflict;
4use crate::mrid::Mrid;
5use crate::schema::{AttrId, ClassId, ProfileMask, Schema};
6use crate::value::Value;
7
8/// One stored attribute occurrence, with the profiles it came from.
9///
10/// Provenance matters because CGMES declares common attributes such as
11/// `IdentifiedObject.mRID` in almost every profile. Deciding what to write from
12/// declarations alone would repeat every object in every profile file; recording where a
13/// value actually came from reproduces the original file set exactly.
14#[derive(Clone, Debug, PartialEq)]
15pub struct Slot {
16    pub attr: AttrId,
17    /// Profiles whose instance files carried this value.
18    ///
19    /// Zero means the provenance is unknown — typically a value set programmatically —
20    /// in which case serialization falls back to the attribute's declared profiles.
21    pub profiles: ProfileMask,
22    pub value: Value,
23}
24
25impl Slot {
26    pub fn new(attr: AttrId, value: Value) -> Slot {
27        Slot {
28            attr,
29            profiles: 0,
30            value,
31        }
32    }
33
34    pub fn in_profiles(attr: AttrId, profiles: ProfileMask, value: Value) -> Slot {
35        Slot {
36            attr,
37            profiles,
38            value,
39        }
40    }
41}
42
43/// A structured value with no identity of its own.
44///
45/// IEC 61970-552 serializes a `Compound` inline — `rdf:parseType="Resource"` inside the
46/// property element that holds it — rather than as a reference, because it has no mRID to
47/// point at. CGMES 3.0 uses this for postal addresses in the Geographical Location
48/// profile (`Location.mainAddress` → `StreetAddress` → `StreetDetail`), and compounds
49/// nest.
50///
51/// Storage mirrors [`Object`]: a vector sorted by [`AttrId`], with repeats adjacent.
52/// A compound carries no profile provenance of its own; it belongs to whichever
53/// [`Slot`] holds it.
54#[derive(Clone, Debug, PartialEq)]
55pub struct Compound {
56    class: ClassId,
57    values: Vec<(AttrId, Value)>,
58}
59
60impl Compound {
61    pub fn new(class: ClassId) -> Compound {
62        Compound {
63            class,
64            values: Vec::new(),
65        }
66    }
67
68    /// The compound type, e.g. `StreetAddress`.
69    #[inline]
70    pub fn class(&self) -> ClassId {
71        self.class
72    }
73
74    /// All stored `(attribute, value)` pairs, in attribute order.
75    #[inline]
76    pub fn values(&self) -> &[(AttrId, Value)] {
77        &self.values
78    }
79
80    #[inline]
81    pub fn is_empty(&self) -> bool {
82        self.values.is_empty()
83    }
84
85    #[inline]
86    pub fn len(&self) -> usize {
87        self.values.len()
88    }
89
90    fn range(&self, attr: AttrId) -> std::ops::Range<usize> {
91        let start = self.values.partition_point(|(a, _)| *a < attr);
92        let end = self.values[start..].partition_point(|(a, _)| *a == attr) + start;
93        start..end
94    }
95
96    /// First value of `attr`, if present.
97    #[inline]
98    pub fn get(&self, attr: AttrId) -> Option<&Value> {
99        let r = self.range(attr);
100        self.values
101            .get(r.start)
102            .filter(|(a, _)| *a == attr)
103            .map(|(_, v)| v)
104    }
105
106    /// All values of `attr`, for many-valued fields.
107    #[inline]
108    pub fn get_all(&self, attr: AttrId) -> &[(AttrId, Value)] {
109        &self.values[self.range(attr)]
110    }
111
112    /// Every value of `attr` — the uniform accessor generated views use.
113    #[inline]
114    pub fn all(&self, attr: AttrId) -> impl Iterator<Item = &Value> {
115        self.get_all(attr).iter().map(|(_, v)| v)
116    }
117
118    pub fn has(&self, attr: AttrId) -> bool {
119        !self.range(attr).is_empty()
120    }
121
122    pub fn count(&self, attr: AttrId) -> usize {
123        self.range(attr).len()
124    }
125
126    /// Replace every occurrence of `attr` with a single value.
127    pub fn set(&mut self, attr: AttrId, value: Value) {
128        let r = self.range(attr);
129        self.values.splice(r, std::iter::once((attr, value)));
130    }
131
132    /// Append another occurrence of `attr`, keeping storage sorted.
133    pub fn push(&mut self, attr: AttrId, value: Value) {
134        let r = self.range(attr);
135        self.values.insert(r.end, (attr, value));
136    }
137}
138
139/// A single CIM object.
140///
141/// Storage is sparse — only attributes actually present are stored — which matches how
142/// CIM data behaves: a `Terminal` carries roughly thirty possible attributes but a
143/// Steady State Hypothesis file sets exactly one of them. Slots are kept sorted by
144/// [`AttrId`], with repeats adjacent for many-valued attributes.
145#[derive(Clone, Debug)]
146pub struct Object {
147    pub(crate) class: ClassId,
148    pub(crate) mrid: Mrid,
149    /// Sorted by `AttrId`; duplicates are permitted and adjacent.
150    pub(crate) values: Vec<Slot>,
151    /// Profiles whose instance files contributed data to this object.
152    pub(crate) profiles: ProfileMask,
153    /// Whether this object came from a file, rather than being built programmatically.
154    ///
155    /// Which file is recorded by the dataset rather than here — see
156    /// [`Dataset::objects_from`](crate::Dataset::objects_from) — because an object appears
157    /// in as many files as there are profiles describing it, and a per-object set would
158    /// cost more than the index does.
159    pub(crate) from_file: bool,
160}
161
162impl Object {
163    pub fn new(class: ClassId, mrid: Mrid) -> Object {
164        Object {
165            class,
166            mrid,
167            values: Vec::new(),
168            profiles: 0,
169            from_file: false,
170        }
171    }
172
173    #[inline]
174    pub fn class(&self) -> ClassId {
175        self.class
176    }
177
178    #[inline]
179    pub fn mrid(&self) -> &Mrid {
180        &self.mrid
181    }
182
183    /// Profiles that contributed data to this object.
184    #[inline]
185    pub fn profiles(&self) -> ProfileMask {
186        self.profiles
187    }
188
189    /// Whether this object was read from a file rather than built programmatically.
190    #[inline]
191    pub fn from_file(&self) -> bool {
192        self.from_file
193    }
194
195    /// Change the object's class, e.g. when a later profile reveals a more specific type.
196    pub(crate) fn set_class(&mut self, class: ClassId) {
197        self.class = class;
198    }
199
200    pub(crate) fn mark_profile(&mut self, mask: ProfileMask) {
201        self.profiles |= mask;
202    }
203
204    /// All stored slots, in attribute order.
205    #[inline]
206    pub fn slots(&self) -> &[Slot] {
207        &self.values
208    }
209
210    /// All stored `(attribute, value)` pairs, in attribute order.
211    pub fn values(&self) -> impl Iterator<Item = (AttrId, &Value)> + '_ {
212        self.values.iter().map(|s| (s.attr, &s.value))
213    }
214
215    /// Number of stored attribute occurrences.
216    #[inline]
217    pub fn len(&self) -> usize {
218        self.values.len()
219    }
220
221    #[inline]
222    pub fn is_empty(&self) -> bool {
223        self.values.is_empty()
224    }
225
226    /// Half-open range of `values` holding occurrences of `attr`.
227    fn range(&self, attr: AttrId) -> std::ops::Range<usize> {
228        let start = self.values.partition_point(|s| s.attr < attr);
229        let end = self.values[start..].partition_point(|s| s.attr == attr) + start;
230        start..end
231    }
232
233    /// First value of `attr`, if present.
234    #[inline]
235    pub fn get(&self, attr: AttrId) -> Option<&Value> {
236        self.get_slot(attr).map(|s| &s.value)
237    }
238
239    /// First slot of `attr`, including its provenance.
240    #[inline]
241    pub fn get_slot(&self, attr: AttrId) -> Option<&Slot> {
242        let r = self.range(attr);
243        // An empty range still points at the next attribute, so the identity of the
244        // slot found must be checked rather than assumed.
245        self.values.get(r.start).filter(|s| s.attr == attr)
246    }
247
248    /// All slots of `attr`, for many-valued attributes.
249    #[inline]
250    pub fn get_all(&self, attr: AttrId) -> &[Slot] {
251        &self.values[self.range(attr)]
252    }
253
254    /// Every value of `attr` — the uniform accessor generated views use.
255    #[inline]
256    pub fn all(&self, attr: AttrId) -> impl Iterator<Item = &Value> {
257        self.get_all(attr).iter().map(|s| &s.value)
258    }
259
260    /// Number of stored occurrences of `attr`.
261    pub fn count(&self, attr: AttrId) -> usize {
262        self.range(attr).len()
263    }
264
265    pub fn has(&self, attr: AttrId) -> bool {
266        !self.range(attr).is_empty()
267    }
268
269    /// Replace every occurrence of `attr` with a single value of unknown provenance.
270    pub fn set(&mut self, attr: AttrId, value: Value) {
271        self.set_slot(Slot::new(attr, value));
272    }
273
274    /// Replace every occurrence of `attr`, recording which profile the value belongs to.
275    pub fn set_in(&mut self, profiles: ProfileMask, attr: AttrId, value: Value) {
276        self.set_slot(Slot::in_profiles(attr, profiles, value));
277    }
278
279    pub fn set_slot(&mut self, slot: Slot) {
280        let r = self.range(slot.attr);
281        self.values.splice(r, std::iter::once(slot));
282    }
283
284    /// Append another occurrence of `attr`, keeping storage sorted.
285    pub fn push(&mut self, attr: AttrId, value: Value) {
286        self.push_slot(Slot::new(attr, value));
287    }
288
289    /// Append another occurrence, recording which profile the value belongs to.
290    pub fn push_in(&mut self, profiles: ProfileMask, attr: AttrId, value: Value) {
291        self.push_slot(Slot::in_profiles(attr, profiles, value));
292    }
293
294    pub fn push_slot(&mut self, slot: Slot) {
295        let r = self.range(slot.attr);
296        self.values.insert(r.end, slot);
297    }
298
299    /// Remove every occurrence of `attr`, returning how many were removed.
300    pub fn remove(&mut self, attr: AttrId) -> usize {
301        let r = self.range(attr);
302        let n = r.len();
303        self.values.drain(r);
304        n
305    }
306
307    /// Remove one specific `(attr, value)` occurrence, e.g. when applying a
308    /// difference model's reverse statements. Returns whether one was removed.
309    pub fn remove_value(&mut self, attr: AttrId, value: &Value) -> bool {
310        let r = self.range(attr);
311        match self.values[r.clone()]
312            .iter()
313            .position(|s| s.value == *value)
314        {
315            Some(i) => {
316                self.values.remove(r.start + i);
317                true
318            }
319            None => false,
320        }
321    }
322
323    /// Keep the slots `keep` accepts, returning the rest in storage order.
324    ///
325    /// The removed slots are handed back rather than dropped so that a caller thinning an
326    /// object — reclassifying it, say — can say what went.
327    pub(crate) fn retain_slots(&mut self, keep: impl Fn(&Slot) -> bool) -> Vec<Slot> {
328        let mut shed = Vec::new();
329        self.values.retain(|s| {
330            let keeping = keep(s);
331            if !keeping {
332                shed.push(s.clone());
333            }
334            keeping
335        });
336        shed
337    }
338
339    /// Record that `attr`'s existing value also came from `profiles`.
340    pub(crate) fn merge_provenance(&mut self, attr: AttrId, value: &Value, profiles: ProfileMask) {
341        let r = self.range(attr);
342        if let Some(s) = self.values[r].iter_mut().find(|s| s.value == *value) {
343            s.profiles |= profiles;
344        }
345    }
346
347    /// Fold in another description of the same object.
348    ///
349    /// The more specific class wins, since a profile may describe an object through a base
350    /// class. A value both hold widens its provenance rather than being stored twice, so an
351    /// export reproduces both files; a many-valued one is added; a single-valued one that
352    /// differs is replaced by the incoming value and returned as a conflict.
353    pub(crate) fn absorb(&mut self, incoming: Object, schema: &Schema) -> Vec<MergeConflict> {
354        if schema.is_a(incoming.class, self.class) {
355            self.class = incoming.class;
356        }
357        self.profiles |= incoming.profiles;
358        self.from_file |= incoming.from_file;
359        let mut conflicts = Vec::new();
360        for slot in incoming.values {
361            if self
362                .get_all(slot.attr)
363                .iter()
364                .any(|s| s.value == slot.value)
365            {
366                self.merge_provenance(slot.attr, &slot.value, slot.profiles);
367            } else if schema.attr(slot.attr).mult.is_many() {
368                self.push_slot(slot);
369            } else {
370                // Provenance is unioned so both files still carry the attribute on export.
371                let mut slot = slot;
372                if let Some(old) = self.get_slot(slot.attr) {
373                    slot.profiles |= old.profiles;
374                    conflicts.push(MergeConflict {
375                        object: self.mrid.clone(),
376                        attr: slot.attr,
377                        kept: slot.value.clone(),
378                        discarded: old.value.clone(),
379                    });
380                }
381                self.set_slot(slot);
382            }
383        }
384        conflicts
385    }
386
387    /// Shrink storage after bulk loading.
388    pub(crate) fn shrink(&mut self) {
389        self.values.shrink_to_fit();
390    }
391
392    /// Release the parser's over-allocation as soon as an object is complete.
393    ///
394    /// Objects are sparse, so a growth-doubled `Vec` typically holds far more capacity
395    /// than it needs; over a million objects that adds up.
396    pub(crate) fn shrink_for_load(&mut self) {
397        if self.values.capacity() > self.values.len() * 2 {
398            self.values.shrink_to_fit();
399        }
400    }
401}
402
403#[cfg(test)]
404mod tests {
405    use super::*;
406
407    fn obj() -> Object {
408        Object::new(
409            ClassId(0),
410            Mrid::parse("70c4656c-f7a0-4319-98bb-84fb5e2e9b37"),
411        )
412    }
413
414    #[test]
415    fn values_stay_sorted_regardless_of_insertion_order() {
416        let mut o = obj();
417        o.push(AttrId(5), Value::Integer(5));
418        o.push(AttrId(1), Value::Integer(1));
419        o.push(AttrId(3), Value::Integer(3));
420        let ids: Vec<u16> = o.slots().iter().map(|s| s.attr.0).collect();
421        assert_eq!(ids, [1, 3, 5]);
422    }
423
424    #[test]
425    fn many_valued_attributes_keep_every_occurrence_in_order() {
426        let mut o = obj();
427        o.push(AttrId(2), Value::Integer(1));
428        o.push(AttrId(9), Value::Integer(99));
429        o.push(AttrId(2), Value::Integer(2));
430        assert_eq!(o.count(AttrId(2)), 2);
431        let got: Vec<i64> = o
432            .get_all(AttrId(2))
433            .iter()
434            .map(|s| s.value.as_i64().unwrap())
435            .collect();
436        assert_eq!(got, [1, 2]);
437        assert_eq!(o.get(AttrId(2)).unwrap().as_i64(), Some(1));
438    }
439
440    #[test]
441    fn set_replaces_all_occurrences() {
442        let mut o = obj();
443        o.push(AttrId(2), Value::Integer(1));
444        o.push(AttrId(2), Value::Integer(2));
445        o.push(AttrId(4), Value::Integer(4));
446        o.set(AttrId(2), Value::Integer(9));
447        assert_eq!(o.count(AttrId(2)), 1);
448        assert_eq!(o.get(AttrId(2)).unwrap().as_i64(), Some(9));
449        // Neighbouring attributes are untouched.
450        assert_eq!(o.get(AttrId(4)).unwrap().as_i64(), Some(4));
451    }
452
453    #[test]
454    fn remove_value_removes_exactly_one_matching_occurrence() {
455        let mut o = obj();
456        o.push(AttrId(2), Value::Integer(1));
457        o.push(AttrId(2), Value::Integer(2));
458        assert!(o.remove_value(AttrId(2), &Value::Integer(1)));
459        assert_eq!(o.count(AttrId(2)), 1);
460        assert_eq!(o.get(AttrId(2)).unwrap().as_i64(), Some(2));
461        assert!(!o.remove_value(AttrId(2), &Value::Integer(7)));
462    }
463
464    #[test]
465    fn missing_attributes_report_absent() {
466        let o = obj();
467        assert!(!o.has(AttrId(1)));
468        assert_eq!(o.get(AttrId(1)), None);
469        assert!(o.get_all(AttrId(1)).is_empty());
470    }
471
472    #[test]
473    fn absent_attribute_does_not_return_its_neighbour() {
474        // Sorted storage means the lookup position for a missing attribute is occupied
475        // by the next one; the identity of what is found must be checked.
476        let mut o = obj();
477        o.push(AttrId(1), Value::Integer(10));
478        o.push(AttrId(3), Value::Integer(30));
479        for missing in [AttrId(0), AttrId(2), AttrId(4)] {
480            assert_eq!(o.get(missing), None, "{missing:?}");
481            assert_eq!(o.get_slot(missing), None, "{missing:?}");
482            assert!(!o.has(missing), "{missing:?}");
483            assert_eq!(o.count(missing), 0, "{missing:?}");
484        }
485        assert_eq!(o.get(AttrId(1)).unwrap().as_i64(), Some(10));
486        assert_eq!(o.get(AttrId(3)).unwrap().as_i64(), Some(30));
487    }
488
489    #[test]
490    fn provenance_is_recorded_and_merged() {
491        let mut o = obj();
492        o.push_in(0b0100, AttrId(1), Value::Integer(1));
493        assert_eq!(o.get_slot(AttrId(1)).unwrap().profiles, 0b0100);
494        // The same value seen again in another profile widens its provenance.
495        o.merge_provenance(AttrId(1), &Value::Integer(1), 0b1000);
496        assert_eq!(o.get_slot(AttrId(1)).unwrap().profiles, 0b1100);
497        // A different value is left alone.
498        o.merge_provenance(AttrId(1), &Value::Integer(2), 0b0001);
499        assert_eq!(o.get_slot(AttrId(1)).unwrap().profiles, 0b1100);
500    }
501
502    #[test]
503    fn provenance_defaults_to_unknown() {
504        let mut o = obj();
505        o.set(AttrId(1), Value::Integer(1));
506        assert_eq!(o.get_slot(AttrId(1)).unwrap().profiles, 0);
507    }
508}