openbim_ifc_binding_core/
relations.rs1use std::sync::Mutex;
20
21use ifc::{EntityId, GlobalIdIndex, Guid, GuidError, ObjectRelationError};
22
23use crate::value::Tagged;
24use crate::{BindingError, IfcModel};
25
26#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct DuplicateGlobalId {
29 pub global_id: String,
31 pub ids: Vec<u64>,
33}
34
35#[derive(Debug)]
37pub(crate) struct CachedIndex {
38 revision: u64,
39 schema: Option<String>,
40 index: GlobalIdIndex,
41}
42
43#[derive(Debug, Default)]
45pub(crate) struct GuidCache(Mutex<Option<CachedIndex>>);
46
47impl IfcModel {
48 pub fn by_guid(&self, global_id: &str) -> Result<Option<u64>, BindingError> {
54 let guid = parse_guid(global_id)?;
55 self.with_index(|index| {
56 index
57 .get(&guid)
58 .map(|found| found.map(|EntityId(id)| id))
59 .map_err(|duplicate| BindingError::InvalidModel(duplicate.to_string()))
60 })
61 }
62
63 pub fn duplicate_global_ids(&self) -> Result<Vec<DuplicateGlobalId>, BindingError> {
66 self.with_index(|index| {
67 Ok(index
68 .duplicates()
69 .map(|(guid, ids)| DuplicateGlobalId {
70 global_id: guid.to_string(),
71 ids: ids.iter().map(|EntityId(id)| *id).collect(),
72 })
73 .collect())
74 })
75 }
76
77 pub fn type_object(&self, occurrence: u64) -> Result<Option<u64>, BindingError> {
79 let schema = self.declared_schema()?;
80 ifc::type_of(&self.inner, schema, EntityId(occurrence))
81 .map(|found| found.map(|EntityId(id)| id))
82 .map_err(relation_error)
83 }
84
85 pub fn occurrences_of(&self, type_object: u64) -> Result<Vec<u64>, BindingError> {
87 let schema = self.declared_schema()?;
88 ifc::occurrences_of(&self.inner, schema, EntityId(type_object))
89 .map(raw)
90 .map_err(relation_error)
91 }
92
93 pub fn openings_of(&self, element: u64) -> Result<Vec<u64>, BindingError> {
96 let schema = self.declared_schema()?;
97 ifc::openings_of(&self.inner, schema, EntityId(element))
98 .map(raw)
99 .map_err(relation_error)
100 }
101
102 pub fn fillings_of(&self, opening: u64) -> Result<Vec<u64>, BindingError> {
105 let schema = self.declared_schema()?;
106 ifc::fillings_of(&self.inner, schema, EntityId(opening))
107 .map(raw)
108 .map_err(relation_error)
109 }
110
111 pub fn voided_element_of(&self, opening: u64) -> Result<Option<u64>, BindingError> {
113 let schema = self.declared_schema()?;
114 ifc::voided_element_of(&self.inner, schema, EntityId(opening))
115 .map(|found| found.map(|EntityId(id)| id))
116 .map_err(relation_error)
117 }
118
119 fn with_index<T>(
122 &self,
123 answer: impl FnOnce(&GlobalIdIndex) -> Result<T, BindingError>,
124 ) -> Result<T, BindingError> {
125 let schema = self.declared_schema()?;
126 let revision = self.inner.revision();
127 let token = self.schema().map(str::to_owned);
128 let mut slot = self
131 .guid_index
132 .0
133 .lock()
134 .unwrap_or_else(std::sync::PoisonError::into_inner);
135 let current = slot
136 .as_ref()
137 .is_some_and(|cached| cached.revision == revision && cached.schema == token);
138 if !current {
139 *slot = Some(CachedIndex {
140 revision,
141 schema: token,
142 index: GlobalIdIndex::build(&self.inner, schema),
143 });
144 }
145 answer(&slot.as_ref().expect("built above").index)
146 }
147}
148
149pub fn new_guid() -> Result<String, BindingError> {
156 ifc::new_guid()
157 .map(|guid| guid.to_string())
158 .map_err(|error: GuidError| BindingError::Unsupported(error.to_string()))
159}
160
161pub(crate) fn fresh_seed() -> Result<u128, BindingError> {
166 ifc::fresh_seed().map_err(|error: GuidError| BindingError::Unsupported(error.to_string()))
167}
168
169pub fn name_based_guid<S: AsRef<str>>(parts: &[S]) -> String {
172 let parts: Vec<&str> = parts.iter().map(AsRef::as_ref).collect();
173 ifc::name_based_guid(&parts).to_string()
174}
175
176pub fn duplicates_to_tagged(duplicates: &[DuplicateGlobalId]) -> Tagged {
179 Tagged::List(
180 duplicates
181 .iter()
182 .map(|duplicate| {
183 Tagged::List(vec![
184 Tagged::Text(duplicate.global_id.clone()),
185 Tagged::List(duplicate.ids.iter().copied().map(Tagged::Ref).collect()),
186 ])
187 })
188 .collect(),
189 )
190}
191
192fn parse_guid(text: &str) -> Result<Guid, BindingError> {
193 Guid::parse(text).ok_or_else(|| {
194 BindingError::InvalidValue(format!(
195 "{text:?} is not a GlobalId: 22 characters of 0-9, A-Z, a-z, _ and $, the first 0-3"
196 ))
197 })
198}
199
200fn raw(ids: Vec<EntityId>) -> Vec<u64> {
201 ids.into_iter().map(|EntityId(id)| id).collect()
202}
203
204fn relation_error(error: ObjectRelationError) -> BindingError {
205 match error {
206 ObjectRelationError::MissingEntity(EntityId(id)) => BindingError::MissingEntity(id),
207 ObjectRelationError::WrongEntityType { .. } => {
208 BindingError::WrongEntityType(error.to_string())
209 }
210 ObjectRelationError::MissingReference { .. } => {
211 BindingError::MissingReference(error.to_string())
212 }
213 _ => BindingError::InvalidModel(error.to_string()),
215 }
216}