ifc_material/usage/index.rs
1//! [`MaterialIndex`] and the lookup plumbing it shares with [`MaterialView`].
2//!
3//! One code path answers both, parameterised by [`Lookup`], so the two agree
4//! by construction.
5
6use std::borrow::Cow;
7use std::collections::BTreeMap;
8use std::fmt;
9
10use ifc_model::{Entity, EntityId, ReverseIndex};
11
12use crate::view::{required_refs, MaterialView};
13use crate::{MaterialAssignment, MaterialError, MaterialResult, ResolvedAssignment};
14
15pub(crate) const ASSOCIATES_MATERIAL: &str = "IFCRELASSOCIATESMATERIAL";
16pub(crate) const DEFINES_BY_TYPE: &str = "IFCRELDEFINESBYTYPE";
17
18/// Where a lookup finds the relationships naming an object, and whether the
19/// refusal of each relationship's `RelatedObjects` is already known.
20#[derive(Clone, Copy)]
21pub(crate) struct Lookup<'a> {
22 /// `None`: scan the record type.
23 pub(crate) referrers: Option<&'a ReverseIndex>,
24 /// `None`: decode `RelatedObjects` per lookup.
25 pub(crate) refused: Option<&'a BTreeMap<EntityId, MaterialError>>,
26}
27
28impl<'m> MaterialView<'m> {
29 /// The per-call lookup: the model's reverse index when something built
30 /// it, and a decode of every candidate's `RelatedObjects`.
31 pub(crate) fn lookup(self) -> Lookup<'m> {
32 Lookup {
33 referrers: self.model().reverse_index_if_built(),
34 refused: None,
35 }
36 }
37
38 /// The strictly decoded `RelatedObjects` of a relationship record.
39 pub(crate) fn related_objects(
40 self,
41 entity: &'static str,
42 id: EntityId,
43 record: &Entity,
44 ) -> MaterialResult<Vec<EntityId>> {
45 let slot = self.release().slot(entity, id, "RelatedObjects")?;
46 required_refs(entity, id, record, slot, "RelatedObjects", 1)
47 }
48
49 /// Whether the relationship's `RelatedObjects` names `object`; a
50 /// malformed list refuses.
51 pub(crate) fn names(
52 self,
53 lookup: Lookup<'_>,
54 entity: &'static str,
55 id: EntityId,
56 record: &Entity,
57 object: EntityId,
58 ) -> MaterialResult<bool> {
59 match lookup.refused {
60 Some(refused) => refused.get(&id).map_or(Ok(true), |e| Err(e.clone())),
61 None => Ok(self.related_objects(entity, id, record)?.contains(&object)),
62 }
63 }
64}
65
66/// The material of many objects, resolved in one pass over the model.
67///
68/// [`MaterialView::assigned_material`] decodes the whole `RelatedObjects` of
69/// every relationship naming the object on each call, so resolving every
70/// product of a model whose relationships share long lists costs the square
71/// of the list length. `MaterialIndex::new` reads the
72/// `IfcRelAssociatesMaterial` and `IfcRelDefinesByType` records once and
73/// checks each one's `RelatedObjects` once; a lookup then costs the
74/// relationships that name the object.
75///
76/// Every answer, refusals included, equals the view's: both run one shared
77/// code path, and a relationship whose `RelatedObjects` is malformed refuses
78/// every object it names, exactly as the view does. The index borrows the
79/// model, so it cannot go stale: the model cannot change while it lives.
80/// When something built the model's reverse index the index reads through
81/// it; otherwise it builds its own over those two record types only. It
82/// never leaves an index on the model.
83///
84/// ```
85/// # use ifc_material::{MaterialIndex, MaterialResult, MaterialView};
86/// # use ifc_model::{EntityId, Model};
87/// # fn demo(model: &Model, products: &[EntityId]) -> MaterialResult<()> {
88/// let index = MaterialIndex::new(MaterialView::new(model));
89/// for &p in products {
90/// index.assigned_material(p)?;
91/// }
92/// # Ok(())
93/// # }
94/// ```
95#[derive(Clone)]
96pub struct MaterialIndex<'m> {
97 view: MaterialView<'m>,
98 referrers: Cow<'m, ReverseIndex>,
99 refused: BTreeMap<EntityId, MaterialError>,
100}
101
102impl fmt::Debug for MaterialIndex<'_> {
103 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104 f.debug_struct("MaterialIndex")
105 .field("schema", &self.view.schema())
106 .field(
107 "borrows_model_index",
108 &matches!(self.referrers, Cow::Borrowed(_)),
109 )
110 .field("refused", &self.refused.len())
111 .finish_non_exhaustive()
112 }
113}
114
115impl<'m> MaterialIndex<'m> {
116 /// Indexes the material and typing relationships of `view`'s model.
117 ///
118 /// Infallible: a malformed relationship is recorded and refuses the
119 /// objects it names at lookup, as the view would.
120 #[must_use]
121 pub fn new(view: MaterialView<'m>) -> Self {
122 let model = view.model();
123 let ids = |entity: &'static str| model.ids_of_type(entity).iter().copied();
124 let referrers = model.reverse_index_if_built().map_or_else(
125 || {
126 Cow::Owned(ReverseIndex::build_from(
127 model,
128 [ASSOCIATES_MATERIAL, DEFINES_BY_TYPE]
129 .into_iter()
130 .flat_map(ids),
131 ))
132 },
133 Cow::Borrowed,
134 );
135 let mut refused = BTreeMap::new();
136 for entity in [ASSOCIATES_MATERIAL, DEFINES_BY_TYPE] {
137 for id in ids(entity) {
138 let Some(record) = model.get(id) else {
139 continue;
140 };
141 if let Err(error) = view.related_objects(entity, id, record) {
142 refused.insert(id, error);
143 }
144 }
145 }
146 Self {
147 view,
148 referrers,
149 refused,
150 }
151 }
152
153 /// The view this index answers for.
154 #[must_use]
155 pub fn view(&self) -> MaterialView<'m> {
156 self.view
157 }
158
159 fn lookup(&self) -> Lookup<'_> {
160 Lookup {
161 referrers: Some(&self.referrers),
162 refused: Some(&self.refused),
163 }
164 }
165
166 /// [`MaterialView::assignments_for`], answered from the index.
167 ///
168 /// # Errors
169 ///
170 /// As [`MaterialView::assignments_for`].
171 pub fn assignments_for(&self, object: EntityId) -> MaterialResult<Vec<MaterialAssignment<'m>>> {
172 self.view.assignments_in(self.lookup(), object)
173 }
174
175 /// [`MaterialView::assigned_material`], answered from the index.
176 ///
177 /// # Errors
178 ///
179 /// As [`MaterialView::assigned_material`].
180 pub fn assigned_material(
181 &self,
182 object: EntityId,
183 ) -> MaterialResult<Option<ResolvedAssignment<'m>>> {
184 self.view.assigned_material_in(self.lookup(), object)
185 }
186}