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