allocator_api2/vec/mod.rs
1//! A contiguous growable array type with heap-allocated contents, written
2//! `Vec<T>`.
3//!
4//! Vectors have *O*(1) indexing, amortized *O*(1) push (to the end) and
5//! *O*(1) pop (from the end).
6//!
7//! Vectors ensure they never allocate more than `isize::MAX` bytes.
8//!
9//! # Examples
10//!
11//! You can explicitly create a [`Vec`] with [`Vec::new`]:
12//!
13//! ```
14//! use allocator_api2::vec::Vec;
15//!
16//! let v: Vec<i32> = Vec::new();
17//! ```
18//!
19//! ...or by using the [`vec!`] macro:
20//!
21//! ```
22//! use allocator_api2::{vec, vec::Vec};
23//!
24//! let v: Vec<i32> = vec![];
25//!
26//! let v = vec![1, 2, 3, 4, 5];
27//!
28//! let v = vec![0; 10]; // ten zeroes
29//! ```
30//!
31//! You can [`push`] values onto the end of a vector (which will grow the vector
32//! as needed):
33//!
34//! ```
35//! use allocator_api2::vec;
36//!
37//! let mut v = vec![1, 2];
38//!
39//! v.push(3);
40//! ```
41//!
42//! Popping values works in much the same way:
43//!
44//! ```
45//! use allocator_api2::vec;
46//!
47//! let mut v = vec![1, 2];
48//!
49//! let two = v.pop();
50//! ```
51//!
52//! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
53//!
54//! ```
55//! use allocator_api2::vec;
56//!
57//! let mut v = vec![1, 2, 3];
58//! let three = v[2];
59//! v[1] = v[1] + 5;
60//! ```
61//!
62//! [`push`]: Vec::push
63
64#[cfg(not(no_global_oom_handling))]
65use core::cmp;
66use core::cmp::Ordering;
67use core::convert::TryFrom;
68use core::fmt;
69use core::hash::{Hash, Hasher};
70#[cfg(not(no_global_oom_handling))]
71use core::iter;
72#[cfg(not(no_global_oom_handling))]
73use core::iter::FromIterator;
74use core::marker::PhantomData;
75use core::mem::{self, size_of, ManuallyDrop, MaybeUninit};
76use core::ops::{self, Bound, Index, IndexMut, RangeBounds};
77use core::ptr::{self, NonNull};
78use core::slice::{self, SliceIndex};
79
80#[cfg(feature = "std")]
81use std::io;
82
83use super::{
84 alloc::{Allocator, Global},
85 assume,
86 boxed::Box,
87 raw_vec::{RawVec, TryReserveError},
88};
89
90#[cfg(not(no_global_oom_handling))]
91pub use self::splice::Splice;
92
93#[cfg(not(no_global_oom_handling))]
94mod splice;
95
96pub use self::drain::Drain;
97
98mod drain;
99
100pub use self::into_iter::IntoIter;
101
102mod into_iter;
103
104mod partial_eq;
105
106#[cfg(not(no_global_oom_handling))]
107mod set_len_on_drop;
108
109#[cfg(not(no_global_oom_handling))]
110use self::set_len_on_drop::SetLenOnDrop;
111
112/// A contiguous growable array type, written as `Vec<T>`, short for 'vector'.
113///
114/// # Examples
115///
116/// ```
117/// use allocator_api2::vec::Vec;
118///
119/// let mut vec = Vec::new();
120/// vec.push(1);
121/// vec.push(2);
122///
123/// assert_eq!(vec.len(), 2);
124/// assert_eq!(vec[0], 1);
125///
126/// assert_eq!(vec.pop(), Some(2));
127/// assert_eq!(vec.len(), 1);
128///
129/// vec[0] = 7;
130/// assert_eq!(vec[0], 7);
131///
132/// vec.extend([1, 2, 3].iter().copied());
133///
134/// for x in &vec {
135/// println!("{x}");
136/// }
137/// assert_eq!(vec, [7, 1, 2, 3]);
138/// ```
139///
140/// The [`vec!`] macro is provided for convenient initialization:
141///
142/// ```
143/// use allocator_api2::{vec, vec::Vec};
144///
145/// let mut vec1 = vec![1, 2, 3];
146/// vec1.push(4);
147/// let vec2 = Vec::from([1, 2, 3, 4]);
148/// assert_eq!(vec1, vec2);
149/// ```
150///
151/// It can also initialize each element of a `Vec<T>` with a given value.
152/// This may be more efficient than performing allocation and initialization
153/// in separate steps, especially when initializing a vector of zeros:
154///
155/// ```
156/// use allocator_api2::{vec, vec::Vec};
157///
158/// let vec = vec![0; 5];
159/// assert_eq!(vec, [0, 0, 0, 0, 0]);
160///
161/// // The following is equivalent, but potentially slower:
162/// let mut vec = Vec::with_capacity(5);
163/// vec.resize(5, 0);
164/// assert_eq!(vec, [0, 0, 0, 0, 0]);
165/// ```
166///
167/// For more information, see
168/// [Capacity and Reallocation](#capacity-and-reallocation).
169///
170/// Use a `Vec<T>` as an efficient stack:
171///
172/// ```
173/// use allocator_api2::vec::Vec;
174///
175/// let mut stack = Vec::new();
176///
177/// stack.push(1);
178/// stack.push(2);
179/// stack.push(3);
180///
181/// while let Some(top) = stack.pop() {
182/// // Prints 3, 2, 1
183/// println!("{top}");
184/// }
185/// ```
186///
187/// # Indexing
188///
189/// The `Vec` type allows to access values by index, because it implements the
190/// [`Index`] trait. An example will be more explicit:
191///
192/// ```
193/// use allocator_api2::vec;
194///
195/// let v = vec![0, 2, 4, 6];
196/// println!("{}", v[1]); // it will display '2'
197/// ```
198///
199/// However be careful: if you try to access an index which isn't in the `Vec`,
200/// your software will panic! You cannot do this:
201///
202/// ```should_panic
203/// use allocator_api2::vec;
204///
205/// let v = vec![0, 2, 4, 6];
206/// println!("{}", v[6]); // it will panic!
207/// ```
208///
209/// Use [`get`] and [`get_mut`] if you want to check whether the index is in
210/// the `Vec`.
211///
212/// # Slicing
213///
214/// A `Vec` can be mutable. On the other hand, slices are read-only objects.
215/// To get a [slice][prim@slice], use [`&`]. Example:
216///
217/// ```
218/// use allocator_api2::vec;
219///
220/// fn read_slice(slice: &[usize]) {
221/// // ...
222/// }
223///
224/// let v = vec![0, 1];
225/// read_slice(&v);
226///
227/// // ... and that's all!
228/// // you can also do it like this:
229/// let u: &[usize] = &v;
230/// // or like this:
231/// let u: &[_] = &v;
232/// ```
233///
234/// In Rust, it's more common to pass slices as arguments rather than vectors
235/// when you just want to provide read access. The same goes for [`String`] and
236/// [`&str`].
237///
238/// # Capacity and reallocation
239///
240/// The capacity of a vector is the amount of space allocated for any future
241/// elements that will be added onto the vector. This is not to be confused with
242/// the *length* of a vector, which specifies the number of actual elements
243/// within the vector. If a vector's length exceeds its capacity, its capacity
244/// will automatically be increased, but its elements will have to be
245/// reallocated.
246///
247/// For example, a vector with capacity 10 and length 0 would be an empty vector
248/// with space for 10 more elements. Pushing 10 or fewer elements onto the
249/// vector will not change its capacity or cause reallocation to occur. However,
250/// if the vector's length is increased to 11, it will have to reallocate, which
251/// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
252/// whenever possible to specify how big the vector is expected to get.
253///
254/// # Guarantees
255///
256/// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
257/// about its design. This ensures that it's as low-overhead as possible in
258/// the general case, and can be correctly manipulated in primitive ways
259/// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
260/// If additional type parameters are added (e.g., to support custom allocators),
261/// overriding their defaults may change the behavior.
262///
263/// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
264/// triplet. No more, no less. The order of these fields is completely
265/// unspecified, and you should use the appropriate methods to modify these.
266/// The pointer will never be null, so this type is null-pointer-optimized.
267///
268/// However, the pointer might not actually point to allocated memory. In particular,
269/// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
270/// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
271/// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
272/// types inside a `Vec`, it will not allocate space for them. *Note that in this case
273/// the `Vec` might not report a [`capacity`] of 0*. `Vec` will allocate if and only
274/// if <code>[mem::size_of::\<T>]\() * [capacity]\() > 0</code>. In general, `Vec`'s allocation
275/// details are very subtle --- if you intend to allocate memory using a `Vec`
276/// and use it for something else (either to pass to unsafe code, or to build your
277/// own memory-backed collection), be sure to deallocate this memory by using
278/// `from_raw_parts` to recover the `Vec` and then dropping it.
279///
280/// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
281/// (as defined by the allocator Rust is configured to use by default), and its
282/// pointer points to [`len`] initialized, contiguous elements in order (what
283/// you would see if you coerced it to a slice), followed by <code>[capacity] - [len]</code>
284/// logically uninitialized, contiguous elements.
285///
286/// A vector containing the elements `'a'` and `'b'` with capacity 4 can be
287/// visualized as below. The top part is the `Vec` struct, it contains a
288/// pointer to the head of the allocation in the heap, length and capacity.
289/// The bottom part is the allocation on the heap, a contiguous memory block.
290///
291/// ```text
292/// ptr len capacity
293/// +--------+--------+--------+
294/// | 0x0123 | 2 | 4 |
295/// +--------+--------+--------+
296/// |
297/// v
298/// Heap +--------+--------+--------+--------+
299/// | 'a' | 'b' | uninit | uninit |
300/// +--------+--------+--------+--------+
301/// ```
302///
303/// - **uninit** represents memory that is not initialized, see [`MaybeUninit`].
304/// - Note: the ABI is not stable and `Vec` makes no guarantees about its memory
305/// layout (including the order of fields).
306///
307/// `Vec` will never perform a "small optimization" where elements are actually
308/// stored on the stack for two reasons:
309///
310/// * It would make it more difficult for unsafe code to correctly manipulate
311/// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
312/// only moved, and it would be more difficult to determine if a `Vec` had
313/// actually allocated memory.
314///
315/// * It would penalize the general case, incurring an additional branch
316/// on every access.
317///
318/// `Vec` will never automatically shrink itself, even if completely empty. This
319/// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
320/// and then filling it back up to the same [`len`] should incur no calls to
321/// the allocator. If you wish to free up unused memory, use
322/// [`shrink_to_fit`] or [`shrink_to`].
323///
324/// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
325/// sufficient. [`push`] and [`insert`] *will* (re)allocate if
326/// <code>[len] == [capacity]</code>. That is, the reported capacity is completely
327/// accurate, and can be relied on. It can even be used to manually free the memory
328/// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
329/// when not necessary.
330///
331/// `Vec` does not guarantee any particular growth strategy when reallocating
332/// when full, nor when [`reserve`] is called. The current strategy is basic
333/// and it may prove desirable to use a non-constant growth factor. Whatever
334/// strategy is used will of course guarantee *O*(1) amortized [`push`].
335///
336/// `vec![x; n]`, `vec![a, b, c, d]`, and
337/// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
338/// with exactly the requested capacity. If <code>[len] == [capacity]</code>,
339/// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
340/// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
341///
342/// `Vec` will not specifically overwrite any data that is removed from it,
343/// but also won't specifically preserve it. Its uninitialized memory is
344/// scratch space that it may use however it wants. It will generally just do
345/// whatever is most efficient or otherwise easy to implement. Do not rely on
346/// removed data to be erased for security purposes. Even if you drop a `Vec`, its
347/// buffer may simply be reused by another allocation. Even if you zero a `Vec`'s memory
348/// first, that might not actually happen because the optimizer does not consider
349/// this a side-effect that must be preserved. There is one case which we will
350/// not break, however: using `unsafe` code to write to the excess capacity,
351/// and then increasing the length to match, is always valid.
352///
353/// Currently, `Vec` does not guarantee the order in which elements are dropped.
354/// The order has changed in the past and may change again.
355///
356/// [`get`]: ../../std/vec/struct.Vec.html#method.get
357/// [`get_mut`]: ../../std/vec/struct.Vec.html#method.get_mut
358/// [`String`]: alloc_crate::string::String
359/// [`&str`]: type@str
360/// [`shrink_to_fit`]: Vec::shrink_to_fit
361/// [`shrink_to`]: Vec::shrink_to
362/// [capacity]: Vec::capacity
363/// [`capacity`]: Vec::capacity
364/// [mem::size_of::\<T>]: core::mem::size_of
365/// [len]: Vec::len
366/// [`len`]: Vec::len
367/// [`push`]: Vec::push
368/// [`insert`]: Vec::insert
369/// [`reserve`]: Vec::reserve
370/// [`MaybeUninit`]: core::mem::MaybeUninit
371/// [owned slice]: Box
372pub struct Vec<T, A: Allocator = Global> {
373 buf: RawVec<T, A>,
374 len: usize,
375}
376
377////////////////////////////////////////////////////////////////////////////////
378// Inherent methods
379////////////////////////////////////////////////////////////////////////////////
380
381impl<T> Vec<T> {
382 /// Constructs a new, empty `Vec<T>`.
383 ///
384 /// The vector will not allocate until elements are pushed onto it.
385 ///
386 /// # Examples
387 ///
388 /// ```
389 /// use allocator_api2::{vec, vec::Vec};
390 ///
391 /// let mut vec: Vec<i32> = Vec::new();
392 /// ```
393 #[inline(always)]
394 #[must_use]
395 pub const fn new() -> Self {
396 Vec {
397 buf: RawVec::new(),
398 len: 0,
399 }
400 }
401
402 /// Constructs a new, empty `Vec<T>` with at least the specified capacity.
403 ///
404 /// The vector will be able to hold at least `capacity` elements without
405 /// reallocating. This method is allowed to allocate for more elements than
406 /// `capacity`. If `capacity` is 0, the vector will not allocate.
407 ///
408 /// It is important to note that although the returned vector has the
409 /// minimum *capacity* specified, the vector will have a zero *length*. For
410 /// an explanation of the difference between length and capacity, see
411 /// *[Capacity and reallocation]*.
412 ///
413 /// If it is important to know the exact allocated capacity of a `Vec`,
414 /// always use the [`capacity`] method after construction.
415 ///
416 /// For `Vec<T>` where `T` is a zero-sized type, there will be no allocation
417 /// and the capacity will always be `usize::MAX`.
418 ///
419 /// [Capacity and reallocation]: #capacity-and-reallocation
420 /// [`capacity`]: Vec::capacity
421 ///
422 /// # Panics
423 ///
424 /// Panics if the new capacity exceeds `isize::MAX` bytes.
425 ///
426 /// # Examples
427 ///
428 /// ```
429 /// use allocator_api2::vec::Vec;
430 ///
431 /// let mut vec = Vec::with_capacity(10);
432 ///
433 /// // The vector contains no items, even though it has capacity for more
434 /// assert_eq!(vec.len(), 0);
435 /// assert!(vec.capacity() >= 10);
436 ///
437 /// // These are all done without reallocating...
438 /// for i in 0..10 {
439 /// vec.push(i);
440 /// }
441 /// assert_eq!(vec.len(), 10);
442 /// assert!(vec.capacity() >= 10);
443 ///
444 /// // ...but this may make the vector reallocate
445 /// vec.push(11);
446 /// assert_eq!(vec.len(), 11);
447 /// assert!(vec.capacity() >= 11);
448 ///
449 /// // A vector of a zero-sized type will always over-allocate, since no
450 /// // allocation is necessary
451 /// let vec_units = Vec::<()>::with_capacity(10);
452 /// assert_eq!(vec_units.capacity(), usize::MAX);
453 /// ```
454 #[cfg(not(no_global_oom_handling))]
455 #[inline(always)]
456 #[must_use]
457 pub fn with_capacity(capacity: usize) -> Self {
458 Self::with_capacity_in(capacity, Global)
459 }
460
461 /// Creates a `Vec<T>` directly from a pointer, a capacity, and a length.
462 ///
463 /// # Safety
464 ///
465 /// This is highly unsafe, due to the number of invariants that aren't
466 /// checked:
467 ///
468 /// * `T` needs to have the same alignment as what `ptr` was allocated with.
469 /// (`T` having a less strict alignment is not sufficient, the alignment really
470 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
471 /// allocated and deallocated with the same layout.)
472 /// * The size of `T` times the `capacity` (ie. the allocated size in bytes) needs
473 /// to be the same size as the pointer was allocated with. (Because similar to
474 /// alignment, [`dealloc`] must be called with the same layout `size`.)
475 /// * `length` needs to be less than or equal to `capacity`.
476 /// * The first `length` values must be properly initialized values of type `T`.
477 /// * `capacity` needs to be the capacity that the pointer was allocated with.
478 /// * The allocated size in bytes must be no larger than `isize::MAX`.
479 /// See the safety documentation of [`pointer::offset`](https://doc.rust-lang.org/nightly/std/primitive.pointer.html#method.offset).
480 ///
481 /// These requirements are always upheld by any `ptr` that has been allocated
482 /// via `Vec<T>`. Other allocation sources are allowed if the invariants are
483 /// upheld.
484 ///
485 /// Violating these may cause problems like corrupting the allocator's
486 /// internal data structures. For example it is normally **not** safe
487 /// to build a `Vec<u8>` from a pointer to a C `char` array with length
488 /// `size_t`, doing so is only safe if the array was initially allocated by
489 /// a `Vec` or `String`.
490 /// It's also not safe to build one from a `Vec<u16>` and its length, because
491 /// the allocator cares about the alignment, and these two types have different
492 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
493 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1. To avoid
494 /// these issues, it is often preferable to do casting/transmuting using
495 /// [`slice::from_raw_parts`] instead.
496 ///
497 /// The ownership of `ptr` is effectively transferred to the
498 /// `Vec<T>` which may then deallocate, reallocate or change the
499 /// contents of memory pointed to by the pointer at will. Ensure
500 /// that nothing else uses the pointer after calling this
501 /// function.
502 ///
503 /// [`String`]: alloc_crate::string::String
504 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
505 ///
506 /// # Examples
507 ///
508 /// ```
509 /// use allocator_api2::{vec, vec::Vec};
510 ///
511 /// use std::ptr;
512 /// use std::mem;
513 ///
514 /// let v = vec![1, 2, 3];
515 ///
516 // FIXME Update this when vec_into_raw_parts is stabilized
517 /// // Prevent running `v`'s destructor so we are in complete control
518 /// // of the allocation.
519 /// let mut v = mem::ManuallyDrop::new(v);
520 ///
521 /// // Pull out the various important pieces of information about `v`
522 /// let p = v.as_mut_ptr();
523 /// let len = v.len();
524 /// let cap = v.capacity();
525 ///
526 /// unsafe {
527 /// // Overwrite memory with 4, 5, 6
528 /// for i in 0..len {
529 /// ptr::write(p.add(i), 4 + i);
530 /// }
531 ///
532 /// // Put everything back together into a Vec
533 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
534 /// assert_eq!(rebuilt, [4, 5, 6]);
535 /// }
536 /// ```
537 ///
538 /// Using memory that was allocated elsewhere:
539 ///
540 /// ```
541 /// use allocator_api2::{vec, vec::Vec, alloc::{AllocError, Allocator, Global, Layout}};
542 ///
543 /// fn main() {
544 /// let layout = Layout::array::<u32>(16).expect("overflow cannot happen");
545 ///
546 /// let vec = unsafe {
547 /// let mem = match Global.allocate(layout) {
548 /// Ok(mem) => mem.cast::<u32>().as_ptr(),
549 /// Err(AllocError) => return,
550 /// };
551 ///
552 /// mem.write(1_000_000);
553 ///
554 /// Vec::from_raw_parts_in(mem, 1, 16, Global)
555 /// };
556 ///
557 /// assert_eq!(vec, &[1_000_000]);
558 /// assert_eq!(vec.capacity(), 16);
559 /// }
560 /// ```
561 #[inline(always)]
562 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {
563 unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) }
564 }
565}
566
567impl<T, A: Allocator> Vec<T, A> {
568 /// Constructs a new, empty `Vec<T, A>`.
569 ///
570 /// The vector will not allocate until elements are pushed onto it.
571 ///
572 /// # Examples
573 ///
574 /// ```
575 /// use allocator_api2::{vec::Vec, alloc::System};
576 ///
577 /// # #[allow(unused_mut)]
578 /// let mut vec: Vec<i32, _> = Vec::new_in(System);
579 /// ```
580 #[inline(always)]
581 pub const fn new_in(alloc: A) -> Self {
582 Vec {
583 buf: RawVec::new_in(alloc),
584 len: 0,
585 }
586 }
587
588 /// Constructs a new, empty `Vec<T, A>` with at least the specified capacity
589 /// with the provided allocator.
590 ///
591 /// The vector will be able to hold at least `capacity` elements without
592 /// reallocating. This method is allowed to allocate for more elements than
593 /// `capacity`. If `capacity` is 0, the vector will not allocate.
594 ///
595 /// It is important to note that although the returned vector has the
596 /// minimum *capacity* specified, the vector will have a zero *length*. For
597 /// an explanation of the difference between length and capacity, see
598 /// *[Capacity and reallocation]*.
599 ///
600 /// If it is important to know the exact allocated capacity of a `Vec`,
601 /// always use the [`capacity`] method after construction.
602 ///
603 /// For `Vec<T, A>` where `T` is a zero-sized type, there will be no allocation
604 /// and the capacity will always be `usize::MAX`.
605 ///
606 /// [Capacity and reallocation]: #capacity-and-reallocation
607 /// [`capacity`]: Vec::capacity
608 ///
609 /// # Panics
610 ///
611 /// Panics if the new capacity exceeds `isize::MAX` bytes.
612 ///
613 /// # Examples
614 ///
615 /// ```
616 /// use allocator_api2::{vec::Vec, alloc::System};
617 ///
618 /// let mut vec = Vec::with_capacity_in(10, System);
619 ///
620 /// // The vector contains no items, even though it has capacity for more
621 /// assert_eq!(vec.len(), 0);
622 /// assert_eq!(vec.capacity(), 10);
623 ///
624 /// // These are all done without reallocating...
625 /// for i in 0..10 {
626 /// vec.push(i);
627 /// }
628 /// assert_eq!(vec.len(), 10);
629 /// assert_eq!(vec.capacity(), 10);
630 ///
631 /// // ...but this may make the vector reallocate
632 /// vec.push(11);
633 /// assert_eq!(vec.len(), 11);
634 /// assert!(vec.capacity() >= 11);
635 ///
636 /// // A vector of a zero-sized type will always over-allocate, since no
637 /// // allocation is necessary
638 /// let vec_units = Vec::<(), System>::with_capacity_in(10, System);
639 /// assert_eq!(vec_units.capacity(), usize::MAX);
640 /// ```
641 #[cfg(not(no_global_oom_handling))]
642 #[inline(always)]
643 pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
644 Vec {
645 buf: RawVec::with_capacity_in(capacity, alloc),
646 len: 0,
647 }
648 }
649
650 /// Creates a `Vec<T, A>` directly from a pointer, a capacity, a length,
651 /// and an allocator.
652 ///
653 /// # Safety
654 ///
655 /// This is highly unsafe, due to the number of invariants that aren't
656 /// checked:
657 ///
658 /// * `T` needs to have the same alignment as what `ptr` was allocated with.
659 /// (`T` having a less strict alignment is not sufficient, the alignment really
660 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
661 /// allocated and deallocated with the same layout.)
662 /// * The size of `T` times the `capacity` (ie. the allocated size in bytes) needs
663 /// to be the same size as the pointer was allocated with. (Because similar to
664 /// alignment, [`dealloc`] must be called with the same layout `size`.)
665 /// * `length` needs to be less than or equal to `capacity`.
666 /// * The first `length` values must be properly initialized values of type `T`.
667 /// * `capacity` needs to [*fit*] the layout size that the pointer was allocated with.
668 /// * The allocated size in bytes must be no larger than `isize::MAX`.
669 /// See the safety documentation of [`pointer::offset`](https://doc.rust-lang.org/nightly/std/primitive.pointer.html#method.offset).
670 ///
671 /// These requirements are always upheld by any `ptr` that has been allocated
672 /// via `Vec<T, A>`. Other allocation sources are allowed if the invariants are
673 /// upheld.
674 ///
675 /// Violating these may cause problems like corrupting the allocator's
676 /// internal data structures. For example it is **not** safe
677 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
678 /// It's also not safe to build one from a `Vec<u16>` and its length, because
679 /// the allocator cares about the alignment, and these two types have different
680 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
681 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
682 ///
683 /// The ownership of `ptr` is effectively transferred to the
684 /// `Vec<T>` which may then deallocate, reallocate or change the
685 /// contents of memory pointed to by the pointer at will. Ensure
686 /// that nothing else uses the pointer after calling this
687 /// function.
688 ///
689 /// [`String`]: alloc_crate::string::String
690 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
691 /// [*fit*]: crate::alloc::Allocator#memory-fitting
692 ///
693 /// # Examples
694 ///
695 /// ```
696 /// use allocator_api2::{vec::Vec, alloc::System};
697 ///
698 /// use std::ptr;
699 /// use std::mem;
700 ///
701 /// let mut v = Vec::with_capacity_in(3, System);
702 /// v.push(1);
703 /// v.push(2);
704 /// v.push(3);
705 ///
706 // FIXME Update this when vec_into_raw_parts is stabilized
707 /// // Prevent running `v`'s destructor so we are in complete control
708 /// // of the allocation.
709 /// let mut v = mem::ManuallyDrop::new(v);
710 ///
711 /// // Pull out the various important pieces of information about `v`
712 /// let p = v.as_mut_ptr();
713 /// let len = v.len();
714 /// let cap = v.capacity();
715 /// let alloc = v.allocator();
716 ///
717 /// unsafe {
718 /// // Overwrite memory with 4, 5, 6
719 /// for i in 0..len {
720 /// ptr::write(p.add(i), 4 + i);
721 /// }
722 ///
723 /// // Put everything back together into a Vec
724 /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());
725 /// assert_eq!(rebuilt, [4, 5, 6]);
726 /// }
727 /// ```
728 ///
729 /// Using memory that was allocated elsewhere:
730 ///
731 /// ```
732 /// use allocator_api2::{vec::Vec, alloc::{alloc, Layout}};
733 ///
734 /// fn main() {
735 /// let layout = Layout::array::<u32>(16).expect("overflow cannot happen");
736 /// let vec = unsafe {
737 /// let mem = alloc(layout).cast::<u32>();
738 /// if mem.is_null() {
739 /// return;
740 /// }
741 ///
742 /// mem.write(1_000_000);
743 ///
744 /// Vec::from_raw_parts(mem, 1, 16)
745 /// };
746 ///
747 /// assert_eq!(vec, &[1_000_000]);
748 /// assert_eq!(vec.capacity(), 16);
749 /// }
750 /// ```
751 #[inline(always)]
752 pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self {
753 unsafe {
754 Vec {
755 buf: RawVec::from_raw_parts_in(ptr, capacity, alloc),
756 len: length,
757 }
758 }
759 }
760
761 /// Decomposes a `Vec<T>` into its raw components.
762 ///
763 /// Returns the raw pointer to the underlying data, the length of
764 /// the vector (in elements), and the allocated capacity of the
765 /// data (in elements). These are the same arguments in the same
766 /// order as the arguments to [`from_raw_parts`].
767 ///
768 /// After calling this function, the caller is responsible for the
769 /// memory previously managed by the `Vec`. The only way to do
770 /// this is to convert the raw pointer, length, and capacity back
771 /// into a `Vec` with the [`from_raw_parts`] function, allowing
772 /// the destructor to perform the cleanup.
773 ///
774 /// [`from_raw_parts`]: Vec::from_raw_parts
775 ///
776 /// # Examples
777 ///
778 /// ```
779 /// use allocator_api2::{vec, vec::Vec};
780 ///
781 /// let v: Vec<i32> = vec![-1, 0, 1];
782 ///
783 /// let (ptr, len, cap) = v.into_raw_parts();
784 ///
785 /// let rebuilt = unsafe {
786 /// // We can now make changes to the components, such as
787 /// // transmuting the raw pointer to a compatible type.
788 /// let ptr = ptr as *mut u32;
789 ///
790 /// Vec::from_raw_parts(ptr, len, cap)
791 /// };
792 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
793 /// ```
794 pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
795 let mut me = ManuallyDrop::new(self);
796 (me.as_mut_ptr(), me.len(), me.capacity())
797 }
798
799 /// Decomposes a `Vec<T>` into its raw components.
800 ///
801 /// Returns the raw pointer to the underlying data, the length of the vector (in elements),
802 /// the allocated capacity of the data (in elements), and the allocator. These are the same
803 /// arguments in the same order as the arguments to [`from_raw_parts_in`].
804 ///
805 /// After calling this function, the caller is responsible for the
806 /// memory previously managed by the `Vec`. The only way to do
807 /// this is to convert the raw pointer, length, and capacity back
808 /// into a `Vec` with the [`from_raw_parts_in`] function, allowing
809 /// the destructor to perform the cleanup.
810 ///
811 /// [`from_raw_parts_in`]: Vec::from_raw_parts_in
812 ///
813 /// # Examples
814 ///
815 /// ```
816 /// use allocator_api2::{vec::Vec, alloc::System};
817 ///
818 /// let mut v: Vec<i32, System> = Vec::new_in(System);
819 /// v.push(-1);
820 /// v.push(0);
821 /// v.push(1);
822 ///
823 /// let (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();
824 ///
825 /// let rebuilt = unsafe {
826 /// // We can now make changes to the components, such as
827 /// // transmuting the raw pointer to a compatible type.
828 /// let ptr = ptr as *mut u32;
829 ///
830 /// Vec::from_raw_parts_in(ptr, len, cap, alloc)
831 /// };
832 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
833 /// ```
834 // #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
835 pub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A) {
836 let mut me = ManuallyDrop::new(self);
837 let len = me.len();
838 let capacity = me.capacity();
839 let ptr = me.as_mut_ptr();
840 let alloc = unsafe { ptr::read(me.allocator()) };
841 (ptr, len, capacity, alloc)
842 }
843
844 /// Returns the total number of elements the vector can hold without
845 /// reallocating.
846 ///
847 /// # Examples
848 ///
849 /// ```
850 /// use allocator_api2::vec::Vec;
851 ///
852 /// let mut vec: Vec<i32> = Vec::with_capacity(10);
853 /// vec.push(42);
854 /// assert_eq!(vec.capacity(), 10);
855 /// ```
856 #[inline(always)]
857 pub fn capacity(&self) -> usize {
858 self.buf.capacity()
859 }
860
861 /// Reserves capacity for at least `additional` more elements to be inserted
862 /// in the given `Vec<T>`. The collection may reserve more space to
863 /// speculatively avoid frequent reallocations. After calling `reserve`,
864 /// capacity will be greater than or equal to `self.len() + additional`.
865 /// Does nothing if capacity is already sufficient.
866 ///
867 /// # Panics
868 ///
869 /// Panics if the new capacity exceeds `isize::MAX` bytes.
870 ///
871 /// # Examples
872 ///
873 /// ```
874 /// use allocator_api2::vec;
875 ///
876 /// let mut vec = vec![1];
877 /// vec.reserve(10);
878 /// assert!(vec.capacity() >= 11);
879 /// ```
880 #[cfg(not(no_global_oom_handling))]
881 #[inline(always)]
882 pub fn reserve(&mut self, additional: usize) {
883 self.buf.reserve(self.len, additional);
884 }
885
886 /// Reserves the minimum capacity for at least `additional` more elements to
887 /// be inserted in the given `Vec<T>`. Unlike [`reserve`], this will not
888 /// deliberately over-allocate to speculatively avoid frequent allocations.
889 /// After calling `reserve_exact`, capacity will be greater than or equal to
890 /// `self.len() + additional`. Does nothing if the capacity is already
891 /// sufficient.
892 ///
893 /// Note that the allocator may give the collection more space than it
894 /// requests. Therefore, capacity can not be relied upon to be precisely
895 /// minimal. Prefer [`reserve`] if future insertions are expected.
896 ///
897 /// [`reserve`]: Vec::reserve
898 ///
899 /// # Panics
900 ///
901 /// Panics if the new capacity exceeds `isize::MAX` bytes.
902 ///
903 /// # Examples
904 ///
905 /// ```
906 /// use allocator_api2::vec;
907 ///
908 /// let mut vec = vec![1];
909 /// vec.reserve_exact(10);
910 /// assert!(vec.capacity() >= 11);
911 /// ```
912 #[cfg(not(no_global_oom_handling))]
913 #[inline(always)]
914 pub fn reserve_exact(&mut self, additional: usize) {
915 self.buf.reserve_exact(self.len, additional);
916 }
917
918 /// Tries to reserve capacity for at least `additional` more elements to be inserted
919 /// in the given `Vec<T>`. The collection may reserve more space to speculatively avoid
920 /// frequent reallocations. After calling `try_reserve`, capacity will be
921 /// greater than or equal to `self.len() + additional` if it returns
922 /// `Ok(())`. Does nothing if capacity is already sufficient. This method
923 /// preserves the contents even if an error occurs.
924 ///
925 /// # Errors
926 ///
927 /// If the capacity overflows, or the allocator reports a failure, then an error
928 /// is returned.
929 ///
930 /// # Examples
931 ///
932 /// ```
933 /// use allocator_api2::{vec::Vec, collections::TryReserveError};
934 ///
935 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
936 /// let mut output = Vec::new();
937 ///
938 /// // Pre-reserve the memory, exiting if we can't
939 /// output.try_reserve(data.len())?;
940 ///
941 /// // Now we know this can't OOM in the middle of our complex work
942 /// output.extend(data.iter().map(|&val| {
943 /// val * 2 + 5 // very complicated
944 /// }));
945 ///
946 /// Ok(output)
947 /// }
948 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
949 /// ```
950 #[inline(always)]
951 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
952 self.buf.try_reserve(self.len, additional)
953 }
954
955 /// Tries to reserve the minimum capacity for at least `additional`
956 /// elements to be inserted in the given `Vec<T>`. Unlike [`try_reserve`],
957 /// this will not deliberately over-allocate to speculatively avoid frequent
958 /// allocations. After calling `try_reserve_exact`, capacity will be greater
959 /// than or equal to `self.len() + additional` if it returns `Ok(())`.
960 /// Does nothing if the capacity is already sufficient.
961 ///
962 /// Note that the allocator may give the collection more space than it
963 /// requests. Therefore, capacity can not be relied upon to be precisely
964 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
965 ///
966 /// [`try_reserve`]: Vec::try_reserve
967 ///
968 /// # Errors
969 ///
970 /// If the capacity overflows, or the allocator reports a failure, then an error
971 /// is returned.
972 ///
973 /// # Examples
974 ///
975 /// ```
976 /// use allocator_api2::{vec::Vec, collections::TryReserveError};
977 ///
978 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
979 /// let mut output = Vec::new();
980 ///
981 /// // Pre-reserve the memory, exiting if we can't
982 /// output.try_reserve_exact(data.len())?;
983 ///
984 /// // Now we know this can't OOM in the middle of our complex work
985 /// output.extend(data.iter().map(|&val| {
986 /// val * 2 + 5 // very complicated
987 /// }));
988 ///
989 /// Ok(output)
990 /// }
991 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
992 /// ```
993 #[inline(always)]
994 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
995 self.buf.try_reserve_exact(self.len, additional)
996 }
997
998 /// Shrinks the capacity of the vector as much as possible.
999 ///
1000 /// It will drop down as close as possible to the length but the allocator
1001 /// may still inform the vector that there is space for a few more elements.
1002 ///
1003 /// # Examples
1004 ///
1005 /// ```
1006 /// use allocator_api2::vec::Vec;
1007 ///
1008 /// let mut vec = Vec::with_capacity(10);
1009 /// vec.extend([1, 2, 3]);
1010 /// assert_eq!(vec.capacity(), 10);
1011 /// vec.shrink_to_fit();
1012 /// assert!(vec.capacity() >= 3);
1013 /// ```
1014 #[cfg(not(no_global_oom_handling))]
1015 #[inline(always)]
1016 pub fn shrink_to_fit(&mut self) {
1017 // The capacity is never less than the length, and there's nothing to do when
1018 // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit`
1019 // by only calling it with a greater capacity.
1020 if self.capacity() > self.len {
1021 self.buf.shrink_to_fit(self.len);
1022 }
1023 }
1024
1025 /// Shrinks the capacity of the vector with a lower bound.
1026 ///
1027 /// The capacity will remain at least as large as both the length
1028 /// and the supplied value.
1029 ///
1030 /// If the current capacity is less than the lower limit, this is a no-op.
1031 ///
1032 /// # Examples
1033 ///
1034 /// ```
1035 /// use allocator_api2::vec::Vec;
1036 ///
1037 /// let mut vec = Vec::with_capacity(10);
1038 /// vec.extend([1, 2, 3]);
1039 /// assert_eq!(vec.capacity(), 10);
1040 /// vec.shrink_to(4);
1041 /// assert!(vec.capacity() >= 4);
1042 /// vec.shrink_to(0);
1043 /// assert!(vec.capacity() >= 3);
1044 /// ```
1045 #[cfg(not(no_global_oom_handling))]
1046 #[inline(always)]
1047 pub fn shrink_to(&mut self, min_capacity: usize) {
1048 if self.capacity() > min_capacity {
1049 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
1050 }
1051 }
1052
1053 /// Converts the vector into [`Box<[T]>`][owned slice].
1054 ///
1055 /// If the vector has excess capacity, its items will be moved into a
1056 /// newly-allocated buffer with exactly the right capacity.
1057 ///
1058 /// [owned slice]: Box
1059 ///
1060 /// # Examples
1061 ///
1062 /// ```
1063 /// use allocator_api2::vec;
1064 ///
1065 /// let v = vec![1, 2, 3];
1066 ///
1067 /// let slice = v.into_boxed_slice();
1068 /// ```
1069 ///
1070 /// Any excess capacity is removed:
1071 ///
1072 /// ```
1073 /// use allocator_api2::vec::Vec;
1074 ///
1075 /// let mut vec = Vec::with_capacity(10);
1076 /// vec.extend([1, 2, 3]);
1077 ///
1078 /// assert_eq!(vec.capacity(), 10);
1079 /// let slice = vec.into_boxed_slice();
1080 /// assert_eq!(slice.into_vec().capacity(), 3);
1081 /// ```
1082 #[cfg(not(no_global_oom_handling))]
1083 #[inline(always)]
1084 pub fn into_boxed_slice(mut self) -> Box<[T], A> {
1085 unsafe {
1086 self.shrink_to_fit();
1087 let me = ManuallyDrop::new(self);
1088 let buf = ptr::read(&me.buf);
1089 let len = me.len();
1090 Box::<[mem::MaybeUninit<T>], A>::assume_init(buf.into_box(len))
1091 }
1092 }
1093
1094 /// Shortens the vector, keeping the first `len` elements and dropping
1095 /// the rest.
1096 ///
1097 /// If `len` is greater than the vector's current length, this has no
1098 /// effect.
1099 ///
1100 /// The [`drain`] method can emulate `truncate`, but causes the excess
1101 /// elements to be returned instead of dropped.
1102 ///
1103 /// Note that this method has no effect on the allocated capacity
1104 /// of the vector.
1105 ///
1106 /// # Examples
1107 ///
1108 /// Truncating a five element vector to two elements:
1109 ///
1110 /// ```
1111 /// use allocator_api2::vec;
1112 ///
1113 /// let mut vec = vec![1, 2, 3, 4, 5];
1114 /// vec.truncate(2);
1115 /// assert_eq!(vec, [1, 2]);
1116 /// ```
1117 ///
1118 /// No truncation occurs when `len` is greater than the vector's current
1119 /// length:
1120 ///
1121 /// ```
1122 /// use allocator_api2::vec;
1123 ///
1124 /// let mut vec = vec![1, 2, 3];
1125 /// vec.truncate(8);
1126 /// assert_eq!(vec, [1, 2, 3]);
1127 /// ```
1128 ///
1129 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
1130 /// method.
1131 ///
1132 /// ```
1133 /// use allocator_api2::vec;
1134 ///
1135 /// let mut vec = vec![1, 2, 3];
1136 /// vec.truncate(0);
1137 /// assert_eq!(vec, []);
1138 /// ```
1139 ///
1140 /// [`clear`]: Vec::clear
1141 /// [`drain`]: Vec::drain
1142 #[inline(always)]
1143 pub fn truncate(&mut self, len: usize) {
1144 // This is safe because:
1145 //
1146 // * the slice passed to `drop_in_place` is valid; the `len > self.len`
1147 // case avoids creating an invalid slice, and
1148 // * the `len` of the vector is shrunk before calling `drop_in_place`,
1149 // such that no value will be dropped twice in case `drop_in_place`
1150 // were to panic once (if it panics twice, the program aborts).
1151 unsafe {
1152 // Note: It's intentional that this is `>` and not `>=`.
1153 // Changing it to `>=` has negative performance
1154 // implications in some cases. See #78884 for more.
1155 if len > self.len {
1156 return;
1157 }
1158 let remaining_len = self.len - len;
1159 let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
1160 self.len = len;
1161 ptr::drop_in_place(s);
1162 }
1163 }
1164
1165 /// Extracts a slice containing the entire vector.
1166 ///
1167 /// Equivalent to `&s[..]`.
1168 ///
1169 /// # Examples
1170 ///
1171 /// ```
1172 /// use allocator_api2::vec;
1173 ///
1174 /// use std::io::{self, Write};
1175 ///
1176 /// let buffer = vec![1, 2, 3, 5, 8];
1177 /// io::sink().write(buffer.as_slice()).unwrap();
1178 /// ```
1179 #[inline(always)]
1180 pub fn as_slice(&self) -> &[T] {
1181 self
1182 }
1183
1184 /// Extracts a mutable slice of the entire vector.
1185 ///
1186 /// Equivalent to `&mut s[..]`.
1187 ///
1188 /// # Examples
1189 ///
1190 /// ```
1191 /// use allocator_api2::vec;
1192 ///
1193 /// use std::io::{self, Read};
1194 ///
1195 /// let mut buffer = vec![0; 3];
1196 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
1197 /// ```
1198 #[inline(always)]
1199 pub fn as_mut_slice(&mut self) -> &mut [T] {
1200 self
1201 }
1202
1203 /// Returns a raw pointer to the vector's buffer, or a dangling raw pointer
1204 /// valid for zero sized reads if the vector didn't allocate.
1205 ///
1206 /// The caller must ensure that the vector outlives the pointer this
1207 /// function returns, or else it will end up pointing to garbage.
1208 /// Modifying the vector may cause its buffer to be reallocated,
1209 /// which would also make any pointers to it invalid.
1210 ///
1211 /// The caller must also ensure that the memory the pointer (non-transitively) points to
1212 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
1213 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
1214 ///
1215 /// # Examples
1216 ///
1217 /// ```
1218 /// use allocator_api2::vec;
1219 ///
1220 /// let x = vec![1, 2, 4];
1221 /// let x_ptr = x.as_ptr();
1222 ///
1223 /// unsafe {
1224 /// for i in 0..x.len() {
1225 /// assert_eq!(*x_ptr.add(i), 1 << i);
1226 /// }
1227 /// }
1228 /// ```
1229 ///
1230 /// [`as_mut_ptr`]: Vec::as_mut_ptr
1231 #[inline(always)]
1232 pub fn as_ptr(&self) -> *const T {
1233 // We shadow the slice method of the same name to avoid going through
1234 // `deref`, which creates an intermediate reference.
1235 let ptr = self.buf.ptr();
1236 unsafe {
1237 assume(!ptr.is_null());
1238 }
1239 ptr
1240 }
1241
1242 /// Returns an unsafe mutable pointer to the vector's buffer, or a dangling
1243 /// raw pointer valid for zero sized reads if the vector didn't allocate.
1244 ///
1245 /// The caller must ensure that the vector outlives the pointer this
1246 /// function returns, or else it will end up pointing to garbage.
1247 /// Modifying the vector may cause its buffer to be reallocated,
1248 /// which would also make any pointers to it invalid.
1249 ///
1250 /// # Examples
1251 ///
1252 /// ```
1253 /// use allocator_api2::vec::Vec;
1254 ///
1255 /// // Allocate vector big enough for 4 elements.
1256 /// let size = 4;
1257 /// let mut x: Vec<i32> = Vec::with_capacity(size);
1258 /// let x_ptr = x.as_mut_ptr();
1259 ///
1260 /// // Initialize elements via raw pointer writes, then set length.
1261 /// unsafe {
1262 /// for i in 0..size {
1263 /// *x_ptr.add(i) = i as i32;
1264 /// }
1265 /// x.set_len(size);
1266 /// }
1267 /// assert_eq!(&*x, &[0, 1, 2, 3]);
1268 /// ```
1269 #[inline(always)]
1270 pub fn as_mut_ptr(&mut self) -> *mut T {
1271 // We shadow the slice method of the same name to avoid going through
1272 // `deref_mut`, which creates an intermediate reference.
1273 let ptr = self.buf.ptr();
1274 unsafe {
1275 assume(!ptr.is_null());
1276 }
1277 ptr
1278 }
1279
1280 /// Returns a reference to the underlying allocator.
1281 #[inline(always)]
1282 pub fn allocator(&self) -> &A {
1283 self.buf.allocator()
1284 }
1285
1286 /// Forces the length of the vector to `new_len`.
1287 ///
1288 /// This is a low-level operation that maintains none of the normal
1289 /// invariants of the type. Normally changing the length of a vector
1290 /// is done using one of the safe operations instead, such as
1291 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
1292 ///
1293 /// [`truncate`]: Vec::truncate
1294 /// [`resize`]: Vec::resize
1295 /// [`extend`]: Extend::extend
1296 /// [`clear`]: Vec::clear
1297 ///
1298 /// # Safety
1299 ///
1300 /// - `new_len` must be less than or equal to [`capacity()`].
1301 /// - The elements at `old_len..new_len` must be initialized.
1302 ///
1303 /// [`capacity()`]: Vec::capacity
1304 ///
1305 /// # Examples
1306 ///
1307 /// This method can be useful for situations in which the vector
1308 /// is serving as a buffer for other code, particularly over FFI:
1309 ///
1310 /// ```no_run
1311 /// # #![allow(dead_code)]
1312 /// use allocator_api2::vec::Vec;
1313 ///
1314 /// # // This is just a minimal skeleton for the doc example;
1315 /// # // don't use this as a starting point for a real library.
1316 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
1317 /// # const Z_OK: i32 = 0;
1318 /// # extern "C" {
1319 /// # fn deflateGetDictionary(
1320 /// # strm: *mut std::ffi::c_void,
1321 /// # dictionary: *mut u8,
1322 /// # dictLength: *mut usize,
1323 /// # ) -> i32;
1324 /// # }
1325 /// # impl StreamWrapper {
1326 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
1327 /// // Per the FFI method's docs, "32768 bytes is always enough".
1328 /// let mut dict = Vec::with_capacity(32_768);
1329 /// let mut dict_length = 0;
1330 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
1331 /// // 1. `dict_length` elements were initialized.
1332 /// // 2. `dict_length` <= the capacity (32_768)
1333 /// // which makes `set_len` safe to call.
1334 /// unsafe {
1335 /// // Make the FFI call...
1336 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
1337 /// if r == Z_OK {
1338 /// // ...and update the length to what was initialized.
1339 /// dict.set_len(dict_length);
1340 /// Some(dict)
1341 /// } else {
1342 /// None
1343 /// }
1344 /// }
1345 /// }
1346 /// # }
1347 /// ```
1348 ///
1349 /// While the following example is sound, there is a memory leak since
1350 /// the inner vectors were not freed prior to the `set_len` call:
1351 ///
1352 /// ```
1353 /// use allocator_api2::vec;
1354 ///
1355 /// let mut vec = vec![vec![1, 0, 0],
1356 /// vec![0, 1, 0],
1357 /// vec![0, 0, 1]];
1358 /// // SAFETY:
1359 /// // 1. `old_len..0` is empty so no elements need to be initialized.
1360 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
1361 /// unsafe {
1362 /// vec.set_len(0);
1363 /// }
1364 /// ```
1365 ///
1366 /// Normally, here, one would use [`clear`] instead to correctly drop
1367 /// the contents and thus not leak memory.
1368 #[inline(always)]
1369 pub unsafe fn set_len(&mut self, new_len: usize) {
1370 debug_assert!(new_len <= self.capacity());
1371
1372 self.len = new_len;
1373 }
1374
1375 /// Removes an element from the vector and returns it.
1376 ///
1377 /// The removed element is replaced by the last element of the vector.
1378 ///
1379 /// This does not preserve ordering, but is *O*(1).
1380 /// If you need to preserve the element order, use [`remove`] instead.
1381 ///
1382 /// [`remove`]: Vec::remove
1383 ///
1384 /// # Panics
1385 ///
1386 /// Panics if `index` is out of bounds.
1387 ///
1388 /// # Examples
1389 ///
1390 /// ```
1391 /// use allocator_api2::vec;
1392 ///
1393 /// let mut v = vec!["foo", "bar", "baz", "qux"];
1394 ///
1395 /// assert_eq!(v.swap_remove(1), "bar");
1396 /// assert_eq!(v, ["foo", "qux", "baz"]);
1397 ///
1398 /// assert_eq!(v.swap_remove(0), "foo");
1399 /// assert_eq!(v, ["baz", "qux"]);
1400 /// ```
1401 #[inline(always)]
1402 pub fn swap_remove(&mut self, index: usize) -> T {
1403 #[cold]
1404 #[inline(never)]
1405 fn assert_failed(index: usize, len: usize) -> ! {
1406 panic!(
1407 "swap_remove index (is {}) should be < len (is {})",
1408 index, len
1409 );
1410 }
1411
1412 let len = self.len();
1413 if index >= len {
1414 assert_failed(index, len);
1415 }
1416 unsafe {
1417 // We replace self[index] with the last element. Note that if the
1418 // bounds check above succeeds there must be a last element (which
1419 // can be self[index] itself).
1420 let value = ptr::read(self.as_ptr().add(index));
1421 let base_ptr = self.as_mut_ptr();
1422 ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1);
1423 self.set_len(len - 1);
1424 value
1425 }
1426 }
1427
1428 /// Inserts an element at position `index` within the vector, shifting all
1429 /// elements after it to the right.
1430 ///
1431 /// # Panics
1432 ///
1433 /// Panics if `index > len`.
1434 ///
1435 /// # Examples
1436 ///
1437 /// ```
1438 /// use allocator_api2::vec;
1439 ///
1440 /// let mut vec = vec![1, 2, 3];
1441 /// vec.insert(1, 4);
1442 /// assert_eq!(vec, [1, 4, 2, 3]);
1443 /// vec.insert(4, 5);
1444 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1445 /// ```
1446 #[cfg(not(no_global_oom_handling))]
1447 pub fn insert(&mut self, index: usize, element: T) {
1448 #[cold]
1449 #[inline(never)]
1450 fn assert_failed(index: usize, len: usize) -> ! {
1451 panic!(
1452 "insertion index (is {}) should be <= len (is {})",
1453 index, len
1454 );
1455 }
1456
1457 let len = self.len();
1458
1459 // space for the new element
1460 if len == self.buf.capacity() {
1461 self.reserve(1);
1462 }
1463
1464 unsafe {
1465 // infallible
1466 // The spot to put the new value
1467 {
1468 let p = self.as_mut_ptr().add(index);
1469 match cmp::Ord::cmp(&index, &len) {
1470 Ordering::Less => {
1471 // Shift everything over to make space. (Duplicating the
1472 // `index`th element into two consecutive places.)
1473 ptr::copy(p, p.add(1), len - index);
1474 }
1475 Ordering::Equal => {
1476 // No elements need shifting.
1477 }
1478 Ordering::Greater => {
1479 assert_failed(index, len);
1480 }
1481 }
1482 // Write it in, overwriting the first copy of the `index`th
1483 // element.
1484 ptr::write(p, element);
1485 }
1486 self.set_len(len + 1);
1487 }
1488 }
1489
1490 /// Removes and returns the element at position `index` within the vector,
1491 /// shifting all elements after it to the left.
1492 ///
1493 /// Note: Because this shifts over the remaining elements, it has a
1494 /// worst-case performance of *O*(*n*). If you don't need the order of elements
1495 /// to be preserved, use [`swap_remove`] instead. If you'd like to remove
1496 /// elements from the beginning of the `Vec`, consider using
1497 /// [`VecDeque::pop_front`] instead.
1498 ///
1499 /// [`swap_remove`]: Vec::swap_remove
1500 /// [`VecDeque::pop_front`]: alloc_crate::collections::VecDeque::pop_front
1501 ///
1502 /// # Panics
1503 ///
1504 /// Panics if `index` is out of bounds.
1505 ///
1506 /// # Examples
1507 ///
1508 /// ```
1509 /// use allocator_api2::vec;
1510 ///
1511 /// let mut v = vec![1, 2, 3];
1512 /// assert_eq!(v.remove(1), 2);
1513 /// assert_eq!(v, [1, 3]);
1514 /// ```
1515 #[track_caller]
1516 #[inline(always)]
1517 pub fn remove(&mut self, index: usize) -> T {
1518 #[cold]
1519 #[inline(never)]
1520 #[track_caller]
1521 fn assert_failed(index: usize, len: usize) -> ! {
1522 panic!("removal index (is {}) should be < len (is {})", index, len);
1523 }
1524
1525 let len = self.len();
1526 if index >= len {
1527 assert_failed(index, len);
1528 }
1529 unsafe {
1530 // infallible
1531 let ret;
1532 {
1533 // the place we are taking from.
1534 let ptr = self.as_mut_ptr().add(index);
1535 // copy it out, unsafely having a copy of the value on
1536 // the stack and in the vector at the same time.
1537 ret = ptr::read(ptr);
1538
1539 // Shift everything down to fill in that spot.
1540 ptr::copy(ptr.add(1), ptr, len - index - 1);
1541 }
1542 self.set_len(len - 1);
1543 ret
1544 }
1545 }
1546
1547 /// Retains only the elements specified by the predicate.
1548 ///
1549 /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
1550 /// This method operates in place, visiting each element exactly once in the
1551 /// original order, and preserves the order of the retained elements.
1552 ///
1553 /// # Examples
1554 ///
1555 /// ```
1556 /// use allocator_api2::vec;
1557 ///
1558 /// let mut vec = vec![1, 2, 3, 4];
1559 /// vec.retain(|&x| x % 2 == 0);
1560 /// assert_eq!(vec, [2, 4]);
1561 /// ```
1562 ///
1563 /// Because the elements are visited exactly once in the original order,
1564 /// external state may be used to decide which elements to keep.
1565 ///
1566 /// ```
1567 /// use allocator_api2::vec;
1568 ///
1569 /// let mut vec = vec![1, 2, 3, 4, 5];
1570 /// let keep = [false, true, true, false, true];
1571 /// let mut iter = keep.iter();
1572 /// vec.retain(|_| *iter.next().unwrap());
1573 /// assert_eq!(vec, [2, 3, 5]);
1574 /// ```
1575 #[inline(always)]
1576 pub fn retain<F>(&mut self, mut f: F)
1577 where
1578 F: FnMut(&T) -> bool,
1579 {
1580 self.retain_mut(|elem| f(elem));
1581 }
1582
1583 /// Retains only the elements specified by the predicate, passing a mutable reference to it.
1584 ///
1585 /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`.
1586 /// This method operates in place, visiting each element exactly once in the
1587 /// original order, and preserves the order of the retained elements.
1588 ///
1589 /// # Examples
1590 ///
1591 /// ```
1592 /// use allocator_api2::vec;
1593 ///
1594 /// let mut vec = vec![1, 2, 3, 4];
1595 /// vec.retain_mut(|x| if *x <= 3 {
1596 /// *x += 1;
1597 /// true
1598 /// } else {
1599 /// false
1600 /// });
1601 /// assert_eq!(vec, [2, 3, 4]);
1602 /// ```
1603 #[inline]
1604 pub fn retain_mut<F>(&mut self, mut f: F)
1605 where
1606 F: FnMut(&mut T) -> bool,
1607 {
1608 let original_len = self.len();
1609 // Avoid double drop if the drop guard is not executed,
1610 // since we may make some holes during the process.
1611 unsafe { self.set_len(0) };
1612
1613 // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked]
1614 // |<- processed len ->| ^- next to check
1615 // |<- deleted cnt ->|
1616 // |<- original_len ->|
1617 // Kept: Elements which predicate returns true on.
1618 // Hole: Moved or dropped element slot.
1619 // Unchecked: Unchecked valid elements.
1620 //
1621 // This drop guard will be invoked when predicate or `drop` of element panicked.
1622 // It shifts unchecked elements to cover holes and `set_len` to the correct length.
1623 // In cases when predicate and `drop` never panick, it will be optimized out.
1624 struct BackshiftOnDrop<'a, T, A: Allocator> {
1625 v: &'a mut Vec<T, A>,
1626 processed_len: usize,
1627 deleted_cnt: usize,
1628 original_len: usize,
1629 }
1630
1631 impl<T, A: Allocator> Drop for BackshiftOnDrop<'_, T, A> {
1632 fn drop(&mut self) {
1633 if self.deleted_cnt > 0 {
1634 // SAFETY: Trailing unchecked items must be valid since we never touch them.
1635 unsafe {
1636 ptr::copy(
1637 self.v.as_ptr().add(self.processed_len),
1638 self.v
1639 .as_mut_ptr()
1640 .add(self.processed_len - self.deleted_cnt),
1641 self.original_len - self.processed_len,
1642 );
1643 }
1644 }
1645 // SAFETY: After filling holes, all items are in contiguous memory.
1646 unsafe {
1647 self.v.set_len(self.original_len - self.deleted_cnt);
1648 }
1649 }
1650 }
1651
1652 let mut g = BackshiftOnDrop {
1653 v: self,
1654 processed_len: 0,
1655 deleted_cnt: 0,
1656 original_len,
1657 };
1658
1659 fn process_loop<F, T, A: Allocator, const DELETED: bool>(
1660 original_len: usize,
1661 f: &mut F,
1662 g: &mut BackshiftOnDrop<'_, T, A>,
1663 ) where
1664 F: FnMut(&mut T) -> bool,
1665 {
1666 while g.processed_len != original_len {
1667 // SAFETY: Unchecked element must be valid.
1668 let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) };
1669 if !f(cur) {
1670 // Advance early to avoid double drop if `drop_in_place` panicked.
1671 g.processed_len += 1;
1672 g.deleted_cnt += 1;
1673 // SAFETY: We never touch this element again after dropped.
1674 unsafe { ptr::drop_in_place(cur) };
1675 // We already advanced the counter.
1676 if DELETED {
1677 continue;
1678 } else {
1679 break;
1680 }
1681 }
1682 if DELETED {
1683 // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element.
1684 // We use copy for move, and never touch this element again.
1685 unsafe {
1686 let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt);
1687 ptr::copy_nonoverlapping(cur, hole_slot, 1);
1688 }
1689 }
1690 g.processed_len += 1;
1691 }
1692 }
1693
1694 // Stage 1: Nothing was deleted.
1695 process_loop::<F, T, A, false>(original_len, &mut f, &mut g);
1696
1697 // Stage 2: Some elements were deleted.
1698 process_loop::<F, T, A, true>(original_len, &mut f, &mut g);
1699
1700 // All item are processed. This can be optimized to `set_len` by LLVM.
1701 drop(g);
1702 }
1703
1704 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1705 /// key.
1706 ///
1707 /// If the vector is sorted, this removes all duplicates.
1708 ///
1709 /// # Examples
1710 ///
1711 /// ```
1712 /// use allocator_api2::vec;
1713 ///
1714 /// let mut vec = vec![10, 20, 21, 30, 20];
1715 ///
1716 /// vec.dedup_by_key(|i| *i / 10);
1717 ///
1718 /// assert_eq!(vec, [10, 20, 30, 20]);
1719 /// ```
1720 #[inline(always)]
1721 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1722 where
1723 F: FnMut(&mut T) -> K,
1724 K: PartialEq,
1725 {
1726 self.dedup_by(|a, b| key(a) == key(b))
1727 }
1728
1729 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1730 /// relation.
1731 ///
1732 /// The `same_bucket` function is passed references to two elements from the vector and
1733 /// must determine if the elements compare equal. The elements are passed in opposite order
1734 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1735 ///
1736 /// If the vector is sorted, this removes all duplicates.
1737 ///
1738 /// # Examples
1739 ///
1740 /// ```
1741 /// use allocator_api2::vec;
1742 ///
1743 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1744 ///
1745 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1746 ///
1747 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1748 /// ```
1749 #[inline]
1750 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1751 where
1752 F: FnMut(&mut T, &mut T) -> bool,
1753 {
1754 let len = self.len();
1755 if len <= 1 {
1756 return;
1757 }
1758
1759 /* INVARIANT: vec.len() > read >= write > write-1 >= 0 */
1760 struct FillGapOnDrop<'a, T, A: Allocator> {
1761 /* Offset of the element we want to check if it is duplicate */
1762 read: usize,
1763
1764 /* Offset of the place where we want to place the non-duplicate
1765 * when we find it. */
1766 write: usize,
1767
1768 /* The Vec that would need correction if `same_bucket` panicked */
1769 vec: &'a mut Vec<T, A>,
1770 }
1771
1772 impl<'a, T, A: Allocator> Drop for FillGapOnDrop<'a, T, A> {
1773 fn drop(&mut self) {
1774 /* This code gets executed when `same_bucket` panics */
1775
1776 /* SAFETY: invariant guarantees that `read - write`
1777 * and `len - read` never overflow and that the copy is always
1778 * in-bounds. */
1779 unsafe {
1780 let ptr = self.vec.as_mut_ptr();
1781 let len = self.vec.len();
1782
1783 /* How many items were left when `same_bucket` panicked.
1784 * Basically vec[read..].len() */
1785 let items_left = len.wrapping_sub(self.read);
1786
1787 /* Pointer to first item in vec[write..write+items_left] slice */
1788 let dropped_ptr = ptr.add(self.write);
1789 /* Pointer to first item in vec[read..] slice */
1790 let valid_ptr = ptr.add(self.read);
1791
1792 /* Copy `vec[read..]` to `vec[write..write+items_left]`.
1793 * The slices can overlap, so `copy_nonoverlapping` cannot be used */
1794 ptr::copy(valid_ptr, dropped_ptr, items_left);
1795
1796 /* How many items have been already dropped
1797 * Basically vec[read..write].len() */
1798 let dropped = self.read.wrapping_sub(self.write);
1799
1800 self.vec.set_len(len - dropped);
1801 }
1802 }
1803 }
1804
1805 let mut gap = FillGapOnDrop {
1806 read: 1,
1807 write: 1,
1808 vec: self,
1809 };
1810 let ptr = gap.vec.as_mut_ptr();
1811
1812 /* Drop items while going through Vec, it should be more efficient than
1813 * doing slice partition_dedup + truncate */
1814
1815 /* SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr
1816 * are always in-bounds and read_ptr never aliases prev_ptr */
1817 unsafe {
1818 while gap.read < len {
1819 let read_ptr = ptr.add(gap.read);
1820 let prev_ptr = ptr.add(gap.write.wrapping_sub(1));
1821
1822 if same_bucket(&mut *read_ptr, &mut *prev_ptr) {
1823 // Increase `gap.read` now since the drop may panic.
1824 gap.read += 1;
1825 /* We have found duplicate, drop it in-place */
1826 ptr::drop_in_place(read_ptr);
1827 } else {
1828 let write_ptr = ptr.add(gap.write);
1829
1830 /* Because `read_ptr` can be equal to `write_ptr`, we either
1831 * have to use `copy` or conditional `copy_nonoverlapping`.
1832 * Looks like the first option is faster. */
1833 ptr::copy(read_ptr, write_ptr, 1);
1834
1835 /* We have filled that place, so go further */
1836 gap.write += 1;
1837 gap.read += 1;
1838 }
1839 }
1840
1841 /* Technically we could let `gap` clean up with its Drop, but
1842 * when `same_bucket` is guaranteed to not panic, this bloats a little
1843 * the codegen, so we just do it manually */
1844 gap.vec.set_len(gap.write);
1845 mem::forget(gap);
1846 }
1847 }
1848
1849 /// Appends an element to the back of a collection.
1850 ///
1851 /// # Panics
1852 ///
1853 /// Panics if the new capacity exceeds `isize::MAX` bytes.
1854 ///
1855 /// # Examples
1856 ///
1857 /// ```
1858 /// use allocator_api2::vec;
1859 ///
1860 /// let mut vec = vec![1, 2];
1861 /// vec.push(3);
1862 /// assert_eq!(vec, [1, 2, 3]);
1863 /// ```
1864 #[cfg(not(no_global_oom_handling))]
1865 #[inline(always)]
1866 pub fn push(&mut self, value: T) {
1867 // This will panic or abort if we would allocate > isize::MAX bytes
1868 // or if the length increment would overflow for zero-sized types.
1869 if self.len == self.buf.capacity() {
1870 self.buf.reserve_for_push(self.len);
1871 }
1872 unsafe {
1873 let end = self.as_mut_ptr().add(self.len);
1874 ptr::write(end, value);
1875 self.len += 1;
1876 }
1877 }
1878
1879 /// Appends an element if there is sufficient spare capacity, otherwise an error is returned
1880 /// with the element.
1881 ///
1882 /// Unlike [`push`] this method will not reallocate when there's insufficient capacity.
1883 /// The caller should use [`reserve`] or [`try_reserve`] to ensure that there is enough capacity.
1884 ///
1885 /// [`push`]: Vec::push
1886 /// [`reserve`]: Vec::reserve
1887 /// [`try_reserve`]: Vec::try_reserve
1888 ///
1889 /// # Examples
1890 ///
1891 /// A manual, panic-free alternative to [`FromIterator`]:
1892 ///
1893 /// ```
1894 /// use std::iter::FromIterator;
1895 ///
1896 /// use allocator_api2::{vec::Vec, collections::TryReserveError};
1897 ///
1898 /// fn from_iter_fallible<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, TryReserveError> {
1899 /// let mut vec = Vec::new();
1900 /// for value in iter {
1901 /// if let Err(value) = vec.push_within_capacity(value) {
1902 /// vec.try_reserve(1)?;
1903 /// // this cannot fail, the previous line either returned or added at least 1 free slot
1904 /// let _ = vec.push_within_capacity(value);
1905 /// }
1906 /// }
1907 /// Ok(vec)
1908 /// }
1909 /// assert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100)));
1910 /// ```
1911 #[inline(always)]
1912 pub fn push_within_capacity(&mut self, value: T) -> Result<(), T> {
1913 if self.len == self.buf.capacity() {
1914 return Err(value);
1915 }
1916 unsafe {
1917 let end = self.as_mut_ptr().add(self.len);
1918 ptr::write(end, value);
1919 self.len += 1;
1920 }
1921 Ok(())
1922 }
1923
1924 /// Removes the last element from a vector and returns it, or [`None`] if it
1925 /// is empty.
1926 ///
1927 /// If you'd like to pop the first element, consider using
1928 /// [`VecDeque::pop_front`] instead.
1929 ///
1930 /// [`VecDeque::pop_front`]: alloc_crate::collections::VecDeque::pop_front
1931 ///
1932 /// # Examples
1933 ///
1934 /// ```
1935 /// use allocator_api2::vec;
1936 ///
1937 /// let mut vec = vec![1, 2, 3];
1938 /// assert_eq!(vec.pop(), Some(3));
1939 /// assert_eq!(vec, [1, 2]);
1940 /// ```
1941 #[inline(always)]
1942 pub fn pop(&mut self) -> Option<T> {
1943 if self.len == 0 {
1944 None
1945 } else {
1946 unsafe {
1947 self.len -= 1;
1948 Some(ptr::read(self.as_ptr().add(self.len())))
1949 }
1950 }
1951 }
1952
1953 /// Moves all the elements of `other` into `self`, leaving `other` empty.
1954 ///
1955 /// # Panics
1956 ///
1957 /// Panics if the new capacity exceeds `isize::MAX` bytes.
1958 ///
1959 /// # Examples
1960 ///
1961 /// ```
1962 /// use allocator_api2::vec;
1963 ///
1964 /// let mut vec = vec![1, 2, 3];
1965 /// let mut vec2 = vec![4, 5, 6];
1966 /// vec.append(&mut vec2);
1967 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1968 /// assert_eq!(vec2, []);
1969 /// ```
1970 #[cfg(not(no_global_oom_handling))]
1971 #[inline(always)]
1972 pub fn append(&mut self, other: &mut Self) {
1973 unsafe {
1974 self.append_elements(other.as_slice() as _);
1975 other.set_len(0);
1976 }
1977 }
1978
1979 /// Appends elements to `self` from other buffer.
1980 #[cfg(not(no_global_oom_handling))]
1981 #[inline(always)]
1982 unsafe fn append_elements(&mut self, other: *const [T]) {
1983 let count = unsafe { (&(*other)).len() };
1984 self.reserve(count);
1985 let len = self.len();
1986 unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
1987 self.len += count;
1988 }
1989
1990 /// Removes the specified range from the vector in bulk, returning all
1991 /// removed elements as an iterator. If the iterator is dropped before
1992 /// being fully consumed, it drops the remaining removed elements.
1993 ///
1994 /// The returned iterator keeps a mutable borrow on the vector to optimize
1995 /// its implementation.
1996 ///
1997 /// # Panics
1998 ///
1999 /// Panics if the starting point is greater than the end point or if
2000 /// the end point is greater than the length of the vector.
2001 ///
2002 /// # Leaking
2003 ///
2004 /// If the returned iterator goes out of scope without being dropped (due to
2005 /// [`mem::forget`], for example), the vector may have lost and leaked
2006 /// elements arbitrarily, including elements outside the range.
2007 ///
2008 /// # Examples
2009 ///
2010 /// ```
2011 /// use allocator_api2::{vec, vec::Vec};
2012 ///
2013 /// let mut v = vec![1, 2, 3];
2014 /// let u: Vec<_> = v.drain(1..).collect();
2015 /// assert_eq!(v, &[1]);
2016 /// assert_eq!(u, &[2, 3]);
2017 ///
2018 /// // A full range clears the vector, like `clear()` does
2019 /// v.drain(..);
2020 /// assert_eq!(v, &[]);
2021 /// ```
2022 #[inline(always)]
2023 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
2024 where
2025 R: RangeBounds<usize>,
2026 {
2027 // Memory safety
2028 //
2029 // When the Drain is first created, it shortens the length of
2030 // the source vector to make sure no uninitialized or moved-from elements
2031 // are accessible at all if the Drain's destructor never gets to run.
2032 //
2033 // Drain will ptr::read out the values to remove.
2034 // When finished, remaining tail of the vec is copied back to cover
2035 // the hole, and the vector length is restored to the new length.
2036 //
2037 let len = self.len();
2038
2039 // Replaced by code below
2040 // let Range { start, end } = slice::range(range, ..len);
2041
2042 // Panics if range is out of bounds
2043 let _ = &self.as_slice()[(range.start_bound().cloned(), range.end_bound().cloned())];
2044
2045 let start = match range.start_bound() {
2046 Bound::Included(&n) => n,
2047 Bound::Excluded(&n) => n + 1,
2048 Bound::Unbounded => 0,
2049 };
2050 let end = match range.end_bound() {
2051 Bound::Included(&n) => n + 1,
2052 Bound::Excluded(&n) => n,
2053 Bound::Unbounded => len,
2054 };
2055
2056 unsafe {
2057 // set self.vec length's to start, to be safe in case Drain is leaked
2058 self.set_len(start);
2059 let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
2060 Drain {
2061 tail_start: end,
2062 tail_len: len - end,
2063 iter: range_slice.iter(),
2064 vec: NonNull::from(self),
2065 }
2066 }
2067 }
2068
2069 /// Clears the vector, removing all values.
2070 ///
2071 /// Note that this method has no effect on the allocated capacity
2072 /// of the vector.
2073 ///
2074 /// # Examples
2075 ///
2076 /// ```
2077 /// use allocator_api2::vec;
2078 ///
2079 /// let mut v = vec![1, 2, 3];
2080 ///
2081 /// v.clear();
2082 ///
2083 /// assert!(v.is_empty());
2084 /// ```
2085 #[inline(always)]
2086 pub fn clear(&mut self) {
2087 let elems: *mut [T] = self.as_mut_slice();
2088
2089 // SAFETY:
2090 // - `elems` comes directly from `as_mut_slice` and is therefore valid.
2091 // - Setting `self.len` before calling `drop_in_place` means that,
2092 // if an element's `Drop` impl panics, the vector's `Drop` impl will
2093 // do nothing (leaking the rest of the elements) instead of dropping
2094 // some twice.
2095 unsafe {
2096 self.len = 0;
2097 ptr::drop_in_place(elems);
2098 }
2099 }
2100
2101 /// Returns the number of elements in the vector, also referred to
2102 /// as its 'length'.
2103 ///
2104 /// # Examples
2105 ///
2106 /// ```
2107 /// use allocator_api2::vec;
2108 ///
2109 /// let a = vec![1, 2, 3];
2110 /// assert_eq!(a.len(), 3);
2111 /// ```
2112 #[inline(always)]
2113 pub fn len(&self) -> usize {
2114 self.len
2115 }
2116
2117 /// Returns `true` if the vector contains no elements.
2118 ///
2119 /// # Examples
2120 ///
2121 /// ```
2122 /// use allocator_api2::vec::Vec;
2123 ///
2124 /// let mut v = Vec::new();
2125 /// assert!(v.is_empty());
2126 ///
2127 /// v.push(1);
2128 /// assert!(!v.is_empty());
2129 /// ```
2130 #[inline(always)]
2131 pub fn is_empty(&self) -> bool {
2132 self.len() == 0
2133 }
2134
2135 /// Splits the collection into two at the given index.
2136 ///
2137 /// Returns a newly allocated vector containing the elements in the range
2138 /// `[at, len)`. After the call, the original vector will be left containing
2139 /// the elements `[0, at)` with its previous capacity unchanged.
2140 ///
2141 /// # Panics
2142 ///
2143 /// Panics if `at > len`.
2144 ///
2145 /// # Examples
2146 ///
2147 /// ```
2148 /// use allocator_api2::vec;
2149 ///
2150 /// let mut vec = vec![1, 2, 3];
2151 /// let vec2 = vec.split_off(1);
2152 /// assert_eq!(vec, [1]);
2153 /// assert_eq!(vec2, [2, 3]);
2154 /// ```
2155 #[cfg(not(no_global_oom_handling))]
2156 #[inline(always)]
2157 #[must_use = "use `.truncate()` if you don't need the other half"]
2158 pub fn split_off(&mut self, at: usize) -> Self
2159 where
2160 A: Clone,
2161 {
2162 #[cold]
2163 #[inline(never)]
2164 fn assert_failed(at: usize, len: usize) -> ! {
2165 panic!("`at` split index (is {}) should be <= len (is {})", at, len);
2166 }
2167
2168 if at > self.len() {
2169 assert_failed(at, self.len());
2170 }
2171
2172 if at == 0 {
2173 // the new vector can take over the original buffer and avoid the copy
2174 return mem::replace(
2175 self,
2176 Vec::with_capacity_in(self.capacity(), self.allocator().clone()),
2177 );
2178 }
2179
2180 let other_len = self.len - at;
2181 let mut other = Vec::with_capacity_in(other_len, self.allocator().clone());
2182
2183 // Unsafely `set_len` and copy items to `other`.
2184 unsafe {
2185 self.set_len(at);
2186 other.set_len(other_len);
2187
2188 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
2189 }
2190 other
2191 }
2192
2193 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
2194 ///
2195 /// If `new_len` is greater than `len`, the `Vec` is extended by the
2196 /// difference, with each additional slot filled with the result of
2197 /// calling the closure `f`. The return values from `f` will end up
2198 /// in the `Vec` in the order they have been generated.
2199 ///
2200 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
2201 ///
2202 /// This method uses a closure to create new values on every push. If
2203 /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you
2204 /// want to use the [`Default`] trait to generate values, you can
2205 /// pass [`Default::default`] as the second argument.
2206 ///
2207 /// # Examples
2208 ///
2209 /// ```
2210 /// use allocator_api2::vec;
2211 ///
2212 /// let mut vec = vec![1, 2, 3];
2213 /// vec.resize_with(5, Default::default);
2214 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
2215 ///
2216 /// let mut vec = vec![];
2217 /// let mut p = 1;
2218 /// vec.resize_with(4, || { p *= 2; p });
2219 /// assert_eq!(vec, [2, 4, 8, 16]);
2220 /// ```
2221 #[cfg(not(no_global_oom_handling))]
2222 #[inline(always)]
2223 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
2224 where
2225 F: FnMut() -> T,
2226 {
2227 let len = self.len();
2228 if new_len > len {
2229 self.extend(iter::repeat_with(f).take(new_len - len));
2230 } else {
2231 self.truncate(new_len);
2232 }
2233 }
2234
2235 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
2236 /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
2237 /// `'a`. If the type has only static references, or none at all, then this
2238 /// may be chosen to be `'static`.
2239 ///
2240 /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`,
2241 /// so the leaked allocation may include unused capacity that is not part
2242 /// of the returned slice.
2243 ///
2244 /// This function is mainly useful for data that lives for the remainder of
2245 /// the program's life. Dropping the returned reference will cause a memory
2246 /// leak.
2247 ///
2248 /// # Examples
2249 ///
2250 /// Simple usage:
2251 ///
2252 /// ```
2253 /// use allocator_api2::vec;
2254 ///
2255 /// let x = vec![1, 2, 3];
2256 /// let static_ref: &'static mut [usize] = x.leak();
2257 /// static_ref[0] += 1;
2258 /// assert_eq!(static_ref, &[2, 2, 3]);
2259 /// ```
2260 #[inline(always)]
2261 pub fn leak<'a>(self) -> &'a mut [T]
2262 where
2263 A: 'a,
2264 {
2265 let mut me = ManuallyDrop::new(self);
2266 unsafe { slice::from_raw_parts_mut(me.as_mut_ptr(), me.len) }
2267 }
2268
2269 /// Returns the remaining spare capacity of the vector as a slice of
2270 /// `MaybeUninit<T>`.
2271 ///
2272 /// The returned slice can be used to fill the vector with data (e.g. by
2273 /// reading from a file) before marking the data as initialized using the
2274 /// [`set_len`] method.
2275 ///
2276 /// [`set_len`]: Vec::set_len
2277 ///
2278 /// # Examples
2279 ///
2280 /// ```
2281 /// use allocator_api2::vec::Vec;
2282 ///
2283 /// // Allocate vector big enough for 10 elements.
2284 /// let mut v = Vec::with_capacity(10);
2285 ///
2286 /// // Fill in the first 3 elements.
2287 /// let uninit = v.spare_capacity_mut();
2288 /// uninit[0].write(0);
2289 /// uninit[1].write(1);
2290 /// uninit[2].write(2);
2291 ///
2292 /// // Mark the first 3 elements of the vector as being initialized.
2293 /// unsafe {
2294 /// v.set_len(3);
2295 /// }
2296 ///
2297 /// assert_eq!(&v, &[0, 1, 2]);
2298 /// ```
2299 #[inline(always)]
2300 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
2301 // Note:
2302 // This method is not implemented in terms of `split_at_spare_mut`,
2303 // to prevent invalidation of pointers to the buffer.
2304 unsafe {
2305 slice::from_raw_parts_mut(
2306 self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
2307 self.buf.capacity() - self.len,
2308 )
2309 }
2310 }
2311
2312 /// Returns vector content as a slice of `T`, along with the remaining spare
2313 /// capacity of the vector as a slice of `MaybeUninit<T>`.
2314 ///
2315 /// The returned spare capacity slice can be used to fill the vector with data
2316 /// (e.g. by reading from a file) before marking the data as initialized using
2317 /// the [`set_len`] method.
2318 ///
2319 /// [`set_len`]: Vec::set_len
2320 ///
2321 /// Note that this is a low-level API, which should be used with care for
2322 /// optimization purposes. If you need to append data to a `Vec`
2323 /// you can use [`push`], [`extend`], [`extend_from_slice`],
2324 /// [`extend_from_within`], [`insert`], [`append`], [`resize`] or
2325 /// [`resize_with`], depending on your exact needs.
2326 ///
2327 /// [`push`]: Vec::push
2328 /// [`extend`]: Vec::extend
2329 /// [`extend_from_slice`]: Vec::extend_from_slice
2330 /// [`extend_from_within`]: Vec::extend_from_within
2331 /// [`insert`]: Vec::insert
2332 /// [`append`]: Vec::append
2333 /// [`resize`]: Vec::resize
2334 /// [`resize_with`]: Vec::resize_with
2335 ///
2336 /// # Examples
2337 ///
2338 /// ```
2339 /// use allocator_api2::vec;
2340 ///
2341 /// let mut v = vec![1, 1, 2];
2342 ///
2343 /// // Reserve additional space big enough for 10 elements.
2344 /// v.reserve(10);
2345 ///
2346 /// let (init, uninit) = v.split_at_spare_mut();
2347 /// let sum = init.iter().copied().sum::<u32>();
2348 ///
2349 /// // Fill in the next 4 elements.
2350 /// uninit[0].write(sum);
2351 /// uninit[1].write(sum * 2);
2352 /// uninit[2].write(sum * 3);
2353 /// uninit[3].write(sum * 4);
2354 ///
2355 /// // Mark the 4 elements of the vector as being initialized.
2356 /// unsafe {
2357 /// let len = v.len();
2358 /// v.set_len(len + 4);
2359 /// }
2360 ///
2361 /// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
2362 /// ```
2363 #[inline(always)]
2364 pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
2365 // SAFETY:
2366 // - len is ignored and so never changed
2367 let (init, spare, _) = unsafe { self.split_at_spare_mut_with_len() };
2368 (init, spare)
2369 }
2370
2371 /// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`.
2372 ///
2373 /// This method provides unique access to all vec parts at once in `extend_from_within`.
2374 unsafe fn split_at_spare_mut_with_len(
2375 &mut self,
2376 ) -> (&mut [T], &mut [MaybeUninit<T>], &mut usize) {
2377 let ptr = self.as_mut_ptr();
2378 // SAFETY:
2379 // - `ptr` is guaranteed to be valid for `self.len` elements
2380 // - but the allocation extends out to `self.buf.capacity()` elements, possibly
2381 // uninitialized
2382 let spare_ptr = unsafe { ptr.add(self.len) };
2383 let spare_ptr = spare_ptr.cast::<MaybeUninit<T>>();
2384 let spare_len = self.buf.capacity() - self.len;
2385
2386 // SAFETY:
2387 // - `ptr` is guaranteed to be valid for `self.len` elements
2388 // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized`
2389 unsafe {
2390 let initialized = slice::from_raw_parts_mut(ptr, self.len);
2391 let spare = slice::from_raw_parts_mut(spare_ptr, spare_len);
2392
2393 (initialized, spare, &mut self.len)
2394 }
2395 }
2396}
2397
2398impl<T: Clone, A: Allocator> Vec<T, A> {
2399 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
2400 ///
2401 /// If `new_len` is greater than `len`, the `Vec` is extended by the
2402 /// difference, with each additional slot filled with `value`.
2403 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
2404 ///
2405 /// This method requires `T` to implement [`Clone`],
2406 /// in order to be able to clone the passed value.
2407 /// If you need more flexibility (or want to rely on [`Default`] instead of
2408 /// [`Clone`]), use [`Vec::resize_with`].
2409 /// If you only need to resize to a smaller size, use [`Vec::truncate`].
2410 ///
2411 /// # Examples
2412 ///
2413 /// ```
2414 /// use allocator_api2::vec;
2415 ///
2416 /// let mut vec = vec!["hello"];
2417 /// vec.resize(3, "world");
2418 /// assert_eq!(vec, ["hello", "world", "world"]);
2419 ///
2420 /// let mut vec = vec![1, 2, 3, 4];
2421 /// vec.resize(2, 0);
2422 /// assert_eq!(vec, [1, 2]);
2423 /// ```
2424 #[cfg(not(no_global_oom_handling))]
2425 #[inline(always)]
2426 pub fn resize(&mut self, new_len: usize, value: T) {
2427 let len = self.len();
2428
2429 if new_len > len {
2430 self.extend_with(new_len - len, ExtendElement(value))
2431 } else {
2432 self.truncate(new_len);
2433 }
2434 }
2435
2436 /// Clones and appends all elements in a slice to the `Vec`.
2437 ///
2438 /// Iterates over the slice `other`, clones each element, and then appends
2439 /// it to this `Vec`. The `other` slice is traversed in-order.
2440 ///
2441 /// Note that this function is same as [`extend`] except that it is
2442 /// specialized to work with slices instead. If and when Rust gets
2443 /// specialization this function will likely be deprecated (but still
2444 /// available).
2445 ///
2446 /// # Examples
2447 ///
2448 /// ```
2449 /// let mut vec = vec![1];
2450 /// vec.extend_from_slice(&[2, 3, 4]);
2451 /// assert_eq!(vec, [1, 2, 3, 4]);
2452 /// ```
2453 ///
2454 /// [`extend`]: Vec::extend
2455 #[cfg(not(no_global_oom_handling))]
2456 #[inline(always)]
2457 pub fn extend_from_slice(&mut self, other: &[T]) {
2458 self.extend(other.iter().cloned())
2459 }
2460
2461 /// Copies elements from `src` range to the end of the vector.
2462 ///
2463 /// # Panics
2464 ///
2465 /// Panics if the starting point is greater than the end point or if
2466 /// the end point is greater than the length of the vector.
2467 ///
2468 /// # Examples
2469 ///
2470 /// ```
2471 /// use allocator_api2::vec;
2472 ///
2473 /// let mut vec = vec![0, 1, 2, 3, 4];
2474 ///
2475 /// vec.extend_from_within(2..);
2476 /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);
2477 ///
2478 /// vec.extend_from_within(..2);
2479 /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);
2480 ///
2481 /// vec.extend_from_within(4..8);
2482 /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
2483 /// ```
2484 #[cfg(not(no_global_oom_handling))]
2485 #[inline(always)]
2486 pub fn extend_from_within<R>(&mut self, src: R)
2487 where
2488 R: RangeBounds<usize>,
2489 {
2490 // let range = slice::range(src, ..self.len());
2491
2492 let _ = &self.as_slice()[(src.start_bound().cloned(), src.end_bound().cloned())];
2493
2494 let len = self.len();
2495
2496 let start: ops::Bound<&usize> = src.start_bound();
2497 let start = match start {
2498 ops::Bound::Included(&start) => start,
2499 ops::Bound::Excluded(start) => start + 1,
2500 ops::Bound::Unbounded => 0,
2501 };
2502
2503 let end: ops::Bound<&usize> = src.end_bound();
2504 let end = match end {
2505 ops::Bound::Included(end) => end + 1,
2506 ops::Bound::Excluded(&end) => end,
2507 ops::Bound::Unbounded => len,
2508 };
2509
2510 let range = start..end;
2511
2512 self.reserve(range.len());
2513
2514 // SAFETY:
2515 // - len is increased only after initializing elements
2516 let (this, spare, len) = unsafe { self.split_at_spare_mut_with_len() };
2517
2518 // SAFETY:
2519 // - caller guarantees that src is a valid index
2520 let to_clone = unsafe { this.get_unchecked(range) };
2521
2522 iter::zip(to_clone, spare)
2523 .map(|(src, dst)| dst.write(src.clone()))
2524 // Note:
2525 // - Element was just initialized with `MaybeUninit::write`, so it's ok to increase len
2526 // - len is increased after each element to prevent leaks (see issue #82533)
2527 .for_each(|_| *len += 1);
2528 }
2529}
2530
2531impl<T, A: Allocator, const N: usize> Vec<[T; N], A> {
2532 /// Takes a `Vec<[T; N]>` and flattens it into a `Vec<T>`.
2533 ///
2534 /// # Panics
2535 ///
2536 /// Panics if the length of the resulting vector would overflow a `usize`.
2537 ///
2538 /// This is only possible when flattening a vector of arrays of zero-sized
2539 /// types, and thus tends to be irrelevant in practice. If
2540 /// `size_of::<T>() > 0`, this will never panic.
2541 ///
2542 /// # Examples
2543 ///
2544 /// ```
2545 /// use allocator_api2::vec;
2546 ///
2547 /// let mut vec = vec![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
2548 /// assert_eq!(vec.pop(), Some([7, 8, 9]));
2549 ///
2550 /// let mut flattened = vec.into_flattened();
2551 /// assert_eq!(flattened.pop(), Some(6));
2552 /// ```
2553 #[inline(always)]
2554 pub fn into_flattened(self) -> Vec<T, A> {
2555 let (ptr, len, cap, alloc) = self.into_raw_parts_with_alloc();
2556 let (new_len, new_cap) = if size_of::<T>() == 0 {
2557 (len.checked_mul(N).expect("vec len overflow"), usize::MAX)
2558 } else {
2559 // SAFETY:
2560 // - `cap * N` cannot overflow because the allocation is already in
2561 // the address space.
2562 // - Each `[T; N]` has `N` valid elements, so there are `len * N`
2563 // valid elements in the allocation.
2564 (len * N, cap * N)
2565 };
2566 // SAFETY:
2567 // - `ptr` was allocated by `self`
2568 // - `ptr` is well-aligned because `[T; N]` has the same alignment as `T`.
2569 // - `new_cap` refers to the same sized allocation as `cap` because
2570 // `new_cap * size_of::<T>()` == `cap * size_of::<[T; N]>()`
2571 // - `len` <= `cap`, so `len * N` <= `cap * N`.
2572 unsafe { Vec::<T, A>::from_raw_parts_in(ptr.cast(), new_len, new_cap, alloc) }
2573 }
2574}
2575
2576// This code generalizes `extend_with_{element,default}`.
2577trait ExtendWith<T> {
2578 fn next(&mut self) -> T;
2579 fn last(self) -> T;
2580}
2581
2582struct ExtendElement<T>(T);
2583impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
2584 #[inline(always)]
2585 fn next(&mut self) -> T {
2586 self.0.clone()
2587 }
2588
2589 #[inline(always)]
2590 fn last(self) -> T {
2591 self.0
2592 }
2593}
2594
2595impl<T, A: Allocator> Vec<T, A> {
2596 #[cfg(not(no_global_oom_handling))]
2597 #[inline(always)]
2598 /// Extend the vector by `n` values, using the given generator.
2599 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
2600 self.reserve(n);
2601
2602 unsafe {
2603 let mut ptr = self.as_mut_ptr().add(self.len());
2604 // Use SetLenOnDrop to work around bug where compiler
2605 // might not realize the store through `ptr` through self.set_len()
2606 // don't alias.
2607 let mut local_len = SetLenOnDrop::new(&mut self.len);
2608
2609 // Write all elements except the last one
2610 for _ in 1..n {
2611 ptr::write(ptr, value.next());
2612 ptr = ptr.add(1);
2613 // Increment the length in every step in case next() panics
2614 local_len.increment_len(1);
2615 }
2616
2617 if n > 0 {
2618 // We can write the last element directly without cloning needlessly
2619 ptr::write(ptr, value.last());
2620 local_len.increment_len(1);
2621 }
2622
2623 // len set by scope guard
2624 }
2625 }
2626}
2627
2628impl<T: PartialEq, A: Allocator> Vec<T, A> {
2629 /// Removes consecutive repeated elements in the vector according to the
2630 /// [`PartialEq`] trait implementation.
2631 ///
2632 /// If the vector is sorted, this removes all duplicates.
2633 ///
2634 /// # Examples
2635 ///
2636 /// ```
2637 /// use allocator_api2::vec;
2638 ///
2639 /// let mut vec = vec![1, 2, 2, 3, 2];
2640 ///
2641 /// vec.dedup();
2642 ///
2643 /// assert_eq!(vec, [1, 2, 3, 2]);
2644 /// ```
2645 #[inline(always)]
2646 pub fn dedup(&mut self) {
2647 self.dedup_by(|a, b| a == b)
2648 }
2649}
2650
2651////////////////////////////////////////////////////////////////////////////////
2652// Common trait implementations for Vec
2653////////////////////////////////////////////////////////////////////////////////
2654
2655impl<T, A: Allocator> ops::Deref for Vec<T, A> {
2656 type Target = [T];
2657
2658 #[inline(always)]
2659 fn deref(&self) -> &[T] {
2660 unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
2661 }
2662}
2663
2664impl<T, A: Allocator> ops::DerefMut for Vec<T, A> {
2665 #[inline(always)]
2666 fn deref_mut(&mut self) -> &mut [T] {
2667 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
2668 }
2669}
2670
2671#[cfg(not(no_global_oom_handling))]
2672impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> {
2673 #[inline(always)]
2674 fn clone(&self) -> Self {
2675 let alloc = self.allocator().clone();
2676 let mut vec = Vec::with_capacity_in(self.len(), alloc);
2677 vec.extend_from_slice(self);
2678 vec
2679 }
2680
2681 #[inline(always)]
2682 fn clone_from(&mut self, other: &Self) {
2683 // drop anything that will not be overwritten
2684 self.truncate(other.len());
2685
2686 // self.len <= other.len due to the truncate above, so the
2687 // slices here are always in-bounds.
2688 let (init, tail) = other.split_at(self.len());
2689
2690 // reuse the contained values' allocations/resources.
2691 self.clone_from_slice(init);
2692 self.extend_from_slice(tail);
2693 }
2694}
2695
2696/// The hash of a vector is the same as that of the corresponding slice,
2697/// as required by the `core::borrow::Borrow` implementation.
2698///
2699/// ```
2700/// use std::hash::BuildHasher;
2701///
2702/// use allocator_api2::{vec, vec::Vec};
2703///
2704/// let b = std::hash::RandomState::new();
2705/// let v: Vec<u8> = vec![0xa8, 0x3c, 0x09];
2706/// let s: &[u8] = &[0xa8, 0x3c, 0x09];
2707/// assert_eq!(b.hash_one(v), b.hash_one(s));
2708/// ```
2709impl<T: Hash, A: Allocator> Hash for Vec<T, A> {
2710 #[inline(always)]
2711 fn hash<H: Hasher>(&self, state: &mut H) {
2712 Hash::hash(&**self, state)
2713 }
2714}
2715
2716impl<T, I: SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> {
2717 type Output = I::Output;
2718
2719 #[inline(always)]
2720 fn index(&self, index: I) -> &Self::Output {
2721 Index::index(&**self, index)
2722 }
2723}
2724
2725impl<T, I: SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> {
2726 #[inline(always)]
2727 fn index_mut(&mut self, index: I) -> &mut Self::Output {
2728 IndexMut::index_mut(&mut **self, index)
2729 }
2730}
2731
2732#[cfg(not(no_global_oom_handling))]
2733impl<T> FromIterator<T> for Vec<T> {
2734 #[inline(always)]
2735 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
2736 let mut vec = Vec::new();
2737 vec.extend(iter);
2738 vec
2739 }
2740}
2741
2742impl<T, A: Allocator> IntoIterator for Vec<T, A> {
2743 type Item = T;
2744 type IntoIter = IntoIter<T, A>;
2745
2746 /// Creates a consuming iterator, that is, one that moves each value out of
2747 /// the vector (from start to end). The vector cannot be used after calling
2748 /// this.
2749 ///
2750 /// # Examples
2751 ///
2752 /// ```
2753 /// use allocator_api2::vec;
2754 ///
2755 /// let v = vec!["a".to_string(), "b".to_string()];
2756 /// let mut v_iter = v.into_iter();
2757 ///
2758 /// let first_element: Option<String> = v_iter.next();
2759 ///
2760 /// assert_eq!(first_element, Some("a".to_string()));
2761 /// assert_eq!(v_iter.next(), Some("b".to_string()));
2762 /// assert_eq!(v_iter.next(), None);
2763 /// ```
2764 #[inline(always)]
2765 fn into_iter(self) -> Self::IntoIter {
2766 unsafe {
2767 let mut me = ManuallyDrop::new(self);
2768 let alloc = ManuallyDrop::new(ptr::read(me.allocator()));
2769 let begin = me.as_mut_ptr();
2770 let end = if size_of::<T>() == 0 {
2771 begin.cast::<u8>().wrapping_add(me.len()).cast()
2772 } else {
2773 begin.add(me.len()) as *const T
2774 };
2775 let cap = me.buf.capacity();
2776 IntoIter {
2777 buf: NonNull::new_unchecked(begin),
2778 phantom: PhantomData,
2779 cap,
2780 alloc,
2781 ptr: begin,
2782 end,
2783 }
2784 }
2785 }
2786}
2787
2788impl<'a, T, A: Allocator> IntoIterator for &'a Vec<T, A> {
2789 type Item = &'a T;
2790 type IntoIter = slice::Iter<'a, T>;
2791
2792 #[inline(always)]
2793 fn into_iter(self) -> Self::IntoIter {
2794 self.iter()
2795 }
2796}
2797
2798impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A> {
2799 type Item = &'a mut T;
2800 type IntoIter = slice::IterMut<'a, T>;
2801
2802 fn into_iter(self) -> Self::IntoIter {
2803 self.iter_mut()
2804 }
2805}
2806
2807#[cfg(not(no_global_oom_handling))]
2808impl<T, A: Allocator> Extend<T> for Vec<T, A> {
2809 #[inline(always)]
2810 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2811 // This is the case for a general iter.
2812 //
2813 // This function should be the moral equivalent of:
2814 //
2815 // for item in iter {
2816 // self.push(item);
2817 // }
2818
2819 let mut iter = iter.into_iter();
2820 while let Some(element) = iter.next() {
2821 let len = self.len();
2822 if len == self.capacity() {
2823 let (lower, _) = iter.size_hint();
2824 self.reserve(lower.saturating_add(1));
2825 }
2826 unsafe {
2827 ptr::write(self.as_mut_ptr().add(len), element);
2828 // Since next() executes user code which can panic we have to bump the length
2829 // after each step.
2830 // NB can't overflow since we would have had to alloc the address space
2831 self.set_len(len + 1);
2832 }
2833 }
2834 }
2835}
2836
2837impl<T, A: Allocator> Vec<T, A> {
2838 /// Creates a splicing iterator that replaces the specified range in the vector
2839 /// with the given `replace_with` iterator and yields the removed items.
2840 /// `replace_with` does not need to be the same length as `range`.
2841 ///
2842 /// `range` is removed even if the iterator is not consumed until the end.
2843 ///
2844 /// It is unspecified how many elements are removed from the vector
2845 /// if the `Splice` value is leaked.
2846 ///
2847 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2848 ///
2849 /// This is optimal if:
2850 ///
2851 /// * The tail (elements in the vector after `range`) is empty,
2852 /// * or `replace_with` yields fewer or equal elements than `range`’s length
2853 /// * or the lower bound of its `size_hint()` is exact.
2854 ///
2855 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2856 ///
2857 /// # Panics
2858 ///
2859 /// Panics if the starting point is greater than the end point or if
2860 /// the end point is greater than the length of the vector.
2861 ///
2862 /// # Examples
2863 ///
2864 /// ```
2865 /// use allocator_api2::{vec, vec::Vec};
2866 ///
2867 /// let mut v = vec![1, 2, 3, 4];
2868 /// let new = [7, 8, 9];
2869 /// let u: Vec<_> = v.splice(1..3, new).collect();
2870 /// assert_eq!(v, &[1, 7, 8, 9, 4]);
2871 /// assert_eq!(u, &[2, 3]);
2872 /// ```
2873 #[cfg(not(no_global_oom_handling))]
2874 #[inline(always)]
2875 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A>
2876 where
2877 R: RangeBounds<usize>,
2878 I: IntoIterator<Item = T>,
2879 {
2880 Splice {
2881 drain: self.drain(range),
2882 replace_with: replace_with.into_iter(),
2883 }
2884 }
2885}
2886
2887/// Extend implementation that copies elements out of references before pushing them onto the Vec.
2888///
2889/// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2890/// append the entire slice at once.
2891///
2892/// [`copy_from_slice`]: slice::copy_from_slice
2893#[cfg(not(no_global_oom_handling))]
2894impl<'a, T: Copy + 'a, A: Allocator + 'a> Extend<&'a T> for Vec<T, A> {
2895 #[inline(always)]
2896 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2897 let mut iter = iter.into_iter();
2898 while let Some(element) = iter.next() {
2899 let len = self.len();
2900 if len == self.capacity() {
2901 let (lower, _) = iter.size_hint();
2902 self.reserve(lower.saturating_add(1));
2903 }
2904 unsafe {
2905 ptr::write(self.as_mut_ptr().add(len), *element);
2906 // Since next() executes user code which can panic we have to bump the length
2907 // after each step.
2908 // NB can't overflow since we would have had to alloc the address space
2909 self.set_len(len + 1);
2910 }
2911 }
2912 }
2913}
2914
2915/// Implements comparison of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
2916impl<T: PartialOrd, A: Allocator> PartialOrd for Vec<T, A> {
2917 #[inline(always)]
2918 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2919 PartialOrd::partial_cmp(&**self, &**other)
2920 }
2921}
2922
2923impl<T: Eq, A: Allocator> Eq for Vec<T, A> {}
2924
2925/// Implements ordering of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
2926impl<T: Ord, A: Allocator> Ord for Vec<T, A> {
2927 #[inline(always)]
2928 fn cmp(&self, other: &Self) -> Ordering {
2929 Ord::cmp(&**self, &**other)
2930 }
2931}
2932
2933impl<T, A: Allocator> Drop for Vec<T, A> {
2934 #[inline(always)]
2935 fn drop(&mut self) {
2936 unsafe {
2937 // use drop for [T]
2938 // use a raw slice to refer to the elements of the vector as weakest necessary type;
2939 // could avoid questions of validity in certain cases
2940 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
2941 }
2942 // RawVec handles deallocation
2943 }
2944}
2945
2946impl<T> Default for Vec<T> {
2947 /// Creates an empty `Vec<T>`.
2948 ///
2949 /// The vector will not allocate until elements are pushed onto it.
2950 #[inline(always)]
2951 fn default() -> Vec<T> {
2952 Vec::new()
2953 }
2954}
2955
2956impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {
2957 #[inline(always)]
2958 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2959 fmt::Debug::fmt(&**self, f)
2960 }
2961}
2962
2963impl<T, A: Allocator> AsRef<Vec<T, A>> for Vec<T, A> {
2964 #[inline(always)]
2965 fn as_ref(&self) -> &Vec<T, A> {
2966 self
2967 }
2968}
2969
2970impl<T, A: Allocator> AsMut<Vec<T, A>> for Vec<T, A> {
2971 #[inline(always)]
2972 fn as_mut(&mut self) -> &mut Vec<T, A> {
2973 self
2974 }
2975}
2976
2977impl<T, A: Allocator> AsRef<[T]> for Vec<T, A> {
2978 #[inline(always)]
2979 fn as_ref(&self) -> &[T] {
2980 self
2981 }
2982}
2983
2984impl<T, A: Allocator> AsMut<[T]> for Vec<T, A> {
2985 #[inline(always)]
2986 fn as_mut(&mut self) -> &mut [T] {
2987 self
2988 }
2989}
2990
2991#[cfg(not(no_global_oom_handling))]
2992impl<T: Clone> From<&[T]> for Vec<T> {
2993 /// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
2994 ///
2995 /// # Examples
2996 ///
2997 /// ```
2998 /// use allocator_api2::{vec, vec::Vec};
2999 ///
3000 /// assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]);
3001 /// ```
3002 #[inline(always)]
3003 fn from(s: &[T]) -> Vec<T> {
3004 let mut vec = Vec::with_capacity(s.len());
3005 vec.extend_from_slice(s);
3006 vec
3007 }
3008}
3009
3010#[cfg(not(no_global_oom_handling))]
3011impl<T: Clone> From<&mut [T]> for Vec<T> {
3012 /// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
3013 ///
3014 /// # Examples
3015 ///
3016 /// ```
3017 /// use allocator_api2::{vec, vec::Vec};
3018 ///
3019 /// assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]);
3020 /// ```
3021 #[inline(always)]
3022 fn from(s: &mut [T]) -> Vec<T> {
3023 let mut vec = Vec::with_capacity(s.len());
3024 vec.extend_from_slice(s);
3025 vec
3026 }
3027}
3028
3029#[cfg(not(no_global_oom_handling))]
3030impl<T, const N: usize> From<[T; N]> for Vec<T> {
3031 #[inline(always)]
3032 fn from(s: [T; N]) -> Vec<T> {
3033 Box::slice(Box::new(s)).into_vec()
3034 }
3035}
3036
3037impl<T, A: Allocator> From<Box<[T], A>> for Vec<T, A> {
3038 /// Convert a boxed slice into a vector by transferring ownership of
3039 /// the existing heap allocation.
3040 ///
3041 /// # Examples
3042 ///
3043 /// ```
3044 /// use allocator_api2::{vec, vec::Vec, boxed::Box};
3045 ///
3046 /// let b: Box<[i32]> = vec![1, 2, 3].into_boxed_slice();
3047 /// assert_eq!(Vec::from(b), vec![1, 2, 3]);
3048 /// ```
3049 #[inline(always)]
3050 fn from(s: Box<[T], A>) -> Self {
3051 s.into_vec()
3052 }
3053}
3054
3055impl<T, A: Allocator, const N: usize> From<Box<[T; N], A>> for Vec<T, A> {
3056 /// Convert a boxed array into a vector by transferring ownership of
3057 /// the existing heap allocation.
3058 ///
3059 /// # Examples
3060 ///
3061 /// ```
3062 /// use allocator_api2::{vec, vec::Vec, boxed::Box};
3063 ///
3064 /// let b: Box<[i32; 3]> = Box::new([1, 2, 3]);
3065 /// assert_eq!(Vec::from(b), vec![1, 2, 3]);
3066 /// ```
3067 #[inline(always)]
3068 fn from(s: Box<[T; N], A>) -> Self {
3069 s.into_vec()
3070 }
3071}
3072
3073// note: test pulls in libstd, which causes errors here
3074#[cfg(not(no_global_oom_handling))]
3075impl<T, A: Allocator> From<Vec<T, A>> for Box<[T], A> {
3076 /// Convert a vector into a boxed slice.
3077 ///
3078 /// If `v` has excess capacity, its items will be moved into a
3079 /// newly-allocated buffer with exactly the right capacity.
3080 ///
3081 /// # Examples
3082 ///
3083 /// ```
3084 /// use allocator_api2::{vec, boxed::Box};
3085 ///
3086 /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice());
3087 /// ```
3088 ///
3089 /// Any excess capacity is removed:
3090 /// ```
3091 /// use allocator_api2::{vec, vec::Vec, boxed::Box};
3092 ///
3093 /// let mut vec = Vec::with_capacity(10);
3094 /// vec.extend([1i32, 2, 3]);
3095 ///
3096 /// assert_eq!(Box::from(vec), vec![1i32, 2, 3].into_boxed_slice());
3097 /// ```
3098 #[inline(always)]
3099 fn from(v: Vec<T, A>) -> Self {
3100 v.into_boxed_slice()
3101 }
3102}
3103
3104#[cfg(not(no_global_oom_handling))]
3105impl From<&str> for Vec<u8> {
3106 /// Allocate a `Vec<u8>` and fill it with a UTF-8 string.
3107 ///
3108 /// # Examples
3109 ///
3110 /// ```
3111 /// use allocator_api2::{vec, vec::Vec};
3112 ///
3113 /// assert_eq!(Vec::from("123"), vec![b'1', b'2', b'3']);
3114 /// ```
3115 #[inline(always)]
3116 fn from(s: &str) -> Vec<u8> {
3117 From::from(s.as_bytes())
3118 }
3119}
3120
3121impl<T, A: Allocator, const N: usize> TryFrom<Vec<T, A>> for [T; N] {
3122 type Error = Vec<T, A>;
3123
3124 /// Gets the entire contents of the `Vec<T>` as an array,
3125 /// if its size exactly matches that of the requested array.
3126 ///
3127 /// # Examples
3128 ///
3129 /// ```
3130 /// use std::convert::TryInto;
3131 ///
3132 /// use allocator_api2::{vec, vec::Vec};
3133 ///
3134 /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
3135 /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
3136 /// ```
3137 ///
3138 /// If the length doesn't match, the input comes back in `Err`:
3139 /// ```
3140 /// use std::convert::TryInto;
3141 ///
3142 /// use allocator_api2::{vec, vec::Vec};
3143 ///
3144 /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
3145 /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
3146 /// ```
3147 ///
3148 /// If you're fine with just getting a prefix of the `Vec<T>`,
3149 /// you can call [`.truncate(N)`](Vec::truncate) first.
3150 /// ```
3151 /// use std::convert::TryInto;
3152 ///
3153 /// use allocator_api2::vec::Vec;
3154 ///
3155 /// let mut v = Vec::new();
3156 /// v.extend_from_slice(b"hello world");
3157 /// v.sort();
3158 /// v.truncate(2);
3159 /// let [a, b]: [_; 2] = v.try_into().unwrap();
3160 /// assert_eq!(a, b' ');
3161 /// assert_eq!(b, b'd');
3162 /// ```
3163 #[inline(always)]
3164 fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> {
3165 if vec.len() != N {
3166 return Err(vec);
3167 }
3168
3169 // SAFETY: `.set_len(0)` is always sound.
3170 unsafe { vec.set_len(0) };
3171
3172 // SAFETY: A `Vec`'s pointer is always aligned properly, and
3173 // the alignment the array needs is the same as the items.
3174 // We checked earlier that we have sufficient items.
3175 // The items will not double-drop as the `set_len`
3176 // tells the `Vec` not to also drop them.
3177 let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };
3178 Ok(array)
3179 }
3180}
3181
3182#[inline(always)]
3183#[cfg(not(no_global_oom_handling))]
3184#[doc(hidden)]
3185pub fn from_elem_in<T: Clone, A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> {
3186 let mut v = Vec::with_capacity_in(n, alloc);
3187 v.extend_with(n, ExtendElement(elem));
3188 v
3189}
3190
3191#[inline(always)]
3192#[cfg(not(no_global_oom_handling))]
3193#[doc(hidden)]
3194pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
3195 let mut v = Vec::with_capacity(n);
3196 v.extend_with(n, ExtendElement(elem));
3197 v
3198}
3199
3200/// Write is implemented for `Vec<u8>` by appending to the vector.
3201/// The vector will grow as needed.
3202#[cfg(feature = "std")]
3203impl<A: Allocator> io::Write for Vec<u8, A> {
3204 #[inline]
3205 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
3206 self.extend_from_slice(buf);
3207 Ok(buf.len())
3208 }
3209
3210 #[inline]
3211 fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
3212 let len = bufs.iter().map(|b| b.len()).sum();
3213 self.reserve(len);
3214 for buf in bufs {
3215 self.extend_from_slice(buf);
3216 }
3217 Ok(len)
3218 }
3219
3220 #[inline]
3221 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
3222 self.extend_from_slice(buf);
3223 Ok(())
3224 }
3225
3226 #[inline]
3227 fn flush(&mut self) -> io::Result<()> {
3228 Ok(())
3229 }
3230}
3231
3232#[cfg(feature = "serde")]
3233impl<T, A> serde::Serialize for Vec<T, A>
3234where
3235 T: serde::Serialize,
3236 A: Allocator,
3237{
3238 #[inline(always)]
3239 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
3240 where
3241 S: serde::ser::Serializer,
3242 {
3243 serializer.collect_seq(self)
3244 }
3245}
3246
3247#[cfg(feature = "serde")]
3248impl<'de, T, A> serde::de::Deserialize<'de> for Vec<T, A>
3249where
3250 T: serde::de::Deserialize<'de>,
3251 A: Allocator + Default,
3252{
3253 #[inline(always)]
3254 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3255 where
3256 D: serde::de::Deserializer<'de>,
3257 {
3258 struct VecVisitor<T, A> {
3259 marker: PhantomData<(T, A)>,
3260 }
3261
3262 impl<'de, T, A> serde::de::Visitor<'de> for VecVisitor<T, A>
3263 where
3264 T: serde::de::Deserialize<'de>,
3265 A: Allocator + Default,
3266 {
3267 type Value = Vec<T, A>;
3268
3269 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
3270 formatter.write_str("a sequence")
3271 }
3272
3273 fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
3274 where
3275 S: serde::de::SeqAccess<'de>,
3276 {
3277 let mut values = Vec::with_capacity_in(cautious(seq.size_hint()), A::default());
3278
3279 while let Some(value) = seq.next_element()? {
3280 values.push(value);
3281 }
3282
3283 Ok(values)
3284 }
3285 }
3286
3287 let visitor = VecVisitor {
3288 marker: PhantomData,
3289 };
3290 deserializer.deserialize_seq(visitor)
3291 }
3292
3293 #[inline(always)]
3294 fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
3295 where
3296 D: serde::de::Deserializer<'de>,
3297 {
3298 struct VecInPlaceVisitor<'a, T: 'a, A: Allocator + 'a>(&'a mut Vec<T, A>);
3299
3300 impl<'a, 'de, T, A> serde::de::Visitor<'de> for VecInPlaceVisitor<'a, T, A>
3301 where
3302 T: serde::de::Deserialize<'de>,
3303 A: Allocator + Default,
3304 {
3305 type Value = ();
3306
3307 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
3308 formatter.write_str("a sequence")
3309 }
3310
3311 fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
3312 where
3313 S: serde::de::SeqAccess<'de>,
3314 {
3315 let hint = cautious(seq.size_hint());
3316 if let Some(additional) = hint.checked_sub(self.0.len()) {
3317 self.0.reserve(additional);
3318 }
3319
3320 for i in 0..self.0.len() {
3321 let next = {
3322 let next_place = InPlaceSeed(&mut self.0[i]);
3323 seq.next_element_seed(next_place)?
3324 };
3325 if next.is_none() {
3326 self.0.truncate(i);
3327 return Ok(());
3328 }
3329 }
3330
3331 while let Some(value) = seq.next_element()? {
3332 self.0.push(value);
3333 }
3334
3335 Ok(())
3336 }
3337 }
3338
3339 deserializer.deserialize_seq(VecInPlaceVisitor(place))
3340 }
3341}
3342
3343#[cfg(feature = "serde")]
3344pub fn cautious(hint: Option<usize>) -> usize {
3345 cmp::min(hint.unwrap_or(0), 4096)
3346}
3347
3348/// A DeserializeSeed helper for implementing deserialize_in_place Visitors.
3349///
3350/// Wraps a mutable reference and calls deserialize_in_place on it.
3351
3352#[cfg(feature = "serde")]
3353pub struct InPlaceSeed<'a, T: 'a>(pub &'a mut T);
3354
3355#[cfg(feature = "serde")]
3356impl<'a, 'de, T> serde::de::DeserializeSeed<'de> for InPlaceSeed<'a, T>
3357where
3358 T: serde::de::Deserialize<'de>,
3359{
3360 type Value = ();
3361 fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
3362 where
3363 D: serde::de::Deserializer<'de>,
3364 {
3365 T::deserialize_in_place(deserializer, self.0)
3366 }
3367}