scolapasta_strbuf/
vec.rs

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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::collections::TryReserveError;
use alloc::string::String;
use alloc::vec::{IntoIter, Vec};
use core::borrow::{Borrow, BorrowMut};
use core::fmt;
use core::ops::{Deref, DerefMut};
use core::slice::{Iter, IterMut};
#[cfg(feature = "std")]
use std::io::{self, IoSlice, Write};

use raw_parts::RawParts;

/// A contiguous growable byte string, written as `Buf`, short for 'buffer'.
///
/// This buffer is a transparent wrapper around [`Vec<u8>`] with a minimized API
/// sufficient for implementing the Ruby [`String`] type.
///
/// This buffer does not assume any encoding. Encoding is a higher-level concept
/// that should be built on top of `Buf`.
///
/// # Examples
///
/// ```
/// use scolapasta_strbuf::Buf;
///
/// let mut buf = Buf::new();
/// buf.push_byte(b'a');
/// buf.push_byte(b'z');
///
/// assert_eq!(buf.len(), 2);
/// assert_eq!(buf[0], b'a');
///
/// assert_eq!(buf.pop_byte(), Some(b'z'));
/// assert_eq!(buf.len(), 1);
///
/// buf[0] = b'!';
/// assert_eq!(buf[0], b'!');
///
/// buf.extend(b"excite!!!");
///
/// for byte in &buf {
///     println!("{byte}");
/// }
/// assert_eq!(buf, b"!excite!!!");
/// ```
///
/// # Indexing
///
/// The `Buf` type allows to access values by index, because it implements the
/// [`Index`] trait. An example will be more explicit:
///
/// ```
/// use scolapasta_strbuf::Buf;
///
/// let buf = Buf::from(b"scolapasta-strbuf");
/// println!("{}", buf[1]); // it will display 'c'
/// ```
///
/// However be careful: if you try to access an index which isn't in the `Buf`,
/// your software will panic! You cannot do this:
///
/// ```should_panic
/// use scolapasta_strbuf::Buf;
///
/// let buf = Buf::from(b"scolapasta-strbuf");
/// println!("{}", buf[100]); // it will panic!
/// ```
///
/// # Capacity and reallocation
///
/// The capacity of a buffer is the amount of space allocated for any future
/// bytes that will be added onto the buffer. This is not to be confused with
/// the _length_ of a buffer, which specifies the number of actual bytes within
/// the buffer. If a buffer's length exceeds its capacity, its capacity will
/// automatically be increased, but its contents will have to be reallocated.
///
/// For example, a buffer with capacity 10 and length 0 would be an empty buffer
/// with space for 10 more bytes. Pushing 10 or fewer bytes into the buffer will
/// not change its capacity or cause reallocation to occur. However, if the
/// buffer's length is increased to 11, it will have to reallocate, which can be
/// slow. For this reason, it is recommended to use `Buf::with_capacity`
/// whenever possible to specify how big the buffer is expected to get.
///
/// # Guarantees
///
/// `Buf` is guaranteed to be a `repr(transparent)` wrapper around a `Vec<u8>`,
/// which means it shares all the same [guarantees as a `Vec`]. See the upstream
/// documentation in [`std`][vec-docs] for more details.
///
/// [`Vec<u8>`]: Vec
/// [`String`]: https://ruby-doc.org/3.2.0/String.html
/// [`Index`]: core::ops::Index
/// [guarantees as a `Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#guarantees
/// [vec-docs]: mod@alloc::vec
#[repr(transparent)]
#[derive(Default, Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Buf {
    inner: Vec<u8>,
}

impl Buf {
    /// Consume this buffer and return its inner [`Vec<u8>`].
    ///
    /// # Examples
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let buf = Buf::from(b"abc");
    /// let vec: Vec<u8> = buf.into_inner();
    /// assert_eq!(vec, b"abc");
    /// ```
    ///
    /// [`Vec<u8>`]: Vec
    #[inline]
    #[must_use]
    pub fn into_inner(self) -> Vec<u8> {
        self.inner
    }
}

