Skip to main content

openbim_ifc_capi/
authoring.rs

1//! Schema-checked entity creation (#330) through the C ABI.
2//!
3//! A batch crosses as one value tape: a `LIST` of operations, each a `LIST`
4//! of an `ENUM` naming it (`CREATE`, `EDIT`, `REMOVE`, `PROJECT`, `SPATIAL`,
5//! `PRODUCT`, `TYPE_OBJECT`, `ASSIGN_TYPE`, `CONTAIN`, `AGGREGATE`,
6//! `PLACEMENT`, `OWNER_HISTORY`, and the shape representation operations
7//! of #481: `SHAPE_REPRESENTATION`, `ASSIGN_REPRESENTATION`,
8//! `UNASSIGN_REPRESENTATION`, `COPY_REPRESENTATION`,
9//! `REMOVE_REPRESENTATION`), then alternating field names (`TEXT`,
10//! snake case) and values; a `NULL` value is an absent field. Ids are `REF`
11//! (or non-negative `INTEGER`), points and directions a `LIST` of three
12//! `REAL`s, flags `BOOL`, attributes a `LIST` of `LIST(TEXT name, value)`.
13//! `ASSIGN_TYPE` takes the flags `map_representations`, `material_usage`
14//! and `replace`, the id `mapping_target`, and the texts
15//! `layer_set_direction` (`AXIS1`..`AXIS3`) and `predefined_type`
16//! (`ignore`, `validate`, `sync`); `CONTAIN` and `AGGREGATE` take
17//! `replace` (#480). The core reads
18//! it (`AuthorOp::from_tagged`), so the layout is the one the other hosts'
19//! objects convert to.
20//!
21//! An operation names the entity an earlier one produced by its handle,
22//! [`OPENBIM_IFC_HANDLE_BASE`] plus the operation's position, anywhere an id
23//! goes.
24
25use openbim_ifc_binding_core::value::Tagged;
26use openbim_ifc_binding_core::{AuthorOp, BindingError};
27
28use crate::buffer::{bytes, fill, put, slice, text};
29use crate::model::{with_model, OpenbimIfcModel};
30use crate::status::{boundary, OpenbimIfcStatus};
31use crate::tape::{OpenbimIfcValueNode, Reader};
32
33/// The first id of the handle range (2^62): `OPENBIM_IFC_HANDLE_BASE + i`
34/// names the entity operation `i` of a batch produced.
35pub const OPENBIM_IFC_HANDLE_BASE: u64 = 4_611_686_018_427_387_904;
36
37const _: () = assert!(OPENBIM_IFC_HANDLE_BASE == openbim_ifc_binding_core::authoring::HANDLE_BASE);
38
39/// Apply the operations on the tape as one checked transaction against the
40/// release the header declares: all of them, in order, or none, and the
41/// model unchanged.
42///
43/// `out_count` gets the number of operations. `out_ids` gets, per
44/// operation, the id of the entity it produced, or 0 for a removal; with
45/// `ids_capacity` below the operation count the call returns
46/// `BufferTooSmall` and applies nothing.
47///
48/// `UnsupportedSchema` for an unbundled release or an undeclared type;
49/// `UnknownAttribute`, `DerivedAttribute`, `MissingAttribute`;
50/// `InvalidValue` for a value of the wrong type, form or cardinality, a
51/// duplicate `GlobalId`, a malformed tape or handle, or a placement the
52/// schema cannot hold; `WrongEntityType` for an abstract type, a builder's
53/// type of the wrong kind or a reference the attribute does not accept;
54/// `MissingEntity`, `MissingReference`; `InvalidModel` for a second
55/// containment, decomposition, typing, material or `IfcProject` (unless
56/// `replace`), a mapped representation that clashes with one the object
57/// has, a `PredefinedType` that contradicts the type's, a shape
58/// representation that already has its one use, a product definition shape
59/// other products share, or a representation not assigned where it is
60/// unassigned from; `InvalidValue` also for a representation type its items
61/// do not fit, items no type fits, or a missing representation identifier;
62/// `Unsupported` for a representation map that cannot be mapped, a material
63/// usage whose defaults cannot be determined, or a representation type check
64/// needing a curve dimension that cannot be derived; `StillReferenced` for a
65/// removal an entity other than a relationship still needs.
66///
67/// # Safety
68/// `nodes` valid for `node_count` reads and `strings` for `string_len`
69/// (either null when its length is 0); `out_ids` null with capacity 0, or
70/// valid for `ids_capacity` writes; `out_count` valid for one write.
71#[no_mangle]
72pub unsafe extern "C" fn openbim_ifc_v0_1_model_author(
73    model: OpenbimIfcModel,
74    nodes: *const OpenbimIfcValueNode,
75    node_count: usize,
76    strings: *const u8,
77    string_len: usize,
78    out_ids: *mut u64,
79    ids_capacity: usize,
80    out_count: *mut usize,
81) -> OpenbimIfcStatus {
82    boundary(|| {
83        if out_count.is_null() || (out_ids.is_null() && ids_capacity != 0) {
84            return OpenbimIfcStatus::NullPointer;
85        }
86        // SAFETY: caller contract above.
87        let (nodes, strings) =
88            match unsafe { (slice(nodes, node_count), bytes(strings, string_len)) } {
89                (Ok(n), Ok(s)) => (n, s),
90                (Err(status), _) | (_, Err(status)) => return status,
91            };
92        with_model(model, |m| {
93            let Tagged::List(items) = Reader::new(nodes, strings).single()? else {
94                return Err(BindingError::InvalidValue(
95                    "an authoring batch is one LIST of operations".into(),
96                ));
97            };
98            let ops = items
99                .iter()
100                .enumerate()
101                .map(|(index, item)| {
102                    AuthorOp::from_tagged(item).map_err(|error| match error {
103                        BindingError::InvalidValue(detail) => {
104                            BindingError::InvalidValue(format!("op {index}: {detail}"))
105                        }
106                        other => other,
107                    })
108                })
109                .collect::<Result<Vec<_>, _>>()?;
110            // SAFETY: checked non-null; caller contract above.
111            if let Err(status) = unsafe { put(out_count, ops.len()) } {
112                return Ok(status);
113            }
114            if ids_capacity < ops.len() {
115                return Ok(OpenbimIfcStatus::BufferTooSmall);
116            }
117            let result = m.author(ops)?;
118            let ids: Vec<u64> = result.ids.iter().map(|id| id.unwrap_or(0)).collect();
119            let mut written = 0;
120            // SAFETY: capacity checked above; caller contract above.
121            Ok(unsafe { fill(&ids, out_ids, ids_capacity, &mut written) })
122        })
123    })
124}
125
126/// Create one entity of `type_name` (UTF-8, any case) from named
127/// attributes: a batch of one `CREATE`. The tape is one `LIST` of
128/// `LIST(TEXT name, value)` pairs (an empty `LIST` for none). An `IfcRoot`
129/// without a `GlobalId` gets a fresh one. `out_id` gets the new id.
130///
131/// Refusals as for [`openbim_ifc_v0_1_model_author`].
132///
133/// # Safety
134/// `type_name` valid for `type_len` reads; the tape as for
135/// [`openbim_ifc_v0_1_model_author`]; `out_id` valid for one write.
136#[no_mangle]
137pub unsafe extern "C" fn openbim_ifc_v0_1_model_create_entity(
138    model: OpenbimIfcModel,
139    type_name: *const u8,
140    type_len: usize,
141    nodes: *const OpenbimIfcValueNode,
142    node_count: usize,
143    strings: *const u8,
144    string_len: usize,
145    out_id: *mut u64,
146) -> OpenbimIfcStatus {
147    boundary(|| {
148        if out_id.is_null() {
149            return OpenbimIfcStatus::NullPointer;
150        }
151        // SAFETY: caller contract above.
152        let inputs = unsafe {
153            (
154                text(type_name, type_len),
155                slice(nodes, node_count),
156                bytes(strings, string_len),
157            )
158        };
159        let (type_name, nodes, strings) = match inputs {
160            (Ok(a), Ok(b), Ok(c)) => (a, b, c),
161            (Err(status), ..) | (_, Err(status), _) | (.., Err(status)) => return status,
162        };
163        with_model(model, |m| {
164            let Tagged::List(pairs) = Reader::new(nodes, strings).single()? else {
165                return Err(BindingError::InvalidValue(
166                    "attributes are one LIST of (TEXT name, value) pairs".into(),
167                ));
168            };
169            let attributes = pairs
170                .into_iter()
171                .map(|pair| match pair {
172                    Tagged::List(pair) => match <[Tagged; 2]>::try_from(pair) {
173                        Ok([Tagged::Text(name), value]) => Ok((name, value)),
174                        _ => Err(()),
175                    },
176                    _ => Err(()),
177                })
178                .collect::<Result<Vec<_>, ()>>()
179                .map_err(|()| {
180                    BindingError::InvalidValue(
181                        "attributes are one LIST of (TEXT name, value) pairs".into(),
182                    )
183                })?;
184            let id = m.create_entity(type_name, attributes)?;
185            // SAFETY: checked non-null; caller contract above.
186            unsafe { out_id.write(id) };
187            Ok(OpenbimIfcStatus::Ok)
188        })
189    })
190}
191
192/// Remove entity `id` with its relationships: it is taken out of every
193/// relationship holding it, and a relationship left without an end goes
194/// too. Unlike `openbim_ifc_v0_1_entity_remove`, nothing is left dangling:
195/// `StillReferenced` while an entity other than a relationship needs `id`,
196/// `MissingEntity` when there is none.
197#[no_mangle]
198pub extern "C" fn openbim_ifc_v0_1_entity_remove_with_relationships(
199    model: OpenbimIfcModel,
200    id: u64,
201) -> OpenbimIfcStatus {
202    boundary(|| {
203        with_model(model, |m| {
204            m.remove_with_relationships(id)?;
205            Ok(OpenbimIfcStatus::Ok)
206        })
207    })
208}