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