Skip to main content

cim_kit/
view.rs

1//! Typed views over stored objects.
2//!
3//! A view is a borrowed, zero-cost wrapper that gives schema-checked access to one
4//! class's attributes. Generated views live in each vintage's `views` module; this
5//! module holds the machinery they share.
6
7use std::marker::PhantomData;
8
9use crate::dataset::{Dataset, ObjectId};
10use crate::mrid::Mrid;
11use crate::object::Object;
12use crate::schema::ClassId;
13
14/// A typed view over an [`Object`] of a known class.
15pub trait TypedView<'a>: Sized + Copy {
16    /// The class this view represents.
17    const CLASS: ClassId;
18
19    /// Wrap an object without checking its class.
20    fn from_object(object: &'a Object) -> Self;
21
22    /// The underlying object.
23    fn object(&self) -> &'a Object;
24
25    /// Wrap an object only if its class matches, including subclasses.
26    fn try_from_object(schema: &crate::schema::Schema, object: &'a Object) -> Option<Self> {
27        schema
28            .is_a(object.class(), Self::CLASS)
29            .then(|| Self::from_object(object))
30    }
31
32    /// The object's master resource identifier.
33    fn mrid(&self) -> &'a Mrid {
34        self.object().mrid()
35    }
36}
37
38/// A reference to an object of a known class, stored as its mRID.
39///
40/// CIM associations are serialized as identifiers, and exactly one side of each
41/// association is written, so references are resolved through the dataset rather than
42/// stored as pointers. `TypedRef` keeps the target class in the type so that resolving
43/// it yields the right view without a cast.
44#[derive(Clone, PartialEq, Eq, Hash)]
45pub struct TypedRef<T> {
46    mrid: Mrid,
47    _marker: PhantomData<fn() -> T>,
48}
49
50impl<T> TypedRef<T> {
51    pub fn new(mrid: Mrid) -> Self {
52        TypedRef {
53            mrid,
54            _marker: PhantomData,
55        }
56    }
57
58    /// The referenced identifier.
59    pub fn mrid(&self) -> &Mrid {
60        &self.mrid
61    }
62
63    pub fn into_mrid(self) -> Mrid {
64        self.mrid
65    }
66}
67
68impl<T> std::fmt::Debug for TypedRef<T> {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        write!(f, "TypedRef({})", self.mrid)
71    }
72}
73
74impl<'a, T: TypedView<'a>> TypedRef<T> {
75    /// Resolve through `dataset`, returning `None` if the target is absent.
76    pub fn get(&self, dataset: &'a Dataset) -> Option<T> {
77        dataset.by_mrid(&self.mrid).map(T::from_object)
78    }
79
80    /// Resolve, checking that the target really is of the expected class.
81    pub fn get_checked(&self, dataset: &'a Dataset) -> Option<T> {
82        let o = dataset.by_mrid(&self.mrid)?;
83        T::try_from_object(dataset.schema(), o)
84    }
85
86    /// Whether the target is present in `dataset`.
87    pub fn is_resolvable(&self, dataset: &Dataset) -> bool {
88        dataset.find(&self.mrid).is_some()
89    }
90}
91
92/// Iterate every object of a class as a typed view, subclasses included.
93pub fn iter_view<'a, T: TypedView<'a>>(dataset: &'a Dataset) -> impl Iterator<Item = T> + 'a {
94    dataset.iter_class(T::CLASS).map(|(_, o)| T::from_object(o))
95}
96
97/// Iterate every object of a class with its handle.
98pub fn iter_view_ids<'a, T: TypedView<'a>>(
99    dataset: &'a Dataset,
100) -> impl Iterator<Item = (ObjectId, T)> + 'a {
101    dataset
102        .iter_class(T::CLASS)
103        .map(|(id, o)| (id, T::from_object(o)))
104}
105
106/// Look up one object by mRID as a typed view.
107pub fn view_by_mrid<'a, T: TypedView<'a>>(dataset: &'a Dataset, mrid: &Mrid) -> Option<T> {
108    let o = dataset.by_mrid(mrid)?;
109    T::try_from_object(dataset.schema(), o)
110}
111
112impl Dataset {
113    /// Every object of `T`'s class, including subclasses, as typed views.
114    ///
115    // An example has to name a vintage, and a vintage is a feature — so the example is
116    // written only into a build that has the one it names. Without this, `cargo test`
117    // under `--no-default-features --features cgmes2` failed on the documentation rather
118    // than on the code.
119    #[cfg_attr(
120        feature = "cgmes3",
121        doc = r#"
122```
123use cim_kit::prelude::*;
124use cim_kit::cgmes3::{SCHEMA, views::ACLineSegment};
125
126let dataset = Dataset::new(SCHEMA);
127for line in dataset.view::<ACLineSegment>() {
128    println!("{:?} r={:?}", line.name(), line.r());
129}
130```
131"#
132    )]
133    pub fn view<'a, T: TypedView<'a>>(&'a self) -> impl Iterator<Item = T> + 'a {
134        iter_view::<T>(self)
135    }
136
137    /// Look up one object by mRID as a typed view, checking its class.
138    pub fn view_by_mrid<'a, T: TypedView<'a>>(&'a self, mrid: &Mrid) -> Option<T> {
139        view_by_mrid::<T>(self, mrid)
140    }
141
142    /// Count objects of `T`'s class.
143    pub fn count_view<'a, T: TypedView<'a>>(&'a self) -> usize {
144        self.count_class(T::CLASS)
145    }
146}