Skip to main content

openbim_ifc_capi/
domains.rs

1//! The domain views (#123) as value tapes.
2//!
3//! Each domain record of the shared core crosses as one `LIST` of its
4//! field values in declaration order, nested records as nested `LIST`s
5//! (`openbim_ifc_binding_core::Record::to_tagged`). An id is a `REF`, an
6//! absent field `NULL`, a count an `INTEGER`, a resolved parameter a
7//! `REAL`, and an IFC value its own tagged node, typed wrapper included.
8//! The field order of every record is listed in the binding docs
9//! (`docs/bindings/c.md`, "Domain record tapes"); the core's record
10//! definitions are the source of truth.
11//!
12//! As for validation, the C protocol sizes buffers with a first call, so
13//! a size query runs the read; a host that wants one run passes buffers it
14//! expects to be large enough and retries only on `BufferTooSmall`.
15
16use openbim_ifc_binding_core::record::{to_records, Record};
17use openbim_ifc_binding_core::value::Tagged;
18use openbim_ifc_binding_core::{BindingError, IfcModel, ToRecord};
19
20use crate::buffer::{put, text};
21use crate::model::{done, fill_tape, with_model, OpenbimIfcModel};
22use crate::status::{boundary, OpenbimIfcStatus};
23use crate::tape::{OpenbimIfcValueNode, Tape};
24
25/// The output side every domain export shares.
26pub(crate) struct Out {
27    pub(crate) nodes: *mut OpenbimIfcValueNode,
28    pub(crate) node_capacity: usize,
29    pub(crate) out_nodes_required: *mut usize,
30    pub(crate) strings: *mut u8,
31    pub(crate) string_capacity: usize,
32    pub(crate) out_strings_required: *mut usize,
33}
34
35impl Out {
36    /// `NullPointer` when `write` would refuse these buffers. Checked
37    /// before an export applies a change, so a refusal never follows one.
38    pub(crate) fn check(&self) -> Result<(), OpenbimIfcStatus> {
39        let missing = self.out_nodes_required.is_null()
40            || self.out_strings_required.is_null()
41            || (self.node_capacity != 0 && self.nodes.is_null())
42            || (self.string_capacity != 0 && self.strings.is_null());
43        if missing {
44            Err(OpenbimIfcStatus::NullPointer)
45        } else {
46            Ok(())
47        }
48    }
49
50    /// Write `value` as a tape.
51    ///
52    /// # Safety
53    /// The buffers as for `openbim_ifc_v0_1_entity_attribute`.
54    pub(crate) unsafe fn write(&self, value: &Tagged) -> Result<OpenbimIfcStatus, BindingError> {
55        let tape = Tape::encode(value);
56        // SAFETY: forwarded caller contract.
57        done(unsafe {
58            fill_tape(
59                &tape,
60                self.nodes,
61                self.node_capacity,
62                self.out_nodes_required,
63                self.strings,
64                self.string_capacity,
65                self.out_strings_required,
66            )
67        })
68    }
69}
70
71/// A list of records as one tape, its length written to `out_count`.
72///
73/// # Safety
74/// `out_count` checked non-null by the caller; the buffers as for `Out`.
75unsafe fn list(
76    records: &[Record],
77    out_count: *mut usize,
78    out: &Out,
79) -> Result<OpenbimIfcStatus, BindingError> {
80    // SAFETY: caller contract above.
81    if let Err(status) = unsafe { put(out_count, records.len()) } {
82        return done(status);
83    }
84    let tape = Tagged::List(records.iter().map(Record::to_tagged).collect());
85    // SAFETY: caller contract above.
86    unsafe { out.write(&tape) }
87}
88
89/// Run a list-returning domain read on `model`.
90///
91/// # Safety
92/// As for [`list`].
93pub(crate) unsafe fn list_export(
94    model: OpenbimIfcModel,
95    out_count: *mut usize,
96    out: Out,
97    read: impl FnOnce(&IfcModel) -> Result<Vec<Record>, BindingError>,
98) -> OpenbimIfcStatus {
99    boundary(|| {
100        if out_count.is_null() {
101            return OpenbimIfcStatus::NullPointer;
102        }
103        with_model(model, |m| {
104            let records = read(m)?;
105            // SAFETY: checked non-null; caller contract.
106            unsafe { list(&records, out_count, &out) }
107        })
108    })
109}
110
111/// Run a single-record domain read on `model`; `None` is a `NULL` tape.
112///
113/// # Safety
114/// The buffers as for `Out`.
115unsafe fn record_export(
116    model: OpenbimIfcModel,
117    out: Out,
118    read: impl FnOnce(&IfcModel) -> Result<Option<Record>, BindingError>,
119) -> OpenbimIfcStatus {
120    boundary(|| {
121        with_model(model, |m| {
122            let value = read(m)?.map_or(Tagged::Null, |record| record.to_tagged());
123            // SAFETY: caller contract.
124            unsafe { out.write(&value) }
125        })
126    })
127}
128
129/// The property sets of `object`: a `LIST` of `PropertySet` records, its
130/// own sets first, then those its type object holds; `out_count` gets their
131/// number. `PropertySet`: id (`REF`), global id, name, type name, source
132/// (`occurrence` or `type`), source id (`REF` or `NULL`), properties
133/// (`LIST` of `Property`). `Property`: id, name, type name, kind, value
134/// type, unit (`REF` or `NULL`), value (tagged, typed), enumeration,
135/// bounds, table, usage, discrimination, quality, members (`LIST` of
136/// `Property`).
137///
138/// `MissingEntity`, `WrongEntityType`, `UnsupportedSchema` (a release other
139/// than IFC2X3, IFC4 or IFC4X3), `InvalidModel`, `FeatureDisabled`.
140///
141/// # Safety
142/// `out_count` valid for one write; otherwise as for
143/// `openbim_ifc_v0_1_entity_attribute`.
144#[no_mangle]
145pub unsafe extern "C" fn openbim_ifc_v0_1_model_property_sets(
146    model: OpenbimIfcModel,
147    object: u64,
148    out_count: *mut usize,
149    nodes: *mut OpenbimIfcValueNode,
150    node_capacity: usize,
151    out_nodes_required: *mut usize,
152    strings: *mut u8,
153    string_capacity: usize,
154    out_strings_required: *mut usize,
155) -> OpenbimIfcStatus {
156    let out = Out {
157        nodes,
158        node_capacity,
159        out_nodes_required,
160        strings,
161        string_capacity,
162        out_strings_required,
163    };
164    // SAFETY: caller contract above.
165    unsafe {
166        list_export(model, out_count, out, |m| {
167            Ok(to_records(&m.property_sets(object)?))
168        })
169    }
170}
171
172/// The property sets of each of `ids` (`id_count` of them), in that
173/// order, or, with `ids` null and `id_count` 0, of every object definition
174/// (`IfcObjectDefinition` and its subtypes) in file order, resolved in one
175/// pass through one property index (#358): a `LIST` of
176/// `ObjectPropertySets` records, their number in `out_count`.
177/// `ObjectPropertySets`: object (`REF`), sets (`LIST` of `PropertySet`, as
178/// for [`openbim_ifc_v0_1_model_property_sets`]; empty when refused),
179/// refusal (`PropertyRefusal` or `NULL`: code (`TEXT`, the shared binding
180/// code), message (`TEXT`)). Each record is exactly what the per-object
181/// call answers for that id, its refusal included.
182///
183/// Refused as a whole only for the model: `UnsupportedSchema`,
184/// `InvalidModel` (a lenient read with skipped records),
185/// `FeatureDisabled`; `NullPointer` for null `ids` with a non-zero count.
186///
187/// # Safety
188/// `ids` valid for `id_count` reads when non-null; `out_count` valid for
189/// one write; otherwise as for `openbim_ifc_v0_1_entity_attribute`.
190#[no_mangle]
191pub unsafe extern "C" fn openbim_ifc_v0_1_model_property_sets_many(
192    model: OpenbimIfcModel,
193    ids: *const u64,
194    id_count: usize,
195    out_count: *mut usize,
196    nodes: *mut OpenbimIfcValueNode,
197    node_capacity: usize,
198    out_nodes_required: *mut usize,
199    strings: *mut u8,
200    string_capacity: usize,
201    out_strings_required: *mut usize,
202) -> OpenbimIfcStatus {
203    // SAFETY: caller contract above.
204    let ids = match unsafe { crate::geometry::selection(ids, id_count) } {
205        Ok(ids) => ids,
206        Err(status) => return status,
207    };
208    let out = Out {
209        nodes,
210        node_capacity,
211        out_nodes_required,
212        strings,
213        string_capacity,
214        out_strings_required,
215    };
216    // SAFETY: caller contract above.
217    unsafe {
218        list_export(model, out_count, out, |m| {
219            Ok(to_records(&m.property_sets_many(ids)?))
220        })
221    }
222}
223
224/// The effective unit of a `measure_type` value (`IFCAREAMEASURE`, UTF-8,
225/// `measure_len` bytes): `unit` when non-zero (a property's stated unit),
226/// otherwise the project default. The tape is one `ResolvedUnit`: unit
227/// (`REF` or `NULL`), from project (`BOOL`), dimensions (`LIST` of seven
228/// `INTEGER`s, SI exponents L M T I Θ N J), scale (`REAL`), offset (`REAL`).
229///
230/// `InvalidValue` for a type that is no measure, `Unsupported`,
231/// `InvalidModel`, `FeatureDisabled`.
232///
233/// # Safety
234/// `measure_type` valid for `measure_len` reads; otherwise as for
235/// `openbim_ifc_v0_1_entity_attribute`.
236#[no_mangle]
237pub unsafe extern "C" fn openbim_ifc_v0_1_model_resolve_unit(
238    model: OpenbimIfcModel,
239    measure_type: *const u8,
240    measure_len: usize,
241    unit: u64,
242    nodes: *mut OpenbimIfcValueNode,
243    node_capacity: usize,
244    out_nodes_required: *mut usize,
245    strings: *mut u8,
246    string_capacity: usize,
247    out_strings_required: *mut usize,
248) -> OpenbimIfcStatus {
249    // SAFETY: caller contract above.
250    let measure = match unsafe { text(measure_type, measure_len) } {
251        Ok(measure) => measure,
252        Err(status) => return status,
253    };
254    let out = Out {
255        nodes,
256        node_capacity,
257        out_nodes_required,
258        strings,
259        string_capacity,
260        out_strings_required,
261    };
262    // SAFETY: caller contract above.
263    unsafe {
264        record_export(model, out, |m| {
265            let unit = m.resolve_unit(measure, (unit != 0).then_some(unit))?;
266            Ok(Some(unit.to_record()))
267        })
268    }
269}
270
271/// The spatial containment tree as one `SpatialTree` record: release
272/// (`TEXT` or `NULL`), roots (`LIST` of `REF`), nodes (`LIST` of
273/// `SpatialNode`: id, global id, name, type name, kind, parent, children,
274/// elements, referenced), orphans, dangling (`LIST` of `[relation,
275/// target]`), anomalies (`LIST` of `[kind, relation, subject, kept]`).
276///
277/// `UnsupportedSchema` when the header names no bundled release;
278/// `FeatureDisabled`.
279///
280/// # Safety
281/// As for `openbim_ifc_v0_1_entity_attribute`.
282#[no_mangle]
283pub unsafe extern "C" fn openbim_ifc_v0_1_model_spatial_tree(
284    model: OpenbimIfcModel,
285    nodes: *mut OpenbimIfcValueNode,
286    node_capacity: usize,
287    out_nodes_required: *mut usize,
288    strings: *mut u8,
289    string_capacity: usize,
290    out_strings_required: *mut usize,
291) -> OpenbimIfcStatus {
292    let out = Out {
293        nodes,
294        node_capacity,
295        out_nodes_required,
296        strings,
297        string_capacity,
298        out_strings_required,
299    };
300    // SAFETY: caller contract above.
301    unsafe { record_export(model, out, |m| Ok(Some(m.spatial_tree()?.to_record()))) }
302}
303
304/// The classifications of `object`: a `LIST` of `Classification` records,
305/// its own then its type object's; `out_count` gets their number.
306/// `Classification`: relationship (`REF`), global id, source, type object,
307/// target (`REF`), kind (`reference`, `system` or `notation`),
308/// identification, name, location, notation (`LIST` of `TEXT`), parents
309/// (`LIST` of `REF`), system (`[id, name, source, edition]` or `NULL`).
310///
311/// `MissingEntity`, `UnsupportedSchema`, `InvalidModel`,
312/// `MissingReference`, `BudgetExceeded`, `FeatureDisabled`.
313///
314/// # Safety
315/// As for `openbim_ifc_v0_1_model_property_sets`.
316#[no_mangle]
317pub unsafe extern "C" fn openbim_ifc_v0_1_model_classifications(
318    model: OpenbimIfcModel,
319    object: u64,
320    out_count: *mut usize,
321    nodes: *mut OpenbimIfcValueNode,
322    node_capacity: usize,
323    out_nodes_required: *mut usize,
324    strings: *mut u8,
325    string_capacity: usize,
326    out_strings_required: *mut usize,
327) -> OpenbimIfcStatus {
328    let out = Out {
329        nodes,
330        node_capacity,
331        out_nodes_required,
332        strings,
333        string_capacity,
334        out_strings_required,
335    };
336    // SAFETY: caller contract above.
337    unsafe {
338        list_export(model, out_count, out, |m| {
339            Ok(to_records(&m.classifications(object)?))
340        })
341    }
342}
343
344/// The material association of `object`, its own or its type object's, as
345/// one `MaterialAssignment` record, or a `NULL` tape when there is none:
346/// relationship, global id, source, type object, target, type name, kind,
347/// set, name, materials, layers, profiles, constituents (each a `LIST` of
348/// records), usage (record or `NULL`).
349///
350/// `MissingEntity`, `UnsupportedSchema`, `InvalidModel`,
351/// `MissingReference`, `FeatureDisabled`.
352///
353/// # Safety
354/// As for `openbim_ifc_v0_1_entity_attribute`.
355#[no_mangle]
356pub unsafe extern "C" fn openbim_ifc_v0_1_model_material(
357    model: OpenbimIfcModel,
358    object: u64,
359    nodes: *mut OpenbimIfcValueNode,
360    node_capacity: usize,
361    out_nodes_required: *mut usize,
362    strings: *mut u8,
363    string_capacity: usize,
364    out_strings_required: *mut usize,
365) -> OpenbimIfcStatus {
366    let out = Out {
367        nodes,
368        node_capacity,
369        out_nodes_required,
370        strings,
371        string_capacity,
372        out_strings_required,
373    };
374    // SAFETY: caller contract above.
375    unsafe {
376        record_export(model, out, |m| {
377            Ok(m.material(object)?.map(|material| material.to_record()))
378        })
379    }
380}
381
382/// Every system as one `Systems` record: systems (`LIST` of `System`: id,
383/// global id, type name, name, long name, predefined type, members,
384/// serviced buildings, serviced facilities) and anomalies (`LIST` of
385/// `[kind, subject, other, message]`).
386///
387/// `UnsupportedSchema`, `FeatureDisabled`.
388///
389/// # Safety
390/// As for `openbim_ifc_v0_1_entity_attribute`.
391#[no_mangle]
392pub unsafe extern "C" fn openbim_ifc_v0_1_model_systems(
393    model: OpenbimIfcModel,
394    nodes: *mut OpenbimIfcValueNode,
395    node_capacity: usize,
396    out_nodes_required: *mut usize,
397    strings: *mut u8,
398    string_capacity: usize,
399    out_strings_required: *mut usize,
400) -> OpenbimIfcStatus {
401    let out = Out {
402        nodes,
403        node_capacity,
404        out_nodes_required,
405        strings,
406        string_capacity,
407        out_strings_required,
408    };
409    // SAFETY: caller contract above.
410    unsafe { record_export(model, out, |m| Ok(Some(m.systems()?.to_record()))) }
411}
412
413/// Every cost schedule and cost item as one `Cost` record: schedules
414/// (`LIST` of `CostSchedule`), items (`LIST` of `CostItem`, each with its
415/// `CostValue` tree, applied values tagged), anomalies.
416///
417/// `UnsupportedSchema`, `MissingReference`, `BudgetExceeded`,
418/// `FeatureDisabled`.
419///
420/// # Safety
421/// As for `openbim_ifc_v0_1_entity_attribute`.
422#[no_mangle]
423pub unsafe extern "C" fn openbim_ifc_v0_1_model_cost(
424    model: OpenbimIfcModel,
425    nodes: *mut OpenbimIfcValueNode,
426    node_capacity: usize,
427    out_nodes_required: *mut usize,
428    strings: *mut u8,
429    string_capacity: usize,
430    out_strings_required: *mut usize,
431) -> OpenbimIfcStatus {
432    let out = Out {
433        nodes,
434        node_capacity,
435        out_nodes_required,
436        strings,
437        string_capacity,
438        out_strings_required,
439    };
440    // SAFETY: caller contract above.
441    unsafe { record_export(model, out, |m| Ok(Some(m.cost()?.to_record()))) }
442}
443
444/// Every coordinate operation, resolved: a `LIST` of `MapConversion`
445/// records, empty when the model has none; `out_count` gets their number.
446/// `MapConversion`: operation, kind, source, source kind, target CRS
447/// (`ProjectedCrs` record), eastings, northings, orthogonal height, x axis
448/// (two `REAL`s), scale, factors (three `REAL`s or `NULL`), project unit
449/// and map unit (`[name, metres per unit]`), map unit declared (`BOOL`),
450/// linear (three columns of three `REAL`s), translation (three `REAL`s).
451///
452/// IFC2X3 is read from the `ePSet_MapConversion` and `ePSet_ProjectedCRS`
453/// property sets: source kind `property-set`, source the `IfcProject` or
454/// `IfcSite` carrying them.
455///
456/// `UnsupportedSchema` (anything but IFC2X3, IFC4 and IFC4X3),
457/// `Unsupported`, `InvalidModel`, `MissingReference`, `FeatureDisabled`.
458///
459/// # Safety
460/// As for `openbim_ifc_v0_1_model_property_sets`.
461#[no_mangle]
462pub unsafe extern "C" fn openbim_ifc_v0_1_model_georeferencing(
463    model: OpenbimIfcModel,
464    out_count: *mut usize,
465    nodes: *mut OpenbimIfcValueNode,
466    node_capacity: usize,
467    out_nodes_required: *mut usize,
468    strings: *mut u8,
469    string_capacity: usize,
470    out_strings_required: *mut usize,
471) -> OpenbimIfcStatus {
472    let out = Out {
473        nodes,
474        node_capacity,
475        out_nodes_required,
476        strings,
477        string_capacity,
478        out_strings_required,
479    };
480    // SAFETY: caller contract above.
481    unsafe {
482        list_export(model, out_count, out, |m| {
483            Ok(to_records(&m.georeferencing()?))
484        })
485    }
486}