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