Skip to main content

jubarte_edit/edit/
anchor.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Anchors that differ from the paragraph only in characters a reader
6//! cannot tell apart: a non-breaking space typed as a space, a curly quote
7//! as a straight one, a non-breaking hyphen as a hyphen, a zero-width
8//! character left out. Such an anchor is found, and an anchor that is not
9//! found is echoed with those characters escaped.
10//!
11//! v2 literal anchors ([`v2_candidates`], [`v2_select`],
12//! [`v2_select_all`]) match the exact logical text only: every character
13//! distinct (a space is not U+00A0, a double space is not a single one),
14//! with no lookalike reading and no Markdown-mark fallback. Those v1
15//! fallbacks stay in `reading_hits` under their versioned contract.
16
17use super::{EditError, err};
18
19// Byte comparisons performed by [`v2_candidates`] on this thread. A
20// linear-time overlapping search is `O(n+m)` (a KMP prefix-function table of
21// the anchor plus one pass of the text); a `starts_with` re-scan at every char
22// index is `O(n*m)`. The tests use the count to reject the quadratic path. It
23// is per thread, so tests running side by side under `cargo test` do not
24// disturb each other's count.
25#[cfg(test)]
26thread_local! {
27    pub(super) static READING_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
28    pub(crate) static ANCHOR_BYTE_PROBES: std::cell::Cell<usize> =
29        const { std::cell::Cell::new(0) };
30}
31
32/// Count one byte comparison. Test-only; an empty inline function in
33/// production builds, so the runtime cost is zero.
34#[cfg(test)]
35#[cfg_attr(all(coverage_nightly, test), coverage(off))]
36#[inline]
37fn probe_compare() {
38    ANCHOR_BYTE_PROBES.with(|probes| probes.set(probes.get() + 1));
39}
40
41#[cfg(not(test))]
42#[cfg_attr(all(coverage_nightly, test), coverage(off))]
43#[inline]
44fn probe_compare() {}
45
46/// What `c` reads as, or `None` for a character that shows nothing.
47pub(super) fn reads_as(c: char) -> Option<char> {
48    match c {
49        '\u{A0}' | '\u{2007}' | '\u{202F}' | '\u{2000}'..='\u{200A}' => Some(' '),
50        // Curled and other look-alike quotes read as the straight one. A
51        // backtick-like mark (`\u{2035}`, `\u{B4}`) does not: the straight
52        // quotes and the backtick are what a shell quotes with.
53        '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}' | '\u{2032}' | '\u{02B9}'
54        | '\u{02BB}' | '\u{02BC}' | '\u{FF07}' => Some('\''),
55        '\u{201C}' | '\u{201D}' | '\u{201E}' | '\u{201F}' | '\u{2033}' | '\u{2036}'
56        | '\u{02BA}' | '\u{02EE}' | '\u{FF02}' | '\u{301D}' | '\u{301E}' | '\u{301F}'
57        | '\u{05F4}' => Some('"'),
58        '\u{2010}' | '\u{2011}' => Some('-'),
59        '\u{AD}' | '\u{200B}'..='\u{200D}' | '\u{2060}' | '\u{FEFF}' => None,
60        c => Some(c),
61    }
62}
63
64/// `text` as it reads, with the byte range of `text` each byte of it
65/// comes from.
66fn reading(text: &str) -> (String, Vec<(usize, usize)>) {
67    let mut out = String::with_capacity(text.len());
68    let mut from = Vec::with_capacity(text.len());
69    for (i, c) in text.char_indices() {
70        if let Some(r) = reads_as(c) {
71            out.push(r);
72            from.extend(std::iter::repeat_n((i, i + c.len_utf8()), r.len_utf8()));
73        }
74    }
75    (out, from)
76}
77
78/// Byte ranges of `text` that read as `find`, in order (overlapping ones
79/// too); none when `find` reads as nothing.
80pub(super) fn reading_hits(text: &str, find: &str) -> Vec<(usize, usize)> {
81    #[cfg(test)]
82    READING_CALLS.with(|calls| calls.set(calls.get() + 1));
83    let (needle, _) = reading(find);
84    if needle.is_empty() {
85        return Vec::new();
86    }
87    let (haystack, from) = reading(text);
88    haystack
89        .char_indices()
90        .map(|(i, _)| i)
91        .filter(|&i| haystack[i..].starts_with(&needle))
92        .map(|i| (from[i].0, from[i + needle.len() - 1].1))
93        .collect()
94}
95
96/// `text` quoted, with every character that looks like another or shows
97/// nothing written as `\u{…}`, so an agent sees why its anchor missed.
98pub(super) fn shown(text: &str) -> String {
99    let mut out = String::from("\"");
100    for c in text.chars() {
101        match c {
102            '"' => out.push_str("\\\""),
103            '\\' => out.push_str("\\\\"),
104            '\n' => out.push_str("\\n"),
105            '\t' => out.push_str("\\t"),
106            c if c.is_control() || reads_as(c) != Some(c) && !c.is_alphanumeric() => {
107                out.push_str(&format!("\\u{{{:x}}}", u32::from(c)));
108            }
109            c => out.push(c),
110        }
111    }
112    out.push('"');
113    out
114}
115
116/// A diagnostic occurrence, never a selected range.
117#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
118pub struct NearOccurrence {
119    /// The document's exact characters, suitable for copying into an anchor.
120    pub text: String,
121    /// The exact text quoted with the same escapes as anchor refusals.
122    pub shown: String,
123    /// UTF-8 byte offset in the searched logical paragraph text.
124    pub offset: usize,
125    /// Paragraph owning the offset, when a search spans several targets.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub target: Option<String>,
128}
129
130/// Report-only whitespace matches accompanying `ANCHOR_NOT_FOUND`.
131#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
132pub struct NearMatches {
133    /// Complete occurrence count, including overlaps and entries beyond the cap.
134    pub total: usize,
135    /// At most five occurrences in source order. None authorizes an edit.
136    pub occurrences: Vec<NearOccurrence>,
137}
138
139impl NearMatches {
140    /// One extra refusal line. Exact text remains available in the JSON report;
141    /// the terminal uses visible escapes for invisible characters.
142    pub fn copy_hint(&self) -> String {
143        let shown: Vec<_> = self
144            .occurrences
145            .iter()
146            .map(|hit| hit.shown.as_str())
147            .collect();
148        format!(
149            "near: {} (whitespace or zero-width characters differ); copy the text exactly",
150            shown.join("; ")
151        )
152    }
153}
154
155/// Collapse nonempty Unicode whitespace runs, mapping each output byte back
156/// to its complete input span. Only the document skips zero-width formats;
157/// they are not whitespace and never disappear from the caller's anchor.
158fn whitespace_reading(text: &str, document: bool) -> (String, Vec<(usize, usize)>) {
159    let mut out = String::with_capacity(text.len());
160    let mut from: Vec<(usize, usize)> = Vec::with_capacity(text.len());
161    let mut in_space = false;
162    for (start, c) in text.char_indices() {
163        if document && matches!(c, '\u{200b}'..='\u{200d}' | '\u{2060}' | '\u{feff}') {
164            continue;
165        }
166        let end = start + c.len_utf8();
167        if c.is_whitespace() {
168            if in_space {
169                from.last_mut()
170                    .expect("a whitespace run has a mapped byte")
171                    .1 = end;
172            } else {
173                out.push(' ');
174                from.push((start, end));
175            }
176            in_space = true;
177        } else {
178            out.push(c);
179            from.extend(std::iter::repeat_n((start, end), c.len_utf8()));
180            in_space = false;
181        }
182    }
183    (out, from)
184}
185
186/// Explain a literal miss without selecting or editing anything. One or more
187/// `char::is_whitespace` characters match one or more on the other side. All
188/// other characters remain distinct, apart from document-only skipped formats.
189/// Offsets map back to original UTF-8 bytes, never the collapsed text.
190#[doc(hidden)]
191pub fn near_matches(text: &str, anchor: &str) -> Option<NearMatches> {
192    let (needle, _) = whitespace_reading(anchor, false);
193    if needle.is_empty() {
194        return None;
195    }
196    let (haystack, from) = whitespace_reading(text, true);
197    let hits = v2_candidates(&haystack, &needle);
198    if hits.is_empty() {
199        return None;
200    }
201    let occurrences = hits
202        .iter()
203        .take(5)
204        .map(|&(start, end)| {
205            let offset = from[start].0;
206            let exact = &text[offset..from[end - 1].1];
207            NearOccurrence {
208                text: exact.to_string(),
209                shown: shown(exact),
210                offset,
211                target: None,
212            }
213        })
214        .collect();
215    Some(NearMatches {
216        total: hits.len(),
217        occurrences,
218    })
219}
220
221fn missing(haystack: &str, anchor: &str) -> EditError {
222    let mut error = err(
223        "ANCHOR_NOT_FOUND",
224        None,
225        format!("{} occurs 0 times in the text", shown(anchor)),
226    );
227    error.near = near_matches(haystack, anchor).map(Box::new);
228    error
229}
230
231/// Every exact occurrence of `anchor` in `haystack`, including overlaps,
232/// as UTF-8 byte ranges in start order. Both ends are character boundaries.
233/// Matching preserves exact characters and whitespace, without normalization
234/// or Markdown fallback. An empty anchor produces no candidates; selection
235/// refuses it as `INVALID_EDIT`.
236pub fn v2_candidates(haystack: &str, anchor: &str) -> Vec<(usize, usize)> {
237    if anchor.is_empty() {
238        return Vec::new();
239    }
240    let needle = anchor.as_bytes();
241    let text = haystack.as_bytes();
242    let m = needle.len();
243    // KMP prefix function: `pi[i]` is the length of the longest proper
244    // prefix of `needle[..=i]` that is also a suffix of it.
245    let mut pi = vec![0usize; m];
246    {
247        let mut k = 0usize;
248        for (i, &b) in needle.iter().enumerate().skip(1) {
249            while k > 0 && needle[k] != b {
250                probe_compare();
251                k = pi[k - 1];
252            }
253            if k > 0 {
254                probe_compare();
255            }
256            if needle[k] == b {
257                k += 1;
258            }
259            pi[i] = k;
260        }
261    }
262    // KMP search. A valid UTF-8 anchor begins with a lead byte, so a
263    // byte-level match against valid UTF-8 text always lands on a char
264    // boundary; that is exactly what callers rely on.
265    let mut hits = Vec::new();
266    let mut k = 0usize;
267    for (i, &b) in text.iter().enumerate() {
268        while k > 0 {
269            probe_compare();
270            if needle[k] == b {
271                break;
272            }
273            k = pi[k - 1];
274        }
275        if k == 0 {
276            probe_compare();
277            if needle[0] == b {
278                k = 1;
279            }
280        } else {
281            k += 1;
282        }
283        if k == m {
284            hits.push((i + 1 - m, i + 1));
285            k = pi[k - 1];
286        }
287    }
288    hits
289}
290
291/// Select the unique v2 literal candidate, or the 1-based `occurrence`
292/// within the complete candidate list, including overlapping ranges.
293///
294/// # Errors
295///
296/// Reuses [`EditError`] codes: `INVALID_EDIT` for an empty anchor or occurrence
297/// zero, `ANCHOR_NOT_FOUND` for no candidates, and `AMBIGUOUS_ANCHOR` for
298/// multiple unqualified candidates or an out-of-range occurrence. Match
299/// refusals report the complete candidate count. No operation is bound yet.
300pub fn v2_select(
301    haystack: &str,
302    anchor: &str,
303    occurrence: Option<usize>,
304) -> Result<(usize, usize), EditError> {
305    if anchor.is_empty() {
306        return Err(err("INVALID_EDIT", None, "anchor must be nonempty"));
307    }
308    if occurrence == Some(0) {
309        return Err(err("INVALID_EDIT", None, "occurrence is 1-based"));
310    }
311    let candidates = v2_candidates(haystack, anchor);
312    match (candidates.as_slice(), occurrence) {
313        ([], _) => Err(missing(haystack, anchor)),
314        ([one], None) => Ok(*one),
315        (many, None) => {
316            let shown = shown(anchor);
317            let n = many.len();
318            Err(err(
319                "AMBIGUOUS_ANCHOR",
320                None,
321                format!("{shown} occurs {n} times in the text; set \"occurrence\" to 1..={n}"),
322            ))
323        }
324        (many, Some(k)) if k <= many.len() => Ok(many[k - 1]),
325        (many, Some(k)) => {
326            let shown = shown(anchor);
327            let n = many.len();
328            Err(err(
329                "AMBIGUOUS_ANCHOR",
330                None,
331                format!(
332                    "{shown} occurs {n} times in the text; occurrence {k} is outside occurrence 1..={n}"
333                ),
334            ))
335        }
336    }
337}
338
339/// Select every exact v2 candidate, requiring the complete count to equal
340/// `expected` and every range to be disjoint. Touching ranges are allowed.
341/// Overlapping ranges never yield a greedy subset.
342///
343/// # Errors
344///
345/// Reuses [`EditError`] codes: `INVALID_EDIT` for an empty anchor,
346/// `ANCHOR_NOT_FOUND` for no candidates (even when `expected` is zero),
347/// `AMBIGUOUS_ANCHOR` for a count mismatch, then `OVERLAPPING_EDITS` for
348/// overlapping ranges. Match refusals report the complete candidate count.
349pub fn v2_select_all(
350    haystack: &str,
351    anchor: &str,
352    expected: usize,
353) -> Result<Vec<(usize, usize)>, EditError> {
354    if anchor.is_empty() {
355        return Err(err("INVALID_EDIT", None, "anchor must be nonempty"));
356    }
357    let candidates = v2_candidates(haystack, anchor);
358    let n = candidates.len();
359    if candidates.is_empty() {
360        return Err(missing(haystack, anchor));
361    }
362    if n != expected {
363        let shown = shown(anchor);
364        return Err(err(
365            "AMBIGUOUS_ANCHOR",
366            None,
367            format!("{shown} occurs {n} times in the text, not the expected {expected}"),
368        ));
369    }
370    // Equal-length ranges are sorted by start, so any overlap appears
371    // between neighbours. Equality at the boundary is not overlap.
372    if candidates.windows(2).any(|pair| pair[0].1 > pair[1].0) {
373        let shown = shown(anchor);
374        return Err(err(
375            "OVERLAPPING_EDITS",
376            None,
377            format!(
378                "{shown} occurs {n} times and those ranges overlap, so none of them is replaced"
379            ),
380        ));
381    }
382    Ok(candidates)
383}
384
385#[cfg(test)]
386#[cfg_attr(all(coverage_nightly, test), coverage(off))]
387mod tests {
388    use super::*;
389
390    #[test]
391    fn text_is_found_by_what_it_reads_as() {
392        let text =
393            "\u{201D} shall mean (1)\u{A0}any officer\u{2019}s attorney\u{2011}in\u{2011}fact";
394        let hit = |find: &str| {
395            reading_hits(text, find)
396                .into_iter()
397                .map(|(s, e)| &text[s..e])
398                .collect::<Vec<_>>()
399        };
400        assert_eq!(
401            hit("\" shall mean (1) any officer's"),
402            ["\u{201D} shall mean (1)\u{A0}any officer\u{2019}s"]
403        );
404        assert_eq!(hit("attorney-in-fact"), ["attorney\u{2011}in\u{2011}fact"]);
405        assert!(hit("attorney in fact").is_empty());
406        // A zero-width character reads as nothing, on either side.
407        assert_eq!(reading_hits("ab\u{200B}c", "abc"), [(0, 6)]);
408        assert_eq!(reading_hits("abc", "a\u{AD}bc"), [(0, 3)]);
409        assert!(reading_hits("abc", "\u{200B}").is_empty());
410        // Repeated text overlaps, as the exact search counts it.
411        assert_eq!(reading_hits("aaa", "aa"), [(0, 2), (1, 3)]);
412        // Every character that reads as a quote is one; a backtick-like
413        // mark is not, and a straight quote finds only itself or a curled one.
414        for (quote, straight) in [
415            ('\u{201C}', '"'),
416            ('\u{201D}', '"'),
417            ('\u{201E}', '"'),
418            ('\u{201F}', '"'),
419            ('\u{2033}', '"'),
420            ('\u{2036}', '"'),
421            ('\u{02BA}', '"'),
422            ('\u{02EE}', '"'),
423            ('\u{FF02}', '"'),
424            ('\u{301D}', '"'),
425            ('\u{301E}', '"'),
426            ('\u{301F}', '"'),
427            ('\u{05F4}', '"'),
428            ('\u{2018}', '\''),
429            ('\u{2019}', '\''),
430            ('\u{02B9}', '\''),
431            ('\u{02BB}', '\''),
432            ('\u{02BC}', '\''),
433            ('\u{FF07}', '\''),
434        ] {
435            let text = format!("say {quote}hi{quote}");
436            let find = format!("say {straight}hi{straight}");
437            assert_eq!(reading_hits(&text, &find).len(), 1, "{quote:?}");
438        }
439        for mark in ['`', '\u{2035}', '\u{B4}'] {
440            assert!(
441                reading_hits(&format!("it{mark}s"), "it's").is_empty(),
442                "{mark:?}"
443            );
444        }
445        assert!(reading_hits("say \"hi\"", "say 'hi'").is_empty());
446    }
447
448    #[test]
449    fn lookalikes_and_invisible_characters_are_shown_escaped() {
450        assert_eq!(
451            shown("(1)\u{A0}any \u{2019}x\u{2019} a\u{2011}b\u{200B}"),
452            r#""(1)\u{a0}any \u{2019}x\u{2019} a\u{2011}b\u{200b}""#
453        );
454        assert_eq!(shown("say \"hi\"\t\\"), r#""say \"hi\"\t\\""#);
455        assert_eq!(shown("café naïve"), r#""café naïve""#);
456    }
457
458    #[test]
459    fn v2_counts_every_exact_start_position_including_overlaps() {
460        assert_eq!(v2_candidates("aaa", "aa"), [(0, 2), (1, 3)]);
461        assert_eq!(v2_candidates("a-a-a", "a"), [(0, 1), (2, 3), (4, 5)]);
462        assert_eq!(v2_candidates("abc", "abc"), [(0, 3)]);
463        // Exact characters only: no lookalike reading, no whitespace folding.
464        assert!(v2_candidates("a\u{A0}b", "a b").is_empty());
465        assert!(v2_candidates("a  b", "a b").is_empty());
466        assert!(v2_candidates("\u{201C}x\u{201D}", "\"x\"").is_empty());
467        // Multi-byte anchors land on character boundaries.
468        assert_eq!(v2_candidates("ééé", "éé"), [(0, 4), (2, 6)]);
469        // Nothing to find, and an empty anchor has no candidates.
470        assert!(v2_candidates("abc", "z").is_empty());
471        assert!(v2_candidates("abc", "").is_empty());
472        assert!(v2_candidates("", "a").is_empty());
473        assert!(v2_candidates("a", "aa").is_empty());
474        assert!(v2_candidates("", "").is_empty());
475    }
476
477    #[test]
478    fn v2_selects_a_unique_anchor_and_refuses_with_the_count_when_repeated() {
479        assert_eq!(v2_select("a-a", "-", None).unwrap(), (1, 2));
480        let e = v2_select("aaa", "aa", None).unwrap_err();
481        assert_eq!(e.code, "AMBIGUOUS_ANCHOR");
482        assert_eq!(e.operation, None);
483        assert!(
484            e.message.contains("occurs 2 times")
485                && e.message.contains("set \"occurrence\" to 1..=2"),
486            "{}",
487            e.message
488        );
489        assert_eq!(
490            v2_select("abc", "z", None).unwrap_err().code,
491            "ANCHOR_NOT_FOUND"
492        );
493    }
494
495    #[test]
496    fn v2_occurrence_picks_the_nth_candidate_and_refuses_past_the_last() {
497        assert_eq!(v2_select("aaa", "aa", Some(1)).unwrap(), (0, 2));
498        assert_eq!(v2_select("aaa", "aa", Some(2)).unwrap(), (1, 3));
499        // A unique anchor takes occurrence 1.
500        assert_eq!(v2_select("abc", "b", Some(1)).unwrap(), (1, 2));
501        let e = v2_select("aaa", "aa", Some(3)).unwrap_err();
502        assert_eq!(e.code, "AMBIGUOUS_ANCHOR");
503        assert!(
504            e.message.contains("occurs 2 times") && e.message.contains("occurrence 3"),
505            "{}",
506            e.message
507        );
508        let e = v2_select("aaa", "aa", Some(0)).unwrap_err();
509        assert_eq!(e.code, "INVALID_EDIT");
510        assert!(e.message.contains("1-based"), "{}", e.message);
511    }
512
513    #[test]
514    fn v2_all_matches_takes_the_complete_disjoint_candidate_set() {
515        assert_eq!(
516            v2_select_all("a-a-a", "a", 3).unwrap(),
517            [(0, 1), (2, 3), (4, 5)]
518        );
519        // A wrong expected count reports the real one.
520        let e = v2_select_all("a-a-a", "a", 2).unwrap_err();
521        assert_eq!(e.code, "AMBIGUOUS_ANCHOR");
522        assert!(
523            e.message.contains("occurs 3 times") && e.message.contains("expected 2"),
524            "{}",
525            e.message
526        );
527        // Overlapping candidates are refused together, even at the right
528        // count: no disjoint subset is kept.
529        let e = v2_select_all("aaa", "aa", 2).unwrap_err();
530        assert_eq!(e.code, "OVERLAPPING_EDITS");
531        assert!(
532            e.message.contains("occurs 2 times") && e.message.contains("overlap"),
533            "{}",
534            e.message
535        );
536        assert_eq!(
537            v2_select_all("abc", "z", 1).unwrap_err().code,
538            "ANCHOR_NOT_FOUND"
539        );
540        assert_eq!(
541            v2_select_all("abc", "z", 0).unwrap_err().code,
542            "ANCHOR_NOT_FOUND"
543        );
544        // Touching ranges are disjoint, even when the anchor has several bytes.
545        assert_eq!(v2_select_all("éé", "é", 2).unwrap(), [(0, 2), (2, 4)]);
546        assert_eq!(
547            v2_select_all("aaaa", "aa", 3).unwrap_err().code,
548            "OVERLAPPING_EDITS"
549        );
550        // The expected count is checked against every candidate, never a subset.
551        let e = v2_select_all("aaaa", "aa", 2).unwrap_err();
552        assert_eq!(e.code, "AMBIGUOUS_ANCHOR");
553        assert!(e.message.contains("occurs 3 times"), "{}", e.message);
554        assert_eq!(v2_select_all("abc", "b", 1).unwrap(), [(1, 2)]);
555        assert_eq!(
556            v2_select_all("abc", "b", 0).unwrap_err().code,
557            "AMBIGUOUS_ANCHOR"
558        );
559    }
560
561    #[test]
562    fn v2_empty_anchor_is_an_invalid_edit() {
563        for refused in [
564            v2_select("abc", "", None).unwrap_err(),
565            v2_select("abc", "", Some(1)).unwrap_err(),
566            v2_select_all("abc", "", 1).unwrap_err(),
567        ] {
568            assert_eq!(refused.code, "INVALID_EDIT");
569            assert!(refused.message.contains("nonempty"), "{}", refused.message);
570        }
571    }
572
573    #[test]
574    fn v2_literal_anchors_preserve_exact_characters() {
575        for anchor in [
576            "a b", "a  b", "a\u{a0}b", "a\tb", "a\nb", "**x**", "e\u{301}", "é",
577        ] {
578            assert_eq!(v2_select(anchor, anchor, None).unwrap(), (0, anchor.len()));
579        }
580        for (text, anchor) in [
581            ("a\u{a0}b", "a b"),
582            ("a  b", "a b"),
583            ("a b", "a  b"),
584            ("a b", "a\u{a0}b"),
585            ("a\tb", "a b"),
586            ("a\nb", "a b"),
587            ("x", "**x**"),
588            ("é", "e\u{301}"),
589            ("e\u{301}", "é"),
590            ("a\u{200b}b", "ab"),
591            ("A", "a"),
592        ] {
593            assert_eq!(
594                v2_select(text, anchor, None).unwrap_err().code,
595                "ANCHOR_NOT_FOUND",
596                "{text:?}, {anchor:?}"
597            );
598        }
599    }
600
601    #[test]
602    fn v2_selection_uses_utf8_byte_ranges() {
603        for (occurrence, expected, range) in [(1, "Xé", (0, 4)), (2, "éX", (2, 6))] {
604            let mut text = String::from("ééé");
605            let (start, end) = v2_select(&text, "éé", Some(occurrence)).unwrap();
606            assert_eq!((start, end), range);
607            assert!(text.is_char_boundary(start) && text.is_char_boundary(end));
608            text.replace_range(start..end, "X");
609            assert_eq!(text, expected);
610        }
611        let e = v2_select_all("ééé", "éé", 2).unwrap_err();
612        assert_eq!(e.code, "OVERLAPPING_EDITS");
613        let mut text = String::from("a-a-a");
614        for (start, end) in v2_select_all(&text, "a", 3).unwrap().into_iter().rev() {
615            text.replace_range(start..end, "XX");
616        }
617        assert_eq!(text, "XX-XX-XX");
618    }
619
620    #[test]
621    fn v2_missing_anchors_refuse_with_zero_candidates() {
622        for e in [
623            v2_select("abc", "z", None).unwrap_err(),
624            v2_select("abc", "z", Some(1)).unwrap_err(),
625            v2_select_all("abc", "z", 0).unwrap_err(),
626            v2_select_all("abc", "z", 1).unwrap_err(),
627            v2_select("", "z", None).unwrap_err(),
628        ] {
629            assert_eq!(e.code, "ANCHOR_NOT_FOUND");
630            assert!(e.message.contains("0 times"), "{}", e.message);
631            assert_eq!(e.operation, None);
632            assert!(e.outcomes.is_empty());
633        }
634    }
635
636    #[test]
637    fn v2_zero_occurrence_is_invalid_even_without_candidates() {
638        for text in ["aaa", "", "bbb"] {
639            assert_eq!(
640                v2_select(text, "aa", Some(0)).unwrap_err().code,
641                "INVALID_EDIT"
642            );
643        }
644        let e = v2_select("abc", "b", Some(usize::MAX)).unwrap_err();
645        assert_eq!(e.code, "AMBIGUOUS_ANCHOR");
646        assert!(e.message.contains("occurs 1 times"), "{}", e.message);
647    }
648
649    /// The quadratic reference: `starts_with` re-scanned at every char
650    /// index. Kept private so the equivalence test can prove the new
651    /// linear search returns identical byte ranges on every fixture.
652    fn naive_v2_candidates(haystack: &str, anchor: &str) -> Vec<(usize, usize)> {
653        if anchor.is_empty() {
654            return Vec::new();
655        }
656        haystack
657            .char_indices()
658            .map(|(i, _)| i)
659            .filter(|&i| haystack[i..].starts_with(anchor))
660            .map(|i| (i, i + anchor.len()))
661            .collect()
662    }
663
664    #[test]
665    fn v2_overlapping_search_matches_naive_scan_on_a_deterministic_corpus() {
666        // Covers: overlaps, no overlap, multibyte, astral, touching
667        // ranges, empty, single char, anchor longer than text, multiple
668        // disjoint matches, anchor at the start / middle / end.
669        let corpus: &[(&str, &str)] = &[
670            // Overlaps.
671            ("aaa", "aa"),
672            ("aaaa", "aa"),
673            ("ababab", "abab"),
674            ("abcabcabc", "abcabc"),
675            // No overlap.
676            ("abc", "b"),
677            ("", "a"),
678            ("a", "aa"),
679            ("abc", ""),
680            ("", ""),
681            // Single-char matches, disjoint.
682            ("a-a-a", "a"),
683            ("xxxx", "x"),
684            // Multibyte anchors / haystacks.
685            ("ééé", "éé"),
686            ("ééé", "é"),
687            ("café", "fé"),
688            // Astral (4-byte UTF-8) anchors and haystacks.
689            ("𐀀𐀀𐀀", "𐀀𐀀"),
690            ("𐀀𐀀𐀀", "𐀀"),
691            // Touching ranges (disjoint, not overlap).
692            ("éé", "é"),
693            ("abcd", "ab"),
694            ("abcdef", "cd"),
695            // Anchor at start / middle / end.
696            ("abcabc", "abc"),
697            ("xyzabcxyz", "abc"),
698            ("abc", "abc"),
699            // Mixed multibyte + ASCII.
700            ("aébéc", "éb"),
701            // Repeated anchor with one-off shift.
702            ("abababab", "abab"),
703            // Long with no match.
704            ("the quick brown fox", "cat"),
705        ];
706        for &(text, anchor) in corpus {
707            assert_eq!(
708                v2_candidates(text, anchor),
709                naive_v2_candidates(text, anchor),
710                "text={text:?}, anchor={anchor:?}"
711            );
712        }
713    }
714
715    #[test]
716    fn v2_overlapping_search_probes_in_linear_time() {
717        // Pathological input: 200k of `a` against a 100k `a` anchor. The
718        // naive scan re-runs `starts_with` at every char index, so it
719        // performs ~2·10¹⁰ byte comparisons before deciding AMBIGUOUS.
720        // The linear search does at most `c·(n+m)` probes for a small
721        // constant `c`; the assertion would time out long before failing
722        // on the naive scan, so it gates the asymptotic improvement.
723        let n: usize = 200_000;
724        let m: usize = 100_000;
725        let haystack = "a".repeat(n);
726        let anchor = "a".repeat(m);
727        let before = ANCHOR_BYTE_PROBES.with(std::cell::Cell::get);
728        let hits = v2_candidates(&haystack, &anchor);
729        let probes = ANCHOR_BYTE_PROBES.with(std::cell::Cell::get) - before;
730        // Sanity: the result is the well-known all-overlapping match.
731        assert_eq!(hits.len(), n - m + 1);
732        assert_eq!(hits[0], (0, m));
733        assert_eq!(hits[hits.len() - 1], (n - m, n));
734        // Linear-time bound: a small constant times (n + m). The naive
735        // scan is Θ(n·m), which dwarfs any linear bound by ~5 orders.
736        const C: usize = 4;
737        assert!(
738            probes <= C * (n + m),
739            "linear search used {probes} probes for n={n}, m={m}; \
740             expected at most {bound}",
741            bound = C * (n + m)
742        );
743    }
744
745    #[test]
746    fn v2_overlap_message_states_the_condition_without_naming_a_flag() {
747        // The library error names the overlap condition itself, not a
748        // CLI flag. PlanV2 has no `all_matches` field; the message must
749        // remain intelligible for Python, WASM, and JSON callers.
750        let e = v2_select_all("aaa", "aa", 2).unwrap_err();
751        assert_eq!(e.code, "OVERLAPPING_EDITS");
752        assert!(
753            e.message.contains("occurs 2 times")
754                && e.message.contains("those ranges overlap")
755                && e.message.contains("so none of them is replaced"),
756            "{}",
757            e.message
758        );
759        assert!(
760            !e.message.contains("all-matches"),
761            "message must not name the CLI flag: {}",
762            e.message
763        );
764    }
765}