]> git.lizzy.rs Git - rust.git/blob - src/libcollections/slice.rs
check: Reword the warning to be more prescriptive
[rust.git] / src / libcollections / slice.rs
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.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Utilities for slice manipulation
12 //!
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.
15 //!
16 //! ```
17 //! // slicing a Vec
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"];
22 //! ```
23 //!
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
27 //! points to:
28 //!
29 //! ```
30 //! let x = &mut [1, 2, 3];
31 //! x[1] = 7;
32 //! assert_eq!(x, &[1, 7, 3]);
33 //! ```
34 //!
35 //! Here are some of the things this module contains:
36 //!
37 //! ## Structs
38 //!
39 //! There are several structs that are useful for slices, such as `Iter`, which
40 //! represents iteration over a slice.
41 //!
42 //! ## Trait Implementations
43 //!
44 //! There are several implementations of common traits for slices. Some examples
45 //! include:
46 //!
47 //! * `Clone`
48 //! * `Eq`, `Ord` - for slices whose element type are `Eq` or `Ord`.
49 //! * `Hash` - for slices whose element type is `Hash`
50 //!
51 //! ## Iteration
52 //!
53 //! The slices implement `IntoIterator`. The iterators of yield references
54 //! to the slice elements.
55 //!
56 //! ```
57 //! let numbers = &[0, 1, 2];
58 //! for n in numbers {
59 //!     println!("{} is a number!", n);
60 //! }
61 //! ```
62 //!
63 //! The mutable slice yields mutable references to the elements:
64 //!
65 //! ```
66 //! let mut scores = [7, 8, 9];
67 //! for score in &mut scores[..] {
68 //!     *score += 1;
69 //! }
70 //! ```
71 //!
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`.
74 //!
75 //! * `.iter()` and `.iter_mut()` are the explicit methods to return the default
76 //!   iterators.
77 //! * Further methods that return iterators are `.split()`, `.splitn()`,
78 //!   `.chunks()`, `.windows()` and more.
79
80 #![doc(primitive = "slice")]
81 #![stable(feature = "rust1", since = "1.0.0")]
82
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;
92 use core::mem;
93 use core::num::wrapping::WrappingOps;
94 use core::ops::FnMut;
95 use core::option::Option::{self, Some, None};
96 use core::ptr;
97 use core::result::Result;
98 use core::slice as core_slice;
99 use self::Direction::*;
100
101 use borrow::{Borrow, BorrowMut, ToOwned};
102 use vec::Vec;
103
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};
111
112 ////////////////////////////////////////////////////////////////////////////////
113 // Basic slice extension methods
114 ////////////////////////////////////////////////////////////////////////////////
115
116 // HACK(japaric) needed for the implementation of `vec!` macro during testing
117 // NB see the hack module in this file for more details
118 #[cfg(test)]
119 pub use self::hack::into_vec;
120
121 // HACK(japaric) needed for the implementation of `Vec::clone` during testing
122 // NB see the hack module in this file for more details
123 #[cfg(test)]
124 pub use self::hack::to_vec;
125
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
130 mod hack {
131     use alloc::boxed::Box;
132     use core::clone::Clone;
133     #[cfg(test)]
134     use core::iter::{Iterator, IteratorExt};
135     use core::mem;
136     #[cfg(test)]
137     use core::option::Option::{Some, None};
138
139     #[cfg(test)]
140     use string::ToString;
141     use vec::Vec;
142
143     use super::{ElementSwaps, Permutations};
144
145     pub fn into_vec<T>(mut b: Box<[T]>) -> Vec<T> {
146         unsafe {
147             let xs = Vec::from_raw_parts(b.as_mut_ptr(), b.len(), b.len());
148             mem::forget(b);
149             xs
150         }
151     }
152
153     pub fn permutations<T>(s: &[T]) -> Permutations<T> where T: Clone {
154         Permutations{
155             swaps: ElementSwaps::new(s.len()),
156             v: to_vec(s),
157         }
158     }
159
160     #[inline]
161     pub fn to_vec<T>(s: &[T]) -> Vec<T> where T: Clone {
162         let mut vector = Vec::with_capacity(s.len());
163         vector.push_all(s);
164         vector
165     }
166
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
170     #[test]
171     fn test_permutations() {
172         {
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);
180         }
181         {
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);
189         }
190         {
191             let v = [1, 2, 3];
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);
206         }
207         {
208             // check that we have N! permutations
209             let v = ['A', 'B', 'C', 'D', 'E', 'F'];
210             let mut amt = 0;
211             let mut it = permutations(&v);
212             let (min_size, max_opt) = it.size_hint();
213             for _perm in it.by_ref() {
214                 amt += 1;
215             }
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());
220         }
221     }
222 }
223
224 /// Allocating extension methods for slices.
225 #[lang = "slice"]
226 #[cfg(not(test))]
227 #[stable(feature = "rust1", since = "1.0.0")]
228 impl<T> [T] {
229     /// Sorts the slice, in place, using `compare` to compare
230     /// elements.
231     ///
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`.
234     ///
235     /// # Examples
236     ///
237     /// ```rust
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]);
241     ///
242     /// // reverse sorting
243     /// v.sort_by(|a, b| b.cmp(a));
244     /// assert!(v == [5, 4, 3, 2, 1]);
245     /// ```
246     #[stable(feature = "rust1", since = "1.0.0")]
247     #[inline]
248     pub fn sort_by<F>(&mut self, compare: F) where F: FnMut(&T, &T) -> Ordering {
249         merge_sort(self, compare)
250     }
251
252     /// Consumes `src` and moves as many elements as it can into `self`
253     /// from the range [start,end).
254     ///
255     /// Returns the number of elements copied (the shorter of `self.len()`
256     /// and `end - start`).
257     ///
258     /// # Arguments
259     ///
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
263     ///
264     /// # Examples
265     ///
266     /// ```rust
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]);
273     /// ```
274     #[unstable(feature = "collections",
275                reason = "uncertain about this API approach")]
276     #[inline]
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()) {
279             mem::swap(a, b);
280         }
281         cmp::min(self.len(), end-start)
282     }
283
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")]
288     #[inline]
289     pub fn slice(&self, start: usize, end: usize) -> &[T] {
290         &self[start .. end]
291     }
292
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")]
297     #[inline]
298     pub fn slice_from(&self, start: usize) -> &[T] {
299         &self[start ..]
300     }
301
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")]
306     #[inline]
307     pub fn slice_to(&self, end: usize) -> &[T] {
308         &self[.. end]
309     }
310
311     /// Divides one slice into two at an index.
312     ///
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).
316     ///
317     /// Panics if `mid > len`.
318     ///
319     /// # Examples
320     ///
321     /// ```
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);
326     /// ```
327     #[stable(feature = "rust1", since = "1.0.0")]
328     #[inline]
329     pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
330         core_slice::SliceExt::split_at(self, mid)
331     }
332
333     /// Returns an iterator over the slice.
334     #[stable(feature = "rust1", since = "1.0.0")]
335     #[inline]
336     pub fn iter(&self) -> Iter<T> {
337         core_slice::SliceExt::iter(self)
338     }
339
340     /// Returns an iterator over subslices separated by elements that match
341     /// `pred`.  The matched element is not contained in the subslices.
342     ///
343     /// # Examples
344     ///
345     /// Print the slice split by numbers divisible by 3 (i.e. `[10, 40]`,
346     /// `[20]`, `[50]`):
347     ///
348     /// ```
349     /// let v = [10, 40, 30, 20, 60, 50];
350     /// for group in v.split(|num| *num % 3 == 0) {
351     ///     println!("{:?}", group);
352     /// }
353     /// ```
354     #[stable(feature = "rust1", since = "1.0.0")]
355     #[inline]
356     pub fn split<F>(&self, pred: F) -> Split<T, F> where F: FnMut(&T) -> bool {
357         core_slice::SliceExt::split(self, pred)
358     }
359
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.
363     ///
364     /// # Examples
365     ///
366     /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
367     /// `[20, 60, 50]`):
368     ///
369     /// ```
370     /// let v = [10, 40, 30, 20, 60, 50];
371     /// for group in v.splitn(1, |num| *num % 3 == 0) {
372     ///     println!("{:?}", group);
373     /// }
374     /// ```
375     #[stable(feature = "rust1", since = "1.0.0")]
376     #[inline]
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)
379     }
380
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
384     /// the subslices.
385     ///
386     /// # Examples
387     ///
388     /// Print the slice split once, starting from the end, by numbers divisible
389     /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
390     ///
391     /// ```
392     /// let v = [10, 40, 30, 20, 60, 50];
393     /// for group in v.rsplitn(1, |num| *num % 3 == 0) {
394     ///     println!("{:?}", group);
395     /// }
396     /// ```
397     #[stable(feature = "rust1", since = "1.0.0")]
398     #[inline]
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)
401     }
402
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.
406     ///
407     /// # Panics
408     ///
409     /// Panics if `size` is 0.
410     ///
411     /// # Example
412     ///
413     /// Print the adjacent pairs of a slice (i.e. `[1,2]`, `[2,3]`,
414     /// `[3,4]`):
415     ///
416     /// ```rust
417     /// let v = &[1, 2, 3, 4];
418     /// for win in v.windows(2) {
419     ///     println!("{:?}", win);
420     /// }
421     /// ```
422     #[stable(feature = "rust1", since = "1.0.0")]
423     #[inline]
424     pub fn windows(&self, size: usize) -> Windows<T> {
425         core_slice::SliceExt::windows(self, size)
426     }
427
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
431     /// `size`.
432     ///
433     /// # Panics
434     ///
435     /// Panics if `size` is 0.
436     ///
437     /// # Example
438     ///
439     /// Print the slice two elements at a time (i.e. `[1,2]`,
440     /// `[3,4]`, `[5]`):
441     ///
442     /// ```rust
443     /// let v = &[1, 2, 3, 4, 5];
444     /// for win in v.chunks(2) {
445     ///     println!("{:?}", win);
446     /// }
447     /// ```
448     #[stable(feature = "rust1", since = "1.0.0")]
449     #[inline]
450     pub fn chunks(&self, size: usize) -> Chunks<T> {
451         core_slice::SliceExt::chunks(self, size)
452     }
453
454     /// Returns the element of a slice at the given index, or `None` if the
455     /// index is out of bounds.
456     ///
457     /// # Examples
458     ///
459     /// ```
460     /// let v = [10, 40, 30];
461     /// assert_eq!(Some(&40), v.get(1));
462     /// assert_eq!(None, v.get(3));
463     /// ```
464     #[stable(feature = "rust1", since = "1.0.0")]
465     #[inline]
466     pub fn get(&self, index: usize) -> Option<&T> {
467         core_slice::SliceExt::get(self, index)
468     }
469
470     /// Returns the first element of a slice, or `None` if it is empty.
471     ///
472     /// # Examples
473     ///
474     /// ```
475     /// let v = [10, 40, 30];
476     /// assert_eq!(Some(&10), v.first());
477     ///
478     /// let w: &[i32] = &[];
479     /// assert_eq!(None, w.first());
480     /// ```
481     #[stable(feature = "rust1", since = "1.0.0")]
482     #[inline]
483     pub fn first(&self) -> Option<&T> {
484         core_slice::SliceExt::first(self)
485     }
486
487     /// Returns all but the first element of a slice.
488     #[unstable(feature = "collections", reason = "likely to be renamed")]
489     #[inline]
490     pub fn tail(&self) -> &[T] {
491         core_slice::SliceExt::tail(self)
492     }
493
494     /// Returns all but the last element of a slice.
495     #[unstable(feature = "collections", reason = "likely to be renamed")]
496     #[inline]
497     pub fn init(&self) -> &[T] {
498         core_slice::SliceExt::init(self)
499     }
500
501     /// Returns the last element of a slice, or `None` if it is empty.
502     ///
503     /// # Examples
504     ///
505     /// ```
506     /// let v = [10, 40, 30];
507     /// assert_eq!(Some(&30), v.last());
508     ///
509     /// let w: &[i32] = &[];
510     /// assert_eq!(None, w.last());
511     /// ```
512     #[stable(feature = "rust1", since = "1.0.0")]
513     #[inline]
514     pub fn last(&self) -> Option<&T> {
515         core_slice::SliceExt::last(self)
516     }
517
518     /// Returns a pointer to the element at the given index, without doing
519     /// bounds checking.
520     #[stable(feature = "rust1", since = "1.0.0")]
521     #[inline]
522     pub unsafe fn get_unchecked(&self, index: usize) -> &T {
523         core_slice::SliceExt::get_unchecked(self, index)
524     }
525
526     /// Returns an unsafe pointer to the slice's buffer
527     ///
528     /// The caller must ensure that the slice outlives the pointer this
529     /// function returns, or else it will end up pointing to garbage.
530     ///
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")]
534     #[inline]
535     pub fn as_ptr(&self) -> *const T {
536         core_slice::SliceExt::as_ptr(self)
537     }
538
539     /// Binary search a sorted slice with a comparator function.
540     ///
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.
545     ///
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.
550     ///
551     /// # Example
552     ///
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]`.
556     ///
557     /// ```rust
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();
561     ///
562     /// let seek = 13;
563     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
564     /// let seek = 4;
565     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
566     /// let seek = 100;
567     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
568     /// let seek = 1;
569     /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
570     /// assert!(match r { Ok(1...4) => true, _ => false, });
571     /// ```
572     #[stable(feature = "rust1", since = "1.0.0")]
573     #[inline]
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)
576     }
577
578     /// Return the number of elements in the slice
579     ///
580     /// # Example
581     ///
582     /// ```
583     /// let a = [1, 2, 3];
584     /// assert_eq!(a.len(), 3);
585     /// ```
586     #[stable(feature = "rust1", since = "1.0.0")]
587     #[inline]
588     pub fn len(&self) -> usize {
589         core_slice::SliceExt::len(self)
590     }
591
592     /// Returns true if the slice has a length of 0
593     ///
594     /// # Example
595     ///
596     /// ```
597     /// let a = [1, 2, 3];
598     /// assert!(!a.is_empty());
599     /// ```
600     #[stable(feature = "rust1", since = "1.0.0")]
601     #[inline]
602     pub fn is_empty(&self) -> bool {
603         core_slice::SliceExt::is_empty(self)
604     }
605
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")]
609     #[inline]
610     pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
611         core_slice::SliceExt::get_mut(self, index)
612     }
613
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)
619     }
620
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")]
625     #[inline]
626     pub fn slice_mut(&mut self, start: usize, end: usize) -> &mut [T] {
627         &mut self[start .. end]
628     }
629
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")]
634     #[inline]
635     pub fn slice_from_mut(&mut self, start: usize) -> &mut [T] {
636         &mut self[start ..]
637     }
638
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")]
643     #[inline]
644     pub fn slice_to_mut(&mut self, end: usize) -> &mut [T] {
645         &mut self[.. end]
646     }
647
648     /// Returns an iterator that allows modifying each value
649     #[stable(feature = "rust1", since = "1.0.0")]
650     #[inline]
651     pub fn iter_mut(&mut self) -> IterMut<T> {
652         core_slice::SliceExt::iter_mut(self)
653     }
654
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")]
657     #[inline]
658     pub fn first_mut(&mut self) -> Option<&mut T> {
659         core_slice::SliceExt::first_mut(self)
660     }
661
662     /// Returns all but the first element of a mutable slice
663     #[unstable(feature = "collections",
664                reason = "likely to be renamed or removed")]
665     #[inline]
666     pub fn tail_mut(&mut self) -> &mut [T] {
667         core_slice::SliceExt::tail_mut(self)
668     }
669
670     /// Returns all but the last element of a mutable slice
671     #[unstable(feature = "collections",
672                reason = "likely to be renamed or removed")]
673     #[inline]
674     pub fn init_mut(&mut self) -> &mut [T] {
675         core_slice::SliceExt::init_mut(self)
676     }
677
678     /// Returns a mutable pointer to the last item in the slice.
679     #[stable(feature = "rust1", since = "1.0.0")]
680     #[inline]
681     pub fn last_mut(&mut self) -> Option<&mut T> {
682         core_slice::SliceExt::last_mut(self)
683     }
684
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")]
688     #[inline]
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)
691     }
692
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")]
697     #[inline]
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)
701     }
702
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
706     /// the subslices.
707     #[stable(feature = "rust1", since = "1.0.0")]
708     #[inline]
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)
712     }
713
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`.
718     ///
719     /// # Panics
720     ///
721     /// Panics if `chunk_size` is 0.
722     #[stable(feature = "rust1", since = "1.0.0")]
723     #[inline]
724     pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
725         core_slice::SliceExt::chunks_mut(self, chunk_size)
726     }
727
728     /// Swaps two elements in a slice.
729     ///
730     /// # Arguments
731     ///
732     /// * a - The index of the first element
733     /// * b - The index of the second element
734     ///
735     /// # Panics
736     ///
737     /// Panics if `a` or `b` are out of bounds.
738     ///
739     /// # Example
740     ///
741     /// ```rust
742     /// let mut v = ["a", "b", "c", "d"];
743     /// v.swap(1, 3);
744     /// assert!(v == ["a", "d", "c", "b"]);
745     /// ```
746     #[stable(feature = "rust1", since = "1.0.0")]
747     #[inline]
748     pub fn swap(&mut self, a: usize, b: usize) {
749         core_slice::SliceExt::swap(self, a, b)
750     }
751
752     /// Divides one `&mut` into two at an index.
753     ///
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).
757     ///
758     /// # Panics
759     ///
760     /// Panics if `mid > len`.
761     ///
762     /// # Example
763     ///
764     /// ```rust
765     /// let mut v = [1, 2, 3, 4, 5, 6];
766     ///
767     /// // scoped to restrict the lifetime of the borrows
768     /// {
769     ///    let (left, right) = v.split_at_mut(0);
770     ///    assert!(left == []);
771     ///    assert!(right == [1, 2, 3, 4, 5, 6]);
772     /// }
773     ///
774     /// {
775     ///     let (left, right) = v.split_at_mut(2);
776     ///     assert!(left == [1, 2]);
777     ///     assert!(right == [3, 4, 5, 6]);
778     /// }
779     ///
780     /// {
781     ///     let (left, right) = v.split_at_mut(6);
782     ///     assert!(left == [1, 2, 3, 4, 5, 6]);
783     ///     assert!(right == []);
784     /// }
785     /// ```
786     #[stable(feature = "rust1", since = "1.0.0")]
787     #[inline]
788     pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
789         core_slice::SliceExt::split_at_mut(self, mid)
790     }
791
792     /// Reverse the order of elements in a slice, in place.
793     ///
794     /// # Example
795     ///
796     /// ```rust
797     /// let mut v = [1, 2, 3];
798     /// v.reverse();
799     /// assert!(v == [3, 2, 1]);
800     /// ```
801     #[stable(feature = "rust1", since = "1.0.0")]
802     #[inline]
803     pub fn reverse(&mut self) {
804         core_slice::SliceExt::reverse(self)
805     }
806
807     /// Returns an unsafe mutable pointer to the element in index
808     #[stable(feature = "rust1", since = "1.0.0")]
809     #[inline]
810     pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
811         core_slice::SliceExt::get_unchecked_mut(self, index)
812     }
813
814     /// Return an unsafe mutable pointer to the slice's buffer.
815     ///
816     /// The caller must ensure that the slice outlives the pointer this
817     /// function returns, or else it will end up pointing to garbage.
818     ///
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")]
822     #[inline]
823     pub fn as_mut_ptr(&mut self) -> *mut T {
824         core_slice::SliceExt::as_mut_ptr(self)
825     }
826
827     /// Copies `self` into a new `Vec`.
828     #[stable(feature = "rust1", since = "1.0.0")]
829     #[inline]
830     pub fn to_vec(&self) -> Vec<T> where T: Clone {
831         // NB see hack module in this file
832         hack::to_vec(self)
833     }
834
835     /// Creates an iterator that yields every possible permutation of the
836     /// vector in succession.
837     ///
838     /// # Examples
839     ///
840     /// ```rust
841     /// # #![feature(collections)]
842     /// let v = [1, 2, 3];
843     /// let mut perms = v.permutations();
844     ///
845     /// for p in perms {
846     ///   println!("{:?}", p);
847     /// }
848     /// ```
849     ///
850     /// Iterating through permutations one by one.
851     ///
852     /// ```rust
853     /// # #![feature(collections)]
854     /// let v = [1, 2, 3];
855     /// let mut perms = v.permutations();
856     ///
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());
860     /// ```
861     #[unstable(feature = "collections")]
862     #[inline]
863     pub fn permutations(&self) -> Permutations<T> where T: Clone {
864         // NB see hack module in this file
865         hack::permutations(self)
866     }
867
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.
871     ///
872     /// # Example
873     ///
874     /// ```rust
875     /// # #![feature(collections)]
876     /// let mut dst = [0, 0, 0];
877     /// let src = [1, 2];
878     ///
879     /// assert!(dst.clone_from_slice(&src) == 2);
880     /// assert!(dst == [1, 2, 0]);
881     ///
882     /// let src2 = [3, 4, 5, 6];
883     /// assert!(dst.clone_from_slice(&src2) == 3);
884     /// assert!(dst == [3, 4, 5]);
885     /// ```
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)
889     }
890
891     /// Sorts the slice, in place.
892     ///
893     /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
894     ///
895     /// # Examples
896     ///
897     /// ```rust
898     /// let mut v = [-5, 4, 1, -3, 2];
899     ///
900     /// v.sort();
901     /// assert!(v == [-5, -3, 1, 2, 4]);
902     /// ```
903     #[stable(feature = "rust1", since = "1.0.0")]
904     #[inline]
905     pub fn sort(&mut self) where T: Ord {
906         self.sort_by(|a, b| a.cmp(b))
907     }
908
909     /// Binary search a sorted slice for a given element.
910     ///
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.
915     ///
916     /// # Example
917     ///
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]`.
921     ///
922     /// ```rust
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();
926     ///
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, });
932     /// ```
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)
936     }
937
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)
943     }
944
945     /// Mutates the slice to the next lexicographic permutation.
946     ///
947     /// Returns `true` if successful and `false` if the slice is at the
948     /// last-ordered permutation.
949     ///
950     /// # Example
951     ///
952     /// ```rust
953     /// # #![feature(collections)]
954     /// let v: &mut [_] = &mut [0, 1, 2];
955     /// v.next_permutation();
956     /// let b: &mut [_] = &mut [0, 2, 1];
957     /// assert!(v == b);
958     /// v.next_permutation();
959     /// let b: &mut [_] = &mut [1, 0, 2];
960     /// assert!(v == b);
961     /// ```
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)
966     }
967
968     /// Mutates the slice to the previous lexicographic permutation.
969     ///
970     /// Returns `true` if successful and `false` if the slice is at the
971     /// first-ordered permutation.
972     ///
973     /// # Example
974     ///
975     /// ```rust
976     /// # #![feature(collections)]
977     /// let v: &mut [_] = &mut [1, 0, 2];
978     /// v.prev_permutation();
979     /// let b: &mut [_] = &mut [0, 2, 1];
980     /// assert!(v == b);
981     /// v.prev_permutation();
982     /// let b: &mut [_] = &mut [0, 1, 2];
983     /// assert!(v == b);
984     /// ```
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)
989     }
990
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)
995     }
996
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)
1001     }
1002
1003     /// Returns true if the slice contains an element with the given value.
1004     ///
1005     /// # Examples
1006     ///
1007     /// ```
1008     /// let v = [10, 40, 30];
1009     /// assert!(v.contains(&30));
1010     /// assert!(!v.contains(&50));
1011     /// ```
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)
1015     }
1016
1017     /// Returns true if `needle` is a prefix of the slice.
1018     ///
1019     /// # Examples
1020     ///
1021     /// ```
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]));
1027     /// ```
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)
1031     }
1032
1033     /// Returns true if `needle` is a suffix of the slice.
1034     ///
1035     /// # Examples
1036     ///
1037     /// ```
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]));
1043     /// ```
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)
1047     }
1048
1049     /// Convert `self` into a vector without clones or allocation.
1050     #[stable(feature = "rust1", since = "1.0.0")]
1051     #[inline]
1052     pub fn into_vec(self: Box<Self>) -> Vec<T> {
1053         // NB see hack module in this file
1054         hack::into_vec(self)
1055     }
1056 }
1057
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`.
1065     ///
1066     /// # Examples
1067     ///
1068     /// ```
1069     /// let v = vec!["hello", "world"];
1070     ///
1071     /// let s: String = v.concat();
1072     ///
1073     /// println!("{}", s); // prints "helloworld"
1074     /// ```
1075     #[stable(feature = "rust1", since = "1.0.0")]
1076     fn concat(&self) -> U;
1077
1078     /// Flattens a slice of `T` into a single value `U`, placing a given separator between each.
1079     ///
1080     /// # Examples
1081     ///
1082     /// ```
1083     /// let v = vec!["hello", "world"];
1084     ///
1085     /// let s: String = v.connect(" ");
1086     ///
1087     /// println!("{}", s); // prints "hello world"
1088     /// ```
1089     #[stable(feature = "rust1", since = "1.0.0")]
1090     fn connect(&self, sep: &T) -> U;
1091 }
1092
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);
1097         for v in self {
1098             result.push_all(v.as_ref())
1099         }
1100         result
1101     }
1102
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;
1107         for v in self {
1108             if first { first = false } else { result.push(sep.clone()) }
1109             result.push_all(v.as_ref())
1110         }
1111         result
1112     }
1113 }
1114
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.
1118 ///
1119 /// The Steinhaus-Johnson-Trotter algorithm is used.
1120 ///
1121 /// Generates even and odd permutations alternately.
1122 ///
1123 /// The last generated swap is always (0, 1), and it returns the
1124 /// sequence to its initial order.
1125 #[unstable(feature = "collections")]
1126 #[derive(Clone)]
1127 pub struct ElementSwaps {
1128     sdir: Vec<SizeDirection>,
1129     /// If `true`, emit the last swap that returns the sequence to initial
1130     /// state.
1131     emit_reset: bool,
1132     swaps_made : usize,
1133 }
1134
1135 impl ElementSwaps {
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).
1142         ElementSwaps{
1143             emit_reset: true,
1144             sdir: (0..length).map(|i| SizeDirection{ size: i, dir: Neg }).collect(),
1145             swaps_made: 0
1146         }
1147     }
1148 }
1149
1150 ////////////////////////////////////////////////////////////////////////////////
1151 // Standard trait implementations for slices
1152 ////////////////////////////////////////////////////////////////////////////////
1153
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 impl<T> Borrow<[T]> for Vec<T> {
1156     fn borrow(&self) -> &[T] { &self[..] }
1157 }
1158
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[..] }
1162 }
1163
1164 #[stable(feature = "rust1", since = "1.0.0")]
1165 impl<T: Clone> ToOwned for [T] {
1166     type Owned = Vec<T>;
1167     #[cfg(not(test))]
1168     fn to_owned(&self) -> Vec<T> { self.to_vec() }
1169
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
1172     // just stub it
1173     // NB see the slice::hack module in slice.rs for more information
1174     #[cfg(test)]
1175     fn to_owned(&self) -> Vec<T> { panic!("not available with cfg(test)") }
1176 }
1177
1178 ////////////////////////////////////////////////////////////////////////////////
1179 // Iterators
1180 ////////////////////////////////////////////////////////////////////////////////
1181
1182 #[derive(Copy, Clone)]
1183 enum Direction { Pos, Neg }
1184
1185 /// An `Index` and `Direction` together.
1186 #[derive(Copy, Clone)]
1187 struct SizeDirection {
1188     size: usize,
1189     dir: Direction,
1190 }
1191
1192 #[stable(feature = "rust1", since = "1.0.0")]
1193 impl Iterator for ElementSwaps {
1194     type Item = (usize, usize);
1195
1196     // #[inline]
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 })
1200         }
1201
1202         fn new_pos(i: usize, s: Direction) -> usize {
1203             match s { Pos => i + 1, Neg => i - 1 }
1204         }
1205
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()
1210                            .filter(|&(i, sd)|
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);
1214         match max {
1215             Some((i, sd)) => {
1216                 let j = new_pos(i, sd.dir);
1217                 self.sdir.swap(i, j);
1218
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 };
1223                     }
1224                 }
1225                 self.swaps_made += 1;
1226                 Some((i, j))
1227             },
1228             None => if self.emit_reset {
1229                 self.emit_reset = false;
1230                 if self.sdir.len() > 1 {
1231                     // The last swap
1232                     self.swaps_made += 1;
1233                     Some((0, 1))
1234                 } else {
1235                     // Vector is of the form [] or [x], and the only permutation is itself
1236                     self.swaps_made += 1;
1237                     Some((0,0))
1238                 }
1239             } else { None }
1240         }
1241     }
1242
1243     #[inline]
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))
1248     }
1249 }
1250
1251 /// An iterator that uses `ElementSwaps` to iterate through
1252 /// all possible permutations of a vector.
1253 ///
1254 /// The first iteration yields a clone of the vector as it is,
1255 /// then each successive element is the vector with one
1256 /// swap applied.
1257 ///
1258 /// Generates even and odd permutations alternately.
1259 #[unstable(feature = "collections")]
1260 pub struct Permutations<T> {
1261     swaps: ElementSwaps,
1262     v: Vec<T>,
1263 }
1264
1265 #[unstable(feature = "collections", reason = "trait is unstable")]
1266 impl<T: Clone> Iterator for Permutations<T> {
1267     type Item = Vec<T>;
1268
1269     #[inline]
1270     fn next(&mut self) -> Option<Vec<T>> {
1271         match self.swaps.next() {
1272             None => None,
1273             Some((0,0)) => Some(self.v.clone()),
1274             Some((a, b)) => {
1275                 let elt = self.v.clone();
1276                 self.v.swap(a, b);
1277                 Some(elt)
1278             }
1279         }
1280     }
1281
1282     #[inline]
1283     fn size_hint(&self) -> (usize, Option<usize>) {
1284         self.swaps.size_hint()
1285     }
1286 }
1287
1288 ////////////////////////////////////////////////////////////////////////////////
1289 // Sorting
1290 ////////////////////////////////////////////////////////////////////////////////
1291
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();
1295
1296     // 1 <= i < len;
1297     for i in 1..len {
1298         // j satisfies: 0 <= j <= i;
1299         let mut j = i;
1300         unsafe {
1301             // `i` is in bounds.
1302             let read_ptr = buf_v.offset(i) as *const T;
1303
1304             // find where to insert, we need to do strict <,
1305             // rather than <=, to maintain stability.
1306
1307             // 0 <= j - 1 < len, so .offset(j - 1) is in bounds.
1308             while j > 0 &&
1309                     compare(&*read_ptr, &*buf_v.offset(j - 1)) == Less {
1310                 j -= 1;
1311             }
1312
1313             // shift everything to the right, to make space to
1314             // insert this value.
1315
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.
1319
1320             if i != j {
1321                 let tmp = ptr::read(read_ptr);
1322                 ptr::copy(buf_v.offset(j + 1),
1323                           &*buf_v.offset(j),
1324                           (i - j) as usize);
1325                 ptr::copy_nonoverlapping(buf_v.offset(j), &tmp, 1);
1326                 mem::forget(tmp);
1327             }
1328         }
1329     }
1330 }
1331
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;
1336
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 {
1341         BASE_INSERTION
1342     } else {
1343         LARGE_INSERTION
1344     };
1345
1346     let len = v.len();
1347
1348     // short vectors get sorted in-place via insertion sort to avoid allocations
1349     if len <= insertion {
1350         insertion_sort(v, compare);
1351         return;
1352     }
1353
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)};
1362
1363     // length `len`.
1364     let buf_v = v.as_ptr();
1365
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.
1369
1370     // We could hardcode the sorting comparisons here, and we could
1371     // manipulate/step the pointers themselves, rather than repeatedly
1372     // .offset-ing.
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;
1378             unsafe {
1379                 // `i` is in bounds.
1380                 let read_ptr = buf_v.offset(i as isize);
1381
1382                 // find where to insert, we need to do strict <,
1383                 // rather than <=, to maintain stability.
1384
1385                 // start <= j - 1 < len, so .offset(j - 1) is in
1386                 // bounds.
1387                 while j > start as isize &&
1388                         compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less {
1389                     j -= 1;
1390                 }
1391
1392                 // shift everything to the right, to make space to
1393                 // insert this value.
1394
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),
1400                           i - j as usize);
1401                 ptr::copy_nonoverlapping(buf_dat.offset(j), read_ptr, 1);
1402             }
1403         }
1404     }
1405
1406     // step 2. merge the sorted runs.
1407     let mut width = insertion;
1408     while width < len {
1409         // merge the sorted runs of length `width` in `buf_dat` two at
1410         // a time, placing the result in `buf_tmp`.
1411
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
1416             // that loop).
1417             unsafe {
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);
1425
1426                 // the pointers to the elements under consideration
1427                 // from the two runs.
1428
1429                 // both of these are in bounds.
1430                 let mut left = buf_dat.offset(start as isize);
1431                 let mut right = right_start;
1432
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);
1439
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
1445                     // case).
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);
1450                         break;
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);
1454                         break;
1455                     }
1456
1457                     // check which side is smaller, and that's the
1458                     // next element for the new run.
1459
1460                     // `left < right_start` and `right < right_end`,
1461                     // so these are valid.
1462                     let to_copy = if compare(&*left, &*right) == Greater {
1463                         step(&mut right)
1464                     } else {
1465                         step(&mut left)
1466                     };
1467                     ptr::copy_nonoverlapping(out, &*to_copy, 1);
1468                     step(&mut out);
1469                 }
1470             }
1471         }
1472
1473         mem::swap(&mut buf_dat, &mut buf_tmp);
1474
1475         width *= 2;
1476     }
1477
1478     // write the result to `v` in one go, so that there are never two copies
1479     // of the same object in `v`.
1480     unsafe {
1481         ptr::copy_nonoverlapping(v.as_mut_ptr(), &*buf_dat, len);
1482     }
1483
1484     // increment the pointer, returning the old pointer.
1485     #[inline(always)]
1486     unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
1487         let old = *ptr;
1488         *ptr = ptr.offset(1);
1489         old
1490     }
1491 }