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