Skip to main content

ifc_cost/
view.rs

1//! The cost view: the entry point for reading cost data out of a model.
2//!
3//! Holds a borrow and nothing else. Constructing one is free, several can
4//! coexist over the same model, and dropping one cannot lose data — which is
5//! what makes `ifc-cost` safe to leave uncompiled.
6
7use crate::error::CostError;
8use crate::item::CostItem;
9use crate::release::ReadRelease;
10use crate::schedule::CostSchedule;
11use crate::value::CostValue;
12use ifc_model::Model;
13
14/// A borrowed cost interpretation of a model.
15#[derive(Debug, Clone, Copy)]
16pub struct CostView<'m> {
17    model: &'m Model,
18}
19
20impl<'m> CostView<'m> {
21    /// Create a cost view over `model`.
22    pub fn new(model: &'m Model) -> Self {
23        Self { model }
24    }
25
26    /// Every cost schedule in the file, read against the model's declared
27    /// release (#212).
28    ///
29    /// # Errors
30    ///
31    /// [`CostError::UnsupportedSchema`] when the header declares a release
32    /// the cost readers are not verified against (IFC4X1, IFC4X2 or an
33    /// unknown token), [`CostError::MultipleSchemas`] when it declares
34    /// several. A header with no schema reads as IFC4.
35    pub fn schedules(&self) -> Result<impl Iterator<Item = CostSchedule<'m>> + '_, CostError> {
36        let release = ReadRelease::of(self.model)?;
37        Ok(self
38            .model
39            .of_type("IFCCOSTSCHEDULE")
40            .map(move |(id, entity)| CostSchedule::bound(id, entity, release))
41            .collect::<Vec<_>>()
42            .into_iter())
43    }
44
45    /// Every cost item in the file.
46    pub fn items(&self) -> impl Iterator<Item = CostItem<'m>> + '_ {
47        self.model
48            .of_type("IFCCOSTITEM")
49            .map(|(id, entity)| CostItem::new(id, entity))
50            .collect::<Vec<_>>()
51            .into_iter()
52    }
53
54    /// The model underneath, for callers that need to resolve references.
55    pub fn model(&self) -> &'m Model {
56        self.model
57    }
58
59    /// Resolve the cost values attached to an item.
60    ///
61    /// A reference that does not resolve is skipped rather than erroring:
62    /// dangling references are common in real files, and one bad link should
63    /// not make the whole cost tree unreadable. Use
64    /// [`Model::dangling_references`] when you need to know about them.
65    pub fn values_of(&self, item: &CostItem<'m>) -> Vec<CostValue<'m>> {
66        item.value_refs()
67            .into_iter()
68            .filter_map(|id| self.model.get(id).map(|e| CostValue::new(id, e)))
69            .collect()
70    }
71}
72
73#[cfg(test)]
74mod tests {
75    use super::*;
76    use ifc_model::{Entity, EntityId, Value};
77
78    fn model_with_cost() -> Model {
79        let mut model = Model::new();
80        model.insert(
81            EntityId(1),
82            Entity::new(
83                "IFCCOSTVALUE",
84                vec![
85                    Value::Text("Estimate".into()),
86                    Value::Null,
87                    Value::Typed {
88                        type_name: "IFCMONETARYMEASURE".into(),
89                        value: Box::new(Value::Real(1500.50)),
90                    },
91                ],
92            ),
93        );
94        model.insert(
95            EntityId(2),
96            Entity::new(
97                "IFCCOSTITEM",
98                vec![
99                    Value::Text("3vB2Y0dTv1LhX9ZzQqFbcd".into()), // 0 GlobalId
100                    Value::Null,                                  // 1 OwnerHistory
101                    Value::Text("Excavation".into()),             // 2 Name
102                    Value::Null,                                  // 3 Description
103                    Value::Null,                                  // 4 ObjectType
104                    Value::Text("A.1".into()),                    // 5 Identification
105                    Value::Enum("MATERIAL".into()),               // 6 PredefinedType
106                    Value::List(vec![Value::Ref(EntityId(1))]),   // 7 CostValues
107                ],
108            ),
109        );
110        model
111    }
112
113    #[test]
114    fn finds_cost_items_without_the_model_knowing_what_cost_is() {
115        let model = model_with_cost();
116        let view = CostView::new(&model);
117        let items: Vec<_> = view.items().collect();
118        assert_eq!(items.len(), 1);
119        assert_eq!(items[0].name(), Some("Excavation"));
120    }
121
122    #[test]
123    fn resolves_values_through_references() {
124        let model = model_with_cost();
125        let view = CostView::new(&model);
126        let item = view.items().next().unwrap();
127        let values = view.values_of(&item);
128        assert_eq!(values.len(), 1);
129        assert_eq!(values[0].amount(), Some(1500.50));
130    }
131
132    /// The applied value is read whole, typed wrapper included, so a
133    /// lossless consumer does not rebuild it from `amount` and `measure`.
134    #[test]
135    fn the_applied_value_is_read_as_authored() {
136        let model = model_with_cost();
137        let view = CostView::new(&model);
138        let item = view.items().next().unwrap();
139        let value = view.values_of(&item).remove(0);
140        assert_eq!(
141            value.applied_value(),
142            Some(&Value::Typed {
143                type_name: "IFCMONETARYMEASURE".into(),
144                value: Box::new(Value::Real(1500.50)),
145            })
146        );
147        assert_eq!(value.unit_basis_component(&model), None, "no basis stated");
148    }
149
150    /// The view is a lens, not storage: dropping it cannot lose data.
151    #[test]
152    fn view_owns_nothing_and_model_is_unchanged() {
153        let model = model_with_cost();
154        let before = model.len();
155        {
156            let view = CostView::new(&model);
157            let _ = view.items().count();
158        }
159        assert_eq!(model.len(), before);
160    }
161
162    /// Slots follow the real IfcControl inheritance chain.
163    ///
164    /// This is a regression test for a shipped defect: the slot constants
165    /// omitted `ObjectType` (IfcObject) and `PredefinedType`, so every
166    /// attribute from `Identification` onward was read one or more positions
167    /// early. It passed only because the hand-built test fixtures encoded the
168    /// same wrong layout, which is exactly how a slot bug survives review.
169    #[test]
170    fn cost_item_slots_match_the_inheritance_chain() {
171        let model = model_with_cost();
172        let view = CostView::new(&model);
173        let item = view
174            .items()
175            .find(|i| i.name() == Some("Excavation"))
176            .expect("item present");
177
178        assert_eq!(
179            item.identification(),
180            Some("A.1"),
181            "Identification is slot 5"
182        );
183        assert_eq!(
184            item.predefined_type(),
185            Some("MATERIAL"),
186            "PredefinedType is slot 6"
187        );
188        assert_eq!(item.value_refs(), vec![EntityId(1)], "CostValues is slot 7");
189    }
190
191    /// A dangling cost value is skipped, not fatal.
192    #[test]
193    fn unresolvable_value_references_are_skipped() {
194        let mut model = model_with_cost();
195        model.insert(
196            EntityId(3),
197            Entity::new(
198                "IFCCOSTITEM",
199                vec![
200                    Value::Text("broken".into()),
201                    Value::Null,
202                    Value::Text("Dangling".into()),
203                    Value::Null,
204                    Value::Null,
205                    Value::Null,
206                    Value::Null,
207                    Value::List(vec![Value::Ref(EntityId(999))]), // 7 CostValues
208                ],
209            ),
210        );
211
212        let view = CostView::new(&model);
213        let item = view
214            .items()
215            .find(|i| i.name() == Some("Dangling"))
216            .expect("item present");
217        assert!(view.values_of(&item).is_empty(), "missing target skipped");
218    }
219}