]> git.proxmox.com Git - rustc.git/blob - src/libcollections/slice.rs
d5a069b194a5de3535c7fdc4664faf70ea095733
[rustc.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 iterator yields references to the
54 //! 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 #![doc(primitive = "slice")]
80 #![stable(feature = "rust1", since = "1.0.0")]
81
82 use alloc::boxed::Box;
83 use core::clone::Clone;
84 use core::cmp::Ordering::{self, Greater, Less};
85 use core::cmp::{self, Ord, PartialEq};
86 use core::iter::Iterator;
87 use core::marker::Sized;
88 use core::mem::size_of;
89 use core::mem;
90 use core::ops::FnMut;
91 use core::option::Option::{self, Some, None};
92 use core::ptr;
93 use core::result::Result;
94 use core::slice as core_slice;
95 use self::Direction::*;
96
97 use borrow::{Borrow, BorrowMut, ToOwned};
98 use vec::Vec;
99
100 pub use core::slice::{Chunks, Windows};
101 pub use core::slice::{Iter, IterMut};
102 pub use core::slice::{IntSliceExt, SplitMut, ChunksMut, Split};
103 pub use core::slice::{SplitN, RSplitN, SplitNMut, RSplitNMut};
104 pub use core::slice::{bytes, mut_ref_slice, ref_slice};
105 pub use core::slice::{from_raw_parts, from_raw_parts_mut};
106
107 ////////////////////////////////////////////////////////////////////////////////
108 // Basic slice extension methods
109 ////////////////////////////////////////////////////////////////////////////////
110
111 // HACK(japaric) needed for the implementation of `vec!` macro during testing
112 // NB see the hack module in this file for more details
113 #[cfg(test)]
114 pub use self::hack::into_vec;
115
116 // HACK(japaric) needed for the implementation of `Vec::clone` during testing
117 // NB see the hack module in this file for more details
118 #[cfg(test)]
119 pub use self::hack::to_vec;
120
121 // HACK(japaric): With cfg(test) `impl [T]` is not available, these three
122 // functions are actually methods that are in `impl [T]` but not in
123 // `core::slice::SliceExt` - we need to supply these functions for the
124 // `test_permutations` test
125 mod hack {
126 use alloc::boxed::Box;
127 use core::clone::Clone;
128 #[cfg(test)]
129 use core::iter::Iterator;
130 use core::mem;
131 #[cfg(test)]
132 use core::option::Option::{Some, None};
133
134 #[cfg(test)]
135 use string::ToString;
136 use vec::Vec;
137
138 use super::{ElementSwaps, Permutations};
139
140 pub fn into_vec<T>(mut b: Box<[T]>) -> Vec<T> {
141 unsafe {
142 let xs = Vec::from_raw_parts(b.as_mut_ptr(), b.len(), b.len());
143 mem::forget(b);
144 xs
145 }
146 }
147
148 pub fn permutations<T>(s: &[T]) -> Permutations<T> where T: Clone {
149 Permutations{
150 swaps: ElementSwaps::new(s.len()),
151 v: to_vec(s),
152 }
153 }
154
155 #[inline]
156 pub fn to_vec<T>(s: &[T]) -> Vec<T> where T: Clone {
157 let mut vector = Vec::with_capacity(s.len());
158 vector.push_all(s);
159 vector
160 }
161
162 // NB we can remove this hack if we move this test to libcollectionstest -
163 // but that can't be done right now because the test needs access to the
164 // private fields of Permutations
165 #[test]
166 fn test_permutations() {
167 {
168 let v: [i32; 0] = [];
169 let mut it = permutations(&v);
170 let (min_size, max_opt) = it.size_hint();
171 assert_eq!(min_size, 1);
172 assert_eq!(max_opt.unwrap(), 1);
173 assert_eq!(it.next(), Some(to_vec(&v)));
174 assert_eq!(it.next(), None);
175 }
176 {
177 let v = ["Hello".to_string()];
178 let mut it = permutations(&v);
179 let (min_size, max_opt) = it.size_hint();
180 assert_eq!(min_size, 1);
181 assert_eq!(max_opt.unwrap(), 1);
182 assert_eq!(it.next(), Some(to_vec(&v)));
183 assert_eq!(it.next(), None);
184 }
185 {
186 let v = [1, 2, 3];
187 let mut it = permutations(&v);
188 let (min_size, max_opt) = it.size_hint();
189 assert_eq!(min_size, 3*2);
190 assert_eq!(max_opt.unwrap(), 3*2);
191 assert_eq!(it.next().unwrap(), [1,2,3]);
192 assert_eq!(it.next().unwrap(), [1,3,2]);
193 assert_eq!(it.next().unwrap(), [3,1,2]);
194 let (min_size, max_opt) = it.size_hint();
195 assert_eq!(min_size, 3);
196 assert_eq!(max_opt.unwrap(), 3);
197 assert_eq!(it.next().unwrap(), [3,2,1]);
198 assert_eq!(it.next().unwrap(), [2,3,1]);
199 assert_eq!(it.next().unwrap(), [2,1,3]);
200 assert_eq!(it.next(), None);
201 }
202 {
203 // check that we have N! permutations
204 let v = ['A', 'B', 'C', 'D', 'E', 'F'];
205 let mut amt = 0;
206 let mut it = permutations(&v);
207 let (min_size, max_opt) = it.size_hint();
208 for _perm in it.by_ref() {
209 amt += 1;
210 }
211 assert_eq!(amt, it.swaps.swaps_made);
212 assert_eq!(amt, min_size);
213 assert_eq!(amt, 2 * 3 * 4 * 5 * 6);
214 assert_eq!(amt, max_opt.unwrap());
215 }
216 }
217 }
218
219 /// Allocating extension methods for slices.
220 #[lang = "slice"]
221 #[cfg(not(test))]
222 #[stable(feature = "rust1", since = "1.0.0")]
223 impl<T> [T] {
224 /// Sorts the slice, in place, using `compare` to compare
225 /// elements.
226 ///
227 /// This sort is `O(n log n)` worst-case and stable, but allocates
228 /// approximately `2 * n`, where `n` is the length of `self`.
229 ///
230 /// # Examples
231 ///
232 /// ```rust
233 /// let mut v = [5, 4, 1, 3, 2];
234 /// v.sort_by(|a, b| a.cmp(b));
235 /// assert!(v == [1, 2, 3, 4, 5]);
236 ///
237 /// // reverse sorting
238 /// v.sort_by(|a, b| b.cmp(a));
239 /// assert!(v == [5, 4, 3, 2, 1]);
240 /// ```
241 #[stable(feature = "rust1", since = "1.0.0")]
242 #[inline]
243 pub fn sort_by<F>(&mut self, compare: F) where F: FnMut(&T, &T) -> Ordering {
244 merge_sort(self, compare)
245 }
246
247 /// Consumes `src` and moves as many elements as it can into `self`
248 /// from the range [start,end).
249 ///
250 /// Returns the number of elements copied (the shorter of `self.len()`
251 /// and `end - start`).
252 ///
253 /// # Arguments
254 ///
255 /// * src - A mutable vector of `T`
256 /// * start - The index into `src` to start copying from
257 /// * end - The index into `src` to stop copying from
258 ///
259 /// # Examples
260 ///
261 /// ```rust
262 /// # #![feature(collections)]
263 /// let mut a = [1, 2, 3, 4, 5];
264 /// let b = vec![6, 7, 8];
265 /// let num_moved = a.move_from(b, 0, 3);
266 /// assert_eq!(num_moved, 3);
267 /// assert!(a == [6, 7, 8, 4, 5]);
268 /// ```
269 #[unstable(feature = "collections",
270 reason = "uncertain about this API approach")]
271 #[inline]
272 pub fn move_from(&mut self, mut src: Vec<T>, start: usize, end: usize) -> usize {
273 for (a, b) in self.iter_mut().zip(src[start .. end].iter_mut()) {
274 mem::swap(a, b);
275 }
276 cmp::min(self.len(), end-start)
277 }
278
279 /// Divides one slice into two at an index.
280 ///
281 /// The first will contain all indices from `[0, mid)` (excluding
282 /// the index `mid` itself) and the second will contain all
283 /// indices from `[mid, len)` (excluding the index `len` itself).
284 ///
285 /// Panics if `mid > len`.
286 ///
287 /// # Examples
288 ///
289 /// ```
290 /// let v = [10, 40, 30, 20, 50];
291 /// let (v1, v2) = v.split_at(2);
292 /// assert_eq!([10, 40], v1);
293 /// assert_eq!([30, 20, 50], v2);
294 /// ```
295 #[stable(feature = "rust1", since = "1.0.0")]
296 #[inline]
297 pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
298 core_slice::SliceExt::split_at(self, mid)
299 }
300
301 /// Returns an iterator over the slice.
302 #[stable(feature = "rust1", since = "1.0.0")]
303 #[inline]
304 pub fn iter(&self) -> Iter<T> {
305 core_slice::SliceExt::iter(self)
306 }
307
308 /// Returns an iterator over subslices separated by elements that match
309 /// `pred`. The matched element is not contained in the subslices.
310 ///
311 /// # Examples
312 ///
313 /// Print the slice split by numbers divisible by 3 (i.e. `[10, 40]`,
314 /// `[20]`, `[50]`):
315 ///
316 /// ```
317 /// let v = [10, 40, 30, 20, 60, 50];
318 /// for group in v.split(|num| *num % 3 == 0) {
319 /// println!("{:?}", group);
320 /// }
321 /// ```
322 #[stable(feature = "rust1", since = "1.0.0")]
323 #[inline]
324 pub fn split<F>(&self, pred: F) -> Split<T, F> where F: FnMut(&T) -> bool {
325 core_slice::SliceExt::split(self, pred)
326 }
327
328 /// Returns an iterator over subslices separated by elements that match
329 /// `pred`, limited to returning at most `n` items. The matched element is
330 /// not contained in the subslices.
331 ///
332 /// The last element returned, if any, will contain the remainder of the
333 /// slice.
334 ///
335 /// # Examples
336 ///
337 /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
338 /// `[20, 60, 50]`):
339 ///
340 /// ```
341 /// let v = [10, 40, 30, 20, 60, 50];
342 /// for group in v.splitn(2, |num| *num % 3 == 0) {
343 /// println!("{:?}", group);
344 /// }
345 /// ```
346 #[stable(feature = "rust1", since = "1.0.0")]
347 #[inline]
348 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F> where F: FnMut(&T) -> bool {
349 core_slice::SliceExt::splitn(self, n, pred)
350 }
351
352 /// Returns an iterator over subslices separated by elements that match
353 /// `pred` limited to returning at most `n` items. This starts at the end of
354 /// the slice and works backwards. The matched element is not contained in
355 /// the subslices.
356 ///
357 /// The last element returned, if any, will contain the remainder of the
358 /// slice.
359 ///
360 /// # Examples
361 ///
362 /// Print the slice split once, starting from the end, by numbers divisible
363 /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
364 ///
365 /// ```
366 /// let v = [10, 40, 30, 20, 60, 50];
367 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
368 /// println!("{:?}", group);
369 /// }
370 /// ```
371 #[stable(feature = "rust1", since = "1.0.0")]
372 #[inline]
373 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F> where F: FnMut(&T) -> bool {
374 core_slice::SliceExt::rsplitn(self, n, pred)
375 }
376
377 /// Returns an iterator over all contiguous windows of length
378 /// `size`. The windows overlap. If the slice is shorter than
379 /// `size`, the iterator returns no values.
380 ///
381 /// # Panics
382 ///
383 /// Panics if `size` is 0.
384 ///
385 /// # Example
386 ///
387 /// Print the adjacent pairs of a slice (i.e. `[1,2]`, `[2,3]`,
388 /// `[3,4]`):
389 ///
390 /// ```rust
391 /// let v = &[1, 2, 3, 4];
392 /// for win in v.windows(2) {
393 /// println!("{:?}", win);
394 /// }
395 /// ```
396 #[stable(feature = "rust1", since = "1.0.0")]
397 #[inline]
398 pub fn windows(&self, size: usize) -> Windows<T> {
399 core_slice::SliceExt::windows(self, size)
400 }
401
402 /// Returns an iterator over `size` elements of the slice at a
403 /// time. The chunks do not overlap. If `size` does not divide the
404 /// length of the slice, then the last chunk will not have length
405 /// `size`.
406 ///
407 /// # Panics
408 ///
409 /// Panics if `size` is 0.
410 ///
411 /// # Example
412 ///
413 /// Print the slice two elements at a time (i.e. `[1,2]`,
414 /// `[3,4]`, `[5]`):
415 ///
416 /// ```rust
417 /// let v = &[1, 2, 3, 4, 5];
418 /// for win in v.chunks(2) {
419 /// println!("{:?}", win);
420 /// }
421 /// ```
422 #[stable(feature = "rust1", since = "1.0.0")]
423 #[inline]
424 pub fn chunks(&self, size: usize) -> Chunks<T> {
425 core_slice::SliceExt::chunks(self, size)
426 }
427
428 /// Returns the element of a slice at the given index, or `None` if the
429 /// index is out of bounds.
430 ///
431 /// # Examples
432 ///
433 /// ```
434 /// let v = [10, 40, 30];
435 /// assert_eq!(Some(&40), v.get(1));
436 /// assert_eq!(None, v.get(3));
437 /// ```
438 #[stable(feature = "rust1", since = "1.0.0")]
439 #[inline]
440 pub fn get(&self, index: usize) -> Option<&T> {
441 core_slice::SliceExt::get(self, index)
442 }
443
444 /// Returns the first element of a slice, or `None` if it is empty.
445 ///
446 /// # Examples
447 ///
448 /// ```
449 /// let v = [10, 40, 30];
450 /// assert_eq!(Some(&10), v.first());
451 ///
452 /// let w: &[i32] = &[];
453 /// assert_eq!(None, w.first());
454 /// ```
455 #[stable(feature = "rust1", since = "1.0.0")]
456 #[inline]
457 pub fn first(&self) -> Option<&T> {
458 core_slice::SliceExt::first(self)
459 }
460
461 /// Returns all but the first element of a slice.
462 #[unstable(feature = "collections", reason = "likely to be renamed")]
463 #[inline]
464 pub fn tail(&self) -> &[T] {
465 core_slice::SliceExt::tail(self)
466 }
467
468 /// Returns all but the last element of a slice.
469 #[unstable(feature = "collections", reason = "likely to be renamed")]
470 #[inline]
471 pub fn init(&self) -> &[T] {
472 core_slice::SliceExt::init(self)
473 }
474
475 /// Returns the last element of a slice, or `None` if it is empty.
476 ///
477 /// # Examples
478 ///
479 /// ```
480 /// let v = [10, 40, 30];
481 /// assert_eq!(Some(&30), v.last());
482 ///
483 /// let w: &[i32] = &[];
484 /// assert_eq!(None, w.last());
485 /// ```
486 #[stable(feature = "rust1", since = "1.0.0")]
487 #[inline]
488 pub fn last(&self) -> Option<&T> {
489 core_slice::SliceExt::last(self)
490 }
491
492 /// Returns a pointer to the element at the given index, without doing
493 /// bounds checking.
494 #[stable(feature = "rust1", since = "1.0.0")]
495 #[inline]
496 pub unsafe fn get_unchecked(&self, index: usize) -> &T {
497 core_slice::SliceExt::get_unchecked(self, index)
498 }
499
500 /// Returns an unsafe pointer to the slice's buffer
501 ///
502 /// The caller must ensure that the slice outlives the pointer this
503 /// function returns, or else it will end up pointing to garbage.
504 ///
505 /// Modifying the slice may cause its buffer to be reallocated, which
506 /// would also make any pointers to it invalid.
507 #[stable(feature = "rust1", since = "1.0.0")]
508 #[inline]
509 pub fn as_ptr(&self) -> *const T {
510 core_slice::SliceExt::as_ptr(self)
511 }
512
513 /// Binary search a sorted slice with a comparator function.
514 ///
515 /// The comparator function should implement an order consistent
516 /// with the sort order of the underlying slice, returning an
517 /// order code that indicates whether its argument is `Less`,
518 /// `Equal` or `Greater` the desired target.
519 ///
520 /// If a matching value is found then returns `Ok`, containing
521 /// the index for the matched element; if no match is found then
522 /// `Err` is returned, containing the index where a matching
523 /// element could be inserted while maintaining sorted order.
524 ///
525 /// # Example
526 ///
527 /// Looks up a series of four elements. The first is found, with a
528 /// uniquely determined position; the second and third are not
529 /// found; the fourth could match any position in `[1,4]`.
530 ///
531 /// ```rust
532 /// # #![feature(core)]
533 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
534 ///
535 /// let seek = 13;
536 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
537 /// let seek = 4;
538 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
539 /// let seek = 100;
540 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
541 /// let seek = 1;
542 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
543 /// assert!(match r { Ok(1...4) => true, _ => false, });
544 /// ```
545 #[stable(feature = "rust1", since = "1.0.0")]
546 #[inline]
547 pub fn binary_search_by<F>(&self, f: F) -> Result<usize, usize> where F: FnMut(&T) -> Ordering {
548 core_slice::SliceExt::binary_search_by(self, f)
549 }
550
551 /// Returns the number of elements in the slice.
552 ///
553 /// # Example
554 ///
555 /// ```
556 /// let a = [1, 2, 3];
557 /// assert_eq!(a.len(), 3);
558 /// ```
559 #[stable(feature = "rust1", since = "1.0.0")]
560 #[inline]
561 pub fn len(&self) -> usize {
562 core_slice::SliceExt::len(self)
563 }
564
565 /// Returns true if the slice has a length of 0
566 ///
567 /// # Example
568 ///
569 /// ```
570 /// let a = [1, 2, 3];
571 /// assert!(!a.is_empty());
572 /// ```
573 #[stable(feature = "rust1", since = "1.0.0")]
574 #[inline]
575 pub fn is_empty(&self) -> bool {
576 core_slice::SliceExt::is_empty(self)
577 }
578
579 /// Returns a mutable reference to the element at the given index,
580 /// or `None` if the index is out of bounds
581 #[stable(feature = "rust1", since = "1.0.0")]
582 #[inline]
583 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
584 core_slice::SliceExt::get_mut(self, index)
585 }
586
587 /// Returns an iterator that allows modifying each value
588 #[stable(feature = "rust1", since = "1.0.0")]
589 #[inline]
590 pub fn iter_mut(&mut self) -> IterMut<T> {
591 core_slice::SliceExt::iter_mut(self)
592 }
593
594 /// Returns a mutable pointer to the first element of a slice, or `None` if it is empty
595 #[stable(feature = "rust1", since = "1.0.0")]
596 #[inline]
597 pub fn first_mut(&mut self) -> Option<&mut T> {
598 core_slice::SliceExt::first_mut(self)
599 }
600
601 /// Returns all but the first element of a mutable slice
602 #[unstable(feature = "collections",
603 reason = "likely to be renamed or removed")]
604 #[inline]
605 pub fn tail_mut(&mut self) -> &mut [T] {
606 core_slice::SliceExt::tail_mut(self)
607 }
608
609 /// Returns all but the last element of a mutable slice
610 #[unstable(feature = "collections",
611 reason = "likely to be renamed or removed")]
612 #[inline]
613 pub fn init_mut(&mut self) -> &mut [T] {
614 core_slice::SliceExt::init_mut(self)
615 }
616
617 /// Returns a mutable pointer to the last item in the slice.
618 #[stable(feature = "rust1", since = "1.0.0")]
619 #[inline]
620 pub fn last_mut(&mut self) -> Option<&mut T> {
621 core_slice::SliceExt::last_mut(self)
622 }
623
624 /// Returns an iterator over mutable subslices separated by elements that
625 /// match `pred`. The matched element is not contained in the subslices.
626 #[stable(feature = "rust1", since = "1.0.0")]
627 #[inline]
628 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F> where F: FnMut(&T) -> bool {
629 core_slice::SliceExt::split_mut(self, pred)
630 }
631
632 /// Returns an iterator over subslices separated by elements that match
633 /// `pred`, limited to returning at most `n` items. The matched element is
634 /// not contained in the subslices.
635 ///
636 /// The last element returned, if any, will contain the remainder of the
637 /// slice.
638 #[stable(feature = "rust1", since = "1.0.0")]
639 #[inline]
640 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, F>
641 where F: FnMut(&T) -> bool {
642 core_slice::SliceExt::splitn_mut(self, n, pred)
643 }
644
645 /// Returns an iterator over subslices separated by elements that match
646 /// `pred` limited to returning at most `n` items. This starts at the end of
647 /// the slice and works backwards. The matched element is not contained in
648 /// the subslices.
649 ///
650 /// The last element returned, if any, will contain the remainder of the
651 /// slice.
652 #[stable(feature = "rust1", since = "1.0.0")]
653 #[inline]
654 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, F>
655 where F: FnMut(&T) -> bool {
656 core_slice::SliceExt::rsplitn_mut(self, n, pred)
657 }
658
659 /// Returns an iterator over `chunk_size` elements of the slice at a time.
660 /// The chunks are mutable and do not overlap. If `chunk_size` does
661 /// not divide the length of the slice, then the last chunk will not
662 /// have length `chunk_size`.
663 ///
664 /// # Panics
665 ///
666 /// Panics if `chunk_size` is 0.
667 #[stable(feature = "rust1", since = "1.0.0")]
668 #[inline]
669 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
670 core_slice::SliceExt::chunks_mut(self, chunk_size)
671 }
672
673 /// Swaps two elements in a slice.
674 ///
675 /// # Arguments
676 ///
677 /// * a - The index of the first element
678 /// * b - The index of the second element
679 ///
680 /// # Panics
681 ///
682 /// Panics if `a` or `b` are out of bounds.
683 ///
684 /// # Example
685 ///
686 /// ```rust
687 /// let mut v = ["a", "b", "c", "d"];
688 /// v.swap(1, 3);
689 /// assert!(v == ["a", "d", "c", "b"]);
690 /// ```
691 #[stable(feature = "rust1", since = "1.0.0")]
692 #[inline]
693 pub fn swap(&mut self, a: usize, b: usize) {
694 core_slice::SliceExt::swap(self, a, b)
695 }
696
697 /// Divides one `&mut` into two at an index.
698 ///
699 /// The first will contain all indices from `[0, mid)` (excluding
700 /// the index `mid` itself) and the second will contain all
701 /// indices from `[mid, len)` (excluding the index `len` itself).
702 ///
703 /// # Panics
704 ///
705 /// Panics if `mid > len`.
706 ///
707 /// # Example
708 ///
709 /// ```rust
710 /// let mut v = [1, 2, 3, 4, 5, 6];
711 ///
712 /// // scoped to restrict the lifetime of the borrows
713 /// {
714 /// let (left, right) = v.split_at_mut(0);
715 /// assert!(left == []);
716 /// assert!(right == [1, 2, 3, 4, 5, 6]);
717 /// }
718 ///
719 /// {
720 /// let (left, right) = v.split_at_mut(2);
721 /// assert!(left == [1, 2]);
722 /// assert!(right == [3, 4, 5, 6]);
723 /// }
724 ///
725 /// {
726 /// let (left, right) = v.split_at_mut(6);
727 /// assert!(left == [1, 2, 3, 4, 5, 6]);
728 /// assert!(right == []);
729 /// }
730 /// ```
731 #[stable(feature = "rust1", since = "1.0.0")]
732 #[inline]
733 pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
734 core_slice::SliceExt::split_at_mut(self, mid)
735 }
736
737 /// Reverse the order of elements in a slice, in place.
738 ///
739 /// # Example
740 ///
741 /// ```rust
742 /// let mut v = [1, 2, 3];
743 /// v.reverse();
744 /// assert!(v == [3, 2, 1]);
745 /// ```
746 #[stable(feature = "rust1", since = "1.0.0")]
747 #[inline]
748 pub fn reverse(&mut self) {
749 core_slice::SliceExt::reverse(self)
750 }
751
752 /// Returns an unsafe mutable pointer to the element in index
753 #[stable(feature = "rust1", since = "1.0.0")]
754 #[inline]
755 pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
756 core_slice::SliceExt::get_unchecked_mut(self, index)
757 }
758
759 /// Returns an unsafe mutable pointer to the slice's buffer.
760 ///
761 /// The caller must ensure that the slice outlives the pointer this
762 /// function returns, or else it will end up pointing to garbage.
763 ///
764 /// Modifying the slice may cause its buffer to be reallocated, which
765 /// would also make any pointers to it invalid.
766 #[stable(feature = "rust1", since = "1.0.0")]
767 #[inline]
768 pub fn as_mut_ptr(&mut self) -> *mut T {
769 core_slice::SliceExt::as_mut_ptr(self)
770 }
771
772 /// Copies `self` into a new `Vec`.
773 #[stable(feature = "rust1", since = "1.0.0")]
774 #[inline]
775 pub fn to_vec(&self) -> Vec<T> where T: Clone {
776 // NB see hack module in this file
777 hack::to_vec(self)
778 }
779
780 /// Creates an iterator that yields every possible permutation of the
781 /// vector in succession.
782 ///
783 /// # Examples
784 ///
785 /// ```rust
786 /// # #![feature(collections)]
787 /// let v = [1, 2, 3];
788 /// let mut perms = v.permutations();
789 ///
790 /// for p in perms {
791 /// println!("{:?}", p);
792 /// }
793 /// ```
794 ///
795 /// Iterating through permutations one by one.
796 ///
797 /// ```rust
798 /// # #![feature(collections)]
799 /// let v = [1, 2, 3];
800 /// let mut perms = v.permutations();
801 ///
802 /// assert_eq!(Some(vec![1, 2, 3]), perms.next());
803 /// assert_eq!(Some(vec![1, 3, 2]), perms.next());
804 /// assert_eq!(Some(vec![3, 1, 2]), perms.next());
805 /// ```
806 #[unstable(feature = "collections")]
807 #[inline]
808 pub fn permutations(&self) -> Permutations<T> where T: Clone {
809 // NB see hack module in this file
810 hack::permutations(self)
811 }
812
813 /// Copies as many elements from `src` as it can into `self` (the
814 /// shorter of `self.len()` and `src.len()`). Returns the number
815 /// of elements copied.
816 ///
817 /// # Example
818 ///
819 /// ```rust
820 /// # #![feature(collections)]
821 /// let mut dst = [0, 0, 0];
822 /// let src = [1, 2];
823 ///
824 /// assert!(dst.clone_from_slice(&src) == 2);
825 /// assert!(dst == [1, 2, 0]);
826 ///
827 /// let src2 = [3, 4, 5, 6];
828 /// assert!(dst.clone_from_slice(&src2) == 3);
829 /// assert!(dst == [3, 4, 5]);
830 /// ```
831 #[unstable(feature = "collections")]
832 pub fn clone_from_slice(&mut self, src: &[T]) -> usize where T: Clone {
833 core_slice::SliceExt::clone_from_slice(self, src)
834 }
835
836 /// Sorts the slice, in place.
837 ///
838 /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
839 ///
840 /// # Examples
841 ///
842 /// ```rust
843 /// let mut v = [-5, 4, 1, -3, 2];
844 ///
845 /// v.sort();
846 /// assert!(v == [-5, -3, 1, 2, 4]);
847 /// ```
848 #[stable(feature = "rust1", since = "1.0.0")]
849 #[inline]
850 pub fn sort(&mut self) where T: Ord {
851 self.sort_by(|a, b| a.cmp(b))
852 }
853
854 /// Binary search a sorted slice for a given element.
855 ///
856 /// If the value is found then `Ok` is returned, containing the
857 /// index of the matching element; if the value is not found then
858 /// `Err` is returned, containing the index where a matching
859 /// element could be inserted while maintaining sorted order.
860 ///
861 /// # Example
862 ///
863 /// Looks up a series of four elements. The first is found, with a
864 /// uniquely determined position; the second and third are not
865 /// found; the fourth could match any position in `[1,4]`.
866 ///
867 /// ```rust
868 /// # #![feature(core)]
869 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
870 ///
871 /// assert_eq!(s.binary_search(&13), Ok(9));
872 /// assert_eq!(s.binary_search(&4), Err(7));
873 /// assert_eq!(s.binary_search(&100), Err(13));
874 /// let r = s.binary_search(&1);
875 /// assert!(match r { Ok(1...4) => true, _ => false, });
876 /// ```
877 #[stable(feature = "rust1", since = "1.0.0")]
878 pub fn binary_search(&self, x: &T) -> Result<usize, usize> where T: Ord {
879 core_slice::SliceExt::binary_search(self, x)
880 }
881
882 /// Mutates the slice to the next lexicographic permutation.
883 ///
884 /// Returns `true` if successful and `false` if the slice is at the
885 /// last-ordered permutation.
886 ///
887 /// # Example
888 ///
889 /// ```rust
890 /// # #![feature(collections)]
891 /// let v: &mut [_] = &mut [0, 1, 2];
892 /// v.next_permutation();
893 /// let b: &mut [_] = &mut [0, 2, 1];
894 /// assert!(v == b);
895 /// v.next_permutation();
896 /// let b: &mut [_] = &mut [1, 0, 2];
897 /// assert!(v == b);
898 /// ```
899 #[unstable(feature = "collections",
900 reason = "uncertain if this merits inclusion in std")]
901 pub fn next_permutation(&mut self) -> bool where T: Ord {
902 core_slice::SliceExt::next_permutation(self)
903 }
904
905 /// Mutates the slice to the previous lexicographic permutation.
906 ///
907 /// Returns `true` if successful and `false` if the slice is at the
908 /// first-ordered permutation.
909 ///
910 /// # Example
911 ///
912 /// ```rust
913 /// # #![feature(collections)]
914 /// let v: &mut [_] = &mut [1, 0, 2];
915 /// v.prev_permutation();
916 /// let b: &mut [_] = &mut [0, 2, 1];
917 /// assert!(v == b);
918 /// v.prev_permutation();
919 /// let b: &mut [_] = &mut [0, 1, 2];
920 /// assert!(v == b);
921 /// ```
922 #[unstable(feature = "collections",
923 reason = "uncertain if this merits inclusion in std")]
924 pub fn prev_permutation(&mut self) -> bool where T: Ord {
925 core_slice::SliceExt::prev_permutation(self)
926 }
927
928 /// Find the first index containing a matching value.
929 #[unstable(feature = "collections")]
930 pub fn position_elem(&self, t: &T) -> Option<usize> where T: PartialEq {
931 core_slice::SliceExt::position_elem(self, t)
932 }
933
934 /// Find the last index containing a matching value.
935 #[unstable(feature = "collections")]
936 pub fn rposition_elem(&self, t: &T) -> Option<usize> where T: PartialEq {
937 core_slice::SliceExt::rposition_elem(self, t)
938 }
939
940 /// Returns true if the slice contains an element with the given value.
941 ///
942 /// # Examples
943 ///
944 /// ```
945 /// let v = [10, 40, 30];
946 /// assert!(v.contains(&30));
947 /// assert!(!v.contains(&50));
948 /// ```
949 #[stable(feature = "rust1", since = "1.0.0")]
950 pub fn contains(&self, x: &T) -> bool where T: PartialEq {
951 core_slice::SliceExt::contains(self, x)
952 }
953
954 /// Returns true if `needle` is a prefix of the slice.
955 ///
956 /// # Examples
957 ///
958 /// ```
959 /// let v = [10, 40, 30];
960 /// assert!(v.starts_with(&[10]));
961 /// assert!(v.starts_with(&[10, 40]));
962 /// assert!(!v.starts_with(&[50]));
963 /// assert!(!v.starts_with(&[10, 50]));
964 /// ```
965 #[stable(feature = "rust1", since = "1.0.0")]
966 pub fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
967 core_slice::SliceExt::starts_with(self, needle)
968 }
969
970 /// Returns true if `needle` is a suffix of the slice.
971 ///
972 /// # Examples
973 ///
974 /// ```
975 /// let v = [10, 40, 30];
976 /// assert!(v.ends_with(&[30]));
977 /// assert!(v.ends_with(&[40, 30]));
978 /// assert!(!v.ends_with(&[50]));
979 /// assert!(!v.ends_with(&[50, 30]));
980 /// ```
981 #[stable(feature = "rust1", since = "1.0.0")]
982 pub fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
983 core_slice::SliceExt::ends_with(self, needle)
984 }
985
986 /// Converts `self` into a vector without clones or allocation.
987 #[stable(feature = "rust1", since = "1.0.0")]
988 #[inline]
989 pub fn into_vec(self: Box<Self>) -> Vec<T> {
990 // NB see hack module in this file
991 hack::into_vec(self)
992 }
993 }
994
995 ////////////////////////////////////////////////////////////////////////////////
996 // Extension traits for slices over specific kinds of data
997 ////////////////////////////////////////////////////////////////////////////////
998 #[unstable(feature = "collections", reason = "recently changed")]
999 /// An extension trait for concatenating slices
1000 pub trait SliceConcatExt<T: ?Sized> {
1001 #[unstable(feature = "collections", reason = "recently changed")]
1002 /// The resulting type after concatenation
1003 type Output;
1004
1005 /// Flattens a slice of `T` into a single value `Self::Output`.
1006 ///
1007 /// # Examples
1008 ///
1009 /// ```
1010 /// assert_eq!(["hello", "world"].concat(), "helloworld");
1011 /// ```
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 fn concat(&self) -> Self::Output;
1014
1015 /// Flattens a slice of `T` into a single value `Self::Output`, placing a given separator
1016 /// between each.
1017 ///
1018 /// # Examples
1019 ///
1020 /// ```
1021 /// assert_eq!(["hello", "world"].connect(" "), "hello world");
1022 /// ```
1023 #[stable(feature = "rust1", since = "1.0.0")]
1024 fn connect(&self, sep: &T) -> Self::Output;
1025 }
1026
1027 impl<T: Clone, V: Borrow<[T]>> SliceConcatExt<T> for [V] {
1028 type Output = Vec<T>;
1029
1030 fn concat(&self) -> Vec<T> {
1031 let size = self.iter().fold(0, |acc, v| acc + v.borrow().len());
1032 let mut result = Vec::with_capacity(size);
1033 for v in self {
1034 result.push_all(v.borrow())
1035 }
1036 result
1037 }
1038
1039 fn connect(&self, sep: &T) -> Vec<T> {
1040 let size = self.iter().fold(0, |acc, v| acc + v.borrow().len());
1041 let mut result = Vec::with_capacity(size + self.len());
1042 let mut first = true;
1043 for v in self {
1044 if first { first = false } else { result.push(sep.clone()) }
1045 result.push_all(v.borrow())
1046 }
1047 result
1048 }
1049 }
1050
1051 /// An iterator that yields the element swaps needed to produce
1052 /// a sequence of all possible permutations for an indexed sequence of
1053 /// elements. Each permutation is only a single swap apart.
1054 ///
1055 /// The Steinhaus-Johnson-Trotter algorithm is used.
1056 ///
1057 /// Generates even and odd permutations alternately.
1058 ///
1059 /// The last generated swap is always (0, 1), and it returns the
1060 /// sequence to its initial order.
1061 #[unstable(feature = "collections")]
1062 #[derive(Clone)]
1063 pub struct ElementSwaps {
1064 sdir: Vec<SizeDirection>,
1065 /// If `true`, emit the last swap that returns the sequence to initial
1066 /// state.
1067 emit_reset: bool,
1068 swaps_made : usize,
1069 }
1070
1071 impl ElementSwaps {
1072 /// Creates an `ElementSwaps` iterator for a sequence of `length` elements.
1073 #[unstable(feature = "collections")]
1074 pub fn new(length: usize) -> ElementSwaps {
1075 // Initialize `sdir` with a direction that position should move in
1076 // (all negative at the beginning) and the `size` of the
1077 // element (equal to the original index).
1078 ElementSwaps{
1079 emit_reset: true,
1080 sdir: (0..length).map(|i| SizeDirection{ size: i, dir: Neg }).collect(),
1081 swaps_made: 0
1082 }
1083 }
1084 }
1085
1086 ////////////////////////////////////////////////////////////////////////////////
1087 // Standard trait implementations for slices
1088 ////////////////////////////////////////////////////////////////////////////////
1089
1090 #[stable(feature = "rust1", since = "1.0.0")]
1091 impl<T> Borrow<[T]> for Vec<T> {
1092 fn borrow(&self) -> &[T] { &self[..] }
1093 }
1094
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 impl<T> BorrowMut<[T]> for Vec<T> {
1097 fn borrow_mut(&mut self) -> &mut [T] { &mut self[..] }
1098 }
1099
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 impl<T: Clone> ToOwned for [T] {
1102 type Owned = Vec<T>;
1103 #[cfg(not(test))]
1104 fn to_owned(&self) -> Vec<T> { self.to_vec() }
1105
1106 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec`, which is required for this method
1107 // definition, is not available. Since we don't require this method for testing purposes, I'll
1108 // just stub it
1109 // NB see the slice::hack module in slice.rs for more information
1110 #[cfg(test)]
1111 fn to_owned(&self) -> Vec<T> { panic!("not available with cfg(test)") }
1112 }
1113
1114 ////////////////////////////////////////////////////////////////////////////////
1115 // Iterators
1116 ////////////////////////////////////////////////////////////////////////////////
1117
1118 #[derive(Copy, Clone)]
1119 enum Direction { Pos, Neg }
1120
1121 /// An `Index` and `Direction` together.
1122 #[derive(Copy, Clone)]
1123 struct SizeDirection {
1124 size: usize,
1125 dir: Direction,
1126 }
1127
1128 #[stable(feature = "rust1", since = "1.0.0")]
1129 impl Iterator for ElementSwaps {
1130 type Item = (usize, usize);
1131
1132 // #[inline]
1133 fn next(&mut self) -> Option<(usize, usize)> {
1134 fn new_pos_wrapping(i: usize, s: Direction) -> usize {
1135 i.wrapping_add(match s { Pos => 1, Neg => !0 /* aka -1 */ })
1136 }
1137
1138 fn new_pos(i: usize, s: Direction) -> usize {
1139 match s { Pos => i + 1, Neg => i - 1 }
1140 }
1141
1142 // Find the index of the largest mobile element:
1143 // The direction should point into the vector, and the
1144 // swap should be with a smaller `size` element.
1145 let max = self.sdir.iter().cloned().enumerate()
1146 .filter(|&(i, sd)|
1147 new_pos_wrapping(i, sd.dir) < self.sdir.len() &&
1148 self.sdir[new_pos(i, sd.dir)].size < sd.size)
1149 .max_by(|&(_, sd)| sd.size);
1150 match max {
1151 Some((i, sd)) => {
1152 let j = new_pos(i, sd.dir);
1153 self.sdir.swap(i, j);
1154
1155 // Swap the direction of each larger SizeDirection
1156 for x in &mut self.sdir {
1157 if x.size > sd.size {
1158 x.dir = match x.dir { Pos => Neg, Neg => Pos };
1159 }
1160 }
1161 self.swaps_made += 1;
1162 Some((i, j))
1163 },
1164 None => if self.emit_reset {
1165 self.emit_reset = false;
1166 if self.sdir.len() > 1 {
1167 // The last swap
1168 self.swaps_made += 1;
1169 Some((0, 1))
1170 } else {
1171 // Vector is of the form [] or [x], and the only permutation is itself
1172 self.swaps_made += 1;
1173 Some((0,0))
1174 }
1175 } else { None }
1176 }
1177 }
1178
1179 #[inline]
1180 fn size_hint(&self) -> (usize, Option<usize>) {
1181 // For a vector of size n, there are exactly n! permutations.
1182 let n: usize = (2..self.sdir.len() + 1).product();
1183 (n - self.swaps_made, Some(n - self.swaps_made))
1184 }
1185 }
1186
1187 /// An iterator that uses `ElementSwaps` to iterate through
1188 /// all possible permutations of a vector.
1189 ///
1190 /// The first iteration yields a clone of the vector as it is,
1191 /// then each successive element is the vector with one
1192 /// swap applied.
1193 ///
1194 /// Generates even and odd permutations alternately.
1195 #[unstable(feature = "collections")]
1196 pub struct Permutations<T> {
1197 swaps: ElementSwaps,
1198 v: Vec<T>,
1199 }
1200
1201 #[unstable(feature = "collections", reason = "trait is unstable")]
1202 impl<T: Clone> Iterator for Permutations<T> {
1203 type Item = Vec<T>;
1204
1205 #[inline]
1206 fn next(&mut self) -> Option<Vec<T>> {
1207 match self.swaps.next() {
1208 None => None,
1209 Some((0,0)) => Some(self.v.clone()),
1210 Some((a, b)) => {
1211 let elt = self.v.clone();
1212 self.v.swap(a, b);
1213 Some(elt)
1214 }
1215 }
1216 }
1217
1218 #[inline]
1219 fn size_hint(&self) -> (usize, Option<usize>) {
1220 self.swaps.size_hint()
1221 }
1222 }
1223
1224 ////////////////////////////////////////////////////////////////////////////////
1225 // Sorting
1226 ////////////////////////////////////////////////////////////////////////////////
1227
1228 fn insertion_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Ordering {
1229 let len = v.len() as isize;
1230 let buf_v = v.as_mut_ptr();
1231
1232 // 1 <= i < len;
1233 for i in 1..len {
1234 // j satisfies: 0 <= j <= i;
1235 let mut j = i;
1236 unsafe {
1237 // `i` is in bounds.
1238 let read_ptr = buf_v.offset(i) as *const T;
1239
1240 // find where to insert, we need to do strict <,
1241 // rather than <=, to maintain stability.
1242
1243 // 0 <= j - 1 < len, so .offset(j - 1) is in bounds.
1244 while j > 0 &&
1245 compare(&*read_ptr, &*buf_v.offset(j - 1)) == Less {
1246 j -= 1;
1247 }
1248
1249 // shift everything to the right, to make space to
1250 // insert this value.
1251
1252 // j + 1 could be `len` (for the last `i`), but in
1253 // that case, `i == j` so we don't copy. The
1254 // `.offset(j)` is always in bounds.
1255
1256 if i != j {
1257 let tmp = ptr::read(read_ptr);
1258 ptr::copy(&*buf_v.offset(j),
1259 buf_v.offset(j + 1),
1260 (i - j) as usize);
1261 ptr::copy_nonoverlapping(&tmp, buf_v.offset(j), 1);
1262 mem::forget(tmp);
1263 }
1264 }
1265 }
1266 }
1267
1268 fn merge_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Ordering {
1269 // warning: this wildly uses unsafe.
1270 const BASE_INSERTION: usize = 32;
1271 const LARGE_INSERTION: usize = 16;
1272
1273 // FIXME #12092: smaller insertion runs seems to make sorting
1274 // vectors of large elements a little faster on some platforms,
1275 // but hasn't been tested/tuned extensively
1276 let insertion = if size_of::<T>() <= 16 {
1277 BASE_INSERTION
1278 } else {
1279 LARGE_INSERTION
1280 };
1281
1282 let len = v.len();
1283
1284 // short vectors get sorted in-place via insertion sort to avoid allocations
1285 if len <= insertion {
1286 insertion_sort(v, compare);
1287 return;
1288 }
1289
1290 // allocate some memory to use as scratch memory, we keep the
1291 // length 0 so we can keep shallow copies of the contents of `v`
1292 // without risking the dtors running on an object twice if
1293 // `compare` panics.
1294 let mut working_space = Vec::with_capacity(2 * len);
1295 // these both are buffers of length `len`.
1296 let mut buf_dat = working_space.as_mut_ptr();
1297 let mut buf_tmp = unsafe {buf_dat.offset(len as isize)};
1298
1299 // length `len`.
1300 let buf_v = v.as_ptr();
1301
1302 // step 1. sort short runs with insertion sort. This takes the
1303 // values from `v` and sorts them into `buf_dat`, leaving that
1304 // with sorted runs of length INSERTION.
1305
1306 // We could hardcode the sorting comparisons here, and we could
1307 // manipulate/step the pointers themselves, rather than repeatedly
1308 // .offset-ing.
1309 for start in (0.. len).step_by(insertion) {
1310 // start <= i < len;
1311 for i in start..cmp::min(start + insertion, len) {
1312 // j satisfies: start <= j <= i;
1313 let mut j = i as isize;
1314 unsafe {
1315 // `i` is in bounds.
1316 let read_ptr = buf_v.offset(i as isize);
1317
1318 // find where to insert, we need to do strict <,
1319 // rather than <=, to maintain stability.
1320
1321 // start <= j - 1 < len, so .offset(j - 1) is in
1322 // bounds.
1323 while j > start as isize &&
1324 compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less {
1325 j -= 1;
1326 }
1327
1328 // shift everything to the right, to make space to
1329 // insert this value.
1330
1331 // j + 1 could be `len` (for the last `i`), but in
1332 // that case, `i == j` so we don't copy. The
1333 // `.offset(j)` is always in bounds.
1334 ptr::copy(&*buf_dat.offset(j),
1335 buf_dat.offset(j + 1),
1336 i - j as usize);
1337 ptr::copy_nonoverlapping(read_ptr, buf_dat.offset(j), 1);
1338 }
1339 }
1340 }
1341
1342 // step 2. merge the sorted runs.
1343 let mut width = insertion;
1344 while width < len {
1345 // merge the sorted runs of length `width` in `buf_dat` two at
1346 // a time, placing the result in `buf_tmp`.
1347
1348 // 0 <= start <= len.
1349 for start in (0..len).step_by(2 * width) {
1350 // manipulate pointers directly for speed (rather than
1351 // using a `for` loop with `range` and `.offset` inside
1352 // that loop).
1353 unsafe {
1354 // the end of the first run & start of the
1355 // second. Offset of `len` is defined, since this is
1356 // precisely one byte past the end of the object.
1357 let right_start = buf_dat.offset(cmp::min(start + width, len) as isize);
1358 // end of the second. Similar reasoning to the above re safety.
1359 let right_end_idx = cmp::min(start + 2 * width, len);
1360 let right_end = buf_dat.offset(right_end_idx as isize);
1361
1362 // the pointers to the elements under consideration
1363 // from the two runs.
1364
1365 // both of these are in bounds.
1366 let mut left = buf_dat.offset(start as isize);
1367 let mut right = right_start;
1368
1369 // where we're putting the results, it is a run of
1370 // length `2*width`, so we step it once for each step
1371 // of either `left` or `right`. `buf_tmp` has length
1372 // `len`, so these are in bounds.
1373 let mut out = buf_tmp.offset(start as isize);
1374 let out_end = buf_tmp.offset(right_end_idx as isize);
1375
1376 while out < out_end {
1377 // Either the left or the right run are exhausted,
1378 // so just copy the remainder from the other run
1379 // and move on; this gives a huge speed-up (order
1380 // of 25%) for mostly sorted vectors (the best
1381 // case).
1382 if left == right_start {
1383 // the number remaining in this run.
1384 let elems = (right_end as usize - right as usize) / mem::size_of::<T>();
1385 ptr::copy_nonoverlapping(&*right, out, elems);
1386 break;
1387 } else if right == right_end {
1388 let elems = (right_start as usize - left as usize) / mem::size_of::<T>();
1389 ptr::copy_nonoverlapping(&*left, out, elems);
1390 break;
1391 }
1392
1393 // check which side is smaller, and that's the
1394 // next element for the new run.
1395
1396 // `left < right_start` and `right < right_end`,
1397 // so these are valid.
1398 let to_copy = if compare(&*left, &*right) == Greater {
1399 step(&mut right)
1400 } else {
1401 step(&mut left)
1402 };
1403 ptr::copy_nonoverlapping(&*to_copy, out, 1);
1404 step(&mut out);
1405 }
1406 }
1407 }
1408
1409 mem::swap(&mut buf_dat, &mut buf_tmp);
1410
1411 width *= 2;
1412 }
1413
1414 // write the result to `v` in one go, so that there are never two copies
1415 // of the same object in `v`.
1416 unsafe {
1417 ptr::copy_nonoverlapping(&*buf_dat, v.as_mut_ptr(), len);
1418 }
1419
1420 // increment the pointer, returning the old pointer.
1421 #[inline(always)]
1422 unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
1423 let old = *ptr;
1424 *ptr = ptr.offset(1);
1425 old
1426 }
1427 }