alma 0.1.1

A Bevy-native modal text editor with Vim-style navigation.
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
//! Validated UTF-8 byte stream storage and CRUD operations.

use bevy::prelude::Resource;
use std::{
    fmt::{Debug, Display, Formatter},
    ops::Range,
    str,
    sync::atomic::{AtomicU64, Ordering},
};

/// Process-local stream identity allocator.
static NEXT_STREAM_ID: AtomicU64 = AtomicU64::new(1);

/// Monotonic revision for a text stream snapshot.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct TextRevision(u64);

impl TextRevision {
    /// Initial stream revision.
    pub const ZERO: Self = Self(0);

    /// Returns the raw revision value for display or serialization.
    #[must_use]
    pub const fn get(self) -> u64 {
        self.0
    }

    /// Returns the next revision, failing closed at counter exhaustion.
    #[must_use]
    pub const fn next(self) -> Option<Self> {
        match self.0.checked_add(1) {
            Some(next) => Some(Self(next)),
            None => None,
        }
    }
}

impl Display for TextRevision {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.0, formatter)
    }
}

impl PartialEq<u64> for TextRevision {
    fn eq(&self, other: &u64) -> bool {
        self.0 == *other
    }
}

#[cfg(test)]
impl From<u64> for TextRevision {
    fn from(revision: u64) -> Self {
        Self(revision)
    }
}

/// Opaque identity for one text stream allocation.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct TextStreamId(u64);

impl TextStreamId {
    /// Allocates a fresh process-local stream identity.
    fn fresh() -> Self {
        Self(NEXT_STREAM_ID.fetch_add(1, Ordering::Relaxed))
    }
}

/// A validated UTF-8 byte stream used as the source of rendered text.
#[derive(Eq, Resource)]
pub struct TextByteStream {
    /// Text storage, kept as UTF-8 so Bevy can render it directly.
    text: String,
    /// Monotonic version counter for external caches and persistence.
    revision: TextRevision,
    /// Process-local identity used to scope validated range proofs.
    id: TextStreamId,
}

impl Debug for TextByteStream {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("TextByteStream")
            .field("shape", &TextByteStreamShape::from(self))
            .finish()
    }
}

impl Clone for TextByteStream {
    fn clone(&self) -> Self {
        Self {
            text: self.text.clone(),
            revision: self.revision,
            id: TextStreamId::fresh(),
        }
    }
}

impl Default for TextByteStream {
    fn default() -> Self {
        Self::new("")
    }
}

impl PartialEq for TextByteStream {
    fn eq(&self, other: &Self) -> bool {
        self.text == other.text && self.revision == other.revision
    }
}

/// Redacted stream diagnostic shape.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TextByteStreamShape {
    /// Stream length in bytes.
    byte_len: usize,
    /// Stream revision.
    revision: TextRevision,
    /// Process-local stream identity.
    id: TextStreamId,
}

impl TextByteStreamShape {
    /// Returns the stream byte length.
    #[must_use]
    pub const fn byte_len(self) -> usize {
        self.byte_len
    }

    /// Returns the stream revision.
    #[must_use]
    pub const fn revision(self) -> TextRevision {
        self.revision
    }

    /// Returns the stream identity.
    #[must_use]
    pub const fn id(self) -> TextStreamId {
        self.id
    }
}

impl From<&TextByteStream> for TextByteStreamShape {
    fn from(stream: &TextByteStream) -> Self {
        Self {
            byte_len: stream.as_bytes().len(),
            revision: stream.revision(),
            id: stream.id(),
        }
    }
}

/// An unvalidated byte range in editor text coordinates.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TextRange {
    /// Start byte index.
    start: usize,
    /// End byte index.
    end: usize,
}

impl TextRange {
    /// Creates a byte range that still needs validation against concrete text.
    #[must_use]
    pub const fn new(start: usize, end: usize) -> Self {
        Self { start, end }
    }