impl From<Vec<u8>> for Buf {
    #[inline]
    fn from(vec: Vec<u8>) -> Self {
        Self { inner: vec }
    }
}

impl<'a> From<&'a [u8]> for Buf {
    #[inline]
    fn from(s: &'a [u8]) -> Self {
        let vec = s.to_vec();
        Self::from(vec)
    }
}

impl<'a> From<&'a mut [u8]> for Buf {
    #[inline]
    fn from(s: &'a mut [u8]) -> Self {
        let vec = s.to_vec();
        Self::from(vec)
    }
}

impl<const N: usize> From<[u8; N]> for Buf {
    #[inline]
    fn from(s: [u8; N]) -> Self {
        let vec = Vec::from(s);
        Self::from(vec)
    }
}

impl<'a, const N: usize> From<&'a [u8; N]> for Buf {
    #[inline]
    fn from(s: &'a [u8; N]) -> Self {
        let vec = s.to_vec();
        Self::from(vec)
    }
}

impl<'a, const N: usize> From<&'a mut [u8; N]> for Buf {
    #[inline]
    fn from(s: &'a mut [u8; N]) -> Self {
        let vec = s.to_vec();
        Self::from(vec)
    }
}

impl<'a> From<Cow<'a, [u8]>> for Buf {
    #[inline]
    fn from(s: Cow<'a, [u8]>) -> Self {
        let vec = s.into_owned();
        Self::from(vec)
    }
}

impl From<String> for Buf {
    #[inline]
    fn from(s: String) -> Self {
        let vec = s.into_bytes();
        Self::from(vec)
    }
}

impl<'a> From<&'a str> for Buf {
    #[inline]
    fn from(s: &'a str) -> Self {
        let vec = s.as_bytes().to_vec();
        Self::from(vec)
    }
}

impl<'a> From<&'a mut str> for Buf {
    #[inline]
    fn from(s: &'a mut str) -> Self {
        let vec = s.as_bytes().to_vec();
        Self::from(vec)
    }
}

impl<'a> From<Cow<'a, str>> for Buf {
    #[inline]
    fn from(s: Cow<'a, str>) -> Self {
        let vec = s.into_owned().into_bytes();
        Self::from(vec)
    }
}

impl From<Buf> for Vec<u8> {
    #[inline]
    fn from(buf: Buf) -> Self {
        buf.inner
    }
}

impl<const N: usize> TryFrom<Buf> for [u8; N] {
    type Error = Buf;

    #[inline]
    fn try_from(buf: Buf) -> Result<Self, Self::Error> {
        match buf.into_inner().try_into() {
            Ok(array) => Ok(array),
            Err(vec) => Err(vec.into()),
        }
    }
}

impl From<Buf> for Cow<'_, [u8]> {
    #[inline]
    fn from(buf: Buf) -> Self {
        Cow::Owned(buf.into())
    }
}

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

impl AsMut<[u8]> for Buf {
    #[inline]
    fn as_mut(&mut self) -> &mut [u8] {
        self.inner.as_mut()
    }
}

impl Borrow<[u8]> for Buf {
    fn borrow(&self) -> &[u8] {
        self
    }
}

impl BorrowMut<[u8]> for Buf {
    fn borrow_mut(&mut self) -> &mut [u8] {
        self
    }
}

