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
use core::{
    borrow::{Borrow, BorrowMut},
    fmt::{self, Debug, Display},
    hash::Hash,
    ops::{Deref, DerefMut, Range, RangeBounds},
    ptr, str,
};

use allocator_api2::alloc::{AllocError, Allocator};

#[cfg(feature = "alloc")]
use allocator_api2::alloc::Global;

use crate::{
    error_behavior_generic_methods, polyfill, BumpBox, BumpScope, BumpVec, ErrorBehavior, FromUtf8Error, MinimumAlignment,
    Stats, SupportedMinimumAlignment,
};

#[cfg(not(no_global_oom_handling))]
use crate::infallible;

/// This is like [`format!`] but allocates inside a `Bump` or `BumpScope`, returning a [`BumpString`].
///
/// If you don't need a `BumpString` you can use [`alloc_fmt`](crate::Bump::alloc_fmt) instead, which does not require a mutable `$bump`.
///
/// # Panics
/// If used without `try`, panics on allocation failure or if a formatting trait implementation returns an error.
///
/// # Errors
/// If used with `try`, errors on allocation failure or if a formatting trait implementation returns an error.
///
/// # Examples
///
/// ```
/// # use bump_scope::{ Bump, bump_format };
/// # let bump: Bump = Bump::new();
/// #
/// let greeting = "Hello";
/// let mut string = bump_format!(in bump, "{greeting} world!");
/// string.push_str(" How are you?");
///
/// assert_eq!(string, "Hello world! How are you?");
/// ```
#[macro_export]
macro_rules! bump_format {
    (in $bump:expr) => {{
        $crate::BumpString::new_in($bump.as_scope())
    }};
    (in $bump:expr, $($arg:tt)*) => {{
        let mut string = $crate::BumpString::new_in($bump.as_scope());
        match $crate::private::core::fmt::Write::write_fmt(&mut string, $crate::private::core::format_args!($($arg)*)) {
            $crate::private::core::result::Result::Ok(_) => string,
            $crate::private::core::result::Result::Err(_) => $crate::private::capacity_overflow(),
        }
    }};
    (try in $bump:expr) => {{
        Ok::<_, $crate::allocator_api2::alloc::AllocError>($crate::BumpString::new_in($bump.as_scope()))
    }};
    (try in $bump:expr, $($arg:tt)*) => {{
        let mut string = $crate::BumpString::new_in($bump.as_scope());
        match $crate::private::core::fmt::Write::write_fmt(&mut string, $crate::private::core::format_args!($($arg)*)) {
            $crate::private::core::result::Result::Ok(_) => $crate::private::core::result::Result::Ok(string),
            $crate::private::core::result::Result::Err(_) => $crate::private::core::result::Result::Err($crate::allocator_api2::alloc::AllocError),
        }
    }};
}

/// A bump allocated [`String`].
///
/// When you are done building the string, you can turn it into a `&str` with [`into_str`].
///
/// # Examples
///
/// You can create a `BumpString` from [a literal string][`&str`] with [`BumpString::from_str_in`]:
///
/// [`into_str`]: BumpString::into_str
///
/// ```
/// # use bump_scope::{ Bump, BumpString };
/// # let bump: Bump = Bump::new();
/// let hello = BumpString::from_str_in("Hello, world!", &bump);
/// ```
///
/// You can append a [`char`] to a `String` with the [`push`] method, and
/// append a [`&str`] with the [`push_str`] method:
///
/// ```
/// # use bump_scope::{ Bump, BumpString };
/// # let bump: Bump = Bump::new();
/// let mut hello = BumpString::from_str_in("Hello, ", &bump);
///
/// hello.push('w');
/// hello.push_str("orld!");
///
/// assert_eq!(hello.as_str(), "Hello, world!");
/// ```
///
/// [`push`]: BumpString::push
/// [`push_str`]: BumpString::push_str
///
/// If you have a vector of UTF-8 bytes, you can create a `BumpString` from it with
/// the [`from_utf8`] method:
///
/// ```
/// # use bump_scope::{ Bump, BumpString, bump_vec };
/// # let bump: Bump = Bump::new();
/// // some bytes, in a vector
/// let sparkle_heart = bump_vec![in bump; 240, 159, 146, 150];
///
/// // We know these bytes are valid, so we'll use `unwrap()`.
/// let sparkle_heart = BumpString::from_utf8(sparkle_heart).unwrap();
///
/// assert_eq!("💖", sparkle_heart);
/// ```
///
/// [`&str`]: prim@str "&str"
/// [`from_utf8`]: BumpString::from_utf8
pub struct BumpString<
    'b,
    'a: 'b,
    #[cfg(feature = "alloc")] A = Global,
    #[cfg(not(feature = "alloc"))] A,
    const MIN_ALIGN: usize = 1,
    const UP: bool = true,
