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/// 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    ///
541    /// # Examples
542    /// ```
543    /// # use bump_scope::{Bump, MutBumpVec};
544    /// # let mut bump: Bump = Bump::new();
545    /// let mut vec = MutBumpVec::with_capacity_in(3, &mut bump);
546    /// vec.append([1, 2]);
547    /// unsafe { vec.push_unchecked(3) };
548    /// assert_eq!(vec, [1, 2, 3]);
549    /// ```
550    #[inline(always)]
551    pub unsafe fn push_unchecked(&mut self, value: T) {
552        _ = unsafe { self.push_mut_unchecked(value) };
553    }
554
555    /// Appends an element to the back of the collection, returning a reference to it.
556    ///
557    /// # Safety
558    /// Vector must not be full.
559    ///
560    /// # Examples
561    /// ```
562    /// # use bump_scope::{Bump, MutBumpVec};
563    /// # let mut bump: Bump = Bump::new();
564    /// let mut vec = MutBumpVec::with_capacity_in(4, &mut bump);
565    /// vec.append([1, 2]);
566    ///
567    /// let last = unsafe { vec.push_mut_unchecked(3) };
568    /// assert_eq!(*last, 3);
569    /// assert_eq!(vec, [1, 2, 3]);
570    ///
571    /// let last = unsafe { vec.push_mut_unchecked(3) };
572    /// *last += 1;
573    /// assert_eq!(vec, [1, 2, 3, 4]);
574    /// ```
575    #[inline(always)]
576    #[must_use = "if you don't need a reference to the value, use `push_unchecked` instead"]
577    pub unsafe fn push_mut_unchecked(&mut self, value: T) -> &mut T {
578        unsafe { self.fixed.cook_mut().push_mut_unchecked(value) }
579    }
580
581    /// Appends an element to the back of the collection.
582    ///
583    /// # Safety
584    /// Vector must not be full.
585    #[inline(always)]
586    #[deprecated = "use `push_unchecked(f())` instead"]
587    pub unsafe fn push_with_unchecked(&mut self, f: impl FnOnce() -> T) {
588        unsafe { self.push_unchecked(f()) }
589    }
590
591    /// Forces the length of the vector to `new_len`.
592    ///
593    /// This is a low-level operation that maintains none of the normal
594    /// invariants of the type. Normally changing the length of a vector
595    /// is done using one of the safe operations instead, such as
596    /// [`resize`], [`truncate`], [`extend`], or [`clear`].
597    ///
598    /// # Safety
599    /// - `new_len` must be less than or equal to the [`capacity`].
600    /// - The elements at `old_len..new_len` must be initialized.
601    ///
602    /// [`resize`]: Self::resize
603    /// [`truncate`]: Self::truncate
604    /// [`extend`]: Self::extend
605    /// [`clear`]: Self::clear
606    /// [`capacity`]: Self::capacity
607    #[inline]
608    pub unsafe fn set_len(&mut self, new_len: usize) {
609        unsafe { self.fixed.set_len(new_len) };
610    }
611
612    #[inline]
613    pub(crate) unsafe fn inc_len(&mut self, amount: usize) {
614        unsafe { self.fixed.cook_mut().inc_len(amount) };
615    }
616}
617
618impl<T, A: MutBumpAllocatorTyped> MutBumpVec<T, A> {
619    /// Constructs a new empty vector with at least the specified capacity
620    /// in the provided bump allocator.
621    ///
622    /// The vector will be able to hold `capacity` elements without
623    /// reallocating. If `capacity` is 0, the vector will not allocate.
624    ///
625    /// It is important to note that although the returned vector has the
626    /// minimum *capacity* specified, the vector will have a zero *length*. For
627    /// an explanation of the difference between length and capacity, see
628    /// *[Capacity and reallocation]*.
629    ///
630    /// When `T` is a zero-sized type, there will be no allocation
631    /// and the capacity will always be `usize::MAX`.
632    ///
633    /// [Capacity and reallocation]: alloc_crate::vec::Vec#capacity-and-reallocation
634    ///
635    /// # Panics
636    /// Panics if the allocation fails.
637    ///
638    /// # Examples
639    /// ```
640    /// # use bump_scope::{Bump, MutBumpVec};
641    /// # let mut bump: Bump = Bump::new();
642    /// let mut vec = MutBumpVec::<i32, _>::with_capacity_in(10, &mut bump);
643    ///
644    /// // The vector contains no items, even though it has capacity for more
645    /// assert_eq!(vec.len(), 0);
646    /// assert!(vec.capacity() >= 10);
647    ///
648    /// // These are all done without reallocating...
649    /// for i in 0..10 {
650    ///     vec.push(i);
651    /// }
652    /// assert_eq!(vec.len(), 10);
653    /// assert!(vec.capacity() >= 10);
654    ///
655    /// // ...but this may make the vector reallocate
656    /// vec.push(11);
657    /// assert_eq!(vec.len(), 11);
658    /// assert!(vec.capacity() >= 11);
659    ///
660    /// // A vector of a zero-sized type will always over-allocate, since no
661    /// // allocation is necessary
662    /// let vec_units = MutBumpVec::<(), _>::with_capacity_in(10, &mut bump);
663    /// assert_eq!(vec_units.capacity(), usize::MAX);
664    /// ```
665    #[must_use]
666    #[inline(always)]
667    #[cfg(feature = "panic-on-alloc")]
668    pub fn with_capacity_in(capacity: usize, allocator: A) -> Self {
669        panic_on_error(Self::generic_with_capacity_in(capacity, allocator))
670    }
671
672    /// Constructs a new empty vector with at least the specified capacity
673    /// in the provided bump allocator.
674    ///
675    /// The vector will be able to hold `capacity` elements without
676    /// reallocating. If `capacity` is 0, the vector will not allocate.
677    ///
678    /// It is important to note that although the returned vector has the
679    /// minimum *capacity* specified, the vector will have a zero *length*. For
680    /// an explanation of the difference between length and capacity, see
681    /// *[Capacity and reallocation]*.
682    ///
683    /// When `T` is a zero-sized type, there will be no allocation
684    /// and the capacity will always be `usize::MAX`.
685    ///
686    /// [Capacity and reallocation]: alloc_crate::vec::Vec#capacity-and-reallocation
687    ///
688    /// # Errors
689    /// Errors if the allocation fails.
690    ///
691    /// # Examples
692    /// ```
693    /// # use bump_scope::{Bump, MutBumpVec};
694    /// # let mut bump: Bump = Bump::new();
695    /// let mut vec = MutBumpVec::<i32, _>::try_with_capacity_in(10, &mut bump)?;
696    ///
697    /// // The vector contains no items, even though it has capacity for more
698    /// assert_eq!(vec.len(), 0);
699    /// assert!(vec.capacity() >= 10);
700    ///
701    /// // These are all done without reallocating...
702    /// for i in 0..10 {
703    ///     vec.push(i);
704    /// }
705    /// assert_eq!(vec.len(), 10);
706    /// assert!(vec.capacity() >= 10);
707    ///
708    /// // ...but this may make the vector reallocate
709    /// vec.push(11);
710    /// assert_eq!(vec.len(), 11);
711    /// assert!(vec.capacity() >= 11);
712    ///
713    /// // A vector of a zero-sized type will always over-allocate, since no
714    /// // allocation is necessary
715    /// let vec_units = MutBumpVec::<(), _>::try_with_capacity_in(10, &mut bump)?;
716    /// assert_eq!(vec_units.capacity(), usize::MAX);
717    /// # Ok::<(), bump_scope::alloc::AllocError>(())
718    /// ```
719    #[inline(always)]
720    pub fn try_with_capacity_in(capacity: usize, allocator: A) -> Result<Self, AllocError> {
721        Self::generic_with_capacity_in(capacity, allocator)
722    }
723
724    #[inline]
725    pub(crate) fn generic_with_capacity_in<E: ErrorBehavior>(capacity: usize, allocator: A) -> Result<Self, E> {
726        let mut allocator = allocator;
727
728        if T::IS_ZST || capacity == 0 {
729            return Ok(Self {
730                fixed: RawFixedBumpVec::EMPTY,
731                allocator,
732            });
733        }
734
735        Ok(Self {
736            fixed: unsafe { RawFixedBumpVec::prepare_allocation(&mut allocator, capacity)? },
737            allocator,
738        })
739    }
740
741    /// Constructs a new `MutBumpVec<T>` and pushes `value` `count` times.
742    ///
743    /// # Panics
744    /// Panics if the allocation fails.
745    ///
746    /// # Examples
747    /// ```
748    /// # use bump_scope::{Bump, MutBumpVec};
749    /// # let mut bump: Bump = Bump::new();
750    /// let vec = MutBumpVec::from_elem_in("ho", 3, &mut bump);
751    /// assert_eq!(vec, ["ho", "ho", "ho"]);
752    /// ```
753    #[must_use]
754    #[inline(always)]
755    #[cfg(feature = "panic-on-alloc")]
756    pub fn from_elem_in(value: T, count: usize, allocator: A) -> Self
757    where
758        T: Clone,
759    {
760        panic_on_error(Self::generic_from_elem_in(value, count, allocator))
761    }
762
763    /// Constructs a new `MutBumpVec<T>` and pushes `value` `count` times.
764    ///
765    /// # Errors
766    /// Errors if the allocation fails.
767    ///
768    /// # Examples
769    /// ```
770    /// # use bump_scope::{Bump, MutBumpVec};
771    /// # let mut bump: Bump = Bump::new();
772    /// let vec = MutBumpVec::try_from_elem_in("ho", 3, &mut bump)?;
773    /// assert_eq!(vec, ["ho", "ho", "ho"]);
774    /// # Ok::<(), bump_scope::alloc::AllocError>(())
775    /// ```
776    #[inline(always)]
777    pub fn try_from_elem_in(value: T, count: usize, allocator: A) -> Result<Self, AllocError>
778    where
779        T: Clone,
780    {
781        Self::generic_from_elem_in(value, count, allocator)
782    }
783
784    #[inline]
785    pub(crate) fn generic_from_elem_in<E: ErrorBehavior>(value: T, count: usize, allocator: A) -> Result<Self, E>
786    where
787        T: Clone,
788    {
789        let mut vec = Self::generic_with_capacity_in(count, allocator)?;
790
791        unsafe {
792            if count != 0 {
793                for _ in 0..(count - 1) {
794                    vec.push_unchecked(value.clone());
795                }
796
797                vec.push_unchecked(value);
798            }
799        }
800
801        Ok(vec)
802    }
803
804    /// Constructs a new `MutBumpVec<T>` from an [`OwnedSlice`].
805    ///
806    /// # Panics
807    /// Panics if the allocation fails.
808    ///
809    /// # Examples
810    /// ```
811    /// # use bump_scope::{Bump, MutBumpVec};
812    /// # let bump: Bump = Bump::new();
813    /// # let mut bump_a: Bump = Bump::new();
814    /// # let mut bump_b: Bump = Bump::new();
815    /// # let mut bump_c: Bump = Bump::new();
816    /// # let mut bump_d: Bump = Bump::new();
817    /// // by value
818    /// let a = MutBumpVec::from_owned_slice_in([1, 2], &mut bump_a);
819    /// let b = MutBumpVec::from_owned_slice_in(vec![3, 4], &mut bump_b);
820    /// let c = MutBumpVec::from_owned_slice_in(bump.alloc_iter(5..=6), &mut bump_c);
821    ///
822    /// // by mutable reference
823    /// let mut other = vec![7, 8];
824    /// let d = MutBumpVec::from_owned_slice_in(&mut other, &mut bump_d);
825    /// assert!(other.is_empty());
826    ///
827    /// assert_eq!(a, [1, 2]);
828    /// assert_eq!(b, [3, 4]);
829    /// assert_eq!(c, [5, 6]);
830    /// assert_eq!(d, [7, 8]);
831    /// ```
832    #[must_use]
833    #[inline(always)]
834    #[cfg(feature = "panic-on-alloc")]
835    pub fn from_owned_slice_in(owned_slice: impl OwnedSlice<Item = T>, allocator: A) -> Self {
836        panic_on_error(Self::generic_from_owned_slice_in(owned_slice, allocator))
837    }
838
839    /// Constructs a new `MutBumpVec<T>` from an [`OwnedSlice`].
840    ///
841    /// # Errors
842    /// Errors if the allocation fails.
843    ///
844    /// # Examples
845    /// ```
846    /// # use bump_scope::{Bump, MutBumpVec};
847    /// # let bump: Bump = Bump::new();
848    /// # let mut bump_a: Bump = Bump::new();
849    /// # let mut bump_b: Bump = Bump::new();
850    /// # let mut bump_c: Bump = Bump::new();
851    /// # let mut bump_d: Bump = Bump::new();
852    /// // by value
853    /// let a = MutBumpVec::try_from_owned_slice_in([1, 2], &mut bump_a)?;
854    /// let b = MutBumpVec::try_from_owned_slice_in(vec![3, 4], &mut bump_b)?;
855    /// let c = MutBumpVec::try_from_owned_slice_in(bump.alloc_iter(5..=6), &mut bump_c)?;
856    ///
857    /// // by mutable reference
858    /// let mut other = vec![7, 8];
859    /// let d = MutBumpVec::try_from_owned_slice_in(&mut other, &mut bump_d)?;
860    /// assert!(other.is_empty());
861    ///
862    /// assert_eq!(a, [1, 2]);
863    /// assert_eq!(b, [3, 4]);
864    /// assert_eq!(c, [5, 6]);
865    /// assert_eq!(d, [7, 8]);
866    /// # Ok::<(), bump_scope::alloc::AllocError>(())
867    /// ```
868    #[inline(always)]
869    pub fn try_from_owned_slice_in(owned_slice: impl OwnedSlice<Item = T>, allocator: A) -> Result<Self, AllocError> {
870        Self::generic_from_owned_slice_in(owned_slice, allocator)
871    }
872
873    #[inline]
874    pub(crate) fn generic_from_owned_slice_in<E: ErrorBehavior>(
875        owned_slice: impl OwnedSlice<Item = T>,
876        allocator: A,
877    ) -> Result<Self, E> {
878        let owned_slice = owned_slice.into_take_owned_slice();
879        let mut this = Self::generic_with_capacity_in(owned_slice.owned_slice_ref().len(), allocator)?;
880        this.generic_append(owned_slice)?;
881        Ok(this)
882    }
883
884    /// Create a new [`MutBumpVec`] whose elements are taken from an iterator and allocated in the given `bump`.
885    ///
886    /// This is behaviorally identical to [`FromIterator::from_iter`].
887    ///
888    /// If you have an `impl ExactSizeIterator` then you can use [`from_iter_exact_in`](Self::from_iter_exact_in) instead for better performance.
889    ///
890    /// # Panics
891    /// Panics if the allocation fails.
892    ///
893    /// # Examples
894    /// ```
895    /// # use bump_scope::{Bump, MutBumpVec};
896    /// # let mut bump: Bump = Bump::new();
897    /// let vec = MutBumpVec::from_iter_in([1, 2, 3], &mut bump);
898    /// assert_eq!(vec, [1, 2, 3]);
899    /// ```
900    #[must_use]
901    #[inline(always)]
902    #[cfg(feature = "panic-on-alloc")]
903    pub fn from_iter_in<I>(iter: I, allocator: A) -> Self
904    where
905        I: IntoIterator<Item = T>,
906    {
907        panic_on_error(Self::generic_from_iter_in(iter, allocator))
908    }
909
910    /// Create a new [`MutBumpVec`] whose elements are taken from an iterator and allocated in the given `bump`.
911    ///
912    /// This is behaviorally identical to [`FromIterator::from_iter`].
913    ///
914    /// 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.
915    ///
916    /// # Errors
917    /// Errors if the allocation fails.
918    ///
919    /// # Examples
920    /// ```
921    /// # use bump_scope::{Bump, MutBumpVec};
922    /// # let mut bump: Bump = Bump::new();
923    /// let vec = MutBumpVec::try_from_iter_in([1, 2, 3], &mut bump)?;
924    /// assert_eq!(vec, [1, 2, 3]);
925    /// # Ok::<(), bump_scope::alloc::AllocError>(())
926    /// ```
927    #[inline(always)]
928    pub fn try_from_iter_in<I>(iter: I, allocator: A) -> Result<Self, AllocError>
929    where
930        I: IntoIterator<Item = T>,
931    {
932        Self::generic_from_iter_in(iter, allocator)
933    }
934
935    #[inline]
936    pub(crate) fn generic_from_iter_in<E: ErrorBehavior, I>(iter: I, allocator: A) -> Result<Self, E>
937    where
938        I: IntoIterator<Item = T>,
939    {
940        let iter = iter.into_iter();
941        let capacity = iter.size_hint().0;
942
943        let mut vec = Self::generic_with_capacity_in(capacity, allocator)?;
944
945        for value in iter {
946            vec.generic_push(value)?;
947        }
948
949        Ok(vec)
950    }
951
952    /// Create a new [`MutBumpVec`] whose elements are taken from an iterator and allocated in the given `bump`.
953    ///
954    /// This is just like [`from_iter_in`](Self::from_iter_in) but optimized for an [`ExactSizeIterator`].
955    ///
956    /// # Panics
957    /// Panics if the allocation fails.
958    ///
959    /// # Examples
960    /// ```
961    /// # use bump_scope::{Bump, MutBumpVec};
962    /// # let mut bump: Bump = Bump::new();
963    /// let vec = MutBumpVec::from_iter_exact_in([1, 2, 3], &mut bump);
964    /// assert_eq!(vec, [1, 2, 3]);
965    /// ```
966    #[must_use]
967    #[inline(always)]
968    #[cfg(feature = "panic-on-alloc")]
969    pub fn from_iter_exact_in<I>(iter: I, allocator: A) -> Self
970    where
971        I: IntoIterator<Item = T>,
972        I::IntoIter: ExactSizeIterator,
973    {
974        panic_on_error(Self::generic_from_iter_exact_in(iter, allocator))
975    }
976
977    /// Create a new [`MutBumpVec`] whose elements are taken from an iterator and allocated in the given `bump`.
978    ///
979    /// This is just like [`from_iter_in`](Self::from_iter_in) but optimized for an [`ExactSizeIterator`].
980    ///
981    /// # Errors
982    /// Errors if the allocation fails.
983    ///
984    /// # Examples
985    /// ```
986    /// # use bump_scope::{Bump, MutBumpVec};
987    /// # let mut bump: Bump = Bump::new();
988    /// let vec = MutBumpVec::try_from_iter_exact_in([1, 2, 3], &mut bump)?;
989    /// assert_eq!(vec, [1, 2, 3]);
990    /// # Ok::<(), bump_scope::alloc::AllocError>(())
991    /// ```
992    #[inline(always)]
993    pub fn try_from_iter_exact_in<I>(iter: I, allocator: A) -> Result<Self, AllocError>
994    where
995        I: IntoIterator<Item = T>,
996        I::IntoIter: ExactSizeIterator,
997    {
998        Self::generic_from_iter_exact_in(iter, allocator)
999    }
1000
1001    #[inline]
1002    pub(crate) fn generic_from_iter_exact_in<E: ErrorBehavior, I>(iter: I, allocator: A) -> Result<Self, E>
1003    where
1004        I: IntoIterator<Item = T>,
1005        I::IntoIter: ExactSizeIterator,
1006    {
1007        let mut iter = iter.into_iter();
1008        let len = iter.len();
1009
1010        let mut vec = Self::generic_with_capacity_in(len, allocator)?;
1011
1012        while vec.len() != vec.capacity() {
1013            match iter.next() {
1014                // SAFETY: we checked above that `len != capacity`, so there is space
1015                Some(value) => unsafe { vec.push_unchecked(value) },
1016                None => break,
1017            }
1018        }
1019
1020        Ok(vec)
1021    }
1022
1023    /// Appends an element to the back of a collection.
1024    ///
1025    /// # Panics
1026    /// Panics if the allocation fails.
1027    ///
1028    /// # Examples
1029    /// ```
1030    /// # use bump_scope::{Bump, mut_bump_vec};
1031    /// # let mut bump: Bump = Bump::new();
1032    /// let mut vec = mut_bump_vec![in &mut bump; 1, 2];
1033    /// vec.push(3);
1034    /// assert_eq!(vec, [1, 2, 3]);
1035    /// ```
1036    #[inline(always)]
1037    #[cfg(feature = "panic-on-alloc")]
1038    pub fn push(&mut self, value: T) {
1039        panic_on_error(self.generic_push(value));
1040    }
1041
1042    /// Appends an element to the back of a collection.
1043    ///
1044    /// # Errors
1045    /// Errors if the allocation fails.
1046    ///
1047    /// # Examples
1048    /// ```
1049    /// # use bump_scope::{Bump, mut_bump_vec};
1050    /// # let mut bump: Bump = Bump::new();
1051    /// let mut vec = mut_bump_vec![try in &mut bump; 1, 2]?;
1052    /// vec.try_push(3)?;
1053    /// assert_eq!(vec, [1, 2, 3]);
1054    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1055    /// ```
1056    #[inline(always)]
1057    pub fn try_push(&mut self, value: T) -> Result<(), AllocError> {
1058        self.generic_push(value)
1059    }
1060
1061    #[inline]
1062    pub(crate) fn generic_push<E: ErrorBehavior>(&mut self, value: T) -> Result<(), E> {
1063        self.generic_push_with(|| value)
1064    }
1065
1066    /// Reserves space for one more element, then calls `f`
1067    /// to produce the value that is appended.
1068    ///
1069    /// In some cases this could be more performant than `push(f())` because it
1070    /// permits the compiler to directly place `T` in the vector instead of
1071    /// constructing it on the stack and copying it over.
1072    ///
1073    /// # Panics
1074    /// Panics if the allocation fails.
1075    ///
1076    /// # Examples
1077    /// ```
1078    /// # use bump_scope::{Bump, mut_bump_vec};
1079    /// # let mut bump: Bump = Bump::new();
1080    /// let mut vec = mut_bump_vec![in &mut bump; 1, 2];
1081    /// vec.push_with(|| 3);
1082    /// assert_eq!(vec, [1, 2, 3]);
1083    /// ```
1084    #[inline(always)]
1085    #[cfg(feature = "panic-on-alloc")]
1086    pub fn push_with(&mut self, f: impl FnOnce() -> T) {
1087        panic_on_error(self.generic_push_with(f));
1088    }
1089
1090    /// Reserves space for one more element, then calls `f`
1091    /// to produce the value that is appended.
1092    ///
1093    /// In some cases this could be more performant than `push(f())` because it
1094    /// permits the compiler to directly place `T` in the vector instead of
1095    /// constructing it on the stack and copying it over.
1096    ///
1097    /// # Errors
1098    /// Errors if the allocation fails.
1099    ///
1100    /// # Examples
1101    /// ```
1102    /// # use bump_scope::{Bump, mut_bump_vec};
1103    /// # let mut bump: Bump = Bump::new();
1104    /// let mut vec = mut_bump_vec![in &mut bump; 1, 2];
1105    /// vec.try_push_with(|| 3)?;
1106    /// assert_eq!(vec, [1, 2, 3]);
1107    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1108    /// ```
1109    #[inline(always)]
1110    pub fn try_push_with(&mut self, f: impl FnOnce() -> T) -> Result<(), AllocError> {
1111        self.generic_push_with(f)
1112    }
1113
1114    #[inline]
1115    pub(crate) fn generic_push_with<E: ErrorBehavior>(&mut self, f: impl FnOnce() -> T) -> Result<(), E> {
1116        self.generic_push_mut_with(f).map(drop)
1117    }
1118
1119    /// Appends an element to the back of a collection.
1120    ///
1121    /// # Panics
1122    /// Panics if the allocation fails.
1123    ///
1124    /// # Examples
1125    /// ```
1126    /// # use bump_scope::{Bump, mut_bump_vec};
1127    /// # let mut bump: Bump = Bump::new();
1128    /// let mut vec = mut_bump_vec![in &mut bump; 1, 2];
1129    ///
1130    /// let last = vec.push_mut(3);
1131    /// assert_eq!(*last, 3);
1132    /// assert_eq!(vec, [1, 2, 3]);
1133    ///
1134    /// let last = vec.push_mut(3);
1135    /// *last += 1;
1136    /// assert_eq!(vec, [1, 2, 3, 4]);
1137    /// ```
1138    #[inline(always)]
1139    #[cfg(feature = "panic-on-alloc")]
1140    #[must_use = "if you don't need a reference to the value, use `push` instead"]
1141    pub fn push_mut(&mut self, value: T) -> &mut T {
1142        panic_on_error(self.generic_push_mut(value))
1143    }
1144
1145    /// Appends an element to the back of a collection.
1146    ///
1147    /// # Errors
1148    /// Errors if the allocation fails.
1149    ///
1150    /// # Examples
1151    /// ```
1152    /// # use bump_scope::{Bump, mut_bump_vec};
1153    /// # let mut bump: Bump = Bump::new();
1154    /// let mut vec = mut_bump_vec![try in &mut bump; 1, 2]?;
1155    ///
1156    /// let last = vec.try_push_mut(3)?;
1157    /// assert_eq!(*last, 3);
1158    /// assert_eq!(vec, [1, 2, 3]);
1159    ///
1160    /// let last = vec.try_push_mut(3)?;
1161    /// *last += 1;
1162    /// assert_eq!(vec, [1, 2, 3, 4]);
1163    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1164    /// ```
1165    #[inline(always)]
1166    #[must_use = "if you don't need a reference to the value, use `push` instead"]
1167    pub fn try_push_mut(&mut self, value: T) -> Result<&mut T, AllocError> {
1168        self.generic_push_mut(value)
1169    }
1170
1171    #[inline]
1172    pub(crate) fn generic_push_mut<E: ErrorBehavior>(&mut self, value: T) -> Result<&mut T, E> {
1173        self.generic_push_mut_with(|| value)
1174    }
1175
1176    /// Reserves space for one more element, then calls `f`
1177    /// to produce the value that is appended.
1178    ///
1179    /// In some cases this could be more performant than `push(f())` because it
1180    /// permits the compiler to directly place `T` in the vector instead of
1181    /// constructing it on the stack and copying it over.
1182    ///
1183    /// # Panics
1184    /// Panics if the allocation fails.
1185    ///
1186    /// # Examples
1187    /// ```
1188    /// # use bump_scope::{Bump, MutBumpVec};
1189    /// # let mut bump: Bump = Bump::new();
1190    /// let mut vec = MutBumpVec::new_in(&mut bump);
1191    /// let item = vec.push_mut_with(i32::default);
1192    /// *item += 1;
1193    /// *item += 2;
1194    /// assert_eq!(*item, 3);
1195    /// ```
1196    #[inline(always)]
1197    #[cfg(feature = "panic-on-alloc")]
1198    #[must_use = "if you don't need a reference to the value, use `push` instead"]
1199    pub fn push_mut_with(&mut self, f: impl FnOnce() -> T) -> &mut T {
1200        panic_on_error(self.generic_push_mut_with(f))
1201    }
1202
1203    /// Reserves space for one more element, then calls `f`
1204    /// to produce the value that is appended.
1205    ///
1206    /// In some cases this could be more performant than `push(f())` because it
1207    /// permits the compiler to directly place `T` in the vector instead of
1208    /// constructing it on the stack and copying it over.
1209    ///
1210    /// # Errors
1211    /// Errors if the allocation fails.
1212    ///
1213    /// # Examples
1214    /// ```
1215    /// # use bump_scope::{Bump, MutBumpVec};
1216    /// # let mut bump: Bump = Bump::new();
1217    /// let mut vec = MutBumpVec::new_in(&mut bump);
1218    /// let item = vec.try_push_mut_with(i32::default)?;
1219    /// *item += 1;
1220    /// *item += 2;
1221    /// assert_eq!(*item, 3);
1222    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1223    /// ```
1224    #[inline(always)]
1225    #[must_use = "if you don't need a reference to the value, use `push` instead"]
1226    pub fn try_push_mut_with(&mut self, f: impl FnOnce() -> T) -> Result<&mut T, AllocError> {
1227        self.generic_push_mut_with(f)
1228    }
1229
1230    #[inline]
1231    pub(crate) fn generic_push_mut_with<E: ErrorBehavior>(&mut self, f: impl FnOnce() -> T) -> Result<&mut T, E> {
1232        self.generic_reserve_one()?;
1233        Ok(unsafe { self.push_mut_unchecked(f()) })
1234    }
1235
1236    /// Inserts an element at position `index` within the vector, shifting all elements after it to the right.
1237    ///
1238    /// # Panics
1239    /// Panics if the allocation fails.
1240    ///
1241    /// Panics if `index > len`.
1242    ///
1243    /// # Examples
1244    /// ```
1245    /// # use bump_scope::{Bump, mut_bump_vec};
1246    /// # let mut bump: Bump = Bump::new();
1247    /// let mut vec = mut_bump_vec![in &mut bump; 'b', 'd'];
1248    /// vec.insert(1, 'c');
1249    /// assert_eq!(vec, ['b', 'c', 'd']);
1250    /// vec.insert(0, 'a');
1251    /// assert_eq!(vec, ['a', 'b', 'c', 'd']);
1252    /// vec.insert(4, 'e');
1253    /// assert_eq!(vec, ['a', 'b', 'c', 'd', 'e']);
1254    /// ```
1255    #[inline(always)]
1256    #[cfg(feature = "panic-on-alloc")]
1257    pub fn insert(&mut self, index: usize, element: T) {
1258        panic_on_error(self.generic_insert_mut(index, element));
1259    }
1260
1261    /// Inserts an element at position `index` within the vector, shifting all elements after it to the right.
1262    ///
1263    /// # Panics
1264    /// Panics if `index > len`.
1265    ///
1266    /// # Errors
1267    /// Errors if the allocation fails.
1268    ///
1269    /// # Examples
1270    /// ```
1271    /// # use bump_scope::{Bump, mut_bump_vec};
1272    /// # let mut bump: Bump = Bump::new();
1273    /// let mut vec = mut_bump_vec![try in &mut bump; 'b', 'd']?;
1274    /// vec.try_insert(1, 'c')?;
1275    /// assert_eq!(vec, ['b', 'c', 'd']);
1276    /// vec.try_insert(0, 'a')?;
1277    /// assert_eq!(vec, ['a', 'b', 'c', 'd']);
1278    /// vec.try_insert(4, 'e')?;
1279    /// assert_eq!(vec, ['a', 'b', 'c', 'd', 'e']);
1280    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1281    /// ```
1282    #[inline(always)]
1283    pub fn try_insert(&mut self, index: usize, element: T) -> Result<(), AllocError> {
1284        self.generic_insert_mut(index, element).map(drop)
1285    }
1286
1287    /// Inserts an element at position `index` within the vector, shifting all elements after it to the right.
1288    ///
1289    /// # Panics
1290    /// Panics if the vector does not have enough capacity.
1291    ///
1292    /// Panics if `index > len`.
1293    ///
1294    /// # Examples
1295    /// ```
1296    /// # use bump_scope::{Bump, mut_bump_vec};
1297    /// # let mut bump: Bump = Bump::new();
1298    /// let mut vec = mut_bump_vec![in &mut bump; 1, 3, 5, 9];
1299    /// let x = vec.insert_mut(3, 6);
1300    /// *x += 1;
1301    /// assert_eq!(vec, [1, 3, 5, 7, 9]);
1302    /// ```
1303    #[inline(always)]
1304    #[cfg(feature = "panic-on-alloc")]
1305    #[must_use = "if you don't need a reference to the value, use `insert` instead"]
1306    pub fn insert_mut(&mut self, index: usize, element: T) -> &mut T {
1307        panic_on_error(self.generic_insert_mut(index, element))
1308    }
1309
1310    /// Inserts an element at position `index` within the vector, shifting all elements after it to the right.
1311    ///
1312    /// # Panics
1313    /// Panics if `index > len`.
1314    ///
1315    /// # Errors
1316    /// Errors if the vector does not have enough capacity.
1317    ///
1318    /// # Examples
1319    /// ```
1320    /// # use bump_scope::{Bump, mut_bump_vec};
1321    /// # let mut bump: Bump = Bump::new();
1322    /// let mut vec = mut_bump_vec![try in &mut bump; 1, 3, 5, 9]?;
1323    /// let x = vec.try_insert_mut(3, 6)?;
1324    /// *x += 1;
1325    /// assert_eq!(vec, [1, 3, 5, 7, 9]);
1326    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1327    /// ```
1328    #[inline(always)]
1329    #[must_use = "if you don't need a reference to the value, use `try_insert` instead"]
1330    pub fn try_insert_mut(&mut self, index: usize, element: T) -> Result<&mut T, AllocError> {
1331        self.generic_insert_mut(index, element)
1332    }
1333
1334    #[inline]
1335    pub(crate) fn generic_insert_mut<E: ErrorBehavior>(&mut self, index: usize, element: T) -> Result<&mut T, E> {
1336        #[cold]
1337        #[track_caller]
1338        #[inline(never)]
1339        fn assert_failed(index: usize, len: usize) -> ! {
1340            panic!("insertion index (is {index}) should be <= len (is {len})");
1341        }
1342
1343        if index > self.len() {
1344            assert_failed(index, self.len());
1345        }
1346
1347        self.generic_reserve_one()?;
1348
1349        unsafe {
1350            let pos = self.as_mut_ptr().add(index);
1351
1352            if index != self.len() {
1353                let len = self.len() - index;
1354                ptr::copy(pos, pos.add(1), len);
1355            }
1356
1357            pos.write(element);
1358            self.inc_len(1);
1359            Ok(&mut *pos)
1360        }
1361    }
1362
1363    /// Copies and appends all elements in a slice to the `MutBumpVec`.
1364    ///
1365    /// Iterates over the `slice`, copies each element, and then appends
1366    /// it to this `MutBumpVec`. The `slice` is traversed in-order.
1367    ///
1368    /// Note that this function is same as [`extend`] except that it is
1369    /// specialized to work with copyable slices instead.
1370    ///
1371    /// [`extend`]: Self::extend
1372    ///
1373    /// # Panics
1374    /// Panics if the allocation fails.
1375    ///
1376    /// # Examples
1377    /// ```
1378    /// # use bump_scope::{ Bump, mut_bump_vec };
1379    /// # let mut bump: Bump = Bump::new();
1380    /// let mut vec = mut_bump_vec![in &mut bump; 1];
1381    /// vec.extend_from_slice_copy(&[2, 3, 4]);
1382    /// assert_eq!(vec, [1, 2, 3, 4]);
1383    /// ```
1384    #[inline(always)]
1385    #[cfg(feature = "panic-on-alloc")]
1386    pub fn extend_from_slice_copy(&mut self, slice: &[T])
1387    where
1388        T: Copy,
1389    {
1390        panic_on_error(self.generic_extend_from_slice_copy(slice));
1391    }
1392
1393    /// Copies and appends all elements in a slice to the `MutBumpVec`.
1394    ///
1395    /// Iterates over the `slice`, copies each element, and then appends
1396    /// it to this `MutBumpVec`. The `slice` is traversed in-order.
1397    ///
1398    /// Note that this function is same as [`extend`] except that it is
1399    /// specialized to work with copyable slices instead.
1400    ///
1401    /// [`extend`]: Self::extend
1402    ///
1403    /// # Errors
1404    /// Errors if the allocation fails.
1405    ///
1406    /// # Examples
1407    /// ```
1408    /// # use bump_scope::{ Bump, mut_bump_vec };
1409    /// # let mut bump: Bump = Bump::new();
1410    /// let mut vec = mut_bump_vec![try in &mut bump; 1]?;
1411    /// vec.try_extend_from_slice_copy(&[2, 3, 4])?;
1412    /// assert_eq!(vec, [1, 2, 3, 4]);
1413    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1414    /// ```
1415    #[inline(always)]
1416    pub fn try_extend_from_slice_copy(&mut self, slice: &[T]) -> Result<(), AllocError>
1417    where
1418        T: Copy,
1419    {
1420        self.generic_extend_from_slice_copy(slice)
1421    }
1422
1423    #[inline]
1424    pub(crate) fn generic_extend_from_slice_copy<E: ErrorBehavior>(&mut self, slice: &[T]) -> Result<(), E>
1425    where
1426        T: Copy,
1427    {
1428        unsafe { self.extend_by_copy_nonoverlapping(slice) }
1429    }
1430
1431    /// Clones and appends all elements in a slice to the `MutBumpVec`.
1432    ///
1433    /// Iterates over the `slice`, clones each element, and then appends
1434    /// it to this `MutBumpVec`. The `slice` is traversed in-order.
1435    ///
1436    /// Note that this function is same as [`extend`] except that it is
1437    /// specialized to work with slices instead.
1438    ///
1439    /// [`extend`]: Self::extend
1440    ///
1441    /// # Panics
1442    /// Panics if the allocation fails.
1443    ///
1444    /// # Examples
1445    /// ```
1446    /// # use std::string::String;
1447    /// # use bump_scope::{ Bump, mut_bump_vec };
1448    /// # let mut bump: Bump = Bump::new();
1449    /// let mut vec = mut_bump_vec![in &mut bump; String::from("a")];
1450    /// vec.extend_from_slice_clone(&[String::from("b"), String::from("c")]);
1451    /// assert_eq!(vec, ["a", "b", "c"]);
1452    /// ```
1453    #[inline(always)]
1454    #[cfg(feature = "panic-on-alloc")]
1455    pub fn extend_from_slice_clone(&mut self, slice: &[T])
1456    where
1457        T: Clone,
1458    {
1459        panic_on_error(self.generic_extend_from_slice_clone(slice));
1460    }
1461
1462    /// Clones and appends all elements in a slice to the `MutBumpVec`.
1463    ///
1464    /// Iterates over the `slice`, clones each element, and then appends
1465    /// it to this `MutBumpVec`. The `slice` is traversed in-order.
1466    ///
1467    /// Note that this function is same as [`extend`] except that it is
1468    /// specialized to work with slices instead.
1469    ///
1470    /// [`extend`]: Self::extend
1471    ///
1472    /// # Errors
1473    /// Errors if the allocation fails.
1474    ///
1475    /// # Examples
1476    /// ```
1477    /// # use std::string::String;
1478    /// # use bump_scope::{ Bump, mut_bump_vec };
1479    /// # let mut bump: Bump = Bump::new();
1480    /// let mut vec = mut_bump_vec![try in &mut bump; String::from("a")]?;
1481    /// vec.try_extend_from_slice_clone(&[String::from("b"), String::from("c")])?;
1482    /// assert_eq!(vec, ["a", "b", "c"]);
1483    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1484    /// ```
1485    #[inline(always)]
1486    pub fn try_extend_from_slice_clone(&mut self, slice: &[T]) -> Result<(), AllocError>
1487    where
1488        T: Clone,
1489    {
1490        self.generic_extend_from_slice_clone(slice)
1491    }
1492
1493    #[inline]
1494    pub(crate) fn generic_extend_from_slice_clone<E: ErrorBehavior>(&mut self, slice: &[T]) -> Result<(), E>
1495    where
1496        T: Clone,
1497    {
1498        self.generic_reserve(slice.len())?;
1499
1500        unsafe {
1501            let mut pos = 0usize;
1502
1503            while likely(pos != slice.len()) {
1504                let elem = slice.get_unchecked(pos);
1505                self.push_unchecked(elem.clone());
1506                pos += 1;
1507            }
1508        }
1509
1510        Ok(())
1511    }
1512
1513    /// Copies elements from `src` range to the end of the vector.
1514    ///
1515    /// # Panics
1516    /// Panics if the allocation fails.
1517    ///
1518    /// Panics if the starting point is greater than the end point or if
1519    /// the end point is greater than the length of the vector.
1520    ///
1521    /// # Examples
1522    /// ```
1523    /// # use bump_scope::{Bump, mut_bump_vec};
1524    /// # let mut bump: Bump = Bump::new();
1525    /// let mut vec = mut_bump_vec![in &mut bump; 0, 1, 2, 3, 4];
1526    ///
1527    /// vec.extend_from_within_copy(2..);
1528    /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);
1529    ///
1530    /// vec.extend_from_within_copy(..2);
1531    /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);
1532    ///
1533    /// vec.extend_from_within_copy(4..8);
1534    /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
1535    /// ```
1536    #[inline(always)]
1537    #[cfg(feature = "panic-on-alloc")]
1538    pub fn extend_from_within_copy<R>(&mut self, src: R)
1539    where
1540        T: Copy,
1541        R: RangeBounds<usize>,
1542    {
1543        panic_on_error(self.generic_extend_from_within_copy(src));
1544    }
1545
1546    /// Copies elements from `src` range to the end of the vector.
1547    ///
1548    /// # Panics
1549    /// Panics if the starting point is greater than the end point or if
1550    /// the end point is greater than the length of the vector.
1551    ///
1552    /// # Errors
1553    /// Errors if the allocation fails.
1554    ///
1555    /// # Examples
1556    /// ```
1557    /// # use bump_scope::{Bump, mut_bump_vec};
1558    /// # let mut bump: Bump = Bump::new();
1559    /// let mut vec = mut_bump_vec![try in &mut bump; 0, 1, 2, 3, 4]?;
1560    ///
1561    /// vec.try_extend_from_within_copy(2..)?;
1562    /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);
1563    ///
1564    /// vec.try_extend_from_within_copy(..2)?;
1565    /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);
1566    ///
1567    /// vec.try_extend_from_within_copy(4..8)?;
1568    /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
1569    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1570    /// ```
1571    #[inline(always)]
1572    pub fn try_extend_from_within_copy<R>(&mut self, src: R) -> Result<(), AllocError>
1573    where
1574        T: Copy,
1575        R: RangeBounds<usize>,
1576    {
1577        self.generic_extend_from_within_copy(src)
1578    }
1579
1580    #[inline]
1581    pub(crate) fn generic_extend_from_within_copy<E: ErrorBehavior, R>(&mut self, src: R) -> Result<(), E>
1582    where
1583        T: Copy,
1584        R: RangeBounds<usize>,
1585    {
1586        let range = slice::range(src, ..self.len());
1587        let count = range.len();
1588
1589        self.generic_reserve(count)?;
1590
1591        // SAFETY:
1592        // - `slice::range` guarantees that the given range is valid for indexing self
1593        unsafe {
1594            let ptr = self.as_mut_ptr();
1595
1596            let src = ptr.add(range.start);
1597            let dst = ptr.add(self.len());
1598            ptr::copy_nonoverlapping(src, dst, count);
1599
1600            self.inc_len(count);
1601            Ok(())
1602        }
1603    }
1604
1605    /// Clones elements from `src` range to the end of the vector.
1606    ///
1607    /// # Panics
1608    /// Panics if the allocation fails.
1609    ///
1610    /// Panics if the starting point is greater than the end point or if
1611    /// the end point is greater than the length of the vector.
1612    ///
1613    /// # Examples
1614    /// ```
1615    /// # use bump_scope::{Bump, mut_bump_vec};
1616    /// # let mut bump: Bump = Bump::new();
1617    /// let mut vec = mut_bump_vec![in &mut bump; 0, 1, 2, 3, 4];
1618    ///
1619    /// vec.extend_from_within_clone(2..);
1620    /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);
1621    ///
1622    /// vec.extend_from_within_clone(..2);
1623    /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);
1624    ///
1625    /// vec.extend_from_within_clone(4..8);
1626    /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
1627    /// ```
1628    #[inline(always)]
1629    #[cfg(feature = "panic-on-alloc")]
1630    pub fn extend_from_within_clone<R>(&mut self, src: R)
1631    where
1632        T: Clone,
1633        R: RangeBounds<usize>,
1634    {
1635        panic_on_error(self.generic_extend_from_within_clone(src));
1636    }
1637
1638    /// Clones elements from `src` range to the end of the vector.
1639    ///
1640    /// # Panics
1641    /// Panics if the starting point is greater than the end point or if
1642    /// the end point is greater than the length of the vector.
1643    ///
1644    /// # Errors
1645    /// Errors if the allocation fails.
1646    ///
1647    /// # Examples
1648    /// ```
1649    /// # use bump_scope::{Bump, mut_bump_vec};
1650    /// # let mut bump: Bump = Bump::new();
1651    /// let mut vec = mut_bump_vec![try in &mut bump; 0, 1, 2, 3, 4]?;
1652    ///
1653    /// vec.try_extend_from_within_clone(2..)?;
1654    /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);
1655    ///
1656    /// vec.try_extend_from_within_clone(..2)?;
1657    /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);
1658    ///
1659    /// vec.try_extend_from_within_clone(4..8)?;
1660    /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
1661    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1662    /// ```
1663    #[inline(always)]
1664    pub fn try_extend_from_within_clone<R>(&mut self, src: R) -> Result<(), AllocError>
1665    where
1666        T: Clone,
1667        R: RangeBounds<usize>,
1668    {
1669        self.generic_extend_from_within_clone(src)
1670    }
1671
1672    #[inline]
1673    pub(crate) fn generic_extend_from_within_clone<E: ErrorBehavior, R>(&mut self, src: R) -> Result<(), E>
1674    where
1675        T: Clone,
1676        R: RangeBounds<usize>,
1677    {
1678        let range = slice::range(src, ..self.len());
1679        let count = range.len();
1680
1681        self.generic_reserve(count)?;
1682
1683        if T::IS_ZST {
1684            unsafe {
1685                // We can materialize ZST's from nothing.
1686                #[expect(clippy::uninit_assumed_init)]
1687                let fake = ManuallyDrop::new(MaybeUninit::<T>::uninit().assume_init());
1688
1689                for _ in 0..count {
1690                    self.push_unchecked((*fake).clone());
1691                }
1692
1693                return Ok(());
1694            }
1695        }
1696
1697        // SAFETY:
1698        // - `slice::range` guarantees that the given range is valid for indexing self
1699        unsafe {
1700            let ptr = self.as_mut_ptr();
1701
1702            let mut src = ptr.add(range.start);
1703            let mut dst = ptr.add(self.len());
1704
1705            let src_end = src.add(count);
1706
1707            while src != src_end {
1708                dst.write((*src).clone());
1709
1710                src = src.add(1);
1711                dst = dst.add(1);
1712                self.inc_len(1);
1713            }
1714        }
1715
1716        Ok(())
1717    }
1718
1719    /// Reserves capacity for at least `additional` more elements to be inserted
1720    /// in the given `MutBumpVec<T>`. The collection may reserve more space to
1721    /// speculatively avoid frequent reallocations. After calling `reserve`,
1722    /// capacity will be greater than or equal to `self.len() + additional`.
1723    /// Does nothing if capacity is already sufficient.
1724    ///
1725    /// # Panics
1726    /// Panics if the allocation fails.
1727    ///
1728    /// # Examples
1729    /// ```
1730    /// # use bump_scope::{Bump, mut_bump_vec};
1731    /// # let mut bump: Bump = Bump::new();
1732    /// let mut vec = mut_bump_vec![in &mut bump; 1];
1733    /// vec.reserve(10);
1734    /// assert!(vec.capacity() >= 11);
1735    /// ```
1736    #[inline(always)]
1737    #[cfg(feature = "panic-on-alloc")]
1738    pub fn reserve(&mut self, additional: usize) {
1739        panic_on_error(self.generic_reserve(additional));
1740    }
1741
1742    /// Reserves capacity for at least `additional` more elements to be inserted
1743    /// in the given `MutBumpVec<T>`. The collection may reserve more space to
1744    /// speculatively avoid frequent reallocations. After calling `reserve`,
1745    /// capacity will be greater than or equal to `self.len() + additional`.
1746    /// Does nothing if capacity is already sufficient.
1747    ///
1748    /// # Errors
1749    /// Errors if the allocation fails.
1750    ///
1751    /// # Examples
1752    /// ```
1753    /// # use bump_scope::{Bump, mut_bump_vec};
1754    /// # let mut bump: Bump = Bump::new();
1755    /// let mut vec = mut_bump_vec![try in &mut bump; 1]?;
1756    /// vec.try_reserve(10)?;
1757    /// assert!(vec.capacity() >= 11);
1758    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1759    /// ```
1760    #[inline(always)]
1761    pub fn try_reserve(&mut self, additional: usize) -> Result<(), AllocError> {
1762        self.generic_reserve(additional)
1763    }
1764
1765    #[inline]
1766    pub(crate) fn generic_reserve<E: ErrorBehavior>(&mut self, additional: usize) -> Result<(), E> {
1767        if additional > (self.capacity() - self.len()) {
1768            self.generic_grow_amortized(additional)?;
1769        }
1770
1771        Ok(())
1772    }
1773
1774    /// Reserves the minimum capacity for at least `additional` more elements to
1775    /// be inserted in the given `MutBumpVec<T>`. Unlike [`reserve`], this will not
1776    /// deliberately over-allocate to speculatively avoid frequent allocations.
1777    /// After calling `reserve_exact`, capacity will be greater than or equal to
1778    /// `self.len() + additional`. Does nothing if the capacity is already
1779    /// sufficient.
1780    ///
1781    /// Note that the allocator may give the collection more space than it
1782    /// requests. Therefore, capacity cannot be relied upon to be precisely
1783    /// minimal. Prefer [`reserve`] if future insertions are expected.
1784    ///
1785    /// [`reserve`]: Self::reserve
1786    ///
1787    /// # Panics
1788    /// Panics if the allocation fails.
1789    ///
1790    /// # Examples
1791    /// ```
1792    /// # use bump_scope::{Bump, mut_bump_vec};
1793    /// # let mut bump: Bump = Bump::new();
1794    /// let mut vec = mut_bump_vec![in &mut bump; 1];
1795    /// vec.reserve_exact(10);
1796    /// assert!(vec.capacity() >= 11);
1797    /// ```
1798    #[inline(always)]
1799    #[cfg(feature = "panic-on-alloc")]
1800    pub fn reserve_exact(&mut self, additional: usize) {
1801        panic_on_error(self.generic_reserve_exact(additional));
1802    }
1803
1804    /// Reserves the minimum capacity for at least `additional` more elements to
1805    /// be inserted in the given `MutBumpVec<T>`. Unlike [`reserve`], this will not
1806    /// deliberately over-allocate to speculatively avoid frequent allocations.
1807    /// After calling `reserve_exact`, capacity will be greater than or equal to
1808    /// `self.len() + additional`. Does nothing if the capacity is already
1809    /// sufficient.
1810    ///
1811    /// Note that the allocator may give the collection more space than it
1812    /// requests. Therefore, capacity cannot be relied upon to be precisely
1813    /// minimal. Prefer [`reserve`] if future insertions are expected.
1814    ///
1815    /// [`reserve`]: Self::reserve
1816    ///
1817    /// # Errors
1818    /// Errors if the allocation fails.
1819    ///
1820    /// # Examples
1821    /// ```
1822    /// # use bump_scope::{Bump, mut_bump_vec};
1823    /// # let mut bump: Bump = Bump::new();
1824    /// let mut vec = mut_bump_vec![try in &mut bump; 1]?;
1825    /// vec.try_reserve_exact(10)?;
1826    /// assert!(vec.capacity() >= 11);
1827    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1828    /// ```
1829    #[inline(always)]
1830    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), AllocError> {
1831        self.generic_reserve_exact(additional)
1832    }
1833
1834    #[inline]
1835    pub(crate) fn generic_reserve_exact<E: ErrorBehavior>(&mut self, additional: usize) -> Result<(), E> {
1836        if additional > (self.capacity() - self.len()) {
1837            self.generic_grow_exact(additional)?;
1838        }
1839
1840        Ok(())
1841    }
1842
1843    /// Resizes the `MutBumpVec` in-place so that `len` is equal to `new_len`.
1844    ///
1845    /// If `new_len` is greater than `len`, the `MutBumpVec` is extended by the
1846    /// difference, with each additional slot filled with `value`.
1847    /// If `new_len` is less than `len`, the `MutBumpVec` is simply truncated.
1848    ///
1849    /// This method requires `T` to implement [`Clone`],
1850    /// in order to be able to clone the passed value.
1851    /// If you need more flexibility (or want to rely on [`Default`] instead of
1852    /// [`Clone`]), use [`resize_with`].
1853    /// If you only need to resize to a smaller size, use [`truncate`].
1854    ///
1855    /// [`resize_with`]: Self::resize_with
1856    /// [`truncate`]: Self::truncate
1857    ///
1858    /// # Panics
1859    /// Panics if the allocation fails.
1860    ///
1861    /// # Examples
1862    /// ```
1863    /// # use bump_scope::{Bump, mut_bump_vec};
1864    /// # let mut bump: Bump = Bump::new();
1865    /// let mut vec = mut_bump_vec![in &mut bump; "hello"];
1866    /// vec.resize(3, "world");
1867    /// assert_eq!(vec, ["hello", "world", "world"]);
1868    /// drop(vec);
1869    ///
1870    /// let mut vec = mut_bump_vec![in &mut bump; 1, 2, 3, 4];
1871    /// vec.resize(2, 0);
1872    /// assert_eq!(vec, [1, 2]);
1873    /// ```
1874    #[inline(always)]
1875    #[cfg(feature = "panic-on-alloc")]
1876    pub fn resize(&mut self, new_len: usize, value: T)
1877    where
1878        T: Clone,
1879    {
1880        panic_on_error(self.generic_resize(new_len, value));
1881    }
1882
1883    /// Resizes the `MutBumpVec` in-place so that `len` is equal to `new_len`.
1884    ///
1885    /// If `new_len` is greater than `len`, the `MutBumpVec` is extended by the
1886    /// difference, with each additional slot filled with `value`.
1887    /// If `new_len` is less than `len`, the `MutBumpVec` is simply truncated.
1888    ///
1889    /// This method requires `T` to implement [`Clone`],
1890    /// in order to be able to clone the passed value.
1891    /// If you need more flexibility (or want to rely on [`Default`] instead of
1892    /// [`Clone`]), use [`resize_with`].
1893    /// If you only need to resize to a smaller size, use [`truncate`].
1894    ///
1895    /// [`resize_with`]: Self::resize_with
1896    /// [`truncate`]: Self::truncate
1897    ///
1898    /// # Errors
1899    /// Errors if the allocation fails.
1900    ///
1901    /// # Examples
1902    /// ```
1903    /// # use bump_scope::{Bump, mut_bump_vec};
1904    /// # let mut bump: Bump = Bump::new();
1905    /// let mut vec = mut_bump_vec![try in &mut bump; "hello"]?;
1906    /// vec.try_resize(3, "world")?;
1907    /// assert_eq!(vec, ["hello", "world", "world"]);
1908    /// drop(vec);
1909    ///
1910    /// let mut vec = mut_bump_vec![try in &mut bump; 1, 2, 3, 4]?;
1911    /// vec.try_resize(2, 0)?;
1912    /// assert_eq!(vec, [1, 2]);
1913    /// # Ok::<(), bump_scope::alloc::AllocError>(())
1914    /// ```
1915    #[inline(always)]
1916    pub fn try_resize(&mut self, new_len: usize, value: T) -> Result<(), AllocError>
1917    where
1918        T: Clone,
1919    {
1920        self.generic_resize(new_len, value)
1921    }
1922
1923    #[inline]
1924    pub(crate) fn generic_resize<E: ErrorBehavior>(&mut self, new_len: usize, value: T) -> Result<(), E>
1925    where
1926        T: Clone,
1927    {
1928        let len = self.len();
1929
1930        if new_len > len {
1931            self.extend_with(new_len - len, value)
1932        } else {
1933            self.truncate(new_len);
1934            Ok(())
1935        }
1936    }
1937
1938    /// Resizes the `MutBumpVec` in-place so that `len` is equal to `new_len`.
1939    ///
1940    /// If `new_len` is greater than `len`, the `MutBumpVec` is extended by the
1941    /// difference, with each additional slot filled with the result of
1942    /// calling the closure `f`. The return values from `f` will end up
1943    /// in the `MutBumpVec` in the order they have been generated.
1944    ///
1945    /// If `new_len` is less than `len`, the `MutBumpVec` is simply truncated.
1946    ///
1947    /// This method uses a closure to create new values on every push. If
1948    /// you'd rather [`Clone`] a given value, use [`MutBumpVec::resize`]. If you
1949    /// want to use the [`Default`] trait to generate values, you can
1950    /// pass [`Default::default`] as the second argument.
1951    ///
1952    /// # Panics
1953    /// Panics if the allocation fails.
1954    ///
1955    /// # Examples
1956    /// ```
1957    /// # use bump_scope::{Bump, mut_bump_vec};
1958    /// # let mut bump: Bump = Bump::new();
1959    /// let mut vec = mut_bump_vec![in &mut bump; 1, 2, 3];
1960    /// vec.resize_with(5, Default::default);
1961    /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1962    /// drop(vec);
1963    ///
1964    /// let mut vec = mut_bump_vec![in &mut bump];
1965    /// let mut p = 1;
1966    /// vec.resize_with(4, || { p *= 2; p });
1967    /// assert_eq!(vec, [2, 4, 8, 16]);
1968    /// ```
1969    #[inline(always)]
1970    #[cfg(feature = "panic-on-alloc")]
1971    pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1972    where
1973        F: FnMut() -> T,
1974    {
1975        panic_on_error(self.generic_resize_with(new_len, f));
1976    }
1977
1978    /// Resizes the `MutBumpVec` in-place so that `len` is equal to `new_len`.
1979    ///
1980    /// If `new_len` is greater than `len`, the `MutBumpVec` is extended by the
1981    /// difference, with each additional slot filled with the result of
1982    /// calling the closure `f`. The return values from `f` will end up
1983    /// in the `MutBumpVec` in the order they have been generated.
1984    ///
1985    /// If `new_len` is less than `len`, the `MutBumpVec` is simply truncated.
1986    ///
1987    /// This method uses a closure to create new values on every push. If
1988    /// you'd rather [`Clone`] a given value, use [`MutBumpVec::resize`]. If you
1989    /// want to use the [`Default`] trait to generate values, you can
1990    /// pass [`Default::default`] as the second argument.
1991    ///
1992    /// # Errors
1993    /// Errors if the allocation fails.
1994    ///
1995    /// # Examples
1996    /// ```
1997    /// # use bump_scope::{Bump, mut_bump_vec};
1998    /// # let mut bump: Bump = Bump::new();
1999    /// let mut vec = mut_bump_vec![try in &mut bump; 1, 2, 3]?;
2000    /// vec.try_resize_with(5, Default::default)?;
2001    /// assert_eq!(vec, [1, 2, 3, 0, 0]);
2002    /// drop(vec);
2003    ///
2004    /// let mut vec = mut_bump_vec![try in &mut bump]?;
2005    /// let mut p = 1;
2006    /// vec.try_resize_with(4, || { p *= 2; p })?;
2007    /// assert_eq!(vec, [2, 4, 8, 16]);
2008    /// # Ok::<(), bump_scope::alloc::AllocError>(())
2009    /// ```
2010    #[inline(always)]
2011    pub fn try_resize_with<F>(&mut self, new_len: usize, f: F) -> Result<(), AllocError>
2012    where
2013        F: FnMut() -> T,
2014    {
2015        self.generic_resize_with(new_len, f)
2016    }
2017
2018    #[inline]
2019    pub(crate) fn generic_resize_with<E: ErrorBehavior, F>(&mut self, new_len: usize, f: F) -> Result<(), E>
2020    where
2021        F: FnMut() -> T,
2022    {
2023        let len = self.len();
2024        if new_len > len {
2025            unsafe { self.extend_trusted(iter::repeat_with(f).take(new_len - len)) }
2026        } else {
2027            self.truncate(new_len);
2028            Ok(())
2029        }
2030    }
2031
2032    /// Moves all the elements of `other` into `self`, leaving `other` empty.
2033    ///
2034    /// # Panics
2035    /// Panics if the allocation fails.
2036    ///
2037    /// # Examples
2038    /// ```
2039    /// # use bump_scope::{Bump, MutBumpVec};
2040    /// # let mut bump: Bump = Bump::new();
2041    /// # let bump2: Bump = Bump::new();
2042    /// let mut vec = MutBumpVec::new_in(&mut bump);
2043    ///
2044    /// // append by value
2045    /// vec.append([1, 2]);
2046    /// vec.append(vec![3, 4]);
2047    /// vec.append(bump2.alloc_iter(5..=6));
2048    ///
2049    /// // append by mutable reference
2050    /// let mut other = vec![7, 8];
2051    /// vec.append(&mut other);
2052    ///
2053    /// assert_eq!(other, []);
2054    /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7, 8]);
2055    /// ```
2056    #[inline(always)]
2057    #[cfg(feature = "panic-on-alloc")]
2058    pub fn append(&mut self, other: impl OwnedSlice<Item = T>) {
2059        panic_on_error(self.generic_append(other));
2060    }
2061
2062    /// Moves all the elements of `other` into `self`, leaving `other` empty.
2063    ///
2064    /// # Errors
2065    /// Errors if the allocation fails.
2066    ///
2067    /// # Examples
2068    /// ```
2069    /// # use bump_scope::{Bump, MutBumpVec};
2070    /// # let mut bump: Bump = Bump::new();
2071    /// # let bump2: Bump = Bump::new();
2072    /// let mut vec = MutBumpVec::new_in(&mut bump);
2073    ///
2074    /// // append by value
2075    /// vec.try_append([1, 2])?;
2076    /// vec.try_append(vec![3, 4])?;
2077    /// vec.try_append(bump2.alloc_iter(5..=6))?;
2078    ///
2079    /// // append by mutable reference
2080    /// let mut other = vec![7, 8];
2081    /// vec.try_append(&mut other)?;
2082    ///
2083    /// assert_eq!(other, []);
2084    /// assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7, 8]);
2085    /// # Ok::<(), bump_scope::alloc::AllocError>(())
2086    /// ```
2087    #[inline(always)]
2088    pub fn try_append(&mut self, other: impl OwnedSlice<Item = T>) -> Result<(), AllocError> {
2089        self.generic_append(other)
2090    }
2091
2092    #[inline]
2093    pub(crate) fn generic_append<E: ErrorBehavior>(&mut self, other: impl OwnedSlice<Item = T>) -> Result<(), E> {
2094        unsafe {
2095            let mut owned_slice = other.into_take_owned_slice();
2096
2097            let slice = NonNull::from(owned_slice.owned_slice_ref());
2098            self.generic_reserve(slice.len())?;
2099
2100            let src = slice.cast::<T>().as_ptr();
2101            let dst = self.as_mut_ptr().add(self.len());
2102            ptr::copy_nonoverlapping(src, dst, slice.len());
2103
2104            owned_slice.take_owned_slice();
2105            self.inc_len(slice.len());
2106            Ok(())
2107        }
2108    }
2109
2110    /// Returns a vector of the same size as `self`, with function `f` applied to each element in order.
2111    ///
2112    /// 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.
2113    ///
2114    /// # Examples
2115    /// Mapping to a type with an equal alignment and size:
2116    /// ```
2117    /// # use bump_scope::{Bump, MutBumpVec};
2118    /// # use core::num::NonZero;
2119    /// # let mut bump: Bump = Bump::new();
2120    /// let a = MutBumpVec::from_iter_in([0, 1, 2], &mut bump);
2121    /// let b = a.map_in_place(NonZero::new);
2122    /// assert_eq!(format!("{b:?}"), "[None, Some(1), Some(2)]");
2123    /// ```
2124    ///
2125    /// Mapping to a type with a smaller alignment and size:
2126    /// ```
2127    /// # use bump_scope::{Bump, MutBumpVec};
2128    /// # let mut bump: Bump = Bump::new();
2129    /// let a: MutBumpVec<u32, _> = MutBumpVec::from_iter_in([0, 1, 2], &mut bump);
2130    /// let a_capacity = a.capacity();
2131    ///
2132    /// let b: MutBumpVec<u16, _> = a.map_in_place(|i| i as u16);
2133    /// assert_eq!(b.capacity(), a_capacity * 2);
2134    ///
2135    /// assert_eq!(b, [0, 1, 2]);
2136    /// ```
2137    ///
2138    /// Mapping to a type with a greater alignment won't compile:
2139    /// ```compile_fail,E0080
2140    /// # use bump_scope::{Bump, MutBumpVec};
2141    /// # let mut bump: Bump = Bump::new();
2142    /// let a: MutBumpVec<u16, _> = MutBumpVec::from_iter_in([0, 1, 2], &mut bump);
2143    /// let b: MutBumpVec<u32, _> = a.map_in_place(|i| i as u32);
2144    /// # _ = b;
2145    /// ```
2146    ///
2147    /// Mapping to a type with a greater size won't compile:
2148    /// ```compile_fail,E0080
2149    /// # use bump_scope::{Bump, MutBumpVec};
2150    /// # let mut bump: Bump = Bump::new();
2151    /// let a: MutBumpVec<u32, _> = MutBumpVec::from_iter_exact_in([42], &mut bump);
2152    /// let b: MutBumpVec<[u32; 2], _> = a.map_in_place(|i| [i; 2]);
2153    /// # _ = b;
2154    /// ```
2155    pub fn map_in_place<U>(self, f: impl FnMut(T) -> U) -> MutBumpVec<U, A> {
2156        let MutBumpVec { fixed, allocator } = self;
2157        let fixed = unsafe { RawFixedBumpVec::from_cooked(fixed.cook().map_in_place(f)) };
2158        MutBumpVec { fixed, allocator }
2159    }
2160
2161    /// Extend the vector by `n` clones of value.
2162    fn extend_with<B: ErrorBehavior>(&mut self, n: usize, value: T) -> Result<(), B>
2163    where
2164        T: Clone,
2165    {
2166        self.generic_reserve(n)?;
2167        unsafe {
2168            self.fixed.cook_mut().extend_with_unchecked(n, value);
2169        }
2170        Ok(())
2171    }
2172
2173    #[inline(always)]
2174    unsafe fn extend_by_copy_nonoverlapping<E: ErrorBehavior>(&mut self, other: *const [T]) -> Result<(), E> {
2175        unsafe {
2176            let len = other.len();
2177            self.generic_reserve(len)?;
2178
2179            let src = other.cast::<T>();
2180            let dst = self.as_mut_ptr().add(self.len());
2181            ptr::copy_nonoverlapping(src, dst, len);
2182
2183            self.inc_len(len);
2184            Ok(())
2185        }
2186    }
2187
2188    #[inline]
2189    fn generic_reserve_one<E: ErrorBehavior>(&mut self) -> Result<(), E> {
2190        if self.capacity() == self.len() {
2191            self.generic_grow_amortized::<E>(1)?;
2192        }
2193
2194        Ok(())
2195    }
2196
2197    #[cold]
2198    #[inline(never)]
2199    fn generic_grow_amortized<E: ErrorBehavior>(&mut self, additional: usize) -> Result<(), E> {
2200        if T::IS_ZST {
2201            // This function is only called after we checked that the current capacity is not
2202            // sufficient. When `T::IS_ZST` the capacity is `usize::MAX`, so it can't grow.
2203            return Err(E::capacity_overflow());
2204        }
2205
2206        let Some(required_cap) = self.len().checked_add(additional) else {
2207            return Err(E::capacity_overflow());
2208        };
2209
2210        // This guarantees exponential growth. The doubling cannot overflow
2211        // because `capacity <= isize::MAX` and the type of `capacity` is usize;
2212        let new_cap = (self.capacity() * 2).max(required_cap).max(min_non_zero_cap(T::SIZE));
2213
2214        unsafe { self.generic_grow_to(new_cap) }
2215    }
2216
2217    #[cold]
2218    #[inline(never)]
2219    fn generic_grow_exact<E: ErrorBehavior>(&mut self, additional: usize) -> Result<(), E> {
2220        if T::IS_ZST {
2221            // This function is only called after we checked that the current capacity is not
2222            // sufficient. When `T::IS_ZST` the capacity is `usize::MAX`, so it can't grow.
2223            return Err(E::capacity_overflow());
2224        }
2225
2226        let Some(required_cap) = self.len().checked_add(additional) else {
2227            return Err(E::capacity_overflow())?;
2228        };
2229
2230        unsafe { self.generic_grow_to(required_cap) }
2231    }
2232
2233    /// # Safety
2234    ///
2235    /// `new_capacity` must be greater than the current capacity.
2236    unsafe fn generic_grow_to<E: ErrorBehavior>(&mut self, new_capacity: usize) -> Result<(), E> {
2237        let Self { fixed, allocator } = self;
2238        unsafe { fixed.grow_prepared_allocation(allocator, new_capacity) }
2239    }
2240
2241    #[must_use]
2242    #[inline]
2243    fn into_slice_ptr(self) -> NonNull<[T]> {
2244        let this = ManuallyDrop::new(self);
2245
2246        unsafe {
2247            if T::IS_ZST {
2248                return NonNull::slice_from_raw_parts(NonNull::dangling(), this.len());
2249            }
2250
2251            if this.capacity() == 0 {
2252                // We didn't touch the allocator, so no need to do anything.
2253                debug_assert_eq!(this.as_non_null(), NonNull::<T>::dangling());
2254                return NonNull::slice_from_raw_parts(NonNull::<T>::dangling(), 0);
2255            }
2256
2257            let ptr = this.as_non_null();
2258            let len = this.len();
2259            let cap = this.capacity();
2260
2261            this.allocator.allocate_prepared_slice(ptr, len, cap)
2262        }
2263    }
2264
2265    /// # Safety
2266    ///
2267    /// `iterator` must satisfy the invariants of nightly's `TrustedLen`.
2268    unsafe fn extend_trusted<B: ErrorBehavior>(&mut self, iterator: impl Iterator<Item = T>) -> Result<(), B> {
2269        unsafe {
2270            let (low, high) = iterator.size_hint();
2271            if let Some(additional) = high {
2272                debug_assert_eq!(
2273                    low,
2274                    additional,
2275                    "TrustedLen iterator's size hint is not exact: {:?}",
2276                    (low, high)
2277                );
2278
2279                self.generic_reserve(additional)?;
2280
2281                let ptr = self.as_mut_ptr();
2282                let mut local_len = self.fixed.set_len_on_drop();
2283
2284                iterator.for_each(move |element| {
2285                    let dst = ptr.add(local_len.current_len());
2286
2287                    ptr::write(dst, element);
2288                    // Since the loop executes user code which can panic we have to update
2289                    // the length every step to correctly drop what we've written.
2290                    // NB can't overflow since we would have had to alloc the address space
2291                    local_len.increment_len(1);
2292                });
2293
2294                Ok(())
2295            } else {
2296                // Per TrustedLen contract a `None` upper bound means that the iterator length
2297                // truly exceeds usize::MAX, which would eventually lead to a capacity overflow anyway.
2298                // Since the other branch already panics eagerly (via `reserve()`) we do the same here.
2299                // This avoids additional codegen for a fallback code path which would eventually
2300                // panic anyway.
2301                Err(B::capacity_overflow())
2302            }
2303        }
2304    }
2305
2306    /// Retains only the elements specified by the predicate, passing a mutable reference to it.
2307    ///
2308    /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`.
2309    /// This method operates in place, visiting each element exactly once in the
2310    /// original order, and preserves the order of the retained elements.
2311    ///
2312    /// # Examples
2313    ///
2314    /// ```
2315    /// # use bump_scope::{Bump, mut_bump_vec};
2316    /// # let mut bump: Bump = Bump::new();
2317    /// #
2318    /// let mut vec = mut_bump_vec![in &mut bump; 1, 2, 3, 4];
2319    ///
2320    /// vec.retain(|x| if *x <= 3 {
2321    ///     *x += 1;
2322    ///     true
2323    /// } else {
2324    ///     false
2325    /// });
2326    ///
2327    /// assert_eq!(vec, [2, 3, 4]);
2328    /// ```
2329    #[expect(clippy::pedantic)]
2330    pub fn retain<F>(&mut self, f: F)
2331    where
2332        F: FnMut(&mut T) -> bool,
2333    {
2334        unsafe { self.fixed.cook_mut() }.retain(f)
2335    }
2336
2337    /// Removes the specified range from the vector in bulk, returning all
2338    /// removed elements as an iterator. If the iterator is dropped before
2339    /// being fully consumed, it drops the remaining removed elements.
2340    ///
2341    /// The returned iterator keeps a mutable borrow on the vector to optimize
2342    /// its implementation.
2343    ///
2344    /// # Panics
2345    ///
2346    /// Panics if the starting point is greater than the end point or if
2347    /// the end point is greater than the length of the vector.
2348    ///
2349    /// # Leaking
2350    ///
2351    /// If the returned iterator goes out of scope without being dropped (due to
2352    /// [`mem::forget`](core::mem::forget), for example), the vector may have lost and leaked
2353    /// elements arbitrarily, including elements outside the range.
2354    ///
2355    /// # Examples
2356    ///
2357    /// ```
2358    /// # use bump_scope::{Bump, mut_bump_vec};
2359    /// # let mut bump1: Bump = Bump::new();
2360    /// # let bump2: Bump = Bump::new();
2361    /// #
2362    /// let mut v = mut_bump_vec![in &mut bump1; 1, 2, 3];
2363    /// let u = bump2.alloc_iter(v.drain(1..));
2364    /// assert_eq!(v, [1]);
2365    /// assert_eq!(u, [2, 3]);
2366    ///
2367    /// // A full range clears the vector, like `clear()` does
2368    /// v.drain(..);
2369    /// assert_eq!(v, []);
2370    /// ```
2371    pub fn drain<R>(&mut self, range: R) -> owned_slice::Drain<'_, T>
2372    where
2373        R: RangeBounds<usize>,
2374    {
2375        unsafe { self.fixed.cook_mut() }.drain(range)
2376    }
2377
2378    /// Creates an iterator which uses a closure to determine if an element should be removed.
2379    ///
2380    /// If the closure returns true, then the element is removed and yielded.
2381    /// If the closure returns false, the element will remain in the vector and will not be yielded
2382    /// by the iterator.
2383    ///
2384    /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
2385    /// or the iteration short-circuits, then the remaining elements will be retained.
2386    /// Use [`retain`] with a negated predicate if you do not need the returned iterator.
2387    ///
2388    /// Using this method is equivalent to the following code:
2389    ///
2390    /// ```
2391    /// # use bump_scope::{Bump, mut_bump_vec};
2392    /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2393    /// # let mut bump: Bump = Bump::new();
2394    /// # let mut vec = mut_bump_vec![in &mut bump; 1, 2, 3, 4, 5, 6];
2395    /// let mut i = 0;
2396    /// while i < vec.len() {
2397    ///     if some_predicate(&mut vec[i]) {
2398    ///         let val = vec.remove(i);
2399    ///         // your code here
2400    /// #       let _ = val;
2401    ///     } else {
2402    ///         i += 1;
2403    ///     }
2404    /// }
2405    ///
2406    /// # assert_eq!(vec, [1, 4, 5]);
2407    /// ```
2408    ///
2409    /// But `extract_if` is easier to use. `extract_if` is also more efficient,
2410    /// because it can backshift the elements of the array in bulk.
2411    ///
2412    /// Note that `extract_if` also lets you mutate every element in the filter closure,
2413    /// regardless of whether you choose to keep or remove it.
2414    ///
2415    /// # Examples
2416    ///
2417    /// Splitting an array into evens and odds, reusing the original allocation:
2418    ///
2419    /// ```
2420    /// # use bump_scope::{Bump, mut_bump_vec};
2421    /// # let mut bump: Bump = Bump::new();
2422    /// let mut numbers = mut_bump_vec![in &mut bump; 1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2423    ///
2424    /// let evens = numbers.extract_if(|x| *x % 2 == 0).collect::<Vec<_>>();
2425    /// let odds = numbers;
2426    ///
2427    /// assert_eq!(evens, [2, 4, 6, 8, 14]);
2428    /// assert_eq!(odds, [1, 3, 5, 9, 11, 13, 15]);
2429    /// ```
2430    ///
2431    /// [`retain`]: Self::retain
2432    pub fn extract_if<F>(&mut self, filter: F) -> owned_slice::ExtractIf<'_, T, F>
2433    where
2434        F: FnMut(&mut T) -> bool,
2435    {
2436        unsafe { self.fixed.cook_mut() }.extract_if(filter)
2437    }
2438
2439    /// Removes consecutive repeated elements in the vector according to the
2440    /// [`PartialEq`] trait implementation.
2441    ///
2442    /// If the vector is sorted, this removes all duplicates.
2443    ///
2444    /// # Examples
2445    ///
2446    /// ```
2447    /// # use bump_scope::{Bump, mut_bump_vec};
2448    /// # let mut bump: Bump = Bump::new();
2449    /// let mut vec = mut_bump_vec![in &mut bump; 1, 2, 2, 3, 2];
2450    ///
2451    /// vec.dedup();
2452    ///
2453    /// assert_eq!(vec, [1, 2, 3, 2]);
2454    /// ```
2455    #[inline]
2456    pub fn dedup(&mut self)
2457    where
2458        T: PartialEq,
2459    {
2460        unsafe { self.fixed.cook_mut() }.dedup();
2461    }
2462
2463    /// Removes all but the first of consecutive elements in the vector that resolve to the same
2464    /// key.
2465    ///
2466    /// If the vector is sorted, this removes all duplicates.
2467    ///
2468    /// # Examples
2469    ///
2470    /// ```
2471    /// # use bump_scope::{Bump, mut_bump_vec};
2472    /// # let mut bump: Bump = Bump::new();
2473    /// let mut vec = mut_bump_vec![in &mut bump; 10, 20, 21, 30, 20];
2474    ///
2475    /// vec.dedup_by_key(|i| *i / 10);
2476    ///
2477    /// assert_eq!(vec, [10, 20, 30, 20]);
2478    /// ```
2479    #[inline]
2480    pub fn dedup_by_key<F, K>(&mut self, key: F)
2481    where
2482        F: FnMut(&mut T) -> K,
2483        K: PartialEq,
2484    {
2485        unsafe { self.fixed.cook_mut() }.dedup_by_key(key);
2486    }
2487
2488    /// Removes all but the first of consecutive elements in the vector satisfying a given equality
2489    /// relation.
2490    ///
2491    /// The `same_bucket` function is passed references to two elements from the vector and
2492    /// must determine if the elements compare equal. The elements are passed in opposite order
2493    /// from their order in the vector, so if `same_bucket(a, b)` returns `true`, `a` is removed.
2494    ///
2495    /// If the vector is sorted, this removes all duplicates.
2496    ///
2497    /// # Examples
2498    ///
2499    /// ```
2500    /// # use bump_scope::{Bump, mut_bump_vec};
2501    /// # let mut bump: Bump = Bump::new();
2502    /// let mut vec = mut_bump_vec![in &mut bump; "foo", "bar", "Bar", "baz", "bar"];
2503    ///
2504    /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
2505    ///
2506    /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
2507    /// ```
2508    pub fn dedup_by<F>(&mut self, same_bucket: F)
2509    where
2510        F: FnMut(&mut T, &mut T) -> bool,
2511    {
2512        unsafe { self.fixed.cook_mut() }.dedup_by(same_bucket);
2513    }
2514
2515    /// Returns the remaining spare capacity of the vector as a slice of
2516    /// `MaybeUninit<T>`.
2517    ///
2518    /// The returned slice can be used to fill the vector with data (e.g. by
2519    /// reading from a file) before marking the data as initialized using the
2520    /// [`set_len`] method.
2521    ///
2522    /// [`set_len`]: Self::set_len
2523    ///
2524    /// # Examples
2525    ///
2526    /// ```
2527    /// # use bump_scope::{Bump, MutBumpVec};
2528    /// # let mut bump: Bump = Bump::new();
2529    /// // Allocate vector big enough for 10 elements.
2530    /// let mut v = MutBumpVec::with_capacity_in(10, &mut bump);
2531    ///
2532    /// // Fill in the first 3 elements.
2533    /// let uninit = v.spare_capacity_mut();
2534    /// uninit[0].write(0);
2535    /// uninit[1].write(1);
2536    /// uninit[2].write(2);
2537    ///
2538    /// // Mark the first 3 elements of the vector as being initialized.
2539    /// unsafe {
2540    ///     v.set_len(3);
2541    /// }
2542    ///
2543    /// assert_eq!(&v, &[0, 1, 2]);
2544    /// ```
2545    #[inline]
2546    pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
2547        // Note:
2548        // This method is not implemented in terms of `split_at_spare_mut`,
2549        // to prevent invalidation of pointers to the buffer.
2550        unsafe {
2551            slice::from_raw_parts_mut(
2552                self.as_mut_ptr().add(self.len()).cast::<MaybeUninit<T>>(),
2553                self.capacity() - self.len(),
2554            )
2555        }
2556    }
2557
2558    /// Returns vector content as a slice of `T`, along with the remaining spare
2559    /// capacity of the vector as a slice of `MaybeUninit<T>`.
2560    ///
2561    /// The returned spare capacity slice can be used to fill the vector with data
2562    /// (e.g. by reading from a file) before marking the data as initialized using
2563    /// the [`set_len`] method.
2564    ///
2565    /// [`set_len`]: Self::set_len
2566    ///
2567    /// Note that this is a low-level API, which should be used with care for
2568    /// optimization purposes. If you need to append data to a `MutBumpVec`
2569    /// you can use [`push`], [`extend`], `extend_from_slice`[`_copy`](MutBumpVec::extend_from_slice_copy)`/`[`_clone`](MutBumpVec::extend_from_within_clone),
2570    /// `extend_from_within`[`_copy`](MutBumpVec::extend_from_within_copy)`/`[`_clone`](MutBumpVec::extend_from_within_clone), [`insert`], [`resize`] or
2571    /// [`resize_with`], depending on your exact needs.
2572    ///
2573    /// [`push`]: Self::push
2574    /// [`extend`]: Self::extend
2575    /// [`insert`]: Self::insert
2576    /// [`append`]: Self::append
2577    /// [`resize`]: Self::resize
2578    /// [`resize_with`]: Self::resize_with
2579    #[inline]
2580    pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
2581        let ptr = self.as_mut_ptr();
2582
2583        // SAFETY:
2584        // - `ptr` is guaranteed to be valid for `self.len` elements
2585        // - but the allocation extends out to `self.buf.capacity()` elements, possibly
2586        // uninitialized
2587        let spare_ptr = unsafe { ptr.add(self.len()) };
2588        let spare_ptr = spare_ptr.cast::<MaybeUninit<T>>();
2589        let spare_len = self.capacity() - self.len();
2590
2591        // SAFETY:
2592        // - `ptr` is guaranteed to be valid for `self.len` elements
2593        // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized`
2594        unsafe {
2595            let initialized = slice::from_raw_parts_mut(ptr, self.len());
2596            let spare = slice::from_raw_parts_mut(spare_ptr, spare_len);
2597
2598            (initialized, spare)
2599        }
2600    }
2601
2602    /// Returns a type which provides statistics about the memory usage of the bump allocator.
2603    ///
2604    /// This collection does not update the bump pointer, so it also doesn't contribute to the `remaining` and `allocated` stats.
2605    #[must_use]
2606    #[inline(always)]
2607    pub fn allocator_stats(&self) -> A::TypedStats<'_> {
2608        self.allocator.typed_stats()
2609    }
2610}
2611
2612impl<'a, T, A: MutBumpAllocatorTypedScope<'a>> MutBumpVec<T, A> {
2613    /// Turns this `MutBumpVec<T>` into a `BumpBox<[T]>`.
2614    ///
2615    /// Unused capacity does not take up space.<br/>
2616    /// When [bumping downwards](crate#bumping-upwards-or-downwards) this needs to shift all elements to the other end of the chunk.
2617    #[must_use]
2618    #[inline(always)]
2619    pub fn into_boxed_slice(self) -> BumpBox<'a, [T]> {
2620        unsafe { BumpBox::from_raw(self.into_slice_ptr()) }
2621    }
2622
2623    /// Turns this `MutBumpVec<T>` into a `&[T]` that is live for this bump scope.
2624    ///
2625    /// Unused capacity does not take up space.<br/>
2626    /// When [bumping downwards](crate#bumping-upwards-or-downwards) this needs to shift all elements to the other end of the chunk.
2627    ///
2628    /// This is only available for [`NoDrop`] types so you don't omit dropping a value for which it matters.
2629    ///
2630    /// `!NoDrop` types can still be turned into slices via <code>BumpBox::[leak](BumpBox::leak)(vec.[into_boxed_slice](Self::into_boxed_slice)())</code>.
2631    #[must_use]
2632    #[inline(always)]
2633    pub fn into_slice(self) -> &'a mut [T]
2634    where
2635        [T]: NoDrop,
2636    {
2637        self.into_boxed_slice().into_mut()
2638    }
2639}
2640
2641impl<T, const N: usize, A> MutBumpVec<[T; N], A> {
2642    /// Takes a `MutBumpVec<[T; N]>` and flattens it into a `MutBumpVec<T>`.
2643    ///
2644    /// # Panics
2645    ///
2646    /// Panics if the length of the resulting vector would overflow a `usize`.
2647    ///
2648    /// This is only possible when flattening a vector of arrays of zero-sized
2649    /// types, and thus tends to be irrelevant in practice. If
2650    /// `size_of::<T>() > 0`, this will never panic.
2651    ///
2652    /// # Examples
2653    ///
2654    /// ```
2655    /// # use bump_scope::{Bump, mut_bump_vec};
2656    /// # let mut bump: Bump = Bump::new();
2657    /// #
2658    /// let mut vec = mut_bump_vec![in &mut bump; [1, 2, 3], [4, 5, 6], [7, 8, 9]];
2659    /// assert_eq!(vec.pop(), Some([7, 8, 9]));
2660    ///
2661    /// let mut flattened = vec.into_flattened();
2662    /// assert_eq!(flattened.pop(), Some(6));
2663    /// ```
2664    #[must_use]
2665    pub fn into_flattened(self) -> MutBumpVec<T, A> {
2666        let Self { fixed, allocator } = self;
2667        let fixed = unsafe { RawFixedBumpVec::from_cooked(fixed.cook().into_flattened()) };
2668        MutBumpVec { fixed, allocator }
2669    }
2670}
2671
2672impl<T: Debug, A> Debug for MutBumpVec<T, A> {
2673    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2674        Debug::fmt(self.as_slice(), f)
2675    }
2676}
2677
2678impl<T, A: MutBumpAllocatorTyped, I: SliceIndex<[T]>> Index<I> for MutBumpVec<T, A> {
2679    type Output = I::Output;
2680
2681    #[inline(always)]
2682    fn index(&self, index: I) -> &Self::Output {
2683        Index::index(self.as_slice(), index)
2684    }
2685}
2686
2687impl<T, A: MutBumpAllocatorTyped, I: SliceIndex<[T]>> IndexMut<I> for MutBumpVec<T, A> {
2688    #[inline(always)]
2689    fn index_mut(&mut self, index: I) -> &mut Self::Output {
2690        IndexMut::index_mut(self.as_mut_slice(), index)
2691    }
2692}
2693
2694#[cfg(feature = "panic-on-alloc")]
2695impl<T, A: MutBumpAllocatorTyped> Extend<T> for MutBumpVec<T, A> {
2696    #[inline]
2697    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2698        let iter = iter.into_iter();
2699
2700        self.reserve(iter.size_hint().0);
2701
2702        for value in iter {
2703            self.push(value);
2704        }
2705    }
2706}
2707
2708#[cfg(feature = "panic-on-alloc")]
2709impl<'t, T: Clone + 't, A: MutBumpAllocatorTyped> Extend<&'t T> for MutBumpVec<T, A> {
2710    #[inline]
2711    fn extend<I: IntoIterator<Item = &'t T>>(&mut self, iter: I) {
2712        let iter = iter.into_iter();
2713
2714        self.reserve(iter.size_hint().0);
2715
2716        for value in iter {
2717            self.push(value.clone());
2718        }
2719    }
2720}
2721
2722impl<T, A> IntoIterator for MutBumpVec<T, A> {
2723    type Item = T;
2724    type IntoIter = IntoIter<T, A>;
2725
2726    /// If you need to use the allocator while iterating you can first turn it to a slice with [`into_slice`] or [`into_boxed_slice`].
2727    ///
2728    /// [`into_slice`]: Self::into_slice
2729    /// [`into_boxed_slice`]: Self::into_boxed_slice
2730    #[inline(always)]
2731    fn into_iter(self) -> Self::IntoIter {
2732        let Self { fixed, allocator } = self;
2733        let (slice, _) = fixed.into_raw_parts();
2734        unsafe { IntoIter::new(slice, allocator) }
2735    }
2736}
2737
2738impl<'c, T, A> IntoIterator for &'c MutBumpVec<T, A> {
2739    type Item = &'c T;
2740    type IntoIter = slice::Iter<'c, T>;
2741
2742    #[inline(always)]
2743    fn into_iter(self) -> Self::IntoIter {
2744        self.as_slice().iter()
2745    }
2746}
2747
2748impl<'c, T, A> IntoIterator for &'c mut MutBumpVec<T, A> {
2749    type Item = &'c mut T;
2750    type IntoIter = slice::IterMut<'c, T>;
2751
2752    #[inline(always)]
2753    fn into_iter(self) -> Self::IntoIter {
2754        self.as_mut_slice().iter_mut()
2755    }
2756}
2757
2758impl<T, A> AsRef<[T]> for MutBumpVec<T, A> {
2759    #[inline(always)]
2760    fn as_ref(&self) -> &[T] {
2761        self
2762    }
2763}
2764
2765impl<T, A> AsMut<[T]> for MutBumpVec<T, A> {
2766    #[inline(always)]
2767    fn as_mut(&mut self) -> &mut [T] {
2768        self
2769    }
2770}
2771
2772impl<T, A> Borrow<[T]> for MutBumpVec<T, A> {
2773    #[inline(always)]
2774    fn borrow(&self) -> &[T] {
2775        self
2776    }
2777}
2778
2779impl<T, A> BorrowMut<[T]> for MutBumpVec<T, A> {
2780    #[inline(always)]
2781    fn borrow_mut(&mut self) -> &mut [T] {
2782        self
2783    }
2784}
2785
2786impl<T: Hash, A> Hash for MutBumpVec<T, A> {
2787    #[inline(always)]
2788    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
2789        self.as_slice().hash(state);
2790    }
2791}
2792
2793/// Returns [`ErrorKind::OutOfMemory`](std::io::ErrorKind::OutOfMemory) when allocations fail.
2794#[cfg(feature = "std")]
2795impl<A: MutBumpAllocatorTyped> std::io::Write for MutBumpVec<u8, A> {
2796    #[inline(always)]
2797    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
2798        if self.try_extend_from_slice_copy(buf).is_err() {
2799            return Err(std::io::ErrorKind::OutOfMemory.into());
2800        }
2801
2802        Ok(buf.len())
2803    }
2804
2805    #[inline(always)]
2806    fn flush(&mut self) -> std::io::Result<()> {
2807        Ok(())
2808    }
2809
2810    #[inline]
2811    fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result<usize> {
2812        let len = bufs.iter().map(|b| b.len()).sum();
2813        self.try_reserve(len).map_err(|_| std::io::ErrorKind::OutOfMemory)?;
2814        for buf in bufs {
2815            self.try_extend_from_slice_copy(buf)
2816                .map_err(|_| std::io::ErrorKind::OutOfMemory)?;
2817        }
2818        Ok(len)
2819    }
2820
2821    #[inline(always)]
2822    fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
2823        if self.try_extend_from_slice_copy(buf).is_err() {
2824            return Err(std::io::ErrorKind::OutOfMemory.into());
2825        }
2826
2827        Ok(())
2828    }
2829}
2830
2831#[cfg(feature = "panic-on-alloc")]
2832impl<T, A: MutBumpAllocatorTyped + Default> FromIterator<T> for MutBumpVec<T, A> {
2833    #[inline]
2834    #[track_caller]
2835    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
2836        Self::from_iter_in(iter, A::default())
2837    }
2838}