smol-bytes 0.2.0

High-performance, clone-efficient byte buffers optimized for small data.
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
use core::{borrow::Borrow, ops::RangeBounds, str};

use super::{
  buffer::Buffer,
  error::*,
  utf8_buf::{Utf8Buf, Utf8BufMut, range_bounds_to_start_end, sealed, validate_char_boundary},
  utf8_drain::Utf8Drain,
  utf8_edit::{RawUtf8Storage, RetainGuard, replace_bytes as raw_replace_bytes},
};

mod cmp;
mod fmt;
mod from;
mod ops;

#[cfg(feature = "arbitrary")]
mod arbitrary;
#[cfg(feature = "borsh")]
mod borsh;
#[cfg(all(feature = "quickcheck", any(feature = "std", feature = "alloc")))]
mod quickcheck;
#[cfg(feature = "serde")]
mod serde;

#[cfg(feature = "pyo3")]
mod python;

#[cfg(feature = "wasm")]
mod wasm;

#[doc = "UTF-8 validated wrapper around `Buffer` with a String-like interface."]
#[doc = ""]
#[doc = "Guarantees valid UTF-8. Split/slice operations check char boundaries."]
#[doc = "Fixed inline capacity of 62 bytes."]
#[cfg_attr(not(feature = "wasm"), doc = "")]
#[cfg_attr(not(feature = "wasm"), doc = "# Examples")]
#[cfg_attr(not(feature = "wasm"), doc = "")]
#[cfg_attr(not(feature = "wasm"), doc = "```")]
#[cfg_attr(not(feature = "wasm"), doc = "use smol_bytes::Utf8Buffer;")]
#[cfg_attr(not(feature = "wasm"), doc = "")]
#[cfg_attr(not(feature = "wasm"), doc = "let mut buf = Utf8Buffer::new();")]
#[cfg_attr(not(feature = "wasm"), doc = "buf.push_str(\"Hello\");")]
#[cfg_attr(not(feature = "wasm"), doc = "buf.push(' ');")]
#[cfg_attr(not(feature = "wasm"), doc = "buf.push_str(\"world!\");")]
#[cfg_attr(
  not(feature = "wasm"),
  doc = "assert_eq!(buf.as_str(), \"Hello world!\");"
)]
#[cfg_attr(not(feature = "wasm"), doc = "```")]
#[cfg_attr(feature = "wasm", doc = "")]
#[cfg_attr(feature = "wasm", doc = "@example")]
#[cfg_attr(feature = "wasm", doc = "```typescript")]
#[cfg_attr(feature = "wasm", doc = "import { Utf8Buffer } from 'smol-bytes';")]
#[cfg_attr(feature = "wasm", doc = "const buf = new Utf8Buffer();")]
#[cfg_attr(feature = "wasm", doc = "buf.pushStr('hello world');")]
#[cfg_attr(
  feature = "wasm",
  doc = "console.log(buf.toString()); // 'hello world'"
)]
#[cfg_attr(feature = "wasm", doc = "```")]
#[derive(Clone, Copy)]
#[cfg_attr(feature = "pyo3", ::pyo3::prelude::pyclass)]
#[cfg_attr(feature = "wasm", wasm_bindgen::prelude::wasm_bindgen)]
pub struct Utf8Buffer {
  inner: Buffer,
}

impl Default for Utf8Buffer {
  #[cfg_attr(not(coverage), inline(always))]
  fn default() -> Self {
    Self::new()
  }
}

impl sealed::Sealed for Utf8Buffer {}

impl core::fmt::Write for Utf8Buffer {
  fn write_str(&mut self, s: &str) -> core::fmt::Result {
    self.try_push_str(s).map_err(|_| core::fmt::Error)
  }
}

struct FormatWriteAdapter<'a> {
  candidate: &'a mut Utf8Buffer,
  capacity_error: Option<TryPutError>,
}

