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