openbim_ifc_binding_core/
model.rs1use std::path::Path;
7
8use ifc::{Codec, Entity, EntityId, Model, ModelError, StepCodec, StepReader};
9
10use crate::value::Tagged;
11use crate::{BindingError, ParseOptions};
12
13#[derive(Debug, Default)]
15pub struct IfcModel {
16 pub(crate) inner: Model,
17 pub(crate) guid_index: crate::relations::GuidCache,
19 pub(crate) reverse_index: crate::inverse::ReverseCache,
21 pub(crate) history: ifc::History,
23}
24
25impl IfcModel {
26 pub fn empty() -> Self {
28 Self::default()
29 }
30
31 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 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 pub fn parse_owned(bytes: Vec<u8>) -> Result<Self, BindingError> {
61 Self::parse_owned_with(bytes, ParseOptions::strict())
62 }
63
64 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 pub fn open(path: &Path) -> Result<Self, BindingError> {
78 Self::open_with(path, ParseOptions::strict())
79 }
80
81 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 pub unsafe fn open_mapped(path: &Path) -> Result<Self, BindingError> {
100 unsafe { Self::open_mapped_with(path, ParseOptions::strict()) }
102 }
103
104 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 Self::loaded(unsafe { reader(options).read_path_mapped(path) })
118 }
119
120 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 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 pub fn len(&self) -> usize {
150 self.inner.len()
151 }
152
153 pub fn is_empty(&self) -> bool {
155 self.inner.is_empty()
156 }
157
158 pub fn schema(&self) -> Option<&str> {
160 self.inner.header().schema_token()
161 }
162
163 pub fn diagnostics(&self) -> Vec<String> {
165 self.inner
166 .diagnostics()
167 .iter()
168 .map(ToString::to_string)
169 .collect()
170 }
171
172 pub fn ids(&self) -> Vec<u64> {
174 self.inner.ids().map(|EntityId(id)| id).collect()
175 }
176
177 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 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 pub fn type_of(&self, id: u64) -> Result<&str, BindingError> {
208 Ok(&self.entity(id)?.type_name)
209 }
210
211 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 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 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 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 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 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 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 #[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#[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
331fn 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
346fn 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 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#[allow(dead_code)]
365const fn assert_send_sync<T: Send + Sync>() {}
366const _: () = assert_send_sync::<IfcModel>();
367
368#[cfg(test)]
369mod tests;