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