mago-text-edit 1.40.2

A text editing library for Mago
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
/// Represents the safety of applying a specific edit.
///
/// Ordered from most safe to least safe.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
#[derive(Default)]
#[non_exhaustive]
pub enum Safety {
    /// Safe to apply automatically. The semantic meaning of the code is preserved.
    /// Example: Formatting, renaming a local variable.
    #[default]
    Safe,
    /// Likely safe, but changes semantics slightly or relies on heuristics.
    /// Example: Removing an unused variable (might have side effects in constructor).
    PotentiallyUnsafe,
    /// Requires manual user review. Valid code, but changes logic significantly.
    /// Example: Changing type casts, altering control flow logic.
    Unsafe,
}

/// Represents a range in the source text identified by byte offsets.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TextRange {
    pub start: u32,
    pub end: u32,
}

impl TextRange {
    #[inline(always)]
    #[must_use]
    pub fn new(start: u32, end: u32) -> Self {
        Self { start, end }
    }

    /// Returns the length of the range in bytes.
    #[inline(always)]
    #[must_use]
    pub fn len(&self) -> u32 {
        self.end - self.start
    }

    /// Returns true if the range has a length of zero.
    #[inline(always)]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.start == self.end
    }

    /// Checks if this range overlaps with another.
    ///
    /// Two ranges conflict only when they share byte positions; i.e. when
    /// applying both would write the same byte twice or write into bytes the
    /// other is deleting. Adjacency at a boundary is fine:
    ///
    /// - Adjacent non-empty ranges (e.g. `0..5` and `5..10`) do not overlap;
    ///   they replace different bytes.
    /// - Two empty ranges at the same offset stack in insertion order; they
    ///   each write their own bytes without touching the other's.
    /// - An empty range at the exact boundary of a non-empty one (e.g. an
    ///   insert at `5` with a replace of `5..10`, or an insert at `10` with
    ///   a replace of `5..10`) does not overlap; the stitcher resolves the
    ///   order deterministically (insert-at-start goes before replacement;
    ///   insert-at-end goes after).
    ///
    /// Only *interior* containment of an empty range inside a non-empty one
    /// is treated as overlap, as is any interior overlap between two
    /// non-empty ranges.
    #[inline(always)]
    #[must_use]
    #[allow(clippy::suspicious_operation_groupings)]
    pub fn overlaps(&self, other: &TextRange) -> bool {
        match (self.is_empty(), other.is_empty()) {
            (true, true) => false,
            (true, false) => self.start > other.start && self.start < other.end,
            (false, true) => other.start > self.start && other.start < self.end,
            (false, false) => self.start < other.end && other.start < self.end,
        }
    }

    /// Checks if this range contains a specific offset.
    #[inline(always)]
    #[must_use]
    pub fn contains(&self, offset: u32) -> bool {
        offset >= self.start && offset < self.end
    }
}

impl<T> From<T> for TextRange
where
    T: std::ops::RangeBounds<u32>,
{
    #[inline(always)]
    fn from(r: T) -> Self {
        let start = match r.start_bound() {
            std::ops::Bound::Included(&s) => s,
            std::ops::Bound::Excluded(&s) => s + 1,
            std::ops::Bound::Unbounded => 0,
        };

        let end = match r.end_bound() {
            std::ops::Bound::Included(&e) => e + 1,
            std::ops::Bound::Excluded(&e) => e,
            std::ops::Bound::Unbounded => u32::MAX, // Will fail bounds check later
        };

        Self::new(start, end)
    }
}

/// A unified atomic edit operation.
///
/// This struct holds the data for a modification but does not execute it.
/// It always refers to the byte offsets in the **ORIGINAL** source code.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TextEdit {
    /// The range in the original text to be replaced.
    pub range: TextRange,
    /// The new text to replace the range with.
    pub new_text: Vec<u8>,
    /// How safe this specific edit is.
    pub safety: Safety,
}

impl TextEdit {
    /// Creates a delete edit (defaults to Safe).
    #[inline]
    #[must_use]
    pub fn delete(range: impl Into<TextRange>) -> Self {
        Self { range: range.into(), new_text: Vec::new(), safety: Safety::Safe }
    }