impl core::fmt::Write for FormatWriteAdapter<'_> {
  fn write_str(&mut self, s: &str) -> core::fmt::Result {
    match self.candidate.try_push_str(s) {
      Ok(()) => Ok(()),
      Err(error) => {
        if self.capacity_error.is_none() {
          self.capacity_error = Some(error);
        }
        Err(core::fmt::Error)
      }
    }
  }
}

impl Utf8Buffer {
  /// Creates a new, empty `Utf8Buffer`.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Buffer;
  ///
  /// let buf = Utf8Buffer::new();
  /// assert!(buf.is_empty());
  /// ```
  #[cfg_attr(not(coverage), inline(always))]
  pub const fn new() -> Self {
    Self {
      inner: Buffer::new(),
    }
  }

  /// Creates a `Utf8Buffer` from a static string slice.
  ///
  /// Unlike the shared immutable UTF-8 wrapper's `from_static` constructor,
  /// this method **copies** the bytes into the inline buffer — `Utf8Buffer`
  /// has no heap variant. It exists as a const constructor for parity.
  ///
  /// # Panics
  ///
  /// Panics at compile time (via `const` assertion) if `s.len() > 62`.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Buffer;
  ///
  /// const GREETING: Utf8Buffer = Utf8Buffer::from_static("hello");
  /// assert_eq!(GREETING.as_str(), "hello");
  /// ```
  #[cfg_attr(not(coverage), inline(always))]
  pub const fn from_static(s: &'static str) -> Self {
    let bytes = s.as_bytes();
    assert!(
      bytes.len() <= crate::INLINE_CAP,
      "string too large for Utf8Buffer inline capacity"
    );
    // SAFETY: length checked against INLINE_CAP above; input is already valid UTF-8.
    Self {
      inner: unsafe { Buffer::copy_from_slice(bytes) },
    }
  }

  /// Returns a reference to the inner `Buffer`.
  #[cfg_attr(not(coverage), inline(always))]
  pub const fn as_inner(&self) -> &Buffer {
    &self.inner
  }

  /// Consumes `self` and returns the inner `Buffer`.
  #[cfg_attr(not(coverage), inline(always))]
  pub const fn into_inner(self) -> Buffer {
    self.inner
  }

  /// Returns the contents as a string slice.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Buffer;
  ///
  /// let buf = Utf8Buffer::try_from("hello").unwrap();
  /// assert_eq!(buf.as_str(), "hello");
  /// ```
  #[cfg_attr(not(coverage), inline(always))]
  pub fn as_str(&self) -> &str {
    // SAFETY: Utf8Buffer guarantees valid UTF-8
    unsafe { str::from_utf8_unchecked(self.inner.as_slice()) }
  }

  /// Returns the contents as a mutable string slice.
  ///
  /// Mutations must preserve UTF-8 validity and the byte length of edited
  /// ranges, as required by [`prim@str`].
  pub fn as_mut_str(&mut self) -> &mut str {
    str::from_utf8_mut(self.inner.as_mut_slice()).expect("UTF-8 invariant")
  }

  /// Returns the length of the buffer in bytes.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Buffer;
  ///
  /// let buf = Utf8Buffer::try_from("hello").unwrap();
  /// assert_eq!(buf.len(), 5);
  /// ```
  #[cfg_attr(not(coverage), inline(always))]
  pub const fn len(&self) -> usize {
    self.inner.len()
  }

  /// Returns `true` if the buffer has a length of 0.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Buffer;
  ///
  /// let buf = Utf8Buffer::new();
  /// assert!(buf.is_empty());
  /// ```
  #[cfg_attr(not(coverage), inline(always))]
  pub const fn is_empty(&self) -> bool {
    self.inner.is_empty()
  }

  /// Returns the number of bytes stored in the buffer.
  ///
  /// This is equivalent to [`len`](Self::len).
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Buffer;
  ///
  /// let buf = Utf8Buffer::try_from("hi").unwrap();
  /// assert_eq!(buf.remaining(), 2);
  /// ```
  #[cfg_attr(not(coverage), inline(always))]
  pub const fn remaining(&self) -> usize {
    self.inner.remaining()
  }

