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