Skip to main content

openbim_ifc_capi/
model.rs

1//! The model exports: create, parse, query, edit, write, destroy.
2//!
3//! Every function follows one shape: validate pointers, look up the handle,
4//! call the shared core, record a failure as the model's last error, and
5//! copy the result into caller memory. No IFC behaviour lives here.
6
7use openbim_ifc_binding_core::{BindingError, IfcModel};
8
9use crate::buffer::{bytes, fill, fill_c_string, put, slice, text};
10use crate::registry::{self, lock, Entry};
11use crate::status::{boundary, OpenbimIfcStatus, OpenbimIfcVersion};
12use crate::tape::{OpenbimIfcValueNode, Reader, Tape};
13
14/// ABI version implemented by this crate; also the `v0_1` symbol prefix.
15const ABI: (u16, u16, u16) = (0, 1, 24);
16
17/// Opaque model handle. Zero is never a valid handle.
18pub type OpenbimIfcModel = u64;
19
20/// Run `operation` against the live model behind `handle`.
21///
22/// A [`BindingError`] is stored as the model's last error and mapped to its
23/// status; a successful call clears the last error, so the error a host
24/// reads always belongs to the call that just failed.
25pub(crate) fn with_model(
26    handle: OpenbimIfcModel,
27    operation: impl FnOnce(&mut IfcModel) -> Result<OpenbimIfcStatus, BindingError>,
28) -> OpenbimIfcStatus {
29    let Some(shared) = registry::get(handle) else {
30        return OpenbimIfcStatus::InvalidHandle;
31    };
32    let mut entry = lock(&shared);
33    let Entry { model, last_error } = &mut *entry;
34    match operation(model) {
35        Ok(status) => {
36            *last_error = None;
37            status
38        }
39        Err(error) => {
40            let status = OpenbimIfcStatus::from(&error);
41            *last_error = Some(error);
42            status
43        }
44    }
45}
46
47/// Status from a buffer helper, which already speaks the C protocol.
48pub(crate) fn done(status: OpenbimIfcStatus) -> Result<OpenbimIfcStatus, BindingError> {
49    Ok(status)
50}
51
52/// Write the ABI and crate versions.
53///
54/// # Safety
55/// `out_version` must be null or valid for one write.
56#[no_mangle]
57pub unsafe extern "C" fn openbim_ifc_v0_1_version(
58    out_version: *mut OpenbimIfcVersion,
59) -> OpenbimIfcStatus {
60    boundary(|| {
61        let version = OpenbimIfcVersion {
62            abi_major: ABI.0,
63            abi_minor: ABI.1,
64            abi_patch: ABI.2,
65            crate_major: env!("CARGO_PKG_VERSION_MAJOR").parse().unwrap_or(0),
66            crate_minor: env!("CARGO_PKG_VERSION_MINOR").parse().unwrap_or(0),
67            crate_patch: env!("CARGO_PKG_VERSION_PATCH").parse().unwrap_or(0),
68        };
69        // SAFETY: caller contract above.
70        unsafe { put(out_version, version) }
71            .err()
72            .unwrap_or(OpenbimIfcStatus::Ok)
73    })
74}
75
76/// Create an empty model and write its handle to `out_model`.
77///
78/// # Safety
79/// `out_model` must be null or valid for one write.
80#[no_mangle]
81pub unsafe extern "C" fn openbim_ifc_v0_1_model_create(
82    out_model: *mut OpenbimIfcModel,
83) -> OpenbimIfcStatus {
84    boundary(|| {
85        if out_model.is_null() {
86            return OpenbimIfcStatus::NullPointer;
87        }
88        let handle = registry::insert(IfcModel::empty());
89        // SAFETY: checked non-null; caller contract above.
90        unsafe { put(out_model, handle) }
91            .err()
92            .unwrap_or(OpenbimIfcStatus::Ok)
93    })
94}
95
96/// Parse `len` bytes of STEP and write the new model's handle.
97///
98/// An ifcZIP archive, recognized by its ZIP signature, is read too: its one
99/// STEP or ifcXML model, within a decompression budget. `Parse` for an
100/// archive with no model or several, `Unsupported` for an encrypted entry
101/// or a compression other than Stored and Deflate, `BudgetExceeded` for an
102/// entry that inflates past the budget.
103///
104/// A parse failure has no model to hold its error, so the message is written
105/// to the optional `error_buffer` (NUL-terminated, truncated to `capacity`).
106///
107/// # Safety
108/// `data` must be valid for `len` reads; `out_model` for one write;
109/// `error_buffer`, if non-null, for `capacity` writes.
110#[no_mangle]
111pub unsafe extern "C" fn openbim_ifc_v0_1_model_parse(
112    data: *const u8,
113    len: usize,
114    out_model: *mut OpenbimIfcModel,
115    error_buffer: *mut u8,
116    capacity: usize,
117) -> OpenbimIfcStatus {
118    boundary(|| {
119        if out_model.is_null() || (capacity != 0 && error_buffer.is_null()) {
120            return OpenbimIfcStatus::NullPointer;
121        }
122        // SAFETY: caller contract above.
123        let input = match unsafe { bytes(data, len) } {
124            Ok(input) => input,
125            Err(status) => return status,
126        };
127        // SAFETY: caller contract above.
128        unsafe { finish_load(IfcModel::parse(input), out_model, error_buffer, capacity) }
129    })
130}
131
132/// Completes a load: registers the model and writes its handle, or writes
133/// the error message to the optional `error_buffer` (NUL-terminated,
134/// truncated on a character boundary to `capacity`) and returns its status.
135///
136/// # Safety
137/// `out_model` must be non-null and valid for one write; `error_buffer`,
138/// if `capacity` is non-zero, non-null and valid for `capacity` writes.
139pub(crate) unsafe fn finish_load(
140    loaded: Result<IfcModel, BindingError>,
141    out_model: *mut OpenbimIfcModel,
142    error_buffer: *mut u8,
143    capacity: usize,
144) -> OpenbimIfcStatus {
145    match loaded {
146        Ok(model) => {
147            let handle = registry::insert(model);
148            // SAFETY: caller contract above.
149            unsafe { put(out_model, handle) }
150                .err()
151                .unwrap_or(OpenbimIfcStatus::Ok)
152        }
153        Err(error) => {
154            if capacity != 0 {
155                let message = error.to_string();
156                let count = message.len().min(capacity - 1);
157                // Truncate on a char boundary so C sees valid UTF-8.
158                let count = (0..=count)
159                    .rev()
160                    .find(|i| message.is_char_boundary(*i))
161                    .unwrap_or(0);
162                // SAFETY: non-null with `capacity` > count bytes (caller contract).
163                unsafe {
164                    std::ptr::copy_nonoverlapping(message.as_ptr(), error_buffer, count);
165                    error_buffer.add(count).write(0);
166                }
167            }
168            OpenbimIfcStatus::from(&error)
169        }
170    }
171}
172
173/// Destroy a model. A stale or repeated handle is `InvalidHandle`.
174#[no_mangle]
175pub extern "C" fn openbim_ifc_v0_1_model_destroy(model: OpenbimIfcModel) -> OpenbimIfcStatus {
176    boundary(|| {
177        if registry::remove(model) {
178            OpenbimIfcStatus::Ok
179        } else {
180            OpenbimIfcStatus::InvalidHandle
181        }
182    })
183}
184
185/// Number of live models, for leak checks.
186///
187/// # Safety
188/// `out_count` must be null or valid for one write.
189#[no_mangle]
190pub unsafe extern "C" fn openbim_ifc_v0_1_live_models(out_count: *mut usize) -> OpenbimIfcStatus {
191    boundary(|| {
192        // SAFETY: caller contract above.
193        unsafe { put(out_count, registry::live()) }
194            .err()
195            .unwrap_or(OpenbimIfcStatus::Ok)
196    })
197}
198
199/// Serialize as STEP into a caller buffer; `out_required` gets the size.
200///
201/// # Safety
202/// `buffer` must be null (with `capacity` 0) or valid for `capacity`
203/// writes; `out_required` valid for one write.
204#[no_mangle]
205pub unsafe extern "C" fn openbim_ifc_v0_1_model_write(
206    model: OpenbimIfcModel,
207    buffer: *mut u8,
208    capacity: usize,
209    out_required: *mut usize,
210) -> OpenbimIfcStatus {
211    boundary(|| {
212        with_model(model, |m| {
213            let bytes = m.write()?;
214            // SAFETY: caller contract above.
215            done(unsafe { fill(&bytes, buffer, capacity, out_required) })
216        })
217    })
218}
219
220/// Number of entities.
221///
222/// # Safety
223/// `out_count` must be null or valid for one write.
224#[no_mangle]
225pub unsafe extern "C" fn openbim_ifc_v0_1_model_len(
226    model: OpenbimIfcModel,
227    out_count: *mut usize,
228) -> OpenbimIfcStatus {
229    boundary(|| {
230        with_model(model, |m| {
231            // SAFETY: caller contract above.
232            done(
233                unsafe { put(out_count, m.len()) }
234                    .err()
235                    .unwrap_or(OpenbimIfcStatus::Ok),
236            )
237        })
238    })
239}
240
241/// The first `FILE_SCHEMA` token as a NUL-terminated string, or `NoValue`.
242///
243/// # Safety
244/// As for [`openbim_ifc_v0_1_model_write`].
245#[no_mangle]
246pub unsafe extern "C" fn openbim_ifc_v0_1_model_schema(
247    model: OpenbimIfcModel,
248    buffer: *mut u8,
249    capacity: usize,
250    out_required: *mut usize,
251) -> OpenbimIfcStatus {
252    boundary(|| {
253        with_model(model, |m| {
254            Ok(match m.schema() {
255                // SAFETY: caller contract above.
256                Some(token) => unsafe { fill_c_string(token, buffer, capacity, out_required) },
257                None => OpenbimIfcStatus::NoValue,
258            })
259        })
260    })
261}
262
263/// Every entity id, in file order.
264///
265/// # Safety
266/// `buffer` must be null (with `capacity` 0) or valid for `capacity` `u64`
267/// writes; `out_required` valid for one write.
268#[no_mangle]
269pub unsafe extern "C" fn openbim_ifc_v0_1_model_ids(
270    model: OpenbimIfcModel,
271    buffer: *mut u64,
272    capacity: usize,
273    out_required: *mut usize,
274) -> OpenbimIfcStatus {
275    boundary(|| {
276        with_model(model, |m| {
277            // SAFETY: caller contract above.
278            done(unsafe { fill(&m.ids(), buffer, capacity, out_required) })
279        })
280    })
281}
282
283/// Ids of every entity of exactly `type_name` (UTF-8, `type_len` bytes,
284/// case-insensitive). Subtypes are not included.
285///
286/// # Safety
287/// `type_name` must be valid for `type_len` reads; otherwise as for
288/// [`openbim_ifc_v0_1_model_ids`].
289#[no_mangle]
290pub unsafe extern "C" fn openbim_ifc_v0_1_model_ids_of_type(
291    model: OpenbimIfcModel,
292    type_name: *const u8,
293    type_len: usize,
294    buffer: *mut u64,
295    capacity: usize,
296    out_required: *mut usize,
297) -> OpenbimIfcStatus {
298    boundary(|| {
299        // SAFETY: caller contract above.
300        let name = match unsafe { text(type_name, type_len) } {
301            Ok(name) => name,
302            Err(status) => return status,
303        };
304        with_model(model, |m| {
305            // SAFETY: caller contract above.
306            done(unsafe { fill(&m.ids_of_type(name), buffer, capacity, out_required) })
307        })
308    })
309}
310
311/// Ids of every entity of `type_name` or any of its subtypes, using the
312/// schema the file's header declares. `UnsupportedSchema` if none is bundled.
313///
314/// # Safety
315/// As for [`openbim_ifc_v0_1_model_ids_of_type`].
316#[no_mangle]
317pub unsafe extern "C" fn openbim_ifc_v0_1_model_ids_of_type_including_subtypes(
318    model: OpenbimIfcModel,
319    type_name: *const u8,
320    type_len: usize,
321    buffer: *mut u64,
322    capacity: usize,
323    out_required: *mut usize,
324) -> OpenbimIfcStatus {
325    boundary(|| {
326        // SAFETY: caller contract above.
327        let name = match unsafe { text(type_name, type_len) } {
328            Ok(name) => name,
329            Err(status) => return status,
330        };
331        with_model(model, |m| {
332            let ids = m.ids_of_type_including_subtypes(name)?;
333            // SAFETY: caller contract above.
334            done(unsafe { fill(&ids, buffer, capacity, out_required) })
335        })
336    })
337}
338
339/// The type name of entity `id`, upper-case, NUL-terminated.
340///
341/// # Safety
342/// As for [`openbim_ifc_v0_1_model_write`].
343#[no_mangle]
344pub unsafe extern "C" fn openbim_ifc_v0_1_entity_type(
345    model: OpenbimIfcModel,
346    id: u64,
347    buffer: *mut u8,
348    capacity: usize,
349    out_required: *mut usize,
350) -> OpenbimIfcStatus {
351    boundary(|| {
352        with_model(model, |m| {
353            let name = m.type_of(id)?;
354            // SAFETY: caller contract above.
355            done(unsafe { fill_c_string(name, buffer, capacity, out_required) })
356        })
357    })
358}
359
360/// Copy a tape into the caller's two buffers.
361///
362/// Both required sizes are written before either capacity is checked, so a
363/// single size query (both buffers null, capacities 0) sizes both.
364///
365/// # Safety
366/// Each buffer must be null (with its capacity 0) or valid for its capacity
367/// in writes; both `out_*_required` valid for one write.
368pub(crate) unsafe fn fill_tape(
369    tape: &Tape,
370    nodes: *mut OpenbimIfcValueNode,
371    node_capacity: usize,
372    out_nodes_required: *mut usize,
373    strings: *mut u8,
374    string_capacity: usize,
375    out_strings_required: *mut usize,
376) -> OpenbimIfcStatus {
377    // SAFETY: forwarded caller contract.
378    let node_status = unsafe { fill(&tape.nodes, nodes, node_capacity, out_nodes_required) };
379    // SAFETY: forwarded caller contract.
380    let string_status = unsafe {
381        fill(
382            &tape.strings,
383            strings,
384            string_capacity,
385            out_strings_required,
386        )
387    };
388    // Report the more serious of the two: a null pointer beats a short buffer.
389    match (node_status, string_status) {
390        (OpenbimIfcStatus::Ok, other) | (other, OpenbimIfcStatus::Ok) => other,
391        (OpenbimIfcStatus::BufferTooSmall, other) => other,
392        (first, _) => first,
393    }
394}
395
396/// Attribute `index` of entity `id` as a value tape (`$` past the end).
397///
398/// # Safety
399/// As for `fill_tape`: each buffer null with capacity 0, or valid for its
400/// capacity; both `out_*_required` valid for one write.
401#[no_mangle]
402pub unsafe extern "C" fn openbim_ifc_v0_1_entity_attribute(
403    model: OpenbimIfcModel,
404    id: u64,
405    index: usize,
406    nodes: *mut OpenbimIfcValueNode,
407    node_capacity: usize,
408    out_nodes_required: *mut usize,
409    strings: *mut u8,
410    string_capacity: usize,
411    out_strings_required: *mut usize,
412) -> OpenbimIfcStatus {
413    boundary(|| {
414        with_model(model, |m| {
415            let tape = Tape::encode(&m.attribute(id, index)?);
416            // SAFETY: caller contract above.
417            done(unsafe {
418                fill_tape(
419                    &tape,
420                    nodes,
421                    node_capacity,
422                    out_nodes_required,
423                    strings,
424                    string_capacity,
425                    out_strings_required,
426                )
427            })
428        })
429    })
430}
431
432/// Every attribute of entity `id`, back to back on one tape, plus how many
433/// top-level values it holds.
434///
435/// # Safety
436/// As for [`openbim_ifc_v0_1_entity_attribute`]; `out_count` valid for one
437/// write.
438#[no_mangle]
439pub unsafe extern "C" fn openbim_ifc_v0_1_entity_attributes(
440    model: OpenbimIfcModel,
441    id: u64,
442    out_count: *mut usize,
443    nodes: *mut OpenbimIfcValueNode,
444    node_capacity: usize,
445    out_nodes_required: *mut usize,
446    strings: *mut u8,
447    string_capacity: usize,
448    out_strings_required: *mut usize,
449) -> OpenbimIfcStatus {
450    boundary(|| {
451        if out_count.is_null() {
452            return OpenbimIfcStatus::NullPointer;
453        }
454        with_model(model, |m| {
455            let values = m.attributes(id)?;
456            let tape = Tape::encode_all(&values);
457            // SAFETY: checked non-null; caller contract above.
458            unsafe { out_count.write(values.len()) };
459            // SAFETY: caller contract above.
460            done(unsafe {
461                fill_tape(
462                    &tape,
463                    nodes,
464                    node_capacity,
465                    out_nodes_required,
466                    strings,
467                    string_capacity,
468                    out_strings_required,
469                )
470            })
471        })
472    })
473}
474
475/// Set attribute `index` of entity `id` from a one-value tape. Writing past
476/// the end pads the gap with `$`.
477///
478/// # Safety
479/// `nodes` must be valid for `node_count` reads and `strings` for
480/// `string_len` reads (either may be null when its length is 0).
481#[no_mangle]
482pub unsafe extern "C" fn openbim_ifc_v0_1_entity_set_attribute(
483    model: OpenbimIfcModel,
484    id: u64,
485    index: usize,
486    nodes: *const OpenbimIfcValueNode,
487    node_count: usize,
488    strings: *const u8,
489    string_len: usize,
490) -> OpenbimIfcStatus {
491    boundary(|| {
492        // SAFETY: caller contract above.
493        let (nodes, strings) =
494            match unsafe { (slice(nodes, node_count), bytes(strings, string_len)) } {
495                (Ok(n), Ok(s)) => (n, s),
496                (Err(status), _) | (_, Err(status)) => return status,
497            };
498        with_model(model, |m| {
499            let value = Reader::new(nodes, strings).single()?;
500            m.set_attribute(id, index, value)?;
501            Ok(OpenbimIfcStatus::Ok)
502        })
503    })
504}
505
506/// Append an entity of `type_name` whose `attribute_count` attributes are
507/// on the tape back to back, and write its new id to `out_id`.
508///
509/// # Safety
510/// As for [`openbim_ifc_v0_1_entity_set_attribute`]; `type_name` valid for
511/// `type_len` reads; `out_id` valid for one write.
512#[no_mangle]
513pub unsafe extern "C" fn openbim_ifc_v0_1_entity_add(
514    model: OpenbimIfcModel,
515    type_name: *const u8,
516    type_len: usize,
517    attribute_count: usize,
518    nodes: *const OpenbimIfcValueNode,
519    node_count: usize,
520    strings: *const u8,
521    string_len: usize,
522    out_id: *mut u64,
523) -> OpenbimIfcStatus {
524    boundary(|| {
525        if out_id.is_null() {
526            return OpenbimIfcStatus::NullPointer;
527        }
528        // SAFETY: caller contract above.
529        let inputs = unsafe {
530            (
531                text(type_name, type_len),
532                slice(nodes, node_count),
533                bytes(strings, string_len),
534            )
535        };
536        let (name, nodes, strings) = match inputs {
537            (Ok(name), Ok(n), Ok(s)) => (name, n, s),
538            (Err(status), _, _) | (_, Err(status), _) | (_, _, Err(status)) => return status,
539        };
540        with_model(model, |m| {
541            let values = Reader::new(nodes, strings).many(attribute_count)?;
542            let id = m.add(name, values)?;
543            // SAFETY: checked non-null; caller contract above.
544            unsafe { out_id.write(id) };
545            Ok(OpenbimIfcStatus::Ok)
546        })
547    })
548}
549
550/// Remove entity `id`; references to it are left dangling.
551///
552/// Deprecated (#478): a file with dangling references parses and is wrong.
553/// Use `openbim_ifc_v0_1_entity_remove_with_relationships` for one entity,
554/// or `openbim_ifc_v0_1_model_remove_product` for a product with what it
555/// solely owns. It keeps working for the life of the `v0_1` ABI.
556#[no_mangle]
557pub extern "C" fn openbim_ifc_v0_1_entity_remove(
558    model: OpenbimIfcModel,
559    id: u64,
560) -> OpenbimIfcStatus {
561    boundary(|| {
562        with_model(model, |m| {
563            m.remove(id)?;
564            Ok(OpenbimIfcStatus::Ok)
565        })
566    })
567}
568
569/// Every dangling reference as `(from, to)` pairs, flattened: element
570/// `2k` is a referencing id, `2k+1` the missing id it points to.
571///
572/// # Safety
573/// As for [`openbim_ifc_v0_1_model_ids`]; sizes count `u64`s, not pairs.
574#[no_mangle]
575pub unsafe extern "C" fn openbim_ifc_v0_1_model_dangling_references(
576    model: OpenbimIfcModel,
577    buffer: *mut u64,
578    capacity: usize,
579    out_required: *mut usize,
580) -> OpenbimIfcStatus {
581    boundary(|| {
582        with_model(model, |m| {
583            let flat: Vec<u64> = m
584                .dangling_references()
585                .into_iter()
586                .flat_map(|(from, to)| [from, to])
587                .collect();
588            // SAFETY: caller contract above.
589            done(unsafe { fill(&flat, buffer, capacity, out_required) })
590        })
591    })
592}
593
594/// Number of non-fatal parse diagnostics.
595///
596/// # Safety
597/// `out_count` must be null or valid for one write.
598#[no_mangle]
599pub unsafe extern "C" fn openbim_ifc_v0_1_model_diagnostic_count(
600    model: OpenbimIfcModel,
601    out_count: *mut usize,
602) -> OpenbimIfcStatus {
603    boundary(|| {
604        with_model(model, |m| {
605            let count = m.diagnostics().len();
606            // SAFETY: caller contract above.
607            done(
608                unsafe { put(out_count, count) }
609                    .err()
610                    .unwrap_or(OpenbimIfcStatus::Ok),
611            )
612        })
613    })
614}
615
616/// Diagnostic `index` as a NUL-terminated string; `OutOfRange` past the end.
617///
618/// # Safety
619/// As for [`openbim_ifc_v0_1_model_write`].
620#[no_mangle]
621pub unsafe extern "C" fn openbim_ifc_v0_1_model_diagnostic(
622    model: OpenbimIfcModel,
623    index: usize,
624    buffer: *mut u8,
625    capacity: usize,
626    out_required: *mut usize,
627) -> OpenbimIfcStatus {
628    boundary(|| {
629        with_model(model, |m| {
630            let all = m.diagnostics();
631            let message = all.get(index).ok_or_else(|| {
632                BindingError::OutOfRange(format!("diagnostic {index} of {}", all.len()))
633            })?;
634            // SAFETY: caller contract above.
635            done(unsafe { fill_c_string(message, buffer, capacity, out_required) })
636        })
637    })
638}
639
640#[cfg(test)]
641mod tests;