  /// Returns the capacity of the buffer.
  #[cfg_attr(not(coverage), inline(always))]
  pub const fn capacity(&self) -> usize {
    self.inner.capacity()
  }

  /// Reclaims consumed fixed-buffer prefix space without allocating.
  ///
  /// Returns `true` when the writable tail can hold `additional` bytes. On
  /// `false`, this value is unchanged.
  ///
  /// ```
  /// use smol_bytes::Utf8Buffer;
  ///
  /// let mut text = Utf8Buffer::try_from("abcd").unwrap();
  /// let _ = text.split_to(2);
  /// assert!(text.try_reclaim(60));
  /// assert_eq!(text.as_str(), "cd");
  /// ```
  pub fn try_reclaim(&mut self, additional: usize) -> bool {
    self.inner.try_reclaim(additional)
  }

  /// Inserts `s` at a UTF-8 character boundary.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Buffer;
  ///
  /// let mut text = Utf8Buffer::try_from("aé").unwrap();
  /// text.insert_str(1, "🦀");
  /// assert_eq!(text.as_str(), "a🦀é");
  /// ```
  ///
  /// # Panics
  ///
  /// Panics if `idx` is invalid or the inserted bytes do not fit.
  pub fn insert_str(&mut self, idx: usize, s: &str) {
    self
      .try_insert_str(idx, s)
      .unwrap_or_else(|error| panic!("insert_str failed: {error}"));
  }

  /// Tries to insert `s` at a UTF-8 character boundary.
  ///
  /// The buffer is unchanged on error. A capacity error reports only the
  /// positive amount by which the edit would grow the current view.
  pub fn try_insert_str(&mut self, idx: usize, s: &str) -> Result<(), Utf8EditError> {
    validate_char_boundary(self.as_str(), idx).map_err(Utf8EditError::Index)?;
    self.replace_range_validated(idx, idx, s)
  }

  /// Inserts a Unicode scalar value at a UTF-8 character boundary.
  ///
  /// # Panics
  ///
  /// Panics if `idx` is invalid or the encoded scalar does not fit.
  pub fn insert(&mut self, idx: usize, ch: char) {
    self
      .try_insert(idx, ch)
      .unwrap_or_else(|error| panic!("insert failed: {error}"));
  }

  /// Tries to insert a Unicode scalar value at a UTF-8 character boundary.
  pub fn try_insert(&mut self, idx: usize, ch: char) -> Result<(), Utf8EditError> {
    let mut encoded = [0_u8; 4];
    self.try_insert_str(idx, ch.encode_utf8(&mut encoded))
  }

  /// Replaces a UTF-8 character-boundary range with `replacement`.
  ///
  /// # Panics
  ///
  /// Panics if the range is invalid or the replacement does not fit.
  pub fn replace_range(&mut self, range: impl RangeBounds<usize>, replacement: &str) {
    self
      .try_replace_range(range, replacement)
      .unwrap_or_else(|error| panic!("replace_range failed: {error}"));
  }

  /// Tries to replace a UTF-8 character-boundary range with `replacement`.
  ///
  /// Validation and capacity checks happen before mutation, so this buffer is
  /// unchanged when an error is returned.
  pub fn try_replace_range(
    &mut self,
    range: impl RangeBounds<usize>,
    replacement: &str,
  ) -> Result<(), Utf8EditError> {
    let (start, end) =
      range_bounds_to_start_end(self.as_str(), range).map_err(Utf8EditError::Index)?;
    self.replace_range_validated(start, end, replacement)
  }

  /// Appends a copy of the specified UTF-8 character-boundary range.
  ///
  /// # Panics
  ///
  /// Panics if the range is invalid or the copied bytes do not fit in the
  /// remaining tail capacity.
  pub fn extend_from_within(&mut self, range: impl RangeBounds<usize>) {
    self
      .try_extend_from_within(range)
      .unwrap_or_else(|error| panic!("extend_from_within failed: {error}"));
  }