    /// Returns the start byte index.
    #[must_use]
    pub const fn start(self) -> usize {
        self.start
    }

    /// Returns the end byte index.
    #[must_use]
    pub const fn end(self) -> usize {
        self.end
    }

    /// Converts this range into Rust's standard range shape.
    #[must_use]
    pub const fn as_range(self) -> Range<usize> {
        self.start..self.end
    }
}

impl From<Range<usize>> for TextRange {
    fn from(range: Range<usize>) -> Self {
        Self {
            start: range.start,
            end: range.end,
        }
    }
}

/// A byte range proven valid for a specific text stream snapshot.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ValidatedTextRange {
    /// Validated byte range.
    range: TextRange,
    /// Stream identity against which the range was validated.
    stream_id: TextStreamId,
    /// Stream revision against which the range was validated.
    revision: TextRevision,
}

impl ValidatedTextRange {
    /// Creates a validated range after all stream invariants have been checked.
    const fn new(range: TextRange, stream_id: TextStreamId, revision: TextRevision) -> Self {
        Self {
            range,
            stream_id,
            revision,
        }
    }

    /// Returns the start byte index.
    #[must_use]
    pub const fn start(self) -> usize {
        self.range.start()
    }

    /// Returns the end byte index.
    #[must_use]
    pub const fn end(self) -> usize {
        self.range.end()
    }

    /// Returns the stream revision against which this range was validated.
    #[must_use]
    pub const fn revision(self) -> TextRevision {
        self.revision
    }

    /// Returns the stream identity against which this range was validated.
    #[must_use]
    pub const fn stream_id(self) -> TextStreamId {
        self.stream_id
    }

    /// Converts this range into Rust's standard range shape.
    #[must_use]
    pub const fn as_range(self) -> Range<usize> {
        self.range.as_range()
    }
}

