utf8-bytes 0.1.1

bytes::Bytes, but UTF-8
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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
use crate::FromUtf8Error;

use super::Utf8Bytes;

use core::iter::FromIterator;
use core::mem::MaybeUninit;
use core::ops::{Deref, DerefMut};
use core::ptr::{self};
use core::{cmp, fmt, hash};

use alloc::{
    borrow::{Borrow, BorrowMut},
    string::String,
    vec::Vec,
};

/// A unique reference to a contiguous slice of UTF-8 memory.
///
/// This is built on [`BytesMut`](bytes::BytesMut), see its documentation for more.
pub struct Utf8BytesMut {
    /// # Invariant
    /// - contains UTF-8.
    #[deprecated = "use the accessors to preserve the invariants"]
    inner: bytes::BytesMut,
}

impl Utf8BytesMut {
    /// Wrap `bytes` if it is UTF-8.
    ///
    /// If it is not, you can perform a lossy conversion using [`FromUtf8Error::into_utf8_lossy`].
    pub fn from_bytes_mut(bytes: bytes::BytesMut) -> Result<Self, FromUtf8Error<bytes::BytesMut>> {
        match str::from_utf8(&bytes) {
            Ok(_) => Ok(unsafe { Self::from_bytes_mut_unchecked(bytes) }),
            Err(error) => Err(FromUtf8Error { bytes, error }),
        }
    }
    /// # Safety
    /// `bytes` must only contain UTF-8.
    pub const unsafe fn from_bytes_mut_unchecked(bytes: bytes::BytesMut) -> Self {
        #[expect(deprecated)]
        Self { inner: bytes }
    }
    /// Get the contents of the buffer.
    pub fn as_str(&self) -> &str {
        unsafe { str::from_utf8_unchecked(self.inner()) }
    }
    /// Get an exclusive reference to the contents of the buffer.
    pub fn as_mut_str(&mut self) -> &mut str {
        // SAFETY:
        // - We don't modify the buffer except as a str.
        // - The inner buffer satisfies our invariant.
        unsafe { str::from_utf8_unchecked_mut(self.inner_mut_unchecked()) }
    }
}

impl Utf8BytesMut {
    /// Return a shared reference to the inner object.
    #[inline]
    pub const fn inner(&self) -> &bytes::BytesMut {
        #[expect(deprecated)]
        &self.inner
    }

    /// Return an exclusive reference to the inner object.
    ///
    /// # Safety
    /// - The returned bytes must be returned containing UTF-8
    #[inline]
    pub const unsafe fn inner_mut_unchecked(&mut self) -> &mut bytes::BytesMut {
        #[expect(deprecated)]
        &mut self.inner
    }
    #[inline]
    pub fn into_inner(self) -> bytes::BytesMut {
        #[expect(deprecated)]
        self.inner
    }
}

impl Utf8BytesMut {
    /// Creates a new [`Utf8BytesMut`] with the specified capacity.
    ///
    /// The returned [`Utf8BytesMut`] will be able to hold at least `capacity` bytes
    /// without reallocating.
    ///
    /// # Examples
    ///
    /// ```
    /// use utf8_bytes::Utf8BytesMut;
    ///
    /// let mut bytes = Utf8BytesMut::with_capacity(64);
    ///
    /// // `bytes` contains no data, even though there is capacity
    /// assert_eq!(bytes.len(), 0);
    ///
    /// bytes.extend_from_str("hello world");
    ///
    /// assert_eq!(bytes, "hello world");
    /// ```
    #[inline]
    pub fn with_capacity(capacity: usize) -> Utf8BytesMut {
        unsafe { Self::from_bytes_mut_unchecked(bytes::BytesMut::with_capacity(capacity)) }
    }