> {
    vec: BumpVec<'b, 'a, u8, A, MIN_ALIGN, UP>,
}

impl<'b, 'a: 'b, const MIN_ALIGN: usize, const UP: bool, A> BumpString<'b, 'a, A, MIN_ALIGN, UP> {
    /// Returns this `BumpString`'s capacity, in bytes.
    #[must_use]
    #[inline(always)]
    pub const fn capacity(&self) -> usize {
        self.vec.capacity()
    }

    /// Returns the length of this `BumpString`, in bytes, not [`char`]s or
    /// graphemes. In other words, it might not be what a human considers the
    /// length of the string.
    #[must_use]
    #[inline(always)]
    pub fn len(&self) -> usize {
        self.vec.len()
    }

    /// Returns `true` if this `BumpString` has a length of zero, and `false` otherwise.
    #[must_use]
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.vec.is_empty()
    }

    /// Truncates this `BumpString`, removing all contents.
    ///
    /// While this means the `BumpString` will have a length of zero, it does not
    /// touch its capacity.
    ///
    /// # Examples
    ///
    /// ```
    /// # use bump_scope::{ Bump, BumpString };
    /// # let bump: Bump = Bump::new();
    /// #
    /// let mut s = BumpString::from_str_in("foo", &bump);
    ///
    /// s.clear();
    ///
    /// assert!(s.is_empty());
    /// assert_eq!(s.len(), 0);
    /// assert!(s.capacity() >= 3);
    /// ```
    #[inline]
    pub fn clear(&mut self) {
        self.vec.clear();
    }

    /// Converts a bump allocated vector of bytes to a `BumpString`.
    ///
    /// A string ([`BumpString`]) is made of bytes ([`u8`]), and a vector of bytes
    /// ([`BumpVec<u8>`]) is made of bytes, so this function converts between the
    /// two. Not all byte slices are valid `BumpString`s, however: `BumpString`
    /// requires that it is valid UTF-8. `from_utf8()` checks to ensure that
    /// the bytes are valid UTF-8, and then does the conversion.
    ///
    /// If you are sure that the byte slice is valid UTF-8, and you don't want
    /// to incur the overhead of the validity check, there is an unsafe version
    /// of this function, [`from_utf8_unchecked`], which has the same behavior
    /// but skips the check.
    ///
    /// This method will take care to not copy the vector, for efficiency's
    /// sake.
    ///
    /// If you need a [`&str`] instead of a `BumpString`, consider
    /// [`str::from_utf8`].
    ///
    /// The inverse of this method is [`into_bytes`].
    ///
    /// # Errors
    ///
    /// Returns [`Err`] if the slice is not UTF-8 with a description as to why the
    /// provided bytes are not UTF-8. The vector you moved in is also included.
    ///
    /// [`from_utf8_unchecked`]: String::from_utf8_unchecked
    /// [`BumpVec<u8>`]: BumpVec
    /// [`&str`]: prim@str "&str"
    /// [`into_bytes`]: BumpString::into_bytes
    pub fn from_utf8(
        vec: BumpVec<'b, 'a, u8, A, MIN_ALIGN, UP>,
    ) -> Result<Self, FromUtf8Error<BumpVec<'b, 'a, u8, A, MIN_ALIGN, UP>>> {
        match str::from_utf8(vec.as_slice()) {
            Ok(_) => Ok(Self { vec }),
            Err(error) => Err(FromUtf8Error { error, bytes: vec }),
        }
    }

    /// Converts a `BumpString` into a `BumpVec<u8>`.
    ///
    /// This consumes the `BumpString`, so we do not need to copy its contents.
    ///
    /// # Examples
    ///
    /// ```
    /// # use bump_scope::{ Bump, BumpString };
    /// # let bump: Bump = Bump::new();
    /// let mut s = BumpString::new_in(&bump);
    /// s.push_str("hello");
    /// let bytes = s.into_bytes();
    ///
    /// assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
    /// ```
    #[inline(always)]
    #[must_use = "`self` will be dropped if the result is not used"]
    pub fn into_bytes(self) -> BumpVec<'b, 'a, u8, A, MIN_ALIGN, UP> {
        self.vec
    }

    /// Returns a byte slice of this `BumpString`'s contents.
    #[must_use]
    #[inline(always)]
    pub fn as_bytes(&self) -> &[u8] {
        self.vec.as_slice()
    }

    /// Extracts a string slice containing the entire `BumpString`.
    #[must_use]
    #[inline(always)]
    pub fn as_str(&self) -> &str {
        unsafe { str::from_utf8_unchecked(self.vec.as_slice()) }
    }

    /// Converts a `BumpString` into a mutable string slice.
    #[must_use]
    #[inline(always)]
    pub fn as_mut_str(&mut self) -> &mut str {
        unsafe { str::from_utf8_unchecked_mut(self.vec.as_mut_slice()) }
    }

    /// Returns a mutable reference to the contents of this `BumpString`.
    ///
    /// # Safety
    ///
    /// This function is unsafe because the returned `&mut Vec` allows writing
    /// bytes which are not valid UTF-8. If this constraint is violated, using
    /// the original `BumpString` after dropping the `&mut Vec` may violate memory
    /// safety, as `BumpString`s must be valid UTF-8.
    #[must_use]
    #[inline(always)]
    pub unsafe fn as_mut_vec(&mut self) -> &BumpVec<'b, 'a, u8, A, MIN_ALIGN, UP> {
        &mut self.vec
    }

    /// Removes a [`char`] from this `String` at a byte position and returns it.
    ///
    /// This is an *O*(*n*) operation, as it requires copying every element in the
    /// buffer.
    ///
    /// # Panics
    ///
    /// Panics if `idx` is larger than or equal to the `String`'s length,
    /// or if it does not lie on a [`char`] boundary.
    ///
    /// # Examples
    ///
    /// ```
    /// # use bump_scope::{ Bump, BumpString };
    /// # let bump: Bump = Bump::new();
    /// #
    /// let mut s = BumpString::from_str_in("abç", &bump);
    ///
    /// assert_eq!(s.remove(0), 'a');
    /// assert_eq!(s.remove(1), 'ç');
    /// assert_eq!(s.remove(0), 'b');
    /// ```
    #[inline]
    pub fn remove(&mut self, idx: usize) -> char {
        let ch = match self[idx..].chars().next() {
            Some(ch) => ch,
            None => panic!("cannot remove a char from the end of a string"),
        };

        let next = idx + ch.len_utf8();
        let len = self.len();
        unsafe {
            ptr::copy(self.vec.as_ptr().add(next), self.vec.as_mut_ptr().add(idx), len - next);
            self.vec.set_len(len - (next - idx));
        }
        ch
    }
}