    /// Creates an insert edit (defaults to Safe).
    #[inline]
    #[must_use]
    pub fn insert(offset: u32, text: impl Into<Vec<u8>>) -> Self {
        Self { range: TextRange::new(offset, offset), new_text: text.into(), safety: Safety::Safe }
    }

    /// Creates a replace edit (defaults to Safe).
    #[inline]
    #[must_use]
    pub fn replace(range: impl Into<TextRange>, text: impl Into<Vec<u8>>) -> Self {
        Self { range: range.into(), new_text: text.into(), safety: Safety::Safe }
    }

    /// Builder method to change the safety level of this edit.
    ///
    /// # Example
    /// ```
    /// use mago_text_edit::{TextEdit, Safety};
    ///
    /// let edit = TextEdit::replace(1..2, "b").with_safety(Safety::Unsafe);
    /// assert_eq!(edit.safety, Safety::Unsafe);
    /// ```
    #[inline]
    #[must_use]
    pub fn with_safety(mut self, safety: Safety) -> Self {
        self.safety = safety;
        self
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum ApplyResult {
    /// The edits were successfully applied.
    Applied,
    /// The edits were invalid (e.g., start > end or > file length).
    OutOfBounds,
    /// The edits overlapped with previously confirmed edits or each other.
    Overlap,
    /// The provided checker function returned `false`.
    Rejected,
    /// Edit rejected because it's unsafe and we're in safe or potentially-unsafe mode.
    Unsafe,
    /// Edit rejected because it's potentially-unsafe and we're in safe mode.
    PotentiallyUnsafe,
}

/// A high-performance, transactional text editor.
///
/// It accumulates edits and applies them in a single pass when `finish()` is called.
/// It ensures all edits are valid, non-overlapping, and safe according to optional user checks.
#[derive(Debug, Clone)]
pub struct TextEditor<'src> {
    original_text: &'src [u8],
    original_len: u32,
    edits: Vec<TextEdit>,
    safety_threshold: Safety,
}

impl<'src> TextEditor<'src> {
    /// Creates a new TextEditor with the default safety threshold (Unsafe - accepts all edits).
    #[inline]
    #[must_use]
    pub fn new(text: &'src [u8]) -> Self {
        Self {
            original_text: text,
            original_len: text.len() as u32,
            edits: Vec::new(),
            safety_threshold: Safety::Unsafe,
        }
    }

    /// Creates a new TextEditor with a specific safety threshold.
    ///
    /// Edits with a safety level above the threshold will be rejected.
    ///
    /// # Example
    /// ```
    /// use mago_text_edit::{TextEditor, Safety};
    ///
    /// // Only accept Safe edits
    /// let editor = TextEditor::with_safety(b"hello", Safety::Safe);
    /// ```
    #[inline]
    #[must_use]
    pub fn with_safety(text: &'src [u8], threshold: Safety) -> Self {
        Self { original_text: text, original_len: text.len() as u32, edits: Vec::new(), safety_threshold: threshold }
    }

    /// Checks if an edit's safety level exceeds the threshold.
    /// Returns the appropriate rejection result, or None if the edit is acceptable.
    #[inline]
    fn check_safety(&self, edit_safety: Safety) -> Option<ApplyResult> {
        if edit_safety > self.safety_threshold {
            Some(match edit_safety {
                Safety::Unsafe => ApplyResult::Unsafe,
                Safety::PotentiallyUnsafe => ApplyResult::PotentiallyUnsafe,
                Safety::Safe => ApplyResult::Unsafe,
            })
        } else {
            None
        }
    }

    /// Applies a single edit.
    ///
    /// Uses binary search to check for overlaps in O(log N).
    /// Rejects edits that exceed the safety threshold.
    #[inline]
    pub fn apply<F>(&mut self, edit: TextEdit, checker: Option<F>) -> ApplyResult
    where
        F: FnOnce(&[u8]) -> bool,
    {
        // Check safety first
        if let Some(rejection) = self.check_safety(edit.safety) {
            return rejection;
        }

        if edit.range.end > self.original_len || edit.range.start > edit.range.end {
            return ApplyResult::OutOfBounds;
        }

        let search_idx = self.edits.partition_point(|e| e.range.end <= edit.range.start);

        if let Some(existing) = self.edits.get(search_idx)
            && existing.range.overlaps(&edit.range)
        {
            return ApplyResult::Overlap;
        }

        if let Some(check_fn) = checker {
            let simulated_str = stitch_one(self.original_text, &self.edits, &edit);
            if !check_fn(&simulated_str) {
                return ApplyResult::Rejected;
            }
        }

        self.edits.insert(search_idx, edit);

        ApplyResult::Applied
    }