    /// Creates a new `BytesMut` with default capacity.
    ///
    /// Resulting object has length 0 and unspecified capacity.
    /// This function does not allocate.
    ///
    /// # Examples
    ///
    /// ```
    /// use utf8_bytes::Utf8BytesMut;
    ///
    /// let mut bytes = Utf8BytesMut::new();
    ///
    /// assert_eq!(0, bytes.len());
    ///
    /// bytes.reserve(2);
    /// bytes.extend_from_str("xy");
    ///
    /// assert_eq!("xy", bytes);
    /// ```
    #[inline]
    pub fn new() -> Utf8BytesMut {
        Utf8BytesMut::with_capacity(0)
    }

    /// Returns the number of bytes contained in this [`Utf8BytesMut`].
    ///
    /// # Examples
    ///
    /// ```
    /// use utf8_bytes::Utf8BytesMut;
    ///
    /// let b = Utf8BytesMut::from("hello");
    /// assert_eq!(b.len(), 5);
    /// ```
    #[inline]
    pub fn len(&self) -> usize {
        self.inner().len()
    }

    /// Returns true if the [`Utf8BytesMut`] has a length of 0.
    ///
    /// # Examples
    ///
    /// ```
    /// use utf8_bytes::Utf8BytesMut;
    ///
    /// let b = Utf8BytesMut::with_capacity(64);
    /// assert!(b.is_empty());
    /// ```
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.inner().is_empty()
    }

    /// Returns the number of bytes the [`Utf8BytesMut`] can hold without reallocating.
    ///
    /// # Examples
    ///
    /// ```
    /// use utf8_bytes::Utf8BytesMut;
    ///
    /// let b = Utf8BytesMut::with_capacity(64);
    /// assert_eq!(b.capacity(), 64);
    /// ```
    #[inline]
    pub fn capacity(&self) -> usize {
        self.inner().capacity()
    }

    /// Converts `self` into an immutable [`Utf8Bytes`].
    ///
    /// The conversion is zero cost and is used to indicate that the slice
    /// referenced by the handle will no longer be mutated. Once the conversion
    /// is done, the handle can be cloned and shared across threads.
    ///
    /// # Examples
    ///
    /// ```
    /// use utf8_bytes::{Utf8BytesMut};
    /// use std::thread;
    ///
    /// let mut b = Utf8BytesMut::with_capacity(64);
    /// b.extend_from_str("hello world");
    /// let b1 = b.freeze();
    /// let b2 = b1.clone();
    ///
    /// let th = thread::spawn(move || {
    ///     assert_eq!(b1, "hello world");
    /// });
    ///
    /// assert_eq!(b2, "hello world");
    /// th.join().unwrap();
    /// ```
    #[inline]
    pub fn freeze(self) -> Utf8Bytes {
        // SAFETY:
        // - contents is still UTF-8
        unsafe { Utf8Bytes::from_bytes_unchecked(self.into_inner().freeze()) }
    }

    /// Creates a new [`Utf8BytesMut`] containing `len` zeros.
    ///
    /// The resulting object has a length of `len` and a capacity greater
    /// than or equal to `len`. The entire length of the object will be filled
    /// with zeros.
    ///
    /// On some platforms or allocators this function may be faster than
    /// a manual implementation.
    ///
    /// # Examples
    ///
    /// ```
    /// use utf8_bytes::Utf8BytesMut;
    ///
    /// let zeros = Utf8BytesMut::zeroed(42);
    ///
    /// assert!(zeros.capacity() >= 42);
    /// assert_eq!(zeros.len(), 42);
    /// zeros.chars().for_each(|ch| assert_eq!(ch, 0 as char));
    /// ```
    pub fn zeroed(len: usize) -> Utf8BytesMut {
        // SAFETY:
        // - null is valid UTF-8
        unsafe { Self::from_bytes_mut_unchecked(bytes::BytesMut::zeroed(len)) }
    }

    /// Splits the [`Utf8BytesMut`] into two at the given index.
    ///
    /// Afterwards `self` contains elements `[0, at)`, and the returned
    /// [`Utf8BytesMut`] contains elements `[at, capacity)`. It's guaranteed that the
    /// memory does not move, that is, the address of `self` does not change,
    /// and the address of the returned slice is `at` bytes after that.
    ///
    /// This is an `O(1)` operation that just increases the reference count
    /// and sets a few indices.
    ///
    /// # Examples
    ///
    /// ```
    /// use utf8_bytes::Utf8BytesMut;
    ///
    /// let mut a = Utf8BytesMut::from("hello world");
    /// let mut b = a.split_off(5);
    ///
    /// assert_eq!(a, "hello");
    /// assert_eq!(b, " world");
    /// ```
    ///
    /// # Panics
    ///
    /// - If `at > capacity`.
    /// - If `at` does not lie on a character boundary.
    #[must_use = "consider Utf8BytesMut::truncate if you don't need the other half"]
    #[track_caller]
    pub fn split_off(&mut self, at: usize) -> Utf8BytesMut {
        let _char_boundary = self.as_str().split_at(at);
        // SAFETY:
        // - checked UTF-8 above!
        unsafe { Self::from_bytes_mut_unchecked(self.inner_mut_unchecked().split_off(at)) }
    }

    /// Removes the bytes from the current view, returning them in a new
    /// [`Utf8BytesMut`] handle.
    ///
    /// Afterwards, `self` will be empty, but will retain any additional
    /// capacity that it had before the operation. This is identical to
    /// `self.split_to(self.len())`.
    ///
    /// This is an `O(1)` operation that just increases the reference count and
    /// sets a few indices.
    ///
    /// # Examples
    ///
    /// ```
    /// use utf8_bytes::Utf8BytesMut;
    ///
    /// let mut buf = Utf8BytesMut::with_capacity(1024);
    /// buf.extend_from_str("hello world");
    ///
    /// let other = buf.split();
    ///
    /// assert!(buf.is_empty());
    /// assert_eq!(1013, buf.capacity());
    ///
    /// assert_eq!(other, "hello world");
    /// ```
    #[must_use = "consider Utf8BytesMut::clear if you don't need the other half"]
    pub fn split(&mut self) -> Utf8BytesMut {
        // SAFETY:
        // - empty is valid UTF-8.
        unsafe { Self::from_bytes_mut_unchecked(self.inner_mut_unchecked().split()) }
    }

    /// Splits the buffer into two at the given index.
    ///
    /// Afterwards `self` contains elements `[at, len)`, and the returned [`Utf8BytesMut`]
    /// contains elements `[0, at)`.
    ///
    /// This is an `O(1)` operation that just increases the reference count and
    /// sets a few indices.
    ///
    /// # Examples
    ///
    /// ```
    /// use utf8_bytes::Utf8BytesMut;
    ///
    /// let mut a = Utf8BytesMut::from("hello world");
    /// let mut b = a.split_to(5);
    ///
    /// b[1..].make_ascii_uppercase();
    /// a[2..].make_ascii_uppercase();
    ///
    /// assert_eq!(&a[..], " wORLD");
    /// assert_eq!(&b[..], "hELLO");
    /// ```
    ///
    /// # Panics
    ///
    /// - If `at > len`.
    /// - If `at` is not on a char boundary.
    #[must_use = "consider Utf8BytesMut::advance if you don't need the other half"]
    #[track_caller]
    pub fn split_to(&mut self, at: usize) -> Utf8BytesMut {
        let _char_boundary = self.as_str().split_at(at);
        // SAFETY:
        // - checked UTF-8 above
        unsafe { Self::from_bytes_mut_unchecked(self.inner_mut_unchecked().split_to(at)) }
    }

    /// Shortens the buffer, keeping the first `len` bytes and dropping the
    /// rest.
    ///
    /// If `len` is greater than the buffer's current length, this has no
    /// effect.
    ///
    /// Existing underlying capacity is preserved.
    ///
    /// The [split_off](`Self::split_off()`) method can emulate `truncate`, but this causes the
    /// excess bytes to be returned instead of dropped.
    ///
    /// # Examples
    ///
    /// ```
    /// use utf8_bytes::Utf8BytesMut;
    ///
    /// let mut buf = Utf8BytesMut::from("hello world");
    /// buf.truncate(5);
    /// assert_eq!(buf, "hello");
    /// ```
    ///
    /// # Panics
    /// - If `len` is not on a char boundary.
    pub fn truncate(&mut self, len: usize) {
        if len < self.len() {
            let _char_boundary = self.as_str().split_at(len);
            // SAFETY:
            // - checked on boundary above
            unsafe { self.inner_mut_unchecked().truncate(len) };
        };
    }

    /// Clears the buffer, removing all data. Existing capacity is preserved.
    ///
    /// # Examples
    ///
    /// ```
    /// use utf8_bytes::Utf8BytesMut;
    ///
    /// let mut buf = Utf8BytesMut::from("hello world");
    /// buf.clear();
    /// assert!(buf.is_empty());
    /// ```
    pub fn clear(&mut self) {
        // SAFETY:
        // - empty is valid UTF-8
        unsafe { self.inner_mut_unchecked().clear() };
    }

    /// Resizes the buffer so that `len` is equal to `new_len`.
    ///
    /// If `new_len` is greater than `len`, the buffer is extended by the
    /// difference with each additional byte set to `value`. If `new_len` is
    /// less than `len`, the buffer is simply truncated.
    ///
    /// # Examples
    ///
    /// ```
    /// use utf8_bytes::Utf8BytesMut;
    ///
    /// let mut buf = Utf8BytesMut::new();
    ///
    /// buf.resize(3, b'A');
    /// assert_eq!(&buf[..], "AAA");
    ///
    /// buf.resize(2, b'B');
    /// assert_eq!(&buf[..], "AA");
    ///
    /// buf.resize(4, b'C');
    /// assert_eq!(&buf[..], "AACC");
    /// ```
    ///
    /// # Panics
    /// - If `new_len` is shorter than [`Self::len`] and does not lie on a char boundary.
    pub fn resize(&mut self, new_len: usize, ch: u8) {
        assert!(ch.is_ascii());
        let additional = if let Some(additional) = new_len.checked_sub(self.len()) {
            additional
        } else {
            self.truncate(new_len);
            return;
        };

        if additional == 0 {
            return;
        }

        self.reserve(additional);
        let dst = self.spare_capacity_mut().as_mut_ptr();
        // SAFETY: `spare_capacity_mut` returns a valid, properly aligned pointer and we've
        // reserved enough space to write `additional` bytes.
        unsafe { ptr::write_bytes(dst, ch, additional) };

        // SAFETY: There are at least `new_len` initialized bytes in the buffer so no
        // uninitialized bytes are being exposed.
        unsafe { self.set_len(new_len) };
    }

    /// Sets the length of the buffer.
    ///
    /// This will explicitly set the size of the buffer without actually
    /// modifying the data, so it is up to the caller to ensure that the data
    /// has been initialized.
    ///
    /// # Examples
    ///
    /// ```
    /// use utf8_bytes::Utf8BytesMut;
    ///
    /// let mut b = Utf8BytesMut::from("hello world");
    ///
    /// unsafe {
    ///     b.set_len(5);
    /// }
    ///
    /// assert_eq!(&b[..], "hello");
    ///
    /// unsafe {
    ///     b.set_len(11);
    /// }
    ///
    /// assert_eq!(&b[..], "hello world");
    /// ```
    ///
    /// # Safety
    /// - Data up to `len` must be initialized with valid UTF-8.
    #[inline]
    pub unsafe fn set_len(&mut self, len: usize) {
        unsafe { self.inner_mut_unchecked().set_len(len) }
    }

    /// Reserves capacity for at least `additional` more bytes to be inserted
    /// into the given [`Utf8BytesMut`].
    ///
    /// More than `additional` bytes may be reserved in order to avoid frequent
    /// reallocations. A call to `reserve` may result in an allocation.
    ///
    /// Before allocating new buffer space, the function will attempt to reclaim
    /// space in the existing buffer. If the current handle references a view
    /// into a larger original buffer, and all other handles referencing part
    /// of the same original buffer have been dropped, then the current view
    /// can be copied/shifted to the front of the buffer and the handle can take
    /// ownership of the full buffer, provided that the full buffer is large
    /// enough to fit the requested additional capacity.
    ///
    /// This optimization will only happen if shifting the data from the current
    /// view to the front of the buffer is not too expensive in terms of the
    /// (amortized) time required. The precise condition is subject to change;
    /// as of now, the length of the data being shifted needs to be at least as
    /// large as the distance that it's shifted by. If the current view is empty
    /// and the original buffer is large enough to fit the requested additional
    /// capacity, then reallocations will never happen.
    ///
    /// # Examples
    ///
    /// In the following example, a new buffer is allocated.
    ///
    /// ```
    /// use utf8_bytes::Utf8BytesMut;
    ///
    /// let mut buf = Utf8BytesMut::from("hello");
    /// buf.reserve(64);
    /// assert!(buf.capacity() >= 69);
    /// ```
    ///
    /// In the following example, the existing buffer is reclaimed.
    ///
    /// ```
    /// use utf8_bytes::{Utf8BytesMut};
    ///
    /// let mut buf = Utf8BytesMut::with_capacity(128);
    /// buf.extend_from_str(str::from_utf8(&[0; 64]).unwrap());
    ///
    /// let ptr = buf.as_ptr();
    /// let other = buf.split();
    ///
    /// assert!(buf.is_empty());
    /// assert_eq!(buf.capacity(), 64);
    ///
    /// drop(other);
    /// buf.reserve(128);
    ///
    /// assert_eq!(buf.capacity(), 128);
    /// assert_eq!(buf.as_ptr(), ptr);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the new capacity overflows `usize`.
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        // SAFETY:
        // - does not change logical contents
        unsafe { self.inner_mut_unchecked() }.reserve(additional);
    }

    /// Attempts to cheaply reclaim already allocated capacity for at least `additional` more
    /// bytes to be inserted into the given [`Utf8BytesMut`] and returns `true` if it succeeded.
    ///
    /// `try_reclaim` behaves exactly like `reserve`, except that it never allocates new storage
    /// and returns a `bool` indicating whether it was successful in doing so:
    ///
    /// `try_reclaim` returns false under these conditions:
    ///  - The spare capacity left is less than `additional` bytes AND
    ///  - The existing allocation cannot be reclaimed cheaply or it was less than
    ///    `additional` bytes in size
    ///
    /// Reclaiming the allocation cheaply is possible if the [`Utf8BytesMut`] has no outstanding
    /// references through other [`Utf8BytesMut`]s or `Bytes` which point to the same underlying
    /// storage.
    ///
    /// # Examples
    ///
    /// ```
    /// use utf8_bytes::Utf8BytesMut;
    ///
    /// let mut buf = Utf8BytesMut::with_capacity(64);
    /// assert_eq!(true, buf.try_reclaim(64));
    /// assert_eq!(64, buf.capacity());
    ///
    /// buf.extend_from_str("abcd");
    /// let mut split = buf.split();
    /// assert_eq!(60, buf.capacity());
    /// assert_eq!(4, split.capacity());
    /// assert_eq!(false, split.try_reclaim(64));
    /// assert_eq!(false, buf.try_reclaim(64));
    /// // The split buffer is filled with "abcd"
    /// assert_eq!(false, split.try_reclaim(4));
    /// // buf is empty and has capacity for 60 bytes
    /// assert_eq!(true, buf.try_reclaim(60));
    ///
    /// drop(buf);
    /// assert_eq!(false, split.try_reclaim(64));
    ///
    /// split.clear();
    /// assert_eq!(4, split.capacity());
    /// assert_eq!(true, split.try_reclaim(64));
    /// assert_eq!(64, split.capacity());
    /// ```
    // I tried splitting out try_reclaim_inner after the short circuits, but it was inlined
    // regardless with Rust 1.78.0 so probably not worth it
    #[inline]
    #[must_use = "consider BytesMut::reserve if you need an infallible reservation"]
    pub fn try_reclaim(&mut self, additional: usize) -> bool {
        // SAFETY:
        // - does not modify logical contents
        unsafe { self.inner_mut_unchecked() }.try_reclaim(additional)
    }

    /// Appends given bytes to this [`Utf8BytesMut`].
    ///
    /// If this [`Utf8BytesMut`] object does not have enough capacity, it is resized
    /// first.
    ///
    /// # Examples
    ///
    /// ```
    /// use utf8_bytes::Utf8BytesMut;
    ///
    /// let mut buf = Utf8BytesMut::with_capacity(0);
    /// buf.extend_from_str("aaabbb");
    /// buf.extend_from_str("cccddd");
    ///
    /// assert_eq!("aaabbbcccddd", &buf[..]);
    /// ```
    #[inline]
    pub fn extend_from_str(&mut self, extend: &str) {
        // SAFETY:
        // - extend: &str
        unsafe { self.inner_mut_unchecked() }.extend_from_slice(extend.as_bytes());
    }

    /// Absorbs a [`Utf8BytesMut`] that was previously split off.
    ///
    /// If the two [`Utf8BytesMut`] objects were previously contiguous and not mutated
    /// in a way that causes re-allocation i.e., if `other` was created by
    /// calling `split_off` on this [`Utf8BytesMut`], then this is an `O(1)` operation
    /// that just decreases a reference count and sets a few indices.
    /// Otherwise this method degenerates to
    /// `self.extend_from_slice(other.as_ref())`.
    ///
    /// # Examples
    ///
    /// ```
    /// use utf8_bytes::Utf8BytesMut;
    ///
    /// let mut buf = Utf8BytesMut::with_capacity(64);
    /// buf.extend_from_str("aaabbbcccddd");
    ///
    /// let split = buf.split_off(6);
    /// assert_eq!("aaabbb", &buf[..]);
    /// assert_eq!("cccddd", &split[..]);
    ///
    /// buf.unsplit(split);
    /// assert_eq!("aaabbbcccddd", &buf[..]);
    /// ```
    pub fn unsplit(&mut self, other: Utf8BytesMut) {
        // SAFETY:
        // - both buffers are UTF-8, and concatenating UTF-8 is safe.
        unsafe { self.inner_mut_unchecked() }.unsplit(other.into_inner());
    }

    /// Returns the remaining spare capacity of the buffer as a slice of `MaybeUninit<u8>`.
    ///
    /// The returned slice can be used to fill the buffer with data (e.g. by
    /// reading from a file) before marking the data as initialized using the
    /// [`set_len`] method.
    ///
    /// [`set_len`]: Utf8BytesMut::set_len
    ///
    /// # Examples
    ///
    /// ```
    /// use utf8_bytes::Utf8BytesMut;
    ///
    /// // Allocate buffer big enough for 10 bytes.
    /// let mut buf = Utf8BytesMut::with_capacity(10);
    ///
    /// // Fill in the first 3 elements.
    /// let uninit = buf.spare_capacity_mut();
    /// uninit[0].write(b'A');
    /// uninit[1].write(b'B');
    /// uninit[2].write(b'C');
    ///
    /// // Mark the first 3 bytes of the buffer as being initialized.
    /// unsafe {
    ///     buf.set_len(3);
    /// }
    ///
    /// assert_eq!(&buf[..], "ABC");
    /// ```
    #[inline]
    pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<u8>] {
        // SAFETY:
        // - does not logically modify contents
        unsafe { self.inner_mut_unchecked() }.spare_capacity_mut()
    }
}

