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