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