impl TextByteStream {
    /// Creates a new text byte stream from valid UTF-8 text.
    #[must_use]
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            revision: TextRevision::ZERO,
            id: TextStreamId::fresh(),
        }
    }

    /// Creates a new text byte stream from raw UTF-8 bytes.
    ///
    /// # Errors
    ///
    /// Returns [`TextStreamError::InvalidUtf8`] when `bytes` are not valid UTF-8.
    pub fn from_bytes(bytes: Vec<u8>) -> Result<Self, TextStreamError> {
        String::from_utf8(bytes)
            .map(Self::new)
            .map_err(|error| TextStreamError::InvalidUtf8 {
                valid_up_to: error.utf8_error().valid_up_to(),
            })
    }

    /// Reads the stream as renderable UTF-8 text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.text
    }

    /// Reads the underlying UTF-8 bytes without allocation.
    #[must_use]
    pub const fn as_bytes(&self) -> &[u8] {
        self.text.as_bytes()
    }

    /// Returns the current stream revision.
    #[must_use]
    pub const fn revision(&self) -> TextRevision {
        self.revision
    }

    /// Returns this stream's opaque identity.
    #[must_use]
    pub const fn id(&self) -> TextStreamId {
        self.id
    }

    /// Replaces the entire stream with valid UTF-8 text.
    pub fn replace_all(&mut self, text: impl Into<String>) {
        self.text = text.into();
        self.bump_revision();
    }

    /// Replaces the entire stream with raw UTF-8 bytes.
    ///
    /// # Errors
    ///
    /// Returns [`TextStreamError::InvalidUtf8`] when `bytes` are not valid UTF-8.
    pub fn replace_all_bytes(&mut self, bytes: Vec<u8>) -> Result<(), TextStreamError> {
        self.text = String::from_utf8(bytes).map_err(|error| TextStreamError::InvalidUtf8 {
            valid_up_to: error.utf8_error().valid_up_to(),
        })?;
        self.bump_revision();
        Ok(())
    }

    /// Inserts valid UTF-8 text at a byte index.
    ///
    /// # Errors
    ///
    /// Returns [`TextStreamError`] when `byte_index` is out of bounds or not a UTF-8 character
    /// boundary.
    pub fn insert_str(&mut self, byte_index: usize, text: &str) -> Result<(), TextStreamError> {
        self.validate_boundary(byte_index)?;
        self.text.insert_str(byte_index, text);
        self.bump_revision();
        Ok(())
    }

    /// Inserts raw UTF-8 bytes at a byte index.
    ///
    /// # Errors
    ///
    /// Returns [`TextStreamError::InvalidUtf8`] when `bytes` are invalid UTF-8, or another
    /// [`TextStreamError`] when `byte_index` is out of bounds or not a UTF-8 character boundary.
    pub fn insert_bytes(&mut self, byte_index: usize, bytes: &[u8]) -> Result<(), TextStreamError> {
        let text = str::from_utf8(bytes).map_err(|error| TextStreamError::InvalidUtf8 {
            valid_up_to: error.valid_up_to(),
        })?;
        self.insert_str(byte_index, text)
    }

    /// Replaces a byte range with valid UTF-8 text.
    ///
    /// # Errors
    ///
    /// Returns [`TextStreamError`] when `range` is invalid, out of bounds, or not aligned to UTF-8
    /// character boundaries.
    pub fn replace_range(
        &mut self,
        range: Range<usize>,
        text: &str,
    ) -> Result<(), TextStreamError> {
        let range = self.validate_range(range)?;
        self.replace_validated_range(range, text)
    }

    /// Replaces a validated byte range with valid UTF-8 text.
    ///
    /// # Errors
    ///
    /// Returns [`TextStreamError::StaleValidatedRange`] when the stream revision has changed since
    /// the range was validated.
    pub fn replace_validated_range(
        &mut self,
        range: ValidatedTextRange,
        text: &str,
    ) -> Result<(), TextStreamError> {
        self.validate_range_revision(range)?;
        self.text.replace_range(range.as_range(), text);
        self.bump_revision();
        Ok(())
    }

    /// Replaces a byte range with raw UTF-8 bytes.
    ///
    /// # Errors
    ///
    /// Returns [`TextStreamError::InvalidUtf8`] when `bytes` are invalid UTF-8, or another
    /// [`TextStreamError`] when `range` is invalid, out of bounds, or not aligned to UTF-8
    /// character boundaries.
    pub fn replace_range_bytes(
        &mut self,
        range: Range<usize>,
        bytes: &[u8],
    ) -> Result<(), TextStreamError> {
        let text = str::from_utf8(bytes).map_err(|error| TextStreamError::InvalidUtf8 {
            valid_up_to: error.valid_up_to(),
        })?;
        self.replace_range(range, text)
    }

    /// Deletes a byte range.
    ///
    /// # Errors
    ///
    /// Returns [`TextStreamError`] when `range` is invalid, out of bounds, or not aligned to UTF-8
    /// character boundaries.
    pub fn delete_range(&mut self, range: Range<usize>) -> Result<(), TextStreamError> {
        self.replace_range(range, "")
    }

    /// Deletes a validated byte range.
    ///
    /// # Errors
    ///
    /// Returns [`TextStreamError::StaleValidatedRange`] when the stream revision has changed since
    /// the range was validated.
    pub fn delete_validated_range(
        &mut self,
        range: ValidatedTextRange,
    ) -> Result<(), TextStreamError> {
        self.replace_validated_range(range, "")
    }

    /// Clears the stream.
    pub fn clear(&mut self) {
        self.text.clear();
        self.bump_revision();
    }

    /// Advances the stream revision after a mutation.
    const fn bump_revision(&mut self) {
        self.revision = self
            .revision
            .next()
            .expect("text revision exhausted; refusing to wrap monotonic revision");
    }

    /// Validates one byte index against the current stream.
    fn validate_boundary(&self, index: usize) -> Result<(), TextStreamError> {
        if self.text.len() < index {
            return Err(TextStreamError::OutOfBounds {
                index,
                len: self.text.len(),
            });
        }

        if !self.text.is_char_boundary(index) {
            return Err(TextStreamError::NotCharBoundary { index });
        }

        Ok(())
    }

    /// Validates a byte range against the current stream.
    ///
    /// # Errors
    ///
    /// Returns [`TextStreamError`] when `range` is invalid, out of bounds, or not aligned to UTF-8
    /// character boundaries.
    pub fn validate_range(
        &self,
        range: impl Into<TextRange>,
    ) -> Result<ValidatedTextRange, TextStreamError> {
        let range = range.into();
        if range.end() < range.start() {
            return Err(TextStreamError::InvalidRange {
                start: range.start(),
                end: range.end(),
            });
        }

        self.validate_boundary(range.start())?;
        self.validate_boundary(range.end())?;
        Ok(ValidatedTextRange::new(range, self.id(), self.revision()))
    }

    /// Validates that a previously proven range still belongs to this stream snapshot.
    ///
    /// # Errors
    ///
    /// Returns [`TextStreamError::WrongTextStream`] when the range was validated against a
    /// different stream, or [`TextStreamError::StaleValidatedRange`] when this stream has changed
    /// since validation.
    pub fn validate_validated_range(
        &self,
        range: ValidatedTextRange,
    ) -> Result<ValidatedTextRange, TextStreamError> {
        if range.stream_id() != self.id() {
            return Err(TextStreamError::WrongTextStream {
                validated_stream: range.stream_id(),
                current_stream: self.id(),
            });
        }

        if range.revision() != self.revision() {
            return Err(TextStreamError::StaleValidatedRange {
                validated_revision: range.revision(),
                current_revision: self.revision(),
            });
        }

        Ok(range)
    }

    /// Validates that a previously proven range still belongs to this stream revision.
    fn validate_range_revision(&self, range: ValidatedTextRange) -> Result<(), TextStreamError> {
        let _range = self.validate_validated_range(range)?;
        Ok(())
    }
}