impl<'b, 'a: 'b, const MIN_ALIGN: usize, const UP: bool, A> BumpString<'b, 'a, A, MIN_ALIGN, UP>
where
    MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
    A: Allocator + Clone,
{
    /// Constructs a new, empty `BumpString`.
    ///
    /// The vector will not allocate until elements are pushed onto it.
    pub fn new_in(bump: impl Into<&'b BumpScope<'a, A, MIN_ALIGN, UP>>) -> Self {
        Self {
            vec: BumpVec::new_in(bump),
        }
    }

    error_behavior_generic_methods! {
        /// Constructs a new, empty `BumpString` with at least the specified capacity
        /// with the provided `BumpScope`.
        ///
        /// The string will be able to hold at least `capacity` bytes without
        /// reallocating. This method allocates for as much elements as the< current chunk can hold.
        /// If `capacity` is 0, the string will not allocate.
        impl
        for fn with_capacity_in
        for fn try_with_capacity_in
        fn generic_with_capacity_in(capacity: usize, bump: impl Into<&'b BumpScope<'a, A, MIN_ALIGN, UP>>) -> Self {
            Ok(Self { vec: BumpVec::generic_with_capacity_in(capacity, bump.into())? } )
        }

        /// Constructs a new `BumpString` from a `&str`.
        impl
        for fn from_str_in
        for fn try_from_str_in
        fn generic_from_str_in(string: &str, bump: impl Into<&'b BumpScope<'a, A, MIN_ALIGN, UP>>) -> Self {
            let mut this = Self::new_in(bump);
            this.generic_push_str(string)?;
            Ok(this)
        }

        /// Appends the given [`char`] to the end of this `BumpString`.
        impl
        for fn push
        for fn try_push
        fn generic_push(&mut self, ch: char) {
            match ch.len_utf8() {
                1 => self.vec.generic_push(ch as u8),
                _ => self.vec.generic_extend_from_slice_copy(ch.encode_utf8(&mut [0; 4]).as_bytes()),
            }
        }

        /// Appends a given string slice onto the end of this `BumpString`.
        impl
        for fn push_str
        for fn try_push_str
        fn generic_push_str(&mut self, string: &str) {
            self.vec.generic_extend_from_slice_copy(string.as_bytes())
        }

        /// Inserts a character into this `BumpString` at a byte position.
        ///
        /// This is an *O*(*n*) operation as it requires copying every element in the
        /// buffer.
        do panics
        /// Panics if `idx` is larger than the `String`'s length, or if it does not
        /// lie on a [`char`] boundary.
        do examples
        /// ```
        /// # use bump_scope::{ Bump, BumpString };
        /// # let bump: Bump = Bump::new();
        /// #
        /// let mut s = BumpString::with_capacity_in(3, &bump);
        ///
        /// s.insert(0, 'f');
        /// s.insert(1, 'o');
        /// s.insert(2, 'o');
        ///
        /// assert_eq!("foo", s);
        /// ```
        impl
        for fn insert
        for fn try_insert
        fn generic_insert(&mut self, idx: usize, ch: char) {
            assert!(self.is_char_boundary(idx));
            let mut bits = [0; 4];
            let bits = ch.encode_utf8(&mut bits).as_bytes();

            unsafe {
                self.insert_bytes(idx, bits)
            }
        }

        /// Inserts a string slice into this `BumpString` at a byte position.
        ///
        /// This is an *O*(*n*) operation as it requires copying every element in the
        /// buffer.
        do panics
        /// Panics if `idx` is larger than the `BumpString`'s length, or if it does not
        /// lie on a [`char`] boundary.
        do examples
        /// ```
        /// # use bump_scope::{ Bump, BumpString };
        /// # let bump: Bump = Bump::new();
        /// #
        /// let mut s = BumpString::from_str_in("bar", &bump);
        ///
        /// s.insert_str(0, "foo");
        ///
        /// assert_eq!("foobar", s);
        /// ```
        impl
        for fn insert_str
        for fn try_insert_str
        fn generic_insert_str(&mut self, idx: usize, string: &str) {
            assert!(self.is_char_boundary(idx));

            unsafe {
                self.insert_bytes(idx, string.as_bytes())
            }
        }

        /// Copies elements from `src` range to the end of the string.
        do panics
        /// Panics if the starting point or end point do not lie on a [`char`]
        /// boundary, or if they're out of bounds.
        do examples
        /// ```
        /// # use bump_scope::{ Bump, BumpString };
        /// # let bump: Bump = Bump::new();
        /// #
        /// let mut string = BumpString::from_str_in("abcde", &bump);
        ///
        /// string.extend_from_within(2..);
        /// assert_eq!(string, "abcdecde");
        ///
        /// string.extend_from_within(..2);
        /// assert_eq!(string, "abcdecdeab");
        ///
        /// string.extend_from_within(4..8);
        /// assert_eq!(string, "abcdecdeabecde");
        /// ```
        impl
        for fn extend_from_within
        for fn try_extend_from_within
        fn generic_extend_from_within<{R}>(&mut self, src: R)
        where {
            R: RangeBounds<usize>,
        } in {
            let src @ Range { start, end } = polyfill::slice::range(src, ..self.len());

            assert!(self.is_char_boundary(start));
            assert!(self.is_char_boundary(end));

            self.vec.generic_extend_from_within_copy(src)
        }

        /// Reserves capacity for at least `additional` bytes more than the
        /// current length. The allocator may reserve more space to speculatively
        /// avoid frequent allocations. After calling `reserve`,
        /// capacity will be greater than or equal to `self.len() + additional`.
        /// Does nothing if capacity is already sufficient.
        impl
        for fn reserve
        for fn try_reserve
        fn generic_reserve(&mut self, additional: usize) {
            self.vec.generic_reserve(additional)
        }
    }

    unsafe fn insert_bytes<B: ErrorBehavior>(&mut self, idx: usize, bytes: &[u8]) -> Result<(), B> {
        let len = self.len();
        let amt = bytes.len();
        self.vec.generic_reserve(amt)?;

        unsafe {
            ptr::copy(self.vec.as_ptr().add(idx), self.vec.as_mut_ptr().add(idx + amt), len - idx);
            ptr::copy_nonoverlapping(bytes.as_ptr(), self.vec.as_mut_ptr().add(idx), amt);
            self.vec.set_len(len + amt);
        }

        Ok(())
    }

    /// Converts a `BumpString` into a `BumpBox<str>`.
    #[must_use]
    #[inline(always)]
    pub fn into_boxed_str(self) -> BumpBox<'a, str> {
        unsafe { self.vec.into_boxed_slice().into_boxed_str_unchecked() }
    }

    /// Converts this `BumpBox<str>` into `&str` that is live for the entire bump scope.
    #[must_use]
    #[inline(always)]
    pub fn into_str(self) -> &'a mut str {
        self.into_boxed_str().into_mut()
    }

    #[doc = crate::doc_fn_stats!()]
    #[doc = crate::doc_fn_stats_greedy!(BumpString)]
    #[must_use]
    #[inline(always)]
    pub fn stats(&self) -> Stats<'a, UP> {
        self.vec.stats()
    }

    #[doc = crate::doc_fn_allocator!()]
    #[must_use]
    #[inline(always)]
    pub fn allocator(&self) -> &A {
        self.vec.allocator()
    }
}