impl fmt::Debug for Utf8BytesMut {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.as_str().fmt(f)
    }
}

impl fmt::Display for Utf8BytesMut {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.as_str().fmt(f)
    }
}

impl AsRef<[u8]> for Utf8BytesMut {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_str().as_bytes()
    }
}

impl AsRef<str> for Utf8BytesMut {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Deref for Utf8BytesMut {
    type Target = str;

    #[inline]
    fn deref(&self) -> &str {
        self.as_str()
    }
}

impl AsMut<str> for Utf8BytesMut {
    #[inline]
    fn as_mut(&mut self) -> &mut str {
        self.as_mut_str()
    }
}

impl DerefMut for Utf8BytesMut {
    #[inline]
    fn deref_mut(&mut self) -> &mut str {
        self.as_mut_str()
    }
}

impl<'a> From<&'a str> for Utf8BytesMut {
    fn from(src: &'a str) -> Utf8BytesMut {
        unsafe { Self::from_bytes_mut_unchecked(src.as_bytes().into()) }
    }
}

impl From<Utf8BytesMut> for Utf8Bytes {
    fn from(src: Utf8BytesMut) -> Utf8Bytes {
        src.freeze()
    }
}

impl From<Utf8BytesMut> for bytes::BytesMut {
    fn from(src: Utf8BytesMut) -> bytes::BytesMut {
        src.into_inner()
    }
}

impl<T: AsRef<str>> PartialEq<T> for Utf8BytesMut {
    fn eq(&self, other: &T) -> bool {
        self.as_str().eq(other.as_ref())
    }
}

impl Eq for Utf8BytesMut {}

impl<T: AsRef<str>> PartialOrd<T> for Utf8BytesMut {
    fn partial_cmp(&self, other: &T) -> Option<cmp::Ordering> {
        self.as_str().partial_cmp(other.as_ref())
    }
}

impl Ord for Utf8BytesMut {
    fn cmp(&self, other: &Utf8BytesMut) -> cmp::Ordering {
        self.as_str().cmp(other.as_str())
    }
}

impl Default for Utf8BytesMut {
    #[inline]
    fn default() -> Utf8BytesMut {
        Utf8BytesMut::new()
    }
}

impl hash::Hash for Utf8BytesMut {
    fn hash<H>(&self, state: &mut H)
    where
        H: hash::Hasher,
    {
        self.as_str().hash(state);
    }
}

impl Borrow<str> for Utf8BytesMut {
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl BorrowMut<str> for Utf8BytesMut {
    fn borrow_mut(&mut self) -> &mut str {
        self.as_mut_str()
    }
}

impl fmt::Write for Utf8BytesMut {
    #[inline]
    fn write_str(&mut self, s: &str) -> fmt::Result {
        // SAFETY:
        // - s: &str
        unsafe { self.inner_mut_unchecked() }.write_str(s)
    }

