ifc_lite_diff/
columns.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//! Columnar transport for precomputed fingerprints. JsString dictionaries and
5//! numeric buffers cross once; opaque JS references remain in the caller.
6use crate::JsString;
7use std::collections::HashMap;
8use crate::model::{EntityAabb, EntityFingerprint};
9pub const ABSENT_STRING: u32 = u32::MAX;
10/// Five string indices per row: key, IFC class, data hash, geometry hash,
11/// container. Only geometry/container may use ABSENT_STRING.
12#[derive(Debug, Default)]
13pub struct FingerprintColumns {
14    pub strings: Vec<JsString>,
15    pub fields: Vec<u32>,
16    /// Bit 0: aabb present, bit 1: volume present, bit 2: components present.
17    pub flags: Vec<u8>,
18    /// Six values per row, min xyz then max xyz, even for absent boxes.
19    pub boxes: Vec<f64>,
20    pub volumes: Vec<f64>,
21    /// Row count + 1 offsets into component_pairs, measured in pairs.
22    pub component_offsets: Vec<u32>,
23    pub component_pairs: Vec<u32>,
24}
25pub fn decode_columns(columns: FingerprintColumns) -> Result<Vec<EntityFingerprint<usize>>, String> {
26    let count = columns.flags.len();
27    if count.checked_mul(5) != Some(columns.fields.len()) || count.checked_mul(6) != Some(columns.boxes.len()) || columns.volumes.len() != count {
28        return Err("fingerprint column lengths disagree".into());
29    }
30    if columns.component_offsets.len() != count + 1 || !columns.component_pairs.len().is_multiple_of(2) {
31        return Err("component column lengths disagree".into());
32    }
33    let offsets = &columns.component_offsets;
34    if offsets.first() != Some(&0) || offsets.last().copied().map(|n|n as usize) != Some(columns.component_pairs.len()/2)
35        || offsets.windows(2).any(|w|w[0]>w[1]) {
36        return Err("component offsets are not a complete monotonic partition".into());
37    }
38    let string = |index: u32| columns.strings.get(index as usize).cloned().ok_or_else(||"fingerprint string index out of range".to_owned());
39    let optional = |index: u32| if index == ABSENT_STRING { Ok(None) } else { string(index).map(Some) };
40    let mut result = Vec::with_capacity(count);
41    for row in 0..count {
42        let fields = &columns.fields[row*5..row*5+5];
43        let flags = columns.flags[row];
44        if flags & !7 != 0 { return Err("unknown fingerprint presence flags".into()); }
45        let component_start = offsets[row] as usize * 2;
46        let component_end = offsets[row+1] as usize * 2;
47        if flags & 4 == 0 && component_start != component_end { return Err("absent components carry values".into()); }
48        let components = if flags & 4 != 0 {
49            // The validated partition supplies the size. Bound the initial
50            // reservation because raw column callers may repeat the same key.
51            let mut map = HashMap::with_capacity_and_hasher(((component_end - component_start) / 2).min(16), crate::JsHash);
52            for pair in columns.component_pairs[component_start..component_end].chunks_exact(2) {
53                map.insert(string(pair[0])?,string(pair[1])?);
54            }
55            Some(map)
56        } else { None };
57        result.push(EntityFingerprint { key:string(fields[0])?,ifc_type:string(fields[1])?,data_hash:string(fields[2])?,
58            geometry_hash:optional(fields[3])?,container:optional(fields[4])?,
59            aabb:if flags & 1 != 0 {Some(EntityAabb {min:std::array::from_fn(|i|columns.boxes[row*6+i]),max:std::array::from_fn(|i|columns.boxes[row*6+3+i])})} else {None},
60            volume:if flags & 2 != 0 {Some(columns.volumes[row])} else {None},components,reference:row });
61    }
62    Ok(result)
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68    fn columns() -> FingerprintColumns {
69        FingerprintColumns {strings:vec!["key".into(),"IfcWall".into(),"data".into()],fields:vec![0,1,2,ABSENT_STRING,ABSENT_STRING],
70            flags:vec![0],boxes:vec![0.0;6],volumes:vec![0.0],component_offsets:vec![0,0],component_pairs:vec![]}
71    }
72    #[test]
73    fn issue_8042_columns_preserve_absence_empty_and_nonfinite() {
74        let absent = decode_columns(columns()).unwrap();
75        assert!(absent[0].components.is_none()); assert!(absent[0].aabb.is_none()); assert!(absent[0].volume.is_none());
76        let mut input=columns(); input.flags[0]=7; input.boxes[0]=f64::NAN; input.volumes[0]=f64::INFINITY;
77        let present=decode_columns(input).unwrap();
78        assert_eq!(present[0].components,Some(crate::model::ComponentMap::default()));
79        assert!(present[0].aabb.as_ref().unwrap().min[0].is_nan());
80        assert_eq!(present[0].volume,Some(f64::INFINITY));
81        assert_eq!(present[0].reference,0);
82    }
83    #[test]
84    fn issue_8042_malformed_columns_refuse_without_partial_results() {
85        let mut input=columns(); input.fields[0]=10; assert!(decode_columns(input).is_err());
86        let mut input=columns(); input.component_offsets=vec![0,1]; assert!(decode_columns(input).is_err());
87        let mut input=columns(); input.flags[0]=8; assert!(decode_columns(input).is_err());
88        let mut input=columns(); input.boxes.pop(); assert!(decode_columns(input).is_err());
89        assert!(decode_columns(FingerprintColumns {component_offsets:vec![0],..Default::default()}).unwrap().is_empty());
90    }
91}