]> git.lizzy.rs Git - rust.git/blob - src/libcollections/vec.rs
Rollup merge of #34911 - frewsxcv:vec-set-len, r=steveklabnik
[rust.git] / src / libcollections / vec.rs
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.
4 //
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.
10
11 //! A contiguous growable array type with heap-allocated contents, written
12 //! `Vec<T>` but pronounced 'vector.'
13 //!
14 //! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and
15 //! `O(1)` pop (from the end).
16 //!
17 //! # Examples
18 //!
19 //! You can explicitly create a `Vec<T>` with `new()`:
20 //!
21 //! ```
22 //! let v: Vec<i32> = Vec::new();
23 //! ```
24 //!
25 //! ...or by using the `vec!` macro:
26 //!
27 //! ```
28 //! let v: Vec<i32> = vec![];
29 //!
30 //! let v = vec![1, 2, 3, 4, 5];
31 //!
32 //! let v = vec![0; 10]; // ten zeroes
33 //! ```
34 //!
35 //! You can `push` values onto the end of a vector (which will grow the vector
36 //! as needed):
37 //!
38 //! ```
39 //! let mut v = vec![1, 2];
40 //!
41 //! v.push(3);
42 //! ```
43 //!
44 //! Popping values works in much the same way:
45 //!
46 //! ```
47 //! let mut v = vec![1, 2];
48 //!
49 //! let two = v.pop();
50 //! ```
51 //!
52 //! Vectors also support indexing (through the `Index` and `IndexMut` traits):
53 //!
54 //! ```
55 //! let mut v = vec![1, 2, 3];
56 //! let three = v[2];
57 //! v[1] = v[1] + 5;
58 //! ```
59
60 #![stable(feature = "rust1", since = "1.0.0")]
61
62 use alloc::boxed::Box;
63 use alloc::heap::EMPTY;
64 use alloc::raw_vec::RawVec;
65 use borrow::ToOwned;
66 use borrow::Cow;
67 use core::cmp::Ordering;
68 use core::fmt;
69 use core::hash::{self, Hash};
70 use core::intrinsics::{arith_offset, assume};
71 use core::iter::FromIterator;
72 use core::mem;
73 use core::ops::{Index, IndexMut};
74 use core::ops;
75 use core::ptr;
76 use core::slice;
77
78 use super::SpecExtend;
79 use super::range::RangeArgument;
80
81 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector.'
82 ///
83 /// # Examples
84 ///
85 /// ```
86 /// let mut vec = Vec::new();
87 /// vec.push(1);
88 /// vec.push(2);
89 ///
90 /// assert_eq!(vec.len(), 2);
91 /// assert_eq!(vec[0], 1);
92 ///
93 /// assert_eq!(vec.pop(), Some(2));
94 /// assert_eq!(vec.len(), 1);
95 ///
96 /// vec[0] = 7;
97 /// assert_eq!(vec[0], 7);
98 ///
99 /// vec.extend([1, 2, 3].iter().cloned());
100 ///
101 /// for x in &vec {
102 ///     println!("{}", x);
103 /// }
104 /// assert_eq!(vec, [7, 1, 2, 3]);
105 /// ```
106 ///
107 /// The `vec!` macro is provided to make initialization more convenient:
108 ///
109 /// ```
110 /// let mut vec = vec![1, 2, 3];
111 /// vec.push(4);
112 /// assert_eq!(vec, [1, 2, 3, 4]);
113 /// ```
114 ///
115 /// It can also initialize each element of a `Vec<T>` with a given value:
116 ///
117 /// ```
118 /// let vec = vec![0; 5];
119 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
120 /// ```
121 ///
122 /// Use a `Vec<T>` as an efficient stack:
123 ///
124 /// ```
125 /// let mut stack = Vec::new();
126 ///
127 /// stack.push(1);
128 /// stack.push(2);
129 /// stack.push(3);
130 ///
131 /// while let Some(top) = stack.pop() {
132 ///     // Prints 3, 2, 1
133 ///     println!("{}", top);
134 /// }
135 /// ```
136 ///
137 /// # Indexing
138 ///
139 /// The Vec type allows to access values by index, because it implements the
140 /// `Index` trait. An example will be more explicit:
141 ///
142 /// ```
143 /// let v = vec!(0, 2, 4, 6);
144 /// println!("{}", v[1]); // it will display '2'
145 /// ```
146 ///
147 /// However be careful: if you try to access an index which isn't in the Vec,
148 /// your software will panic! You cannot do this:
149 ///
150 /// ```ignore
151 /// let v = vec!(0, 2, 4, 6);
152 /// println!("{}", v[6]); // it will panic!
153 /// ```
154 ///
155 /// In conclusion: always check if the index you want to get really exists
156 /// before doing it.
157 ///
158 /// # Slicing
159 ///
160 /// A Vec can be mutable. Slices, on the other hand, are read-only objects.
161 /// To get a slice, use "&". Example:
162 ///
163 /// ```
164 /// fn read_slice(slice: &[usize]) {
165 ///     // ...
166 /// }
167 ///
168 /// let v = vec!(0, 1);
169 /// read_slice(&v);
170 ///
171 /// // ... and that's all!
172 /// // you can also do it like this:
173 /// let x : &[usize] = &v;
174 /// ```
175 ///
176 /// In Rust, it's more common to pass slices as arguments rather than vectors
177 /// when you just want to provide a read access. The same goes for String and
178 /// &str.
179 ///
180 /// # Capacity and reallocation
181 ///
182 /// The capacity of a vector is the amount of space allocated for any future
183 /// elements that will be added onto the vector. This is not to be confused with
184 /// the *length* of a vector, which specifies the number of actual elements
185 /// within the vector. If a vector's length exceeds its capacity, its capacity
186 /// will automatically be increased, but its elements will have to be
187 /// reallocated.
188 ///
189 /// For example, a vector with capacity 10 and length 0 would be an empty vector
190 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
191 /// vector will not change its capacity or cause reallocation to occur. However,
192 /// if the vector's length is increased to 11, it will have to reallocate, which
193 /// can be slow. For this reason, it is recommended to use `Vec::with_capacity`
194 /// whenever possible to specify how big the vector is expected to get.
195 ///
196 /// # Guarantees
197 ///
198 /// Due to its incredibly fundamental nature, Vec makes a lot of guarantees
199 /// about its design. This ensures that it's as low-overhead as possible in
200 /// the general case, and can be correctly manipulated in primitive ways
201 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
202 /// If additional type parameters are added (e.g. to support custom allocators),
203 /// overriding their defaults may change the behavior.
204 ///
205 /// Most fundamentally, Vec is and always will be a (pointer, capacity, length)
206 /// triplet. No more, no less. The order of these fields is completely
207 /// unspecified, and you should use the appropriate methods to modify these.
208 /// The pointer will never be null, so this type is null-pointer-optimized.
209 ///
210 /// However, the pointer may not actually point to allocated memory. In particular,
211 /// if you construct a Vec with capacity 0 via `Vec::new()`, `vec![]`,
212 /// `Vec::with_capacity(0)`, or by calling `shrink_to_fit()` on an empty Vec, it
213 /// will not allocate memory. Similarly, if you store zero-sized types inside
214 /// a Vec, it will not allocate space for them. *Note that in this case the
215 /// Vec may not report a `capacity()` of 0*. Vec will allocate if and only
216 /// if `mem::size_of::<T>() * capacity() > 0`. In general, Vec's allocation
217 /// details are subtle enough that it is strongly recommended that you only
218 /// free memory allocated by a Vec by creating a new Vec and dropping it.
219 ///
220 /// If a Vec *has* allocated memory, then the memory it points to is on the heap
221 /// (as defined by the allocator Rust is configured to use by default), and its
222 /// pointer points to `len()` initialized elements in order (what you would see
223 /// if you coerced it to a slice), followed by `capacity() - len()` logically
224 /// uninitialized elements.
225 ///
226 /// Vec will never perform a "small optimization" where elements are actually
227 /// stored on the stack for two reasons:
228 ///
229 /// * It would make it more difficult for unsafe code to correctly manipulate
230 ///   a Vec. The contents of a Vec wouldn't have a stable address if it were
231 ///   only moved, and it would be more difficult to determine if a Vec had
232 ///   actually allocated memory.
233 ///
234 /// * It would penalize the general case, incurring an additional branch
235 ///   on every access.
236 ///
237 /// Vec will never automatically shrink itself, even if completely empty. This
238 /// ensures no unnecessary allocations or deallocations occur. Emptying a Vec
239 /// and then filling it back up to the same `len()` should incur no calls to
240 /// the allocator. If you wish to free up unused memory, use `shrink_to_fit`.
241 ///
242 /// `push` and `insert` will never (re)allocate if the reported capacity is
243 /// sufficient. `push` and `insert` *will* (re)allocate if `len() == capacity()`.
244 /// That is, the reported capacity is completely accurate, and can be relied on.
245 /// It can even be used to manually free the memory allocated by a Vec if
246 /// desired. Bulk insertion methods *may* reallocate, even when not necessary.
247 ///
248 /// Vec does not guarantee any particular growth strategy when reallocating
249 /// when full, nor when `reserve` is called. The current strategy is basic
250 /// and it may prove desirable to use a non-constant growth factor. Whatever
251 /// strategy is used will of course guarantee `O(1)` amortized `push`.
252 ///
253 /// `vec![x; n]`, `vec![a, b, c, d]`, and `Vec::with_capacity(n)`, will all
254 /// produce a Vec with exactly the requested capacity. If `len() == capacity()`,
255 /// (as is the case for the `vec!` macro), then a `Vec<T>` can be converted
256 /// to and from a `Box<[T]>` without reallocating or moving the elements.
257 ///
258 /// Vec will not specifically overwrite any data that is removed from it,
259 /// but also won't specifically preserve it. Its uninitialized memory is
260 /// scratch space that it may use however it wants. It will generally just do
261 /// whatever is most efficient or otherwise easy to implement. Do not rely on
262 /// removed data to be erased for security purposes. Even if you drop a Vec, its
263 /// buffer may simply be reused by another Vec. Even if you zero a Vec's memory
264 /// first, that may not actually happen because the optimizer does not consider
265 /// this a side-effect that must be preserved.
266 ///
267 /// Vec does not currently guarantee the order in which elements are dropped
268 /// (the order has changed in the past, and may change again).
269 ///
270 #[unsafe_no_drop_flag]
271 #[stable(feature = "rust1", since = "1.0.0")]
272 pub struct Vec<T> {
273     buf: RawVec<T>,
274     len: usize,
275 }
276
277 ////////////////////////////////////////////////////////////////////////////////
278 // Inherent methods
279 ////////////////////////////////////////////////////////////////////////////////
280
281 impl<T> Vec<T> {
282     /// Constructs a new, empty `Vec<T>`.
283     ///
284     /// The vector will not allocate until elements are pushed onto it.
285     ///
286     /// # Examples
287     ///
288     /// ```
289     /// # #![allow(unused_mut)]
290     /// let mut vec: Vec<i32> = Vec::new();
291     /// ```
292     #[inline]
293     #[stable(feature = "rust1", since = "1.0.0")]
294     pub fn new() -> Vec<T> {
295         Vec {
296             buf: RawVec::new(),
297             len: 0,
298         }
299     }
300
301     /// Constructs a new, empty `Vec<T>` with the specified capacity.
302     ///
303     /// The vector will be able to hold exactly `capacity` elements without
304     /// reallocating. If `capacity` is 0, the vector will not allocate.
305     ///
306     /// It is important to note that this function does not specify the *length*
307     /// of the returned vector, but only the *capacity*. (For an explanation of
308     /// the difference between length and capacity, see the main `Vec<T>` docs
309     /// above, 'Capacity and reallocation'.)
310     ///
311     /// # Examples
312     ///
313     /// ```
314     /// let mut vec = Vec::with_capacity(10);
315     ///
316     /// // The vector contains no items, even though it has capacity for more
317     /// assert_eq!(vec.len(), 0);
318     ///
319     /// // These are all done without reallocating...
320     /// for i in 0..10 {
321     ///     vec.push(i);
322     /// }
323     ///
324     /// // ...but this may make the vector reallocate
325     /// vec.push(11);
326     /// ```
327     #[inline]
328     #[stable(feature = "rust1", since = "1.0.0")]
329     pub fn with_capacity(capacity: usize) -> Vec<T> {
330         Vec {
331             buf: RawVec::with_capacity(capacity),
332             len: 0,
333         }
334     }
335
336     /// Creates a `Vec<T>` directly from the raw components of another vector.
337     ///
338     /// # Safety
339     ///
340     /// This is highly unsafe, due to the number of invariants that aren't
341     /// checked:
342     ///
343     /// * `ptr` needs to have been previously allocated via `String`/`Vec<T>`
344     ///   (at least, it's highly likely to be incorrect if it wasn't).
345     /// * `length` needs to be less than or equal to `capacity`.
346     /// * `capacity` needs to be the capacity that the pointer was allocated with.
347     ///
348     /// Violating these may cause problems like corrupting the allocator's
349     /// internal datastructures.
350     ///
351     /// The ownership of `ptr` is effectively transferred to the
352     /// `Vec<T>` which may then deallocate, reallocate or change the
353     /// contents of memory pointed to by the pointer at will. Ensure
354     /// that nothing else uses the pointer after calling this
355     /// function.
356     ///
357     /// # Examples
358     ///
359     /// ```
360     /// use std::ptr;
361     /// use std::mem;
362     ///
363     /// fn main() {
364     ///     let mut v = vec![1, 2, 3];
365     ///
366     ///     // Pull out the various important pieces of information about `v`
367     ///     let p = v.as_mut_ptr();
368     ///     let len = v.len();
369     ///     let cap = v.capacity();
370     ///
371     ///     unsafe {
372     ///         // Cast `v` into the void: no destructor run, so we are in
373     ///         // complete control of the allocation to which `p` points.
374     ///         mem::forget(v);
375     ///
376     ///         // Overwrite memory with 4, 5, 6
377     ///         for i in 0..len as isize {
378     ///             ptr::write(p.offset(i), 4 + i);
379     ///         }
380     ///
381     ///         // Put everything back together into a Vec
382     ///         let rebuilt = Vec::from_raw_parts(p, len, cap);
383     ///         assert_eq!(rebuilt, [4, 5, 6]);
384     ///     }
385     /// }
386     /// ```
387     #[stable(feature = "rust1", since = "1.0.0")]
388     pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
389         Vec {
390             buf: RawVec::from_raw_parts(ptr, capacity),
391             len: length,
392         }
393     }
394
395     /// Returns the number of elements the vector can hold without
396     /// reallocating.
397     ///
398     /// # Examples
399     ///
400     /// ```
401     /// let vec: Vec<i32> = Vec::with_capacity(10);
402     /// assert_eq!(vec.capacity(), 10);
403     /// ```
404     #[inline]
405     #[stable(feature = "rust1", since = "1.0.0")]
406     pub fn capacity(&self) -> usize {
407         self.buf.cap()
408     }
409
410     /// Reserves capacity for at least `additional` more elements to be inserted
411     /// in the given `Vec<T>`. The collection may reserve more space to avoid
412     /// frequent reallocations.
413     ///
414     /// # Panics
415     ///
416     /// Panics if the new capacity overflows `usize`.
417     ///
418     /// # Examples
419     ///
420     /// ```
421     /// let mut vec = vec![1];
422     /// vec.reserve(10);
423     /// assert!(vec.capacity() >= 11);
424     /// ```
425     #[stable(feature = "rust1", since = "1.0.0")]
426     pub fn reserve(&mut self, additional: usize) {
427         self.buf.reserve(self.len, additional);
428     }
429
430     /// Reserves the minimum capacity for exactly `additional` more elements to
431     /// be inserted in the given `Vec<T>`. Does nothing if the capacity is already
432     /// sufficient.
433     ///
434     /// Note that the allocator may give the collection more space than it
435     /// requests. Therefore capacity can not be relied upon to be precisely
436     /// minimal. Prefer `reserve` if future insertions are expected.
437     ///
438     /// # Panics
439     ///
440     /// Panics if the new capacity overflows `usize`.
441     ///
442     /// # Examples
443     ///
444     /// ```
445     /// let mut vec = vec![1];
446     /// vec.reserve_exact(10);
447     /// assert!(vec.capacity() >= 11);
448     /// ```
449     #[stable(feature = "rust1", since = "1.0.0")]
450     pub fn reserve_exact(&mut self, additional: usize) {
451         self.buf.reserve_exact(self.len, additional);
452     }
453
454     /// Shrinks the capacity of the vector as much as possible.
455     ///
456     /// It will drop down as close as possible to the length but the allocator
457     /// may still inform the vector that there is space for a few more elements.
458     ///
459     /// # Examples
460     ///
461     /// ```
462     /// let mut vec = Vec::with_capacity(10);
463     /// vec.extend([1, 2, 3].iter().cloned());
464     /// assert_eq!(vec.capacity(), 10);
465     /// vec.shrink_to_fit();
466     /// assert!(vec.capacity() >= 3);
467     /// ```
468     #[stable(feature = "rust1", since = "1.0.0")]
469     pub fn shrink_to_fit(&mut self) {
470         self.buf.shrink_to_fit(self.len);
471     }
472
473     /// Converts the vector into Box<[T]>.
474     ///
475     /// Note that this will drop any excess capacity. Calling this and
476     /// converting back to a vector with `into_vec()` is equivalent to calling
477     /// `shrink_to_fit()`.
478     #[stable(feature = "rust1", since = "1.0.0")]
479     pub fn into_boxed_slice(mut self) -> Box<[T]> {
480         unsafe {
481             self.shrink_to_fit();
482             let buf = ptr::read(&self.buf);
483             mem::forget(self);
484             buf.into_box()
485         }
486     }
487
488     /// Shortens the vector, keeping the first `len` elements and dropping
489     /// the rest.
490     ///
491     /// If `len` is greater than the vector's current length, this has no
492     /// effect.
493     ///
494     /// The [`drain`] method can emulate `truncate`, but causes the excess
495     /// elements to be returned instead of dropped.
496     ///
497     /// # Examples
498     ///
499     /// Truncating a five element vector to two elements:
500     ///
501     /// ```
502     /// let mut vec = vec![1, 2, 3, 4, 5];
503     /// vec.truncate(2);
504     /// assert_eq!(vec, [1, 2]);
505     /// ```
506     ///
507     /// No truncation occurs when `len` is greater than the vector's current
508     /// length:
509     ///
510     /// ```
511     /// let mut vec = vec![1, 2, 3];
512     /// vec.truncate(8);
513     /// assert_eq!(vec, [1, 2, 3]);
514     /// ```
515     ///
516     /// Truncating when `len == 0` is equivalent to calling the [`clear`]
517     /// method.
518     ///
519     /// ```
520     /// let mut vec = vec![1, 2, 3];
521     /// vec.truncate(0);
522     /// assert_eq!(vec, []);
523     /// ```
524     ///
525     /// [`clear`]: #method.clear
526     /// [`drain`]: #method.drain
527     #[stable(feature = "rust1", since = "1.0.0")]
528     pub fn truncate(&mut self, len: usize) {
529         unsafe {
530             // drop any extra elements
531             while len < self.len {
532                 // decrement len before the drop_in_place(), so a panic on Drop
533                 // doesn't re-drop the just-failed value.
534                 self.len -= 1;
535                 let len = self.len;
536                 ptr::drop_in_place(self.get_unchecked_mut(len));
537             }
538         }
539     }
540
541     /// Extracts a slice containing the entire vector.
542     ///
543     /// Equivalent to `&s[..]`.
544     #[inline]
545     #[stable(feature = "vec_as_slice", since = "1.7.0")]
546     pub fn as_slice(&self) -> &[T] {
547         self
548     }
549
550     /// Extracts a mutable slice of the entire vector.
551     ///
552     /// Equivalent to `&mut s[..]`.
553     #[inline]
554     #[stable(feature = "vec_as_slice", since = "1.7.0")]
555     pub fn as_mut_slice(&mut self) -> &mut [T] {
556         self
557     }
558
559     /// Sets the length of a vector.
560     ///
561     /// This will explicitly set the size of the vector, without actually
562     /// modifying its buffers, so it is up to the caller to ensure that the
563     /// vector is actually the specified size.
564     ///
565     /// # Examples
566     ///
567     /// ```
568     /// use std::ptr;
569     ///
570     /// let mut vec = vec!['r', 'u', 's', 't'];
571     ///
572     /// unsafe {
573     ///     ptr::drop_in_place(&mut vec[3]);
574     ///     vec.set_len(3);
575     /// }
576     /// assert_eq!(vec, ['r', 'u', 's']);
577     /// ```
578     ///
579     /// In this example, there is a memory leak since the memory locations
580     /// owned by the vector were not freed prior to the `set_len` call:
581     ///
582     /// ```
583     /// let mut vec = vec!['r', 'u', 's', 't'];
584     ///
585     /// unsafe {
586     ///     vec.set_len(0);
587     /// }
588     /// ```
589     ///
590     /// In this example, the vector gets expanded from zero to four items
591     /// without any memory allocations occurring, resulting in vector
592     /// values of unallocated memory:
593     ///
594     /// ```
595     /// let mut vec: Vec<char> = Vec::new();
596     ///
597     /// unsafe {
598     ///     vec.set_len(4);
599     /// }
600     /// ```
601     #[inline]
602     #[stable(feature = "rust1", since = "1.0.0")]
603     pub unsafe fn set_len(&mut self, len: usize) {
604         self.len = len;
605     }
606
607     /// Removes an element from anywhere in the vector and return it, replacing
608     /// it with the last element.
609     ///
610     /// This does not preserve ordering, but is O(1).
611     ///
612     /// # Panics
613     ///
614     /// Panics if `index` is out of bounds.
615     ///
616     /// # Examples
617     ///
618     /// ```
619     /// let mut v = vec!["foo", "bar", "baz", "qux"];
620     ///
621     /// assert_eq!(v.swap_remove(1), "bar");
622     /// assert_eq!(v, ["foo", "qux", "baz"]);
623     ///
624     /// assert_eq!(v.swap_remove(0), "foo");
625     /// assert_eq!(v, ["baz", "qux"]);
626     /// ```
627     #[inline]
628     #[stable(feature = "rust1", since = "1.0.0")]
629     pub fn swap_remove(&mut self, index: usize) -> T {
630         let length = self.len();
631         self.swap(index, length - 1);
632         self.pop().unwrap()
633     }
634
635     /// Inserts an element at position `index` within the vector, shifting all
636     /// elements after it to the right.
637     ///
638     /// # Panics
639     ///
640     /// Panics if `index` is greater than the vector's length.
641     ///
642     /// # Examples
643     ///
644     /// ```
645     /// let mut vec = vec![1, 2, 3];
646     /// vec.insert(1, 4);
647     /// assert_eq!(vec, [1, 4, 2, 3]);
648     /// vec.insert(4, 5);
649     /// assert_eq!(vec, [1, 4, 2, 3, 5]);
650     /// ```
651     #[stable(feature = "rust1", since = "1.0.0")]
652     pub fn insert(&mut self, index: usize, element: T) {
653         let len = self.len();
654         assert!(index <= len);
655
656         // space for the new element
657         if len == self.buf.cap() {
658             self.buf.double();
659         }
660
661         unsafe {
662             // infallible
663             // The spot to put the new value
664             {
665                 let p = self.as_mut_ptr().offset(index as isize);
666                 // Shift everything over to make space. (Duplicating the
667                 // `index`th element into two consecutive places.)
668                 ptr::copy(p, p.offset(1), len - index);
669                 // Write it in, overwriting the first copy of the `index`th
670                 // element.
671                 ptr::write(p, element);
672             }
673             self.set_len(len + 1);
674         }
675     }
676
677     /// Removes and returns the element at position `index` within the vector,
678     /// shifting all elements after it to the left.
679     ///
680     /// # Panics
681     ///
682     /// Panics if `index` is out of bounds.
683     ///
684     /// # Examples
685     ///
686     /// ```
687     /// let mut v = vec![1, 2, 3];
688     /// assert_eq!(v.remove(1), 2);
689     /// assert_eq!(v, [1, 3]);
690     /// ```
691     #[stable(feature = "rust1", since = "1.0.0")]
692     pub fn remove(&mut self, index: usize) -> T {
693         let len = self.len();
694         assert!(index < len);
695         unsafe {
696             // infallible
697             let ret;
698             {
699                 // the place we are taking from.
700                 let ptr = self.as_mut_ptr().offset(index as isize);
701                 // copy it out, unsafely having a copy of the value on
702                 // the stack and in the vector at the same time.
703                 ret = ptr::read(ptr);
704
705                 // Shift everything down to fill in that spot.
706                 ptr::copy(ptr.offset(1), ptr, len - index - 1);
707             }
708             self.set_len(len - 1);
709             ret
710         }
711     }
712
713     /// Retains only the elements specified by the predicate.
714     ///
715     /// In other words, remove all elements `e` such that `f(&e)` returns false.
716     /// This method operates in place and preserves the order of the retained
717     /// elements.
718     ///
719     /// # Examples
720     ///
721     /// ```
722     /// let mut vec = vec![1, 2, 3, 4];
723     /// vec.retain(|&x| x%2 == 0);
724     /// assert_eq!(vec, [2, 4]);
725     /// ```
726     #[stable(feature = "rust1", since = "1.0.0")]
727     pub fn retain<F>(&mut self, mut f: F)
728         where F: FnMut(&T) -> bool
729     {
730         let len = self.len();
731         let mut del = 0;
732         {
733             let v = &mut **self;
734
735             for i in 0..len {
736                 if !f(&v[i]) {
737                     del += 1;
738                 } else if del > 0 {
739                     v.swap(i - del, i);
740                 }
741             }
742         }
743         if del > 0 {
744             self.truncate(len - del);
745         }
746     }
747
748     /// Appends an element to the back of a collection.
749     ///
750     /// # Panics
751     ///
752     /// Panics if the number of elements in the vector overflows a `usize`.
753     ///
754     /// # Examples
755     ///
756     /// ```
757     /// let mut vec = vec![1, 2];
758     /// vec.push(3);
759     /// assert_eq!(vec, [1, 2, 3]);
760     /// ```
761     #[inline]
762     #[stable(feature = "rust1", since = "1.0.0")]
763     pub fn push(&mut self, value: T) {
764         // This will panic or abort if we would allocate > isize::MAX bytes
765         // or if the length increment would overflow for zero-sized types.
766         if self.len == self.buf.cap() {
767             self.buf.double();
768         }
769         unsafe {
770             let end = self.as_mut_ptr().offset(self.len as isize);
771             ptr::write(end, value);
772             self.len += 1;
773         }
774     }
775
776     /// Removes the last element from a vector and returns it, or `None` if it
777     /// is empty.
778     ///
779     /// # Examples
780     ///
781     /// ```
782     /// let mut vec = vec![1, 2, 3];
783     /// assert_eq!(vec.pop(), Some(3));
784     /// assert_eq!(vec, [1, 2]);
785     /// ```
786     #[inline]
787     #[stable(feature = "rust1", since = "1.0.0")]
788     pub fn pop(&mut self) -> Option<T> {
789         if self.len == 0 {
790             None
791         } else {
792             unsafe {
793                 self.len -= 1;
794                 Some(ptr::read(self.get_unchecked(self.len())))
795             }
796         }
797     }
798
799     /// Moves all the elements of `other` into `Self`, leaving `other` empty.
800     ///
801     /// # Panics
802     ///
803     /// Panics if the number of elements in the vector overflows a `usize`.
804     ///
805     /// # Examples
806     ///
807     /// ```
808     /// let mut vec = vec![1, 2, 3];
809     /// let mut vec2 = vec![4, 5, 6];
810     /// vec.append(&mut vec2);
811     /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
812     /// assert_eq!(vec2, []);
813     /// ```
814     #[inline]
815     #[stable(feature = "append", since = "1.4.0")]
816     pub fn append(&mut self, other: &mut Self) {
817         self.reserve(other.len());
818         let len = self.len();
819         unsafe {
820             ptr::copy_nonoverlapping(other.as_ptr(), self.get_unchecked_mut(len), other.len());
821         }
822
823         self.len += other.len();
824         unsafe {
825             other.set_len(0);
826         }
827     }
828
829     /// Create a draining iterator that removes the specified range in the vector
830     /// and yields the removed items.
831     ///
832     /// Note 1: The element range is removed even if the iterator is not
833     /// consumed until the end.
834     ///
835     /// Note 2: It is unspecified how many elements are removed from the vector,
836     /// if the `Drain` value is leaked.
837     ///
838     /// # Panics
839     ///
840     /// Panics if the starting point is greater than the end point or if
841     /// the end point is greater than the length of the vector.
842     ///
843     /// # Examples
844     ///
845     /// ```
846     /// let mut v = vec![1, 2, 3];
847     /// let u: Vec<_> = v.drain(1..).collect();
848     /// assert_eq!(v, &[1]);
849     /// assert_eq!(u, &[2, 3]);
850     ///
851     /// // A full range clears the vector
852     /// v.drain(..);
853     /// assert_eq!(v, &[]);
854     /// ```
855     #[stable(feature = "drain", since = "1.6.0")]
856     pub fn drain<R>(&mut self, range: R) -> Drain<T>
857         where R: RangeArgument<usize>
858     {
859         // Memory safety
860         //
861         // When the Drain is first created, it shortens the length of
862         // the source vector to make sure no uninitalized or moved-from elements
863         // are accessible at all if the Drain's destructor never gets to run.
864         //
865         // Drain will ptr::read out the values to remove.
866         // When finished, remaining tail of the vec is copied back to cover
867         // the hole, and the vector length is restored to the new length.
868         //
869         let len = self.len();
870         let start = *range.start().unwrap_or(&0);
871         let end = *range.end().unwrap_or(&len);
872         assert!(start <= end);
873         assert!(end <= len);
874
875         unsafe {
876             // set self.vec length's to start, to be safe in case Drain is leaked
877             self.set_len(start);
878             // Use the borrow in the IterMut to indicate borrowing behavior of the
879             // whole Drain iterator (like &mut T).
880             let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().offset(start as isize),
881                                                         end - start);
882             Drain {
883                 tail_start: end,
884                 tail_len: len - end,
885                 iter: range_slice.iter_mut(),
886                 vec: self as *mut _,
887             }
888         }
889     }
890
891     /// Clears the vector, removing all values.
892     ///
893     /// # Examples
894     ///
895     /// ```
896     /// let mut v = vec![1, 2, 3];
897     ///
898     /// v.clear();
899     ///
900     /// assert!(v.is_empty());
901     /// ```
902     #[inline]
903     #[stable(feature = "rust1", since = "1.0.0")]
904     pub fn clear(&mut self) {
905         self.truncate(0)
906     }
907
908     /// Returns the number of elements in the vector.
909     ///
910     /// # Examples
911     ///
912     /// ```
913     /// let a = vec![1, 2, 3];
914     /// assert_eq!(a.len(), 3);
915     /// ```
916     #[inline]
917     #[stable(feature = "rust1", since = "1.0.0")]
918     pub fn len(&self) -> usize {
919         self.len
920     }
921
922     /// Returns `true` if the vector contains no elements.
923     ///
924     /// # Examples
925     ///
926     /// ```
927     /// let mut v = Vec::new();
928     /// assert!(v.is_empty());
929     ///
930     /// v.push(1);
931     /// assert!(!v.is_empty());
932     /// ```
933     #[stable(feature = "rust1", since = "1.0.0")]
934     pub fn is_empty(&self) -> bool {
935         self.len() == 0
936     }
937
938     /// Splits the collection into two at the given index.
939     ///
940     /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
941     /// and the returned `Self` contains elements `[at, len)`.
942     ///
943     /// Note that the capacity of `self` does not change.
944     ///
945     /// # Panics
946     ///
947     /// Panics if `at > len`.
948     ///
949     /// # Examples
950     ///
951     /// ```
952     /// let mut vec = vec![1,2,3];
953     /// let vec2 = vec.split_off(1);
954     /// assert_eq!(vec, [1]);
955     /// assert_eq!(vec2, [2, 3]);
956     /// ```
957     #[inline]
958     #[stable(feature = "split_off", since = "1.4.0")]
959     pub fn split_off(&mut self, at: usize) -> Self {
960         assert!(at <= self.len(), "`at` out of bounds");
961
962         let other_len = self.len - at;
963         let mut other = Vec::with_capacity(other_len);
964
965         // Unsafely `set_len` and copy items to `other`.
966         unsafe {
967             self.set_len(at);
968             other.set_len(other_len);
969
970             ptr::copy_nonoverlapping(self.as_ptr().offset(at as isize),
971                                      other.as_mut_ptr(),
972                                      other.len());
973         }
974         other
975     }
976 }
977
978 impl<T: Clone> Vec<T> {
979     /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
980     ///
981     /// If `new_len` is greater than `len()`, the `Vec` is extended by the
982     /// difference, with each additional slot filled with `value`.
983     /// If `new_len` is less than `len()`, the `Vec` is simply truncated.
984     ///
985     /// # Examples
986     ///
987     /// ```
988     /// let mut vec = vec!["hello"];
989     /// vec.resize(3, "world");
990     /// assert_eq!(vec, ["hello", "world", "world"]);
991     ///
992     /// let mut vec = vec![1, 2, 3, 4];
993     /// vec.resize(2, 0);
994     /// assert_eq!(vec, [1, 2]);
995     /// ```
996     #[stable(feature = "vec_resize", since = "1.5.0")]
997     pub fn resize(&mut self, new_len: usize, value: T) {
998         let len = self.len();
999
1000         if new_len > len {
1001             self.extend_with_element(new_len - len, value);
1002         } else {
1003             self.truncate(new_len);
1004         }
1005     }
1006
1007     /// Extend the vector by `n` additional clones of `value`.
1008     fn extend_with_element(&mut self, n: usize, value: T) {
1009         self.reserve(n);
1010
1011         unsafe {
1012             let len = self.len();
1013             let mut ptr = self.as_mut_ptr().offset(len as isize);
1014             // Write all elements except the last one
1015             for i in 1..n {
1016                 ptr::write(ptr, value.clone());
1017                 ptr = ptr.offset(1);
1018                 // Increment the length in every step in case clone() panics
1019                 self.set_len(len + i);
1020             }
1021
1022             if n > 0 {
1023                 // We can write the last element directly without cloning needlessly
1024                 ptr::write(ptr, value);
1025                 self.set_len(len + n);
1026             }
1027         }
1028     }
1029
1030     /// Clones and appends all elements in a slice to the `Vec`.
1031     ///
1032     /// Iterates over the slice `other`, clones each element, and then appends
1033     /// it to this `Vec`. The `other` vector is traversed in-order.
1034     ///
1035     /// Note that this function is same as `extend` except that it is
1036     /// specialized to work with slices instead. If and when Rust gets
1037     /// specialization this function will likely be deprecated (but still
1038     /// available).
1039     ///
1040     /// # Examples
1041     ///
1042     /// ```
1043     /// let mut vec = vec![1];
1044     /// vec.extend_from_slice(&[2, 3, 4]);
1045     /// assert_eq!(vec, [1, 2, 3, 4]);
1046     /// ```
1047     #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1048     pub fn extend_from_slice(&mut self, other: &[T]) {
1049         self.reserve(other.len());
1050
1051         for i in 0..other.len() {
1052             let len = self.len();
1053
1054             // Unsafe code so this can be optimised to a memcpy (or something
1055             // similarly fast) when T is Copy. LLVM is easily confused, so any
1056             // extra operations during the loop can prevent this optimisation.
1057             unsafe {
1058                 ptr::write(self.get_unchecked_mut(len), other.get_unchecked(i).clone());
1059                 self.set_len(len + 1);
1060             }
1061         }
1062     }
1063 }
1064
1065 impl<T: PartialEq> Vec<T> {
1066     /// Removes consecutive repeated elements in the vector.
1067     ///
1068     /// If the vector is sorted, this removes all duplicates.
1069     ///
1070     /// # Examples
1071     ///
1072     /// ```
1073     /// let mut vec = vec![1, 2, 2, 3, 2];
1074     ///
1075     /// vec.dedup();
1076     ///
1077     /// assert_eq!(vec, [1, 2, 3, 2]);
1078     /// ```
1079     #[stable(feature = "rust1", since = "1.0.0")]
1080     pub fn dedup(&mut self) {
1081         unsafe {
1082             // Although we have a mutable reference to `self`, we cannot make
1083             // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
1084             // must ensure that the vector is in a valid state at all time.
1085             //
1086             // The way that we handle this is by using swaps; we iterate
1087             // over all the elements, swapping as we go so that at the end
1088             // the elements we wish to keep are in the front, and those we
1089             // wish to reject are at the back. We can then truncate the
1090             // vector. This operation is still O(n).
1091             //
1092             // Example: We start in this state, where `r` represents "next
1093             // read" and `w` represents "next_write`.
1094             //
1095             //           r
1096             //     +---+---+---+---+---+---+
1097             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1098             //     +---+---+---+---+---+---+
1099             //           w
1100             //
1101             // Comparing self[r] against self[w-1], this is not a duplicate, so
1102             // we swap self[r] and self[w] (no effect as r==w) and then increment both
1103             // r and w, leaving us with:
1104             //
1105             //               r
1106             //     +---+---+---+---+---+---+
1107             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1108             //     +---+---+---+---+---+---+
1109             //               w
1110             //
1111             // Comparing self[r] against self[w-1], this value is a duplicate,
1112             // so we increment `r` but leave everything else unchanged:
1113             //
1114             //                   r
1115             //     +---+---+---+---+---+---+
1116             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1117             //     +---+---+---+---+---+---+
1118             //               w
1119             //
1120             // Comparing self[r] against self[w-1], this is not a duplicate,
1121             // so swap self[r] and self[w] and advance r and w:
1122             //
1123             //                       r
1124             //     +---+---+---+---+---+---+
1125             //     | 0 | 1 | 2 | 1 | 3 | 3 |
1126             //     +---+---+---+---+---+---+
1127             //                   w
1128             //
1129             // Not a duplicate, repeat:
1130             //
1131             //                           r
1132             //     +---+---+---+---+---+---+
1133             //     | 0 | 1 | 2 | 3 | 1 | 3 |
1134             //     +---+---+---+---+---+---+
1135             //                       w
1136             //
1137             // Duplicate, advance r. End of vec. Truncate to w.
1138
1139             let ln = self.len();
1140             if ln <= 1 {
1141                 return;
1142             }
1143
1144             // Avoid bounds checks by using raw pointers.
1145             let p = self.as_mut_ptr();
1146             let mut r: usize = 1;
1147             let mut w: usize = 1;
1148
1149             while r < ln {
1150                 let p_r = p.offset(r as isize);
1151                 let p_wm1 = p.offset((w - 1) as isize);
1152                 if *p_r != *p_wm1 {
1153                     if r != w {
1154                         let p_w = p_wm1.offset(1);
1155                         mem::swap(&mut *p_r, &mut *p_w);
1156                     }
1157                     w += 1;
1158                 }
1159                 r += 1;
1160             }
1161
1162             self.truncate(w);
1163         }
1164     }
1165 }
1166
1167 ////////////////////////////////////////////////////////////////////////////////
1168 // Internal methods and functions
1169 ////////////////////////////////////////////////////////////////////////////////
1170
1171 #[doc(hidden)]
1172 #[stable(feature = "rust1", since = "1.0.0")]
1173 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1174     let mut v = Vec::with_capacity(n);
1175     v.extend_with_element(n, elem);
1176     v
1177 }
1178
1179 ////////////////////////////////////////////////////////////////////////////////
1180 // Common trait implementations for Vec
1181 ////////////////////////////////////////////////////////////////////////////////
1182
1183 #[stable(feature = "rust1", since = "1.0.0")]
1184 impl<T: Clone> Clone for Vec<T> {
1185     #[cfg(not(test))]
1186     fn clone(&self) -> Vec<T> {
1187         <[T]>::to_vec(&**self)
1188     }
1189
1190     // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1191     // required for this method definition, is not available. Instead use the
1192     // `slice::to_vec`  function which is only available with cfg(test)
1193     // NB see the slice::hack module in slice.rs for more information
1194     #[cfg(test)]
1195     fn clone(&self) -> Vec<T> {
1196         ::slice::to_vec(&**self)
1197     }
1198
1199     fn clone_from(&mut self, other: &Vec<T>) {
1200         // drop anything in self that will not be overwritten
1201         self.truncate(other.len());
1202         let len = self.len();
1203
1204         // reuse the contained values' allocations/resources.
1205         self.clone_from_slice(&other[..len]);
1206
1207         // self.len <= other.len due to the truncate above, so the
1208         // slice here is always in-bounds.
1209         self.extend_from_slice(&other[len..]);
1210     }
1211 }
1212
1213 #[stable(feature = "rust1", since = "1.0.0")]
1214 impl<T: Hash> Hash for Vec<T> {
1215     #[inline]
1216     fn hash<H: hash::Hasher>(&self, state: &mut H) {
1217         Hash::hash(&**self, state)
1218     }
1219 }
1220
1221 #[stable(feature = "rust1", since = "1.0.0")]
1222 impl<T> Index<usize> for Vec<T> {
1223     type Output = T;
1224
1225     #[inline]
1226     fn index(&self, index: usize) -> &T {
1227         // NB built-in indexing via `&[T]`
1228         &(**self)[index]
1229     }
1230 }
1231
1232 #[stable(feature = "rust1", since = "1.0.0")]
1233 impl<T> IndexMut<usize> for Vec<T> {
1234     #[inline]
1235     fn index_mut(&mut self, index: usize) -> &mut T {
1236         // NB built-in indexing via `&mut [T]`
1237         &mut (**self)[index]
1238     }
1239 }
1240
1241
1242 #[stable(feature = "rust1", since = "1.0.0")]
1243 impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
1244     type Output = [T];
1245
1246     #[inline]
1247     fn index(&self, index: ops::Range<usize>) -> &[T] {
1248         Index::index(&**self, index)
1249     }
1250 }
1251 #[stable(feature = "rust1", since = "1.0.0")]
1252 impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
1253     type Output = [T];
1254
1255     #[inline]
1256     fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
1257         Index::index(&**self, index)
1258     }
1259 }
1260 #[stable(feature = "rust1", since = "1.0.0")]
1261 impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
1262     type Output = [T];
1263
1264     #[inline]
1265     fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
1266         Index::index(&**self, index)
1267     }
1268 }
1269 #[stable(feature = "rust1", since = "1.0.0")]
1270 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1271     type Output = [T];
1272
1273     #[inline]
1274     fn index(&self, _index: ops::RangeFull) -> &[T] {
1275         self
1276     }
1277 }
1278 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1279 impl<T> ops::Index<ops::RangeInclusive<usize>> for Vec<T> {
1280     type Output = [T];
1281
1282     #[inline]
1283     fn index(&self, index: ops::RangeInclusive<usize>) -> &[T] {
1284         Index::index(&**self, index)
1285     }
1286 }
1287 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1288 impl<T> ops::Index<ops::RangeToInclusive<usize>> for Vec<T> {
1289     type Output = [T];
1290
1291     #[inline]
1292     fn index(&self, index: ops::RangeToInclusive<usize>) -> &[T] {
1293         Index::index(&**self, index)
1294     }
1295 }
1296
1297 #[stable(feature = "rust1", since = "1.0.0")]
1298 impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
1299     #[inline]
1300     fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
1301         IndexMut::index_mut(&mut **self, index)
1302     }
1303 }
1304 #[stable(feature = "rust1", since = "1.0.0")]
1305 impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
1306     #[inline]
1307     fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
1308         IndexMut::index_mut(&mut **self, index)
1309     }
1310 }
1311 #[stable(feature = "rust1", since = "1.0.0")]
1312 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
1313     #[inline]
1314     fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
1315         IndexMut::index_mut(&mut **self, index)
1316     }
1317 }
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
1320     #[inline]
1321     fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] {
1322         self
1323     }
1324 }
1325 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1326 impl<T> ops::IndexMut<ops::RangeInclusive<usize>> for Vec<T> {
1327     #[inline]
1328     fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut [T] {
1329         IndexMut::index_mut(&mut **self, index)
1330     }
1331 }
1332 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1333 impl<T> ops::IndexMut<ops::RangeToInclusive<usize>> for Vec<T> {
1334     #[inline]
1335     fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut [T] {
1336         IndexMut::index_mut(&mut **self, index)
1337     }
1338 }
1339
1340 #[stable(feature = "rust1", since = "1.0.0")]
1341 impl<T> ops::Deref for Vec<T> {
1342     type Target = [T];
1343
1344     fn deref(&self) -> &[T] {
1345         unsafe {
1346             let p = self.buf.ptr();
1347             assume(!p.is_null());
1348             slice::from_raw_parts(p, self.len)
1349         }
1350     }
1351 }
1352
1353 #[stable(feature = "rust1", since = "1.0.0")]
1354 impl<T> ops::DerefMut for Vec<T> {
1355     fn deref_mut(&mut self) -> &mut [T] {
1356         unsafe {
1357             let ptr = self.buf.ptr();
1358             assume(!ptr.is_null());
1359             slice::from_raw_parts_mut(ptr, self.len)
1360         }
1361     }
1362 }
1363
1364 #[stable(feature = "rust1", since = "1.0.0")]
1365 impl<T> FromIterator<T> for Vec<T> {
1366     #[inline]
1367     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
1368         // Unroll the first iteration, as the vector is going to be
1369         // expanded on this iteration in every case when the iterable is not
1370         // empty, but the loop in extend_desugared() is not going to see the
1371         // vector being full in the few subsequent loop iterations.
1372         // So we get better branch prediction.
1373         let mut iterator = iter.into_iter();
1374         let mut vector = match iterator.next() {
1375             None => return Vec::new(),
1376             Some(element) => {
1377                 let (lower, _) = iterator.size_hint();
1378                 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1379                 unsafe {
1380                     ptr::write(vector.get_unchecked_mut(0), element);
1381                     vector.set_len(1);
1382                 }
1383                 vector
1384             }
1385         };
1386         vector.extend_desugared(iterator);
1387         vector
1388     }
1389 }
1390
1391 #[stable(feature = "rust1", since = "1.0.0")]
1392 impl<T> IntoIterator for Vec<T> {
1393     type Item = T;
1394     type IntoIter = IntoIter<T>;
1395
1396     /// Creates a consuming iterator, that is, one that moves each value out of
1397     /// the vector (from start to end). The vector cannot be used after calling
1398     /// this.
1399     ///
1400     /// # Examples
1401     ///
1402     /// ```
1403     /// let v = vec!["a".to_string(), "b".to_string()];
1404     /// for s in v.into_iter() {
1405     ///     // s has type String, not &String
1406     ///     println!("{}", s);
1407     /// }
1408     /// ```
1409     #[inline]
1410     fn into_iter(mut self) -> IntoIter<T> {
1411         unsafe {
1412             let ptr = self.as_mut_ptr();
1413             assume(!ptr.is_null());
1414             let begin = ptr as *const T;
1415             let end = if mem::size_of::<T>() == 0 {
1416                 arith_offset(ptr as *const i8, self.len() as isize) as *const T
1417             } else {
1418                 ptr.offset(self.len() as isize) as *const T
1419             };
1420             let buf = ptr::read(&self.buf);
1421             mem::forget(self);
1422             IntoIter {
1423                 _buf: buf,
1424                 ptr: begin,
1425                 end: end,
1426             }
1427         }
1428     }
1429 }
1430
1431 #[stable(feature = "rust1", since = "1.0.0")]
1432 impl<'a, T> IntoIterator for &'a Vec<T> {
1433     type Item = &'a T;
1434     type IntoIter = slice::Iter<'a, T>;
1435
1436     fn into_iter(self) -> slice::Iter<'a, T> {
1437         self.iter()
1438     }
1439 }
1440
1441 #[stable(feature = "rust1", since = "1.0.0")]
1442 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1443     type Item = &'a mut T;
1444     type IntoIter = slice::IterMut<'a, T>;
1445
1446     fn into_iter(mut self) -> slice::IterMut<'a, T> {
1447         self.iter_mut()
1448     }
1449 }
1450
1451 #[stable(feature = "rust1", since = "1.0.0")]
1452 impl<T> Extend<T> for Vec<T> {
1453     #[inline]
1454     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1455         <Self as SpecExtend<I>>::spec_extend(self, iter);
1456     }
1457 }
1458
1459 impl<I: IntoIterator> SpecExtend<I> for Vec<I::Item> {
1460     default fn spec_extend(&mut self, iter: I) {
1461         self.extend_desugared(iter.into_iter())
1462     }
1463 }
1464
1465 impl<T> SpecExtend<Vec<T>> for Vec<T> {
1466     fn spec_extend(&mut self, ref mut other: Vec<T>) {
1467         self.append(other);
1468     }
1469 }
1470
1471 impl<T> Vec<T> {
1472     fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
1473         // This function should be the moral equivalent of:
1474         //
1475         //      for item in iterator {
1476         //          self.push(item);
1477         //      }
1478         while let Some(element) = iterator.next() {
1479             let len = self.len();
1480             if len == self.capacity() {
1481                 let (lower, _) = iterator.size_hint();
1482                 self.reserve(lower.saturating_add(1));
1483             }
1484             unsafe {
1485                 ptr::write(self.get_unchecked_mut(len), element);
1486                 // NB can't overflow since we would have had to alloc the address space
1487                 self.set_len(len + 1);
1488             }
1489         }
1490     }
1491 }
1492
1493 #[stable(feature = "extend_ref", since = "1.2.0")]
1494 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
1495     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1496         self.extend(iter.into_iter().cloned());
1497     }
1498 }
1499
1500 macro_rules! __impl_slice_eq1 {
1501     ($Lhs: ty, $Rhs: ty) => {
1502         __impl_slice_eq1! { $Lhs, $Rhs, Sized }
1503     };
1504     ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
1505         #[stable(feature = "rust1", since = "1.0.0")]
1506         impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
1507             #[inline]
1508             fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] }
1509             #[inline]
1510             fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] }
1511         }
1512     }
1513 }
1514
1515 __impl_slice_eq1! { Vec<A>, Vec<B> }
1516 __impl_slice_eq1! { Vec<A>, &'b [B] }
1517 __impl_slice_eq1! { Vec<A>, &'b mut [B] }
1518 __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone }
1519 __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone }
1520 __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone }
1521
1522 macro_rules! array_impls {
1523     ($($N: expr)+) => {
1524         $(
1525             // NOTE: some less important impls are omitted to reduce code bloat
1526             __impl_slice_eq1! { Vec<A>, [B; $N] }
1527             __impl_slice_eq1! { Vec<A>, &'b [B; $N] }
1528             // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
1529             // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
1530             // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
1531             // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
1532         )+
1533     }
1534 }
1535
1536 array_impls! {
1537      0  1  2  3  4  5  6  7  8  9
1538     10 11 12 13 14 15 16 17 18 19
1539     20 21 22 23 24 25 26 27 28 29
1540     30 31 32
1541 }
1542
1543 #[stable(feature = "rust1", since = "1.0.0")]
1544 impl<T: PartialOrd> PartialOrd for Vec<T> {
1545     #[inline]
1546     fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1547         PartialOrd::partial_cmp(&**self, &**other)
1548     }
1549 }
1550
1551 #[stable(feature = "rust1", since = "1.0.0")]
1552 impl<T: Eq> Eq for Vec<T> {}
1553
1554 #[stable(feature = "rust1", since = "1.0.0")]
1555 impl<T: Ord> Ord for Vec<T> {
1556     #[inline]
1557     fn cmp(&self, other: &Vec<T>) -> Ordering {
1558         Ord::cmp(&**self, &**other)
1559     }
1560 }
1561
1562 #[stable(feature = "rust1", since = "1.0.0")]
1563 impl<T> Drop for Vec<T> {
1564     #[unsafe_destructor_blind_to_params]
1565     fn drop(&mut self) {
1566         if self.buf.unsafe_no_drop_flag_needs_drop() {
1567             unsafe {
1568                 // use drop for [T]
1569                 ptr::drop_in_place(&mut self[..]);
1570             }
1571         }
1572         // RawVec handles deallocation
1573     }
1574 }
1575
1576 #[stable(feature = "rust1", since = "1.0.0")]
1577 impl<T> Default for Vec<T> {
1578     fn default() -> Vec<T> {
1579         Vec::new()
1580     }
1581 }
1582
1583 #[stable(feature = "rust1", since = "1.0.0")]
1584 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
1585     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1586         fmt::Debug::fmt(&**self, f)
1587     }
1588 }
1589
1590 #[stable(feature = "rust1", since = "1.0.0")]
1591 impl<T> AsRef<Vec<T>> for Vec<T> {
1592     fn as_ref(&self) -> &Vec<T> {
1593         self
1594     }
1595 }
1596
1597 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1598 impl<T> AsMut<Vec<T>> for Vec<T> {
1599     fn as_mut(&mut self) -> &mut Vec<T> {
1600         self
1601     }
1602 }
1603
1604 #[stable(feature = "rust1", since = "1.0.0")]
1605 impl<T> AsRef<[T]> for Vec<T> {
1606     fn as_ref(&self) -> &[T] {
1607         self
1608     }
1609 }
1610
1611 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1612 impl<T> AsMut<[T]> for Vec<T> {
1613     fn as_mut(&mut self) -> &mut [T] {
1614         self
1615     }
1616 }
1617
1618 #[stable(feature = "rust1", since = "1.0.0")]
1619 impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
1620     #[cfg(not(test))]
1621     fn from(s: &'a [T]) -> Vec<T> {
1622         s.to_vec()
1623     }
1624     #[cfg(test)]
1625     fn from(s: &'a [T]) -> Vec<T> {
1626         ::slice::to_vec(s)
1627     }
1628 }
1629
1630 #[stable(feature = "rust1", since = "1.0.0")]
1631 impl<'a> From<&'a str> for Vec<u8> {
1632     fn from(s: &'a str) -> Vec<u8> {
1633         From::from(s.as_bytes())
1634     }
1635 }
1636
1637 ////////////////////////////////////////////////////////////////////////////////
1638 // Clone-on-write
1639 ////////////////////////////////////////////////////////////////////////////////
1640
1641 #[stable(feature = "cow_from_vec", since = "1.7.0")]
1642 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
1643     fn from(s: &'a [T]) -> Cow<'a, [T]> {
1644         Cow::Borrowed(s)
1645     }
1646 }
1647
1648 #[stable(feature = "cow_from_vec", since = "1.7.0")]
1649 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
1650     fn from(v: Vec<T>) -> Cow<'a, [T]> {
1651         Cow::Owned(v)
1652     }
1653 }
1654
1655 #[stable(feature = "rust1", since = "1.0.0")]
1656 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
1657     fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
1658         Cow::Owned(FromIterator::from_iter(it))
1659     }
1660 }
1661
1662 ////////////////////////////////////////////////////////////////////////////////
1663 // Iterators
1664 ////////////////////////////////////////////////////////////////////////////////
1665
1666 /// An iterator that moves out of a vector.
1667 ///
1668 /// This `struct` is created by the `into_iter` method on [`Vec`][`Vec`] (provided
1669 /// by the [`IntoIterator`] trait).
1670 ///
1671 /// [`Vec`]: struct.Vec.html
1672 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
1673 #[stable(feature = "rust1", since = "1.0.0")]
1674 pub struct IntoIter<T> {
1675     _buf: RawVec<T>,
1676     ptr: *const T,
1677     end: *const T,
1678 }
1679
1680 #[stable(feature = "rust1", since = "1.0.0")]
1681 unsafe impl<T: Send> Send for IntoIter<T> {}
1682 #[stable(feature = "rust1", since = "1.0.0")]
1683 unsafe impl<T: Sync> Sync for IntoIter<T> {}
1684
1685 #[stable(feature = "rust1", since = "1.0.0")]
1686 impl<T> Iterator for IntoIter<T> {
1687     type Item = T;
1688
1689     #[inline]
1690     fn next(&mut self) -> Option<T> {
1691         unsafe {
1692             if self.ptr == self.end {
1693                 None
1694             } else {
1695                 if mem::size_of::<T>() == 0 {
1696                     // purposefully don't use 'ptr.offset' because for
1697                     // vectors with 0-size elements this would return the
1698                     // same pointer.
1699                     self.ptr = arith_offset(self.ptr as *const i8, 1) as *const T;
1700
1701                     // Use a non-null pointer value
1702                     Some(ptr::read(EMPTY as *mut T))
1703                 } else {
1704                     let old = self.ptr;
1705                     self.ptr = self.ptr.offset(1);
1706
1707                     Some(ptr::read(old))
1708                 }
1709             }
1710         }
1711     }
1712
1713     #[inline]
1714     fn size_hint(&self) -> (usize, Option<usize>) {
1715         let diff = (self.end as usize) - (self.ptr as usize);
1716         let size = mem::size_of::<T>();
1717         let exact = diff /
1718                     (if size == 0 {
1719                          1
1720                      } else {
1721                          size
1722                      });
1723         (exact, Some(exact))
1724     }
1725
1726     #[inline]
1727     fn count(self) -> usize {
1728         self.len()
1729     }
1730 }
1731
1732 #[stable(feature = "rust1", since = "1.0.0")]
1733 impl<T> DoubleEndedIterator for IntoIter<T> {
1734     #[inline]
1735     fn next_back(&mut self) -> Option<T> {
1736         unsafe {
1737             if self.end == self.ptr {
1738                 None
1739             } else {
1740                 if mem::size_of::<T>() == 0 {
1741                     // See above for why 'ptr.offset' isn't used
1742                     self.end = arith_offset(self.end as *const i8, -1) as *const T;
1743
1744                     // Use a non-null pointer value
1745                     Some(ptr::read(EMPTY as *mut T))
1746                 } else {
1747                     self.end = self.end.offset(-1);
1748
1749                     Some(ptr::read(self.end))
1750                 }
1751             }
1752         }
1753     }
1754 }
1755
1756 #[stable(feature = "rust1", since = "1.0.0")]
1757 impl<T> ExactSizeIterator for IntoIter<T> {}
1758
1759 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
1760 impl<T: Clone> Clone for IntoIter<T> {
1761     fn clone(&self) -> IntoIter<T> {
1762         unsafe {
1763             slice::from_raw_parts(self.ptr, self.len()).to_owned().into_iter()
1764         }
1765     }
1766 }
1767
1768 #[stable(feature = "rust1", since = "1.0.0")]
1769 impl<T> Drop for IntoIter<T> {
1770     #[unsafe_destructor_blind_to_params]
1771     fn drop(&mut self) {
1772         // destroy the remaining elements
1773         for _x in self {}
1774
1775         // RawVec handles deallocation
1776     }
1777 }
1778
1779 /// A draining iterator for `Vec<T>`.
1780 ///
1781 /// This `struct` is created by the [`drain`] method on [`Vec`].
1782 ///
1783 /// [`drain`]: struct.Vec.html#method.drain
1784 /// [`Vec`]: struct.Vec.html
1785 #[stable(feature = "drain", since = "1.6.0")]
1786 pub struct Drain<'a, T: 'a> {
1787     /// Index of tail to preserve
1788     tail_start: usize,
1789     /// Length of tail
1790     tail_len: usize,
1791     /// Current remaining range to remove
1792     iter: slice::IterMut<'a, T>,
1793     vec: *mut Vec<T>,
1794 }
1795
1796 #[stable(feature = "drain", since = "1.6.0")]
1797 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1798 #[stable(feature = "drain", since = "1.6.0")]
1799 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1800
1801 #[stable(feature = "rust1", since = "1.0.0")]
1802 impl<'a, T> Iterator for Drain<'a, T> {
1803     type Item = T;
1804
1805     #[inline]
1806     fn next(&mut self) -> Option<T> {
1807         self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
1808     }
1809
1810     fn size_hint(&self) -> (usize, Option<usize>) {
1811         self.iter.size_hint()
1812     }
1813 }
1814
1815 #[stable(feature = "rust1", since = "1.0.0")]
1816 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1817     #[inline]
1818     fn next_back(&mut self) -> Option<T> {
1819         self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
1820     }
1821 }
1822
1823 #[stable(feature = "rust1", since = "1.0.0")]
1824 impl<'a, T> Drop for Drain<'a, T> {
1825     fn drop(&mut self) {
1826         // exhaust self first
1827         while let Some(_) = self.next() {}
1828
1829         if self.tail_len > 0 {
1830             unsafe {
1831                 let source_vec = &mut *self.vec;
1832                 // memmove back untouched tail, update to new length
1833                 let start = source_vec.len();
1834                 let tail = self.tail_start;
1835                 let src = source_vec.as_ptr().offset(tail as isize);
1836                 let dst = source_vec.as_mut_ptr().offset(start as isize);
1837                 ptr::copy(src, dst, self.tail_len);
1838                 source_vec.set_len(start + self.tail_len);
1839             }
1840         }
1841     }
1842 }
1843
1844
1845 #[stable(feature = "rust1", since = "1.0.0")]
1846 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}