    /// Applies a batch of edits atomically.
    ///
    /// Either all edits are applied, or none are (if overlap/check/safety fails).
    /// If any edit in the batch exceeds the safety threshold, the entire batch is rejected.
    #[inline]
    pub fn apply_batch<F>(&mut self, mut new_edits: Vec<TextEdit>, checker: Option<F>) -> ApplyResult
    where
        F: FnOnce(&[u8]) -> bool,
    {
        if new_edits.is_empty() {
            return ApplyResult::Applied;
        }

        // Check safety of all edits first
        for edit in &new_edits {
            if let Some(rejection) = self.check_safety(edit.safety) {
                return rejection;
            }
        }

        new_edits.sort_by(|a, b| a.range.start.cmp(&b.range.start).then_with(|| a.range.end.cmp(&b.range.end)));

        for i in 0..new_edits.len() {
            let edit = &new_edits[i];

            if edit.range.end > self.original_len || edit.range.start > edit.range.end {
                return ApplyResult::OutOfBounds;
            }

            if i > 0 && new_edits[i - 1].range.overlaps(&edit.range) {
                return ApplyResult::Overlap;
            }
        }

        {
            let mut old_iter = self.edits.iter();
            let mut new_iter = new_edits.iter();
            let mut next_old = old_iter.next();
            let mut next_new = new_iter.next();

            while let (Some(old), Some(new)) = (next_old, next_new) {
                if old.range.overlaps(&new.range) {
                    return ApplyResult::Overlap;
                }
                if old.range.start < new.range.start {
                    next_old = old_iter.next();
                } else {
                    next_new = new_iter.next();
                }
            }
        }

        if let Some(check_fn) = checker {
            let simulated_str = stitch_merged(self.original_text, &self.edits, &new_edits);
            if !check_fn(&simulated_str) {
                return ApplyResult::Rejected;
            }
        }

        self.edits.reserve(new_edits.len());
        self.edits.extend(new_edits);
        self.edits.sort_by(|a, b| a.range.start.cmp(&b.range.start).then_with(|| a.range.end.cmp(&b.range.end)));

        ApplyResult::Applied
    }

    /// Consumes the editor and returns the final modified string.
    #[inline]
    #[must_use]
    pub fn finish(self) -> Vec<u8> {
        stitch(self.original_text, &self.edits)
    }

    /// Returns a slice of the currently applied edits.
    #[inline]
    #[must_use]
    pub fn get_edits(&self) -> &[TextEdit] {
        &self.edits
    }