impl Deref for Buf {
    type Target = [u8];

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl DerefMut for Buf {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl FromIterator<u8> for Buf {
    #[inline]
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = u8>,
    {
        let inner = iter.into_iter().collect();
        Self { inner }
    }
}

impl Extend<u8> for Buf {
    #[inline]
    fn extend<I: IntoIterator<Item = u8>>(&mut self, iter: I) {
        self.inner.extend(iter);
    }
}

impl<'a> Extend<&'a u8> for Buf {
    #[inline]
    fn extend<I: IntoIterator<Item = &'a u8>>(&mut self, iter: I) {
        self.inner.extend(iter.into_iter().copied());
    }
}

impl_partial_eq!(Buf, Vec<u8>);
impl_partial_eq!(Buf, &'a Vec<u8>);
impl_partial_eq!(Buf, [u8]);
impl_partial_eq!(Buf, &'a [u8]);
impl_partial_eq!(Buf, &'a mut [u8]);
impl_partial_eq!(Buf, String);
impl_partial_eq!(Buf, &'a String);
impl_partial_eq!(Buf, str);
impl_partial_eq!(Buf, &'a str);
impl_partial_eq!(Buf, &'a mut str);
impl_partial_eq_array!(Buf, [u8; N]);
impl_partial_eq_array!(Buf, &'a [u8; N]);
impl_partial_eq_array!(Buf, &'a mut [u8; N]);

impl IntoIterator for Buf {
    type Item = u8;
    type IntoIter = IntoIter<u8>;

    fn into_iter(self) -> Self::IntoIter {
        self.into_inner().into_iter()
    }
}

impl<'a> IntoIterator for &'a Buf {
    type Item = &'a u8;
    type IntoIter = Iter<'a, u8>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a> IntoIterator for &'a mut Buf {
    type Item = &'a mut u8;
    type IntoIter = IterMut<'a, u8>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

/// Minimal [`Vec`] API.
impl Buf {
    /// Constructs a new, empty `Buf`.
    ///
    /// The buffer will not allocate until bytes are pushed into it.
    ///
    /// # Examples
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::new();
    /// ```
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        let inner = Vec::new();
        Self { inner }
    }

    /// Constructs a new, empty `Buf` with at least the specified capacity.
    ///
    /// The buffer will be able to hold at least `capacity` bytes without
    /// reallocating. This method is allowed to allocate for more elements than
    /// `capacity`. If `capacity` is 0, the buffer will not allocate.
    ///
    /// It is important to note that although the returned buffer has the
    /// minimum *capacity* specified, the vector will have a zero *length*. For
    /// an explanation of the difference between length and capacity, see
    /// *[Capacity and reallocation]*.
    ///
    /// If it is important to know the exact allocated capacity of a `Buf`,
    /// always use the [`capacity`] method after construction.
    ///
    /// [Capacity and reallocation]: #capacity-and-reallocation
    /// [`capacity`]: Self::capacity
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `isize::MAX` bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::with_capacity(26);
    ///
    /// // The buffer is empty, even though it has capacity for more
    /// assert_eq!(buf.len(), 0);
    /// assert!(buf.capacity() >= 26);
    ///
    /// // These are all done without reallocating...
    /// for ch in b'a'..=b'z' {
    ///     buf.push_byte(ch);
    /// }
    /// assert_eq!(buf.len(), 26);
    /// assert!(buf.capacity() >= 26);
    ///
    /// // ...but this may make the buffer reallocate
    /// buf.push_byte(b'!');
    /// assert_eq!(buf.len(), 27);
    /// assert!(buf.capacity() >= 27);
    /// ```
    #[inline]
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        let inner = Vec::with_capacity(capacity);
        Self { inner }
    }

    /// Creates a `Buf` directly from a pointer, a capacity, and a length.
    ///
    /// # Safety
    ///
    /// This is highly unsafe, due to the number of invariants that aren't
    /// checked.
    ///
    /// Refer to the safety documentation for [`Vec::from_raw_parts`] for more
    /// details.
    ///
    /// # Examples
    ///
    /// ```
    /// use core::ptr;
    ///
    /// use raw_parts::RawParts;
    /// use scolapasta_strbuf::Buf;
    ///
    /// let buf = Buf::from(b"abcde");
    /// let RawParts { ptr, length, capacity } = buf.into_raw_parts();
    ///
    /// unsafe {
    ///     ptr::write(ptr, b'A');
    ///     ptr::write(ptr.add(1), b'B');
    ///
    ///     let raw_parts = RawParts { ptr, length, capacity };
    ///     let rebuilt = Buf::from_raw_parts(raw_parts);
    ///
    ///     assert_eq!(rebuilt, b"ABcde");
    /// }
    /// ```
    #[inline]
    #[must_use]
    pub unsafe fn from_raw_parts(raw_parts: RawParts<u8>) -> Self {
        // SAFETY: Callers ensure that the raw parts safety invariants are
        // upheld.
        let inner = unsafe { raw_parts.into_vec() };
        Self { inner }
    }

    /// Decomposes a `Buf` into its raw components.
    ///
    /// Returns the raw pointer to the underlying bytes, the length of the
    /// buffer (in bytes), and the allocated capacity of the data (in bytes).
    ///
    /// After calling this function, the caller is responsible for the memory
    /// previously managed by the `Buf`. The only way to do this is to convert
    /// the raw pointer, length, and capacity back into a `Buf` with the
    /// [`from_raw_parts`] function, allowing the destructor to perform the cleanup.
    ///
    /// [`from_raw_parts`]: Self::from_raw_parts
    ///
    /// # Examples
    ///
    /// ```
    /// use core::ptr;
    ///
    /// use raw_parts::RawParts;
    /// use scolapasta_strbuf::Buf;
    ///
    /// let buf = Buf::from(b"abcde");
    /// let RawParts { ptr, length, capacity } = buf.into_raw_parts();
    ///
    /// unsafe {
    ///     ptr::write(ptr, b'A');
    ///     ptr::write(ptr.add(1), b'B');
    ///
    ///     let raw_parts = RawParts { ptr, length, capacity };
    ///     let rebuilt = Buf::from_raw_parts(raw_parts);
    ///
    ///     assert_eq!(rebuilt, b"ABcde");
    /// }
    /// ```
    #[inline]
    #[must_use]
    pub fn into_raw_parts(self) -> RawParts<u8> {
        RawParts::from_vec(self.inner)
    }

    /// Returns the total number of bytes the buffer can hold without
    /// reallocating.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(not(feature = "nul-terminated"))]
    /// # {
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::with_capacity(10);
    /// buf.push_byte(b'!');
    /// assert_eq!(buf.capacity(), 10);
    /// # }
    /// ```
    #[inline]
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.inner.capacity()
    }

    /// Reserves capacity for at least `additional` more bytes to be inserted in
    /// the given `Buf`.
    ///
    /// The buffer may reserve more space to speculatively avoid frequent
    /// reallocations. After calling `reserve`, capacity will be greater than or
    /// equal to `self.len() + additional`. Does nothing if capacity is already
    /// sufficient.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `isize::MAX` bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::from(b"@");
    /// buf.reserve(10);
    /// assert!(buf.capacity() >= 11);
    /// ```
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        self.inner.reserve(additional);
    }

    /// Reserves the minimum capacity for at least `additional` more bytes to
    /// be inserted in the given `Buf`.
    ///
    /// Unlike [`reserve`], this will not deliberately over-allocate to
    /// speculatively avoid frequent allocations. After calling `reserve_exact`,
    /// capacity will be greater than or equal to `self.len() + additional`.
    /// Does nothing if the capacity is already sufficient.
    ///
    /// Note that the allocator may give the buffer more space than it requests.
    /// Therefore, capacity can not be relied upon to be precisely minimal.
    /// Prefer [`reserve`] if future insertions are expected.
    ///
    /// [`reserve`]: Self::reserve
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `isize::MAX` bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::from(b"@");
    /// buf.reserve_exact(10);
    /// assert!(buf.capacity() >= 11);
    /// ```
    #[inline]
    pub fn reserve_exact(&mut self, additional: usize) {
        self.inner.reserve_exact(additional);
    }

    /// Tries to reserve capacity for at least `additional` more bytes to be
    /// inserted in the given `Buf`.
    ///
    /// The buffer may reserve more space to speculatively avoid frequent
    /// reallocations. After calling `try_reserve`, capacity will be greater
    /// than or equal to `self.len() + additional` if it returns `Ok(())`. Does
    /// nothing if capacity is already sufficient. This method preserves the
    /// byte contents even if an error occurs.
    ///
    /// # Errors
    ///
    /// If the capacity overflows, or the allocator reports a failure, then an
    /// error is returned.
    #[inline]
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
        self.inner.try_reserve(additional)
    }

    /// Tries to reserve the minimum capacity for at least `additional`
    /// elements to be inserted in the given `Buf`.
    ///
    /// Unlike [`try_reserve`], this will not deliberately over-allocate to
    /// speculatively avoid frequent allocations. After calling
    /// `try_reserve_exact`, capacity will be greater than or equal to
    /// `self.len() + additional` if it returns `Ok(())`. Does nothing if the
    /// capacity is already sufficient.
    ///
    /// Note that the allocator may give the buffer more space than it requests.
    /// Therefore, capacity can not be relied upon to be precisely minimal.
    /// Prefer [`try_reserve`] if future insertions are expected.
    ///
    /// [`try_reserve`]: Self::try_reserve
    ///
    /// # Errors
    ///
    /// If the capacity overflows, or the allocator reports a failure, then an
    /// error is returned.
    #[inline]
    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
        self.inner.try_reserve_exact(additional)
    }

    /// Shrinks the capacity of the buffer as much as possible.
    ///
    /// It will drop down as close as possible to the length but the allocator
    /// may still inform the buffer that there is space for a few more bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(not(feature = "nul-terminated"))]
    /// # {
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::with_capacity(10);
    /// buf.extend(b"123");
    /// assert_eq!(buf.capacity(), 10);
    /// buf.shrink_to(4);
    /// assert!(buf.capacity() >= 4);
    /// buf.shrink_to_fit();
    /// assert!(buf.capacity() >= 3);
    /// # }
    /// ```
    #[inline]
    pub fn shrink_to_fit(&mut self) {
        self.inner.shrink_to_fit();
    }

    /// Shrinks the capacity of the buffer with a lower bound.
    ///
    /// The capacity will remain at least as large as both the length and the
    /// supplied value.
    ///
    /// If the current capacity is less than the lower limit, this is a no-op.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(not(feature = "nul-terminated"))]
    /// # {
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::with_capacity(10);
    /// buf.extend(b"123");
    /// assert_eq!(buf.capacity(), 10);
    /// buf.shrink_to(4);
    /// assert!(buf.capacity() >= 4);
    /// buf.shrink_to(0);
    /// assert!(buf.capacity() >= 3);
    /// # }
    /// ```
    #[inline]
    pub fn shrink_to(&mut self, min_capacity: usize) {
        self.inner.shrink_to(min_capacity);
    }

    /// Converts the buffer into [`Box<[u8]>`][owned slice].
    ///
    /// If the buffer has excess capacity, its bytes will be moved into a
    /// newly-allocated buffer with exactly the right capacity.
    ///
    /// [owned slice]: Box
    ///
    /// # Examples
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let buf = Buf::from(b"123");
    ///
    /// let slice = buf.into_boxed_slice();
    /// ```
    ///
    /// Any excess capacity is removed:
    ///
    /// ```
    /// # #[cfg(not(feature = "nul-terminated"))]
    /// # {
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::with_capacity(10);
    /// buf.extend(b"123");
    ///
    /// assert_eq!(buf.capacity(), 10);
    /// let slice = buf.into_boxed_slice();
    /// assert_eq!(slice.into_vec().capacity(), 3);
    /// # }
    /// ```
    #[inline]
    #[must_use]
    pub fn into_boxed_slice(self) -> Box<[u8]> {
        self.inner.into_boxed_slice()
    }

    /// Shorten 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.
    ///
    /// Note that this method has no effect on the allocated capacity of the
    /// buffer.
    ///
    /// # Examples
    ///
    /// Truncating a five byte buffer to two bytes:
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::from(b"12345");
    /// buf.truncate(2);
    /// assert_eq!(buf, b"12");
    /// ```
    ///
    /// No truncation occurs when `len` is greater than the buffer's current
    /// length:
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::from(b"123");
    /// buf.truncate(8);
    /// assert_eq!(buf, b"123");
    /// ```
    ///
    /// Truncating when `len == 0` is equivalent to calling the [`clear`]
    /// method.
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::from(b"123");
    /// buf.truncate(0);
    /// assert_eq!(buf, b"");
    /// ```
    ///
    /// [`clear`]: Self::clear
    #[inline]
    pub fn truncate(&mut self, len: usize) {
        self.inner.truncate(len);
    }

    /// Extract a slice containing the entire buffer.
    ///
    /// Equivalent to `&buf[..]`.
    #[inline]
    #[must_use]
    pub fn as_slice(&self) -> &[u8] {
        self.inner.as_slice()
    }

    /// Extract a mutable slice containing the entire buffer.
    ///
    /// Equivalent to `&mut buf[..]`.
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [u8] {
        self.inner.as_mut_slice()
    }

    /// Return a raw pointer to the buffer's inner vec, or a dangling raw
    /// pointer valid for zero sized reads if the buffer didn't allocate.
    ///
    /// The caller must ensure correct use of the pointer. See [`Vec::as_ptr`]
    /// for more details.
    #[inline]
    #[must_use]
    pub fn as_ptr(&self) -> *const u8 {
        self.inner.as_ptr()
    }

    /// Return an unsafe mutable pointer to the buffer's inner vec, or a
    /// dangling raw pointer valid for zero sized reads if the buffer didn't
    /// allocate.
    ///
    /// The caller must ensure correct use of the pointer. See [`Vec::as_mut_ptr`]
    /// for more details.
    #[inline]
    #[must_use]
    pub fn as_mut_ptr(&mut self) -> *mut u8 {
        self.inner.as_mut_ptr()
    }

    /// Force the length of the buffer to `new_len`.
    ///
    /// This is a low-level operation that maintains none of the normal
    /// invariants of the type. Normally changing the length of a vector is done
    /// using one of the safe operations instead, such as [`truncate`],
    /// [`resize`], [`extend`], or [`clear`].
    ///
    /// [`truncate`]: Self::truncate
    /// [`resize`]: Self::resize
    /// [`extend`]: Self::extend
    /// [`clear`]: Self::clear
    ///
    /// # Safety
    ///
    /// - `new_len` must be less than or equal to [`capacity()`].
    /// - The elements at `old_len..new_len` must be initialized.
    ///
    /// [`capacity()`]: Self::capacity
    #[inline]
    pub unsafe fn set_len(&mut self, new_len: usize) {
        // SAFETY: Caller has guaranteed the safety invariants of `Vec::set_len`
        // are upheld.
        unsafe {
            self.inner.set_len(new_len);
        }
    }

    /// Insert a byte at position `index` within the buffer, shifting all
    /// elements after it to the right.
    ///
    /// # Panics
    ///
    /// Panics if `index > len`.
    ///
    /// # Examples
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::from(b"123");
    /// buf.insert(1, b'4');
    /// assert_eq!(buf, b"1423");
    /// buf.insert(4, b'5');
    /// assert_eq!(buf, b"14235");
    /// ```
    #[inline]
    pub fn insert(&mut self, index: usize, element: u8) {
        self.inner.insert(index, element);
    }

    /// Remove and return the byte at position `index` within the buffer,
    /// shifting all bytes after it to the left.
    ///
    /// **Note**: Because this shifts over the remaining bytes, it has a
    /// worst-case performance of *O*(*n*).
    ///
    /// # Panics
    ///
    /// Panics if `index` is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::from(b"123");
    /// assert_eq!(buf.remove(1), b'2');
    /// assert_eq!(buf, b"13");
    /// ```
    #[inline]
    #[track_caller]
    pub fn remove(&mut self, index: usize) -> u8 {
        self.inner.remove(index)
    }

    /// Retain only the bytes specified by the predicate.
    ///
    /// In other words, remove all bytes `b` for which `f(&b)` returns `false`.
    /// This method operates in place, visiting each byte exactly once in the
    /// original order, and preserves the order of the retained bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::from(b"abc, 123!");
    /// buf.retain(|&b| b.is_ascii_alphanumeric());
    /// assert_eq!(buf, b"abc123");
    /// ```
    ///
    /// Because the bytes are visited exactly once in the original order,
    /// external state may be used to decide which elements to keep.
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::from(b"abc, 123!");
    /// let mut seen_space = false;
    /// buf.retain(|&b| {
    ///     if seen_space {
    ///         true
    ///     } else {
    ///         seen_space = b.is_ascii_whitespace();
    ///         false
    ///     }
    /// });
    /// assert_eq!(buf, b"123!");
    /// ```
    #[inline]
    pub fn retain<F>(&mut self, f: F)
    where
        F: FnMut(&u8) -> bool,
    {
        self.inner.retain(f);
    }

    /// Remove the last byte from the buffer and return it, or [`None`] if the
    /// buffer is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::from(b"abc, 123!");
    /// assert_eq!(buf.pop_byte(), Some(b'!'));
    /// assert_eq!(buf, "abc, 123");
    /// ```
    #[inline]
    pub fn pop_byte(&mut self) -> Option<u8> {
        self.inner.pop()
    }

    /// Clear the buffer, removing all bytes.
    ///
    /// This method sets the length of the buffer to zero. Note that this method
    /// has no effect on the allocated capacity of the buffer.
    ///
    /// # Examples
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::from(b"abc, 123!");
    /// let capacity = buf.capacity();
    ///
    /// buf.clear();
    ///
    /// assert!(buf.is_empty());
    /// assert_eq!(buf.capacity(), capacity);
    /// ```
    #[inline]
    pub fn clear(&mut self) {
        self.inner.clear();
    }

    /// Return the number of bytes in the buffer, also referred to as its
    /// 'length' or 'bytesize'.
    ///
    /// # Examples
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let buf = Buf::from(b"abc");
    /// assert_eq!(buf.len(), 3);
    /// ```
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Return `true` if the buffer has empty byte content.
    ///
    /// # Examples
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::new();
    /// assert!(buf.is_empty());
    ///
    /// buf.push_byte(b'!');
    /// assert!(!buf.is_empty());
    /// ```
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Resize the `Buf` in-place so that `len` is equal to `new_len`.
    ///
    /// If `new_len` is greater than `len`, the `Vec` is extended by the
    /// difference, with each additional slot filled with `value`. If `new_len`
    /// is less than `len`, the `Buf` is simply truncated.
    ///
    /// # Examples
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::from(b"hello");
    /// buf.resize(8, b'!');
    /// assert_eq!(buf, b"hello!!!");
    ///
    /// let mut buf = Buf::from("wxyz");
    /// buf.resize(2, b'.');
    /// assert_eq!(buf, b"wx");
    /// ```
    #[inline]
    pub fn resize(&mut self, new_len: usize, value: u8) {
        self.inner.resize(new_len, value);
    }

    /// Copy and append all bytes in the given slice to the `Buf`.
    ///
    /// Iterate over the slice `other`, copy each byte, and then append
    /// it to this `Buf`. The `other` slice is traversed in-order.
    ///
    /// # Examples
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::from(b"h");
    /// buf.extend_from_slice(b"ello world");
    /// assert_eq!(buf, b"hello world");
    /// ```
    #[inline]
    pub fn extend_from_slice(&mut self, other: &[u8]) {
        self.inner.extend_from_slice(other);
    }
}

/// Implementation of useful extension methods from [`bstr::ByteVec`].
///
/// [`bstr::ByteVec`]: https://docs.rs/bstr/latest/bstr/trait.ByteVec.html
impl Buf {
    /// Append the given byte to the end of this buffer.
    ///
    /// Note that this is equivalent to the generic [`Vec::push`] method. This
    /// method is provided to permit callers to explicitly differentiate
    /// between pushing bytes, codepoints and strings.
    ///
    /// # Examples
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::from(b"abc");
    /// buf.push_byte(b'\xF0');
    /// buf.push_byte(b'\x9F');
    /// buf.push_byte(b'\xA6');
    /// buf.push_byte(b'\x80');
    /// assert_eq!(buf, "abc🦀");
    /// ```
    #[inline]
    pub fn push_byte(&mut self, byte: u8) {
        self.inner.push(byte);
    }

    /// Append the given [`char`] to the end of the buffer.
    ///
    /// The given `char` is encoded to its UTF-8 byte sequence which is appended
    /// to the buffer.
    ///
    /// # Examples
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::from(b"abc");
    /// buf.push_char('🦀');
    /// assert_eq!(buf, "abc🦀");
    /// ```
    #[inline]
    pub fn push_char(&mut self, ch: char) {
        let mut buf = [0; 4];
        let s = ch.encode_utf8(&mut buf[..]);
        self.push_str(s);
    }

    /// Append the given slice to the end of this buffer.
    ///
    /// This method accepts any type that be converted to a `&[u8]`. This
    /// includes, but is not limited to, `&str`, `&Buf`, and of course, `&[u8]`
    /// itself.
    ///
    /// # Examples
    ///
    /// ```
    /// use scolapasta_strbuf::Buf;
    ///
    /// let mut buf = Buf::from(b"abc");
    /// buf.push_str("🦀");
    /// assert_eq!(buf, "abc🦀");
    ///
    /// buf.push_str(b"\xF0\x9F\xA6\x80");
    /// assert_eq!(buf, "abc🦀🦀");
    /// ```
    #[inline]
    pub fn push_str<B: AsRef<[u8]>>(&mut self, bytes: B) {
        self.extend_from_slice(bytes.as_ref());
    }
}

impl fmt::Write for Buf {
    #[inline]
    fn write_str(&mut self, s: &str) -> fmt::Result {
        self.push_str(s);
        Ok(())
    }

    #[inline]
    fn write_char(&mut self, c: char) -> fmt::Result {
        self.push_char(c);
        Ok(())
    }
}

#[cfg(feature = "std")]
impl Write for Buf {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.inner.write(buf)
    }

    #[inline]
    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
        self.inner.write_vectored(bufs)
    }

    #[inline]
    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
        self.inner.write_all(buf)
    }

    #[inline]
    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}

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

    #[test]
    fn default_is_new() {
        assert_eq!(Buf::default(), Buf::new());
    }

    #[test]
    fn extra_capa_is_not_included_in_len() {
        let buf = Buf::new();
        assert!(buf.is_empty());
        assert_eq!(buf.len(), 0);

        let buf = Buf::with_capacity(0);
        assert!(buf.is_empty());
        assert_eq!(buf.len(), 0);

        let buf = Buf::with_capacity(100);
        assert!(buf.is_empty());
        assert_eq!(buf.len(), 0);
    }

    #[test]
    fn clone_is_equal() {
        let buf = Buf::from("abc");
        assert_eq!(buf, buf.clone());
    }

    #[test]
    fn try_reserve_overflow_is_err() {
        let mut buf = Buf::new();
        assert!(buf.try_reserve(usize::MAX).is_err());
        assert!(buf.is_empty());
        assert_eq!(buf.len(), 0);
    }

    #[test]
    fn try_reserve_exact_overflow_is_err() {
        let mut buf = Buf::new();
        assert!(buf.try_reserve_exact(usize::MAX).is_err());
        assert!(buf.is_empty());
        assert_eq!(buf.len(), 0);
    }

    #[test]
    fn try_reserve_zero_is_ok() {
        let mut buf = Buf::new();
        assert!(buf.try_reserve(0).is_ok());
        assert_eq!(buf.capacity(), 0);
        assert!(buf.is_empty());
        assert_eq!(buf.len(), 0);
    }

    #[test]
    fn try_reserve_exact_zero_is_ok() {
        let mut buf = Buf::new();
        assert!(buf.try_reserve_exact(0).is_ok());
        assert_eq!(buf.capacity(), 0);
        assert!(buf.is_empty());
        assert_eq!(buf.len(), 0);
    }
}