  /// Tries to append a copy of the specified UTF-8 character-boundary range.
  ///
  /// Validation and capacity preflight happen before mutation. Consumed prefix
  /// storage is not reclaimed implicitly.
  pub fn try_extend_from_within(
    &mut self,
    range: impl RangeBounds<usize>,
  ) -> Result<(), Utf8EditError> {
    let old_len = self.len();
    let (start, end) = range_bounds_to_start_end(self.as_str(), range)?;
    let count = end - start;
    let new_len = old_len.checked_add(count).expect("buffer length overflow");
    let available = self.inner.remaining_mut();
    if count > available {
      return Err(
        TryPutError {
          requested: count,
          available,
        }
        .into(),
      );
    }

    if count == 0 {
      return Ok(());
    }

    self.inner.resize(new_len, 0);
    self.inner.as_mut_slice().copy_within(start..end, old_len);
    Ok(())
  }

  fn replace_range_validated(
    &mut self,
    start: usize,
    end: usize,
    replacement: &str,
  ) -> Result<(), Utf8EditError> {
    let old_len = self.inner.len();
    let removed = end - start;
    let growth = replacement.len().saturating_sub(removed);
    let available = self.inner.capacity() - old_len;
    if growth > available {
      return Err(
        TryPutError {
          requested: growth,
          available,
        }
        .into(),
      );
    }

    let mut storage = RawUtf8Storage::fixed(&mut self.inner);
    raw_replace_bytes(&mut storage, start, end, replacement.as_bytes());
    Ok(())
  }

  /// Removes and returns the Unicode scalar value at `idx`.
  ///
  /// # Panics
  ///
  /// Panics if `idx` is outside the visible string or is not a UTF-8
  /// character boundary.
  pub fn remove(&mut self, idx: usize) -> char {
    self
      .try_remove(idx)
      .unwrap_or_else(|error| panic!("remove failed: {error}"))
  }

  /// Tries to remove and return the Unicode scalar value at `idx`.
  pub fn try_remove(&mut self, idx: usize) -> Result<char, Utf8IndexError> {
    let len = self.len();
    if idx >= len {
      return Err(OutOfBounds::new(idx, len).into());
    }
    validate_char_boundary(self.as_str(), idx)?;
    let ch = self.as_str()[idx..]
      .chars()
      .next()
      .expect("index below string length has a scalar");
    self
      .replace_range_validated(idx, idx + ch.len_utf8(), "")
      .expect("removing a scalar cannot exceed fixed capacity");
    Ok(ch)
  }

  /// Retains only the characters for which `predicate` returns `true`.
  ///
  /// The predicate runs once per character in original order without
  /// allocating. If it panics, decisions already returned from the predicate
  /// are kept, while the current character and unvisited suffix remain.
  ///
  /// ```
  /// use smol_bytes::Utf8Buffer;
  ///
  /// let mut text = Utf8Buffer::try_from("aé🦀").unwrap();
  /// text.retain(|character| character != 'é');
  /// assert_eq!(text.as_str(), "a🦀");
  /// ```
  pub fn retain<F>(&mut self, mut predicate: F)
  where
    F: FnMut(char) -> bool,
  {
    let mut guard = RetainGuard::new(RawUtf8Storage::fixed(&mut self.inner));
    guard.retain(&mut predicate);
  }

