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 //! Utilities for slice manipulation
13 //! The `slice` module contains useful code to help work with slice values.
14 //! Slices are a view into a block of memory represented as a pointer and a length.
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 iterators of yield references
54 //! to the slice elements.
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 the element
73 //! type of the slice is `i32`, the element type of the iterator is `&mut i32`.
75 //! * `.iter()` and `.iter_mut()` are the explicit methods to return the default
77 //! * Further methods that return iterators are `.split()`, `.splitn()`,
78 //! `.chunks()`, `.windows()` and more.
80 #![doc(primitive = "slice")]
81 #![stable(feature = "rust1", since = "1.0.0")]
83 use alloc::boxed::Box;
84 use core::convert::AsRef;
85 use core::clone::Clone;
86 use core::cmp::Ordering::{self, Greater, Less};
87 use core::cmp::{self, Ord, PartialEq};
88 use core::iter::{Iterator, IteratorExt};
89 use core::iter::MultiplicativeIterator;
90 use core::marker::Sized;
91 use core::mem::size_of;
93 use core::num::wrapping::WrappingOps;
95 use core::option::Option::{self, Some, None};
97 use core::result::Result;
98 use core::slice as core_slice;
99 use self::Direction::*;
101 use borrow::{Borrow, BorrowMut, ToOwned};
104 pub use core::slice::{Chunks, AsSlice, Windows};
105 pub use core::slice::{Iter, IterMut};
106 pub use core::slice::{IntSliceExt, SplitMut, ChunksMut, Split};
107 pub use core::slice::{SplitN, RSplitN, SplitNMut, RSplitNMut};
108 pub use core::slice::{bytes, mut_ref_slice, ref_slice};
109 pub use core::slice::{from_raw_parts, from_raw_parts_mut};
110 pub use core::slice::{from_raw_buf, from_raw_mut_buf};
112 ////////////////////////////////////////////////////////////////////////////////
113 // Basic slice extension methods
114 ////////////////////////////////////////////////////////////////////////////////
116 // HACK(japaric) needed for the implementation of `vec!` macro during testing
117 // NB see the hack module in this file for more details
119 pub use self::hack::into_vec;
121 // HACK(japaric) needed for the implementation of `Vec::clone` during testing
122 // NB see the hack module in this file for more details
124 pub use self::hack::to_vec;
126 // HACK(japaric): With cfg(test) `impl [T]` is not available, these three
127 // functions are actually methods that are in `impl [T]` but not in
128 // `core::slice::SliceExt` - we need to supply these functions for the
129 // `test_permutations` test
131 use alloc::boxed::Box;
132 use core::clone::Clone;
134 use core::iter::{Iterator, IteratorExt};
137 use core::option::Option::{Some, None};
140 use string::ToString;
143 use super::{ElementSwaps, Permutations};
145 pub fn into_vec<T>(mut b: Box<[T]>) -> Vec<T> {
147 let xs = Vec::from_raw_parts(b.as_mut_ptr(), b.len(), b.len());
153 pub fn permutations<T>(s: &[T]) -> Permutations<T> where T: Clone {
155 swaps: ElementSwaps::new(s.len()),
161 pub fn to_vec<T>(s: &[T]) -> Vec<T> where T: Clone {
162 let mut vector = Vec::with_capacity(s.len());
167 // NB we can remove this hack if we move this test to libcollectionstest -
168 // but that can't be done right now because the test needs access to the
169 // private fields of Permutations
171 fn test_permutations() {
173 let v: [i32; 0] = [];
174 let mut it = permutations(&v);
175 let (min_size, max_opt) = it.size_hint();
176 assert_eq!(min_size, 1);
177 assert_eq!(max_opt.unwrap(), 1);
178 assert_eq!(it.next(), Some(to_vec(&v)));
179 assert_eq!(it.next(), None);
182 let v = ["Hello".to_string()];
183 let mut it = permutations(&v);
184 let (min_size, max_opt) = it.size_hint();
185 assert_eq!(min_size, 1);
186 assert_eq!(max_opt.unwrap(), 1);
187 assert_eq!(it.next(), Some(to_vec(&v)));
188 assert_eq!(it.next(), None);
192 let mut it = permutations(&v);
193 let (min_size, max_opt) = it.size_hint();
194 assert_eq!(min_size, 3*2);
195 assert_eq!(max_opt.unwrap(), 3*2);
196 assert_eq!(it.next().unwrap(), [1,2,3]);
197 assert_eq!(it.next().unwrap(), [1,3,2]);
198 assert_eq!(it.next().unwrap(), [3,1,2]);
199 let (min_size, max_opt) = it.size_hint();
200 assert_eq!(min_size, 3);
201 assert_eq!(max_opt.unwrap(), 3);
202 assert_eq!(it.next().unwrap(), [3,2,1]);
203 assert_eq!(it.next().unwrap(), [2,3,1]);
204 assert_eq!(it.next().unwrap(), [2,1,3]);
205 assert_eq!(it.next(), None);
208 // check that we have N! permutations
209 let v = ['A', 'B', 'C', 'D', 'E', 'F'];
211 let mut it = permutations(&v);
212 let (min_size, max_opt) = it.size_hint();
213 for _perm in it.by_ref() {
216 assert_eq!(amt, it.swaps.swaps_made);
217 assert_eq!(amt, min_size);
218 assert_eq!(amt, 2 * 3 * 4 * 5 * 6);
219 assert_eq!(amt, max_opt.unwrap());
224 /// Allocating extension methods for slices.
227 #[stable(feature = "rust1", since = "1.0.0")]
229 /// Sorts the slice, in place, using `compare` to compare
232 /// This sort is `O(n log n)` worst-case and stable, but allocates
233 /// approximately `2 * n`, where `n` is the length of `self`.
238 /// let mut v = [5, 4, 1, 3, 2];
239 /// v.sort_by(|a, b| a.cmp(b));
240 /// assert!(v == [1, 2, 3, 4, 5]);
242 /// // reverse sorting
243 /// v.sort_by(|a, b| b.cmp(a));
244 /// assert!(v == [5, 4, 3, 2, 1]);
246 #[stable(feature = "rust1", since = "1.0.0")]
248 pub fn sort_by<F>(&mut self, compare: F) where F: FnMut(&T, &T) -> Ordering {
249 merge_sort(self, compare)
252 /// Consumes `src` and moves as many elements as it can into `self`
253 /// from the range [start,end).
255 /// Returns the number of elements copied (the shorter of `self.len()`
256 /// and `end - start`).
260 /// * src - A mutable vector of `T`
261 /// * start - The index into `src` to start copying from
262 /// * end - The index into `src` to stop copying from
267 /// # #![feature(collections)]
268 /// let mut a = [1, 2, 3, 4, 5];
269 /// let b = vec![6, 7, 8];
270 /// let num_moved = a.move_from(b, 0, 3);
271 /// assert_eq!(num_moved, 3);
272 /// assert!(a == [6, 7, 8, 4, 5]);
274 #[unstable(feature = "collections",
275 reason = "uncertain about this API approach")]
277 pub fn move_from(&mut self, mut src: Vec<T>, start: usize, end: usize) -> usize {
278 for (a, b) in self.iter_mut().zip(src[start .. end].iter_mut()) {
281 cmp::min(self.len(), end-start)
284 /// Deprecated: use `&s[start .. end]` notation instead.
285 #[unstable(feature = "collections",
286 reason = "will be replaced by slice syntax")]
287 #[deprecated(since = "1.0.0", reason = "use &s[start .. end] instead")]
289 pub fn slice(&self, start: usize, end: usize) -> &[T] {
293 /// Deprecated: use `&s[start..]` notation instead.
294 #[unstable(feature = "collections",
295 reason = "will be replaced by slice syntax")]
296 #[deprecated(since = "1.0.0", reason = "use &s[start..] instead")]
298 pub fn slice_from(&self, start: usize) -> &[T] {
302 /// Deprecated: use `&s[..end]` notation instead.
303 #[unstable(feature = "collections",
304 reason = "will be replaced by slice syntax")]
305 #[deprecated(since = "1.0.0", reason = "use &s[..end] instead")]
307 pub fn slice_to(&self, end: usize) -> &[T] {
311 /// Divides one slice into two at an index.
313 /// The first will contain all indices from `[0, mid)` (excluding
314 /// the index `mid` itself) and the second will contain all
315 /// indices from `[mid, len)` (excluding the index `len` itself).
317 /// Panics if `mid > len`.
322 /// let v = [10, 40, 30, 20, 50];
323 /// let (v1, v2) = v.split_at(2);
324 /// assert_eq!([10, 40], v1);
325 /// assert_eq!([30, 20, 50], v2);
327 #[stable(feature = "rust1", since = "1.0.0")]
329 pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
330 core_slice::SliceExt::split_at(self, mid)
333 /// Returns an iterator over the slice.
334 #[stable(feature = "rust1", since = "1.0.0")]
336 pub fn iter(&self) -> Iter<T> {
337 core_slice::SliceExt::iter(self)
340 /// Returns an iterator over subslices separated by elements that match
341 /// `pred`. The matched element is not contained in the subslices.
345 /// Print the slice split by numbers divisible by 3 (i.e. `[10, 40]`,
349 /// let v = [10, 40, 30, 20, 60, 50];
350 /// for group in v.split(|num| *num % 3 == 0) {
351 /// println!("{:?}", group);
354 #[stable(feature = "rust1", since = "1.0.0")]
356 pub fn split<F>(&self, pred: F) -> Split<T, F> where F: FnMut(&T) -> bool {
357 core_slice::SliceExt::split(self, pred)
360 /// Returns an iterator over subslices separated by elements that match
361 /// `pred`, limited to splitting at most `n` times. The matched element is
362 /// not contained in the subslices.
366 /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
370 /// let v = [10, 40, 30, 20, 60, 50];
371 /// for group in v.splitn(1, |num| *num % 3 == 0) {
372 /// println!("{:?}", group);
375 #[stable(feature = "rust1", since = "1.0.0")]
377 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F> where F: FnMut(&T) -> bool {
378 core_slice::SliceExt::splitn(self, n, pred)
381 /// Returns an iterator over subslices separated by elements that match
382 /// `pred` limited to splitting at most `n` times. This starts at the end of
383 /// the slice and works backwards. The matched element is not contained in
388 /// Print the slice split once, starting from the end, by numbers divisible
389 /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
392 /// let v = [10, 40, 30, 20, 60, 50];
393 /// for group in v.rsplitn(1, |num| *num % 3 == 0) {
394 /// println!("{:?}", group);
397 #[stable(feature = "rust1", since = "1.0.0")]
399 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F> where F: FnMut(&T) -> bool {
400 core_slice::SliceExt::rsplitn(self, n, pred)
403 /// Returns an iterator over all contiguous windows of length
404 /// `size`. The windows overlap. If the slice is shorter than
405 /// `size`, the iterator returns no values.
409 /// Panics if `size` is 0.
413 /// Print the adjacent pairs of a slice (i.e. `[1,2]`, `[2,3]`,
417 /// let v = &[1, 2, 3, 4];
418 /// for win in v.windows(2) {
419 /// println!("{:?}", win);
422 #[stable(feature = "rust1", since = "1.0.0")]
424 pub fn windows(&self, size: usize) -> Windows<T> {
425 core_slice::SliceExt::windows(self, size)
428 /// Returns an iterator over `size` elements of the slice at a
429 /// time. The chunks do not overlap. If `size` does not divide the
430 /// length of the slice, then the last chunk will not have length
435 /// Panics if `size` is 0.
439 /// Print the slice two elements at a time (i.e. `[1,2]`,
443 /// let v = &[1, 2, 3, 4, 5];
444 /// for win in v.chunks(2) {
445 /// println!("{:?}", win);
448 #[stable(feature = "rust1", since = "1.0.0")]
450 pub fn chunks(&self, size: usize) -> Chunks<T> {
451 core_slice::SliceExt::chunks(self, size)
454 /// Returns the element of a slice at the given index, or `None` if the
455 /// index is out of bounds.
460 /// let v = [10, 40, 30];
461 /// assert_eq!(Some(&40), v.get(1));
462 /// assert_eq!(None, v.get(3));
464 #[stable(feature = "rust1", since = "1.0.0")]
466 pub fn get(&self, index: usize) -> Option<&T> {
467 core_slice::SliceExt::get(self, index)
470 /// Returns the first element of a slice, or `None` if it is empty.
475 /// let v = [10, 40, 30];
476 /// assert_eq!(Some(&10), v.first());
478 /// let w: &[i32] = &[];
479 /// assert_eq!(None, w.first());
481 #[stable(feature = "rust1", since = "1.0.0")]
483 pub fn first(&self) -> Option<&T> {
484 core_slice::SliceExt::first(self)
487 /// Returns all but the first element of a slice.
488 #[unstable(feature = "collections", reason = "likely to be renamed")]
490 pub fn tail(&self) -> &[T] {
491 core_slice::SliceExt::tail(self)
494 /// Returns all but the last element of a slice.
495 #[unstable(feature = "collections", reason = "likely to be renamed")]
497 pub fn init(&self) -> &[T] {
498 core_slice::SliceExt::init(self)
501 /// Returns the last element of a slice, or `None` if it is empty.
506 /// let v = [10, 40, 30];
507 /// assert_eq!(Some(&30), v.last());
509 /// let w: &[i32] = &[];
510 /// assert_eq!(None, w.last());
512 #[stable(feature = "rust1", since = "1.0.0")]
514 pub fn last(&self) -> Option<&T> {
515 core_slice::SliceExt::last(self)
518 /// Returns a pointer to the element at the given index, without doing
520 #[stable(feature = "rust1", since = "1.0.0")]
522 pub unsafe fn get_unchecked(&self, index: usize) -> &T {
523 core_slice::SliceExt::get_unchecked(self, index)
526 /// Returns an unsafe pointer to the slice's buffer
528 /// The caller must ensure that the slice outlives the pointer this
529 /// function returns, or else it will end up pointing to garbage.
531 /// Modifying the slice may cause its buffer to be reallocated, which
532 /// would also make any pointers to it invalid.
533 #[stable(feature = "rust1", since = "1.0.0")]
535 pub fn as_ptr(&self) -> *const T {
536 core_slice::SliceExt::as_ptr(self)
539 /// Binary search a sorted slice with a comparator function.
541 /// The comparator function should implement an order consistent
542 /// with the sort order of the underlying slice, returning an
543 /// order code that indicates whether its argument is `Less`,
544 /// `Equal` or `Greater` the desired target.
546 /// If a matching value is found then returns `Ok`, containing
547 /// the index for the matched element; if no match is found then
548 /// `Err` is returned, containing the index where a matching
549 /// element could be inserted while maintaining sorted order.
553 /// Looks up a series of four elements. The first is found, with a
554 /// uniquely determined position; the second and third are not
555 /// found; the fourth could match any position in `[1,4]`.
558 /// # #![feature(core)]
559 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
560 /// let s = s.as_slice();
563 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
565 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
567 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
569 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
570 /// assert!(match r { Ok(1...4) => true, _ => false, });
572 #[stable(feature = "rust1", since = "1.0.0")]
574 pub fn binary_search_by<F>(&self, f: F) -> Result<usize, usize> where F: FnMut(&T) -> Ordering {
575 core_slice::SliceExt::binary_search_by(self, f)
578 /// Return the number of elements in the slice
583 /// let a = [1, 2, 3];
584 /// assert_eq!(a.len(), 3);
586 #[stable(feature = "rust1", since = "1.0.0")]
588 pub fn len(&self) -> usize {
589 core_slice::SliceExt::len(self)
592 /// Returns true if the slice has a length of 0
597 /// let a = [1, 2, 3];
598 /// assert!(!a.is_empty());
600 #[stable(feature = "rust1", since = "1.0.0")]
602 pub fn is_empty(&self) -> bool {
603 core_slice::SliceExt::is_empty(self)
606 /// Returns a mutable reference to the element at the given index,
607 /// or `None` if the index is out of bounds
608 #[stable(feature = "rust1", since = "1.0.0")]
610 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
611 core_slice::SliceExt::get_mut(self, index)
614 /// Work with `self` as a mut slice.
615 /// Primarily intended for getting a &mut [T] from a [T; N].
616 #[stable(feature = "rust1", since = "1.0.0")]
617 pub fn as_mut_slice(&mut self) -> &mut [T] {
618 core_slice::SliceExt::as_mut_slice(self)
621 /// Deprecated: use `&mut s[start .. end]` instead.
622 #[unstable(feature = "collections",
623 reason = "will be replaced by slice syntax")]
624 #[deprecated(since = "1.0.0", reason = "use &mut s[start .. end] instead")]
626 pub fn slice_mut(&mut self, start: usize, end: usize) -> &mut [T] {
627 &mut self[start .. end]
630 /// Deprecated: use `&mut s[start ..]` instead.
631 #[unstable(feature = "collections",
632 reason = "will be replaced by slice syntax")]
633 #[deprecated(since = "1.0.0", reason = "use &mut s[start ..] instead")]
635 pub fn slice_from_mut(&mut self, start: usize) -> &mut [T] {
639 /// Deprecated: use `&mut s[.. end]` instead.
640 #[unstable(feature = "collections",
641 reason = "will be replaced by slice syntax")]
642 #[deprecated(since = "1.0.0", reason = "use &mut s[.. end] instead")]
644 pub fn slice_to_mut(&mut self, end: usize) -> &mut [T] {
648 /// Returns an iterator that allows modifying each value
649 #[stable(feature = "rust1", since = "1.0.0")]
651 pub fn iter_mut(&mut self) -> IterMut<T> {
652 core_slice::SliceExt::iter_mut(self)
655 /// Returns a mutable pointer to the first element of a slice, or `None` if it is empty
656 #[stable(feature = "rust1", since = "1.0.0")]
658 pub fn first_mut(&mut self) -> Option<&mut T> {
659 core_slice::SliceExt::first_mut(self)
662 /// Returns all but the first element of a mutable slice
663 #[unstable(feature = "collections",
664 reason = "likely to be renamed or removed")]
666 pub fn tail_mut(&mut self) -> &mut [T] {
667 core_slice::SliceExt::tail_mut(self)
670 /// Returns all but the last element of a mutable slice
671 #[unstable(feature = "collections",
672 reason = "likely to be renamed or removed")]
674 pub fn init_mut(&mut self) -> &mut [T] {
675 core_slice::SliceExt::init_mut(self)
678 /// Returns a mutable pointer to the last item in the slice.
679 #[stable(feature = "rust1", since = "1.0.0")]
681 pub fn last_mut(&mut self) -> Option<&mut T> {
682 core_slice::SliceExt::last_mut(self)
685 /// Returns an iterator over mutable subslices separated by elements that
686 /// match `pred`. The matched element is not contained in the subslices.
687 #[stable(feature = "rust1", since = "1.0.0")]
689 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F> where F: FnMut(&T) -> bool {
690 core_slice::SliceExt::split_mut(self, pred)
693 /// Returns an iterator over subslices separated by elements that match
694 /// `pred`, limited to splitting at most `n` times. The matched element is
695 /// not contained in the subslices.
696 #[stable(feature = "rust1", since = "1.0.0")]
698 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, F>
699 where F: FnMut(&T) -> bool {
700 core_slice::SliceExt::splitn_mut(self, n, pred)
703 /// Returns an iterator over subslices separated by elements that match
704 /// `pred` limited to splitting at most `n` times. This starts at the end of
705 /// the slice and works backwards. The matched element is not contained in
707 #[stable(feature = "rust1", since = "1.0.0")]
709 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, F>
710 where F: FnMut(&T) -> bool {
711 core_slice::SliceExt::rsplitn_mut(self, n, pred)
714 /// Returns an iterator over `chunk_size` elements of the slice at a time.
715 /// The chunks are mutable and do not overlap. If `chunk_size` does
716 /// not divide the length of the slice, then the last chunk will not
717 /// have length `chunk_size`.
721 /// Panics if `chunk_size` is 0.
722 #[stable(feature = "rust1", since = "1.0.0")]
724 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
725 core_slice::SliceExt::chunks_mut(self, chunk_size)
728 /// Swaps two elements in a slice.
732 /// * a - The index of the first element
733 /// * b - The index of the second element
737 /// Panics if `a` or `b` are out of bounds.
742 /// let mut v = ["a", "b", "c", "d"];
744 /// assert!(v == ["a", "d", "c", "b"]);
746 #[stable(feature = "rust1", since = "1.0.0")]
748 pub fn swap(&mut self, a: usize, b: usize) {
749 core_slice::SliceExt::swap(self, a, b)
752 /// Divides one `&mut` into two at an index.
754 /// The first will contain all indices from `[0, mid)` (excluding
755 /// the index `mid` itself) and the second will contain all
756 /// indices from `[mid, len)` (excluding the index `len` itself).
760 /// Panics if `mid > len`.
765 /// let mut v = [1, 2, 3, 4, 5, 6];
767 /// // scoped to restrict the lifetime of the borrows
769 /// let (left, right) = v.split_at_mut(0);
770 /// assert!(left == []);
771 /// assert!(right == [1, 2, 3, 4, 5, 6]);
775 /// let (left, right) = v.split_at_mut(2);
776 /// assert!(left == [1, 2]);
777 /// assert!(right == [3, 4, 5, 6]);
781 /// let (left, right) = v.split_at_mut(6);
782 /// assert!(left == [1, 2, 3, 4, 5, 6]);
783 /// assert!(right == []);
786 #[stable(feature = "rust1", since = "1.0.0")]
788 pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
789 core_slice::SliceExt::split_at_mut(self, mid)
792 /// Reverse the order of elements in a slice, in place.
797 /// let mut v = [1, 2, 3];
799 /// assert!(v == [3, 2, 1]);
801 #[stable(feature = "rust1", since = "1.0.0")]
803 pub fn reverse(&mut self) {
804 core_slice::SliceExt::reverse(self)
807 /// Returns an unsafe mutable pointer to the element in index
808 #[stable(feature = "rust1", since = "1.0.0")]
810 pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
811 core_slice::SliceExt::get_unchecked_mut(self, index)
814 /// Return an unsafe mutable pointer to the slice's buffer.
816 /// The caller must ensure that the slice outlives the pointer this
817 /// function returns, or else it will end up pointing to garbage.
819 /// Modifying the slice may cause its buffer to be reallocated, which
820 /// would also make any pointers to it invalid.
821 #[stable(feature = "rust1", since = "1.0.0")]
823 pub fn as_mut_ptr(&mut self) -> *mut T {
824 core_slice::SliceExt::as_mut_ptr(self)
827 /// Copies `self` into a new `Vec`.
828 #[stable(feature = "rust1", since = "1.0.0")]
830 pub fn to_vec(&self) -> Vec<T> where T: Clone {
831 // NB see hack module in this file
835 /// Creates an iterator that yields every possible permutation of the
836 /// vector in succession.
841 /// # #![feature(collections)]
842 /// let v = [1, 2, 3];
843 /// let mut perms = v.permutations();
846 /// println!("{:?}", p);
850 /// Iterating through permutations one by one.
853 /// # #![feature(collections)]
854 /// let v = [1, 2, 3];
855 /// let mut perms = v.permutations();
857 /// assert_eq!(Some(vec![1, 2, 3]), perms.next());
858 /// assert_eq!(Some(vec![1, 3, 2]), perms.next());
859 /// assert_eq!(Some(vec![3, 1, 2]), perms.next());
861 #[unstable(feature = "collections")]
863 pub fn permutations(&self) -> Permutations<T> where T: Clone {
864 // NB see hack module in this file
865 hack::permutations(self)
868 /// Copies as many elements from `src` as it can into `self` (the
869 /// shorter of `self.len()` and `src.len()`). Returns the number
870 /// of elements copied.
875 /// # #![feature(collections)]
876 /// let mut dst = [0, 0, 0];
877 /// let src = [1, 2];
879 /// assert!(dst.clone_from_slice(&src) == 2);
880 /// assert!(dst == [1, 2, 0]);
882 /// let src2 = [3, 4, 5, 6];
883 /// assert!(dst.clone_from_slice(&src2) == 3);
884 /// assert!(dst == [3, 4, 5]);
886 #[unstable(feature = "collections")]
887 pub fn clone_from_slice(&mut self, src: &[T]) -> usize where T: Clone {
888 core_slice::SliceExt::clone_from_slice(self, src)
891 /// Sorts the slice, in place.
893 /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
898 /// let mut v = [-5, 4, 1, -3, 2];
901 /// assert!(v == [-5, -3, 1, 2, 4]);
903 #[stable(feature = "rust1", since = "1.0.0")]
905 pub fn sort(&mut self) where T: Ord {
906 self.sort_by(|a, b| a.cmp(b))
909 /// Binary search a sorted slice for a given element.
911 /// If the value is found then `Ok` is returned, containing the
912 /// index of the matching element; if the value is not found then
913 /// `Err` is returned, containing the index where a matching
914 /// element could be inserted while maintaining sorted order.
918 /// Looks up a series of four elements. The first is found, with a
919 /// uniquely determined position; the second and third are not
920 /// found; the fourth could match any position in `[1,4]`.
923 /// # #![feature(core)]
924 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
925 /// let s = s.as_slice();
927 /// assert_eq!(s.binary_search(&13), Ok(9));
928 /// assert_eq!(s.binary_search(&4), Err(7));
929 /// assert_eq!(s.binary_search(&100), Err(13));
930 /// let r = s.binary_search(&1);
931 /// assert!(match r { Ok(1...4) => true, _ => false, });
933 #[stable(feature = "rust1", since = "1.0.0")]
934 pub fn binary_search(&self, x: &T) -> Result<usize, usize> where T: Ord {
935 core_slice::SliceExt::binary_search(self, x)
938 /// Deprecated: use `binary_search` instead.
939 #[unstable(feature = "collections")]
940 #[deprecated(since = "1.0.0", reason = "use binary_search instead")]
941 pub fn binary_search_elem(&self, x: &T) -> Result<usize, usize> where T: Ord {
942 self.binary_search(x)
945 /// Mutates the slice to the next lexicographic permutation.
947 /// Returns `true` if successful and `false` if the slice is at the
948 /// last-ordered permutation.
953 /// # #![feature(collections)]
954 /// let v: &mut [_] = &mut [0, 1, 2];
955 /// v.next_permutation();
956 /// let b: &mut [_] = &mut [0, 2, 1];
958 /// v.next_permutation();
959 /// let b: &mut [_] = &mut [1, 0, 2];
962 #[unstable(feature = "collections",
963 reason = "uncertain if this merits inclusion in std")]
964 pub fn next_permutation(&mut self) -> bool where T: Ord {
965 core_slice::SliceExt::next_permutation(self)
968 /// Mutates the slice to the previous lexicographic permutation.
970 /// Returns `true` if successful and `false` if the slice is at the
971 /// first-ordered permutation.
976 /// # #![feature(collections)]
977 /// let v: &mut [_] = &mut [1, 0, 2];
978 /// v.prev_permutation();
979 /// let b: &mut [_] = &mut [0, 2, 1];
981 /// v.prev_permutation();
982 /// let b: &mut [_] = &mut [0, 1, 2];
985 #[unstable(feature = "collections",
986 reason = "uncertain if this merits inclusion in std")]
987 pub fn prev_permutation(&mut self) -> bool where T: Ord {
988 core_slice::SliceExt::prev_permutation(self)
991 /// Find the first index containing a matching value.
992 #[unstable(feature = "collections")]
993 pub fn position_elem(&self, t: &T) -> Option<usize> where T: PartialEq {
994 core_slice::SliceExt::position_elem(self, t)
997 /// Find the last index containing a matching value.
998 #[unstable(feature = "collections")]
999 pub fn rposition_elem(&self, t: &T) -> Option<usize> where T: PartialEq {
1000 core_slice::SliceExt::rposition_elem(self, t)
1003 /// Returns true if the slice contains an element with the given value.
1008 /// let v = [10, 40, 30];
1009 /// assert!(v.contains(&30));
1010 /// assert!(!v.contains(&50));
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 pub fn contains(&self, x: &T) -> bool where T: PartialEq {
1014 core_slice::SliceExt::contains(self, x)
1017 /// Returns true if `needle` is a prefix of the slice.
1022 /// let v = [10, 40, 30];
1023 /// assert!(v.starts_with(&[10]));
1024 /// assert!(v.starts_with(&[10, 40]));
1025 /// assert!(!v.starts_with(&[50]));
1026 /// assert!(!v.starts_with(&[10, 50]));
1028 #[stable(feature = "rust1", since = "1.0.0")]
1029 pub fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
1030 core_slice::SliceExt::starts_with(self, needle)
1033 /// Returns true if `needle` is a suffix of the slice.
1038 /// let v = [10, 40, 30];
1039 /// assert!(v.ends_with(&[30]));
1040 /// assert!(v.ends_with(&[40, 30]));
1041 /// assert!(!v.ends_with(&[50]));
1042 /// assert!(!v.ends_with(&[50, 30]));
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 pub fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
1046 core_slice::SliceExt::ends_with(self, needle)
1049 /// Convert `self` into a vector without clones or allocation.
1050 #[stable(feature = "rust1", since = "1.0.0")]
1052 pub fn into_vec(self: Box<Self>) -> Vec<T> {
1053 // NB see hack module in this file
1054 hack::into_vec(self)
1058 ////////////////////////////////////////////////////////////////////////////////
1059 // Extension traits for slices over specific kinds of data
1060 ////////////////////////////////////////////////////////////////////////////////
1061 #[unstable(feature = "collections", reason = "U should be an associated type")]
1062 /// An extension trait for concatenating slices
1063 pub trait SliceConcatExt<T: ?Sized, U> {
1064 /// Flattens a slice of `T` into a single value `U`.
1069 /// let v = vec!["hello", "world"];
1071 /// let s: String = v.concat();
1073 /// println!("{}", s); // prints "helloworld"
1075 #[stable(feature = "rust1", since = "1.0.0")]
1076 fn concat(&self) -> U;
1078 /// Flattens a slice of `T` into a single value `U`, placing a given separator between each.
1083 /// let v = vec!["hello", "world"];
1085 /// let s: String = v.connect(" ");
1087 /// println!("{}", s); // prints "hello world"
1089 #[stable(feature = "rust1", since = "1.0.0")]
1090 fn connect(&self, sep: &T) -> U;
1093 impl<T: Clone, V: AsRef<[T]>> SliceConcatExt<T, Vec<T>> for [V] {
1094 fn concat(&self) -> Vec<T> {
1095 let size = self.iter().fold(0, |acc, v| acc + v.as_ref().len());
1096 let mut result = Vec::with_capacity(size);
1098 result.push_all(v.as_ref())
1103 fn connect(&self, sep: &T) -> Vec<T> {
1104 let size = self.iter().fold(0, |acc, v| acc + v.as_ref().len());
1105 let mut result = Vec::with_capacity(size + self.len());
1106 let mut first = true;
1108 if first { first = false } else { result.push(sep.clone()) }
1109 result.push_all(v.as_ref())
1115 /// An iterator that yields the element swaps needed to produce
1116 /// a sequence of all possible permutations for an indexed sequence of
1117 /// elements. Each permutation is only a single swap apart.
1119 /// The Steinhaus-Johnson-Trotter algorithm is used.
1121 /// Generates even and odd permutations alternately.
1123 /// The last generated swap is always (0, 1), and it returns the
1124 /// sequence to its initial order.
1125 #[unstable(feature = "collections")]
1127 pub struct ElementSwaps {
1128 sdir: Vec<SizeDirection>,
1129 /// If `true`, emit the last swap that returns the sequence to initial
1136 /// Creates an `ElementSwaps` iterator for a sequence of `length` elements.
1137 #[unstable(feature = "collections")]
1138 pub fn new(length: usize) -> ElementSwaps {
1139 // Initialize `sdir` with a direction that position should move in
1140 // (all negative at the beginning) and the `size` of the
1141 // element (equal to the original index).
1144 sdir: (0..length).map(|i| SizeDirection{ size: i, dir: Neg }).collect(),
1150 ////////////////////////////////////////////////////////////////////////////////
1151 // Standard trait implementations for slices
1152 ////////////////////////////////////////////////////////////////////////////////
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 impl<T> Borrow<[T]> for Vec<T> {
1156 fn borrow(&self) -> &[T] { &self[..] }
1159 #[stable(feature = "rust1", since = "1.0.0")]
1160 impl<T> BorrowMut<[T]> for Vec<T> {
1161 fn borrow_mut(&mut self) -> &mut [T] { &mut self[..] }
1164 #[stable(feature = "rust1", since = "1.0.0")]
1165 impl<T: Clone> ToOwned for [T] {
1166 type Owned = Vec<T>;
1168 fn to_owned(&self) -> Vec<T> { self.to_vec() }
1170 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec`, which is required for this method
1171 // definition, is not available. Since we don't require this method for testing purposes, I'll
1173 // NB see the slice::hack module in slice.rs for more information
1175 fn to_owned(&self) -> Vec<T> { panic!("not available with cfg(test)") }
1178 ////////////////////////////////////////////////////////////////////////////////
1180 ////////////////////////////////////////////////////////////////////////////////
1182 #[derive(Copy, Clone)]
1183 enum Direction { Pos, Neg }
1185 /// An `Index` and `Direction` together.
1186 #[derive(Copy, Clone)]
1187 struct SizeDirection {
1192 #[stable(feature = "rust1", since = "1.0.0")]
1193 impl Iterator for ElementSwaps {
1194 type Item = (usize, usize);
1197 fn next(&mut self) -> Option<(usize, usize)> {
1198 fn new_pos_wrapping(i: usize, s: Direction) -> usize {
1199 i.wrapping_add(match s { Pos => 1, Neg => -1 })
1202 fn new_pos(i: usize, s: Direction) -> usize {
1203 match s { Pos => i + 1, Neg => i - 1 }
1206 // Find the index of the largest mobile element:
1207 // The direction should point into the vector, and the
1208 // swap should be with a smaller `size` element.
1209 let max = self.sdir.iter().cloned().enumerate()
1211 new_pos_wrapping(i, sd.dir) < self.sdir.len() &&
1212 self.sdir[new_pos(i, sd.dir)].size < sd.size)
1213 .max_by(|&(_, sd)| sd.size);
1216 let j = new_pos(i, sd.dir);
1217 self.sdir.swap(i, j);
1219 // Swap the direction of each larger SizeDirection
1220 for x in &mut self.sdir {
1221 if x.size > sd.size {
1222 x.dir = match x.dir { Pos => Neg, Neg => Pos };
1225 self.swaps_made += 1;
1228 None => if self.emit_reset {
1229 self.emit_reset = false;
1230 if self.sdir.len() > 1 {
1232 self.swaps_made += 1;
1235 // Vector is of the form [] or [x], and the only permutation is itself
1236 self.swaps_made += 1;
1244 fn size_hint(&self) -> (usize, Option<usize>) {
1245 // For a vector of size n, there are exactly n! permutations.
1246 let n = (2..self.sdir.len() + 1).product();
1247 (n - self.swaps_made, Some(n - self.swaps_made))
1251 /// An iterator that uses `ElementSwaps` to iterate through
1252 /// all possible permutations of a vector.
1254 /// The first iteration yields a clone of the vector as it is,
1255 /// then each successive element is the vector with one
1258 /// Generates even and odd permutations alternately.
1259 #[unstable(feature = "collections")]
1260 pub struct Permutations<T> {
1261 swaps: ElementSwaps,
1265 #[unstable(feature = "collections", reason = "trait is unstable")]
1266 impl<T: Clone> Iterator for Permutations<T> {
1270 fn next(&mut self) -> Option<Vec<T>> {
1271 match self.swaps.next() {
1273 Some((0,0)) => Some(self.v.clone()),
1275 let elt = self.v.clone();
1283 fn size_hint(&self) -> (usize, Option<usize>) {
1284 self.swaps.size_hint()
1288 ////////////////////////////////////////////////////////////////////////////////
1290 ////////////////////////////////////////////////////////////////////////////////
1292 fn insertion_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Ordering {
1293 let len = v.len() as isize;
1294 let buf_v = v.as_mut_ptr();
1298 // j satisfies: 0 <= j <= i;
1301 // `i` is in bounds.
1302 let read_ptr = buf_v.offset(i) as *const T;
1304 // find where to insert, we need to do strict <,
1305 // rather than <=, to maintain stability.
1307 // 0 <= j - 1 < len, so .offset(j - 1) is in bounds.
1309 compare(&*read_ptr, &*buf_v.offset(j - 1)) == Less {
1313 // shift everything to the right, to make space to
1314 // insert this value.
1316 // j + 1 could be `len` (for the last `i`), but in
1317 // that case, `i == j` so we don't copy. The
1318 // `.offset(j)` is always in bounds.
1321 let tmp = ptr::read(read_ptr);
1322 ptr::copy(buf_v.offset(j + 1),
1325 ptr::copy_nonoverlapping(buf_v.offset(j), &tmp, 1);
1332 fn merge_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Ordering {
1333 // warning: this wildly uses unsafe.
1334 const BASE_INSERTION: usize = 32;
1335 const LARGE_INSERTION: usize = 16;
1337 // FIXME #12092: smaller insertion runs seems to make sorting
1338 // vectors of large elements a little faster on some platforms,
1339 // but hasn't been tested/tuned extensively
1340 let insertion = if size_of::<T>() <= 16 {
1348 // short vectors get sorted in-place via insertion sort to avoid allocations
1349 if len <= insertion {
1350 insertion_sort(v, compare);
1354 // allocate some memory to use as scratch memory, we keep the
1355 // length 0 so we can keep shallow copies of the contents of `v`
1356 // without risking the dtors running on an object twice if
1357 // `compare` panics.
1358 let mut working_space = Vec::with_capacity(2 * len);
1359 // these both are buffers of length `len`.
1360 let mut buf_dat = working_space.as_mut_ptr();
1361 let mut buf_tmp = unsafe {buf_dat.offset(len as isize)};
1364 let buf_v = v.as_ptr();
1366 // step 1. sort short runs with insertion sort. This takes the
1367 // values from `v` and sorts them into `buf_dat`, leaving that
1368 // with sorted runs of length INSERTION.
1370 // We could hardcode the sorting comparisons here, and we could
1371 // manipulate/step the pointers themselves, rather than repeatedly
1373 for start in (0.. len).step_by(insertion) {
1374 // start <= i < len;
1375 for i in start..cmp::min(start + insertion, len) {
1376 // j satisfies: start <= j <= i;
1377 let mut j = i as isize;
1379 // `i` is in bounds.
1380 let read_ptr = buf_v.offset(i as isize);
1382 // find where to insert, we need to do strict <,
1383 // rather than <=, to maintain stability.
1385 // start <= j - 1 < len, so .offset(j - 1) is in
1387 while j > start as isize &&
1388 compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less {
1392 // shift everything to the right, to make space to
1393 // insert this value.
1395 // j + 1 could be `len` (for the last `i`), but in
1396 // that case, `i == j` so we don't copy. The
1397 // `.offset(j)` is always in bounds.
1398 ptr::copy(buf_dat.offset(j + 1),
1399 &*buf_dat.offset(j),
1401 ptr::copy_nonoverlapping(buf_dat.offset(j), read_ptr, 1);
1406 // step 2. merge the sorted runs.
1407 let mut width = insertion;
1409 // merge the sorted runs of length `width` in `buf_dat` two at
1410 // a time, placing the result in `buf_tmp`.
1412 // 0 <= start <= len.
1413 for start in (0..len).step_by(2 * width) {
1414 // manipulate pointers directly for speed (rather than
1415 // using a `for` loop with `range` and `.offset` inside
1418 // the end of the first run & start of the
1419 // second. Offset of `len` is defined, since this is
1420 // precisely one byte past the end of the object.
1421 let right_start = buf_dat.offset(cmp::min(start + width, len) as isize);
1422 // end of the second. Similar reasoning to the above re safety.
1423 let right_end_idx = cmp::min(start + 2 * width, len);
1424 let right_end = buf_dat.offset(right_end_idx as isize);
1426 // the pointers to the elements under consideration
1427 // from the two runs.
1429 // both of these are in bounds.
1430 let mut left = buf_dat.offset(start as isize);
1431 let mut right = right_start;
1433 // where we're putting the results, it is a run of
1434 // length `2*width`, so we step it once for each step
1435 // of either `left` or `right`. `buf_tmp` has length
1436 // `len`, so these are in bounds.
1437 let mut out = buf_tmp.offset(start as isize);
1438 let out_end = buf_tmp.offset(right_end_idx as isize);
1440 while out < out_end {
1441 // Either the left or the right run are exhausted,
1442 // so just copy the remainder from the other run
1443 // and move on; this gives a huge speed-up (order
1444 // of 25%) for mostly sorted vectors (the best
1446 if left == right_start {
1447 // the number remaining in this run.
1448 let elems = (right_end as usize - right as usize) / mem::size_of::<T>();
1449 ptr::copy_nonoverlapping(out, &*right, elems);
1451 } else if right == right_end {
1452 let elems = (right_start as usize - left as usize) / mem::size_of::<T>();
1453 ptr::copy_nonoverlapping(out, &*left, elems);
1457 // check which side is smaller, and that's the
1458 // next element for the new run.
1460 // `left < right_start` and `right < right_end`,
1461 // so these are valid.
1462 let to_copy = if compare(&*left, &*right) == Greater {
1467 ptr::copy_nonoverlapping(out, &*to_copy, 1);
1473 mem::swap(&mut buf_dat, &mut buf_tmp);
1478 // write the result to `v` in one go, so that there are never two copies
1479 // of the same object in `v`.
1481 ptr::copy_nonoverlapping(v.as_mut_ptr(), &*buf_dat, len);
1484 // increment the pointer, returning the old pointer.
1486 unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
1488 *ptr = ptr.offset(1);