]> git.lizzy.rs Git - rust.git/blob - src/libcollections/vec.rs
rustfmt libcollections
[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, Deref};
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     /// #![feature(drain)]
743     ///
744     /// // Draining using `..` clears the whole vector.
745     /// let mut v = vec![1, 2, 3];
746     /// let u: Vec<_> = v.drain(..).collect();
747     /// assert_eq!(v, &[]);
748     /// assert_eq!(u, &[1, 2, 3]);
749     /// ```
750     #[unstable(feature = "drain",
751                reason = "recently added, matches RFC",
752                issue = "27711")]
753     pub fn drain<R>(&mut self, range: R) -> Drain<T>
754         where R: RangeArgument<usize>
755     {
756         // Memory safety
757         //
758         // When the Drain is first created, it shortens the length of
759         // the source vector to make sure no uninitalized or moved-from elements
760         // are accessible at all if the Drain's destructor never gets to run.
761         //
762         // Drain will ptr::read out the values to remove.
763         // When finished, remaining tail of the vec is copied back to cover
764         // the hole, and the vector length is restored to the new length.
765         //
766         let len = self.len();
767         let start = *range.start().unwrap_or(&0);
768         let end = *range.end().unwrap_or(&len);
769         assert!(start <= end);
770         assert!(end <= len);
771
772         unsafe {
773             // set self.vec length's to start, to be safe in case Drain is leaked
774             self.set_len(start);
775             // Use the borrow in the IterMut to indicate borrowing behavior of the
776             // whole Drain iterator (like &mut T).
777             let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().offset(start as isize),
778                                                         end - start);
779             Drain {
780                 tail_start: end,
781                 tail_len: len - end,
782                 iter: range_slice.iter_mut(),
783                 vec: self as *mut _,
784             }
785         }
786     }
787
788     /// Clears the vector, removing all values.
789     ///
790     /// # Examples
791     ///
792     /// ```
793     /// let mut v = vec![1, 2, 3];
794     ///
795     /// v.clear();
796     ///
797     /// assert!(v.is_empty());
798     /// ```
799     #[inline]
800     #[stable(feature = "rust1", since = "1.0.0")]
801     pub fn clear(&mut self) {
802         self.truncate(0)
803     }
804
805     /// Returns the number of elements in the vector.
806     ///
807     /// # Examples
808     ///
809     /// ```
810     /// let a = vec![1, 2, 3];
811     /// assert_eq!(a.len(), 3);
812     /// ```
813     #[inline]
814     #[stable(feature = "rust1", since = "1.0.0")]
815     pub fn len(&self) -> usize {
816         self.len
817     }
818
819     /// Returns `true` if the vector contains no elements.
820     ///
821     /// # Examples
822     ///
823     /// ```
824     /// let mut v = Vec::new();
825     /// assert!(v.is_empty());
826     ///
827     /// v.push(1);
828     /// assert!(!v.is_empty());
829     /// ```
830     #[stable(feature = "rust1", since = "1.0.0")]
831     pub fn is_empty(&self) -> bool {
832         self.len() == 0
833     }
834
835     /// Splits the collection into two at the given index.
836     ///
837     /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
838     /// and the returned `Self` contains elements `[at, len)`.
839     ///
840     /// Note that the capacity of `self` does not change.
841     ///
842     /// # Panics
843     ///
844     /// Panics if `at > len`.
845     ///
846     /// # Examples
847     ///
848     /// ```
849     /// let mut vec = vec![1,2,3];
850     /// let vec2 = vec.split_off(1);
851     /// assert_eq!(vec, [1]);
852     /// assert_eq!(vec2, [2, 3]);
853     /// ```
854     #[inline]
855     #[stable(feature = "split_off", since = "1.4.0")]
856     pub fn split_off(&mut self, at: usize) -> Self {
857         assert!(at <= self.len(), "`at` out of bounds");
858
859         let other_len = self.len - at;
860         let mut other = Vec::with_capacity(other_len);
861
862         // Unsafely `set_len` and copy items to `other`.
863         unsafe {
864             self.set_len(at);
865             other.set_len(other_len);
866
867             ptr::copy_nonoverlapping(self.as_ptr().offset(at as isize),
868                                      other.as_mut_ptr(),
869                                      other.len());
870         }
871         other
872     }
873 }
874
875 impl<T: Clone> Vec<T> {
876     /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
877     ///
878     /// If `new_len` is greater than `len()`, the `Vec` is extended by the
879     /// difference, with each additional slot filled with `value`.
880     /// If `new_len` is less than `len()`, the `Vec` is simply truncated.
881     ///
882     /// # Examples
883     ///
884     /// ```
885     /// let mut vec = vec!["hello"];
886     /// vec.resize(3, "world");
887     /// assert_eq!(vec, ["hello", "world", "world"]);
888     ///
889     /// let mut vec = vec![1, 2, 3, 4];
890     /// vec.resize(2, 0);
891     /// assert_eq!(vec, [1, 2]);
892     /// ```
893     #[stable(feature = "vec_resize", since = "1.5.0")]
894     pub fn resize(&mut self, new_len: usize, value: T) {
895         let len = self.len();
896
897         if new_len > len {
898             self.extend_with_element(new_len - len, value);
899         } else {
900             self.truncate(new_len);
901         }
902     }
903
904     /// Extend the vector by `n` additional clones of `value`.
905     fn extend_with_element(&mut self, n: usize, value: T) {
906         self.reserve(n);
907
908         unsafe {
909             let len = self.len();
910             let mut ptr = self.as_mut_ptr().offset(len as isize);
911             // Write all elements except the last one
912             for i in 1..n {
913                 ptr::write(ptr, value.clone());
914                 ptr = ptr.offset(1);
915                 // Increment the length in every step in case clone() panics
916                 self.set_len(len + i);
917             }
918
919             if n > 0 {
920                 // We can write the last element directly without cloning needlessly
921                 ptr::write(ptr, value);
922                 self.set_len(len + n);
923             }
924         }
925     }
926
927     /// Appends all elements in a slice to the `Vec`.
928     ///
929     /// Iterates over the slice `other`, clones each element, and then appends
930     /// it to this `Vec`. The `other` vector is traversed in-order.
931     ///
932     /// # Examples
933     ///
934     /// ```
935     /// #![feature(vec_push_all)]
936     ///
937     /// let mut vec = vec![1];
938     /// vec.push_all(&[2, 3, 4]);
939     /// assert_eq!(vec, [1, 2, 3, 4]);
940     /// ```
941     #[inline]
942     #[unstable(feature = "vec_push_all",
943                reason = "likely to be replaced by a more optimized extend",
944                issue = "27744")]
945     pub fn push_all(&mut self, other: &[T]) {
946         self.reserve(other.len());
947
948         for i in 0..other.len() {
949             let len = self.len();
950
951             // Unsafe code so this can be optimised to a memcpy (or something
952             // similarly fast) when T is Copy. LLVM is easily confused, so any
953             // extra operations during the loop can prevent this optimisation.
954             unsafe {
955                 ptr::write(self.get_unchecked_mut(len), other.get_unchecked(i).clone());
956                 self.set_len(len + 1);
957             }
958         }
959     }
960 }
961
962 impl<T: PartialEq> Vec<T> {
963     /// Removes consecutive repeated elements in the vector.
964     ///
965     /// If the vector is sorted, this removes all duplicates.
966     ///
967     /// # Examples
968     ///
969     /// ```
970     /// let mut vec = vec![1, 2, 2, 3, 2];
971     ///
972     /// vec.dedup();
973     ///
974     /// assert_eq!(vec, [1, 2, 3, 2]);
975     /// ```
976     #[stable(feature = "rust1", since = "1.0.0")]
977     pub fn dedup(&mut self) {
978         unsafe {
979             // Although we have a mutable reference to `self`, we cannot make
980             // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
981             // must ensure that the vector is in a valid state at all time.
982             //
983             // The way that we handle this is by using swaps; we iterate
984             // over all the elements, swapping as we go so that at the end
985             // the elements we wish to keep are in the front, and those we
986             // wish to reject are at the back. We can then truncate the
987             // vector. This operation is still O(n).
988             //
989             // Example: We start in this state, where `r` represents "next
990             // read" and `w` represents "next_write`.
991             //
992             //           r
993             //     +---+---+---+---+---+---+
994             //     | 0 | 1 | 1 | 2 | 3 | 3 |
995             //     +---+---+---+---+---+---+
996             //           w
997             //
998             // Comparing self[r] against self[w-1], this is not a duplicate, so
999             // we swap self[r] and self[w] (no effect as r==w) and then increment both
1000             // r and w, leaving us with:
1001             //
1002             //               r
1003             //     +---+---+---+---+---+---+
1004             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1005             //     +---+---+---+---+---+---+
1006             //               w
1007             //
1008             // Comparing self[r] against self[w-1], this value is a duplicate,
1009             // so we increment `r` but leave everything else unchanged:
1010             //
1011             //                   r
1012             //     +---+---+---+---+---+---+
1013             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1014             //     +---+---+---+---+---+---+
1015             //               w
1016             //
1017             // Comparing self[r] against self[w-1], this is not a duplicate,
1018             // so swap self[r] and self[w] and advance r and w:
1019             //
1020             //                       r
1021             //     +---+---+---+---+---+---+
1022             //     | 0 | 1 | 2 | 1 | 3 | 3 |
1023             //     +---+---+---+---+---+---+
1024             //                   w
1025             //
1026             // Not a duplicate, repeat:
1027             //
1028             //                           r
1029             //     +---+---+---+---+---+---+
1030             //     | 0 | 1 | 2 | 3 | 1 | 3 |
1031             //     +---+---+---+---+---+---+
1032             //                       w
1033             //
1034             // Duplicate, advance r. End of vec. Truncate to w.
1035
1036             let ln = self.len();
1037             if ln <= 1 {
1038                 return;
1039             }
1040
1041             // Avoid bounds checks by using raw pointers.
1042             let p = self.as_mut_ptr();
1043             let mut r: usize = 1;
1044             let mut w: usize = 1;
1045
1046             while r < ln {
1047                 let p_r = p.offset(r as isize);
1048                 let p_wm1 = p.offset((w - 1) as isize);
1049                 if *p_r != *p_wm1 {
1050                     if r != w {
1051                         let p_w = p_wm1.offset(1);
1052                         mem::swap(&mut *p_r, &mut *p_w);
1053                     }
1054                     w += 1;
1055                 }
1056                 r += 1;
1057             }
1058
1059             self.truncate(w);
1060         }
1061     }
1062 }
1063
1064 ////////////////////////////////////////////////////////////////////////////////
1065 // Internal methods and functions
1066 ////////////////////////////////////////////////////////////////////////////////
1067
1068 #[doc(hidden)]
1069 #[stable(feature = "rust1", since = "1.0.0")]
1070 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1071     let mut v = Vec::with_capacity(n);
1072     v.extend_with_element(n, elem);
1073     v
1074 }
1075
1076 ////////////////////////////////////////////////////////////////////////////////
1077 // Common trait implementations for Vec
1078 ////////////////////////////////////////////////////////////////////////////////
1079
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 impl<T: Clone> Clone for Vec<T> {
1082     #[cfg(not(test))]
1083     fn clone(&self) -> Vec<T> {
1084         <[T]>::to_vec(&**self)
1085     }
1086
1087     // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1088     // required for this method definition, is not available. Instead use the
1089     // `slice::to_vec`  function which is only available with cfg(test)
1090     // NB see the slice::hack module in slice.rs for more information
1091     #[cfg(test)]
1092     fn clone(&self) -> Vec<T> {
1093         ::slice::to_vec(&**self)
1094     }
1095
1096     fn clone_from(&mut self, other: &Vec<T>) {
1097         // drop anything in self that will not be overwritten
1098         self.truncate(other.len());
1099         let len = self.len();
1100
1101         // reuse the contained values' allocations/resources.
1102         self.clone_from_slice(&other[..len]);
1103
1104         // self.len <= other.len due to the truncate above, so the
1105         // slice here is always in-bounds.
1106         self.push_all(&other[len..]);
1107     }
1108 }
1109
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 impl<T: Hash> Hash for Vec<T> {
1112     #[inline]
1113     fn hash<H: hash::Hasher>(&self, state: &mut H) {
1114         Hash::hash(&**self, state)
1115     }
1116 }
1117
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 impl<T> Index<usize> for Vec<T> {
1120     type Output = T;
1121
1122     #[inline]
1123     fn index(&self, index: usize) -> &T {
1124         // NB built-in indexing via `&[T]`
1125         &(**self)[index]
1126     }
1127 }
1128
1129 #[stable(feature = "rust1", since = "1.0.0")]
1130 impl<T> IndexMut<usize> for Vec<T> {
1131     #[inline]
1132     fn index_mut(&mut self, index: usize) -> &mut T {
1133         // NB built-in indexing via `&mut [T]`
1134         &mut (**self)[index]
1135     }
1136 }
1137
1138
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
1141     type Output = [T];
1142
1143     #[inline]
1144     fn index(&self, index: ops::Range<usize>) -> &[T] {
1145         Index::index(&**self, index)
1146     }
1147 }
1148 #[stable(feature = "rust1", since = "1.0.0")]
1149 impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
1150     type Output = [T];
1151
1152     #[inline]
1153     fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
1154         Index::index(&**self, index)
1155     }
1156 }
1157 #[stable(feature = "rust1", since = "1.0.0")]
1158 impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
1159     type Output = [T];
1160
1161     #[inline]
1162     fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
1163         Index::index(&**self, index)
1164     }
1165 }
1166 #[stable(feature = "rust1", since = "1.0.0")]
1167 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1168     type Output = [T];
1169
1170     #[inline]
1171     fn index(&self, _index: ops::RangeFull) -> &[T] {
1172         self
1173     }
1174 }
1175
1176 #[stable(feature = "rust1", since = "1.0.0")]
1177 impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
1178     #[inline]
1179     fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
1180         IndexMut::index_mut(&mut **self, index)
1181     }
1182 }
1183 #[stable(feature = "rust1", since = "1.0.0")]
1184 impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
1185     #[inline]
1186     fn index_mut(&mut self, index: ops::RangeTo<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::RangeFrom<usize>> for Vec<T> {
1192     #[inline]
1193     fn index_mut(&mut self, index: ops::RangeFrom<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::RangeFull> for Vec<T> {
1199     #[inline]
1200     fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] {
1201         self
1202     }
1203 }
1204
1205 #[stable(feature = "rust1", since = "1.0.0")]
1206 impl<T> ops::Deref for Vec<T> {
1207     type Target = [T];
1208
1209     fn deref(&self) -> &[T] {
1210         unsafe {
1211             let p = self.buf.ptr();
1212             assume(!p.is_null());
1213             slice::from_raw_parts(p, self.len)
1214         }
1215     }
1216 }
1217
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 impl<T> ops::DerefMut for Vec<T> {
1220     fn deref_mut(&mut self) -> &mut [T] {
1221         unsafe {
1222             let ptr = self.buf.ptr();
1223             assume(!ptr.is_null());
1224             slice::from_raw_parts_mut(ptr, self.len)
1225         }
1226     }
1227 }
1228
1229 #[stable(feature = "rust1", since = "1.0.0")]
1230 impl<T> FromIterator<T> for Vec<T> {
1231     #[inline]
1232     fn from_iter<I: IntoIterator<Item = T>>(iterable: I) -> Vec<T> {
1233         // Unroll the first iteration, as the vector is going to be
1234         // expanded on this iteration in every case when the iterable is not
1235         // empty, but the loop in extend_desugared() is not going to see the
1236         // vector being full in the few subsequent loop iterations.
1237         // So we get better branch prediction.
1238         let mut iterator = iterable.into_iter();
1239         let mut vector = match iterator.next() {
1240             None => return Vec::new(),
1241             Some(element) => {
1242                 let (lower, _) = iterator.size_hint();
1243                 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1244                 unsafe {
1245                     ptr::write(vector.get_unchecked_mut(0), element);
1246                     vector.set_len(1);
1247                 }
1248                 vector
1249             }
1250         };
1251         vector.extend_desugared(iterator);
1252         vector
1253     }
1254 }
1255
1256 #[stable(feature = "rust1", since = "1.0.0")]
1257 impl<T> IntoIterator for Vec<T> {
1258     type Item = T;
1259     type IntoIter = IntoIter<T>;
1260
1261     /// Creates a consuming iterator, that is, one that moves each value out of
1262     /// the vector (from start to end). The vector cannot be used after calling
1263     /// this.
1264     ///
1265     /// # Examples
1266     ///
1267     /// ```
1268     /// let v = vec!["a".to_string(), "b".to_string()];
1269     /// for s in v.into_iter() {
1270     ///     // s has type String, not &String
1271     ///     println!("{}", s);
1272     /// }
1273     /// ```
1274     #[inline]
1275     fn into_iter(mut self) -> IntoIter<T> {
1276         unsafe {
1277             let ptr = self.as_mut_ptr();
1278             assume(!ptr.is_null());
1279             let begin = ptr as *const T;
1280             let end = if mem::size_of::<T>() == 0 {
1281                 arith_offset(ptr as *const i8, self.len() as isize) as *const T
1282             } else {
1283                 ptr.offset(self.len() as isize) as *const T
1284             };
1285             let buf = ptr::read(&self.buf);
1286             mem::forget(self);
1287             IntoIter {
1288                 _buf: buf,
1289                 ptr: begin,
1290                 end: end,
1291             }
1292         }
1293     }
1294 }
1295
1296 #[stable(feature = "rust1", since = "1.0.0")]
1297 impl<'a, T> IntoIterator for &'a Vec<T> {
1298     type Item = &'a T;
1299     type IntoIter = slice::Iter<'a, T>;
1300
1301     fn into_iter(self) -> slice::Iter<'a, T> {
1302         self.iter()
1303     }
1304 }
1305
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1308     type Item = &'a mut T;
1309     type IntoIter = slice::IterMut<'a, T>;
1310
1311     fn into_iter(mut self) -> slice::IterMut<'a, T> {
1312         self.iter_mut()
1313     }
1314 }
1315
1316 #[stable(feature = "rust1", since = "1.0.0")]
1317 impl<T> Extend<T> for Vec<T> {
1318     #[inline]
1319     fn extend<I: IntoIterator<Item = T>>(&mut self, iterable: I) {
1320         self.extend_desugared(iterable.into_iter())
1321     }
1322 }
1323
1324 impl<T> Vec<T> {
1325     fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
1326         // This function should be the moral equivalent of:
1327         //
1328         //      for item in iterator {
1329         //          self.push(item);
1330         //      }
1331         while let Some(element) = iterator.next() {
1332             let len = self.len();
1333             if len == self.capacity() {
1334                 let (lower, _) = iterator.size_hint();
1335                 self.reserve(lower.saturating_add(1));
1336             }
1337             unsafe {
1338                 ptr::write(self.get_unchecked_mut(len), element);
1339                 // NB can't overflow since we would have had to alloc the address space
1340                 self.set_len(len + 1);
1341             }
1342         }
1343     }
1344 }
1345
1346 #[stable(feature = "extend_ref", since = "1.2.0")]
1347 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
1348     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1349         self.extend(iter.into_iter().cloned());
1350     }
1351 }
1352
1353 __impl_slice_eq1! { Vec<A>, Vec<B> }
1354 __impl_slice_eq1! { Vec<A>, &'b [B] }
1355 __impl_slice_eq1! { Vec<A>, &'b mut [B] }
1356 __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone }
1357 __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone }
1358 __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone }
1359
1360 macro_rules! array_impls {
1361     ($($N: expr)+) => {
1362         $(
1363             // NOTE: some less important impls are omitted to reduce code bloat
1364             __impl_slice_eq1! { Vec<A>, [B; $N] }
1365             __impl_slice_eq1! { Vec<A>, &'b [B; $N] }
1366             // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
1367             // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
1368             // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
1369             // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
1370         )+
1371     }
1372 }
1373
1374 array_impls! {
1375      0  1  2  3  4  5  6  7  8  9
1376     10 11 12 13 14 15 16 17 18 19
1377     20 21 22 23 24 25 26 27 28 29
1378     30 31 32
1379 }
1380
1381 #[stable(feature = "rust1", since = "1.0.0")]
1382 impl<T: PartialOrd> PartialOrd for Vec<T> {
1383     #[inline]
1384     fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1385         PartialOrd::partial_cmp(&**self, &**other)
1386     }
1387 }
1388
1389 #[stable(feature = "rust1", since = "1.0.0")]
1390 impl<T: Eq> Eq for Vec<T> {}
1391
1392 #[stable(feature = "rust1", since = "1.0.0")]
1393 impl<T: Ord> Ord for Vec<T> {
1394     #[inline]
1395     fn cmp(&self, other: &Vec<T>) -> Ordering {
1396         Ord::cmp(&**self, &**other)
1397     }
1398 }
1399
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 impl<T> Drop for Vec<T> {
1402     #[unsafe_destructor_blind_to_params]
1403     fn drop(&mut self) {
1404         if self.buf.unsafe_no_drop_flag_needs_drop() {
1405             unsafe {
1406                 // The branch on needs_drop() is an -O1 performance optimization.
1407                 // Without the branch, dropping Vec<u8> takes linear time.
1408                 if needs_drop::<T>() {
1409                     for x in self.iter_mut() {
1410                         ptr::drop_in_place(x);
1411                     }
1412                 }
1413             }
1414         }
1415         // RawVec handles deallocation
1416     }
1417 }
1418
1419 #[stable(feature = "rust1", since = "1.0.0")]
1420 impl<T> Default for Vec<T> {
1421     fn default() -> Vec<T> {
1422         Vec::new()
1423     }
1424 }
1425
1426 #[stable(feature = "rust1", since = "1.0.0")]
1427 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
1428     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1429         fmt::Debug::fmt(&**self, f)
1430     }
1431 }
1432
1433 #[stable(feature = "rust1", since = "1.0.0")]
1434 impl<T> AsRef<Vec<T>> for Vec<T> {
1435     fn as_ref(&self) -> &Vec<T> {
1436         self
1437     }
1438 }
1439
1440 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1441 impl<T> AsMut<Vec<T>> for Vec<T> {
1442     fn as_mut(&mut self) -> &mut Vec<T> {
1443         self
1444     }
1445 }
1446
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 impl<T> AsRef<[T]> for Vec<T> {
1449     fn as_ref(&self) -> &[T] {
1450         self
1451     }
1452 }
1453
1454 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1455 impl<T> AsMut<[T]> for Vec<T> {
1456     fn as_mut(&mut self) -> &mut [T] {
1457         self
1458     }
1459 }
1460
1461 #[stable(feature = "rust1", since = "1.0.0")]
1462 impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
1463     #[cfg(not(test))]
1464     fn from(s: &'a [T]) -> Vec<T> {
1465         s.to_vec()
1466     }
1467     #[cfg(test)]
1468     fn from(s: &'a [T]) -> Vec<T> {
1469         ::slice::to_vec(s)
1470     }
1471 }
1472
1473 #[stable(feature = "rust1", since = "1.0.0")]
1474 impl<'a> From<&'a str> for Vec<u8> {
1475     fn from(s: &'a str) -> Vec<u8> {
1476         From::from(s.as_bytes())
1477     }
1478 }
1479
1480 ////////////////////////////////////////////////////////////////////////////////
1481 // Clone-on-write
1482 ////////////////////////////////////////////////////////////////////////////////
1483
1484 #[stable(feature = "rust1", since = "1.0.0")]
1485 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
1486     fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
1487         Cow::Owned(FromIterator::from_iter(it))
1488     }
1489 }
1490
1491 #[stable(feature = "rust1", since = "1.0.0")]
1492 impl<'a, T: 'a> IntoCow<'a, [T]> for Vec<T> where T: Clone {
1493     fn into_cow(self) -> Cow<'a, [T]> {
1494         Cow::Owned(self)
1495     }
1496 }
1497
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 impl<'a, T> IntoCow<'a, [T]> for &'a [T] where T: Clone {
1500     fn into_cow(self) -> Cow<'a, [T]> {
1501         Cow::Borrowed(self)
1502     }
1503 }
1504
1505 ////////////////////////////////////////////////////////////////////////////////
1506 // Iterators
1507 ////////////////////////////////////////////////////////////////////////////////
1508
1509 /// An iterator that moves out of a vector.
1510 #[stable(feature = "rust1", since = "1.0.0")]
1511 pub struct IntoIter<T> {
1512     _buf: RawVec<T>,
1513     ptr: *const T,
1514     end: *const T,
1515 }
1516
1517 #[stable(feature = "rust1", since = "1.0.0")]
1518 unsafe impl<T: Send> Send for IntoIter<T> {}
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 unsafe impl<T: Sync> Sync for IntoIter<T> {}
1521
1522 #[stable(feature = "rust1", since = "1.0.0")]
1523 impl<T> Iterator for IntoIter<T> {
1524     type Item = T;
1525
1526     #[inline]
1527     fn next(&mut self) -> Option<T> {
1528         unsafe {
1529             if self.ptr == self.end {
1530                 None
1531             } else {
1532                 if mem::size_of::<T>() == 0 {
1533                     // purposefully don't use 'ptr.offset' because for
1534                     // vectors with 0-size elements this would return the
1535                     // same pointer.
1536                     self.ptr = arith_offset(self.ptr as *const i8, 1) as *const T;
1537
1538                     // Use a non-null pointer value
1539                     Some(ptr::read(EMPTY as *mut T))
1540                 } else {
1541                     let old = self.ptr;
1542                     self.ptr = self.ptr.offset(1);
1543
1544                     Some(ptr::read(old))
1545                 }
1546             }
1547         }
1548     }
1549
1550     #[inline]
1551     fn size_hint(&self) -> (usize, Option<usize>) {
1552         let diff = (self.end as usize) - (self.ptr as usize);
1553         let size = mem::size_of::<T>();
1554         let exact = diff /
1555                     (if size == 0 {
1556                          1
1557                      } else {
1558                          size
1559                      });
1560         (exact, Some(exact))
1561     }
1562
1563     #[inline]
1564     fn count(self) -> usize {
1565         self.size_hint().0
1566     }
1567 }
1568
1569 #[stable(feature = "rust1", since = "1.0.0")]
1570 impl<T> DoubleEndedIterator for IntoIter<T> {
1571     #[inline]
1572     fn next_back(&mut self) -> Option<T> {
1573         unsafe {
1574             if self.end == self.ptr {
1575                 None
1576             } else {
1577                 if mem::size_of::<T>() == 0 {
1578                     // See above for why 'ptr.offset' isn't used
1579                     self.end = arith_offset(self.end as *const i8, -1) as *const T;
1580
1581                     // Use a non-null pointer value
1582                     Some(ptr::read(EMPTY as *mut T))
1583                 } else {
1584                     self.end = self.end.offset(-1);
1585
1586                     Some(ptr::read(self.end))
1587                 }
1588             }
1589         }
1590     }
1591 }
1592
1593 #[stable(feature = "rust1", since = "1.0.0")]
1594 impl<T> ExactSizeIterator for IntoIter<T> {}
1595
1596 #[stable(feature = "rust1", since = "1.0.0")]
1597 impl<T> Drop for IntoIter<T> {
1598     #[unsafe_destructor_blind_to_params]
1599     fn drop(&mut self) {
1600         // destroy the remaining elements
1601         for _x in self {}
1602
1603         // RawVec handles deallocation
1604     }
1605 }
1606
1607 /// A draining iterator for `Vec<T>`.
1608 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1609 pub struct Drain<'a, T: 'a> {
1610     /// Index of tail to preserve
1611     tail_start: usize,
1612     /// Length of tail
1613     tail_len: usize,
1614     /// Current remaining range to remove
1615     iter: slice::IterMut<'a, T>,
1616     vec: *mut Vec<T>,
1617 }
1618
1619 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1620 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1621 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1622 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1623
1624 #[stable(feature = "rust1", since = "1.0.0")]
1625 impl<'a, T> Iterator for Drain<'a, T> {
1626     type Item = T;
1627
1628     #[inline]
1629     fn next(&mut self) -> Option<T> {
1630         self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
1631     }
1632
1633     fn size_hint(&self) -> (usize, Option<usize>) {
1634         self.iter.size_hint()
1635     }
1636 }
1637
1638 #[stable(feature = "rust1", since = "1.0.0")]
1639 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1640     #[inline]
1641     fn next_back(&mut self) -> Option<T> {
1642         self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
1643     }
1644 }
1645
1646 #[stable(feature = "rust1", since = "1.0.0")]
1647 impl<'a, T> Drop for Drain<'a, T> {
1648     fn drop(&mut self) {
1649         // exhaust self first
1650         while let Some(_) = self.next() {}
1651
1652         if self.tail_len > 0 {
1653             unsafe {
1654                 let source_vec = &mut *self.vec;
1655                 // memmove back untouched tail, update to new length
1656                 let start = source_vec.len();
1657                 let tail = self.tail_start;
1658                 let src = source_vec.as_ptr().offset(tail as isize);
1659                 let dst = source_vec.as_mut_ptr().offset(start as isize);
1660                 ptr::copy(src, dst, self.tail_len);
1661                 source_vec.set_len(start + self.tail_len);
1662             }
1663         }
1664     }
1665 }
1666
1667
1668 #[stable(feature = "rust1", since = "1.0.0")]
1669 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}