  /// Returns an iterator over a range that is removed when the iterator drops.
  ///
  /// # Panics
  ///
  /// Panics if the range is out of bounds or not on UTF-8 character boundaries.
  pub fn drain(&mut self, range: impl RangeBounds<usize>) -> Utf8Drain<'_> {
    self.try_drain(range).expect("drain range failed")
  }

  /// Tries to return an iterator over a range removed when it drops.
  ///
  /// The selected range is not removed eagerly. Dropping this iterator removes
  /// the entire original range, even if it was only partly consumed.
  pub fn try_drain(
    &mut self,
    range: impl RangeBounds<usize>,
  ) -> Result<Utf8Drain<'_>, Utf8IndexError> {
    let (start, end) = range_bounds_to_start_end(self.as_str(), range)?;
    Ok(Utf8Drain::new(
      RawUtf8Storage::fixed(&mut self.inner),
      start,
      end,
    ))
  }

  /// Appends a character to the buffer.
  ///
  /// `Utf8Buffer` is backed by a fixed 62-byte inline [`Buffer`]; this
  /// method panics when the character would not fit. Use [`try_push`]
  /// for a fallible variant.
  ///
  /// [`try_push`]: Self::try_push
  ///
  /// # Panics
  ///
  /// Panics if the buffer's remaining capacity is less than `ch.len_utf8()`.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Buffer;
  ///
  /// let mut buf = Utf8Buffer::new();
  /// buf.push('a');
  /// buf.push('é'); // 2-byte char
  /// assert_eq!(buf.as_str(), "aé");
  /// ```
  pub fn push(&mut self, ch: char) {
    <Self as Utf8BufMut>::push(self, ch)
  }

  /// Appends a string slice to the buffer.
  ///
  /// `Utf8Buffer` is backed by a fixed 62-byte inline [`Buffer`]; this
  /// method panics when the string would not fit. Use [`try_push_str`]
  /// for a fallible variant.
  ///
  /// [`try_push_str`]: Self::try_push_str
  ///
  /// # Panics
  ///
  /// Panics if the buffer's remaining capacity is less than `s.len()`.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Buffer;
  ///
  /// let mut buf = Utf8Buffer::new();
  /// buf.push_str("hello");
  /// assert_eq!(buf.as_str(), "hello");
  /// ```
  pub fn push_str(&mut self, s: &str) {
    <Self as Utf8BufMut>::push_str(self, s)
  }

  /// Tries to append a character to the buffer.
  ///
  /// # Errors
  ///
  /// Returns [`TryPutError`] if the buffer's remaining capacity is less
  /// than `ch.len_utf8()`. On error the buffer is unchanged.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Buffer;
  ///
  /// let mut buf = Utf8Buffer::try_from("a".repeat(60).as_str()).unwrap();
  /// assert!(buf.try_push('a').is_ok());        // 61 bytes
  /// assert!(buf.try_push('a').is_ok());        // 62 bytes
  /// assert!(buf.try_push('a').is_err());       // full
  /// ```
  pub fn try_push(&mut self, ch: char) -> Result<(), TryPutError> {
    let mut buf = [0u8; 4];
    let s = ch.encode_utf8(&mut buf);
    self.inner.try_put_slice(s.as_bytes())
  }

  /// Tries to append a string slice to the buffer.
  ///
  /// # Errors
  ///
  /// Returns [`TryPutError`] if the buffer's remaining capacity is less
  /// than `s.len()`. On error the buffer is unchanged.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Buffer;
  ///
  /// let mut buf = Utf8Buffer::new();
  /// assert!(buf.try_push_str("hello").is_ok());
  /// assert_eq!(buf.as_str(), "hello");
  /// ```
  pub fn try_push_str(&mut self, s: &str) -> Result<(), TryPutError> {
    self.inner.try_put_slice(s.as_bytes())
  }

  /// Formats `args` into this buffer without changing it on failure.
  ///
  /// Capacity failures report the first formatter chunk that did not fit. If
  /// a formatter swallows that writer failure and returns success, the
  /// capacity error still takes precedence.
  pub fn try_write_fmt(&mut self, args: core::fmt::Arguments<'_>) -> Result<(), Utf8FormatError> {
    let mut candidate = *self;
    let (format_result, capacity_error) = {
      let mut writer = FormatWriteAdapter {
        candidate: &mut candidate,
        capacity_error: None,
      };
      let result = core::fmt::write(&mut writer, args);
      (result, writer.capacity_error)
    };

    if let Some(error) = capacity_error {
      return Err(error.into());
    }
    if let Err(error) = format_result {
      return Err(error.into());
    }

    *self = candidate;
    Ok(())
  }

  /// Clears the buffer, removing all contents.
  pub fn clear(&mut self) {
    self.inner.clear();
  }

  /// Truncates the buffer to the specified length.
  ///
  /// # Panics
  ///
  /// Panics if `new_len` does not lie on a UTF-8 character boundary.
  pub fn truncate(&mut self, new_len: usize) {
    self
      .try_truncate(new_len)
      .expect("new_len must lie on a UTF-8 character boundary");
  }

  /// Truncates the buffer at a UTF-8 character boundary.
  pub fn try_truncate(&mut self, new_len: usize) -> Result<(), Utf8IndexError> {
    <Self as Utf8BufMut>::try_truncate(self, new_len)
  }

  /// Removes and returns the last Unicode scalar value.
  ///
  /// This operates on Unicode scalar values, not grapheme clusters, and never
  /// allocates.
  ///
  /// ```
  /// use smol_bytes::Utf8Buffer;
  ///
  /// let mut text = Utf8Buffer::try_from("aé").unwrap();
  /// assert_eq!(text.pop(), Some('é'));
  /// assert_eq!(text.as_str(), "a");
  /// ```
  pub fn pop(&mut self) -> Option<char> {
    let ch = self.as_str().chars().next_back()?;
    self.truncate(self.len() - ch.len_utf8());
    Some(ch)
  }

  /// Splits the buffer at `at`, returning the head `[0, at)` and leaving
  /// `self` with `[at, len)`.
  ///
  /// # Panics
  ///
  /// Panics if `at` is out of bounds or not on a UTF-8 character boundary.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Buffer;
  ///
  /// let mut buf = Utf8Buffer::try_from("hello world").unwrap();
  /// let head = buf.split_to(5);
  /// assert_eq!(head.as_str(), "hello");
  /// assert_eq!(buf.as_str(), " world");
  /// ```
  pub fn split_to(&mut self, at: usize) -> Self {
    <Self as Utf8Buf>::split_to(self, at)
  }

  /// Tries to split the buffer at `at`.
  ///
  /// # Errors
  ///
  /// Returns [`Utf8IndexError::InvalidCharBoundary`] if `at` is not on a
  /// character boundary, or [`Utf8IndexError::IndexOutOfBounds`] if `at > len`.
  pub fn try_split_to(&mut self, at: usize) -> Result<Self, Utf8IndexError> {
    <Self as Utf8Buf>::try_split_to(self, at)
  }

  /// Splits the buffer at `at`, returning the tail `[at, len)` and leaving
  /// `self` with `[0, at)`.
  ///
  /// # Panics
  ///
  /// Panics if `at` is out of bounds or not on a UTF-8 character boundary.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Buffer;
  ///
  /// let mut buf = Utf8Buffer::try_from("hello world").unwrap();
  /// let tail = buf.split_off(6);
  /// assert_eq!(buf.as_str(), "hello ");
  /// assert_eq!(tail.as_str(), "world");
  /// ```
  pub fn split_off(&mut self, at: usize) -> Self {
    <Self as Utf8Buf>::split_off(self, at)
  }

  /// Tries to split the buffer at `at`, returning the tail.
  ///
  /// # Errors
  ///
  /// Returns [`Utf8IndexError::InvalidCharBoundary`] if `at` is not on a
  /// character boundary, or [`Utf8IndexError::IndexOutOfBounds`] if `at > len`.
  pub fn try_split_off(&mut self, at: usize) -> Result<Self, Utf8IndexError> {
    <Self as Utf8Buf>::try_split_off(self, at)
  }

  /// Returns a copy of a sub-range of the buffer.
  ///
  /// # Panics
  ///
  /// Panics if the range is out of bounds or not on UTF-8 character boundaries.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Buffer;
  ///
  /// let buf = Utf8Buffer::try_from("hello world").unwrap();
  /// let slice = buf.slice(0..5);
  /// assert_eq!(slice.as_str(), "hello");
  /// ```
  pub fn slice(&self, range: impl core::ops::RangeBounds<usize>) -> Self {
    <Self as Utf8Buf>::slice(self, range)
  }

  /// Tries to return a copy of a sub-range of the buffer.
  ///
  /// # Errors
  ///
  /// Returns [`Utf8IndexError`] if the range is out of bounds or not on
  /// character boundaries.
  pub fn try_slice(
    &self,
    range: impl core::ops::RangeBounds<usize>,
  ) -> Result<Self, Utf8IndexError> {
    <Self as Utf8Buf>::try_slice(self, range)
  }
}