    #[inline]
    fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
        // SAFETY:
        // - args emit UTF-8
        unsafe { self.inner_mut_unchecked() }.write_fmt(args)
    }
}

impl Clone for Utf8BytesMut {
    fn clone(&self) -> Utf8BytesMut {
        Utf8BytesMut::from(&self[..])
    }
}

impl Extend<char> for Utf8BytesMut {
    fn extend<T>(&mut self, iter: T)
    where
        T: IntoIterator<Item = char>,
    {
        let iter = iter.into_iter();

        let (lower, _) = iter.size_hint();
        self.reserve(lower);

        for c in iter {
            fmt::Write::write_char(self, c).unwrap()
        }
    }
}

impl<'a> Extend<&'a char> for Utf8BytesMut {
    fn extend<T>(&mut self, iter: T)
    where
        T: IntoIterator<Item = &'a char>,
    {
        self.extend(iter.into_iter().copied())
    }
}

impl Extend<Utf8Bytes> for Utf8BytesMut {
    fn extend<T>(&mut self, iter: T)
    where
        T: IntoIterator<Item = Utf8Bytes>,
    {
        for bytes in iter {
            self.extend_from_str(&bytes)
        }
    }
}

impl FromIterator<char> for Utf8BytesMut {
    fn from_iter<T: IntoIterator<Item = char>>(into_iter: T) -> Self {
        unsafe {
            Self::from_bytes_mut_unchecked(
                String::from_iter(into_iter)
                    .into_bytes()
                    .into_iter()
                    .collect(),
            )
        }
    }
}

impl<'a> FromIterator<&'a char> for Utf8BytesMut {
    fn from_iter<T: IntoIterator<Item = &'a char>>(into_iter: T) -> Self {
        Self::from_iter(into_iter.into_iter().copied())
    }
}

