ifc_lite_processing/data_model/spatial_walk.rs
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! The one spatial walk the export formats share (D48, EXPORT-DATA-16, C6-10).
6//!
7//! Export walks the raw aggregation and containment edges
8//! (`ifc_lite_export::relationships().spatial_children`), not the server's
9//! canonical hierarchy. The rule, for every format: pre-order depth first from
10//! the project, children in SOURCE order, and the first parent to reach a node
11//! owns it (a later edge to it is ignored). CSV did this, USD's recursive
12//! emitter does this, and IFCX walked a stack whose siblings came out
13//! reversed, so the same file listed its nodes in a different order per format.
14
15use std::collections::{HashMap, HashSet};
16use std::hash::BuildHasher;
17
18/// One node reached by [`walk`].
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct SpatialVisit {
21 pub id: u32,
22 /// The parent that reached it first; `None` for the root.
23 pub parent: Option<u32>,
24 /// Edges from the root.
25 pub level: usize,
26}
27
28/// Every node reachable from `root`, in pre-order, source order, first parent
29/// wins. Iterative, so the depth of a hostile file cannot overflow the stack;
30/// each node is visited once, so a cycle ends.
31pub fn walk<S: BuildHasher>(children: &HashMap<u32, Vec<u32>, S>, root: u32) -> Vec<SpatialVisit> {
32 let mut out = Vec::new();
33 let mut visited = HashSet::new();
34 let mut stack = vec![SpatialVisit { id: root, parent: None, level: 0 }];
35 while let Some(visit) = stack.pop() {
36 if !visited.insert(visit.id) {
37 continue;
38 }
39 out.push(visit);
40 if let Some(kids) = children.get(&visit.id) {
41 // Pushed reversed so the first child is popped, and so owned, first.
42 for &kid in kids.iter().rev() {
43 if !visited.contains(&kid) {
44 stack.push(SpatialVisit { id: kid, parent: Some(visit.id), level: visit.level + 1 });
45 }
46 }
47 }
48 }
49 out
50}
51
52#[cfg(test)]
53#[path = "spatial_walk_tests.rs"]
54mod tests;