]> git.lizzy.rs Git - rust.git/blob - src/libcollections/vec.rs
Auto merge of #41433 - estebank:constructor, r=michaelwoerister
[rust.git] / src / libcollections / vec.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! A contiguous growable array type with heap-allocated contents, written
12 //! `Vec<T>` but pronounced 'vector.'
13 //!
14 //! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and
15 //! `O(1)` pop (from the end).
16 //!
17 //! # Examples
18 //!
19 //! You can explicitly create a [`Vec<T>`] with [`new`]:
20 //!
21 //! ```
22 //! let v: Vec<i32> = Vec::new();
23 //! ```
24 //!
25 //! ...or by using the [`vec!`] macro:
26 //!
27 //! ```
28 //! let v: Vec<i32> = vec![];
29 //!
30 //! let v = vec![1, 2, 3, 4, 5];
31 //!
32 //! let v = vec![0; 10]; // ten zeroes
33 //! ```
34 //!
35 //! You can [`push`] values onto the end of a vector (which will grow the vector
36 //! as needed):
37 //!
38 //! ```
39 //! let mut v = vec![1, 2];
40 //!
41 //! v.push(3);
42 //! ```
43 //!
44 //! Popping values works in much the same way:
45 //!
46 //! ```
47 //! let mut v = vec![1, 2];
48 //!
49 //! let two = v.pop();
50 //! ```
51 //!
52 //! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
53 //!
54 //! ```
55 //! let mut v = vec![1, 2, 3];
56 //! let three = v[2];
57 //! v[1] = v[1] + 5;
58 //! ```
59 //!
60 //! [`Vec<T>`]: ../../std/vec/struct.Vec.html
61 //! [`new`]: ../../std/vec/struct.Vec.html#method.new
62 //! [`push`]: ../../std/vec/struct.Vec.html#method.push
63 //! [`Index`]: ../../std/ops/trait.Index.html
64 //! [`IndexMut`]: ../../std/ops/trait.IndexMut.html
65 //! [`vec!`]: ../../std/macro.vec.html
66
67 #![stable(feature = "rust1", since = "1.0.0")]
68
69 use alloc::boxed::Box;
70 use alloc::heap::EMPTY;
71 use alloc::raw_vec::RawVec;
72 use borrow::ToOwned;
73 use borrow::Cow;
74 use core::cmp::Ordering;
75 use core::fmt;
76 use core::hash::{self, Hash};
77 use core::intrinsics::{arith_offset, assume};
78 use core::iter::{FromIterator, FusedIterator, TrustedLen};
79 use core::mem;
80 #[cfg(not(test))]
81 use core::num::Float;
82 use core::ops::{InPlace, Index, IndexMut, Place, Placer};
83 use core::ops;
84 use core::ptr;
85 use core::ptr::Shared;
86 use core::slice;
87
88 use super::range::RangeArgument;
89 use Bound::{Excluded, Included, Unbounded};
90
91 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'.
92 ///
93 /// # Examples
94 ///
95 /// ```
96 /// let mut vec = Vec::new();
97 /// vec.push(1);
98 /// vec.push(2);
99 ///
100 /// assert_eq!(vec.len(), 2);
101 /// assert_eq!(vec[0], 1);
102 ///
103 /// assert_eq!(vec.pop(), Some(2));
104 /// assert_eq!(vec.len(), 1);
105 ///
106 /// vec[0] = 7;
107 /// assert_eq!(vec[0], 7);
108 ///
109 /// vec.extend([1, 2, 3].iter().cloned());
110 ///
111 /// for x in &vec {
112 ///     println!("{}", x);
113 /// }
114 /// assert_eq!(vec, [7, 1, 2, 3]);
115 /// ```
116 ///
117 /// The [`vec!`] macro is provided to make initialization more convenient:
118 ///
119 /// ```
120 /// let mut vec = vec![1, 2, 3];
121 /// vec.push(4);
122 /// assert_eq!(vec, [1, 2, 3, 4]);
123 /// ```
124 ///
125 /// It can also initialize each element of a `Vec<T>` with a given value:
126 ///
127 /// ```
128 /// let vec = vec![0; 5];
129 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
130 /// ```
131 ///
132 /// Use a `Vec<T>` as an efficient stack:
133 ///
134 /// ```
135 /// let mut stack = Vec::new();
136 ///
137 /// stack.push(1);
138 /// stack.push(2);
139 /// stack.push(3);
140 ///
141 /// while let Some(top) = stack.pop() {
142 ///     // Prints 3, 2, 1
143 ///     println!("{}", top);
144 /// }
145 /// ```
146 ///
147 /// # Indexing
148 ///
149 /// The `Vec` type allows to access values by index, because it implements the
150 /// [`Index`] trait. An example will be more explicit:
151 ///
152 /// ```
153 /// let v = vec![0, 2, 4, 6];
154 /// println!("{}", v[1]); // it will display '2'
155 /// ```
156 ///
157 /// However be careful: if you try to access an index which isn't in the `Vec`,
158 /// your software will panic! You cannot do this:
159 ///
160 /// ```ignore
161 /// let v = vec![0, 2, 4, 6];
162 /// println!("{}", v[6]); // it will panic!
163 /// ```
164 ///
165 /// In conclusion: always check if the index you want to get really exists
166 /// before doing it.
167 ///
168 /// # Slicing
169 ///
170 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
171 /// To get a slice, use `&`. Example:
172 ///
173 /// ```
174 /// fn read_slice(slice: &[usize]) {
175 ///     // ...
176 /// }
177 ///
178 /// let v = vec![0, 1];
179 /// read_slice(&v);
180 ///
181 /// // ... and that's all!
182 /// // you can also do it like this:
183 /// let x : &[usize] = &v;
184 /// ```
185 ///
186 /// In Rust, it's more common to pass slices as arguments rather than vectors
187 /// when you just want to provide a read access. The same goes for [`String`] and
188 /// [`&str`].
189 ///
190 /// # Capacity and reallocation
191 ///
192 /// The capacity of a vector is the amount of space allocated for any future
193 /// elements that will be added onto the vector. This is not to be confused with
194 /// the *length* of a vector, which specifies the number of actual elements
195 /// within the vector. If a vector's length exceeds its capacity, its capacity
196 /// will automatically be increased, but its elements will have to be
197 /// reallocated.
198 ///
199 /// For example, a vector with capacity 10 and length 0 would be an empty vector
200 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
201 /// vector will not change its capacity or cause reallocation to occur. However,
202 /// if the vector's length is increased to 11, it will have to reallocate, which
203 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
204 /// whenever possible to specify how big the vector is expected to get.
205 ///
206 /// # Guarantees
207 ///
208 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
209 /// about its design. This ensures that it's as low-overhead as possible in
210 /// the general case, and can be correctly manipulated in primitive ways
211 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
212 /// If additional type parameters are added (e.g. to support custom allocators),
213 /// overriding their defaults may change the behavior.
214 ///
215 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
216 /// triplet. No more, no less. The order of these fields is completely
217 /// unspecified, and you should use the appropriate methods to modify these.
218 /// The pointer will never be null, so this type is null-pointer-optimized.
219 ///
220 /// However, the pointer may not actually point to allocated memory. In particular,
221 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
222 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
223 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
224 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
225 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
226 /// if [`mem::size_of::<T>`]` * capacity() > 0`. In general, `Vec`'s allocation
227 /// details are subtle enough that it is strongly recommended that you only
228 /// free memory allocated by a `Vec` by creating a new `Vec` and dropping it.
229 ///
230 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
231 /// (as defined by the allocator Rust is configured to use by default), and its
232 /// pointer points to [`len`] initialized elements in order (what you would see
233 /// if you coerced it to a slice), followed by [`capacity`]` - `[`len`]
234 /// logically uninitialized elements.
235 ///
236 /// `Vec` will never perform a "small optimization" where elements are actually
237 /// stored on the stack for two reasons:
238 ///
239 /// * It would make it more difficult for unsafe code to correctly manipulate
240 ///   a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
241 ///   only moved, and it would be more difficult to determine if a `Vec` had
242 ///   actually allocated memory.
243 ///
244 /// * It would penalize the general case, incurring an additional branch
245 ///   on every access.
246 ///
247 /// `Vec` will never automatically shrink itself, even if completely empty. This
248 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
249 /// and then filling it back up to the same [`len`] should incur no calls to
250 /// the allocator. If you wish to free up unused memory, use
251 /// [`shrink_to_fit`][`shrink_to_fit`].
252 ///
253 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
254 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
255 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
256 /// accurate, and can be relied on. It can even be used to manually free the memory
257 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
258 /// when not necessary.
259 ///
260 /// `Vec` does not guarantee any particular growth strategy when reallocating
261 /// when full, nor when [`reserve`] is called. The current strategy is basic
262 /// and it may prove desirable to use a non-constant growth factor. Whatever
263 /// strategy is used will of course guarantee `O(1)` amortized [`push`].
264 ///
265 /// `vec![x; n]`, `vec![a, b, c, d]`, and
266 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
267 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
268 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
269 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
270 ///
271 /// `Vec` will not specifically overwrite any data that is removed from it,
272 /// but also won't specifically preserve it. Its uninitialized memory is
273 /// scratch space that it may use however it wants. It will generally just do
274 /// whatever is most efficient or otherwise easy to implement. Do not rely on
275 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
276 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
277 /// first, that may not actually happen because the optimizer does not consider
278 /// this a side-effect that must be preserved. There is one case which we will
279 /// not break, however: using `unsafe` code to write to the excess capacity,
280 /// and then increasing the length to match, is always valid.
281 ///
282 /// `Vec` does not currently guarantee the order in which elements are dropped
283 /// (the order has changed in the past, and may change again).
284 ///
285 /// [`vec!`]: ../../std/macro.vec.html
286 /// [`Index`]: ../../std/ops/trait.Index.html
287 /// [`String`]: ../../std/string/struct.String.html
288 /// [`&str`]: ../../std/primitive.str.html
289 /// [`Vec::with_capacity`]: ../../std/vec/struct.Vec.html#method.with_capacity
290 /// [`Vec::new`]: ../../std/vec/struct.Vec.html#method.new
291 /// [`shrink_to_fit`]: ../../std/vec/struct.Vec.html#method.shrink_to_fit
292 /// [`capacity`]: ../../std/vec/struct.Vec.html#method.capacity
293 /// [`mem::size_of::<T>`]: ../../std/mem/fn.size_of.html
294 /// [`len`]: ../../std/vec/struct.Vec.html#method.len
295 /// [`push`]: ../../std/vec/struct.Vec.html#method.push
296 /// [`insert`]: ../../std/vec/struct.Vec.html#method.insert
297 /// [`reserve`]: ../../std/vec/struct.Vec.html#method.reserve
298 /// [owned slice]: ../../std/boxed/struct.Box.html
299 #[stable(feature = "rust1", since = "1.0.0")]
300 pub struct Vec<T> {
301     buf: RawVec<T>,
302     len: usize,
303 }
304
305 ////////////////////////////////////////////////////////////////////////////////
306 // Inherent methods
307 ////////////////////////////////////////////////////////////////////////////////
308
309 impl<T> Vec<T> {
310     /// Constructs a new, empty `Vec<T>`.
311     ///
312     /// The vector will not allocate until elements are pushed onto it.
313     ///
314     /// # Examples
315     ///
316     /// ```
317     /// # #![allow(unused_mut)]
318     /// let mut vec: Vec<i32> = Vec::new();
319     /// ```
320     #[inline]
321     #[stable(feature = "rust1", since = "1.0.0")]
322     pub fn new() -> Vec<T> {
323         Vec {
324             buf: RawVec::new(),
325             len: 0,
326         }
327     }
328
329     /// Constructs a new, empty `Vec<T>` with the specified capacity.
330     ///
331     /// The vector will be able to hold exactly `capacity` elements without
332     /// reallocating. If `capacity` is 0, the vector will not allocate.
333     ///
334     /// It is important to note that this function does not specify the *length*
335     /// of the returned vector, but only the *capacity*. For an explanation of
336     /// the difference between length and capacity, see *[Capacity and reallocation]*.
337     ///
338     /// [Capacity and reallocation]: #capacity-and-reallocation
339     ///
340     /// # Examples
341     ///
342     /// ```
343     /// let mut vec = Vec::with_capacity(10);
344     ///
345     /// // The vector contains no items, even though it has capacity for more
346     /// assert_eq!(vec.len(), 0);
347     ///
348     /// // These are all done without reallocating...
349     /// for i in 0..10 {
350     ///     vec.push(i);
351     /// }
352     ///
353     /// // ...but this may make the vector reallocate
354     /// vec.push(11);
355     /// ```
356     #[inline]
357     #[stable(feature = "rust1", since = "1.0.0")]
358     pub fn with_capacity(capacity: usize) -> Vec<T> {
359         Vec {
360             buf: RawVec::with_capacity(capacity),
361             len: 0,
362         }
363     }
364
365     /// Creates a `Vec<T>` directly from the raw components of another vector.
366     ///
367     /// # Safety
368     ///
369     /// This is highly unsafe, due to the number of invariants that aren't
370     /// checked:
371     ///
372     /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
373     ///   (at least, it's highly likely to be incorrect if it wasn't).
374     /// * `length` needs to be less than or equal to `capacity`.
375     /// * `capacity` needs to be the capacity that the pointer was allocated with.
376     ///
377     /// Violating these may cause problems like corrupting the allocator's
378     /// internal datastructures. For example it is **not** safe
379     /// to build a `Vec<u8>` from a pointer to a C `char` array and a `size_t`.
380     ///
381     /// The ownership of `ptr` is effectively transferred to the
382     /// `Vec<T>` which may then deallocate, reallocate or change the
383     /// contents of memory pointed to by the pointer at will. Ensure
384     /// that nothing else uses the pointer after calling this
385     /// function.
386     ///
387     /// [`String`]: ../../std/string/struct.String.html
388     ///
389     /// # Examples
390     ///
391     /// ```
392     /// use std::ptr;
393     /// use std::mem;
394     ///
395     /// fn main() {
396     ///     let mut v = vec![1, 2, 3];
397     ///
398     ///     // Pull out the various important pieces of information about `v`
399     ///     let p = v.as_mut_ptr();
400     ///     let len = v.len();
401     ///     let cap = v.capacity();
402     ///
403     ///     unsafe {
404     ///         // Cast `v` into the void: no destructor run, so we are in
405     ///         // complete control of the allocation to which `p` points.
406     ///         mem::forget(v);
407     ///
408     ///         // Overwrite memory with 4, 5, 6
409     ///         for i in 0..len as isize {
410     ///             ptr::write(p.offset(i), 4 + i);
411     ///         }
412     ///
413     ///         // Put everything back together into a Vec
414     ///         let rebuilt = Vec::from_raw_parts(p, len, cap);
415     ///         assert_eq!(rebuilt, [4, 5, 6]);
416     ///     }
417     /// }
418     /// ```
419     #[stable(feature = "rust1", since = "1.0.0")]
420     pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
421         Vec {
422             buf: RawVec::from_raw_parts(ptr, capacity),
423             len: length,
424         }
425     }
426
427     /// Returns the number of elements the vector can hold without
428     /// reallocating.
429     ///
430     /// # Examples
431     ///
432     /// ```
433     /// let vec: Vec<i32> = Vec::with_capacity(10);
434     /// assert_eq!(vec.capacity(), 10);
435     /// ```
436     #[inline]
437     #[stable(feature = "rust1", since = "1.0.0")]
438     pub fn capacity(&self) -> usize {
439         self.buf.cap()
440     }
441
442     /// Reserves capacity for at least `additional` more elements to be inserted
443     /// in the given `Vec<T>`. The collection may reserve more space to avoid
444     /// frequent reallocations. After calling `reserve`, capacity will be
445     /// greater than or equal to `self.len() + additional`. Does nothing if
446     /// capacity is already sufficient.
447     ///
448     /// # Panics
449     ///
450     /// Panics if the new capacity overflows `usize`.
451     ///
452     /// # Examples
453     ///
454     /// ```
455     /// let mut vec = vec![1];
456     /// vec.reserve(10);
457     /// assert!(vec.capacity() >= 11);
458     /// ```
459     #[stable(feature = "rust1", since = "1.0.0")]
460     pub fn reserve(&mut self, additional: usize) {
461         self.buf.reserve(self.len, additional);
462     }
463
464     /// Reserves the minimum capacity for exactly `additional` more elements to
465     /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
466     /// capacity will be greater than or equal to `self.len() + additional`.
467     /// Does nothing if the capacity is already sufficient.
468     ///
469     /// Note that the allocator may give the collection more space than it
470     /// requests. Therefore capacity can not be relied upon to be precisely
471     /// minimal. Prefer `reserve` if future insertions are expected.
472     ///
473     /// # Panics
474     ///
475     /// Panics if the new capacity overflows `usize`.
476     ///
477     /// # Examples
478     ///
479     /// ```
480     /// let mut vec = vec![1];
481     /// vec.reserve_exact(10);
482     /// assert!(vec.capacity() >= 11);
483     /// ```
484     #[stable(feature = "rust1", since = "1.0.0")]
485     pub fn reserve_exact(&mut self, additional: usize) {
486         self.buf.reserve_exact(self.len, additional);
487     }
488
489     /// Shrinks the capacity of the vector as much as possible.
490     ///
491     /// It will drop down as close as possible to the length but the allocator
492     /// may still inform the vector that there is space for a few more elements.
493     ///
494     /// # Examples
495     ///
496     /// ```
497     /// let mut vec = Vec::with_capacity(10);
498     /// vec.extend([1, 2, 3].iter().cloned());
499     /// assert_eq!(vec.capacity(), 10);
500     /// vec.shrink_to_fit();
501     /// assert!(vec.capacity() >= 3);
502     /// ```
503     #[stable(feature = "rust1", since = "1.0.0")]
504     pub fn shrink_to_fit(&mut self) {
505         self.buf.shrink_to_fit(self.len);
506     }
507
508     /// Converts the vector into [`Box<[T]>`][owned slice].
509     ///
510     /// Note that this will drop any excess capacity. Calling this and
511     /// converting back to a vector with [`into_vec`] is equivalent to calling
512     /// [`shrink_to_fit`].
513     ///
514     /// [owned slice]: ../../std/boxed/struct.Box.html
515     /// [`into_vec`]: ../../std/primitive.slice.html#method.into_vec
516     /// [`shrink_to_fit`]: #method.shrink_to_fit
517     ///
518     /// # Examples
519     ///
520     /// ```
521     /// let v = vec![1, 2, 3];
522     ///
523     /// let slice = v.into_boxed_slice();
524     /// ```
525     ///
526     /// Any excess capacity is removed:
527     ///
528     /// ```
529     /// let mut vec = Vec::with_capacity(10);
530     /// vec.extend([1, 2, 3].iter().cloned());
531     ///
532     /// assert_eq!(vec.capacity(), 10);
533     /// let slice = vec.into_boxed_slice();
534     /// assert_eq!(slice.into_vec().capacity(), 3);
535     /// ```
536     #[stable(feature = "rust1", since = "1.0.0")]
537     pub fn into_boxed_slice(mut self) -> Box<[T]> {
538         unsafe {
539             self.shrink_to_fit();
540             let buf = ptr::read(&self.buf);
541             mem::forget(self);
542             buf.into_box()
543         }
544     }
545
546     /// Shortens the vector, keeping the first `len` elements and dropping
547     /// the rest.
548     ///
549     /// If `len` is greater than the vector's current length, this has no
550     /// effect.
551     ///
552     /// The [`drain`] method can emulate `truncate`, but causes the excess
553     /// elements to be returned instead of dropped.
554     ///
555     /// Note that this method has no effect on the allocated capacity
556     /// of the vector.
557     ///
558     /// # Examples
559     ///
560     /// Truncating a five element vector to two elements:
561     ///
562     /// ```
563     /// let mut vec = vec![1, 2, 3, 4, 5];
564     /// vec.truncate(2);
565     /// assert_eq!(vec, [1, 2]);
566     /// ```
567     ///
568     /// No truncation occurs when `len` is greater than the vector's current
569     /// length:
570     ///
571     /// ```
572     /// let mut vec = vec![1, 2, 3];
573     /// vec.truncate(8);
574     /// assert_eq!(vec, [1, 2, 3]);
575     /// ```
576     ///
577     /// Truncating when `len == 0` is equivalent to calling the [`clear`]
578     /// method.
579     ///
580     /// ```
581     /// let mut vec = vec![1, 2, 3];
582     /// vec.truncate(0);
583     /// assert_eq!(vec, []);
584     /// ```
585     ///
586     /// [`clear`]: #method.clear
587     /// [`drain`]: #method.drain
588     #[stable(feature = "rust1", since = "1.0.0")]
589     pub fn truncate(&mut self, len: usize) {
590         unsafe {
591             // drop any extra elements
592             while len < self.len {
593                 // decrement len before the drop_in_place(), so a panic on Drop
594                 // doesn't re-drop the just-failed value.
595                 self.len -= 1;
596                 let len = self.len;
597                 ptr::drop_in_place(self.get_unchecked_mut(len));
598             }
599         }
600     }
601
602     /// Extracts a slice containing the entire vector.
603     ///
604     /// Equivalent to `&s[..]`.
605     ///
606     /// # Examples
607     ///
608     /// ```
609     /// use std::io::{self, Write};
610     /// let buffer = vec![1, 2, 3, 5, 8];
611     /// io::sink().write(buffer.as_slice()).unwrap();
612     /// ```
613     #[inline]
614     #[stable(feature = "vec_as_slice", since = "1.7.0")]
615     pub fn as_slice(&self) -> &[T] {
616         self
617     }
618
619     /// Extracts a mutable slice of the entire vector.
620     ///
621     /// Equivalent to `&mut s[..]`.
622     ///
623     /// # Examples
624     ///
625     /// ```
626     /// use std::io::{self, Read};
627     /// let mut buffer = vec![0; 3];
628     /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
629     /// ```
630     #[inline]
631     #[stable(feature = "vec_as_slice", since = "1.7.0")]
632     pub fn as_mut_slice(&mut self) -> &mut [T] {
633         self
634     }
635
636     /// Sets the length of a vector.
637     ///
638     /// This will explicitly set the size of the vector, without actually
639     /// modifying its buffers, so it is up to the caller to ensure that the
640     /// vector is actually the specified size.
641     ///
642     /// # Examples
643     ///
644     /// ```
645     /// use std::ptr;
646     ///
647     /// let mut vec = vec!['r', 'u', 's', 't'];
648     ///
649     /// unsafe {
650     ///     ptr::drop_in_place(&mut vec[3]);
651     ///     vec.set_len(3);
652     /// }
653     /// assert_eq!(vec, ['r', 'u', 's']);
654     /// ```
655     ///
656     /// In this example, there is a memory leak since the memory locations
657     /// owned by the inner vectors were not freed prior to the `set_len` call:
658     ///
659     /// ```
660     /// let mut vec = vec![vec![1, 0, 0],
661     ///                    vec![0, 1, 0],
662     ///                    vec![0, 0, 1]];
663     /// unsafe {
664     ///     vec.set_len(0);
665     /// }
666     /// ```
667     ///
668     /// In this example, the vector gets expanded from zero to four items
669     /// without any memory allocations occurring, resulting in vector
670     /// values of unallocated memory:
671     ///
672     /// ```
673     /// let mut vec: Vec<char> = Vec::new();
674     ///
675     /// unsafe {
676     ///     vec.set_len(4);
677     /// }
678     /// ```
679     #[inline]
680     #[stable(feature = "rust1", since = "1.0.0")]
681     pub unsafe fn set_len(&mut self, len: usize) {
682         self.len = len;
683     }
684
685     /// Removes an element from the vector and returns it.
686     ///
687     /// The removed element is replaced by the last element of the vector.
688     ///
689     /// This does not preserve ordering, but is O(1).
690     ///
691     /// # Panics
692     ///
693     /// Panics if `index` is out of bounds.
694     ///
695     /// # Examples
696     ///
697     /// ```
698     /// let mut v = vec!["foo", "bar", "baz", "qux"];
699     ///
700     /// assert_eq!(v.swap_remove(1), "bar");
701     /// assert_eq!(v, ["foo", "qux", "baz"]);
702     ///
703     /// assert_eq!(v.swap_remove(0), "foo");
704     /// assert_eq!(v, ["baz", "qux"]);
705     /// ```
706     #[inline]
707     #[stable(feature = "rust1", since = "1.0.0")]
708     pub fn swap_remove(&mut self, index: usize) -> T {
709         let length = self.len();
710         self.swap(index, length - 1);
711         self.pop().unwrap()
712     }
713
714     /// Inserts an element at position `index` within the vector, shifting all
715     /// elements after it to the right.
716     ///
717     /// # Panics
718     ///
719     /// Panics if `index` is out of bounds.
720     ///
721     /// # Examples
722     ///
723     /// ```
724     /// let mut vec = vec![1, 2, 3];
725     /// vec.insert(1, 4);
726     /// assert_eq!(vec, [1, 4, 2, 3]);
727     /// vec.insert(4, 5);
728     /// assert_eq!(vec, [1, 4, 2, 3, 5]);
729     /// ```
730     #[stable(feature = "rust1", since = "1.0.0")]
731     pub fn insert(&mut self, index: usize, element: T) {
732         let len = self.len();
733         assert!(index <= len);
734
735         // space for the new element
736         if len == self.buf.cap() {
737             self.buf.double();
738         }
739
740         unsafe {
741             // infallible
742             // The spot to put the new value
743             {
744                 let p = self.as_mut_ptr().offset(index as isize);
745                 // Shift everything over to make space. (Duplicating the
746                 // `index`th element into two consecutive places.)
747                 ptr::copy(p, p.offset(1), len - index);
748                 // Write it in, overwriting the first copy of the `index`th
749                 // element.
750                 ptr::write(p, element);
751             }
752             self.set_len(len + 1);
753         }
754     }
755
756     /// Removes and returns the element at position `index` within the vector,
757     /// shifting all elements after it to the left.
758     ///
759     /// # Panics
760     ///
761     /// Panics if `index` is out of bounds.
762     ///
763     /// # Examples
764     ///
765     /// ```
766     /// let mut v = vec![1, 2, 3];
767     /// assert_eq!(v.remove(1), 2);
768     /// assert_eq!(v, [1, 3]);
769     /// ```
770     #[stable(feature = "rust1", since = "1.0.0")]
771     pub fn remove(&mut self, index: usize) -> T {
772         let len = self.len();
773         assert!(index < len);
774         unsafe {
775             // infallible
776             let ret;
777             {
778                 // the place we are taking from.
779                 let ptr = self.as_mut_ptr().offset(index as isize);
780                 // copy it out, unsafely having a copy of the value on
781                 // the stack and in the vector at the same time.
782                 ret = ptr::read(ptr);
783
784                 // Shift everything down to fill in that spot.
785                 ptr::copy(ptr.offset(1), ptr, len - index - 1);
786             }
787             self.set_len(len - 1);
788             ret
789         }
790     }
791
792     /// Retains only the elements specified by the predicate.
793     ///
794     /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
795     /// This method operates in place and preserves the order of the retained
796     /// elements.
797     ///
798     /// # Examples
799     ///
800     /// ```
801     /// let mut vec = vec![1, 2, 3, 4];
802     /// vec.retain(|&x| x%2 == 0);
803     /// assert_eq!(vec, [2, 4]);
804     /// ```
805     #[stable(feature = "rust1", since = "1.0.0")]
806     pub fn retain<F>(&mut self, mut f: F)
807         where F: FnMut(&T) -> bool
808     {
809         let len = self.len();
810         let mut del = 0;
811         {
812             let v = &mut **self;
813
814             for i in 0..len {
815                 if !f(&v[i]) {
816                     del += 1;
817                 } else if del > 0 {
818                     v.swap(i - del, i);
819                 }
820             }
821         }
822         if del > 0 {
823             self.truncate(len - del);
824         }
825     }
826
827     /// Removes consecutive elements in the vector that resolve to the same key.
828     ///
829     /// If the vector is sorted, this removes all duplicates.
830     ///
831     /// # Examples
832     ///
833     /// ```
834     /// let mut vec = vec![10, 20, 21, 30, 20];
835     ///
836     /// vec.dedup_by_key(|i| *i / 10);
837     ///
838     /// assert_eq!(vec, [10, 20, 30, 20]);
839     /// ```
840     #[stable(feature = "dedup_by", since = "1.16.0")]
841     #[inline]
842     pub fn dedup_by_key<F, K>(&mut self, mut key: F) where F: FnMut(&mut T) -> K, K: PartialEq {
843         self.dedup_by(|a, b| key(a) == key(b))
844     }
845
846     /// Removes consecutive elements in the vector according to a predicate.
847     ///
848     /// The `same_bucket` function is passed references to two elements from the vector, and
849     /// returns `true` if the elements compare equal, or `false` if they do not. Only the first
850     /// of adjacent equal items is kept.
851     ///
852     /// If the vector is sorted, this removes all duplicates.
853     ///
854     /// # Examples
855     ///
856     /// ```
857     /// use std::ascii::AsciiExt;
858     ///
859     /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
860     ///
861     /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
862     ///
863     /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
864     /// ```
865     #[stable(feature = "dedup_by", since = "1.16.0")]
866     pub fn dedup_by<F>(&mut self, mut same_bucket: F) where F: FnMut(&mut T, &mut T) -> bool {
867         unsafe {
868             // Although we have a mutable reference to `self`, we cannot make
869             // *arbitrary* changes. The `same_bucket` calls could panic, so we
870             // must ensure that the vector is in a valid state at all time.
871             //
872             // The way that we handle this is by using swaps; we iterate
873             // over all the elements, swapping as we go so that at the end
874             // the elements we wish to keep are in the front, and those we
875             // wish to reject are at the back. We can then truncate the
876             // vector. This operation is still O(n).
877             //
878             // Example: We start in this state, where `r` represents "next
879             // read" and `w` represents "next_write`.
880             //
881             //           r
882             //     +---+---+---+---+---+---+
883             //     | 0 | 1 | 1 | 2 | 3 | 3 |
884             //     +---+---+---+---+---+---+
885             //           w
886             //
887             // Comparing self[r] against self[w-1], this is not a duplicate, so
888             // we swap self[r] and self[w] (no effect as r==w) and then increment both
889             // r and w, leaving us with:
890             //
891             //               r
892             //     +---+---+---+---+---+---+
893             //     | 0 | 1 | 1 | 2 | 3 | 3 |
894             //     +---+---+---+---+---+---+
895             //               w
896             //
897             // Comparing self[r] against self[w-1], this value is a duplicate,
898             // so we increment `r` but leave everything else unchanged:
899             //
900             //                   r
901             //     +---+---+---+---+---+---+
902             //     | 0 | 1 | 1 | 2 | 3 | 3 |
903             //     +---+---+---+---+---+---+
904             //               w
905             //
906             // Comparing self[r] against self[w-1], this is not a duplicate,
907             // so swap self[r] and self[w] and advance r and w:
908             //
909             //                       r
910             //     +---+---+---+---+---+---+
911             //     | 0 | 1 | 2 | 1 | 3 | 3 |
912             //     +---+---+---+---+---+---+
913             //                   w
914             //
915             // Not a duplicate, repeat:
916             //
917             //                           r
918             //     +---+---+---+---+---+---+
919             //     | 0 | 1 | 2 | 3 | 1 | 3 |
920             //     +---+---+---+---+---+---+
921             //                       w
922             //
923             // Duplicate, advance r. End of vec. Truncate to w.
924
925             let ln = self.len();
926             if ln <= 1 {
927                 return;
928             }
929
930             // Avoid bounds checks by using raw pointers.
931             let p = self.as_mut_ptr();
932             let mut r: usize = 1;
933             let mut w: usize = 1;
934
935             while r < ln {
936                 let p_r = p.offset(r as isize);
937                 let p_wm1 = p.offset((w - 1) as isize);
938                 if !same_bucket(&mut *p_r, &mut *p_wm1) {
939                     if r != w {
940                         let p_w = p_wm1.offset(1);
941                         mem::swap(&mut *p_r, &mut *p_w);
942                     }
943                     w += 1;
944                 }
945                 r += 1;
946             }
947
948             self.truncate(w);
949         }
950     }
951
952     /// Appends an element to the back of a collection.
953     ///
954     /// # Panics
955     ///
956     /// Panics if the number of elements in the vector overflows a `usize`.
957     ///
958     /// # Examples
959     ///
960     /// ```
961     /// let mut vec = vec![1, 2];
962     /// vec.push(3);
963     /// assert_eq!(vec, [1, 2, 3]);
964     /// ```
965     #[inline]
966     #[stable(feature = "rust1", since = "1.0.0")]
967     pub fn push(&mut self, value: T) {
968         // This will panic or abort if we would allocate > isize::MAX bytes
969         // or if the length increment would overflow for zero-sized types.
970         if self.len == self.buf.cap() {
971             self.buf.double();
972         }
973         unsafe {
974             let end = self.as_mut_ptr().offset(self.len as isize);
975             ptr::write(end, value);
976             self.len += 1;
977         }
978     }
979
980     /// Returns a place for insertion at the back of the `Vec`.
981     ///
982     /// Using this method with placement syntax is equivalent to [`push`](#method.push),
983     /// but may be more efficient.
984     ///
985     /// # Examples
986     ///
987     /// ```
988     /// #![feature(collection_placement)]
989     /// #![feature(placement_in_syntax)]
990     ///
991     /// let mut vec = vec![1, 2];
992     /// vec.place_back() <- 3;
993     /// vec.place_back() <- 4;
994     /// assert_eq!(&vec, &[1, 2, 3, 4]);
995     /// ```
996     #[unstable(feature = "collection_placement",
997                reason = "placement protocol is subject to change",
998                issue = "30172")]
999     pub fn place_back(&mut self) -> PlaceBack<T> {
1000         PlaceBack { vec: self }
1001     }
1002
1003     /// Removes the last element from a vector and returns it, or [`None`] if it
1004     /// is empty.
1005     ///
1006     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1007     ///
1008     /// # Examples
1009     ///
1010     /// ```
1011     /// let mut vec = vec![1, 2, 3];
1012     /// assert_eq!(vec.pop(), Some(3));
1013     /// assert_eq!(vec, [1, 2]);
1014     /// ```
1015     #[inline]
1016     #[stable(feature = "rust1", since = "1.0.0")]
1017     pub fn pop(&mut self) -> Option<T> {
1018         if self.len == 0 {
1019             None
1020         } else {
1021             unsafe {
1022                 self.len -= 1;
1023                 Some(ptr::read(self.get_unchecked(self.len())))
1024             }
1025         }
1026     }
1027
1028     /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1029     ///
1030     /// # Panics
1031     ///
1032     /// Panics if the number of elements in the vector overflows a `usize`.
1033     ///
1034     /// # Examples
1035     ///
1036     /// ```
1037     /// let mut vec = vec![1, 2, 3];
1038     /// let mut vec2 = vec![4, 5, 6];
1039     /// vec.append(&mut vec2);
1040     /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1041     /// assert_eq!(vec2, []);
1042     /// ```
1043     #[inline]
1044     #[stable(feature = "append", since = "1.4.0")]
1045     pub fn append(&mut self, other: &mut Self) {
1046         unsafe {
1047             self.append_elements(other.as_slice() as _);
1048             other.set_len(0);
1049         }
1050     }
1051
1052     /// Appends elements to `Self` from other buffer.
1053     #[inline]
1054     unsafe fn append_elements(&mut self, other: *const [T]) {
1055         let count = (*other).len();
1056         self.reserve(count);
1057         let len = self.len();
1058         ptr::copy_nonoverlapping(other as *const T, self.get_unchecked_mut(len), count);
1059         self.len += count;
1060     }
1061
1062     /// Creates a draining iterator that removes the specified range in the vector
1063     /// and yields the removed items.
1064     ///
1065     /// Note 1: The element range is removed even if the iterator is only
1066     /// partially consumed or not consumed at all.
1067     ///
1068     /// Note 2: It is unspecified how many elements are removed from the vector
1069     /// if the `Drain` value is leaked.
1070     ///
1071     /// # Panics
1072     ///
1073     /// Panics if the starting point is greater than the end point or if
1074     /// the end point is greater than the length of the vector.
1075     ///
1076     /// # Examples
1077     ///
1078     /// ```
1079     /// let mut v = vec![1, 2, 3];
1080     /// let u: Vec<_> = v.drain(1..).collect();
1081     /// assert_eq!(v, &[1]);
1082     /// assert_eq!(u, &[2, 3]);
1083     ///
1084     /// // A full range clears the vector
1085     /// v.drain(..);
1086     /// assert_eq!(v, &[]);
1087     /// ```
1088     #[stable(feature = "drain", since = "1.6.0")]
1089     pub fn drain<R>(&mut self, range: R) -> Drain<T>
1090         where R: RangeArgument<usize>
1091     {
1092         // Memory safety
1093         //
1094         // When the Drain is first created, it shortens the length of
1095         // the source vector to make sure no uninitalized or moved-from elements
1096         // are accessible at all if the Drain's destructor never gets to run.
1097         //
1098         // Drain will ptr::read out the values to remove.
1099         // When finished, remaining tail of the vec is copied back to cover
1100         // the hole, and the vector length is restored to the new length.
1101         //
1102         let len = self.len();
1103         let start = match range.start() {
1104             Included(&n) => n,
1105             Excluded(&n) => n + 1,
1106             Unbounded    => 0,
1107         };
1108         let end = match range.end() {
1109             Included(&n) => n + 1,
1110             Excluded(&n) => n,
1111             Unbounded    => len,
1112         };
1113         assert!(start <= end);
1114         assert!(end <= len);
1115
1116         unsafe {
1117             // set self.vec length's to start, to be safe in case Drain is leaked
1118             self.set_len(start);
1119             // Use the borrow in the IterMut to indicate borrowing behavior of the
1120             // whole Drain iterator (like &mut T).
1121             let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().offset(start as isize),
1122                                                         end - start);
1123             Drain {
1124                 tail_start: end,
1125                 tail_len: len - end,
1126                 iter: range_slice.iter(),
1127                 vec: Shared::new(self as *mut _),
1128             }
1129         }
1130     }
1131
1132     /// Clears the vector, removing all values.
1133     ///
1134     /// Note that this method has no effect on the allocated capacity
1135     /// of the vector.
1136     ///
1137     /// # Examples
1138     ///
1139     /// ```
1140     /// let mut v = vec![1, 2, 3];
1141     ///
1142     /// v.clear();
1143     ///
1144     /// assert!(v.is_empty());
1145     /// ```
1146     #[inline]
1147     #[stable(feature = "rust1", since = "1.0.0")]
1148     pub fn clear(&mut self) {
1149         self.truncate(0)
1150     }
1151
1152     /// Returns the number of elements in the vector, also referred to
1153     /// as its 'length'.
1154     ///
1155     /// # Examples
1156     ///
1157     /// ```
1158     /// let a = vec![1, 2, 3];
1159     /// assert_eq!(a.len(), 3);
1160     /// ```
1161     #[inline]
1162     #[stable(feature = "rust1", since = "1.0.0")]
1163     pub fn len(&self) -> usize {
1164         self.len
1165     }
1166
1167     /// Returns `true` if the vector contains no elements.
1168     ///
1169     /// # Examples
1170     ///
1171     /// ```
1172     /// let mut v = Vec::new();
1173     /// assert!(v.is_empty());
1174     ///
1175     /// v.push(1);
1176     /// assert!(!v.is_empty());
1177     /// ```
1178     #[stable(feature = "rust1", since = "1.0.0")]
1179     pub fn is_empty(&self) -> bool {
1180         self.len() == 0
1181     }
1182
1183     /// Splits the collection into two at the given index.
1184     ///
1185     /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1186     /// and the returned `Self` contains elements `[at, len)`.
1187     ///
1188     /// Note that the capacity of `self` does not change.
1189     ///
1190     /// # Panics
1191     ///
1192     /// Panics if `at > len`.
1193     ///
1194     /// # Examples
1195     ///
1196     /// ```
1197     /// let mut vec = vec![1,2,3];
1198     /// let vec2 = vec.split_off(1);
1199     /// assert_eq!(vec, [1]);
1200     /// assert_eq!(vec2, [2, 3]);
1201     /// ```
1202     #[inline]
1203     #[stable(feature = "split_off", since = "1.4.0")]
1204     pub fn split_off(&mut self, at: usize) -> Self {
1205         assert!(at <= self.len(), "`at` out of bounds");
1206
1207         let other_len = self.len - at;
1208         let mut other = Vec::with_capacity(other_len);
1209
1210         // Unsafely `set_len` and copy items to `other`.
1211         unsafe {
1212             self.set_len(at);
1213             other.set_len(other_len);
1214
1215             ptr::copy_nonoverlapping(self.as_ptr().offset(at as isize),
1216                                      other.as_mut_ptr(),
1217                                      other.len());
1218         }
1219         other
1220     }
1221 }
1222
1223 impl<T: Clone> Vec<T> {
1224     /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
1225     ///
1226     /// If `new_len` is greater than `len()`, the `Vec` is extended by the
1227     /// difference, with each additional slot filled with `value`.
1228     /// If `new_len` is less than `len()`, the `Vec` is simply truncated.
1229     ///
1230     /// # Examples
1231     ///
1232     /// ```
1233     /// let mut vec = vec!["hello"];
1234     /// vec.resize(3, "world");
1235     /// assert_eq!(vec, ["hello", "world", "world"]);
1236     ///
1237     /// let mut vec = vec![1, 2, 3, 4];
1238     /// vec.resize(2, 0);
1239     /// assert_eq!(vec, [1, 2]);
1240     /// ```
1241     #[stable(feature = "vec_resize", since = "1.5.0")]
1242     pub fn resize(&mut self, new_len: usize, value: T) {
1243         let len = self.len();
1244
1245         if new_len > len {
1246             self.extend_with_element(new_len - len, value);
1247         } else {
1248             self.truncate(new_len);
1249         }
1250     }
1251
1252     /// Extend the vector by `n` additional clones of `value`.
1253     fn extend_with_element(&mut self, n: usize, value: T) {
1254         self.reserve(n);
1255
1256         unsafe {
1257             let mut ptr = self.as_mut_ptr().offset(self.len() as isize);
1258             // Use SetLenOnDrop to work around bug where compiler
1259             // may not realize the store through `ptr` through self.set_len()
1260             // don't alias.
1261             let mut local_len = SetLenOnDrop::new(&mut self.len);
1262
1263             // Write all elements except the last one
1264             for _ in 1..n {
1265                 ptr::write(ptr, value.clone());
1266                 ptr = ptr.offset(1);
1267                 // Increment the length in every step in case clone() panics
1268                 local_len.increment_len(1);
1269             }
1270
1271             if n > 0 {
1272                 // We can write the last element directly without cloning needlessly
1273                 ptr::write(ptr, value);
1274                 local_len.increment_len(1);
1275             }
1276
1277             // len set by scope guard
1278         }
1279     }
1280
1281     /// Clones and appends all elements in a slice to the `Vec`.
1282     ///
1283     /// Iterates over the slice `other`, clones each element, and then appends
1284     /// it to this `Vec`. The `other` vector is traversed in-order.
1285     ///
1286     /// Note that this function is same as `extend` except that it is
1287     /// specialized to work with slices instead. If and when Rust gets
1288     /// specialization this function will likely be deprecated (but still
1289     /// available).
1290     ///
1291     /// # Examples
1292     ///
1293     /// ```
1294     /// let mut vec = vec![1];
1295     /// vec.extend_from_slice(&[2, 3, 4]);
1296     /// assert_eq!(vec, [1, 2, 3, 4]);
1297     /// ```
1298     #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1299     pub fn extend_from_slice(&mut self, other: &[T]) {
1300         self.spec_extend(other.iter())
1301     }
1302 }
1303
1304 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1305 //
1306 // The idea is: The length field in SetLenOnDrop is a local variable
1307 // that the optimizer will see does not alias with any stores through the Vec's data
1308 // pointer. This is a workaround for alias analysis issue #32155
1309 struct SetLenOnDrop<'a> {
1310     len: &'a mut usize,
1311     local_len: usize,
1312 }
1313
1314 impl<'a> SetLenOnDrop<'a> {
1315     #[inline]
1316     fn new(len: &'a mut usize) -> Self {
1317         SetLenOnDrop { local_len: *len, len: len }
1318     }
1319
1320     #[inline]
1321     fn increment_len(&mut self, increment: usize) {
1322         self.local_len += increment;
1323     }
1324 }
1325
1326 impl<'a> Drop for SetLenOnDrop<'a> {
1327     #[inline]
1328     fn drop(&mut self) {
1329         *self.len = self.local_len;
1330     }
1331 }
1332
1333 impl<T: PartialEq> Vec<T> {
1334     /// Removes consecutive repeated elements in the vector.
1335     ///
1336     /// If the vector is sorted, this removes all duplicates.
1337     ///
1338     /// # Examples
1339     ///
1340     /// ```
1341     /// let mut vec = vec![1, 2, 2, 3, 2];
1342     ///
1343     /// vec.dedup();
1344     ///
1345     /// assert_eq!(vec, [1, 2, 3, 2]);
1346     /// ```
1347     #[stable(feature = "rust1", since = "1.0.0")]
1348     #[inline]
1349     pub fn dedup(&mut self) {
1350         self.dedup_by(|a, b| a == b)
1351     }
1352
1353     /// Removes the first instance of `item` from the vector if the item exists.
1354     ///
1355     /// # Examples
1356     ///
1357     /// ```
1358     /// # #![feature(vec_remove_item)]
1359     /// let mut vec = vec![1, 2, 3, 1];
1360     ///
1361     /// vec.remove_item(&1);
1362     ///
1363     /// assert_eq!(vec, vec![2, 3, 1]);
1364     /// ```
1365     #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1366     pub fn remove_item(&mut self, item: &T) -> Option<T> {
1367         let pos = match self.iter().position(|x| *x == *item) {
1368             Some(x) => x,
1369             None => return None,
1370         };
1371         Some(self.remove(pos))
1372     }
1373 }
1374
1375 ////////////////////////////////////////////////////////////////////////////////
1376 // Internal methods and functions
1377 ////////////////////////////////////////////////////////////////////////////////
1378
1379 #[doc(hidden)]
1380 #[stable(feature = "rust1", since = "1.0.0")]
1381 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1382     <T as SpecFromElem>::from_elem(elem, n)
1383 }
1384
1385 // Specialization trait used for Vec::from_elem
1386 trait SpecFromElem: Sized {
1387     fn from_elem(elem: Self, n: usize) -> Vec<Self>;
1388 }
1389
1390 impl<T: Clone> SpecFromElem for T {
1391     default fn from_elem(elem: Self, n: usize) -> Vec<Self> {
1392         let mut v = Vec::with_capacity(n);
1393         v.extend_with_element(n, elem);
1394         v
1395     }
1396 }
1397
1398 impl SpecFromElem for u8 {
1399     #[inline]
1400     fn from_elem(elem: u8, n: usize) -> Vec<u8> {
1401         if elem == 0 {
1402             return Vec {
1403                 buf: RawVec::with_capacity_zeroed(n),
1404                 len: n,
1405             }
1406         }
1407         unsafe {
1408             let mut v = Vec::with_capacity(n);
1409             ptr::write_bytes(v.as_mut_ptr(), elem, n);
1410             v.set_len(n);
1411             v
1412         }
1413     }
1414 }
1415
1416 macro_rules! impl_spec_from_elem {
1417     ($t: ty, $is_zero: expr) => {
1418         impl SpecFromElem for $t {
1419             #[inline]
1420             fn from_elem(elem: $t, n: usize) -> Vec<$t> {
1421                 if $is_zero(elem) {
1422                     return Vec {
1423                         buf: RawVec::with_capacity_zeroed(n),
1424                         len: n,
1425                     }
1426                 }
1427                 let mut v = Vec::with_capacity(n);
1428                 v.extend_with_element(n, elem);
1429                 v
1430             }
1431         }
1432     };
1433 }
1434
1435 impl_spec_from_elem!(i8, |x| x == 0);
1436 impl_spec_from_elem!(i16, |x| x == 0);
1437 impl_spec_from_elem!(i32, |x| x == 0);
1438 impl_spec_from_elem!(i64, |x| x == 0);
1439 impl_spec_from_elem!(i128, |x| x == 0);
1440 impl_spec_from_elem!(isize, |x| x == 0);
1441
1442 impl_spec_from_elem!(u16, |x| x == 0);
1443 impl_spec_from_elem!(u32, |x| x == 0);
1444 impl_spec_from_elem!(u64, |x| x == 0);
1445 impl_spec_from_elem!(u128, |x| x == 0);
1446 impl_spec_from_elem!(usize, |x| x == 0);
1447
1448 impl_spec_from_elem!(f32, |x: f32| x == 0. && x.is_sign_positive());
1449 impl_spec_from_elem!(f64, |x: f64| x == 0. && x.is_sign_positive());
1450
1451 ////////////////////////////////////////////////////////////////////////////////
1452 // Common trait implementations for Vec
1453 ////////////////////////////////////////////////////////////////////////////////
1454
1455 #[stable(feature = "rust1", since = "1.0.0")]
1456 impl<T: Clone> Clone for Vec<T> {
1457     #[cfg(not(test))]
1458     fn clone(&self) -> Vec<T> {
1459         <[T]>::to_vec(&**self)
1460     }
1461
1462     // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1463     // required for this method definition, is not available. Instead use the
1464     // `slice::to_vec`  function which is only available with cfg(test)
1465     // NB see the slice::hack module in slice.rs for more information
1466     #[cfg(test)]
1467     fn clone(&self) -> Vec<T> {
1468         ::slice::to_vec(&**self)
1469     }
1470
1471     fn clone_from(&mut self, other: &Vec<T>) {
1472         other.as_slice().clone_into(self);
1473     }
1474 }
1475
1476 #[stable(feature = "rust1", since = "1.0.0")]
1477 impl<T: Hash> Hash for Vec<T> {
1478     #[inline]
1479     fn hash<H: hash::Hasher>(&self, state: &mut H) {
1480         Hash::hash(&**self, state)
1481     }
1482 }
1483
1484 #[stable(feature = "rust1", since = "1.0.0")]
1485 impl<T> Index<usize> for Vec<T> {
1486     type Output = T;
1487
1488     #[inline]
1489     fn index(&self, index: usize) -> &T {
1490         // NB built-in indexing via `&[T]`
1491         &(**self)[index]
1492     }
1493 }
1494
1495 #[stable(feature = "rust1", since = "1.0.0")]
1496 impl<T> IndexMut<usize> for Vec<T> {
1497     #[inline]
1498     fn index_mut(&mut self, index: usize) -> &mut T {
1499         // NB built-in indexing via `&mut [T]`
1500         &mut (**self)[index]
1501     }
1502 }
1503
1504
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
1507     type Output = [T];
1508
1509     #[inline]
1510     fn index(&self, index: ops::Range<usize>) -> &[T] {
1511         Index::index(&**self, index)
1512     }
1513 }
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
1516     type Output = [T];
1517
1518     #[inline]
1519     fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
1520         Index::index(&**self, index)
1521     }
1522 }
1523 #[stable(feature = "rust1", since = "1.0.0")]
1524 impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
1525     type Output = [T];
1526
1527     #[inline]
1528     fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
1529         Index::index(&**self, index)
1530     }
1531 }
1532 #[stable(feature = "rust1", since = "1.0.0")]
1533 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1534     type Output = [T];
1535
1536     #[inline]
1537     fn index(&self, _index: ops::RangeFull) -> &[T] {
1538         self
1539     }
1540 }
1541 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1542 impl<T> ops::Index<ops::RangeInclusive<usize>> for Vec<T> {
1543     type Output = [T];
1544
1545     #[inline]
1546     fn index(&self, index: ops::RangeInclusive<usize>) -> &[T] {
1547         Index::index(&**self, index)
1548     }
1549 }
1550 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1551 impl<T> ops::Index<ops::RangeToInclusive<usize>> for Vec<T> {
1552     type Output = [T];
1553
1554     #[inline]
1555     fn index(&self, index: ops::RangeToInclusive<usize>) -> &[T] {
1556         Index::index(&**self, index)
1557     }
1558 }
1559
1560 #[stable(feature = "rust1", since = "1.0.0")]
1561 impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
1562     #[inline]
1563     fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
1564         IndexMut::index_mut(&mut **self, index)
1565     }
1566 }
1567 #[stable(feature = "rust1", since = "1.0.0")]
1568 impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
1569     #[inline]
1570     fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
1571         IndexMut::index_mut(&mut **self, index)
1572     }
1573 }
1574 #[stable(feature = "rust1", since = "1.0.0")]
1575 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
1576     #[inline]
1577     fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
1578         IndexMut::index_mut(&mut **self, index)
1579     }
1580 }
1581 #[stable(feature = "rust1", since = "1.0.0")]
1582 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
1583     #[inline]
1584     fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] {
1585         self
1586     }
1587 }
1588 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1589 impl<T> ops::IndexMut<ops::RangeInclusive<usize>> for Vec<T> {
1590     #[inline]
1591     fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut [T] {
1592         IndexMut::index_mut(&mut **self, index)
1593     }
1594 }
1595 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1596 impl<T> ops::IndexMut<ops::RangeToInclusive<usize>> for Vec<T> {
1597     #[inline]
1598     fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut [T] {
1599         IndexMut::index_mut(&mut **self, index)
1600     }
1601 }
1602
1603 #[stable(feature = "rust1", since = "1.0.0")]
1604 impl<T> ops::Deref for Vec<T> {
1605     type Target = [T];
1606
1607     fn deref(&self) -> &[T] {
1608         unsafe {
1609             let p = self.buf.ptr();
1610             assume(!p.is_null());
1611             slice::from_raw_parts(p, self.len)
1612         }
1613     }
1614 }
1615
1616 #[stable(feature = "rust1", since = "1.0.0")]
1617 impl<T> ops::DerefMut for Vec<T> {
1618     fn deref_mut(&mut self) -> &mut [T] {
1619         unsafe {
1620             let ptr = self.buf.ptr();
1621             assume(!ptr.is_null());
1622             slice::from_raw_parts_mut(ptr, self.len)
1623         }
1624     }
1625 }
1626
1627 #[stable(feature = "rust1", since = "1.0.0")]
1628 impl<T> FromIterator<T> for Vec<T> {
1629     #[inline]
1630     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
1631         <Self as SpecExtend<T, I::IntoIter>>::from_iter(iter.into_iter())
1632     }
1633 }
1634
1635 #[stable(feature = "rust1", since = "1.0.0")]
1636 impl<T> IntoIterator for Vec<T> {
1637     type Item = T;
1638     type IntoIter = IntoIter<T>;
1639
1640     /// Creates a consuming iterator, that is, one that moves each value out of
1641     /// the vector (from start to end). The vector cannot be used after calling
1642     /// this.
1643     ///
1644     /// # Examples
1645     ///
1646     /// ```
1647     /// let v = vec!["a".to_string(), "b".to_string()];
1648     /// for s in v.into_iter() {
1649     ///     // s has type String, not &String
1650     ///     println!("{}", s);
1651     /// }
1652     /// ```
1653     #[inline]
1654     fn into_iter(mut self) -> IntoIter<T> {
1655         unsafe {
1656             let begin = self.as_mut_ptr();
1657             assume(!begin.is_null());
1658             let end = if mem::size_of::<T>() == 0 {
1659                 arith_offset(begin as *const i8, self.len() as isize) as *const T
1660             } else {
1661                 begin.offset(self.len() as isize) as *const T
1662             };
1663             let cap = self.buf.cap();
1664             mem::forget(self);
1665             IntoIter {
1666                 buf: Shared::new(begin),
1667                 cap: cap,
1668                 ptr: begin,
1669                 end: end,
1670             }
1671         }
1672     }
1673 }
1674
1675 #[stable(feature = "rust1", since = "1.0.0")]
1676 impl<'a, T> IntoIterator for &'a Vec<T> {
1677     type Item = &'a T;
1678     type IntoIter = slice::Iter<'a, T>;
1679
1680     fn into_iter(self) -> slice::Iter<'a, T> {
1681         self.iter()
1682     }
1683 }
1684
1685 #[stable(feature = "rust1", since = "1.0.0")]
1686 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1687     type Item = &'a mut T;
1688     type IntoIter = slice::IterMut<'a, T>;
1689
1690     fn into_iter(mut self) -> slice::IterMut<'a, T> {
1691         self.iter_mut()
1692     }
1693 }
1694
1695 #[stable(feature = "rust1", since = "1.0.0")]
1696 impl<T> Extend<T> for Vec<T> {
1697     #[inline]
1698     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1699         <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
1700     }
1701 }
1702
1703 // Specialization trait used for Vec::from_iter and Vec::extend
1704 trait SpecExtend<T, I> {
1705     fn from_iter(iter: I) -> Self;
1706     fn spec_extend(&mut self, iter: I);
1707 }
1708
1709 impl<T, I> SpecExtend<T, I> for Vec<T>
1710     where I: Iterator<Item=T>,
1711 {
1712     default fn from_iter(mut iterator: I) -> Self {
1713         // Unroll the first iteration, as the vector is going to be
1714         // expanded on this iteration in every case when the iterable is not
1715         // empty, but the loop in extend_desugared() is not going to see the
1716         // vector being full in the few subsequent loop iterations.
1717         // So we get better branch prediction.
1718         let mut vector = match iterator.next() {
1719             None => return Vec::new(),
1720             Some(element) => {
1721                 let (lower, _) = iterator.size_hint();
1722                 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1723                 unsafe {
1724                     ptr::write(vector.get_unchecked_mut(0), element);
1725                     vector.set_len(1);
1726                 }
1727                 vector
1728             }
1729         };
1730         <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
1731         vector
1732     }
1733
1734     default fn spec_extend(&mut self, iter: I) {
1735         self.extend_desugared(iter)
1736     }
1737 }
1738
1739 impl<T, I> SpecExtend<T, I> for Vec<T>
1740     where I: TrustedLen<Item=T>,
1741 {
1742     default fn from_iter(iterator: I) -> Self {
1743         let mut vector = Vec::new();
1744         vector.spec_extend(iterator);
1745         vector
1746     }
1747
1748     default fn spec_extend(&mut self, iterator: I) {
1749         // This is the case for a TrustedLen iterator.
1750         let (low, high) = iterator.size_hint();
1751         if let Some(high_value) = high {
1752             debug_assert_eq!(low, high_value,
1753                              "TrustedLen iterator's size hint is not exact: {:?}",
1754                              (low, high));
1755         }
1756         if let Some(additional) = high {
1757             self.reserve(additional);
1758             unsafe {
1759                 let mut ptr = self.as_mut_ptr().offset(self.len() as isize);
1760                 let mut local_len = SetLenOnDrop::new(&mut self.len);
1761                 for element in iterator {
1762                     ptr::write(ptr, element);
1763                     ptr = ptr.offset(1);
1764                     // NB can't overflow since we would have had to alloc the address space
1765                     local_len.increment_len(1);
1766                 }
1767             }
1768         } else {
1769             self.extend_desugared(iterator)
1770         }
1771     }
1772 }
1773
1774 impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
1775     fn from_iter(iterator: IntoIter<T>) -> Self {
1776         // A common case is passing a vector into a function which immediately
1777         // re-collects into a vector. We can short circuit this if the IntoIter
1778         // has not been advanced at all.
1779         if *iterator.buf == iterator.ptr as *mut T {
1780             unsafe {
1781                 let vec = Vec::from_raw_parts(*iterator.buf as *mut T,
1782                                               iterator.len(),
1783                                               iterator.cap);
1784                 mem::forget(iterator);
1785                 vec
1786             }
1787         } else {
1788             let mut vector = Vec::new();
1789             vector.spec_extend(iterator);
1790             vector
1791         }
1792     }
1793
1794     fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
1795         unsafe {
1796             self.append_elements(iterator.as_slice() as _);
1797         }
1798         iterator.ptr = iterator.end;
1799     }
1800 }
1801
1802 impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T>
1803     where I: Iterator<Item=&'a T>,
1804           T: Clone,
1805 {
1806     default fn from_iter(iterator: I) -> Self {
1807         SpecExtend::from_iter(iterator.cloned())
1808     }
1809
1810     default fn spec_extend(&mut self, iterator: I) {
1811         self.spec_extend(iterator.cloned())
1812     }
1813 }
1814
1815 impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T>
1816     where T: Copy,
1817 {
1818     fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
1819         let slice = iterator.as_slice();
1820         self.reserve(slice.len());
1821         unsafe {
1822             let len = self.len();
1823             self.set_len(len + slice.len());
1824             self.get_unchecked_mut(len..).copy_from_slice(slice);
1825         }
1826     }
1827 }
1828
1829 impl<T> Vec<T> {
1830     fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
1831         // This is the case for a general iterator.
1832         //
1833         // This function should be the moral equivalent of:
1834         //
1835         //      for item in iterator {
1836         //          self.push(item);
1837         //      }
1838         while let Some(element) = iterator.next() {
1839             let len = self.len();
1840             if len == self.capacity() {
1841                 let (lower, _) = iterator.size_hint();
1842                 self.reserve(lower.saturating_add(1));
1843             }
1844             unsafe {
1845                 ptr::write(self.get_unchecked_mut(len), element);
1846                 // NB can't overflow since we would have had to alloc the address space
1847                 self.set_len(len + 1);
1848             }
1849         }
1850     }
1851
1852     /// Creates a splicing iterator that replaces the specified range in the vector
1853     /// with the given `replace_with` iterator and yields the removed items.
1854     /// `replace_with` does not need to be the same length as `range`.
1855     ///
1856     /// Note 1: The element range is removed even if the iterator is not
1857     /// consumed until the end.
1858     ///
1859     /// Note 2: It is unspecified how many elements are removed from the vector,
1860     /// if the `Splice` value is leaked.
1861     ///
1862     /// Note 3: The input iterator `replace_with` is only consumed
1863     /// when the `Splice` value is dropped.
1864     ///
1865     /// Note 4: This is optimal if:
1866     ///
1867     /// * The tail (elements in the vector after `range`) is empty,
1868     /// * or `replace_with` yields fewer elements than `range`’s length
1869     /// * or the lower bound of its `size_hint()` is exact.
1870     ///
1871     /// Otherwise, a temporary vector is allocated and the tail is moved twice.
1872     ///
1873     /// # Panics
1874     ///
1875     /// Panics if the starting point is greater than the end point or if
1876     /// the end point is greater than the length of the vector.
1877     ///
1878     /// # Examples
1879     ///
1880     /// ```
1881     /// #![feature(splice)]
1882     /// let mut v = vec![1, 2, 3];
1883     /// let new = [7, 8];
1884     /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
1885     /// assert_eq!(v, &[7, 8, 3]);
1886     /// assert_eq!(u, &[1, 2]);
1887     /// ```
1888     #[inline]
1889     #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
1890     pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<I::IntoIter>
1891         where R: RangeArgument<usize>, I: IntoIterator<Item=T>
1892     {
1893         Splice {
1894             drain: self.drain(range),
1895             replace_with: replace_with.into_iter(),
1896         }
1897     }
1898
1899 }
1900
1901 #[stable(feature = "extend_ref", since = "1.2.0")]
1902 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
1903     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1904         self.spec_extend(iter.into_iter())
1905     }
1906 }
1907
1908 macro_rules! __impl_slice_eq1 {
1909     ($Lhs: ty, $Rhs: ty) => {
1910         __impl_slice_eq1! { $Lhs, $Rhs, Sized }
1911     };
1912     ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
1913         #[stable(feature = "rust1", since = "1.0.0")]
1914         impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
1915             #[inline]
1916             fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] }
1917             #[inline]
1918             fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] }
1919         }
1920     }
1921 }
1922
1923 __impl_slice_eq1! { Vec<A>, Vec<B> }
1924 __impl_slice_eq1! { Vec<A>, &'b [B] }
1925 __impl_slice_eq1! { Vec<A>, &'b mut [B] }
1926 __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone }
1927 __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone }
1928 __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone }
1929
1930 macro_rules! array_impls {
1931     ($($N: expr)+) => {
1932         $(
1933             // NOTE: some less important impls are omitted to reduce code bloat
1934             __impl_slice_eq1! { Vec<A>, [B; $N] }
1935             __impl_slice_eq1! { Vec<A>, &'b [B; $N] }
1936             // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
1937             // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
1938             // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
1939             // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
1940         )+
1941     }
1942 }
1943
1944 array_impls! {
1945      0  1  2  3  4  5  6  7  8  9
1946     10 11 12 13 14 15 16 17 18 19
1947     20 21 22 23 24 25 26 27 28 29
1948     30 31 32
1949 }
1950
1951 /// Implements comparison of vectors, lexicographically.
1952 #[stable(feature = "rust1", since = "1.0.0")]
1953 impl<T: PartialOrd> PartialOrd for Vec<T> {
1954     #[inline]
1955     fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1956         PartialOrd::partial_cmp(&**self, &**other)
1957     }
1958 }
1959
1960 #[stable(feature = "rust1", since = "1.0.0")]
1961 impl<T: Eq> Eq for Vec<T> {}
1962
1963 /// Implements ordering of vectors, lexicographically.
1964 #[stable(feature = "rust1", since = "1.0.0")]
1965 impl<T: Ord> Ord for Vec<T> {
1966     #[inline]
1967     fn cmp(&self, other: &Vec<T>) -> Ordering {
1968         Ord::cmp(&**self, &**other)
1969     }
1970 }
1971
1972 #[stable(feature = "rust1", since = "1.0.0")]
1973 unsafe impl<#[may_dangle] T> Drop for Vec<T> {
1974     fn drop(&mut self) {
1975         unsafe {
1976             // use drop for [T]
1977             ptr::drop_in_place(&mut self[..]);
1978         }
1979         // RawVec handles deallocation
1980     }
1981 }
1982
1983 #[stable(feature = "rust1", since = "1.0.0")]
1984 impl<T> Default for Vec<T> {
1985     /// Creates an empty `Vec<T>`.
1986     fn default() -> Vec<T> {
1987         Vec::new()
1988     }
1989 }
1990
1991 #[stable(feature = "rust1", since = "1.0.0")]
1992 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
1993     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1994         fmt::Debug::fmt(&**self, f)
1995     }
1996 }
1997
1998 #[stable(feature = "rust1", since = "1.0.0")]
1999 impl<T> AsRef<Vec<T>> for Vec<T> {
2000     fn as_ref(&self) -> &Vec<T> {
2001         self
2002     }
2003 }
2004
2005 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2006 impl<T> AsMut<Vec<T>> for Vec<T> {
2007     fn as_mut(&mut self) -> &mut Vec<T> {
2008         self
2009     }
2010 }
2011
2012 #[stable(feature = "rust1", since = "1.0.0")]
2013 impl<T> AsRef<[T]> for Vec<T> {
2014     fn as_ref(&self) -> &[T] {
2015         self
2016     }
2017 }
2018
2019 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2020 impl<T> AsMut<[T]> for Vec<T> {
2021     fn as_mut(&mut self) -> &mut [T] {
2022         self
2023     }
2024 }
2025
2026 #[stable(feature = "rust1", since = "1.0.0")]
2027 impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
2028     #[cfg(not(test))]
2029     fn from(s: &'a [T]) -> Vec<T> {
2030         s.to_vec()
2031     }
2032     #[cfg(test)]
2033     fn from(s: &'a [T]) -> Vec<T> {
2034         ::slice::to_vec(s)
2035     }
2036 }
2037
2038 #[stable(feature = "vec_from_mut", since = "1.21.0")]
2039 impl<'a, T: Clone> From<&'a mut [T]> for Vec<T> {
2040     #[cfg(not(test))]
2041     fn from(s: &'a mut [T]) -> Vec<T> {
2042         s.to_vec()
2043     }
2044     #[cfg(test)]
2045     fn from(s: &'a mut [T]) -> Vec<T> {
2046         ::slice::to_vec(s)
2047     }
2048 }
2049
2050 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2051 impl<'a, T> From<Cow<'a, [T]>> for Vec<T> where [T]: ToOwned<Owned=Vec<T>> {
2052     fn from(s: Cow<'a, [T]>) -> Vec<T> {
2053         s.into_owned()
2054     }
2055 }
2056
2057 // note: test pulls in libstd, which causes errors here
2058 #[cfg(not(test))]
2059 #[stable(feature = "vec_from_box", since = "1.17.0")]
2060 impl<T> From<Box<[T]>> for Vec<T> {
2061     fn from(s: Box<[T]>) -> Vec<T> {
2062         s.into_vec()
2063     }
2064 }
2065
2066 #[stable(feature = "box_from_vec", since = "1.17.0")]
2067 impl<T> Into<Box<[T]>> for Vec<T> {
2068     fn into(self) -> Box<[T]> {
2069         self.into_boxed_slice()
2070     }
2071 }
2072
2073 #[stable(feature = "rust1", since = "1.0.0")]
2074 impl<'a> From<&'a str> for Vec<u8> {
2075     fn from(s: &'a str) -> Vec<u8> {
2076         From::from(s.as_bytes())
2077     }
2078 }
2079
2080 ////////////////////////////////////////////////////////////////////////////////
2081 // Clone-on-write
2082 ////////////////////////////////////////////////////////////////////////////////
2083
2084 #[stable(feature = "cow_from_vec", since = "1.7.0")]
2085 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2086     fn from(s: &'a [T]) -> Cow<'a, [T]> {
2087         Cow::Borrowed(s)
2088     }
2089 }
2090
2091 #[stable(feature = "cow_from_vec", since = "1.7.0")]
2092 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2093     fn from(v: Vec<T>) -> Cow<'a, [T]> {
2094         Cow::Owned(v)
2095     }
2096 }
2097
2098 #[stable(feature = "rust1", since = "1.0.0")]
2099 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
2100     fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2101         Cow::Owned(FromIterator::from_iter(it))
2102     }
2103 }
2104
2105 ////////////////////////////////////////////////////////////////////////////////
2106 // Iterators
2107 ////////////////////////////////////////////////////////////////////////////////
2108
2109 /// An iterator that moves out of a vector.
2110 ///
2111 /// This `struct` is created by the `into_iter` method on [`Vec`][`Vec`] (provided
2112 /// by the [`IntoIterator`] trait).
2113 ///
2114 /// [`Vec`]: struct.Vec.html
2115 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
2116 #[stable(feature = "rust1", since = "1.0.0")]
2117 pub struct IntoIter<T> {
2118     buf: Shared<T>,
2119     cap: usize,
2120     ptr: *const T,
2121     end: *const T,
2122 }
2123
2124 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
2125 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2126     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2127         f.debug_tuple("IntoIter")
2128             .field(&self.as_slice())
2129             .finish()
2130     }
2131 }
2132
2133 impl<T> IntoIter<T> {
2134     /// Returns the remaining items of this iterator as a slice.
2135     ///
2136     /// # Examples
2137     ///
2138     /// ```
2139     /// let vec = vec!['a', 'b', 'c'];
2140     /// let mut into_iter = vec.into_iter();
2141     /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2142     /// let _ = into_iter.next().unwrap();
2143     /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2144     /// ```
2145     #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2146     pub fn as_slice(&self) -> &[T] {
2147         unsafe {
2148             slice::from_raw_parts(self.ptr, self.len())
2149         }
2150     }
2151
2152     /// Returns the remaining items of this iterator as a mutable slice.
2153     ///
2154     /// # Examples
2155     ///
2156     /// ```
2157     /// let vec = vec!['a', 'b', 'c'];
2158     /// let mut into_iter = vec.into_iter();
2159     /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2160     /// into_iter.as_mut_slice()[2] = 'z';
2161     /// assert_eq!(into_iter.next().unwrap(), 'a');
2162     /// assert_eq!(into_iter.next().unwrap(), 'b');
2163     /// assert_eq!(into_iter.next().unwrap(), 'z');
2164     /// ```
2165     #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2166     pub fn as_mut_slice(&mut self) -> &mut [T] {
2167         unsafe {
2168             slice::from_raw_parts_mut(self.ptr as *mut T, self.len())
2169         }
2170     }
2171 }
2172
2173 #[stable(feature = "rust1", since = "1.0.0")]
2174 unsafe impl<T: Send> Send for IntoIter<T> {}
2175 #[stable(feature = "rust1", since = "1.0.0")]
2176 unsafe impl<T: Sync> Sync for IntoIter<T> {}
2177
2178 #[stable(feature = "rust1", since = "1.0.0")]
2179 impl<T> Iterator for IntoIter<T> {
2180     type Item = T;
2181
2182     #[inline]
2183     fn next(&mut self) -> Option<T> {
2184         unsafe {
2185             if self.ptr as *const _ == self.end {
2186                 None
2187             } else {
2188                 if mem::size_of::<T>() == 0 {
2189                     // purposefully don't use 'ptr.offset' because for
2190                     // vectors with 0-size elements this would return the
2191                     // same pointer.
2192                     self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
2193
2194                     // Use a non-null pointer value
2195                     Some(ptr::read(EMPTY as *mut T))
2196                 } else {
2197                     let old = self.ptr;
2198                     self.ptr = self.ptr.offset(1);
2199
2200                     Some(ptr::read(old))
2201                 }
2202             }
2203         }
2204     }
2205
2206     #[inline]
2207     fn size_hint(&self) -> (usize, Option<usize>) {
2208         let exact = match self.ptr.offset_to(self.end) {
2209             Some(x) => x as usize,
2210             None => (self.end as usize).wrapping_sub(self.ptr as usize),
2211         };
2212         (exact, Some(exact))
2213     }
2214
2215     #[inline]
2216     fn count(self) -> usize {
2217         self.len()
2218     }
2219 }
2220
2221 #[stable(feature = "rust1", since = "1.0.0")]
2222 impl<T> DoubleEndedIterator for IntoIter<T> {
2223     #[inline]
2224     fn next_back(&mut self) -> Option<T> {
2225         unsafe {
2226             if self.end == self.ptr {
2227                 None
2228             } else {
2229                 if mem::size_of::<T>() == 0 {
2230                     // See above for why 'ptr.offset' isn't used
2231                     self.end = arith_offset(self.end as *const i8, -1) as *mut T;
2232
2233                     // Use a non-null pointer value
2234                     Some(ptr::read(EMPTY as *mut T))
2235                 } else {
2236                     self.end = self.end.offset(-1);
2237
2238                     Some(ptr::read(self.end))
2239                 }
2240             }
2241         }
2242     }
2243 }
2244
2245 #[stable(feature = "rust1", since = "1.0.0")]
2246 impl<T> ExactSizeIterator for IntoIter<T> {
2247     fn is_empty(&self) -> bool {
2248         self.ptr == self.end
2249     }
2250 }
2251
2252 #[unstable(feature = "fused", issue = "35602")]
2253 impl<T> FusedIterator for IntoIter<T> {}
2254
2255 #[unstable(feature = "trusted_len", issue = "37572")]
2256 unsafe impl<T> TrustedLen for IntoIter<T> {}
2257
2258 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
2259 impl<T: Clone> Clone for IntoIter<T> {
2260     fn clone(&self) -> IntoIter<T> {
2261         self.as_slice().to_owned().into_iter()
2262     }
2263 }
2264
2265 #[stable(feature = "rust1", since = "1.0.0")]
2266 unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
2267     fn drop(&mut self) {
2268         // destroy the remaining elements
2269         for _x in self.by_ref() {}
2270
2271         // RawVec handles deallocation
2272         let _ = unsafe { RawVec::from_raw_parts(self.buf.as_mut_ptr(), self.cap) };
2273     }
2274 }
2275
2276 /// A draining iterator for `Vec<T>`.
2277 ///
2278 /// This `struct` is created by the [`drain`] method on [`Vec`].
2279 ///
2280 /// [`drain`]: struct.Vec.html#method.drain
2281 /// [`Vec`]: struct.Vec.html
2282 #[stable(feature = "drain", since = "1.6.0")]
2283 pub struct Drain<'a, T: 'a> {
2284     /// Index of tail to preserve
2285     tail_start: usize,
2286     /// Length of tail
2287     tail_len: usize,
2288     /// Current remaining range to remove
2289     iter: slice::Iter<'a, T>,
2290     vec: Shared<Vec<T>>,
2291 }
2292
2293 #[stable(feature = "collection_debug", since = "1.17.0")]
2294 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Drain<'a, T> {
2295     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2296         f.debug_tuple("Drain")
2297          .field(&self.iter.as_slice())
2298          .finish()
2299     }
2300 }
2301
2302 #[stable(feature = "drain", since = "1.6.0")]
2303 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
2304 #[stable(feature = "drain", since = "1.6.0")]
2305 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
2306
2307 #[stable(feature = "drain", since = "1.6.0")]
2308 impl<'a, T> Iterator for Drain<'a, T> {
2309     type Item = T;
2310
2311     #[inline]
2312     fn next(&mut self) -> Option<T> {
2313         self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
2314     }
2315
2316     fn size_hint(&self) -> (usize, Option<usize>) {
2317         self.iter.size_hint()
2318     }
2319 }
2320
2321 #[stable(feature = "drain", since = "1.6.0")]
2322 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
2323     #[inline]
2324     fn next_back(&mut self) -> Option<T> {
2325         self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
2326     }
2327 }
2328
2329 #[stable(feature = "drain", since = "1.6.0")]
2330 impl<'a, T> Drop for Drain<'a, T> {
2331     fn drop(&mut self) {
2332         // exhaust self first
2333         while let Some(_) = self.next() {}
2334
2335         if self.tail_len > 0 {
2336             unsafe {
2337                 let source_vec = &mut *self.vec.as_mut_ptr();
2338                 // memmove back untouched tail, update to new length
2339                 let start = source_vec.len();
2340                 let tail = self.tail_start;
2341                 let src = source_vec.as_ptr().offset(tail as isize);
2342                 let dst = source_vec.as_mut_ptr().offset(start as isize);
2343                 ptr::copy(src, dst, self.tail_len);
2344                 source_vec.set_len(start + self.tail_len);
2345             }
2346         }
2347     }
2348 }
2349
2350
2351 #[stable(feature = "drain", since = "1.6.0")]
2352 impl<'a, T> ExactSizeIterator for Drain<'a, T> {
2353     fn is_empty(&self) -> bool {
2354         self.iter.is_empty()
2355     }
2356 }
2357
2358 #[unstable(feature = "fused", issue = "35602")]
2359 impl<'a, T> FusedIterator for Drain<'a, T> {}
2360
2361 /// A place for insertion at the back of a `Vec`.
2362 ///
2363 /// See [`Vec::place_back`](struct.Vec.html#method.place_back) for details.
2364 #[must_use = "places do nothing unless written to with `<-` syntax"]
2365 #[unstable(feature = "collection_placement",
2366            reason = "struct name and placement protocol are subject to change",
2367            issue = "30172")]
2368 #[derive(Debug)]
2369 pub struct PlaceBack<'a, T: 'a> {
2370     vec: &'a mut Vec<T>,
2371 }
2372
2373 #[unstable(feature = "collection_placement",
2374            reason = "placement protocol is subject to change",
2375            issue = "30172")]
2376 impl<'a, T> Placer<T> for PlaceBack<'a, T> {
2377     type Place = PlaceBack<'a, T>;
2378
2379     fn make_place(self) -> Self {
2380         // This will panic or abort if we would allocate > isize::MAX bytes
2381         // or if the length increment would overflow for zero-sized types.
2382         if self.vec.len == self.vec.buf.cap() {
2383             self.vec.buf.double();
2384         }
2385         self
2386     }
2387 }
2388
2389 #[unstable(feature = "collection_placement",
2390            reason = "placement protocol is subject to change",
2391            issue = "30172")]
2392 impl<'a, T> Place<T> for PlaceBack<'a, T> {
2393     fn pointer(&mut self) -> *mut T {
2394         unsafe { self.vec.as_mut_ptr().offset(self.vec.len as isize) }
2395     }
2396 }
2397
2398 #[unstable(feature = "collection_placement",
2399            reason = "placement protocol is subject to change",
2400            issue = "30172")]
2401 impl<'a, T> InPlace<T> for PlaceBack<'a, T> {
2402     type Owner = &'a mut T;
2403
2404     unsafe fn finalize(mut self) -> &'a mut T {
2405         let ptr = self.pointer();
2406         self.vec.len += 1;
2407         &mut *ptr
2408     }
2409 }
2410
2411
2412 /// A splicing iterator for `Vec`.
2413 ///
2414 /// This struct is created by the [`splice()`] method on [`Vec`]. See its
2415 /// documentation for more.
2416 ///
2417 /// [`splice()`]: struct.Vec.html#method.splice
2418 /// [`Vec`]: struct.Vec.html
2419 #[derive(Debug)]
2420 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2421 pub struct Splice<'a, I: Iterator + 'a> {
2422     drain: Drain<'a, I::Item>,
2423     replace_with: I,
2424 }
2425
2426 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2427 impl<'a, I: Iterator> Iterator for Splice<'a, I> {
2428     type Item = I::Item;
2429
2430     fn next(&mut self) -> Option<Self::Item> {
2431         self.drain.next()
2432     }
2433
2434     fn size_hint(&self) -> (usize, Option<usize>) {
2435         self.drain.size_hint()
2436     }
2437 }
2438
2439 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2440 impl<'a, I: Iterator> DoubleEndedIterator for Splice<'a, I> {
2441     fn next_back(&mut self) -> Option<Self::Item> {
2442         self.drain.next_back()
2443     }
2444 }
2445
2446 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2447 impl<'a, I: Iterator> ExactSizeIterator for Splice<'a, I> {}
2448
2449
2450 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2451 impl<'a, I: Iterator> Drop for Splice<'a, I> {
2452     fn drop(&mut self) {
2453         // exhaust drain first
2454         while let Some(_) = self.drain.next() {}
2455
2456
2457         unsafe {
2458             if self.drain.tail_len == 0 {
2459                 let vec = &mut *self.drain.vec.as_mut_ptr();
2460                 vec.extend(self.replace_with.by_ref());
2461                 return
2462             }
2463
2464             // First fill the range left by drain().
2465             if !self.drain.fill(&mut self.replace_with) {
2466                 return
2467             }
2468
2469             // There may be more elements. Use the lower bound as an estimate.
2470             // FIXME: Is the upper bound a better guess? Or something else?
2471             let (lower_bound, _upper_bound) = self.replace_with.size_hint();
2472             if lower_bound > 0  {
2473                 self.drain.move_tail(lower_bound);
2474                 if !self.drain.fill(&mut self.replace_with) {
2475                     return
2476                 }
2477             }
2478
2479             // Collect any remaining elements.
2480             // This is a zero-length vector which does not allocate if `lower_bound` was exact.
2481             let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
2482             // Now we have an exact count.
2483             if collected.len() > 0 {
2484                 self.drain.move_tail(collected.len());
2485                 let filled = self.drain.fill(&mut collected);
2486                 debug_assert!(filled);
2487                 debug_assert_eq!(collected.len(), 0);
2488             }
2489         }
2490         // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
2491     }
2492 }
2493
2494 /// Private helper methods for `Splice::drop`
2495 impl<'a, T> Drain<'a, T> {
2496     /// The range from `self.vec.len` to `self.tail_start` contains elements
2497     /// that have been moved out.
2498     /// Fill that range as much as possible with new elements from the `replace_with` iterator.
2499     /// Return whether we filled the entire range. (`replace_with.next()` didn’t return `None`.)
2500     unsafe fn fill<I: Iterator<Item=T>>(&mut self, replace_with: &mut I) -> bool {
2501         let vec = &mut *self.vec.as_mut_ptr();
2502         let range_start = vec.len;
2503         let range_end = self.tail_start;
2504         let range_slice = slice::from_raw_parts_mut(
2505             vec.as_mut_ptr().offset(range_start as isize),
2506             range_end - range_start);
2507
2508         for place in range_slice {
2509             if let Some(new_item) = replace_with.next() {
2510                 ptr::write(place, new_item);
2511                 vec.len += 1;
2512             } else {
2513                 return false
2514             }
2515         }
2516         true
2517     }
2518
2519     /// Make room for inserting more elements before the tail.
2520     unsafe fn move_tail(&mut self, extra_capacity: usize) {
2521         let vec = &mut *self.vec.as_mut_ptr();
2522         let used_capacity = self.tail_start + self.tail_len;
2523         vec.buf.reserve(used_capacity, extra_capacity);
2524
2525         let new_tail_start = self.tail_start + extra_capacity;
2526         let src = vec.as_ptr().offset(self.tail_start as isize);
2527         let dst = vec.as_mut_ptr().offset(new_tail_start as isize);
2528         ptr::copy(src, dst, self.tail_len);
2529         self.tail_start = new_tail_start;
2530     }
2531 }