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 #![cfg_attr(test, allow(unused_imports, dead_code))]
88 use alloc::boxed::Box;
89 use core::cmp::Ordering::{self, Greater, Less};
91 use core::mem::size_of;
94 use core::slice as core_slice;
96 use borrow::{Borrow, BorrowMut, ToOwned};
99 #[stable(feature = "rust1", since = "1.0.0")]
100 pub use core::slice::{Chunks, Windows};
101 #[stable(feature = "rust1", since = "1.0.0")]
102 pub use core::slice::{Iter, IterMut};
103 #[stable(feature = "rust1", since = "1.0.0")]
104 pub use core::slice::{SplitMut, ChunksMut, Split};
105 #[stable(feature = "rust1", since = "1.0.0")]
106 pub use core::slice::{SplitN, RSplitN, SplitNMut, RSplitNMut};
107 #[unstable(feature = "slice_bytes", issue = "27740")]
109 pub use core::slice::bytes;
110 #[stable(feature = "rust1", since = "1.0.0")]
111 pub use core::slice::{from_raw_parts, from_raw_parts_mut};
113 ////////////////////////////////////////////////////////////////////////////////
114 // Basic slice extension methods
115 ////////////////////////////////////////////////////////////////////////////////
117 // HACK(japaric) needed for the implementation of `vec!` macro during testing
118 // NB see the hack module in this file for more details
120 pub use self::hack::into_vec;
122 // HACK(japaric) needed for the implementation of `Vec::clone` during testing
123 // NB see the hack module in this file for more details
125 pub use self::hack::to_vec;
127 // HACK(japaric): With cfg(test) `impl [T]` is not available, these three
128 // functions are actually methods that are in `impl [T]` but not in
129 // `core::slice::SliceExt` - we need to supply these functions for the
130 // `test_permutations` test
132 use alloc::boxed::Box;
136 use string::ToString;
139 pub fn into_vec<T>(mut b: Box<[T]>) -> Vec<T> {
141 let xs = Vec::from_raw_parts(b.as_mut_ptr(), b.len(), b.len());
148 pub fn to_vec<T>(s: &[T]) -> Vec<T>
151 let mut vector = Vec::with_capacity(s.len());
152 vector.extend_from_slice(s);
157 /// Allocating extension methods for slices.
161 /// Returns the number of elements in the slice.
166 /// let a = [1, 2, 3];
167 /// assert_eq!(a.len(), 3);
169 #[stable(feature = "rust1", since = "1.0.0")]
171 pub fn len(&self) -> usize {
172 core_slice::SliceExt::len(self)
175 /// Returns true if the slice has a length of 0
180 /// let a = [1, 2, 3];
181 /// assert!(!a.is_empty());
183 #[stable(feature = "rust1", since = "1.0.0")]
185 pub fn is_empty(&self) -> bool {
186 core_slice::SliceExt::is_empty(self)
189 /// Returns the first element of a slice, or `None` if it is empty.
194 /// let v = [10, 40, 30];
195 /// assert_eq!(Some(&10), v.first());
197 /// let w: &[i32] = &[];
198 /// assert_eq!(None, w.first());
200 #[stable(feature = "rust1", since = "1.0.0")]
202 pub fn first(&self) -> Option<&T> {
203 core_slice::SliceExt::first(self)
206 /// Returns a mutable pointer to the first element of a slice, or `None` if it is empty
207 #[stable(feature = "rust1", since = "1.0.0")]
209 pub fn first_mut(&mut self) -> Option<&mut T> {
210 core_slice::SliceExt::first_mut(self)
213 /// Returns the first and all the rest of the elements of a slice.
214 #[stable(feature = "slice_splits", since = "1.5.0")]
216 pub fn split_first(&self) -> Option<(&T, &[T])> {
217 core_slice::SliceExt::split_first(self)
220 /// Returns the first and all the rest of the elements of a slice.
221 #[stable(feature = "slice_splits", since = "1.5.0")]
223 pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
224 core_slice::SliceExt::split_first_mut(self)
227 /// Returns the last and all the rest of the elements of a slice.
228 #[stable(feature = "slice_splits", since = "1.5.0")]
230 pub fn split_last(&self) -> Option<(&T, &[T])> {
231 core_slice::SliceExt::split_last(self)
235 /// Returns the last and all the rest of the elements of a slice.
236 #[stable(feature = "slice_splits", since = "1.5.0")]
238 pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
239 core_slice::SliceExt::split_last_mut(self)
242 /// Returns the last element of a slice, or `None` if it is empty.
247 /// let v = [10, 40, 30];
248 /// assert_eq!(Some(&30), v.last());
250 /// let w: &[i32] = &[];
251 /// assert_eq!(None, w.last());
253 #[stable(feature = "rust1", since = "1.0.0")]
255 pub fn last(&self) -> Option<&T> {
256 core_slice::SliceExt::last(self)
259 /// Returns a mutable pointer to the last item in the slice.
260 #[stable(feature = "rust1", since = "1.0.0")]
262 pub fn last_mut(&mut self) -> Option<&mut T> {
263 core_slice::SliceExt::last_mut(self)
266 /// Returns the element of a slice at the given index, or `None` if the
267 /// index is out of bounds.
272 /// let v = [10, 40, 30];
273 /// assert_eq!(Some(&40), v.get(1));
274 /// assert_eq!(None, v.get(3));
276 #[stable(feature = "rust1", since = "1.0.0")]
278 pub fn get(&self, index: usize) -> Option<&T> {
279 core_slice::SliceExt::get(self, index)
282 /// Returns a mutable reference to the element at the given index,
283 /// or `None` if the index is out of bounds
284 #[stable(feature = "rust1", since = "1.0.0")]
286 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
287 core_slice::SliceExt::get_mut(self, index)
290 /// Returns a pointer to the element at the given index, without doing
292 #[stable(feature = "rust1", since = "1.0.0")]
294 pub unsafe fn get_unchecked(&self, index: usize) -> &T {
295 core_slice::SliceExt::get_unchecked(self, index)
298 /// Returns an unsafe mutable pointer to the element in index
299 #[stable(feature = "rust1", since = "1.0.0")]
301 pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
302 core_slice::SliceExt::get_unchecked_mut(self, index)
305 /// Returns an raw pointer to the slice's buffer
307 /// The caller must ensure that the slice outlives the pointer this
308 /// function returns, or else it will end up pointing to garbage.
310 /// Modifying the slice may cause its buffer to be reallocated, which
311 /// would also make any pointers to it invalid.
312 #[stable(feature = "rust1", since = "1.0.0")]
314 pub fn as_ptr(&self) -> *const T {
315 core_slice::SliceExt::as_ptr(self)
318 /// Returns an unsafe mutable pointer to the slice's buffer.
320 /// The caller must ensure that the slice outlives the pointer this
321 /// function returns, or else it will end up pointing to garbage.
323 /// Modifying the slice may cause its buffer to be reallocated, which
324 /// would also make any pointers to it invalid.
325 #[stable(feature = "rust1", since = "1.0.0")]
327 pub fn as_mut_ptr(&mut self) -> *mut T {
328 core_slice::SliceExt::as_mut_ptr(self)
331 /// Swaps two elements in a slice.
335 /// * a - The index of the first element
336 /// * b - The index of the second element
340 /// Panics if `a` or `b` are out of bounds.
345 /// let mut v = ["a", "b", "c", "d"];
347 /// assert!(v == ["a", "d", "c", "b"]);
349 #[stable(feature = "rust1", since = "1.0.0")]
351 pub fn swap(&mut self, a: usize, b: usize) {
352 core_slice::SliceExt::swap(self, a, b)
355 /// Reverse the order of elements in a slice, in place.
360 /// let mut v = [1, 2, 3];
362 /// assert!(v == [3, 2, 1]);
364 #[stable(feature = "rust1", since = "1.0.0")]
366 pub fn reverse(&mut self) {
367 core_slice::SliceExt::reverse(self)
370 /// Returns an iterator over the slice.
371 #[stable(feature = "rust1", since = "1.0.0")]
373 pub fn iter(&self) -> Iter<T> {
374 core_slice::SliceExt::iter(self)
377 /// Returns an iterator that allows modifying each value
378 #[stable(feature = "rust1", since = "1.0.0")]
380 pub fn iter_mut(&mut self) -> IterMut<T> {
381 core_slice::SliceExt::iter_mut(self)
384 /// Returns an iterator over all contiguous windows of length
385 /// `size`. The windows overlap. If the slice is shorter than
386 /// `size`, the iterator returns no values.
390 /// Panics if `size` is 0.
394 /// Print the adjacent pairs of a slice (i.e. `[1,2]`, `[2,3]`,
398 /// let v = &[1, 2, 3, 4];
399 /// for win in v.windows(2) {
400 /// println!("{:?}", win);
403 #[stable(feature = "rust1", since = "1.0.0")]
405 pub fn windows(&self, size: usize) -> Windows<T> {
406 core_slice::SliceExt::windows(self, size)
409 /// Returns an iterator over `size` elements of the slice at a
410 /// time. The chunks do not overlap. If `size` does not divide the
411 /// length of the slice, then the last chunk will not have length
416 /// Panics if `size` is 0.
420 /// Print the slice two elements at a time (i.e. `[1,2]`,
424 /// let v = &[1, 2, 3, 4, 5];
425 /// for win in v.chunks(2) {
426 /// println!("{:?}", win);
429 #[stable(feature = "rust1", since = "1.0.0")]
431 pub fn chunks(&self, size: usize) -> Chunks<T> {
432 core_slice::SliceExt::chunks(self, size)
435 /// Returns an iterator over `chunk_size` elements of the slice at a time.
436 /// The chunks are mutable and do not overlap. If `chunk_size` does
437 /// not divide the length of the slice, then the last chunk will not
438 /// have length `chunk_size`.
442 /// Panics if `chunk_size` is 0.
443 #[stable(feature = "rust1", since = "1.0.0")]
445 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
446 core_slice::SliceExt::chunks_mut(self, chunk_size)
449 /// Divides one slice into two at an index.
451 /// The first will contain all indices from `[0, mid)` (excluding
452 /// the index `mid` itself) and the second will contain all
453 /// indices from `[mid, len)` (excluding the index `len` itself).
457 /// Panics if `mid > len`.
462 /// let v = [10, 40, 30, 20, 50];
463 /// let (v1, v2) = v.split_at(2);
464 /// assert_eq!([10, 40], v1);
465 /// assert_eq!([30, 20, 50], v2);
467 #[stable(feature = "rust1", since = "1.0.0")]
469 pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
470 core_slice::SliceExt::split_at(self, mid)
473 /// Divides one `&mut` into two at an index.
475 /// The first will contain all indices from `[0, mid)` (excluding
476 /// the index `mid` itself) and the second will contain all
477 /// indices from `[mid, len)` (excluding the index `len` itself).
481 /// Panics if `mid > len`.
486 /// let mut v = [1, 2, 3, 4, 5, 6];
488 /// // scoped to restrict the lifetime of the borrows
490 /// let (left, right) = v.split_at_mut(0);
491 /// assert!(left == []);
492 /// assert!(right == [1, 2, 3, 4, 5, 6]);
496 /// let (left, right) = v.split_at_mut(2);
497 /// assert!(left == [1, 2]);
498 /// assert!(right == [3, 4, 5, 6]);
502 /// let (left, right) = v.split_at_mut(6);
503 /// assert!(left == [1, 2, 3, 4, 5, 6]);
504 /// assert!(right == []);
507 #[stable(feature = "rust1", since = "1.0.0")]
509 pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
510 core_slice::SliceExt::split_at_mut(self, mid)
513 /// Returns an iterator over subslices separated by elements that match
514 /// `pred`. The matched element is not contained in the subslices.
518 /// Print the slice split by numbers divisible by 3 (i.e. `[10, 40]`,
522 /// let v = [10, 40, 30, 20, 60, 50];
523 /// for group in v.split(|num| *num % 3 == 0) {
524 /// println!("{:?}", group);
527 #[stable(feature = "rust1", since = "1.0.0")]
529 pub fn split<F>(&self, pred: F) -> Split<T, F>
530 where F: FnMut(&T) -> bool
532 core_slice::SliceExt::split(self, pred)
535 /// Returns an iterator over mutable subslices separated by elements that
536 /// match `pred`. The matched element is not contained in the subslices.
537 #[stable(feature = "rust1", since = "1.0.0")]
539 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F>
540 where F: FnMut(&T) -> bool
542 core_slice::SliceExt::split_mut(self, pred)
545 /// Returns an iterator over subslices separated by elements that match
546 /// `pred`, limited to returning at most `n` items. The matched element is
547 /// not contained in the subslices.
549 /// The last element returned, if any, will contain the remainder of the
554 /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
558 /// let v = [10, 40, 30, 20, 60, 50];
559 /// for group in v.splitn(2, |num| *num % 3 == 0) {
560 /// println!("{:?}", group);
563 #[stable(feature = "rust1", since = "1.0.0")]
565 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F>
566 where F: FnMut(&T) -> bool
568 core_slice::SliceExt::splitn(self, n, pred)
571 /// Returns an iterator over subslices separated by elements that match
572 /// `pred`, limited to returning at most `n` items. The matched element is
573 /// not contained in the subslices.
575 /// The last element returned, if any, will contain the remainder of the
577 #[stable(feature = "rust1", since = "1.0.0")]
579 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, F>
580 where F: FnMut(&T) -> bool
582 core_slice::SliceExt::splitn_mut(self, n, pred)
585 /// Returns an iterator over subslices separated by elements that match
586 /// `pred` limited to returning at most `n` items. This starts at the end of
587 /// the slice and works backwards. The matched element is not contained in
590 /// The last element returned, if any, will contain the remainder of the
595 /// Print the slice split once, starting from the end, by numbers divisible
596 /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
599 /// let v = [10, 40, 30, 20, 60, 50];
600 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
601 /// println!("{:?}", group);
604 #[stable(feature = "rust1", since = "1.0.0")]
606 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F>
607 where F: FnMut(&T) -> bool
609 core_slice::SliceExt::rsplitn(self, n, pred)
612 /// Returns an iterator over subslices separated by elements that match
613 /// `pred` limited to returning at most `n` items. This starts at the end of
614 /// the slice and works backwards. The matched element is not contained in
617 /// The last element returned, if any, will contain the remainder of the
619 #[stable(feature = "rust1", since = "1.0.0")]
621 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, F>
622 where F: FnMut(&T) -> bool
624 core_slice::SliceExt::rsplitn_mut(self, n, pred)
627 /// Returns true if the slice contains an element with the given value.
632 /// let v = [10, 40, 30];
633 /// assert!(v.contains(&30));
634 /// assert!(!v.contains(&50));
636 #[stable(feature = "rust1", since = "1.0.0")]
637 pub fn contains(&self, x: &T) -> bool
640 core_slice::SliceExt::contains(self, x)
643 /// Returns true if `needle` is a prefix of the slice.
648 /// let v = [10, 40, 30];
649 /// assert!(v.starts_with(&[10]));
650 /// assert!(v.starts_with(&[10, 40]));
651 /// assert!(!v.starts_with(&[50]));
652 /// assert!(!v.starts_with(&[10, 50]));
654 #[stable(feature = "rust1", since = "1.0.0")]
655 pub fn starts_with(&self, needle: &[T]) -> bool
658 core_slice::SliceExt::starts_with(self, needle)
661 /// Returns true if `needle` is a suffix of the slice.
666 /// let v = [10, 40, 30];
667 /// assert!(v.ends_with(&[30]));
668 /// assert!(v.ends_with(&[40, 30]));
669 /// assert!(!v.ends_with(&[50]));
670 /// assert!(!v.ends_with(&[50, 30]));
672 #[stable(feature = "rust1", since = "1.0.0")]
673 pub fn ends_with(&self, needle: &[T]) -> bool
676 core_slice::SliceExt::ends_with(self, needle)
679 /// Binary search a sorted slice for a given element.
681 /// If the value is found then `Ok` is returned, containing the
682 /// index of the matching element; if the value is not found then
683 /// `Err` is returned, containing the index where a matching
684 /// element could be inserted while maintaining sorted order.
688 /// Looks up a series of four elements. The first is found, with a
689 /// uniquely determined position; the second and third are not
690 /// found; the fourth could match any position in `[1,4]`.
693 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
695 /// assert_eq!(s.binary_search(&13), Ok(9));
696 /// assert_eq!(s.binary_search(&4), Err(7));
697 /// assert_eq!(s.binary_search(&100), Err(13));
698 /// let r = s.binary_search(&1);
699 /// assert!(match r { Ok(1...4) => true, _ => false, });
701 #[stable(feature = "rust1", since = "1.0.0")]
702 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
705 core_slice::SliceExt::binary_search(self, x)
708 /// Binary search a sorted slice with a comparator function.
710 /// The comparator function should implement an order consistent
711 /// with the sort order of the underlying slice, returning an
712 /// order code that indicates whether its argument is `Less`,
713 /// `Equal` or `Greater` the desired target.
715 /// If a matching value is found then returns `Ok`, containing
716 /// the index for the matched element; if no match is found then
717 /// `Err` is returned, containing the index where a matching
718 /// element could be inserted while maintaining sorted order.
722 /// Looks up a series of four elements. The first is found, with a
723 /// uniquely determined position; the second and third are not
724 /// found; the fourth could match any position in `[1,4]`.
727 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
730 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
732 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
734 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
736 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
737 /// assert!(match r { Ok(1...4) => true, _ => false, });
739 #[stable(feature = "rust1", since = "1.0.0")]
741 pub fn binary_search_by<F>(&self, f: F) -> Result<usize, usize>
742 where F: FnMut(&T) -> Ordering
744 core_slice::SliceExt::binary_search_by(self, f)
747 /// Sorts the slice, in place.
749 /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
751 /// This is a stable sort.
756 /// let mut v = [-5, 4, 1, -3, 2];
759 /// assert!(v == [-5, -3, 1, 2, 4]);
761 #[stable(feature = "rust1", since = "1.0.0")]
763 pub fn sort(&mut self)
766 self.sort_by(|a, b| a.cmp(b))
769 /// Sorts the slice, in place, using `key` to extract a key by which to
770 /// order the sort by.
772 /// This sort is `O(n log n)` worst-case and stable, but allocates
773 /// approximately `2 * n`, where `n` is the length of `self`.
775 /// This is a stable sort.
780 /// let mut v = [-5i32, 4, 1, -3, 2];
782 /// v.sort_by_key(|k| k.abs());
783 /// assert!(v == [1, 2, -3, 4, -5]);
785 #[stable(feature = "slice_sort_by_key", since = "1.7.0")]
787 pub fn sort_by_key<B, F>(&mut self, mut f: F)
788 where F: FnMut(&T) -> B, B: Ord
790 self.sort_by(|a, b| f(a).cmp(&f(b)))
793 /// Sorts the slice, in place, using `compare` to compare
796 /// This sort is `O(n log n)` worst-case and stable, but allocates
797 /// approximately `2 * n`, where `n` is the length of `self`.
802 /// let mut v = [5, 4, 1, 3, 2];
803 /// v.sort_by(|a, b| a.cmp(b));
804 /// assert!(v == [1, 2, 3, 4, 5]);
806 /// // reverse sorting
807 /// v.sort_by(|a, b| b.cmp(a));
808 /// assert!(v == [5, 4, 3, 2, 1]);
810 #[stable(feature = "rust1", since = "1.0.0")]
812 pub fn sort_by<F>(&mut self, compare: F)
813 where F: FnMut(&T, &T) -> Ordering
815 merge_sort(self, compare)
818 /// Copies the elements from `src` into `self`.
820 /// The length of this slice must be the same as the slice passed in.
824 /// This function will panic if the two slices have different lengths.
829 /// let mut dst = [0, 0, 0];
830 /// let src = [1, 2, 3];
832 /// dst.clone_from_slice(&src);
833 /// assert!(dst == [1, 2, 3]);
835 #[stable(feature = "clone_from_slice", since = "1.7.0")]
836 pub fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
837 core_slice::SliceExt::clone_from_slice(self, src)
840 /// Copies `self` into a new `Vec`.
841 #[stable(feature = "rust1", since = "1.0.0")]
843 pub fn to_vec(&self) -> Vec<T>
846 // NB see hack module in this file
850 /// Converts `self` into a vector without clones or allocation.
851 #[stable(feature = "rust1", since = "1.0.0")]
853 pub fn into_vec(self: Box<Self>) -> Vec<T> {
854 // NB see hack module in this file
859 ////////////////////////////////////////////////////////////////////////////////
860 // Extension traits for slices over specific kinds of data
861 ////////////////////////////////////////////////////////////////////////////////
862 #[unstable(feature = "slice_concat_ext",
863 reason = "trait should not have to exist",
865 /// An extension trait for concatenating slices
866 pub trait SliceConcatExt<T: ?Sized> {
867 #[unstable(feature = "slice_concat_ext",
868 reason = "trait should not have to exist",
870 /// The resulting type after concatenation
873 /// Flattens a slice of `T` into a single value `Self::Output`.
878 /// assert_eq!(["hello", "world"].concat(), "helloworld");
880 #[stable(feature = "rust1", since = "1.0.0")]
881 fn concat(&self) -> Self::Output;
883 /// Flattens a slice of `T` into a single value `Self::Output`, placing a
884 /// given separator between each.
889 /// assert_eq!(["hello", "world"].join(" "), "hello world");
891 #[stable(feature = "rename_connect_to_join", since = "1.3.0")]
892 fn join(&self, sep: &T) -> Self::Output;
894 #[stable(feature = "rust1", since = "1.0.0")]
895 #[rustc_deprecated(since = "1.3.0", reason = "renamed to join")]
896 fn connect(&self, sep: &T) -> Self::Output;
899 #[unstable(feature = "slice_concat_ext",
900 reason = "trait should not have to exist",
902 impl<T: Clone, V: Borrow<[T]>> SliceConcatExt<T> for [V] {
903 type Output = Vec<T>;
905 fn concat(&self) -> Vec<T> {
906 let size = self.iter().fold(0, |acc, v| acc + v.borrow().len());
907 let mut result = Vec::with_capacity(size);
909 result.extend_from_slice(v.borrow())
914 fn join(&self, sep: &T) -> Vec<T> {
915 let size = self.iter().fold(0, |acc, v| acc + v.borrow().len());
916 let mut result = Vec::with_capacity(size + self.len());
917 let mut first = true;
922 result.push(sep.clone())
924 result.extend_from_slice(v.borrow())
929 fn connect(&self, sep: &T) -> Vec<T> {
934 ////////////////////////////////////////////////////////////////////////////////
935 // Standard trait implementations for slices
936 ////////////////////////////////////////////////////////////////////////////////
938 #[stable(feature = "rust1", since = "1.0.0")]
939 impl<T> Borrow<[T]> for Vec<T> {
940 fn borrow(&self) -> &[T] {
945 #[stable(feature = "rust1", since = "1.0.0")]
946 impl<T> BorrowMut<[T]> for Vec<T> {
947 fn borrow_mut(&mut self) -> &mut [T] {
952 #[stable(feature = "rust1", since = "1.0.0")]
953 impl<T: Clone> ToOwned for [T] {
956 fn to_owned(&self) -> Vec<T> {
960 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec`, which is required for this method
961 // definition, is not available. Since we don't require this method for testing purposes, I'll
963 // NB see the slice::hack module in slice.rs for more information
965 fn to_owned(&self) -> Vec<T> {
966 panic!("not available with cfg(test)")
970 ////////////////////////////////////////////////////////////////////////////////
972 ////////////////////////////////////////////////////////////////////////////////
974 fn insertion_sort<T, F>(v: &mut [T], mut compare: F)
975 where F: FnMut(&T, &T) -> Ordering
977 let len = v.len() as isize;
978 let buf_v = v.as_mut_ptr();
982 // j satisfies: 0 <= j <= i;
986 let read_ptr = buf_v.offset(i) as *const T;
988 // find where to insert, we need to do strict <,
989 // rather than <=, to maintain stability.
991 // 0 <= j - 1 < len, so .offset(j - 1) is in bounds.
992 while j > 0 && compare(&*read_ptr, &*buf_v.offset(j - 1)) == Less {
996 // shift everything to the right, to make space to
997 // insert this value.
999 // j + 1 could be `len` (for the last `i`), but in
1000 // that case, `i == j` so we don't copy. The
1001 // `.offset(j)` is always in bounds.
1004 let tmp = ptr::read(read_ptr);
1005 ptr::copy(&*buf_v.offset(j), buf_v.offset(j + 1), (i - j) as usize);
1006 ptr::copy_nonoverlapping(&tmp, buf_v.offset(j), 1);
1013 fn merge_sort<T, F>(v: &mut [T], mut compare: F)
1014 where F: FnMut(&T, &T) -> Ordering
1016 // warning: this wildly uses unsafe.
1017 const BASE_INSERTION: usize = 32;
1018 const LARGE_INSERTION: usize = 16;
1020 // FIXME #12092: smaller insertion runs seems to make sorting
1021 // vectors of large elements a little faster on some platforms,
1022 // but hasn't been tested/tuned extensively
1023 let insertion = if size_of::<T>() <= 16 {
1031 // short vectors get sorted in-place via insertion sort to avoid allocations
1032 if len <= insertion {
1033 insertion_sort(v, compare);
1037 // allocate some memory to use as scratch memory, we keep the
1038 // length 0 so we can keep shallow copies of the contents of `v`
1039 // without risking the dtors running on an object twice if
1040 // `compare` panics.
1041 let mut working_space = Vec::with_capacity(2 * len);
1042 // these both are buffers of length `len`.
1043 let mut buf_dat = working_space.as_mut_ptr();
1044 let mut buf_tmp = unsafe { buf_dat.offset(len as isize) };
1047 let buf_v = v.as_ptr();
1049 // step 1. sort short runs with insertion sort. This takes the
1050 // values from `v` and sorts them into `buf_dat`, leaving that
1051 // with sorted runs of length INSERTION.
1053 // We could hardcode the sorting comparisons here, and we could
1054 // manipulate/step the pointers themselves, rather than repeatedly
1056 for start in (0..len).step_by(insertion) {
1057 // start <= i < len;
1058 for i in start..cmp::min(start + insertion, len) {
1059 // j satisfies: start <= j <= i;
1060 let mut j = i as isize;
1062 // `i` is in bounds.
1063 let read_ptr = buf_v.offset(i as isize);
1065 // find where to insert, we need to do strict <,
1066 // rather than <=, to maintain stability.
1068 // start <= j - 1 < len, so .offset(j - 1) is in
1070 while j > start as isize && compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less {
1074 // shift everything to the right, to make space to
1075 // insert this value.
1077 // j + 1 could be `len` (for the last `i`), but in
1078 // that case, `i == j` so we don't copy. The
1079 // `.offset(j)` is always in bounds.
1080 ptr::copy(&*buf_dat.offset(j), buf_dat.offset(j + 1), i - j as usize);
1081 ptr::copy_nonoverlapping(read_ptr, buf_dat.offset(j), 1);
1086 // step 2. merge the sorted runs.
1087 let mut width = insertion;
1089 // merge the sorted runs of length `width` in `buf_dat` two at
1090 // a time, placing the result in `buf_tmp`.
1092 // 0 <= start <= len.
1093 for start in (0..len).step_by(2 * width) {
1094 // manipulate pointers directly for speed (rather than
1095 // using a `for` loop with `range` and `.offset` inside
1098 // the end of the first run & start of the
1099 // second. Offset of `len` is defined, since this is
1100 // precisely one byte past the end of the object.
1101 let right_start = buf_dat.offset(cmp::min(start + width, len) as isize);
1102 // end of the second. Similar reasoning to the above re safety.
1103 let right_end_idx = cmp::min(start + 2 * width, len);
1104 let right_end = buf_dat.offset(right_end_idx as isize);
1106 // the pointers to the elements under consideration
1107 // from the two runs.
1109 // both of these are in bounds.
1110 let mut left = buf_dat.offset(start as isize);
1111 let mut right = right_start;
1113 // where we're putting the results, it is a run of
1114 // length `2*width`, so we step it once for each step
1115 // of either `left` or `right`. `buf_tmp` has length
1116 // `len`, so these are in bounds.
1117 let mut out = buf_tmp.offset(start as isize);
1118 let out_end = buf_tmp.offset(right_end_idx as isize);
1120 // If left[last] <= right[0], they are already in order:
1121 // fast-forward the left side (the right side is handled
1123 // If `right` is not empty then left is not empty, and
1124 // the offsets are in bounds.
1125 if right != right_end && compare(&*right.offset(-1), &*right) != Greater {
1126 let elems = (right_start as usize - left as usize) / mem::size_of::<T>();
1127 ptr::copy_nonoverlapping(&*left, out, elems);
1128 out = out.offset(elems as isize);
1132 while out < out_end {
1133 // Either the left or the right run are exhausted,
1134 // so just copy the remainder from the other run
1135 // and move on; this gives a huge speed-up (order
1136 // of 25%) for mostly sorted vectors (the best
1138 if left == right_start {
1139 // the number remaining in this run.
1140 let elems = (right_end as usize - right as usize) / mem::size_of::<T>();
1141 ptr::copy_nonoverlapping(&*right, out, elems);
1143 } else if right == right_end {
1144 let elems = (right_start as usize - left as usize) / mem::size_of::<T>();
1145 ptr::copy_nonoverlapping(&*left, out, elems);
1149 // check which side is smaller, and that's the
1150 // next element for the new run.
1152 // `left < right_start` and `right < right_end`,
1153 // so these are valid.
1154 let to_copy = if compare(&*left, &*right) == Greater {
1159 ptr::copy_nonoverlapping(&*to_copy, out, 1);
1165 mem::swap(&mut buf_dat, &mut buf_tmp);
1170 // write the result to `v` in one go, so that there are never two copies
1171 // of the same object in `v`.
1173 ptr::copy_nonoverlapping(&*buf_dat, v.as_mut_ptr(), len);
1176 // increment the pointer, returning the old pointer.
1178 unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
1180 *ptr = ptr.offset(1);