/// Errors returned by [`TextByteStream`] mutations.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum TextStreamError {
    /// Raw bytes were not valid UTF-8.
    InvalidUtf8 {
        /// The byte index up to which the input was valid UTF-8.
        valid_up_to: usize,
    },
    /// A byte index exceeded the stream length.
    OutOfBounds {
        /// The rejected byte index.
        index: usize,
        /// The current stream length in bytes.
        len: usize,
    },
    /// A byte index split a UTF-8 scalar value.
    NotCharBoundary {
        /// The rejected byte index.
        index: usize,
    },
    /// A byte range had its end before its start.
    InvalidRange {
        /// The start byte index.
        start: usize,
        /// The end byte index.
        end: usize,
    },
    /// A validated range was reused after the stream changed.
    StaleValidatedRange {
        /// Revision recorded by the validated range.
        validated_revision: TextRevision,
        /// Current stream revision.
        current_revision: TextRevision,
    },
    /// A validated range was reused with a different text stream.
    WrongTextStream {
        /// Stream identity recorded by the validated range.
        validated_stream: TextStreamId,
        /// Current stream identity.
        current_stream: TextStreamId,
    },
}

impl Display for TextStreamError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidUtf8 { valid_up_to } => {
                write!(formatter, "invalid UTF-8 after byte {valid_up_to}")
            }
            Self::OutOfBounds { index, len } => {
                write!(
                    formatter,
                    "byte index {index} is outside stream length {len}"
                )
            }
            Self::NotCharBoundary { index } => {
                write!(
                    formatter,
                    "byte index {index} is not a UTF-8 character boundary"
                )
            }
            Self::InvalidRange { start, end } => {
                write!(formatter, "invalid byte range {start}..{end}")
            }
            Self::StaleValidatedRange {
                validated_revision,
                current_revision,
            } => write!(
                formatter,
                "validated range from revision {validated_revision} cannot be applied to revision {current_revision}"
            ),
            Self::WrongTextStream {
                validated_stream,
                current_stream,
            } => write!(
                formatter,
                "validated range from stream {validated_stream:?} cannot be applied to stream {current_stream:?}"
            ),
        }
    }
}

