]> git.proxmox.com Git - rustc.git/blob - src/libcollections/slice.rs
New upstream version 1.17.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, Less};
102 use core::mem::size_of;
103 use core::mem;
104 use core::ptr;
105 use core::slice as core_slice;
106
107 use borrow::{Borrow, BorrowMut, ToOwned};
108 use vec::Vec;
109
110 #[stable(feature = "rust1", since = "1.0.0")]
111 pub use core::slice::{Chunks, Windows};
112 #[stable(feature = "rust1", since = "1.0.0")]
113 pub use core::slice::{Iter, IterMut};
114 #[stable(feature = "rust1", since = "1.0.0")]
115 pub use core::slice::{SplitMut, ChunksMut, Split};
116 #[stable(feature = "rust1", since = "1.0.0")]
117 pub use core::slice::{SplitN, RSplitN, SplitNMut, RSplitNMut};
118 #[stable(feature = "rust1", since = "1.0.0")]
119 pub use core::slice::{from_raw_parts, from_raw_parts_mut};
120 #[unstable(feature = "slice_get_slice", issue = "35729")]
121 pub use core::slice::SliceIndex;
122
123 ////////////////////////////////////////////////////////////////////////////////
124 // Basic slice extension methods
125 ////////////////////////////////////////////////////////////////////////////////
126
127 // HACK(japaric) needed for the implementation of `vec!` macro during testing
128 // NB see the hack module in this file for more details
129 #[cfg(test)]
130 pub use self::hack::into_vec;
131
132 // HACK(japaric) needed for the implementation of `Vec::clone` during testing
133 // NB see the hack module in this file for more details
134 #[cfg(test)]
135 pub use self::hack::to_vec;
136
137 // HACK(japaric): With cfg(test) `impl [T]` is not available, these three
138 // functions are actually methods that are in `impl [T]` but not in
139 // `core::slice::SliceExt` - we need to supply these functions for the
140 // `test_permutations` test
141 mod hack {
142 use alloc::boxed::Box;
143 use core::mem;
144
145 #[cfg(test)]
146 use string::ToString;
147 use vec::Vec;
148
149 pub fn into_vec<T>(mut b: Box<[T]>) -> Vec<T> {
150 unsafe {
151 let xs = Vec::from_raw_parts(b.as_mut_ptr(), b.len(), b.len());
152 mem::forget(b);
153 xs
154 }
155 }
156
157 #[inline]
158 pub fn to_vec<T>(s: &[T]) -> Vec<T>
159 where T: Clone
160 {
161 let mut vector = Vec::with_capacity(s.len());
162 vector.extend_from_slice(s);
163 vector
164 }
165 }
166
167 #[lang = "slice"]
168 #[cfg(not(test))]
169 impl<T> [T] {
170 /// Returns the number of elements in the slice.
171 ///
172 /// # Example
173 ///
174 /// ```
175 /// let a = [1, 2, 3];
176 /// assert_eq!(a.len(), 3);
177 /// ```
178 #[stable(feature = "rust1", since = "1.0.0")]
179 #[inline]
180 pub fn len(&self) -> usize {
181 core_slice::SliceExt::len(self)
182 }
183
184 /// Returns `true` if the slice has a length of 0.
185 ///
186 /// # Example
187 ///
188 /// ```
189 /// let a = [1, 2, 3];
190 /// assert!(!a.is_empty());
191 /// ```
192 #[stable(feature = "rust1", since = "1.0.0")]
193 #[inline]
194 pub fn is_empty(&self) -> bool {
195 core_slice::SliceExt::is_empty(self)
196 }
197
198 /// Returns the first element of a slice, or `None` if it is empty.
199 ///
200 /// # Examples
201 ///
202 /// ```
203 /// let v = [10, 40, 30];
204 /// assert_eq!(Some(&10), v.first());
205 ///
206 /// let w: &[i32] = &[];
207 /// assert_eq!(None, w.first());
208 /// ```
209 #[stable(feature = "rust1", since = "1.0.0")]
210 #[inline]
211 pub fn first(&self) -> Option<&T> {
212 core_slice::SliceExt::first(self)
213 }
214
215 /// Returns a mutable pointer to the first element of a slice, or `None` if it is empty.
216 ///
217 /// # Examples
218 ///
219 /// ```
220 /// let x = &mut [0, 1, 2];
221 ///
222 /// if let Some(first) = x.first_mut() {
223 /// *first = 5;
224 /// }
225 /// assert_eq!(x, &[5, 1, 2]);
226 /// ```
227 #[stable(feature = "rust1", since = "1.0.0")]
228 #[inline]
229 pub fn first_mut(&mut self) -> Option<&mut T> {
230 core_slice::SliceExt::first_mut(self)
231 }
232
233 /// Returns the first and all the rest of the elements of a slice.
234 ///
235 /// # Examples
236 ///
237 /// ```
238 /// let x = &[0, 1, 2];
239 ///
240 /// if let Some((first, elements)) = x.split_first() {
241 /// assert_eq!(first, &0);
242 /// assert_eq!(elements, &[1, 2]);
243 /// }
244 /// ```
245 #[stable(feature = "slice_splits", since = "1.5.0")]
246 #[inline]
247 pub fn split_first(&self) -> Option<(&T, &[T])> {
248 core_slice::SliceExt::split_first(self)
249 }
250
251 /// Returns the first and all the rest of the elements of a slice.
252 ///
253 /// # Examples
254 ///
255 /// ```
256 /// let x = &mut [0, 1, 2];
257 ///
258 /// if let Some((first, elements)) = x.split_first_mut() {
259 /// *first = 3;
260 /// elements[0] = 4;
261 /// elements[1] = 5;
262 /// }
263 /// assert_eq!(x, &[3, 4, 5]);
264 /// ```
265 #[stable(feature = "slice_splits", since = "1.5.0")]
266 #[inline]
267 pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
268 core_slice::SliceExt::split_first_mut(self)
269 }
270
271 /// Returns the last and all the rest of the elements of a slice.
272 ///
273 /// # Examples
274 ///
275 /// ```
276 /// let x = &[0, 1, 2];
277 ///
278 /// if let Some((last, elements)) = x.split_last() {
279 /// assert_eq!(last, &2);
280 /// assert_eq!(elements, &[0, 1]);
281 /// }
282 /// ```
283 #[stable(feature = "slice_splits", since = "1.5.0")]
284 #[inline]
285 pub fn split_last(&self) -> Option<(&T, &[T])> {
286 core_slice::SliceExt::split_last(self)
287
288 }
289
290 /// Returns the last and all the rest of the elements of a slice.
291 ///
292 /// # Examples
293 ///
294 /// ```
295 /// let x = &mut [0, 1, 2];
296 ///
297 /// if let Some((last, elements)) = x.split_last_mut() {
298 /// *last = 3;
299 /// elements[0] = 4;
300 /// elements[1] = 5;
301 /// }
302 /// assert_eq!(x, &[4, 5, 3]);
303 /// ```
304 #[stable(feature = "slice_splits", since = "1.5.0")]
305 #[inline]
306 pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
307 core_slice::SliceExt::split_last_mut(self)
308 }
309
310 /// Returns the last element of a slice, or `None` if it is empty.
311 ///
312 /// # Examples
313 ///
314 /// ```
315 /// let v = [10, 40, 30];
316 /// assert_eq!(Some(&30), v.last());
317 ///
318 /// let w: &[i32] = &[];
319 /// assert_eq!(None, w.last());
320 /// ```
321 #[stable(feature = "rust1", since = "1.0.0")]
322 #[inline]
323 pub fn last(&self) -> Option<&T> {
324 core_slice::SliceExt::last(self)
325 }
326
327 /// Returns a mutable pointer to the last item in the slice.
328 ///
329 /// # Examples
330 ///
331 /// ```
332 /// let x = &mut [0, 1, 2];
333 ///
334 /// if let Some(last) = x.last_mut() {
335 /// *last = 10;
336 /// }
337 /// assert_eq!(x, &[0, 1, 10]);
338 /// ```
339 #[stable(feature = "rust1", since = "1.0.0")]
340 #[inline]
341 pub fn last_mut(&mut self) -> Option<&mut T> {
342 core_slice::SliceExt::last_mut(self)
343 }
344
345 /// Returns a reference to an element or subslice depending on the type of
346 /// index.
347 ///
348 /// - If given a position, returns a reference to the element at that
349 /// position or `None` if out of bounds.
350 /// - If given a range, returns the subslice corresponding to that range,
351 /// or `None` if out of bounds.
352 ///
353 /// # Examples
354 ///
355 /// ```
356 /// let v = [10, 40, 30];
357 /// assert_eq!(Some(&40), v.get(1));
358 /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
359 /// assert_eq!(None, v.get(3));
360 /// assert_eq!(None, v.get(0..4));
361 /// ```
362 #[stable(feature = "rust1", since = "1.0.0")]
363 #[inline]
364 pub fn get<I>(&self, index: I) -> Option<&I::Output>
365 where I: SliceIndex<T>
366 {
367 core_slice::SliceExt::get(self, index)
368 }
369
370 /// Returns a mutable reference to an element or subslice depending on the
371 /// type of index (see [`get()`]) or `None` if the index is out of bounds.
372 ///
373 /// [`get()`]: #method.get
374 ///
375 /// # Examples
376 ///
377 /// ```
378 /// let x = &mut [0, 1, 2];
379 ///
380 /// if let Some(elem) = x.get_mut(1) {
381 /// *elem = 42;
382 /// }
383 /// assert_eq!(x, &[0, 42, 2]);
384 /// ```
385 #[stable(feature = "rust1", since = "1.0.0")]
386 #[inline]
387 pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
388 where I: SliceIndex<T>
389 {
390 core_slice::SliceExt::get_mut(self, index)
391 }
392
393 /// Returns a reference to an element or subslice, without doing bounds
394 /// checking. So use it very carefully!
395 ///
396 /// # Examples
397 ///
398 /// ```
399 /// let x = &[1, 2, 4];
400 ///
401 /// unsafe {
402 /// assert_eq!(x.get_unchecked(1), &2);
403 /// }
404 /// ```
405 #[stable(feature = "rust1", since = "1.0.0")]
406 #[inline]
407 pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
408 where I: SliceIndex<T>
409 {
410 core_slice::SliceExt::get_unchecked(self, index)
411 }
412
413 /// Returns a mutable reference to an element or subslice, without doing
414 /// bounds checking. So use it very carefully!
415 ///
416 /// # Examples
417 ///
418 /// ```
419 /// let x = &mut [1, 2, 4];
420 ///
421 /// unsafe {
422 /// let elem = x.get_unchecked_mut(1);
423 /// *elem = 13;
424 /// }
425 /// assert_eq!(x, &[1, 13, 4]);
426 /// ```
427 #[stable(feature = "rust1", since = "1.0.0")]
428 #[inline]
429 pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
430 where I: SliceIndex<T>
431 {
432 core_slice::SliceExt::get_unchecked_mut(self, index)
433 }
434
435 /// Returns a raw pointer to the slice's buffer.
436 ///
437 /// The caller must ensure that the slice outlives the pointer this
438 /// function returns, or else it will end up pointing to garbage.
439 ///
440 /// Modifying the slice may cause its buffer to be reallocated, which
441 /// would also make any pointers to it invalid.
442 ///
443 /// # Examples
444 ///
445 /// ```
446 /// let x = &[1, 2, 4];
447 /// let x_ptr = x.as_ptr();
448 ///
449 /// unsafe {
450 /// for i in 0..x.len() {
451 /// assert_eq!(x.get_unchecked(i), &*x_ptr.offset(i as isize));
452 /// }
453 /// }
454 /// ```
455 #[stable(feature = "rust1", since = "1.0.0")]
456 #[inline]
457 pub fn as_ptr(&self) -> *const T {
458 core_slice::SliceExt::as_ptr(self)
459 }
460
461 /// Returns an unsafe mutable pointer to the slice's buffer.
462 ///
463 /// The caller must ensure that the slice outlives the pointer this
464 /// function returns, or else it will end up pointing to garbage.
465 ///
466 /// Modifying the slice may cause its buffer to be reallocated, which
467 /// would also make any pointers to it invalid.
468 ///
469 /// # Examples
470 ///
471 /// ```
472 /// let x = &mut [1, 2, 4];
473 /// let x_ptr = x.as_mut_ptr();
474 ///
475 /// unsafe {
476 /// for i in 0..x.len() {
477 /// *x_ptr.offset(i as isize) += 2;
478 /// }
479 /// }
480 /// assert_eq!(x, &[3, 4, 6]);
481 /// ```
482 #[stable(feature = "rust1", since = "1.0.0")]
483 #[inline]
484 pub fn as_mut_ptr(&mut self) -> *mut T {
485 core_slice::SliceExt::as_mut_ptr(self)
486 }
487
488 /// Swaps two elements in a slice.
489 ///
490 /// # Arguments
491 ///
492 /// * a - The index of the first element
493 /// * b - The index of the second element
494 ///
495 /// # Panics
496 ///
497 /// Panics if `a` or `b` are out of bounds.
498 ///
499 /// # Examples
500 ///
501 /// ```
502 /// let mut v = ["a", "b", "c", "d"];
503 /// v.swap(1, 3);
504 /// assert!(v == ["a", "d", "c", "b"]);
505 /// ```
506 #[stable(feature = "rust1", since = "1.0.0")]
507 #[inline]
508 pub fn swap(&mut self, a: usize, b: usize) {
509 core_slice::SliceExt::swap(self, a, b)
510 }
511
512 /// Reverses the order of elements in a slice, in place.
513 ///
514 /// # Example
515 ///
516 /// ```
517 /// let mut v = [1, 2, 3];
518 /// v.reverse();
519 /// assert!(v == [3, 2, 1]);
520 /// ```
521 #[stable(feature = "rust1", since = "1.0.0")]
522 #[inline]
523 pub fn reverse(&mut self) {
524 core_slice::SliceExt::reverse(self)
525 }
526
527 /// Returns an iterator over the slice.
528 ///
529 /// # Examples
530 ///
531 /// ```
532 /// let x = &[1, 2, 4];
533 /// let mut iterator = x.iter();
534 ///
535 /// assert_eq!(iterator.next(), Some(&1));
536 /// assert_eq!(iterator.next(), Some(&2));
537 /// assert_eq!(iterator.next(), Some(&4));
538 /// assert_eq!(iterator.next(), None);
539 /// ```
540 #[stable(feature = "rust1", since = "1.0.0")]
541 #[inline]
542 pub fn iter(&self) -> Iter<T> {
543 core_slice::SliceExt::iter(self)
544 }
545
546 /// Returns an iterator that allows modifying each value.
547 ///
548 /// # Examples
549 ///
550 /// ```
551 /// let x = &mut [1, 2, 4];
552 /// for elem in x.iter_mut() {
553 /// *elem += 2;
554 /// }
555 /// assert_eq!(x, &[3, 4, 6]);
556 /// ```
557 #[stable(feature = "rust1", since = "1.0.0")]
558 #[inline]
559 pub fn iter_mut(&mut self) -> IterMut<T> {
560 core_slice::SliceExt::iter_mut(self)
561 }
562
563 /// Returns an iterator over all contiguous windows of length
564 /// `size`. The windows overlap. If the slice is shorter than
565 /// `size`, the iterator returns no values.
566 ///
567 /// # Panics
568 ///
569 /// Panics if `size` is 0.
570 ///
571 /// # Example
572 ///
573 /// ```
574 /// let slice = ['r', 'u', 's', 't'];
575 /// let mut iter = slice.windows(2);
576 /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
577 /// assert_eq!(iter.next().unwrap(), &['u', 's']);
578 /// assert_eq!(iter.next().unwrap(), &['s', 't']);
579 /// assert!(iter.next().is_none());
580 /// ```
581 ///
582 /// If the slice is shorter than `size`:
583 ///
584 /// ```
585 /// let slice = ['f', 'o', 'o'];
586 /// let mut iter = slice.windows(4);
587 /// assert!(iter.next().is_none());
588 /// ```
589 #[stable(feature = "rust1", since = "1.0.0")]
590 #[inline]
591 pub fn windows(&self, size: usize) -> Windows<T> {
592 core_slice::SliceExt::windows(self, size)
593 }
594
595 /// Returns an iterator over `size` elements of the slice at a
596 /// time. The chunks are slices and do not overlap. If `size` does
597 /// not divide the length of the slice, then the last chunk will
598 /// not have length `size`.
599 ///
600 /// # Panics
601 ///
602 /// Panics if `size` is 0.
603 ///
604 /// # Example
605 ///
606 /// ```
607 /// let slice = ['l', 'o', 'r', 'e', 'm'];
608 /// let mut iter = slice.chunks(2);
609 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
610 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
611 /// assert_eq!(iter.next().unwrap(), &['m']);
612 /// assert!(iter.next().is_none());
613 /// ```
614 #[stable(feature = "rust1", since = "1.0.0")]
615 #[inline]
616 pub fn chunks(&self, size: usize) -> Chunks<T> {
617 core_slice::SliceExt::chunks(self, size)
618 }
619
620 /// Returns an iterator over `chunk_size` elements of the slice at a time.
621 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does
622 /// not divide the length of the slice, then the last chunk will not
623 /// have length `chunk_size`.
624 ///
625 /// # Panics
626 ///
627 /// Panics if `chunk_size` is 0.
628 ///
629 /// # Examples
630 ///
631 /// ```
632 /// let v = &mut [0, 0, 0, 0, 0];
633 /// let mut count = 1;
634 ///
635 /// for chunk in v.chunks_mut(2) {
636 /// for elem in chunk.iter_mut() {
637 /// *elem += count;
638 /// }
639 /// count += 1;
640 /// }
641 /// assert_eq!(v, &[1, 1, 2, 2, 3]);
642 /// ```
643 #[stable(feature = "rust1", since = "1.0.0")]
644 #[inline]
645 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
646 core_slice::SliceExt::chunks_mut(self, chunk_size)
647 }
648
649 /// Divides one slice into two at an index.
650 ///
651 /// The first will contain all indices from `[0, mid)` (excluding
652 /// the index `mid` itself) and the second will contain all
653 /// indices from `[mid, len)` (excluding the index `len` itself).
654 ///
655 /// # Panics
656 ///
657 /// Panics if `mid > len`.
658 ///
659 /// # Examples
660 ///
661 /// ```
662 /// let v = [10, 40, 30, 20, 50];
663 /// let (v1, v2) = v.split_at(2);
664 /// assert_eq!([10, 40], v1);
665 /// assert_eq!([30, 20, 50], v2);
666 /// ```
667 #[stable(feature = "rust1", since = "1.0.0")]
668 #[inline]
669 pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
670 core_slice::SliceExt::split_at(self, mid)
671 }
672
673 /// Divides one `&mut` into two at an index.
674 ///
675 /// The first will contain all indices from `[0, mid)` (excluding
676 /// the index `mid` itself) and the second will contain all
677 /// indices from `[mid, len)` (excluding the index `len` itself).
678 ///
679 /// # Panics
680 ///
681 /// Panics if `mid > len`.
682 ///
683 /// # Examples
684 ///
685 /// ```
686 /// let mut v = [1, 2, 3, 4, 5, 6];
687 ///
688 /// // scoped to restrict the lifetime of the borrows
689 /// {
690 /// let (left, right) = v.split_at_mut(0);
691 /// assert!(left == []);
692 /// assert!(right == [1, 2, 3, 4, 5, 6]);
693 /// }
694 ///
695 /// {
696 /// let (left, right) = v.split_at_mut(2);
697 /// assert!(left == [1, 2]);
698 /// assert!(right == [3, 4, 5, 6]);
699 /// }
700 ///
701 /// {
702 /// let (left, right) = v.split_at_mut(6);
703 /// assert!(left == [1, 2, 3, 4, 5, 6]);
704 /// assert!(right == []);
705 /// }
706 /// ```
707 #[stable(feature = "rust1", since = "1.0.0")]
708 #[inline]
709 pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
710 core_slice::SliceExt::split_at_mut(self, mid)
711 }
712
713 /// Returns an iterator over subslices separated by elements that match
714 /// `pred`. The matched element is not contained in the subslices.
715 ///
716 /// # Examples
717 ///
718 /// ```
719 /// let slice = [10, 40, 33, 20];
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(), &[20]);
724 /// assert!(iter.next().is_none());
725 /// ```
726 ///
727 /// If the first element is matched, an empty slice will be the first item
728 /// returned by the iterator. Similarly, if the last element in the slice
729 /// is matched, an empty slice will be the last item returned by the
730 /// iterator:
731 ///
732 /// ```
733 /// let slice = [10, 40, 33];
734 /// let mut iter = slice.split(|num| num % 3 == 0);
735 ///
736 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
737 /// assert_eq!(iter.next().unwrap(), &[]);
738 /// assert!(iter.next().is_none());
739 /// ```
740 ///
741 /// If two matched elements are directly adjacent, an empty slice will be
742 /// present between them:
743 ///
744 /// ```
745 /// let slice = [10, 6, 33, 20];
746 /// let mut iter = slice.split(|num| num % 3 == 0);
747 ///
748 /// assert_eq!(iter.next().unwrap(), &[10]);
749 /// assert_eq!(iter.next().unwrap(), &[]);
750 /// assert_eq!(iter.next().unwrap(), &[20]);
751 /// assert!(iter.next().is_none());
752 /// ```
753 #[stable(feature = "rust1", since = "1.0.0")]
754 #[inline]
755 pub fn split<F>(&self, pred: F) -> Split<T, F>
756 where F: FnMut(&T) -> bool
757 {
758 core_slice::SliceExt::split(self, pred)
759 }
760
761 /// Returns an iterator over mutable subslices separated by elements that
762 /// match `pred`. The matched element is not contained in the subslices.
763 ///
764 /// # Examples
765 ///
766 /// ```
767 /// let mut v = [10, 40, 30, 20, 60, 50];
768 ///
769 /// for group in v.split_mut(|num| *num % 3 == 0) {
770 /// group[0] = 1;
771 /// }
772 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
773 /// ```
774 #[stable(feature = "rust1", since = "1.0.0")]
775 #[inline]
776 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F>
777 where F: FnMut(&T) -> bool
778 {
779 core_slice::SliceExt::split_mut(self, pred)
780 }
781
782 /// Returns an iterator over subslices separated by elements that match
783 /// `pred`, limited to returning at most `n` items. The matched element is
784 /// not contained in the subslices.
785 ///
786 /// The last element returned, if any, will contain the remainder of the
787 /// slice.
788 ///
789 /// # Examples
790 ///
791 /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
792 /// `[20, 60, 50]`):
793 ///
794 /// ```
795 /// let v = [10, 40, 30, 20, 60, 50];
796 ///
797 /// for group in v.splitn(2, |num| *num % 3 == 0) {
798 /// println!("{:?}", group);
799 /// }
800 /// ```
801 #[stable(feature = "rust1", since = "1.0.0")]
802 #[inline]
803 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F>
804 where F: FnMut(&T) -> bool
805 {
806 core_slice::SliceExt::splitn(self, n, pred)
807 }
808
809 /// Returns an iterator over subslices separated by elements that match
810 /// `pred`, limited to returning at most `n` items. The matched element is
811 /// not contained in the subslices.
812 ///
813 /// The last element returned, if any, will contain the remainder of the
814 /// slice.
815 ///
816 /// # Examples
817 ///
818 /// ```
819 /// let mut v = [10, 40, 30, 20, 60, 50];
820 ///
821 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
822 /// group[0] = 1;
823 /// }
824 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
825 /// ```
826 #[stable(feature = "rust1", since = "1.0.0")]
827 #[inline]
828 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, F>
829 where F: FnMut(&T) -> bool
830 {
831 core_slice::SliceExt::splitn_mut(self, n, pred)
832 }
833
834 /// Returns an iterator over subslices separated by elements that match
835 /// `pred` limited to returning at most `n` items. This starts at the end of
836 /// the slice and works backwards. The matched element is not contained in
837 /// the subslices.
838 ///
839 /// The last element returned, if any, will contain the remainder of the
840 /// slice.
841 ///
842 /// # Examples
843 ///
844 /// Print the slice split once, starting from the end, by numbers divisible
845 /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
846 ///
847 /// ```
848 /// let v = [10, 40, 30, 20, 60, 50];
849 ///
850 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
851 /// println!("{:?}", group);
852 /// }
853 /// ```
854 #[stable(feature = "rust1", since = "1.0.0")]
855 #[inline]
856 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F>
857 where F: FnMut(&T) -> bool
858 {
859 core_slice::SliceExt::rsplitn(self, n, pred)
860 }
861
862 /// Returns an iterator over subslices separated by elements that match
863 /// `pred` limited to returning at most `n` items. This starts at the end of
864 /// the slice and works backwards. The matched element is not contained in
865 /// the subslices.
866 ///
867 /// The last element returned, if any, will contain the remainder of the
868 /// slice.
869 ///
870 /// # Examples
871 ///
872 /// ```
873 /// let mut s = [10, 40, 30, 20, 60, 50];
874 ///
875 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
876 /// group[0] = 1;
877 /// }
878 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
879 /// ```
880 #[stable(feature = "rust1", since = "1.0.0")]
881 #[inline]
882 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, F>
883 where F: FnMut(&T) -> bool
884 {
885 core_slice::SliceExt::rsplitn_mut(self, n, pred)
886 }
887
888 /// Returns `true` if the slice contains an element with the given value.
889 ///
890 /// # Examples
891 ///
892 /// ```
893 /// let v = [10, 40, 30];
894 /// assert!(v.contains(&30));
895 /// assert!(!v.contains(&50));
896 /// ```
897 #[stable(feature = "rust1", since = "1.0.0")]
898 pub fn contains(&self, x: &T) -> bool
899 where T: PartialEq
900 {
901 core_slice::SliceExt::contains(self, x)
902 }
903
904 /// Returns `true` if `needle` is a prefix of the slice.
905 ///
906 /// # Examples
907 ///
908 /// ```
909 /// let v = [10, 40, 30];
910 /// assert!(v.starts_with(&[10]));
911 /// assert!(v.starts_with(&[10, 40]));
912 /// assert!(!v.starts_with(&[50]));
913 /// assert!(!v.starts_with(&[10, 50]));
914 /// ```
915 ///
916 /// Always returns `true` if `needle` is an empty slice:
917 ///
918 /// ```
919 /// let v = &[10, 40, 30];
920 /// assert!(v.starts_with(&[]));
921 /// let v: &[u8] = &[];
922 /// assert!(v.starts_with(&[]));
923 /// ```
924 #[stable(feature = "rust1", since = "1.0.0")]
925 pub fn starts_with(&self, needle: &[T]) -> bool
926 where T: PartialEq
927 {
928 core_slice::SliceExt::starts_with(self, needle)
929 }
930
931 /// Returns `true` if `needle` is a suffix of the slice.
932 ///
933 /// # Examples
934 ///
935 /// ```
936 /// let v = [10, 40, 30];
937 /// assert!(v.ends_with(&[30]));
938 /// assert!(v.ends_with(&[40, 30]));
939 /// assert!(!v.ends_with(&[50]));
940 /// assert!(!v.ends_with(&[50, 30]));
941 /// ```
942 ///
943 /// Always returns `true` if `needle` is an empty slice:
944 ///
945 /// ```
946 /// let v = &[10, 40, 30];
947 /// assert!(v.ends_with(&[]));
948 /// let v: &[u8] = &[];
949 /// assert!(v.ends_with(&[]));
950 /// ```
951 #[stable(feature = "rust1", since = "1.0.0")]
952 pub fn ends_with(&self, needle: &[T]) -> bool
953 where T: PartialEq
954 {
955 core_slice::SliceExt::ends_with(self, needle)
956 }
957
958 /// Binary search a sorted slice for a given element.
959 ///
960 /// If the value is found then `Ok` is returned, containing the
961 /// index of the matching element; if the value is not found then
962 /// `Err` is returned, containing the index where a matching
963 /// element could be inserted while maintaining sorted order.
964 ///
965 /// # Example
966 ///
967 /// Looks up a series of four elements. The first is found, with a
968 /// uniquely determined position; the second and third are not
969 /// found; the fourth could match any position in `[1, 4]`.
970 ///
971 /// ```
972 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
973 ///
974 /// assert_eq!(s.binary_search(&13), Ok(9));
975 /// assert_eq!(s.binary_search(&4), Err(7));
976 /// assert_eq!(s.binary_search(&100), Err(13));
977 /// let r = s.binary_search(&1);
978 /// assert!(match r { Ok(1...4) => true, _ => false, });
979 /// ```
980 #[stable(feature = "rust1", since = "1.0.0")]
981 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
982 where T: Ord
983 {
984 core_slice::SliceExt::binary_search(self, x)
985 }
986
987 /// Binary search a sorted slice with a comparator function.
988 ///
989 /// The comparator function should implement an order consistent
990 /// with the sort order of the underlying slice, returning an
991 /// order code that indicates whether its argument is `Less`,
992 /// `Equal` or `Greater` the desired target.
993 ///
994 /// If a matching value is found then returns `Ok`, containing
995 /// the index for the matched element; if no match is found then
996 /// `Err` is returned, containing the index where a matching
997 /// element could be inserted while maintaining sorted order.
998 ///
999 /// # Example
1000 ///
1001 /// Looks up a series of four elements. The first is found, with a
1002 /// uniquely determined position; the second and third are not
1003 /// found; the fourth could match any position in `[1, 4]`.
1004 ///
1005 /// ```
1006 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1007 ///
1008 /// let seek = 13;
1009 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
1010 /// let seek = 4;
1011 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
1012 /// let seek = 100;
1013 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
1014 /// let seek = 1;
1015 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
1016 /// assert!(match r { Ok(1...4) => true, _ => false, });
1017 /// ```
1018 #[stable(feature = "rust1", since = "1.0.0")]
1019 #[inline]
1020 pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
1021 where F: FnMut(&'a T) -> Ordering
1022 {
1023 core_slice::SliceExt::binary_search_by(self, f)
1024 }
1025
1026 /// Binary search a sorted slice with a key extraction function.
1027 ///
1028 /// Assumes that the slice is sorted by the key, for instance with
1029 /// [`sort_by_key`] using the same key extraction function.
1030 ///
1031 /// If a matching value is found then returns `Ok`, containing the
1032 /// index for the matched element; if no match is found then `Err`
1033 /// is returned, containing the index where a matching element could
1034 /// be inserted while maintaining sorted order.
1035 ///
1036 /// [`sort_by_key`]: #method.sort_by_key
1037 ///
1038 /// # Examples
1039 ///
1040 /// Looks up a series of four elements in a slice of pairs sorted by
1041 /// their second elements. The first is found, with a uniquely
1042 /// determined position; the second and third are not found; the
1043 /// fourth could match any position in `[1, 4]`.
1044 ///
1045 /// ```
1046 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
1047 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
1048 /// (1, 21), (2, 34), (4, 55)];
1049 ///
1050 /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
1051 /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7));
1052 /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
1053 /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
1054 /// assert!(match r { Ok(1...4) => true, _ => false, });
1055 /// ```
1056 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
1057 #[inline]
1058 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<usize, usize>
1059 where F: FnMut(&'a T) -> B,
1060 B: Ord
1061 {
1062 core_slice::SliceExt::binary_search_by_key(self, b, f)
1063 }
1064
1065 /// Sorts the slice.
1066 ///
1067 /// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case.
1068 ///
1069 /// # Current implementation
1070 ///
1071 /// The current algorithm is an adaptive, iterative merge sort inspired by
1072 /// [timsort](https://en.wikipedia.org/wiki/Timsort).
1073 /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
1074 /// two or more sorted sequences concatenated one after another.
1075 ///
1076 /// Also, it allocates temporary storage half the size of `self`, but for short slices a
1077 /// non-allocating insertion sort is used instead.
1078 ///
1079 /// # Examples
1080 ///
1081 /// ```
1082 /// let mut v = [-5, 4, 1, -3, 2];
1083 ///
1084 /// v.sort();
1085 /// assert!(v == [-5, -3, 1, 2, 4]);
1086 /// ```
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 #[inline]
1089 pub fn sort(&mut self)
1090 where T: Ord
1091 {
1092 merge_sort(self, |a, b| a.lt(b));
1093 }
1094
1095 /// Sorts the slice using `f` to extract a key to compare elements by.
1096 ///
1097 /// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case.
1098 ///
1099 /// # Current implementation
1100 ///
1101 /// The current algorithm is an adaptive, iterative merge sort inspired by
1102 /// [timsort](https://en.wikipedia.org/wiki/Timsort).
1103 /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
1104 /// two or more sorted sequences concatenated one after another.
1105 ///
1106 /// Also, it allocates temporary storage half the size of `self`, but for short slices a
1107 /// non-allocating insertion sort is used instead.
1108 ///
1109 /// # Examples
1110 ///
1111 /// ```
1112 /// let mut v = [-5i32, 4, 1, -3, 2];
1113 ///
1114 /// v.sort_by_key(|k| k.abs());
1115 /// assert!(v == [1, 2, -3, 4, -5]);
1116 /// ```
1117 #[stable(feature = "slice_sort_by_key", since = "1.7.0")]
1118 #[inline]
1119 pub fn sort_by_key<B, F>(&mut self, mut f: F)
1120 where F: FnMut(&T) -> B, B: Ord
1121 {
1122 merge_sort(self, |a, b| f(a).lt(&f(b)));
1123 }
1124
1125 /// Sorts the slice using `compare` to compare elements.
1126 ///
1127 /// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case.
1128 ///
1129 /// # Current implementation
1130 ///
1131 /// The current algorithm is an adaptive, iterative merge sort inspired by
1132 /// [timsort](https://en.wikipedia.org/wiki/Timsort).
1133 /// It is designed to be very fast in cases where the slice is nearly sorted, or consists of
1134 /// two or more sorted sequences concatenated one after another.
1135 ///
1136 /// Also, it allocates temporary storage half the size of `self`, but for short slices a
1137 /// non-allocating insertion sort is used instead.
1138 ///
1139 /// # Examples
1140 ///
1141 /// ```
1142 /// let mut v = [5, 4, 1, 3, 2];
1143 /// v.sort_by(|a, b| a.cmp(b));
1144 /// assert!(v == [1, 2, 3, 4, 5]);
1145 ///
1146 /// // reverse sorting
1147 /// v.sort_by(|a, b| b.cmp(a));
1148 /// assert!(v == [5, 4, 3, 2, 1]);
1149 /// ```
1150 #[stable(feature = "rust1", since = "1.0.0")]
1151 #[inline]
1152 pub fn sort_by<F>(&mut self, mut compare: F)
1153 where F: FnMut(&T, &T) -> Ordering
1154 {
1155 merge_sort(self, |a, b| compare(a, b) == Less);
1156 }
1157
1158 /// Copies the elements from `src` into `self`.
1159 ///
1160 /// The length of `src` must be the same as `self`.
1161 ///
1162 /// # Panics
1163 ///
1164 /// This function will panic if the two slices have different lengths.
1165 ///
1166 /// # Example
1167 ///
1168 /// ```
1169 /// let mut dst = [0, 0, 0];
1170 /// let src = [1, 2, 3];
1171 ///
1172 /// dst.clone_from_slice(&src);
1173 /// assert!(dst == [1, 2, 3]);
1174 /// ```
1175 #[stable(feature = "clone_from_slice", since = "1.7.0")]
1176 pub fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
1177 core_slice::SliceExt::clone_from_slice(self, src)
1178 }
1179
1180 /// Copies all elements from `src` into `self`, using a memcpy.
1181 ///
1182 /// The length of `src` must be the same as `self`.
1183 ///
1184 /// # Panics
1185 ///
1186 /// This function will panic if the two slices have different lengths.
1187 ///
1188 /// # Example
1189 ///
1190 /// ```
1191 /// let mut dst = [0, 0, 0];
1192 /// let src = [1, 2, 3];
1193 ///
1194 /// dst.copy_from_slice(&src);
1195 /// assert_eq!(src, dst);
1196 /// ```
1197 #[stable(feature = "copy_from_slice", since = "1.9.0")]
1198 pub fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
1199 core_slice::SliceExt::copy_from_slice(self, src)
1200 }
1201
1202
1203 /// Copies `self` into a new `Vec`.
1204 ///
1205 /// # Examples
1206 ///
1207 /// ```
1208 /// let s = [10, 40, 30];
1209 /// let x = s.to_vec();
1210 /// // Here, `s` and `x` can be modified independently.
1211 /// ```
1212 #[stable(feature = "rust1", since = "1.0.0")]
1213 #[inline]
1214 pub fn to_vec(&self) -> Vec<T>
1215 where T: Clone
1216 {
1217 // NB see hack module in this file
1218 hack::to_vec(self)
1219 }
1220
1221 /// Converts `self` into a vector without clones or allocation.
1222 ///
1223 /// # Examples
1224 ///
1225 /// ```
1226 /// let s: Box<[i32]> = Box::new([10, 40, 30]);
1227 /// let x = s.into_vec();
1228 /// // `s` cannot be used anymore because it has been converted into `x`.
1229 ///
1230 /// assert_eq!(x, vec![10, 40, 30]);
1231 /// ```
1232 #[stable(feature = "rust1", since = "1.0.0")]
1233 #[inline]
1234 pub fn into_vec(self: Box<Self>) -> Vec<T> {
1235 // NB see hack module in this file
1236 hack::into_vec(self)
1237 }
1238 }
1239
1240 ////////////////////////////////////////////////////////////////////////////////
1241 // Extension traits for slices over specific kinds of data
1242 ////////////////////////////////////////////////////////////////////////////////
1243 #[unstable(feature = "slice_concat_ext",
1244 reason = "trait should not have to exist",
1245 issue = "27747")]
1246 /// An extension trait for concatenating slices
1247 pub trait SliceConcatExt<T: ?Sized> {
1248 #[unstable(feature = "slice_concat_ext",
1249 reason = "trait should not have to exist",
1250 issue = "27747")]
1251 /// The resulting type after concatenation
1252 type Output;
1253
1254 /// Flattens a slice of `T` into a single value `Self::Output`.
1255 ///
1256 /// # Examples
1257 ///
1258 /// ```
1259 /// assert_eq!(["hello", "world"].concat(), "helloworld");
1260 /// ```
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 fn concat(&self) -> Self::Output;
1263
1264 /// Flattens a slice of `T` into a single value `Self::Output`, placing a
1265 /// given separator between each.
1266 ///
1267 /// # Examples
1268 ///
1269 /// ```
1270 /// assert_eq!(["hello", "world"].join(" "), "hello world");
1271 /// ```
1272 #[stable(feature = "rename_connect_to_join", since = "1.3.0")]
1273 fn join(&self, sep: &T) -> Self::Output;
1274
1275 #[stable(feature = "rust1", since = "1.0.0")]
1276 #[rustc_deprecated(since = "1.3.0", reason = "renamed to join")]
1277 fn connect(&self, sep: &T) -> Self::Output;
1278 }
1279
1280 #[unstable(feature = "slice_concat_ext",
1281 reason = "trait should not have to exist",
1282 issue = "27747")]
1283 impl<T: Clone, V: Borrow<[T]>> SliceConcatExt<T> for [V] {
1284 type Output = Vec<T>;
1285
1286 fn concat(&self) -> Vec<T> {
1287 let size = self.iter().fold(0, |acc, v| acc + v.borrow().len());
1288 let mut result = Vec::with_capacity(size);
1289 for v in self {
1290 result.extend_from_slice(v.borrow())
1291 }
1292 result
1293 }
1294
1295 fn join(&self, sep: &T) -> Vec<T> {
1296 let size = self.iter().fold(0, |acc, v| acc + v.borrow().len());
1297 let mut result = Vec::with_capacity(size + self.len());
1298 let mut first = true;
1299 for v in self {
1300 if first {
1301 first = false
1302 } else {
1303 result.push(sep.clone())
1304 }
1305 result.extend_from_slice(v.borrow())
1306 }
1307 result
1308 }
1309
1310 fn connect(&self, sep: &T) -> Vec<T> {
1311 self.join(sep)
1312 }
1313 }
1314
1315 ////////////////////////////////////////////////////////////////////////////////
1316 // Standard trait implementations for slices
1317 ////////////////////////////////////////////////////////////////////////////////
1318
1319 #[stable(feature = "rust1", since = "1.0.0")]
1320 impl<T> Borrow<[T]> for Vec<T> {
1321 fn borrow(&self) -> &[T] {
1322 &self[..]
1323 }
1324 }
1325
1326 #[stable(feature = "rust1", since = "1.0.0")]
1327 impl<T> BorrowMut<[T]> for Vec<T> {
1328 fn borrow_mut(&mut self) -> &mut [T] {
1329 &mut self[..]
1330 }
1331 }
1332
1333 #[stable(feature = "rust1", since = "1.0.0")]
1334 impl<T: Clone> ToOwned for [T] {
1335 type Owned = Vec<T>;
1336 #[cfg(not(test))]
1337 fn to_owned(&self) -> Vec<T> {
1338 self.to_vec()
1339 }
1340
1341 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec`, which is required for this method
1342 // definition, is not available. Since we don't require this method for testing purposes, I'll
1343 // just stub it
1344 // NB see the slice::hack module in slice.rs for more information
1345 #[cfg(test)]
1346 fn to_owned(&self) -> Vec<T> {
1347 panic!("not available with cfg(test)")
1348 }
1349 }
1350
1351 ////////////////////////////////////////////////////////////////////////////////
1352 // Sorting
1353 ////////////////////////////////////////////////////////////////////////////////
1354
1355 /// Inserts `v[0]` into pre-sorted sequence `v[1..]` so that whole `v[..]` becomes sorted.
1356 ///
1357 /// This is the integral subroutine of insertion sort.
1358 fn insert_head<T, F>(v: &mut [T], is_less: &mut F)
1359 where F: FnMut(&T, &T) -> bool
1360 {
1361 if v.len() >= 2 && is_less(&v[1], &v[0]) {
1362 unsafe {
1363 // There are three ways to implement insertion here:
1364 //
1365 // 1. Swap adjacent elements until the first one gets to its final destination.
1366 // However, this way we copy data around more than is necessary. If elements are big
1367 // structures (costly to copy), this method will be slow.
1368 //
1369 // 2. Iterate until the right place for the first element is found. Then shift the
1370 // elements succeeding it to make room for it and finally place it into the
1371 // remaining hole. This is a good method.
1372 //
1373 // 3. Copy the first element into a temporary variable. Iterate until the right place
1374 // for it is found. As we go along, copy every traversed element into the slot
1375 // preceding it. Finally, copy data from the temporary variable into the remaining
1376 // hole. This method is very good. Benchmarks demonstrated slightly better
1377 // performance than with the 2nd method.
1378 //
1379 // All methods were benchmarked, and the 3rd showed best results. So we chose that one.
1380 let mut tmp = NoDrop { value: ptr::read(&v[0]) };
1381
1382 // Intermediate state of the insertion process is always tracked by `hole`, which
1383 // serves two purposes:
1384 // 1. Protects integrity of `v` from panics in `is_less`.
1385 // 2. Fills the remaining hole in `v` in the end.
1386 //
1387 // Panic safety:
1388 //
1389 // If `is_less` panics at any point during the process, `hole` will get dropped and
1390 // fill the hole in `v` with `tmp`, thus ensuring that `v` still holds every object it
1391 // initially held exactly once.
1392 let mut hole = InsertionHole {
1393 src: &mut tmp.value,
1394 dest: &mut v[1],
1395 };
1396 ptr::copy_nonoverlapping(&v[1], &mut v[0], 1);
1397
1398 for i in 2..v.len() {
1399 if !is_less(&v[i], &tmp.value) {
1400 break;
1401 }
1402 ptr::copy_nonoverlapping(&v[i], &mut v[i - 1], 1);
1403 hole.dest = &mut v[i];
1404 }
1405 // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
1406 }
1407 }
1408
1409 // Holds a value, but never drops it.
1410 #[allow(unions_with_drop_fields)]
1411 union NoDrop<T> {
1412 value: T
1413 }
1414
1415 // When dropped, copies from `src` into `dest`.
1416 struct InsertionHole<T> {
1417 src: *mut T,
1418 dest: *mut T,
1419 }
1420
1421 impl<T> Drop for InsertionHole<T> {
1422 fn drop(&mut self) {
1423 unsafe { ptr::copy_nonoverlapping(self.src, self.dest, 1); }
1424 }
1425 }
1426 }
1427
1428 /// Merges non-decreasing runs `v[..mid]` and `v[mid..]` using `buf` as temporary storage, and
1429 /// stores the result into `v[..]`.
1430 ///
1431 /// # Safety
1432 ///
1433 /// The two slices must be non-empty and `mid` must be in bounds. Buffer `buf` must be long enough
1434 /// to hold a copy of the shorter slice. Also, `T` must not be a zero-sized type.
1435 unsafe fn merge<T, F>(v: &mut [T], mid: usize, buf: *mut T, is_less: &mut F)
1436 where F: FnMut(&T, &T) -> bool
1437 {
1438 let len = v.len();
1439 let v = v.as_mut_ptr();
1440 let v_mid = v.offset(mid as isize);
1441 let v_end = v.offset(len as isize);
1442
1443 // The merge process first copies the shorter run into `buf`. Then it traces the newly copied
1444 // run and the longer run forwards (or backwards), comparing their next unconsumed elements and
1445 // copying the lesser (or greater) one into `v`.
1446 //
1447 // As soon as the shorter run is fully consumed, the process is done. If the longer run gets
1448 // consumed first, then we must copy whatever is left of the shorter run into the remaining
1449 // hole in `v`.
1450 //
1451 // Intermediate state of the process is always tracked by `hole`, which serves two purposes:
1452 // 1. Protects integrity of `v` from panics in `is_less`.
1453 // 2. Fills the remaining hole in `v` if the longer run gets consumed first.
1454 //
1455 // Panic safety:
1456 //
1457 // If `is_less` panics at any point during the process, `hole` will get dropped and fill the
1458 // hole in `v` with the unconsumed range in `buf`, thus ensuring that `v` still holds every
1459 // object it initially held exactly once.
1460 let mut hole;
1461
1462 if mid <= len - mid {
1463 // The left run is shorter.
1464 ptr::copy_nonoverlapping(v, buf, mid);
1465 hole = MergeHole {
1466 start: buf,
1467 end: buf.offset(mid as isize),
1468 dest: v,
1469 };
1470
1471 // Initially, these pointers point to the beginnings of their arrays.
1472 let left = &mut hole.start;
1473 let mut right = v_mid;
1474 let out = &mut hole.dest;
1475
1476 while *left < hole.end && right < v_end {
1477 // Consume the lesser side.
1478 // If equal, prefer the left run to maintain stability.
1479 let to_copy = if is_less(&*right, &**left) {
1480 get_and_increment(&mut right)
1481 } else {
1482 get_and_increment(left)
1483 };
1484 ptr::copy_nonoverlapping(to_copy, get_and_increment(out), 1);
1485 }
1486 } else {
1487 // The right run is shorter.
1488 ptr::copy_nonoverlapping(v_mid, buf, len - mid);
1489 hole = MergeHole {
1490 start: buf,
1491 end: buf.offset((len - mid) as isize),
1492 dest: v_mid,
1493 };
1494
1495 // Initially, these pointers point past the ends of their arrays.
1496 let left = &mut hole.dest;
1497 let right = &mut hole.end;
1498 let mut out = v_end;
1499
1500 while v < *left && buf < *right {
1501 // Consume the greater side.
1502 // If equal, prefer the right run to maintain stability.
1503 let to_copy = if is_less(&*right.offset(-1), &*left.offset(-1)) {
1504 decrement_and_get(left)
1505 } else {
1506 decrement_and_get(right)
1507 };
1508 ptr::copy_nonoverlapping(to_copy, decrement_and_get(&mut out), 1);
1509 }
1510 }
1511 // Finally, `hole` gets dropped. If the shorter run was not fully consumed, whatever remains of
1512 // it will now be copied into the hole in `v`.
1513
1514 unsafe fn get_and_increment<T>(ptr: &mut *mut T) -> *mut T {
1515 let old = *ptr;
1516 *ptr = ptr.offset(1);
1517 old
1518 }
1519
1520 unsafe fn decrement_and_get<T>(ptr: &mut *mut T) -> *mut T {
1521 *ptr = ptr.offset(-1);
1522 *ptr
1523 }
1524
1525 // When dropped, copies the range `start..end` into `dest..`.
1526 struct MergeHole<T> {
1527 start: *mut T,
1528 end: *mut T,
1529 dest: *mut T,
1530 }
1531
1532 impl<T> Drop for MergeHole<T> {
1533 fn drop(&mut self) {
1534 // `T` is not a zero-sized type, so it's okay to divide by it's size.
1535 let len = (self.end as usize - self.start as usize) / mem::size_of::<T>();
1536 unsafe { ptr::copy_nonoverlapping(self.start, self.dest, len); }
1537 }
1538 }
1539 }
1540
1541 /// This merge sort borrows some (but not all) ideas from TimSort, which is described in detail
1542 /// [here](http://svn.python.org/projects/python/trunk/Objects/listsort.txt).
1543 ///
1544 /// The algorithm identifies strictly descending and non-descending subsequences, which are called
1545 /// natural runs. There is a stack of pending runs yet to be merged. Each newly found run is pushed
1546 /// onto the stack, and then some pairs of adjacent runs are merged until these two invariants are
1547 /// satisfied:
1548 ///
1549 /// 1. for every `i` in `1..runs.len()`: `runs[i - 1].len > runs[i].len`
1550 /// 2. for every `i` in `2..runs.len()`: `runs[i - 2].len > runs[i - 1].len + runs[i].len`
1551 ///
1552 /// The invariants ensure that the total running time is `O(n log n)` worst-case.
1553 fn merge_sort<T, F>(v: &mut [T], mut is_less: F)
1554 where F: FnMut(&T, &T) -> bool
1555 {
1556 // Sorting has no meaningful behavior on zero-sized types.
1557 if size_of::<T>() == 0 {
1558 return;
1559 }
1560
1561 // FIXME #12092: These numbers are platform-specific and need more extensive testing/tuning.
1562 //
1563 // If `v` has length up to `max_insertion`, simply switch to insertion sort because it is going
1564 // to perform better than merge sort. For bigger types `T`, the threshold is smaller.
1565 //
1566 // Short runs are extended using insertion sort to span at least `min_run` elements, in order
1567 // to improve performance.
1568 let (max_insertion, min_run) = if size_of::<T>() <= 2 * mem::size_of::<usize>() {
1569 (64, 32)
1570 } else {
1571 (32, 16)
1572 };
1573
1574 let len = v.len();
1575
1576 // Short arrays get sorted in-place via insertion sort to avoid allocations.
1577 if len <= max_insertion {
1578 if len >= 2 {
1579 for i in (0..len-1).rev() {
1580 insert_head(&mut v[i..], &mut is_less);
1581 }
1582 }
1583 return;
1584 }
1585
1586 // Allocate a buffer to use as scratch memory. We keep the length 0 so we can keep in it
1587 // shallow copies of the contents of `v` without risking the dtors running on copies if
1588 // `is_less` panics. When merging two sorted runs, this buffer holds a copy of the shorter run,
1589 // which will always have length at most `len / 2`.
1590 let mut buf = Vec::with_capacity(len / 2);
1591
1592 // In order to identify natural runs in `v`, we traverse it backwards. That might seem like a
1593 // strange decision, but consider the fact that merges more often go in the opposite direction
1594 // (forwards). According to benchmarks, merging forwards is slightly faster than merging
1595 // backwards. To conclude, identifying runs by traversing backwards improves performance.
1596 let mut runs = vec![];
1597 let mut end = len;
1598 while end > 0 {
1599 // Find the next natural run, and reverse it if it's strictly descending.
1600 let mut start = end - 1;
1601 if start > 0 {
1602 start -= 1;
1603 unsafe {
1604 if is_less(v.get_unchecked(start + 1), v.get_unchecked(start)) {
1605 while start > 0 && is_less(v.get_unchecked(start),
1606 v.get_unchecked(start - 1)) {
1607 start -= 1;
1608 }
1609 v[start..end].reverse();
1610 } else {
1611 while start > 0 && !is_less(v.get_unchecked(start),
1612 v.get_unchecked(start - 1)) {
1613 start -= 1;
1614 }
1615 }
1616 }
1617 }
1618
1619 // Insert some more elements into the run if it's too short. Insertion sort is faster than
1620 // merge sort on short sequences, so this significantly improves performance.
1621 while start > 0 && end - start < min_run {
1622 start -= 1;
1623 insert_head(&mut v[start..end], &mut is_less);
1624 }
1625
1626 // Push this run onto the stack.
1627 runs.push(Run {
1628 start: start,
1629 len: end - start,
1630 });
1631 end = start;
1632
1633 // Merge some pairs of adjacent runs to satisfy the invariants.
1634 while let Some(r) = collapse(&runs) {
1635 let left = runs[r + 1];
1636 let right = runs[r];
1637 unsafe {
1638 merge(&mut v[left.start .. right.start + right.len], left.len, buf.as_mut_ptr(),
1639 &mut is_less);
1640 }
1641 runs[r] = Run {
1642 start: left.start,
1643 len: left.len + right.len,
1644 };
1645 runs.remove(r + 1);
1646 }
1647 }
1648
1649 // Finally, exactly one run must remain in the stack.
1650 debug_assert!(runs.len() == 1 && runs[0].start == 0 && runs[0].len == len);
1651
1652 // Examines the stack of runs and identifies the next pair of runs to merge. More specifically,
1653 // if `Some(r)` is returned, that means `runs[r]` and `runs[r + 1]` must be merged next. If the
1654 // algorithm should continue building a new run instead, `None` is returned.
1655 //
1656 // TimSort is infamous for it's buggy implementations, as described here:
1657 // http://envisage-project.eu/timsort-specification-and-verification/
1658 //
1659 // The gist of the story is: we must enforce the invariants on the top four runs on the stack.
1660 // Enforcing them on just top three is not sufficient to ensure that the invariants will still
1661 // hold for *all* runs in the stack.
1662 //
1663 // This function correctly checks invariants for the top four runs. Additionally, if the top
1664 // run starts at index 0, it will always demand a merge operation until the stack is fully
1665 // collapsed, in order to complete the sort.
1666 #[inline]
1667 fn collapse(runs: &[Run]) -> Option<usize> {
1668 let n = runs.len();
1669 if n >= 2 && (runs[n - 1].start == 0 ||
1670 runs[n - 2].len <= runs[n - 1].len ||
1671 (n >= 3 && runs[n - 3].len <= runs[n - 2].len + runs[n - 1].len) ||
1672 (n >= 4 && runs[n - 4].len <= runs[n - 3].len + runs[n - 2].len)) {
1673 if n >= 3 && runs[n - 3].len < runs[n - 1].len {
1674 Some(n - 3)
1675 } else {
1676 Some(n - 2)
1677 }
1678 } else {
1679 None
1680 }
1681 }
1682
1683 #[derive(Clone, Copy)]
1684 struct Run {
1685 start: usize,
1686 len: usize,
1687 }
1688 }