    /// Returns the current safety threshold.
    #[inline]
    #[must_use]
    pub fn safety_threshold(&self) -> Safety {
        self.safety_threshold
    }
}

/// Standard stitching of a sorted list.
/// Calculates exact capacity first to guarantee exactly 1 allocation.
fn stitch(original: &[u8], edits: &[TextEdit]) -> Vec<u8> {
    let mut final_len = original.len();
    for edit in edits {
        final_len = final_len.saturating_sub(edit.range.len() as usize).saturating_add(edit.new_text.len());
    }

    let mut output = Vec::with_capacity(final_len);
    let mut last_processed = 0;

    for edit in edits {
        let start = edit.range.start as usize;
        let end = edit.range.end as usize;

        if start > last_processed {
            output.extend_from_slice(&original[last_processed..start]);
        }
        output.extend_from_slice(&edit.new_text);
        last_processed = end;
    }

    if last_processed < original.len() {
        output.extend_from_slice(&original[last_processed..]);
    }

    output
}

/// Simulation for a single new edit (avoids creating a new vector).
fn stitch_one(original: &[u8], existing_edits: &[TextEdit], new_edit: &TextEdit) -> Vec<u8> {
    let slice = std::slice::from_ref(new_edit);
    stitch_merged(original, existing_edits, slice)
}

/// Simulation for merging two sorted lists of edits without mutating the original.
/// Used by the checker to verify validity before committing.
fn stitch_merged(original: &[u8], old_edits: &[TextEdit], new_edits: &[TextEdit]) -> Vec<u8> {
    let mut final_len = original.len();
    for e in old_edits {
        final_len = final_len - e.range.len() as usize + e.new_text.len();
    }
    for e in new_edits {
        final_len = final_len - e.range.len() as usize + e.new_text.len();
    }

    let mut output = Vec::with_capacity(final_len);
    let mut last_processed = 0;

    let mut old_iter = old_edits.iter();
    let mut new_iter = new_edits.iter();
    let mut next_old = old_iter.next();
    let mut next_new = new_iter.next();

    loop {
        let next_edit = match (next_old, next_new) {
            (Some(o), Some(n)) => {
                if (o.range.start, o.range.end) <= (n.range.start, n.range.end) {
                    next_old = old_iter.next();
                    o
                } else {
                    next_new = new_iter.next();
                    n
                }
            }
            (Some(o), None) => {
                next_old = old_iter.next();
                o
            }
            (None, Some(n)) => {
                next_new = new_iter.next();
                n
            }
            (None, None) => break,
        };

        let start = next_edit.range.start as usize;
        let end = next_edit.range.end as usize;

        if start > last_processed {
            output.extend_from_slice(&original[last_processed..start]);
        }
        output.extend_from_slice(&next_edit.new_text);
        last_processed = end;
    }

    if last_processed < original.len() {
        output.extend_from_slice(&original[last_processed..]);
    }

    output
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_apply_single() {
        let mut editor = TextEditor::new(b"hello world");
        editor.apply(TextEdit::replace(0..5, "hi"), None::<fn(&[u8]) -> bool>);
        assert_eq!(editor.finish(), b"hi world");
    }

    #[test]
    fn test_checker_fail() {
        let mut editor = TextEditor::new(b"abc");
        // Fail if length of result > 10 (it won't be, so this passes check logic is inverted? No.)
        // Checker logic: return TRUE if valid.
        let res = editor.apply(TextEdit::delete(0..1), Some(|s: &[u8]| s.len() > 10));
        // "bc" len is 2. 2 > 10 is false. Checker returns false.
        assert_eq!(res, ApplyResult::Rejected);
        assert_eq!(editor.finish(), b"abc"); // Unchanged
    }

    #[test]
    fn test_overlap_search() {
        let mut editor = TextEditor::new(b"0123456789");
        editor.apply(TextEdit::replace(2..4, "x"), None::<fn(&[u8]) -> bool>); // 2,3

        // Try edit at 3..5 (Overlaps 2..4)
        assert_eq!(editor.apply(TextEdit::replace(3..5, "y"), None::<fn(&[u8]) -> bool>), ApplyResult::Overlap);

        // Try edit at 1..3 (Overlaps 2..4)
        assert_eq!(editor.apply(TextEdit::replace(1..3, "y"), None::<fn(&[u8]) -> bool>), ApplyResult::Overlap);

        // Try edit at 4..5 (Safe)
        assert_eq!(editor.apply(TextEdit::replace(4..5, "y"), None::<fn(&[u8]) -> bool>), ApplyResult::Applied);

        assert_eq!(editor.finish(), b"01xy56789");
    }

    #[test]
    fn test_batch_apply_ordering() {
        let mut editor = TextEditor::new(b"abcdef");

        // Batch with mixed order inputs
        let batch = vec![
            TextEdit::replace(4..5, "E"), // e -> E
            TextEdit::replace(0..1, "A"), // a -> A
        ];

        editor.apply_batch(batch, None::<fn(&[u8]) -> bool>);
        assert_eq!(editor.finish(), b"AbcdEf");
    }

    #[test]
    fn test_safety_default_is_safe() {
        let edit = TextEdit::replace(0..1, b"x");
        assert_eq!(edit.safety, Safety::Safe);
    }

    #[test]
    fn test_with_safety_builder() {
        let edit = TextEdit::replace(0..1, b"x").with_safety(Safety::Unsafe);
        assert_eq!(edit.safety, Safety::Unsafe);

        let edit = TextEdit::delete(0..1).with_safety(Safety::PotentiallyUnsafe);
        assert_eq!(edit.safety, Safety::PotentiallyUnsafe);
    }

    #[test]
    fn test_safety_threshold_safe_mode() {
        let mut editor = TextEditor::with_safety(b"hello world", Safety::Safe);

        // Safe edit should be accepted
        let res = editor.apply(TextEdit::replace(0..5, b"hi"), None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Applied);

        // PotentiallyUnsafe edit should be rejected
        let res = editor.apply(
            TextEdit::replace(6..11, b"there").with_safety(Safety::PotentiallyUnsafe),
            None::<fn(&[u8]) -> bool>,
        );
        assert_eq!(res, ApplyResult::PotentiallyUnsafe);

        // Unsafe edit should be rejected
        let res =
            editor.apply(TextEdit::replace(6..11, b"there").with_safety(Safety::Unsafe), None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Unsafe);

        assert_eq!(editor.finish(), b"hi world"); // Only safe edit applied
    }

    #[test]
    fn test_safety_threshold_potentially_unsafe_mode() {
        let mut editor = TextEditor::with_safety(b"hello world", Safety::PotentiallyUnsafe);

        // Safe edit should be accepted
        let res = editor.apply(TextEdit::replace(0..5, "hi"), None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Applied);

        // PotentiallyUnsafe edit should be accepted
        let res = editor
            .apply(TextEdit::replace(6..11, "there").with_safety(Safety::PotentiallyUnsafe), None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Applied);

        assert_eq!(editor.finish(), b"hi there");
    }

    #[test]
    fn test_safety_threshold_unsafe_mode() {
        let mut editor = TextEditor::with_safety(b"hello world", Safety::Unsafe);

        // All safety levels should be accepted
        let res = editor.apply(TextEdit::replace(0..1, b"H"), None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Applied);

        let res = editor
            .apply(TextEdit::replace(1..2, b"E").with_safety(Safety::PotentiallyUnsafe), None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Applied);

        let res = editor.apply(TextEdit::replace(2..3, b"L").with_safety(Safety::Unsafe), None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Applied);

        assert_eq!(editor.finish(), b"HELlo world");
    }

    #[test]
    fn test_batch_safety_rejection() {
        let mut editor = TextEditor::with_safety(b"hello", Safety::Safe);

        // Batch with one unsafe edit should reject entire batch
        let batch = vec![
            TextEdit::replace(0..1, "H"),                             // Safe
            TextEdit::replace(1..2, "E").with_safety(Safety::Unsafe), // Unsafe - should cause rejection
        ];

        let res = editor.apply_batch(batch, None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Unsafe);

        // Original text unchanged
        assert_eq!(editor.finish(), b"hello");
    }

    #[test]
    fn test_safety_ordering() {
        // Test that Safety enum orders correctly (Safe < PotentiallyUnsafe < Unsafe)
        assert!(Safety::Safe < Safety::PotentiallyUnsafe);
        assert!(Safety::PotentiallyUnsafe < Safety::Unsafe);
        assert!(Safety::Safe < Safety::Unsafe);
    }

    #[test]
    fn test_insert_at_start_of_replace_applies_before_replacement() {
        let mut editor = TextEditor::new(b"0123456789");

        let res = editor.apply(TextEdit::replace(2..8, "replaced"), None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Applied);

        let res = editor.apply(TextEdit::insert(2, "inserted"), None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Applied);

        assert_eq!(editor.finish(), b"01insertedreplaced89");
    }

    #[test]
    fn test_insert_after_replace_at_different_offset() {
        let mut editor = TextEditor::new(b"0123456789");

        let res = editor.apply(TextEdit::replace(2..5, "ABC"), None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Applied);

        let res = editor.apply(TextEdit::insert(6, "X"), None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Applied);

        assert_eq!(editor.finish(), b"01ABC5X6789");
    }

    #[test]
    fn test_insert_at_start_of_replace_coexists() {
        let mut editor = TextEditor::new(b"0123456789");

        let res = editor.apply(TextEdit::replace(2..5, "ABC"), None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Applied);

        let res = editor.apply(TextEdit::insert(2, "X"), None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Applied);

        assert_eq!(editor.finish(), b"01XABC56789");
    }

    #[test]
    fn test_batch_insert_and_replace_at_same_offset_coexist() {
        let mut editor = TextEditor::new(b"0123456789");

        let batch = vec![
            TextEdit::insert(2, "inserted"), // insert at 2
            TextEdit::replace(2..5, "ABC"),  // replace starting at 2
        ];

        let res = editor.apply_batch(batch, None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Applied);

        assert_eq!(editor.finish(), b"01insertedABC56789");
    }

    #[test]
    fn test_multiple_inserts_at_same_offset_stack_in_insertion_order() {
        let mut editor = TextEditor::new(b"ABC");
        let batch = vec![TextEdit::insert(0, "X"), TextEdit::insert(0, "Y"), TextEdit::insert(0, "Z")];
        let res = editor.apply_batch(batch, None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Applied);
        assert_eq!(editor.finish(), b"XYZABC");
    }

    #[test]
    fn test_insert_at_end_of_replace_applies_after_replacement() {
        let mut editor = TextEditor::new(b"0123456789");
        let res = editor.apply(TextEdit::replace(2..5, "ABC"), None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Applied);
        let res = editor.apply(TextEdit::insert(5, "X"), None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Applied);
        assert_eq!(editor.finish(), b"01ABCX56789");
    }

    #[test]
    fn test_insert_inside_replace_overlaps() {
        let mut editor = TextEditor::new(b"0123456789");
        let res = editor.apply(TextEdit::replace(2..8, "ABCDEF"), None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Applied);
        let res = editor.apply(TextEdit::insert(5, "X"), None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Overlap);
    }

    #[test]
    fn test_issue_828_regression_both_edits_apply_correctly() {
        let mut editor = TextEditor::new(b"function ($v) { return $v; }");
        let batch = vec![TextEdit::insert(0, "static "), TextEdit::replace(0..8, "fn")];
        let res = editor.apply_batch(batch, None::<fn(&[u8]) -> bool>);
        assert_eq!(res, ApplyResult::Applied);
        assert_eq!(editor.finish(), b"static fn ($v) { return $v; }");
    }

    #[test]
    fn test_checker_simulation_matches_final_output_for_stacked_inserts() {
        let mut editor = TextEditor::new(b"ABC");
        editor.apply(TextEdit::insert(0, b"X"), None::<fn(&[u8]) -> bool>);

        let simulated: std::cell::RefCell<Option<Vec<u8>>> = std::cell::RefCell::new(None);
        let checker = |s: &[u8]| {
            *simulated.borrow_mut() = Some(s.to_vec());
            true
        };
        let batch = vec![TextEdit::insert(0, b"Y")];
        assert_eq!(editor.apply_batch(batch, Some(checker)), ApplyResult::Applied);

        #[allow(clippy::expect_used)]
        let simulated = simulated.borrow().clone().expect("checker called");
        let final_str = editor.finish();
        assert_eq!(simulated, final_str);
        assert_eq!(final_str, b"XYABC");
    }

    #[test]
    fn test_touching_non_empty_ranges_do_not_overlap() {
        let range1 = TextRange::new(0, 5);
        let range2 = TextRange::new(5, 10);
        assert!(!range1.overlaps(&range2));
        assert!(!range2.overlaps(&range1));
    }

    #[test]
    fn test_insert_at_boundary_of_replace_does_not_overlap() {
        let insert_at_start = TextRange::new(5, 5);
        let insert_at_end = TextRange::new(10, 10);
        let replace_range = TextRange::new(5, 10);
        assert!(!insert_at_start.overlaps(&replace_range));
        assert!(!replace_range.overlaps(&insert_at_start));
        assert!(!insert_at_end.overlaps(&replace_range));
        assert!(!replace_range.overlaps(&insert_at_end));
    }

    #[test]
    fn test_insert_inside_non_empty_range_overlaps() {
        let insert = TextRange::new(7, 7);
        let replace = TextRange::new(5, 10);
        assert!(insert.overlaps(&replace));
        assert!(replace.overlaps(&insert));
    }

    #[test]
    fn test_two_empty_ranges_at_same_offset_do_not_overlap() {
        let a = TextRange::new(5, 5);
        let b = TextRange::new(5, 5);
        assert!(!a.overlaps(&b));
        assert!(!b.overlaps(&a));
    }
}