impl AsRef<str> for Utf8Buffer {
  #[cfg_attr(not(coverage), inline(always))]
  fn as_ref(&self) -> &str {
    self.as_str()
  }
}

impl AsRef<[u8]> for Utf8Buffer {
  #[cfg_attr(not(coverage), inline(always))]
  fn as_ref(&self) -> &[u8] {
    self.as_str().as_bytes()
  }
}

impl Borrow<str> for Utf8Buffer {
  #[cfg_attr(not(coverage), inline(always))]
  fn borrow(&self) -> &str {
    self.as_str()
  }
}

impl core::ops::Deref for Utf8Buffer {
  type Target = str;

  #[cfg_attr(not(coverage), inline(always))]
  fn deref(&self) -> &Self::Target {
    self.as_str()
  }
}

#[cfg(feature = "std")]
impl AsRef<std::ffi::OsStr> for Utf8Buffer {
  fn as_ref(&self) -> &std::ffi::OsStr {
    std::ffi::OsStr::new(self.as_str())
  }
}

#[cfg(feature = "std")]
impl AsRef<std::path::Path> for Utf8Buffer {
  fn as_ref(&self) -> &std::path::Path {
    std::path::Path::new(self.as_str())
  }
}

impl Utf8Buf for Utf8Buffer {
  fn try_split_to(&mut self, at: usize) -> Result<Self, Utf8IndexError> {
    validate_char_boundary(self.as_str(), at)?;

    Ok(Self {
      inner: self.inner.try_split_to(at).expect("already checked bounds"),
    })
  }

