Skip to main content

ifc_cost/
value.rs

1//! `IfcCostValue` and the applied-value tree beneath it.
2//!
3//! # Slots, verified against IFC4 EXPRESS
4//!
5//! `IfcCostValue` adds nothing of its own; every slot comes from
6//! `IfcAppliedValue`:
7//!
8//! ```text
9//! 0 Name                1 Description        2 AppliedValue
10//! 3 UnitBasis           4 ApplicableDate     5 FixedUntilDate
11//! 6 Category            7 Condition          8 ArithmeticOperator
12//! 9 Components
13//! ```
14//!
15//! # A cost value is a tree, not a number
16//!
17//! `Components` holds nested `IfcAppliedValue`s and `ArithmeticOperator` says
18//! how to combine them. A value with components and an `ADD` operator is the
19//! sum of its children; the `AppliedValue` slot may then be absent entirely.
20//! Reading only slot 2 and calling that "the amount" silently reports nothing
21//! for every composed rate in the file.
22//!
23//! # What this module refuses to do
24//!
25//! It does not evaluate the tree. `ArithmeticOperator` is `ADD`, `DIVIDE`,
26//! `MULTIPLY` or `SUBTRACT` over a LIST whose order the schema does not
27//! constrain to be meaningful for non-commutative operators: `SUBTRACT` over
28//! `[a, b, c]` has no defined bracketing in the standard. Folding it anyway
29//! would produce a number that looks authoritative and is not. So the shape is
30//! reported and evaluation is left to a caller who knows their own convention.
31
32use ifc_model::{Entity, EntityId, Model, Value};
33
34/// `IfcAppliedValue` slots. `IfcCostValue` adds none of its own.
35mod slot {
36    /// `Name`.
37    pub const NAME: usize = 0;
38    /// `Description`.
39    pub const DESCRIPTION: usize = 1;
40    /// `AppliedValue`, usually `IFCMONETARYMEASURE`.
41    pub const APPLIED_VALUE: usize = 2;
42    /// `UnitBasis`, an `IfcMeasureWithUnit`.
43    pub const UNIT_BASIS: usize = 3;
44    /// `ApplicableDate`.
45    pub const APPLICABLE_DATE: usize = 4;
46    /// `FixedUntilDate`.
47    pub const FIXED_UNTIL_DATE: usize = 5;
48    /// `Category`.
49    pub const CATEGORY: usize = 6;
50    /// `Condition`.
51    pub const CONDITION: usize = 7;
52    /// `ArithmeticOperator`.
53    pub const ARITHMETIC_OPERATOR: usize = 8;
54    /// `Components`.
55    pub const COMPONENTS: usize = 9;
56}
57
58/// How an applied value combines its components.
59///
60/// `IfcArithmeticOperatorEnum`, verified against IFC4 EXPRESS.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62#[non_exhaustive]
63pub enum ArithmeticOperator {
64    /// `.ADD.`
65    Add,
66    /// `.DIVIDE.`
67    Divide,
68    /// `.MULTIPLY.`
69    Multiply,
70    /// `.SUBTRACT.`
71    Subtract,
72}
73
74impl ArithmeticOperator {
75    /// Parse the enum token, without its dots.
76    #[must_use]
77    pub fn parse(token: &str) -> Option<Self> {
78        Some(match token {
79            "ADD" => Self::Add,
80            "DIVIDE" => Self::Divide,
81            "MULTIPLY" => Self::Multiply,
82            "SUBTRACT" => Self::Subtract,
83            _ => return None,
84        })
85    }
86
87    /// Whether operand order changes the result.
88    ///
89    /// `ADD` and `MULTIPLY` are commutative, so folding a component list in
90    /// file order is safe. `SUBTRACT` and `DIVIDE` are not, and IFC does not
91    /// define the bracketing, so a caller folding them is choosing a
92    /// convention rather than reading one.
93    #[must_use]
94    pub fn is_order_sensitive(self) -> bool {
95        matches!(self, Self::Divide | Self::Subtract)
96    }
97}
98
99/// How a rate is expressed per unit of something.
100///
101/// `UnitBasis` is an `IfcMeasureWithUnit`: "45.50 per 1 cubic metre". Without
102/// it a cost value is a lump sum; with it, it is a rate and multiplying it by
103/// a quantity is meaningful.
104#[derive(Debug, Clone, Copy, PartialEq)]
105#[non_exhaustive]
106pub struct UnitBasis {
107    /// The entity holding the basis.
108    pub id: EntityId,
109    /// The numeric component of the basis measure.
110    pub value: Option<f64>,
111    /// The measure type wrapping it, e.g. `IFCVOLUMEMEASURE`.
112    pub measure: Option<&'static str>,
113    /// The unit entity the basis names, if it resolves.
114    pub unit: Option<EntityId>,
115}
116
117/// A borrowed view of an `IfcCostValue` entity.
118#[derive(Debug, Clone, Copy)]
119pub struct CostValue<'m> {
120    id: EntityId,
121    entity: &'m Entity,
122}
123
124impl<'m> CostValue<'m> {
125    /// Wrap an entity known to be an `IfcCostValue`.
126    #[must_use]
127    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
128        Self { id, entity }
129    }
130
131    /// The entity id in the file.
132    #[must_use]
133    pub fn id(&self) -> EntityId {
134        self.id
135    }
136
137    /// The value's name, e.g. `Estimate`.
138    #[must_use]
139    pub fn name(&self) -> Option<&'m str> {
140        self.entity.text(slot::NAME)
141    }
142
143    /// The value's description.
144    #[must_use]
145    pub fn description(&self) -> Option<&'m str> {
146        self.entity.text(slot::DESCRIPTION)
147    }
148
149    /// The directly stated amount.
150    ///
151    /// `None` for a composed value that states only `Components`. Use
152    /// [`CostValue::component_refs`] and [`CostValue::operator`] for those, or
153    /// [`CostValue::is_composed`] to tell the two shapes apart.
154    #[must_use]
155    pub fn amount(&self) -> Option<f64> {
156        self.entity
157            .attribute(slot::APPLIED_VALUE)?
158            .unwrap_typed()
159            .as_f64()
160    }
161
162    /// `AppliedValue` exactly as the file states it, typed wrapper and all
163    /// (`IFCMONETARYMEASURE(1500.5)`), or `None` when it is unset.
164    ///
165    /// [`CostValue::amount`] and [`CostValue::measure`] split this into a
166    /// number and a type name; a caller that must carry the value without
167    /// loss, such as a language binding, reads it whole here: an
168    /// `IfcCountMeasure` stays an integer, and an `IfcMeasureWithUnit` or
169    /// `IfcReference` stays a reference (#123).
170    #[must_use]
171    pub fn applied_value(&self) -> Option<&'m Value> {
172        match self.entity.attribute(slot::APPLIED_VALUE)? {
173            Value::Null => None,
174            value => Some(value),
175        }
176    }
177
178    /// The measure type wrapping the applied value, e.g. `IFCMONETARYMEASURE`.
179    ///
180    /// A cost value is not required to be monetary: `IfcAppliedValueSelect`
181    /// also admits ratios and plain measures. Reporting the wrapper lets a
182    /// caller refuse to add a ratio to a currency.
183    #[must_use]
184    pub fn measure(&self) -> Option<&'m str> {
185        match self.entity.attribute(slot::APPLIED_VALUE)? {
186            Value::Typed { type_name, .. } => Some(type_name),
187            _ => None,
188        }
189    }
190
191    /// Whether the applied value is a monetary measure.
192    #[must_use]
193    pub fn is_monetary(&self) -> bool {
194        self.measure()
195            .is_some_and(|m| m.eq_ignore_ascii_case("IFCMONETARYMEASURE"))
196    }
197
198    /// The rate category, e.g. `Labour` or `Material`.
199    #[must_use]
200    pub fn category(&self) -> Option<&'m str> {
201        self.entity.text(slot::CATEGORY)
202    }
203
204    /// The condition under which the value applies.
205    #[must_use]
206    pub fn condition(&self) -> Option<&'m str> {
207        self.entity.text(slot::CONDITION)
208    }
209
210    /// The date from which the value applies, as authored.
211    #[must_use]
212    pub fn applicable_date(&self) -> Option<&'m str> {
213        self.entity.text(slot::APPLICABLE_DATE)
214    }
215
216    /// The date after which the value no longer holds, as authored.
217    #[must_use]
218    pub fn fixed_until_date(&self) -> Option<&'m str> {
219        self.entity.text(slot::FIXED_UNTIL_DATE)
220    }
221
222    /// How this value's components combine, if stated.
223    #[must_use]
224    pub fn operator(&self) -> Option<ArithmeticOperator> {
225        match self.entity.attribute(slot::ARITHMETIC_OPERATOR)? {
226            Value::Enum(token) => ArithmeticOperator::parse(token),
227            _ => None,
228        }
229    }
230
231    /// Ids of the nested `IfcAppliedValue` components, in file order.
232    ///
233    /// Order is preserved because it is the only ordering information the file
234    /// carries, and an order-sensitive operator needs it.
235    #[must_use]
236    pub fn component_refs(&self) -> Vec<EntityId> {
237        let mut out = Vec::new();
238        if let Some(v) = self.entity.attribute(slot::COMPONENTS) {
239            v.for_each_ref(&mut |id| out.push(id));
240        }
241        out
242    }
243
244    /// Whether this value is composed from components rather than stated.
245    #[must_use]
246    pub fn is_composed(&self) -> bool {
247        !self.component_refs().is_empty()
248    }
249
250    /// The `ValueComponent` of the rate basis exactly as the file states
251    /// it (`IFCVOLUMEMEASURE(1.)`), when [`CostValue::unit_basis`] resolves.
252    ///
253    /// [`UnitBasis::value`] is the same value as a number; this keeps its
254    /// declared type and an integer payload intact (#123).
255    #[must_use]
256    pub fn unit_basis_component<'a>(&self, model: &'a Model) -> Option<&'a Value> {
257        let id = match self.entity.attribute(slot::UNIT_BASIS)? {
258            Value::Ref(id) => *id,
259            _ => return None,
260        };
261        match model.get(id)?.attribute(0)? {
262            Value::Null => None,
263            value => Some(value),
264        }
265    }
266
267    /// The rate basis, if this value is a rate rather than a lump sum.
268    ///
269    /// Resolves the `IfcMeasureWithUnit`: slot 0 is `ValueComponent`, slot 1
270    /// is `UnitComponent`.
271    #[must_use]
272    pub fn unit_basis(&self, model: &Model) -> Option<UnitBasis> {
273        let id = match self.entity.attribute(slot::UNIT_BASIS)? {
274            Value::Ref(id) => *id,
275            _ => return None,
276        };
277        let measure_with_unit = model.get(id)?;
278        let component = measure_with_unit.attribute(0);
279        Some(UnitBasis {
280            id,
281            value: component.and_then(|v| v.unwrap_typed().as_f64()),
282            measure: component.and_then(|v| match v {
283                // Leaked as 'static only when the name is one we know; a
284                // borrowed lifetime would tie UnitBasis to the model borrow
285                // and stop it being Copy.
286                Value::Typed { type_name, .. } => KNOWN_MEASURES
287                    .iter()
288                    .find(|m| type_name.eq_ignore_ascii_case(m))
289                    .copied(),
290                _ => None,
291            }),
292            unit: match measure_with_unit.attribute(1) {
293                Some(Value::Ref(unit)) => Some(*unit),
294                _ => None,
295            },
296        })
297    }
298}
299
300/// Measure names a unit basis is expected to carry.
301///
302/// Anything outside this list reports `None` rather than being invented: the
303/// point of the field is to let a caller check dimensional agreement, and an
304/// unrecognised name is not evidence of agreement.
305const KNOWN_MEASURES: &[&str] = &[
306    "IFCVOLUMEMEASURE",
307    "IFCAREAMEASURE",
308    "IFCLENGTHMEASURE",
309    "IFCMASSMEASURE",
310    "IFCCOUNTMEASURE",
311    "IFCTIMEMEASURE",
312    "IFCMONETARYMEASURE",
313];