ifc_lite_diff/
key_diff.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 GlobalId classification pass, before optional content matching (#8042).
6use crate::JsString;
7use std::collections::{HashMap, HashSet};
8use crate::model::*;
9use crate::utf16::cmp_code_units;
10
11fn normalize_type(value: &JsString) -> JsString {
12    value.normalized_class()
13}
14
15type KeyIndex<'a> = HashMap<&'a JsString, usize, crate::JsHash>;
16
17fn index<R>(entities: &[EntityFingerprint<R>]) -> (Vec<(JsString, usize)>, KeyIndex<'_>) {
18    let mut lookup = HashMap::with_capacity_and_hasher(entities.len(), crate::JsHash);
19    let mut order = Vec::with_capacity(entities.len());
20    for (i, entity) in entities.iter().enumerate() {
21        if let std::collections::hash_map::Entry::Vacant(slot) = lookup.entry(&entity.key) {
22            slot.insert(i);
23            order.push((entity.key.clone(), i));
24        }
25    }
26    (order, lookup)
27}
28
29fn resolve_aliases(
30    base: &[(JsString, usize)], head: &mut [(JsString, usize)],
31    aliases: &HashMap<JsString, JsString>,
32) -> Vec<(JsString, JsString)> {
33    let base_keys: HashSet<_> = base.iter().map(|(key, _)| key).collect();
34    let head_keys: HashSet<_> = head.iter().map(|(key, _)| key).collect();
35    let mut proposals = Vec::new();
36    let mut claims = HashMap::<&JsString, usize>::new();
37    for (key, _) in head.iter() {
38        let Some(target) = aliases.get(key) else { continue };
39        if target.is_empty() || target == key || !base_keys.contains(target)
40            || head_keys.contains(target) { continue; }
41        proposals.push((key.clone(), target.clone()));
42        *claims.entry(target).or_default() += 1;
43    }
44    let applied: Vec<_> = proposals.into_iter()
45        .filter(|(_, target)| claims[target] == 1).collect();
46    let replacements: HashMap<_, _> = applied.iter().map(|(key, value)| (key, value)).collect();
47    for (key, _) in head.iter_mut() {
48        if let Some(target) = replacements.get(key) { *key = (*target).clone(); }
49    }
50    applied
51}
52
53pub(crate) fn changed_components(base: &ComponentMap, head: &ComponentMap) -> Vec<JsString> {
54    // #8042: visit each map directly, without allocating and hashing a union.
55    // Equal cardinality plus no changed base members proves equality; the
56    // overwhelmingly common unchanged case needs only one lookup per member.
57    // #8351: when every base member is also a head member, equal cardinality
58    // proves the key sets are equal, so head-only members need no second pass.
59    let mut shared = true;
60    let mut keys: Vec<_> = base.iter().filter(|(key, value)| match head.get(*key) {
61        Some(other) => other != *value,
62        None => { shared = false; true },
63    }).map(|(key, _)| key.clone()).collect();
64    if shared && base.len() == head.len() {
65        keys.sort_by(cmp_code_units);
66        return keys;
67    }
68    keys.extend(head.keys().filter(|key| !base.contains_key(*key)).cloned());
69    keys.sort_by(cmp_code_units);
70    keys
71}
72
73/// The key pass is reusable by the subsequent content stages. Its output order
74/// follows JS Map insertion order: first base appearances, then head-only keys.
75pub fn diff_by_key<'a, R>(
76    base: &'a [EntityFingerprint<R>], head: &'a [EntityFingerprint<R>], options: &KeyDiffOptions,
77) -> KeyDiff<'a, R> {
78    diff_by_key_impl(base, head, options, true)
79}
80
81pub(crate) fn diff_by_key_for_transport<'a, R>(
82    base: &'a [EntityFingerprint<R>], head: &'a [EntityFingerprint<R>], options: &KeyDiffOptions,
83) -> KeyDiff<'a, R> {
84    diff_by_key_impl(base, head, options, false)
85}
86
87fn diff_by_key_impl<'a, R>(
88    base: &'a [EntityFingerprint<R>], head: &'a [EntityFingerprint<R>], options: &KeyDiffOptions,
89    build_index: bool,
90) -> KeyDiff<'a, R> {
91    let excluded: HashSet<JsString> = options.exclude_types.iter().map(normalize_type)
92        .filter(|name| !name.is_empty()).collect();
93    let is_excluded = |entity: &EntityFingerprint<R>| !excluded.is_empty() && excluded.contains(&normalize_type(&entity.ifc_type));
94    let (base_order, base_index) = index(base);
95    let (mut head_order, mut head_index) = index(head);
96    let applied_key_aliases = options.key_aliases.as_ref()
97        .map(|aliases| resolve_aliases(&base_order, &mut head_order, aliases));
98    // The deduplication maps are already the first-occurrence indices. Only
99    // alias replacement changes keys and requires rebuilding the head index.
100    if applied_key_aliases.as_ref().is_some_and(|aliases| !aliases.is_empty()) {
101        head_index = head_order.iter().map(|(key, i)| (key, *i)).collect();
102    }
103    let base_has_geometry = base_order.iter().any(|(key, i)| {
104        base[*i].geometry_hash(options.strip_placement_geometry).is_some() && !is_excluded(&base[*i])
105            && head_index.get(key).is_none_or(|j| !is_excluded(&head[*j]))
106    });
107    let head_has_geometry = head_order.iter().any(|(key, i)| {
108        head[*i].geometry_hash(options.strip_placement_geometry).is_some() && !is_excluded(&head[*i])
109            && base_index.get(key).is_none_or(|j| !is_excluded(&base[*j]))
110    });
111    let consider_data = options.scope != DiffScope::Geometry;
112    let use_geometry = options.scope != DiffScope::Data && base_has_geometry == head_has_geometry;
113    let mut entries = Vec::with_capacity(base_order.len().max(head_order.len()));
114    // Ordered keys are unique on both sides, aliases included, so the base
115    // pass already decides which head rows have a base key (#8351).
116    let mut paired = vec![false; head.len()];
117    for (key, i) in &base_order {
118        let base_entity = &base[*i];
119        let head_entity = head_index.get(key).map(|&j| { paired[j] = true; &head[j] });
120        if is_excluded(base_entity) || head_entity.is_some_and(&is_excluded) { continue; }
121        let mut entry = DiffEntry {
122            key: key.clone(), state: DiffState::Deleted, change_kinds: Vec::new(),
123            base: Some(base_entity), head: head_entity, changed_components: None,
124        };
125        if let Some(other) = head_entity {
126            if consider_data && (base_entity.ifc_type != other.ifc_type || base_entity.data_hash != other.data_hash) {
127                entry.change_kinds.push(DiffChangeKind::Data);
128            }
129            if use_geometry && base_entity.geometry_hash(options.strip_placement_geometry) != other.geometry_hash(options.strip_placement_geometry) {
130                entry.change_kinds.push(DiffChangeKind::Geometry);
131            }
132            if consider_data {
133                if let (Some(a), Some(b)) = (&base_entity.container, &other.container) {
134                    if !a.is_empty() && !b.is_empty() && a != b {
135                        entry.change_kinds.push(DiffChangeKind::Container);
136                    }
137                }
138            }
139            if let (Some(a), Some(b)) = (&base_entity.components, &other.components) {
140                entry.changed_components = Some(changed_components(a, b));
141            }
142            entry.state = if entry.change_kinds.is_empty() { DiffState::Unchanged } else { DiffState::Modified };
143        }
144        entries.push(entry);
145    }
146    for (key, i) in &head_order {
147        if paired[*i] || is_excluded(&head[*i]) { continue; }
148        entries.push(DiffEntry {
149            key: key.clone(), state: DiffState::Added, change_kinds: Vec::new(),
150            base: None, head: Some(&head[*i]), changed_components: None,
151        });
152    }
153    let mut counts = DiffCounts::default();
154    let mut by_key = if build_index { HashMap::with_capacity(entries.len()) } else { HashMap::new() };
155    for (i, entry) in entries.iter().enumerate() {
156        if build_index { by_key.insert(entry.key.clone(), i); }
157        match entry.state {
158            DiffState::Added => counts.added += 1,
159            DiffState::Modified => counts.modified += 1,
160            DiffState::Deleted => counts.deleted += 1,
161            DiffState::Unchanged => counts.unchanged += 1,
162        }
163    }
164    let mut excluded_types: Vec<_> = excluded.into_iter().collect();
165    excluded_types.sort_by(cmp_code_units);
166    KeyDiff { scope: options.scope, excluded_types, entries, by_key, counts, applied_key_aliases, use_geometry, strip_placement_geometry: options.strip_placement_geometry }
167}
168
169#[cfg(test)]
170#[path = "key_diff_tests.rs"]
171mod tests;