Skip to main content

openbim_ifc_capi/
edits.rs

1//! Writing property sets (#123) through the C ABI.
2//!
3//! A batch crosses as one value tape: a `LIST` of edits, each a `LIST` of
4//! an `ENUM` (`SET` or `REMOVE`), the object (`REF` or `INTEGER`), the set
5//! name and the property name (`TEXT`), then, for `SET`, the value (the read
6//! side's `value` field, typed) and an optional set type (`TEXT` or
7//! `NULL`). The core reads it (`PropertyEdit::from_tagged`), so the layout
8//! is the same one the other hosts' objects carry.
9//!
10//! A batch is applied once: unlike a read, it has no size query that runs
11//! it. The caller passes a buffer for one id per edit, which is checked
12//! before anything is written.
13
14use openbim_ifc_binding_core::property_edit::PropertyEdit;
15use openbim_ifc_binding_core::value::Tagged;
16use openbim_ifc_binding_core::BindingError;
17
18use crate::buffer::{bytes, fill, put, slice, text};
19use crate::model::{with_model, OpenbimIfcModel};
20use crate::status::{boundary, OpenbimIfcStatus};
21use crate::tape::{OpenbimIfcValueNode, Reader};
22
23/// Apply the edits on the tape as one checked transaction: all of them, in
24/// order, or none, and the model unchanged.
25///
26/// `out_count` gets the number of edits. `out_properties` gets, per edit,
27/// the id of the entity holding the property afterwards, or 0 when the
28/// batch leaves none; with `properties_capacity` below the edit count the
29/// call returns `BufferTooSmall` and applies nothing.
30///
31/// `InvalidArgument` or `InvalidValue` for a malformed tape;
32/// `MissingEntity`, `WrongEntityType`, `UnsupportedSchema`, `InvalidValue`,
33/// `TemplateViolation`, `MissingProperty`, `Unsupported`, `InvalidModel`,
34/// `FeatureDisabled` as the shared codes say.
35///
36/// # Safety
37/// `nodes` valid for `node_count` reads and `strings` for `string_len`
38/// (either null when its length is 0); `out_properties` null with capacity
39/// 0, or valid for `properties_capacity` writes; `out_count` valid for one
40/// write.
41#[no_mangle]
42pub unsafe extern "C" fn openbim_ifc_v0_1_model_set_properties(
43    model: OpenbimIfcModel,
44    nodes: *const OpenbimIfcValueNode,
45    node_count: usize,
46    strings: *const u8,
47    string_len: usize,
48    out_properties: *mut u64,
49    properties_capacity: usize,
50    out_count: *mut usize,
51) -> OpenbimIfcStatus {
52    boundary(|| {
53        if out_count.is_null() || (out_properties.is_null() && properties_capacity != 0) {
54            return OpenbimIfcStatus::NullPointer;
55        }
56        // SAFETY: caller contract above.
57        let (nodes, strings) =
58            match unsafe { (slice(nodes, node_count), bytes(strings, string_len)) } {
59                (Ok(n), Ok(s)) => (n, s),
60                (Err(status), _) | (_, Err(status)) => return status,
61            };
62        with_model(model, |m| {
63            let Tagged::List(items) = Reader::new(nodes, strings).single()? else {
64                return Err(BindingError::InvalidValue(
65                    "property edits are one LIST of edits".into(),
66                ));
67            };
68            let edits = items
69                .iter()
70                .enumerate()
71                .map(|(index, item)| {
72                    PropertyEdit::from_tagged(item).map_err(|error| match error {
73                        BindingError::InvalidValue(detail) => {
74                            BindingError::InvalidValue(format!("edit {index}: {detail}"))
75                        }
76                        other => other,
77                    })
78                })
79                .collect::<Result<Vec<_>, _>>()?;
80            // SAFETY: checked non-null; caller contract above.
81            if let Err(status) = unsafe { put(out_count, edits.len()) } {
82                return Ok(status);
83            }
84            if properties_capacity < edits.len() {
85                return Ok(OpenbimIfcStatus::BufferTooSmall);
86            }
87            let result = m.set_properties(edits)?;
88            let ids: Vec<u64> = result.properties.iter().map(|id| id.unwrap_or(0)).collect();
89            let mut written = 0;
90            // SAFETY: capacity checked above; caller contract above.
91            Ok(unsafe { fill(&ids, out_properties, properties_capacity, &mut written) })
92        })
93    })
94}
95
96/// Write one value: [`openbim_ifc_v0_1_model_set_properties`] with one
97/// `SET` edit. `set` and `name` are UTF-8; the value is a one-value tape;
98/// `set_type` (`IfcPropertySet` or `IfcElementQuantity`) may be null with
99/// length 0. `out_id` gets the entity holding the property.
100///
101/// # Safety
102/// `set`, `name` and `set_type` valid for their lengths (null only for 0);
103/// the tape as for `openbim_ifc_v0_1_entity_set_attribute`; `out_id` valid
104/// for one write.
105#[no_mangle]
106pub unsafe extern "C" fn openbim_ifc_v0_1_model_set_property(
107    model: OpenbimIfcModel,
108    object: u64,
109    set: *const u8,
110    set_len: usize,
111    name: *const u8,
112    name_len: usize,
113    nodes: *const OpenbimIfcValueNode,
114    node_count: usize,
115    strings: *const u8,
116    string_len: usize,
117    set_type: *const u8,
118    set_type_len: usize,
119    out_id: *mut u64,
120) -> OpenbimIfcStatus {
121    boundary(|| {
122        if out_id.is_null() {
123            return OpenbimIfcStatus::NullPointer;
124        }
125        // SAFETY: caller contract above.
126        let inputs = unsafe {
127            (
128                text(set, set_len),
129                text(name, name_len),
130                text(set_type, set_type_len),
131                slice(nodes, node_count),
132                bytes(strings, string_len),
133            )
134        };
135        let (set, name, set_type, nodes, strings) = match inputs {
136            (Ok(a), Ok(b), Ok(c), Ok(d), Ok(e)) => (a, b, c, d, e),
137            (Err(status), ..)
138            | (_, Err(status), ..)
139            | (_, _, Err(status), ..)
140            | (_, _, _, Err(status), _)
141            | (.., Err(status)) => return status,
142        };
143        let set_type = (!set_type.is_empty()).then(|| set_type.to_owned());
144        with_model(model, |m| {
145            let value = Reader::new(nodes, strings).single()?;
146            let id = m.set_property(object, set, name, value, set_type)?;
147            // SAFETY: checked non-null; caller contract above.
148            unsafe { out_id.write(id) };
149            Ok(OpenbimIfcStatus::Ok)
150        })
151    })
152}
153
154/// Remove one property from `object`'s own set:
155/// [`openbim_ifc_v0_1_model_set_properties`] with one `REMOVE` edit.
156///
157/// # Safety
158/// `set` and `name` valid for their lengths (null only for 0).
159#[no_mangle]
160pub unsafe extern "C" fn openbim_ifc_v0_1_model_remove_property(
161    model: OpenbimIfcModel,
162    object: u64,
163    set: *const u8,
164    set_len: usize,
165    name: *const u8,
166    name_len: usize,
167) -> OpenbimIfcStatus {
168    boundary(|| {
169        // SAFETY: caller contract above.
170        let (set, name) = match unsafe { (text(set, set_len), text(name, name_len)) } {
171            (Ok(set), Ok(name)) => (set, name),
172            (Err(status), _) | (_, Err(status)) => return status,
173        };
174        with_model(model, |m| {
175            m.remove_property(object, set, name)?;
176            Ok(OpenbimIfcStatus::Ok)
177        })
178    })
179}