/// Property tests for UTF-8 byte-stream CRUD operations.
#[cfg(test)]
mod tests {
    use super::{TextByteStream, TextRange, TextStreamError};
    use proptest::{
        prelude::{Strategy, any, proptest},
        prop_assert_eq,
    };

    /// Generates Unicode scalar values that occupy more than one UTF-8 byte.
    fn multibyte_char() -> impl Strategy<Value = char> {
        any::<char>().prop_filter("character must use multiple UTF-8 bytes", |character| {
            1 < character.len_utf8()
        })
    }

    #[test]
    fn validated_ranges_encode_stream_byte_invariants() {
        let stream = TextByteStream::new("aλb");

        let range = stream
            .validate_range(TextRange::new(1, 3))
            .expect("lambda range should be valid");

        assert_eq!(range.start(), 1);
        assert_eq!(range.end(), 3);
        assert_eq!(range.stream_id(), stream.id());
        assert_eq!(range.revision(), 0);
        assert_eq!(range.as_range(), 1..3);
        assert_eq!(
            stream.validate_range(TextRange::new(2, 3)),
            Err(TextStreamError::NotCharBoundary { index: 2 })
        );
        assert_eq!(
            stream.validate_range(TextRange::new(4, 3)),
            Err(TextStreamError::InvalidRange { start: 4, end: 3 })
        );
    }

    #[test]
    fn validated_ranges_are_revision_scoped() {
        let mut stream = TextByteStream::new("abc");
        let range = stream
            .validate_range(TextRange::new(1, 2))
            .expect("range should validate");
        stream.replace_all("aλc");

        assert_eq!(
            stream.delete_validated_range(range),
            Err(TextStreamError::StaleValidatedRange {
                validated_revision: 0.into(),
                current_revision: 1.into(),
            })
        );
        assert_eq!(stream.as_str(), "aλc");
    }

    #[test]
    fn validated_ranges_are_stream_scoped() {
        let source = TextByteStream::new("abcdef");
        let mut target = TextByteStream::new("λ");
        let range = source
            .validate_range(TextRange::new(1, 4))
            .expect("source range should validate");

        assert_eq!(
            target.delete_validated_range(range),
            Err(TextStreamError::WrongTextStream {
                validated_stream: source.id(),
                current_stream: target.id(),
            })
        );
        assert_eq!(target.as_str(), "λ");
        assert_eq!(target.revision(), 0);
    }

