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