/*
 *
 * ===== PartialEq / PartialOrd =====
 *
 */

impl PartialEq<[u8]> for Utf8BytesMut {
    fn eq(&self, other: &[u8]) -> bool {
        self.as_str().as_bytes() == other
    }
}

impl PartialOrd<[u8]> for Utf8BytesMut {
    fn partial_cmp(&self, other: &[u8]) -> Option<cmp::Ordering> {
        self.as_str().as_bytes().partial_cmp(other)
    }
}

impl PartialEq<Utf8BytesMut> for [u8] {
    fn eq(&self, other: &Utf8BytesMut) -> bool {
        *other == *self
    }
}

impl PartialOrd<Utf8BytesMut> for [u8] {
    fn partial_cmp(&self, other: &Utf8BytesMut) -> Option<cmp::Ordering> {
        <[u8] as PartialOrd<[u8]>>::partial_cmp(self, other.as_bytes())
    }
}

impl PartialEq<str> for Utf8BytesMut {
    fn eq(&self, other: &str) -> bool {
        &**self == other
    }
}

impl PartialOrd<str> for Utf8BytesMut {
    fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
        (**self).partial_cmp(other)
    }
}

impl PartialEq<Utf8BytesMut> for str {
    fn eq(&self, other: &Utf8BytesMut) -> bool {
        *other == *self
    }
}

