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