    proptest! {
        /// Replacing the whole stream round-trips arbitrary valid Unicode.
        #[test]
        fn replace_all_round_trips_arbitrary_unicode(input in any::<String>()) {
            let mut stream = TextByteStream::default();

            stream.replace_all(input.clone());

            prop_assert_eq!(stream.as_str(), input.as_str());
            prop_assert_eq!(stream.as_bytes(), input.as_bytes());
            prop_assert_eq!(stream.revision(), 1);
        }

        /// Creating from valid UTF-8 bytes round-trips arbitrary Unicode.
        #[test]
        fn from_bytes_accepts_valid_utf8(input in any::<String>()) {
            let stream = TextByteStream::from_bytes(input.clone().into_bytes());

            prop_assert_eq!(stream, Ok(TextByteStream::new(input)));
        }

        /// Inserting at a UTF-8 character boundary matches Rust's `String` model.
        #[test]
        fn insert_str_matches_string_model(
            prefix in any::<String>(),
            inserted in any::<String>(),
            suffix in any::<String>(),
        ) {
            let original = format!("{prefix}{suffix}");
            let expected = format!("{prefix}{inserted}{suffix}");
            let mut stream = TextByteStream::new(original);

            prop_assert_eq!(stream.insert_str(prefix.len(), inserted.as_str()), Ok(()));
            prop_assert_eq!(stream.as_str(), expected.as_str());
            prop_assert_eq!(stream.revision(), 1);
        }

        /// Replacing a UTF-8-aligned byte range matches Rust's `String` model.
        #[test]
        fn replace_range_matches_string_model(
            prefix in any::<String>(),
            removed in any::<String>(),
            suffix in any::<String>(),
            replacement in any::<String>(),
        ) {
            let original = format!("{prefix}{removed}{suffix}");
            let expected = format!("{prefix}{replacement}{suffix}");
            let range = prefix.len()..prefix.len() + removed.len();
            let mut stream = TextByteStream::new(original);

            prop_assert_eq!(stream.replace_range(range, replacement.as_str()), Ok(()));
            prop_assert_eq!(stream.as_str(), expected.as_str());
            prop_assert_eq!(stream.revision(), 1);
        }

        /// Deleting a UTF-8-aligned byte range matches Rust's `String` model.
        #[test]
        fn delete_range_matches_string_model(
            prefix in any::<String>(),
            removed in any::<String>(),
            suffix in any::<String>(),
        ) {
            let original = format!("{prefix}{removed}{suffix}");
            let expected = format!("{prefix}{suffix}");
            let range = prefix.len()..prefix.len() + removed.len();
            let mut stream = TextByteStream::new(original);

            prop_assert_eq!(stream.delete_range(range), Ok(()));
            prop_assert_eq!(stream.as_str(), expected.as_str());
            prop_assert_eq!(stream.revision(), 1);
        }

        /// Byte-range edits reject indices that split a Unicode scalar.
        #[test]
        fn delete_range_rejects_split_scalar(
            prefix in any::<String>(),
            character in multibyte_char(),
        ) {
            let mut stream = TextByteStream::new(format!("{prefix}{character}"));
            let split_index = prefix.len() + 1;

            prop_assert_eq!(
                stream.delete_range(split_index..split_index),
                Err(TextStreamError::NotCharBoundary { index: split_index }),
            );
            prop_assert_eq!(stream.revision(), 0);
        }

        /// Raw byte insertion matches string insertion when bytes are valid UTF-8.
        #[test]
        fn insert_bytes_matches_string_model(
            prefix in any::<String>(),
            inserted in any::<String>(),
            suffix in any::<String>(),
        ) {
            let original = format!("{prefix}{suffix}");
            let expected = format!("{prefix}{inserted}{suffix}");
            let mut stream = TextByteStream::new(original);

            prop_assert_eq!(stream.insert_bytes(prefix.len(), inserted.as_bytes()), Ok(()));
            prop_assert_eq!(stream.as_str(), expected.as_str());
        }
    }

    /// Creating a stream from invalid bytes fails without lossy conversion.
    #[test]
    fn from_bytes_rejects_invalid_utf8() {
        assert_eq!(
            TextByteStream::from_bytes(vec![0x66, 0x80]),
            Err(TextStreamError::InvalidUtf8 { valid_up_to: 1 })
        );
    }

    #[test]
    fn debug_output_redacts_stream_text() {
        let stream = TextByteStream::new("secret buffer text");
        let debug = format!("{stream:?}");

        assert!(debug.contains("TextByteStream"));
        assert!(debug.contains("byte_len"));
        assert!(!debug.contains("secret"));
        assert!(!debug.contains("buffer text"));
    }

    /// Newline bytes remain literal stream data for Bevy layout.
    #[test]
    fn newline_remains_layout_data() {
        let mut stream = TextByteStream::new("ALMA");

        assert_eq!(stream.insert_str(4, "\nΑλμα"), Ok(()));
        assert_eq!(stream.as_str(), "ALMA\nΑλμα");
    }
}