Skip to main content

bump_scope/
mut_bump_vec.rs

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