Skip to main content

cim_kit/
object.rs

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