]> git.lizzy.rs Git - rust.git/blob - src/libcollections/vec.rs
bd1bf6e9cc37591b3269d2e1ad6308ab2fd54a48
[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 the length that 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     /// # Examples
352     ///
353     /// ```
354     /// use std::ptr;
355     /// use std::mem;
356     ///
357     /// fn main() {
358     ///     let mut v = vec![1, 2, 3];
359     ///
360     ///     // Pull out the various important pieces of information about `v`
361     ///     let p = v.as_mut_ptr();
362     ///     let len = v.len();
363     ///     let cap = v.capacity();
364     ///
365     ///     unsafe {
366     ///         // Cast `v` into the void: no destructor run, so we are in
367     ///         // complete control of the allocation to which `p` points.
368     ///         mem::forget(v);
369     ///
370     ///         // Overwrite memory with 4, 5, 6
371     ///         for i in 0..len as isize {
372     ///             ptr::write(p.offset(i), 4 + i);
373     ///         }
374     ///
375     ///         // Put everything back together into a Vec
376     ///         let rebuilt = Vec::from_raw_parts(p, len, cap);
377     ///         assert_eq!(rebuilt, [4, 5, 6]);
378     ///     }
379     /// }
380     /// ```
381     #[stable(feature = "rust1", since = "1.0.0")]
382     pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
383         Vec {
384             buf: RawVec::from_raw_parts(ptr, capacity),
385             len: length,
386         }
387     }
388
389     /// Returns the number of elements the vector can hold without
390     /// reallocating.
391     ///
392     /// # Examples
393     ///
394     /// ```
395     /// let vec: Vec<i32> = Vec::with_capacity(10);
396     /// assert_eq!(vec.capacity(), 10);
397     /// ```
398     #[inline]
399     #[stable(feature = "rust1", since = "1.0.0")]
400     pub fn capacity(&self) -> usize {
401         self.buf.cap()
402     }
403
404     /// Reserves capacity for at least `additional` more elements to be inserted
405     /// in the given `Vec<T>`. The collection may reserve more space to avoid
406     /// frequent reallocations.
407     ///
408     /// # Panics
409     ///
410     /// Panics if the new capacity overflows `usize`.
411     ///
412     /// # Examples
413     ///
414     /// ```
415     /// let mut vec = vec![1];
416     /// vec.reserve(10);
417     /// assert!(vec.capacity() >= 11);
418     /// ```
419     #[stable(feature = "rust1", since = "1.0.0")]
420     pub fn reserve(&mut self, additional: usize) {
421         self.buf.reserve(self.len, additional);
422     }
423
424     /// Reserves the minimum capacity for exactly `additional` more elements to
425     /// be inserted in the given `Vec<T>`. Does nothing if the capacity is already
426     /// sufficient.
427     ///
428     /// Note that the allocator may give the collection more space than it
429     /// requests. Therefore capacity can not be relied upon to be precisely
430     /// minimal. Prefer `reserve` if future insertions are expected.
431     ///
432     /// # Panics
433     ///
434     /// Panics if the new capacity overflows `usize`.
435     ///
436     /// # Examples
437     ///
438     /// ```
439     /// let mut vec = vec![1];
440     /// vec.reserve_exact(10);
441     /// assert!(vec.capacity() >= 11);
442     /// ```
443     #[stable(feature = "rust1", since = "1.0.0")]
444     pub fn reserve_exact(&mut self, additional: usize) {
445         self.buf.reserve_exact(self.len, additional);
446     }
447
448     /// Shrinks the capacity of the vector as much as possible.
449     ///
450     /// It will drop down as close as possible to the length but the allocator
451     /// may still inform the vector that there is space for a few more elements.
452     ///
453     /// # Examples
454     ///
455     /// ```
456     /// let mut vec = Vec::with_capacity(10);
457     /// vec.extend([1, 2, 3].iter().cloned());
458     /// assert_eq!(vec.capacity(), 10);
459     /// vec.shrink_to_fit();
460     /// assert!(vec.capacity() >= 3);
461     /// ```
462     #[stable(feature = "rust1", since = "1.0.0")]
463     pub fn shrink_to_fit(&mut self) {
464         self.buf.shrink_to_fit(self.len);
465     }
466
467     /// Converts the vector into Box<[T]>.
468     ///
469     /// Note that this will drop any excess capacity. Calling this and
470     /// converting back to a vector with `into_vec()` is equivalent to calling
471     /// `shrink_to_fit()`.
472     #[stable(feature = "rust1", since = "1.0.0")]
473     pub fn into_boxed_slice(mut self) -> Box<[T]> {
474         unsafe {
475             self.shrink_to_fit();
476             let buf = ptr::read(&self.buf);
477             mem::forget(self);
478             buf.into_box()
479         }
480     }
481
482     /// Shorten a vector to be `len` elements long, dropping excess elements.
483     ///
484     /// If `len` is greater than the vector's current length, this has no
485     /// effect.
486     ///
487     /// # Examples
488     ///
489     /// ```
490     /// let mut vec = vec![1, 2, 3, 4, 5];
491     /// vec.truncate(2);
492     /// assert_eq!(vec, [1, 2]);
493     /// ```
494     #[stable(feature = "rust1", since = "1.0.0")]
495     pub fn truncate(&mut self, len: usize) {
496         unsafe {
497             // drop any extra elements
498             while len < self.len {
499                 // decrement len before the drop_in_place(), so a panic on Drop
500                 // doesn't re-drop the just-failed value.
501                 self.len -= 1;
502                 let len = self.len;
503                 ptr::drop_in_place(self.get_unchecked_mut(len));
504             }
505         }
506     }
507
508     /// Extracts a slice containing the entire vector.
509     ///
510     /// Equivalent to `&s[..]`.
511     #[inline]
512     #[stable(feature = "vec_as_slice", since = "1.7.0")]
513     pub fn as_slice(&self) -> &[T] {
514         self
515     }
516
517     /// Extracts a mutable slice of the entire vector.
518     ///
519     /// Equivalent to `&mut s[..]`.
520     #[inline]
521     #[stable(feature = "vec_as_slice", since = "1.7.0")]
522     pub fn as_mut_slice(&mut self) -> &mut [T] {
523         &mut self[..]
524     }
525
526     /// Sets the length of a vector.
527     ///
528     /// This will explicitly set the size of the vector, without actually
529     /// modifying its buffers, so it is up to the caller to ensure that the
530     /// vector is actually the specified size.
531     ///
532     /// # Examples
533     ///
534     /// ```
535     /// let mut v = vec![1, 2, 3, 4];
536     /// unsafe {
537     ///     v.set_len(1);
538     /// }
539     /// ```
540     #[inline]
541     #[stable(feature = "rust1", since = "1.0.0")]
542     pub unsafe fn set_len(&mut self, len: usize) {
543         self.len = len;
544     }
545
546     /// Removes an element from anywhere in the vector and return it, replacing
547     /// it with the last element.
548     ///
549     /// This does not preserve ordering, but is O(1).
550     ///
551     /// # Panics
552     ///
553     /// Panics if `index` is out of bounds.
554     ///
555     /// # Examples
556     ///
557     /// ```
558     /// let mut v = vec!["foo", "bar", "baz", "qux"];
559     ///
560     /// assert_eq!(v.swap_remove(1), "bar");
561     /// assert_eq!(v, ["foo", "qux", "baz"]);
562     ///
563     /// assert_eq!(v.swap_remove(0), "foo");
564     /// assert_eq!(v, ["baz", "qux"]);
565     /// ```
566     #[inline]
567     #[stable(feature = "rust1", since = "1.0.0")]
568     pub fn swap_remove(&mut self, index: usize) -> T {
569         let length = self.len();
570         self.swap(index, length - 1);
571         self.pop().unwrap()
572     }
573
574     /// Inserts an element at position `index` within the vector, shifting all
575     /// elements after it to the right.
576     ///
577     /// # Panics
578     ///
579     /// Panics if `index` is greater than the vector's length.
580     ///
581     /// # Examples
582     ///
583     /// ```
584     /// let mut vec = vec![1, 2, 3];
585     /// vec.insert(1, 4);
586     /// assert_eq!(vec, [1, 4, 2, 3]);
587     /// vec.insert(4, 5);
588     /// assert_eq!(vec, [1, 4, 2, 3, 5]);
589     /// ```
590     #[stable(feature = "rust1", since = "1.0.0")]
591     pub fn insert(&mut self, index: usize, element: T) {
592         let len = self.len();
593         assert!(index <= len);
594
595         // space for the new element
596         if len == self.buf.cap() {
597             self.buf.double();
598         }
599
600         unsafe {
601             // infallible
602             // The spot to put the new value
603             {
604                 let p = self.as_mut_ptr().offset(index as isize);
605                 // Shift everything over to make space. (Duplicating the
606                 // `index`th element into two consecutive places.)
607                 ptr::copy(p, p.offset(1), len - index);
608                 // Write it in, overwriting the first copy of the `index`th
609                 // element.
610                 ptr::write(p, element);
611             }
612             self.set_len(len + 1);
613         }
614     }
615
616     /// Removes and returns the element at position `index` within the vector,
617     /// shifting all elements after it to the left.
618     ///
619     /// # Panics
620     ///
621     /// Panics if `index` is out of bounds.
622     ///
623     /// # Examples
624     ///
625     /// ```
626     /// let mut v = vec![1, 2, 3];
627     /// assert_eq!(v.remove(1), 2);
628     /// assert_eq!(v, [1, 3]);
629     /// ```
630     #[stable(feature = "rust1", since = "1.0.0")]
631     pub fn remove(&mut self, index: usize) -> T {
632         let len = self.len();
633         assert!(index < len);
634         unsafe {
635             // infallible
636             let ret;
637             {
638                 // the place we are taking from.
639                 let ptr = self.as_mut_ptr().offset(index as isize);
640                 // copy it out, unsafely having a copy of the value on
641                 // the stack and in the vector at the same time.
642                 ret = ptr::read(ptr);
643
644                 // Shift everything down to fill in that spot.
645                 ptr::copy(ptr.offset(1), ptr, len - index - 1);
646             }
647             self.set_len(len - 1);
648             ret
649         }
650     }
651
652     /// Retains only the elements specified by the predicate.
653     ///
654     /// In other words, remove all elements `e` such that `f(&e)` returns false.
655     /// This method operates in place and preserves the order of the retained
656     /// elements.
657     ///
658     /// # Examples
659     ///
660     /// ```
661     /// let mut vec = vec![1, 2, 3, 4];
662     /// vec.retain(|&x| x%2 == 0);
663     /// assert_eq!(vec, [2, 4]);
664     /// ```
665     #[stable(feature = "rust1", since = "1.0.0")]
666     pub fn retain<F>(&mut self, mut f: F)
667         where F: FnMut(&T) -> bool
668     {
669         let len = self.len();
670         let mut del = 0;
671         {
672             let v = &mut **self;
673
674             for i in 0..len {
675                 if !f(&v[i]) {
676                     del += 1;
677                 } else if del > 0 {
678                     v.swap(i - del, i);
679                 }
680             }
681         }
682         if del > 0 {
683             self.truncate(len - del);
684         }
685     }
686
687     /// Appends an element to the back of a collection.
688     ///
689     /// # Panics
690     ///
691     /// Panics if the number of elements in the vector overflows a `usize`.
692     ///
693     /// # Examples
694     ///
695     /// ```
696     /// let mut vec = vec![1, 2];
697     /// vec.push(3);
698     /// assert_eq!(vec, [1, 2, 3]);
699     /// ```
700     #[inline]
701     #[stable(feature = "rust1", since = "1.0.0")]
702     pub fn push(&mut self, value: T) {
703         // This will panic or abort if we would allocate > isize::MAX bytes
704         // or if the length increment would overflow for zero-sized types.
705         if self.len == self.buf.cap() {
706             self.buf.double();
707         }
708         unsafe {
709             let end = self.as_mut_ptr().offset(self.len as isize);
710             ptr::write(end, value);
711             self.len += 1;
712         }
713     }
714
715     /// Removes the last element from a vector and returns it, or `None` if it
716     /// is empty.
717     ///
718     /// # Examples
719     ///
720     /// ```
721     /// let mut vec = vec![1, 2, 3];
722     /// assert_eq!(vec.pop(), Some(3));
723     /// assert_eq!(vec, [1, 2]);
724     /// ```
725     #[inline]
726     #[stable(feature = "rust1", since = "1.0.0")]
727     pub fn pop(&mut self) -> Option<T> {
728         if self.len == 0 {
729             None
730         } else {
731             unsafe {
732                 self.len -= 1;
733                 Some(ptr::read(self.get_unchecked(self.len())))
734             }
735         }
736     }
737
738     /// Moves all the elements of `other` into `Self`, leaving `other` empty.
739     ///
740     /// # Panics
741     ///
742     /// Panics if the number of elements in the vector overflows a `usize`.
743     ///
744     /// # Examples
745     ///
746     /// ```
747     /// let mut vec = vec![1, 2, 3];
748     /// let mut vec2 = vec![4, 5, 6];
749     /// vec.append(&mut vec2);
750     /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
751     /// assert_eq!(vec2, []);
752     /// ```
753     #[inline]
754     #[stable(feature = "append", since = "1.4.0")]
755     pub fn append(&mut self, other: &mut Self) {
756         self.reserve(other.len());
757         let len = self.len();
758         unsafe {
759             ptr::copy_nonoverlapping(other.as_ptr(), self.get_unchecked_mut(len), other.len());
760         }
761
762         self.len += other.len();
763         unsafe {
764             other.set_len(0);
765         }
766     }
767
768     /// Create a draining iterator that removes the specified range in the vector
769     /// and yields the removed items.
770     ///
771     /// Note 1: The element range is removed even if the iterator is not
772     /// consumed until the end.
773     ///
774     /// Note 2: It is unspecified how many elements are removed from the vector,
775     /// if the `Drain` value is leaked.
776     ///
777     /// # Panics
778     ///
779     /// Panics if the starting point is greater than the end point or if
780     /// the end point is greater than the length of the vector.
781     ///
782     /// # Examples
783     ///
784     /// ```
785     /// let mut v = vec![1, 2, 3];
786     /// let u: Vec<_> = v.drain(1..).collect();
787     /// assert_eq!(v, &[1]);
788     /// assert_eq!(u, &[2, 3]);
789     ///
790     /// // A full range clears the vector
791     /// v.drain(..);
792     /// assert_eq!(v, &[]);
793     /// ```
794     #[stable(feature = "drain", since = "1.6.0")]
795     pub fn drain<R>(&mut self, range: R) -> Drain<T>
796         where R: RangeArgument<usize>
797     {
798         // Memory safety
799         //
800         // When the Drain is first created, it shortens the length of
801         // the source vector to make sure no uninitalized or moved-from elements
802         // are accessible at all if the Drain's destructor never gets to run.
803         //
804         // Drain will ptr::read out the values to remove.
805         // When finished, remaining tail of the vec is copied back to cover
806         // the hole, and the vector length is restored to the new length.
807         //
808         let len = self.len();
809         let start = *range.start().unwrap_or(&0);
810         let end = *range.end().unwrap_or(&len);
811         assert!(start <= end);
812         assert!(end <= len);
813
814         unsafe {
815             // set self.vec length's to start, to be safe in case Drain is leaked
816             self.set_len(start);
817             // Use the borrow in the IterMut to indicate borrowing behavior of the
818             // whole Drain iterator (like &mut T).
819             let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().offset(start as isize),
820                                                         end - start);
821             Drain {
822                 tail_start: end,
823                 tail_len: len - end,
824                 iter: range_slice.iter_mut(),
825                 vec: self as *mut _,
826             }
827         }
828     }
829
830     /// Clears the vector, removing all values.
831     ///
832     /// # Examples
833     ///
834     /// ```
835     /// let mut v = vec![1, 2, 3];
836     ///
837     /// v.clear();
838     ///
839     /// assert!(v.is_empty());
840     /// ```
841     #[inline]
842     #[stable(feature = "rust1", since = "1.0.0")]
843     pub fn clear(&mut self) {
844         self.truncate(0)
845     }
846
847     /// Returns the number of elements in the vector.
848     ///
849     /// # Examples
850     ///
851     /// ```
852     /// let a = vec![1, 2, 3];
853     /// assert_eq!(a.len(), 3);
854     /// ```
855     #[inline]
856     #[stable(feature = "rust1", since = "1.0.0")]
857     pub fn len(&self) -> usize {
858         self.len
859     }
860
861     /// Returns `true` if the vector contains no elements.
862     ///
863     /// # Examples
864     ///
865     /// ```
866     /// let mut v = Vec::new();
867     /// assert!(v.is_empty());
868     ///
869     /// v.push(1);
870     /// assert!(!v.is_empty());
871     /// ```
872     #[stable(feature = "rust1", since = "1.0.0")]
873     pub fn is_empty(&self) -> bool {
874         self.len() == 0
875     }
876
877     /// Splits the collection into two at the given index.
878     ///
879     /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
880     /// and the returned `Self` contains elements `[at, len)`.
881     ///
882     /// Note that the capacity of `self` does not change.
883     ///
884     /// # Panics
885     ///
886     /// Panics if `at > len`.
887     ///
888     /// # Examples
889     ///
890     /// ```
891     /// let mut vec = vec![1,2,3];
892     /// let vec2 = vec.split_off(1);
893     /// assert_eq!(vec, [1]);
894     /// assert_eq!(vec2, [2, 3]);
895     /// ```
896     #[inline]
897     #[stable(feature = "split_off", since = "1.4.0")]
898     pub fn split_off(&mut self, at: usize) -> Self {
899         assert!(at <= self.len(), "`at` out of bounds");
900
901         let other_len = self.len - at;
902         let mut other = Vec::with_capacity(other_len);
903
904         // Unsafely `set_len` and copy items to `other`.
905         unsafe {
906             self.set_len(at);
907             other.set_len(other_len);
908
909             ptr::copy_nonoverlapping(self.as_ptr().offset(at as isize),
910                                      other.as_mut_ptr(),
911                                      other.len());
912         }
913         other
914     }
915 }
916
917 impl<T: Clone> Vec<T> {
918     /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
919     ///
920     /// If `new_len` is greater than `len()`, the `Vec` is extended by the
921     /// difference, with each additional slot filled with `value`.
922     /// If `new_len` is less than `len()`, the `Vec` is simply truncated.
923     ///
924     /// # Examples
925     ///
926     /// ```
927     /// let mut vec = vec!["hello"];
928     /// vec.resize(3, "world");
929     /// assert_eq!(vec, ["hello", "world", "world"]);
930     ///
931     /// let mut vec = vec![1, 2, 3, 4];
932     /// vec.resize(2, 0);
933     /// assert_eq!(vec, [1, 2]);
934     /// ```
935     #[stable(feature = "vec_resize", since = "1.5.0")]
936     pub fn resize(&mut self, new_len: usize, value: T) {
937         let len = self.len();
938
939         if new_len > len {
940             self.extend_with_element(new_len - len, value);
941         } else {
942             self.truncate(new_len);
943         }
944     }
945
946     /// Extend the vector by `n` additional clones of `value`.
947     fn extend_with_element(&mut self, n: usize, value: T) {
948         self.reserve(n);
949
950         unsafe {
951             let len = self.len();
952             let mut ptr = self.as_mut_ptr().offset(len as isize);
953             // Write all elements except the last one
954             for i in 1..n {
955                 ptr::write(ptr, value.clone());
956                 ptr = ptr.offset(1);
957                 // Increment the length in every step in case clone() panics
958                 self.set_len(len + i);
959             }
960
961             if n > 0 {
962                 // We can write the last element directly without cloning needlessly
963                 ptr::write(ptr, value);
964                 self.set_len(len + n);
965             }
966         }
967     }
968
969     /// Clones and appends all elements in a slice to the `Vec`.
970     ///
971     /// Iterates over the slice `other`, clones each element, and then appends
972     /// it to this `Vec`. The `other` vector is traversed in-order.
973     ///
974     /// Note that this function is same as `extend` except that it is
975     /// specialized to work with slices instead. If and when Rust gets
976     /// specialization this function will likely be deprecated (but still
977     /// available).
978     ///
979     /// # Examples
980     ///
981     /// ```
982     /// let mut vec = vec![1];
983     /// vec.extend_from_slice(&[2, 3, 4]);
984     /// assert_eq!(vec, [1, 2, 3, 4]);
985     /// ```
986     #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
987     pub fn extend_from_slice(&mut self, other: &[T]) {
988         self.reserve(other.len());
989
990         for i in 0..other.len() {
991             let len = self.len();
992
993             // Unsafe code so this can be optimised to a memcpy (or something
994             // similarly fast) when T is Copy. LLVM is easily confused, so any
995             // extra operations during the loop can prevent this optimisation.
996             unsafe {
997                 ptr::write(self.get_unchecked_mut(len), other.get_unchecked(i).clone());
998                 self.set_len(len + 1);
999             }
1000         }
1001     }
1002 }
1003
1004 impl<T: PartialEq> Vec<T> {
1005     /// Removes consecutive repeated elements in the vector.
1006     ///
1007     /// If the vector is sorted, this removes all duplicates.
1008     ///
1009     /// # Examples
1010     ///
1011     /// ```
1012     /// let mut vec = vec![1, 2, 2, 3, 2];
1013     ///
1014     /// vec.dedup();
1015     ///
1016     /// assert_eq!(vec, [1, 2, 3, 2]);
1017     /// ```
1018     #[stable(feature = "rust1", since = "1.0.0")]
1019     pub fn dedup(&mut self) {
1020         unsafe {
1021             // Although we have a mutable reference to `self`, we cannot make
1022             // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
1023             // must ensure that the vector is in a valid state at all time.
1024             //
1025             // The way that we handle this is by using swaps; we iterate
1026             // over all the elements, swapping as we go so that at the end
1027             // the elements we wish to keep are in the front, and those we
1028             // wish to reject are at the back. We can then truncate the
1029             // vector. This operation is still O(n).
1030             //
1031             // Example: We start in this state, where `r` represents "next
1032             // read" and `w` represents "next_write`.
1033             //
1034             //           r
1035             //     +---+---+---+---+---+---+
1036             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1037             //     +---+---+---+---+---+---+
1038             //           w
1039             //
1040             // Comparing self[r] against self[w-1], this is not a duplicate, so
1041             // we swap self[r] and self[w] (no effect as r==w) and then increment both
1042             // r and w, leaving us with:
1043             //
1044             //               r
1045             //     +---+---+---+---+---+---+
1046             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1047             //     +---+---+---+---+---+---+
1048             //               w
1049             //
1050             // Comparing self[r] against self[w-1], this value is a duplicate,
1051             // so we increment `r` but leave everything else unchanged:
1052             //
1053             //                   r
1054             //     +---+---+---+---+---+---+
1055             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1056             //     +---+---+---+---+---+---+
1057             //               w
1058             //
1059             // Comparing self[r] against self[w-1], this is not a duplicate,
1060             // so swap self[r] and self[w] and advance r and w:
1061             //
1062             //                       r
1063             //     +---+---+---+---+---+---+
1064             //     | 0 | 1 | 2 | 1 | 3 | 3 |
1065             //     +---+---+---+---+---+---+
1066             //                   w
1067             //
1068             // Not a duplicate, repeat:
1069             //
1070             //                           r
1071             //     +---+---+---+---+---+---+
1072             //     | 0 | 1 | 2 | 3 | 1 | 3 |
1073             //     +---+---+---+---+---+---+
1074             //                       w
1075             //
1076             // Duplicate, advance r. End of vec. Truncate to w.
1077
1078             let ln = self.len();
1079             if ln <= 1 {
1080                 return;
1081             }
1082
1083             // Avoid bounds checks by using raw pointers.
1084             let p = self.as_mut_ptr();
1085             let mut r: usize = 1;
1086             let mut w: usize = 1;
1087
1088             while r < ln {
1089                 let p_r = p.offset(r as isize);
1090                 let p_wm1 = p.offset((w - 1) as isize);
1091                 if *p_r != *p_wm1 {
1092                     if r != w {
1093                         let p_w = p_wm1.offset(1);
1094                         mem::swap(&mut *p_r, &mut *p_w);
1095                     }
1096                     w += 1;
1097                 }
1098                 r += 1;
1099             }
1100
1101             self.truncate(w);
1102         }
1103     }
1104 }
1105
1106 ////////////////////////////////////////////////////////////////////////////////
1107 // Internal methods and functions
1108 ////////////////////////////////////////////////////////////////////////////////
1109
1110 #[doc(hidden)]
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1113     let mut v = Vec::with_capacity(n);
1114     v.extend_with_element(n, elem);
1115     v
1116 }
1117
1118 ////////////////////////////////////////////////////////////////////////////////
1119 // Common trait implementations for Vec
1120 ////////////////////////////////////////////////////////////////////////////////
1121
1122 #[stable(feature = "rust1", since = "1.0.0")]
1123 impl<T: Clone> Clone for Vec<T> {
1124     #[cfg(not(test))]
1125     fn clone(&self) -> Vec<T> {
1126         <[T]>::to_vec(&**self)
1127     }
1128
1129     // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1130     // required for this method definition, is not available. Instead use the
1131     // `slice::to_vec`  function which is only available with cfg(test)
1132     // NB see the slice::hack module in slice.rs for more information
1133     #[cfg(test)]
1134     fn clone(&self) -> Vec<T> {
1135         ::slice::to_vec(&**self)
1136     }
1137
1138     fn clone_from(&mut self, other: &Vec<T>) {
1139         // drop anything in self that will not be overwritten
1140         self.truncate(other.len());
1141         let len = self.len();
1142
1143         // reuse the contained values' allocations/resources.
1144         self.clone_from_slice(&other[..len]);
1145
1146         // self.len <= other.len due to the truncate above, so the
1147         // slice here is always in-bounds.
1148         self.extend_from_slice(&other[len..]);
1149     }
1150 }
1151
1152 #[stable(feature = "rust1", since = "1.0.0")]
1153 impl<T: Hash> Hash for Vec<T> {
1154     #[inline]
1155     fn hash<H: hash::Hasher>(&self, state: &mut H) {
1156         Hash::hash(&**self, state)
1157     }
1158 }
1159
1160 #[stable(feature = "rust1", since = "1.0.0")]
1161 impl<T> Index<usize> for Vec<T> {
1162     type Output = T;
1163
1164     #[inline]
1165     fn index(&self, index: usize) -> &T {
1166         // NB built-in indexing via `&[T]`
1167         &(**self)[index]
1168     }
1169 }
1170
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 impl<T> IndexMut<usize> for Vec<T> {
1173     #[inline]
1174     fn index_mut(&mut self, index: usize) -> &mut T {
1175         // NB built-in indexing via `&mut [T]`
1176         &mut (**self)[index]
1177     }
1178 }
1179
1180
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
1183     type Output = [T];
1184
1185     #[inline]
1186     fn index(&self, index: ops::Range<usize>) -> &[T] {
1187         Index::index(&**self, index)
1188     }
1189 }
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
1192     type Output = [T];
1193
1194     #[inline]
1195     fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
1196         Index::index(&**self, index)
1197     }
1198 }
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
1201     type Output = [T];
1202
1203     #[inline]
1204     fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
1205         Index::index(&**self, index)
1206     }
1207 }
1208 #[stable(feature = "rust1", since = "1.0.0")]
1209 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1210     type Output = [T];
1211
1212     #[inline]
1213     fn index(&self, _index: ops::RangeFull) -> &[T] {
1214         self
1215     }
1216 }
1217 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1218 impl<T> ops::Index<ops::RangeInclusive<usize>> for Vec<T> {
1219     type Output = [T];
1220
1221     #[inline]
1222     fn index(&self, index: ops::RangeInclusive<usize>) -> &[T] {
1223         Index::index(&**self, index)
1224     }
1225 }
1226 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1227 impl<T> ops::Index<ops::RangeToInclusive<usize>> for Vec<T> {
1228     type Output = [T];
1229
1230     #[inline]
1231     fn index(&self, index: ops::RangeToInclusive<usize>) -> &[T] {
1232         Index::index(&**self, index)
1233     }
1234 }
1235
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
1238     #[inline]
1239     fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
1240         IndexMut::index_mut(&mut **self, index)
1241     }
1242 }
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
1245     #[inline]
1246     fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
1247         IndexMut::index_mut(&mut **self, index)
1248     }
1249 }
1250 #[stable(feature = "rust1", since = "1.0.0")]
1251 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
1252     #[inline]
1253     fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
1254         IndexMut::index_mut(&mut **self, index)
1255     }
1256 }
1257 #[stable(feature = "rust1", since = "1.0.0")]
1258 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
1259     #[inline]
1260     fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] {
1261         self
1262     }
1263 }
1264 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1265 impl<T> ops::IndexMut<ops::RangeInclusive<usize>> for Vec<T> {
1266     #[inline]
1267     fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut [T] {
1268         IndexMut::index_mut(&mut **self, index)
1269     }
1270 }
1271 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1272 impl<T> ops::IndexMut<ops::RangeToInclusive<usize>> for Vec<T> {
1273     #[inline]
1274     fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut [T] {
1275         IndexMut::index_mut(&mut **self, index)
1276     }
1277 }
1278
1279 #[stable(feature = "rust1", since = "1.0.0")]
1280 impl<T> ops::Deref for Vec<T> {
1281     type Target = [T];
1282
1283     fn deref(&self) -> &[T] {
1284         unsafe {
1285             let p = self.buf.ptr();
1286             assume(!p.is_null());
1287             slice::from_raw_parts(p, self.len)
1288         }
1289     }
1290 }
1291
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 impl<T> ops::DerefMut for Vec<T> {
1294     fn deref_mut(&mut self) -> &mut [T] {
1295         unsafe {
1296             let ptr = self.buf.ptr();
1297             assume(!ptr.is_null());
1298             slice::from_raw_parts_mut(ptr, self.len)
1299         }
1300     }
1301 }
1302
1303 #[stable(feature = "rust1", since = "1.0.0")]
1304 impl<T> FromIterator<T> for Vec<T> {
1305     #[inline]
1306     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
1307         // Unroll the first iteration, as the vector is going to be
1308         // expanded on this iteration in every case when the iterable is not
1309         // empty, but the loop in extend_desugared() is not going to see the
1310         // vector being full in the few subsequent loop iterations.
1311         // So we get better branch prediction.
1312         let mut iterator = iter.into_iter();
1313         let mut vector = match iterator.next() {
1314             None => return Vec::new(),
1315             Some(element) => {
1316                 let (lower, _) = iterator.size_hint();
1317                 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1318                 unsafe {
1319                     ptr::write(vector.get_unchecked_mut(0), element);
1320                     vector.set_len(1);
1321                 }
1322                 vector
1323             }
1324         };
1325         vector.extend_desugared(iterator);
1326         vector
1327     }
1328 }
1329
1330 #[stable(feature = "rust1", since = "1.0.0")]
1331 impl<T> IntoIterator for Vec<T> {
1332     type Item = T;
1333     type IntoIter = IntoIter<T>;
1334
1335     /// Creates a consuming iterator, that is, one that moves each value out of
1336     /// the vector (from start to end). The vector cannot be used after calling
1337     /// this.
1338     ///
1339     /// # Examples
1340     ///
1341     /// ```
1342     /// let v = vec!["a".to_string(), "b".to_string()];
1343     /// for s in v.into_iter() {
1344     ///     // s has type String, not &String
1345     ///     println!("{}", s);
1346     /// }
1347     /// ```
1348     #[inline]
1349     fn into_iter(mut self) -> IntoIter<T> {
1350         unsafe {
1351             let ptr = self.as_mut_ptr();
1352             assume(!ptr.is_null());
1353             let begin = ptr as *const T;
1354             let end = if mem::size_of::<T>() == 0 {
1355                 arith_offset(ptr as *const i8, self.len() as isize) as *const T
1356             } else {
1357                 ptr.offset(self.len() as isize) as *const T
1358             };
1359             let buf = ptr::read(&self.buf);
1360             mem::forget(self);
1361             IntoIter {
1362                 _buf: buf,
1363                 ptr: begin,
1364                 end: end,
1365             }
1366         }
1367     }
1368 }
1369
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 impl<'a, T> IntoIterator for &'a Vec<T> {
1372     type Item = &'a T;
1373     type IntoIter = slice::Iter<'a, T>;
1374
1375     fn into_iter(self) -> slice::Iter<'a, T> {
1376         self.iter()
1377     }
1378 }
1379
1380 #[stable(feature = "rust1", since = "1.0.0")]
1381 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1382     type Item = &'a mut T;
1383     type IntoIter = slice::IterMut<'a, T>;
1384
1385     fn into_iter(mut self) -> slice::IterMut<'a, T> {
1386         self.iter_mut()
1387     }
1388 }
1389
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 impl<T> Extend<T> for Vec<T> {
1392     #[inline]
1393     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1394         <Self as SpecExtend<I>>::spec_extend(self, iter);
1395     }
1396 }
1397
1398 impl<I: IntoIterator> SpecExtend<I> for Vec<I::Item> {
1399     default fn spec_extend(&mut self, iter: I) {
1400         self.extend_desugared(iter.into_iter())
1401     }
1402 }
1403
1404 impl<T> SpecExtend<Vec<T>> for Vec<T> {
1405     fn spec_extend(&mut self, ref mut other: Vec<T>) {
1406         self.append(other);
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 ////////////////////////////////////////////////////////////////////////////////
1602 // Iterators
1603 ////////////////////////////////////////////////////////////////////////////////
1604
1605 /// An iterator that moves out of a vector.
1606 #[stable(feature = "rust1", since = "1.0.0")]
1607 pub struct IntoIter<T> {
1608     _buf: RawVec<T>,
1609     ptr: *const T,
1610     end: *const T,
1611 }
1612
1613 #[stable(feature = "rust1", since = "1.0.0")]
1614 unsafe impl<T: Send> Send for IntoIter<T> {}
1615 #[stable(feature = "rust1", since = "1.0.0")]
1616 unsafe impl<T: Sync> Sync for IntoIter<T> {}
1617
1618 #[stable(feature = "rust1", since = "1.0.0")]
1619 impl<T> Iterator for IntoIter<T> {
1620     type Item = T;
1621
1622     #[inline]
1623     fn next(&mut self) -> Option<T> {
1624         unsafe {
1625             if self.ptr == self.end {
1626                 None
1627             } else {
1628                 if mem::size_of::<T>() == 0 {
1629                     // purposefully don't use 'ptr.offset' because for
1630                     // vectors with 0-size elements this would return the
1631                     // same pointer.
1632                     self.ptr = arith_offset(self.ptr as *const i8, 1) as *const T;
1633
1634                     // Use a non-null pointer value
1635                     Some(ptr::read(EMPTY as *mut T))
1636                 } else {
1637                     let old = self.ptr;
1638                     self.ptr = self.ptr.offset(1);
1639
1640                     Some(ptr::read(old))
1641                 }
1642             }
1643         }
1644     }
1645
1646     #[inline]
1647     fn size_hint(&self) -> (usize, Option<usize>) {
1648         let diff = (self.end as usize) - (self.ptr as usize);
1649         let size = mem::size_of::<T>();
1650         let exact = diff /
1651                     (if size == 0 {
1652                          1
1653                      } else {
1654                          size
1655                      });
1656         (exact, Some(exact))
1657     }
1658
1659     #[inline]
1660     fn count(self) -> usize {
1661         self.size_hint().0
1662     }
1663 }
1664
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 impl<T> DoubleEndedIterator for IntoIter<T> {
1667     #[inline]
1668     fn next_back(&mut self) -> Option<T> {
1669         unsafe {
1670             if self.end == self.ptr {
1671                 None
1672             } else {
1673                 if mem::size_of::<T>() == 0 {
1674                     // See above for why 'ptr.offset' isn't used
1675                     self.end = arith_offset(self.end as *const i8, -1) as *const T;
1676
1677                     // Use a non-null pointer value
1678                     Some(ptr::read(EMPTY as *mut T))
1679                 } else {
1680                     self.end = self.end.offset(-1);
1681
1682                     Some(ptr::read(self.end))
1683                 }
1684             }
1685         }
1686     }
1687 }
1688
1689 #[stable(feature = "rust1", since = "1.0.0")]
1690 impl<T> ExactSizeIterator for IntoIter<T> {}
1691
1692 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
1693 impl<T: Clone> Clone for IntoIter<T> {
1694     fn clone(&self) -> IntoIter<T> {
1695         unsafe {
1696             slice::from_raw_parts(self.ptr, self.len()).to_owned().into_iter()
1697         }
1698     }
1699 }
1700
1701 #[stable(feature = "rust1", since = "1.0.0")]
1702 impl<T> Drop for IntoIter<T> {
1703     #[unsafe_destructor_blind_to_params]
1704     fn drop(&mut self) {
1705         // destroy the remaining elements
1706         for _x in self {}
1707
1708         // RawVec handles deallocation
1709     }
1710 }
1711
1712 /// A draining iterator for `Vec<T>`.
1713 #[stable(feature = "drain", since = "1.6.0")]
1714 pub struct Drain<'a, T: 'a> {
1715     /// Index of tail to preserve
1716     tail_start: usize,
1717     /// Length of tail
1718     tail_len: usize,
1719     /// Current remaining range to remove
1720     iter: slice::IterMut<'a, T>,
1721     vec: *mut Vec<T>,
1722 }
1723
1724 #[stable(feature = "drain", since = "1.6.0")]
1725 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1726 #[stable(feature = "drain", since = "1.6.0")]
1727 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1728
1729 #[stable(feature = "rust1", since = "1.0.0")]
1730 impl<'a, T> Iterator for Drain<'a, T> {
1731     type Item = T;
1732
1733     #[inline]
1734     fn next(&mut self) -> Option<T> {
1735         self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
1736     }
1737
1738     fn size_hint(&self) -> (usize, Option<usize>) {
1739         self.iter.size_hint()
1740     }
1741 }
1742
1743 #[stable(feature = "rust1", since = "1.0.0")]
1744 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1745     #[inline]
1746     fn next_back(&mut self) -> Option<T> {
1747         self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
1748     }
1749 }
1750
1751 #[stable(feature = "rust1", since = "1.0.0")]
1752 impl<'a, T> Drop for Drain<'a, T> {
1753     fn drop(&mut self) {
1754         // exhaust self first
1755         while let Some(_) = self.next() {}
1756
1757         if self.tail_len > 0 {
1758             unsafe {
1759                 let source_vec = &mut *self.vec;
1760                 // memmove back untouched tail, update to new length
1761                 let start = source_vec.len();
1762                 let tail = self.tail_start;
1763                 let src = source_vec.as_ptr().offset(tail as isize);
1764                 let dst = source_vec.as_mut_ptr().offset(start as isize);
1765                 ptr::copy(src, dst, self.tail_len);
1766                 source_vec.set_len(start + self.tail_len);
1767             }
1768         }
1769     }
1770 }
1771
1772
1773 #[stable(feature = "rust1", since = "1.0.0")]
1774 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}