Skip to main content

openbim_ifc_capi/
errors.rs

1//! Last-error access, per model.
2
3use crate::buffer::fill_c_string;
4use crate::model::OpenbimIfcModel;
5use crate::registry::{self, lock};
6use crate::status::{boundary, OpenbimIfcStatus};
7
8/// The last error on `model` as its stable code (`parse`, `missing-entity`,
9/// ...), NUL-terminated; `NoValue` if the last call succeeded.
10///
11/// # Safety
12/// `buffer` must be null (with `capacity` 0) or valid for `capacity`
13/// writes; `out_required` valid for one write.
14#[no_mangle]
15pub unsafe extern "C" fn openbim_ifc_v0_1_last_error_code(
16    model: OpenbimIfcModel,
17    buffer: *mut u8,
18    capacity: usize,
19    out_required: *mut usize,
20) -> OpenbimIfcStatus {
21    // SAFETY: forwarded caller contract.
22    boundary(|| {
23        last_error(
24            model,
25            |e| e.code().to_owned(),
26            buffer,
27            capacity,
28            out_required,
29        )
30    })
31}
32
33/// The last error on `model` as a human message, NUL-terminated; `NoValue`
34/// if the last call succeeded.
35///
36/// # Safety
37/// As for [`openbim_ifc_v0_1_last_error_code`].
38#[no_mangle]
39pub unsafe extern "C" fn openbim_ifc_v0_1_last_error_message(
40    model: OpenbimIfcModel,
41    buffer: *mut u8,
42    capacity: usize,
43    out_required: *mut usize,
44) -> OpenbimIfcStatus {
45    boundary(|| last_error(model, ToString::to_string, buffer, capacity, out_required))
46}
47
48fn last_error(
49    model: OpenbimIfcModel,
50    render: impl FnOnce(&openbim_ifc_binding_core::BindingError) -> String,
51    buffer: *mut u8,
52    capacity: usize,
53    out_required: *mut usize,
54) -> OpenbimIfcStatus {
55    let Some(shared) = registry::get(model) else {
56        return OpenbimIfcStatus::InvalidHandle;
57    };
58    // Read without going through `with_model`, which would clear the error.
59    let entry = lock(&shared);
60    match &entry.last_error {
61        None => OpenbimIfcStatus::NoValue,
62        // SAFETY: the exported callers pass their own caller contract here.
63        Some(error) => unsafe { fill_c_string(&render(error), buffer, capacity, out_required) },
64    }
65}