Skip to main content

openbim_ifc_binding_core/
model.rs

1//! The exported model handle.
2//!
3//! `IfcModel` owns one `ifc::Model`. Every binding crate wraps this type and
4//! converts host arguments to and from it; none re-implements an operation.
5
6use std::path::Path;
7
8use ifc::{Codec, Entity, EntityId, Model, ModelError, StepCodec, StepReader};
9
10use crate::value::Tagged;
11use crate::{BindingError, ParseOptions};
12
13/// An IFC model: entities keyed by their `#id`, in file order.
14#[derive(Debug, Default)]
15pub struct IfcModel {
16    pub(crate) inner: Model,
17    /// The `GlobalId` index `by_guid` builds on first use (#463).
18    pub(crate) guid_index: crate::relations::GuidCache,
19    /// The reverse index `INVERSE` reads build on first use (#462).
20    pub(crate) reverse_index: crate::inverse::ReverseCache,
21    /// Undo and redo entries; off until a limit is set (#465).
22    pub(crate) history: ifc::History,
23}
24
25impl IfcModel {
26    /// An empty model.
27    pub fn empty() -> Self {
28        Self::default()
29    }
30
31    /// Parse a STEP (`.ifc`) file, or an ifcZIP archive holding STEP or
32    /// ifcXML, recognized by its ZIP signature (feature `zip`, see
33    /// [`crate::ifczip`]).
34    ///
35    /// Non-fatal problems do not fail the parse; they are reported by
36    /// [`Self::diagnostics`], so a caller can tell a complete read from a
37    /// partial one.
38    ///
39    /// A strict read keeps the file as the model's source and decodes each
40    /// entity on first access, so `bytes` is copied once;
41    /// [`Self::parse_owned`] hands a buffer over instead.
42    pub fn parse(bytes: &[u8]) -> Result<Self, BindingError> {
43        if ifc::ifczip::is_zip(bytes) {
44            return crate::ifczip::load(bytes, ParseOptions::strict());
45        }
46        Self::loaded(StepCodec.read_bytes(bytes))
47    }
48
49    /// [`Self::parse`] under explicit [`ParseOptions`]: a lenient read
50    /// skips malformed records and reports each one in
51    /// [`Self::diagnostics`] instead of failing.
52    pub fn parse_with(bytes: &[u8], options: ParseOptions) -> Result<Self, BindingError> {
53        if ifc::ifczip::is_zip(bytes) {
54            return crate::ifczip::load(bytes, options);
55        }
56        Self::loaded(reader(options).read_bytes(bytes))
57    }
58
59    /// [`Self::parse`] from a buffer the model keeps, without copying it.
60    pub fn parse_owned(bytes: Vec<u8>) -> Result<Self, BindingError> {
61        Self::parse_owned_with(bytes, ParseOptions::strict())
62    }
63
64    /// [`Self::parse_owned`] under explicit [`ParseOptions`].
65    pub fn parse_owned_with(bytes: Vec<u8>, options: ParseOptions) -> Result<Self, BindingError> {
66        if ifc::ifczip::is_zip(&bytes) {
67            return crate::ifczip::load(&bytes, options);
68        }
69        Self::loaded(reader(options).read_owned(bytes))
70    }
71
72    /// Read a STEP file, or an ifcZIP archive (as [`Self::parse`]), from
73    /// disk into a buffer the model owns.
74    ///
75    /// Cheaper than reading the file in the host and passing its bytes: the
76    /// file is read once, straight into the model's source.
77    pub fn open(path: &Path) -> Result<Self, BindingError> {
78        Self::open_with(path, ParseOptions::strict())
79    }
80
81    /// [`Self::open`] under explicit [`ParseOptions`].
82    pub fn open_with(path: &Path, options: ParseOptions) -> Result<Self, BindingError> {
83        let bytes = std::fs::read(path).map_err(|error| BindingError::Io(error.to_string()))?;
84        Self::parse_owned_with(bytes, options)
85    }
86
87    /// Read a memory-mapped STEP file: no copy, and the pages belong to the
88    /// page cache rather than the process heap.
89    ///
90    /// An ifcZIP archive is read as [`Self::open`] reads it: its model is
91    /// inflated into the heap, and nothing stays mapped.
92    ///
93    /// # Safety
94    ///
95    /// The file must not be modified or truncated while the model is alive:
96    /// the model decodes entities from the mapping on access, and a changed
97    /// file makes that panic, end the process (`SIGBUS` on truncation), or
98    /// read other content. See `ifc_step::StepReader::read_path_mapped`.
99    pub unsafe fn open_mapped(path: &Path) -> Result<Self, BindingError> {
100        // SAFETY: forwarded caller contract.
101        unsafe { Self::open_mapped_with(path, ParseOptions::strict()) }
102    }
103
104    /// [`Self::open_mapped`] under explicit [`ParseOptions`].
105    ///
106    /// # Safety
107    ///
108    /// As [`Self::open_mapped`].
109    pub unsafe fn open_mapped_with(
110        path: &Path,
111        options: ParseOptions,
112    ) -> Result<Self, BindingError> {
113        if starts_like_zip(path)? {
114            return Self::open_with(path, options);
115        }
116        // SAFETY: forwarded caller contract.
117        Self::loaded(unsafe { reader(options).read_path_mapped(path) })
118    }
119
120    /// A read through any codec, its failure named for `format`.
121    pub(crate) fn loaded_as(
122        format: &str,
123        result: Result<Model, ModelError>,
124    ) -> Result<Self, BindingError> {
125        match result {
126            Ok(inner) => Ok(Self {
127                inner,
128                guid_index: Default::default(),
129                history: Default::default(),
130                reverse_index: Default::default(),
131            }),
132            Err(ModelError::Io(detail)) => Err(BindingError::Io(detail)),
133            Err(error) => Err(BindingError::Parse(format!("{format}: {error}"))),
134        }
135    }
136
137    fn loaded(result: Result<Model, ModelError>) -> Result<Self, BindingError> {
138        Self::loaded_as("STEP", result)
139    }
140
141    /// Serialize as STEP.
142    pub fn write(&self) -> Result<Vec<u8>, BindingError> {
143        StepCodec
144            .write_bytes(&self.inner)
145            .map_err(|error| BindingError::Write(format!("STEP: {error}")))
146    }
147
148    /// Number of entities.
149    pub fn len(&self) -> usize {
150        self.inner.len()
151    }
152
153    /// Whether the model has no entities.
154    pub fn is_empty(&self) -> bool {
155        self.inner.is_empty()
156    }
157
158    /// The first `FILE_SCHEMA` token, e.g. `IFC4`, if any.
159    pub fn schema(&self) -> Option<&str> {
160        self.inner.header().schema_token()
161    }
162
163    /// Every non-fatal problem found while reading, as display strings.
164    pub fn diagnostics(&self) -> Vec<String> {
165        self.inner
166            .diagnostics()
167            .iter()
168            .map(ToString::to_string)
169            .collect()
170    }
171
172    /// Every entity id, in file order.
173    pub fn ids(&self) -> Vec<u64> {
174        self.inner.ids().map(|EntityId(id)| id).collect()
175    }
176
177    /// Ids of every entity of exactly `type_name` (case-insensitive), in
178    /// file order. Subtypes are not included.
179    pub fn ids_of_type(&self, type_name: &str) -> Vec<u64> {
180        self.inner
181            .ids_of_type(&type_name.to_ascii_uppercase())
182            .iter()
183            .map(|EntityId(id)| *id)
184            .collect()
185    }
186
187    /// Ids of every entity of `type_name` or any of its subtypes, in file
188    /// order, using the schema the file's header declares.
189    ///
190    /// `IfcWall` then finds `IFCWALLSTANDARDCASE` too, which exact
191    /// [`Self::ids_of_type`] does not. An undeclared name finds nothing.
192    /// Fails when the header names no schema this crate bundles.
193    pub fn ids_of_type_including_subtypes(
194        &self,
195        type_name: &str,
196    ) -> Result<Vec<u64>, BindingError> {
197        let schema = self.declared_schema()?;
198        Ok(
199            ifc::ids_of_type_including_subtypes(&self.inner, schema, type_name)
200                .into_iter()
201                .map(|EntityId(id)| id)
202                .collect(),
203        )
204    }
205
206    /// The type name of entity `id`, upper-case.
207    pub fn type_of(&self, id: u64) -> Result<&str, BindingError> {
208        Ok(&self.entity(id)?.type_name)
209    }
210
211    /// Every attribute of entity `id`, in declaration order.
212    pub fn attributes(&self, id: u64) -> Result<Vec<Tagged>, BindingError> {
213        Ok(self
214            .entity(id)?
215            .attributes
216            .iter()
217            .map(Tagged::from_value)
218            .collect())
219    }
220
221    /// Attribute `index` of entity `id`; `null` past the last attribute,
222    /// the same as an unset `$`.
223    pub fn attribute(&self, id: u64, index: usize) -> Result<Tagged, BindingError> {
224        Ok(self
225            .entity(id)?
226            .attribute(index)
227            .map_or(Tagged::Null, Tagged::from_value))
228    }
229
230    /// Set attribute `index` of entity `id`, returning the previous value.
231    ///
232    /// Writing past the end pads the gap with `$`, as the model does.
233    pub fn set_attribute(
234        &mut self,
235        id: u64,
236        index: usize,
237        value: Tagged,
238    ) -> Result<Tagged, BindingError> {
239        let value = value.into_value()?;
240        self.tracked(|this| {
241            this.inner
242                .set_attribute(EntityId(id), index, value)
243                .map(|previous| Tagged::from_value(&previous))
244                .ok_or(BindingError::MissingEntity(id))
245        })
246    }
247
248    /// Append a new entity, returning its id.
249    pub fn add(&mut self, type_name: &str, attributes: Vec<Tagged>) -> Result<u64, BindingError> {
250        let entity = entity(type_name, attributes)?;
251        Ok(self.tracked(|this| this.inner.push(entity)).0)
252    }
253
254    /// Remove entity `id`. References to it are left dangling, as in the
255    /// model; find them with [`Self::dangling_references`].
256    ///
257    /// Deprecated in every host (#478): a file with dangling references
258    /// parses and is wrong. Use [`Self::remove_with_relationships`] for one
259    /// entity, or [`Self::remove_product`] for a product with what it
260    /// solely owns. It keeps working.
261    pub fn remove(&mut self, id: u64) -> Result<(), BindingError> {
262        self.tracked(|this| {
263            this.inner
264                .remove(EntityId(id))
265                .map(drop)
266                .ok_or(BindingError::MissingEntity(id))
267        })
268    }
269
270    /// Every `(from, to)` pair where `from` references a missing `to`.
271    pub fn dangling_references(&self) -> Vec<(u64, u64)> {
272        self.inner
273            .dangling_references()
274            .into_iter()
275            .map(|(EntityId(from), EntityId(to))| (from, to))
276            .collect()
277    }
278
279    /// The bundled schema the header declares.
280    ///
281    /// An unknown token and a release this build does not bundle are both
282    /// `UnsupportedSchema`; the message names which.
283    pub(crate) fn declared_schema(&self) -> Result<&'static ifc::Schema, BindingError> {
284        let token = self.schema().unwrap_or("");
285        let version = ifc::SchemaVersion::from_header_token(token)
286            .ok_or_else(|| BindingError::UnsupportedSchema(token.to_owned()))?;
287        ifc::schema::for_version(version)
288            .map_err(|refused| BindingError::UnsupportedSchema(format!("{token} ({refused})")))
289    }
290
291    /// The `GlobalId` and `Name` of `id` when the declared release makes
292    /// it an `IfcRoot`; both `None` otherwise. Refused like
293    /// [`Self::declared_schema`]: a domain record never reads an identity
294    /// against a release the file did not declare.
295    #[cfg_attr(
296        not(any(
297            feature = "properties",
298            feature = "spatial",
299            feature = "classification",
300            feature = "material",
301            feature = "systems",
302            feature = "cost",
303            feature = "placements"
304        )),
305        allow(dead_code)
306    )]
307    pub(crate) fn identity(&self, id: u64) -> Result<Identity, BindingError> {
308        let schema = self.declared_schema()?;
309        Ok(ifc::root_identity(&self.inner, schema, EntityId(id))
310            .map(|identity| Identity {
311                global_id: identity.global_id.map(str::to_owned),
312                name: identity.name.map(str::to_owned),
313            })
314            .unwrap_or_default())
315    }
316
317    pub(crate) fn entity(&self, id: u64) -> Result<&Entity, BindingError> {
318        self.inner
319            .get(EntityId(id))
320            .ok_or(BindingError::MissingEntity(id))
321    }
322}
323
324/// The identity attributes of an `IfcRoot` (see [`IfcModel::identity`]).
325#[derive(Debug, Clone, Default, PartialEq, Eq)]
326pub(crate) struct Identity {
327    pub(crate) global_id: Option<String>,
328    pub(crate) name: Option<String>,
329}
330
331/// A STEP reader applying `options`.
332/// Does the file at `path` start with a ZIP signature?
333fn starts_like_zip(path: &Path) -> Result<bool, BindingError> {
334    use std::io::Read;
335    let mut head = Vec::with_capacity(4);
336    std::fs::File::open(path)
337        .and_then(|file| file.take(4).read_to_end(&mut head))
338        .map_err(|error| BindingError::Io(error.to_string()))?;
339    Ok(ifc::ifczip::is_zip(&head))
340}
341
342pub(crate) fn reader(options: ParseOptions) -> StepReader {
343    StepReader::new(options.to_facade())
344}
345
346/// Build an entity, validating the type name as a STEP identifier.
347fn entity(type_name: &str, attributes: Vec<Tagged>) -> Result<Entity, BindingError> {
348    let probe = Tagged::Typed {
349        type_name: type_name.to_owned(),
350        value: Box::new(Tagged::Null),
351    };
352    // Reuse the typed-wrapper name check rather than duplicating it.
353    probe.into_value()?;
354    let values = attributes
355        .into_iter()
356        .map(Tagged::into_value)
357        .collect::<Result<_, _>>()?;
358    Ok(Entity::new(type_name.to_ascii_uppercase(), values))
359}
360
361/// Every host binding may move a model across threads (the Python GIL, a
362/// C host's worker pool). Pin that here so a non-`Send` field fails the
363/// core's build, not a binding's.
364#[allow(dead_code)]
365const fn assert_send_sync<T: Send + Sync>() {}
366const _: () = assert_send_sync::<IfcModel>();
367
368#[cfg(test)]
369mod tests;