bumpalo/collections/vec.rs
1// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11//! A contiguous growable array type with heap-allocated contents, written
12//! `Vec<'bump, T>`.
13//!
14//! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and
15//! `O(1)` pop (from the end).
16//!
17//! # Examples
18//!
19//! You can explicitly create a [`Vec<'bump, T>`] with [`new`]:
20//!
21//! ```
22//! use bumpalo::{Bump, collections::Vec};
23//!
24//! let b = Bump::new();
25//! let v: Vec<i32> = Vec::new_in(&b);
26//! ```
27//!
28//! ...or by using the [`vec!`] macro:
29//!
30//! ```
31//! use bumpalo::{Bump, collections::Vec};
32//!
33//! let b = Bump::new();
34//!
35//! let v: Vec<i32> = bumpalo::vec![in &b];
36//!
37//! let v = bumpalo::vec![in &b; 1, 2, 3, 4, 5];
38//!
39//! let v = bumpalo::vec![in &b; 0; 10]; // ten zeroes
40//! ```
41//!
42//! You can [`push`] values onto the end of a vector (which will grow the vector
43//! as needed):
44//!
45//! ```
46//! use bumpalo::{Bump, collections::Vec};
47//!
48//! let b = Bump::new();
49//!
50//! let mut v = bumpalo::vec![in &b; 1, 2];
51//!
52//! v.push(3);
53//! ```
54//!
55//! Popping values works in much the same way:
56//!
57//! ```
58//! use bumpalo::{Bump, collections::Vec};
59//!
60//! let b = Bump::new();
61//!
62//! let mut v = bumpalo::vec![in &b; 1, 2];
63//!
64//! let two = v.pop();
65//! ```
66//!
67//! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
68//!
69//! ```
70//! use bumpalo::{Bump, collections::Vec};
71//!
72//! let b = Bump::new();
73//!
74//! let mut v = bumpalo::vec![in &b; 1, 2, 3];
75//! let three = v[2];
76//! v[1] = v[1] + 5;
77//! ```
78//!
79//! [`Vec<'bump, T>`]: ./struct.Vec.html
80//! [`new`]: ./struct.Vec.html#method.new
81//! [`push`]: ./struct.Vec.html#method.push
82//! [`Index`]: https://doc.rust-lang.org/nightly/std/ops/trait.Index.html
83//! [`IndexMut`]: ../../std/ops/trait.IndexMut.html
84//! [`vec!`]: ../../macro.vec.html
85
86use super::raw_vec::RawVec;
87use crate::Bump;
88use core::cmp::Ordering;
89use core::fmt;
90use core::hash::{self, Hash};
91use core::iter::FusedIterator;
92use core::marker::PhantomData;
93use core::mem;
94use core::ops;
95use core::ops::Bound::{Excluded, Included, Unbounded};
96use core::ops::{Index, IndexMut, RangeBounds};
97use core::ptr;
98use core::ptr::NonNull;
99use core::slice;
100
101unsafe fn arith_offset<T>(p: *const T, offset: isize) -> *const T {
102 p.offset(offset)
103}
104
105fn partition_dedup_by<T, F>(s: &mut [T], mut same_bucket: F) -> (&mut [T], &mut [T])
106where
107 F: FnMut(&mut T, &mut T) -> bool,
108{
109 // Although we have a mutable reference to `s`, we cannot make
110 // *arbitrary* changes. The `same_bucket` calls could panic, so we
111 // must ensure that the slice is in a valid state at all times.
112 //
113 // The way that we handle this is by using swaps; we iterate
114 // over all the elements, swapping as we go so that at the end
115 // the elements we wish to keep are in the front, and those we
116 // wish to reject are at the back. We can then split the slice.
117 // This operation is still O(n).
118 //
119 // Example: We start in this state, where `r` represents "next
120 // read" and `w` represents "next_write`.
121 //
122 // r
123 // +---+---+---+---+---+---+
124 // | 0 | 1 | 1 | 2 | 3 | 3 |
125 // +---+---+---+---+---+---+
126 // w
127 //
128 // Comparing s[r] against s[w-1], this is not a duplicate, so
129 // we swap s[r] and s[w] (no effect as r==w) and then increment both
130 // r and w, leaving us with:
131 //
132 // r
133 // +---+---+---+---+---+---+
134 // | 0 | 1 | 1 | 2 | 3 | 3 |
135 // +---+---+---+---+---+---+
136 // w
137 //
138 // Comparing s[r] against s[w-1], this value is a duplicate,
139 // so we increment `r` but leave everything else unchanged:
140 //
141 // r
142 // +---+---+---+---+---+---+
143 // | 0 | 1 | 1 | 2 | 3 | 3 |
144 // +---+---+---+---+---+---+
145 // w
146 //
147 // Comparing s[r] against s[w-1], this is not a duplicate,
148 // so swap s[r] and s[w] and advance r and w:
149 //
150 // r
151 // +---+---+---+---+---+---+
152 // | 0 | 1 | 2 | 1 | 3 | 3 |
153 // +---+---+---+---+---+---+
154 // w
155 //
156 // Not a duplicate, repeat:
157 //
158 // r
159 // +---+---+---+---+---+---+
160 // | 0 | 1 | 2 | 3 | 1 | 3 |
161 // +---+---+---+---+---+---+
162 // w
163 //
164 // Duplicate, advance r. End of slice. Split at w.
165
166 let len = s.len();
167 if len <= 1 {
168 return (s, &mut []);
169 }
170
171 let ptr = s.as_mut_ptr();
172 let mut next_read: usize = 1;
173 let mut next_write: usize = 1;
174
175 unsafe {
176 // Avoid bounds checks by using raw pointers.
177 while next_read < len {
178 let ptr_read = ptr.add(next_read);
179 let prev_ptr_write = ptr.add(next_write - 1);
180 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
181 if next_read != next_write {
182 let ptr_write = prev_ptr_write.offset(1);
183 mem::swap(&mut *ptr_read, &mut *ptr_write);
184 }
185 next_write += 1;
186 }
187 next_read += 1;
188 }
189 }
190
191 s.split_at_mut(next_write)
192}
193
194unsafe fn offset_from<T>(p: *const T, origin: *const T) -> isize
195where
196 T: Sized,
197{
198 let pointee_size = mem::size_of::<T>();
199 assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize);
200
201 // This is the same sequence that Clang emits for pointer subtraction.
202 // It can be neither `nsw` nor `nuw` because the input is treated as
203 // unsigned but then the output is treated as signed, so neither works.
204 let d = isize::wrapping_sub(p as _, origin as _);
205 d / (pointee_size as isize)
206}
207
208/// Creates a [`Vec`] containing the arguments.
209///
210/// `vec!` allows `Vec`s to be defined with the same syntax as array expressions.
211/// There are two forms of this macro:
212///
213/// - Create a [`Vec`] containing a given list of elements:
214///
215/// ```
216/// use bumpalo::{Bump, vec};
217///
218/// let b = Bump::new();
219/// let v = bumpalo::vec![in &b; 1, 2, 3];
220/// assert_eq!(v[0], 1);
221/// assert_eq!(v[1], 2);
222/// assert_eq!(v[2], 3);
223/// ```
224///
225/// - Create a [`Vec`] from a given element and size:
226///
227/// ```
228/// use bumpalo::{Bump, vec};
229///
230/// let b = Bump::new();
231/// let v = bumpalo::vec![in &b; 1; 3];
232/// assert_eq!(v, [1, 1, 1]);
233/// ```
234///
235/// Note that unlike array expressions this syntax supports all elements
236/// which implement [`Clone`] and the number of elements doesn't have to be
237/// a constant.
238///
239/// This will use `clone` to duplicate an expression, so one should be careful
240/// using this with types having a nonstandard `Clone` implementation. For
241/// example, `bumpalo::vec![in ≎ Rc::new(1); 5]` will create a vector of five references
242/// to the same boxed integer value, not five references pointing to independently
243/// boxed integers.
244///
245/// [`Vec`]: ../collections/vec/struct.Vec.html
246/// [`Clone`]: https://doc.rust-lang.org/nightly/std/clone/trait.Clone.html
247#[macro_export]
248macro_rules! vec {
249 (in $bump:expr; $elem:expr; $n:expr) => {{
250 let n = $n;
251 let mut v = $crate::collections::Vec::with_capacity_in(n, $bump);
252 if n > 0 {
253 let elem = $elem;
254 for _ in 0..n - 1 {
255 v.push(elem.clone());
256 }
257 v.push(elem);
258 }
259 v
260 }};
261 (in $bump:expr) => { $crate::collections::Vec::new_in($bump) };
262 (in $bump:expr; $($x:expr),*) => {{
263 let mut v = $crate::collections::Vec::new_in($bump);
264 $( v.push($x); )*
265 v
266 }};
267 (in $bump:expr; $($x:expr,)*) => (bumpalo::vec![in $bump; $($x),*])
268}
269
270/// A contiguous growable array type, written `Vec<'bump, T>` but pronounced 'vector'.
271///
272/// # Examples
273///
274/// ```
275/// use bumpalo::{Bump, collections::Vec};
276///
277/// let b = Bump::new();
278///
279/// let mut vec = Vec::new_in(&b);
280/// vec.push(1);
281/// vec.push(2);
282///
283/// assert_eq!(vec.len(), 2);
284/// assert_eq!(vec[0], 1);
285///
286/// assert_eq!(vec.pop(), Some(2));
287/// assert_eq!(vec.len(), 1);
288///
289/// vec[0] = 7;
290/// assert_eq!(vec[0], 7);
291///
292/// vec.extend([1, 2, 3].iter().cloned());
293///
294/// for x in &vec {
295/// println!("{}", x);
296/// }
297/// assert_eq!(vec, [7, 1, 2, 3]);
298/// ```
299///
300/// The [`vec!`] macro is provided to make initialization more convenient:
301///
302/// ```
303/// use bumpalo::{Bump, collections::Vec};
304///
305/// let b = Bump::new();
306///
307/// let mut vec = bumpalo::vec![in &b; 1, 2, 3];
308/// vec.push(4);
309/// assert_eq!(vec, [1, 2, 3, 4]);
310/// ```
311///
312/// It can also initialize each element of a `Vec<'bump, T>` with a given value.
313/// This may be more efficient than performing allocation and initialization
314/// in separate steps, especially when initializing a vector of zeros:
315///
316/// ```
317/// use bumpalo::{Bump, collections::Vec};
318///
319/// let b = Bump::new();
320///
321/// let vec = bumpalo::vec![in &b; 0; 5];
322/// assert_eq!(vec, [0, 0, 0, 0, 0]);
323///
324/// // The following is equivalent, but potentially slower:
325/// let mut vec1 = Vec::with_capacity_in(5, &b);
326/// vec1.resize(5, 0);
327/// ```
328///
329/// Use a `Vec<'bump, T>` as an efficient stack:
330///
331/// ```
332/// use bumpalo::{Bump, collections::Vec};
333///
334/// let b = Bump::new();
335///
336/// let mut stack = Vec::new_in(&b);
337///
338/// stack.push(1);
339/// stack.push(2);
340/// stack.push(3);
341///
342/// while let Some(top) = stack.pop() {
343/// // Prints 3, 2, 1
344/// println!("{}", top);
345/// }
346/// ```
347///
348/// # Indexing
349///
350/// The `Vec` type allows to access values by index, because it implements the
351/// [`Index`] trait. An example will be more explicit:
352///
353/// ```
354/// use bumpalo::{Bump, collections::Vec};
355///
356/// let b = Bump::new();
357///
358/// let v = bumpalo::vec![in &b; 0, 2, 4, 6];
359/// println!("{}", v[1]); // it will display '2'
360/// ```
361///
362/// However be careful: if you try to access an index which isn't in the `Vec`,
363/// your software will panic! You cannot do this:
364///
365/// ```should_panic
366/// use bumpalo::{Bump, collections::Vec};
367///
368/// let b = Bump::new();
369///
370/// let v = bumpalo::vec![in &b; 0, 2, 4, 6];
371/// println!("{}", v[6]); // it will panic!
372/// ```
373///
374/// In conclusion: always check if the index you want to get really exists
375/// before doing it.
376///
377/// # Slicing
378///
379/// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
380/// To get a slice, use `&`. Example:
381///
382/// ```
383/// use bumpalo::{Bump, collections::Vec};
384///
385/// fn read_slice(slice: &[usize]) {
386/// // ...
387/// }
388///
389/// let b = Bump::new();
390///
391/// let v = bumpalo::vec![in &b; 0, 1];
392/// read_slice(&v);
393///
394/// // ... and that's all!
395/// // you can also do it like this:
396/// let x : &[usize] = &v;
397/// ```
398///
399/// In Rust, it's more common to pass slices as arguments rather than vectors
400/// when you just want to provide a read access. The same goes for [`String`] and
401/// [`&str`].
402///
403/// # Capacity and reallocation
404///
405/// The capacity of a vector is the amount of space allocated for any future
406/// elements that will be added onto the vector. This is not to be confused with
407/// the *length* of a vector, which specifies the number of actual elements
408/// within the vector. If a vector's length exceeds its capacity, its capacity
409/// will automatically be increased, but its elements will have to be
410/// reallocated.
411///
412/// For example, a vector with capacity 10 and length 0 would be an empty vector
413/// with space for 10 more elements. Pushing 10 or fewer elements onto the
414/// vector will not change its capacity or cause reallocation to occur. However,
415/// if the vector's length is increased to 11, it will have to reallocate, which
416/// can be slow. For this reason, it is recommended to use [`Vec::with_capacity_in`]
417/// whenever possible to specify how big the vector is expected to get.
418///
419/// # Guarantees
420///
421/// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
422/// about its design. This ensures that it's as low-overhead as possible in
423/// the general case, and can be correctly manipulated in primitive ways
424/// by unsafe code. Note that these guarantees refer to an unqualified `Vec<'bump, T>`.
425/// If additional type parameters are added (e.g. to support custom allocators),
426/// overriding their defaults may change the behavior.
427///
428/// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
429/// triplet. No more, no less. The order of these fields is completely
430/// unspecified, and you should use the appropriate methods to modify these.
431/// The pointer will never be null, so this type is null-pointer-optimized.
432///
433/// However, the pointer may not actually point to allocated memory. In particular,
434/// if you construct a `Vec` with capacity 0 via [`Vec::new_in`], [`bumpalo::vec![in bump]`][`vec!`],
435/// [`Vec::with_capacity_in(0)`][`Vec::with_capacity_in`], or by calling [`shrink_to_fit`]
436/// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
437/// types inside a `Vec`, it will not allocate space for them. *Note that in this case
438/// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
439/// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation
440/// details are very subtle — if you intend to allocate memory using a `Vec`
441/// and use it for something else (either to pass to unsafe code, or to build your
442/// own memory-backed collection), be sure to deallocate this memory by using
443/// `from_raw_parts` to recover the `Vec` and then dropping it.
444///
445/// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
446/// (as defined by the allocator Rust is configured to use by default), and its
447/// pointer points to [`len`] initialized, contiguous elements in order (what
448/// you would see if you coerced it to a slice), followed by [`capacity`]` -
449/// `[`len`] logically uninitialized, contiguous elements.
450///
451/// `Vec` will never perform a "small optimization" where elements are actually
452/// stored on the stack for two reasons:
453///
454/// * It would make it more difficult for unsafe code to correctly manipulate
455/// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
456/// only moved, and it would be more difficult to determine if a `Vec` had
457/// actually allocated memory.
458///
459/// * It would penalize the general case, incurring an additional branch
460/// on every access.
461///
462/// `Vec` will never automatically shrink itself, even if completely empty. This
463/// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
464/// and then filling it back up to the same [`len`] should incur no calls to
465/// the allocator. If you wish to free up unused memory, use
466/// [`shrink_to_fit`][`shrink_to_fit`].
467///
468/// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
469/// sufficient. [`push`] and [`insert`] *will* (re)allocate if
470/// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
471/// accurate, and can be relied on. It can even be used to manually free the memory
472/// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
473/// when not necessary.
474///
475/// `Vec` does not guarantee any particular growth strategy when reallocating
476/// when full, nor when [`reserve`] is called. The current strategy is basic
477/// and it may prove desirable to use a non-constant growth factor. Whatever
478/// strategy is used will of course guarantee `O(1)` amortized [`push`].
479///
480/// `bumpalo::vec![in bump; x; n]`, `bumpalo::vec![in bump; a, b, c, d]`, and
481/// [`Vec::with_capacity_in(n)`][`Vec::with_capacity_in`], will all produce a
482/// `Vec` with exactly the requested capacity. If [`len`]` == `[`capacity`], (as
483/// is the case for the [`vec!`] macro), then a `Vec<'bump, T>` can be converted
484/// to and from a [`Box<[T]>`][owned slice] without reallocating or moving the
485/// elements.
486///
487/// `Vec` will not specifically overwrite any data that is removed from it,
488/// but also won't specifically preserve it. Its uninitialized memory is
489/// scratch space that it may use however it wants. It will generally just do
490/// whatever is most efficient or otherwise easy to implement. Do not rely on
491/// removed data to be erased for security purposes. Even if you drop a `Vec`, its
492/// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
493/// first, that may not actually happen because the optimizer does not consider
494/// this a side-effect that must be preserved. There is one case which we will
495/// not break, however: using `unsafe` code to write to the excess capacity,
496/// and then increasing the length to match, is always valid.
497///
498/// `Vec` does not currently guarantee the order in which elements are dropped.
499/// The order has changed in the past and may change again.
500///
501/// [`vec!`]: ../../macro.vec.html
502/// [`Index`]: https://doc.rust-lang.org/nightly/std/ops/trait.Index.html
503/// [`String`]: https://doc.rust-lang.org/nightly/std/string/struct.String.html
504/// [`&str`]: https://doc.rust-lang.org/nightly/std/primitive.str.html
505/// [`Vec::with_capacity_in`]: ./struct.Vec.html#method.with_capacity_in
506/// [`Vec::new_in`]: ./struct.Vec.html#method.new
507/// [`shrink_to_fit`]: ./struct.Vec.html#method.shrink_to_fit
508/// [`capacity`]: ./struct.Vec.html#method.capacity
509/// [`mem::size_of::<T>`]: https://doc.rust-lang.org/nightly/std/mem/fn.size_of.html
510/// [`len`]: ./struct.Vec.html#method.len
511/// [`push`]: ./struct.Vec.html#method.push
512/// [`insert`]: ./struct.Vec.html#method.insert
513/// [`reserve`]: ./struct.Vec.html#method.reserve
514/// [owned slice]: https://doc.rust-lang.org/nightly/std/boxed/struct.Box.html
515pub struct Vec<'bump, T: 'bump> {
516 buf: RawVec<'bump, T>,
517 len: usize,
518}
519
520////////////////////////////////////////////////////////////////////////////////
521// Inherent methods
522////////////////////////////////////////////////////////////////////////////////
523
524impl<'bump, T: 'bump> Vec<'bump, T> {
525 /// Constructs a new, empty `Vec<'bump, T>`.
526 ///
527 /// The vector will not allocate until elements are pushed onto it.
528 ///
529 /// # Examples
530 ///
531 /// ```
532 /// # #![allow(unused_mut)]
533 /// use bumpalo::{Bump, collections::Vec};
534 ///
535 /// let b = Bump::new();
536 /// let mut vec: Vec<i32> = Vec::new_in(&b);
537 /// ```
538 #[inline]
539 pub fn new_in(bump: &'bump Bump) -> Vec<'bump, T> {
540 Vec {
541 buf: RawVec::new_in(bump),
542 len: 0,
543 }
544 }
545
546 /// Constructs a new, empty `Vec<'bump, T>` with the specified capacity.
547 ///
548 /// The vector will be able to hold exactly `capacity` elements without
549 /// reallocating. If `capacity` is 0, the vector will not allocate.
550 ///
551 /// It is important to note that although the returned vector has the
552 /// *capacity* specified, the vector will have a zero *length*. For an
553 /// explanation of the difference between length and capacity, see
554 /// *[Capacity and reallocation]*.
555 ///
556 /// [Capacity and reallocation]: #capacity-and-reallocation
557 ///
558 /// # Examples
559 ///
560 /// ```
561 /// use bumpalo::{Bump, collections::Vec};
562 ///
563 /// let b = Bump::new();
564 ///
565 /// let mut vec = Vec::with_capacity_in(10, &b);
566 ///
567 /// // The vector contains no items, even though it has capacity for more
568 /// assert_eq!(vec.len(), 0);
569 ///
570 /// // These are all done without reallocating...
571 /// for i in 0..10 {
572 /// vec.push(i);
573 /// }
574 ///
575 /// // ...but this may make the vector reallocate
576 /// vec.push(11);
577 /// ```
578 #[inline]
579 pub fn with_capacity_in(capacity: usize, bump: &'bump Bump) -> Vec<'bump, T> {
580 Vec {
581 buf: RawVec::with_capacity_in(capacity, bump),
582 len: 0,
583 }
584 }
585
586 /// Construct a new `Vec` from the given iterator's items.
587 ///
588 /// # Examples
589 ///
590 /// ```
591 /// use bumpalo::{Bump, collections::Vec};
592 /// use std::iter;
593 ///
594 /// let b = Bump::new();
595 /// let v = Vec::from_iter_in(iter::repeat(7).take(3), &b);
596 /// assert_eq!(v, [7, 7, 7]);
597 /// ```
598 pub fn from_iter_in<I: IntoIterator<Item = T>>(iter: I, bump: &'bump Bump) -> Vec<'bump, T> {
599 let mut v = Vec::new_in(bump);
600 v.extend(iter);
601 v
602 }
603
604 /// Creates a `Vec<'bump, T>` directly from the raw components of another vector.
605 ///
606 /// # Safety
607 ///
608 /// This is highly unsafe, due to the number of invariants that aren't
609 /// checked:
610 ///
611 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<'bump, T>`
612 /// (at least, it's highly likely to be incorrect if it wasn't).
613 /// * `ptr`'s `T` needs to have the same size and alignment as it was allocated with.
614 /// * `length` needs to be less than or equal to `capacity`.
615 /// * `capacity` needs to be the capacity that the pointer was allocated with.
616 ///
617 /// Violating these may cause problems like corrupting the allocator's
618 /// internal data structures. For example it is **not** safe
619 /// to build a `Vec<u8>` from a pointer to a C `char` array and a `size_t`.
620 ///
621 /// The ownership of `ptr` is effectively transferred to the
622 /// `Vec<'bump, T>` which may then deallocate, reallocate or change the
623 /// contents of memory pointed to by the pointer at will. Ensure
624 /// that nothing else uses the pointer after calling this
625 /// function.
626 ///
627 /// [`String`]: https://doc.rust-lang.org/nightly/std/string/struct.String.html
628 ///
629 /// # Examples
630 ///
631 /// ```
632 /// use bumpalo::{Bump, collections::Vec};
633 ///
634 /// use std::ptr;
635 /// use std::mem;
636 ///
637 /// let b = Bump::new();
638 ///
639 /// let mut v = bumpalo::vec![in &b; 1, 2, 3];
640 ///
641 /// // Pull out the various important pieces of information about `v`
642 /// let p = v.as_mut_ptr();
643 /// let len = v.len();
644 /// let cap = v.capacity();
645 ///
646 /// unsafe {
647 /// // Cast `v` into the void: no destructor run, so we are in
648 /// // complete control of the allocation to which `p` points.
649 /// mem::forget(v);
650 ///
651 /// // Overwrite memory with 4, 5, 6
652 /// for i in 0..len as isize {
653 /// ptr::write(p.offset(i), 4 + i);
654 /// }
655 ///
656 /// // Put everything back together into a Vec
657 /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, &b);
658 /// assert_eq!(rebuilt, [4, 5, 6]);
659 /// }
660 /// ```
661 pub unsafe fn from_raw_parts_in(
662 ptr: *mut T,
663 length: usize,
664 capacity: usize,
665 bump: &'bump Bump,
666 ) -> Vec<'bump, T> {
667 Vec {
668 buf: RawVec::from_raw_parts_in(ptr, capacity, bump),
669 len: length,
670 }
671 }
672
673 /// Returns the number of elements the vector can hold without
674 /// reallocating.
675 ///
676 /// # Examples
677 ///
678 /// ```
679 /// use bumpalo::{Bump, collections::Vec};
680 ///
681 /// let b = Bump::new();
682 /// let vec: Vec<i32> = Vec::with_capacity_in(10, &b);
683 /// assert_eq!(vec.capacity(), 10);
684 /// ```
685 #[inline]
686 pub fn capacity(&self) -> usize {
687 self.buf.cap()
688 }
689
690 /// Reserves capacity for at least `additional` more elements to be inserted
691 /// in the given `Vec<'bump, T>`. The collection may reserve more space to avoid
692 /// frequent reallocations. After calling `reserve`, capacity will be
693 /// greater than or equal to `self.len() + additional`. Does nothing if
694 /// capacity is already sufficient.
695 ///
696 /// # Panics
697 ///
698 /// Panics if the new capacity overflows `usize`.
699 ///
700 /// # Examples
701 ///
702 /// ```
703 /// use bumpalo::{Bump, collections::Vec};
704 ///
705 /// let b = Bump::new();
706 /// let mut vec = bumpalo::vec![in &b; 1];
707 /// vec.reserve(10);
708 /// assert!(vec.capacity() >= 11);
709 /// ```
710 pub fn reserve(&mut self, additional: usize) {
711 self.buf.reserve(self.len, additional);
712 }
713
714 /// Reserves the minimum capacity for exactly `additional` more elements to
715 /// be inserted in the given `Vec<'bump, T>`. After calling `reserve_exact`,
716 /// capacity will be greater than or equal to `self.len() + additional`.
717 /// Does nothing if the capacity is already sufficient.
718 ///
719 /// Note that the allocator may give the collection more space than it
720 /// requests. Therefore capacity can not be relied upon to be precisely
721 /// minimal. Prefer `reserve` if future insertions are expected.
722 ///
723 /// # Panics
724 ///
725 /// Panics if the new capacity overflows `usize`.
726 ///
727 /// # Examples
728 ///
729 /// ```
730 /// use bumpalo::{Bump, collections::Vec};
731 ///
732 /// let b = Bump::new();
733 /// let mut vec = bumpalo::vec![in &b; 1];
734 /// vec.reserve_exact(10);
735 /// assert!(vec.capacity() >= 11);
736 /// ```
737 pub fn reserve_exact(&mut self, additional: usize) {
738 self.buf.reserve_exact(self.len, additional);
739 }
740
741 /// Shrinks the capacity of the vector as much as possible.
742 ///
743 /// It will drop down as close as possible to the length but the allocator
744 /// may still inform the vector that there is space for a few more elements.
745 ///
746 /// # Examples
747 ///
748 /// ```
749 /// use bumpalo::{Bump, collections::Vec};
750 ///
751 /// let b = Bump::new();
752 ///
753 /// let mut vec = Vec::with_capacity_in(10, &b);
754 /// vec.extend([1, 2, 3].iter().cloned());
755 /// assert_eq!(vec.capacity(), 10);
756 /// vec.shrink_to_fit();
757 /// assert!(vec.capacity() >= 3);
758 /// ```
759 pub fn shrink_to_fit(&mut self) {
760 if self.capacity() != self.len {
761 self.buf.shrink_to_fit(self.len);
762 }
763 }
764
765 /// Converts the vector into `&'bump [T]`.
766 ///
767 /// # Examples
768 ///
769 /// ```
770 /// use bumpalo::{Bump, collections::Vec};
771 ///
772 /// let b = Bump::new();
773 /// let v = bumpalo::vec![in &b; 1, 2, 3];
774 ///
775 /// let slice = v.into_bump_slice();
776 /// assert_eq!(slice, [1, 2, 3]);
777 /// ```
778 pub fn into_bump_slice(self) -> &'bump [T] {
779 unsafe {
780 let ptr = self.as_ptr();
781 let len = self.len();
782 mem::forget(self);
783 slice::from_raw_parts(ptr, len)
784 }
785 }
786
787 /// Converts the vector into `&'bump mut [T]`.
788 ///
789 /// # Examples
790 ///
791 /// ```
792 /// use bumpalo::{Bump, collections::Vec};
793 ///
794 /// let b = Bump::new();
795 /// let v = bumpalo::vec![in &b; 1, 2, 3];
796 ///
797 /// let mut slice = v.into_bump_slice_mut();
798 ///
799 /// slice[0] = 3;
800 /// slice[2] = 1;
801 ///
802 /// assert_eq!(slice, [3, 2, 1]);
803 /// ```
804 pub fn into_bump_slice_mut(mut self) -> &'bump mut [T] {
805 let ptr = self.as_mut_ptr();
806 let len = self.len();
807 mem::forget(self);
808
809 unsafe {
810 slice::from_raw_parts_mut(ptr, len)
811 }
812 }
813
814 /// Shortens the vector, keeping the first `len` elements and dropping
815 /// the rest.
816 ///
817 /// If `len` is greater than the vector's current length, this has no
818 /// effect.
819 ///
820 /// The [`drain`] method can emulate `truncate`, but causes the excess
821 /// elements to be returned instead of dropped.
822 ///
823 /// Note that this method has no effect on the allocated capacity
824 /// of the vector.
825 ///
826 /// # Examples
827 ///
828 /// Truncating a five element vector to two elements:
829 ///
830 /// ```
831 /// use bumpalo::{Bump, collections::Vec};
832 ///
833 /// let b = Bump::new();
834 ///
835 /// let mut vec = bumpalo::vec![in &b; 1, 2, 3, 4, 5];
836 /// vec.truncate(2);
837 /// assert_eq!(vec, [1, 2]);
838 /// ```
839 ///
840 /// No truncation occurs when `len` is greater than the vector's current
841 /// length:
842 ///
843 /// ```
844 /// use bumpalo::{Bump, collections::Vec};
845 ///
846 /// let b = Bump::new();
847 ///
848 /// let mut vec = bumpalo::vec![in &b; 1, 2, 3];
849 /// vec.truncate(8);
850 /// assert_eq!(vec, [1, 2, 3]);
851 /// ```
852 ///
853 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
854 /// method.
855 ///
856 /// ```
857 /// use bumpalo::{Bump, collections::Vec};
858 ///
859 /// let b = Bump::new();
860 ///
861 /// let mut vec = bumpalo::vec![in &b; 1, 2, 3];
862 /// vec.truncate(0);
863 /// assert_eq!(vec, []);
864 /// ```
865 ///
866 /// [`clear`]: #method.clear
867 /// [`drain`]: #method.drain
868 pub fn truncate(&mut self, len: usize) {
869 let current_len = self.len;
870 unsafe {
871 let mut ptr = self.as_mut_ptr().add(self.len);
872 // Set the final length at the end, keeping in mind that
873 // dropping an element might panic. Works around a missed
874 // optimization, as seen in the following issue:
875 // https://github.com/rust-lang/rust/issues/51802
876 let mut local_len = SetLenOnDrop::new(&mut self.len);
877
878 // drop any extra elements
879 for _ in len..current_len {
880 local_len.decrement_len(1);
881 ptr = ptr.offset(-1);
882 ptr::drop_in_place(ptr);
883 }
884 }
885 }
886
887 /// Extracts a slice containing the entire vector.
888 ///
889 /// Equivalent to `&s[..]`.
890 ///
891 /// # Examples
892 ///
893 /// ```
894 /// use bumpalo::{Bump, collections::Vec};
895 /// use std::io::{self, Write};
896 ///
897 /// let b = Bump::new();
898 ///
899 /// let buffer = bumpalo::vec![in &b; 1, 2, 3, 5, 8];
900 /// io::sink().write(buffer.as_slice()).unwrap();
901 /// ```
902 #[inline]
903 pub fn as_slice(&self) -> &[T] {
904 self
905 }
906
907 /// Extracts a mutable slice of the entire vector.
908 ///
909 /// Equivalent to `&mut s[..]`.
910 ///
911 /// # Examples
912 ///
913 /// ```
914 /// use bumpalo::{Bump, collections::Vec};
915 /// use std::io::{self, Read};
916 ///
917 /// let b = Bump::new();
918 /// let mut buffer = bumpalo::vec![in &b; 0; 3];
919 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
920 /// ```
921 #[inline]
922 pub fn as_mut_slice(&mut self) -> &mut [T] {
923 self
924 }
925
926 /// Sets the length of a vector.
927 ///
928 /// This will explicitly set the size of the vector, without actually
929 /// modifying its buffers, so it is up to the caller to ensure that the
930 /// vector is actually the specified size.
931 ///
932 /// # Safety
933 ///
934 /// - `new_len` must be less than or equal to [`capacity()`].
935 /// - The elements at `old_len..new_len` must be initialized.
936 ///
937 /// # Examples
938 ///
939 /// ```
940 /// use bumpalo::{Bump, collections::Vec};
941 ///
942 /// use std::ptr;
943 ///
944 /// let b = Bump::new();
945 ///
946 /// let mut vec = bumpalo::vec![in &b; 'r', 'u', 's', 't'];
947 ///
948 /// unsafe {
949 /// ptr::drop_in_place(&mut vec[3]);
950 /// vec.set_len(3);
951 /// }
952 /// assert_eq!(vec, ['r', 'u', 's']);
953 /// ```
954 ///
955 /// In this example, there is a memory leak since the memory locations
956 /// owned by the inner vectors were not freed prior to the `set_len` call:
957 ///
958 /// ```
959 /// use bumpalo::{Bump, collections::Vec};
960 ///
961 /// let b = Bump::new();
962 ///
963 /// let mut vec = bumpalo::vec![in &b;
964 /// bumpalo::vec![in &b; 1, 0, 0],
965 /// bumpalo::vec![in &b; 0, 1, 0],
966 /// bumpalo::vec![in &b; 0, 0, 1]];
967 /// unsafe {
968 /// vec.set_len(0);
969 /// }
970 /// ```
971 ///
972 /// In this example, the vector gets expanded from zero to four items
973 /// without any memory allocations occurring, resulting in vector
974 /// values of unallocated memory:
975 ///
976 /// ```
977 /// use bumpalo::{Bump, collections::Vec};
978 ///
979 /// let b = Bump::new();
980 ///
981 /// let mut vec: Vec<char> = Vec::new_in(&b);
982 ///
983 /// unsafe {
984 /// vec.set_len(4);
985 /// }
986 /// ```
987 #[inline]
988 pub unsafe fn set_len(&mut self, new_len: usize) {
989 self.len = new_len;
990 }
991
992 /// Removes an element from the vector and returns it.
993 ///
994 /// The removed element is replaced by the last element of the vector.
995 ///
996 /// This does not preserve ordering, but is O(1).
997 ///
998 /// # Panics
999 ///
1000 /// Panics if `index` is out of bounds.
1001 ///
1002 /// # Examples
1003 ///
1004 /// ```
1005 /// use bumpalo::{Bump, collections::Vec};
1006 ///
1007 /// let b = Bump::new();
1008 ///
1009 /// let mut v = bumpalo::vec![in &b; "foo", "bar", "baz", "qux"];
1010 ///
1011 /// assert_eq!(v.swap_remove(1), "bar");
1012 /// assert_eq!(v, ["foo", "qux", "baz"]);
1013 ///
1014 /// assert_eq!(v.swap_remove(0), "foo");
1015 /// assert_eq!(v, ["baz", "qux"]);
1016 /// ```
1017 #[inline]
1018 pub fn swap_remove(&mut self, index: usize) -> T {
1019 unsafe {
1020 // We replace self[index] with the last element. Note that if the
1021 // bounds check on hole succeeds there must be a last element (which
1022 // can be self[index] itself).
1023 let hole: *mut T = &mut self[index];
1024 let last = ptr::read(self.get_unchecked(self.len - 1));
1025 self.len -= 1;
1026 ptr::replace(hole, last)
1027 }
1028 }
1029
1030 /// Inserts an element at position `index` within the vector, shifting all
1031 /// elements after it to the right.
1032 ///
1033 /// # Panics
1034 ///
1035 /// Panics if `index > len`.
1036 ///
1037 /// # Examples
1038 ///
1039 /// ```
1040 /// use bumpalo::{Bump, collections::Vec};
1041 ///
1042 /// let b = Bump::new();
1043 ///
1044 /// let mut vec = bumpalo::vec![in &b; 1, 2, 3];
1045 /// vec.insert(1, 4);
1046 /// assert_eq!(vec, [1, 4, 2, 3]);
1047 /// vec.insert(4, 5);
1048 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1049 /// ```
1050 pub fn insert(&mut self, index: usize, element: T) {
1051 let len = self.len();
1052 assert!(index <= len);
1053
1054 // space for the new element
1055 if len == self.buf.cap() {
1056 self.reserve(1);
1057 }
1058
1059 unsafe {
1060 // infallible
1061 // The spot to put the new value
1062 {
1063 let p = self.as_mut_ptr().add(index);
1064 // Shift everything over to make space. (Duplicating the
1065 // `index`th element into two consecutive places.)
1066 ptr::copy(p, p.offset(1), len - index);
1067 // Write it in, overwriting the first copy of the `index`th
1068 // element.
1069 ptr::write(p, element);
1070 }
1071 self.set_len(len + 1);
1072 }
1073 }
1074
1075 /// Removes and returns the element at position `index` within the vector,
1076 /// shifting all elements after it to the left.
1077 ///
1078 /// # Panics
1079 ///
1080 /// Panics if `index` is out of bounds.
1081 ///
1082 /// # Examples
1083 ///
1084 /// ```
1085 /// use bumpalo::{Bump, collections::Vec};
1086 ///
1087 /// let b = Bump::new();
1088 ///
1089 /// let mut v = bumpalo::vec![in &b; 1, 2, 3];
1090 /// assert_eq!(v.remove(1), 2);
1091 /// assert_eq!(v, [1, 3]);
1092 /// ```
1093 pub fn remove(&mut self, index: usize) -> T {
1094 let len = self.len();
1095 assert!(index < len);
1096 unsafe {
1097 // infallible
1098 let ret;
1099 {
1100 // the place we are taking from.
1101 let ptr = self.as_mut_ptr().add(index);
1102 // copy it out, unsafely having a copy of the value on
1103 // the stack and in the vector at the same time.
1104 ret = ptr::read(ptr);
1105
1106 // Shift everything down to fill in that spot.
1107 ptr::copy(ptr.offset(1), ptr, len - index - 1);
1108 }
1109 self.set_len(len - 1);
1110 ret
1111 }
1112 }
1113
1114 /// Retains only the elements specified by the predicate.
1115 ///
1116 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
1117 /// This method operates in place and preserves the order of the retained
1118 /// elements.
1119 ///
1120 /// # Examples
1121 ///
1122 /// ```
1123 /// use bumpalo::{Bump, collections::Vec};
1124 ///
1125 /// let b = Bump::new();
1126 ///
1127 /// let mut vec = bumpalo::vec![in &b; 1, 2, 3, 4];
1128 /// vec.retain(|&x| x%2 == 0);
1129 /// assert_eq!(vec, [2, 4]);
1130 /// ```
1131 pub fn retain<F>(&mut self, mut f: F)
1132 where
1133 F: FnMut(&T) -> bool,
1134 {
1135 self.drain_filter(|x| !f(x));
1136 }
1137
1138 fn drain_filter<'a, F>(&'a mut self, filter: F) -> DrainFilter<'a, 'bump, T, F>
1139 where
1140 F: FnMut(&mut T) -> bool,
1141 {
1142 let old_len = self.len();
1143
1144 // Guard against us getting leaked (leak amplification)
1145 unsafe {
1146 self.set_len(0);
1147 }
1148
1149 DrainFilter {
1150 vec: self,
1151 idx: 0,
1152 del: 0,
1153 old_len,
1154 pred: filter,
1155 }
1156 }
1157
1158 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1159 /// key.
1160 ///
1161 /// If the vector is sorted, this removes all duplicates.
1162 ///
1163 /// # Examples
1164 ///
1165 /// ```
1166 /// use bumpalo::{Bump, collections::Vec};
1167 ///
1168 /// let b = Bump::new();
1169 ///
1170 /// let mut vec = bumpalo::vec![in &b; 10, 20, 21, 30, 20];
1171 ///
1172 /// vec.dedup_by_key(|i| *i / 10);
1173 ///
1174 /// assert_eq!(vec, [10, 20, 30, 20]);
1175 /// ```
1176 #[inline]
1177 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1178 where
1179 F: FnMut(&mut T) -> K,
1180 K: PartialEq,
1181 {
1182 self.dedup_by(|a, b| key(a) == key(b))
1183 }
1184
1185 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1186 /// relation.
1187 ///
1188 /// The `same_bucket` function is passed references to two elements from the vector and
1189 /// must determine if the elements compare equal. The elements are passed in opposite order
1190 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1191 ///
1192 /// If the vector is sorted, this removes all duplicates.
1193 ///
1194 /// # Examples
1195 ///
1196 /// ```
1197 /// use bumpalo::{Bump, collections::Vec};
1198 ///
1199 /// let b = Bump::new();
1200 ///
1201 /// let mut vec = bumpalo::vec![in &b; "foo", "bar", "Bar", "baz", "bar"];
1202 ///
1203 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1204 ///
1205 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1206 /// ```
1207 pub fn dedup_by<F>(&mut self, same_bucket: F)
1208 where
1209 F: FnMut(&mut T, &mut T) -> bool,
1210 {
1211 let len = {
1212 let (dedup, _) = partition_dedup_by(self.as_mut_slice(), same_bucket);
1213 dedup.len()
1214 };
1215 self.truncate(len);
1216 }
1217
1218 /// Appends an element to the back of a collection.
1219 ///
1220 /// # Panics
1221 ///
1222 /// Panics if the number of elements in the vector overflows a `usize`.
1223 ///
1224 /// # Examples
1225 ///
1226 /// ```
1227 /// use bumpalo::{Bump, collections::Vec};
1228 ///
1229 /// let b = Bump::new();
1230 ///
1231 /// let mut vec = bumpalo::vec![in &b; 1, 2];
1232 /// vec.push(3);
1233 /// assert_eq!(vec, [1, 2, 3]);
1234 /// ```
1235 #[inline]
1236 pub fn push(&mut self, value: T) {
1237 // This will panic or abort if we would allocate > isize::MAX bytes
1238 // or if the length increment would overflow for zero-sized types.
1239 if self.len == self.buf.cap() {
1240 self.reserve(1);
1241 }
1242 unsafe {
1243 let end = self.as_mut_ptr().add(self.len);
1244 ptr::write(end, value);
1245 self.len += 1;
1246 }
1247 }
1248
1249 /// Removes the last element from a vector and returns it, or [`None`] if it
1250 /// is empty.
1251 ///
1252 /// [`None`]: https://doc.rust-lang.org/nightly/std/option/enum.Option.html#variant.None
1253 ///
1254 /// # Examples
1255 ///
1256 /// ```
1257 /// use bumpalo::{Bump, collections::Vec};
1258 ///
1259 /// let b = Bump::new();
1260 ///
1261 /// let mut vec = bumpalo::vec![in &b; 1, 2, 3];
1262 /// assert_eq!(vec.pop(), Some(3));
1263 /// assert_eq!(vec, [1, 2]);
1264 /// ```
1265 #[inline]
1266 pub fn pop(&mut self) -> Option<T> {
1267 if self.len == 0 {
1268 None
1269 } else {
1270 unsafe {
1271 self.len -= 1;
1272 Some(ptr::read(self.get_unchecked(self.len())))
1273 }
1274 }
1275 }
1276
1277 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1278 ///
1279 /// # Panics
1280 ///
1281 /// Panics if the number of elements in the vector overflows a `usize`.
1282 ///
1283 /// # Examples
1284 ///
1285 /// ```
1286 /// use bumpalo::{Bump, collections::Vec};
1287 ///
1288 /// let b = Bump::new();
1289 ///
1290 /// let mut vec = bumpalo::vec![in &b; 1, 2, 3];
1291 /// let mut vec2 = bumpalo::vec![in &b; 4, 5, 6];
1292 /// vec.append(&mut vec2);
1293 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1294 /// assert_eq!(vec2, []);
1295 /// ```
1296 #[inline]
1297 pub fn append(&mut self, other: &mut Self) {
1298 unsafe {
1299 self.append_elements(other.as_slice() as _);
1300 other.set_len(0);
1301 }
1302 }
1303
1304 /// Appends elements to `Self` from other buffer.
1305 #[inline]
1306 unsafe fn append_elements(&mut self, other: *const [T]) {
1307 let count = (*other).len();
1308 self.reserve(count);
1309 let len = self.len();
1310 ptr::copy_nonoverlapping(other as *const T, self.get_unchecked_mut(len), count);
1311 self.len += count;
1312 }
1313
1314 /// Creates a draining iterator that removes the specified range in the vector
1315 /// and yields the removed items.
1316 ///
1317 /// Note 1: The element range is removed even if the iterator is only
1318 /// partially consumed or not consumed at all.
1319 ///
1320 /// Note 2: It is unspecified how many elements are removed from the vector
1321 /// if the `Drain` value is leaked.
1322 ///
1323 /// # Panics
1324 ///
1325 /// Panics if the starting point is greater than the end point or if
1326 /// the end point is greater than the length of the vector.
1327 ///
1328 /// # Examples
1329 ///
1330 /// ```
1331 /// use bumpalo::{Bump, collections::Vec};
1332 ///
1333 /// let b = Bump::new();
1334 ///
1335 /// let mut v = bumpalo::vec![in &b; 1, 2, 3];
1336 ///
1337 /// let mut u: Vec<_> = Vec::new_in(&b);
1338 /// u.extend(v.drain(1..));
1339 ///
1340 /// assert_eq!(v, &[1]);
1341 /// assert_eq!(u, &[2, 3]);
1342 ///
1343 /// // A full range clears the vector
1344 /// v.drain(..);
1345 /// assert_eq!(v, &[]);
1346 /// ```
1347 pub fn drain<R>(&mut self, range: R) -> Drain<T>
1348 where
1349 R: RangeBounds<usize>,
1350 {
1351 // Memory safety
1352 //
1353 // When the Drain is first created, it shortens the length of
1354 // the source vector to make sure no uninitialized or moved-from elements
1355 // are accessible at all if the Drain's destructor never gets to run.
1356 //
1357 // Drain will ptr::read out the values to remove.
1358 // When finished, remaining tail of the vec is copied back to cover
1359 // the hole, and the vector length is restored to the new length.
1360 //
1361 let len = self.len();
1362 let start = match range.start_bound() {
1363 Included(&n) => n,
1364 Excluded(&n) => n + 1,
1365 Unbounded => 0,
1366 };
1367 let end = match range.end_bound() {
1368 Included(&n) => n + 1,
1369 Excluded(&n) => n,
1370 Unbounded => len,
1371 };
1372 assert!(start <= end);
1373 assert!(end <= len);
1374
1375 unsafe {
1376 // set self.vec length's to start, to be safe in case Drain is leaked
1377 self.set_len(start);
1378 // Use the borrow in the IterMut to indicate borrowing behavior of the
1379 // whole Drain iterator (like &mut T).
1380 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start);
1381 Drain {
1382 tail_start: end,
1383 tail_len: len - end,
1384 iter: range_slice.iter(),
1385 vec: NonNull::from(self),
1386 }
1387 }
1388 }
1389
1390 /// Clears the vector, removing all values.
1391 ///
1392 /// Note that this method has no effect on the allocated capacity
1393 /// of the vector.
1394 ///
1395 /// # Examples
1396 ///
1397 /// ```
1398 /// use bumpalo::{Bump, collections::Vec};
1399 ///
1400 /// let b = Bump::new();
1401 ///
1402 /// let mut v = bumpalo::vec![in &b; 1, 2, 3];
1403 ///
1404 /// v.clear();
1405 ///
1406 /// assert!(v.is_empty());
1407 /// ```
1408 #[inline]
1409 pub fn clear(&mut self) {
1410 self.truncate(0)
1411 }
1412
1413 /// Returns the number of elements in the vector, also referred to
1414 /// as its 'length'.
1415 ///
1416 /// # Examples
1417 ///
1418 /// ```
1419 /// use bumpalo::{Bump, collections::Vec};
1420 ///
1421 /// let b = Bump::new();
1422 ///
1423 /// let a = bumpalo::vec![in &b; 1, 2, 3];
1424 /// assert_eq!(a.len(), 3);
1425 /// ```
1426 #[inline]
1427 pub fn len(&self) -> usize {
1428 self.len
1429 }
1430
1431 /// Returns `true` if the vector contains no elements.
1432 ///
1433 /// # Examples
1434 ///
1435 /// ```
1436 /// use bumpalo::{Bump, collections::Vec};
1437 ///
1438 /// let b = Bump::new();
1439 ///
1440 /// let mut v = Vec::new_in(&b);
1441 /// assert!(v.is_empty());
1442 ///
1443 /// v.push(1);
1444 /// assert!(!v.is_empty());
1445 /// ```
1446 pub fn is_empty(&self) -> bool {
1447 self.len() == 0
1448 }
1449
1450 /// Splits the collection into two at the given index.
1451 ///
1452 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1453 /// and the returned `Self` contains elements `[at, len)`.
1454 ///
1455 /// Note that the capacity of `self` does not change.
1456 ///
1457 /// # Panics
1458 ///
1459 /// Panics if `at > len`.
1460 ///
1461 /// # Examples
1462 ///
1463 /// ```
1464 /// use bumpalo::{Bump, collections::Vec};
1465 ///
1466 /// let b = Bump::new();
1467 ///
1468 /// let mut vec = bumpalo::vec![in &b; 1,2,3];
1469 /// let vec2 = vec.split_off(1);
1470 /// assert_eq!(vec, [1]);
1471 /// assert_eq!(vec2, [2, 3]);
1472 /// ```
1473 #[inline]
1474 pub fn split_off(&mut self, at: usize) -> Self {
1475 assert!(at <= self.len(), "`at` out of bounds");
1476
1477 let other_len = self.len - at;
1478 let mut other = Vec::with_capacity_in(other_len, self.buf.bump());
1479
1480 // Unsafely `set_len` and copy items to `other`.
1481 unsafe {
1482 self.set_len(at);
1483 other.set_len(other_len);
1484
1485 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
1486 }
1487 other
1488 }
1489}
1490
1491impl<'bump, T: 'bump + Clone> Vec<'bump, T> {
1492 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1493 ///
1494 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1495 /// difference, with each additional slot filled with `value`.
1496 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1497 ///
1498 /// This method requires [`Clone`] to be able clone the passed value. If
1499 /// you need more flexibility (or want to rely on [`Default`] instead of
1500 /// [`Clone`]), use [`resize_with`].
1501 ///
1502 /// # Examples
1503 ///
1504 /// ```
1505 /// use bumpalo::{Bump, collections::Vec};
1506 ///
1507 /// let b = Bump::new();
1508 ///
1509 /// let mut vec = bumpalo::vec![in &b; "hello"];
1510 /// vec.resize(3, "world");
1511 /// assert_eq!(vec, ["hello", "world", "world"]);
1512 ///
1513 /// let mut vec = bumpalo::vec![in &b; 1, 2, 3, 4];
1514 /// vec.resize(2, 0);
1515 /// assert_eq!(vec, [1, 2]);
1516 /// ```
1517 ///
1518 /// [`Clone`]: https://doc.rust-lang.org/nightly/std/clone/trait.Clone.html
1519 /// [`Default`]: https://doc.rust-lang.org/nightly/std/default/trait.Default.html
1520 /// [`resize_with`]: #method.resize_with
1521 pub fn resize(&mut self, new_len: usize, value: T) {
1522 let len = self.len();
1523
1524 if new_len > len {
1525 self.extend_with(new_len - len, ExtendElement(value))
1526 } else {
1527 self.truncate(new_len);
1528 }
1529 }
1530
1531 /// Clones and appends all elements in a slice to the `Vec`.
1532 ///
1533 /// Iterates over the slice `other`, clones each element, and then appends
1534 /// it to this `Vec`. The `other` vector is traversed in-order.
1535 ///
1536 /// Note that this function is same as [`extend`] except that it is
1537 /// specialized to work with slices instead. If and when Rust gets
1538 /// specialization this function will likely be deprecated (but still
1539 /// available).
1540 ///
1541 /// # Examples
1542 ///
1543 /// ```
1544 /// use bumpalo::{Bump, collections::Vec};
1545 ///
1546 /// let b = Bump::new();
1547 ///
1548 /// let mut vec = bumpalo::vec![in &b; 1];
1549 /// vec.extend_from_slice(&[2, 3, 4]);
1550 /// assert_eq!(vec, [1, 2, 3, 4]);
1551 /// ```
1552 ///
1553 /// [`extend`]: #method.extend
1554 pub fn extend_from_slice(&mut self, other: &[T]) {
1555 self.extend(other.iter().cloned())
1556 }
1557}
1558
1559// This code generalises `extend_with_{element,default}`.
1560trait ExtendWith<T> {
1561 fn next(&mut self) -> T;
1562 fn last(self) -> T;
1563}
1564
1565struct ExtendElement<T>(T);
1566impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1567 fn next(&mut self) -> T {
1568 self.0.clone()
1569 }
1570 fn last(self) -> T {
1571 self.0
1572 }
1573}
1574
1575impl<'bump, T: 'bump> Vec<'bump, T> {
1576 /// Extend the vector by `n` values, using the given generator.
1577 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
1578 self.reserve(n);
1579
1580 unsafe {
1581 let mut ptr = self.as_mut_ptr().add(self.len());
1582 // Use SetLenOnDrop to work around bug where compiler
1583 // may not realize the store through `ptr` through self.set_len()
1584 // don't alias.
1585 let mut local_len = SetLenOnDrop::new(&mut self.len);
1586
1587 // Write all elements except the last one
1588 for _ in 1..n {
1589 ptr::write(ptr, value.next());
1590 ptr = ptr.offset(1);
1591 // Increment the length in every step in case next() panics
1592 local_len.increment_len(1);
1593 }
1594
1595 if n > 0 {
1596 // We can write the last element directly without cloning needlessly
1597 ptr::write(ptr, value.last());
1598 local_len.increment_len(1);
1599 }
1600
1601 // len set by scope guard
1602 }
1603 }
1604}
1605
1606// Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1607//
1608// The idea is: The length field in SetLenOnDrop is a local variable
1609// that the optimizer will see does not alias with any stores through the Vec's data
1610// pointer. This is a workaround for alias analysis issue #32155
1611struct SetLenOnDrop<'a> {
1612 len: &'a mut usize,
1613 local_len: usize,
1614}
1615
1616impl<'a> SetLenOnDrop<'a> {
1617 #[inline]
1618 fn new(len: &'a mut usize) -> Self {
1619 SetLenOnDrop {
1620 local_len: *len,
1621 len,
1622 }
1623 }
1624
1625 #[inline]
1626 fn increment_len(&mut self, increment: usize) {
1627 self.local_len += increment;
1628 }
1629
1630 #[inline]
1631 fn decrement_len(&mut self, decrement: usize) {
1632 self.local_len -= decrement;
1633 }
1634}
1635
1636impl<'a> Drop for SetLenOnDrop<'a> {
1637 #[inline]
1638 fn drop(&mut self) {
1639 *self.len = self.local_len;
1640 }
1641}
1642
1643impl<'bump, T: 'bump + PartialEq> Vec<'bump, T> {
1644 /// Removes consecutive repeated elements in the vector according to the
1645 /// [`PartialEq`] trait implementation.
1646 ///
1647 /// If the vector is sorted, this removes all duplicates.
1648 ///
1649 /// # Examples
1650 ///
1651 /// ```
1652 /// use bumpalo::{Bump, collections::Vec};
1653 ///
1654 /// let b = Bump::new();
1655 ///
1656 /// let mut vec = bumpalo::vec![in &b; 1, 2, 2, 3, 2];
1657 ///
1658 /// vec.dedup();
1659 ///
1660 /// assert_eq!(vec, [1, 2, 3, 2]);
1661 /// ```
1662 #[inline]
1663 pub fn dedup(&mut self) {
1664 self.dedup_by(|a, b| a == b)
1665 }
1666}
1667
1668////////////////////////////////////////////////////////////////////////////////
1669// Common trait implementations for Vec
1670////////////////////////////////////////////////////////////////////////////////
1671
1672impl<'bump, T: 'bump + Clone> Clone for Vec<'bump, T> {
1673 #[cfg(not(test))]
1674 fn clone(&self) -> Vec<'bump, T> {
1675 let mut v = Vec::with_capacity_in(self.len(), self.buf.bump());
1676 v.extend(self.iter().cloned());
1677 v
1678 }
1679
1680 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1681 // required for this method definition, is not available. Instead use the
1682 // `slice::to_vec` function which is only available with cfg(test)
1683 // NB see the slice::hack module in slice.rs for more information
1684 #[cfg(test)]
1685 fn clone(&self) -> Vec<'bump, T> {
1686 let mut v = Vec::new_in(self.buf.bump());
1687 v.extend(self.iter().cloned());
1688 v
1689 }
1690}
1691
1692impl<'bump, T: 'bump + Hash> Hash for Vec<'bump, T> {
1693 #[inline]
1694 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1695 Hash::hash(&**self, state)
1696 }
1697}
1698
1699impl<'bump, T, I> Index<I> for Vec<'bump, T>
1700where
1701 I: ::core::slice::SliceIndex<[T]>,
1702{
1703 type Output = I::Output;
1704
1705 #[inline]
1706 fn index(&self, index: I) -> &Self::Output {
1707 Index::index(&**self, index)
1708 }
1709}
1710
1711impl<'bump, T, I> IndexMut<I> for Vec<'bump, T>
1712where
1713 I: ::core::slice::SliceIndex<[T]>,
1714{
1715 #[inline]
1716 fn index_mut(&mut self, index: I) -> &mut Self::Output {
1717 IndexMut::index_mut(&mut **self, index)
1718 }
1719}
1720
1721impl<'bump, T: 'bump> ops::Deref for Vec<'bump, T> {
1722 type Target = [T];
1723
1724 fn deref(&self) -> &[T] {
1725 unsafe {
1726 let p = self.buf.ptr();
1727 // assume(!p.is_null());
1728 slice::from_raw_parts(p, self.len)
1729 }
1730 }
1731}
1732
1733impl<'bump, T: 'bump> ops::DerefMut for Vec<'bump, T> {
1734 fn deref_mut(&mut self) -> &mut [T] {
1735 unsafe {
1736 let ptr = self.buf.ptr();
1737 // assume(!ptr.is_null());
1738 slice::from_raw_parts_mut(ptr, self.len)
1739 }
1740 }
1741}
1742
1743impl<'bump, T: 'bump> IntoIterator for Vec<'bump, T> {
1744 type Item = T;
1745 type IntoIter = IntoIter<T>;
1746
1747 /// Creates a consuming iterator, that is, one that moves each value out of
1748 /// the vector (from start to end). The vector cannot be used after calling
1749 /// this.
1750 ///
1751 /// # Examples
1752 ///
1753 /// ```
1754 /// use bumpalo::{Bump, collections::Vec};
1755 ///
1756 /// let b = Bump::new();
1757 ///
1758 /// let v = bumpalo::vec![in &b; "a".to_string(), "b".to_string()];
1759 /// for s in v.into_iter() {
1760 /// // s has type String, not &String
1761 /// println!("{}", s);
1762 /// }
1763 /// ```
1764 #[inline]
1765 fn into_iter(mut self) -> IntoIter<T> {
1766 unsafe {
1767 let begin = self.as_mut_ptr();
1768 // assume(!begin.is_null());
1769 let end = if mem::size_of::<T>() == 0 {
1770 arith_offset(begin as *const i8, self.len() as isize) as *const T
1771 } else {
1772 begin.add(self.len()) as *const T
1773 };
1774 mem::forget(self);
1775 IntoIter {
1776 phantom: PhantomData,
1777 ptr: begin,
1778 end,
1779 }
1780 }
1781 }
1782}
1783
1784impl<'a, 'bump, T> IntoIterator for &'a Vec<'bump, T> {
1785 type Item = &'a T;
1786 type IntoIter = slice::Iter<'a, T>;
1787
1788 fn into_iter(self) -> slice::Iter<'a, T> {
1789 self.iter()
1790 }
1791}
1792
1793impl<'a, 'bump, T> IntoIterator for &'a mut Vec<'bump, T> {
1794 type Item = &'a mut T;
1795 type IntoIter = slice::IterMut<'a, T>;
1796
1797 fn into_iter(self) -> slice::IterMut<'a, T> {
1798 self.iter_mut()
1799 }
1800}
1801
1802impl<'bump, T: 'bump> Extend<T> for Vec<'bump, T> {
1803 #[inline]
1804 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1805 let iter = iter.into_iter();
1806 self.reserve(iter.size_hint().0);
1807
1808 for t in iter {
1809 self.push(t);
1810 }
1811 }
1812}
1813
1814impl<'bump, T: 'bump> Vec<'bump, T> {
1815 /// Creates a splicing iterator that replaces the specified range in the vector
1816 /// with the given `replace_with` iterator and yields the removed items.
1817 /// `replace_with` does not need to be the same length as `range`.
1818 ///
1819 /// Note 1: The element range is removed even if the iterator is not
1820 /// consumed until the end.
1821 ///
1822 /// Note 2: It is unspecified how many elements are removed from the vector,
1823 /// if the `Splice` value is leaked.
1824 ///
1825 /// Note 3: The input iterator `replace_with` is only consumed
1826 /// when the `Splice` value is dropped.
1827 ///
1828 /// Note 4: This is optimal if:
1829 ///
1830 /// * The tail (elements in the vector after `range`) is empty,
1831 /// * or `replace_with` yields fewer elements than `range`’s length
1832 /// * or the lower bound of its `size_hint()` is exact.
1833 ///
1834 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
1835 ///
1836 /// # Panics
1837 ///
1838 /// Panics if the starting point is greater than the end point or if
1839 /// the end point is greater than the length of the vector.
1840 ///
1841 /// # Examples
1842 ///
1843 /// ```
1844 /// use bumpalo::{Bump, collections::Vec};
1845 ///
1846 /// let b = Bump::new();
1847 ///
1848 /// let mut v = bumpalo::vec![in &b; 1, 2, 3];
1849 /// let new = [7, 8];
1850 /// let u: Vec<_> = Vec::from_iter_in(v.splice(..2, new.iter().cloned()), &b);
1851 /// assert_eq!(v, &[7, 8, 3]);
1852 /// assert_eq!(u, &[1, 2]);
1853 /// ```
1854 #[inline]
1855 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<I::IntoIter>
1856 where
1857 R: RangeBounds<usize>,
1858 I: IntoIterator<Item = T>,
1859 {
1860 Splice {
1861 drain: self.drain(range),
1862 replace_with: replace_with.into_iter(),
1863 }
1864 }
1865}
1866
1867/// Extend implementation that copies elements out of references before pushing them onto the Vec.
1868///
1869/// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
1870/// append the entire slice at once.
1871///
1872/// [`copy_from_slice`]: https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.copy_from_slice
1873impl<'a, 'bump, T: 'a + Copy> Extend<&'a T> for Vec<'bump, T> {
1874 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1875 self.extend(iter.into_iter().cloned())
1876 }
1877}
1878
1879macro_rules! __impl_slice_eq1 {
1880 ($Lhs: ty, $Rhs: ty) => {
1881 __impl_slice_eq1! { $Lhs, $Rhs, Sized }
1882 };
1883 ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
1884 impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs
1885 where
1886 A: PartialEq<B>,
1887 {
1888 #[inline]
1889 fn eq(&self, other: &$Rhs) -> bool {
1890 self[..] == other[..]
1891 }
1892 }
1893 };
1894}
1895
1896__impl_slice_eq1! { Vec<'a, A>, Vec<'b, B> }
1897__impl_slice_eq1! { Vec<'a, A>, &'b [B] }
1898__impl_slice_eq1! { Vec<'a, A>, &'b mut [B] }
1899// __impl_slice_eq1! { Cow<'a, [A]>, Vec<'b, B>, Clone }
1900
1901macro_rules! array_impls {
1902 ($($N: expr)+) => {
1903 $(
1904 // NOTE: some less important impls are omitted to reduce code bloat
1905 __impl_slice_eq1! { Vec<'a, A>, [B; $N] }
1906 __impl_slice_eq1! { Vec<'a, A>, &'b [B; $N] }
1907 // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
1908 // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
1909 // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
1910 // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
1911 )+
1912 }
1913}
1914
1915array_impls! {
1916 0 1 2 3 4 5 6 7 8 9
1917 10 11 12 13 14 15 16 17 18 19
1918 20 21 22 23 24 25 26 27 28 29
1919 30 31 32
1920}
1921
1922/// Implements comparison of vectors, lexicographically.
1923impl<'bump, T: 'bump + PartialOrd> PartialOrd for Vec<'bump, T> {
1924 #[inline]
1925 fn partial_cmp(&self, other: &Vec<'bump, T>) -> Option<Ordering> {
1926 PartialOrd::partial_cmp(&**self, &**other)
1927 }
1928}
1929
1930impl<'bump, T: 'bump + Eq> Eq for Vec<'bump, T> {}
1931
1932/// Implements ordering of vectors, lexicographically.
1933impl<'bump, T: 'bump + Ord> Ord for Vec<'bump, T> {
1934 #[inline]
1935 fn cmp(&self, other: &Vec<'bump, T>) -> Ordering {
1936 Ord::cmp(&**self, &**other)
1937 }
1938}
1939
1940impl<'bump, T: 'bump + fmt::Debug> fmt::Debug for Vec<'bump, T> {
1941 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1942 fmt::Debug::fmt(&**self, f)
1943 }
1944}
1945
1946impl<'bump, T: 'bump> AsRef<Vec<'bump, T>> for Vec<'bump, T> {
1947 fn as_ref(&self) -> &Vec<'bump, T> {
1948 self
1949 }
1950}
1951
1952impl<'bump, T: 'bump> AsMut<Vec<'bump, T>> for Vec<'bump, T> {
1953 fn as_mut(&mut self) -> &mut Vec<'bump, T> {
1954 self
1955 }
1956}
1957
1958impl<'bump, T: 'bump> AsRef<[T]> for Vec<'bump, T> {
1959 fn as_ref(&self) -> &[T] {
1960 self
1961 }
1962}
1963
1964impl<'bump, T: 'bump> AsMut<[T]> for Vec<'bump, T> {
1965 fn as_mut(&mut self) -> &mut [T] {
1966 self
1967 }
1968}
1969
1970// // note: test pulls in libstd, which causes errors here
1971// #[cfg(not(test))]
1972// impl<'bump, T: 'bump> From<Vec<'bump, T>> for Box<[T]> {
1973// fn from(v: Vec<'bump, T>) -> Box<[T]> {
1974// v.into_boxed_slice()
1975// }
1976// }
1977
1978////////////////////////////////////////////////////////////////////////////////
1979// Clone-on-write
1980////////////////////////////////////////////////////////////////////////////////
1981
1982// impl<'a, 'bump, T: Clone> From<Vec<'bump, T>> for Cow<'a, [T]> {
1983// fn from(v: Vec<'bump, T>) -> Cow<'a, [T]> {
1984// Cow::Owned(v)
1985// }
1986// }
1987
1988// impl<'a, 'bump, T: Clone> From<&'a Vec<'bump, T>> for Cow<'a, [T]> {
1989// fn from(v: &'a Vec<'bump, T>) -> Cow<'a, [T]> {
1990// Cow::Borrowed(v.as_slice())
1991// }
1992// }
1993
1994////////////////////////////////////////////////////////////////////////////////
1995// Iterators
1996////////////////////////////////////////////////////////////////////////////////
1997
1998/// An iterator that moves out of a vector.
1999///
2000/// This `struct` is created by the `into_iter` method on [`Vec`][`Vec`] (provided
2001/// by the [`IntoIterator`] trait).
2002///
2003/// [`Vec`]: struct.Vec.html
2004/// [`IntoIterator`]: https://doc.rust-lang.org/nightly/std/iter/trait.IntoIterator.html
2005pub struct IntoIter<T> {
2006 phantom: PhantomData<T>,
2007 ptr: *const T,
2008 end: *const T,
2009}
2010
2011impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2012 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2013 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2014 }
2015}
2016
2017impl<'bump, T: 'bump> IntoIter<T> {
2018 /// Returns the remaining items of this iterator as a slice.
2019 ///
2020 /// # Examples
2021 ///
2022 /// ```
2023 /// use bumpalo::{Bump, collections::Vec};
2024 ///
2025 /// let b = Bump::new();
2026 ///
2027 /// let vec = bumpalo::vec![in &b; 'a', 'b', 'c'];
2028 /// let mut into_iter = vec.into_iter();
2029 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2030 /// let _ = into_iter.next().unwrap();
2031 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2032 /// ```
2033 pub fn as_slice(&self) -> &[T] {
2034 unsafe { slice::from_raw_parts(self.ptr, self.len()) }
2035 }
2036
2037 /// Returns the remaining items of this iterator as a mutable slice.
2038 ///
2039 /// # Examples
2040 ///
2041 /// ```
2042 /// use bumpalo::{Bump, collections::Vec};
2043 ///
2044 /// let b = Bump::new();
2045 ///
2046 /// let vec = bumpalo::vec![in &b; 'a', 'b', 'c'];
2047 /// let mut into_iter = vec.into_iter();
2048 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2049 /// into_iter.as_mut_slice()[2] = 'z';
2050 /// assert_eq!(into_iter.next().unwrap(), 'a');
2051 /// assert_eq!(into_iter.next().unwrap(), 'b');
2052 /// assert_eq!(into_iter.next().unwrap(), 'z');
2053 /// ```
2054 pub fn as_mut_slice(&mut self) -> &mut [T] {
2055 unsafe { slice::from_raw_parts_mut(self.ptr as *mut T, self.len()) }
2056 }
2057}
2058
2059unsafe impl<T: Send> Send for IntoIter<T> {}
2060unsafe impl<T: Sync> Sync for IntoIter<T> {}
2061
2062impl<'bump, T: 'bump> Iterator for IntoIter<T> {
2063 type Item = T;
2064
2065 #[inline]
2066 fn next(&mut self) -> Option<T> {
2067 unsafe {
2068 if self.ptr as *const _ == self.end {
2069 None
2070 } else if mem::size_of::<T>() == 0 {
2071 // purposefully don't use 'ptr.offset' because for
2072 // vectors with 0-size elements this would return the
2073 // same pointer.
2074 self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
2075
2076 // Make up a value of this ZST.
2077 Some(mem::zeroed())
2078 } else {
2079 let old = self.ptr;
2080 self.ptr = self.ptr.offset(1);
2081
2082 Some(ptr::read(old))
2083 }
2084 }
2085 }
2086
2087 #[inline]
2088 fn size_hint(&self) -> (usize, Option<usize>) {
2089 let exact = if mem::size_of::<T>() == 0 {
2090 (self.end as usize).wrapping_sub(self.ptr as usize)
2091 } else {
2092 unsafe { offset_from(self.end, self.ptr) as usize }
2093 };
2094 (exact, Some(exact))
2095 }
2096
2097 #[inline]
2098 fn count(self) -> usize {
2099 self.len()
2100 }
2101}
2102
2103impl<'bump, T: 'bump> DoubleEndedIterator for IntoIter<T> {
2104 #[inline]
2105 fn next_back(&mut self) -> Option<T> {
2106 unsafe {
2107 if self.end == self.ptr {
2108 None
2109 } else if mem::size_of::<T>() == 0 {
2110 // See above for why 'ptr.offset' isn't used
2111 self.end = arith_offset(self.end as *const i8, -1) as *mut T;
2112
2113 // Make up a value of this ZST.
2114 Some(mem::zeroed())
2115 } else {
2116 self.end = self.end.offset(-1);
2117
2118 Some(ptr::read(self.end))
2119 }
2120 }
2121 }
2122}
2123
2124impl<'bump, T: 'bump> ExactSizeIterator for IntoIter<T> {}
2125
2126impl<'bump, T: 'bump> FusedIterator for IntoIter<T> {}
2127
2128/// A draining iterator for `Vec<'bump, T>`.
2129///
2130/// This `struct` is created by the [`drain`] method on [`Vec`].
2131///
2132/// [`drain`]: struct.Vec.html#method.drain
2133/// [`Vec`]: struct.Vec.html
2134pub struct Drain<'a, 'bump, T: 'a + 'bump> {
2135 /// Index of tail to preserve
2136 tail_start: usize,
2137 /// Length of tail
2138 tail_len: usize,
2139 /// Current remaining range to remove
2140 iter: slice::Iter<'a, T>,
2141 vec: NonNull<Vec<'bump, T>>,
2142}
2143
2144impl<'a, 'bump, T: 'a + 'bump + fmt::Debug> fmt::Debug for Drain<'a, 'bump, T> {
2145 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2146 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
2147 }
2148}
2149
2150unsafe impl<'a, 'bump, T: Sync> Sync for Drain<'a, 'bump, T> {}
2151unsafe impl<'a, 'bump, T: Send> Send for Drain<'a, 'bump, T> {}
2152
2153impl<'a, 'bump, T> Iterator for Drain<'a, 'bump, T> {
2154 type Item = T;
2155
2156 #[inline]
2157 fn next(&mut self) -> Option<T> {
2158 self.iter
2159 .next()
2160 .map(|elt| unsafe { ptr::read(elt as *const _) })
2161 }
2162
2163 fn size_hint(&self) -> (usize, Option<usize>) {
2164 self.iter.size_hint()
2165 }
2166}
2167
2168impl<'a, 'bump, T> DoubleEndedIterator for Drain<'a, 'bump, T> {
2169 #[inline]
2170 fn next_back(&mut self) -> Option<T> {
2171 self.iter
2172 .next_back()
2173 .map(|elt| unsafe { ptr::read(elt as *const _) })
2174 }
2175}
2176
2177impl<'a, 'bump, T> Drop for Drain<'a, 'bump, T> {
2178 fn drop(&mut self) {
2179 // exhaust self first
2180 self.for_each(drop);
2181
2182 if self.tail_len > 0 {
2183 unsafe {
2184 let source_vec = self.vec.as_mut();
2185 // memmove back untouched tail, update to new length
2186 let start = source_vec.len();
2187 let tail = self.tail_start;
2188 if tail != start {
2189 let src = source_vec.as_ptr().add(tail);
2190 let dst = source_vec.as_mut_ptr().add(start);
2191 ptr::copy(src, dst, self.tail_len);
2192 }
2193 source_vec.set_len(start + self.tail_len);
2194 }
2195 }
2196 }
2197}
2198
2199impl<'a, 'bump, T> ExactSizeIterator for Drain<'a, 'bump, T> {}
2200
2201impl<'a, 'bump, T> FusedIterator for Drain<'a, 'bump, T> {}
2202
2203/// A splicing iterator for `Vec`.
2204///
2205/// This struct is created by the [`splice()`] method on [`Vec`]. See its
2206/// documentation for more.
2207///
2208/// [`splice()`]: struct.Vec.html#method.splice
2209/// [`Vec`]: struct.Vec.html
2210#[derive(Debug)]
2211pub struct Splice<'a, 'bump, I: Iterator + 'a + 'bump> {
2212 drain: Drain<'a, 'bump, I::Item>,
2213 replace_with: I,
2214}
2215
2216impl<'a, 'bump, I: Iterator> Iterator for Splice<'a, 'bump, I> {
2217 type Item = I::Item;
2218
2219 fn next(&mut self) -> Option<Self::Item> {
2220 self.drain.next()
2221 }
2222
2223 fn size_hint(&self) -> (usize, Option<usize>) {
2224 self.drain.size_hint()
2225 }
2226}
2227
2228impl<'a, 'bump, I: Iterator> DoubleEndedIterator for Splice<'a, 'bump, I> {
2229 fn next_back(&mut self) -> Option<Self::Item> {
2230 self.drain.next_back()
2231 }
2232}
2233
2234impl<'a, 'bump, I: Iterator> ExactSizeIterator for Splice<'a, 'bump, I> {}
2235
2236impl<'a, 'bump, I: Iterator> Drop for Splice<'a, 'bump, I> {
2237 fn drop(&mut self) {
2238 self.drain.by_ref().for_each(drop);
2239
2240 unsafe {
2241 if self.drain.tail_len == 0 {
2242 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
2243 return;
2244 }
2245
2246 // First fill the range left by drain().
2247 if !self.drain.fill(&mut self.replace_with) {
2248 return;
2249 }
2250
2251 // There may be more elements. Use the lower bound as an estimate.
2252 // FIXME: Is the upper bound a better guess? Or something else?
2253 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
2254 if lower_bound > 0 {
2255 self.drain.move_tail(lower_bound);
2256 if !self.drain.fill(&mut self.replace_with) {
2257 return;
2258 }
2259 }
2260
2261 // Collect any remaining elements.
2262 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
2263 let mut collected = Vec::new_in(self.drain.vec.as_ref().buf.bump());
2264 collected.extend(self.replace_with.by_ref());
2265 let mut collected = collected.into_iter();
2266 // Now we have an exact count.
2267 if collected.len() > 0 {
2268 self.drain.move_tail(collected.len());
2269 let filled = self.drain.fill(&mut collected);
2270 debug_assert!(filled);
2271 debug_assert_eq!(collected.len(), 0);
2272 }
2273 }
2274 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
2275 }
2276}
2277
2278/// Private helper methods for `Splice::drop`
2279impl<'a, 'bump, T> Drain<'a, 'bump, T> {
2280 /// The range from `self.vec.len` to `self.tail_start` contains elements
2281 /// that have been moved out.
2282 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
2283 /// Return whether we filled the entire range. (`replace_with.next()` didn’t return `None`.)
2284 unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool {
2285 let vec = self.vec.as_mut();
2286 let range_start = vec.len;
2287 let range_end = self.tail_start;
2288 let range_slice =
2289 slice::from_raw_parts_mut(vec.as_mut_ptr().add(range_start), range_end - range_start);
2290
2291 for place in range_slice {
2292 if let Some(new_item) = replace_with.next() {
2293 ptr::write(place, new_item);
2294 vec.len += 1;
2295 } else {
2296 return false;
2297 }
2298 }
2299 true
2300 }
2301
2302 /// Make room for inserting more elements before the tail.
2303 unsafe fn move_tail(&mut self, extra_capacity: usize) {
2304 let vec = self.vec.as_mut();
2305 let used_capacity = self.tail_start + self.tail_len;
2306 vec.buf.reserve(used_capacity, extra_capacity);
2307
2308 let new_tail_start = self.tail_start + extra_capacity;
2309 let src = vec.as_ptr().add(self.tail_start);
2310 let dst = vec.as_mut_ptr().add(new_tail_start);
2311 ptr::copy(src, dst, self.tail_len);
2312 self.tail_start = new_tail_start;
2313 }
2314}
2315
2316/// An iterator produced by calling `drain_filter` on Vec.
2317#[derive(Debug)]
2318pub struct DrainFilter<'a, 'bump: 'a, T: 'a + 'bump, F>
2319where
2320 F: FnMut(&mut T) -> bool,
2321{
2322 vec: &'a mut Vec<'bump, T>,
2323 idx: usize,
2324 del: usize,
2325 old_len: usize,
2326 pred: F,
2327}
2328
2329impl<'a, 'bump, T, F> Iterator for DrainFilter<'a, 'bump, T, F>
2330where
2331 F: FnMut(&mut T) -> bool,
2332{
2333 type Item = T;
2334
2335 fn next(&mut self) -> Option<T> {
2336 unsafe {
2337 while self.idx != self.old_len {
2338 let i = self.idx;
2339 self.idx += 1;
2340 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
2341 if (self.pred)(&mut v[i]) {
2342 self.del += 1;
2343 return Some(ptr::read(&v[i]));
2344 } else if self.del > 0 {
2345 let del = self.del;
2346 let src: *const T = &v[i];
2347 let dst: *mut T = &mut v[i - del];
2348 // This is safe because self.vec has length 0
2349 // thus its elements will not have Drop::drop
2350 // called on them in the event of a panic.
2351 ptr::copy_nonoverlapping(src, dst, 1);
2352 }
2353 }
2354 None
2355 }
2356 }
2357
2358 fn size_hint(&self) -> (usize, Option<usize>) {
2359 (0, Some(self.old_len - self.idx))
2360 }
2361}
2362
2363impl<'a, 'bump, T, F> Drop for DrainFilter<'a, 'bump, T, F>
2364where
2365 F: FnMut(&mut T) -> bool,
2366{
2367 fn drop(&mut self) {
2368 self.for_each(drop);
2369 unsafe {
2370 self.vec.set_len(self.old_len - self.del);
2371 }
2372 }
2373}