Skip to main content

codeint_config/
finding_anchor.rs

1use std::collections::{BTreeMap, HashMap, VecDeque};
2
3use codeint_model::StableHasher;
4use serde::{Deserialize, Serialize};
5
6#[cfg(test)]
7mod tests;
8
9const MAX_EXACT_MATCH_GROUP: usize = 64;
10const MAX_LINE_DISTANCE: u32 = 1_000_000;
11const MATCH_WEIGHT: i64 = 1 << 44;
12const CONTEXT_SHIFT: u32 = 34;
13const LINE_SHIFT: u32 = 7;
14
15#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
16#[serde(deny_unknown_fields)]
17pub struct FindingAnchor {
18    pub id: String,
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub content: Option<String>,
21    #[serde(default, skip_serializing_if = "Option::is_none")]
22    pub body: Option<String>,
23    #[serde(default, skip_serializing_if = "Vec::is_empty")]
24    pub paths: Vec<String>,
25    #[serde(default, skip_serializing_if = "Option::is_none")]
26    pub before: Option<String>,
27    #[serde(default, skip_serializing_if = "Option::is_none")]
28    pub after: Option<String>,
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub line: Option<u32>,
31    #[serde(default, skip_serializing_if = "Vec::is_empty")]
32    pub clone_lines: Vec<CloneLineAnchor>,
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
36#[serde(deny_unknown_fields)]
37pub struct CloneLineAnchor {
38    path: u64,
39    occurrence: u32,
40    content: u64,
41}
42
43impl CloneLineAnchor {
44    pub fn new(path: &str, occurrence: u32, content: u64) -> Self {
45        Self {
46            path: anchor_path_digest(path),
47            occurrence,
48            content,
49        }
50    }
51
52    pub(crate) fn with_rename(self, renames: &HashMap<u64, u64>) -> Self {
53        Self {
54            path: renames.get(&self.path).copied().unwrap_or(self.path),
55            ..self
56        }
57    }
58}
59
60pub(crate) fn clone_line_renames(renames: &BTreeMap<String, String>) -> HashMap<u64, u64> {
61    renames
62        .iter()
63        .map(|(old, new)| (anchor_path_digest(old), anchor_path_digest(new)))
64        .collect()
65}
66
67impl FindingAnchor {
68    pub fn id_only(id: impl Into<String>) -> FindingAnchor {
69        FindingAnchor {
70            id: id.into(),
71            content: None,
72            body: None,
73            paths: Vec::new(),
74            before: None,
75            after: None,
76            line: None,
77            clone_lines: Vec::new(),
78        }
79    }
80
81    pub fn from_hashes(
82        id: String,
83        content: u64,
84        before: Option<u64>,
85        after: Option<u64>,
86        line: Option<u32>,
87    ) -> FindingAnchor {
88        FindingAnchor {
89            id,
90            content: Some(format!("{content:016x}")),
91            body: None,
92            paths: Vec::new(),
93            before: before.map(|value| format!("{value:016x}")),
94            after: after.map(|value| format!("{value:016x}")),
95            line,
96            clone_lines: Vec::new(),
97        }
98    }
99
100    pub fn with_body_and_paths(mut self, body: Option<u64>, paths: Vec<String>) -> FindingAnchor {
101        self.body = body
102            .filter(|&value| value != 0)
103            .map(|value| format!("{value:016x}"));
104        let mut hashed: Vec<String> = paths
105            .into_iter()
106            .map(|path| hash_anchor_path(&path))
107            .collect();
108        hashed.sort();
109        hashed.dedup();
110        self.paths = hashed;
111        self
112    }
113}
114
115fn hash_anchor_path(path: &str) -> String {
116    format!("{:016x}", anchor_path_digest(path))
117}
118
119fn anchor_path_digest(path: &str) -> u64 {
120    StableHasher::new()
121        .write_bytes(b"codeint.anchor.path.v1")
122        .write_u64(path.len() as u64)
123        .write_bytes(path.as_bytes())
124        .finish()
125}
126
127#[derive(Debug, Clone, Default, PartialEq, Eq)]
128pub struct AnchorMatch {
129    pub matched_pairs: Vec<(usize, usize)>,
130}
131
132impl AnchorMatch {
133    pub fn matched_references(&self, len: usize) -> Vec<bool> {
134        let mut matched = vec![false; len];
135        for &(reference_index, _) in &self.matched_pairs {
136            matched[reference_index] = true;
137        }
138        matched
139    }
140
141    pub fn matched_candidates(&self, len: usize) -> Vec<bool> {
142        let mut matched = vec![false; len];
143        for &(_, candidate_index) in &self.matched_pairs {
144            matched[candidate_index] = true;
145        }
146        matched
147    }
148}
149
150pub fn remap_anchor_paths(
151    anchor: &FindingAnchor,
152    renames: &BTreeMap<String, String>,
153) -> FindingAnchor {
154    if renames.is_empty() {
155        return anchor.clone();
156    }
157    let mut remapped = anchor.clone();
158    remapped.id = remap_paths_in_id(&anchor.id, renames);
159    remapped
160}
161
162pub fn match_anchors_with_renames(
163    references: &[FindingAnchor],
164    candidates: &[FindingAnchor],
165    renames: &BTreeMap<String, String>,
166) -> AnchorMatch {
167    if renames.is_empty() {
168        return match_anchors(references, candidates);
169    }
170    let remapped_references: Vec<FindingAnchor> = references
171        .iter()
172        .map(|reference| remap_anchor_paths(reference, renames))
173        .collect();
174    let direct = match_anchors(&remapped_references, candidates);
175    let max_matches = references.len().min(candidates.len());
176    if direct.matched_pairs.len() == max_matches {
177        return direct;
178    }
179    let mut used_references = direct.matched_references(references.len());
180    let mut used_candidates = direct.matched_candidates(candidates.len());
181    let mut matched_pairs = direct.matched_pairs;
182    match_remapped_ids(
183        references,
184        &remapped_references,
185        candidates,
186        &mut used_references,
187        &mut used_candidates,
188        &mut matched_pairs,
189    );
190    if matched_pairs.len() < max_matches {
191        match_renamed_body_groups(
192            references,
193            candidates,
194            renames,
195            &used_references,
196            &used_candidates,
197            &mut matched_pairs,
198        );
199    }
200    matched_pairs.sort_unstable();
201    AnchorMatch { matched_pairs }
202}
203
204fn match_candidates_by_id<'a>(
205    candidates: &'a [FindingAnchor],
206    used_references: &mut [bool],
207    used_candidates: &mut [bool],
208    matched_pairs: &mut Vec<(usize, usize)>,
209    reference_ids: impl Iterator<Item = (usize, &'a str)>,
210) {
211    let mut candidates_by_id: HashMap<&str, VecDeque<usize>> = HashMap::new();
212    for (index, candidate) in candidates.iter().enumerate() {
213        if !used_candidates[index] {
214            candidates_by_id
215                .entry(candidate.id.as_str())
216                .or_default()
217                .push_back(index);
218        }
219    }
220    for (ref_index, target_id) in reference_ids {
221        if let Some(queue) = candidates_by_id.get_mut(target_id)
222            && let Some(cand_index) = queue.pop_front()
223        {
224            used_references[ref_index] = true;
225            used_candidates[cand_index] = true;
226            matched_pairs.push((ref_index, cand_index));
227        }
228    }
229}
230
231fn match_remapped_ids(
232    references: &[FindingAnchor],
233    remapped_references: &[FindingAnchor],
234    candidates: &[FindingAnchor],
235    used_references: &mut [bool],
236    used_candidates: &mut [bool],
237    matched_pairs: &mut Vec<(usize, usize)>,
238) {
239    let targets: Vec<(usize, &str)> = references
240        .iter()
241        .zip(remapped_references.iter())
242        .enumerate()
243        .filter(|&(index, (original, remapped))| {
244            !used_references[index] && original.id != remapped.id
245        })
246        .map(|(index, (_, remapped))| (index, remapped.id.as_str()))
247        .collect();
248    match_candidates_by_id(
249        candidates,
250        used_references,
251        used_candidates,
252        matched_pairs,
253        targets.into_iter(),
254    );
255}
256
257fn canonical_paths(paths: &[String], renames: Option<&HashMap<String, String>>) -> Vec<String> {
258    let mut normalized: Vec<String> = paths
259        .iter()
260        .map(|path| match renames.and_then(|map| map.get(path)) {
261            Some(renamed) => renamed.clone(),
262            None => path.clone(),
263        })
264        .collect();
265    normalized.sort();
266    normalized.dedup();
267    normalized
268}
269
270fn build_rename_lookup(renames: &BTreeMap<String, String>) -> HashMap<String, String> {
271    let mut lookup = HashMap::with_capacity(renames.len() * 2);
272    for (old_path, new_path) in renames {
273        lookup.insert(old_path.clone(), new_path.clone());
274        lookup.insert(hash_anchor_path(old_path), hash_anchor_path(new_path));
275    }
276    lookup
277}
278
279fn group_anchors_by_body_and_paths<'a>(
280    anchors: &'a [FindingAnchor],
281    used: &[bool],
282    rename_lookup: Option<&HashMap<String, String>>,
283) -> BTreeMap<(&'a str, Vec<String>), Vec<usize>> {
284    let mut groups: BTreeMap<(&'a str, Vec<String>), Vec<usize>> = BTreeMap::new();
285    for (index, anchor) in anchors.iter().enumerate() {
286        if used[index] || anchor.paths.is_empty() {
287            continue;
288        }
289        let Some(body) = anchor.body.as_deref() else {
290            continue;
291        };
292        if let Some(lookup) = rename_lookup
293            && !anchor.paths.iter().any(|path| lookup.contains_key(path))
294        {
295            continue;
296        }
297        let key = (body, canonical_paths(&anchor.paths, rename_lookup));
298        groups.entry(key).or_default().push(index);
299    }
300    groups
301}
302
303fn match_renamed_body_groups(
304    references: &[FindingAnchor],
305    candidates: &[FindingAnchor],
306    renames: &BTreeMap<String, String>,
307    used_references: &[bool],
308    used_candidates: &[bool],
309    matched_pairs: &mut Vec<(usize, usize)>,
310) {
311    let rename_lookup = build_rename_lookup(renames);
312    let reference_groups =
313        group_anchors_by_body_and_paths(references, used_references, Some(&rename_lookup));
314    if reference_groups.is_empty() {
315        return;
316    }
317    let candidate_groups = group_anchors_by_body_and_paths(candidates, used_candidates, None);
318    for (key, ref_indices) in reference_groups {
319        let Some(cand_indices) = candidate_groups.get(&key) else {
320            continue;
321        };
322        match_content_group(
323            references,
324            candidates,
325            &ref_indices,
326            cand_indices,
327            matched_pairs,
328        );
329    }
330}
331
332pub fn match_anchors_with_aliases(
333    references: &[FindingAnchor],
334    candidates: &[FindingAnchor],
335    candidate_aliases: &[Option<FindingAnchor>],
336    renames: &BTreeMap<String, String>,
337) -> AnchorMatch {
338    let direct = match_anchors_with_renames(references, candidates, renames);
339    if candidate_aliases.is_empty()
340        || direct.matched_pairs.len() == references.len().min(candidates.len())
341    {
342        return direct;
343    }
344    let ref_used = direct.matched_references(references.len());
345    let cand_used = direct.matched_candidates(candidates.len());
346
347    let unmatched_ref_indices: Vec<usize> = ref_used
348        .iter()
349        .enumerate()
350        .filter_map(|(index, &used)| (!used).then_some(index))
351        .collect();
352    let unmatched_alias_entries: Vec<(usize, FindingAnchor)> = candidate_aliases
353        .iter()
354        .enumerate()
355        .filter_map(|(index, alias)| {
356            if index < candidates.len() && !cand_used[index] {
357                alias.clone().map(|anchor| (index, anchor))
358            } else {
359                None
360            }
361        })
362        .collect();
363    if unmatched_ref_indices.is_empty() || unmatched_alias_entries.is_empty() {
364        return direct;
365    }
366
367    let unmatched_refs: Vec<FindingAnchor> = unmatched_ref_indices
368        .iter()
369        .map(|&index| references[index].clone())
370        .collect();
371    let unmatched_aliases: Vec<FindingAnchor> = unmatched_alias_entries
372        .iter()
373        .map(|(_, anchor)| anchor.clone())
374        .collect();
375    let alias_match = match_anchors(&unmatched_refs, &unmatched_aliases);
376    if alias_match.matched_pairs.is_empty() {
377        return direct;
378    }
379
380    let mut matched_pairs = direct.matched_pairs;
381    for (local_ref, local_alias) in alias_match.matched_pairs {
382        matched_pairs.push((
383            unmatched_ref_indices[local_ref],
384            unmatched_alias_entries[local_alias].0,
385        ));
386    }
387    matched_pairs.sort_unstable();
388    AnchorMatch { matched_pairs }
389}
390
391fn remap_paths_in_id(id: &str, renames: &BTreeMap<String, String>) -> String {
392    if let Some(exact) = renames.get(id) {
393        return exact.clone();
394    }
395    let mut ordered: Vec<(&str, &str)> = renames
396        .iter()
397        .filter(|(old_path, _)| !old_path.is_empty() && id.contains(old_path.as_str()))
398        .map(|(old_path, new_path)| (old_path.as_str(), new_path.as_str()))
399        .collect();
400    if ordered.is_empty() {
401        return id.to_owned();
402    }
403    ordered.sort_by(|left, right| {
404        right
405            .0
406            .len()
407            .cmp(&left.0.len())
408            .then_with(|| left.0.cmp(right.0))
409    });
410    let mut result = id.to_owned();
411    for (old_path, new_path) in ordered {
412        result = replace_path_bounded(&result, old_path, new_path);
413    }
414    result
415}
416
417fn replace_path_bounded(text: &str, old_path: &str, new_path: &str) -> String {
418    let mut output = String::with_capacity(text.len());
419    let mut rest = text;
420    let mut offset = 0usize;
421    while let Some(pos) = rest.find(old_path) {
422        let abs_start = offset + pos;
423        let abs_end = abs_start + old_path.len();
424        let left_ok = abs_start == 0
425            || text[..abs_start]
426                .chars()
427                .next_back()
428                .is_some_and(is_path_delimiter);
429        let right_ok = abs_end == text.len()
430            || text[abs_end..]
431                .chars()
432                .next()
433                .is_some_and(is_path_delimiter);
434        output.push_str(&rest[..pos]);
435        if left_ok && right_ok {
436            output.push_str(new_path);
437        } else {
438            output.push_str(old_path);
439        }
440        let advance = pos + old_path.len();
441        rest = &rest[advance..];
442        offset += advance;
443    }
444    output.push_str(rest);
445    output
446}
447
448fn is_path_delimiter(ch: char) -> bool {
449    matches!(
450        ch,
451        ':' | ',' | ' ' | '\t' | '|' | '[' | ']' | '(' | ')' | '#' | '@' | ';'
452    )
453}
454
455pub fn match_anchors(references: &[FindingAnchor], candidates: &[FindingAnchor]) -> AnchorMatch {
456    if references.is_empty() || candidates.is_empty() {
457        return AnchorMatch::default();
458    }
459    let mut matched_pairs = Vec::new();
460    let mut used_references = vec![false; references.len()];
461    let mut used_candidates = vec![false; candidates.len()];
462
463    match_id_only_references(
464        references,
465        candidates,
466        &mut used_references,
467        &mut used_candidates,
468        &mut matched_pairs,
469    );
470
471    let reference_groups = group_unused_by_content(references, &used_references);
472    let candidate_groups = group_unused_by_content(candidates, &used_candidates);
473
474    for (content, ref_indices) in reference_groups {
475        let Some(cand_indices) = candidate_groups.get(content) else {
476            continue;
477        };
478        match_content_group(
479            references,
480            candidates,
481            &ref_indices,
482            cand_indices,
483            &mut matched_pairs,
484        );
485    }
486
487    matched_pairs.sort_unstable();
488    AnchorMatch { matched_pairs }
489}
490
491fn group_unused_by_content<'a>(
492    anchors: &'a [FindingAnchor],
493    used: &[bool],
494) -> BTreeMap<&'a str, Vec<usize>> {
495    let mut groups: BTreeMap<&'a str, Vec<usize>> = BTreeMap::new();
496    for (index, anchor) in anchors.iter().enumerate() {
497        if !used[index]
498            && let Some(content) = anchor.content.as_deref()
499        {
500            groups.entry(content).or_default().push(index);
501        }
502    }
503    groups
504}
505
506fn match_id_only_references(
507    references: &[FindingAnchor],
508    candidates: &[FindingAnchor],
509    used_references: &mut [bool],
510    used_candidates: &mut [bool],
511    matched_pairs: &mut Vec<(usize, usize)>,
512) {
513    let targets = references
514        .iter()
515        .enumerate()
516        .filter(|(_, reference)| reference.content.is_none())
517        .map(|(index, reference)| (index, reference.id.as_str()));
518    match_candidates_by_id(
519        candidates,
520        used_references,
521        used_candidates,
522        matched_pairs,
523        targets,
524    );
525}
526
527fn match_content_group(
528    references: &[FindingAnchor],
529    candidates: &[FindingAnchor],
530    ref_indices: &[usize],
531    cand_indices: &[usize],
532    matched_pairs: &mut Vec<(usize, usize)>,
533) {
534    if ref_indices.len() == 1 && cand_indices.len() == 1 {
535        matched_pairs.push((ref_indices[0], cand_indices[0]));
536        return;
537    }
538    if ref_indices.len().max(cand_indices.len()) <= MAX_EXACT_MATCH_GROUP {
539        match_group_exact(
540            references,
541            candidates,
542            ref_indices,
543            cand_indices,
544            matched_pairs,
545        );
546    } else {
547        match_group_bucketed(
548            references,
549            candidates,
550            ref_indices,
551            cand_indices,
552            matched_pairs,
553        );
554    }
555}
556
557fn match_group_exact(
558    references: &[FindingAnchor],
559    candidates: &[FindingAnchor],
560    ref_indices: &[usize],
561    cand_indices: &[usize],
562    matched_pairs: &mut Vec<(usize, usize)>,
563) {
564    let size = ref_indices.len().max(cand_indices.len());
565    let mut weights = vec![vec![0i64; size]; size];
566    for (row, &ref_index) in ref_indices.iter().enumerate() {
567        for (col, &cand_index) in cand_indices.iter().enumerate() {
568            weights[row][col] = pair_weight(&references[ref_index], &candidates[cand_index]);
569        }
570    }
571    let assignment = hungarian_max_weight(&weights);
572    for (row, &col) in assignment.iter().enumerate() {
573        if row < ref_indices.len() && col < cand_indices.len() {
574            matched_pairs.push((ref_indices[row], cand_indices[col]));
575        }
576    }
577}
578
579fn pair_weight(reference: &FindingAnchor, candidate: &FindingAnchor) -> i64 {
580    let context_score = context_match_score(reference, candidate);
581    let line_bonus = line_proximity_bonus(reference.line, candidate.line);
582    let same_id = i64::from(reference.id == candidate.id);
583    MATCH_WEIGHT + (context_score << CONTEXT_SHIFT) + (line_bonus << LINE_SHIFT) + same_id
584}
585
586fn context_match_score(reference: &FindingAnchor, candidate: &FindingAnchor) -> i64 {
587    let has_line_bounds = reference.line.is_some() && candidate.line.is_some();
588    side_match_score(
589        reference.before.as_deref(),
590        candidate.before.as_deref(),
591        has_line_bounds,
592    ) + side_match_score(
593        reference.after.as_deref(),
594        candidate.after.as_deref(),
595        has_line_bounds,
596    )
597}
598
599fn side_match_score(
600    reference_side: Option<&str>,
601    candidate_side: Option<&str>,
602    has_line_bounds: bool,
603) -> i64 {
604    match (reference_side, candidate_side) {
605        (Some(left), Some(right)) if left == right => 3,
606        (None, None) if has_line_bounds => 2,
607        _ => 0,
608    }
609}
610
611fn line_proximity_bonus(reference_line: Option<u32>, candidate_line: Option<u32>) -> i64 {
612    let distance = match (reference_line, candidate_line) {
613        (Some(left), Some(right)) => left.abs_diff(right).min(MAX_LINE_DISTANCE),
614        _ => MAX_LINE_DISTANCE,
615    };
616    i64::from(MAX_LINE_DISTANCE - distance)
617}
618
619struct HungarianSolver<'a> {
620    weights: &'a [Vec<i64>],
621    max_weight: i64,
622    u: Vec<i64>,
623    v: Vec<i64>,
624    p: Vec<usize>,
625    way: Vec<usize>,
626}
627
628impl<'a> HungarianSolver<'a> {
629    fn new(weights: &'a [Vec<i64>]) -> HungarianSolver<'a> {
630        let n = weights.len();
631        let max_weight = weights
632            .iter()
633            .flat_map(|row| row.iter().copied())
634            .max()
635            .unwrap_or(0);
636        HungarianSolver {
637            weights,
638            max_weight,
639            u: vec![0; n + 1],
640            v: vec![0; n + 1],
641            p: vec![0; n + 1],
642            way: vec![0; n + 1],
643        }
644    }
645
646    fn solve(mut self) -> Vec<usize> {
647        let n = self.weights.len();
648        for row in 1..=n {
649            self.augment_row(row);
650        }
651        let mut assignment = vec![0usize; n];
652        for col in 1..=n {
653            if self.p[col] > 0 {
654                assignment[self.p[col] - 1] = col - 1;
655            }
656        }
657        assignment
658    }
659
660    fn augment_row(&mut self, row: usize) {
661        let n = self.weights.len();
662        self.p[0] = row;
663        let mut col0 = 0usize;
664        let mut min_v = vec![i64::MAX; n + 1];
665        let mut used = vec![false; n + 1];
666        loop {
667            used[col0] = true;
668            let (delta, next_col) = self.relax_columns(col0, &used, &mut min_v);
669            self.shift_potentials(&used, &mut min_v, delta);
670            col0 = next_col;
671            if self.p[col0] == 0 {
672                break;
673            }
674        }
675        self.unwind_path(col0);
676    }
677
678    fn relax_columns(&mut self, col0: usize, used: &[bool], min_v: &mut [i64]) -> (i64, usize) {
679        let row0 = self.p[col0];
680        let mut delta = i64::MAX;
681        let mut best_col = 0usize;
682        for col in 1..=self.weights.len() {
683            if used[col] {
684                continue;
685            }
686            let cost = self.max_weight - self.weights[row0 - 1][col - 1];
687            let current = cost - self.u[row0] - self.v[col];
688            if current < min_v[col] {
689                min_v[col] = current;
690                self.way[col] = col0;
691            }
692            if min_v[col] < delta {
693                delta = min_v[col];
694                best_col = col;
695            }
696        }
697        (delta, best_col)
698    }
699
700    fn shift_potentials(&mut self, used: &[bool], min_v: &mut [i64], delta: i64) {
701        for col in 0..=self.weights.len() {
702            if used[col] {
703                self.u[self.p[col]] += delta;
704                self.v[col] -= delta;
705            } else {
706                min_v[col] -= delta;
707            }
708        }
709    }
710
711    fn unwind_path(&mut self, mut col0: usize) {
712        while col0 != 0 {
713            let col1 = self.way[col0];
714            self.p[col0] = self.p[col1];
715            col0 = col1;
716        }
717    }
718}
719
720fn hungarian_max_weight(weights: &[Vec<i64>]) -> Vec<usize> {
721    HungarianSolver::new(weights).solve()
722}
723
724struct BucketedMatcher<'a> {
725    references: &'a [FindingAnchor],
726    candidates: &'a [FindingAnchor],
727    ref_indices: &'a [usize],
728    cand_indices: &'a [usize],
729    ref_used: Vec<bool>,
730    cand_used: Vec<bool>,
731}
732
733impl<'a> BucketedMatcher<'a> {
734    fn pair_by_key<K: Eq + std::hash::Hash>(
735        &mut self,
736        matched_pairs: &mut Vec<(usize, usize)>,
737        key_of: impl Fn(&'a FindingAnchor) -> Option<K>,
738    ) {
739        let mut buckets: HashMap<K, VecDeque<usize>> = HashMap::new();
740        for (cand_pos, &cand_index) in self.cand_indices.iter().enumerate() {
741            if !self.cand_used[cand_pos]
742                && let Some(key) = key_of(&self.candidates[cand_index])
743            {
744                buckets.entry(key).or_default().push_back(cand_pos);
745            }
746        }
747        for (ref_pos, &ref_index) in self.ref_indices.iter().enumerate() {
748            if self.ref_used[ref_pos] {
749                continue;
750            }
751            if let Some(key) = key_of(&self.references[ref_index])
752                && let Some(queue) = buckets.get_mut(&key)
753                && let Some(cand_pos) = queue.pop_front()
754            {
755                self.ref_used[ref_pos] = true;
756                self.cand_used[cand_pos] = true;
757                matched_pairs.push((ref_index, self.cand_indices[cand_pos]));
758            }
759        }
760    }
761}
762
763fn match_group_bucketed(
764    references: &[FindingAnchor],
765    candidates: &[FindingAnchor],
766    ref_indices: &[usize],
767    cand_indices: &[usize],
768    matched_pairs: &mut Vec<(usize, usize)>,
769) {
770    let mut matcher = BucketedMatcher {
771        references,
772        candidates,
773        ref_indices,
774        cand_indices,
775        ref_used: vec![false; ref_indices.len()],
776        cand_used: vec![false; cand_indices.len()],
777    };
778    matcher.pair_by_key(matched_pairs, |anchor| {
779        Some((anchor.before.as_deref(), anchor.after.as_deref()))
780    });
781    matcher.pair_by_key(matched_pairs, |anchor| anchor.before.as_deref());
782    matcher.pair_by_key(matched_pairs, |anchor| anchor.after.as_deref());
783    let remaining_refs = ref_indices
784        .iter()
785        .enumerate()
786        .filter(|&(pos, _)| !matcher.ref_used[pos])
787        .map(|(_, &index)| index);
788    let remaining_cands = cand_indices
789        .iter()
790        .enumerate()
791        .filter(|&(pos, _)| !matcher.cand_used[pos])
792        .map(|(_, &index)| index);
793    matched_pairs.extend(remaining_refs.zip(remaining_cands));
794}