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