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