  fn try_split_off(&mut self, at: usize) -> Result<Self, Utf8IndexError> {
    validate_char_boundary(self.as_str(), at)?;

    Ok(Self {
      inner: self
        .inner
        .try_split_off(at)
        .expect("already checked bounds"),
    })
  }

  fn try_slice(&self, range: impl RangeBounds<usize>) -> Result<Self, Utf8IndexError> {
    let (start, end) = range_bounds_to_start_end(self.as_str(), range)?;

    Ok(Self {
      inner: self
        .inner
        .try_slice(start..end)
        .expect("already checked bounds"),
    })
  }
}

impl Utf8BufMut for Utf8Buffer {
  type CapacityError = TryPutError;

  fn try_truncate(&mut self, new_len: usize) -> Result<(), Utf8IndexError> {
    if new_len >= self.len() {
      return Ok(());
    }
    if !self.as_str().is_char_boundary(new_len) {
      return Err(Utf8IndexError::InvalidCharBoundary { index: new_len });
    }
    self.inner.truncate(new_len);
    Ok(())
  }

  fn try_push(&mut self, ch: char) -> Result<(), Self::CapacityError> {
    let mut buf = [0u8; 4];
    let s = ch.encode_utf8(&mut buf);
    self.inner.try_put_slice(s.as_bytes())
  }

  fn try_push_str(&mut self, s: &str) -> Result<(), Self::CapacityError> {
    self.inner.try_put_slice(s.as_bytes())
  }

  fn clear(&mut self) {
    self.inner.clear();
  }
}