1use ifc_lite_diff::fingerprint::canonical_value_string;
38use ifc_lite_diff::input::{DataFingerprintInput, PropertyEntryInput, PropertyValue};
39use ifc_lite_diff::sparse_collection::SparseCollection;
40use ifc_lite_diff::JsString;
41
42use crate::node::{Component, Field, FieldValue, Node, SetKind};
43use crate::tree::TreeEntry;
44
45#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum AdapterError {
48 NotWellFormed {
58 field: &'static str,
60 },
61 Hole {
75 field: &'static str,
77 count: usize,
79 },
80}
81
82impl std::fmt::Display for AdapterError {
83 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84 match self {
85 AdapterError::NotWellFormed { field } => write!(
86 f,
87 "{field} holds an unpaired surrogate, so it has no well-formed \
88 Unicode form; refusing rather than collapsing it"
89 ),
90 AdapterError::Hole { field, count } => write!(
91 f,
92 "{field} carries {count} array hole(s), which are content to the \
93 diff engine; the node encoding has no form for one, and dropping \
94 them would collide two different projections on one address"
95 ),
96 }
97 }
98}
99
100impl std::error::Error for AdapterError {}
101
102#[derive(Debug, Clone, PartialEq)]
104pub struct EntityNodes {
105 pub nodes: Vec<Node>,
108 pub entry: TreeEntry,
110}
111
112fn text(value: &JsString, field: &'static str) -> Result<String, AdapterError> {
113 value
114 .as_str()
115 .map(str::to_owned)
116 .ok_or(AdapterError::NotWellFormed { field })
117}
118
119fn optional_text(
120 value: &Option<JsString>,
121 field: &'static str,
122) -> Result<Option<String>, AdapterError> {
123 match value {
124 None => Ok(None),
125 Some(inner) => Ok(Some(text(inner, field)?)),
126 }
127}
128
129fn value_of(value: &PropertyValue, field: &'static str) -> Result<FieldValue, AdapterError> {
137 if matches!(value, PropertyValue::Array(_) | PropertyValue::Object(_)) { validate_value_strings(value, field)?; }
138 Ok(match value {
139 PropertyValue::Null => FieldValue::Absent,
140 PropertyValue::Bool(flag) => FieldValue::Bool(*flag),
141 PropertyValue::Number(number) if number.is_finite() => FieldValue::Number(*number),
142 _ => FieldValue::Text(text(&canonical_value_string(value).expect("text-normalized value"), field)?),
143 })
144}
145
146fn validate_value_strings(value: &PropertyValue, field: &'static str) -> Result<(), AdapterError> {
148 let mut pending = vec![value];
149 while let Some(next) = pending.pop() {
150 match next {
151 PropertyValue::String(value) if value.as_str().is_none() => return Err(AdapterError::NotWellFormed { field }),
152 PropertyValue::Array(values) => pending.extend(values),
153 PropertyValue::Object(entries) => {
154 for (key, value) in entries {
155 if key.as_str().is_none() { return Err(AdapterError::NotWellFormed { field }); }
156 pending.push(value);
157 }
158 }
159 _ => {}
160 }
161 }
162 Ok(())
163}
164
165fn refuse_holes(count: usize, field: &'static str) -> Result<(), AdapterError> {
167 if count > 0 {
168 return Err(AdapterError::Hole { field, count });
169 }
170 Ok(())
171}
172
173fn members(
174 entries: &SparseCollection<PropertyEntryInput>,
175 name_field: &'static str,
176 value_field: &'static str,
177) -> Result<Vec<Field>, AdapterError> {
178 refuse_holes(entries.holes(), "property members")?;
179 entries
180 .present()
181 .map(|entry| {
182 Ok(Field {
183 name: text(&entry.name, name_field)?,
184 value: value_of(&entry.value, value_field)?,
185 })
186 })
187 .collect()
188}
189
190fn attributes_node(input: &DataFingerprintInput) -> Result<Node, AdapterError> {
197 let field = |name: &str, value: Option<String>| Field {
198 name: name.to_owned(),
199 value: value.map_or(FieldValue::Absent, FieldValue::Text),
200 };
201 Ok(Node::Set {
202 kind: SetKind::Attributes,
203 name: "core".to_owned(),
204 members: vec![
205 field("Type", Some(text(&input.ifc_type, "ifcType")?)),
206 field("Name", optional_text(&input.name, "name")?),
207 field(
208 "Description",
209 optional_text(&input.description, "description")?,
210 ),
211 field(
212 "ObjectType",
213 optional_text(&input.object_type, "objectType")?,
214 ),
215 field(
216 "PredefinedType",
217 optional_text(&input.predefined_type, "predefinedType")?,
218 ),
219 field("Tag", optional_text(&input.tag, "tag")?),
220 ],
221 })
222}
223
224fn name_bag(kind: &str, names: &[JsString], field: &'static str) -> Result<Option<Node>, AdapterError> {
225 let names = names.iter().filter(|name| !name.is_blank())
226 .map(|name| text(name, field)).collect::<Result<Vec<_>, _>>()?;
227 Ok((!names.is_empty()).then(|| Node::NameBag { kind: kind.to_owned(), names }))
228}
229
230pub fn entity_nodes(key: &str, input: &DataFingerprintInput) -> Result<EntityNodes, AdapterError> {
235 let mut nodes = Vec::new();
236 let mut components = Vec::new();
237
238 let attributes = attributes_node(input)?;
239 components.push(Component {
240 key: "attr:core".to_owned(),
241 node: attributes.address(),
242 });
243 nodes.push(attributes);
244
245 refuse_holes(input.property_sets.holes(), "property sets")?;
246 for set in input.property_sets.present() {
247 let name = text(&set.name, "pset name")?;
248 let node = Node::Set {
249 kind: SetKind::Property,
250 name: name.clone(),
251 members: members(&set.properties, "property name", "property value")?,
252 };
253 components.push(Component {
254 key: format!("pset:{name}"),
255 node: node.address(),
256 });
257 nodes.push(node);
258 }
259
260 refuse_holes(input.quantity_sets.holes(), "quantity sets")?;
261 for set in input.quantity_sets.present() {
262 let name = text(&set.name, "qset name")?;
263 let node = Node::Set {
264 kind: SetKind::Quantity,
265 name: name.clone(),
266 members: members(&set.quantities, "quantity name", "quantity value")?,
267 };
268 components.push(Component {
269 key: format!("qset:{name}"),
270 node: node.address(),
271 });
272 nodes.push(node);
273 }
274
275 refuse_holes(input.type_assignments.holes(), "type assignments")?;
276 if input.type_assignments.present().next().is_some() {
277 let mut assignments = Vec::new();
282 for assignment in input.type_assignments.present() {
283 assignments.push(Field {
284 name: optional_text(&assignment.type_name, "type class")?.unwrap_or_default(),
285 value: FieldValue::Text(
286 optional_text(&assignment.name, "type name")?.unwrap_or_default(),
287 ),
288 });
289 }
290 let node = Node::Set {
291 kind: SetKind::TypeAssignment,
292 name: String::new(),
293 members: assignments,
294 };
295 components.push(Component {
296 key: "type-assignment".to_owned(),
297 node: node.address(),
298 });
299 nodes.push(node);
300 }
301
302 if let Some(node) = name_bag("material", &input.materials, "material name")? {
308 components.push(Component {
309 key: "material".to_owned(),
310 node: node.address(),
311 });
312 nodes.push(node);
313 }
314 if let Some(node) = name_bag("classification", &input.classifications, "classification")? {
315 components.push(Component {
316 key: "classification".to_owned(),
317 node: node.address(),
318 });
319 nodes.push(node);
320 }
321
322 let ifc_type = text(&input.ifc_type, "ifcType")?;
323 let element = Node::Element {
324 ifc_type: ifc_type.clone(),
325 components,
326 };
327 let entry = TreeEntry {
328 key: key.to_owned(),
329 node: element.address(),
330 ifc_type,
331 };
332 nodes.push(element);
333
334 Ok(EntityNodes { nodes, entry })
335}
336
337#[cfg(test)]
338#[path = "adapter_tests.rs"]
339mod tests;