ifc_style/units.rs
1//! Project unit factors a caller resolved for hatch measures.
2//!
3//! `ifc-style` links no unit resolver (ADR 0003): the caller reads the
4//! project's `IfcUnitAssignment` and passes the two factors this crate needs.
5//! A factor the project does not state stays `None`, and a measure that needs
6//! it is refused, never read as metres or radians.
7
8use ifc_model::EntityId;
9
10use crate::error::{StyleError, StyleResult};
11
12/// Project unit factors a caller resolved (ifc-style links no unit resolver; ADR 0003).
13///
14/// The fields are private so that every value is finite and positive: build
15/// one with [`StyleUnits::new`] or take [`StyleUnits::SI`].
16///
17/// ```compile_fail
18/// use ifc_style::StyleUnits;
19/// let _ = StyleUnits { metres_per_length: Some(f64::NAN), radians_per_angle: None };
20/// ```
21#[derive(Debug, Clone, Copy, PartialEq)]
22pub struct StyleUnits {
23 metres_per_length: Option<f64>,
24 radians_per_angle: Option<f64>,
25}
26
27impl StyleUnits {
28 /// Metres and radians; for files known to be SI, never a fallback for undeclared units.
29 pub const SI: Self = Self {
30 metres_per_length: Some(1.0),
31 radians_per_angle: Some(1.0),
32 };
33
34 /// Metres per project length unit; `None` when the project declares no `LENGTHUNIT`.
35 #[must_use]
36 pub fn metres_per_length(&self) -> Option<f64> {
37 self.metres_per_length
38 }
39
40 /// Radians per project plane angle unit; `None` when no `PLANEANGLEUNIT`.
41 #[must_use]
42 pub fn radians_per_angle(&self) -> Option<f64> {
43 self.radians_per_angle
44 }
45
46 /// Unit factors from the two project factors; `None` states "not declared".
47 ///
48 /// # Errors
49 ///
50 /// [`StyleError::InvalidUnits`] for a factor that is not finite and
51 /// greater than zero.
52 pub fn new(
53 metres_per_length: Option<f64>,
54 radians_per_angle: Option<f64>,
55 ) -> StyleResult<Self> {
56 check("metres_per_length", metres_per_length)?;
57 check("radians_per_angle", radians_per_angle)?;
58 Ok(Self {
59 metres_per_length,
60 radians_per_angle,
61 })
62 }
63
64 /// `value` in metres, read by `entity`.
65 pub(crate) fn length(&self, entity: EntityId, value: f64) -> StyleResult<f64> {
66 scale(self.metres_per_length, entity, "LENGTHUNIT", value)
67 }
68
69 /// `value` in radians, read by `entity`.
70 pub(crate) fn angle(&self, entity: EntityId, value: f64) -> StyleResult<f64> {
71 scale(self.radians_per_angle, entity, "PLANEANGLEUNIT", value)
72 }
73}
74
75fn check(factor: &'static str, value: Option<f64>) -> StyleResult<()> {
76 match value {
77 Some(value) if !(value.is_finite() && value > 0.0) => {
78 Err(StyleError::InvalidUnits { factor, value })
79 }
80 _ => Ok(()),
81 }
82}
83
84fn scale(
85 factor: Option<f64>,
86 entity: EntityId,
87 unit: &'static str,
88 value: f64,
89) -> StyleResult<f64> {
90 factor
91 .map(|factor| value * factor)
92 .ok_or(StyleError::UnitUndeclared { entity, unit })
93}