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