1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A contiguous growable array type with heap-allocated contents, written
12 //! `Vec<T>` but pronounced 'vector.'
14 //! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and
15 //! `O(1)` pop (from the end).
19 //! You can explicitly create a `Vec<T>` with `new()`:
22 //! let v: Vec<i32> = Vec::new();
25 //! ...or by using the `vec!` macro:
28 //! let v: Vec<i32> = vec![];
30 //! let v = vec![1, 2, 3, 4, 5];
32 //! let v = vec![0; 10]; // ten zeroes
35 //! You can `push` values onto the end of a vector (which will grow the vector
39 //! let mut v = vec![1, 2];
44 //! Popping values works in much the same way:
47 //! let mut v = vec![1, 2];
49 //! let two = v.pop();
52 //! Vectors also support indexing (through the `Index` and `IndexMut` traits):
55 //! let mut v = vec![1, 2, 3];
60 #![stable(feature = "rust1", since = "1.0.0")]
62 use alloc
::boxed
::Box
;
63 use alloc
::heap
::EMPTY
;
64 use alloc
::raw_vec
::RawVec
;
67 use core
::cmp
::Ordering
;
69 use core
::hash
::{self, Hash}
;
70 use core
::intrinsics
::{arith_offset, assume}
;
71 use core
::iter
::{FromIterator, FusedIterator}
;
73 use core
::ops
::{Index, IndexMut}
;
76 use core
::ptr
::Shared
;
79 use super::SpecExtend
;
80 use super::range
::RangeArgument
;
82 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector.'
87 /// let mut vec = Vec::new();
91 /// assert_eq!(vec.len(), 2);
92 /// assert_eq!(vec[0], 1);
94 /// assert_eq!(vec.pop(), Some(2));
95 /// assert_eq!(vec.len(), 1);
98 /// assert_eq!(vec[0], 7);
100 /// vec.extend([1, 2, 3].iter().cloned());
103 /// println!("{}", x);
105 /// assert_eq!(vec, [7, 1, 2, 3]);
108 /// The `vec!` macro is provided to make initialization more convenient:
111 /// let mut vec = vec![1, 2, 3];
113 /// assert_eq!(vec, [1, 2, 3, 4]);
116 /// It can also initialize each element of a `Vec<T>` with a given value:
119 /// let vec = vec![0; 5];
120 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
123 /// Use a `Vec<T>` as an efficient stack:
126 /// let mut stack = Vec::new();
132 /// while let Some(top) = stack.pop() {
133 /// // Prints 3, 2, 1
134 /// println!("{}", top);
140 /// The Vec type allows to access values by index, because it implements the
141 /// `Index` trait. An example will be more explicit:
144 /// let v = vec!(0, 2, 4, 6);
145 /// println!("{}", v[1]); // it will display '2'
148 /// However be careful: if you try to access an index which isn't in the Vec,
149 /// your software will panic! You cannot do this:
152 /// let v = vec!(0, 2, 4, 6);
153 /// println!("{}", v[6]); // it will panic!
156 /// In conclusion: always check if the index you want to get really exists
161 /// A Vec can be mutable. Slices, on the other hand, are read-only objects.
162 /// To get a slice, use "&". Example:
165 /// fn read_slice(slice: &[usize]) {
169 /// let v = vec!(0, 1);
172 /// // ... and that's all!
173 /// // you can also do it like this:
174 /// let x : &[usize] = &v;
177 /// In Rust, it's more common to pass slices as arguments rather than vectors
178 /// when you just want to provide a read access. The same goes for String and
181 /// # Capacity and reallocation
183 /// The capacity of a vector is the amount of space allocated for any future
184 /// elements that will be added onto the vector. This is not to be confused with
185 /// the *length* of a vector, which specifies the number of actual elements
186 /// within the vector. If a vector's length exceeds its capacity, its capacity
187 /// will automatically be increased, but its elements will have to be
190 /// For example, a vector with capacity 10 and length 0 would be an empty vector
191 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
192 /// vector will not change its capacity or cause reallocation to occur. However,
193 /// if the vector's length is increased to 11, it will have to reallocate, which
194 /// can be slow. For this reason, it is recommended to use `Vec::with_capacity`
195 /// whenever possible to specify how big the vector is expected to get.
199 /// Due to its incredibly fundamental nature, Vec makes a lot of guarantees
200 /// about its design. This ensures that it's as low-overhead as possible in
201 /// the general case, and can be correctly manipulated in primitive ways
202 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
203 /// If additional type parameters are added (e.g. to support custom allocators),
204 /// overriding their defaults may change the behavior.
206 /// Most fundamentally, Vec is and always will be a (pointer, capacity, length)
207 /// triplet. No more, no less. The order of these fields is completely
208 /// unspecified, and you should use the appropriate methods to modify these.
209 /// The pointer will never be null, so this type is null-pointer-optimized.
211 /// However, the pointer may not actually point to allocated memory. In particular,
212 /// if you construct a Vec with capacity 0 via `Vec::new()`, `vec![]`,
213 /// `Vec::with_capacity(0)`, or by calling `shrink_to_fit()` on an empty Vec, it
214 /// will not allocate memory. Similarly, if you store zero-sized types inside
215 /// a Vec, it will not allocate space for them. *Note that in this case the
216 /// Vec may not report a `capacity()` of 0*. Vec will allocate if and only
217 /// if `mem::size_of::<T>() * capacity() > 0`. In general, Vec's allocation
218 /// details are subtle enough that it is strongly recommended that you only
219 /// free memory allocated by a Vec by creating a new Vec and dropping it.
221 /// If a Vec *has* allocated memory, then the memory it points to is on the heap
222 /// (as defined by the allocator Rust is configured to use by default), and its
223 /// pointer points to `len()` initialized elements in order (what you would see
224 /// if you coerced it to a slice), followed by `capacity() - len()` logically
225 /// uninitialized elements.
227 /// Vec will never perform a "small optimization" where elements are actually
228 /// stored on the stack for two reasons:
230 /// * It would make it more difficult for unsafe code to correctly manipulate
231 /// a Vec. The contents of a Vec wouldn't have a stable address if it were
232 /// only moved, and it would be more difficult to determine if a Vec had
233 /// actually allocated memory.
235 /// * It would penalize the general case, incurring an additional branch
238 /// Vec will never automatically shrink itself, even if completely empty. This
239 /// ensures no unnecessary allocations or deallocations occur. Emptying a Vec
240 /// and then filling it back up to the same `len()` should incur no calls to
241 /// the allocator. If you wish to free up unused memory, use `shrink_to_fit`.
243 /// `push` and `insert` will never (re)allocate if the reported capacity is
244 /// sufficient. `push` and `insert` *will* (re)allocate if `len() == capacity()`.
245 /// That is, the reported capacity is completely accurate, and can be relied on.
246 /// It can even be used to manually free the memory allocated by a Vec if
247 /// desired. Bulk insertion methods *may* reallocate, even when not necessary.
249 /// Vec does not guarantee any particular growth strategy when reallocating
250 /// when full, nor when `reserve` is called. The current strategy is basic
251 /// and it may prove desirable to use a non-constant growth factor. Whatever
252 /// strategy is used will of course guarantee `O(1)` amortized `push`.
254 /// `vec![x; n]`, `vec![a, b, c, d]`, and `Vec::with_capacity(n)`, will all
255 /// produce a Vec with exactly the requested capacity. If `len() == capacity()`,
256 /// (as is the case for the `vec!` macro), then a `Vec<T>` can be converted
257 /// to and from a `Box<[T]>` without reallocating or moving the elements.
259 /// Vec will not specifically overwrite any data that is removed from it,
260 /// but also won't specifically preserve it. Its uninitialized memory is
261 /// scratch space that it may use however it wants. It will generally just do
262 /// whatever is most efficient or otherwise easy to implement. Do not rely on
263 /// removed data to be erased for security purposes. Even if you drop a Vec, its
264 /// buffer may simply be reused by another Vec. Even if you zero a Vec's memory
265 /// first, that may not actually happen because the optimizer does not consider
266 /// this a side-effect that must be preserved.
268 /// Vec does not currently guarantee the order in which elements are dropped
269 /// (the order has changed in the past, and may change again).
271 #[cfg_attr(stage0, unsafe_no_drop_flag)]
272 #[stable(feature = "rust1", since = "1.0.0")]
278 ////////////////////////////////////////////////////////////////////////////////
280 ////////////////////////////////////////////////////////////////////////////////
283 /// Constructs a new, empty `Vec<T>`.
285 /// The vector will not allocate until elements are pushed onto it.
290 /// # #![allow(unused_mut)]
291 /// let mut vec: Vec<i32> = Vec::new();
294 #[stable(feature = "rust1", since = "1.0.0")]
295 pub fn new() -> Vec
<T
> {
302 /// Constructs a new, empty `Vec<T>` with the specified capacity.
304 /// The vector will be able to hold exactly `capacity` elements without
305 /// reallocating. If `capacity` is 0, the vector will not allocate.
307 /// It is important to note that this function does not specify the *length*
308 /// of the returned vector, but only the *capacity*. (For an explanation of
309 /// the difference between length and capacity, see the main `Vec<T>` docs
310 /// above, 'Capacity and reallocation'.)
315 /// let mut vec = Vec::with_capacity(10);
317 /// // The vector contains no items, even though it has capacity for more
318 /// assert_eq!(vec.len(), 0);
320 /// // These are all done without reallocating...
325 /// // ...but this may make the vector reallocate
329 #[stable(feature = "rust1", since = "1.0.0")]
330 pub fn with_capacity(capacity
: usize) -> Vec
<T
> {
332 buf
: RawVec
::with_capacity(capacity
),
337 /// Creates a `Vec<T>` directly from the raw components of another vector.
341 /// This is highly unsafe, due to the number of invariants that aren't
344 /// * `ptr` needs to have been previously allocated via `String`/`Vec<T>`
345 /// (at least, it's highly likely to be incorrect if it wasn't).
346 /// * `length` needs to be less than or equal to `capacity`.
347 /// * `capacity` needs to be the capacity that the pointer was allocated with.
349 /// Violating these may cause problems like corrupting the allocator's
350 /// internal datastructures.
352 /// The ownership of `ptr` is effectively transferred to the
353 /// `Vec<T>` which may then deallocate, reallocate or change the
354 /// contents of memory pointed to by the pointer at will. Ensure
355 /// that nothing else uses the pointer after calling this
365 /// let mut v = vec![1, 2, 3];
367 /// // Pull out the various important pieces of information about `v`
368 /// let p = v.as_mut_ptr();
369 /// let len = v.len();
370 /// let cap = v.capacity();
373 /// // Cast `v` into the void: no destructor run, so we are in
374 /// // complete control of the allocation to which `p` points.
377 /// // Overwrite memory with 4, 5, 6
378 /// for i in 0..len as isize {
379 /// ptr::write(p.offset(i), 4 + i);
382 /// // Put everything back together into a Vec
383 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
384 /// assert_eq!(rebuilt, [4, 5, 6]);
388 #[stable(feature = "rust1", since = "1.0.0")]
389 pub unsafe fn from_raw_parts(ptr
: *mut T
, length
: usize, capacity
: usize) -> Vec
<T
> {
391 buf
: RawVec
::from_raw_parts(ptr
, capacity
),
396 /// Returns the number of elements the vector can hold without
402 /// let vec: Vec<i32> = Vec::with_capacity(10);
403 /// assert_eq!(vec.capacity(), 10);
406 #[stable(feature = "rust1", since = "1.0.0")]
407 pub fn capacity(&self) -> usize {
411 /// Reserves capacity for at least `additional` more elements to be inserted
412 /// in the given `Vec<T>`. The collection may reserve more space to avoid
413 /// frequent reallocations.
417 /// Panics if the new capacity overflows `usize`.
422 /// let mut vec = vec![1];
424 /// assert!(vec.capacity() >= 11);
426 #[stable(feature = "rust1", since = "1.0.0")]
427 pub fn reserve(&mut self, additional
: usize) {
428 self.buf
.reserve(self.len
, additional
);
431 /// Reserves the minimum capacity for exactly `additional` more elements to
432 /// be inserted in the given `Vec<T>`. Does nothing if the capacity is already
435 /// Note that the allocator may give the collection more space than it
436 /// requests. Therefore capacity can not be relied upon to be precisely
437 /// minimal. Prefer `reserve` if future insertions are expected.
441 /// Panics if the new capacity overflows `usize`.
446 /// let mut vec = vec![1];
447 /// vec.reserve_exact(10);
448 /// assert!(vec.capacity() >= 11);
450 #[stable(feature = "rust1", since = "1.0.0")]
451 pub fn reserve_exact(&mut self, additional
: usize) {
452 self.buf
.reserve_exact(self.len
, additional
);
455 /// Shrinks the capacity of the vector as much as possible.
457 /// It will drop down as close as possible to the length but the allocator
458 /// may still inform the vector that there is space for a few more elements.
463 /// let mut vec = Vec::with_capacity(10);
464 /// vec.extend([1, 2, 3].iter().cloned());
465 /// assert_eq!(vec.capacity(), 10);
466 /// vec.shrink_to_fit();
467 /// assert!(vec.capacity() >= 3);
469 #[stable(feature = "rust1", since = "1.0.0")]
470 pub fn shrink_to_fit(&mut self) {
471 self.buf
.shrink_to_fit(self.len
);
474 /// Converts the vector into Box<[T]>.
476 /// Note that this will drop any excess capacity. Calling this and
477 /// converting back to a vector with `into_vec()` is equivalent to calling
478 /// `shrink_to_fit()`.
483 /// let v = vec![1, 2, 3];
485 /// let slice = v.into_boxed_slice();
488 /// Any excess capacity is removed:
491 /// let mut vec = Vec::with_capacity(10);
492 /// vec.extend([1, 2, 3].iter().cloned());
494 /// assert_eq!(vec.capacity(), 10);
495 /// let slice = vec.into_boxed_slice();
496 /// assert_eq!(slice.into_vec().capacity(), 3);
498 #[stable(feature = "rust1", since = "1.0.0")]
499 pub fn into_boxed_slice(mut self) -> Box
<[T
]> {
501 self.shrink_to_fit();
502 let buf
= ptr
::read(&self.buf
);
508 /// Shortens the vector, keeping the first `len` elements and dropping
511 /// If `len` is greater than the vector's current length, this has no
514 /// The [`drain`] method can emulate `truncate`, but causes the excess
515 /// elements to be returned instead of dropped.
519 /// Truncating a five element vector to two elements:
522 /// let mut vec = vec![1, 2, 3, 4, 5];
524 /// assert_eq!(vec, [1, 2]);
527 /// No truncation occurs when `len` is greater than the vector's current
531 /// let mut vec = vec![1, 2, 3];
533 /// assert_eq!(vec, [1, 2, 3]);
536 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
540 /// let mut vec = vec![1, 2, 3];
542 /// assert_eq!(vec, []);
545 /// [`clear`]: #method.clear
546 /// [`drain`]: #method.drain
547 #[stable(feature = "rust1", since = "1.0.0")]
548 pub fn truncate(&mut self, len
: usize) {
550 // drop any extra elements
551 while len
< self.len
{
552 // decrement len before the drop_in_place(), so a panic on Drop
553 // doesn't re-drop the just-failed value.
556 ptr
::drop_in_place(self.get_unchecked_mut(len
));
561 /// Extracts a slice containing the entire vector.
563 /// Equivalent to `&s[..]`.
568 /// use std::io::{self, Write};
569 /// let buffer = vec![1, 2, 3, 5, 8];
570 /// io::sink().write(buffer.as_slice()).unwrap();
573 #[stable(feature = "vec_as_slice", since = "1.7.0")]
574 pub fn as_slice(&self) -> &[T
] {
578 /// Extracts a mutable slice of the entire vector.
580 /// Equivalent to `&mut s[..]`.
585 /// use std::io::{self, Read};
586 /// let mut buffer = vec![0; 3];
587 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
590 #[stable(feature = "vec_as_slice", since = "1.7.0")]
591 pub fn as_mut_slice(&mut self) -> &mut [T
] {
595 /// Sets the length of a vector.
597 /// This will explicitly set the size of the vector, without actually
598 /// modifying its buffers, so it is up to the caller to ensure that the
599 /// vector is actually the specified size.
606 /// let mut vec = vec!['r', 'u', 's', 't'];
609 /// ptr::drop_in_place(&mut vec[3]);
612 /// assert_eq!(vec, ['r', 'u', 's']);
615 /// In this example, there is a memory leak since the memory locations
616 /// owned by the inner vectors were not freed prior to the `set_len` call:
619 /// let mut vec = vec![vec![1, 0, 0],
627 /// In this example, the vector gets expanded from zero to four items
628 /// without any memory allocations occurring, resulting in vector
629 /// values of unallocated memory:
632 /// let mut vec: Vec<char> = Vec::new();
639 #[stable(feature = "rust1", since = "1.0.0")]
640 pub unsafe fn set_len(&mut self, len
: usize) {
644 /// Removes an element from anywhere in the vector and return it, replacing
645 /// it with the last element.
647 /// This does not preserve ordering, but is O(1).
651 /// Panics if `index` is out of bounds.
656 /// let mut v = vec!["foo", "bar", "baz", "qux"];
658 /// assert_eq!(v.swap_remove(1), "bar");
659 /// assert_eq!(v, ["foo", "qux", "baz"]);
661 /// assert_eq!(v.swap_remove(0), "foo");
662 /// assert_eq!(v, ["baz", "qux"]);
665 #[stable(feature = "rust1", since = "1.0.0")]
666 pub fn swap_remove(&mut self, index
: usize) -> T
{
667 let length
= self.len();
668 self.swap(index
, length
- 1);
672 /// Inserts an element at position `index` within the vector, shifting all
673 /// elements after it to the right.
677 /// Panics if `index` is greater than the vector's length.
682 /// let mut vec = vec![1, 2, 3];
683 /// vec.insert(1, 4);
684 /// assert_eq!(vec, [1, 4, 2, 3]);
685 /// vec.insert(4, 5);
686 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
688 #[stable(feature = "rust1", since = "1.0.0")]
689 pub fn insert(&mut self, index
: usize, element
: T
) {
690 let len
= self.len();
691 assert
!(index
<= len
);
693 // space for the new element
694 if len
== self.buf
.cap() {
700 // The spot to put the new value
702 let p
= self.as_mut_ptr().offset(index
as isize);
703 // Shift everything over to make space. (Duplicating the
704 // `index`th element into two consecutive places.)
705 ptr
::copy(p
, p
.offset(1), len
- index
);
706 // Write it in, overwriting the first copy of the `index`th
708 ptr
::write(p
, element
);
710 self.set_len(len
+ 1);
714 /// Removes and returns the element at position `index` within the vector,
715 /// shifting all elements after it to the left.
719 /// Panics if `index` is out of bounds.
724 /// let mut v = vec![1, 2, 3];
725 /// assert_eq!(v.remove(1), 2);
726 /// assert_eq!(v, [1, 3]);
728 #[stable(feature = "rust1", since = "1.0.0")]
729 pub fn remove(&mut self, index
: usize) -> T
{
730 let len
= self.len();
731 assert
!(index
< len
);
736 // the place we are taking from.
737 let ptr
= self.as_mut_ptr().offset(index
as isize);
738 // copy it out, unsafely having a copy of the value on
739 // the stack and in the vector at the same time.
740 ret
= ptr
::read(ptr
);
742 // Shift everything down to fill in that spot.
743 ptr
::copy(ptr
.offset(1), ptr
, len
- index
- 1);
745 self.set_len(len
- 1);
750 /// Retains only the elements specified by the predicate.
752 /// In other words, remove all elements `e` such that `f(&e)` returns false.
753 /// This method operates in place and preserves the order of the retained
759 /// let mut vec = vec![1, 2, 3, 4];
760 /// vec.retain(|&x| x%2 == 0);
761 /// assert_eq!(vec, [2, 4]);
763 #[stable(feature = "rust1", since = "1.0.0")]
764 pub fn retain
<F
>(&mut self, mut f
: F
)
765 where F
: FnMut(&T
) -> bool
767 let len
= self.len();
781 self.truncate(len
- del
);
785 /// Appends an element to the back of a collection.
789 /// Panics if the number of elements in the vector overflows a `usize`.
794 /// let mut vec = vec![1, 2];
796 /// assert_eq!(vec, [1, 2, 3]);
799 #[stable(feature = "rust1", since = "1.0.0")]
800 pub fn push(&mut self, value
: T
) {
801 // This will panic or abort if we would allocate > isize::MAX bytes
802 // or if the length increment would overflow for zero-sized types.
803 if self.len
== self.buf
.cap() {
807 let end
= self.as_mut_ptr().offset(self.len
as isize);
808 ptr
::write(end
, value
);
813 /// Removes the last element from a vector and returns it, or `None` if it
819 /// let mut vec = vec![1, 2, 3];
820 /// assert_eq!(vec.pop(), Some(3));
821 /// assert_eq!(vec, [1, 2]);
824 #[stable(feature = "rust1", since = "1.0.0")]
825 pub fn pop(&mut self) -> Option
<T
> {
831 Some(ptr
::read(self.get_unchecked(self.len())))
836 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
840 /// Panics if the number of elements in the vector overflows a `usize`.
845 /// let mut vec = vec![1, 2, 3];
846 /// let mut vec2 = vec![4, 5, 6];
847 /// vec.append(&mut vec2);
848 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
849 /// assert_eq!(vec2, []);
852 #[stable(feature = "append", since = "1.4.0")]
853 pub fn append(&mut self, other
: &mut Self) {
854 self.reserve(other
.len());
855 let len
= self.len();
857 ptr
::copy_nonoverlapping(other
.as_ptr(), self.get_unchecked_mut(len
), other
.len());
860 self.len
+= other
.len();
866 /// Create a draining iterator that removes the specified range in the vector
867 /// and yields the removed items.
869 /// Note 1: The element range is removed even if the iterator is not
870 /// consumed until the end.
872 /// Note 2: It is unspecified how many elements are removed from the vector,
873 /// if the `Drain` value is leaked.
877 /// Panics if the starting point is greater than the end point or if
878 /// the end point is greater than the length of the vector.
883 /// let mut v = vec![1, 2, 3];
884 /// let u: Vec<_> = v.drain(1..).collect();
885 /// assert_eq!(v, &[1]);
886 /// assert_eq!(u, &[2, 3]);
888 /// // A full range clears the vector
890 /// assert_eq!(v, &[]);
892 #[stable(feature = "drain", since = "1.6.0")]
893 pub fn drain
<R
>(&mut self, range
: R
) -> Drain
<T
>
894 where R
: RangeArgument
<usize>
898 // When the Drain is first created, it shortens the length of
899 // the source vector to make sure no uninitalized or moved-from elements
900 // are accessible at all if the Drain's destructor never gets to run.
902 // Drain will ptr::read out the values to remove.
903 // When finished, remaining tail of the vec is copied back to cover
904 // the hole, and the vector length is restored to the new length.
906 let len
= self.len();
907 let start
= *range
.start().unwrap_or(&0);
908 let end
= *range
.end().unwrap_or(&len
);
909 assert
!(start
<= end
);
913 // set self.vec length's to start, to be safe in case Drain is leaked
915 // Use the borrow in the IterMut to indicate borrowing behavior of the
916 // whole Drain iterator (like &mut T).
917 let range_slice
= slice
::from_raw_parts_mut(self.as_mut_ptr().offset(start
as isize),
922 iter
: range_slice
.iter(),
923 vec
: Shared
::new(self as *mut _
),
928 /// Clears the vector, removing all values.
933 /// let mut v = vec![1, 2, 3];
937 /// assert!(v.is_empty());
940 #[stable(feature = "rust1", since = "1.0.0")]
941 pub fn clear(&mut self) {
945 /// Returns the number of elements in the vector.
950 /// let a = vec![1, 2, 3];
951 /// assert_eq!(a.len(), 3);
954 #[stable(feature = "rust1", since = "1.0.0")]
955 pub fn len(&self) -> usize {
959 /// Returns `true` if the vector contains no elements.
964 /// let mut v = Vec::new();
965 /// assert!(v.is_empty());
968 /// assert!(!v.is_empty());
970 #[stable(feature = "rust1", since = "1.0.0")]
971 pub fn is_empty(&self) -> bool
{
975 /// Splits the collection into two at the given index.
977 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
978 /// and the returned `Self` contains elements `[at, len)`.
980 /// Note that the capacity of `self` does not change.
984 /// Panics if `at > len`.
989 /// let mut vec = vec![1,2,3];
990 /// let vec2 = vec.split_off(1);
991 /// assert_eq!(vec, [1]);
992 /// assert_eq!(vec2, [2, 3]);
995 #[stable(feature = "split_off", since = "1.4.0")]
996 pub fn split_off(&mut self, at
: usize) -> Self {
997 assert
!(at
<= self.len(), "`at` out of bounds");
999 let other_len
= self.len
- at
;
1000 let mut other
= Vec
::with_capacity(other_len
);
1002 // Unsafely `set_len` and copy items to `other`.
1005 other
.set_len(other_len
);
1007 ptr
::copy_nonoverlapping(self.as_ptr().offset(at
as isize),
1015 impl<T
: Clone
> Vec
<T
> {
1016 /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
1018 /// If `new_len` is greater than `len()`, the `Vec` is extended by the
1019 /// difference, with each additional slot filled with `value`.
1020 /// If `new_len` is less than `len()`, the `Vec` is simply truncated.
1025 /// let mut vec = vec!["hello"];
1026 /// vec.resize(3, "world");
1027 /// assert_eq!(vec, ["hello", "world", "world"]);
1029 /// let mut vec = vec![1, 2, 3, 4];
1030 /// vec.resize(2, 0);
1031 /// assert_eq!(vec, [1, 2]);
1033 #[stable(feature = "vec_resize", since = "1.5.0")]
1034 pub fn resize(&mut self, new_len
: usize, value
: T
) {
1035 let len
= self.len();
1038 self.extend_with_element(new_len
- len
, value
);
1040 self.truncate(new_len
);
1044 /// Extend the vector by `n` additional clones of `value`.
1045 fn extend_with_element(&mut self, n
: usize, value
: T
) {
1049 let mut ptr
= self.as_mut_ptr().offset(self.len() as isize);
1050 // Use SetLenOnDrop to work around bug where compiler
1051 // may not realize the store through `ptr` trough self.set_len()
1053 let mut local_len
= SetLenOnDrop
::new(&mut self.len
);
1055 // Write all elements except the last one
1057 ptr
::write(ptr
, value
.clone());
1058 ptr
= ptr
.offset(1);
1059 // Increment the length in every step in case clone() panics
1060 local_len
.increment_len(1);
1064 // We can write the last element directly without cloning needlessly
1065 ptr
::write(ptr
, value
);
1066 local_len
.increment_len(1);
1069 // len set by scope guard
1073 /// Clones and appends all elements in a slice to the `Vec`.
1075 /// Iterates over the slice `other`, clones each element, and then appends
1076 /// it to this `Vec`. The `other` vector is traversed in-order.
1078 /// Note that this function is same as `extend` except that it is
1079 /// specialized to work with slices instead. If and when Rust gets
1080 /// specialization this function will likely be deprecated (but still
1086 /// let mut vec = vec![1];
1087 /// vec.extend_from_slice(&[2, 3, 4]);
1088 /// assert_eq!(vec, [1, 2, 3, 4]);
1090 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1091 pub fn extend_from_slice(&mut self, other
: &[T
]) {
1092 self.reserve(other
.len());
1094 // Unsafe code so this can be optimised to a memcpy (or something
1095 // similarly fast) when T is Copy. LLVM is easily confused, so any
1096 // extra operations during the loop can prevent this optimisation.
1098 let len
= self.len();
1099 let ptr
= self.get_unchecked_mut(len
) as *mut T
;
1100 // Use SetLenOnDrop to work around bug where compiler
1101 // may not realize the store through `ptr` trough self.set_len()
1103 let mut local_len
= SetLenOnDrop
::new(&mut self.len
);
1105 for i
in 0..other
.len() {
1106 ptr
::write(ptr
.offset(i
as isize), other
.get_unchecked(i
).clone());
1107 local_len
.increment_len(1);
1110 // len set by scope guard
1115 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1117 // The idea is: The length field in SetLenOnDrop is a local variable
1118 // that the optimizer will see does not alias with any stores through the Vec's data
1119 // pointer. This is a workaround for alias analysis issue #32155
1120 struct SetLenOnDrop
<'a
> {
1125 impl<'a
> SetLenOnDrop
<'a
> {
1127 fn new(len
: &'a
mut usize) -> Self {
1128 SetLenOnDrop { local_len: *len, len: len }
1132 fn increment_len(&mut self, increment
: usize) {
1133 self.local_len
+= increment
;
1137 impl<'a
> Drop
for SetLenOnDrop
<'a
> {
1139 fn drop(&mut self) {
1140 *self.len
= self.local_len
;
1144 impl<T
: PartialEq
> Vec
<T
> {
1145 /// Removes consecutive repeated elements in the vector.
1147 /// If the vector is sorted, this removes all duplicates.
1152 /// let mut vec = vec![1, 2, 2, 3, 2];
1156 /// assert_eq!(vec, [1, 2, 3, 2]);
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 pub fn dedup(&mut self) {
1161 // Although we have a mutable reference to `self`, we cannot make
1162 // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
1163 // must ensure that the vector is in a valid state at all time.
1165 // The way that we handle this is by using swaps; we iterate
1166 // over all the elements, swapping as we go so that at the end
1167 // the elements we wish to keep are in the front, and those we
1168 // wish to reject are at the back. We can then truncate the
1169 // vector. This operation is still O(n).
1171 // Example: We start in this state, where `r` represents "next
1172 // read" and `w` represents "next_write`.
1175 // +---+---+---+---+---+---+
1176 // | 0 | 1 | 1 | 2 | 3 | 3 |
1177 // +---+---+---+---+---+---+
1180 // Comparing self[r] against self[w-1], this is not a duplicate, so
1181 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1182 // r and w, leaving us with:
1185 // +---+---+---+---+---+---+
1186 // | 0 | 1 | 1 | 2 | 3 | 3 |
1187 // +---+---+---+---+---+---+
1190 // Comparing self[r] against self[w-1], this value is a duplicate,
1191 // so we increment `r` but leave everything else unchanged:
1194 // +---+---+---+---+---+---+
1195 // | 0 | 1 | 1 | 2 | 3 | 3 |
1196 // +---+---+---+---+---+---+
1199 // Comparing self[r] against self[w-1], this is not a duplicate,
1200 // so swap self[r] and self[w] and advance r and w:
1203 // +---+---+---+---+---+---+
1204 // | 0 | 1 | 2 | 1 | 3 | 3 |
1205 // +---+---+---+---+---+---+
1208 // Not a duplicate, repeat:
1211 // +---+---+---+---+---+---+
1212 // | 0 | 1 | 2 | 3 | 1 | 3 |
1213 // +---+---+---+---+---+---+
1216 // Duplicate, advance r. End of vec. Truncate to w.
1218 let ln
= self.len();
1223 // Avoid bounds checks by using raw pointers.
1224 let p
= self.as_mut_ptr();
1225 let mut r
: usize = 1;
1226 let mut w
: usize = 1;
1229 let p_r
= p
.offset(r
as isize);
1230 let p_wm1
= p
.offset((w
- 1) as isize);
1233 let p_w
= p_wm1
.offset(1);
1234 mem
::swap(&mut *p_r
, &mut *p_w
);
1246 ////////////////////////////////////////////////////////////////////////////////
1247 // Internal methods and functions
1248 ////////////////////////////////////////////////////////////////////////////////
1251 #[stable(feature = "rust1", since = "1.0.0")]
1252 pub fn from_elem
<T
: Clone
>(elem
: T
, n
: usize) -> Vec
<T
> {
1253 let mut v
= Vec
::with_capacity(n
);
1254 v
.extend_with_element(n
, elem
);
1258 ////////////////////////////////////////////////////////////////////////////////
1259 // Common trait implementations for Vec
1260 ////////////////////////////////////////////////////////////////////////////////
1262 #[stable(feature = "rust1", since = "1.0.0")]
1263 impl<T
: Clone
> Clone
for Vec
<T
> {
1265 fn clone(&self) -> Vec
<T
> {
1266 <[T
]>::to_vec(&**self)
1269 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1270 // required for this method definition, is not available. Instead use the
1271 // `slice::to_vec` function which is only available with cfg(test)
1272 // NB see the slice::hack module in slice.rs for more information
1274 fn clone(&self) -> Vec
<T
> {
1275 ::slice
::to_vec(&**self)
1278 fn clone_from(&mut self, other
: &Vec
<T
>) {
1279 // drop anything in self that will not be overwritten
1280 self.truncate(other
.len());
1281 let len
= self.len();
1283 // reuse the contained values' allocations/resources.
1284 self.clone_from_slice(&other
[..len
]);
1286 // self.len <= other.len due to the truncate above, so the
1287 // slice here is always in-bounds.
1288 self.extend_from_slice(&other
[len
..]);
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 impl<T
: Hash
> Hash
for Vec
<T
> {
1295 fn hash
<H
: hash
::Hasher
>(&self, state
: &mut H
) {
1296 Hash
::hash(&**self, state
)
1300 #[stable(feature = "rust1", since = "1.0.0")]
1301 impl<T
> Index
<usize> for Vec
<T
> {
1305 fn index(&self, index
: usize) -> &T
{
1306 // NB built-in indexing via `&[T]`
1311 #[stable(feature = "rust1", since = "1.0.0")]
1312 impl<T
> IndexMut
<usize> for Vec
<T
> {
1314 fn index_mut(&mut self, index
: usize) -> &mut T
{
1315 // NB built-in indexing via `&mut [T]`
1316 &mut (**self)[index
]
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 impl<T
> ops
::Index
<ops
::Range
<usize>> for Vec
<T
> {
1326 fn index(&self, index
: ops
::Range
<usize>) -> &[T
] {
1327 Index
::index(&**self, index
)
1330 #[stable(feature = "rust1", since = "1.0.0")]
1331 impl<T
> ops
::Index
<ops
::RangeTo
<usize>> for Vec
<T
> {
1335 fn index(&self, index
: ops
::RangeTo
<usize>) -> &[T
] {
1336 Index
::index(&**self, index
)
1339 #[stable(feature = "rust1", since = "1.0.0")]
1340 impl<T
> ops
::Index
<ops
::RangeFrom
<usize>> for Vec
<T
> {
1344 fn index(&self, index
: ops
::RangeFrom
<usize>) -> &[T
] {
1345 Index
::index(&**self, index
)
1348 #[stable(feature = "rust1", since = "1.0.0")]
1349 impl<T
> ops
::Index
<ops
::RangeFull
> for Vec
<T
> {
1353 fn index(&self, _index
: ops
::RangeFull
) -> &[T
] {
1357 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1358 impl<T
> ops
::Index
<ops
::RangeInclusive
<usize>> for Vec
<T
> {
1362 fn index(&self, index
: ops
::RangeInclusive
<usize>) -> &[T
] {
1363 Index
::index(&**self, index
)
1366 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1367 impl<T
> ops
::Index
<ops
::RangeToInclusive
<usize>> for Vec
<T
> {
1371 fn index(&self, index
: ops
::RangeToInclusive
<usize>) -> &[T
] {
1372 Index
::index(&**self, index
)
1376 #[stable(feature = "rust1", since = "1.0.0")]
1377 impl<T
> ops
::IndexMut
<ops
::Range
<usize>> for Vec
<T
> {
1379 fn index_mut(&mut self, index
: ops
::Range
<usize>) -> &mut [T
] {
1380 IndexMut
::index_mut(&mut **self, index
)
1383 #[stable(feature = "rust1", since = "1.0.0")]
1384 impl<T
> ops
::IndexMut
<ops
::RangeTo
<usize>> for Vec
<T
> {
1386 fn index_mut(&mut self, index
: ops
::RangeTo
<usize>) -> &mut [T
] {
1387 IndexMut
::index_mut(&mut **self, index
)
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 impl<T
> ops
::IndexMut
<ops
::RangeFrom
<usize>> for Vec
<T
> {
1393 fn index_mut(&mut self, index
: ops
::RangeFrom
<usize>) -> &mut [T
] {
1394 IndexMut
::index_mut(&mut **self, index
)
1397 #[stable(feature = "rust1", since = "1.0.0")]
1398 impl<T
> ops
::IndexMut
<ops
::RangeFull
> for Vec
<T
> {
1400 fn index_mut(&mut self, _index
: ops
::RangeFull
) -> &mut [T
] {
1404 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1405 impl<T
> ops
::IndexMut
<ops
::RangeInclusive
<usize>> for Vec
<T
> {
1407 fn index_mut(&mut self, index
: ops
::RangeInclusive
<usize>) -> &mut [T
] {
1408 IndexMut
::index_mut(&mut **self, index
)
1411 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1412 impl<T
> ops
::IndexMut
<ops
::RangeToInclusive
<usize>> for Vec
<T
> {
1414 fn index_mut(&mut self, index
: ops
::RangeToInclusive
<usize>) -> &mut [T
] {
1415 IndexMut
::index_mut(&mut **self, index
)
1419 #[stable(feature = "rust1", since = "1.0.0")]
1420 impl<T
> ops
::Deref
for Vec
<T
> {
1423 fn deref(&self) -> &[T
] {
1425 let p
= self.buf
.ptr();
1426 assume(!p
.is_null());
1427 slice
::from_raw_parts(p
, self.len
)
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 impl<T
> ops
::DerefMut
for Vec
<T
> {
1434 fn deref_mut(&mut self) -> &mut [T
] {
1436 let ptr
= self.buf
.ptr();
1437 assume(!ptr
.is_null());
1438 slice
::from_raw_parts_mut(ptr
, self.len
)
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 impl<T
> FromIterator
<T
> for Vec
<T
> {
1446 fn from_iter
<I
: IntoIterator
<Item
= T
>>(iter
: I
) -> Vec
<T
> {
1447 // Unroll the first iteration, as the vector is going to be
1448 // expanded on this iteration in every case when the iterable is not
1449 // empty, but the loop in extend_desugared() is not going to see the
1450 // vector being full in the few subsequent loop iterations.
1451 // So we get better branch prediction.
1452 let mut iterator
= iter
.into_iter();
1453 let mut vector
= match iterator
.next() {
1454 None
=> return Vec
::new(),
1456 let (lower
, _
) = iterator
.size_hint();
1457 let mut vector
= Vec
::with_capacity(lower
.saturating_add(1));
1459 ptr
::write(vector
.get_unchecked_mut(0), element
);
1465 vector
.extend_desugared(iterator
);
1470 #[stable(feature = "rust1", since = "1.0.0")]
1471 impl<T
> IntoIterator
for Vec
<T
> {
1473 type IntoIter
= IntoIter
<T
>;
1475 /// Creates a consuming iterator, that is, one that moves each value out of
1476 /// the vector (from start to end). The vector cannot be used after calling
1482 /// let v = vec!["a".to_string(), "b".to_string()];
1483 /// for s in v.into_iter() {
1484 /// // s has type String, not &String
1485 /// println!("{}", s);
1489 fn into_iter(mut self) -> IntoIter
<T
> {
1491 let begin
= self.as_mut_ptr();
1492 assume(!begin
.is_null());
1493 let end
= if mem
::size_of
::<T
>() == 0 {
1494 arith_offset(begin
as *const i8, self.len() as isize) as *const T
1496 begin
.offset(self.len() as isize) as *const T
1498 let cap
= self.buf
.cap();
1501 buf
: Shared
::new(begin
),
1510 #[stable(feature = "rust1", since = "1.0.0")]
1511 impl<'a
, T
> IntoIterator
for &'a Vec
<T
> {
1513 type IntoIter
= slice
::Iter
<'a
, T
>;
1515 fn into_iter(self) -> slice
::Iter
<'a
, T
> {
1520 #[stable(feature = "rust1", since = "1.0.0")]
1521 impl<'a
, T
> IntoIterator
for &'a
mut Vec
<T
> {
1522 type Item
= &'a
mut T
;
1523 type IntoIter
= slice
::IterMut
<'a
, T
>;
1525 fn into_iter(mut self) -> slice
::IterMut
<'a
, T
> {
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 impl<T
> Extend
<T
> for Vec
<T
> {
1533 fn extend
<I
: IntoIterator
<Item
= T
>>(&mut self, iter
: I
) {
1534 <Self as SpecExtend
<I
>>::spec_extend(self, iter
);
1538 impl<I
: IntoIterator
> SpecExtend
<I
> for Vec
<I
::Item
> {
1539 default fn spec_extend(&mut self, iter
: I
) {
1540 self.extend_desugared(iter
.into_iter())
1544 impl<T
> SpecExtend
<Vec
<T
>> for Vec
<T
> {
1545 fn spec_extend(&mut self, ref mut other
: Vec
<T
>) {
1551 fn extend_desugared
<I
: Iterator
<Item
= T
>>(&mut self, mut iterator
: I
) {
1552 // This function should be the moral equivalent of:
1554 // for item in iterator {
1557 while let Some(element
) = iterator
.next() {
1558 let len
= self.len();
1559 if len
== self.capacity() {
1560 let (lower
, _
) = iterator
.size_hint();
1561 self.reserve(lower
.saturating_add(1));
1564 ptr
::write(self.get_unchecked_mut(len
), element
);
1565 // NB can't overflow since we would have had to alloc the address space
1566 self.set_len(len
+ 1);
1572 #[stable(feature = "extend_ref", since = "1.2.0")]
1573 impl<'a
, T
: 'a
+ Copy
> Extend
<&'a T
> for Vec
<T
> {
1574 fn extend
<I
: IntoIterator
<Item
= &'a T
>>(&mut self, iter
: I
) {
1575 self.extend(iter
.into_iter().cloned());
1579 macro_rules
! __impl_slice_eq1
{
1580 ($Lhs
: ty
, $Rhs
: ty
) => {
1581 __impl_slice_eq1
! { $Lhs, $Rhs, Sized }
1583 ($Lhs
: ty
, $Rhs
: ty
, $Bound
: ident
) => {
1584 #[stable(feature = "rust1", since = "1.0.0")]
1585 impl<'a
, 'b
, A
: $Bound
, B
> PartialEq
<$Rhs
> for $Lhs
where A
: PartialEq
<B
> {
1587 fn eq(&self, other
: &$Rhs
) -> bool { self[..] == other[..] }
1589 fn ne(&self, other
: &$Rhs
) -> bool { self[..] != other[..] }
1594 __impl_slice_eq1
! { Vec<A>, Vec<B> }
1595 __impl_slice_eq1
! { Vec<A>, &'b [B] }
1596 __impl_slice_eq1
! { Vec<A>, &'b mut [B] }
1597 __impl_slice_eq1
! { Cow<'a, [A]>, &'b [B], Clone }
1598 __impl_slice_eq1
! { Cow<'a, [A]>, &'b mut [B], Clone }
1599 __impl_slice_eq1
! { Cow<'a, [A]>, Vec<B>, Clone }
1601 macro_rules
! array_impls
{
1604 // NOTE: some less important impls are omitted to reduce code bloat
1605 __impl_slice_eq1
! { Vec<A>, [B; $N] }
1606 __impl_slice_eq1
! { Vec<A>, &'b [B; $N] }
1607 // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
1608 // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
1609 // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
1610 // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
1617 10 11 12 13 14 15 16 17 18 19
1618 20 21 22 23 24 25 26 27 28 29
1622 #[stable(feature = "rust1", since = "1.0.0")]
1623 impl<T
: PartialOrd
> PartialOrd
for Vec
<T
> {
1625 fn partial_cmp(&self, other
: &Vec
<T
>) -> Option
<Ordering
> {
1626 PartialOrd
::partial_cmp(&**self, &**other
)
1630 #[stable(feature = "rust1", since = "1.0.0")]
1631 impl<T
: Eq
> Eq
for Vec
<T
> {}
1633 #[stable(feature = "rust1", since = "1.0.0")]
1634 impl<T
: Ord
> Ord
for Vec
<T
> {
1636 fn cmp(&self, other
: &Vec
<T
>) -> Ordering
{
1637 Ord
::cmp(&**self, &**other
)
1641 #[stable(feature = "rust1", since = "1.0.0")]
1642 impl<T
> Drop
for Vec
<T
> {
1643 #[unsafe_destructor_blind_to_params]
1644 fn drop(&mut self) {
1647 ptr
::drop_in_place(&mut self[..]);
1649 // RawVec handles deallocation
1653 #[stable(feature = "rust1", since = "1.0.0")]
1654 impl<T
> Default
for Vec
<T
> {
1655 /// Creates an empty `Vec<T>`.
1656 fn default() -> Vec
<T
> {
1661 #[stable(feature = "rust1", since = "1.0.0")]
1662 impl<T
: fmt
::Debug
> fmt
::Debug
for Vec
<T
> {
1663 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1664 fmt
::Debug
::fmt(&**self, f
)
1668 #[stable(feature = "rust1", since = "1.0.0")]
1669 impl<T
> AsRef
<Vec
<T
>> for Vec
<T
> {
1670 fn as_ref(&self) -> &Vec
<T
> {
1675 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1676 impl<T
> AsMut
<Vec
<T
>> for Vec
<T
> {
1677 fn as_mut(&mut self) -> &mut Vec
<T
> {
1682 #[stable(feature = "rust1", since = "1.0.0")]
1683 impl<T
> AsRef
<[T
]> for Vec
<T
> {
1684 fn as_ref(&self) -> &[T
] {
1689 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1690 impl<T
> AsMut
<[T
]> for Vec
<T
> {
1691 fn as_mut(&mut self) -> &mut [T
] {
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 impl<'a
, T
: Clone
> From
<&'a
[T
]> for Vec
<T
> {
1699 fn from(s
: &'a
[T
]) -> Vec
<T
> {
1703 fn from(s
: &'a
[T
]) -> Vec
<T
> {
1708 #[stable(feature = "rust1", since = "1.0.0")]
1709 impl<'a
> From
<&'a
str> for Vec
<u8> {
1710 fn from(s
: &'a
str) -> Vec
<u8> {
1711 From
::from(s
.as_bytes())
1715 ////////////////////////////////////////////////////////////////////////////////
1717 ////////////////////////////////////////////////////////////////////////////////
1719 #[stable(feature = "cow_from_vec", since = "1.7.0")]
1720 impl<'a
, T
: Clone
> From
<&'a
[T
]> for Cow
<'a
, [T
]> {
1721 fn from(s
: &'a
[T
]) -> Cow
<'a
, [T
]> {
1726 #[stable(feature = "cow_from_vec", since = "1.7.0")]
1727 impl<'a
, T
: Clone
> From
<Vec
<T
>> for Cow
<'a
, [T
]> {
1728 fn from(v
: Vec
<T
>) -> Cow
<'a
, [T
]> {
1733 #[stable(feature = "rust1", since = "1.0.0")]
1734 impl<'a
, T
> FromIterator
<T
> for Cow
<'a
, [T
]> where T
: Clone
{
1735 fn from_iter
<I
: IntoIterator
<Item
= T
>>(it
: I
) -> Cow
<'a
, [T
]> {
1736 Cow
::Owned(FromIterator
::from_iter(it
))
1740 ////////////////////////////////////////////////////////////////////////////////
1742 ////////////////////////////////////////////////////////////////////////////////
1744 /// An iterator that moves out of a vector.
1746 /// This `struct` is created by the `into_iter` method on [`Vec`][`Vec`] (provided
1747 /// by the [`IntoIterator`] trait).
1749 /// [`Vec`]: struct.Vec.html
1750 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
1751 #[stable(feature = "rust1", since = "1.0.0")]
1752 pub struct IntoIter
<T
> {
1759 #[stable(feature = "vec_intoiter_debug", since = "")]
1760 impl<T
: fmt
::Debug
> fmt
::Debug
for IntoIter
<T
> {
1761 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1762 f
.debug_tuple("IntoIter")
1763 .field(&self.as_slice())
1768 impl<T
> IntoIter
<T
> {
1769 /// Returns the remaining items of this iterator as a slice.
1774 /// # #![feature(vec_into_iter_as_slice)]
1775 /// let vec = vec!['a', 'b', 'c'];
1776 /// let mut into_iter = vec.into_iter();
1777 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
1778 /// let _ = into_iter.next().unwrap();
1779 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
1781 #[unstable(feature = "vec_into_iter_as_slice", issue = "35601")]
1782 pub fn as_slice(&self) -> &[T
] {
1784 slice
::from_raw_parts(self.ptr
, self.len())
1788 /// Returns the remaining items of this iterator as a mutable slice.
1793 /// # #![feature(vec_into_iter_as_slice)]
1794 /// let vec = vec!['a', 'b', 'c'];
1795 /// let mut into_iter = vec.into_iter();
1796 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
1797 /// into_iter.as_mut_slice()[2] = 'z';
1798 /// assert_eq!(into_iter.next().unwrap(), 'a');
1799 /// assert_eq!(into_iter.next().unwrap(), 'b');
1800 /// assert_eq!(into_iter.next().unwrap(), 'z');
1802 #[unstable(feature = "vec_into_iter_as_slice", issue = "35601")]
1803 pub fn as_mut_slice(&self) -> &mut [T
] {
1805 slice
::from_raw_parts_mut(self.ptr
as *mut T
, self.len())
1810 #[stable(feature = "rust1", since = "1.0.0")]
1811 unsafe impl<T
: Send
> Send
for IntoIter
<T
> {}
1812 #[stable(feature = "rust1", since = "1.0.0")]
1813 unsafe impl<T
: Sync
> Sync
for IntoIter
<T
> {}
1815 #[stable(feature = "rust1", since = "1.0.0")]
1816 impl<T
> Iterator
for IntoIter
<T
> {
1820 fn next(&mut self) -> Option
<T
> {
1822 if self.ptr
as *const _
== self.end
{
1825 if mem
::size_of
::<T
>() == 0 {
1826 // purposefully don't use 'ptr.offset' because for
1827 // vectors with 0-size elements this would return the
1829 self.ptr
= arith_offset(self.ptr
as *const i8, 1) as *mut T
;
1831 // Use a non-null pointer value
1832 Some(ptr
::read(EMPTY
as *mut T
))
1835 self.ptr
= self.ptr
.offset(1);
1837 Some(ptr
::read(old
))
1844 fn size_hint(&self) -> (usize, Option
<usize>) {
1845 let diff
= (self.end
as usize) - (self.ptr
as usize);
1846 let size
= mem
::size_of
::<T
>();
1853 (exact
, Some(exact
))
1857 fn count(self) -> usize {
1862 #[stable(feature = "rust1", since = "1.0.0")]
1863 impl<T
> DoubleEndedIterator
for IntoIter
<T
> {
1865 fn next_back(&mut self) -> Option
<T
> {
1867 if self.end
== self.ptr
{
1870 if mem
::size_of
::<T
>() == 0 {
1871 // See above for why 'ptr.offset' isn't used
1872 self.end
= arith_offset(self.end
as *const i8, -1) as *mut T
;
1874 // Use a non-null pointer value
1875 Some(ptr
::read(EMPTY
as *mut T
))
1877 self.end
= self.end
.offset(-1);
1879 Some(ptr
::read(self.end
))
1886 #[stable(feature = "rust1", since = "1.0.0")]
1887 impl<T
> ExactSizeIterator
for IntoIter
<T
> {}
1889 #[unstable(feature = "fused", issue = "35602")]
1890 impl<T
> FusedIterator
for IntoIter
<T
> {}
1892 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
1893 impl<T
: Clone
> Clone
for IntoIter
<T
> {
1894 fn clone(&self) -> IntoIter
<T
> {
1895 self.as_slice().to_owned().into_iter()
1899 #[stable(feature = "rust1", since = "1.0.0")]
1900 impl<T
> Drop
for IntoIter
<T
> {
1901 #[unsafe_destructor_blind_to_params]
1902 fn drop(&mut self) {
1903 // destroy the remaining elements
1904 for _x
in self.by_ref() {}
1906 // RawVec handles deallocation
1907 let _
= unsafe { RawVec::from_raw_parts(*self.buf, self.cap) }
;
1911 /// A draining iterator for `Vec<T>`.
1913 /// This `struct` is created by the [`drain`] method on [`Vec`].
1915 /// [`drain`]: struct.Vec.html#method.drain
1916 /// [`Vec`]: struct.Vec.html
1917 #[stable(feature = "drain", since = "1.6.0")]
1918 pub struct Drain
<'a
, T
: 'a
> {
1919 /// Index of tail to preserve
1923 /// Current remaining range to remove
1924 iter
: slice
::Iter
<'a
, T
>,
1925 vec
: Shared
<Vec
<T
>>,
1928 #[stable(feature = "drain", since = "1.6.0")]
1929 unsafe impl<'a
, T
: Sync
> Sync
for Drain
<'a
, T
> {}
1930 #[stable(feature = "drain", since = "1.6.0")]
1931 unsafe impl<'a
, T
: Send
> Send
for Drain
<'a
, T
> {}
1933 #[stable(feature = "rust1", since = "1.0.0")]
1934 impl<'a
, T
> Iterator
for Drain
<'a
, T
> {
1938 fn next(&mut self) -> Option
<T
> {
1939 self.iter
.next().map(|elt
| unsafe { ptr::read(elt as *const _) }
)
1942 fn size_hint(&self) -> (usize, Option
<usize>) {
1943 self.iter
.size_hint()
1947 #[stable(feature = "rust1", since = "1.0.0")]
1948 impl<'a
, T
> DoubleEndedIterator
for Drain
<'a
, T
> {
1950 fn next_back(&mut self) -> Option
<T
> {
1951 self.iter
.next_back().map(|elt
| unsafe { ptr::read(elt as *const _) }
)
1955 #[stable(feature = "rust1", since = "1.0.0")]
1956 impl<'a
, T
> Drop
for Drain
<'a
, T
> {
1957 fn drop(&mut self) {
1958 // exhaust self first
1959 while let Some(_
) = self.next() {}
1961 if self.tail_len
> 0 {
1963 let source_vec
= &mut **self.vec
;
1964 // memmove back untouched tail, update to new length
1965 let start
= source_vec
.len();
1966 let tail
= self.tail_start
;
1967 let src
= source_vec
.as_ptr().offset(tail
as isize);
1968 let dst
= source_vec
.as_mut_ptr().offset(start
as isize);
1969 ptr
::copy(src
, dst
, self.tail_len
);
1970 source_vec
.set_len(start
+ self.tail_len
);
1977 #[stable(feature = "rust1", since = "1.0.0")]
1978 impl<'a
, T
> ExactSizeIterator
for Drain
<'a
, T
> {}
1980 #[unstable(feature = "fused", issue = "35602")]
1981 impl<'a
, T
> FusedIterator
for Drain
<'a
, T
> {}