Skip to main content

openbim_ifc_capi/
table.rs

1//! Tables of values by path (#474).
2//!
3//! `openbim_ifc_v0_1_model_export_table` writes the entities a selector
4//! selects as CSV, TSV or XLSX bytes into the caller's buffer;
5//! `openbim_ifc_v0_1_model_import_table` applies a table back by key as one
6//! checked transaction and answers with a `TableImport` record tape:
7//! applied (`BOOL`), changes (`LIST` of `TableChange`: row, column
8//! `INTEGER`; key, path `TEXT`; entity, target entity `REF`; target,
9//! before, after `TEXT`), refusals (`LIST` of `TableRefusal`: row, column
10//! `INTEGER` or `NULL`; code, message `TEXT`; span `LIST` of two
11//! `INTEGER`s or `NULL`). Any refusal means nothing was written.
12//!
13//! The import never applies a table it cannot report: it plans first, and
14//! a size query or a short buffer answers `BufferTooSmall` with the sizes
15//! and leaves the model unchanged.
16
17use openbim_ifc_binding_core::{BindingError, IfcModel, TableImport, ToRecord};
18
19use crate::buffer::{bytes, fill, text};
20use crate::domains::Out;
21use crate::model::{done, with_model, OpenbimIfcModel};
22use crate::status::{boundary, OpenbimIfcStatus};
23use crate::tape::{OpenbimIfcValueNode, Tape};
24
25/// Table format: RFC 4180 CSV, UTF-8.
26pub const OPENBIM_IFC_TABLE_CSV: u32 = 0;
27/// Table format: tab-separated values with `\t`, `\n`, `\r`, `\\` escapes.
28pub const OPENBIM_IFC_TABLE_TSV: u32 = 1;
29/// Table format: an XLSX workbook, every cell text.
30pub const OPENBIM_IFC_TABLE_XLSX: u32 = 2;
31/// Key column: `GlobalId` for an export; for an import `GlobalId` when the
32/// table has one, else `id`.
33pub const OPENBIM_IFC_TABLE_KEY_AUTO: u32 = 0;
34/// Key column: `GlobalId`.
35pub const OPENBIM_IFC_TABLE_KEY_GLOBAL_ID: u32 = 1;
36/// Key column: `id`, the entity's `#id`.
37pub const OPENBIM_IFC_TABLE_KEY_ID: u32 = 2;
38/// `openbim_ifc_v0_1_model_import_table` flag: plan and report only.
39pub const OPENBIM_IFC_TABLE_DRY_RUN: u32 = 1;
40
41fn format_name(format: u32) -> Option<&'static str> {
42    match format {
43        OPENBIM_IFC_TABLE_CSV => Some("csv"),
44        OPENBIM_IFC_TABLE_TSV => Some("tsv"),
45        OPENBIM_IFC_TABLE_XLSX => Some("xlsx"),
46        _ => None,
47    }
48}
49
50fn key_name(key: u32) -> Result<Option<&'static str>, OpenbimIfcStatus> {
51    match key {
52        OPENBIM_IFC_TABLE_KEY_AUTO => Ok(None),
53        OPENBIM_IFC_TABLE_KEY_GLOBAL_ID => Ok(Some("GlobalId")),
54        OPENBIM_IFC_TABLE_KEY_ID => Ok(Some("id")),
55        _ => Err(OpenbimIfcStatus::InvalidArgument),
56    }
57}
58
59/// The entities selector `query` (UTF-8) selects as a table in `format`
60/// (`OPENBIM_IFC_TABLE_CSV`, `_TSV`, `_XLSX`), filling `buffer` as
61/// `openbim_ifc_v0_1_model_write` does: the key column first (`key`:
62/// `OPENBIM_IFC_TABLE_KEY_AUTO` or `_GLOBAL_ID` for `GlobalId`, `_ID` for
63/// `id`), then one column per value path of `columns` (`column_count`
64/// UTF-8 paths of `column_lengths[i]` bytes, e.g. `type.Name`,
65/// `Pset_WallCommon.FireRating`), each cell the value the path reads as
66/// text, `NULL` as `null` (UTF-8, may be empty).
67///
68/// `InvalidSelector` (span through `openbim_ifc_v0_1_last_error_span`) for
69/// a query or path that does not parse; `WrongEntityType` for an entity
70/// without a `GlobalId` in a table keyed by it; `InvalidArgument` for an
71/// unknown format or key, or text that is not UTF-8; `FeatureDisabled`;
72/// and as for `openbim_ifc_v0_1_model_select`.
73///
74/// # Safety
75/// `query`, `null` valid for their lengths; `columns` and
76/// `column_lengths` null (with `column_count` 0) or valid for
77/// `column_count` reads, each column valid for its length; the buffer as
78/// for `openbim_ifc_v0_1_model_write`.
79#[no_mangle]
80pub unsafe extern "C" fn openbim_ifc_v0_1_model_export_table(
81    model: OpenbimIfcModel,
82    query: *const u8,
83    query_len: usize,
84    columns: *const *const u8,
85    column_lengths: *const usize,
86    column_count: usize,
87    format: u32,
88    key: u32,
89    null: *const u8,
90    null_len: usize,
91    buffer: *mut u8,
92    capacity: usize,
93    out_required: *mut usize,
94) -> OpenbimIfcStatus {
95    let (Some(format), Ok(key)) = (format_name(format), key_name(key)) else {
96        return OpenbimIfcStatus::InvalidArgument;
97    };
98    if column_count > 0 && (columns.is_null() || column_lengths.is_null()) {
99        return OpenbimIfcStatus::NullPointer;
100    }
101    boundary(|| {
102        // SAFETY: caller contract above.
103        let inputs = unsafe { (text(query, query_len), text(null, null_len)) };
104        let (query, null) = match inputs {
105            (Ok(query), Ok(null)) => (query, null),
106            (Err(status), _) | (_, Err(status)) => return status,
107        };
108        let mut paths = Vec::with_capacity(column_count);
109        for index in 0..column_count {
110            // SAFETY: both arrays hold `column_count` items (caller contract).
111            let (column, length) = unsafe { (*columns.add(index), *column_lengths.add(index)) };
112            // SAFETY: each column is valid for its length (caller contract).
113            match unsafe { text(column, length) } {
114                Ok(path) => paths.push(path.to_owned()),
115                Err(status) => return status,
116            }
117        }
118        with_model(model, |m| {
119            let table = m.export_table(query, &paths, format, key, null)?;
120            // SAFETY: caller contract above.
121            done(unsafe { fill(&table, buffer, capacity, out_required) })
122        })
123    })
124}
125
126/// Apply the table `data` (`data_len` bytes in `format`) to the model by
127/// its key column (`key`, as for `openbim_ifc_v0_1_model_export_table`) as
128/// one checked transaction, `null` (UTF-8) being the cell text of `NULL`.
129/// `flags`: `OPENBIM_IFC_TABLE_DRY_RUN`. The answer is a `TableImport`
130/// tape: applied (`BOOL`), changes (`LIST` of `TableChange`: row, column
131/// `INTEGER`, key, path `TEXT`, entity, target entity `REF`, target,
132/// before, after `TEXT`), refusals (`LIST` of `TableRefusal`: row, column
133/// `INTEGER` or `NULL`, code, message `TEXT`, span `LIST` of two
134/// `INTEGER`s or `NULL`). Any refusal means nothing was written; a size
135/// query or a short buffer plans the import and writes nothing.
136///
137/// `Parse` for bytes that are no table of the format; `InvalidArgument`
138/// for an unknown format, key or flag, or a `null` that is not UTF-8;
139/// `FeatureDisabled`; `UnsupportedSchema`.
140///
141/// # Safety
142/// `data` and `null` valid for their lengths; the buffers as for
143/// `openbim_ifc_v0_1_entity_attribute`.
144#[no_mangle]
145pub unsafe extern "C" fn openbim_ifc_v0_1_model_import_table(
146    model: OpenbimIfcModel,
147    data: *const u8,
148    data_len: usize,
149    format: u32,
150    key: u32,
151    null: *const u8,
152    null_len: usize,
153    flags: u32,
154    nodes: *mut OpenbimIfcValueNode,
155    node_capacity: usize,
156    out_nodes_required: *mut usize,
157    strings: *mut u8,
158    string_capacity: usize,
159    out_strings_required: *mut usize,
160) -> OpenbimIfcStatus {
161    let (Some(format), Ok(key)) = (format_name(format), key_name(key)) else {
162        return OpenbimIfcStatus::InvalidArgument;
163    };
164    if flags & !OPENBIM_IFC_TABLE_DRY_RUN != 0 {
165        return OpenbimIfcStatus::InvalidArgument;
166    }
167    let out = Out {
168        nodes,
169        node_capacity,
170        out_nodes_required,
171        strings,
172        string_capacity,
173        out_strings_required,
174    };
175    let dry_run = flags & OPENBIM_IFC_TABLE_DRY_RUN != 0;
176    boundary(|| {
177        // SAFETY: caller contract above.
178        let inputs = unsafe { (bytes(data, data_len), text(null, null_len)) };
179        let (data, null) = match inputs {
180            (Ok(data), Ok(null)) => (data, null),
181            (Err(status), _) | (_, Err(status)) => return status,
182        };
183        with_model(model, |m| {
184            let run = |m: &mut IfcModel, plan: bool| -> Result<TableImport, BindingError> {
185                m.import_table(data, format, key, null, plan)
186            };
187            let planned = run(m, true)?;
188            let tape = Tape::encode(&planned.to_record().to_tagged());
189            let fits =
190                tape.nodes.len() <= out.node_capacity && tape.strings.len() <= out.string_capacity;
191            let report = if dry_run || !fits || !planned.refusals.is_empty() {
192                planned
193            } else {
194                run(m, false)?
195            };
196            // SAFETY: caller contract above.
197            unsafe { out.write(&report.to_record().to_tagged()) }
198        })
199    })
200}