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