Skip to main content

bump_scope/
mut_bump_vec_rev.rs

1use core::{
2    borrow::{Borrow, BorrowMut},
3    fmt::Debug,
4    hash::Hash,
5    iter,
6    marker::PhantomData,
7    mem::{ManuallyDrop, MaybeUninit},
8    ops::{Deref, DerefMut, Index, IndexMut, RangeBounds},
9    ptr::{self, NonNull},
10    slice::{self, SliceIndex},
11};
12
13use crate::{
14    BumpBox, ErrorBehavior, NoDrop, SetLenOnDrop, SizedTypeProperties,
15    alloc::AllocError,
16    destructure::destructure,
17    min_non_zero_cap,
18    mut_bump_vec::IntoIter,
19    owned_slice::{OwnedSlice, TakeOwnedSlice},
20    polyfill::{self, hint::likely, non_null, pointer},
21    traits::{MutBumpAllocatorTyped, MutBumpAllocatorTypedScope},
22};
23
24#[cfg(feature = "panic-on-alloc")]
25use crate::panic_on_error;
26
27/// This is like [`vec!`](alloc_crate::vec!) but allocates inside a bump allocator, returning a [`MutBumpVecRev`].
28///
29/// `$bump` can be any type that implements [`MutBumpAllocatorTyped`].
30///
31/// # Panics
32/// If used without `try`, panics on allocation failure.
33///
34/// # Errors
35/// If used with `try`, errors on allocation failure.
36///
37/// # Examples
38///
39/// There are three forms of this macro:
40///
41/// - Create an empty [`MutBumpVecRev`]:
42/// ```
43/// # use bump_scope::{Bump, mut_bump_vec_rev, MutBumpVecRev};
44/// # let mut bump: Bump = Bump::new();
45/// let vec: MutBumpVecRev<i32, _> = mut_bump_vec_rev![in &mut bump];
46/// assert!(vec.is_empty());
47/// ```
48///
49/// - Create a [`MutBumpVecRev`] containing a given list of elements:
50///
51/// ```
52/// # use bump_scope::{Bump, mut_bump_vec_rev};
53/// # let mut bump: Bump = Bump::new();
54/// let vec = mut_bump_vec_rev![in &mut bump; 1, 2, 3];
55/// assert_eq!(vec[0], 1);
56/// assert_eq!(vec[1], 2);
57/// assert_eq!(vec[2], 3);
58/// ```
59///
60/// - Create a [`MutBumpVecRev`] from a given element and size:
61///
62/// ```
63/// # use bump_scope::{Bump, mut_bump_vec_rev};
64/// # let mut bump: Bump = Bump::new();
65/// let vec = mut_bump_vec_rev![in &mut bump; 1; 3];
66/// assert_eq!(vec, [1, 1, 1]);
67/// ```
68///
69/// Note that unlike array expressions this syntax supports all elements
70/// which implement [`Clone`] and the number of elements doesn't have to be
71/// a constant.
72///
73/// This will use `clone` to duplicate an expression, so one should be careful
74/// using this with types having a nonstandard `Clone` implementation. For
75/// example, `mut_bump_vec_rev![in &mut bump; Rc::new(1); 5]` will create a vector of five references
76/// to the same boxed integer value, not five references pointing to independently
77/// boxed integers.
78///
79/// Also, note that `mut_bump_vec_rev![in &mut bump; expr; 0]` is allowed, and produces an empty vector.
80/// This will still evaluate `expr`, however, and immediately drop the resulting value, so
81/// be mindful of side effects.
82#[macro_export]
83macro_rules! mut_bump_vec_rev {
84    [in $bump:expr] => {
85        $crate::MutBumpVecRev::new_in($bump)
86    };
87    [in $bump:expr; $($values:expr),* $(,)?] => {
88        $crate::__mut_bump_vec_rev_panic_on_alloc![in $bump; $($values),*]
89    };
90    [in $bump:expr; $value:expr; $count:expr] => {
91        $crate::__mut_bump_vec_rev_panic_on_alloc![in $bump; $value; $count]
92    };
93    [try in $bump:expr] => {
94        Ok::<_, $crate::alloc::AllocError>($crate::MutBumpVecRev::new_in($bump))
95    };
96    [try in $bump:expr; $($values:expr),* $(,)?] => {
97        $crate::MutBumpVecRev::try_from_owned_slice_in([$($values),*], $bump)
98    };
99    [try in $bump:expr; $value:expr; $count:expr] => {
100        $crate::MutBumpVecRev::try_from_elem_in($value, $count, $bump)
101    };
102}
103
104#[doc(hidden)]
105#[macro_export]
106#[cfg(feature = "panic-on-alloc")]
107macro_rules! __mut_bump_vec_rev_panic_on_alloc {
108    [in $bump:expr; $($values:expr),* $(,)?] => {
109        $crate::MutBumpVecRev::from_owned_slice_in([$($values),*], $bump)
110    };
111    [in $bump:expr; $value:expr; $count:expr] => {
112        $crate::MutBumpVecRev::from_elem_in($value, $count, $bump)
113    };
114}
115
116#[doc(hidden)]
117#[macro_export]
118#[cfg(not(feature = "panic-on-alloc"))]
119macro_rules! __mut_bump_vec_rev_panic_on_alloc {
120    [in $bump:expr; $($values:expr),* $(,)?] => {
121        compile_error!(concat!(
122            "the potentially panicking api of `mut_bump_vec_rev!` is not available\n",
123            "help: enable `bump-scope`'s \"panic-on-alloc\" feature or use `try`:\n",
124            "      `mut_bump_vec_rev![try in ",
125            stringify!($bump),
126            "; ",
127            stringify!($($values),*),
128            "]`"
129        ))
130    };
131    [in $bump:expr; $value:expr; $count:expr] => {
132        compile_error!(concat!(
133            "the potentially panicking api of `mut_bump_vec_rev!` is not available\n",
134            "help: enable `bump-scope`'s \"panic-on-alloc\" feature or use `try`:\n",
135            "      `mut_bump_vec_rev![try in ",
136            stringify!($bump),
137            "; ",
138            stringify!($value),
139            "; ",
140            stringify!($count),
141            "]`"
142        ))
143    };
144}
145
146/// A type like [`MutBumpVec`](crate::MutBumpVec) but new elements are pushed to the front.
147///
148/// The point of this vector is to have a more performant <code>[into](Self::into_slice)([_boxed](Self::into_boxed_slice))[_slice](Self::into_slice)</code> for a downwards bumping allocator.
149///
150/// # Examples
151///
152/// This type can be used to allocate a slice, when `alloc_*` methods are too limiting:
153/// ```
154/// # use bump_scope::{Bump, mut_bump_vec_rev};
155/// # let mut bump: Bump = Bump::new();
156/// let mut vec = mut_bump_vec_rev![in &mut bump];
157///
158/// vec.push(1);
159/// vec.push(2);
160/// vec.push(3);
161///
162/// let slice: &[i32] = vec.into_slice();
163///
164/// assert_eq!(slice, [3, 2, 1]);
165/// ```
166///
167/// When extending a `MutBumpVecRev` by a slice, the elements have the same order as in the source slice.
168///
169/// ```
170/// # use bump_scope::{Bump, mut_bump_vec_rev};
171/// # let mut bump: Bump = Bump::new();
172/// let mut vec = mut_bump_vec_rev![in &mut bump; 4, 5, 6];
173///
174/// vec.extend_from_slice_copy(&[1, 2, 3]);
175///
176/// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
177/// ```
178//
179// MutBumpVecRev never actually moves a bump pointer.
180// It may force allocation of a new chunk, but it does not move the pointer within.
181// So we don't need to move the bump pointer when dropping.
182//
183// If we want to reset the bump pointer to a previous chunk, we use a bump scope.
184// We could do it here, by resetting to the last non-empty chunk but that would require a loop.
185// Chunk allocations are supposed to be very rare, so this wouldn't be worth it.
186pub struct MutBumpVecRev<T, A> {
187    /// This points at the end of the slice (`ptr` + `len`).
188    /// When `T` is a ZST this is always `NonNull::<T>::dangling()`.
189    pub(crate) end: NonNull<T>,
190    pub(crate) len: usize,
191
192    /// When `T` is a ZST this is always `usize::MAX`.
193    cap: usize,
194
195    allocator: A,
196
197    /// Marks ownership over T. (<https://doc.rust-lang.org/nomicon/phantom-data.html#generic-parameters-and-drop-checking>)
198    marker: PhantomData<T>,
199}
200
201impl<T, A> MutBumpVecRev<T, A> {
202    /// Constructs a new empty `MutBumpVecRev<T>`.
203    ///
204    /// The vector will not allocate until elements are pushed onto it.
205    ///
206    /// # Examples
207    /// ```
208    /// # use bump_scope::{Bump, MutBumpVecRev};
209    /// # let mut bump: Bump = Bump::new();
210    /// let vec = MutBumpVecRev::<i32, _>::new_in(&mut bump);
211    /// assert_eq!(vec.len(), 0);
212    /// assert_eq!(vec.capacity(), 0);
213    /// ```
214    #[inline]
215    pub fn new_in(allocator: A) -> Self {
216        Self {
217            end: NonNull::dangling(),
218            len: 0,
219            cap: if T::IS_ZST { usize::MAX } else { 0 },
220            allocator,
221            marker: PhantomData,
222        }
223    }
224
225    /// Returns the total number of elements the vector can hold without
226    /// reallocating.
227    ///
228    /// # Examples
229    ///
230    /// ```
231    /// # use bump_scope::{Bump, MutBumpVecRev};
232    /// # let mut bump: Bump = Bump::new();
233    /// let vec = MutBumpVecRev::<i32, _>::with_capacity_in(2048, &mut bump);
234    /// assert!(vec.capacity() >= 2048);
235    /// ```
236    #[must_use]
237    #[inline(always)]
238    pub const fn capacity(&self) -> usize {
239        self.cap
240    }
241
242    /// Returns the number of elements in the vector, also referred to
243    /// as its 'length'.
244    ///
245    /// # Examples
246    /// ```
247    /// # use bump_scope::{Bump, mut_bump_vec_rev};
248    /// # let mut bump: Bump = Bump::new();
249    /// let a = mut_bump_vec_rev![in &mut bump; 1, 2, 3];
250    /// assert_eq!(a.len(), 3);
251    /// ```
252    #[must_use]
253    #[inline(always)]
254    pub const fn len(&self) -> usize {
255        self.len
256    }
257
258    /// Returns `true` if the vector contains no elements.
259    ///
260    /// # Examples
261    /// ```
262    /// # use bump_scope::{Bump, MutBumpVecRev};
263    /// # let mut bump: Bump = Bump::new();
264    /// let mut v = MutBumpVecRev::new_in(&mut bump);
265    /// assert!(v.is_empty());
266    ///
267    /// v.push(1);
268    /// assert!(!v.is_empty());
269    /// ```
270    #[must_use]
271    #[inline(always)]
272    pub const fn is_empty(&self) -> bool {
273        self.len == 0
274    }
275
276    /// Appends an element to the back of the collection.
277    ///
278    /// # Safety
279    /// Vector must not be full.
280    #[inline(always)]
281    pub unsafe fn push_unchecked(&mut self, value: T) {
282        unsafe { self.push_with_unchecked(|| value) };
283    }
284
285    /// Appends an element to the back of the collection.
286    ///
287    /// # Safety
288    /// Vector must not be full.
289    #[inline(always)]
290    pub unsafe fn push_with_unchecked(&mut self, f: impl FnOnce() -> T) {
291        debug_assert!(self.len < self.cap);
292
293        unsafe {
294            let ptr = self.end.sub(self.len + 1);
295            non_null::write_with(ptr, f);
296        }
297
298        // We set the len here so when `f` panics, `self.len` doesn't change.
299        self.len += 1;
300    }
301
302    /// Removes the first element from a vector and returns it, or [`None`] if it
303    /// is empty.
304    ///
305    /// # Examples
306    /// ```
307    /// # use bump_scope::{Bump, mut_bump_vec_rev};
308    /// # let mut bump: Bump = Bump::new();
309    /// let mut vec = mut_bump_vec_rev![in &mut bump; 1, 2, 3];
310    /// assert_eq!(vec.pop(), Some(1));
311    /// assert_eq!(vec, [2, 3]);
312    /// ```
313    ///
314    /// # Time complexity
315    /// Takes *O*(1) time.
316    #[inline(always)]
317    pub fn pop(&mut self) -> Option<T> {
318        if self.len == 0 {
319            None
320        } else {
321            unsafe {
322                let ptr = self.as_ptr();
323                self.len -= 1;
324                Some(ptr.read())
325            }
326        }
327    }
328
329    /// Removes and returns the last element from a vector if the predicate
330    /// returns `true`, or [`None`] if the predicate returns false or the vector
331    /// is empty (the predicate will not be called in that case).
332    ///
333    /// # Examples
334    ///
335    /// ```
336    /// # use bump_scope::{Bump, mut_bump_vec_rev};
337    /// # let mut bump: Bump = Bump::new();
338    /// let mut vec = mut_bump_vec_rev![in &mut bump; 1, 2, 3, 4];
339    /// let pred = |x: &mut i32| *x % 2 != 0;
340    ///
341    /// assert_eq!(vec.pop_if(pred), Some(1));
342    /// assert_eq!(vec, [2, 3, 4]);
343    /// assert_eq!(vec.pop_if(pred), None);
344    /// ```
345    pub fn pop_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
346        let last = self.first_mut()?;
347        if predicate(last) { self.pop() } else { None }
348    }
349
350    /// Clears the vector, removing all values.
351    ///
352    /// Note that this method has no effect on the allocated capacity
353    /// of the vector.
354    ///
355    /// # Examples
356    ///
357    /// ```
358    /// # use bump_scope::{Bump, mut_bump_vec_rev};
359    /// # let mut bump: Bump = Bump::new();
360    /// let mut v = mut_bump_vec_rev![in &mut bump; 1, 2, 3];
361    ///
362    /// v.clear();
363    ///
364    /// assert!(v.is_empty());
365    /// ```
366    #[inline(always)]
367    pub fn clear(&mut self) {
368        let elems: *mut [T] = self.as_mut_slice();
369
370        // SAFETY:
371        // - `elems` comes directly from `as_mut_slice` and is therefore valid.
372        // - Setting `self.len` before calling `drop_in_place` means that,
373        //   if an element's `Drop` impl panics, the vector's `Drop` impl will
374        //   do nothing (leaking the rest of the elements) instead of dropping
375        //   some twice.
376        unsafe {
377            self.len = 0;
378            ptr::drop_in_place(elems);
379        }
380    }
381
382    /// Extracts a slice containing the entire vector.
383    ///
384    /// Equivalent to `&s[..]`.
385    #[must_use]
386    #[inline(always)]
387    pub fn as_slice(&self) -> &[T] {
388        unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
389    }
390
391    /// Extracts a mutable slice of the entire vector.
392    ///
393    /// Equivalent to `&mut s[..]`.
394    #[must_use]
395    #[inline(always)]
396    pub fn as_mut_slice(&mut self) -> &mut [T] {
397        unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
398    }
399
400    /// Returns a raw pointer to the vector's buffer, or a dangling raw pointer
401    /// valid for zero sized reads if the vector didn't allocate.
402    ///
403    /// The caller must ensure that the vector outlives the pointer this
404    /// function returns, or else it will end up pointing to garbage.
405    /// Modifying the vector may cause its buffer to be reallocated,
406    /// which would also make any pointers to it invalid.
407    ///
408    /// The caller must also ensure that the memory the pointer (non-transitively) points to
409    /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
410    /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
411    ///
412    /// # Examples
413    ///
414    /// ```
415    /// # use bump_scope::{Bump, mut_bump_vec_rev};
416    /// # let mut bump: Bump = Bump::new();
417    /// #
418    /// let x = mut_bump_vec_rev![in &mut bump; 1, 2, 4];
419    /// let x_ptr = x.as_ptr();
420    ///
421    /// unsafe {
422    ///     for i in 0..x.len() {
423    ///         assert_eq!(*x_ptr.add(i), 1 << i);
424    ///     }
425    /// }
426    /// ```
427    ///
428    /// [`as_mut_ptr`]: Self::as_mut_ptr
429    #[inline]
430    #[must_use]
431    pub fn as_ptr(&self) -> *const T {
432        // We shadow the slice method of the same name to avoid going through
433        // `deref`, which creates an intermediate reference.
434        self.as_non_null().as_ptr()
435    }
436
437    /// Returns an unsafe mutable pointer to the vector's buffer, or a dangling
438    /// raw pointer valid for zero sized reads if the vector didn't allocate.
439    ///
440    /// The caller must ensure that the vector outlives the pointer this
441    /// function returns, or else it will end up pointing to garbage.
442    /// Modifying the vector may cause its buffer to be reallocated,
443    /// which would also make any pointers to it invalid.
444    ///
445    /// # Examples
446    ///
447    /// ```
448    /// # use bump_scope::{Bump, MutBumpVecRev};
449    /// # let mut bump: Bump = Bump::new();
450    /// // Allocate vector big enough for 4 elements.
451    /// let size = 4;
452    /// let mut x = MutBumpVecRev::<i32, _>::with_capacity_in(size, &mut bump);
453    /// let x_ptr = unsafe { x.as_mut_ptr().sub(size) };
454    ///
455    /// // Initialize elements via raw pointer writes, then set length.
456    /// unsafe {
457    ///     for i in 0..size {
458    ///         *x_ptr.add(i) = i as i32;
459    ///     }
460    ///     x.set_len(size);
461    /// }
462    ///
463    /// assert_eq!(&*x, &[0, 1, 2, 3]);
464    /// ```
465    #[inline]
466    pub fn as_mut_ptr(&mut self) -> *mut T {
467        // We shadow the slice method of the same name to avoid going through
468        // `deref_mut`, which creates an intermediate reference.
469        self.as_non_null().as_ptr()
470    }
471
472    /// Returns a `NonNull` pointer to the vector's buffer, or a dangling
473    /// `NonNull` pointer valid for zero sized reads if the vector didn't allocate.
474    ///
475    /// The caller must ensure that the vector outlives the pointer this
476    /// function returns, or else it will end up dangling.
477    /// Modifying the vector may cause its buffer to be reallocated,
478    /// which would also make any pointers to it invalid.
479    ///
480    /// This method guarantees that for the purpose of the aliasing model, this method
481    /// does not materialize a reference to the underlying slice, and thus the returned pointer
482    /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`],
483    /// and [`as_non_null`].
484    /// Note that calling other methods that materialize references to the slice,
485    /// or references to specific elements you are planning on accessing through this pointer,
486    /// may still invalidate this pointer.
487    /// See the second example below for how this guarantee can be used.
488    ///
489    /// # Examples
490    ///
491    /// ```
492    /// # use bump_scope::{Bump, MutBumpVecRev};
493    /// # let mut bump: Bump = Bump::new();
494    /// // Allocate vector big enough for 4 elements.
495    /// let size = 4;
496    /// let mut x: MutBumpVecRev<i32, _> = MutBumpVecRev::with_capacity_in(size, &mut bump);
497    /// let x_ptr = x.as_non_null();
498    ///
499    /// // Initialize elements via raw pointer writes, then set length.
500    /// unsafe {
501    ///     for i in 0..size {
502    ///         x_ptr.sub(i + 1).write(i as i32);
503    ///     }
504    ///     x.set_len(size);
505    /// }
506    /// assert_eq!(&*x, &[3, 2, 1, 0]);
507    /// ```
508    ///
509    /// Due to the aliasing guarantee, the following code is legal:
510    ///
511    /// ```
512    /// # use bump_scope::{Bump, mut_bump_vec_rev};
513    /// # let mut bump: Bump = Bump::new();
514    /// unsafe {
515    ///     let v = mut_bump_vec_rev![in &mut bump; 0];
516    ///     let ptr1 = v.as_non_null();
517    ///     ptr1.write(1);
518    ///     let ptr2 = v.as_non_null();
519    ///     ptr2.write(2);
520    ///     // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
521    ///     ptr1.write(3);
522    /// }
523    /// ```
524    ///
525    /// [`as_mut_ptr`]: Self::as_mut_ptr
526    /// [`as_ptr`]: Self::as_ptr
527    /// [`as_non_null`]: Self::as_non_null
528    #[must_use]
529    #[inline(always)]
530    pub const fn as_non_null(&self) -> NonNull<T> {
531        // SAFETY: The start pointer is never null.
532        unsafe { self.end.sub(self.len) }
533    }
534
535    /// Shortens the vector, keeping the first `len` elements and dropping
536    /// the rest.
537    ///
538    /// If `len` is greater than the vector's current length, this has no
539    /// effect.
540    ///
541    /// Note that this method has no effect on the allocated capacity
542    /// of the vector.
543    ///
544    /// # Examples
545    ///
546    /// Truncating a five element vector to two elements:
547    ///
548    /// ```
549    /// # use bump_scope::{Bump, mut_bump_vec_rev};
550    /// # let mut bump: Bump = Bump::new();
551    /// #
552    /// let mut vec = mut_bump_vec_rev![in &mut bump; 1, 2, 3, 4, 5];
553    /// vec.truncate(2);
554    /// assert_eq!(vec, [4, 5]);
555    /// ```
556    ///
557    /// No truncation occurs when `len` is greater than the vector's current
558    /// length:
559    ///
560    /// ```
561    /// # use bump_scope::{Bump, mut_bump_vec_rev};
562    /// # let mut bump: Bump = Bump::new();
563    /// #
564    /// let mut vec = mut_bump_vec_rev![in &mut bump; 1, 2, 3];
565    /// vec.truncate(8);
566    /// assert_eq!(vec, [1, 2, 3]);
567    /// ```
568    ///
569    /// Truncating when `len == 0` is equivalent to calling the [`clear`]
570    /// method.
571    ///
572    /// ```
573    /// # use bump_scope::{Bump, mut_bump_vec_rev};
574    /// # let mut bump: Bump = Bump::new();
575    /// #
576    /// let mut vec = mut_bump_vec_rev![in &mut bump; 1, 2, 3];
577    /// vec.truncate(0);
578    /// assert_eq!(vec, []);
579    /// ```
580    ///
581    /// [`clear`]: Self::clear
582    pub fn truncate(&mut self, len: usize) {
583        // This is safe because:
584        //
585        // * the slice passed to `drop_in_place` is valid; the `len > self.len`
586        //   case avoids creating an invalid slice, and
587        // * the `len` of the vector is shrunk before calling `drop_in_place`,
588        //   such that no value will be dropped twice in case `drop_in_place`
589        //   were to panic once (if it panics twice, the program aborts).
590        unsafe {
591            // Unlike std this is `>=`. Std uses `>` because when a call is inlined with `len` of `0` that optimizes better.
592            // But this was likely only motivated because `clear` used to be implemented as `truncate(0)`.
593            // See <https://github.com/rust-lang/rust/issues/76089#issuecomment-1889416842>.
594            if len >= self.len {
595                return;
596            }
597
598            let remaining_len = self.len - len;
599
600            let ptr = self.as_mut_ptr();
601            let slice = ptr::slice_from_raw_parts_mut(ptr, remaining_len);
602
603            self.len = len;
604            slice.drop_in_place();
605        }
606    }
607
608    /// Forces the length of the vector to `new_len`.
609    ///
610    /// This is a low-level operation that maintains none of the normal
611    /// invariants of the type. Normally changing the length of a vector
612    /// is done using one of the safe operations instead, such as
613    /// [`resize`], [`truncate`], [`extend`], or [`clear`].
614    ///
615    /// [`truncate`]: Self::truncate
616    /// [`resize`]: Self::resize
617    /// [`extend`]: Self::extend
618    /// [`clear`]: Self::clear
619    ///
620    /// # Safety
621    ///
622    /// - `new_len` must be less than or equal to [`capacity`].
623    /// - The elements at `old_len..new_len` must be initialized.
624    ///
625    /// [`capacity`]: Self::capacity
626    #[inline]
627    pub unsafe fn set_len(&mut self, new_len: usize) {
628        debug_assert!(new_len <= self.cap);
629        self.len = new_len;
630    }
631
632    #[inline]
633    pub(crate) unsafe fn inc_len(&mut self, amount: usize) {
634        self.len += amount;
635    }
636
637    #[inline(always)]
638    fn into_raw_parts(self) -> (NonNull<T>, usize, usize, A) {
639        destructure!(let Self { end, len, cap, allocator } = self);
640        (end, len, cap, allocator)
641    }
642
643    #[inline(always)]
644    unsafe fn from_raw_parts(end: NonNull<T>, len: usize, cap: usize, allocator: A) -> Self {
645        Self {
646            end,
647            len,
648            cap,
649            allocator,
650            marker: PhantomData,
651        }
652    }
653}
654
655impl<T, A: MutBumpAllocatorTyped> MutBumpVecRev<T, A> {
656    /// Constructs a new empty vector with at least the specified capacity
657    /// in the provided bump allocator.
658    ///
659    /// The vector will be able to hold `capacity` elements without
660    /// reallocating. If `capacity` is 0, the vector will not allocate.
661    ///
662    /// It is important to note that although the returned vector has the
663    /// minimum *capacity* specified, the vector will have a zero *length*. For
664    /// an explanation of the difference between length and capacity, see
665    /// *[Capacity and reallocation]*.
666    ///
667    /// When `T` is a zero-sized type, there will be no allocation
668    /// and the capacity will always be `usize::MAX`.
669    ///
670    /// [Capacity and reallocation]: alloc_crate::vec::Vec#capacity-and-reallocation
671    ///
672    /// # Panics
673    /// Panics if the allocation fails.
674    ///
675    /// # Examples
676    /// ```
677    /// # use bump_scope::{Bump, MutBumpVecRev};
678    /// # let mut bump: Bump = Bump::new();
679    /// let mut vec = MutBumpVecRev::<i32, _>::with_capacity_in(10, &mut bump);
680    ///
681    /// // The vector contains no items, even though it has capacity for more
682    /// assert_eq!(vec.len(), 0);
683    /// assert!(vec.capacity() >= 10);
684    ///
685    /// // These are all done without reallocating...
686    /// for i in 0..10 {
687    ///     vec.push(i);
688    /// }
689    /// assert_eq!(vec.len(), 10);
690    /// assert!(vec.capacity() >= 10);
691    ///
692    /// // ...but this may make the vector reallocate
693    /// vec.push(11);
694    /// assert_eq!(vec.len(), 11);
695    /// assert!(vec.capacity() >= 11);
696    ///
697    /// drop(vec);
698    ///
699    /// // A vector of a zero-sized type will always over-allocate, since no
700    /// // allocation is necessary
701    /// let vec_units = MutBumpVecRev::<(), _>::with_capacity_in(10, &mut bump);
702    /// assert_eq!(vec_units.capacity(), usize::MAX);
703    /// ```
704    #[must_use]
705    #[inline(always)]
706    #[cfg(feature = "panic-on-alloc")]
707    pub fn with_capacity_in(capacity: usize, allocator: A) -> Self {
708        panic_on_error(Self::generic_with_capacity_in(capacity, allocator))
709    }
710
711    /// Constructs a new empty vector with at least the specified capacity
712    /// in the provided bump allocator.
713    ///
714    /// The vector will be able to hold `capacity` elements without
715    /// reallocating. If `capacity` is 0, the vector will not allocate.
716    ///
717    /// It is important to note that although the returned vector has the
718    /// minimum *capacity* specified, the vector will have a zero *length*. For
719    /// an explanation of the difference between length and capacity, see
720    /// *[Capacity and reallocation]*.
721    ///
722    /// When `T` is a zero-sized type, there will be no allocation
723    /// and the capacity will always be `usize::MAX`.
724    ///
725    /// [Capacity and reallocation]: alloc_crate::vec::Vec#capacity-and-reallocation
726    ///
727    /// # Errors
728    /// Errors if the allocation fails.
729    ///
730    /// # Examples
731    /// ```
732    /// # use bump_scope::{Bump, MutBumpVecRev};
733    /// # let mut bump: Bump = Bump::new();
734    /// let mut vec = MutBumpVecRev::<i32, _>::try_with_capacity_in(10, &mut bump)?;
735    ///
736    /// // The vector contains no items, even though it has capacity for more
737    /// assert_eq!(vec.len(), 0);
738    /// assert!(vec.capacity() >= 10);
739    ///
740    /// // These are all done without reallocating...
741    /// for i in 0..10 {
742    ///     vec.push(i);
743    /// }
744    /// assert_eq!(vec.len(), 10);
745    /// assert!(vec.capacity() >= 10);
746    ///
747    /// // ...but this may make the vector reallocate
748    /// vec.push(11);
749    /// assert_eq!(vec.len(), 11);
750    /// assert!(vec.capacity() >= 11);
751    ///
752    /// drop(vec);
753    ///
754    /// // A vector of a zero-sized type will always over-allocate, since no
755    /// // allocation is necessary
756    /// let vec_units = MutBumpVecRev::<(), _>::try_with_capacity_in(10, &mut bump)?;
757    /// assert_eq!(vec_units.capacity(), usize::MAX);
758    /// # Ok::<(), bump_scope::alloc::AllocError>(())
759    /// ```
760    #[inline(always)]
761    pub fn try_with_capacity_in(capacity: usize, allocator: A) -> Result<Self, AllocError> {
762        Self::generic_with_capacity_in(capacity, allocator)
763    }
764
765    #[inline]
766    pub(crate) fn generic_with_capacity_in<E: ErrorBehavior>(capacity: usize, allocator: A) -> Result<Self, E> {
767        let mut allocator = allocator;
768
769        if T::IS_ZST {
770            return Ok(Self {
771                end: NonNull::dangling(),
772                len: 0,
773                cap: usize::MAX,
774                allocator,
775                marker: PhantomData,
776            });
777        }
778
779        if capacity == 0 {
780            return Ok(Self {
781                end: NonNull::dangling(),
782                len: 0,
783                cap: 0,
784                allocator,
785                marker: PhantomData,
786            });
787        }
788
789        let (end, cap) = unsafe { E::prepare_slice_allocation_rev::<T>(&mut allocator, capacity)? };
790
791        Ok(Self {
792            end,
793            len: 0,
794            cap,
795            allocator,
796            marker: PhantomData,
797        })
798    }
799
800    /// Constructs a new `MutBumpVecRev<T>` and pushes `value` `count` times.
801    ///
802    /// # Panics
803    /// Panics if the allocation fails.
804    ///
805    /// # Examples
806    /// ```
807    /// # use bump_scope::{Bump, MutBumpVecRev};
808    /// # let mut bump: Bump = Bump::new();
809    /// let vec = MutBumpVecRev::from_elem_in("ho", 3, &mut bump);
810    /// assert_eq!(vec, ["ho", "ho", "ho"]);
811    /// ```
812    #[must_use]
813    #[inline(always)]
814    #[cfg(feature = "panic-on-alloc")]
815    pub fn from_elem_in(value: T, count: usize, allocator: A) -> Self
816    where
817        T: Clone,
818    {
819        panic_on_error(Self::generic_from_elem_in(value, count, allocator))
820    }
821
822    /// Constructs a new `MutBumpVecRev<T>` and pushes `value` `count` times.
823    ///
824    /// # Errors
825    /// Errors if the allocation fails.
826    ///
827    /// # Examples
828    /// ```
829    /// # use bump_scope::{Bump, MutBumpVecRev};
830    /// # let mut bump: Bump = Bump::new();
831    /// let vec = MutBumpVecRev::try_from_elem_in("ho", 3, &mut bump)?;
832    /// assert_eq!(vec, ["ho", "ho", "ho"]);
833    /// # Ok::<(), bump_scope::alloc::AllocError>(())
834    /// ```
835    #[inline(always)]
836    pub fn try_from_elem_in(value: T, count: usize, allocator: A) -> Result<Self, AllocError>
837    where
838        T: Clone,
839    {
840        Self::generic_from_elem_in(value, count, allocator)
841    }
842
843    #[inline]
844    pub(crate) fn generic_from_elem_in<E: ErrorBehavior>(value: T, count: usize, allocator: A) -> Result<Self, E>
845    where
846        T: Clone,
847    {
848        let mut vec = Self::generic_with_capacity_in(count, allocator)?;
849
850        unsafe {
851            if count != 0 {
852                for _ in 0..(count - 1) {
853                    vec.push_with_unchecked(|| value.clone());
854                }
855
856                vec.push_with_unchecked(|| value);
857            }
858        }
859
860        Ok(vec)
861    }
862
863    /// Constructs a new `MutBumpVecRev<T>` from an [`OwnedSlice`].
864    ///
865    /// # Panics
866    /// Panics if the allocation fails.
867    ///
868    /// # Examples
869    /// ```
870    /// # use bump_scope::{Bump, MutBumpVecRev};
871    /// # let bump: Bump = Bump::new();
872    /// # let mut bump_a: Bump = Bump::new();
873    /// # let mut bump_b: Bump = Bump::new();
874    /// # let mut bump_c: Bump = Bump::new();
875    /// # let mut bump_d: Bump = Bump::new();
876    /// // by value
877    /// let a = MutBumpVecRev::from_owned_slice_in([1, 2], &mut bump_a);
878    /// let b = MutBumpVecRev::from_owned_slice_in(vec![3, 4], &mut bump_b);
879    /// let c = MutBumpVecRev::from_owned_slice_in(bump.alloc_iter(5..=6), &mut bump_c);
880    ///
881    /// // by mutable reference
882    /// let mut other = vec![7, 8];
883    /// let d = MutBumpVecRev::from_owned_slice_in(&mut other, &mut bump_d);
884    /// assert!(other.is_empty());
885    ///
886    /// assert_eq!(a, [1, 2]);
887    /// assert_eq!(b, [3, 4]);
888    /// assert_eq!(c, [5, 6]);
889    /// assert_eq!(d, [7, 8]);
890    /// ```
891    #[must_use]
892    #[inline(always)]
893    #[cfg(feature = "panic-on-alloc")]
894    pub fn from_owned_slice_in(owned_slice: impl OwnedSlice<Item = T>, allocator: A) -> Self {
895        panic_on_error(Self::generic_from_owned_slice_in(owned_slice, allocator))
896    }
897
898    /// Constructs a new `MutBumpVecRev<T>` from an [`OwnedSlice`].
899    ///
900    /// # Errors
901    /// Errors if the allocation fails.
902    ///
903    /// # Examples
904    /// ```
905    /// # use bump_scope::{Bump, MutBumpVecRev};
906    /// # let bump: Bump = Bump::new();
907    /// # let mut bump_a: Bump = Bump::new();
908    /// # let mut bump_b: Bump = Bump::new();
909    /// # let mut bump_c: Bump = Bump::new();
910    /// # let mut bump_d: Bump = Bump::new();
911    /// // by value
912    /// let a = MutBumpVecRev::try_from_owned_slice_in([1, 2], &mut bump_a)?;
913    /// let b = MutBumpVecRev::try_from_owned_slice_in(vec![3, 4], &mut bump_b)?;
914    /// let c = MutBumpVecRev::try_from_owned_slice_in(bump.alloc_iter(5..=6), &mut bump_c)?;
915    ///
916    /// // by mutable reference
917    /// let mut other = vec![7, 8];
918    /// let d = MutBumpVecRev::try_from_owned_slice_in(&mut other, &mut bump_d)?;
919    /// assert!(other.is_empty());
920    ///
921    /// assert_eq!(a, [1, 2]);
922    /// assert_eq!(b, [3, 4]);
923    /// assert_eq!(c, [5, 6]);
924    /// assert_eq!(d, [7, 8]);
925    /// # Ok::<(), bump_scope::alloc::AllocError>(())
926    /// ```
927    #[inline(always)]
928    pub fn try_from_owned_slice_in(owned_slice: impl OwnedSlice<Item = T>, allocator: A) -> Result<Self, AllocError> {
929        Self::generic_from_owned_slice_in(owned_slice, allocator)
930    }
931
932    #[inline]
933    pub(crate) fn generic_from_owned_slice_in<E: ErrorBehavior>(
934        owned_slice: impl OwnedSlice<Item = T>,
935        allocator: A,
936    ) -> Result<Self, E> {
937        let owned_slice = owned_slice.into_take_owned_slice();
938        let mut this = Self::generic_with_capacity_in(owned_slice.owned_slice_ref().len(), allocator)?;
939        this.generic_append(owned_slice)?;
940        Ok(this)
941    }
942
943    /// Create a new [`MutBumpVecRev`] whose elements are taken from an iterator and allocated in the given `bump`.
944    ///
945    /// This is behaviorally identical to [`FromIterator::from_iter`].
946    ///
947    /// If you have an `impl ExactSizeIterator` then you can use [`from_iter_exact_in`](Self::from_iter_exact_in) instead for better performance.
948    ///
949    /// # Panics
950    /// Panics if the allocation fails.
951    ///
952    /// # Examples
953    /// ```
954    /// # use bump_scope::{Bump, MutBumpVecRev};
955    /// # let mut bump: Bump = Bump::new();
956    /// let vec = MutBumpVecRev::from_iter_in([1, 2, 3], &mut bump);
957    /// assert_eq!(vec, [3, 2, 1]);
958    /// ```
959    #[must_use]
960    #[inline(always)]
961    #[cfg(feature = "panic-on-alloc")]
962    pub fn from_iter_in<I>(iter: I, allocator: A) -> Self
963    where
964        I: IntoIterator<Item = T>,
965    {
966        panic_on_error(Self::generic_from_iter_in(iter, allocator))
967    }
968
969    /// Create a new [`MutBumpVecRev`] whose elements are taken from an iterator and allocated in the given `bump`.
970    ///
971    /// This is behaviorally identical to [`FromIterator::from_iter`].
972    ///
973    /// If you have an `impl ExactSizeIterator` then you can use [`try_from_iter_exact_in`](Self::try_from_iter_exact_in) instead for better performance.
974    ///
975    /// # Errors
976    /// Errors if the allocation fails.
977    ///
978    /// # Examples
979    /// ```
980    /// # use bump_scope::{Bump, MutBumpVecRev};
981    /// # let mut bump: Bump = Bump::new();
982    /// let vec = MutBumpVecRev::try_from_iter_in([1, 2, 3], &mut bump)?;
983    /// assert_eq!(vec, [3, 2, 1]);
984    /// # Ok::<(), bump_scope::alloc::AllocError>(())
985    /// ```
986    #[inline(always)]
987    pub fn try_from_iter_in<I>(iter: I, allocator: A) -> Result<Self, AllocError>
988    where
989        I: IntoIterator<Item = T>,
990    {
991        Self::generic_from_iter_in(iter, allocator)
992    }
993
994    #[inline]
995    pub(crate) fn generic_from_iter_in<E: ErrorBehavior, I>(iter: I, allocator: A) -> Result<Self, E>
996    where
997        I: IntoIterator<Item = T>,
998    {
999        let iter = iter.into_iter();
1000        let capacity = iter.size_hint().0;
1001
1002        let mut vec = Self::generic_with_capacity_in(capacity, allocator)?;
1003
1004        for value in iter {
1005            vec.generic_push(value)?;
1006        }
1007
1008        Ok(vec)
1009    }
1010
1011    /// Create a new [`MutBumpVecRev`] whose elements are taken from an iterator and allocated in the given `bump`.
1012    ///
1013    /// This is just like [`from_iter_in`](Self::from_iter_in) but optimized for an [`ExactSizeIterator`].
1014    ///
1015    /// # Panics
1016    /// Panics if the allocation fails.
1017    ///
1018    /// # Examples
1019    /// ```
1020    /// # use bump_scope::{Bump, MutBumpVecRev};
1021    /// # let mut bump: Bump = Bump::new();
1022    /// let vec = MutBumpVecRev::from_iter_exact_in([1, 2, 3], &mut bump);
1023    /// assert_eq!(vec, [3, 2, 1]);
1024    /// ```
1025    #[must_use]
1026    #[inline(always)]
1027    #[cfg(feature = "panic-on-alloc")]
1028    pub fn from_iter_exact_in<I>(iter: I, allocator: A) -> Self
1029    where
1030        I: IntoIterator<Item = T>,
1031        I::IntoIter: ExactSizeIterator,
1032    {
1033        panic_on_error(Self::generic_from_iter_exact_in(iter, allocator))
1034    }
1035
1036    /// Create a new [`MutBumpVecRev`] whose elements are taken from an iterator and allocated in the given `bump`.
1037    ///
1038    /// This is just like [`from_iter_in`](Self::from_iter_in) but optimized for an [`ExactSizeIterator`].
1039    ///
1040    /// # Errors
1041    /// Errors if the allocation fails.
1042    ///
1043    /// # Examples
1044    /// ```
1045    /// # use bump_scope::{Bump, MutBumpVecRev};
1046    /// # let mut bump: Bump = Bump::new();
1047    /// let vec = MutBumpVecRev::try_from_iter_exact_in([1, 2, 3], &mut bump)?;
1048    /// assert_eq!(vec, [3, 2, 1]);
1049    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1050    /// ```
1051    #[inline(always)]
1052    pub fn try_from_iter_exact_in<I>(iter: I, allocator: A) -> Result<Self, AllocError>
1053    where
1054        I: IntoIterator<Item = T>,
1055        I::IntoIter: ExactSizeIterator,
1056    {
1057        Self::generic_from_iter_exact_in(iter, allocator)
1058    }
1059
1060    #[inline]
1061    pub(crate) fn generic_from_iter_exact_in<E: ErrorBehavior, I>(iter: I, allocator: A) -> Result<Self, E>
1062    where
1063        I: IntoIterator<Item = T>,
1064        I::IntoIter: ExactSizeIterator,
1065    {
1066        let mut iter = iter.into_iter();
1067        let len = iter.len();
1068
1069        let mut vec = Self::generic_with_capacity_in(len, allocator)?;
1070
1071        while vec.len() != vec.capacity() {
1072            match iter.next() {
1073                // SAFETY: we checked above that `len != capacity`, so there is space
1074                Some(value) => unsafe { vec.push_unchecked(value) },
1075                None => break,
1076            }
1077        }
1078
1079        Ok(vec)
1080    }
1081
1082    /// Appends an element to the front of a collection.
1083    ///
1084    /// # Panics
1085    /// Panics if the allocation fails.
1086    ///
1087    /// # Examples
1088    /// ```
1089    /// # use bump_scope::{mut_bump_vec_rev, Bump};
1090    /// # let mut bump: Bump = Bump::new();
1091    /// let mut vec = mut_bump_vec_rev![in &mut bump; 2, 1];
1092    /// vec.push(3);
1093    /// assert_eq!(vec, [3, 2, 1]);
1094    /// # let _ = vec;
1095    /// ```
1096    #[inline(always)]
1097    #[cfg(feature = "panic-on-alloc")]
1098    pub fn push(&mut self, value: T) {
1099        panic_on_error(self.generic_push(value));
1100    }
1101
1102    /// Appends an element to the front of a collection.
1103    ///
1104    /// # Errors
1105    /// Errors if the allocation fails.
1106    ///
1107    /// # Examples
1108    /// ```
1109    /// # use bump_scope::{mut_bump_vec_rev, Bump};
1110    /// # let mut bump: Bump = Bump::new();
1111    /// let mut vec = mut_bump_vec_rev![try in &mut bump; 2, 1]?;
1112    /// vec.try_push(3)?;
1113    /// assert_eq!(vec, [3, 2, 1]);
1114    /// # let _ = vec;
1115    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1116    /// ```
1117    #[inline(always)]
1118    pub fn try_push(&mut self, value: T) -> Result<(), AllocError> {
1119        self.generic_push(value)
1120    }
1121
1122    #[inline]
1123    pub(crate) fn generic_push<E: ErrorBehavior>(&mut self, value: T) -> Result<(), E> {
1124        self.generic_push_with(|| value)
1125    }
1126
1127    /// Reserves space for one more element, then calls `f`
1128    /// to produce the value that is appended.
1129    ///
1130    /// In some cases this could be more performant than `push(f())` because it
1131    /// permits the compiler to directly place `T` in the vector instead of
1132    /// constructing it on the stack and copying it over.
1133    ///
1134    /// # Panics
1135    /// Panics if the allocation fails.
1136    ///
1137    /// # Examples
1138    /// ```
1139    /// # use bump_scope::{Bump, mut_bump_vec_rev};
1140    /// # let mut bump: Bump = Bump::new();
1141    /// let mut vec = mut_bump_vec_rev![in &mut bump; 2, 3];
1142    /// vec.push_with(|| 1);
1143    /// assert_eq!(vec, [1, 2, 3]);
1144    /// ```
1145    #[inline(always)]
1146    #[cfg(feature = "panic-on-alloc")]
1147    pub fn push_with(&mut self, f: impl FnOnce() -> T) {
1148        panic_on_error(self.generic_push_with(f));
1149    }
1150
1151    /// Reserves space for one more element, then calls `f`
1152    /// to produce the value that is appended.
1153    ///
1154    /// In some cases this could be more performant than `push(f())` because it
1155    /// permits the compiler to directly place `T` in the vector instead of
1156    /// constructing it on the stack and copying it over.
1157    ///
1158    /// # Errors
1159    /// Errors if the allocation fails.
1160    ///
1161    /// # Examples
1162    /// ```
1163    /// # use bump_scope::{Bump, mut_bump_vec_rev};
1164    /// # let mut bump: Bump = Bump::new();
1165    /// let mut vec = mut_bump_vec_rev![in &mut bump; 2, 3];
1166    /// vec.try_push_with(|| 1)?;
1167    /// assert_eq!(vec, [1, 2, 3]);
1168    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1169    /// ```
1170    #[inline(always)]
1171    pub fn try_push_with(&mut self, f: impl FnOnce() -> T) -> Result<(), AllocError> {
1172        self.generic_push_with(f)
1173    }
1174
1175    #[inline]
1176    pub(crate) fn generic_push_with<E: ErrorBehavior>(&mut self, f: impl FnOnce() -> T) -> Result<(), E> {
1177        self.generic_reserve_one()?;
1178        unsafe {
1179            self.push_with_unchecked(f);
1180        }
1181        Ok(())
1182    }
1183
1184    /// Inserts an element at position `index` within the vector, shifting all elements after it to the right.
1185    ///
1186    /// # Panics
1187    /// Panics if the allocation fails.
1188    ///
1189    /// Panics if `index > len`.
1190    ///
1191    /// # Examples
1192    /// ```
1193    /// # use bump_scope::{mut_bump_vec_rev, Bump};
1194    /// # let mut bump: Bump = Bump::new();
1195    /// let mut vec = mut_bump_vec_rev![in &mut bump; 1, 2, 3];
1196    /// vec.insert(1, 4);
1197    /// assert_eq!(vec, [1, 4, 2, 3]);
1198    /// vec.insert(4, 5);
1199    /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1200    /// ```
1201    #[inline(always)]
1202    #[cfg(feature = "panic-on-alloc")]
1203    pub fn insert(&mut self, index: usize, element: T) {
1204        panic_on_error(self.generic_insert(index, element));
1205    }
1206
1207    /// Inserts an element at position `index` within the vector, shifting all elements after it to the right.
1208    ///
1209    /// # Panics
1210    /// Panics if `index > len`.
1211    ///
1212    /// # Errors
1213    /// Errors if the allocation fails.
1214    ///
1215    /// # Examples
1216    /// ```
1217    /// # use bump_scope::{mut_bump_vec_rev, Bump};
1218    /// # let mut bump: Bump = Bump::new();
1219    /// let mut vec = mut_bump_vec_rev![try in &mut bump; 1, 2, 3]?;
1220    /// vec.try_insert(1, 4)?;
1221    /// assert_eq!(vec, [1, 4, 2, 3]);
1222    /// vec.try_insert(4, 5)?;
1223    /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1224    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1225    /// ```
1226    #[inline(always)]
1227    pub fn try_insert(&mut self, index: usize, element: T) -> Result<(), AllocError> {
1228        self.generic_insert(index, element)
1229    }
1230
1231    #[inline]
1232    pub(crate) fn generic_insert<E: ErrorBehavior>(&mut self, index: usize, element: T) -> Result<(), E> {
1233        #[cold]
1234        #[track_caller]
1235        #[inline(never)]
1236        fn assert_failed(index: usize, len: usize) -> ! {
1237            panic!("insertion index (is {index}) should be <= len (is {len})");
1238        }
1239
1240        if index > self.len {
1241            assert_failed(index, self.len);
1242        }
1243
1244        self.generic_reserve_one()?;
1245
1246        unsafe {
1247            if index == 0 {
1248                self.len += 1;
1249                self.as_mut_ptr().write(element);
1250            } else {
1251                let start = self.as_mut_ptr();
1252                let start_sub = start.sub(1);
1253                ptr::copy(start, start_sub, index);
1254                self.len += 1;
1255                start_sub.add(index).write(element);
1256            }
1257        }
1258
1259        Ok(())
1260    }
1261
1262    /// Copies and appends all elements in a slice to the `MutBumpVecRev`.
1263    ///
1264    /// Iterates over the `slice`, copies each element, and then appends
1265    /// it to this `MutBumpVecRev`. The `slice` is traversed in-order.
1266    ///
1267    /// Note that this function is same as [`extend`] except that it is
1268    /// specialized to work with copyable slices instead.
1269    ///
1270    /// [`extend`]: Self::extend
1271    ///
1272    /// # Panics
1273    /// Panics if the allocation fails.
1274    ///
1275    /// # Examples
1276    /// ```
1277    /// # use bump_scope::{ Bump, mut_bump_vec_rev };
1278    /// # let mut bump: Bump = Bump::new();
1279    /// let mut vec = mut_bump_vec_rev![in &mut bump; 4];
1280    /// vec.extend_from_slice_copy(&[1, 2, 3]);
1281    /// assert_eq!(vec, [1, 2, 3, 4]);
1282    /// ```
1283    #[inline(always)]
1284    #[cfg(feature = "panic-on-alloc")]
1285    pub fn extend_from_slice_copy(&mut self, slice: &[T])
1286    where
1287        T: Copy,
1288    {
1289        panic_on_error(self.generic_extend_from_slice_copy(slice));
1290    }
1291
1292    /// Copies and appends all elements in a slice to the `MutBumpVecRev`.
1293    ///
1294    /// Iterates over the `slice`, copies each element, and then appends
1295    /// it to this `MutBumpVecRev`. The `slice` is traversed in-order.
1296    ///
1297    /// Note that this function is same as [`extend`] except that it is
1298    /// specialized to work with copyable slices instead.
1299    ///
1300    /// [`extend`]: Self::extend
1301    ///
1302    /// # Errors
1303    /// Errors if the allocation fails.
1304    ///
1305    /// # Examples
1306    /// ```
1307    /// # use bump_scope::{ Bump, mut_bump_vec_rev };
1308    /// # let mut bump: Bump = Bump::new();
1309    /// let mut vec = mut_bump_vec_rev![try in &mut bump; 4]?;
1310    /// vec.try_extend_from_slice_copy(&[1, 2, 3])?;
1311    /// assert_eq!(vec, [1, 2, 3, 4]);
1312    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1313    /// ```
1314    #[inline(always)]
1315    pub fn try_extend_from_slice_copy(&mut self, slice: &[T]) -> Result<(), AllocError>
1316    where
1317        T: Copy,
1318    {
1319        self.generic_extend_from_slice_copy(slice)
1320    }
1321
1322    #[inline]
1323    pub(crate) fn generic_extend_from_slice_copy<E: ErrorBehavior>(&mut self, slice: &[T]) -> Result<(), E>
1324    where
1325        T: Copy,
1326    {
1327        unsafe { self.extend_by_copy_nonoverlapping(slice) }
1328    }
1329
1330    /// Clones and appends all elements in a slice to the `MutBumpVecRev`.
1331    ///
1332    /// Iterates over the `slice`, clones each element, and then appends
1333    /// it to this `MutBumpVecRev`. The `slice` is traversed in-order.
1334    ///
1335    /// Note that this function is same as [`extend`] except that it is
1336    /// specialized to work with slices instead.
1337    ///
1338    /// [`extend`]: Self::extend
1339    ///
1340    /// # Panics
1341    /// Panics if the allocation fails.
1342    ///
1343    /// # Examples
1344    /// ```
1345    /// # use std::string::String;
1346    /// # use bump_scope::{ Bump, mut_bump_vec_rev };
1347    /// # let mut bump: Bump = Bump::new();
1348    /// let mut vec = mut_bump_vec_rev![in &mut bump; String::from("c")];
1349    /// vec.extend_from_slice_clone(&[String::from("a"), String::from("b")]);
1350    /// assert_eq!(vec, ["a", "b", "c"]);
1351    /// ```
1352    #[inline(always)]
1353    #[cfg(feature = "panic-on-alloc")]
1354    pub fn extend_from_slice_clone(&mut self, slice: &[T])
1355    where
1356        T: Clone,
1357    {
1358        panic_on_error(self.generic_extend_from_slice_clone(slice));
1359    }
1360
1361    /// Clones and appends all elements in a slice to the `MutBumpVecRev`.
1362    ///
1363    /// Iterates over the `slice`, clones each element, and then appends
1364    /// it to this `MutBumpVecRev`. The `slice` is traversed in-order.
1365    ///
1366    /// Note that this function is same as [`extend`] except that it is
1367    /// specialized to work with slices instead.
1368    ///
1369    /// [`extend`]: Self::extend
1370    ///
1371    /// # Errors
1372    /// Errors if the allocation fails.
1373    ///
1374    /// # Examples
1375    /// ```
1376    /// # use std::string::String;
1377    /// # use bump_scope::{ Bump, mut_bump_vec_rev };
1378    /// # let mut bump: Bump = Bump::new();
1379    /// let mut vec = mut_bump_vec_rev![try in &mut bump; String::from("c")]?;
1380    /// vec.try_extend_from_slice_clone(&[String::from("a"), String::from("b")])?;
1381    /// assert_eq!(vec, ["a", "b", "c"]);
1382    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1383    /// ```
1384    #[inline(always)]
1385    pub fn try_extend_from_slice_clone(&mut self, slice: &[T]) -> Result<(), AllocError>
1386    where
1387        T: Clone,
1388    {
1389        self.generic_extend_from_slice_clone(slice)
1390    }
1391
1392    #[inline]
1393    pub(crate) fn generic_extend_from_slice_clone<E: ErrorBehavior>(&mut self, slice: &[T]) -> Result<(), E>
1394    where
1395        T: Clone,
1396    {
1397        self.generic_reserve(slice.len())?;
1398
1399        unsafe {
1400            let src = slice.as_ptr().add(slice.len());
1401            let mut pos = 0usize;
1402
1403            while likely(pos != slice.len()) {
1404                let elem = &*src.sub(pos + 1);
1405                self.push_unchecked(elem.clone());
1406                pos += 1;
1407            }
1408        }
1409
1410        Ok(())
1411    }
1412
1413    /// Copies elements from `src` range to the start of the vector.
1414    ///
1415    /// # Panics
1416    /// Panics if the allocation fails.
1417    ///
1418    /// Panics if the starting point is greater than the end point or if
1419    /// the end point is greater than the length of the vector.
1420    ///
1421    /// # Examples
1422    /// ```
1423    /// # use bump_scope::{Bump, mut_bump_vec_rev};
1424    /// # let mut bump: Bump = Bump::new();
1425    /// let mut vec = mut_bump_vec_rev![in &mut bump; 0, 1, 2, 3, 4];
1426    ///
1427    /// vec.extend_from_within_copy(2..);
1428    /// assert_eq!(vec, [2, 3, 4, 0, 1, 2, 3, 4]);
1429    ///
1430    /// vec.extend_from_within_copy(..2);
1431    /// assert_eq!(vec, [2, 3, 2, 3, 4, 0, 1, 2, 3, 4]);
1432    ///
1433    /// vec.extend_from_within_copy(4..8);
1434    /// assert_eq!(vec, [4, 0, 1, 2, 2, 3, 2, 3, 4, 0, 1, 2, 3, 4]);
1435    /// ```
1436    #[inline(always)]
1437    #[cfg(feature = "panic-on-alloc")]
1438    pub fn extend_from_within_copy<R>(&mut self, src: R)
1439    where
1440        T: Copy,
1441        R: RangeBounds<usize>,
1442    {
1443        panic_on_error(self.generic_extend_from_within_copy(src));
1444    }
1445
1446    /// Copies elements from `src` range to the start of the vector.
1447    ///
1448    /// # Panics
1449    /// Panics if the starting point is greater than the end point or if
1450    /// the end point is greater than the length of the vector.
1451    ///
1452    /// # Errors
1453    /// Errors if the allocation fails.
1454    ///
1455    /// # Examples
1456    /// ```
1457    /// # use bump_scope::{Bump, mut_bump_vec_rev};
1458    /// # let mut bump: Bump = Bump::new();
1459    /// let mut vec = mut_bump_vec_rev![try in &mut bump; 0, 1, 2, 3, 4]?;
1460    ///
1461    /// vec.try_extend_from_within_copy(2..)?;
1462    /// assert_eq!(vec, [2, 3, 4, 0, 1, 2, 3, 4]);
1463    ///
1464    /// vec.try_extend_from_within_copy(..2)?;
1465    /// assert_eq!(vec, [2, 3, 2, 3, 4, 0, 1, 2, 3, 4]);
1466    ///
1467    /// vec.try_extend_from_within_copy(4..8)?;
1468    /// assert_eq!(vec, [4, 0, 1, 2, 2, 3, 2, 3, 4, 0, 1, 2, 3, 4]);
1469    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1470    /// ```
1471    #[inline(always)]
1472    pub fn try_extend_from_within_copy<R>(&mut self, src: R) -> Result<(), AllocError>
1473    where
1474        T: Copy,
1475        R: RangeBounds<usize>,
1476    {
1477        self.generic_extend_from_within_copy(src)
1478    }
1479
1480    #[inline]
1481    pub(crate) fn generic_extend_from_within_copy<E: ErrorBehavior, R>(&mut self, src: R) -> Result<(), E>
1482    where
1483        T: Copy,
1484        R: RangeBounds<usize>,
1485    {
1486        let range = polyfill::slice::range(src, ..self.len());
1487        let count = range.len();
1488
1489        self.generic_reserve(count)?;
1490
1491        // SAFETY:
1492        // - `slice::range` guarantees that the given range is valid for indexing self
1493        unsafe {
1494            let ptr = self.as_mut_ptr();
1495
1496            let src = ptr.add(range.start);
1497            let dst = ptr.sub(count);
1498            ptr::copy_nonoverlapping(src, dst, count);
1499        }
1500
1501        self.len += count;
1502        Ok(())
1503    }
1504
1505    /// Clones elements from `src` range to the end of the vector.
1506    ///
1507    /// # Panics
1508    /// Panics if the allocation fails.
1509    ///
1510    /// Panics if the starting point is greater than the end point or if
1511    /// the end point is greater than the length of the vector.
1512    ///
1513    /// # Examples
1514    /// ```
1515    /// # use bump_scope::{Bump, mut_bump_vec_rev};
1516    /// # let mut bump: Bump = Bump::new();
1517    /// let mut vec = mut_bump_vec_rev![in &mut bump; 0, 1, 2, 3, 4];
1518    ///
1519    /// vec.extend_from_within_clone(2..);
1520    /// assert_eq!(vec, [2, 3, 4, 0, 1, 2, 3, 4]);
1521    ///
1522    /// vec.extend_from_within_clone(..2);
1523    /// assert_eq!(vec, [2, 3, 2, 3, 4, 0, 1, 2, 3, 4]);
1524    ///
1525    /// vec.extend_from_within_clone(4..8);
1526    /// assert_eq!(vec, [4, 0, 1, 2, 2, 3, 2, 3, 4, 0, 1, 2, 3, 4]);
1527    /// ```
1528    #[inline(always)]
1529    #[cfg(feature = "panic-on-alloc")]
1530    pub fn extend_from_within_clone<R>(&mut self, src: R)
1531    where
1532        T: Clone,
1533        R: RangeBounds<usize>,
1534    {
1535        panic_on_error(self.generic_extend_from_within_clone(src));
1536    }
1537
1538    /// Clones elements from `src` range to the end of the vector.
1539    ///
1540    /// # Panics
1541    /// Panics if the starting point is greater than the end point or if
1542    /// the end point is greater than the length of the vector.
1543    ///
1544    /// # Errors
1545    /// Errors if the allocation fails.
1546    ///
1547    /// # Examples
1548    /// ```
1549    /// # use bump_scope::{Bump, mut_bump_vec_rev};
1550    /// # let mut bump: Bump = Bump::new();
1551    /// let mut vec = mut_bump_vec_rev![try in &mut bump; 0, 1, 2, 3, 4]?;
1552    ///
1553    /// vec.try_extend_from_within_clone(2..)?;
1554    /// assert_eq!(vec, [2, 3, 4, 0, 1, 2, 3, 4]);
1555    ///
1556    /// vec.try_extend_from_within_clone(..2)?;
1557    /// assert_eq!(vec, [2, 3, 2, 3, 4, 0, 1, 2, 3, 4]);
1558    ///
1559    /// vec.try_extend_from_within_clone(4..8)?;
1560    /// assert_eq!(vec, [4, 0, 1, 2, 2, 3, 2, 3, 4, 0, 1, 2, 3, 4]);
1561    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1562    /// ```
1563    #[inline(always)]
1564    pub fn try_extend_from_within_clone<R>(&mut self, src: R) -> Result<(), AllocError>
1565    where
1566        T: Clone,
1567        R: RangeBounds<usize>,
1568    {
1569        self.generic_extend_from_within_clone(src)
1570    }
1571
1572    #[inline]
1573    pub(crate) fn generic_extend_from_within_clone<E: ErrorBehavior, R>(&mut self, src: R) -> Result<(), E>
1574    where
1575        T: Clone,
1576        R: RangeBounds<usize>,
1577    {
1578        let range = polyfill::slice::range(src, ..self.len());
1579        let count = range.len();
1580
1581        self.generic_reserve(count)?;
1582
1583        if T::IS_ZST {
1584            unsafe {
1585                // We can materialize ZST's from nothing.
1586                #[expect(clippy::uninit_assumed_init)]
1587                let fake = ManuallyDrop::new(MaybeUninit::<T>::uninit().assume_init());
1588
1589                for _ in 0..count {
1590                    self.push_unchecked((*fake).clone());
1591                }
1592
1593                return Ok(());
1594            }
1595        }
1596
1597        // SAFETY:
1598        // - `slice::range` guarantees that the given range is valid for indexing self
1599        unsafe {
1600            let ptr = self.as_mut_ptr();
1601
1602            let mut src = ptr.add(range.end);
1603            let mut dst = ptr;
1604
1605            let src_end = src.sub(count);
1606
1607            while src != src_end {
1608                src = src.sub(1);
1609                dst = dst.sub(1);
1610
1611                dst.write((*src).clone());
1612
1613                self.len += 1;
1614            }
1615        }
1616
1617        Ok(())
1618    }
1619
1620    /// Reserves capacity for at least `additional` more elements to be inserted
1621    /// in the given `MutBumpVecRev<T>`. The collection may reserve more space to
1622    /// speculatively avoid frequent reallocations. After calling `reserve`,
1623    /// capacity will be greater than or equal to `self.len() + additional`.
1624    /// Does nothing if capacity is already sufficient.
1625    ///
1626    /// # Panics
1627    /// Panics if the allocation fails.
1628    ///
1629    /// # Examples
1630    /// ```
1631    /// # use bump_scope::{Bump, mut_bump_vec_rev};
1632    /// # let mut bump: Bump = Bump::new();
1633    /// let mut vec = mut_bump_vec_rev![in &mut bump; 1];
1634    /// vec.reserve(10);
1635    /// assert!(vec.capacity() >= 11);
1636    /// ```
1637    #[inline(always)]
1638    #[cfg(feature = "panic-on-alloc")]
1639    pub fn reserve(&mut self, additional: usize) {
1640        panic_on_error(self.generic_reserve(additional));
1641    }
1642
1643    /// Reserves capacity for at least `additional` more elements to be inserted
1644    /// in the given `MutBumpVecRev<T>`. The collection may reserve more space to
1645    /// speculatively avoid frequent reallocations. After calling `reserve`,
1646    /// capacity will be greater than or equal to `self.len() + additional`.
1647    /// Does nothing if capacity is already sufficient.
1648    ///
1649    /// # Errors
1650    /// Errors if the allocation fails.
1651    ///
1652    /// # Examples
1653    /// ```
1654    /// # use bump_scope::{Bump, mut_bump_vec_rev};
1655    /// # let mut bump: Bump = Bump::new();
1656    /// let mut vec = mut_bump_vec_rev![try in &mut bump; 1]?;
1657    /// vec.try_reserve(10)?;
1658    /// assert!(vec.capacity() >= 11);
1659    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1660    /// ```
1661    #[inline(always)]
1662    pub fn try_reserve(&mut self, additional: usize) -> Result<(), AllocError> {
1663        self.generic_reserve(additional)
1664    }
1665
1666    #[inline]
1667    pub(crate) fn generic_reserve<E: ErrorBehavior>(&mut self, additional: usize) -> Result<(), E> {
1668        if additional > (self.capacity() - self.len()) {
1669            self.generic_grow_amortized(additional)?;
1670        }
1671
1672        Ok(())
1673    }
1674
1675    /// Reserves the minimum capacity for at least `additional` more elements to
1676    /// be inserted in the given `MutBumpVecRev<T>`. Unlike [`reserve`], this will not
1677    /// deliberately over-allocate to speculatively avoid frequent allocations.
1678    /// After calling `reserve_exact`, capacity will be greater than or equal to
1679    /// `self.len() + additional`. Does nothing if the capacity is already
1680    /// sufficient.
1681    ///
1682    /// Note that the allocator may give the collection more space than it
1683    /// requests. Therefore, capacity cannot be relied upon to be precisely
1684    /// minimal. Prefer [`reserve`] if future insertions are expected.
1685    ///
1686    /// [`reserve`]: Self::reserve
1687    ///
1688    /// # Panics
1689    /// Panics if the allocation fails.
1690    ///
1691    /// # Examples
1692    /// ```
1693    /// # use bump_scope::{Bump, mut_bump_vec_rev};
1694    /// # let mut bump: Bump = Bump::new();
1695    /// let mut vec = mut_bump_vec_rev![in &mut bump; 1];
1696    /// vec.reserve_exact(10);
1697    /// assert!(vec.capacity() >= 11);
1698    /// ```
1699    #[inline(always)]
1700    #[cfg(feature = "panic-on-alloc")]
1701    pub fn reserve_exact(&mut self, additional: usize) {
1702        panic_on_error(self.generic_reserve_exact(additional));
1703    }
1704
1705    /// Reserves the minimum capacity for at least `additional` more elements to
1706    /// be inserted in the given `MutBumpVecRev<T>`. Unlike [`reserve`], this will not
1707    /// deliberately over-allocate to speculatively avoid frequent allocations.
1708    /// After calling `reserve_exact`, capacity will be greater than or equal to
1709    /// `self.len() + additional`. Does nothing if the capacity is already
1710    /// sufficient.
1711    ///
1712    /// Note that the allocator may give the collection more space than it
1713    /// requests. Therefore, capacity cannot be relied upon to be precisely
1714    /// minimal. Prefer [`reserve`] if future insertions are expected.
1715    ///
1716    /// [`reserve`]: Self::reserve
1717    ///
1718    /// # Errors
1719    /// Errors if the allocation fails.
1720    ///
1721    /// # Examples
1722    /// ```
1723    /// # use bump_scope::{Bump, mut_bump_vec_rev};
1724    /// # let mut bump: Bump = Bump::new();
1725    /// let mut vec = mut_bump_vec_rev![try in &mut bump; 1]?;
1726    /// vec.try_reserve_exact(10)?;
1727    /// assert!(vec.capacity() >= 11);
1728    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1729    /// ```
1730    #[inline(always)]
1731    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), AllocError> {
1732        self.generic_reserve_exact(additional)
1733    }
1734
1735    #[inline]
1736    pub(crate) fn generic_reserve_exact<E: ErrorBehavior>(&mut self, additional: usize) -> Result<(), E> {
1737        if additional > (self.capacity() - self.len()) {
1738            self.generic_grow_exact(additional)?;
1739        }
1740
1741        Ok(())
1742    }
1743
1744    /// Resizes the `MutBumpVecRev` in-place so that `len` is equal to `new_len`.
1745    ///
1746    /// If `new_len` is greater than `len`, the `MutBumpVecRev` is extended by the
1747    /// difference, with each additional slot filled with `value`.
1748    /// If `new_len` is less than `len`, the `MutBumpVecRev` is simply truncated.
1749    ///
1750    /// This method requires `T` to implement [`Clone`],
1751    /// in order to be able to clone the passed value.
1752    /// If you need more flexibility (or want to rely on [`Default`] instead of
1753    /// [`Clone`]), use [`resize_with`].
1754    /// If you only need to resize to a smaller size, use [`truncate`].
1755    ///
1756    /// [`resize_with`]: Self::resize_with
1757    /// [`truncate`]: Self::truncate
1758    ///
1759    /// # Panics
1760    /// Panics if the allocation fails.
1761    ///
1762    /// # Examples
1763    /// ```
1764    /// # use bump_scope::{Bump, mut_bump_vec_rev};
1765    /// # let mut bump: Bump = Bump::new();
1766    /// let mut vec = mut_bump_vec_rev![in &mut bump; "hello"];
1767    /// vec.resize(3, "world");
1768    /// assert_eq!(vec, ["world", "world", "hello"]);
1769    /// drop(vec);
1770    ///
1771    /// let mut vec = mut_bump_vec_rev![in &mut bump; 1, 2, 3, 4];
1772    /// vec.resize(2, 0);
1773    /// assert_eq!(vec, [3, 4]);
1774    /// ```
1775    #[inline(always)]
1776    #[cfg(feature = "panic-on-alloc")]
1777    pub fn resize(&mut self, new_len: usize, value: T)
1778    where
1779        T: Clone,
1780    {
1781        panic_on_error(self.generic_resize(new_len, value));
1782    }
1783
1784    /// Resizes the `MutBumpVecRev` in-place so that `len` is equal to `new_len`.
1785    ///
1786    /// If `new_len` is greater than `len`, the `MutBumpVecRev` is extended by the
1787    /// difference, with each additional slot filled with `value`.
1788    /// If `new_len` is less than `len`, the `MutBumpVecRev` is simply truncated.
1789    ///
1790    /// This method requires `T` to implement [`Clone`],
1791    /// in order to be able to clone the passed value.
1792    /// If you need more flexibility (or want to rely on [`Default`] instead of
1793    /// [`Clone`]), use [`resize_with`].
1794    /// If you only need to resize to a smaller size, use [`truncate`].
1795    ///
1796    /// [`resize_with`]: Self::resize_with
1797    /// [`truncate`]: Self::truncate
1798    ///
1799    /// # Errors
1800    /// Errors if the allocation fails.
1801    ///
1802    /// # Examples
1803    /// ```
1804    /// # use bump_scope::{Bump, mut_bump_vec_rev};
1805    /// # let mut bump: Bump = Bump::new();
1806    /// let mut vec = mut_bump_vec_rev![try in &mut bump; "hello"]?;
1807    /// vec.try_resize(3, "world")?;
1808    /// assert_eq!(vec, ["world", "world", "hello"]);
1809    /// drop(vec);
1810    ///
1811    /// let mut vec = mut_bump_vec_rev![try in &mut bump; 1, 2, 3, 4]?;
1812    /// vec.try_resize(2, 0)?;
1813    /// assert_eq!(vec, [3, 4]);
1814    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1815    /// ```
1816    #[inline(always)]
1817    pub fn try_resize(&mut self, new_len: usize, value: T) -> Result<(), AllocError>
1818    where
1819        T: Clone,
1820    {
1821        self.generic_resize(new_len, value)
1822    }
1823
1824    #[inline]
1825    pub(crate) fn generic_resize<E: ErrorBehavior>(&mut self, new_len: usize, value: T) -> Result<(), E>
1826    where
1827        T: Clone,
1828    {
1829        let len = self.len();
1830
1831        if new_len > len {
1832            self.extend_with(new_len - len, value)
1833        } else {
1834            self.truncate(new_len);
1835            Ok(())
1836        }
1837    }
1838
1839    /// Resizes the `MutBumpVecRev` in-place so that `len` is equal to `new_len`.
1840    ///
1841    /// If `new_len` is greater than `len`, the `MutBumpVecRev` is extended by the
1842    /// difference, with each additional slot filled with the result of
1843    /// calling the closure `f`. The return values from `f` will end up
1844    /// in the `MutBumpVecRev` in the order they have been generated.
1845    ///
1846    /// If `new_len` is less than `len`, the `MutBumpVecRev` is simply truncated.
1847    ///
1848    /// This method uses a closure to create new values on every push. If
1849    /// you'd rather [`Clone`] a given value, use [`MutBumpVecRev::resize`]. If you
1850    /// want to use the [`Default`] trait to generate values, you can
1851    /// pass [`Default::default`] as the second argument.
1852    ///
1853    /// # Panics
1854    /// Panics if the allocation fails.
1855    ///
1856    /// # Examples
1857    /// ```
1858    /// # use bump_scope::{Bump, mut_bump_vec_rev};
1859    /// # let mut bump: Bump = Bump::new();
1860    /// let mut vec = mut_bump_vec_rev![in &mut bump; 1, 2, 3];
1861    /// vec.resize_with(5, Default::default);
1862    /// assert_eq!(vec, [0, 0, 1, 2, 3]);
1863    /// drop(vec);
1864    ///
1865    /// let mut vec = mut_bump_vec_rev![in &mut bump];
1866    /// let mut p = 1;
1867    /// vec.resize_with(4, || { p *= 2; p });
1868    /// assert_eq!(vec, [16, 8, 4, 2]);
1869    /// ```
1870    #[inline(always)]
1871    #[cfg(feature = "panic-on-alloc")]
1872    pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1873    where
1874        F: FnMut() -> T,
1875    {
1876        panic_on_error(self.generic_resize_with(new_len, f));
1877    }
1878
1879    /// Resizes the `MutBumpVecRev` in-place so that `len` is equal to `new_len`.
1880    ///
1881    /// If `new_len` is greater than `len`, the `MutBumpVecRev` is extended by the
1882    /// difference, with each additional slot filled with the result of
1883    /// calling the closure `f`. The return values from `f` will end up
1884    /// in the `MutBumpVecRev` in the order they have been generated.
1885    ///
1886    /// If `new_len` is less than `len`, the `MutBumpVecRev` is simply truncated.
1887    ///
1888    /// This method uses a closure to create new values on every push. If
1889    /// you'd rather [`Clone`] a given value, use [`MutBumpVecRev::resize`]. If you
1890    /// want to use the [`Default`] trait to generate values, you can
1891    /// pass [`Default::default`] as the second argument.
1892    ///
1893    /// # Errors
1894    /// Errors if the allocation fails.
1895    ///
1896    /// # Examples
1897    /// ```
1898    /// # use bump_scope::{Bump, mut_bump_vec_rev};
1899    /// # let mut bump: Bump = Bump::new();
1900    /// let mut vec = mut_bump_vec_rev![try in &mut bump; 1, 2, 3]?;
1901    /// vec.try_resize_with(5, Default::default)?;
1902    /// assert_eq!(vec, [0, 0, 1, 2, 3]);
1903    /// drop(vec);
1904    ///
1905    /// let mut vec = mut_bump_vec_rev![try in &mut bump]?;
1906    /// let mut p = 1;
1907    /// vec.try_resize_with(4, || { p *= 2; p })?;
1908    /// assert_eq!(vec, [16, 8, 4, 2]);
1909    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1910    /// ```
1911    #[inline(always)]
1912    pub fn try_resize_with<F>(&mut self, new_len: usize, f: F) -> Result<(), AllocError>
1913    where
1914        F: FnMut() -> T,
1915    {
1916        self.generic_resize_with(new_len, f)
1917    }
1918
1919    #[inline]
1920    pub(crate) fn generic_resize_with<E: ErrorBehavior, F>(&mut self, new_len: usize, f: F) -> Result<(), E>
1921    where
1922        F: FnMut() -> T,
1923    {
1924        let len = self.len();
1925        if new_len > len {
1926            unsafe { self.extend_trusted(iter::repeat_with(f).take(new_len - len)) }
1927        } else {
1928            self.truncate(new_len);
1929            Ok(())
1930        }
1931    }
1932
1933    /// Moves all the elements of `other` into `self`, leaving `other` empty.
1934    ///
1935    /// # Panics
1936    /// Panics if the allocation fails.
1937    ///
1938    /// # Examples
1939    /// ```
1940    /// # use bump_scope::{Bump, MutBumpVecRev};
1941    /// # let mut bump: Bump = Bump::new();
1942    /// # let bump2: Bump = Bump::new();
1943    /// let mut vec = MutBumpVecRev::new_in(&mut bump);
1944    ///
1945    /// // append by value
1946    /// vec.append([1, 2]);
1947    /// vec.append(vec![3, 4]);
1948    /// vec.append(bump2.alloc_iter(5..=6));
1949    ///
1950    /// // append by mutable reference
1951    /// let mut other = vec![7, 8];
1952    /// vec.append(&mut other);
1953    ///
1954    /// assert_eq!(other, []);
1955    /// assert_eq!(vec, [7, 8, 5, 6, 3, 4, 1, 2]);
1956    /// ```
1957    #[inline(always)]
1958    #[cfg(feature = "panic-on-alloc")]
1959    pub fn append(&mut self, other: impl OwnedSlice<Item = T>) {
1960        panic_on_error(self.generic_append(other));
1961    }
1962
1963    /// Moves all the elements of `other` into `self`, leaving `other` empty.
1964    ///
1965    /// # Errors
1966    /// Errors if the allocation fails.
1967    ///
1968    /// # Examples
1969    /// ```
1970    /// # use bump_scope::{Bump, MutBumpVecRev};
1971    /// # let mut bump: Bump = Bump::new();
1972    /// # let bump2: Bump = Bump::new();
1973    /// let mut vec = MutBumpVecRev::new_in(&mut bump);
1974    ///
1975    /// // append by value
1976    /// vec.try_append([1, 2])?;
1977    /// vec.try_append(vec![3, 4])?;
1978    /// vec.try_append(bump2.alloc_iter(5..=6))?;
1979    ///
1980    /// // append by mutable reference
1981    /// let mut other = vec![7, 8];
1982    /// vec.try_append(&mut other)?;
1983    ///
1984    /// assert_eq!(other, []);
1985    /// assert_eq!(vec, [7, 8, 5, 6, 3, 4, 1, 2]);
1986    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1987    /// ```
1988    #[inline(always)]
1989    pub fn try_append(&mut self, other: impl OwnedSlice<Item = T>) -> Result<(), AllocError> {
1990        self.generic_append(other)
1991    }
1992
1993    #[inline]
1994    pub(crate) fn generic_append<E: ErrorBehavior>(&mut self, other: impl OwnedSlice<Item = T>) -> Result<(), E> {
1995        unsafe {
1996            let mut owned_slice = other.into_take_owned_slice();
1997
1998            let slice = NonNull::from(owned_slice.owned_slice_ref());
1999            self.generic_reserve(slice.len())?;
2000
2001            let src = slice.cast::<T>().as_ptr();
2002            let dst = self.end.as_ptr().sub(self.len + slice.len());
2003            ptr::copy_nonoverlapping(src, dst, slice.len());
2004
2005            owned_slice.take_owned_slice();
2006            self.inc_len(slice.len());
2007            Ok(())
2008        }
2009    }
2010
2011    /// Extend the vector by `n` clones of value.
2012    fn extend_with<B: ErrorBehavior>(&mut self, n: usize, value: T) -> Result<(), B>
2013    where
2014        T: Clone,
2015    {
2016        self.generic_reserve(n)?;
2017
2018        unsafe {
2019            let mut ptr = self.as_mut_ptr().sub(1);
2020
2021            // Use SetLenOnDrop to work around bug where compiler
2022            // might not realize the store through `ptr` through self.set_len()
2023            // don't alias.
2024            let mut local_len = SetLenOnDrop::new(&mut self.len);
2025
2026            // Write all elements except the last one
2027            for _ in 1..n {
2028                pointer::write_with(ptr, || value.clone());
2029                ptr = ptr.sub(1);
2030
2031                // Increment the length in every step in case clone() panics
2032                local_len.increment_len(1);
2033            }
2034
2035            if n > 0 {
2036                // We can write the last element directly without cloning needlessly
2037                ptr.write(value);
2038                local_len.increment_len(1);
2039            }
2040
2041            Ok(())
2042            // len set by scope guard
2043        }
2044    }
2045
2046    #[inline(always)]
2047    unsafe fn extend_by_copy_nonoverlapping<E: ErrorBehavior>(&mut self, other: *const [T]) -> Result<(), E> {
2048        unsafe {
2049            let len = other.len();
2050            self.generic_reserve(len)?;
2051
2052            let src = other.cast::<T>();
2053            self.len += len;
2054            let dst = self.as_mut_ptr();
2055
2056            ptr::copy_nonoverlapping(src, dst, len);
2057
2058            Ok(())
2059        }
2060    }
2061
2062    #[inline]
2063    fn generic_reserve_one<E: ErrorBehavior>(&mut self) -> Result<(), E> {
2064        if self.cap == self.len {
2065            self.generic_grow_amortized::<E>(1)?;
2066        }
2067
2068        Ok(())
2069    }
2070
2071    #[cold]
2072    #[inline(never)]
2073    fn generic_grow_amortized<E: ErrorBehavior>(&mut self, additional: usize) -> Result<(), E> {
2074        if T::IS_ZST {
2075            // This function is only called after we checked that the current capacity is not
2076            // sufficient. When `T::IS_ZST` the capacity is `usize::MAX`, so it can't grow.
2077            return Err(E::capacity_overflow());
2078        }
2079
2080        let Some(required_cap) = self.len().checked_add(additional) else {
2081            return Err(E::capacity_overflow())?;
2082        };
2083
2084        // This guarantees exponential growth. The doubling cannot overflow
2085        // because `capacity <= isize::MAX` and the type of `capacity` is usize;
2086        let new_cap = (self.capacity() * 2).max(required_cap).max(min_non_zero_cap(T::SIZE));
2087
2088        unsafe { self.generic_grow_to(new_cap) }
2089    }
2090
2091    #[cold]
2092    #[inline(never)]
2093    fn generic_grow_exact<E: ErrorBehavior>(&mut self, additional: usize) -> Result<(), E> {
2094        if T::IS_ZST {
2095            // This function is only called after we checked that the current capacity is not
2096            // sufficient. When `T::IS_ZST` the capacity is `usize::MAX`, so it can't grow.
2097            return Err(E::capacity_overflow());
2098        }
2099
2100        let Some(required_cap) = self.len().checked_add(additional) else {
2101            return Err(E::capacity_overflow());
2102        };
2103
2104        unsafe { self.generic_grow_to(required_cap) }
2105    }
2106
2107    /// # Safety
2108    ///
2109    /// `new_capacity` must be greater than the current capacity.
2110    unsafe fn generic_grow_to<E: ErrorBehavior>(&mut self, new_capacity: usize) -> Result<(), E> {
2111        unsafe {
2112            let (end, cap) = E::prepare_slice_allocation_rev::<T>(&mut self.allocator, new_capacity)?;
2113
2114            let src = self.as_mut_ptr();
2115            let dst = end.as_ptr().sub(self.len);
2116            ptr::copy_nonoverlapping(src, dst, self.len);
2117
2118            self.end = end;
2119            self.cap = cap;
2120
2121            Ok(())
2122        }
2123    }
2124
2125    /// Removes and returns the element at position `index` within the vector,
2126    /// shifting all elements after it to the right.
2127    ///
2128    /// Note: Because this shifts over the remaining elements, it has a
2129    /// worst-case performance of *O*(*n*). If you don't need the order of elements
2130    /// to be preserved, use [`swap_remove`] instead.
2131    ///
2132    /// # Panics
2133    /// Panics if `index` is out of bounds.
2134    ///
2135    /// [`swap_remove`]: Self::swap_remove
2136    ///
2137    /// # Examples
2138    ///
2139    /// ```
2140    /// # use bump_scope::{Bump, mut_bump_vec_rev};
2141    /// # let mut bump: Bump = Bump::new();
2142    /// let mut v = mut_bump_vec_rev![in &mut bump; 1, 2, 3];
2143    /// assert_eq!(v.remove(1), 2);
2144    /// assert_eq!(v, [1, 3]);
2145    /// ```
2146    #[track_caller]
2147    pub fn remove(&mut self, index: usize) -> T {
2148        #[cold]
2149        #[track_caller]
2150        fn assert_failed(index: usize, len: usize) -> ! {
2151            panic!("removal index (is {index}) should be < len (is {len})");
2152        }
2153
2154        if index >= self.len {
2155            assert_failed(index, self.len);
2156        }
2157
2158        unsafe {
2159            let start = self.as_mut_ptr();
2160            let value_ptr = start.add(index);
2161
2162            // copy it out, unsafely having a copy of the value on
2163            // the stack and in the vector at the same time
2164            let value = value_ptr.read();
2165
2166            // shift everything to fill in that spot
2167            if index != 0 {
2168                start.copy_to(start.add(1), index);
2169            }
2170
2171            self.len -= 1;
2172            value
2173        }
2174    }
2175
2176    /// Removes an element from the vector and returns it.
2177    ///
2178    /// The removed element is replaced by the first element of the vector.
2179    ///
2180    /// This does not preserve ordering, but is *O*(1).
2181    /// If you need to preserve the element order, use [`remove`] instead.
2182    ///
2183    /// # Panics
2184    /// Panics if `index` is out of bounds.
2185    ///
2186    /// [`remove`]: Self::remove
2187    ///
2188    /// # Examples
2189    ///
2190    /// ```
2191    /// # use bump_scope::{Bump, mut_bump_vec_rev};
2192    /// # let mut bump: Bump = Bump::new();
2193    /// #
2194    /// let mut v = mut_bump_vec_rev![in &mut bump; "foo", "bar", "baz", "qux"];
2195    ///
2196    /// assert_eq!(v.swap_remove(1), "bar");
2197    /// assert_eq!(v, ["foo", "baz", "qux"]);
2198    ///
2199    /// assert_eq!(v.swap_remove(0), "foo");
2200    /// assert_eq!(v, ["baz", "qux"]);
2201    /// ```
2202    #[inline]
2203    pub fn swap_remove(&mut self, index: usize) -> T {
2204        #[cold]
2205        #[inline(never)]
2206        #[track_caller]
2207        fn assert_failed(index: usize, len: usize) -> ! {
2208            panic!("swap_remove index (is {index}) should be < len (is {len})");
2209        }
2210
2211        if index >= self.len {
2212            assert_failed(index, self.len);
2213        }
2214
2215        unsafe {
2216            // We replace self[index] with the first element. Note that if the
2217            // bounds check above succeeds there must be a first element (which
2218            // can be self[index] itself).
2219
2220            let start = self.as_mut_ptr();
2221            let value_ptr = start.add(index);
2222            let value = value_ptr.read();
2223            self.len -= 1;
2224
2225            start.copy_to(value_ptr, 1);
2226            value
2227        }
2228    }
2229
2230    #[must_use]
2231    #[inline]
2232    fn into_slice_ptr(self) -> NonNull<[T]> {
2233        let this = ManuallyDrop::new(self);
2234
2235        if T::IS_ZST {
2236            return NonNull::slice_from_raw_parts(NonNull::dangling(), this.len());
2237        }
2238
2239        if this.cap == 0 {
2240            // We didn't touch the bump, so no need to do anything.
2241            debug_assert_eq!(this.end, NonNull::<T>::dangling());
2242            return NonNull::slice_from_raw_parts(NonNull::<T>::dangling(), 0);
2243        }
2244
2245        let end = this.end;
2246        let len = this.len;
2247        let cap = this.cap;
2248        unsafe { this.allocator.allocate_prepared_slice_rev(end, len, cap) }
2249    }
2250
2251    /// # Safety
2252    ///
2253    /// `iterator` must satisfy the invariants of nightly's `TrustedLen`.
2254    // specific extend for `TrustedLen` iterators, called both by the specializations
2255    // and internal places where resolving specialization makes compilation slower
2256    unsafe fn extend_trusted<B: ErrorBehavior>(&mut self, iterator: impl Iterator<Item = T>) -> Result<(), B> {
2257        unsafe {
2258            let (low, high) = iterator.size_hint();
2259            if let Some(additional) = high {
2260                debug_assert_eq!(
2261                    low,
2262                    additional,
2263                    "TrustedLen iterator's size hint is not exact: {:?}",
2264                    (low, high)
2265                );
2266
2267                self.generic_reserve(additional)?;
2268
2269                let ptr = self.end.as_ptr();
2270                let mut local_len = SetLenOnDrop::new(&mut self.len);
2271
2272                iterator.for_each(move |element| {
2273                    let dst = ptr.sub(local_len.current_len() + 1);
2274
2275                    ptr::write(dst, element);
2276                    // Since the loop executes user code which can panic we have to update
2277                    // the length every step to correctly drop what we've written.
2278                    // NB can't overflow since we would have had to alloc the address space
2279                    local_len.increment_len(1);
2280                });
2281
2282                Ok(())
2283            } else {
2284                // Per TrustedLen contract a `None` upper bound means that the iterator length
2285                // truly exceeds usize::MAX, which would eventually lead to a capacity overflow anyway.
2286                // Since the other branch already panics eagerly (via `reserve()`) we do the same here.
2287                // This avoids additional codegen for a fallback code path which would eventually
2288                // panic anyway.
2289                Err(B::capacity_overflow())
2290            }
2291        }
2292    }
2293
2294    /// Returns the remaining spare capacity of the vector as a slice of
2295    /// `MaybeUninit<T>`.
2296    ///
2297    /// The returned slice can be used to fill the vector with data (e.g. by
2298    /// reading from a file) before marking the data as initialized using the
2299    /// [`set_len`] method.
2300    ///
2301    /// [`set_len`]: Self::set_len
2302    ///
2303    /// # Examples
2304    ///
2305    /// ```
2306    /// # use bump_scope::{Bump, MutBumpVecRev};
2307    /// # let mut bump: Bump = Bump::new();
2308    /// // Allocate vector big enough for 10 elements.
2309    /// let mut v = MutBumpVecRev::with_capacity_in(10, &mut bump);
2310    ///
2311    /// // Fill in the first 3 elements.
2312    /// let uninit = v.spare_capacity_mut();
2313    /// let len = uninit.len();
2314    /// uninit[len - 3].write(0);
2315    /// uninit[len - 2].write(1);
2316    /// uninit[len - 1].write(2);
2317    ///
2318    /// // Mark the first 3 elements of the vector as being initialized.
2319    /// unsafe {
2320    ///     v.set_len(3);
2321    /// }
2322    ///
2323    /// assert_eq!(&v, &[0, 1, 2]);
2324    /// ```
2325    #[inline]
2326    pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
2327        // Note:
2328        // This method is not implemented in terms of `split_at_spare_mut`,
2329        // to prevent invalidation of pointers to the buffer.
2330        unsafe {
2331            slice::from_raw_parts_mut(
2332                self.end.as_ptr().sub(self.capacity()).cast::<MaybeUninit<T>>(),
2333                self.capacity() - self.len(),
2334            )
2335        }
2336    }
2337
2338    /// Returns vector content as a slice of `T`, along with the remaining spare
2339    /// capacity of the vector as a slice of `MaybeUninit<T>`.
2340    ///
2341    /// The returned spare capacity slice can be used to fill the vector with data
2342    /// (e.g. by reading from a file) before marking the data as initialized using
2343    /// the [`set_len`] method.
2344    ///
2345    /// [`set_len`]: Self::set_len
2346    ///
2347    /// Note that this is a low-level API, which should be used with care for
2348    /// optimization purposes. If you need to append data to a `MutBumpVecRev`
2349    /// you can use [`push`], [`extend`], `extend_from_slice`[`_copy`](MutBumpVecRev::extend_from_slice_copy)`/`[`_clone`](MutBumpVecRev::extend_from_within_clone),
2350    /// `extend_from_within`[`_copy`](MutBumpVecRev::extend_from_within_copy)`/`[`_clone`](MutBumpVecRev::extend_from_within_clone), [`insert`], [`resize`] or
2351    /// [`resize_with`], depending on your exact needs.
2352    ///
2353    /// [`push`]: Self::push
2354    /// [`extend`]: Self::extend
2355    /// [`insert`]: Self::insert
2356    /// [`append`]: Self::append
2357    /// [`resize`]: Self::resize
2358    /// [`resize_with`]: Self::resize_with
2359    #[inline]
2360    pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
2361        // SAFETY:
2362        // - len is ignored and so never changed
2363        let (init, spare, _) = unsafe { self.split_at_spare_mut_with_len() };
2364        (init, spare)
2365    }
2366
2367    /// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`.
2368    ///
2369    /// This method provides unique access to all vec parts at once in `extend_from_within_clone`.
2370    unsafe fn split_at_spare_mut_with_len(&mut self) -> (&mut [T], &mut [MaybeUninit<T>], &mut usize) {
2371        unsafe {
2372            let end = self.end.as_ptr();
2373
2374            let spare_ptr = end.sub(self.cap);
2375            let spare_ptr = spare_ptr.cast::<MaybeUninit<T>>();
2376            let spare_len = self.cap - self.len;
2377
2378            let initialized = slice::from_raw_parts_mut(self.as_mut_ptr(), self.len);
2379            let spare = slice::from_raw_parts_mut(spare_ptr, spare_len);
2380
2381            (initialized, spare, &mut self.len)
2382        }
2383    }
2384
2385    /// Returns a type which provides statistics about the memory usage of the bump allocator.
2386    ///
2387    /// This collection does not update the bump pointer, so it also doesn't contribute to the `remaining` and `allocated` stats.
2388    #[must_use]
2389    #[inline(always)]
2390    pub fn allocator_stats(&self) -> A::TypedStats<'_> {
2391        self.allocator.typed_stats()
2392    }
2393}
2394
2395impl<'a, T, A: MutBumpAllocatorTypedScope<'a>> MutBumpVecRev<T, A> {
2396    /// Turns this `MutBumpVecRev<T>` into a `BumpBox<[T]>`.
2397    ///
2398    /// Unused capacity does not take up space.<br/>
2399    /// When [bumping upwards](crate#bumping-upwards-or-downwards) this needs to shift all elements to the other end of the chunk.
2400    #[must_use]
2401    #[inline(always)]
2402    pub fn into_boxed_slice(self) -> BumpBox<'a, [T]> {
2403        unsafe { BumpBox::from_raw(self.into_slice_ptr()) }
2404    }
2405
2406    /// Turns this `MutBumpVecRev<T>` into a `&[T]` that is live for this bump scope.
2407    ///
2408    /// Unused capacity does not take up space.<br/>
2409    /// When [bumping upwards](crate#bumping-upwards-or-downwards) this needs to shift all elements to the other end of the chunk.
2410    ///
2411    /// This is only available for [`NoDrop`] types so you don't omit dropping a value for which it matters.
2412    ///
2413    /// `!NoDrop` types can still be turned into slices via <code>BumpBox::[leak](BumpBox::leak)(vec.[into_boxed_slice](Self::into_boxed_slice)())</code>.
2414    #[must_use]
2415    #[inline(always)]
2416    pub fn into_slice(self) -> &'a mut [T]
2417    where
2418        [T]: NoDrop,
2419    {
2420        self.into_boxed_slice().into_mut()
2421    }
2422}
2423
2424impl<T, A, const N: usize> MutBumpVecRev<[T; N], A> {
2425    /// Takes a `MutBumpVecRev<[T; N]>` and flattens it into a `MutBumpVecRev<T>`.
2426    ///
2427    /// # Panics
2428    ///
2429    /// Panics if the length of the resulting vector would overflow a `usize`.
2430    ///
2431    /// This is only possible when flattening a vector of arrays of zero-sized
2432    /// types, and thus tends to be irrelevant in practice. If
2433    /// `size_of::<T>() > 0`, this will never panic.
2434    ///
2435    /// # Examples
2436    ///
2437    /// ```
2438    /// # use bump_scope::{Bump, mut_bump_vec_rev};
2439    /// # let mut bump: Bump = Bump::new();
2440    /// #
2441    /// let mut vec = mut_bump_vec_rev![in &mut bump; [1, 2, 3], [4, 5, 6], [7, 8, 9]];
2442    /// assert_eq!(vec.pop(), Some([1, 2, 3]));
2443    ///
2444    /// let mut flattened = vec.into_flattened();
2445    /// assert_eq!(flattened.pop(), Some(4));
2446    /// ```
2447    #[must_use]
2448    pub fn into_flattened(self) -> MutBumpVecRev<T, A> {
2449        let (end, len, cap, allocator) = self.into_raw_parts();
2450
2451        let (new_len, new_cap) = if T::IS_ZST {
2452            (len.checked_mul(N).expect("vec len overflow"), usize::MAX)
2453        } else {
2454            // SAFETY:
2455            // - `cap * N` cannot overflow because the allocation is already in
2456            // the address space.
2457            // - Each `[T; N]` has `N` valid elements, so there are `len * N`
2458            // valid elements in the allocation.
2459            unsafe { (len.unchecked_mul(N), cap.unchecked_mul(N)) }
2460        };
2461
2462        unsafe { MutBumpVecRev::from_raw_parts(end.cast(), new_len, new_cap, allocator) }
2463    }
2464}
2465
2466impl<T: Debug, A> Debug for MutBumpVecRev<T, A> {
2467    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2468        Debug::fmt(self.as_slice(), f)
2469    }
2470}
2471
2472impl<T, A> Deref for MutBumpVecRev<T, A> {
2473    type Target = [T];
2474
2475    #[inline(always)]
2476    fn deref(&self) -> &Self::Target {
2477        self.as_slice()
2478    }
2479}
2480
2481impl<T, A> DerefMut for MutBumpVecRev<T, A> {
2482    #[inline(always)]
2483    fn deref_mut(&mut self) -> &mut Self::Target {
2484        self.as_mut_slice()
2485    }
2486}
2487
2488impl<T, A: Default> Default for MutBumpVecRev<T, A> {
2489    fn default() -> Self {
2490        Self::new_in(A::default())
2491    }
2492}
2493
2494impl<T, A, I: SliceIndex<[T]>> Index<I> for MutBumpVecRev<T, A> {
2495    type Output = I::Output;
2496
2497    #[inline(always)]
2498    fn index(&self, index: I) -> &Self::Output {
2499        Index::index(self.as_slice(), index)
2500    }
2501}
2502
2503impl<T, A, I: SliceIndex<[T]>> IndexMut<I> for MutBumpVecRev<T, A> {
2504    #[inline(always)]
2505    fn index_mut(&mut self, index: I) -> &mut Self::Output {
2506        IndexMut::index_mut(self.as_mut_slice(), index)
2507    }
2508}
2509
2510#[cfg(feature = "panic-on-alloc")]
2511impl<U, A: MutBumpAllocatorTyped> Extend<U> for MutBumpVecRev<U, A> {
2512    #[inline]
2513    fn extend<T: IntoIterator<Item = U>>(&mut self, iter: T) {
2514        let iter = iter.into_iter();
2515
2516        self.reserve(iter.size_hint().0);
2517
2518        for value in iter {
2519            self.push(value);
2520        }
2521    }
2522}
2523
2524impl<T, A> MutBumpVecRev<T, A> {
2525    /// # Safety
2526    ///
2527    /// Must only be called from the drop implementation and a call to this function
2528    /// must be the only thing in that drop implementation.
2529    #[inline]
2530    unsafe fn drop_inner(&mut self) {
2531        // MutBumpVecRev never actually moves a bump pointer.
2532        // It may force allocation of a new chunk, but it does not move the pointer within.
2533        // So we don't need to move the bump pointer when dropping.
2534
2535        // If we want to reset the bump pointer to a previous chunk, we use a bump scope.
2536        // We could do it here, by resetting to the last non-empty chunk but that would require a loop.
2537        // Chunk allocations are supposed to be very rare, so this wouldn't be worth it.
2538
2539        unsafe {
2540            let to_drop = NonNull::slice_from_raw_parts(self.as_non_null(), self.len);
2541            to_drop.drop_in_place();
2542        }
2543    }
2544}
2545
2546#[cfg(feature = "nightly-dropck-eyepatch")]
2547unsafe impl<#[may_dangle] T, A> Drop for MutBumpVecRev<T, A> {
2548    #[inline(always)]
2549    fn drop(&mut self) {
2550        unsafe { self.drop_inner() }
2551    }
2552}
2553
2554#[cfg(not(feature = "nightly-dropck-eyepatch"))]
2555impl<T, A> Drop for MutBumpVecRev<T, A> {
2556    #[inline(always)]
2557    fn drop(&mut self) {
2558        unsafe { self.drop_inner() }
2559    }
2560}
2561
2562#[cfg(feature = "panic-on-alloc")]
2563impl<'t, T: Clone + 't, A: MutBumpAllocatorTyped> Extend<&'t T> for MutBumpVecRev<T, A> {
2564    #[inline]
2565    fn extend<I: IntoIterator<Item = &'t T>>(&mut self, iter: I) {
2566        let iter = iter.into_iter();
2567
2568        self.reserve(iter.size_hint().0);
2569
2570        for value in iter {
2571            self.push(value.clone());
2572        }
2573    }
2574}
2575
2576impl<T, A> IntoIterator for MutBumpVecRev<T, A> {
2577    type Item = T;
2578    type IntoIter = IntoIter<T, A>;
2579
2580    /// If you need to use the allocator while iterating you can first turn it to a slice with [`into_slice`] or [`into_boxed_slice`].
2581    ///
2582    /// [`into_slice`]: Self::into_slice
2583    /// [`into_boxed_slice`]: Self::into_boxed_slice
2584    #[inline(always)]
2585    fn into_iter(self) -> Self::IntoIter {
2586        let (end, len, _cap, allocator) = self.into_raw_parts();
2587        let start = unsafe { end.sub(len) };
2588        let slice = NonNull::slice_from_raw_parts(start, len);
2589        unsafe { IntoIter::new(slice, allocator) }
2590    }
2591}
2592
2593impl<'c, T, A> IntoIterator for &'c MutBumpVecRev<T, A> {
2594    type Item = &'c T;
2595    type IntoIter = slice::Iter<'c, T>;
2596
2597    #[inline(always)]
2598    fn into_iter(self) -> Self::IntoIter {
2599        self.as_slice().iter()
2600    }
2601}
2602
2603impl<'c, T, A> IntoIterator for &'c mut MutBumpVecRev<T, A> {
2604    type Item = &'c mut T;
2605    type IntoIter = slice::IterMut<'c, T>;
2606
2607    #[inline(always)]
2608    fn into_iter(self) -> Self::IntoIter {
2609        self.as_mut_slice().iter_mut()
2610    }
2611}
2612
2613impl<T, A> AsRef<Self> for MutBumpVecRev<T, A> {
2614    #[inline(always)]
2615    fn as_ref(&self) -> &Self {
2616        self
2617    }
2618}
2619
2620impl<T, A> AsMut<Self> for MutBumpVecRev<T, A> {
2621    #[inline(always)]
2622    fn as_mut(&mut self) -> &mut Self {
2623        self
2624    }
2625}
2626
2627impl<T, A> AsRef<[T]> for MutBumpVecRev<T, A> {
2628    #[inline(always)]
2629    fn as_ref(&self) -> &[T] {
2630        self
2631    }
2632}
2633
2634impl<T, A> AsMut<[T]> for MutBumpVecRev<T, A> {
2635    #[inline(always)]
2636    fn as_mut(&mut self) -> &mut [T] {
2637        self
2638    }
2639}
2640
2641impl<T, A> Borrow<[T]> for MutBumpVecRev<T, A> {
2642    #[inline(always)]
2643    fn borrow(&self) -> &[T] {
2644        self
2645    }
2646}
2647
2648impl<T, A> BorrowMut<[T]> for MutBumpVecRev<T, A> {
2649    #[inline(always)]
2650    fn borrow_mut(&mut self) -> &mut [T] {
2651        self
2652    }
2653}
2654
2655impl<T: Hash, A> Hash for MutBumpVecRev<T, A> {
2656    #[inline(always)]
2657    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
2658        self.as_slice().hash(state);
2659    }
2660}
2661
2662#[cfg(feature = "panic-on-alloc")]
2663impl<T, A: MutBumpAllocatorTyped + Default> FromIterator<T> for MutBumpVecRev<T, A> {
2664    #[inline]
2665    #[track_caller]
2666    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
2667        Self::from_iter_in(iter, A::default())
2668    }
2669}