use super::*; #[derive(Debug)] pub struct Replacement { pub removed: usize, pub added: usize, pub explanation: String, /// Explanation matching is never object identity or geometric equivalence. pub match_rule: &'static str, } type Group = (u16, Option, Option, Option); fn group(object: &ObjectChange, bounds: bool) -> Group { ( object.kind, object.layer, object.target.clone(), if bounds && object.target.is_none() { object.bounds } else { None }, ) } /// Pair only unique candidates in the remaining multisets. Ambiguous groups /// remain additions/removals; no identity or geometric equivalence is inferred. pub(super) fn replacements(old: &[ObjectChange], new: &[ObjectChange]) -> Vec { let (mut used_old, mut used_new) = (BTreeSet::new(), BTreeSet::new()); let mut result = Vec::new(); for bounds in [true, false] { let (mut a, mut b) = ( BTreeMap::>::new(), BTreeMap::>::new(), ); for (i, object) in old .iter() .enumerate() .filter(|(i, _)| !used_old.contains(i)) { a.entry(group(object, bounds)).or_default().push(i); } for (i, object) in new .iter() .enumerate() .filter(|(i, _)| !used_new.contains(i)) { b.entry(group(object, bounds)).or_default().push(i); } for (key, indices) in a { if let (1, Some(others)) = (indices.len(), b.get(&key)) && others.len() == 1 { let (i, j) = (indices[0], others[0]); result.push(Replacement { removed: i, added: j, explanation: explain(&old[i], &new[j]), match_rule: if old[i].target.is_some() { "unique_kind_target" } else if bounds { "unique_kind_layer_bounds" } else { "unique_kind_layer" }, }); used_old.insert(i); used_new.insert(j); } } } result.sort_by_key(|r| (r.removed, r.added)); result } fn explain(old: &ObjectChange, new: &ObjectChange) -> String { let mut parts = vec![format!( "{} modified{}", kind_name(old.kind), old.target .as_ref() .map(|t| format!(" target={t:?}")) .unwrap_or_default() )]; if old.target.is_some() && old.origin != new.origin && let (Some(a), Some(b)) = (old.origin, new.origin) { parts.push(format!( "origin {a:?} -> {b:?}, delta=({}, {}) dbu", i64::from(b[0]) - i64::from(a[0]), i64::from(b[1]) - i64::from(a[1]) )); } if old.counts != new.counts { let counts = |c: Option<[u16; 2]>| { c.map(|[a, b]| format!("{a} x {b}")) .unwrap_or_else(|| "absent".to_string()) }; parts.push(format!( "columns/rows {} -> {}", counts(old.counts), counts(new.counts) )); } if old.width != new.width { let width = |n: Option| { n.map(|n| n.to_string()) .unwrap_or_else(|| "absent".to_string()) }; parts.push(format!( "width {} -> {} dbu", width(old.width), width(new.width) )); } if old.bounds == new.bounds { parts.push("coordinate bounds unchanged".to_string()); } else { parts.push(format!( "coordinate bounds {:?} -> {:?}", old.bounds, new.bounds )); } parts.join("; ") }