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