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](../../std/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 #[stable(feature = "rust1", since = "1.0.0")]
108 pub use core::slice::{from_raw_parts, from_raw_parts_mut};
110 ////////////////////////////////////////////////////////////////////////////////
111 // Basic slice extension methods
112 ////////////////////////////////////////////////////////////////////////////////
114 // HACK(japaric) needed for the implementation of `vec!` macro during testing
115 // NB see the hack module in this file for more details
117 pub use self::hack::into_vec;
119 // HACK(japaric) needed for the implementation of `Vec::clone` during testing
120 // NB see the hack module in this file for more details
122 pub use self::hack::to_vec;
124 // HACK(japaric): With cfg(test) `impl [T]` is not available, these three
125 // functions are actually methods that are in `impl [T]` but not in
126 // `core::slice::SliceExt` - we need to supply these functions for the
127 // `test_permutations` test
129 use alloc::boxed::Box;
133 use string::ToString;
136 pub fn into_vec<T>(mut b: Box<[T]>) -> Vec<T> {
138 let xs = Vec::from_raw_parts(b.as_mut_ptr(), b.len(), b.len());
145 pub fn to_vec<T>(s: &[T]) -> Vec<T>
148 let mut vector = Vec::with_capacity(s.len());
149 vector.extend_from_slice(s);
157 /// Returns the number of elements in the slice.
162 /// let a = [1, 2, 3];
163 /// assert_eq!(a.len(), 3);
165 #[stable(feature = "rust1", since = "1.0.0")]
167 pub fn len(&self) -> usize {
168 core_slice::SliceExt::len(self)
171 /// Returns true if the slice has a length of 0
176 /// let a = [1, 2, 3];
177 /// assert!(!a.is_empty());
179 #[stable(feature = "rust1", since = "1.0.0")]
181 pub fn is_empty(&self) -> bool {
182 core_slice::SliceExt::is_empty(self)
185 /// Returns the first element of a slice, or `None` if it is empty.
190 /// let v = [10, 40, 30];
191 /// assert_eq!(Some(&10), v.first());
193 /// let w: &[i32] = &[];
194 /// assert_eq!(None, w.first());
196 #[stable(feature = "rust1", since = "1.0.0")]
198 pub fn first(&self) -> Option<&T> {
199 core_slice::SliceExt::first(self)
202 /// Returns a mutable pointer to the first element of a slice, or `None` if it is empty.
207 /// let x = &mut [0, 1, 2];
209 /// if let Some(first) = x.first_mut() {
212 /// assert_eq!(x, &[5, 1, 2]);
214 #[stable(feature = "rust1", since = "1.0.0")]
216 pub fn first_mut(&mut self) -> Option<&mut T> {
217 core_slice::SliceExt::first_mut(self)
220 /// Returns the first and all the rest of the elements of a slice.
225 /// let x = &[0, 1, 2];
227 /// if let Some((first, elements)) = x.split_first() {
228 /// assert_eq!(first, &0);
229 /// assert_eq!(elements, &[1, 2]);
232 #[stable(feature = "slice_splits", since = "1.5.0")]
234 pub fn split_first(&self) -> Option<(&T, &[T])> {
235 core_slice::SliceExt::split_first(self)
238 /// Returns the first and all the rest of the elements of a slice.
243 /// let x = &mut [0, 1, 2];
245 /// if let Some((first, elements)) = x.split_first_mut() {
250 /// assert_eq!(x, &[3, 4, 5]);
252 #[stable(feature = "slice_splits", since = "1.5.0")]
254 pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
255 core_slice::SliceExt::split_first_mut(self)
258 /// Returns the last and all the rest of the elements of a slice.
263 /// let x = &[0, 1, 2];
265 /// if let Some((last, elements)) = x.split_last() {
266 /// assert_eq!(last, &2);
267 /// assert_eq!(elements, &[0, 1]);
270 #[stable(feature = "slice_splits", since = "1.5.0")]
272 pub fn split_last(&self) -> Option<(&T, &[T])> {
273 core_slice::SliceExt::split_last(self)
277 /// Returns the last and all the rest of the elements of a slice.
282 /// let x = &mut [0, 1, 2];
284 /// if let Some((last, elements)) = x.split_last_mut() {
289 /// assert_eq!(x, &[4, 5, 3]);
291 #[stable(feature = "slice_splits", since = "1.5.0")]
293 pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
294 core_slice::SliceExt::split_last_mut(self)
297 /// Returns the last element of a slice, or `None` if it is empty.
302 /// let v = [10, 40, 30];
303 /// assert_eq!(Some(&30), v.last());
305 /// let w: &[i32] = &[];
306 /// assert_eq!(None, w.last());
308 #[stable(feature = "rust1", since = "1.0.0")]
310 pub fn last(&self) -> Option<&T> {
311 core_slice::SliceExt::last(self)
314 /// Returns a mutable pointer to the last item in the slice.
319 /// let x = &mut [0, 1, 2];
321 /// if let Some(last) = x.last_mut() {
324 /// assert_eq!(x, &[0, 1, 10]);
326 #[stable(feature = "rust1", since = "1.0.0")]
328 pub fn last_mut(&mut self) -> Option<&mut T> {
329 core_slice::SliceExt::last_mut(self)
332 /// Returns the element of a slice at the given index, or `None` if the
333 /// index is out of bounds.
338 /// let v = [10, 40, 30];
339 /// assert_eq!(Some(&40), v.get(1));
340 /// assert_eq!(None, v.get(3));
342 #[stable(feature = "rust1", since = "1.0.0")]
344 pub fn get(&self, index: usize) -> Option<&T> {
345 core_slice::SliceExt::get(self, index)
348 /// Returns a mutable reference to the element at the given index.
353 /// let x = &mut [0, 1, 2];
355 /// if let Some(elem) = x.get_mut(1) {
358 /// assert_eq!(x, &[0, 42, 2]);
360 /// or `None` if the index is out of bounds
361 #[stable(feature = "rust1", since = "1.0.0")]
363 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
364 core_slice::SliceExt::get_mut(self, index)
367 /// Returns a pointer to the element at the given index, without doing
368 /// bounds checking. So use it very carefully!
373 /// let x = &[1, 2, 4];
376 /// assert_eq!(x.get_unchecked(1), &2);
379 #[stable(feature = "rust1", since = "1.0.0")]
381 pub unsafe fn get_unchecked(&self, index: usize) -> &T {
382 core_slice::SliceExt::get_unchecked(self, index)
385 /// Returns an unsafe mutable pointer to the element in index. So use it
391 /// let x = &mut [1, 2, 4];
394 /// let elem = x.get_unchecked_mut(1);
397 /// assert_eq!(x, &[1, 13, 4]);
399 #[stable(feature = "rust1", since = "1.0.0")]
401 pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
402 core_slice::SliceExt::get_unchecked_mut(self, index)
405 /// Returns an raw pointer to the slice's buffer
407 /// The caller must ensure that the slice outlives the pointer this
408 /// function returns, or else it will end up pointing to garbage.
410 /// Modifying the slice may cause its buffer to be reallocated, which
411 /// would also make any pointers to it invalid.
416 /// let x = &[1, 2, 4];
417 /// let x_ptr = x.as_ptr();
420 /// for i in 0..x.len() {
421 /// assert_eq!(x.get_unchecked(i), &*x_ptr.offset(i as isize));
425 #[stable(feature = "rust1", since = "1.0.0")]
427 pub fn as_ptr(&self) -> *const T {
428 core_slice::SliceExt::as_ptr(self)
431 /// Returns an unsafe mutable pointer to the slice's buffer.
433 /// The caller must ensure that the slice outlives the pointer this
434 /// function returns, or else it will end up pointing to garbage.
436 /// Modifying the slice may cause its buffer to be reallocated, which
437 /// would also make any pointers to it invalid.
442 /// let x = &mut [1, 2, 4];
443 /// let x_ptr = x.as_mut_ptr();
446 /// for i in 0..x.len() {
447 /// *x_ptr.offset(i as isize) += 2;
450 /// assert_eq!(x, &[3, 4, 6]);
452 #[stable(feature = "rust1", since = "1.0.0")]
454 pub fn as_mut_ptr(&mut self) -> *mut T {
455 core_slice::SliceExt::as_mut_ptr(self)
458 /// Swaps two elements in a slice.
462 /// * a - The index of the first element
463 /// * b - The index of the second element
467 /// Panics if `a` or `b` are out of bounds.
472 /// let mut v = ["a", "b", "c", "d"];
474 /// assert!(v == ["a", "d", "c", "b"]);
476 #[stable(feature = "rust1", since = "1.0.0")]
478 pub fn swap(&mut self, a: usize, b: usize) {
479 core_slice::SliceExt::swap(self, a, b)
482 /// Reverse the order of elements in a slice, in place.
487 /// let mut v = [1, 2, 3];
489 /// assert!(v == [3, 2, 1]);
491 #[stable(feature = "rust1", since = "1.0.0")]
493 pub fn reverse(&mut self) {
494 core_slice::SliceExt::reverse(self)
497 /// Returns an iterator over the slice.
502 /// let x = &[1, 2, 4];
503 /// let mut iterator = x.iter();
505 /// assert_eq!(iterator.next(), Some(&1));
506 /// assert_eq!(iterator.next(), Some(&2));
507 /// assert_eq!(iterator.next(), Some(&4));
508 /// assert_eq!(iterator.next(), None);
510 #[stable(feature = "rust1", since = "1.0.0")]
512 pub fn iter(&self) -> Iter<T> {
513 core_slice::SliceExt::iter(self)
516 /// Returns an iterator that allows modifying each value.
521 /// let x = &mut [1, 2, 4];
523 /// let iterator = x.iter_mut();
525 /// for elem in iterator {
529 /// assert_eq!(x, &[3, 4, 6]);
531 #[stable(feature = "rust1", since = "1.0.0")]
533 pub fn iter_mut(&mut self) -> IterMut<T> {
534 core_slice::SliceExt::iter_mut(self)
537 /// Returns an iterator over all contiguous windows of length
538 /// `size`. The windows overlap. If the slice is shorter than
539 /// `size`, the iterator returns no values.
543 /// Panics if `size` is 0.
547 /// Print the adjacent pairs of a slice (i.e. `[1,2]`, `[2,3]`,
551 /// let v = &[1, 2, 3, 4];
552 /// for win in v.windows(2) {
553 /// println!("{:?}", win);
556 #[stable(feature = "rust1", since = "1.0.0")]
558 pub fn windows(&self, size: usize) -> Windows<T> {
559 core_slice::SliceExt::windows(self, size)
562 /// Returns an iterator over `size` elements of the slice at a
563 /// time. The chunks are slices and do not overlap. If `size` does not divide the
564 /// length of the slice, then the last chunk will not have length
569 /// Panics if `size` is 0.
573 /// Print the slice two elements at a time (i.e. `[1,2]`,
577 /// let v = &[1, 2, 3, 4, 5];
579 /// for chunk in v.chunks(2) {
580 /// println!("{:?}", chunk);
583 #[stable(feature = "rust1", since = "1.0.0")]
585 pub fn chunks(&self, size: usize) -> Chunks<T> {
586 core_slice::SliceExt::chunks(self, size)
589 /// Returns an iterator over `chunk_size` elements of the slice at a time.
590 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does
591 /// not divide the length of the slice, then the last chunk will not
592 /// have length `chunk_size`.
596 /// Panics if `chunk_size` is 0.
601 /// let v = &mut [0, 0, 0, 0, 0];
602 /// let mut count = 1;
604 /// for chunk in v.chunks_mut(2) {
605 /// for elem in chunk.iter_mut() {
610 /// assert_eq!(v, &[1, 1, 2, 2, 3]);
612 #[stable(feature = "rust1", since = "1.0.0")]
614 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
615 core_slice::SliceExt::chunks_mut(self, chunk_size)
618 /// Divides one slice into two at an index.
620 /// The first will contain all indices from `[0, mid)` (excluding
621 /// the index `mid` itself) and the second will contain all
622 /// indices from `[mid, len)` (excluding the index `len` itself).
626 /// Panics if `mid > len`.
631 /// let v = [10, 40, 30, 20, 50];
632 /// let (v1, v2) = v.split_at(2);
633 /// assert_eq!([10, 40], v1);
634 /// assert_eq!([30, 20, 50], v2);
636 #[stable(feature = "rust1", since = "1.0.0")]
638 pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
639 core_slice::SliceExt::split_at(self, mid)
642 /// Divides one `&mut` into two at an index.
644 /// The first will contain all indices from `[0, mid)` (excluding
645 /// the index `mid` itself) and the second will contain all
646 /// indices from `[mid, len)` (excluding the index `len` itself).
650 /// Panics if `mid > len`.
655 /// let mut v = [1, 2, 3, 4, 5, 6];
657 /// // scoped to restrict the lifetime of the borrows
659 /// let (left, right) = v.split_at_mut(0);
660 /// assert!(left == []);
661 /// assert!(right == [1, 2, 3, 4, 5, 6]);
665 /// let (left, right) = v.split_at_mut(2);
666 /// assert!(left == [1, 2]);
667 /// assert!(right == [3, 4, 5, 6]);
671 /// let (left, right) = v.split_at_mut(6);
672 /// assert!(left == [1, 2, 3, 4, 5, 6]);
673 /// assert!(right == []);
676 #[stable(feature = "rust1", since = "1.0.0")]
678 pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
679 core_slice::SliceExt::split_at_mut(self, mid)
682 /// Returns an iterator over subslices separated by elements that match
683 /// `pred`. The matched element is not contained in the subslices.
687 /// Print the slice split by numbers divisible by 3 (i.e. `[10, 40]`,
691 /// let v = [10, 40, 30, 20, 60, 50];
693 /// for group in v.split(|num| *num % 3 == 0) {
694 /// println!("{:?}", group);
697 #[stable(feature = "rust1", since = "1.0.0")]
699 pub fn split<F>(&self, pred: F) -> Split<T, F>
700 where F: FnMut(&T) -> bool
702 core_slice::SliceExt::split(self, pred)
705 /// Returns an iterator over mutable subslices separated by elements that
706 /// match `pred`. The matched element is not contained in the subslices.
711 /// let mut v = [10, 40, 30, 20, 60, 50];
713 /// for group in v.split_mut(|num| *num % 3 == 0) {
716 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
718 #[stable(feature = "rust1", since = "1.0.0")]
720 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F>
721 where F: FnMut(&T) -> bool
723 core_slice::SliceExt::split_mut(self, pred)
726 /// Returns an iterator over subslices separated by elements that match
727 /// `pred`, limited to returning at most `n` items. The matched element is
728 /// not contained in the subslices.
730 /// The last element returned, if any, will contain the remainder of the
735 /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
739 /// let v = [10, 40, 30, 20, 60, 50];
741 /// for group in v.splitn(2, |num| *num % 3 == 0) {
742 /// println!("{:?}", group);
745 #[stable(feature = "rust1", since = "1.0.0")]
747 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F>
748 where F: FnMut(&T) -> bool
750 core_slice::SliceExt::splitn(self, n, pred)
753 /// Returns an iterator over subslices separated by elements that match
754 /// `pred`, limited to returning at most `n` items. The matched element is
755 /// not contained in the subslices.
757 /// The last element returned, if any, will contain the remainder of the
763 /// let mut v = [10, 40, 30, 20, 60, 50];
765 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
768 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
770 #[stable(feature = "rust1", since = "1.0.0")]
772 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, F>
773 where F: FnMut(&T) -> bool
775 core_slice::SliceExt::splitn_mut(self, n, pred)
778 /// Returns an iterator over subslices separated by elements that match
779 /// `pred` limited to returning at most `n` items. This starts at the end of
780 /// the slice and works backwards. The matched element is not contained in
783 /// The last element returned, if any, will contain the remainder of the
788 /// Print the slice split once, starting from the end, by numbers divisible
789 /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
792 /// let v = [10, 40, 30, 20, 60, 50];
794 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
795 /// println!("{:?}", group);
798 #[stable(feature = "rust1", since = "1.0.0")]
800 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F>
801 where F: FnMut(&T) -> bool
803 core_slice::SliceExt::rsplitn(self, n, pred)
806 /// Returns an iterator over subslices separated by elements that match
807 /// `pred` limited to returning at most `n` items. This starts at the end of
808 /// the slice and works backwards. The matched element is not contained in
811 /// The last element returned, if any, will contain the remainder of the
817 /// let mut s = [10, 40, 30, 20, 60, 50];
819 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
822 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
824 #[stable(feature = "rust1", since = "1.0.0")]
826 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, F>
827 where F: FnMut(&T) -> bool
829 core_slice::SliceExt::rsplitn_mut(self, n, pred)
832 /// Returns true if the slice contains an element with the given value.
837 /// let v = [10, 40, 30];
838 /// assert!(v.contains(&30));
839 /// assert!(!v.contains(&50));
841 #[stable(feature = "rust1", since = "1.0.0")]
842 pub fn contains(&self, x: &T) -> bool
845 core_slice::SliceExt::contains(self, x)
848 /// Returns true if `needle` is a prefix of the slice.
853 /// let v = [10, 40, 30];
854 /// assert!(v.starts_with(&[10]));
855 /// assert!(v.starts_with(&[10, 40]));
856 /// assert!(!v.starts_with(&[50]));
857 /// assert!(!v.starts_with(&[10, 50]));
859 #[stable(feature = "rust1", since = "1.0.0")]
860 pub fn starts_with(&self, needle: &[T]) -> bool
863 core_slice::SliceExt::starts_with(self, needle)
866 /// Returns true if `needle` is a suffix of the slice.
871 /// let v = [10, 40, 30];
872 /// assert!(v.ends_with(&[30]));
873 /// assert!(v.ends_with(&[40, 30]));
874 /// assert!(!v.ends_with(&[50]));
875 /// assert!(!v.ends_with(&[50, 30]));
877 #[stable(feature = "rust1", since = "1.0.0")]
878 pub fn ends_with(&self, needle: &[T]) -> bool
881 core_slice::SliceExt::ends_with(self, needle)
884 /// Binary search a sorted slice for a given element.
886 /// If the value is found then `Ok` is returned, containing the
887 /// index of the matching element; if the value is not found then
888 /// `Err` is returned, containing the index where a matching
889 /// element could be inserted while maintaining sorted order.
893 /// Looks up a series of four elements. The first is found, with a
894 /// uniquely determined position; the second and third are not
895 /// found; the fourth could match any position in `[1,4]`.
898 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
900 /// assert_eq!(s.binary_search(&13), Ok(9));
901 /// assert_eq!(s.binary_search(&4), Err(7));
902 /// assert_eq!(s.binary_search(&100), Err(13));
903 /// let r = s.binary_search(&1);
904 /// assert!(match r { Ok(1...4) => true, _ => false, });
906 #[stable(feature = "rust1", since = "1.0.0")]
907 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
910 core_slice::SliceExt::binary_search(self, x)
913 /// Binary search a sorted slice with a comparator function.
915 /// The comparator function should implement an order consistent
916 /// with the sort order of the underlying slice, returning an
917 /// order code that indicates whether its argument is `Less`,
918 /// `Equal` or `Greater` the desired target.
920 /// If a matching value is found then returns `Ok`, containing
921 /// the index for the matched element; if no match is found then
922 /// `Err` is returned, containing the index where a matching
923 /// element could be inserted while maintaining sorted order.
927 /// Looks up a series of four elements. The first is found, with a
928 /// uniquely determined position; the second and third are not
929 /// found; the fourth could match any position in `[1,4]`.
932 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
935 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
937 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
939 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
941 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
942 /// assert!(match r { Ok(1...4) => true, _ => false, });
944 #[stable(feature = "rust1", since = "1.0.0")]
946 pub fn binary_search_by<F>(&self, f: F) -> Result<usize, usize>
947 where F: FnMut(&T) -> Ordering
949 core_slice::SliceExt::binary_search_by(self, f)
952 /// Binary search a sorted slice with a key extraction function.
954 /// Assumes that the slice is sorted by the key, for instance with
955 /// `sort_by_key` using the same key extraction function.
957 /// If a matching value is found then returns `Ok`, containing the
958 /// index for the matched element; if no match is found then `Err`
959 /// is returned, containing the index where a matching element could
960 /// be inserted while maintaining sorted order.
964 /// Looks up a series of four elements in a slice of pairs sorted by
965 /// their second elements. The first is found, with a uniquely
966 /// determined position; the second and third are not found; the
967 /// fourth could match any position in `[1,4]`.
970 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
971 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
972 /// (1, 21), (2, 34), (4, 55)];
974 /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
975 /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7));
976 /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
977 /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
978 /// assert!(match r { Ok(1...4) => true, _ => false, });
980 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
982 pub fn binary_search_by_key<B, F>(&self, b: &B, f: F) -> Result<usize, usize>
983 where F: FnMut(&T) -> B,
986 core_slice::SliceExt::binary_search_by_key(self, b, f)
989 /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
991 /// This sort is stable and `O(n log n)` worst-case but allocates
992 /// approximately `2 * n` where `n` is the length of `self`.
997 /// let mut v = [-5, 4, 1, -3, 2];
1000 /// assert!(v == [-5, -3, 1, 2, 4]);
1002 #[stable(feature = "rust1", since = "1.0.0")]
1004 pub fn sort(&mut self)
1007 self.sort_by(|a, b| a.cmp(b))
1010 /// Sorts the slice, in place, using `key` to extract a key by which to
1011 /// order the sort by.
1013 /// This sort is stable and `O(n log n)` worst-case but allocates
1014 /// approximately `2 * n`, where `n` is the length of `self`.
1019 /// let mut v = [-5i32, 4, 1, -3, 2];
1021 /// v.sort_by_key(|k| k.abs());
1022 /// assert!(v == [1, 2, -3, 4, -5]);
1024 #[stable(feature = "slice_sort_by_key", since = "1.7.0")]
1026 pub fn sort_by_key<B, F>(&mut self, mut f: F)
1027 where F: FnMut(&T) -> B, B: Ord
1029 self.sort_by(|a, b| f(a).cmp(&f(b)))
1032 /// Sorts the slice, in place, using `compare` to compare
1035 /// This sort is stable and `O(n log n)` worst-case but allocates
1036 /// approximately `2 * n`, where `n` is the length of `self`.
1041 /// let mut v = [5, 4, 1, 3, 2];
1042 /// v.sort_by(|a, b| a.cmp(b));
1043 /// assert!(v == [1, 2, 3, 4, 5]);
1045 /// // reverse sorting
1046 /// v.sort_by(|a, b| b.cmp(a));
1047 /// assert!(v == [5, 4, 3, 2, 1]);
1049 #[stable(feature = "rust1", since = "1.0.0")]
1051 pub fn sort_by<F>(&mut self, compare: F)
1052 where F: FnMut(&T, &T) -> Ordering
1054 merge_sort(self, compare)
1057 /// Copies the elements from `src` into `self`.
1059 /// The length of `src` must be the same as `self`.
1063 /// This function will panic if the two slices have different lengths.
1068 /// let mut dst = [0, 0, 0];
1069 /// let src = [1, 2, 3];
1071 /// dst.clone_from_slice(&src);
1072 /// assert!(dst == [1, 2, 3]);
1074 #[stable(feature = "clone_from_slice", since = "1.7.0")]
1075 pub fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
1076 core_slice::SliceExt::clone_from_slice(self, src)
1079 /// Copies all elements from `src` into `self`, using a memcpy.
1081 /// The length of `src` must be the same as `self`.
1085 /// This function will panic if the two slices have different lengths.
1090 /// let mut dst = [0, 0, 0];
1091 /// let src = [1, 2, 3];
1093 /// dst.copy_from_slice(&src);
1094 /// assert_eq!(src, dst);
1096 #[stable(feature = "copy_from_slice", since = "1.9.0")]
1097 pub fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
1098 core_slice::SliceExt::copy_from_slice(self, src)
1102 /// Copies `self` into a new `Vec`.
1107 /// let s = [10, 40, 30];
1108 /// let x = s.to_vec();
1109 /// // Here, `s` and `x` can be modified independently.
1111 #[stable(feature = "rust1", since = "1.0.0")]
1113 pub fn to_vec(&self) -> Vec<T>
1116 // NB see hack module in this file
1120 /// Converts `self` into a vector without clones or allocation.
1125 /// let s: Box<[i32]> = Box::new([10, 40, 30]);
1126 /// let x = s.into_vec();
1127 /// // `s` cannot be used anymore because it has been converted into `x`.
1129 /// assert_eq!(x, vec!(10, 40, 30));
1131 #[stable(feature = "rust1", since = "1.0.0")]
1133 pub fn into_vec(self: Box<Self>) -> Vec<T> {
1134 // NB see hack module in this file
1135 hack::into_vec(self)
1139 ////////////////////////////////////////////////////////////////////////////////
1140 // Extension traits for slices over specific kinds of data
1141 ////////////////////////////////////////////////////////////////////////////////
1142 #[unstable(feature = "slice_concat_ext",
1143 reason = "trait should not have to exist",
1145 /// An extension trait for concatenating slices
1146 pub trait SliceConcatExt<T: ?Sized> {
1147 #[unstable(feature = "slice_concat_ext",
1148 reason = "trait should not have to exist",
1150 /// The resulting type after concatenation
1153 /// Flattens a slice of `T` into a single value `Self::Output`.
1158 /// assert_eq!(["hello", "world"].concat(), "helloworld");
1160 #[stable(feature = "rust1", since = "1.0.0")]
1161 fn concat(&self) -> Self::Output;
1163 /// Flattens a slice of `T` into a single value `Self::Output`, placing a
1164 /// given separator between each.
1169 /// assert_eq!(["hello", "world"].join(" "), "hello world");
1171 #[stable(feature = "rename_connect_to_join", since = "1.3.0")]
1172 fn join(&self, sep: &T) -> Self::Output;
1174 #[stable(feature = "rust1", since = "1.0.0")]
1175 #[rustc_deprecated(since = "1.3.0", reason = "renamed to join")]
1176 fn connect(&self, sep: &T) -> Self::Output;
1179 #[unstable(feature = "slice_concat_ext",
1180 reason = "trait should not have to exist",
1182 impl<T: Clone, V: Borrow<[T]>> SliceConcatExt<T> for [V] {
1183 type Output = Vec<T>;
1185 fn concat(&self) -> Vec<T> {
1186 let size = self.iter().fold(0, |acc, v| acc + v.borrow().len());
1187 let mut result = Vec::with_capacity(size);
1189 result.extend_from_slice(v.borrow())
1194 fn join(&self, sep: &T) -> Vec<T> {
1195 let size = self.iter().fold(0, |acc, v| acc + v.borrow().len());
1196 let mut result = Vec::with_capacity(size + self.len());
1197 let mut first = true;
1202 result.push(sep.clone())
1204 result.extend_from_slice(v.borrow())
1209 fn connect(&self, sep: &T) -> Vec<T> {
1214 ////////////////////////////////////////////////////////////////////////////////
1215 // Standard trait implementations for slices
1216 ////////////////////////////////////////////////////////////////////////////////
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 impl<T> Borrow<[T]> for Vec<T> {
1220 fn borrow(&self) -> &[T] {
1225 #[stable(feature = "rust1", since = "1.0.0")]
1226 impl<T> BorrowMut<[T]> for Vec<T> {
1227 fn borrow_mut(&mut self) -> &mut [T] {
1232 #[stable(feature = "rust1", since = "1.0.0")]
1233 impl<T: Clone> ToOwned for [T] {
1234 type Owned = Vec<T>;
1236 fn to_owned(&self) -> Vec<T> {
1240 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec`, which is required for this method
1241 // definition, is not available. Since we don't require this method for testing purposes, I'll
1243 // NB see the slice::hack module in slice.rs for more information
1245 fn to_owned(&self) -> Vec<T> {
1246 panic!("not available with cfg(test)")
1250 ////////////////////////////////////////////////////////////////////////////////
1252 ////////////////////////////////////////////////////////////////////////////////
1254 fn insertion_sort<T, F>(v: &mut [T], mut compare: F)
1255 where F: FnMut(&T, &T) -> Ordering
1257 let len = v.len() as isize;
1258 let buf_v = v.as_mut_ptr();
1262 // j satisfies: 0 <= j <= i;
1265 // `i` is in bounds.
1266 let read_ptr = buf_v.offset(i) as *const T;
1268 // find where to insert, we need to do strict <,
1269 // rather than <=, to maintain stability.
1271 // 0 <= j - 1 < len, so .offset(j - 1) is in bounds.
1272 while j > 0 && compare(&*read_ptr, &*buf_v.offset(j - 1)) == Less {
1276 // shift everything to the right, to make space to
1277 // insert this value.
1279 // j + 1 could be `len` (for the last `i`), but in
1280 // that case, `i == j` so we don't copy. The
1281 // `.offset(j)` is always in bounds.
1284 let tmp = ptr::read(read_ptr);
1285 ptr::copy(&*buf_v.offset(j), buf_v.offset(j + 1), (i - j) as usize);
1286 ptr::copy_nonoverlapping(&tmp, buf_v.offset(j), 1);
1293 fn merge_sort<T, F>(v: &mut [T], mut compare: F)
1294 where F: FnMut(&T, &T) -> Ordering
1296 // warning: this wildly uses unsafe.
1297 const BASE_INSERTION: usize = 32;
1298 const LARGE_INSERTION: usize = 16;
1300 // FIXME #12092: smaller insertion runs seems to make sorting
1301 // vectors of large elements a little faster on some platforms,
1302 // but hasn't been tested/tuned extensively
1303 let insertion = if size_of::<T>() <= 16 {
1311 // short vectors get sorted in-place via insertion sort to avoid allocations
1312 if len <= insertion {
1313 insertion_sort(v, compare);
1317 // allocate some memory to use as scratch memory, we keep the
1318 // length 0 so we can keep shallow copies of the contents of `v`
1319 // without risking the dtors running on an object twice if
1320 // `compare` panics.
1321 let mut working_space = Vec::with_capacity(2 * len);
1322 // these both are buffers of length `len`.
1323 let mut buf_dat = working_space.as_mut_ptr();
1324 let mut buf_tmp = unsafe { buf_dat.offset(len as isize) };
1327 let buf_v = v.as_ptr();
1329 // step 1. sort short runs with insertion sort. This takes the
1330 // values from `v` and sorts them into `buf_dat`, leaving that
1331 // with sorted runs of length INSERTION.
1333 // We could hardcode the sorting comparisons here, and we could
1334 // manipulate/step the pointers themselves, rather than repeatedly
1336 for start in (0..len).step_by(insertion) {
1337 // start <= i < len;
1338 for i in start..cmp::min(start + insertion, len) {
1339 // j satisfies: start <= j <= i;
1340 let mut j = i as isize;
1342 // `i` is in bounds.
1343 let read_ptr = buf_v.offset(i as isize);
1345 // find where to insert, we need to do strict <,
1346 // rather than <=, to maintain stability.
1348 // start <= j - 1 < len, so .offset(j - 1) is in
1350 while j > start as isize && compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less {
1354 // shift everything to the right, to make space to
1355 // insert this value.
1357 // j + 1 could be `len` (for the last `i`), but in
1358 // that case, `i == j` so we don't copy. The
1359 // `.offset(j)` is always in bounds.
1360 ptr::copy(&*buf_dat.offset(j), buf_dat.offset(j + 1), i - j as usize);
1361 ptr::copy_nonoverlapping(read_ptr, buf_dat.offset(j), 1);
1366 // step 2. merge the sorted runs.
1367 let mut width = insertion;
1369 // merge the sorted runs of length `width` in `buf_dat` two at
1370 // a time, placing the result in `buf_tmp`.
1372 // 0 <= start <= len.
1373 for start in (0..len).step_by(2 * width) {
1374 // manipulate pointers directly for speed (rather than
1375 // using a `for` loop with `range` and `.offset` inside
1378 // the end of the first run & start of the
1379 // second. Offset of `len` is defined, since this is
1380 // precisely one byte past the end of the object.
1381 let right_start = buf_dat.offset(cmp::min(start + width, len) as isize);
1382 // end of the second. Similar reasoning to the above re safety.
1383 let right_end_idx = cmp::min(start + 2 * width, len);
1384 let right_end = buf_dat.offset(right_end_idx as isize);
1386 // the pointers to the elements under consideration
1387 // from the two runs.
1389 // both of these are in bounds.
1390 let mut left = buf_dat.offset(start as isize);
1391 let mut right = right_start;
1393 // where we're putting the results, it is a run of
1394 // length `2*width`, so we step it once for each step
1395 // of either `left` or `right`. `buf_tmp` has length
1396 // `len`, so these are in bounds.
1397 let mut out = buf_tmp.offset(start as isize);
1398 let out_end = buf_tmp.offset(right_end_idx as isize);
1400 // If left[last] <= right[0], they are already in order:
1401 // fast-forward the left side (the right side is handled
1403 // If `right` is not empty then left is not empty, and
1404 // the offsets are in bounds.
1405 if right != right_end && compare(&*right.offset(-1), &*right) != Greater {
1406 let elems = (right_start as usize - left as usize) / mem::size_of::<T>();
1407 ptr::copy_nonoverlapping(&*left, out, elems);
1408 out = out.offset(elems as isize);
1412 while out < out_end {
1413 // Either the left or the right run are exhausted,
1414 // so just copy the remainder from the other run
1415 // and move on; this gives a huge speed-up (order
1416 // of 25%) for mostly sorted vectors (the best
1418 if left == right_start {
1419 // the number remaining in this run.
1420 let elems = (right_end as usize - right as usize) / mem::size_of::<T>();
1421 ptr::copy_nonoverlapping(&*right, out, elems);
1423 } else if right == right_end {
1424 let elems = (right_start as usize - left as usize) / mem::size_of::<T>();
1425 ptr::copy_nonoverlapping(&*left, out, elems);
1429 // check which side is smaller, and that's the
1430 // next element for the new run.
1432 // `left < right_start` and `right < right_end`,
1433 // so these are valid.
1434 let to_copy = if compare(&*left, &*right) == Greater {
1439 ptr::copy_nonoverlapping(&*to_copy, out, 1);
1445 mem::swap(&mut buf_dat, &mut buf_tmp);
1450 // write the result to `v` in one go, so that there are never two copies
1451 // of the same object in `v`.
1453 ptr::copy_nonoverlapping(&*buf_dat, v.as_mut_ptr(), len);
1456 // increment the pointer, returning the old pointer.
1458 unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
1460 *ptr = ptr.offset(1);