]> git.proxmox.com Git - rustc.git/blob - library/alloc/src/vec.rs
New upstream version 1.50.0+dfsg1
[rustc.git] / library / alloc / src / vec.rs
1 // ignore-tidy-filelength
2 //! A contiguous growable array type with heap-allocated contents, written
3 //! `Vec<T>`.
4 //!
5 //! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and
6 //! `O(1)` pop (from the end).
7 //!
8 //! Vectors ensure they never allocate more than `isize::MAX` bytes.
9 //!
10 //! # Examples
11 //!
12 //! You can explicitly create a [`Vec`] with [`Vec::new`]:
13 //!
14 //! ```
15 //! let v: Vec<i32> = Vec::new();
16 //! ```
17 //!
18 //! ...or by using the [`vec!`] macro:
19 //!
20 //! ```
21 //! let v: Vec<i32> = vec![];
22 //!
23 //! let v = vec![1, 2, 3, 4, 5];
24 //!
25 //! let v = vec![0; 10]; // ten zeroes
26 //! ```
27 //!
28 //! You can [`push`] values onto the end of a vector (which will grow the vector
29 //! as needed):
30 //!
31 //! ```
32 //! let mut v = vec![1, 2];
33 //!
34 //! v.push(3);
35 //! ```
36 //!
37 //! Popping values works in much the same way:
38 //!
39 //! ```
40 //! let mut v = vec![1, 2];
41 //!
42 //! let two = v.pop();
43 //! ```
44 //!
45 //! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
46 //!
47 //! ```
48 //! let mut v = vec![1, 2, 3];
49 //! let three = v[2];
50 //! v[1] = v[1] + 5;
51 //! ```
52 //!
53 //! [`push`]: Vec::push
54
55 #![stable(feature = "rust1", since = "1.0.0")]
56
57 use core::cmp::{self, Ordering};
58 use core::convert::TryFrom;
59 use core::fmt;
60 use core::hash::{Hash, Hasher};
61 use core::intrinsics::{arith_offset, assume};
62 use core::iter::{
63 FromIterator, FusedIterator, InPlaceIterable, SourceIter, TrustedLen, TrustedRandomAccess,
64 };
65 use core::marker::PhantomData;
66 use core::mem::{self, ManuallyDrop, MaybeUninit};
67 use core::ops::{self, Index, IndexMut, Range, RangeBounds};
68 use core::ptr::{self, NonNull};
69 use core::slice::{self, SliceIndex};
70
71 use crate::alloc::{Allocator, Global};
72 use crate::borrow::{Cow, ToOwned};
73 use crate::boxed::Box;
74 use crate::collections::TryReserveError;
75 use crate::raw_vec::RawVec;
76
77 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'.
78 ///
79 /// # Examples
80 ///
81 /// ```
82 /// let mut vec = Vec::new();
83 /// vec.push(1);
84 /// vec.push(2);
85 ///
86 /// assert_eq!(vec.len(), 2);
87 /// assert_eq!(vec[0], 1);
88 ///
89 /// assert_eq!(vec.pop(), Some(2));
90 /// assert_eq!(vec.len(), 1);
91 ///
92 /// vec[0] = 7;
93 /// assert_eq!(vec[0], 7);
94 ///
95 /// vec.extend([1, 2, 3].iter().copied());
96 ///
97 /// for x in &vec {
98 /// println!("{}", x);
99 /// }
100 /// assert_eq!(vec, [7, 1, 2, 3]);
101 /// ```
102 ///
103 /// The [`vec!`] macro is provided to make initialization more convenient:
104 ///
105 /// ```
106 /// let mut vec = vec![1, 2, 3];
107 /// vec.push(4);
108 /// assert_eq!(vec, [1, 2, 3, 4]);
109 /// ```
110 ///
111 /// It can also initialize each element of a `Vec<T>` with a given value.
112 /// This may be more efficient than performing allocation and initialization
113 /// in separate steps, especially when initializing a vector of zeros:
114 ///
115 /// ```
116 /// let vec = vec![0; 5];
117 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
118 ///
119 /// // The following is equivalent, but potentially slower:
120 /// let mut vec = Vec::with_capacity(5);
121 /// vec.resize(5, 0);
122 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
123 /// ```
124 ///
125 /// For more information, see
126 /// [Capacity and Reallocation](#capacity-and-reallocation).
127 ///
128 /// Use a `Vec<T>` as an efficient stack:
129 ///
130 /// ```
131 /// let mut stack = Vec::new();
132 ///
133 /// stack.push(1);
134 /// stack.push(2);
135 /// stack.push(3);
136 ///
137 /// while let Some(top) = stack.pop() {
138 /// // Prints 3, 2, 1
139 /// println!("{}", top);
140 /// }
141 /// ```
142 ///
143 /// # Indexing
144 ///
145 /// The `Vec` type allows to access values by index, because it implements the
146 /// [`Index`] trait. An example will be more explicit:
147 ///
148 /// ```
149 /// let v = vec![0, 2, 4, 6];
150 /// println!("{}", v[1]); // it will display '2'
151 /// ```
152 ///
153 /// However be careful: if you try to access an index which isn't in the `Vec`,
154 /// your software will panic! You cannot do this:
155 ///
156 /// ```should_panic
157 /// let v = vec![0, 2, 4, 6];
158 /// println!("{}", v[6]); // it will panic!
159 /// ```
160 ///
161 /// Use [`get`] and [`get_mut`] if you want to check whether the index is in
162 /// the `Vec`.
163 ///
164 /// # Slicing
165 ///
166 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
167 /// To get a [slice], use [`&`]. Example:
168 ///
169 /// ```
170 /// fn read_slice(slice: &[usize]) {
171 /// // ...
172 /// }
173 ///
174 /// let v = vec![0, 1];
175 /// read_slice(&v);
176 ///
177 /// // ... and that's all!
178 /// // you can also do it like this:
179 /// let u: &[usize] = &v;
180 /// // or like this:
181 /// let u: &[_] = &v;
182 /// ```
183 ///
184 /// In Rust, it's more common to pass slices as arguments rather than vectors
185 /// when you just want to provide read access. The same goes for [`String`] and
186 /// [`&str`].
187 ///
188 /// # Capacity and reallocation
189 ///
190 /// The capacity of a vector is the amount of space allocated for any future
191 /// elements that will be added onto the vector. This is not to be confused with
192 /// the *length* of a vector, which specifies the number of actual elements
193 /// within the vector. If a vector's length exceeds its capacity, its capacity
194 /// will automatically be increased, but its elements will have to be
195 /// reallocated.
196 ///
197 /// For example, a vector with capacity 10 and length 0 would be an empty vector
198 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
199 /// vector will not change its capacity or cause reallocation to occur. However,
200 /// if the vector's length is increased to 11, it will have to reallocate, which
201 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
202 /// whenever possible to specify how big the vector is expected to get.
203 ///
204 /// # Guarantees
205 ///
206 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
207 /// about its design. This ensures that it's as low-overhead as possible in
208 /// the general case, and can be correctly manipulated in primitive ways
209 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
210 /// If additional type parameters are added (e.g., to support custom allocators),
211 /// overriding their defaults may change the behavior.
212 ///
213 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
214 /// triplet. No more, no less. The order of these fields is completely
215 /// unspecified, and you should use the appropriate methods to modify these.
216 /// The pointer will never be null, so this type is null-pointer-optimized.
217 ///
218 /// However, the pointer may not actually point to allocated memory. In particular,
219 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
220 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
221 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
222 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
223 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
224 /// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation
225 /// details are very subtle &mdash; if you intend to allocate memory using a `Vec`
226 /// and use it for something else (either to pass to unsafe code, or to build your
227 /// own memory-backed collection), be sure to deallocate this memory by using
228 /// `from_raw_parts` to recover the `Vec` and then dropping it.
229 ///
230 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
231 /// (as defined by the allocator Rust is configured to use by default), and its
232 /// pointer points to [`len`] initialized, contiguous elements in order (what
233 /// you would see if you coerced it to a slice), followed by [`capacity`]` -
234 /// `[`len`] logically uninitialized, contiguous elements.
235 ///
236 /// `Vec` will never perform a "small optimization" where elements are actually
237 /// stored on the stack for two reasons:
238 ///
239 /// * It would make it more difficult for unsafe code to correctly manipulate
240 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
241 /// only moved, and it would be more difficult to determine if a `Vec` had
242 /// actually allocated memory.
243 ///
244 /// * It would penalize the general case, incurring an additional branch
245 /// on every access.
246 ///
247 /// `Vec` will never automatically shrink itself, even if completely empty. This
248 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
249 /// and then filling it back up to the same [`len`] should incur no calls to
250 /// the allocator. If you wish to free up unused memory, use
251 /// [`shrink_to_fit`].
252 ///
253 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
254 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
255 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
256 /// accurate, and can be relied on. It can even be used to manually free the memory
257 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
258 /// when not necessary.
259 ///
260 /// `Vec` does not guarantee any particular growth strategy when reallocating
261 /// when full, nor when [`reserve`] is called. The current strategy is basic
262 /// and it may prove desirable to use a non-constant growth factor. Whatever
263 /// strategy is used will of course guarantee *O*(1) amortized [`push`].
264 ///
265 /// `vec![x; n]`, `vec![a, b, c, d]`, and
266 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
267 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
268 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
269 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
270 ///
271 /// `Vec` will not specifically overwrite any data that is removed from it,
272 /// but also won't specifically preserve it. Its uninitialized memory is
273 /// scratch space that it may use however it wants. It will generally just do
274 /// whatever is most efficient or otherwise easy to implement. Do not rely on
275 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
276 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
277 /// first, that may not actually happen because the optimizer does not consider
278 /// this a side-effect that must be preserved. There is one case which we will
279 /// not break, however: using `unsafe` code to write to the excess capacity,
280 /// and then increasing the length to match, is always valid.
281 ///
282 /// `Vec` does not currently guarantee the order in which elements are dropped.
283 /// The order has changed in the past and may change again.
284 ///
285 /// [`get`]: ../../std/vec/struct.Vec.html#method.get
286 /// [`get_mut`]: ../../std/vec/struct.Vec.html#method.get_mut
287 /// [`String`]: crate::string::String
288 /// [`&str`]: type@str
289 /// [`shrink_to_fit`]: Vec::shrink_to_fit
290 /// [`capacity`]: Vec::capacity
291 /// [`mem::size_of::<T>`]: core::mem::size_of
292 /// [`len`]: Vec::len
293 /// [`push`]: Vec::push
294 /// [`insert`]: Vec::insert
295 /// [`reserve`]: Vec::reserve
296 /// [owned slice]: Box
297 /// [slice]: ../../std/primitive.slice.html
298 /// [`&`]: ../../std/primitive.reference.html
299 #[stable(feature = "rust1", since = "1.0.0")]
300 #[cfg_attr(not(test), rustc_diagnostic_item = "vec_type")]
301 pub struct Vec<T, #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global> {
302 buf: RawVec<T, A>,
303 len: usize,
304 }
305
306 ////////////////////////////////////////////////////////////////////////////////
307 // Inherent methods
308 ////////////////////////////////////////////////////////////////////////////////
309
310 impl<T> Vec<T> {
311 /// Constructs a new, empty `Vec<T>`.
312 ///
313 /// The vector will not allocate until elements are pushed onto it.
314 ///
315 /// # Examples
316 ///
317 /// ```
318 /// # #![allow(unused_mut)]
319 /// let mut vec: Vec<i32> = Vec::new();
320 /// ```
321 #[inline]
322 #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")]
323 #[stable(feature = "rust1", since = "1.0.0")]
324 pub const fn new() -> Self {
325 Vec { buf: RawVec::NEW, len: 0 }
326 }
327
328 /// Constructs a new, empty `Vec<T>` with the specified capacity.
329 ///
330 /// The vector will be able to hold exactly `capacity` elements without
331 /// reallocating. If `capacity` is 0, the vector will not allocate.
332 ///
333 /// It is important to note that although the returned vector has the
334 /// *capacity* specified, the vector will have a zero *length*. For an
335 /// explanation of the difference between length and capacity, see
336 /// *[Capacity and reallocation]*.
337 ///
338 /// [Capacity and reallocation]: #capacity-and-reallocation
339 ///
340 /// # Examples
341 ///
342 /// ```
343 /// let mut vec = Vec::with_capacity(10);
344 ///
345 /// // The vector contains no items, even though it has capacity for more
346 /// assert_eq!(vec.len(), 0);
347 /// assert_eq!(vec.capacity(), 10);
348 ///
349 /// // These are all done without reallocating...
350 /// for i in 0..10 {
351 /// vec.push(i);
352 /// }
353 /// assert_eq!(vec.len(), 10);
354 /// assert_eq!(vec.capacity(), 10);
355 ///
356 /// // ...but this may make the vector reallocate
357 /// vec.push(11);
358 /// assert_eq!(vec.len(), 11);
359 /// assert!(vec.capacity() >= 11);
360 /// ```
361 #[inline]
362 #[stable(feature = "rust1", since = "1.0.0")]
363 pub fn with_capacity(capacity: usize) -> Self {
364 Self::with_capacity_in(capacity, Global)
365 }
366
367 /// Creates a `Vec<T>` directly from the raw components of another vector.
368 ///
369 /// # Safety
370 ///
371 /// This is highly unsafe, due to the number of invariants that aren't
372 /// checked:
373 ///
374 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
375 /// (at least, it's highly likely to be incorrect if it wasn't).
376 /// * `T` needs to have the same size and alignment as what `ptr` was allocated with.
377 /// (`T` having a less strict alignment is not sufficient, the alignment really
378 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
379 /// allocated and deallocated with the same layout.)
380 /// * `length` needs to be less than or equal to `capacity`.
381 /// * `capacity` needs to be the capacity that the pointer was allocated with.
382 ///
383 /// Violating these may cause problems like corrupting the allocator's
384 /// internal data structures. For example it is **not** safe
385 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
386 /// It's also not safe to build one from a `Vec<u16>` and its length, because
387 /// the allocator cares about the alignment, and these two types have different
388 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
389 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
390 ///
391 /// The ownership of `ptr` is effectively transferred to the
392 /// `Vec<T>` which may then deallocate, reallocate or change the
393 /// contents of memory pointed to by the pointer at will. Ensure
394 /// that nothing else uses the pointer after calling this
395 /// function.
396 ///
397 /// [`String`]: crate::string::String
398 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
399 ///
400 /// # Examples
401 ///
402 /// ```
403 /// use std::ptr;
404 /// use std::mem;
405 ///
406 /// let v = vec![1, 2, 3];
407 ///
408 // FIXME Update this when vec_into_raw_parts is stabilized
409 /// // Prevent running `v`'s destructor so we are in complete control
410 /// // of the allocation.
411 /// let mut v = mem::ManuallyDrop::new(v);
412 ///
413 /// // Pull out the various important pieces of information about `v`
414 /// let p = v.as_mut_ptr();
415 /// let len = v.len();
416 /// let cap = v.capacity();
417 ///
418 /// unsafe {
419 /// // Overwrite memory with 4, 5, 6
420 /// for i in 0..len as isize {
421 /// ptr::write(p.offset(i), 4 + i);
422 /// }
423 ///
424 /// // Put everything back together into a Vec
425 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
426 /// assert_eq!(rebuilt, [4, 5, 6]);
427 /// }
428 /// ```
429 #[inline]
430 #[stable(feature = "rust1", since = "1.0.0")]
431 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {
432 unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) }
433 }
434 }
435
436 impl<T, A: Allocator> Vec<T, A> {
437 /// Constructs a new, empty `Vec<T, A>`.
438 ///
439 /// The vector will not allocate until elements are pushed onto it.
440 ///
441 /// # Examples
442 ///
443 /// ```
444 /// #![feature(allocator_api)]
445 ///
446 /// use std::alloc::System;
447 ///
448 /// # #[allow(unused_mut)]
449 /// let mut vec: Vec<i32, _> = Vec::new_in(System);
450 /// ```
451 #[inline]
452 #[unstable(feature = "allocator_api", issue = "32838")]
453 pub const fn new_in(alloc: A) -> Self {
454 Vec { buf: RawVec::new_in(alloc), len: 0 }
455 }
456
457 /// Constructs a new, empty `Vec<T, A>` with the specified capacity with the provided
458 /// allocator.
459 ///
460 /// The vector will be able to hold exactly `capacity` elements without
461 /// reallocating. If `capacity` is 0, the vector will not allocate.
462 ///
463 /// It is important to note that although the returned vector has the
464 /// *capacity* specified, the vector will have a zero *length*. For an
465 /// explanation of the difference between length and capacity, see
466 /// *[Capacity and reallocation]*.
467 ///
468 /// [Capacity and reallocation]: #capacity-and-reallocation
469 ///
470 /// # Examples
471 ///
472 /// ```
473 /// #![feature(allocator_api)]
474 ///
475 /// use std::alloc::System;
476 ///
477 /// let mut vec = Vec::with_capacity_in(10, System);
478 ///
479 /// // The vector contains no items, even though it has capacity for more
480 /// assert_eq!(vec.len(), 0);
481 /// assert_eq!(vec.capacity(), 10);
482 ///
483 /// // These are all done without reallocating...
484 /// for i in 0..10 {
485 /// vec.push(i);
486 /// }
487 /// assert_eq!(vec.len(), 10);
488 /// assert_eq!(vec.capacity(), 10);
489 ///
490 /// // ...but this may make the vector reallocate
491 /// vec.push(11);
492 /// assert_eq!(vec.len(), 11);
493 /// assert!(vec.capacity() >= 11);
494 /// ```
495 #[inline]
496 #[unstable(feature = "allocator_api", issue = "32838")]
497 pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
498 Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 }
499 }
500
501 /// Creates a `Vec<T, A>` directly from the raw components of another vector.
502 ///
503 /// # Safety
504 ///
505 /// This is highly unsafe, due to the number of invariants that aren't
506 /// checked:
507 ///
508 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
509 /// (at least, it's highly likely to be incorrect if it wasn't).
510 /// * `T` needs to have the same size and alignment as what `ptr` was allocated with.
511 /// (`T` having a less strict alignment is not sufficient, the alignment really
512 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
513 /// allocated and deallocated with the same layout.)
514 /// * `length` needs to be less than or equal to `capacity`.
515 /// * `capacity` needs to be the capacity that the pointer was allocated with.
516 ///
517 /// Violating these may cause problems like corrupting the allocator's
518 /// internal data structures. For example it is **not** safe
519 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
520 /// It's also not safe to build one from a `Vec<u16>` and its length, because
521 /// the allocator cares about the alignment, and these two types have different
522 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
523 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
524 ///
525 /// The ownership of `ptr` is effectively transferred to the
526 /// `Vec<T>` which may then deallocate, reallocate or change the
527 /// contents of memory pointed to by the pointer at will. Ensure
528 /// that nothing else uses the pointer after calling this
529 /// function.
530 ///
531 /// [`String`]: crate::string::String
532 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
533 ///
534 /// # Examples
535 ///
536 /// ```
537 /// #![feature(allocator_api)]
538 ///
539 /// use std::alloc::System;
540 ///
541 /// use std::ptr;
542 /// use std::mem;
543 ///
544 /// let mut v = Vec::with_capacity_in(3, System);
545 /// v.push(1);
546 /// v.push(2);
547 /// v.push(3);
548 ///
549 // FIXME Update this when vec_into_raw_parts is stabilized
550 /// // Prevent running `v`'s destructor so we are in complete control
551 /// // of the allocation.
552 /// let mut v = mem::ManuallyDrop::new(v);
553 ///
554 /// // Pull out the various important pieces of information about `v`
555 /// let p = v.as_mut_ptr();
556 /// let len = v.len();
557 /// let cap = v.capacity();
558 /// let alloc = v.allocator();
559 ///
560 /// unsafe {
561 /// // Overwrite memory with 4, 5, 6
562 /// for i in 0..len as isize {
563 /// ptr::write(p.offset(i), 4 + i);
564 /// }
565 ///
566 /// // Put everything back together into a Vec
567 /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());
568 /// assert_eq!(rebuilt, [4, 5, 6]);
569 /// }
570 /// ```
571 #[inline]
572 #[unstable(feature = "allocator_api", issue = "32838")]
573 pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self {
574 unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } }
575 }
576
577 /// Decomposes a `Vec<T>` into its raw components.
578 ///
579 /// Returns the raw pointer to the underlying data, the length of
580 /// the vector (in elements), and the allocated capacity of the
581 /// data (in elements). These are the same arguments in the same
582 /// order as the arguments to [`from_raw_parts`].
583 ///
584 /// After calling this function, the caller is responsible for the
585 /// memory previously managed by the `Vec`. The only way to do
586 /// this is to convert the raw pointer, length, and capacity back
587 /// into a `Vec` with the [`from_raw_parts`] function, allowing
588 /// the destructor to perform the cleanup.
589 ///
590 /// [`from_raw_parts`]: Vec::from_raw_parts
591 ///
592 /// # Examples
593 ///
594 /// ```
595 /// #![feature(vec_into_raw_parts)]
596 /// let v: Vec<i32> = vec![-1, 0, 1];
597 ///
598 /// let (ptr, len, cap) = v.into_raw_parts();
599 ///
600 /// let rebuilt = unsafe {
601 /// // We can now make changes to the components, such as
602 /// // transmuting the raw pointer to a compatible type.
603 /// let ptr = ptr as *mut u32;
604 ///
605 /// Vec::from_raw_parts(ptr, len, cap)
606 /// };
607 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
608 /// ```
609 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
610 pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
611 let mut me = ManuallyDrop::new(self);
612 (me.as_mut_ptr(), me.len(), me.capacity())
613 }
614
615 /// Decomposes a `Vec<T>` into its raw components.
616 ///
617 /// Returns the raw pointer to the underlying data, the length of the vector (in elements),
618 /// the allocated capacity of the data (in elements), and the allocator. These are the same
619 /// arguments in the same order as the arguments to [`from_raw_parts_in`].
620 ///
621 /// After calling this function, the caller is responsible for the
622 /// memory previously managed by the `Vec`. The only way to do
623 /// this is to convert the raw pointer, length, and capacity back
624 /// into a `Vec` with the [`from_raw_parts_in`] function, allowing
625 /// the destructor to perform the cleanup.
626 ///
627 /// [`from_raw_parts_in`]: Vec::from_raw_parts_in
628 ///
629 /// # Examples
630 ///
631 /// ```
632 /// #![feature(allocator_api, vec_into_raw_parts)]
633 ///
634 /// use std::alloc::System;
635 ///
636 /// let mut v: Vec<i32, System> = Vec::new_in(System);
637 /// v.push(-1);
638 /// v.push(0);
639 /// v.push(1);
640 ///
641 /// let (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();
642 ///
643 /// let rebuilt = unsafe {
644 /// // We can now make changes to the components, such as
645 /// // transmuting the raw pointer to a compatible type.
646 /// let ptr = ptr as *mut u32;
647 ///
648 /// Vec::from_raw_parts_in(ptr, len, cap, alloc)
649 /// };
650 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
651 /// ```
652 #[unstable(feature = "allocator_api", issue = "32838")]
653 // #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
654 pub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A) {
655 let mut me = ManuallyDrop::new(self);
656 let len = me.len();
657 let capacity = me.capacity();
658 let ptr = me.as_mut_ptr();
659 let alloc = unsafe { ptr::read(me.allocator()) };
660 (ptr, len, capacity, alloc)
661 }
662
663 /// Returns the number of elements the vector can hold without
664 /// reallocating.
665 ///
666 /// # Examples
667 ///
668 /// ```
669 /// let vec: Vec<i32> = Vec::with_capacity(10);
670 /// assert_eq!(vec.capacity(), 10);
671 /// ```
672 #[inline]
673 #[stable(feature = "rust1", since = "1.0.0")]
674 pub fn capacity(&self) -> usize {
675 self.buf.capacity()
676 }
677
678 /// Reserves capacity for at least `additional` more elements to be inserted
679 /// in the given `Vec<T>`. The collection may reserve more space to avoid
680 /// frequent reallocations. After calling `reserve`, capacity will be
681 /// greater than or equal to `self.len() + additional`. Does nothing if
682 /// capacity is already sufficient.
683 ///
684 /// # Panics
685 ///
686 /// Panics if the new capacity exceeds `isize::MAX` bytes.
687 ///
688 /// # Examples
689 ///
690 /// ```
691 /// let mut vec = vec![1];
692 /// vec.reserve(10);
693 /// assert!(vec.capacity() >= 11);
694 /// ```
695 #[stable(feature = "rust1", since = "1.0.0")]
696 pub fn reserve(&mut self, additional: usize) {
697 self.buf.reserve(self.len, additional);
698 }
699
700 /// Reserves the minimum capacity for exactly `additional` more elements to
701 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
702 /// capacity will be greater than or equal to `self.len() + additional`.
703 /// Does nothing if the capacity is already sufficient.
704 ///
705 /// Note that the allocator may give the collection more space than it
706 /// requests. Therefore, capacity can not be relied upon to be precisely
707 /// minimal. Prefer `reserve` if future insertions are expected.
708 ///
709 /// # Panics
710 ///
711 /// Panics if the new capacity overflows `usize`.
712 ///
713 /// # Examples
714 ///
715 /// ```
716 /// let mut vec = vec![1];
717 /// vec.reserve_exact(10);
718 /// assert!(vec.capacity() >= 11);
719 /// ```
720 #[stable(feature = "rust1", since = "1.0.0")]
721 pub fn reserve_exact(&mut self, additional: usize) {
722 self.buf.reserve_exact(self.len, additional);
723 }
724
725 /// Tries to reserve capacity for at least `additional` more elements to be inserted
726 /// in the given `Vec<T>`. The collection may reserve more space to avoid
727 /// frequent reallocations. After calling `try_reserve`, capacity will be
728 /// greater than or equal to `self.len() + additional`. Does nothing if
729 /// capacity is already sufficient.
730 ///
731 /// # Errors
732 ///
733 /// If the capacity overflows, or the allocator reports a failure, then an error
734 /// is returned.
735 ///
736 /// # Examples
737 ///
738 /// ```
739 /// #![feature(try_reserve)]
740 /// use std::collections::TryReserveError;
741 ///
742 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
743 /// let mut output = Vec::new();
744 ///
745 /// // Pre-reserve the memory, exiting if we can't
746 /// output.try_reserve(data.len())?;
747 ///
748 /// // Now we know this can't OOM in the middle of our complex work
749 /// output.extend(data.iter().map(|&val| {
750 /// val * 2 + 5 // very complicated
751 /// }));
752 ///
753 /// Ok(output)
754 /// }
755 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
756 /// ```
757 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
758 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
759 self.buf.try_reserve(self.len, additional)
760 }
761
762 /// Tries to reserve the minimum capacity for exactly `additional`
763 /// elements to be inserted in the given `Vec<T>`. After calling
764 /// `try_reserve_exact`, capacity will be greater than or equal to
765 /// `self.len() + additional` if it returns `Ok(())`.
766 /// Does nothing if the capacity is already sufficient.
767 ///
768 /// Note that the allocator may give the collection more space than it
769 /// requests. Therefore, capacity can not be relied upon to be precisely
770 /// minimal. Prefer `reserve` if future insertions are expected.
771 ///
772 /// # Errors
773 ///
774 /// If the capacity overflows, or the allocator reports a failure, then an error
775 /// is returned.
776 ///
777 /// # Examples
778 ///
779 /// ```
780 /// #![feature(try_reserve)]
781 /// use std::collections::TryReserveError;
782 ///
783 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
784 /// let mut output = Vec::new();
785 ///
786 /// // Pre-reserve the memory, exiting if we can't
787 /// output.try_reserve_exact(data.len())?;
788 ///
789 /// // Now we know this can't OOM in the middle of our complex work
790 /// output.extend(data.iter().map(|&val| {
791 /// val * 2 + 5 // very complicated
792 /// }));
793 ///
794 /// Ok(output)
795 /// }
796 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
797 /// ```
798 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
799 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
800 self.buf.try_reserve_exact(self.len, additional)
801 }
802
803 /// Shrinks the capacity of the vector as much as possible.
804 ///
805 /// It will drop down as close as possible to the length but the allocator
806 /// may still inform the vector that there is space for a few more elements.
807 ///
808 /// # Examples
809 ///
810 /// ```
811 /// let mut vec = Vec::with_capacity(10);
812 /// vec.extend([1, 2, 3].iter().cloned());
813 /// assert_eq!(vec.capacity(), 10);
814 /// vec.shrink_to_fit();
815 /// assert!(vec.capacity() >= 3);
816 /// ```
817 #[stable(feature = "rust1", since = "1.0.0")]
818 pub fn shrink_to_fit(&mut self) {
819 // The capacity is never less than the length, and there's nothing to do when
820 // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit`
821 // by only calling it with a greater capacity.
822 if self.capacity() > self.len {
823 self.buf.shrink_to_fit(self.len);
824 }
825 }
826
827 /// Shrinks the capacity of the vector with a lower bound.
828 ///
829 /// The capacity will remain at least as large as both the length
830 /// and the supplied value.
831 ///
832 /// # Panics
833 ///
834 /// Panics if the current capacity is smaller than the supplied
835 /// minimum capacity.
836 ///
837 /// # Examples
838 ///
839 /// ```
840 /// #![feature(shrink_to)]
841 /// let mut vec = Vec::with_capacity(10);
842 /// vec.extend([1, 2, 3].iter().cloned());
843 /// assert_eq!(vec.capacity(), 10);
844 /// vec.shrink_to(4);
845 /// assert!(vec.capacity() >= 4);
846 /// vec.shrink_to(0);
847 /// assert!(vec.capacity() >= 3);
848 /// ```
849 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
850 pub fn shrink_to(&mut self, min_capacity: usize) {
851 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
852 }
853
854 /// Converts the vector into [`Box<[T]>`][owned slice].
855 ///
856 /// Note that this will drop any excess capacity.
857 ///
858 /// [owned slice]: Box
859 ///
860 /// # Examples
861 ///
862 /// ```
863 /// let v = vec![1, 2, 3];
864 ///
865 /// let slice = v.into_boxed_slice();
866 /// ```
867 ///
868 /// Any excess capacity is removed:
869 ///
870 /// ```
871 /// let mut vec = Vec::with_capacity(10);
872 /// vec.extend([1, 2, 3].iter().cloned());
873 ///
874 /// assert_eq!(vec.capacity(), 10);
875 /// let slice = vec.into_boxed_slice();
876 /// assert_eq!(slice.into_vec().capacity(), 3);
877 /// ```
878 #[stable(feature = "rust1", since = "1.0.0")]
879 pub fn into_boxed_slice(mut self) -> Box<[T], A> {
880 unsafe {
881 self.shrink_to_fit();
882 let me = ManuallyDrop::new(self);
883 let buf = ptr::read(&me.buf);
884 let len = me.len();
885 buf.into_box(len).assume_init()
886 }
887 }
888
889 /// Shortens the vector, keeping the first `len` elements and dropping
890 /// the rest.
891 ///
892 /// If `len` is greater than the vector's current length, this has no
893 /// effect.
894 ///
895 /// The [`drain`] method can emulate `truncate`, but causes the excess
896 /// elements to be returned instead of dropped.
897 ///
898 /// Note that this method has no effect on the allocated capacity
899 /// of the vector.
900 ///
901 /// # Examples
902 ///
903 /// Truncating a five element vector to two elements:
904 ///
905 /// ```
906 /// let mut vec = vec![1, 2, 3, 4, 5];
907 /// vec.truncate(2);
908 /// assert_eq!(vec, [1, 2]);
909 /// ```
910 ///
911 /// No truncation occurs when `len` is greater than the vector's current
912 /// length:
913 ///
914 /// ```
915 /// let mut vec = vec![1, 2, 3];
916 /// vec.truncate(8);
917 /// assert_eq!(vec, [1, 2, 3]);
918 /// ```
919 ///
920 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
921 /// method.
922 ///
923 /// ```
924 /// let mut vec = vec![1, 2, 3];
925 /// vec.truncate(0);
926 /// assert_eq!(vec, []);
927 /// ```
928 ///
929 /// [`clear`]: Vec::clear
930 /// [`drain`]: Vec::drain
931 #[stable(feature = "rust1", since = "1.0.0")]
932 pub fn truncate(&mut self, len: usize) {
933 // This is safe because:
934 //
935 // * the slice passed to `drop_in_place` is valid; the `len > self.len`
936 // case avoids creating an invalid slice, and
937 // * the `len` of the vector is shrunk before calling `drop_in_place`,
938 // such that no value will be dropped twice in case `drop_in_place`
939 // were to panic once (if it panics twice, the program aborts).
940 unsafe {
941 if len > self.len {
942 return;
943 }
944 let remaining_len = self.len - len;
945 let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
946 self.len = len;
947 ptr::drop_in_place(s);
948 }
949 }
950
951 /// Extracts a slice containing the entire vector.
952 ///
953 /// Equivalent to `&s[..]`.
954 ///
955 /// # Examples
956 ///
957 /// ```
958 /// use std::io::{self, Write};
959 /// let buffer = vec![1, 2, 3, 5, 8];
960 /// io::sink().write(buffer.as_slice()).unwrap();
961 /// ```
962 #[inline]
963 #[stable(feature = "vec_as_slice", since = "1.7.0")]
964 pub fn as_slice(&self) -> &[T] {
965 self
966 }
967
968 /// Extracts a mutable slice of the entire vector.
969 ///
970 /// Equivalent to `&mut s[..]`.
971 ///
972 /// # Examples
973 ///
974 /// ```
975 /// use std::io::{self, Read};
976 /// let mut buffer = vec![0; 3];
977 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
978 /// ```
979 #[inline]
980 #[stable(feature = "vec_as_slice", since = "1.7.0")]
981 pub fn as_mut_slice(&mut self) -> &mut [T] {
982 self
983 }
984
985 /// Returns a raw pointer to the vector's buffer.
986 ///
987 /// The caller must ensure that the vector outlives the pointer this
988 /// function returns, or else it will end up pointing to garbage.
989 /// Modifying the vector may cause its buffer to be reallocated,
990 /// which would also make any pointers to it invalid.
991 ///
992 /// The caller must also ensure that the memory the pointer (non-transitively) points to
993 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
994 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
995 ///
996 /// # Examples
997 ///
998 /// ```
999 /// let x = vec![1, 2, 4];
1000 /// let x_ptr = x.as_ptr();
1001 ///
1002 /// unsafe {
1003 /// for i in 0..x.len() {
1004 /// assert_eq!(*x_ptr.add(i), 1 << i);
1005 /// }
1006 /// }
1007 /// ```
1008 ///
1009 /// [`as_mut_ptr`]: Vec::as_mut_ptr
1010 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1011 #[inline]
1012 pub fn as_ptr(&self) -> *const T {
1013 // We shadow the slice method of the same name to avoid going through
1014 // `deref`, which creates an intermediate reference.
1015 let ptr = self.buf.ptr();
1016 unsafe {
1017 assume(!ptr.is_null());
1018 }
1019 ptr
1020 }
1021
1022 /// Returns an unsafe mutable pointer to the vector's buffer.
1023 ///
1024 /// The caller must ensure that the vector outlives the pointer this
1025 /// function returns, or else it will end up pointing to garbage.
1026 /// Modifying the vector may cause its buffer to be reallocated,
1027 /// which would also make any pointers to it invalid.
1028 ///
1029 /// # Examples
1030 ///
1031 /// ```
1032 /// // Allocate vector big enough for 4 elements.
1033 /// let size = 4;
1034 /// let mut x: Vec<i32> = Vec::with_capacity(size);
1035 /// let x_ptr = x.as_mut_ptr();
1036 ///
1037 /// // Initialize elements via raw pointer writes, then set length.
1038 /// unsafe {
1039 /// for i in 0..size {
1040 /// *x_ptr.add(i) = i as i32;
1041 /// }
1042 /// x.set_len(size);
1043 /// }
1044 /// assert_eq!(&*x, &[0, 1, 2, 3]);
1045 /// ```
1046 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1047 #[inline]
1048 pub fn as_mut_ptr(&mut self) -> *mut T {
1049 // We shadow the slice method of the same name to avoid going through
1050 // `deref_mut`, which creates an intermediate reference.
1051 let ptr = self.buf.ptr();
1052 unsafe {
1053 assume(!ptr.is_null());
1054 }
1055 ptr
1056 }
1057
1058 /// Returns a reference to the underlying allocator.
1059 #[unstable(feature = "allocator_api", issue = "32838")]
1060 #[inline]
1061 pub fn allocator(&self) -> &A {
1062 self.buf.allocator()
1063 }
1064
1065 /// Forces the length of the vector to `new_len`.
1066 ///
1067 /// This is a low-level operation that maintains none of the normal
1068 /// invariants of the type. Normally changing the length of a vector
1069 /// is done using one of the safe operations instead, such as
1070 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
1071 ///
1072 /// [`truncate`]: Vec::truncate
1073 /// [`resize`]: Vec::resize
1074 /// [`extend`]: Extend::extend
1075 /// [`clear`]: Vec::clear
1076 ///
1077 /// # Safety
1078 ///
1079 /// - `new_len` must be less than or equal to [`capacity()`].
1080 /// - The elements at `old_len..new_len` must be initialized.
1081 ///
1082 /// [`capacity()`]: Vec::capacity
1083 ///
1084 /// # Examples
1085 ///
1086 /// This method can be useful for situations in which the vector
1087 /// is serving as a buffer for other code, particularly over FFI:
1088 ///
1089 /// ```no_run
1090 /// # #![allow(dead_code)]
1091 /// # // This is just a minimal skeleton for the doc example;
1092 /// # // don't use this as a starting point for a real library.
1093 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
1094 /// # const Z_OK: i32 = 0;
1095 /// # extern "C" {
1096 /// # fn deflateGetDictionary(
1097 /// # strm: *mut std::ffi::c_void,
1098 /// # dictionary: *mut u8,
1099 /// # dictLength: *mut usize,
1100 /// # ) -> i32;
1101 /// # }
1102 /// # impl StreamWrapper {
1103 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
1104 /// // Per the FFI method's docs, "32768 bytes is always enough".
1105 /// let mut dict = Vec::with_capacity(32_768);
1106 /// let mut dict_length = 0;
1107 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
1108 /// // 1. `dict_length` elements were initialized.
1109 /// // 2. `dict_length` <= the capacity (32_768)
1110 /// // which makes `set_len` safe to call.
1111 /// unsafe {
1112 /// // Make the FFI call...
1113 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
1114 /// if r == Z_OK {
1115 /// // ...and update the length to what was initialized.
1116 /// dict.set_len(dict_length);
1117 /// Some(dict)
1118 /// } else {
1119 /// None
1120 /// }
1121 /// }
1122 /// }
1123 /// # }
1124 /// ```
1125 ///
1126 /// While the following example is sound, there is a memory leak since
1127 /// the inner vectors were not freed prior to the `set_len` call:
1128 ///
1129 /// ```
1130 /// let mut vec = vec![vec![1, 0, 0],
1131 /// vec![0, 1, 0],
1132 /// vec![0, 0, 1]];
1133 /// // SAFETY:
1134 /// // 1. `old_len..0` is empty so no elements need to be initialized.
1135 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
1136 /// unsafe {
1137 /// vec.set_len(0);
1138 /// }
1139 /// ```
1140 ///
1141 /// Normally, here, one would use [`clear`] instead to correctly drop
1142 /// the contents and thus not leak memory.
1143 #[inline]
1144 #[stable(feature = "rust1", since = "1.0.0")]
1145 pub unsafe fn set_len(&mut self, new_len: usize) {
1146 debug_assert!(new_len <= self.capacity());
1147
1148 self.len = new_len;
1149 }
1150
1151 /// Removes an element from the vector and returns it.
1152 ///
1153 /// The removed element is replaced by the last element of the vector.
1154 ///
1155 /// This does not preserve ordering, but is O(1).
1156 ///
1157 /// # Panics
1158 ///
1159 /// Panics if `index` is out of bounds.
1160 ///
1161 /// # Examples
1162 ///
1163 /// ```
1164 /// let mut v = vec!["foo", "bar", "baz", "qux"];
1165 ///
1166 /// assert_eq!(v.swap_remove(1), "bar");
1167 /// assert_eq!(v, ["foo", "qux", "baz"]);
1168 ///
1169 /// assert_eq!(v.swap_remove(0), "foo");
1170 /// assert_eq!(v, ["baz", "qux"]);
1171 /// ```
1172 #[inline]
1173 #[stable(feature = "rust1", since = "1.0.0")]
1174 pub fn swap_remove(&mut self, index: usize) -> T {
1175 #[cold]
1176 #[inline(never)]
1177 fn assert_failed(index: usize, len: usize) -> ! {
1178 panic!("swap_remove index (is {}) should be < len (is {})", index, len);
1179 }
1180
1181 let len = self.len();
1182 if index >= len {
1183 assert_failed(index, len);
1184 }
1185 unsafe {
1186 // We replace self[index] with the last element. Note that if the
1187 // bounds check above succeeds there must be a last element (which
1188 // can be self[index] itself).
1189 let last = ptr::read(self.as_ptr().add(len - 1));
1190 let hole = self.as_mut_ptr().add(index);
1191 self.set_len(len - 1);
1192 ptr::replace(hole, last)
1193 }
1194 }
1195
1196 /// Inserts an element at position `index` within the vector, shifting all
1197 /// elements after it to the right.
1198 ///
1199 /// # Panics
1200 ///
1201 /// Panics if `index > len`.
1202 ///
1203 /// # Examples
1204 ///
1205 /// ```
1206 /// let mut vec = vec![1, 2, 3];
1207 /// vec.insert(1, 4);
1208 /// assert_eq!(vec, [1, 4, 2, 3]);
1209 /// vec.insert(4, 5);
1210 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1211 /// ```
1212 #[stable(feature = "rust1", since = "1.0.0")]
1213 pub fn insert(&mut self, index: usize, element: T) {
1214 #[cold]
1215 #[inline(never)]
1216 fn assert_failed(index: usize, len: usize) -> ! {
1217 panic!("insertion index (is {}) should be <= len (is {})", index, len);
1218 }
1219
1220 let len = self.len();
1221 if index > len {
1222 assert_failed(index, len);
1223 }
1224
1225 // space for the new element
1226 if len == self.buf.capacity() {
1227 self.reserve(1);
1228 }
1229
1230 unsafe {
1231 // infallible
1232 // The spot to put the new value
1233 {
1234 let p = self.as_mut_ptr().add(index);
1235 // Shift everything over to make space. (Duplicating the
1236 // `index`th element into two consecutive places.)
1237 ptr::copy(p, p.offset(1), len - index);
1238 // Write it in, overwriting the first copy of the `index`th
1239 // element.
1240 ptr::write(p, element);
1241 }
1242 self.set_len(len + 1);
1243 }
1244 }
1245
1246 /// Removes and returns the element at position `index` within the vector,
1247 /// shifting all elements after it to the left.
1248 ///
1249 /// # Panics
1250 ///
1251 /// Panics if `index` is out of bounds.
1252 ///
1253 /// # Examples
1254 ///
1255 /// ```
1256 /// let mut v = vec![1, 2, 3];
1257 /// assert_eq!(v.remove(1), 2);
1258 /// assert_eq!(v, [1, 3]);
1259 /// ```
1260 #[stable(feature = "rust1", since = "1.0.0")]
1261 pub fn remove(&mut self, index: usize) -> T {
1262 #[cold]
1263 #[inline(never)]
1264 fn assert_failed(index: usize, len: usize) -> ! {
1265 panic!("removal index (is {}) should be < len (is {})", index, len);
1266 }
1267
1268 let len = self.len();
1269 if index >= len {
1270 assert_failed(index, len);
1271 }
1272 unsafe {
1273 // infallible
1274 let ret;
1275 {
1276 // the place we are taking from.
1277 let ptr = self.as_mut_ptr().add(index);
1278 // copy it out, unsafely having a copy of the value on
1279 // the stack and in the vector at the same time.
1280 ret = ptr::read(ptr);
1281
1282 // Shift everything down to fill in that spot.
1283 ptr::copy(ptr.offset(1), ptr, len - index - 1);
1284 }
1285 self.set_len(len - 1);
1286 ret
1287 }
1288 }
1289
1290 /// Retains only the elements specified by the predicate.
1291 ///
1292 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
1293 /// This method operates in place, visiting each element exactly once in the
1294 /// original order, and preserves the order of the retained elements.
1295 ///
1296 /// # Examples
1297 ///
1298 /// ```
1299 /// let mut vec = vec![1, 2, 3, 4];
1300 /// vec.retain(|&x| x % 2 == 0);
1301 /// assert_eq!(vec, [2, 4]);
1302 /// ```
1303 ///
1304 /// The exact order may be useful for tracking external state, like an index.
1305 ///
1306 /// ```
1307 /// let mut vec = vec![1, 2, 3, 4, 5];
1308 /// let keep = [false, true, true, false, true];
1309 /// let mut i = 0;
1310 /// vec.retain(|_| (keep[i], i += 1).0);
1311 /// assert_eq!(vec, [2, 3, 5]);
1312 /// ```
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 pub fn retain<F>(&mut self, mut f: F)
1315 where
1316 F: FnMut(&T) -> bool,
1317 {
1318 let len = self.len();
1319 let mut del = 0;
1320 {
1321 let v = &mut **self;
1322
1323 for i in 0..len {
1324 if !f(&v[i]) {
1325 del += 1;
1326 } else if del > 0 {
1327 v.swap(i - del, i);
1328 }
1329 }
1330 }
1331 if del > 0 {
1332 self.truncate(len - del);
1333 }
1334 }
1335
1336 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1337 /// key.
1338 ///
1339 /// If the vector is sorted, this removes all duplicates.
1340 ///
1341 /// # Examples
1342 ///
1343 /// ```
1344 /// let mut vec = vec![10, 20, 21, 30, 20];
1345 ///
1346 /// vec.dedup_by_key(|i| *i / 10);
1347 ///
1348 /// assert_eq!(vec, [10, 20, 30, 20]);
1349 /// ```
1350 #[stable(feature = "dedup_by", since = "1.16.0")]
1351 #[inline]
1352 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1353 where
1354 F: FnMut(&mut T) -> K,
1355 K: PartialEq,
1356 {
1357 self.dedup_by(|a, b| key(a) == key(b))
1358 }
1359
1360 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1361 /// relation.
1362 ///
1363 /// The `same_bucket` function is passed references to two elements from the vector and
1364 /// must determine if the elements compare equal. The elements are passed in opposite order
1365 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1366 ///
1367 /// If the vector is sorted, this removes all duplicates.
1368 ///
1369 /// # Examples
1370 ///
1371 /// ```
1372 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1373 ///
1374 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1375 ///
1376 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1377 /// ```
1378 #[stable(feature = "dedup_by", since = "1.16.0")]
1379 pub fn dedup_by<F>(&mut self, same_bucket: F)
1380 where
1381 F: FnMut(&mut T, &mut T) -> bool,
1382 {
1383 let len = {
1384 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1385 dedup.len()
1386 };
1387 self.truncate(len);
1388 }
1389
1390 /// Appends an element to the back of a collection.
1391 ///
1392 /// # Panics
1393 ///
1394 /// Panics if the new capacity exceeds `isize::MAX` bytes.
1395 ///
1396 /// # Examples
1397 ///
1398 /// ```
1399 /// let mut vec = vec![1, 2];
1400 /// vec.push(3);
1401 /// assert_eq!(vec, [1, 2, 3]);
1402 /// ```
1403 #[inline]
1404 #[stable(feature = "rust1", since = "1.0.0")]
1405 pub fn push(&mut self, value: T) {
1406 // This will panic or abort if we would allocate > isize::MAX bytes
1407 // or if the length increment would overflow for zero-sized types.
1408 if self.len == self.buf.capacity() {
1409 self.reserve(1);
1410 }
1411 unsafe {
1412 let end = self.as_mut_ptr().add(self.len);
1413 ptr::write(end, value);
1414 self.len += 1;
1415 }
1416 }
1417
1418 /// Removes the last element from a vector and returns it, or [`None`] if it
1419 /// is empty.
1420 ///
1421 /// # Examples
1422 ///
1423 /// ```
1424 /// let mut vec = vec![1, 2, 3];
1425 /// assert_eq!(vec.pop(), Some(3));
1426 /// assert_eq!(vec, [1, 2]);
1427 /// ```
1428 #[inline]
1429 #[stable(feature = "rust1", since = "1.0.0")]
1430 pub fn pop(&mut self) -> Option<T> {
1431 if self.len == 0 {
1432 None
1433 } else {
1434 unsafe {
1435 self.len -= 1;
1436 Some(ptr::read(self.as_ptr().add(self.len())))
1437 }
1438 }
1439 }
1440
1441 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1442 ///
1443 /// # Panics
1444 ///
1445 /// Panics if the number of elements in the vector overflows a `usize`.
1446 ///
1447 /// # Examples
1448 ///
1449 /// ```
1450 /// let mut vec = vec![1, 2, 3];
1451 /// let mut vec2 = vec![4, 5, 6];
1452 /// vec.append(&mut vec2);
1453 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1454 /// assert_eq!(vec2, []);
1455 /// ```
1456 #[inline]
1457 #[stable(feature = "append", since = "1.4.0")]
1458 pub fn append(&mut self, other: &mut Self) {
1459 unsafe {
1460 self.append_elements(other.as_slice() as _);
1461 other.set_len(0);
1462 }
1463 }
1464
1465 /// Appends elements to `Self` from other buffer.
1466 #[inline]
1467 unsafe fn append_elements(&mut self, other: *const [T]) {
1468 let count = unsafe { (*other).len() };
1469 self.reserve(count);
1470 let len = self.len();
1471 unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
1472 self.len += count;
1473 }
1474
1475 /// Creates a draining iterator that removes the specified range in the vector
1476 /// and yields the removed items.
1477 ///
1478 /// When the iterator **is** dropped, all elements in the range are removed
1479 /// from the vector, even if the iterator was not fully consumed. If the
1480 /// iterator **is not** dropped (with [`mem::forget`] for example), it is
1481 /// unspecified how many elements are removed.
1482 ///
1483 /// # Panics
1484 ///
1485 /// Panics if the starting point is greater than the end point or if
1486 /// the end point is greater than the length of the vector.
1487 ///
1488 /// # Examples
1489 ///
1490 /// ```
1491 /// let mut v = vec![1, 2, 3];
1492 /// let u: Vec<_> = v.drain(1..).collect();
1493 /// assert_eq!(v, &[1]);
1494 /// assert_eq!(u, &[2, 3]);
1495 ///
1496 /// // A full range clears the vector
1497 /// v.drain(..);
1498 /// assert_eq!(v, &[]);
1499 /// ```
1500 #[stable(feature = "drain", since = "1.6.0")]
1501 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1502 where
1503 R: RangeBounds<usize>,
1504 {
1505 // Memory safety
1506 //
1507 // When the Drain is first created, it shortens the length of
1508 // the source vector to make sure no uninitialized or moved-from elements
1509 // are accessible at all if the Drain's destructor never gets to run.
1510 //
1511 // Drain will ptr::read out the values to remove.
1512 // When finished, remaining tail of the vec is copied back to cover
1513 // the hole, and the vector length is restored to the new length.
1514 //
1515 let len = self.len();
1516 let Range { start, end } = range.assert_len(len);
1517
1518 unsafe {
1519 // set self.vec length's to start, to be safe in case Drain is leaked
1520 self.set_len(start);
1521 // Use the borrow in the IterMut to indicate borrowing behavior of the
1522 // whole Drain iterator (like &mut T).
1523 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start);
1524 Drain {
1525 tail_start: end,
1526 tail_len: len - end,
1527 iter: range_slice.iter(),
1528 vec: NonNull::from(self),
1529 }
1530 }
1531 }
1532
1533 /// Clears the vector, removing all values.
1534 ///
1535 /// Note that this method has no effect on the allocated capacity
1536 /// of the vector.
1537 ///
1538 /// # Examples
1539 ///
1540 /// ```
1541 /// let mut v = vec![1, 2, 3];
1542 ///
1543 /// v.clear();
1544 ///
1545 /// assert!(v.is_empty());
1546 /// ```
1547 #[inline]
1548 #[stable(feature = "rust1", since = "1.0.0")]
1549 pub fn clear(&mut self) {
1550 self.truncate(0)
1551 }
1552
1553 /// Returns the number of elements in the vector, also referred to
1554 /// as its 'length'.
1555 ///
1556 /// # Examples
1557 ///
1558 /// ```
1559 /// let a = vec![1, 2, 3];
1560 /// assert_eq!(a.len(), 3);
1561 /// ```
1562 #[inline]
1563 #[stable(feature = "rust1", since = "1.0.0")]
1564 pub fn len(&self) -> usize {
1565 self.len
1566 }
1567
1568 /// Returns `true` if the vector contains no elements.
1569 ///
1570 /// # Examples
1571 ///
1572 /// ```
1573 /// let mut v = Vec::new();
1574 /// assert!(v.is_empty());
1575 ///
1576 /// v.push(1);
1577 /// assert!(!v.is_empty());
1578 /// ```
1579 #[stable(feature = "rust1", since = "1.0.0")]
1580 pub fn is_empty(&self) -> bool {
1581 self.len() == 0
1582 }
1583
1584 /// Splits the collection into two at the given index.
1585 ///
1586 /// Returns a newly allocated vector containing the elements in the range
1587 /// `[at, len)`. After the call, the original vector will be left containing
1588 /// the elements `[0, at)` with its previous capacity unchanged.
1589 ///
1590 /// # Panics
1591 ///
1592 /// Panics if `at > len`.
1593 ///
1594 /// # Examples
1595 ///
1596 /// ```
1597 /// let mut vec = vec![1, 2, 3];
1598 /// let vec2 = vec.split_off(1);
1599 /// assert_eq!(vec, [1]);
1600 /// assert_eq!(vec2, [2, 3]);
1601 /// ```
1602 #[inline]
1603 #[must_use = "use `.truncate()` if you don't need the other half"]
1604 #[stable(feature = "split_off", since = "1.4.0")]
1605 pub fn split_off(&mut self, at: usize) -> Self
1606 where
1607 A: Clone,
1608 {
1609 #[cold]
1610 #[inline(never)]
1611 fn assert_failed(at: usize, len: usize) -> ! {
1612 panic!("`at` split index (is {}) should be <= len (is {})", at, len);
1613 }
1614
1615 if at > self.len() {
1616 assert_failed(at, self.len());
1617 }
1618
1619 if at == 0 {
1620 // the new vector can take over the original buffer and avoid the copy
1621 return mem::replace(
1622 self,
1623 Vec::with_capacity_in(self.capacity(), self.allocator().clone()),
1624 );
1625 }
1626
1627 let other_len = self.len - at;
1628 let mut other = Vec::with_capacity_in(other_len, self.allocator().clone());
1629
1630 // Unsafely `set_len` and copy items to `other`.
1631 unsafe {
1632 self.set_len(at);
1633 other.set_len(other_len);
1634
1635 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
1636 }
1637 other
1638 }
1639
1640 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1641 ///
1642 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1643 /// difference, with each additional slot filled with the result of
1644 /// calling the closure `f`. The return values from `f` will end up
1645 /// in the `Vec` in the order they have been generated.
1646 ///
1647 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1648 ///
1649 /// This method uses a closure to create new values on every push. If
1650 /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you
1651 /// want to use the [`Default`] trait to generate values, you can
1652 /// pass [`Default::default`] as the second argument.
1653 ///
1654 /// # Examples
1655 ///
1656 /// ```
1657 /// let mut vec = vec![1, 2, 3];
1658 /// vec.resize_with(5, Default::default);
1659 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1660 ///
1661 /// let mut vec = vec![];
1662 /// let mut p = 1;
1663 /// vec.resize_with(4, || { p *= 2; p });
1664 /// assert_eq!(vec, [2, 4, 8, 16]);
1665 /// ```
1666 #[stable(feature = "vec_resize_with", since = "1.33.0")]
1667 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1668 where
1669 F: FnMut() -> T,
1670 {
1671 let len = self.len();
1672 if new_len > len {
1673 self.extend_with(new_len - len, ExtendFunc(f));
1674 } else {
1675 self.truncate(new_len);
1676 }
1677 }
1678
1679 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
1680 /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
1681 /// `'a`. If the type has only static references, or none at all, then this
1682 /// may be chosen to be `'static`.
1683 ///
1684 /// This function is similar to the [`leak`][Box::leak] function on [`Box`]
1685 /// except that there is no way to recover the leaked memory.
1686 ///
1687 /// This function is mainly useful for data that lives for the remainder of
1688 /// the program's life. Dropping the returned reference will cause a memory
1689 /// leak.
1690 ///
1691 /// # Examples
1692 ///
1693 /// Simple usage:
1694 ///
1695 /// ```
1696 /// let x = vec![1, 2, 3];
1697 /// let static_ref: &'static mut [usize] = x.leak();
1698 /// static_ref[0] += 1;
1699 /// assert_eq!(static_ref, &[2, 2, 3]);
1700 /// ```
1701 #[stable(feature = "vec_leak", since = "1.47.0")]
1702 #[inline]
1703 pub fn leak<'a>(self) -> &'a mut [T]
1704 where
1705 A: 'a,
1706 {
1707 Box::leak(self.into_boxed_slice())
1708 }
1709
1710 /// Returns the remaining spare capacity of the vector as a slice of
1711 /// `MaybeUninit<T>`.
1712 ///
1713 /// The returned slice can be used to fill the vector with data (e.g. by
1714 /// reading from a file) before marking the data as initialized using the
1715 /// [`set_len`] method.
1716 ///
1717 /// [`set_len`]: Vec::set_len
1718 ///
1719 /// # Examples
1720 ///
1721 /// ```
1722 /// #![feature(vec_spare_capacity, maybe_uninit_extra)]
1723 ///
1724 /// // Allocate vector big enough for 10 elements.
1725 /// let mut v = Vec::with_capacity(10);
1726 ///
1727 /// // Fill in the first 3 elements.
1728 /// let uninit = v.spare_capacity_mut();
1729 /// uninit[0].write(0);
1730 /// uninit[1].write(1);
1731 /// uninit[2].write(2);
1732 ///
1733 /// // Mark the first 3 elements of the vector as being initialized.
1734 /// unsafe {
1735 /// v.set_len(3);
1736 /// }
1737 ///
1738 /// assert_eq!(&v, &[0, 1, 2]);
1739 /// ```
1740 #[unstable(feature = "vec_spare_capacity", issue = "75017")]
1741 #[inline]
1742 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
1743 unsafe {
1744 slice::from_raw_parts_mut(
1745 self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
1746 self.buf.capacity() - self.len,
1747 )
1748 }
1749 }
1750 }
1751
1752 impl<T: Clone, A: Allocator> Vec<T, A> {
1753 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1754 ///
1755 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1756 /// difference, with each additional slot filled with `value`.
1757 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1758 ///
1759 /// This method requires `T` to implement [`Clone`],
1760 /// in order to be able to clone the passed value.
1761 /// If you need more flexibility (or want to rely on [`Default`] instead of
1762 /// [`Clone`]), use [`Vec::resize_with`].
1763 ///
1764 /// # Examples
1765 ///
1766 /// ```
1767 /// let mut vec = vec!["hello"];
1768 /// vec.resize(3, "world");
1769 /// assert_eq!(vec, ["hello", "world", "world"]);
1770 ///
1771 /// let mut vec = vec![1, 2, 3, 4];
1772 /// vec.resize(2, 0);
1773 /// assert_eq!(vec, [1, 2]);
1774 /// ```
1775 #[stable(feature = "vec_resize", since = "1.5.0")]
1776 pub fn resize(&mut self, new_len: usize, value: T) {
1777 let len = self.len();
1778
1779 if new_len > len {
1780 self.extend_with(new_len - len, ExtendElement(value))
1781 } else {
1782 self.truncate(new_len);
1783 }
1784 }
1785
1786 /// Clones and appends all elements in a slice to the `Vec`.
1787 ///
1788 /// Iterates over the slice `other`, clones each element, and then appends
1789 /// it to this `Vec`. The `other` vector is traversed in-order.
1790 ///
1791 /// Note that this function is same as [`extend`] except that it is
1792 /// specialized to work with slices instead. If and when Rust gets
1793 /// specialization this function will likely be deprecated (but still
1794 /// available).
1795 ///
1796 /// # Examples
1797 ///
1798 /// ```
1799 /// let mut vec = vec![1];
1800 /// vec.extend_from_slice(&[2, 3, 4]);
1801 /// assert_eq!(vec, [1, 2, 3, 4]);
1802 /// ```
1803 ///
1804 /// [`extend`]: Vec::extend
1805 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1806 pub fn extend_from_slice(&mut self, other: &[T]) {
1807 self.spec_extend(other.iter())
1808 }
1809 }
1810
1811 // This code generalizes `extend_with_{element,default}`.
1812 trait ExtendWith<T> {
1813 fn next(&mut self) -> T;
1814 fn last(self) -> T;
1815 }
1816
1817 struct ExtendElement<T>(T);
1818 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1819 fn next(&mut self) -> T {
1820 self.0.clone()
1821 }
1822 fn last(self) -> T {
1823 self.0
1824 }
1825 }
1826
1827 struct ExtendDefault;
1828 impl<T: Default> ExtendWith<T> for ExtendDefault {
1829 fn next(&mut self) -> T {
1830 Default::default()
1831 }
1832 fn last(self) -> T {
1833 Default::default()
1834 }
1835 }
1836
1837 struct ExtendFunc<F>(F);
1838 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
1839 fn next(&mut self) -> T {
1840 (self.0)()
1841 }
1842 fn last(mut self) -> T {
1843 (self.0)()
1844 }
1845 }
1846
1847 impl<T, A: Allocator> Vec<T, A> {
1848 /// Extend the vector by `n` values, using the given generator.
1849 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
1850 self.reserve(n);
1851
1852 unsafe {
1853 let mut ptr = self.as_mut_ptr().add(self.len());
1854 // Use SetLenOnDrop to work around bug where compiler
1855 // may not realize the store through `ptr` through self.set_len()
1856 // don't alias.
1857 let mut local_len = SetLenOnDrop::new(&mut self.len);
1858
1859 // Write all elements except the last one
1860 for _ in 1..n {
1861 ptr::write(ptr, value.next());
1862 ptr = ptr.offset(1);
1863 // Increment the length in every step in case next() panics
1864 local_len.increment_len(1);
1865 }
1866
1867 if n > 0 {
1868 // We can write the last element directly without cloning needlessly
1869 ptr::write(ptr, value.last());
1870 local_len.increment_len(1);
1871 }
1872
1873 // len set by scope guard
1874 }
1875 }
1876 }
1877
1878 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1879 //
1880 // The idea is: The length field in SetLenOnDrop is a local variable
1881 // that the optimizer will see does not alias with any stores through the Vec's data
1882 // pointer. This is a workaround for alias analysis issue #32155
1883 struct SetLenOnDrop<'a> {
1884 len: &'a mut usize,
1885 local_len: usize,
1886 }
1887
1888 impl<'a> SetLenOnDrop<'a> {
1889 #[inline]
1890 fn new(len: &'a mut usize) -> Self {
1891 SetLenOnDrop { local_len: *len, len }
1892 }
1893
1894 #[inline]
1895 fn increment_len(&mut self, increment: usize) {
1896 self.local_len += increment;
1897 }
1898 }
1899
1900 impl Drop for SetLenOnDrop<'_> {
1901 #[inline]
1902 fn drop(&mut self) {
1903 *self.len = self.local_len;
1904 }
1905 }
1906
1907 impl<T: PartialEq, A: Allocator> Vec<T, A> {
1908 /// Removes consecutive repeated elements in the vector according to the
1909 /// [`PartialEq`] trait implementation.
1910 ///
1911 /// If the vector is sorted, this removes all duplicates.
1912 ///
1913 /// # Examples
1914 ///
1915 /// ```
1916 /// let mut vec = vec![1, 2, 2, 3, 2];
1917 ///
1918 /// vec.dedup();
1919 ///
1920 /// assert_eq!(vec, [1, 2, 3, 2]);
1921 /// ```
1922 #[stable(feature = "rust1", since = "1.0.0")]
1923 #[inline]
1924 pub fn dedup(&mut self) {
1925 self.dedup_by(|a, b| a == b)
1926 }
1927 }
1928
1929 impl<T, A: Allocator> Vec<T, A> {
1930 /// Removes the first instance of `item` from the vector if the item exists.
1931 ///
1932 /// This method will be removed soon.
1933 #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1934 #[rustc_deprecated(
1935 reason = "Removing the first item equal to a needle is already easily possible \
1936 with iterators and the current Vec methods. Furthermore, having a method for \
1937 one particular case of removal (linear search, only the first item, no swap remove) \
1938 but not for others is inconsistent. This method will be removed soon.",
1939 since = "1.46.0"
1940 )]
1941 pub fn remove_item<V>(&mut self, item: &V) -> Option<T>
1942 where
1943 T: PartialEq<V>,
1944 {
1945 let pos = self.iter().position(|x| *x == *item)?;
1946 Some(self.remove(pos))
1947 }
1948 }
1949
1950 ////////////////////////////////////////////////////////////////////////////////
1951 // Internal methods and functions
1952 ////////////////////////////////////////////////////////////////////////////////
1953
1954 #[doc(hidden)]
1955 #[stable(feature = "rust1", since = "1.0.0")]
1956 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1957 <T as SpecFromElem>::from_elem(elem, n, Global)
1958 }
1959
1960 #[doc(hidden)]
1961 #[unstable(feature = "allocator_api", issue = "32838")]
1962 pub fn from_elem_in<T: Clone, A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> {
1963 <T as SpecFromElem>::from_elem(elem, n, alloc)
1964 }
1965
1966 // Specialization trait used for Vec::from_elem
1967 trait SpecFromElem: Sized {
1968 fn from_elem<A: Allocator>(elem: Self, n: usize, alloc: A) -> Vec<Self, A>;
1969 }
1970
1971 impl<T: Clone> SpecFromElem for T {
1972 default fn from_elem<A: Allocator>(elem: Self, n: usize, alloc: A) -> Vec<Self, A> {
1973 let mut v = Vec::with_capacity_in(n, alloc);
1974 v.extend_with(n, ExtendElement(elem));
1975 v
1976 }
1977 }
1978
1979 impl SpecFromElem for i8 {
1980 #[inline]
1981 fn from_elem<A: Allocator>(elem: i8, n: usize, alloc: A) -> Vec<i8, A> {
1982 if elem == 0 {
1983 return Vec { buf: RawVec::with_capacity_zeroed_in(n, alloc), len: n };
1984 }
1985 unsafe {
1986 let mut v = Vec::with_capacity_in(n, alloc);
1987 ptr::write_bytes(v.as_mut_ptr(), elem as u8, n);
1988 v.set_len(n);
1989 v
1990 }
1991 }
1992 }
1993
1994 impl SpecFromElem for u8 {
1995 #[inline]
1996 fn from_elem<A: Allocator>(elem: u8, n: usize, alloc: A) -> Vec<u8, A> {
1997 if elem == 0 {
1998 return Vec { buf: RawVec::with_capacity_zeroed_in(n, alloc), len: n };
1999 }
2000 unsafe {
2001 let mut v = Vec::with_capacity_in(n, alloc);
2002 ptr::write_bytes(v.as_mut_ptr(), elem, n);
2003 v.set_len(n);
2004 v
2005 }
2006 }
2007 }
2008
2009 impl<T: Clone + IsZero> SpecFromElem for T {
2010 #[inline]
2011 fn from_elem<A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> {
2012 if elem.is_zero() {
2013 return Vec { buf: RawVec::with_capacity_zeroed_in(n, alloc), len: n };
2014 }
2015 let mut v = Vec::with_capacity_in(n, alloc);
2016 v.extend_with(n, ExtendElement(elem));
2017 v
2018 }
2019 }
2020
2021 #[rustc_specialization_trait]
2022 unsafe trait IsZero {
2023 /// Whether this value is zero
2024 fn is_zero(&self) -> bool;
2025 }
2026
2027 macro_rules! impl_is_zero {
2028 ($t:ty, $is_zero:expr) => {
2029 unsafe impl IsZero for $t {
2030 #[inline]
2031 fn is_zero(&self) -> bool {
2032 $is_zero(*self)
2033 }
2034 }
2035 };
2036 }
2037
2038 impl_is_zero!(i16, |x| x == 0);
2039 impl_is_zero!(i32, |x| x == 0);
2040 impl_is_zero!(i64, |x| x == 0);
2041 impl_is_zero!(i128, |x| x == 0);
2042 impl_is_zero!(isize, |x| x == 0);
2043
2044 impl_is_zero!(u16, |x| x == 0);
2045 impl_is_zero!(u32, |x| x == 0);
2046 impl_is_zero!(u64, |x| x == 0);
2047 impl_is_zero!(u128, |x| x == 0);
2048 impl_is_zero!(usize, |x| x == 0);
2049
2050 impl_is_zero!(bool, |x| x == false);
2051 impl_is_zero!(char, |x| x == '\0');
2052
2053 impl_is_zero!(f32, |x: f32| x.to_bits() == 0);
2054 impl_is_zero!(f64, |x: f64| x.to_bits() == 0);
2055
2056 unsafe impl<T> IsZero for *const T {
2057 #[inline]
2058 fn is_zero(&self) -> bool {
2059 (*self).is_null()
2060 }
2061 }
2062
2063 unsafe impl<T> IsZero for *mut T {
2064 #[inline]
2065 fn is_zero(&self) -> bool {
2066 (*self).is_null()
2067 }
2068 }
2069
2070 // `Option<&T>` and `Option<Box<T>>` are guaranteed to represent `None` as null.
2071 // For fat pointers, the bytes that would be the pointer metadata in the `Some`
2072 // variant are padding in the `None` variant, so ignoring them and
2073 // zero-initializing instead is ok.
2074 // `Option<&mut T>` never implements `Clone`, so there's no need for an impl of
2075 // `SpecFromElem`.
2076
2077 unsafe impl<T: ?Sized> IsZero for Option<&T> {
2078 #[inline]
2079 fn is_zero(&self) -> bool {
2080 self.is_none()
2081 }
2082 }
2083
2084 unsafe impl<T: ?Sized> IsZero for Option<Box<T>> {
2085 #[inline]
2086 fn is_zero(&self) -> bool {
2087 self.is_none()
2088 }
2089 }
2090
2091 ////////////////////////////////////////////////////////////////////////////////
2092 // Common trait implementations for Vec
2093 ////////////////////////////////////////////////////////////////////////////////
2094
2095 #[stable(feature = "rust1", since = "1.0.0")]
2096 impl<T, A: Allocator> ops::Deref for Vec<T, A> {
2097 type Target = [T];
2098
2099 fn deref(&self) -> &[T] {
2100 unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
2101 }
2102 }
2103
2104 #[stable(feature = "rust1", since = "1.0.0")]
2105 impl<T, A: Allocator> ops::DerefMut for Vec<T, A> {
2106 fn deref_mut(&mut self) -> &mut [T] {
2107 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
2108 }
2109 }
2110
2111 #[stable(feature = "rust1", since = "1.0.0")]
2112 impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> {
2113 #[cfg(not(test))]
2114 fn clone(&self) -> Self {
2115 let alloc = self.allocator().clone();
2116 <[T]>::to_vec_in(&**self, alloc)
2117 }
2118
2119 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
2120 // required for this method definition, is not available. Instead use the
2121 // `slice::to_vec` function which is only available with cfg(test)
2122 // NB see the slice::hack module in slice.rs for more information
2123 #[cfg(test)]
2124 fn clone(&self) -> Self {
2125 let alloc = self.allocator().clone();
2126 crate::slice::to_vec(&**self, alloc)
2127 }
2128
2129 fn clone_from(&mut self, other: &Self) {
2130 // drop anything that will not be overwritten
2131 self.truncate(other.len());
2132
2133 // self.len <= other.len due to the truncate above, so the
2134 // slices here are always in-bounds.
2135 let (init, tail) = other.split_at(self.len());
2136
2137 // reuse the contained values' allocations/resources.
2138 self.clone_from_slice(init);
2139 self.extend_from_slice(tail);
2140 }
2141 }
2142
2143 #[stable(feature = "rust1", since = "1.0.0")]
2144 impl<T: Hash, A: Allocator> Hash for Vec<T, A> {
2145 #[inline]
2146 fn hash<H: Hasher>(&self, state: &mut H) {
2147 Hash::hash(&**self, state)
2148 }
2149 }
2150
2151 #[stable(feature = "rust1", since = "1.0.0")]
2152 #[rustc_on_unimplemented(
2153 message = "vector indices are of type `usize` or ranges of `usize`",
2154 label = "vector indices are of type `usize` or ranges of `usize`"
2155 )]
2156 impl<T, I: SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> {
2157 type Output = I::Output;
2158
2159 #[inline]
2160 fn index(&self, index: I) -> &Self::Output {
2161 Index::index(&**self, index)
2162 }
2163 }
2164
2165 #[stable(feature = "rust1", since = "1.0.0")]
2166 #[rustc_on_unimplemented(
2167 message = "vector indices are of type `usize` or ranges of `usize`",
2168 label = "vector indices are of type `usize` or ranges of `usize`"
2169 )]
2170 impl<T, I: SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> {
2171 #[inline]
2172 fn index_mut(&mut self, index: I) -> &mut Self::Output {
2173 IndexMut::index_mut(&mut **self, index)
2174 }
2175 }
2176
2177 #[stable(feature = "rust1", since = "1.0.0")]
2178 impl<T> FromIterator<T> for Vec<T> {
2179 #[inline]
2180 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
2181 <Self as SpecFromIter<T, I::IntoIter>>::from_iter(iter.into_iter())
2182 }
2183 }
2184
2185 #[stable(feature = "rust1", since = "1.0.0")]
2186 impl<T, A: Allocator> IntoIterator for Vec<T, A> {
2187 type Item = T;
2188 type IntoIter = IntoIter<T, A>;
2189
2190 /// Creates a consuming iterator, that is, one that moves each value out of
2191 /// the vector (from start to end). The vector cannot be used after calling
2192 /// this.
2193 ///
2194 /// # Examples
2195 ///
2196 /// ```
2197 /// let v = vec!["a".to_string(), "b".to_string()];
2198 /// for s in v.into_iter() {
2199 /// // s has type String, not &String
2200 /// println!("{}", s);
2201 /// }
2202 /// ```
2203 #[inline]
2204 fn into_iter(self) -> IntoIter<T, A> {
2205 unsafe {
2206 let mut me = ManuallyDrop::new(self);
2207 let alloc = ptr::read(me.allocator());
2208 let begin = me.as_mut_ptr();
2209 let end = if mem::size_of::<T>() == 0 {
2210 arith_offset(begin as *const i8, me.len() as isize) as *const T
2211 } else {
2212 begin.add(me.len()) as *const T
2213 };
2214 let cap = me.buf.capacity();
2215 IntoIter {
2216 buf: NonNull::new_unchecked(begin),
2217 phantom: PhantomData,
2218 cap,
2219 alloc,
2220 ptr: begin,
2221 end,
2222 }
2223 }
2224 }
2225 }
2226
2227 #[stable(feature = "rust1", since = "1.0.0")]
2228 impl<'a, T, A: Allocator> IntoIterator for &'a Vec<T, A> {
2229 type Item = &'a T;
2230 type IntoIter = slice::Iter<'a, T>;
2231
2232 fn into_iter(self) -> slice::Iter<'a, T> {
2233 self.iter()
2234 }
2235 }
2236
2237 #[stable(feature = "rust1", since = "1.0.0")]
2238 impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A> {
2239 type Item = &'a mut T;
2240 type IntoIter = slice::IterMut<'a, T>;
2241
2242 fn into_iter(self) -> slice::IterMut<'a, T> {
2243 self.iter_mut()
2244 }
2245 }
2246
2247 #[stable(feature = "rust1", since = "1.0.0")]
2248 impl<T, A: Allocator> Extend<T> for Vec<T, A> {
2249 #[inline]
2250 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2251 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
2252 }
2253
2254 #[inline]
2255 fn extend_one(&mut self, item: T) {
2256 self.push(item);
2257 }
2258
2259 #[inline]
2260 fn extend_reserve(&mut self, additional: usize) {
2261 self.reserve(additional);
2262 }
2263 }
2264
2265 /// Specialization trait used for Vec::from_iter
2266 ///
2267 /// ## The delegation graph:
2268 ///
2269 /// ```text
2270 /// +-------------+
2271 /// |FromIterator |
2272 /// +-+-----------+
2273 /// |
2274 /// v
2275 /// +-+-------------------------------+ +---------------------+
2276 /// |SpecFromIter +---->+SpecFromIterNested |
2277 /// |where I: | | |where I: |
2278 /// | Iterator (default)----------+ | | Iterator (default) |
2279 /// | vec::IntoIter | | | TrustedLen |
2280 /// | SourceIterMarker---fallback-+ | | |
2281 /// | slice::Iter | | |
2282 /// | Iterator<Item = &Clone> | +---------------------+
2283 /// +---------------------------------+
2284 /// ```
2285 trait SpecFromIter<T, I> {
2286 fn from_iter(iter: I) -> Self;
2287 }
2288
2289 /// Another specialization trait for Vec::from_iter
2290 /// necessary to manually prioritize overlapping specializations
2291 /// see [`SpecFromIter`] for details.
2292 trait SpecFromIterNested<T, I> {
2293 fn from_iter(iter: I) -> Self;
2294 }
2295
2296 impl<T, I> SpecFromIterNested<T, I> for Vec<T>
2297 where
2298 I: Iterator<Item = T>,
2299 {
2300 default fn from_iter(mut iterator: I) -> Self {
2301 // Unroll the first iteration, as the vector is going to be
2302 // expanded on this iteration in every case when the iterable is not
2303 // empty, but the loop in extend_desugared() is not going to see the
2304 // vector being full in the few subsequent loop iterations.
2305 // So we get better branch prediction.
2306 let mut vector = match iterator.next() {
2307 None => return Vec::new(),
2308 Some(element) => {
2309 let (lower, _) = iterator.size_hint();
2310 let mut vector = Vec::with_capacity(lower.saturating_add(1));
2311 unsafe {
2312 ptr::write(vector.as_mut_ptr(), element);
2313 vector.set_len(1);
2314 }
2315 vector
2316 }
2317 };
2318 // must delegate to spec_extend() since extend() itself delegates
2319 // to spec_from for empty Vecs
2320 <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
2321 vector
2322 }
2323 }
2324
2325 impl<T, I> SpecFromIterNested<T, I> for Vec<T>
2326 where
2327 I: TrustedLen<Item = T>,
2328 {
2329 fn from_iter(iterator: I) -> Self {
2330 let mut vector = match iterator.size_hint() {
2331 (_, Some(upper)) => Vec::with_capacity(upper),
2332 _ => Vec::new(),
2333 };
2334 // must delegate to spec_extend() since extend() itself delegates
2335 // to spec_from for empty Vecs
2336 vector.spec_extend(iterator);
2337 vector
2338 }
2339 }
2340
2341 impl<T, I> SpecFromIter<T, I> for Vec<T>
2342 where
2343 I: Iterator<Item = T>,
2344 {
2345 default fn from_iter(iterator: I) -> Self {
2346 SpecFromIterNested::from_iter(iterator)
2347 }
2348 }
2349
2350 // A helper struct for in-place iteration that drops the destination slice of iteration,
2351 // i.e. the head. The source slice (the tail) is dropped by IntoIter.
2352 struct InPlaceDrop<T> {
2353 inner: *mut T,
2354 dst: *mut T,
2355 }
2356
2357 impl<T> InPlaceDrop<T> {
2358 fn len(&self) -> usize {
2359 unsafe { self.dst.offset_from(self.inner) as usize }
2360 }
2361 }
2362
2363 impl<T> Drop for InPlaceDrop<T> {
2364 #[inline]
2365 fn drop(&mut self) {
2366 unsafe {
2367 ptr::drop_in_place(slice::from_raw_parts_mut(self.inner, self.len()));
2368 }
2369 }
2370 }
2371
2372 impl<T> SpecFromIter<T, IntoIter<T>> for Vec<T> {
2373 fn from_iter(iterator: IntoIter<T>) -> Self {
2374 // A common case is passing a vector into a function which immediately
2375 // re-collects into a vector. We can short circuit this if the IntoIter
2376 // has not been advanced at all.
2377 // When it has been advanced We can also reuse the memory and move the data to the front.
2378 // But we only do so when the resulting Vec wouldn't have more unused capacity
2379 // than creating it through the generic FromIterator implementation would. That limitation
2380 // is not strictly necessary as Vec's allocation behavior is intentionally unspecified.
2381 // But it is a conservative choice.
2382 let has_advanced = iterator.buf.as_ptr() as *const _ != iterator.ptr;
2383 if !has_advanced || iterator.len() >= iterator.cap / 2 {
2384 unsafe {
2385 let it = ManuallyDrop::new(iterator);
2386 if has_advanced {
2387 ptr::copy(it.ptr, it.buf.as_ptr(), it.len());
2388 }
2389 return Vec::from_raw_parts(it.buf.as_ptr(), it.len(), it.cap);
2390 }
2391 }
2392
2393 let mut vec = Vec::new();
2394 // must delegate to spec_extend() since extend() itself delegates
2395 // to spec_from for empty Vecs
2396 vec.spec_extend(iterator);
2397 vec
2398 }
2399 }
2400
2401 fn write_in_place_with_drop<T>(
2402 src_end: *const T,
2403 ) -> impl FnMut(InPlaceDrop<T>, T) -> Result<InPlaceDrop<T>, !> {
2404 move |mut sink, item| {
2405 unsafe {
2406 // the InPlaceIterable contract cannot be verified precisely here since
2407 // try_fold has an exclusive reference to the source pointer
2408 // all we can do is check if it's still in range
2409 debug_assert!(sink.dst as *const _ <= src_end, "InPlaceIterable contract violation");
2410 ptr::write(sink.dst, item);
2411 sink.dst = sink.dst.add(1);
2412 }
2413 Ok(sink)
2414 }
2415 }
2416
2417 /// Specialization marker for collecting an iterator pipeline into a Vec while reusing the
2418 /// source allocation, i.e. executing the pipeline in place.
2419 ///
2420 /// The SourceIter parent trait is necessary for the specializing function to access the allocation
2421 /// which is to be reused. But it is not sufficient for the specialization to be valid. See
2422 /// additional bounds on the impl.
2423 #[rustc_unsafe_specialization_marker]
2424 trait SourceIterMarker: SourceIter<Source: AsIntoIter> {}
2425
2426 // The std-internal SourceIter/InPlaceIterable traits are only implemented by chains of
2427 // Adapter<Adapter<Adapter<IntoIter>>> (all owned by core/std). Additional bounds
2428 // on the adapter implementations (beyond `impl<I: Trait> Trait for Adapter<I>`) only depend on other
2429 // traits already marked as specialization traits (Copy, TrustedRandomAccess, FusedIterator).
2430 // I.e. the marker does not depend on lifetimes of user-supplied types. Modulo the Copy hole, which
2431 // several other specializations already depend on.
2432 impl<T> SourceIterMarker for T where T: SourceIter<Source: AsIntoIter> + InPlaceIterable {}
2433
2434 impl<T, I> SpecFromIter<T, I> for Vec<T>
2435 where
2436 I: Iterator<Item = T> + SourceIterMarker,
2437 {
2438 default fn from_iter(mut iterator: I) -> Self {
2439 // Additional requirements which cannot expressed via trait bounds. We rely on const eval
2440 // instead:
2441 // a) no ZSTs as there would be no allocation to reuse and pointer arithmetic would panic
2442 // b) size match as required by Alloc contract
2443 // c) alignments match as required by Alloc contract
2444 if mem::size_of::<T>() == 0
2445 || mem::size_of::<T>()
2446 != mem::size_of::<<<I as SourceIter>::Source as AsIntoIter>::Item>()
2447 || mem::align_of::<T>()
2448 != mem::align_of::<<<I as SourceIter>::Source as AsIntoIter>::Item>()
2449 {
2450 // fallback to more generic implementations
2451 return SpecFromIterNested::from_iter(iterator);
2452 }
2453
2454 let (src_buf, src_ptr, dst_buf, dst_end, cap) = unsafe {
2455 let inner = iterator.as_inner().as_into_iter();
2456 (
2457 inner.buf.as_ptr(),
2458 inner.ptr,
2459 inner.buf.as_ptr() as *mut T,
2460 inner.end as *const T,
2461 inner.cap,
2462 )
2463 };
2464
2465 // use try-fold since
2466 // - it vectorizes better for some iterator adapters
2467 // - unlike most internal iteration methods, it only takes a &mut self
2468 // - it lets us thread the write pointer through its innards and get it back in the end
2469 let sink = InPlaceDrop { inner: dst_buf, dst: dst_buf };
2470 let sink = iterator
2471 .try_fold::<_, _, Result<_, !>>(sink, write_in_place_with_drop(dst_end))
2472 .unwrap();
2473 // iteration succeeded, don't drop head
2474 let dst = ManuallyDrop::new(sink).dst;
2475
2476 let src = unsafe { iterator.as_inner().as_into_iter() };
2477 // check if SourceIter contract was upheld
2478 // caveat: if they weren't we may not even make it to this point
2479 debug_assert_eq!(src_buf, src.buf.as_ptr());
2480 // check InPlaceIterable contract. This is only possible if the iterator advanced the
2481 // source pointer at all. If it uses unchecked access via TrustedRandomAccess
2482 // then the source pointer will stay in its initial position and we can't use it as reference
2483 if src.ptr != src_ptr {
2484 debug_assert!(
2485 dst as *const _ <= src.ptr,
2486 "InPlaceIterable contract violation, write pointer advanced beyond read pointer"
2487 );
2488 }
2489
2490 // drop any remaining values at the tail of the source
2491 src.drop_remaining();
2492 // but prevent drop of the allocation itself once IntoIter goes out of scope
2493 src.forget_allocation();
2494
2495 let vec = unsafe {
2496 let len = dst.offset_from(dst_buf) as usize;
2497 Vec::from_raw_parts(dst_buf, len, cap)
2498 };
2499
2500 vec
2501 }
2502 }
2503
2504 impl<'a, T: 'a, I> SpecFromIter<&'a T, I> for Vec<T>
2505 where
2506 I: Iterator<Item = &'a T>,
2507 T: Clone,
2508 {
2509 default fn from_iter(iterator: I) -> Self {
2510 SpecFromIter::from_iter(iterator.cloned())
2511 }
2512 }
2513
2514 // This utilizes `iterator.as_slice().to_vec()` since spec_extend
2515 // must take more steps to reason about the final capacity + length
2516 // and thus do more work. `to_vec()` directly allocates the correct amount
2517 // and fills it exactly.
2518 impl<'a, T: 'a + Clone> SpecFromIter<&'a T, slice::Iter<'a, T>> for Vec<T> {
2519 #[cfg(not(test))]
2520 fn from_iter(iterator: slice::Iter<'a, T>) -> Self {
2521 iterator.as_slice().to_vec()
2522 }
2523
2524 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
2525 // required for this method definition, is not available. Instead use the
2526 // `slice::to_vec` function which is only available with cfg(test)
2527 // NB see the slice::hack module in slice.rs for more information
2528 #[cfg(test)]
2529 fn from_iter(iterator: slice::Iter<'a, T>) -> Self {
2530 crate::slice::to_vec(iterator.as_slice(), Global)
2531 }
2532 }
2533
2534 // Specialization trait used for Vec::extend
2535 trait SpecExtend<T, I> {
2536 fn spec_extend(&mut self, iter: I);
2537 }
2538
2539 impl<T, I, A: Allocator> SpecExtend<T, I> for Vec<T, A>
2540 where
2541 I: Iterator<Item = T>,
2542 {
2543 default fn spec_extend(&mut self, iter: I) {
2544 self.extend_desugared(iter)
2545 }
2546 }
2547
2548 impl<T, I, A: Allocator> SpecExtend<T, I> for Vec<T, A>
2549 where
2550 I: TrustedLen<Item = T>,
2551 {
2552 default fn spec_extend(&mut self, iterator: I) {
2553 // This is the case for a TrustedLen iterator.
2554 let (low, high) = iterator.size_hint();
2555 if let Some(high_value) = high {
2556 debug_assert_eq!(
2557 low,
2558 high_value,
2559 "TrustedLen iterator's size hint is not exact: {:?}",
2560 (low, high)
2561 );
2562 }
2563 if let Some(additional) = high {
2564 self.reserve(additional);
2565 unsafe {
2566 let mut ptr = self.as_mut_ptr().add(self.len());
2567 let mut local_len = SetLenOnDrop::new(&mut self.len);
2568 iterator.for_each(move |element| {
2569 ptr::write(ptr, element);
2570 ptr = ptr.offset(1);
2571 // NB can't overflow since we would have had to alloc the address space
2572 local_len.increment_len(1);
2573 });
2574 }
2575 } else {
2576 self.extend_desugared(iterator)
2577 }
2578 }
2579 }
2580
2581 impl<T, A: Allocator> SpecExtend<T, IntoIter<T>> for Vec<T, A> {
2582 fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
2583 unsafe {
2584 self.append_elements(iterator.as_slice() as _);
2585 }
2586 iterator.ptr = iterator.end;
2587 }
2588 }
2589
2590 impl<'a, T: 'a, I, A: Allocator + 'a> SpecExtend<&'a T, I> for Vec<T, A>
2591 where
2592 I: Iterator<Item = &'a T>,
2593 T: Clone,
2594 {
2595 default fn spec_extend(&mut self, iterator: I) {
2596 self.spec_extend(iterator.cloned())
2597 }
2598 }
2599
2600 impl<'a, T: 'a, A: Allocator + 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T, A>
2601 where
2602 T: Copy,
2603 {
2604 fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
2605 let slice = iterator.as_slice();
2606 unsafe { self.append_elements(slice) };
2607 }
2608 }
2609
2610 impl<T, A: Allocator> Vec<T, A> {
2611 // leaf method to which various SpecFrom/SpecExtend implementations delegate when
2612 // they have no further optimizations to apply
2613 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
2614 // This is the case for a general iterator.
2615 //
2616 // This function should be the moral equivalent of:
2617 //
2618 // for item in iterator {
2619 // self.push(item);
2620 // }
2621 while let Some(element) = iterator.next() {
2622 let len = self.len();
2623 if len == self.capacity() {
2624 let (lower, _) = iterator.size_hint();
2625 self.reserve(lower.saturating_add(1));
2626 }
2627 unsafe {
2628 ptr::write(self.as_mut_ptr().add(len), element);
2629 // NB can't overflow since we would have had to alloc the address space
2630 self.set_len(len + 1);
2631 }
2632 }
2633 }
2634
2635 /// Creates a splicing iterator that replaces the specified range in the vector
2636 /// with the given `replace_with` iterator and yields the removed items.
2637 /// `replace_with` does not need to be the same length as `range`.
2638 ///
2639 /// `range` is removed even if the iterator is not consumed until the end.
2640 ///
2641 /// It is unspecified how many elements are removed from the vector
2642 /// if the `Splice` value is leaked.
2643 ///
2644 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2645 ///
2646 /// This is optimal if:
2647 ///
2648 /// * The tail (elements in the vector after `range`) is empty,
2649 /// * or `replace_with` yields fewer elements than `range`’s length
2650 /// * or the lower bound of its `size_hint()` is exact.
2651 ///
2652 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2653 ///
2654 /// # Panics
2655 ///
2656 /// Panics if the starting point is greater than the end point or if
2657 /// the end point is greater than the length of the vector.
2658 ///
2659 /// # Examples
2660 ///
2661 /// ```
2662 /// let mut v = vec![1, 2, 3];
2663 /// let new = [7, 8];
2664 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
2665 /// assert_eq!(v, &[7, 8, 3]);
2666 /// assert_eq!(u, &[1, 2]);
2667 /// ```
2668 #[inline]
2669 #[stable(feature = "vec_splice", since = "1.21.0")]
2670 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A>
2671 where
2672 R: RangeBounds<usize>,
2673 I: IntoIterator<Item = T>,
2674 {
2675 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
2676 }
2677
2678 /// Creates an iterator which uses a closure to determine if an element should be removed.
2679 ///
2680 /// If the closure returns true, then the element is removed and yielded.
2681 /// If the closure returns false, the element will remain in the vector and will not be yielded
2682 /// by the iterator.
2683 ///
2684 /// Using this method is equivalent to the following code:
2685 ///
2686 /// ```
2687 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2688 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2689 /// let mut i = 0;
2690 /// while i != vec.len() {
2691 /// if some_predicate(&mut vec[i]) {
2692 /// let val = vec.remove(i);
2693 /// // your code here
2694 /// } else {
2695 /// i += 1;
2696 /// }
2697 /// }
2698 ///
2699 /// # assert_eq!(vec, vec![1, 4, 5]);
2700 /// ```
2701 ///
2702 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2703 /// because it can backshift the elements of the array in bulk.
2704 ///
2705 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2706 /// regardless of whether you choose to keep or remove it.
2707 ///
2708 /// # Examples
2709 ///
2710 /// Splitting an array into evens and odds, reusing the original allocation:
2711 ///
2712 /// ```
2713 /// #![feature(drain_filter)]
2714 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2715 ///
2716 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2717 /// let odds = numbers;
2718 ///
2719 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2720 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2721 /// ```
2722 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2723 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F, A>
2724 where
2725 F: FnMut(&mut T) -> bool,
2726 {
2727 let old_len = self.len();
2728
2729 // Guard against us getting leaked (leak amplification)
2730 unsafe {
2731 self.set_len(0);
2732 }
2733
2734 DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
2735 }
2736 }
2737
2738 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2739 ///
2740 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2741 /// append the entire slice at once.
2742 ///
2743 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2744 #[stable(feature = "extend_ref", since = "1.2.0")]
2745 impl<'a, T: Copy + 'a, A: Allocator + 'a> Extend<&'a T> for Vec<T, A> {
2746 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2747 self.spec_extend(iter.into_iter())
2748 }
2749
2750 #[inline]
2751 fn extend_one(&mut self, &item: &'a T) {
2752 self.push(item);
2753 }
2754
2755 #[inline]
2756 fn extend_reserve(&mut self, additional: usize) {
2757 self.reserve(additional);
2758 }
2759 }
2760
2761 macro_rules! __impl_slice_eq1 {
2762 ([$($vars:tt)*] $lhs:ty, $rhs:ty $(where $ty:ty: $bound:ident)?, #[$stability:meta]) => {
2763 #[$stability]
2764 impl<T, U, $($vars)*> PartialEq<$rhs> for $lhs
2765 where
2766 T: PartialEq<U>,
2767 $($ty: $bound)?
2768 {
2769 #[inline]
2770 fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }
2771 #[inline]
2772 fn ne(&self, other: &$rhs) -> bool { self[..] != other[..] }
2773 }
2774 }
2775 }
2776
2777 __impl_slice_eq1! { [A: Allocator] Vec<T, A>, Vec<U, A>, #[stable(feature = "rust1", since = "1.0.0")] }
2778 __impl_slice_eq1! { [A: Allocator] Vec<T, A>, &[U], #[stable(feature = "rust1", since = "1.0.0")] }
2779 __impl_slice_eq1! { [A: Allocator] Vec<T, A>, &mut [U], #[stable(feature = "rust1", since = "1.0.0")] }
2780 __impl_slice_eq1! { [A: Allocator] &[T], Vec<U, A>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2781 __impl_slice_eq1! { [A: Allocator] &mut [T], Vec<U, A>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2782 __impl_slice_eq1! { [A: Allocator] Vec<T, A>, [U], #[stable(feature = "partialeq_vec_for_slice", since = "1.48.0")] }
2783 __impl_slice_eq1! { [A: Allocator] [T], Vec<U, A>, #[stable(feature = "partialeq_vec_for_slice", since = "1.48.0")] }
2784 __impl_slice_eq1! { [A: Allocator] Cow<'_, [T]>, Vec<U, A> where T: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2785 __impl_slice_eq1! { [] Cow<'_, [T]>, &[U] where T: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2786 __impl_slice_eq1! { [] Cow<'_, [T]>, &mut [U] where T: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2787 __impl_slice_eq1! { [A: Allocator, const N: usize] Vec<T, A>, [U; N], #[stable(feature = "rust1", since = "1.0.0")] }
2788 __impl_slice_eq1! { [A: Allocator, const N: usize] Vec<T, A>, &[U; N], #[stable(feature = "rust1", since = "1.0.0")] }
2789
2790 // NOTE: some less important impls are omitted to reduce code bloat
2791 // FIXME(Centril): Reconsider this?
2792 //__impl_slice_eq1! { [const N: usize] Vec<A>, &mut [B; N], }
2793 //__impl_slice_eq1! { [const N: usize] [A; N], Vec<B>, }
2794 //__impl_slice_eq1! { [const N: usize] &[A; N], Vec<B>, }
2795 //__impl_slice_eq1! { [const N: usize] &mut [A; N], Vec<B>, }
2796 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, [B; N], }
2797 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &[B; N], }
2798 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &mut [B; N], }
2799
2800 /// Implements comparison of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
2801 #[stable(feature = "rust1", since = "1.0.0")]
2802 impl<T: PartialOrd, A: Allocator> PartialOrd for Vec<T, A> {
2803 #[inline]
2804 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2805 PartialOrd::partial_cmp(&**self, &**other)
2806 }
2807 }
2808
2809 #[stable(feature = "rust1", since = "1.0.0")]
2810 impl<T: Eq, A: Allocator> Eq for Vec<T, A> {}
2811
2812 /// Implements ordering of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
2813 #[stable(feature = "rust1", since = "1.0.0")]
2814 impl<T: Ord, A: Allocator> Ord for Vec<T, A> {
2815 #[inline]
2816 fn cmp(&self, other: &Self) -> Ordering {
2817 Ord::cmp(&**self, &**other)
2818 }
2819 }
2820
2821 #[stable(feature = "rust1", since = "1.0.0")]
2822 unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec<T, A> {
2823 fn drop(&mut self) {
2824 unsafe {
2825 // use drop for [T]
2826 // use a raw slice to refer to the elements of the vector as weakest necessary type;
2827 // could avoid questions of validity in certain cases
2828 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
2829 }
2830 // RawVec handles deallocation
2831 }
2832 }
2833
2834 #[stable(feature = "rust1", since = "1.0.0")]
2835 impl<T> Default for Vec<T> {
2836 /// Creates an empty `Vec<T>`.
2837 fn default() -> Vec<T> {
2838 Vec::new()
2839 }
2840 }
2841
2842 #[stable(feature = "rust1", since = "1.0.0")]
2843 impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {
2844 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2845 fmt::Debug::fmt(&**self, f)
2846 }
2847 }
2848
2849 #[stable(feature = "rust1", since = "1.0.0")]
2850 impl<T, A: Allocator> AsRef<Vec<T, A>> for Vec<T, A> {
2851 fn as_ref(&self) -> &Vec<T, A> {
2852 self
2853 }
2854 }
2855
2856 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2857 impl<T, A: Allocator> AsMut<Vec<T, A>> for Vec<T, A> {
2858 fn as_mut(&mut self) -> &mut Vec<T, A> {
2859 self
2860 }
2861 }
2862
2863 #[stable(feature = "rust1", since = "1.0.0")]
2864 impl<T, A: Allocator> AsRef<[T]> for Vec<T, A> {
2865 fn as_ref(&self) -> &[T] {
2866 self
2867 }
2868 }
2869
2870 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2871 impl<T, A: Allocator> AsMut<[T]> for Vec<T, A> {
2872 fn as_mut(&mut self) -> &mut [T] {
2873 self
2874 }
2875 }
2876
2877 #[stable(feature = "rust1", since = "1.0.0")]
2878 impl<T: Clone> From<&[T]> for Vec<T> {
2879 #[cfg(not(test))]
2880 fn from(s: &[T]) -> Vec<T> {
2881 s.to_vec()
2882 }
2883 #[cfg(test)]
2884 fn from(s: &[T]) -> Vec<T> {
2885 crate::slice::to_vec(s, Global)
2886 }
2887 }
2888
2889 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2890 impl<T: Clone> From<&mut [T]> for Vec<T> {
2891 #[cfg(not(test))]
2892 fn from(s: &mut [T]) -> Vec<T> {
2893 s.to_vec()
2894 }
2895 #[cfg(test)]
2896 fn from(s: &mut [T]) -> Vec<T> {
2897 crate::slice::to_vec(s, Global)
2898 }
2899 }
2900
2901 #[stable(feature = "vec_from_array", since = "1.44.0")]
2902 impl<T, const N: usize> From<[T; N]> for Vec<T> {
2903 #[cfg(not(test))]
2904 fn from(s: [T; N]) -> Vec<T> {
2905 <[T]>::into_vec(box s)
2906 }
2907 #[cfg(test)]
2908 fn from(s: [T; N]) -> Vec<T> {
2909 crate::slice::into_vec(box s)
2910 }
2911 }
2912
2913 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2914 impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
2915 where
2916 [T]: ToOwned<Owned = Vec<T>>,
2917 {
2918 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2919 s.into_owned()
2920 }
2921 }
2922
2923 // note: test pulls in libstd, which causes errors here
2924 #[cfg(not(test))]
2925 #[stable(feature = "vec_from_box", since = "1.18.0")]
2926 impl<T, A: Allocator> From<Box<[T], A>> for Vec<T, A> {
2927 fn from(s: Box<[T], A>) -> Self {
2928 let len = s.len();
2929 Self { buf: RawVec::from_box(s), len }
2930 }
2931 }
2932
2933 // note: test pulls in libstd, which causes errors here
2934 #[cfg(not(test))]
2935 #[stable(feature = "box_from_vec", since = "1.20.0")]
2936 impl<T, A: Allocator> From<Vec<T, A>> for Box<[T], A> {
2937 fn from(v: Vec<T, A>) -> Self {
2938 v.into_boxed_slice()
2939 }
2940 }
2941
2942 #[stable(feature = "rust1", since = "1.0.0")]
2943 impl From<&str> for Vec<u8> {
2944 fn from(s: &str) -> Vec<u8> {
2945 From::from(s.as_bytes())
2946 }
2947 }
2948
2949 #[stable(feature = "array_try_from_vec", since = "1.48.0")]
2950 impl<T, A: Allocator, const N: usize> TryFrom<Vec<T, A>> for [T; N] {
2951 type Error = Vec<T, A>;
2952
2953 /// Gets the entire contents of the `Vec<T>` as an array,
2954 /// if its size exactly matches that of the requested array.
2955 ///
2956 /// # Examples
2957 ///
2958 /// ```
2959 /// use std::convert::TryInto;
2960 /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
2961 /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
2962 /// ```
2963 ///
2964 /// If the length doesn't match, the input comes back in `Err`:
2965 /// ```
2966 /// use std::convert::TryInto;
2967 /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
2968 /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
2969 /// ```
2970 ///
2971 /// If you're fine with just getting a prefix of the `Vec<T>`,
2972 /// you can call [`.truncate(N)`](Vec::truncate) first.
2973 /// ```
2974 /// use std::convert::TryInto;
2975 /// let mut v = String::from("hello world").into_bytes();
2976 /// v.sort();
2977 /// v.truncate(2);
2978 /// let [a, b]: [_; 2] = v.try_into().unwrap();
2979 /// assert_eq!(a, b' ');
2980 /// assert_eq!(b, b'd');
2981 /// ```
2982 fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> {
2983 if vec.len() != N {
2984 return Err(vec);
2985 }
2986
2987 // SAFETY: `.set_len(0)` is always sound.
2988 unsafe { vec.set_len(0) };
2989
2990 // SAFETY: A `Vec`'s pointer is always aligned properly, and
2991 // the alignment the array needs is the same as the items.
2992 // We checked earlier that we have sufficient items.
2993 // The items will not double-drop as the `set_len`
2994 // tells the `Vec` not to also drop them.
2995 let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };
2996 Ok(array)
2997 }
2998 }
2999
3000 ////////////////////////////////////////////////////////////////////////////////
3001 // Clone-on-write
3002 ////////////////////////////////////////////////////////////////////////////////
3003
3004 #[stable(feature = "cow_from_vec", since = "1.8.0")]
3005 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
3006 fn from(s: &'a [T]) -> Cow<'a, [T]> {
3007 Cow::Borrowed(s)
3008 }
3009 }
3010
3011 #[stable(feature = "cow_from_vec", since = "1.8.0")]
3012 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
3013 fn from(v: Vec<T>) -> Cow<'a, [T]> {
3014 Cow::Owned(v)
3015 }
3016 }
3017
3018 #[stable(feature = "cow_from_vec_ref", since = "1.28.0")]
3019 impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]> {
3020 fn from(v: &'a Vec<T>) -> Cow<'a, [T]> {
3021 Cow::Borrowed(v.as_slice())
3022 }
3023 }
3024
3025 #[stable(feature = "rust1", since = "1.0.0")]
3026 impl<'a, T> FromIterator<T> for Cow<'a, [T]>
3027 where
3028 T: Clone,
3029 {
3030 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
3031 Cow::Owned(FromIterator::from_iter(it))
3032 }
3033 }
3034
3035 ////////////////////////////////////////////////////////////////////////////////
3036 // Iterators
3037 ////////////////////////////////////////////////////////////////////////////////
3038
3039 /// An iterator that moves out of a vector.
3040 ///
3041 /// This `struct` is created by the `into_iter` method on [`Vec`] (provided
3042 /// by the [`IntoIterator`] trait).
3043 ///
3044 /// # Example
3045 ///
3046 /// ```
3047 /// let v = vec![0, 1, 2];
3048 /// let iter: std::vec::IntoIter<_> = v.into_iter();
3049 /// ```
3050 #[stable(feature = "rust1", since = "1.0.0")]
3051 pub struct IntoIter<
3052 T,
3053 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
3054 > {
3055 buf: NonNull<T>,
3056 phantom: PhantomData<T>,
3057 cap: usize,
3058 alloc: A,
3059 ptr: *const T,
3060 end: *const T,
3061 }
3062
3063 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
3064 impl<T: fmt::Debug, A: Allocator> fmt::Debug for IntoIter<T, A> {
3065 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3066 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
3067 }
3068 }
3069
3070 impl<T, A: Allocator> IntoIter<T, A> {
3071 /// Returns the remaining items of this iterator as a slice.
3072 ///
3073 /// # Examples
3074 ///
3075 /// ```
3076 /// let vec = vec!['a', 'b', 'c'];
3077 /// let mut into_iter = vec.into_iter();
3078 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
3079 /// let _ = into_iter.next().unwrap();
3080 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
3081 /// ```
3082 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
3083 pub fn as_slice(&self) -> &[T] {
3084 unsafe { slice::from_raw_parts(self.ptr, self.len()) }
3085 }
3086
3087 /// Returns the remaining items of this iterator as a mutable slice.
3088 ///
3089 /// # Examples
3090 ///
3091 /// ```
3092 /// let vec = vec!['a', 'b', 'c'];
3093 /// let mut into_iter = vec.into_iter();
3094 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
3095 /// into_iter.as_mut_slice()[2] = 'z';
3096 /// assert_eq!(into_iter.next().unwrap(), 'a');
3097 /// assert_eq!(into_iter.next().unwrap(), 'b');
3098 /// assert_eq!(into_iter.next().unwrap(), 'z');
3099 /// ```
3100 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
3101 pub fn as_mut_slice(&mut self) -> &mut [T] {
3102 unsafe { &mut *self.as_raw_mut_slice() }
3103 }
3104
3105 /// Returns a reference to the underlying allocator.
3106 #[unstable(feature = "allocator_api", issue = "32838")]
3107 #[inline]
3108 pub fn allocator(&self) -> &A {
3109 &self.alloc
3110 }
3111
3112 fn as_raw_mut_slice(&mut self) -> *mut [T] {
3113 ptr::slice_from_raw_parts_mut(self.ptr as *mut T, self.len())
3114 }
3115
3116 fn drop_remaining(&mut self) {
3117 unsafe {
3118 ptr::drop_in_place(self.as_mut_slice());
3119 }
3120 self.ptr = self.end;
3121 }
3122
3123 /// Relinquishes the backing allocation, equivalent to
3124 /// `ptr::write(&mut self, Vec::new().into_iter())`
3125 fn forget_allocation(&mut self) {
3126 self.cap = 0;
3127 self.buf = unsafe { NonNull::new_unchecked(RawVec::NEW.ptr()) };
3128 self.ptr = self.buf.as_ptr();
3129 self.end = self.buf.as_ptr();
3130 }
3131 }
3132
3133 #[stable(feature = "vec_intoiter_as_ref", since = "1.46.0")]
3134 impl<T, A: Allocator> AsRef<[T]> for IntoIter<T, A> {
3135 fn as_ref(&self) -> &[T] {
3136 self.as_slice()
3137 }
3138 }
3139
3140 #[stable(feature = "rust1", since = "1.0.0")]
3141 unsafe impl<T: Send, A: Allocator + Send> Send for IntoIter<T, A> {}
3142 #[stable(feature = "rust1", since = "1.0.0")]
3143 unsafe impl<T: Sync, A: Allocator> Sync for IntoIter<T, A> {}
3144
3145 #[stable(feature = "rust1", since = "1.0.0")]
3146 impl<T, A: Allocator> Iterator for IntoIter<T, A> {
3147 type Item = T;
3148
3149 #[inline]
3150 fn next(&mut self) -> Option<T> {
3151 if self.ptr as *const _ == self.end {
3152 None
3153 } else if mem::size_of::<T>() == 0 {
3154 // purposefully don't use 'ptr.offset' because for
3155 // vectors with 0-size elements this would return the
3156 // same pointer.
3157 self.ptr = unsafe { arith_offset(self.ptr as *const i8, 1) as *mut T };
3158
3159 // Make up a value of this ZST.
3160 Some(unsafe { mem::zeroed() })
3161 } else {
3162 let old = self.ptr;
3163 self.ptr = unsafe { self.ptr.offset(1) };
3164
3165 Some(unsafe { ptr::read(old) })
3166 }
3167 }
3168
3169 #[inline]
3170 fn size_hint(&self) -> (usize, Option<usize>) {
3171 let exact = if mem::size_of::<T>() == 0 {
3172 (self.end as usize).wrapping_sub(self.ptr as usize)
3173 } else {
3174 unsafe { self.end.offset_from(self.ptr) as usize }
3175 };
3176 (exact, Some(exact))
3177 }
3178
3179 #[inline]
3180 fn count(self) -> usize {
3181 self.len()
3182 }
3183
3184 unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> Self::Item
3185 where
3186 Self: TrustedRandomAccess,
3187 {
3188 // SAFETY: the caller must guarantee that `i` is in bounds of the
3189 // `Vec<T>`, so `i` cannot overflow an `isize`, and the `self.ptr.add(i)`
3190 // is guaranteed to pointer to an element of the `Vec<T>` and
3191 // thus guaranteed to be valid to dereference.
3192 //
3193 // Also note the implementation of `Self: TrustedRandomAccess` requires
3194 // that `T: Copy` so reading elements from the buffer doesn't invalidate
3195 // them for `Drop`.
3196 unsafe {
3197 if mem::size_of::<T>() == 0 { mem::zeroed() } else { ptr::read(self.ptr.add(i)) }
3198 }
3199 }
3200 }
3201
3202 #[stable(feature = "rust1", since = "1.0.0")]
3203 impl<T, A: Allocator> DoubleEndedIterator for IntoIter<T, A> {
3204 #[inline]
3205 fn next_back(&mut self) -> Option<T> {
3206 if self.end == self.ptr {
3207 None
3208 } else if mem::size_of::<T>() == 0 {
3209 // See above for why 'ptr.offset' isn't used
3210 self.end = unsafe { arith_offset(self.end as *const i8, -1) as *mut T };
3211
3212 // Make up a value of this ZST.
3213 Some(unsafe { mem::zeroed() })
3214 } else {
3215 self.end = unsafe { self.end.offset(-1) };
3216
3217 Some(unsafe { ptr::read(self.end) })
3218 }
3219 }
3220 }
3221
3222 #[stable(feature = "rust1", since = "1.0.0")]
3223 impl<T, A: Allocator> ExactSizeIterator for IntoIter<T, A> {
3224 fn is_empty(&self) -> bool {
3225 self.ptr == self.end
3226 }
3227 }
3228
3229 #[stable(feature = "fused", since = "1.26.0")]
3230 impl<T, A: Allocator> FusedIterator for IntoIter<T, A> {}
3231
3232 #[unstable(feature = "trusted_len", issue = "37572")]
3233 unsafe impl<T, A: Allocator> TrustedLen for IntoIter<T, A> {}
3234
3235 #[doc(hidden)]
3236 #[unstable(issue = "none", feature = "std_internals")]
3237 // T: Copy as approximation for !Drop since get_unchecked does not advance self.ptr
3238 // and thus we can't implement drop-handling
3239 unsafe impl<T, A: Allocator> TrustedRandomAccess for IntoIter<T, A>
3240 where
3241 T: Copy,
3242 {
3243 fn may_have_side_effect() -> bool {
3244 false
3245 }
3246 }
3247
3248 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
3249 impl<T: Clone, A: Allocator + Clone> Clone for IntoIter<T, A> {
3250 #[cfg(not(test))]
3251 fn clone(&self) -> Self {
3252 self.as_slice().to_vec_in(self.alloc.clone()).into_iter()
3253 }
3254 #[cfg(test)]
3255 fn clone(&self) -> Self {
3256 crate::slice::to_vec(self.as_slice(), self.alloc.clone()).into_iter()
3257 }
3258 }
3259
3260 #[stable(feature = "rust1", since = "1.0.0")]
3261 unsafe impl<#[may_dangle] T, A: Allocator> Drop for IntoIter<T, A> {
3262 fn drop(&mut self) {
3263 struct DropGuard<'a, T, A: Allocator>(&'a mut IntoIter<T, A>);
3264
3265 impl<T, A: Allocator> Drop for DropGuard<'_, T, A> {
3266 fn drop(&mut self) {
3267 unsafe {
3268 // `IntoIter::alloc` is not used anymore after this
3269 let alloc = ptr::read(&self.0.alloc);
3270 // RawVec handles deallocation
3271 let _ = RawVec::from_raw_parts_in(self.0.buf.as_ptr(), self.0.cap, alloc);
3272 }
3273 }
3274 }
3275
3276 let guard = DropGuard(self);
3277 // destroy the remaining elements
3278 unsafe {
3279 ptr::drop_in_place(guard.0.as_raw_mut_slice());
3280 }
3281 // now `guard` will be dropped and do the rest
3282 }
3283 }
3284
3285 #[unstable(issue = "none", feature = "inplace_iteration")]
3286 unsafe impl<T, A: Allocator> InPlaceIterable for IntoIter<T, A> {}
3287
3288 #[unstable(issue = "none", feature = "inplace_iteration")]
3289 unsafe impl<T, A: Allocator> SourceIter for IntoIter<T, A> {
3290 type Source = Self;
3291
3292 #[inline]
3293 unsafe fn as_inner(&mut self) -> &mut Self::Source {
3294 self
3295 }
3296 }
3297
3298 // internal helper trait for in-place iteration specialization.
3299 #[rustc_specialization_trait]
3300 pub(crate) trait AsIntoIter {
3301 type Item;
3302 fn as_into_iter(&mut self) -> &mut IntoIter<Self::Item>;
3303 }
3304
3305 impl<T> AsIntoIter for IntoIter<T> {
3306 type Item = T;
3307
3308 fn as_into_iter(&mut self) -> &mut IntoIter<Self::Item> {
3309 self
3310 }
3311 }
3312
3313 /// A draining iterator for `Vec<T>`.
3314 ///
3315 /// This `struct` is created by [`Vec::drain`].
3316 /// See its documentation for more.
3317 ///
3318 /// # Example
3319 ///
3320 /// ```
3321 /// let mut v = vec![0, 1, 2];
3322 /// let iter: std::vec::Drain<_> = v.drain(..);
3323 /// ```
3324 #[stable(feature = "drain", since = "1.6.0")]
3325 pub struct Drain<
3326 'a,
3327 T: 'a,
3328 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + 'a = Global,
3329 > {
3330 /// Index of tail to preserve
3331 tail_start: usize,
3332 /// Length of tail
3333 tail_len: usize,
3334 /// Current remaining range to remove
3335 iter: slice::Iter<'a, T>,
3336 vec: NonNull<Vec<T, A>>,
3337 }
3338
3339 #[stable(feature = "collection_debug", since = "1.17.0")]
3340 impl<T: fmt::Debug, A: Allocator> fmt::Debug for Drain<'_, T, A> {
3341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3342 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
3343 }
3344 }
3345
3346 impl<'a, T, A: Allocator> Drain<'a, T, A> {
3347 /// Returns the remaining items of this iterator as a slice.
3348 ///
3349 /// # Examples
3350 ///
3351 /// ```
3352 /// let mut vec = vec!['a', 'b', 'c'];
3353 /// let mut drain = vec.drain(..);
3354 /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
3355 /// let _ = drain.next().unwrap();
3356 /// assert_eq!(drain.as_slice(), &['b', 'c']);
3357 /// ```
3358 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
3359 pub fn as_slice(&self) -> &[T] {
3360 self.iter.as_slice()
3361 }
3362
3363 /// Returns a reference to the underlying allocator.
3364 #[unstable(feature = "allocator_api", issue = "32838")]
3365 #[inline]
3366 pub fn allocator(&self) -> &A {
3367 unsafe { self.vec.as_ref().allocator() }
3368 }
3369 }
3370
3371 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
3372 impl<'a, T, A: Allocator> AsRef<[T]> for Drain<'a, T, A> {
3373 fn as_ref(&self) -> &[T] {
3374 self.as_slice()
3375 }
3376 }
3377
3378 #[stable(feature = "drain", since = "1.6.0")]
3379 unsafe impl<T: Sync, A: Sync + Allocator> Sync for Drain<'_, T, A> {}
3380 #[stable(feature = "drain", since = "1.6.0")]
3381 unsafe impl<T: Send, A: Send + Allocator> Send for Drain<'_, T, A> {}
3382
3383 #[stable(feature = "drain", since = "1.6.0")]
3384 impl<T, A: Allocator> Iterator for Drain<'_, T, A> {
3385 type Item = T;
3386
3387 #[inline]
3388 fn next(&mut self) -> Option<T> {
3389 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
3390 }
3391
3392 fn size_hint(&self) -> (usize, Option<usize>) {
3393 self.iter.size_hint()
3394 }
3395 }
3396
3397 #[stable(feature = "drain", since = "1.6.0")]
3398 impl<T, A: Allocator> DoubleEndedIterator for Drain<'_, T, A> {
3399 #[inline]
3400 fn next_back(&mut self) -> Option<T> {
3401 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
3402 }
3403 }
3404
3405 #[stable(feature = "drain", since = "1.6.0")]
3406 impl<T, A: Allocator> Drop for Drain<'_, T, A> {
3407 fn drop(&mut self) {
3408 /// Continues dropping the remaining elements in the `Drain`, then moves back the
3409 /// un-`Drain`ed elements to restore the original `Vec`.
3410 struct DropGuard<'r, 'a, T, A: Allocator>(&'r mut Drain<'a, T, A>);
3411
3412 impl<'r, 'a, T, A: Allocator> Drop for DropGuard<'r, 'a, T, A> {
3413 fn drop(&mut self) {
3414 // Continue the same loop we have below. If the loop already finished, this does
3415 // nothing.
3416 self.0.for_each(drop);
3417
3418 if self.0.tail_len > 0 {
3419 unsafe {
3420 let source_vec = self.0.vec.as_mut();
3421 // memmove back untouched tail, update to new length
3422 let start = source_vec.len();
3423 let tail = self.0.tail_start;
3424 if tail != start {
3425 let src = source_vec.as_ptr().add(tail);
3426 let dst = source_vec.as_mut_ptr().add(start);
3427 ptr::copy(src, dst, self.0.tail_len);
3428 }
3429 source_vec.set_len(start + self.0.tail_len);
3430 }
3431 }
3432 }
3433 }
3434
3435 // exhaust self first
3436 while let Some(item) = self.next() {
3437 let guard = DropGuard(self);
3438 drop(item);
3439 mem::forget(guard);
3440 }
3441
3442 // Drop a `DropGuard` to move back the non-drained tail of `self`.
3443 DropGuard(self);
3444 }
3445 }
3446
3447 #[stable(feature = "drain", since = "1.6.0")]
3448 impl<T, A: Allocator> ExactSizeIterator for Drain<'_, T, A> {
3449 fn is_empty(&self) -> bool {
3450 self.iter.is_empty()
3451 }
3452 }
3453
3454 #[unstable(feature = "trusted_len", issue = "37572")]
3455 unsafe impl<T, A: Allocator> TrustedLen for Drain<'_, T, A> {}
3456
3457 #[stable(feature = "fused", since = "1.26.0")]
3458 impl<T, A: Allocator> FusedIterator for Drain<'_, T, A> {}
3459
3460 /// A splicing iterator for `Vec`.
3461 ///
3462 /// This struct is created by [`Vec::splice()`].
3463 /// See its documentation for more.
3464 ///
3465 /// # Example
3466 ///
3467 /// ```
3468 /// let mut v = vec![0, 1, 2];
3469 /// let new = [7, 8];
3470 /// let iter: std::vec::Splice<_> = v.splice(1.., new.iter().cloned());
3471 /// ```
3472 #[derive(Debug)]
3473 #[stable(feature = "vec_splice", since = "1.21.0")]
3474 pub struct Splice<
3475 'a,
3476 I: Iterator + 'a,
3477 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + 'a = Global,
3478 > {
3479 drain: Drain<'a, I::Item, A>,
3480 replace_with: I,
3481 }
3482
3483 #[stable(feature = "vec_splice", since = "1.21.0")]
3484 impl<I: Iterator, A: Allocator> Iterator for Splice<'_, I, A> {
3485 type Item = I::Item;
3486
3487 fn next(&mut self) -> Option<Self::Item> {
3488 self.drain.next()
3489 }
3490
3491 fn size_hint(&self) -> (usize, Option<usize>) {
3492 self.drain.size_hint()
3493 }
3494 }
3495
3496 #[stable(feature = "vec_splice", since = "1.21.0")]
3497 impl<I: Iterator, A: Allocator> DoubleEndedIterator for Splice<'_, I, A> {
3498 fn next_back(&mut self) -> Option<Self::Item> {
3499 self.drain.next_back()
3500 }
3501 }
3502
3503 #[stable(feature = "vec_splice", since = "1.21.0")]
3504 impl<I: Iterator, A: Allocator> ExactSizeIterator for Splice<'_, I, A> {}
3505
3506 #[stable(feature = "vec_splice", since = "1.21.0")]
3507 impl<I: Iterator, A: Allocator> Drop for Splice<'_, I, A> {
3508 fn drop(&mut self) {
3509 self.drain.by_ref().for_each(drop);
3510
3511 unsafe {
3512 if self.drain.tail_len == 0 {
3513 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
3514 return;
3515 }
3516
3517 // First fill the range left by drain().
3518 if !self.drain.fill(&mut self.replace_with) {
3519 return;
3520 }
3521
3522 // There may be more elements. Use the lower bound as an estimate.
3523 // FIXME: Is the upper bound a better guess? Or something else?
3524 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
3525 if lower_bound > 0 {
3526 self.drain.move_tail(lower_bound);
3527 if !self.drain.fill(&mut self.replace_with) {
3528 return;
3529 }
3530 }
3531
3532 // Collect any remaining elements.
3533 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
3534 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
3535 // Now we have an exact count.
3536 if collected.len() > 0 {
3537 self.drain.move_tail(collected.len());
3538 let filled = self.drain.fill(&mut collected);
3539 debug_assert!(filled);
3540 debug_assert_eq!(collected.len(), 0);
3541 }
3542 }
3543 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
3544 }
3545 }
3546
3547 /// Private helper methods for `Splice::drop`
3548 impl<T, A: Allocator> Drain<'_, T, A> {
3549 /// The range from `self.vec.len` to `self.tail_start` contains elements
3550 /// that have been moved out.
3551 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
3552 /// Returns `true` if we filled the entire range. (`replace_with.next()` didn’t return `None`.)
3553 unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool {
3554 let vec = unsafe { self.vec.as_mut() };
3555 let range_start = vec.len;
3556 let range_end = self.tail_start;
3557 let range_slice = unsafe {
3558 slice::from_raw_parts_mut(vec.as_mut_ptr().add(range_start), range_end - range_start)
3559 };
3560
3561 for place in range_slice {
3562 if let Some(new_item) = replace_with.next() {
3563 unsafe { ptr::write(place, new_item) };
3564 vec.len += 1;
3565 } else {
3566 return false;
3567 }
3568 }
3569 true
3570 }
3571
3572 /// Makes room for inserting more elements before the tail.
3573 unsafe fn move_tail(&mut self, additional: usize) {
3574 let vec = unsafe { self.vec.as_mut() };
3575 let len = self.tail_start + self.tail_len;
3576 vec.buf.reserve(len, additional);
3577
3578 let new_tail_start = self.tail_start + additional;
3579 unsafe {
3580 let src = vec.as_ptr().add(self.tail_start);
3581 let dst = vec.as_mut_ptr().add(new_tail_start);
3582 ptr::copy(src, dst, self.tail_len);
3583 }
3584 self.tail_start = new_tail_start;
3585 }
3586 }
3587
3588 /// An iterator which uses a closure to determine if an element should be removed.
3589 ///
3590 /// This struct is created by [`Vec::drain_filter`].
3591 /// See its documentation for more.
3592 ///
3593 /// # Example
3594 ///
3595 /// ```
3596 /// #![feature(drain_filter)]
3597 ///
3598 /// let mut v = vec![0, 1, 2];
3599 /// let iter: std::vec::DrainFilter<_, _> = v.drain_filter(|x| *x % 2 == 0);
3600 /// ```
3601 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3602 #[derive(Debug)]
3603 pub struct DrainFilter<
3604 'a,
3605 T,
3606 F,
3607 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
3608 > where
3609 F: FnMut(&mut T) -> bool,
3610 {
3611 vec: &'a mut Vec<T, A>,
3612 /// The index of the item that will be inspected by the next call to `next`.
3613 idx: usize,
3614 /// The number of items that have been drained (removed) thus far.
3615 del: usize,
3616 /// The original length of `vec` prior to draining.
3617 old_len: usize,
3618 /// The filter test predicate.
3619 pred: F,
3620 /// A flag that indicates a panic has occurred in the filter test predicate.
3621 /// This is used as a hint in the drop implementation to prevent consumption
3622 /// of the remainder of the `DrainFilter`. Any unprocessed items will be
3623 /// backshifted in the `vec`, but no further items will be dropped or
3624 /// tested by the filter predicate.
3625 panic_flag: bool,
3626 }
3627
3628 impl<T, F, A: Allocator> DrainFilter<'_, T, F, A>
3629 where
3630 F: FnMut(&mut T) -> bool,
3631 {
3632 /// Returns a reference to the underlying allocator.
3633 #[unstable(feature = "allocator_api", issue = "32838")]
3634 #[inline]
3635 pub fn allocator(&self) -> &A {
3636 self.vec.allocator()
3637 }
3638 }
3639
3640 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3641 impl<T, F, A: Allocator> Iterator for DrainFilter<'_, T, F, A>
3642 where
3643 F: FnMut(&mut T) -> bool,
3644 {
3645 type Item = T;
3646
3647 fn next(&mut self) -> Option<T> {
3648 unsafe {
3649 while self.idx < self.old_len {
3650 let i = self.idx;
3651 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
3652 self.panic_flag = true;
3653 let drained = (self.pred)(&mut v[i]);
3654 self.panic_flag = false;
3655 // Update the index *after* the predicate is called. If the index
3656 // is updated prior and the predicate panics, the element at this
3657 // index would be leaked.
3658 self.idx += 1;
3659 if drained {
3660 self.del += 1;
3661 return Some(ptr::read(&v[i]));
3662 } else if self.del > 0 {
3663 let del = self.del;
3664 let src: *const T = &v[i];
3665 let dst: *mut T = &mut v[i - del];
3666 ptr::copy_nonoverlapping(src, dst, 1);
3667 }
3668 }
3669 None
3670 }
3671 }
3672
3673 fn size_hint(&self) -> (usize, Option<usize>) {
3674 (0, Some(self.old_len - self.idx))
3675 }
3676 }
3677
3678 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3679 impl<T, F, A: Allocator> Drop for DrainFilter<'_, T, F, A>
3680 where
3681 F: FnMut(&mut T) -> bool,
3682 {
3683 fn drop(&mut self) {
3684 struct BackshiftOnDrop<'a, 'b, T, F, A: Allocator>
3685 where
3686 F: FnMut(&mut T) -> bool,
3687 {
3688 drain: &'b mut DrainFilter<'a, T, F, A>,
3689 }
3690
3691 impl<'a, 'b, T, F, A: Allocator> Drop for BackshiftOnDrop<'a, 'b, T, F, A>
3692 where
3693 F: FnMut(&mut T) -> bool,
3694 {
3695 fn drop(&mut self) {
3696 unsafe {
3697 if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
3698 // This is a pretty messed up state, and there isn't really an
3699 // obviously right thing to do. We don't want to keep trying
3700 // to execute `pred`, so we just backshift all the unprocessed
3701 // elements and tell the vec that they still exist. The backshift
3702 // is required to prevent a double-drop of the last successfully
3703 // drained item prior to a panic in the predicate.
3704 let ptr = self.drain.vec.as_mut_ptr();
3705 let src = ptr.add(self.drain.idx);
3706 let dst = src.sub(self.drain.del);
3707 let tail_len = self.drain.old_len - self.drain.idx;
3708 src.copy_to(dst, tail_len);
3709 }
3710 self.drain.vec.set_len(self.drain.old_len - self.drain.del);
3711 }
3712 }
3713 }
3714
3715 let backshift = BackshiftOnDrop { drain: self };
3716
3717 // Attempt to consume any remaining elements if the filter predicate
3718 // has not yet panicked. We'll backshift any remaining elements
3719 // whether we've already panicked or if the consumption here panics.
3720 if !backshift.drain.panic_flag {
3721 backshift.drain.for_each(drop);
3722 }
3723 }
3724 }