impl<'b, 'a: 'b, const MIN_ALIGN: usize, const UP: bool, A> fmt::Write for BumpString<'b, 'a, A, MIN_ALIGN, UP>
where
    MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
    A: Allocator + Clone,
{
    #[inline(always)]
    fn write_str(&mut self, s: &str) -> fmt::Result {
        self.try_push_str(s).map_err(|_| fmt::Error)
    }

    #[inline(always)]
    fn write_char(&mut self, c: char) -> fmt::Result {
        self.try_push(c).map_err(|_| fmt::Error)
    }
}

impl<'b, 'a, const MIN_ALIGN: usize, const UP: bool, A> Debug for BumpString<'b, 'a, A, MIN_ALIGN, UP> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        Debug::fmt(self.as_str(), f)
    }
}

impl<'b, 'a, const MIN_ALIGN: usize, const UP: bool, A> Display for BumpString<'b, 'a, A, MIN_ALIGN, UP> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        Display::fmt(self.as_str(), f)
    }
}

impl<'b, 'a, const MIN_ALIGN: usize, const UP: bool, A> Deref for BumpString<'b, 'a, A, MIN_ALIGN, UP> {
    type Target = str;

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

impl<'b, 'a, const MIN_ALIGN: usize, const UP: bool, A> DerefMut for BumpString<'b, 'a, A, MIN_ALIGN, UP> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.as_mut_str()
    }
}

