ifc_lite_diff/
identity_map.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/.
4use crate::JsString;
5use std::collections::{HashMap, HashSet};
6use crate::content_types::{ContentMatch, ContentMatchKind};
7use crate::successor::{SuccessorClaim, SuccessorConfidence};
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct IdentityMapEntry { pub base: JsString, pub here: JsString, pub reason: JsString }
10pub const CONTENT_MATCH_REASON_PREFIX: &str = "content-match:";
11pub const SUCCESSOR_REASON_PREFIX: &str = "successor:";
12pub const ACCEPTED_AMBIGUOUS_REASON: &str = "accepted:ambiguous";
13
14pub fn identity_map_from_content_matches<R>(matches: &[ContentMatch<'_, R>]) -> Vec<IdentityMapEntry> {
15    matches.iter().filter_map(|m| {
16        let name = match m.kind {
17            ContentMatchKind::Renamed => "renamed", ContentMatchKind::Moved => "moved",
18            ContentMatchKind::Reshaped => "reshaped", ContentMatchKind::Respecified => "respecified", _ => return None,
19        };
20        if m.base.len() != 1 || m.head.len() != 1 || m.base[0].key == m.head[0].key { return None; }
21        Some(IdentityMapEntry { base: m.base[0].key.clone(), here: m.head[0].key.clone(), reason: format!("{CONTENT_MATCH_REASON_PREFIX}{name}").into() })
22    }).collect()
23}
24/// Callers must explicitly choose the accepted successor claims; this is never
25/// called automatically on the detector's suggestions.
26pub fn identity_map_from_successors<R>(accepted: &[SuccessorClaim<'_, R>]) -> Vec<IdentityMapEntry> {
27    let mut bases_by_here: HashMap<&JsString, HashSet<&JsString>> = HashMap::new();
28    for claim in accepted {
29        if claim.base.key != claim.head.key { bases_by_here.entry(&claim.head.key).or_default().insert(&claim.base.key); }
30    }
31    let mut seen = HashSet::new();
32    accepted.iter().filter_map(|claim| {
33        let base = &claim.base.key;
34        let here = &claim.head.key;
35        if base == here || bases_by_here.get(here).is_some_and(|s| s.len() > 1) { return None; }
36        if !seen.insert(JsString::concat(&[base, here], "\0")) { return None; }
37        let confidence = match claim.confidence { SuccessorConfidence::Footprint => "footprint", SuccessorConfidence::Position => "position" };
38        Some(IdentityMapEntry { base: base.clone(), here: here.clone(), reason: format!("{SUCCESSOR_REASON_PREFIX}{confidence}").into() })
39    }).collect()
40}