Skip to main content

openbim_ifc_capi/
units.rs

1//! Unit conversion and a model's length unit (#469).
2//!
3//! A unit is named as UTF-8 text: an SI unit with its prefix written before
4//! it (`METRE`, `MILLIMETRE`, `MILLI METRE`, `SQUARE_MILLIMETRE`,
5//! `KILOGRAM`; `METER` spellings accepted), or a named conversion-based
6//! unit of IFC4 Table 673 with exact factors (`inch`, `foot`, `yard`,
7//! `mile`, `square foot`, `gallon US`, `pound`, `degree` ...) or `US survey
8//! foot`.
9//!
10//! `openbim_ifc_v0_1_model_convert_length_unit` answers with a
11//! `LengthUnitReport` record tape: from and to (`TEXT`), length factor
12//! (`REAL`), area and volume factors (`REAL` or `NULL` when that unit does
13//! not follow), the new length, area and volume unit ids (`REF` or `NULL`),
14//! converted (`LIST` of `ConvertedValues`: entity type, attribute, kind
15//! `TEXT` -- `length`, `area`, `volume`, `inverse-length`,
16//! `inverse-area`, `map-scale` -- entities and values `INTEGER`), kept
17//! (`LIST` of `KeptValues`: entity type, attribute, reason `TEXT` --
18//! `explicit-unit`, `map-unit`, `unitless-parameter`, `unit-not-followed`
19//! -- values), entities changed and values converted (`INTEGER`), created
20//! and removed (`LIST`s of `REF`), applied (`BOOL`, false for a dry run).
21//! The call never applies a conversion it cannot report: it plans first,
22//! and a size query or a short buffer answers `BufferTooSmall` with the
23//! sizes and leaves the model unchanged. The plan lists the ids the
24//! commit creates, so the applied report has the planned one's size.
25
26use openbim_ifc_binding_core::{convert_unit, format_length, LengthUnitOptions, ToRecord};
27
28use crate::buffer::{fill_c_string, put, text};
29use crate::domains::Out;
30use crate::model::{done, with_model, OpenbimIfcModel};
31use crate::status::{boundary, OpenbimIfcStatus};
32use crate::tape::{OpenbimIfcValueNode, Tape};
33
34/// `openbim_ifc_v0_1_model_convert_length_unit` flag: keep the area and
35/// volume units and their values instead of replacing them by the square
36/// and cube of the new length unit.
37pub const OPENBIM_IFC_LENGTH_UNIT_KEEP_AREA_AND_VOLUME: u32 = 1;
38/// `openbim_ifc_v0_1_model_convert_length_unit` flag: keep the replaced
39/// unit entities even when nothing else refers to them.
40pub const OPENBIM_IFC_LENGTH_UNIT_KEEP_REPLACED_UNITS: u32 = 2;
41/// `openbim_ifc_v0_1_model_convert_length_unit` flag: report only.
42pub const OPENBIM_IFC_LENGTH_UNIT_DRY_RUN: u32 = 4;
43/// `openbim_ifc_v0_1_format_length` style: decimal, in `display_unit`
44/// (default the value's unit) with `places` digits after the point.
45pub const OPENBIM_IFC_LENGTH_FORMAT_DECIMAL: u32 = 0;
46/// `openbim_ifc_v0_1_format_length` style: feet and inches, `5' - 6 1/2"`,
47/// rounded to `1/places` of an inch.
48pub const OPENBIM_IFC_LENGTH_FORMAT_FEET_INCHES: u32 = 1;
49/// `openbim_ifc_v0_1_format_length` style: inches, `66 1/2"`, rounded to
50/// `1/places` of an inch.
51pub const OPENBIM_IFC_LENGTH_FORMAT_INCHES: u32 = 2;
52/// `openbim_ifc_v0_1_format_length` flag: write a whole number of feet as
53/// `5'` rather than `5' - 0"`.
54pub const OPENBIM_IFC_LENGTH_FORMAT_SUPPRESS_ZERO_INCHES: u32 = 1;
55
56const ALL_FLAGS: u32 = 7;
57
58/// Convert `value` from the unit named `from` (`from_len` UTF-8 bytes) to
59/// the unit named `to`, written to `out_value`. Needs no model.
60/// `InvalidValue` for text that names no unit; `TypeMismatch` for units of
61/// different dimensions; `Unsupported` for a unit with an offset (degree
62/// Fahrenheit, #110); `InvalidArgument` for text that is not UTF-8.
63///
64/// # Safety
65/// `from` and `to` valid for their lengths; `out_value` valid for one
66/// write.
67#[no_mangle]
68pub unsafe extern "C" fn openbim_ifc_v0_1_convert_unit(
69    value: f64,
70    from: *const u8,
71    from_len: usize,
72    to: *const u8,
73    to_len: usize,
74    out_value: *mut f64,
75) -> OpenbimIfcStatus {
76    boundary(|| {
77        // SAFETY: caller contract above.
78        let (from, to) = match unsafe { (text(from, from_len), text(to, to_len)) } {
79            (Ok(from), Ok(to)) => (from, to),
80            (Err(status), _) | (_, Err(status)) => return status,
81        };
82        match convert_unit(value, from, to) {
83            // SAFETY: caller contract above.
84            Ok(converted) => unsafe { put(out_value, converted) }
85                .err()
86                .unwrap_or(OpenbimIfcStatus::Ok),
87            Err(error) => OpenbimIfcStatus::from(&error),
88        }
89    })
90}
91
92/// Write `value`, a length in the unit named `unit`, as NUL-terminated
93/// text. `style` is `OPENBIM_IFC_LENGTH_FORMAT_DECIMAL` (in `display_unit`,
94/// or the value's unit when `display_unit` is null, with `places` decimals),
95/// `OPENBIM_IFC_LENGTH_FORMAT_FEET_INCHES` or
96/// `OPENBIM_IFC_LENGTH_FORMAT_INCHES` (rounded to `1/places` of an inch);
97/// `flags`: `OPENBIM_IFC_LENGTH_FORMAT_SUPPRESS_ZERO_INCHES`. Needs no
98/// model. `InvalidValue` for a unit name, a zero denominator or a length
99/// too large; `TypeMismatch` for a unit that is not a length;
100/// `OutOfRange` for more than 255 decimals; `InvalidArgument` for an
101/// unknown style or flag, or text that is not UTF-8.
102///
103/// # Safety
104/// `unit` valid for `unit_len`; `display_unit` null or valid for
105/// `display_unit_len`; `buffer` and `out_required` as for
106/// `openbim_ifc_v0_1_new_guid`.
107#[no_mangle]
108#[allow(clippy::too_many_arguments)]
109pub unsafe extern "C" fn openbim_ifc_v0_1_format_length(
110    value: f64,
111    unit: *const u8,
112    unit_len: usize,
113    style: u32,
114    places: u32,
115    display_unit: *const u8,
116    display_unit_len: usize,
117    flags: u32,
118    buffer: *mut u8,
119    capacity: usize,
120    out_required: *mut usize,
121) -> OpenbimIfcStatus {
122    boundary(|| {
123        let style = match style {
124            OPENBIM_IFC_LENGTH_FORMAT_DECIMAL => "decimal",
125            OPENBIM_IFC_LENGTH_FORMAT_FEET_INCHES => "feet-inches",
126            OPENBIM_IFC_LENGTH_FORMAT_INCHES => "inches",
127            _ => return OpenbimIfcStatus::InvalidArgument,
128        };
129        if flags & !OPENBIM_IFC_LENGTH_FORMAT_SUPPRESS_ZERO_INCHES != 0 {
130            return OpenbimIfcStatus::InvalidArgument;
131        }
132        // SAFETY: caller contract above.
133        let unit = match unsafe { text(unit, unit_len) } {
134            Ok(unit) => unit,
135            Err(status) => return status,
136        };
137        let display = if display_unit.is_null() {
138            None
139        } else {
140            // SAFETY: caller contract above.
141            match unsafe { text(display_unit, display_unit_len) } {
142                Ok(display) => Some(display),
143                Err(status) => return status,
144            }
145        };
146        let suppress = flags & OPENBIM_IFC_LENGTH_FORMAT_SUPPRESS_ZERO_INCHES != 0;
147        match format_length(value, unit, style, places, display, suppress) {
148            // SAFETY: caller contract above.
149            Ok(formatted) => unsafe { fill_c_string(&formatted, buffer, capacity, out_required) },
150            Err(error) => OpenbimIfcStatus::from(&error),
151        }
152    })
153}
154
155/// Convert `value` from unit entity `from` to unit entity `to` of the model
156/// (an `IfcSIUnit`, `IfcConversionBasedUnit` or `IfcDerivedUnit`), written
157/// to `out_value`. `MissingEntity`; `TypeMismatch` for units of different
158/// dimensions; `Unsupported` for a monetary, context-dependent or offset
159/// unit; `InvalidModel` for a unit that does not resolve;
160/// `UnsupportedSchema`; `FeatureDisabled`.
161///
162/// # Safety
163/// `out_value` valid for one write.
164#[no_mangle]
165pub unsafe extern "C" fn openbim_ifc_v0_1_model_convert_unit_value(
166    model: OpenbimIfcModel,
167    value: f64,
168    from: u64,
169    to: u64,
170    out_value: *mut f64,
171) -> OpenbimIfcStatus {
172    boundary(|| {
173        with_model(model, |m| {
174            let converted = m.convert_unit_value(value, from, to)?;
175            // SAFETY: caller contract above.
176            done(
177                unsafe { put(out_value, converted) }
178                    .err()
179                    .unwrap_or(OpenbimIfcStatus::Ok),
180            )
181        })
182    })
183}
184
185/// Convert the model's length unit to the unit named `target`
186/// (`target_len` UTF-8 bytes): an SI `METRE` with any prefix, or `inch`,
187/// `foot`, `yard`, `mile`, `US survey foot`. Every length, area and volume
188/// value is rescaled as one checked transaction. `flags`:
189/// `OPENBIM_IFC_LENGTH_UNIT_KEEP_AREA_AND_VOLUME`,
190/// `OPENBIM_IFC_LENGTH_UNIT_KEEP_REPLACED_UNITS`,
191/// `OPENBIM_IFC_LENGTH_UNIT_DRY_RUN`. The answer is the `LengthUnitReport`
192/// tape of the module docs; a size query or a short buffer plans the
193/// conversion and answers `BufferTooSmall` without applying it.
194///
195/// `InvalidValue` for a target that is not a length unit;
196/// `Unsupported` naming the values the conversion cannot carry (a
197/// parameter on a curve whose parameter space IFC leaves undefined, a
198/// p-curve off a plane, polynomial coefficients ...) and for an offset
199/// unit (#110); `InvalidModel` when the project length unit does not
200/// resolve; `UnsupportedSchema`; `InvalidArgument` for an unknown flag or
201/// text that is not UTF-8; `FeatureDisabled`.
202///
203/// # Safety
204/// `target` valid for `target_len`; the buffers as for
205/// `openbim_ifc_v0_1_entity_attribute`.
206#[no_mangle]
207#[allow(clippy::too_many_arguments)]
208pub unsafe extern "C" fn openbim_ifc_v0_1_model_convert_length_unit(
209    model: OpenbimIfcModel,
210    target: *const u8,
211    target_len: usize,
212    flags: u32,
213    nodes: *mut OpenbimIfcValueNode,
214    node_capacity: usize,
215    out_nodes_required: *mut usize,
216    strings: *mut u8,
217    string_capacity: usize,
218    out_strings_required: *mut usize,
219) -> OpenbimIfcStatus {
220    if flags & !ALL_FLAGS != 0 {
221        return OpenbimIfcStatus::InvalidArgument;
222    }
223    let out = Out {
224        nodes,
225        node_capacity,
226        out_nodes_required,
227        strings,
228        string_capacity,
229        out_strings_required,
230    };
231    boundary(|| {
232        // SAFETY: caller contract above.
233        let target = match unsafe { text(target, target_len) } {
234            Ok(target) => target.to_owned(),
235            Err(status) => return status,
236        };
237        let options = |dry_run| {
238            let mut options = LengthUnitOptions::new();
239            options.area_and_volume = flags & OPENBIM_IFC_LENGTH_UNIT_KEEP_AREA_AND_VOLUME == 0;
240            options.remove_replaced_units =
241                flags & OPENBIM_IFC_LENGTH_UNIT_KEEP_REPLACED_UNITS == 0;
242            options.dry_run = dry_run;
243            options
244        };
245        let dry_run = flags & OPENBIM_IFC_LENGTH_UNIT_DRY_RUN != 0;
246        with_model(model, |m| {
247            let planned = m.convert_length_unit(&target, options(true))?;
248            if dry_run {
249                // SAFETY: caller contract.
250                return unsafe { out.write(&planned.to_record().to_tagged()) };
251            }
252            // The plan lists the ids the commit creates, so the applied
253            // report has the planned one's size.
254            let mut sized = planned.clone();
255            sized.applied = true;
256            let sized = sized.to_record().to_tagged();
257            let tape = Tape::encode(&sized);
258            let fits =
259                tape.nodes.len() <= out.node_capacity && tape.strings.len() <= out.string_capacity;
260            if !fits {
261                // SAFETY: caller contract; too small, so only sizes are written.
262                return unsafe { out.write(&sized) };
263            }
264            let report = m.convert_length_unit(&target, options(false))?;
265            // SAFETY: caller contract.
266            unsafe { out.write(&report.to_record().to_tagged()) }
267        })
268    })
269}