#[cfg(not(no_global_oom_handling))]
impl<'b, 'a, const MIN_ALIGN: usize, const UP: bool, A> core::ops::AddAssign<&str> for BumpString<'b, 'a, A, MIN_ALIGN, UP>
where
    MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
    A: Allocator + Clone,
{
    #[inline]
    fn add_assign(&mut self, rhs: &str) {
        self.push_str(rhs);
    }
}

impl<'b, 'a, const MIN_ALIGN: usize, const UP: bool, A> AsRef<str> for BumpString<'b, 'a, A, MIN_ALIGN, UP> {
    #[inline]
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<'b, 'a, const MIN_ALIGN: usize, const UP: bool, A> AsMut<str> for BumpString<'b, 'a, A, MIN_ALIGN, UP> {
    #[inline]
    fn as_mut(&mut self) -> &mut str {
        self.as_mut_str()
    }
}

impl<'b, 'a, const MIN_ALIGN: usize, const UP: bool, A> Borrow<str> for BumpString<'b, 'a, A, MIN_ALIGN, UP> {
    #[inline]
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl<'b, 'a, const MIN_ALIGN: usize, const UP: bool, A> BorrowMut<str> for BumpString<'b, 'a, A, MIN_ALIGN, UP> {
    #[inline]
    fn borrow_mut(&mut self) -> &mut str {
        self.as_mut_str()
    }
}

impl<'b, 'a, const MIN_ALIGN: usize, const UP: bool, A> PartialEq for BumpString<'b, 'a, A, MIN_ALIGN, UP> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        <str as PartialEq>::eq(self, other)
    }

