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