1 // Copyright 2012-2015 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.
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.
11 //! A dynamically-sized view into a contiguous sequence, `[T]`.
13 //! Slices are a view into a block of memory represented as a pointer and a
18 //! let vec = vec![1, 2, 3];
19 //! let int_slice = &vec[..];
20 //! // coercing an array to a slice
21 //! let str_slice: &[&str] = &["one", "two", "three"];
24 //! Slices are either mutable or shared. The shared slice type is `&[T]`,
25 //! while the mutable slice type is `&mut [T]`, where `T` represents the element
26 //! type. For example, you can mutate the block of memory that a mutable slice
30 //! let x = &mut [1, 2, 3];
32 //! assert_eq!(x, &[1, 7, 3]);
35 //! Here are some of the things this module contains:
39 //! There are several structs that are useful for slices, such as `Iter`, which
40 //! represents iteration over a slice.
42 //! ## Trait Implementations
44 //! There are several implementations of common traits for slices. Some examples
48 //! * `Eq`, `Ord` - for slices whose element type are `Eq` or `Ord`.
49 //! * `Hash` - for slices whose element type is `Hash`
53 //! The slices implement `IntoIterator`. The iterator yields references to the
57 //! let numbers = &[0, 1, 2];
58 //! for n in numbers {
59 //! println!("{} is a number!", n);
63 //! The mutable slice yields mutable references to the elements:
66 //! let mut scores = [7, 8, 9];
67 //! for score in &mut scores[..] {
72 //! This iterator yields mutable references to the slice's elements, so while
73 //! the element type of the slice is `i32`, the element type of the iterator is
76 //! * `.iter()` and `.iter_mut()` are the explicit methods to return the default
78 //! * Further methods that return iterators are `.split()`, `.splitn()`,
79 //! `.chunks()`, `.windows()` and more.
81 //! *[See also the slice primitive type](../primitive.slice.html).*
82 #![stable(feature = "rust1", since = "1.0.0")]
84 // Many of the usings in this module are only used in the test configuration.
85 // It's cleaner to just turn off the unused_imports warning than to fix them.
86 #![allow(unused_imports)]
88 use alloc::boxed::Box;
89 use core::clone::Clone;
90 use core::cmp::Ordering::{self, Greater, Less};
91 use core::cmp::{self, Ord, PartialEq};
92 use core::iter::Iterator;
93 use core::marker::Sized;
94 use core::mem::size_of;
97 use core::option::Option::{self, Some, None};
99 use core::result::Result;
100 use core::slice as core_slice;
102 use borrow::{Borrow, BorrowMut, ToOwned};
105 #[stable(feature = "rust1", since = "1.0.0")]
106 pub use core::slice::{Chunks, Windows};
107 #[stable(feature = "rust1", since = "1.0.0")]
108 pub use core::slice::{Iter, IterMut};
109 #[stable(feature = "rust1", since = "1.0.0")]
110 pub use core::slice::{SplitMut, ChunksMut, Split};
111 #[stable(feature = "rust1", since = "1.0.0")]
112 pub use core::slice::{SplitN, RSplitN, SplitNMut, RSplitNMut};
113 #[unstable(feature = "ref_slice", issue = "27774")]
115 pub use core::slice::{bytes, mut_ref_slice, ref_slice};
116 #[stable(feature = "rust1", since = "1.0.0")]
117 pub use core::slice::{from_raw_parts, from_raw_parts_mut};
119 ////////////////////////////////////////////////////////////////////////////////
120 // Basic slice extension methods
121 ////////////////////////////////////////////////////////////////////////////////
123 // HACK(japaric) needed for the implementation of `vec!` macro during testing
124 // NB see the hack module in this file for more details
126 pub use self::hack::into_vec;
128 // HACK(japaric) needed for the implementation of `Vec::clone` during testing
129 // NB see the hack module in this file for more details
131 pub use self::hack::to_vec;
133 // HACK(japaric): With cfg(test) `impl [T]` is not available, these three
134 // functions are actually methods that are in `impl [T]` but not in
135 // `core::slice::SliceExt` - we need to supply these functions for the
136 // `test_permutations` test
138 use alloc::boxed::Box;
139 use core::clone::Clone;
141 use core::iter::Iterator;
144 use core::option::Option::{Some, None};
147 use string::ToString;
150 pub fn into_vec<T>(mut b: Box<[T]>) -> Vec<T> {
152 let xs = Vec::from_raw_parts(b.as_mut_ptr(), b.len(), b.len());
159 pub fn to_vec<T>(s: &[T]) -> Vec<T>
162 let mut vector = Vec::with_capacity(s.len());
163 vector.extend_from_slice(s);
168 /// Allocating extension methods for slices.
172 /// Returns the number of elements in the slice.
177 /// let a = [1, 2, 3];
178 /// assert_eq!(a.len(), 3);
180 #[stable(feature = "rust1", since = "1.0.0")]
182 pub fn len(&self) -> usize {
183 core_slice::SliceExt::len(self)
186 /// Returns true if the slice has a length of 0
191 /// let a = [1, 2, 3];
192 /// assert!(!a.is_empty());
194 #[stable(feature = "rust1", since = "1.0.0")]
196 pub fn is_empty(&self) -> bool {
197 core_slice::SliceExt::is_empty(self)
200 /// Returns the first element of a slice, or `None` if it is empty.
205 /// let v = [10, 40, 30];
206 /// assert_eq!(Some(&10), v.first());
208 /// let w: &[i32] = &[];
209 /// assert_eq!(None, w.first());
211 #[stable(feature = "rust1", since = "1.0.0")]
213 pub fn first(&self) -> Option<&T> {
214 core_slice::SliceExt::first(self)
217 /// Returns a mutable pointer to the first element of a slice, or `None` if it is empty
218 #[stable(feature = "rust1", since = "1.0.0")]
220 pub fn first_mut(&mut self) -> Option<&mut T> {
221 core_slice::SliceExt::first_mut(self)
224 /// Returns the first and all the rest of the elements of a slice.
225 #[stable(feature = "slice_splits", since = "1.5.0")]
227 pub fn split_first(&self) -> Option<(&T, &[T])> {
228 core_slice::SliceExt::split_first(self)
231 /// Returns the first and all the rest of the elements of a slice.
232 #[stable(feature = "slice_splits", since = "1.5.0")]
234 pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
235 core_slice::SliceExt::split_first_mut(self)
238 /// Returns the last and all the rest of the elements of a slice.
239 #[stable(feature = "slice_splits", since = "1.5.0")]
241 pub fn split_last(&self) -> Option<(&T, &[T])> {
242 core_slice::SliceExt::split_last(self)
246 /// Returns the last and all the rest of the elements of a slice.
247 #[stable(feature = "slice_splits", since = "1.5.0")]
249 pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
250 core_slice::SliceExt::split_last_mut(self)
253 /// Returns the last element of a slice, or `None` if it is empty.
258 /// let v = [10, 40, 30];
259 /// assert_eq!(Some(&30), v.last());
261 /// let w: &[i32] = &[];
262 /// assert_eq!(None, w.last());
264 #[stable(feature = "rust1", since = "1.0.0")]
266 pub fn last(&self) -> Option<&T> {
267 core_slice::SliceExt::last(self)
270 /// Returns a mutable pointer to the last item in the slice.
271 #[stable(feature = "rust1", since = "1.0.0")]
273 pub fn last_mut(&mut self) -> Option<&mut T> {
274 core_slice::SliceExt::last_mut(self)
277 /// Returns the element of a slice at the given index, or `None` if the
278 /// index is out of bounds.
283 /// let v = [10, 40, 30];
284 /// assert_eq!(Some(&40), v.get(1));
285 /// assert_eq!(None, v.get(3));
287 #[stable(feature = "rust1", since = "1.0.0")]
289 pub fn get(&self, index: usize) -> Option<&T> {
290 core_slice::SliceExt::get(self, index)
293 /// Returns a mutable reference to the element at the given index,
294 /// or `None` if the index is out of bounds
295 #[stable(feature = "rust1", since = "1.0.0")]
297 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
298 core_slice::SliceExt::get_mut(self, index)
301 /// Returns a pointer to the element at the given index, without doing
303 #[stable(feature = "rust1", since = "1.0.0")]
305 pub unsafe fn get_unchecked(&self, index: usize) -> &T {
306 core_slice::SliceExt::get_unchecked(self, index)
309 /// Returns an unsafe mutable pointer to the element in index
310 #[stable(feature = "rust1", since = "1.0.0")]
312 pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
313 core_slice::SliceExt::get_unchecked_mut(self, index)
316 /// Returns an raw pointer to the slice's buffer
318 /// The caller must ensure that the slice outlives the pointer this
319 /// function returns, or else it will end up pointing to garbage.
321 /// Modifying the slice may cause its buffer to be reallocated, which
322 /// would also make any pointers to it invalid.
323 #[stable(feature = "rust1", since = "1.0.0")]
325 pub fn as_ptr(&self) -> *const T {
326 core_slice::SliceExt::as_ptr(self)
329 /// Returns an unsafe mutable pointer to the slice's buffer.
331 /// The caller must ensure that the slice outlives the pointer this
332 /// function returns, or else it will end up pointing to garbage.
334 /// Modifying the slice may cause its buffer to be reallocated, which
335 /// would also make any pointers to it invalid.
336 #[stable(feature = "rust1", since = "1.0.0")]
338 pub fn as_mut_ptr(&mut self) -> *mut T {
339 core_slice::SliceExt::as_mut_ptr(self)
342 /// Swaps two elements in a slice.
346 /// * a - The index of the first element
347 /// * b - The index of the second element
351 /// Panics if `a` or `b` are out of bounds.
356 /// let mut v = ["a", "b", "c", "d"];
358 /// assert!(v == ["a", "d", "c", "b"]);
360 #[stable(feature = "rust1", since = "1.0.0")]
362 pub fn swap(&mut self, a: usize, b: usize) {
363 core_slice::SliceExt::swap(self, a, b)
366 /// Reverse the order of elements in a slice, in place.
371 /// let mut v = [1, 2, 3];
373 /// assert!(v == [3, 2, 1]);
375 #[stable(feature = "rust1", since = "1.0.0")]
377 pub fn reverse(&mut self) {
378 core_slice::SliceExt::reverse(self)
381 /// Returns an iterator over the slice.
382 #[stable(feature = "rust1", since = "1.0.0")]
384 pub fn iter(&self) -> Iter<T> {
385 core_slice::SliceExt::iter(self)
388 /// Returns an iterator that allows modifying each value
389 #[stable(feature = "rust1", since = "1.0.0")]
391 pub fn iter_mut(&mut self) -> IterMut<T> {
392 core_slice::SliceExt::iter_mut(self)
395 /// Returns an iterator over all contiguous windows of length
396 /// `size`. The windows overlap. If the slice is shorter than
397 /// `size`, the iterator returns no values.
401 /// Panics if `size` is 0.
405 /// Print the adjacent pairs of a slice (i.e. `[1,2]`, `[2,3]`,
409 /// let v = &[1, 2, 3, 4];
410 /// for win in v.windows(2) {
411 /// println!("{:?}", win);
414 #[stable(feature = "rust1", since = "1.0.0")]
416 pub fn windows(&self, size: usize) -> Windows<T> {
417 core_slice::SliceExt::windows(self, size)
420 /// Returns an iterator over `size` elements of the slice at a
421 /// time. The chunks do not overlap. If `size` does not divide the
422 /// length of the slice, then the last chunk will not have length
427 /// Panics if `size` is 0.
431 /// Print the slice two elements at a time (i.e. `[1,2]`,
435 /// let v = &[1, 2, 3, 4, 5];
436 /// for win in v.chunks(2) {
437 /// println!("{:?}", win);
440 #[stable(feature = "rust1", since = "1.0.0")]
442 pub fn chunks(&self, size: usize) -> Chunks<T> {
443 core_slice::SliceExt::chunks(self, size)
446 /// Returns an iterator over `chunk_size` elements of the slice at a time.
447 /// The chunks are mutable and do not overlap. If `chunk_size` does
448 /// not divide the length of the slice, then the last chunk will not
449 /// have length `chunk_size`.
453 /// Panics if `chunk_size` is 0.
454 #[stable(feature = "rust1", since = "1.0.0")]
456 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
457 core_slice::SliceExt::chunks_mut(self, chunk_size)
460 /// Divides one slice into two at an index.
462 /// The first will contain all indices from `[0, mid)` (excluding
463 /// the index `mid` itself) and the second will contain all
464 /// indices from `[mid, len)` (excluding the index `len` itself).
468 /// Panics if `mid > len`.
473 /// let v = [10, 40, 30, 20, 50];
474 /// let (v1, v2) = v.split_at(2);
475 /// assert_eq!([10, 40], v1);
476 /// assert_eq!([30, 20, 50], v2);
478 #[stable(feature = "rust1", since = "1.0.0")]
480 pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
481 core_slice::SliceExt::split_at(self, mid)
484 /// Divides one `&mut` into two at an index.
486 /// The first will contain all indices from `[0, mid)` (excluding
487 /// the index `mid` itself) and the second will contain all
488 /// indices from `[mid, len)` (excluding the index `len` itself).
492 /// Panics if `mid > len`.
497 /// let mut v = [1, 2, 3, 4, 5, 6];
499 /// // scoped to restrict the lifetime of the borrows
501 /// let (left, right) = v.split_at_mut(0);
502 /// assert!(left == []);
503 /// assert!(right == [1, 2, 3, 4, 5, 6]);
507 /// let (left, right) = v.split_at_mut(2);
508 /// assert!(left == [1, 2]);
509 /// assert!(right == [3, 4, 5, 6]);
513 /// let (left, right) = v.split_at_mut(6);
514 /// assert!(left == [1, 2, 3, 4, 5, 6]);
515 /// assert!(right == []);
518 #[stable(feature = "rust1", since = "1.0.0")]
520 pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
521 core_slice::SliceExt::split_at_mut(self, mid)
524 /// Returns an iterator over subslices separated by elements that match
525 /// `pred`. The matched element is not contained in the subslices.
529 /// Print the slice split by numbers divisible by 3 (i.e. `[10, 40]`,
533 /// let v = [10, 40, 30, 20, 60, 50];
534 /// for group in v.split(|num| *num % 3 == 0) {
535 /// println!("{:?}", group);
538 #[stable(feature = "rust1", since = "1.0.0")]
540 pub fn split<F>(&self, pred: F) -> Split<T, F>
541 where F: FnMut(&T) -> bool
543 core_slice::SliceExt::split(self, pred)
546 /// Returns an iterator over mutable subslices separated by elements that
547 /// match `pred`. The matched element is not contained in the subslices.
548 #[stable(feature = "rust1", since = "1.0.0")]
550 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F>
551 where F: FnMut(&T) -> bool
553 core_slice::SliceExt::split_mut(self, pred)
556 /// Returns an iterator over subslices separated by elements that match
557 /// `pred`, limited to returning at most `n` items. The matched element is
558 /// not contained in the subslices.
560 /// The last element returned, if any, will contain the remainder of the
565 /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
569 /// let v = [10, 40, 30, 20, 60, 50];
570 /// for group in v.splitn(2, |num| *num % 3 == 0) {
571 /// println!("{:?}", group);
574 #[stable(feature = "rust1", since = "1.0.0")]
576 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F>
577 where F: FnMut(&T) -> bool
579 core_slice::SliceExt::splitn(self, n, pred)
582 /// Returns an iterator over subslices separated by elements that match
583 /// `pred`, limited to returning at most `n` items. The matched element is
584 /// not contained in the subslices.
586 /// The last element returned, if any, will contain the remainder of the
588 #[stable(feature = "rust1", since = "1.0.0")]
590 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, F>
591 where F: FnMut(&T) -> bool
593 core_slice::SliceExt::splitn_mut(self, n, pred)
596 /// Returns an iterator over subslices separated by elements that match
597 /// `pred` limited to returning at most `n` items. This starts at the end of
598 /// the slice and works backwards. The matched element is not contained in
601 /// The last element returned, if any, will contain the remainder of the
606 /// Print the slice split once, starting from the end, by numbers divisible
607 /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
610 /// let v = [10, 40, 30, 20, 60, 50];
611 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
612 /// println!("{:?}", group);
615 #[stable(feature = "rust1", since = "1.0.0")]
617 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F>
618 where F: FnMut(&T) -> bool
620 core_slice::SliceExt::rsplitn(self, n, pred)
623 /// Returns an iterator over subslices separated by elements that match
624 /// `pred` limited to returning at most `n` items. This starts at the end of
625 /// the slice and works backwards. The matched element is not contained in
628 /// The last element returned, if any, will contain the remainder of the
630 #[stable(feature = "rust1", since = "1.0.0")]
632 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, F>
633 where F: FnMut(&T) -> bool
635 core_slice::SliceExt::rsplitn_mut(self, n, pred)
638 /// Returns true if the slice contains an element with the given value.
643 /// let v = [10, 40, 30];
644 /// assert!(v.contains(&30));
645 /// assert!(!v.contains(&50));
647 #[stable(feature = "rust1", since = "1.0.0")]
648 pub fn contains(&self, x: &T) -> bool
651 core_slice::SliceExt::contains(self, x)
654 /// Returns true if `needle` is a prefix of the slice.
659 /// let v = [10, 40, 30];
660 /// assert!(v.starts_with(&[10]));
661 /// assert!(v.starts_with(&[10, 40]));
662 /// assert!(!v.starts_with(&[50]));
663 /// assert!(!v.starts_with(&[10, 50]));
665 #[stable(feature = "rust1", since = "1.0.0")]
666 pub fn starts_with(&self, needle: &[T]) -> bool
669 core_slice::SliceExt::starts_with(self, needle)
672 /// Returns true if `needle` is a suffix of the slice.
677 /// let v = [10, 40, 30];
678 /// assert!(v.ends_with(&[30]));
679 /// assert!(v.ends_with(&[40, 30]));
680 /// assert!(!v.ends_with(&[50]));
681 /// assert!(!v.ends_with(&[50, 30]));
683 #[stable(feature = "rust1", since = "1.0.0")]
684 pub fn ends_with(&self, needle: &[T]) -> bool
687 core_slice::SliceExt::ends_with(self, needle)
690 /// Binary search a sorted slice for a given element.
692 /// If the value is found then `Ok` is returned, containing the
693 /// index of the matching element; if the value is not found then
694 /// `Err` is returned, containing the index where a matching
695 /// element could be inserted while maintaining sorted order.
699 /// Looks up a series of four elements. The first is found, with a
700 /// uniquely determined position; the second and third are not
701 /// found; the fourth could match any position in `[1,4]`.
704 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
706 /// assert_eq!(s.binary_search(&13), Ok(9));
707 /// assert_eq!(s.binary_search(&4), Err(7));
708 /// assert_eq!(s.binary_search(&100), Err(13));
709 /// let r = s.binary_search(&1);
710 /// assert!(match r { Ok(1...4) => true, _ => false, });
712 #[stable(feature = "rust1", since = "1.0.0")]
713 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
716 core_slice::SliceExt::binary_search(self, x)
719 /// Binary search a sorted slice with a comparator function.
721 /// The comparator function should implement an order consistent
722 /// with the sort order of the underlying slice, returning an
723 /// order code that indicates whether its argument is `Less`,
724 /// `Equal` or `Greater` the desired target.
726 /// If a matching value is found then returns `Ok`, containing
727 /// the index for the matched element; if no match is found then
728 /// `Err` is returned, containing the index where a matching
729 /// element could be inserted while maintaining sorted order.
733 /// Looks up a series of four elements. The first is found, with a
734 /// uniquely determined position; the second and third are not
735 /// found; the fourth could match any position in `[1,4]`.
738 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
741 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
743 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
745 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
747 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
748 /// assert!(match r { Ok(1...4) => true, _ => false, });
750 #[stable(feature = "rust1", since = "1.0.0")]
752 pub fn binary_search_by<F>(&self, f: F) -> Result<usize, usize>
753 where F: FnMut(&T) -> Ordering
755 core_slice::SliceExt::binary_search_by(self, f)
758 /// Sorts the slice, in place.
760 /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
762 /// This is a stable sort.
767 /// let mut v = [-5, 4, 1, -3, 2];
770 /// assert!(v == [-5, -3, 1, 2, 4]);
772 #[stable(feature = "rust1", since = "1.0.0")]
774 pub fn sort(&mut self)
777 self.sort_by(|a, b| a.cmp(b))
780 /// Sorts the slice, in place, using `key` to extract a key by which to
781 /// order the sort by.
783 /// This sort is `O(n log n)` worst-case and stable, but allocates
784 /// approximately `2 * n`, where `n` is the length of `self`.
786 /// This is a stable sort.
791 /// #![feature(slice_sort_by_key)]
793 /// let mut v = [-5i32, 4, 1, -3, 2];
795 /// v.sort_by_key(|k| k.abs());
796 /// assert!(v == [1, 2, -3, 4, -5]);
798 #[unstable(feature = "slice_sort_by_key", reason = "recently added",
801 pub fn sort_by_key<B, F>(&mut self, mut f: F)
802 where F: FnMut(&T) -> B, B: Ord
804 self.sort_by(|a, b| f(a).cmp(&f(b)))
807 /// Sorts the slice, in place, using `compare` to compare
810 /// This sort is `O(n log n)` worst-case and stable, but allocates
811 /// approximately `2 * n`, where `n` is the length of `self`.
816 /// let mut v = [5, 4, 1, 3, 2];
817 /// v.sort_by(|a, b| a.cmp(b));
818 /// assert!(v == [1, 2, 3, 4, 5]);
820 /// // reverse sorting
821 /// v.sort_by(|a, b| b.cmp(a));
822 /// assert!(v == [5, 4, 3, 2, 1]);
824 #[stable(feature = "rust1", since = "1.0.0")]
826 pub fn sort_by<F>(&mut self, compare: F)
827 where F: FnMut(&T, &T) -> Ordering
829 merge_sort(self, compare)
832 /// Copies as many elements from `src` as it can into `self` (the
833 /// shorter of `self.len()` and `src.len()`). Returns the number
834 /// of elements copied.
839 /// #![feature(clone_from_slice)]
841 /// let mut dst = [0, 0, 0];
842 /// let src = [1, 2];
844 /// assert!(dst.clone_from_slice(&src) == 2);
845 /// assert!(dst == [1, 2, 0]);
847 /// let src2 = [3, 4, 5, 6];
848 /// assert!(dst.clone_from_slice(&src2) == 3);
849 /// assert!(dst == [3, 4, 5]);
851 #[unstable(feature = "clone_from_slice", issue = "27750")]
852 pub fn clone_from_slice(&mut self, src: &[T]) -> usize
855 core_slice::SliceExt::clone_from_slice(self, src)
858 /// Copies `self` into a new `Vec`.
859 #[stable(feature = "rust1", since = "1.0.0")]
861 pub fn to_vec(&self) -> Vec<T>
864 // NB see hack module in this file
868 /// Converts `self` into a vector without clones or allocation.
869 #[stable(feature = "rust1", since = "1.0.0")]
871 pub fn into_vec(self: Box<Self>) -> Vec<T> {
872 // NB see hack module in this file
877 ////////////////////////////////////////////////////////////////////////////////
878 // Extension traits for slices over specific kinds of data
879 ////////////////////////////////////////////////////////////////////////////////
880 #[unstable(feature = "slice_concat_ext",
881 reason = "trait should not have to exist",
883 /// An extension trait for concatenating slices
884 pub trait SliceConcatExt<T: ?Sized> {
885 #[unstable(feature = "slice_concat_ext",
886 reason = "trait should not have to exist",
888 /// The resulting type after concatenation
891 /// Flattens a slice of `T` into a single value `Self::Output`.
896 /// assert_eq!(["hello", "world"].concat(), "helloworld");
898 #[stable(feature = "rust1", since = "1.0.0")]
899 fn concat(&self) -> Self::Output;
901 /// Flattens a slice of `T` into a single value `Self::Output`, placing a
902 /// given separator between each.
907 /// assert_eq!(["hello", "world"].join(" "), "hello world");
909 #[stable(feature = "rename_connect_to_join", since = "1.3.0")]
910 fn join(&self, sep: &T) -> Self::Output;
912 /// Flattens a slice of `T` into a single value `Self::Output`, placing a
913 /// given separator between each.
918 /// # #![allow(deprecated)]
919 /// assert_eq!(["hello", "world"].connect(" "), "hello world");
921 #[stable(feature = "rust1", since = "1.0.0")]
922 #[rustc_deprecated(since = "1.3.0", reason = "renamed to join")]
923 fn connect(&self, sep: &T) -> Self::Output;
926 #[unstable(feature = "slice_concat_ext",
927 reason = "trait should not have to exist",
929 impl<T: Clone, V: Borrow<[T]>> SliceConcatExt<T> for [V] {
930 type Output = Vec<T>;
932 fn concat(&self) -> Vec<T> {
933 let size = self.iter().fold(0, |acc, v| acc + v.borrow().len());
934 let mut result = Vec::with_capacity(size);
936 result.extend_from_slice(v.borrow())
941 fn join(&self, sep: &T) -> Vec<T> {
942 let size = self.iter().fold(0, |acc, v| acc + v.borrow().len());
943 let mut result = Vec::with_capacity(size + self.len());
944 let mut first = true;
949 result.push(sep.clone())
951 result.extend_from_slice(v.borrow())
956 fn connect(&self, sep: &T) -> Vec<T> {
961 ////////////////////////////////////////////////////////////////////////////////
962 // Standard trait implementations for slices
963 ////////////////////////////////////////////////////////////////////////////////
965 #[stable(feature = "rust1", since = "1.0.0")]
966 impl<T> Borrow<[T]> for Vec<T> {
967 fn borrow(&self) -> &[T] {
972 #[stable(feature = "rust1", since = "1.0.0")]
973 impl<T> BorrowMut<[T]> for Vec<T> {
974 fn borrow_mut(&mut self) -> &mut [T] {
979 #[stable(feature = "rust1", since = "1.0.0")]
980 impl<T: Clone> ToOwned for [T] {
983 fn to_owned(&self) -> Vec<T> {
987 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec`, which is required for this method
988 // definition, is not available. Since we don't require this method for testing purposes, I'll
990 // NB see the slice::hack module in slice.rs for more information
992 fn to_owned(&self) -> Vec<T> {
993 panic!("not available with cfg(test)")
997 ////////////////////////////////////////////////////////////////////////////////
999 ////////////////////////////////////////////////////////////////////////////////
1001 fn insertion_sort<T, F>(v: &mut [T], mut compare: F)
1002 where F: FnMut(&T, &T) -> Ordering
1004 let len = v.len() as isize;
1005 let buf_v = v.as_mut_ptr();
1009 // j satisfies: 0 <= j <= i;
1012 // `i` is in bounds.
1013 let read_ptr = buf_v.offset(i) as *const T;
1015 // find where to insert, we need to do strict <,
1016 // rather than <=, to maintain stability.
1018 // 0 <= j - 1 < len, so .offset(j - 1) is in bounds.
1019 while j > 0 && compare(&*read_ptr, &*buf_v.offset(j - 1)) == Less {
1023 // shift everything to the right, to make space to
1024 // insert this value.
1026 // j + 1 could be `len` (for the last `i`), but in
1027 // that case, `i == j` so we don't copy. The
1028 // `.offset(j)` is always in bounds.
1031 let tmp = ptr::read(read_ptr);
1032 ptr::copy(&*buf_v.offset(j), buf_v.offset(j + 1), (i - j) as usize);
1033 ptr::copy_nonoverlapping(&tmp, buf_v.offset(j), 1);
1040 fn merge_sort<T, F>(v: &mut [T], mut compare: F)
1041 where F: FnMut(&T, &T) -> Ordering
1043 // warning: this wildly uses unsafe.
1044 const BASE_INSERTION: usize = 32;
1045 const LARGE_INSERTION: usize = 16;
1047 // FIXME #12092: smaller insertion runs seems to make sorting
1048 // vectors of large elements a little faster on some platforms,
1049 // but hasn't been tested/tuned extensively
1050 let insertion = if size_of::<T>() <= 16 {
1058 // short vectors get sorted in-place via insertion sort to avoid allocations
1059 if len <= insertion {
1060 insertion_sort(v, compare);
1064 // allocate some memory to use as scratch memory, we keep the
1065 // length 0 so we can keep shallow copies of the contents of `v`
1066 // without risking the dtors running on an object twice if
1067 // `compare` panics.
1068 let mut working_space = Vec::with_capacity(2 * len);
1069 // these both are buffers of length `len`.
1070 let mut buf_dat = working_space.as_mut_ptr();
1071 let mut buf_tmp = unsafe { buf_dat.offset(len as isize) };
1074 let buf_v = v.as_ptr();
1076 // step 1. sort short runs with insertion sort. This takes the
1077 // values from `v` and sorts them into `buf_dat`, leaving that
1078 // with sorted runs of length INSERTION.
1080 // We could hardcode the sorting comparisons here, and we could
1081 // manipulate/step the pointers themselves, rather than repeatedly
1083 for start in (0..len).step_by(insertion) {
1084 // start <= i < len;
1085 for i in start..cmp::min(start + insertion, len) {
1086 // j satisfies: start <= j <= i;
1087 let mut j = i as isize;
1089 // `i` is in bounds.
1090 let read_ptr = buf_v.offset(i as isize);
1092 // find where to insert, we need to do strict <,
1093 // rather than <=, to maintain stability.
1095 // start <= j - 1 < len, so .offset(j - 1) is in
1097 while j > start as isize && compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less {
1101 // shift everything to the right, to make space to
1102 // insert this value.
1104 // j + 1 could be `len` (for the last `i`), but in
1105 // that case, `i == j` so we don't copy. The
1106 // `.offset(j)` is always in bounds.
1107 ptr::copy(&*buf_dat.offset(j), buf_dat.offset(j + 1), i - j as usize);
1108 ptr::copy_nonoverlapping(read_ptr, buf_dat.offset(j), 1);
1113 // step 2. merge the sorted runs.
1114 let mut width = insertion;
1116 // merge the sorted runs of length `width` in `buf_dat` two at
1117 // a time, placing the result in `buf_tmp`.
1119 // 0 <= start <= len.
1120 for start in (0..len).step_by(2 * width) {
1121 // manipulate pointers directly for speed (rather than
1122 // using a `for` loop with `range` and `.offset` inside
1125 // the end of the first run & start of the
1126 // second. Offset of `len` is defined, since this is
1127 // precisely one byte past the end of the object.
1128 let right_start = buf_dat.offset(cmp::min(start + width, len) as isize);
1129 // end of the second. Similar reasoning to the above re safety.
1130 let right_end_idx = cmp::min(start + 2 * width, len);
1131 let right_end = buf_dat.offset(right_end_idx as isize);
1133 // the pointers to the elements under consideration
1134 // from the two runs.
1136 // both of these are in bounds.
1137 let mut left = buf_dat.offset(start as isize);
1138 let mut right = right_start;
1140 // where we're putting the results, it is a run of
1141 // length `2*width`, so we step it once for each step
1142 // of either `left` or `right`. `buf_tmp` has length
1143 // `len`, so these are in bounds.
1144 let mut out = buf_tmp.offset(start as isize);
1145 let out_end = buf_tmp.offset(right_end_idx as isize);
1147 // If left[last] <= right[0], they are already in order:
1148 // fast-forward the left side (the right side is handled
1150 // If `right` is not empty then left is not empty, and
1151 // the offsets are in bounds.
1152 if right != right_end && compare(&*right.offset(-1), &*right) != Greater {
1153 let elems = (right_start as usize - left as usize) / mem::size_of::<T>();
1154 ptr::copy_nonoverlapping(&*left, out, elems);
1155 out = out.offset(elems as isize);
1159 while out < out_end {
1160 // Either the left or the right run are exhausted,
1161 // so just copy the remainder from the other run
1162 // and move on; this gives a huge speed-up (order
1163 // of 25%) for mostly sorted vectors (the best
1165 if left == right_start {
1166 // the number remaining in this run.
1167 let elems = (right_end as usize - right as usize) / mem::size_of::<T>();
1168 ptr::copy_nonoverlapping(&*right, out, elems);
1170 } else if right == right_end {
1171 let elems = (right_start as usize - left as usize) / mem::size_of::<T>();
1172 ptr::copy_nonoverlapping(&*left, out, elems);
1176 // check which side is smaller, and that's the
1177 // next element for the new run.
1179 // `left < right_start` and `right < right_end`,
1180 // so these are valid.
1181 let to_copy = if compare(&*left, &*right) == Greater {
1186 ptr::copy_nonoverlapping(&*to_copy, out, 1);
1192 mem::swap(&mut buf_dat, &mut buf_tmp);
1197 // write the result to `v` in one go, so that there are never two copies
1198 // of the same object in `v`.
1200 ptr::copy_nonoverlapping(&*buf_dat, v.as_mut_ptr(), len);
1203 // increment the pointer, returning the old pointer.
1205 unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
1207 *ptr = ptr.offset(1);