    #[inline]
    fn ne(&self, other: &Self) -> bool {
        <str as PartialEq>::ne(self, other)
    }
}

macro_rules! impl_partial_eq {
    (
        $(
            $(#[$attr:meta])*
            $string_like:ty,
        )*
    ) => {
        $(
            $(#[$attr])*
            impl<'b, 'a, const MIN_ALIGN: usize, const UP: bool, A> PartialEq<$string_like> for BumpString<'b, 'a, A, MIN_ALIGN, UP> {
                #[inline]
                fn eq(&self, other: &$string_like) -> bool {
                    <str as PartialEq>::eq(self, other)
                }

                #[inline]
                fn ne(&self, other: &$string_like) -> bool {
                    <str as PartialEq>::ne(self, other)
                }
            }

            $(#[$attr])*
            impl<'b, 'a, const MIN_ALIGN: usize, const UP: bool, A> PartialEq<BumpString<'b, 'a, A, MIN_ALIGN, UP>> for $string_like {
                #[inline]
                fn eq(&self, other: &BumpString<'b, 'a, A, MIN_ALIGN, UP>) -> bool {
                    <str as PartialEq>::eq(self, other)
                }

                #[inline]
                fn ne(&self, other: &BumpString<'b, 'a, A, MIN_ALIGN, UP>) -> bool {
                    <str as PartialEq>::ne(self, other)
                }
            }
        )*
    };
}

impl_partial_eq! {
    str,

    &str,

    #[cfg(feature = "alloc")]
    alloc::string::String,

    #[cfg(feature = "alloc")]
    alloc::borrow::Cow<'_, str>,
}

impl<'b, 'a, const MIN_ALIGN: usize, const UP: bool, A> Eq for BumpString<'b, 'a, A, MIN_ALIGN, UP> {}

impl<'b, 'a, const MIN_ALIGN: usize, const UP: bool, A> PartialOrd for BumpString<'b, 'a, A, MIN_ALIGN, UP> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }

    #[inline]
    fn lt(&self, other: &Self) -> bool {
        <str as PartialOrd>::lt(self, other)
    }

    #[inline]
    fn le(&self, other: &Self) -> bool {
        <str as PartialOrd>::le(self, other)
    }

    #[inline]
    fn gt(&self, other: &Self) -> bool {
        <str as PartialOrd>::gt(self, other)
    }

    #[inline]
    fn ge(&self, other: &Self) -> bool {
        <str as PartialOrd>::ge(self, other)
    }
}

impl<'b, 'a, const MIN_ALIGN: usize, const UP: bool, A> Ord for BumpString<'b, 'a, A, MIN_ALIGN, UP> {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        <str as Ord>::cmp(self, other)
    }
}

impl<'b, 'a, const MIN_ALIGN: usize, const UP: bool, A> Hash for BumpString<'b, 'a, A, MIN_ALIGN, UP> {
    #[inline]
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.vec.hash(state);
    }
}

#[cfg(not(no_global_oom_handling))]
impl<'s, 'b, 'a, const MIN_ALIGN: usize, const UP: bool, A> Extend<&'s str> for BumpString<'b, 'a, A, MIN_ALIGN, UP>
where
    MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
    A: Allocator + Clone,
{
    #[inline]
    fn extend<T: IntoIterator<Item = &'s str>>(&mut self, iter: T) {
        for str in iter {
            self.push_str(str);
        }
    }
}

#[cfg(feature = "alloc")]
impl<'b, 'a, const MIN_ALIGN: usize, const UP: bool, A> From<BumpString<'b, 'a, A, MIN_ALIGN, UP>>
    for alloc::string::String
{
    #[inline]
    fn from(value: BumpString<'b, 'a, A, MIN_ALIGN, UP>) -> Self {
        value.as_str().into()
    }
}