Skip to main content

openbim_ifc_capi/
removal.rs

1//! Removing a product with what it solely owns, and purging what nothing
2//! uses (#478); removing a shape representation with what only it uses
3//! (#481).
4//!
5//! Each answers with a `RemovalReport` record tape: removed (`LIST` of
6//! `RemovedEntity`: id `REF`, type name `TEXT`), kept (`LIST` of
7//! `KeptEntity`: id, type name, reason `TEXT` -- `shared`,
8//! `related-object`, `definition` or `protected` -- and users, a `LIST` of
9//! `REF`), detached (`LIST` of `REF`), rebased (`LIST` of `REF`), applied
10//! (`BOOL`, false for a dry run).
11//!
12//! The buffer protocol never applies a removal it cannot report: the call
13//! plans it first, and a size query or a short buffer answers
14//! `BufferTooSmall` with the sizes and leaves the model unchanged. The
15//! applied report has the planned one's size.
16
17use openbim_ifc_binding_core::{
18    BindingError, IfcModel, PurgeOptions, RemovalReport, RemoveProductOptions, ToRecord,
19};
20
21use crate::buffer::text;
22use crate::domains::Out;
23use crate::model::{with_model, OpenbimIfcModel};
24use crate::status::{boundary, OpenbimIfcStatus};
25use crate::tape::{OpenbimIfcValueNode, Tape};
26
27/// `openbim_ifc_v0_1_model_remove_product` flag: re-base placements relative
28/// to a removed placement instead of refusing.
29pub const OPENBIM_IFC_REMOVE_REBASE_PLACEMENTS: u32 = 1;
30/// `openbim_ifc_v0_1_model_remove_product` flag: untype a type object's
31/// occurrences instead of refusing.
32pub const OPENBIM_IFC_REMOVE_UNTYPE_OCCURRENCES: u32 = 2;
33/// `openbim_ifc_v0_1_model_remove_product` flag: report only.
34pub const OPENBIM_IFC_REMOVE_DRY_RUN: u32 = 4;
35/// `openbim_ifc_v0_1_model_purge` flag: also purge unreferenced `IfcRoot`s of
36/// the classes.
37pub const OPENBIM_IFC_PURGE_INCLUDE_ROOTS: u32 = 1;
38/// `openbim_ifc_v0_1_model_purge` flag: also purge an unreferenced owner
39/// history with its actors.
40pub const OPENBIM_IFC_PURGE_INCLUDE_OWNER_HISTORY: u32 = 2;
41/// `openbim_ifc_v0_1_model_purge` flag: report only.
42pub const OPENBIM_IFC_PURGE_DRY_RUN: u32 = 4;
43
44const ALL_FLAGS: u32 = 7;
45
46/// Plan with `run(model, true)`; then write the report, applying with
47/// `run(model, false)` first unless `dry_run`, and only when it fits.
48///
49/// # Safety
50/// The buffers as for `Out`.
51unsafe fn removal_export(
52    model: OpenbimIfcModel,
53    out: &Out,
54    dry_run: bool,
55    run: impl Fn(&mut IfcModel, bool) -> Result<RemovalReport, BindingError>,
56) -> OpenbimIfcStatus {
57    boundary(|| {
58        with_model(model, |m| {
59            if let Err(status) = out.check() {
60                return Ok(status);
61            }
62            let planned = run(m, true)?;
63            let tape = Tape::encode(&planned.to_record().to_tagged());
64            let fits =
65                tape.nodes.len() <= out.node_capacity && tape.strings.len() <= out.string_capacity;
66            let report = if dry_run || !fits {
67                planned
68            } else {
69                run(m, false)?
70            };
71            // SAFETY: caller contract.
72            unsafe { out.write(&report.to_record().to_tagged()) }
73        })
74    })
75}
76
77/// Remove product (or type object) `product` with everything it solely
78/// owns -- its placement, representation, own property and quantity sets,
79/// material usage, openings and ports, and relationships left without an
80/// end -- keeping what is shared, as one checked transaction. `flags`:
81/// `OPENBIM_IFC_REMOVE_REBASE_PLACEMENTS`,
82/// `OPENBIM_IFC_REMOVE_UNTYPE_OCCURRENCES`, `OPENBIM_IFC_REMOVE_DRY_RUN`.
83/// The answer is a `RemovalReport` tape: removed (`LIST` of
84/// `RemovedEntity`: id `REF`, type name `TEXT`), kept (`LIST` of
85/// `KeptEntity`: id, type name, reason `TEXT` -- `shared`,
86/// `related-object`, `definition`, `protected` -- users `LIST` of `REF`),
87/// detached and rebased (`LIST`s of `REF`), applied (`BOOL`, false for a
88/// dry run). A size query or a short buffer plans the removal and answers
89/// `BufferTooSmall` without applying it.
90///
91/// `MissingEntity`; `WrongEntityType` for an entity that is neither an
92/// `IfcProduct` nor an `IfcTypeObject`; `StillReferenced` for a placement
93/// other placements are relative to, a type that still types objects, or
94/// an entity that stays and needs something removed; `Unsupported` for a
95/// placement that cannot be re-based; `InvalidArgument` for an unknown
96/// flag; `FeatureDisabled`.
97///
98/// # Safety
99/// As for `openbim_ifc_v0_1_entity_attribute`.
100#[no_mangle]
101pub unsafe extern "C" fn openbim_ifc_v0_1_model_remove_product(
102    model: OpenbimIfcModel,
103    product: u64,
104    flags: u32,
105    nodes: *mut OpenbimIfcValueNode,
106    node_capacity: usize,
107    out_nodes_required: *mut usize,
108    strings: *mut u8,
109    string_capacity: usize,
110    out_strings_required: *mut usize,
111) -> OpenbimIfcStatus {
112    if flags & !ALL_FLAGS != 0 {
113        return OpenbimIfcStatus::InvalidArgument;
114    }
115    let out = Out {
116        nodes,
117        node_capacity,
118        out_nodes_required,
119        strings,
120        string_capacity,
121        out_strings_required,
122    };
123    let dry_run = flags & OPENBIM_IFC_REMOVE_DRY_RUN != 0;
124    // SAFETY: caller contract above.
125    unsafe {
126        removal_export(model, &out, dry_run, |m, plan| {
127            let mut options = RemoveProductOptions::new();
128            options.rebase_placements = flags & OPENBIM_IFC_REMOVE_REBASE_PLACEMENTS != 0;
129            options.untype_occurrences = flags & OPENBIM_IFC_REMOVE_UNTYPE_OCCURRENCES != 0;
130            options.dry_run = plan;
131            m.remove_product(product, options)
132        })
133    }
134}
135
136/// Remove shape representation `representation` with what only it uses, as
137/// one checked transaction: taken off its product definition shape (which
138/// goes when left empty), representation map or shape aspects, then removed
139/// with its items down to what nothing else uses; shared items, profiles,
140/// points and styles stay. `flags`: `OPENBIM_IFC_REMOVE_DRY_RUN` alone. The
141/// answer is the `RemovalReport` tape of
142/// `openbim_ifc_v0_1_model_remove_product`; a size query or a short buffer
143/// plans the removal and answers `BufferTooSmall` without applying it.
144///
145/// `MissingEntity`; `WrongEntityType` for an entity that is not an
146/// `IfcShapeModel`; `StillReferenced` for a representation map an
147/// `IfcMappedItem` still maps; `InvalidArgument` for another flag;
148/// `FeatureDisabled`.
149///
150/// # Safety
151/// As for `openbim_ifc_v0_1_entity_attribute`.
152#[no_mangle]
153pub unsafe extern "C" fn openbim_ifc_v0_1_model_remove_representation(
154    model: OpenbimIfcModel,
155    representation: u64,
156    flags: u32,
157    nodes: *mut OpenbimIfcValueNode,
158    node_capacity: usize,
159    out_nodes_required: *mut usize,
160    strings: *mut u8,
161    string_capacity: usize,
162    out_strings_required: *mut usize,
163) -> OpenbimIfcStatus {
164    if flags & !OPENBIM_IFC_REMOVE_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_REMOVE_DRY_RUN != 0;
176    // SAFETY: caller contract above.
177    unsafe {
178        removal_export(model, &out, dry_run, |m, plan| {
179            m.remove_representation(representation, plan)
180        })
181    }
182}
183
184/// Purge unreferenced entities as one checked transaction. With
185/// `class_count` 0, every resource entity no `IfcRoot` reaches (nor
186/// annotates something reached); otherwise entities of the `class_count`
187/// classes (UTF-8 names of `class_lengths[i]` bytes, any case, subtypes
188/// included) that nothing references. `flags`:
189/// `OPENBIM_IFC_PURGE_INCLUDE_ROOTS`,
190/// `OPENBIM_IFC_PURGE_INCLUDE_OWNER_HISTORY`, `OPENBIM_IFC_PURGE_DRY_RUN`.
191/// The answer is a `RemovalReport` tape: removed (`LIST` of
192/// `RemovedEntity`: id `REF`, type name `TEXT`), kept (`LIST` of
193/// `KeptEntity`: id, type name, reason `TEXT` -- `shared`,
194/// `related-object`, `definition`, `protected` -- users `LIST` of `REF`),
195/// detached and rebased (`LIST`s of `REF`), applied (`BOOL`, false for a
196/// dry run). A size query or a short buffer plans the removal and answers
197/// `BufferTooSmall` without applying it.
198///
199/// `UnsupportedSchema` for a class the release does not declare;
200/// `InvalidArgument` for a class that is not UTF-8 or an unknown flag;
201/// `FeatureDisabled`.
202///
203/// # Safety
204/// `classes` and `class_lengths` null (with `class_count` 0) or valid for
205/// `class_count` reads, each class valid for its length; the buffers as
206/// for `openbim_ifc_v0_1_entity_attribute`.
207#[no_mangle]
208pub unsafe extern "C" fn openbim_ifc_v0_1_model_purge(
209    model: OpenbimIfcModel,
210    classes: *const *const u8,
211    class_lengths: *const usize,
212    class_count: usize,
213    flags: u32,
214    nodes: *mut OpenbimIfcValueNode,
215    node_capacity: usize,
216    out_nodes_required: *mut usize,
217    strings: *mut u8,
218    string_capacity: usize,
219    out_strings_required: *mut usize,
220) -> OpenbimIfcStatus {
221    if flags & !ALL_FLAGS != 0 {
222        return OpenbimIfcStatus::InvalidArgument;
223    }
224    if class_count > 0 && (classes.is_null() || class_lengths.is_null()) {
225        return OpenbimIfcStatus::NullPointer;
226    }
227    let mut names = Vec::with_capacity(class_count);
228    for index in 0..class_count {
229        // SAFETY: both arrays hold `class_count` items (caller contract).
230        let (class, length) = unsafe { (*classes.add(index), *class_lengths.add(index)) };
231        // SAFETY: each class is valid for its length (caller contract).
232        match unsafe { text(class, length) } {
233            Ok(name) => names.push(name.to_owned()),
234            Err(status) => return status,
235        }
236    }
237    let out = Out {
238        nodes,
239        node_capacity,
240        out_nodes_required,
241        strings,
242        string_capacity,
243        out_strings_required,
244    };
245    let dry_run = flags & OPENBIM_IFC_PURGE_DRY_RUN != 0;
246    // SAFETY: caller contract above.
247    unsafe {
248        removal_export(model, &out, dry_run, |m, plan| {
249            let mut options = PurgeOptions::new();
250            options.classes.clone_from(&names);
251            options.include_roots = flags & OPENBIM_IFC_PURGE_INCLUDE_ROOTS != 0;
252            options.include_owner_history = flags & OPENBIM_IFC_PURGE_INCLUDE_OWNER_HISTORY != 0;
253            options.dry_run = plan;
254            m.purge(options)
255        })
256    }
257}