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