impl PartialOrd<Utf8BytesMut> for str {
    fn partial_cmp(&self, other: &Utf8BytesMut) -> Option<cmp::Ordering> {
        <str as PartialOrd<str>>::partial_cmp(self, other)
    }
}

impl PartialEq<Utf8BytesMut> for Vec<u8> {
    fn eq(&self, other: &Utf8BytesMut) -> bool {
        self == other.as_bytes()
    }
}

impl PartialEq<Utf8BytesMut> for String {
    fn eq(&self, other: &Utf8BytesMut) -> bool {
        *other == *self
    }
}

impl PartialOrd<Utf8BytesMut> for String {
    fn partial_cmp(&self, other: &Utf8BytesMut) -> Option<cmp::Ordering> {
        <str as PartialOrd<str>>::partial_cmp(self, other)
    }
}

impl PartialEq<Utf8BytesMut> for &[u8] {
    fn eq(&self, other: &Utf8BytesMut) -> bool {
        *self == other.as_bytes()
    }
}

impl PartialOrd<Utf8BytesMut> for &[u8] {
    fn partial_cmp(&self, other: &Utf8BytesMut) -> Option<cmp::Ordering> {
        <[u8] as PartialOrd<[u8]>>::partial_cmp(self, other.as_bytes())
    }
}

impl PartialEq<Utf8BytesMut> for &str {
    fn eq(&self, other: &Utf8BytesMut) -> bool {
        *self == other.as_str()
    }
}

impl PartialOrd<Utf8BytesMut> for &str {
    fn partial_cmp(&self, other: &Utf8BytesMut) -> Option<cmp::Ordering> {
        other.partial_cmp(self)
    }
}

impl PartialEq<Utf8BytesMut> for bytes::Bytes {
    fn eq(&self, other: &Utf8BytesMut) -> bool {
        self == other.as_bytes()
    }
}

impl From<Utf8BytesMut> for Vec<u8> {
    fn from(value: Utf8BytesMut) -> Self {
        value.into_inner().into()
    }
}

impl From<Utf8BytesMut> for String {
    fn from(bytes: Utf8BytesMut) -> Self {
        // SAFETY:
        // - bytes is UTF-8
        unsafe { Self::from_utf8_unchecked(Vec::from(bytes.into_inner())) }
    }
}

impl From<String> for Utf8BytesMut {
    fn from(value: String) -> Self {
        // SAFETY:
        // - value is UTF-8
        unsafe { Self::from_bytes_mut_unchecked(value.into_bytes().into_iter().collect()) }
    }
}