]> git.lizzy.rs Git - rust.git/blob - src/libcore/slice/mod.rs
reduce list to functions callable in const ctx.
[rust.git] / src / libcore / slice / mod.rs
1 // Copyright 2012-2017 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 //! Slice management and manipulation
12 //!
13 //! For more details see [`std::slice`].
14 //!
15 //! [`std::slice`]: ../../std/slice/index.html
16
17 #![stable(feature = "rust1", since = "1.0.0")]
18
19 // How this module is organized.
20 //
21 // The library infrastructure for slices is fairly messy. There's
22 // a lot of stuff defined here. Let's keep it clean.
23 //
24 // The layout of this file is thus:
25 //
26 // * Inherent methods. This is where most of the slice API resides.
27 // * Implementations of a few common traits with important slice ops.
28 // * Definitions of a bunch of iterators.
29 // * Free functions.
30 // * The `raw` and `bytes` submodules.
31 // * Boilerplate trait implementations.
32
33 use cmp::Ordering::{self, Less, Equal, Greater};
34 use cmp;
35 use fmt;
36 use intrinsics::assume;
37 use isize;
38 use iter::*;
39 use ops::{FnMut, Try, self};
40 use option::Option;
41 use option::Option::{None, Some};
42 use result::Result;
43 use result::Result::{Ok, Err};
44 use ptr;
45 use mem;
46 use marker::{Copy, Send, Sync, Sized, self};
47 use iter_private::TrustedRandomAccess;
48
49 #[unstable(feature = "slice_internals", issue = "0",
50            reason = "exposed from core to be reused in std; use the memchr crate")]
51 /// Pure rust memchr implementation, taken from rust-memchr
52 pub mod memchr;
53
54 mod rotate;
55 mod sort;
56
57 #[repr(C)]
58 union Repr<'a, T: 'a> {
59     rust: &'a [T],
60     rust_mut: &'a mut [T],
61     raw: FatPtr<T>,
62 }
63
64 #[repr(C)]
65 struct FatPtr<T> {
66     data: *const T,
67     len: usize,
68 }
69
70 //
71 // Extension traits
72 //
73
74 #[lang = "slice"]
75 #[cfg(not(test))]
76 impl<T> [T] {
77     /// Returns the number of elements in the slice.
78     ///
79     /// # Examples
80     ///
81     /// ```
82     /// let a = [1, 2, 3];
83     /// assert_eq!(a.len(), 3);
84     /// ```
85     #[stable(feature = "rust1", since = "1.0.0")]
86     #[inline]
87     #[rustc_const_unstable(feature = "const_slice_len")]
88     pub const fn len(&self) -> usize {
89         unsafe {
90             Repr { rust: self }.raw.len
91         }
92     }
93
94     /// Returns `true` if the slice has a length of 0.
95     ///
96     /// # Examples
97     ///
98     /// ```
99     /// let a = [1, 2, 3];
100     /// assert!(!a.is_empty());
101     /// ```
102     #[stable(feature = "rust1", since = "1.0.0")]
103     #[inline]
104     #[rustc_const_unstable(feature = "const_slice_len")]
105     pub const fn is_empty(&self) -> bool {
106         self.len() == 0
107     }
108
109     /// Returns the first element of the slice, or `None` if it is empty.
110     ///
111     /// # Examples
112     ///
113     /// ```
114     /// let v = [10, 40, 30];
115     /// assert_eq!(Some(&10), v.first());
116     ///
117     /// let w: &[i32] = &[];
118     /// assert_eq!(None, w.first());
119     /// ```
120     #[stable(feature = "rust1", since = "1.0.0")]
121     #[inline]
122     pub fn first(&self) -> Option<&T> {
123         self.get(0)
124     }
125
126     /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
127     ///
128     /// # Examples
129     ///
130     /// ```
131     /// let x = &mut [0, 1, 2];
132     ///
133     /// if let Some(first) = x.first_mut() {
134     ///     *first = 5;
135     /// }
136     /// assert_eq!(x, &[5, 1, 2]);
137     /// ```
138     #[stable(feature = "rust1", since = "1.0.0")]
139     #[inline]
140     pub fn first_mut(&mut self) -> Option<&mut T> {
141         self.get_mut(0)
142     }
143
144     /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
145     ///
146     /// # Examples
147     ///
148     /// ```
149     /// let x = &[0, 1, 2];
150     ///
151     /// if let Some((first, elements)) = x.split_first() {
152     ///     assert_eq!(first, &0);
153     ///     assert_eq!(elements, &[1, 2]);
154     /// }
155     /// ```
156     #[stable(feature = "slice_splits", since = "1.5.0")]
157     #[inline]
158     pub fn split_first(&self) -> Option<(&T, &[T])> {
159         if self.is_empty() { None } else { Some((&self[0], &self[1..])) }
160     }
161
162     /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
163     ///
164     /// # Examples
165     ///
166     /// ```
167     /// let x = &mut [0, 1, 2];
168     ///
169     /// if let Some((first, elements)) = x.split_first_mut() {
170     ///     *first = 3;
171     ///     elements[0] = 4;
172     ///     elements[1] = 5;
173     /// }
174     /// assert_eq!(x, &[3, 4, 5]);
175     /// ```
176     #[stable(feature = "slice_splits", since = "1.5.0")]
177     #[inline]
178     pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
179         if self.is_empty() { None } else {
180             let split = self.split_at_mut(1);
181             Some((&mut split.0[0], split.1))
182         }
183     }
184
185     /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
186     ///
187     /// # Examples
188     ///
189     /// ```
190     /// let x = &[0, 1, 2];
191     ///
192     /// if let Some((last, elements)) = x.split_last() {
193     ///     assert_eq!(last, &2);
194     ///     assert_eq!(elements, &[0, 1]);
195     /// }
196     /// ```
197     #[stable(feature = "slice_splits", since = "1.5.0")]
198     #[inline]
199     pub fn split_last(&self) -> Option<(&T, &[T])> {
200         let len = self.len();
201         if len == 0 { None } else { Some((&self[len - 1], &self[..(len - 1)])) }
202     }
203
204     /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
205     ///
206     /// # Examples
207     ///
208     /// ```
209     /// let x = &mut [0, 1, 2];
210     ///
211     /// if let Some((last, elements)) = x.split_last_mut() {
212     ///     *last = 3;
213     ///     elements[0] = 4;
214     ///     elements[1] = 5;
215     /// }
216     /// assert_eq!(x, &[4, 5, 3]);
217     /// ```
218     #[stable(feature = "slice_splits", since = "1.5.0")]
219     #[inline]
220     pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
221         let len = self.len();
222         if len == 0 { None } else {
223             let split = self.split_at_mut(len - 1);
224             Some((&mut split.1[0], split.0))
225         }
226
227     }
228
229     /// Returns the last element of the slice, or `None` if it is empty.
230     ///
231     /// # Examples
232     ///
233     /// ```
234     /// let v = [10, 40, 30];
235     /// assert_eq!(Some(&30), v.last());
236     ///
237     /// let w: &[i32] = &[];
238     /// assert_eq!(None, w.last());
239     /// ```
240     #[stable(feature = "rust1", since = "1.0.0")]
241     #[inline]
242     pub fn last(&self) -> Option<&T> {
243         let last_idx = self.len().checked_sub(1)?;
244         self.get(last_idx)
245     }
246
247     /// Returns a mutable pointer to the last item in the slice.
248     ///
249     /// # Examples
250     ///
251     /// ```
252     /// let x = &mut [0, 1, 2];
253     ///
254     /// if let Some(last) = x.last_mut() {
255     ///     *last = 10;
256     /// }
257     /// assert_eq!(x, &[0, 1, 10]);
258     /// ```
259     #[stable(feature = "rust1", since = "1.0.0")]
260     #[inline]
261     pub fn last_mut(&mut self) -> Option<&mut T> {
262         let last_idx = self.len().checked_sub(1)?;
263         self.get_mut(last_idx)
264     }
265
266     /// Returns a reference to an element or subslice depending on the type of
267     /// index.
268     ///
269     /// - If given a position, returns a reference to the element at that
270     ///   position or `None` if out of bounds.
271     /// - If given a range, returns the subslice corresponding to that range,
272     ///   or `None` if out of bounds.
273     ///
274     /// # Examples
275     ///
276     /// ```
277     /// let v = [10, 40, 30];
278     /// assert_eq!(Some(&40), v.get(1));
279     /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
280     /// assert_eq!(None, v.get(3));
281     /// assert_eq!(None, v.get(0..4));
282     /// ```
283     #[stable(feature = "rust1", since = "1.0.0")]
284     #[inline]
285     pub fn get<I>(&self, index: I) -> Option<&I::Output>
286         where I: SliceIndex<Self>
287     {
288         index.get(self)
289     }
290
291     /// Returns a mutable reference to an element or subslice depending on the
292     /// type of index (see [`get`]) or `None` if the index is out of bounds.
293     ///
294     /// [`get`]: #method.get
295     ///
296     /// # Examples
297     ///
298     /// ```
299     /// let x = &mut [0, 1, 2];
300     ///
301     /// if let Some(elem) = x.get_mut(1) {
302     ///     *elem = 42;
303     /// }
304     /// assert_eq!(x, &[0, 42, 2]);
305     /// ```
306     #[stable(feature = "rust1", since = "1.0.0")]
307     #[inline]
308     pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
309         where I: SliceIndex<Self>
310     {
311         index.get_mut(self)
312     }
313
314     /// Returns a reference to an element or subslice, without doing bounds
315     /// checking.
316     ///
317     /// This is generally not recommended, use with caution! For a safe
318     /// alternative see [`get`].
319     ///
320     /// [`get`]: #method.get
321     ///
322     /// # Examples
323     ///
324     /// ```
325     /// let x = &[1, 2, 4];
326     ///
327     /// unsafe {
328     ///     assert_eq!(x.get_unchecked(1), &2);
329     /// }
330     /// ```
331     #[stable(feature = "rust1", since = "1.0.0")]
332     #[inline]
333     pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
334         where I: SliceIndex<Self>
335     {
336         index.get_unchecked(self)
337     }
338
339     /// Returns a mutable reference to an element or subslice, without doing
340     /// bounds checking.
341     ///
342     /// This is generally not recommended, use with caution! For a safe
343     /// alternative see [`get_mut`].
344     ///
345     /// [`get_mut`]: #method.get_mut
346     ///
347     /// # Examples
348     ///
349     /// ```
350     /// let x = &mut [1, 2, 4];
351     ///
352     /// unsafe {
353     ///     let elem = x.get_unchecked_mut(1);
354     ///     *elem = 13;
355     /// }
356     /// assert_eq!(x, &[1, 13, 4]);
357     /// ```
358     #[stable(feature = "rust1", since = "1.0.0")]
359     #[inline]
360     pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
361         where I: SliceIndex<Self>
362     {
363         index.get_unchecked_mut(self)
364     }
365
366     /// Returns a raw pointer to the slice's buffer.
367     ///
368     /// The caller must ensure that the slice outlives the pointer this
369     /// function returns, or else it will end up pointing to garbage.
370     ///
371     /// Modifying the container referenced by this slice may cause its buffer
372     /// to be reallocated, which would also make any pointers to it invalid.
373     ///
374     /// # Examples
375     ///
376     /// ```
377     /// let x = &[1, 2, 4];
378     /// let x_ptr = x.as_ptr();
379     ///
380     /// unsafe {
381     ///     for i in 0..x.len() {
382     ///         assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
383     ///     }
384     /// }
385     /// ```
386     #[stable(feature = "rust1", since = "1.0.0")]
387     #[inline]
388     pub const fn as_ptr(&self) -> *const T {
389         self as *const [T] as *const T
390     }
391
392     /// Returns an unsafe mutable pointer to the slice's buffer.
393     ///
394     /// The caller must ensure that the slice outlives the pointer this
395     /// function returns, or else it will end up pointing to garbage.
396     ///
397     /// Modifying the container referenced by this slice may cause its buffer
398     /// to be reallocated, which would also make any pointers to it invalid.
399     ///
400     /// # Examples
401     ///
402     /// ```
403     /// let x = &mut [1, 2, 4];
404     /// let x_ptr = x.as_mut_ptr();
405     ///
406     /// unsafe {
407     ///     for i in 0..x.len() {
408     ///         *x_ptr.add(i) += 2;
409     ///     }
410     /// }
411     /// assert_eq!(x, &[3, 4, 6]);
412     /// ```
413     #[stable(feature = "rust1", since = "1.0.0")]
414     #[inline]
415     pub fn as_mut_ptr(&mut self) -> *mut T {
416         self as *mut [T] as *mut T
417     }
418
419     /// Swaps two elements in the slice.
420     ///
421     /// # Arguments
422     ///
423     /// * a - The index of the first element
424     /// * b - The index of the second element
425     ///
426     /// # Panics
427     ///
428     /// Panics if `a` or `b` are out of bounds.
429     ///
430     /// # Examples
431     ///
432     /// ```
433     /// let mut v = ["a", "b", "c", "d"];
434     /// v.swap(1, 3);
435     /// assert!(v == ["a", "d", "c", "b"]);
436     /// ```
437     #[stable(feature = "rust1", since = "1.0.0")]
438     #[inline]
439     pub fn swap(&mut self, a: usize, b: usize) {
440         unsafe {
441             // Can't take two mutable loans from one vector, so instead just cast
442             // them to their raw pointers to do the swap
443             let pa: *mut T = &mut self[a];
444             let pb: *mut T = &mut self[b];
445             ptr::swap(pa, pb);
446         }
447     }
448
449     /// Reverses the order of elements in the slice, in place.
450     ///
451     /// # Examples
452     ///
453     /// ```
454     /// let mut v = [1, 2, 3];
455     /// v.reverse();
456     /// assert!(v == [3, 2, 1]);
457     /// ```
458     #[stable(feature = "rust1", since = "1.0.0")]
459     #[inline]
460     pub fn reverse(&mut self) {
461         let mut i: usize = 0;
462         let ln = self.len();
463
464         // For very small types, all the individual reads in the normal
465         // path perform poorly.  We can do better, given efficient unaligned
466         // load/store, by loading a larger chunk and reversing a register.
467
468         // Ideally LLVM would do this for us, as it knows better than we do
469         // whether unaligned reads are efficient (since that changes between
470         // different ARM versions, for example) and what the best chunk size
471         // would be.  Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
472         // the loop, so we need to do this ourselves.  (Hypothesis: reverse
473         // is troublesome because the sides can be aligned differently --
474         // will be, when the length is odd -- so there's no way of emitting
475         // pre- and postludes to use fully-aligned SIMD in the middle.)
476
477         let fast_unaligned =
478             cfg!(any(target_arch = "x86", target_arch = "x86_64"));
479
480         if fast_unaligned && mem::size_of::<T>() == 1 {
481             // Use the llvm.bswap intrinsic to reverse u8s in a usize
482             let chunk = mem::size_of::<usize>();
483             while i + chunk - 1 < ln / 2 {
484                 unsafe {
485                     let pa: *mut T = self.get_unchecked_mut(i);
486                     let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
487                     let va = ptr::read_unaligned(pa as *mut usize);
488                     let vb = ptr::read_unaligned(pb as *mut usize);
489                     ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
490                     ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
491                 }
492                 i += chunk;
493             }
494         }
495
496         if fast_unaligned && mem::size_of::<T>() == 2 {
497             // Use rotate-by-16 to reverse u16s in a u32
498             let chunk = mem::size_of::<u32>() / 2;
499             while i + chunk - 1 < ln / 2 {
500                 unsafe {
501                     let pa: *mut T = self.get_unchecked_mut(i);
502                     let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
503                     let va = ptr::read_unaligned(pa as *mut u32);
504                     let vb = ptr::read_unaligned(pb as *mut u32);
505                     ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
506                     ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
507                 }
508                 i += chunk;
509             }
510         }
511
512         while i < ln / 2 {
513             // Unsafe swap to avoid the bounds check in safe swap.
514             unsafe {
515                 let pa: *mut T = self.get_unchecked_mut(i);
516                 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
517                 ptr::swap(pa, pb);
518             }
519             i += 1;
520         }
521     }
522
523     /// Returns an iterator over the slice.
524     ///
525     /// # Examples
526     ///
527     /// ```
528     /// let x = &[1, 2, 4];
529     /// let mut iterator = x.iter();
530     ///
531     /// assert_eq!(iterator.next(), Some(&1));
532     /// assert_eq!(iterator.next(), Some(&2));
533     /// assert_eq!(iterator.next(), Some(&4));
534     /// assert_eq!(iterator.next(), None);
535     /// ```
536     #[stable(feature = "rust1", since = "1.0.0")]
537     #[inline]
538     pub fn iter(&self) -> Iter<T> {
539         unsafe {
540             let ptr = self.as_ptr();
541             assume(!ptr.is_null());
542
543             let end = if mem::size_of::<T>() == 0 {
544                 (ptr as *const u8).wrapping_add(self.len()) as *const T
545             } else {
546                 ptr.add(self.len())
547             };
548
549             Iter {
550                 ptr,
551                 end,
552                 _marker: marker::PhantomData
553             }
554         }
555     }
556
557     /// Returns an iterator that allows modifying each value.
558     ///
559     /// # Examples
560     ///
561     /// ```
562     /// let x = &mut [1, 2, 4];
563     /// for elem in x.iter_mut() {
564     ///     *elem += 2;
565     /// }
566     /// assert_eq!(x, &[3, 4, 6]);
567     /// ```
568     #[stable(feature = "rust1", since = "1.0.0")]
569     #[inline]
570     pub fn iter_mut(&mut self) -> IterMut<T> {
571         unsafe {
572             let ptr = self.as_mut_ptr();
573             assume(!ptr.is_null());
574
575             let end = if mem::size_of::<T>() == 0 {
576                 (ptr as *mut u8).wrapping_add(self.len()) as *mut T
577             } else {
578                 ptr.add(self.len())
579             };
580
581             IterMut {
582                 ptr,
583                 end,
584                 _marker: marker::PhantomData
585             }
586         }
587     }
588
589     /// Returns an iterator over all contiguous windows of length
590     /// `size`. The windows overlap. If the slice is shorter than
591     /// `size`, the iterator returns no values.
592     ///
593     /// # Panics
594     ///
595     /// Panics if `size` is 0.
596     ///
597     /// # Examples
598     ///
599     /// ```
600     /// let slice = ['r', 'u', 's', 't'];
601     /// let mut iter = slice.windows(2);
602     /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
603     /// assert_eq!(iter.next().unwrap(), &['u', 's']);
604     /// assert_eq!(iter.next().unwrap(), &['s', 't']);
605     /// assert!(iter.next().is_none());
606     /// ```
607     ///
608     /// If the slice is shorter than `size`:
609     ///
610     /// ```
611     /// let slice = ['f', 'o', 'o'];
612     /// let mut iter = slice.windows(4);
613     /// assert!(iter.next().is_none());
614     /// ```
615     #[stable(feature = "rust1", since = "1.0.0")]
616     #[inline]
617     pub fn windows(&self, size: usize) -> Windows<T> {
618         assert!(size != 0);
619         Windows { v: self, size }
620     }
621
622     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
623     /// beginning of the slice.
624     ///
625     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
626     /// slice, then the last chunk will not have length `chunk_size`.
627     ///
628     /// See [`chunks_exact`] for a variant of this iterator that returns chunks of always exactly
629     /// `chunk_size` elements, and [`rchunks`] for the same iterator but starting at the end of the
630     /// slice of the slice.
631     ///
632     /// # Panics
633     ///
634     /// Panics if `chunk_size` is 0.
635     ///
636     /// # Examples
637     ///
638     /// ```
639     /// let slice = ['l', 'o', 'r', 'e', 'm'];
640     /// let mut iter = slice.chunks(2);
641     /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
642     /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
643     /// assert_eq!(iter.next().unwrap(), &['m']);
644     /// assert!(iter.next().is_none());
645     /// ```
646     ///
647     /// [`chunks_exact`]: #method.chunks_exact
648     /// [`rchunks`]: #method.rchunks
649     #[stable(feature = "rust1", since = "1.0.0")]
650     #[inline]
651     pub fn chunks(&self, chunk_size: usize) -> Chunks<T> {
652         assert!(chunk_size != 0);
653         Chunks { v: self, chunk_size }
654     }
655
656     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
657     /// beginning of the slice.
658     ///
659     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
660     /// length of the slice, then the last chunk will not have length `chunk_size`.
661     ///
662     /// See [`chunks_exact_mut`] for a variant of this iterator that returns chunks of always
663     /// exactly `chunk_size` elements, and [`rchunks_mut`] for the same iterator but starting at
664     /// the end of the slice of the slice.
665     ///
666     /// # Panics
667     ///
668     /// Panics if `chunk_size` is 0.
669     ///
670     /// # Examples
671     ///
672     /// ```
673     /// let v = &mut [0, 0, 0, 0, 0];
674     /// let mut count = 1;
675     ///
676     /// for chunk in v.chunks_mut(2) {
677     ///     for elem in chunk.iter_mut() {
678     ///         *elem += count;
679     ///     }
680     ///     count += 1;
681     /// }
682     /// assert_eq!(v, &[1, 1, 2, 2, 3]);
683     /// ```
684     ///
685     /// [`chunks_exact_mut`]: #method.chunks_exact_mut
686     /// [`rchunks_mut`]: #method.rchunks_mut
687     #[stable(feature = "rust1", since = "1.0.0")]
688     #[inline]
689     pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
690         assert!(chunk_size != 0);
691         ChunksMut { v: self, chunk_size }
692     }
693
694     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
695     /// beginning of the slice.
696     ///
697     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
698     /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
699     /// from the `remainder` function of the iterator.
700     ///
701     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
702     /// resulting code better than in the case of [`chunks`].
703     ///
704     /// See [`chunks`] for a variant of this iterator that also returns the remainder as a smaller
705     /// chunk, and [`rchunks_exact`] for the same iterator but starting at the end of the slice of
706     /// the slice.
707     ///
708     /// # Panics
709     ///
710     /// Panics if `chunk_size` is 0.
711     ///
712     /// # Examples
713     ///
714     /// ```
715     /// let slice = ['l', 'o', 'r', 'e', 'm'];
716     /// let mut iter = slice.chunks_exact(2);
717     /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
718     /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
719     /// assert!(iter.next().is_none());
720     /// assert_eq!(iter.remainder(), &['m']);
721     /// ```
722     ///
723     /// [`chunks`]: #method.chunks
724     /// [`rchunks_exact`]: #method.rchunks_exact
725     #[stable(feature = "chunks_exact", since = "1.31.0")]
726     #[inline]
727     pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<T> {
728         assert!(chunk_size != 0);
729         let rem = self.len() % chunk_size;
730         let len = self.len() - rem;
731         let (fst, snd) = self.split_at(len);
732         ChunksExact { v: fst, rem: snd, chunk_size }
733     }
734
735     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
736     /// beginning of the slice.
737     ///
738     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
739     /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
740     /// retrieved from the `into_remainder` function of the iterator.
741     ///
742     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
743     /// resulting code better than in the case of [`chunks_mut`].
744     ///
745     /// See [`chunks_mut`] for a variant of this iterator that also returns the remainder as a
746     /// smaller chunk, and [`rchunks_exact_mut`] for the same iterator but starting at the end of
747     /// the slice of the slice.
748     ///
749     /// # Panics
750     ///
751     /// Panics if `chunk_size` is 0.
752     ///
753     /// # Examples
754     ///
755     /// ```
756     /// let v = &mut [0, 0, 0, 0, 0];
757     /// let mut count = 1;
758     ///
759     /// for chunk in v.chunks_exact_mut(2) {
760     ///     for elem in chunk.iter_mut() {
761     ///         *elem += count;
762     ///     }
763     ///     count += 1;
764     /// }
765     /// assert_eq!(v, &[1, 1, 2, 2, 0]);
766     /// ```
767     ///
768     /// [`chunks_mut`]: #method.chunks_mut
769     /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
770     #[stable(feature = "chunks_exact", since = "1.31.0")]
771     #[inline]
772     pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<T> {
773         assert!(chunk_size != 0);
774         let rem = self.len() % chunk_size;
775         let len = self.len() - rem;
776         let (fst, snd) = self.split_at_mut(len);
777         ChunksExactMut { v: fst, rem: snd, chunk_size }
778     }
779
780     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
781     /// of the slice.
782     ///
783     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
784     /// slice, then the last chunk will not have length `chunk_size`.
785     ///
786     /// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always exactly
787     /// `chunk_size` elements, and [`chunks`] for the same iterator but starting at the beginning
788     /// of the slice.
789     ///
790     /// # Panics
791     ///
792     /// Panics if `chunk_size` is 0.
793     ///
794     /// # Examples
795     ///
796     /// ```
797     /// let slice = ['l', 'o', 'r', 'e', 'm'];
798     /// let mut iter = slice.rchunks(2);
799     /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
800     /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
801     /// assert_eq!(iter.next().unwrap(), &['l']);
802     /// assert!(iter.next().is_none());
803     /// ```
804     ///
805     /// [`rchunks_exact`]: #method.rchunks_exact
806     /// [`chunks`]: #method.chunks
807     #[stable(feature = "rchunks", since = "1.31.0")]
808     #[inline]
809     pub fn rchunks(&self, chunk_size: usize) -> RChunks<T> {
810         assert!(chunk_size != 0);
811         RChunks { v: self, chunk_size }
812     }
813
814     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
815     /// of the slice.
816     ///
817     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
818     /// length of the slice, then the last chunk will not have length `chunk_size`.
819     ///
820     /// See [`rchunks_exact_mut`] for a variant of this iterator that returns chunks of always
821     /// exactly `chunk_size` elements, and [`chunks_mut`] for the same iterator but starting at the
822     /// beginning of the slice.
823     ///
824     /// # Panics
825     ///
826     /// Panics if `chunk_size` is 0.
827     ///
828     /// # Examples
829     ///
830     /// ```
831     /// let v = &mut [0, 0, 0, 0, 0];
832     /// let mut count = 1;
833     ///
834     /// for chunk in v.rchunks_mut(2) {
835     ///     for elem in chunk.iter_mut() {
836     ///         *elem += count;
837     ///     }
838     ///     count += 1;
839     /// }
840     /// assert_eq!(v, &[3, 2, 2, 1, 1]);
841     /// ```
842     ///
843     /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
844     /// [`chunks_mut`]: #method.chunks_mut
845     #[stable(feature = "rchunks", since = "1.31.0")]
846     #[inline]
847     pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<T> {
848         assert!(chunk_size != 0);
849         RChunksMut { v: self, chunk_size }
850     }
851
852     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
853     /// beginning of the slice.
854     ///
855     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
856     /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
857     /// from the `remainder` function of the iterator.
858     ///
859     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
860     /// resulting code better than in the case of [`chunks`].
861     ///
862     /// See [`rchunks`] for a variant of this iterator that also returns the remainder as a smaller
863     /// chunk, and [`chunks_exact`] for the same iterator but starting at the beginning of the
864     /// slice of the slice.
865     ///
866     /// # Panics
867     ///
868     /// Panics if `chunk_size` is 0.
869     ///
870     /// # Examples
871     ///
872     /// ```
873     /// let slice = ['l', 'o', 'r', 'e', 'm'];
874     /// let mut iter = slice.rchunks_exact(2);
875     /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
876     /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
877     /// assert!(iter.next().is_none());
878     /// assert_eq!(iter.remainder(), &['l']);
879     /// ```
880     ///
881     /// [`rchunks`]: #method.rchunks
882     /// [`chunks_exact`]: #method.chunks_exact
883     #[stable(feature = "rchunks", since = "1.31.0")]
884     #[inline]
885     pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<T> {
886         assert!(chunk_size != 0);
887         let rem = self.len() % chunk_size;
888         let (fst, snd) = self.split_at(rem);
889         RChunksExact { v: snd, rem: fst, chunk_size }
890     }
891
892     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
893     /// of the slice.
894     ///
895     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
896     /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
897     /// retrieved from the `into_remainder` function of the iterator.
898     ///
899     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
900     /// resulting code better than in the case of [`chunks_mut`].
901     ///
902     /// See [`rchunks_mut`] for a variant of this iterator that also returns the remainder as a
903     /// smaller chunk, and [`chunks_exact_mut`] for the same iterator but starting at the beginning
904     /// of the slice of the slice.
905     ///
906     /// # Panics
907     ///
908     /// Panics if `chunk_size` is 0.
909     ///
910     /// # Examples
911     ///
912     /// ```
913     /// let v = &mut [0, 0, 0, 0, 0];
914     /// let mut count = 1;
915     ///
916     /// for chunk in v.rchunks_exact_mut(2) {
917     ///     for elem in chunk.iter_mut() {
918     ///         *elem += count;
919     ///     }
920     ///     count += 1;
921     /// }
922     /// assert_eq!(v, &[0, 2, 2, 1, 1]);
923     /// ```
924     ///
925     /// [`rchunks_mut`]: #method.rchunks_mut
926     /// [`chunks_exact_mut`]: #method.chunks_exact_mut
927     #[stable(feature = "rchunks", since = "1.31.0")]
928     #[inline]
929     pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<T> {
930         assert!(chunk_size != 0);
931         let rem = self.len() % chunk_size;
932         let (fst, snd) = self.split_at_mut(rem);
933         RChunksExactMut { v: snd, rem: fst, chunk_size }
934     }
935
936     /// Divides one slice into two at an index.
937     ///
938     /// The first will contain all indices from `[0, mid)` (excluding
939     /// the index `mid` itself) and the second will contain all
940     /// indices from `[mid, len)` (excluding the index `len` itself).
941     ///
942     /// # Panics
943     ///
944     /// Panics if `mid > len`.
945     ///
946     /// # Examples
947     ///
948     /// ```
949     /// let v = [1, 2, 3, 4, 5, 6];
950     ///
951     /// {
952     ///    let (left, right) = v.split_at(0);
953     ///    assert!(left == []);
954     ///    assert!(right == [1, 2, 3, 4, 5, 6]);
955     /// }
956     ///
957     /// {
958     ///     let (left, right) = v.split_at(2);
959     ///     assert!(left == [1, 2]);
960     ///     assert!(right == [3, 4, 5, 6]);
961     /// }
962     ///
963     /// {
964     ///     let (left, right) = v.split_at(6);
965     ///     assert!(left == [1, 2, 3, 4, 5, 6]);
966     ///     assert!(right == []);
967     /// }
968     /// ```
969     #[stable(feature = "rust1", since = "1.0.0")]
970     #[inline]
971     pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
972         (&self[..mid], &self[mid..])
973     }
974
975     /// Divides one mutable slice into two at an index.
976     ///
977     /// The first will contain all indices from `[0, mid)` (excluding
978     /// the index `mid` itself) and the second will contain all
979     /// indices from `[mid, len)` (excluding the index `len` itself).
980     ///
981     /// # Panics
982     ///
983     /// Panics if `mid > len`.
984     ///
985     /// # Examples
986     ///
987     /// ```
988     /// let mut v = [1, 0, 3, 0, 5, 6];
989     /// // scoped to restrict the lifetime of the borrows
990     /// {
991     ///     let (left, right) = v.split_at_mut(2);
992     ///     assert!(left == [1, 0]);
993     ///     assert!(right == [3, 0, 5, 6]);
994     ///     left[1] = 2;
995     ///     right[1] = 4;
996     /// }
997     /// assert!(v == [1, 2, 3, 4, 5, 6]);
998     /// ```
999     #[stable(feature = "rust1", since = "1.0.0")]
1000     #[inline]
1001     pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1002         let len = self.len();
1003         let ptr = self.as_mut_ptr();
1004
1005         unsafe {
1006             assert!(mid <= len);
1007
1008             (from_raw_parts_mut(ptr, mid),
1009              from_raw_parts_mut(ptr.add(mid), len - mid))
1010         }
1011     }
1012
1013     /// Returns an iterator over subslices separated by elements that match
1014     /// `pred`. The matched element is not contained in the subslices.
1015     ///
1016     /// # Examples
1017     ///
1018     /// ```
1019     /// let slice = [10, 40, 33, 20];
1020     /// let mut iter = slice.split(|num| num % 3 == 0);
1021     ///
1022     /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1023     /// assert_eq!(iter.next().unwrap(), &[20]);
1024     /// assert!(iter.next().is_none());
1025     /// ```
1026     ///
1027     /// If the first element is matched, an empty slice will be the first item
1028     /// returned by the iterator. Similarly, if the last element in the slice
1029     /// is matched, an empty slice will be the last item returned by the
1030     /// iterator:
1031     ///
1032     /// ```
1033     /// let slice = [10, 40, 33];
1034     /// let mut iter = slice.split(|num| num % 3 == 0);
1035     ///
1036     /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1037     /// assert_eq!(iter.next().unwrap(), &[]);
1038     /// assert!(iter.next().is_none());
1039     /// ```
1040     ///
1041     /// If two matched elements are directly adjacent, an empty slice will be
1042     /// present between them:
1043     ///
1044     /// ```
1045     /// let slice = [10, 6, 33, 20];
1046     /// let mut iter = slice.split(|num| num % 3 == 0);
1047     ///
1048     /// assert_eq!(iter.next().unwrap(), &[10]);
1049     /// assert_eq!(iter.next().unwrap(), &[]);
1050     /// assert_eq!(iter.next().unwrap(), &[20]);
1051     /// assert!(iter.next().is_none());
1052     /// ```
1053     #[stable(feature = "rust1", since = "1.0.0")]
1054     #[inline]
1055     pub fn split<F>(&self, pred: F) -> Split<T, F>
1056         where F: FnMut(&T) -> bool
1057     {
1058         Split {
1059             v: self,
1060             pred,
1061             finished: false
1062         }
1063     }
1064
1065     /// Returns an iterator over mutable subslices separated by elements that
1066     /// match `pred`. The matched element is not contained in the subslices.
1067     ///
1068     /// # Examples
1069     ///
1070     /// ```
1071     /// let mut v = [10, 40, 30, 20, 60, 50];
1072     ///
1073     /// for group in v.split_mut(|num| *num % 3 == 0) {
1074     ///     group[0] = 1;
1075     /// }
1076     /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
1077     /// ```
1078     #[stable(feature = "rust1", since = "1.0.0")]
1079     #[inline]
1080     pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F>
1081         where F: FnMut(&T) -> bool
1082     {
1083         SplitMut { v: self, pred, finished: false }
1084     }
1085
1086     /// Returns an iterator over subslices separated by elements that match
1087     /// `pred`, starting at the end of the slice and working backwards.
1088     /// The matched element is not contained in the subslices.
1089     ///
1090     /// # Examples
1091     ///
1092     /// ```
1093     /// let slice = [11, 22, 33, 0, 44, 55];
1094     /// let mut iter = slice.rsplit(|num| *num == 0);
1095     ///
1096     /// assert_eq!(iter.next().unwrap(), &[44, 55]);
1097     /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
1098     /// assert_eq!(iter.next(), None);
1099     /// ```
1100     ///
1101     /// As with `split()`, if the first or last element is matched, an empty
1102     /// slice will be the first (or last) item returned by the iterator.
1103     ///
1104     /// ```
1105     /// let v = &[0, 1, 1, 2, 3, 5, 8];
1106     /// let mut it = v.rsplit(|n| *n % 2 == 0);
1107     /// assert_eq!(it.next().unwrap(), &[]);
1108     /// assert_eq!(it.next().unwrap(), &[3, 5]);
1109     /// assert_eq!(it.next().unwrap(), &[1, 1]);
1110     /// assert_eq!(it.next().unwrap(), &[]);
1111     /// assert_eq!(it.next(), None);
1112     /// ```
1113     #[stable(feature = "slice_rsplit", since = "1.27.0")]
1114     #[inline]
1115     pub fn rsplit<F>(&self, pred: F) -> RSplit<T, F>
1116         where F: FnMut(&T) -> bool
1117     {
1118         RSplit { inner: self.split(pred) }
1119     }
1120
1121     /// Returns an iterator over mutable subslices separated by elements that
1122     /// match `pred`, starting at the end of the slice and working
1123     /// backwards. The matched element is not contained in the subslices.
1124     ///
1125     /// # Examples
1126     ///
1127     /// ```
1128     /// let mut v = [100, 400, 300, 200, 600, 500];
1129     ///
1130     /// let mut count = 0;
1131     /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
1132     ///     count += 1;
1133     ///     group[0] = count;
1134     /// }
1135     /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
1136     /// ```
1137     ///
1138     #[stable(feature = "slice_rsplit", since = "1.27.0")]
1139     #[inline]
1140     pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<T, F>
1141         where F: FnMut(&T) -> bool
1142     {
1143         RSplitMut { inner: self.split_mut(pred) }
1144     }
1145
1146     /// Returns an iterator over subslices separated by elements that match
1147     /// `pred`, limited to returning at most `n` items. The matched element is
1148     /// not contained in the subslices.
1149     ///
1150     /// The last element returned, if any, will contain the remainder of the
1151     /// slice.
1152     ///
1153     /// # Examples
1154     ///
1155     /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
1156     /// `[20, 60, 50]`):
1157     ///
1158     /// ```
1159     /// let v = [10, 40, 30, 20, 60, 50];
1160     ///
1161     /// for group in v.splitn(2, |num| *num % 3 == 0) {
1162     ///     println!("{:?}", group);
1163     /// }
1164     /// ```
1165     #[stable(feature = "rust1", since = "1.0.0")]
1166     #[inline]
1167     pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F>
1168         where F: FnMut(&T) -> bool
1169     {
1170         SplitN {
1171             inner: GenericSplitN {
1172                 iter: self.split(pred),
1173                 count: n
1174             }
1175         }
1176     }
1177
1178     /// Returns an iterator over subslices separated by elements that match
1179     /// `pred`, limited to returning at most `n` items. The matched element is
1180     /// not contained in the subslices.
1181     ///
1182     /// The last element returned, if any, will contain the remainder of the
1183     /// slice.
1184     ///
1185     /// # Examples
1186     ///
1187     /// ```
1188     /// let mut v = [10, 40, 30, 20, 60, 50];
1189     ///
1190     /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
1191     ///     group[0] = 1;
1192     /// }
1193     /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
1194     /// ```
1195     #[stable(feature = "rust1", since = "1.0.0")]
1196     #[inline]
1197     pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, F>
1198         where F: FnMut(&T) -> bool
1199     {
1200         SplitNMut {
1201             inner: GenericSplitN {
1202                 iter: self.split_mut(pred),
1203                 count: n
1204             }
1205         }
1206     }
1207
1208     /// Returns an iterator over subslices separated by elements that match
1209     /// `pred` limited to returning at most `n` items. This starts at the end of
1210     /// the slice and works backwards.  The matched element is not contained in
1211     /// the subslices.
1212     ///
1213     /// The last element returned, if any, will contain the remainder of the
1214     /// slice.
1215     ///
1216     /// # Examples
1217     ///
1218     /// Print the slice split once, starting from the end, by numbers divisible
1219     /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
1220     ///
1221     /// ```
1222     /// let v = [10, 40, 30, 20, 60, 50];
1223     ///
1224     /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
1225     ///     println!("{:?}", group);
1226     /// }
1227     /// ```
1228     #[stable(feature = "rust1", since = "1.0.0")]
1229     #[inline]
1230     pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F>
1231         where F: FnMut(&T) -> bool
1232     {
1233         RSplitN {
1234             inner: GenericSplitN {
1235                 iter: self.rsplit(pred),
1236                 count: n
1237             }
1238         }
1239     }
1240
1241     /// Returns an iterator over subslices separated by elements that match
1242     /// `pred` limited to returning at most `n` items. This starts at the end of
1243     /// the slice and works backwards. The matched element is not contained in
1244     /// the subslices.
1245     ///
1246     /// The last element returned, if any, will contain the remainder of the
1247     /// slice.
1248     ///
1249     /// # Examples
1250     ///
1251     /// ```
1252     /// let mut s = [10, 40, 30, 20, 60, 50];
1253     ///
1254     /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
1255     ///     group[0] = 1;
1256     /// }
1257     /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
1258     /// ```
1259     #[stable(feature = "rust1", since = "1.0.0")]
1260     #[inline]
1261     pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, F>
1262         where F: FnMut(&T) -> bool
1263     {
1264         RSplitNMut {
1265             inner: GenericSplitN {
1266                 iter: self.rsplit_mut(pred),
1267                 count: n
1268             }
1269         }
1270     }
1271
1272     /// Returns `true` if the slice contains an element with the given value.
1273     ///
1274     /// # Examples
1275     ///
1276     /// ```
1277     /// let v = [10, 40, 30];
1278     /// assert!(v.contains(&30));
1279     /// assert!(!v.contains(&50));
1280     /// ```
1281     #[stable(feature = "rust1", since = "1.0.0")]
1282     pub fn contains(&self, x: &T) -> bool
1283         where T: PartialEq
1284     {
1285         x.slice_contains(self)
1286     }
1287
1288     /// Returns `true` if `needle` is a prefix of the slice.
1289     ///
1290     /// # Examples
1291     ///
1292     /// ```
1293     /// let v = [10, 40, 30];
1294     /// assert!(v.starts_with(&[10]));
1295     /// assert!(v.starts_with(&[10, 40]));
1296     /// assert!(!v.starts_with(&[50]));
1297     /// assert!(!v.starts_with(&[10, 50]));
1298     /// ```
1299     ///
1300     /// Always returns `true` if `needle` is an empty slice:
1301     ///
1302     /// ```
1303     /// let v = &[10, 40, 30];
1304     /// assert!(v.starts_with(&[]));
1305     /// let v: &[u8] = &[];
1306     /// assert!(v.starts_with(&[]));
1307     /// ```
1308     #[stable(feature = "rust1", since = "1.0.0")]
1309     pub fn starts_with(&self, needle: &[T]) -> bool
1310         where T: PartialEq
1311     {
1312         let n = needle.len();
1313         self.len() >= n && needle == &self[..n]
1314     }
1315
1316     /// Returns `true` if `needle` is a suffix of the slice.
1317     ///
1318     /// # Examples
1319     ///
1320     /// ```
1321     /// let v = [10, 40, 30];
1322     /// assert!(v.ends_with(&[30]));
1323     /// assert!(v.ends_with(&[40, 30]));
1324     /// assert!(!v.ends_with(&[50]));
1325     /// assert!(!v.ends_with(&[50, 30]));
1326     /// ```
1327     ///
1328     /// Always returns `true` if `needle` is an empty slice:
1329     ///
1330     /// ```
1331     /// let v = &[10, 40, 30];
1332     /// assert!(v.ends_with(&[]));
1333     /// let v: &[u8] = &[];
1334     /// assert!(v.ends_with(&[]));
1335     /// ```
1336     #[stable(feature = "rust1", since = "1.0.0")]
1337     pub fn ends_with(&self, needle: &[T]) -> bool
1338         where T: PartialEq
1339     {
1340         let (m, n) = (self.len(), needle.len());
1341         m >= n && needle == &self[m-n..]
1342     }
1343
1344     /// Binary searches this sorted slice for a given element.
1345     ///
1346     /// If the value is found then [`Result::Ok`] is returned, containing the
1347     /// index of the matching element. If there are multiple matches, then any
1348     /// one of the matches could be returned. If the value is not found then
1349     /// [`Result::Err`] is returned, containing the index where a matching
1350     /// element could be inserted while maintaining sorted order.
1351     ///
1352     /// # Examples
1353     ///
1354     /// Looks up a series of four elements. The first is found, with a
1355     /// uniquely determined position; the second and third are not
1356     /// found; the fourth could match any position in `[1, 4]`.
1357     ///
1358     /// ```
1359     /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1360     ///
1361     /// assert_eq!(s.binary_search(&13),  Ok(9));
1362     /// assert_eq!(s.binary_search(&4),   Err(7));
1363     /// assert_eq!(s.binary_search(&100), Err(13));
1364     /// let r = s.binary_search(&1);
1365     /// assert!(match r { Ok(1..=4) => true, _ => false, });
1366     /// ```
1367     #[stable(feature = "rust1", since = "1.0.0")]
1368     pub fn binary_search(&self, x: &T) -> Result<usize, usize>
1369         where T: Ord
1370     {
1371         self.binary_search_by(|p| p.cmp(x))
1372     }
1373
1374     /// Binary searches this sorted slice with a comparator function.
1375     ///
1376     /// The comparator function should implement an order consistent
1377     /// with the sort order of the underlying slice, returning an
1378     /// order code that indicates whether its argument is `Less`,
1379     /// `Equal` or `Greater` the desired target.
1380     ///
1381     /// If the value is found then [`Result::Ok`] is returned, containing the
1382     /// index of the matching element. If there are multiple matches, then any
1383     /// one of the matches could be returned. If the value is not found then
1384     /// [`Result::Err`] is returned, containing the index where a matching
1385     /// element could be inserted while maintaining sorted order.
1386     ///
1387     /// # Examples
1388     ///
1389     /// Looks up a series of four elements. The first is found, with a
1390     /// uniquely determined position; the second and third are not
1391     /// found; the fourth could match any position in `[1, 4]`.
1392     ///
1393     /// ```
1394     /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1395     ///
1396     /// let seek = 13;
1397     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
1398     /// let seek = 4;
1399     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
1400     /// let seek = 100;
1401     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
1402     /// let seek = 1;
1403     /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
1404     /// assert!(match r { Ok(1..=4) => true, _ => false, });
1405     /// ```
1406     #[stable(feature = "rust1", since = "1.0.0")]
1407     #[inline]
1408     pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
1409         where F: FnMut(&'a T) -> Ordering
1410     {
1411         let s = self;
1412         let mut size = s.len();
1413         if size == 0 {
1414             return Err(0);
1415         }
1416         let mut base = 0usize;
1417         while size > 1 {
1418             let half = size / 2;
1419             let mid = base + half;
1420             // mid is always in [0, size), that means mid is >= 0 and < size.
1421             // mid >= 0: by definition
1422             // mid < size: mid = size / 2 + size / 4 + size / 8 ...
1423             let cmp = f(unsafe { s.get_unchecked(mid) });
1424             base = if cmp == Greater { base } else { mid };
1425             size -= half;
1426         }
1427         // base is always in [0, size) because base <= mid.
1428         let cmp = f(unsafe { s.get_unchecked(base) });
1429         if cmp == Equal { Ok(base) } else { Err(base + (cmp == Less) as usize) }
1430
1431     }
1432
1433     /// Binary searches this sorted slice with a key extraction function.
1434     ///
1435     /// Assumes that the slice is sorted by the key, for instance with
1436     /// [`sort_by_key`] using the same key extraction function.
1437     ///
1438     /// If the value is found then [`Result::Ok`] is returned, containing the
1439     /// index of the matching element. If there are multiple matches, then any
1440     /// one of the matches could be returned. If the value is not found then
1441     /// [`Result::Err`] is returned, containing the index where a matching
1442     /// element could be inserted while maintaining sorted order.
1443     ///
1444     /// [`sort_by_key`]: #method.sort_by_key
1445     ///
1446     /// # Examples
1447     ///
1448     /// Looks up a series of four elements in a slice of pairs sorted by
1449     /// their second elements. The first is found, with a uniquely
1450     /// determined position; the second and third are not found; the
1451     /// fourth could match any position in `[1, 4]`.
1452     ///
1453     /// ```
1454     /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
1455     ///          (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
1456     ///          (1, 21), (2, 34), (4, 55)];
1457     ///
1458     /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b),  Ok(9));
1459     /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b),   Err(7));
1460     /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
1461     /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
1462     /// assert!(match r { Ok(1..=4) => true, _ => false, });
1463     /// ```
1464     #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
1465     #[inline]
1466     pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
1467         where F: FnMut(&'a T) -> B,
1468               B: Ord
1469     {
1470         self.binary_search_by(|k| f(k).cmp(b))
1471     }
1472
1473     /// Sorts the slice, but may not preserve the order of equal elements.
1474     ///
1475     /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1476     /// and `O(n log n)` worst-case.
1477     ///
1478     /// # Current implementation
1479     ///
1480     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1481     /// which combines the fast average case of randomized quicksort with the fast worst case of
1482     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1483     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1484     /// deterministic behavior.
1485     ///
1486     /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1487     /// slice consists of several concatenated sorted sequences.
1488     ///
1489     /// # Examples
1490     ///
1491     /// ```
1492     /// let mut v = [-5, 4, 1, -3, 2];
1493     ///
1494     /// v.sort_unstable();
1495     /// assert!(v == [-5, -3, 1, 2, 4]);
1496     /// ```
1497     ///
1498     /// [pdqsort]: https://github.com/orlp/pdqsort
1499     #[stable(feature = "sort_unstable", since = "1.20.0")]
1500     #[inline]
1501     pub fn sort_unstable(&mut self)
1502         where T: Ord
1503     {
1504         sort::quicksort(self, |a, b| a.lt(b));
1505     }
1506
1507     /// Sorts the slice with a comparator function, but may not preserve the order of equal
1508     /// elements.
1509     ///
1510     /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1511     /// and `O(n log n)` worst-case.
1512     ///
1513     /// # Current implementation
1514     ///
1515     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1516     /// which combines the fast average case of randomized quicksort with the fast worst case of
1517     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1518     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1519     /// deterministic behavior.
1520     ///
1521     /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1522     /// slice consists of several concatenated sorted sequences.
1523     ///
1524     /// # Examples
1525     ///
1526     /// ```
1527     /// let mut v = [5, 4, 1, 3, 2];
1528     /// v.sort_unstable_by(|a, b| a.cmp(b));
1529     /// assert!(v == [1, 2, 3, 4, 5]);
1530     ///
1531     /// // reverse sorting
1532     /// v.sort_unstable_by(|a, b| b.cmp(a));
1533     /// assert!(v == [5, 4, 3, 2, 1]);
1534     /// ```
1535     ///
1536     /// [pdqsort]: https://github.com/orlp/pdqsort
1537     #[stable(feature = "sort_unstable", since = "1.20.0")]
1538     #[inline]
1539     pub fn sort_unstable_by<F>(&mut self, mut compare: F)
1540         where F: FnMut(&T, &T) -> Ordering
1541     {
1542         sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
1543     }
1544
1545     /// Sorts the slice with a key extraction function, but may not preserve the order of equal
1546     /// elements.
1547     ///
1548     /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1549     /// and `O(m n log(m n))` worst-case, where the key function is `O(m)`.
1550     ///
1551     /// # Current implementation
1552     ///
1553     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1554     /// which combines the fast average case of randomized quicksort with the fast worst case of
1555     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1556     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1557     /// deterministic behavior.
1558     ///
1559     /// # Examples
1560     ///
1561     /// ```
1562     /// let mut v = [-5i32, 4, 1, -3, 2];
1563     ///
1564     /// v.sort_unstable_by_key(|k| k.abs());
1565     /// assert!(v == [1, 2, -3, 4, -5]);
1566     /// ```
1567     ///
1568     /// [pdqsort]: https://github.com/orlp/pdqsort
1569     #[stable(feature = "sort_unstable", since = "1.20.0")]
1570     #[inline]
1571     pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
1572         where F: FnMut(&T) -> K, K: Ord
1573     {
1574         sort::quicksort(self, |a, b| f(a).lt(&f(b)));
1575     }
1576
1577     /// Moves all consecutive repeated elements to the end of the slice according to the
1578     /// [`PartialEq`] trait implementation.
1579     ///
1580     /// Returns two slices. The first contains no consecutive repeated elements.
1581     /// The second contains all the duplicates in no specified order.
1582     ///
1583     /// If the slice is sorted, the first returned slice contains no duplicates.
1584     ///
1585     /// # Examples
1586     ///
1587     /// ```
1588     /// #![feature(slice_partition_dedup)]
1589     ///
1590     /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
1591     ///
1592     /// let (dedup, duplicates) = slice.partition_dedup();
1593     ///
1594     /// assert_eq!(dedup, [1, 2, 3, 2, 1]);
1595     /// assert_eq!(duplicates, [2, 3, 1]);
1596     /// ```
1597     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1598     #[inline]
1599     pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
1600         where T: PartialEq
1601     {
1602         self.partition_dedup_by(|a, b| a == b)
1603     }
1604
1605     /// Moves all but the first of consecutive elements to the end of the slice satisfying
1606     /// a given equality relation.
1607     ///
1608     /// Returns two slices. The first contains no consecutive repeated elements.
1609     /// The second contains all the duplicates in no specified order.
1610     ///
1611     /// The `same_bucket` function is passed references to two elements from the slice and
1612     /// must determine if the elements compare equal. The elements are passed in opposite order
1613     /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved
1614     /// at the end of the slice.
1615     ///
1616     /// If the slice is sorted, the first returned slice contains no duplicates.
1617     ///
1618     /// # Examples
1619     ///
1620     /// ```
1621     /// #![feature(slice_partition_dedup)]
1622     ///
1623     /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
1624     ///
1625     /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1626     ///
1627     /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
1628     /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
1629     /// ```
1630     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1631     #[inline]
1632     pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])
1633         where F: FnMut(&mut T, &mut T) -> bool
1634     {
1635         // Although we have a mutable reference to `self`, we cannot make
1636         // *arbitrary* changes. The `same_bucket` calls could panic, so we
1637         // must ensure that the slice is in a valid state at all times.
1638         //
1639         // The way that we handle this is by using swaps; we iterate
1640         // over all the elements, swapping as we go so that at the end
1641         // the elements we wish to keep are in the front, and those we
1642         // wish to reject are at the back. We can then split the slice.
1643         // This operation is still O(n).
1644         //
1645         // Example: We start in this state, where `r` represents "next
1646         // read" and `w` represents "next_write`.
1647         //
1648         //           r
1649         //     +---+---+---+---+---+---+
1650         //     | 0 | 1 | 1 | 2 | 3 | 3 |
1651         //     +---+---+---+---+---+---+
1652         //           w
1653         //
1654         // Comparing self[r] against self[w-1], this is not a duplicate, so
1655         // we swap self[r] and self[w] (no effect as r==w) and then increment both
1656         // r and w, leaving us with:
1657         //
1658         //               r
1659         //     +---+---+---+---+---+---+
1660         //     | 0 | 1 | 1 | 2 | 3 | 3 |
1661         //     +---+---+---+---+---+---+
1662         //               w
1663         //
1664         // Comparing self[r] against self[w-1], this value is a duplicate,
1665         // so we increment `r` but leave everything else unchanged:
1666         //
1667         //                   r
1668         //     +---+---+---+---+---+---+
1669         //     | 0 | 1 | 1 | 2 | 3 | 3 |
1670         //     +---+---+---+---+---+---+
1671         //               w
1672         //
1673         // Comparing self[r] against self[w-1], this is not a duplicate,
1674         // so swap self[r] and self[w] and advance r and w:
1675         //
1676         //                       r
1677         //     +---+---+---+---+---+---+
1678         //     | 0 | 1 | 2 | 1 | 3 | 3 |
1679         //     +---+---+---+---+---+---+
1680         //                   w
1681         //
1682         // Not a duplicate, repeat:
1683         //
1684         //                           r
1685         //     +---+---+---+---+---+---+
1686         //     | 0 | 1 | 2 | 3 | 1 | 3 |
1687         //     +---+---+---+---+---+---+
1688         //                       w
1689         //
1690         // Duplicate, advance r. End of slice. Split at w.
1691
1692         let len = self.len();
1693         if len <= 1 {
1694             return (self, &mut [])
1695         }
1696
1697         let ptr = self.as_mut_ptr();
1698         let mut next_read: usize = 1;
1699         let mut next_write: usize = 1;
1700
1701         unsafe {
1702             // Avoid bounds checks by using raw pointers.
1703             while next_read < len {
1704                 let ptr_read = ptr.add(next_read);
1705                 let prev_ptr_write = ptr.add(next_write - 1);
1706                 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
1707                     if next_read != next_write {
1708                         let ptr_write = prev_ptr_write.offset(1);
1709                         mem::swap(&mut *ptr_read, &mut *ptr_write);
1710                     }
1711                     next_write += 1;
1712                 }
1713                 next_read += 1;
1714             }
1715         }
1716
1717         self.split_at_mut(next_write)
1718     }
1719
1720     /// Moves all but the first of consecutive elements to the end of the slice that resolve
1721     /// to the same key.
1722     ///
1723     /// Returns two slices. The first contains no consecutive repeated elements.
1724     /// The second contains all the duplicates in no specified order.
1725     ///
1726     /// If the slice is sorted, the first returned slice contains no duplicates.
1727     ///
1728     /// # Examples
1729     ///
1730     /// ```
1731     /// #![feature(slice_partition_dedup)]
1732     ///
1733     /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
1734     ///
1735     /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
1736     ///
1737     /// assert_eq!(dedup, [10, 20, 30, 20, 11]);
1738     /// assert_eq!(duplicates, [21, 30, 13]);
1739     /// ```
1740     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1741     #[inline]
1742     pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])
1743         where F: FnMut(&mut T) -> K,
1744               K: PartialEq,
1745     {
1746         self.partition_dedup_by(|a, b| key(a) == key(b))
1747     }
1748
1749     /// Rotates the slice in-place such that the first `mid` elements of the
1750     /// slice move to the end while the last `self.len() - mid` elements move to
1751     /// the front. After calling `rotate_left`, the element previously at index
1752     /// `mid` will become the first element in the slice.
1753     ///
1754     /// # Panics
1755     ///
1756     /// This function will panic if `mid` is greater than the length of the
1757     /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
1758     /// rotation.
1759     ///
1760     /// # Complexity
1761     ///
1762     /// Takes linear (in `self.len()`) time.
1763     ///
1764     /// # Examples
1765     ///
1766     /// ```
1767     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1768     /// a.rotate_left(2);
1769     /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
1770     /// ```
1771     ///
1772     /// Rotating a subslice:
1773     ///
1774     /// ```
1775     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1776     /// a[1..5].rotate_left(1);
1777     /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
1778    /// ```
1779     #[stable(feature = "slice_rotate", since = "1.26.0")]
1780     pub fn rotate_left(&mut self, mid: usize) {
1781         assert!(mid <= self.len());
1782         let k = self.len() - mid;
1783
1784         unsafe {
1785             let p = self.as_mut_ptr();
1786             rotate::ptr_rotate(mid, p.add(mid), k);
1787         }
1788     }
1789
1790     /// Rotates the slice in-place such that the first `self.len() - k`
1791     /// elements of the slice move to the end while the last `k` elements move
1792     /// to the front. After calling `rotate_right`, the element previously at
1793     /// index `self.len() - k` will become the first element in the slice.
1794     ///
1795     /// # Panics
1796     ///
1797     /// This function will panic if `k` is greater than the length of the
1798     /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
1799     /// rotation.
1800     ///
1801     /// # Complexity
1802     ///
1803     /// Takes linear (in `self.len()`) time.
1804     ///
1805     /// # Examples
1806     ///
1807     /// ```
1808     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1809     /// a.rotate_right(2);
1810     /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
1811     /// ```
1812     ///
1813     /// Rotate a subslice:
1814     ///
1815     /// ```
1816     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1817     /// a[1..5].rotate_right(1);
1818     /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
1819     /// ```
1820     #[stable(feature = "slice_rotate", since = "1.26.0")]
1821     pub fn rotate_right(&mut self, k: usize) {
1822         assert!(k <= self.len());
1823         let mid = self.len() - k;
1824
1825         unsafe {
1826             let p = self.as_mut_ptr();
1827             rotate::ptr_rotate(mid, p.add(mid), k);
1828         }
1829     }
1830
1831     /// Copies the elements from `src` into `self`.
1832     ///
1833     /// The length of `src` must be the same as `self`.
1834     ///
1835     /// If `src` implements `Copy`, it can be more performant to use
1836     /// [`copy_from_slice`].
1837     ///
1838     /// # Panics
1839     ///
1840     /// This function will panic if the two slices have different lengths.
1841     ///
1842     /// # Examples
1843     ///
1844     /// Cloning two elements from a slice into another:
1845     ///
1846     /// ```
1847     /// let src = [1, 2, 3, 4];
1848     /// let mut dst = [0, 0];
1849     ///
1850     /// // Because the slices have to be the same length,
1851     /// // we slice the source slice from four elements
1852     /// // to two. It will panic if we don't do this.
1853     /// dst.clone_from_slice(&src[2..]);
1854     ///
1855     /// assert_eq!(src, [1, 2, 3, 4]);
1856     /// assert_eq!(dst, [3, 4]);
1857     /// ```
1858     ///
1859     /// Rust enforces that there can only be one mutable reference with no
1860     /// immutable references to a particular piece of data in a particular
1861     /// scope. Because of this, attempting to use `clone_from_slice` on a
1862     /// single slice will result in a compile failure:
1863     ///
1864     /// ```compile_fail
1865     /// let mut slice = [1, 2, 3, 4, 5];
1866     ///
1867     /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
1868     /// ```
1869     ///
1870     /// To work around this, we can use [`split_at_mut`] to create two distinct
1871     /// sub-slices from a slice:
1872     ///
1873     /// ```
1874     /// let mut slice = [1, 2, 3, 4, 5];
1875     ///
1876     /// {
1877     ///     let (left, right) = slice.split_at_mut(2);
1878     ///     left.clone_from_slice(&right[1..]);
1879     /// }
1880     ///
1881     /// assert_eq!(slice, [4, 5, 3, 4, 5]);
1882     /// ```
1883     ///
1884     /// [`copy_from_slice`]: #method.copy_from_slice
1885     /// [`split_at_mut`]: #method.split_at_mut
1886     #[stable(feature = "clone_from_slice", since = "1.7.0")]
1887     pub fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
1888         assert!(self.len() == src.len(),
1889                 "destination and source slices have different lengths");
1890         // NOTE: We need to explicitly slice them to the same length
1891         // for bounds checking to be elided, and the optimizer will
1892         // generate memcpy for simple cases (for example T = u8).
1893         let len = self.len();
1894         let src = &src[..len];
1895         for i in 0..len {
1896             self[i].clone_from(&src[i]);
1897         }
1898
1899     }
1900
1901     /// Copies all elements from `src` into `self`, using a memcpy.
1902     ///
1903     /// The length of `src` must be the same as `self`.
1904     ///
1905     /// If `src` does not implement `Copy`, use [`clone_from_slice`].
1906     ///
1907     /// # Panics
1908     ///
1909     /// This function will panic if the two slices have different lengths.
1910     ///
1911     /// # Examples
1912     ///
1913     /// Copying two elements from a slice into another:
1914     ///
1915     /// ```
1916     /// let src = [1, 2, 3, 4];
1917     /// let mut dst = [0, 0];
1918     ///
1919     /// // Because the slices have to be the same length,
1920     /// // we slice the source slice from four elements
1921     /// // to two. It will panic if we don't do this.
1922     /// dst.copy_from_slice(&src[2..]);
1923     ///
1924     /// assert_eq!(src, [1, 2, 3, 4]);
1925     /// assert_eq!(dst, [3, 4]);
1926     /// ```
1927     ///
1928     /// Rust enforces that there can only be one mutable reference with no
1929     /// immutable references to a particular piece of data in a particular
1930     /// scope. Because of this, attempting to use `copy_from_slice` on a
1931     /// single slice will result in a compile failure:
1932     ///
1933     /// ```compile_fail
1934     /// let mut slice = [1, 2, 3, 4, 5];
1935     ///
1936     /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
1937     /// ```
1938     ///
1939     /// To work around this, we can use [`split_at_mut`] to create two distinct
1940     /// sub-slices from a slice:
1941     ///
1942     /// ```
1943     /// let mut slice = [1, 2, 3, 4, 5];
1944     ///
1945     /// {
1946     ///     let (left, right) = slice.split_at_mut(2);
1947     ///     left.copy_from_slice(&right[1..]);
1948     /// }
1949     ///
1950     /// assert_eq!(slice, [4, 5, 3, 4, 5]);
1951     /// ```
1952     ///
1953     /// [`clone_from_slice`]: #method.clone_from_slice
1954     /// [`split_at_mut`]: #method.split_at_mut
1955     #[stable(feature = "copy_from_slice", since = "1.9.0")]
1956     pub fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
1957         assert_eq!(self.len(), src.len(),
1958                    "destination and source slices have different lengths");
1959         unsafe {
1960             ptr::copy_nonoverlapping(
1961                 src.as_ptr(), self.as_mut_ptr(), self.len());
1962         }
1963     }
1964
1965     /// Copies elements from one part of the slice to another part of itself,
1966     /// using a memmove.
1967     ///
1968     /// `src` is the range within `self` to copy from. `dest` is the starting
1969     /// index of the range within `self` to copy to, which will have the same
1970     /// length as `src`. The two ranges may overlap. The ends of the two ranges
1971     /// must be less than or equal to `self.len()`.
1972     ///
1973     /// # Panics
1974     ///
1975     /// This function will panic if either range exceeds the end of the slice,
1976     /// or if the end of `src` is before the start.
1977     ///
1978     /// # Examples
1979     ///
1980     /// Copying four bytes within a slice:
1981     ///
1982     /// ```
1983     /// # #![feature(copy_within)]
1984     /// let mut bytes = *b"Hello, World!";
1985     ///
1986     /// bytes.copy_within(1..5, 8);
1987     ///
1988     /// assert_eq!(&bytes, b"Hello, Wello!");
1989     /// ```
1990     #[unstable(feature = "copy_within", issue = "54236")]
1991     pub fn copy_within<R: ops::RangeBounds<usize>>(&mut self, src: R, dest: usize)
1992     where
1993         T: Copy,
1994     {
1995         let src_start = match src.start_bound() {
1996             ops::Bound::Included(&n) => n,
1997             ops::Bound::Excluded(&n) => n
1998                 .checked_add(1)
1999                 .unwrap_or_else(|| slice_index_overflow_fail()),
2000             ops::Bound::Unbounded => 0,
2001         };
2002         let src_end = match src.end_bound() {
2003             ops::Bound::Included(&n) => n
2004                 .checked_add(1)
2005                 .unwrap_or_else(|| slice_index_overflow_fail()),
2006             ops::Bound::Excluded(&n) => n,
2007             ops::Bound::Unbounded => self.len(),
2008         };
2009         assert!(src_start <= src_end, "src end is before src start");
2010         assert!(src_end <= self.len(), "src is out of bounds");
2011         let count = src_end - src_start;
2012         assert!(dest <= self.len() - count, "dest is out of bounds");
2013         unsafe {
2014             ptr::copy(
2015                 self.get_unchecked(src_start),
2016                 self.get_unchecked_mut(dest),
2017                 count,
2018             );
2019         }
2020     }
2021
2022     /// Swaps all elements in `self` with those in `other`.
2023     ///
2024     /// The length of `other` must be the same as `self`.
2025     ///
2026     /// # Panics
2027     ///
2028     /// This function will panic if the two slices have different lengths.
2029     ///
2030     /// # Example
2031     ///
2032     /// Swapping two elements across slices:
2033     ///
2034     /// ```
2035     /// let mut slice1 = [0, 0];
2036     /// let mut slice2 = [1, 2, 3, 4];
2037     ///
2038     /// slice1.swap_with_slice(&mut slice2[2..]);
2039     ///
2040     /// assert_eq!(slice1, [3, 4]);
2041     /// assert_eq!(slice2, [1, 2, 0, 0]);
2042     /// ```
2043     ///
2044     /// Rust enforces that there can only be one mutable reference to a
2045     /// particular piece of data in a particular scope. Because of this,
2046     /// attempting to use `swap_with_slice` on a single slice will result in
2047     /// a compile failure:
2048     ///
2049     /// ```compile_fail
2050     /// let mut slice = [1, 2, 3, 4, 5];
2051     /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
2052     /// ```
2053     ///
2054     /// To work around this, we can use [`split_at_mut`] to create two distinct
2055     /// mutable sub-slices from a slice:
2056     ///
2057     /// ```
2058     /// let mut slice = [1, 2, 3, 4, 5];
2059     ///
2060     /// {
2061     ///     let (left, right) = slice.split_at_mut(2);
2062     ///     left.swap_with_slice(&mut right[1..]);
2063     /// }
2064     ///
2065     /// assert_eq!(slice, [4, 5, 3, 1, 2]);
2066     /// ```
2067     ///
2068     /// [`split_at_mut`]: #method.split_at_mut
2069     #[stable(feature = "swap_with_slice", since = "1.27.0")]
2070     pub fn swap_with_slice(&mut self, other: &mut [T]) {
2071         assert!(self.len() == other.len(),
2072                 "destination and source slices have different lengths");
2073         unsafe {
2074             ptr::swap_nonoverlapping(
2075                 self.as_mut_ptr(), other.as_mut_ptr(), self.len());
2076         }
2077     }
2078
2079     /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
2080     fn align_to_offsets<U>(&self) -> (usize, usize) {
2081         // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
2082         // lowest number of `T`s. And how many `T`s we need for each such "multiple".
2083         //
2084         // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
2085         // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
2086         // place of every 3 Ts in the `rest` slice. A bit more complicated.
2087         //
2088         // Formula to calculate this is:
2089         //
2090         // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
2091         // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
2092         //
2093         // Expanded and simplified:
2094         //
2095         // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
2096         // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
2097         //
2098         // Luckily since all this is constant-evaluated... performance here matters not!
2099         #[inline]
2100         fn gcd(a: usize, b: usize) -> usize {
2101             // iterative stein’s algorithm
2102             // We should still make this `const fn` (and revert to recursive algorithm if we do)
2103             // because relying on llvm to consteval all this is… well, it makes me uncomfortable.
2104             let (ctz_a, mut ctz_b) = unsafe {
2105                 if a == 0 { return b; }
2106                 if b == 0 { return a; }
2107                 (::intrinsics::cttz_nonzero(a), ::intrinsics::cttz_nonzero(b))
2108             };
2109             let k = ctz_a.min(ctz_b);
2110             let mut a = a >> ctz_a;
2111             let mut b = b;
2112             loop {
2113                 // remove all factors of 2 from b
2114                 b >>= ctz_b;
2115                 if a > b {
2116                     ::mem::swap(&mut a, &mut b);
2117                 }
2118                 b = b - a;
2119                 unsafe {
2120                     if b == 0 {
2121                         break;
2122                     }
2123                     ctz_b = ::intrinsics::cttz_nonzero(b);
2124                 }
2125             }
2126             a << k
2127         }
2128         let gcd: usize = gcd(::mem::size_of::<T>(), ::mem::size_of::<U>());
2129         let ts: usize = ::mem::size_of::<U>() / gcd;
2130         let us: usize = ::mem::size_of::<T>() / gcd;
2131
2132         // Armed with this knowledge, we can find how many `U`s we can fit!
2133         let us_len = self.len() / ts * us;
2134         // And how many `T`s will be in the trailing slice!
2135         let ts_len = self.len() % ts;
2136         (us_len, ts_len)
2137     }
2138
2139     /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2140     /// maintained.
2141     ///
2142     /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2143     /// slice of a new type, and the suffix slice. The method does a best effort to make the
2144     /// middle slice the greatest length possible for a given type and input slice, but only
2145     /// your algorithm's performance should depend on that, not its correctness.
2146     ///
2147     /// This method has no purpose when either input element `T` or output element `U` are
2148     /// zero-sized and will return the original slice without splitting anything.
2149     ///
2150     /// # Unsafety
2151     ///
2152     /// This method is essentially a `transmute` with respect to the elements in the returned
2153     /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2154     ///
2155     /// # Examples
2156     ///
2157     /// Basic usage:
2158     ///
2159     /// ```
2160     /// unsafe {
2161     ///     let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2162     ///     let (prefix, shorts, suffix) = bytes.align_to::<u16>();
2163     ///     // less_efficient_algorithm_for_bytes(prefix);
2164     ///     // more_efficient_algorithm_for_aligned_shorts(shorts);
2165     ///     // less_efficient_algorithm_for_bytes(suffix);
2166     /// }
2167     /// ```
2168     #[stable(feature = "slice_align_to", since = "1.30.0")]
2169     pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
2170         // Note that most of this function will be constant-evaluated,
2171         if ::mem::size_of::<U>() == 0 || ::mem::size_of::<T>() == 0 {
2172             // handle ZSTs specially, which is â€“ don't handle them at all.
2173             return (self, &[], &[]);
2174         }
2175
2176         // First, find at what point do we split between the first and 2nd slice. Easy with
2177         // ptr.align_offset.
2178         let ptr = self.as_ptr();
2179         let offset = ::ptr::align_offset(ptr, ::mem::align_of::<U>());
2180         if offset > self.len() {
2181             (self, &[], &[])
2182         } else {
2183             let (left, rest) = self.split_at(offset);
2184             // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
2185             let (us_len, ts_len) = rest.align_to_offsets::<U>();
2186             (left,
2187              from_raw_parts(rest.as_ptr() as *const U, us_len),
2188              from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len))
2189         }
2190     }
2191
2192     /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2193     /// maintained.
2194     ///
2195     /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2196     /// slice of a new type, and the suffix slice. The method does a best effort to make the
2197     /// middle slice the greatest length possible for a given type and input slice, but only
2198     /// your algorithm's performance should depend on that, not its correctness.
2199     ///
2200     /// This method has no purpose when either input element `T` or output element `U` are
2201     /// zero-sized and will return the original slice without splitting anything.
2202     ///
2203     /// # Unsafety
2204     ///
2205     /// This method is essentially a `transmute` with respect to the elements in the returned
2206     /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2207     ///
2208     /// # Examples
2209     ///
2210     /// Basic usage:
2211     ///
2212     /// ```
2213     /// unsafe {
2214     ///     let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2215     ///     let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
2216     ///     // less_efficient_algorithm_for_bytes(prefix);
2217     ///     // more_efficient_algorithm_for_aligned_shorts(shorts);
2218     ///     // less_efficient_algorithm_for_bytes(suffix);
2219     /// }
2220     /// ```
2221     #[stable(feature = "slice_align_to", since = "1.30.0")]
2222     pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
2223         // Note that most of this function will be constant-evaluated,
2224         if ::mem::size_of::<U>() == 0 || ::mem::size_of::<T>() == 0 {
2225             // handle ZSTs specially, which is â€“ don't handle them at all.
2226             return (self, &mut [], &mut []);
2227         }
2228
2229         // First, find at what point do we split between the first and 2nd slice. Easy with
2230         // ptr.align_offset.
2231         let ptr = self.as_ptr();
2232         let offset = ::ptr::align_offset(ptr, ::mem::align_of::<U>());
2233         if offset > self.len() {
2234             (self, &mut [], &mut [])
2235         } else {
2236             let (left, rest) = self.split_at_mut(offset);
2237             // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
2238             let (us_len, ts_len) = rest.align_to_offsets::<U>();
2239             let mut_ptr = rest.as_mut_ptr();
2240             (left,
2241              from_raw_parts_mut(mut_ptr as *mut U, us_len),
2242              from_raw_parts_mut(mut_ptr.add(rest.len() - ts_len), ts_len))
2243         }
2244     }
2245 }
2246
2247 #[lang = "slice_u8"]
2248 #[cfg(not(test))]
2249 impl [u8] {
2250     /// Checks if all bytes in this slice are within the ASCII range.
2251     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2252     #[inline]
2253     pub fn is_ascii(&self) -> bool {
2254         self.iter().all(|b| b.is_ascii())
2255     }
2256
2257     /// Checks that two slices are an ASCII case-insensitive match.
2258     ///
2259     /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2260     /// but without allocating and copying temporaries.
2261     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2262     #[inline]
2263     pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
2264         self.len() == other.len() &&
2265             self.iter().zip(other).all(|(a, b)| {
2266                 a.eq_ignore_ascii_case(b)
2267             })
2268     }
2269
2270     /// Converts this slice to its ASCII upper case equivalent in-place.
2271     ///
2272     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2273     /// but non-ASCII letters are unchanged.
2274     ///
2275     /// To return a new uppercased value without modifying the existing one, use
2276     /// [`to_ascii_uppercase`].
2277     ///
2278     /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2279     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2280     #[inline]
2281     pub fn make_ascii_uppercase(&mut self) {
2282         for byte in self {
2283             byte.make_ascii_uppercase();
2284         }
2285     }
2286
2287     /// Converts this slice to its ASCII lower case equivalent in-place.
2288     ///
2289     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2290     /// but non-ASCII letters are unchanged.
2291     ///
2292     /// To return a new lowercased value without modifying the existing one, use
2293     /// [`to_ascii_lowercase`].
2294     ///
2295     /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2296     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2297     #[inline]
2298     pub fn make_ascii_lowercase(&mut self) {
2299         for byte in self {
2300             byte.make_ascii_lowercase();
2301         }
2302     }
2303
2304 }
2305
2306 #[stable(feature = "rust1", since = "1.0.0")]
2307 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
2308 impl<T, I> ops::Index<I> for [T]
2309     where I: SliceIndex<[T]>
2310 {
2311     type Output = I::Output;
2312
2313     #[inline]
2314     fn index(&self, index: I) -> &I::Output {
2315         index.index(self)
2316     }
2317 }
2318
2319 #[stable(feature = "rust1", since = "1.0.0")]
2320 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
2321 impl<T, I> ops::IndexMut<I> for [T]
2322     where I: SliceIndex<[T]>
2323 {
2324     #[inline]
2325     fn index_mut(&mut self, index: I) -> &mut I::Output {
2326         index.index_mut(self)
2327     }
2328 }
2329
2330 #[inline(never)]
2331 #[cold]
2332 fn slice_index_len_fail(index: usize, len: usize) -> ! {
2333     panic!("index {} out of range for slice of length {}", index, len);
2334 }
2335
2336 #[inline(never)]
2337 #[cold]
2338 fn slice_index_order_fail(index: usize, end: usize) -> ! {
2339     panic!("slice index starts at {} but ends at {}", index, end);
2340 }
2341
2342 #[inline(never)]
2343 #[cold]
2344 fn slice_index_overflow_fail() -> ! {
2345     panic!("attempted to index slice up to maximum usize");
2346 }
2347
2348 mod private_slice_index {
2349     use super::ops;
2350     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2351     pub trait Sealed {}
2352
2353     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2354     impl Sealed for usize {}
2355     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2356     impl Sealed for ops::Range<usize> {}
2357     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2358     impl Sealed for ops::RangeTo<usize> {}
2359     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2360     impl Sealed for ops::RangeFrom<usize> {}
2361     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2362     impl Sealed for ops::RangeFull {}
2363     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2364     impl Sealed for ops::RangeInclusive<usize> {}
2365     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2366     impl Sealed for ops::RangeToInclusive<usize> {}
2367 }
2368
2369 /// A helper trait used for indexing operations.
2370 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2371 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
2372 pub trait SliceIndex<T: ?Sized>: private_slice_index::Sealed {
2373     /// The output type returned by methods.
2374     #[stable(feature = "slice_get_slice", since = "1.28.0")]
2375     type Output: ?Sized;
2376
2377     /// Returns a shared reference to the output at this location, if in
2378     /// bounds.
2379     #[unstable(feature = "slice_index_methods", issue = "0")]
2380     fn get(self, slice: &T) -> Option<&Self::Output>;
2381
2382     /// Returns a mutable reference to the output at this location, if in
2383     /// bounds.
2384     #[unstable(feature = "slice_index_methods", issue = "0")]
2385     fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
2386
2387     /// Returns a shared reference to the output at this location, without
2388     /// performing any bounds checking.
2389     #[unstable(feature = "slice_index_methods", issue = "0")]
2390     unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
2391
2392     /// Returns a mutable reference to the output at this location, without
2393     /// performing any bounds checking.
2394     #[unstable(feature = "slice_index_methods", issue = "0")]
2395     unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
2396
2397     /// Returns a shared reference to the output at this location, panicking
2398     /// if out of bounds.
2399     #[unstable(feature = "slice_index_methods", issue = "0")]
2400     fn index(self, slice: &T) -> &Self::Output;
2401
2402     /// Returns a mutable reference to the output at this location, panicking
2403     /// if out of bounds.
2404     #[unstable(feature = "slice_index_methods", issue = "0")]
2405     fn index_mut(self, slice: &mut T) -> &mut Self::Output;
2406 }
2407
2408 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2409 impl<T> SliceIndex<[T]> for usize {
2410     type Output = T;
2411
2412     #[inline]
2413     fn get(self, slice: &[T]) -> Option<&T> {
2414         if self < slice.len() {
2415             unsafe {
2416                 Some(self.get_unchecked(slice))
2417             }
2418         } else {
2419             None
2420         }
2421     }
2422
2423     #[inline]
2424     fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
2425         if self < slice.len() {
2426             unsafe {
2427                 Some(self.get_unchecked_mut(slice))
2428             }
2429         } else {
2430             None
2431         }
2432     }
2433
2434     #[inline]
2435     unsafe fn get_unchecked(self, slice: &[T]) -> &T {
2436         &*slice.as_ptr().add(self)
2437     }
2438
2439     #[inline]
2440     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
2441         &mut *slice.as_mut_ptr().add(self)
2442     }
2443
2444     #[inline]
2445     fn index(self, slice: &[T]) -> &T {
2446         // NB: use intrinsic indexing
2447         &(*slice)[self]
2448     }
2449
2450     #[inline]
2451     fn index_mut(self, slice: &mut [T]) -> &mut T {
2452         // NB: use intrinsic indexing
2453         &mut (*slice)[self]
2454     }
2455 }
2456
2457 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2458 impl<T> SliceIndex<[T]> for  ops::Range<usize> {
2459     type Output = [T];
2460
2461     #[inline]
2462     fn get(self, slice: &[T]) -> Option<&[T]> {
2463         if self.start > self.end || self.end > slice.len() {
2464             None
2465         } else {
2466             unsafe {
2467                 Some(self.get_unchecked(slice))
2468             }
2469         }
2470     }
2471
2472     #[inline]
2473     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2474         if self.start > self.end || self.end > slice.len() {
2475             None
2476         } else {
2477             unsafe {
2478                 Some(self.get_unchecked_mut(slice))
2479             }
2480         }
2481     }
2482
2483     #[inline]
2484     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2485         from_raw_parts(slice.as_ptr().add(self.start), self.end - self.start)
2486     }
2487
2488     #[inline]
2489     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2490         from_raw_parts_mut(slice.as_mut_ptr().add(self.start), self.end - self.start)
2491     }
2492
2493     #[inline]
2494     fn index(self, slice: &[T]) -> &[T] {
2495         if self.start > self.end {
2496             slice_index_order_fail(self.start, self.end);
2497         } else if self.end > slice.len() {
2498             slice_index_len_fail(self.end, slice.len());
2499         }
2500         unsafe {
2501             self.get_unchecked(slice)
2502         }
2503     }
2504
2505     #[inline]
2506     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2507         if self.start > self.end {
2508             slice_index_order_fail(self.start, self.end);
2509         } else if self.end > slice.len() {
2510             slice_index_len_fail(self.end, slice.len());
2511         }
2512         unsafe {
2513             self.get_unchecked_mut(slice)
2514         }
2515     }
2516 }
2517
2518 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2519 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
2520     type Output = [T];
2521
2522     #[inline]
2523     fn get(self, slice: &[T]) -> Option<&[T]> {
2524         (0..self.end).get(slice)
2525     }
2526
2527     #[inline]
2528     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2529         (0..self.end).get_mut(slice)
2530     }
2531
2532     #[inline]
2533     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2534         (0..self.end).get_unchecked(slice)
2535     }
2536
2537     #[inline]
2538     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2539         (0..self.end).get_unchecked_mut(slice)
2540     }
2541
2542     #[inline]
2543     fn index(self, slice: &[T]) -> &[T] {
2544         (0..self.end).index(slice)
2545     }
2546
2547     #[inline]
2548     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2549         (0..self.end).index_mut(slice)
2550     }
2551 }
2552
2553 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2554 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
2555     type Output = [T];
2556
2557     #[inline]
2558     fn get(self, slice: &[T]) -> Option<&[T]> {
2559         (self.start..slice.len()).get(slice)
2560     }
2561
2562     #[inline]
2563     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2564         (self.start..slice.len()).get_mut(slice)
2565     }
2566
2567     #[inline]
2568     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2569         (self.start..slice.len()).get_unchecked(slice)
2570     }
2571
2572     #[inline]
2573     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2574         (self.start..slice.len()).get_unchecked_mut(slice)
2575     }
2576
2577     #[inline]
2578     fn index(self, slice: &[T]) -> &[T] {
2579         (self.start..slice.len()).index(slice)
2580     }
2581
2582     #[inline]
2583     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2584         (self.start..slice.len()).index_mut(slice)
2585     }
2586 }
2587
2588 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2589 impl<T> SliceIndex<[T]> for ops::RangeFull {
2590     type Output = [T];
2591
2592     #[inline]
2593     fn get(self, slice: &[T]) -> Option<&[T]> {
2594         Some(slice)
2595     }
2596
2597     #[inline]
2598     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2599         Some(slice)
2600     }
2601
2602     #[inline]
2603     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2604         slice
2605     }
2606
2607     #[inline]
2608     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2609         slice
2610     }
2611
2612     #[inline]
2613     fn index(self, slice: &[T]) -> &[T] {
2614         slice
2615     }
2616
2617     #[inline]
2618     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2619         slice
2620     }
2621 }
2622
2623
2624 #[stable(feature = "inclusive_range", since = "1.26.0")]
2625 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
2626     type Output = [T];
2627
2628     #[inline]
2629     fn get(self, slice: &[T]) -> Option<&[T]> {
2630         if *self.end() == usize::max_value() { None }
2631         else { (*self.start()..self.end() + 1).get(slice) }
2632     }
2633
2634     #[inline]
2635     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2636         if *self.end() == usize::max_value() { None }
2637         else { (*self.start()..self.end() + 1).get_mut(slice) }
2638     }
2639
2640     #[inline]
2641     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2642         (*self.start()..self.end() + 1).get_unchecked(slice)
2643     }
2644
2645     #[inline]
2646     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2647         (*self.start()..self.end() + 1).get_unchecked_mut(slice)
2648     }
2649
2650     #[inline]
2651     fn index(self, slice: &[T]) -> &[T] {
2652         if *self.end() == usize::max_value() { slice_index_overflow_fail(); }
2653         (*self.start()..self.end() + 1).index(slice)
2654     }
2655
2656     #[inline]
2657     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2658         if *self.end() == usize::max_value() { slice_index_overflow_fail(); }
2659         (*self.start()..self.end() + 1).index_mut(slice)
2660     }
2661 }
2662
2663 #[stable(feature = "inclusive_range", since = "1.26.0")]
2664 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
2665     type Output = [T];
2666
2667     #[inline]
2668     fn get(self, slice: &[T]) -> Option<&[T]> {
2669         (0..=self.end).get(slice)
2670     }
2671
2672     #[inline]
2673     fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2674         (0..=self.end).get_mut(slice)
2675     }
2676
2677     #[inline]
2678     unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2679         (0..=self.end).get_unchecked(slice)
2680     }
2681
2682     #[inline]
2683     unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2684         (0..=self.end).get_unchecked_mut(slice)
2685     }
2686
2687     #[inline]
2688     fn index(self, slice: &[T]) -> &[T] {
2689         (0..=self.end).index(slice)
2690     }
2691
2692     #[inline]
2693     fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2694         (0..=self.end).index_mut(slice)
2695     }
2696 }
2697
2698 ////////////////////////////////////////////////////////////////////////////////
2699 // Common traits
2700 ////////////////////////////////////////////////////////////////////////////////
2701
2702 #[stable(feature = "rust1", since = "1.0.0")]
2703 impl<T> Default for &[T] {
2704     /// Creates an empty slice.
2705     fn default() -> Self { &[] }
2706 }
2707
2708 #[stable(feature = "mut_slice_default", since = "1.5.0")]
2709 impl<T> Default for &mut [T] {
2710     /// Creates a mutable empty slice.
2711     fn default() -> Self { &mut [] }
2712 }
2713
2714 //
2715 // Iterators
2716 //
2717
2718 #[stable(feature = "rust1", since = "1.0.0")]
2719 impl<'a, T> IntoIterator for &'a [T] {
2720     type Item = &'a T;
2721     type IntoIter = Iter<'a, T>;
2722
2723     fn into_iter(self) -> Iter<'a, T> {
2724         self.iter()
2725     }
2726 }
2727
2728 #[stable(feature = "rust1", since = "1.0.0")]
2729 impl<'a, T> IntoIterator for &'a mut [T] {
2730     type Item = &'a mut T;
2731     type IntoIter = IterMut<'a, T>;
2732
2733     fn into_iter(self) -> IterMut<'a, T> {
2734         self.iter_mut()
2735     }
2736 }
2737
2738 // Macro helper functions
2739 #[inline(always)]
2740 const fn size_from_ptr<T>(_: *const T) -> usize {
2741     mem::size_of::<T>()
2742 }
2743
2744 // Inlining is_empty and len makes a huge performance difference
2745 macro_rules! is_empty {
2746     // The way we encode the length of a ZST iterator, this works both for ZST
2747     // and non-ZST.
2748     ($self: ident) => {$self.ptr == $self.end}
2749 }
2750 // To get rid of some bounds checks (see `position`), we compute the length in a somewhat
2751 // unexpected way. (Tested by `codegen/slice-position-bounds-check`.)
2752 macro_rules! len {
2753     ($self: ident) => {{
2754         let start = $self.ptr;
2755         let diff = ($self.end as usize).wrapping_sub(start as usize);
2756         let size = size_from_ptr(start);
2757         if size == 0 {
2758             diff
2759         } else {
2760             // Using division instead of `offset_from` helps LLVM remove bounds checks
2761             diff / size
2762         }
2763     }}
2764 }
2765
2766 // The shared definition of the `Iter` and `IterMut` iterators
2767 macro_rules! iterator {
2768     (struct $name:ident -> $ptr:ty, $elem:ty, $raw_mut:tt, $( $mut_:tt )*) => {
2769         impl<'a, T> $name<'a, T> {
2770             // Helper function for creating a slice from the iterator.
2771             #[inline(always)]
2772             fn make_slice(&self) -> &'a [T] {
2773                 unsafe { from_raw_parts(self.ptr, len!(self)) }
2774             }
2775
2776             // Helper function for moving the start of the iterator forwards by `offset` elements,
2777             // returning the old start.
2778             // Unsafe because the offset must be in-bounds or one-past-the-end.
2779             #[inline(always)]
2780             unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T {
2781                 if mem::size_of::<T>() == 0 {
2782                     // This is *reducing* the length.  `ptr` never changes with ZST.
2783                     self.end = (self.end as * $raw_mut u8).wrapping_offset(-offset) as * $raw_mut T;
2784                     self.ptr
2785                 } else {
2786                     let old = self.ptr;
2787                     self.ptr = self.ptr.offset(offset);
2788                     old
2789                 }
2790             }
2791
2792             // Helper function for moving the end of the iterator backwards by `offset` elements,
2793             // returning the new end.
2794             // Unsafe because the offset must be in-bounds or one-past-the-end.
2795             #[inline(always)]
2796             unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T {
2797                 if mem::size_of::<T>() == 0 {
2798                     self.end = (self.end as * $raw_mut u8).wrapping_offset(-offset) as * $raw_mut T;
2799                     self.ptr
2800                 } else {
2801                     self.end = self.end.offset(-offset);
2802                     self.end
2803                 }
2804             }
2805         }
2806
2807         #[stable(feature = "rust1", since = "1.0.0")]
2808         impl<'a, T> ExactSizeIterator for $name<'a, T> {
2809             #[inline(always)]
2810             fn len(&self) -> usize {
2811                 len!(self)
2812             }
2813
2814             #[inline(always)]
2815             fn is_empty(&self) -> bool {
2816                 is_empty!(self)
2817             }
2818         }
2819
2820         #[stable(feature = "rust1", since = "1.0.0")]
2821         impl<'a, T> Iterator for $name<'a, T> {
2822             type Item = $elem;
2823
2824             #[inline]
2825             fn next(&mut self) -> Option<$elem> {
2826                 // could be implemented with slices, but this avoids bounds checks
2827                 unsafe {
2828                     assume(!self.ptr.is_null());
2829                     if mem::size_of::<T>() != 0 {
2830                         assume(!self.end.is_null());
2831                     }
2832                     if is_empty!(self) {
2833                         None
2834                     } else {
2835                         Some(& $( $mut_ )* *self.post_inc_start(1))
2836                     }
2837                 }
2838             }
2839
2840             #[inline]
2841             fn size_hint(&self) -> (usize, Option<usize>) {
2842                 let exact = len!(self);
2843                 (exact, Some(exact))
2844             }
2845
2846             #[inline]
2847             fn count(self) -> usize {
2848                 len!(self)
2849             }
2850
2851             #[inline]
2852             fn nth(&mut self, n: usize) -> Option<$elem> {
2853                 if n >= len!(self) {
2854                     // This iterator is now empty.
2855                     if mem::size_of::<T>() == 0 {
2856                         // We have to do it this way as `ptr` may never be 0, but `end`
2857                         // could be (due to wrapping).
2858                         self.end = self.ptr;
2859                     } else {
2860                         self.ptr = self.end;
2861                     }
2862                     return None;
2863                 }
2864                 // We are in bounds. `offset` does the right thing even for ZSTs.
2865                 unsafe {
2866                     let elem = Some(& $( $mut_ )* *self.ptr.add(n));
2867                     self.post_inc_start((n as isize).wrapping_add(1));
2868                     elem
2869                 }
2870             }
2871
2872             #[inline]
2873             fn last(mut self) -> Option<$elem> {
2874                 self.next_back()
2875             }
2876
2877             #[inline]
2878             fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
2879                 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
2880             {
2881                 // manual unrolling is needed when there are conditional exits from the loop
2882                 let mut accum = init;
2883                 unsafe {
2884                     while len!(self) >= 4 {
2885                         accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2886                         accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2887                         accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2888                         accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2889                     }
2890                     while !is_empty!(self) {
2891                         accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2892                     }
2893                 }
2894                 Try::from_ok(accum)
2895             }
2896
2897             #[inline]
2898             fn fold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
2899                 where Fold: FnMut(Acc, Self::Item) -> Acc,
2900             {
2901                 // Let LLVM unroll this, rather than using the default
2902                 // impl that would force the manual unrolling above
2903                 let mut accum = init;
2904                 while let Some(x) = self.next() {
2905                     accum = f(accum, x);
2906                 }
2907                 accum
2908             }
2909
2910             #[inline]
2911             #[rustc_inherit_overflow_checks]
2912             fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
2913                 Self: Sized,
2914                 P: FnMut(Self::Item) -> bool,
2915             {
2916                 // The addition might panic on overflow.
2917                 let n = len!(self);
2918                 self.try_fold(0, move |i, x| {
2919                     if predicate(x) { Err(i) }
2920                     else { Ok(i + 1) }
2921                 }).err()
2922                     .map(|i| {
2923                         unsafe { assume(i < n) };
2924                         i
2925                     })
2926             }
2927
2928             #[inline]
2929             fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
2930                 P: FnMut(Self::Item) -> bool,
2931                 Self: Sized + ExactSizeIterator + DoubleEndedIterator
2932             {
2933                 // No need for an overflow check here, because `ExactSizeIterator`
2934                 let n = len!(self);
2935                 self.try_rfold(n, move |i, x| {
2936                     let i = i - 1;
2937                     if predicate(x) { Err(i) }
2938                     else { Ok(i) }
2939                 }).err()
2940                     .map(|i| {
2941                         unsafe { assume(i < n) };
2942                         i
2943                     })
2944             }
2945         }
2946
2947         #[stable(feature = "rust1", since = "1.0.0")]
2948         impl<'a, T> DoubleEndedIterator for $name<'a, T> {
2949             #[inline]
2950             fn next_back(&mut self) -> Option<$elem> {
2951                 // could be implemented with slices, but this avoids bounds checks
2952                 unsafe {
2953                     assume(!self.ptr.is_null());
2954                     if mem::size_of::<T>() != 0 {
2955                         assume(!self.end.is_null());
2956                     }
2957                     if is_empty!(self) {
2958                         None
2959                     } else {
2960                         Some(& $( $mut_ )* *self.pre_dec_end(1))
2961                     }
2962                 }
2963             }
2964
2965             #[inline]
2966             fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where
2967                 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
2968             {
2969                 // manual unrolling is needed when there are conditional exits from the loop
2970                 let mut accum = init;
2971                 unsafe {
2972                     while len!(self) >= 4 {
2973                         accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2974                         accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2975                         accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2976                         accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2977                     }
2978                     // inlining is_empty everywhere makes a huge performance difference
2979                     while !is_empty!(self) {
2980                         accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2981                     }
2982                 }
2983                 Try::from_ok(accum)
2984             }
2985
2986             #[inline]
2987             fn rfold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
2988                 where Fold: FnMut(Acc, Self::Item) -> Acc,
2989             {
2990                 // Let LLVM unroll this, rather than using the default
2991                 // impl that would force the manual unrolling above
2992                 let mut accum = init;
2993                 while let Some(x) = self.next_back() {
2994                     accum = f(accum, x);
2995                 }
2996                 accum
2997             }
2998         }
2999
3000         #[stable(feature = "fused", since = "1.26.0")]
3001         impl<'a, T> FusedIterator for $name<'a, T> {}
3002
3003         #[unstable(feature = "trusted_len", issue = "37572")]
3004         unsafe impl<'a, T> TrustedLen for $name<'a, T> {}
3005     }
3006 }
3007
3008 /// Immutable slice iterator
3009 ///
3010 /// This struct is created by the [`iter`] method on [slices].
3011 ///
3012 /// # Examples
3013 ///
3014 /// Basic usage:
3015 ///
3016 /// ```
3017 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
3018 /// let slice = &[1, 2, 3];
3019 ///
3020 /// // Then, we iterate over it:
3021 /// for element in slice.iter() {
3022 ///     println!("{}", element);
3023 /// }
3024 /// ```
3025 ///
3026 /// [`iter`]: ../../std/primitive.slice.html#method.iter
3027 /// [slices]: ../../std/primitive.slice.html
3028 #[stable(feature = "rust1", since = "1.0.0")]
3029 pub struct Iter<'a, T: 'a> {
3030     ptr: *const T,
3031     end: *const T, // If T is a ZST, this is actually ptr+len.  This encoding is picked so that
3032                    // ptr == end is a quick test for the Iterator being empty, that works
3033                    // for both ZST and non-ZST.
3034     _marker: marker::PhantomData<&'a T>,
3035 }
3036
3037 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3038 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
3039     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3040         f.debug_tuple("Iter")
3041             .field(&self.as_slice())
3042             .finish()
3043     }
3044 }
3045
3046 #[stable(feature = "rust1", since = "1.0.0")]
3047 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
3048 #[stable(feature = "rust1", since = "1.0.0")]
3049 unsafe impl<T: Sync> Send for Iter<'_, T> {}
3050
3051 impl<'a, T> Iter<'a, T> {
3052     /// View the underlying data as a subslice of the original data.
3053     ///
3054     /// This has the same lifetime as the original slice, and so the
3055     /// iterator can continue to be used while this exists.
3056     ///
3057     /// # Examples
3058     ///
3059     /// Basic usage:
3060     ///
3061     /// ```
3062     /// // First, we declare a type which has the `iter` method to get the `Iter`
3063     /// // struct (&[usize here]):
3064     /// let slice = &[1, 2, 3];
3065     ///
3066     /// // Then, we get the iterator:
3067     /// let mut iter = slice.iter();
3068     /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
3069     /// println!("{:?}", iter.as_slice());
3070     ///
3071     /// // Next, we move to the second element of the slice:
3072     /// iter.next();
3073     /// // Now `as_slice` returns "[2, 3]":
3074     /// println!("{:?}", iter.as_slice());
3075     /// ```
3076     #[stable(feature = "iter_to_slice", since = "1.4.0")]
3077     pub fn as_slice(&self) -> &'a [T] {
3078         self.make_slice()
3079     }
3080 }
3081
3082 iterator!{struct Iter -> *const T, &'a T, const, /* no mut */}
3083
3084 #[stable(feature = "rust1", since = "1.0.0")]
3085 impl<T> Clone for Iter<'_, T> {
3086     fn clone(&self) -> Self { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
3087 }
3088
3089 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
3090 impl<T> AsRef<[T]> for Iter<'_, T> {
3091     fn as_ref(&self) -> &[T] {
3092         self.as_slice()
3093     }
3094 }
3095
3096 /// Mutable slice iterator.
3097 ///
3098 /// This struct is created by the [`iter_mut`] method on [slices].
3099 ///
3100 /// # Examples
3101 ///
3102 /// Basic usage:
3103 ///
3104 /// ```
3105 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3106 /// // struct (&[usize here]):
3107 /// let mut slice = &mut [1, 2, 3];
3108 ///
3109 /// // Then, we iterate over it and increment each element value:
3110 /// for element in slice.iter_mut() {
3111 ///     *element += 1;
3112 /// }
3113 ///
3114 /// // We now have "[2, 3, 4]":
3115 /// println!("{:?}", slice);
3116 /// ```
3117 ///
3118 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
3119 /// [slices]: ../../std/primitive.slice.html
3120 #[stable(feature = "rust1", since = "1.0.0")]
3121 pub struct IterMut<'a, T: 'a> {
3122     ptr: *mut T,
3123     end: *mut T, // If T is a ZST, this is actually ptr+len.  This encoding is picked so that
3124                  // ptr == end is a quick test for the Iterator being empty, that works
3125                  // for both ZST and non-ZST.
3126     _marker: marker::PhantomData<&'a mut T>,
3127 }
3128
3129 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3130 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
3131     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3132         f.debug_tuple("IterMut")
3133             .field(&self.make_slice())
3134             .finish()
3135     }
3136 }
3137
3138 #[stable(feature = "rust1", since = "1.0.0")]
3139 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
3140 #[stable(feature = "rust1", since = "1.0.0")]
3141 unsafe impl<T: Send> Send for IterMut<'_, T> {}
3142
3143 impl<'a, T> IterMut<'a, T> {
3144     /// View the underlying data as a subslice of the original data.
3145     ///
3146     /// To avoid creating `&mut` references that alias, this is forced
3147     /// to consume the iterator.
3148     ///
3149     /// # Examples
3150     ///
3151     /// Basic usage:
3152     ///
3153     /// ```
3154     /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3155     /// // struct (&[usize here]):
3156     /// let mut slice = &mut [1, 2, 3];
3157     ///
3158     /// {
3159     ///     // Then, we get the iterator:
3160     ///     let mut iter = slice.iter_mut();
3161     ///     // We move to next element:
3162     ///     iter.next();
3163     ///     // So if we print what `into_slice` method returns here, we have "[2, 3]":
3164     ///     println!("{:?}", iter.into_slice());
3165     /// }
3166     ///
3167     /// // Now let's modify a value of the slice:
3168     /// {
3169     ///     // First we get back the iterator:
3170     ///     let mut iter = slice.iter_mut();
3171     ///     // We change the value of the first element of the slice returned by the `next` method:
3172     ///     *iter.next().unwrap() += 1;
3173     /// }
3174     /// // Now slice is "[2, 2, 3]":
3175     /// println!("{:?}", slice);
3176     /// ```
3177     #[stable(feature = "iter_to_slice", since = "1.4.0")]
3178     pub fn into_slice(self) -> &'a mut [T] {
3179         unsafe { from_raw_parts_mut(self.ptr, len!(self)) }
3180     }
3181 }
3182
3183 iterator!{struct IterMut -> *mut T, &'a mut T, mut, mut}
3184
3185 /// An internal abstraction over the splitting iterators, so that
3186 /// splitn, splitn_mut etc can be implemented once.
3187 #[doc(hidden)]
3188 trait SplitIter: DoubleEndedIterator {
3189     /// Marks the underlying iterator as complete, extracting the remaining
3190     /// portion of the slice.
3191     fn finish(&mut self) -> Option<Self::Item>;
3192 }
3193
3194 /// An iterator over subslices separated by elements that match a predicate
3195 /// function.
3196 ///
3197 /// This struct is created by the [`split`] method on [slices].
3198 ///
3199 /// [`split`]: ../../std/primitive.slice.html#method.split
3200 /// [slices]: ../../std/primitive.slice.html
3201 #[stable(feature = "rust1", since = "1.0.0")]
3202 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
3203     v: &'a [T],
3204     pred: P,
3205     finished: bool
3206 }
3207
3208 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3209 impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P> where P: FnMut(&T) -> bool {
3210     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3211         f.debug_struct("Split")
3212             .field("v", &self.v)
3213             .field("finished", &self.finished)
3214             .finish()
3215     }
3216 }
3217
3218 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3219 #[stable(feature = "rust1", since = "1.0.0")]
3220 impl<T, P> Clone for Split<'_, T, P> where P: Clone + FnMut(&T) -> bool {
3221     fn clone(&self) -> Self {
3222         Split {
3223             v: self.v,
3224             pred: self.pred.clone(),
3225             finished: self.finished,
3226         }
3227     }
3228 }
3229
3230 #[stable(feature = "rust1", since = "1.0.0")]
3231 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
3232     type Item = &'a [T];
3233
3234     #[inline]
3235     fn next(&mut self) -> Option<&'a [T]> {
3236         if self.finished { return None; }
3237
3238         match self.v.iter().position(|x| (self.pred)(x)) {
3239             None => self.finish(),
3240             Some(idx) => {
3241                 let ret = Some(&self.v[..idx]);
3242                 self.v = &self.v[idx + 1..];
3243                 ret
3244             }
3245         }
3246     }
3247
3248     #[inline]
3249     fn size_hint(&self) -> (usize, Option<usize>) {
3250         if self.finished {
3251             (0, Some(0))
3252         } else {
3253             (1, Some(self.v.len() + 1))
3254         }
3255     }
3256 }
3257
3258 #[stable(feature = "rust1", since = "1.0.0")]
3259 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
3260     #[inline]
3261     fn next_back(&mut self) -> Option<&'a [T]> {
3262         if self.finished { return None; }
3263
3264         match self.v.iter().rposition(|x| (self.pred)(x)) {
3265             None => self.finish(),
3266             Some(idx) => {
3267                 let ret = Some(&self.v[idx + 1..]);
3268                 self.v = &self.v[..idx];
3269                 ret
3270             }
3271         }
3272     }
3273 }
3274
3275 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
3276     #[inline]
3277     fn finish(&mut self) -> Option<&'a [T]> {
3278         if self.finished { None } else { self.finished = true; Some(self.v) }
3279     }
3280 }
3281
3282 #[stable(feature = "fused", since = "1.26.0")]
3283 impl<T, P> FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {}
3284
3285 /// An iterator over the subslices of the vector which are separated
3286 /// by elements that match `pred`.
3287 ///
3288 /// This struct is created by the [`split_mut`] method on [slices].
3289 ///
3290 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
3291 /// [slices]: ../../std/primitive.slice.html
3292 #[stable(feature = "rust1", since = "1.0.0")]
3293 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3294     v: &'a mut [T],
3295     pred: P,
3296     finished: bool
3297 }
3298
3299 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3300 impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {
3301     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3302         f.debug_struct("SplitMut")
3303             .field("v", &self.v)
3304             .field("finished", &self.finished)
3305             .finish()
3306     }
3307 }
3308
3309 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3310     #[inline]
3311     fn finish(&mut self) -> Option<&'a mut [T]> {
3312         if self.finished {
3313             None
3314         } else {
3315             self.finished = true;
3316             Some(mem::replace(&mut self.v, &mut []))
3317         }
3318     }
3319 }
3320
3321 #[stable(feature = "rust1", since = "1.0.0")]
3322 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3323     type Item = &'a mut [T];
3324
3325     #[inline]
3326     fn next(&mut self) -> Option<&'a mut [T]> {
3327         if self.finished { return None; }
3328
3329         let idx_opt = { // work around borrowck limitations
3330             let pred = &mut self.pred;
3331             self.v.iter().position(|x| (*pred)(x))
3332         };
3333         match idx_opt {
3334             None => self.finish(),
3335             Some(idx) => {
3336                 let tmp = mem::replace(&mut self.v, &mut []);
3337                 let (head, tail) = tmp.split_at_mut(idx);
3338                 self.v = &mut tail[1..];
3339                 Some(head)
3340             }
3341         }
3342     }
3343
3344     #[inline]
3345     fn size_hint(&self) -> (usize, Option<usize>) {
3346         if self.finished {
3347             (0, Some(0))
3348         } else {
3349             // if the predicate doesn't match anything, we yield one slice
3350             // if it matches every element, we yield len+1 empty slices.
3351             (1, Some(self.v.len() + 1))
3352         }
3353     }
3354 }
3355
3356 #[stable(feature = "rust1", since = "1.0.0")]
3357 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
3358     P: FnMut(&T) -> bool,
3359 {
3360     #[inline]
3361     fn next_back(&mut self) -> Option<&'a mut [T]> {
3362         if self.finished { return None; }
3363
3364         let idx_opt = { // work around borrowck limitations
3365             let pred = &mut self.pred;
3366             self.v.iter().rposition(|x| (*pred)(x))
3367         };
3368         match idx_opt {
3369             None => self.finish(),
3370             Some(idx) => {
3371                 let tmp = mem::replace(&mut self.v, &mut []);
3372                 let (head, tail) = tmp.split_at_mut(idx);
3373                 self.v = head;
3374                 Some(&mut tail[1..])
3375             }
3376         }
3377     }
3378 }
3379
3380 #[stable(feature = "fused", since = "1.26.0")]
3381 impl<T, P> FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
3382
3383 /// An iterator over subslices separated by elements that match a predicate
3384 /// function, starting from the end of the slice.
3385 ///
3386 /// This struct is created by the [`rsplit`] method on [slices].
3387 ///
3388 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
3389 /// [slices]: ../../std/primitive.slice.html
3390 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3391 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
3392 pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool {
3393     inner: Split<'a, T, P>
3394 }
3395
3396 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3397 impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P> where P: FnMut(&T) -> bool {
3398     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3399         f.debug_struct("RSplit")
3400             .field("v", &self.inner.v)
3401             .field("finished", &self.inner.finished)
3402             .finish()
3403     }
3404 }
3405
3406 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3407 impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3408     type Item = &'a [T];
3409
3410     #[inline]
3411     fn next(&mut self) -> Option<&'a [T]> {
3412         self.inner.next_back()
3413     }
3414
3415     #[inline]
3416     fn size_hint(&self) -> (usize, Option<usize>) {
3417         self.inner.size_hint()
3418     }
3419 }
3420
3421 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3422 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3423     #[inline]
3424     fn next_back(&mut self) -> Option<&'a [T]> {
3425         self.inner.next()
3426     }
3427 }
3428
3429 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3430 impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3431     #[inline]
3432     fn finish(&mut self) -> Option<&'a [T]> {
3433         self.inner.finish()
3434     }
3435 }
3436
3437 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3438 impl<T, P> FusedIterator for RSplit<'_, T, P> where P: FnMut(&T) -> bool {}
3439
3440 /// An iterator over the subslices of the vector which are separated
3441 /// by elements that match `pred`, starting from the end of the slice.
3442 ///
3443 /// This struct is created by the [`rsplit_mut`] method on [slices].
3444 ///
3445 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
3446 /// [slices]: ../../std/primitive.slice.html
3447 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3448 pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3449     inner: SplitMut<'a, T, P>
3450 }
3451
3452 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3453 impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {
3454     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3455         f.debug_struct("RSplitMut")
3456             .field("v", &self.inner.v)
3457             .field("finished", &self.inner.finished)
3458             .finish()
3459     }
3460 }
3461
3462 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3463 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3464     #[inline]
3465     fn finish(&mut self) -> Option<&'a mut [T]> {
3466         self.inner.finish()
3467     }
3468 }
3469
3470 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3471 impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3472     type Item = &'a mut [T];
3473
3474     #[inline]
3475     fn next(&mut self) -> Option<&'a mut [T]> {
3476         self.inner.next_back()
3477     }
3478
3479     #[inline]
3480     fn size_hint(&self) -> (usize, Option<usize>) {
3481         self.inner.size_hint()
3482     }
3483 }
3484
3485 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3486 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where
3487     P: FnMut(&T) -> bool,
3488 {
3489     #[inline]
3490     fn next_back(&mut self) -> Option<&'a mut [T]> {
3491         self.inner.next()
3492     }
3493 }
3494
3495 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3496 impl<T, P> FusedIterator for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
3497
3498 /// An private iterator over subslices separated by elements that
3499 /// match a predicate function, splitting at most a fixed number of
3500 /// times.
3501 #[derive(Debug)]
3502 struct GenericSplitN<I> {
3503     iter: I,
3504     count: usize,
3505 }
3506
3507 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
3508     type Item = T;
3509
3510     #[inline]
3511     fn next(&mut self) -> Option<T> {
3512         match self.count {
3513             0 => None,
3514             1 => { self.count -= 1; self.iter.finish() }
3515             _ => { self.count -= 1; self.iter.next() }
3516         }
3517     }
3518
3519     #[inline]
3520     fn size_hint(&self) -> (usize, Option<usize>) {
3521         let (lower, upper_opt) = self.iter.size_hint();
3522         (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
3523     }
3524 }
3525
3526 /// An iterator over subslices separated by elements that match a predicate
3527 /// function, limited to a given number of splits.
3528 ///
3529 /// This struct is created by the [`splitn`] method on [slices].
3530 ///
3531 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
3532 /// [slices]: ../../std/primitive.slice.html
3533 #[stable(feature = "rust1", since = "1.0.0")]
3534 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3535     inner: GenericSplitN<Split<'a, T, P>>
3536 }
3537
3538 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3539 impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P> where P: FnMut(&T) -> bool {
3540     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3541         f.debug_struct("SplitN")
3542             .field("inner", &self.inner)
3543             .finish()
3544     }
3545 }
3546
3547 /// An iterator over subslices separated by elements that match a
3548 /// predicate function, limited to a given number of splits, starting
3549 /// from the end of the slice.
3550 ///
3551 /// This struct is created by the [`rsplitn`] method on [slices].
3552 ///
3553 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
3554 /// [slices]: ../../std/primitive.slice.html
3555 #[stable(feature = "rust1", since = "1.0.0")]
3556 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3557     inner: GenericSplitN<RSplit<'a, T, P>>
3558 }
3559
3560 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3561 impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P> where P: FnMut(&T) -> bool {
3562     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3563         f.debug_struct("RSplitN")
3564             .field("inner", &self.inner)
3565             .finish()
3566     }
3567 }
3568
3569 /// An iterator over subslices separated by elements that match a predicate
3570 /// function, limited to a given number of splits.
3571 ///
3572 /// This struct is created by the [`splitn_mut`] method on [slices].
3573 ///
3574 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
3575 /// [slices]: ../../std/primitive.slice.html
3576 #[stable(feature = "rust1", since = "1.0.0")]
3577 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3578     inner: GenericSplitN<SplitMut<'a, T, P>>
3579 }
3580
3581 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3582 impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P> where P: FnMut(&T) -> bool {
3583     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3584         f.debug_struct("SplitNMut")
3585             .field("inner", &self.inner)
3586             .finish()
3587     }
3588 }
3589
3590 /// An iterator over subslices separated by elements that match a
3591 /// predicate function, limited to a given number of splits, starting
3592 /// from the end of the slice.
3593 ///
3594 /// This struct is created by the [`rsplitn_mut`] method on [slices].
3595 ///
3596 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
3597 /// [slices]: ../../std/primitive.slice.html
3598 #[stable(feature = "rust1", since = "1.0.0")]
3599 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3600     inner: GenericSplitN<RSplitMut<'a, T, P>>
3601 }
3602
3603 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3604 impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P> where P: FnMut(&T) -> bool {
3605     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3606         f.debug_struct("RSplitNMut")
3607             .field("inner", &self.inner)
3608             .finish()
3609     }
3610 }
3611
3612 macro_rules! forward_iterator {
3613     ($name:ident: $elem:ident, $iter_of:ty) => {
3614         #[stable(feature = "rust1", since = "1.0.0")]
3615         impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
3616             P: FnMut(&T) -> bool
3617         {
3618             type Item = $iter_of;
3619
3620             #[inline]
3621             fn next(&mut self) -> Option<$iter_of> {
3622                 self.inner.next()
3623             }
3624
3625             #[inline]
3626             fn size_hint(&self) -> (usize, Option<usize>) {
3627                 self.inner.size_hint()
3628             }
3629         }
3630
3631         #[stable(feature = "fused", since = "1.26.0")]
3632         impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
3633             where P: FnMut(&T) -> bool {}
3634     }
3635 }
3636
3637 forward_iterator! { SplitN: T, &'a [T] }
3638 forward_iterator! { RSplitN: T, &'a [T] }
3639 forward_iterator! { SplitNMut: T, &'a mut [T] }
3640 forward_iterator! { RSplitNMut: T, &'a mut [T] }
3641
3642 /// An iterator over overlapping subslices of length `size`.
3643 ///
3644 /// This struct is created by the [`windows`] method on [slices].
3645 ///
3646 /// [`windows`]: ../../std/primitive.slice.html#method.windows
3647 /// [slices]: ../../std/primitive.slice.html
3648 #[derive(Debug)]
3649 #[stable(feature = "rust1", since = "1.0.0")]
3650 pub struct Windows<'a, T:'a> {
3651     v: &'a [T],
3652     size: usize
3653 }
3654
3655 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3656 #[stable(feature = "rust1", since = "1.0.0")]
3657 impl<T> Clone for Windows<'_, T> {
3658     fn clone(&self) -> Self {
3659         Windows {
3660             v: self.v,
3661             size: self.size,
3662         }
3663     }
3664 }
3665
3666 #[stable(feature = "rust1", since = "1.0.0")]
3667 impl<'a, T> Iterator for Windows<'a, T> {
3668     type Item = &'a [T];
3669
3670     #[inline]
3671     fn next(&mut self) -> Option<&'a [T]> {
3672         if self.size > self.v.len() {
3673             None
3674         } else {
3675             let ret = Some(&self.v[..self.size]);
3676             self.v = &self.v[1..];
3677             ret
3678         }
3679     }
3680
3681     #[inline]
3682     fn size_hint(&self) -> (usize, Option<usize>) {
3683         if self.size > self.v.len() {
3684             (0, Some(0))
3685         } else {
3686             let size = self.v.len() - self.size + 1;
3687             (size, Some(size))
3688         }
3689     }
3690
3691     #[inline]
3692     fn count(self) -> usize {
3693         self.len()
3694     }
3695
3696     #[inline]
3697     fn nth(&mut self, n: usize) -> Option<Self::Item> {
3698         let (end, overflow) = self.size.overflowing_add(n);
3699         if end > self.v.len() || overflow {
3700             self.v = &[];
3701             None
3702         } else {
3703             let nth = &self.v[n..end];
3704             self.v = &self.v[n+1..];
3705             Some(nth)
3706         }
3707     }
3708
3709     #[inline]
3710     fn last(self) -> Option<Self::Item> {
3711         if self.size > self.v.len() {
3712             None
3713         } else {
3714             let start = self.v.len() - self.size;
3715             Some(&self.v[start..])
3716         }
3717     }
3718 }
3719
3720 #[stable(feature = "rust1", since = "1.0.0")]
3721 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
3722     #[inline]
3723     fn next_back(&mut self) -> Option<&'a [T]> {
3724         if self.size > self.v.len() {
3725             None
3726         } else {
3727             let ret = Some(&self.v[self.v.len()-self.size..]);
3728             self.v = &self.v[..self.v.len()-1];
3729             ret
3730         }
3731     }
3732 }
3733
3734 #[stable(feature = "rust1", since = "1.0.0")]
3735 impl<T> ExactSizeIterator for Windows<'_, T> {}
3736
3737 #[unstable(feature = "trusted_len", issue = "37572")]
3738 unsafe impl<T> TrustedLen for Windows<'_, T> {}
3739
3740 #[stable(feature = "fused", since = "1.26.0")]
3741 impl<T> FusedIterator for Windows<'_, T> {}
3742
3743 #[doc(hidden)]
3744 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
3745     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3746         from_raw_parts(self.v.as_ptr().add(i), self.size)
3747     }
3748     fn may_have_side_effect() -> bool { false }
3749 }
3750
3751 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
3752 /// time), starting at the beginning of the slice.
3753 ///
3754 /// When the slice len is not evenly divided by the chunk size, the last slice
3755 /// of the iteration will be the remainder.
3756 ///
3757 /// This struct is created by the [`chunks`] method on [slices].
3758 ///
3759 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
3760 /// [slices]: ../../std/primitive.slice.html
3761 #[derive(Debug)]
3762 #[stable(feature = "rust1", since = "1.0.0")]
3763 pub struct Chunks<'a, T:'a> {
3764     v: &'a [T],
3765     chunk_size: usize
3766 }
3767
3768 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3769 #[stable(feature = "rust1", since = "1.0.0")]
3770 impl<T> Clone for Chunks<'_, T> {
3771     fn clone(&self) -> Self {
3772         Chunks {
3773             v: self.v,
3774             chunk_size: self.chunk_size,
3775         }
3776     }
3777 }
3778
3779 #[stable(feature = "rust1", since = "1.0.0")]
3780 impl<'a, T> Iterator for Chunks<'a, T> {
3781     type Item = &'a [T];
3782
3783     #[inline]
3784     fn next(&mut self) -> Option<&'a [T]> {
3785         if self.v.is_empty() {
3786             None
3787         } else {
3788             let chunksz = cmp::min(self.v.len(), self.chunk_size);
3789             let (fst, snd) = self.v.split_at(chunksz);
3790             self.v = snd;
3791             Some(fst)
3792         }
3793     }
3794
3795     #[inline]
3796     fn size_hint(&self) -> (usize, Option<usize>) {
3797         if self.v.is_empty() {
3798             (0, Some(0))
3799         } else {
3800             let n = self.v.len() / self.chunk_size;
3801             let rem = self.v.len() % self.chunk_size;
3802             let n = if rem > 0 { n+1 } else { n };
3803             (n, Some(n))
3804         }
3805     }
3806
3807     #[inline]
3808     fn count(self) -> usize {
3809         self.len()
3810     }
3811
3812     #[inline]
3813     fn nth(&mut self, n: usize) -> Option<Self::Item> {
3814         let (start, overflow) = n.overflowing_mul(self.chunk_size);
3815         if start >= self.v.len() || overflow {
3816             self.v = &[];
3817             None
3818         } else {
3819             let end = match start.checked_add(self.chunk_size) {
3820                 Some(sum) => cmp::min(self.v.len(), sum),
3821                 None => self.v.len(),
3822             };
3823             let nth = &self.v[start..end];
3824             self.v = &self.v[end..];
3825             Some(nth)
3826         }
3827     }
3828
3829     #[inline]
3830     fn last(self) -> Option<Self::Item> {
3831         if self.v.is_empty() {
3832             None
3833         } else {
3834             let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
3835             Some(&self.v[start..])
3836         }
3837     }
3838 }
3839
3840 #[stable(feature = "rust1", since = "1.0.0")]
3841 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
3842     #[inline]
3843     fn next_back(&mut self) -> Option<&'a [T]> {
3844         if self.v.is_empty() {
3845             None
3846         } else {
3847             let remainder = self.v.len() % self.chunk_size;
3848             let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
3849             let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
3850             self.v = fst;
3851             Some(snd)
3852         }
3853     }
3854 }
3855
3856 #[stable(feature = "rust1", since = "1.0.0")]
3857 impl<T> ExactSizeIterator for Chunks<'_, T> {}
3858
3859 #[unstable(feature = "trusted_len", issue = "37572")]
3860 unsafe impl<T> TrustedLen for Chunks<'_, T> {}
3861
3862 #[stable(feature = "fused", since = "1.26.0")]
3863 impl<T> FusedIterator for Chunks<'_, T> {}
3864
3865 #[doc(hidden)]
3866 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
3867     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3868         let start = i * self.chunk_size;
3869         let end = match start.checked_add(self.chunk_size) {
3870             None => self.v.len(),
3871             Some(end) => cmp::min(end, self.v.len()),
3872         };
3873         from_raw_parts(self.v.as_ptr().add(start), end - start)
3874     }
3875     fn may_have_side_effect() -> bool { false }
3876 }
3877
3878 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
3879 /// elements at a time), starting at the beginning of the slice.
3880 ///
3881 /// When the slice len is not evenly divided by the chunk size, the last slice
3882 /// of the iteration will be the remainder.
3883 ///
3884 /// This struct is created by the [`chunks_mut`] method on [slices].
3885 ///
3886 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
3887 /// [slices]: ../../std/primitive.slice.html
3888 #[derive(Debug)]
3889 #[stable(feature = "rust1", since = "1.0.0")]
3890 pub struct ChunksMut<'a, T:'a> {
3891     v: &'a mut [T],
3892     chunk_size: usize
3893 }
3894
3895 #[stable(feature = "rust1", since = "1.0.0")]
3896 impl<'a, T> Iterator for ChunksMut<'a, T> {
3897     type Item = &'a mut [T];
3898
3899     #[inline]
3900     fn next(&mut self) -> Option<&'a mut [T]> {
3901         if self.v.is_empty() {
3902             None
3903         } else {
3904             let sz = cmp::min(self.v.len(), self.chunk_size);
3905             let tmp = mem::replace(&mut self.v, &mut []);
3906             let (head, tail) = tmp.split_at_mut(sz);
3907             self.v = tail;
3908             Some(head)
3909         }
3910     }
3911
3912     #[inline]
3913     fn size_hint(&self) -> (usize, Option<usize>) {
3914         if self.v.is_empty() {
3915             (0, Some(0))
3916         } else {
3917             let n = self.v.len() / self.chunk_size;
3918             let rem = self.v.len() % self.chunk_size;
3919             let n = if rem > 0 { n + 1 } else { n };
3920             (n, Some(n))
3921         }
3922     }
3923
3924     #[inline]
3925     fn count(self) -> usize {
3926         self.len()
3927     }
3928
3929     #[inline]
3930     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
3931         let (start, overflow) = n.overflowing_mul(self.chunk_size);
3932         if start >= self.v.len() || overflow {
3933             self.v = &mut [];
3934             None
3935         } else {
3936             let end = match start.checked_add(self.chunk_size) {
3937                 Some(sum) => cmp::min(self.v.len(), sum),
3938                 None => self.v.len(),
3939             };
3940             let tmp = mem::replace(&mut self.v, &mut []);
3941             let (head, tail) = tmp.split_at_mut(end);
3942             let (_, nth) =  head.split_at_mut(start);
3943             self.v = tail;
3944             Some(nth)
3945         }
3946     }
3947
3948     #[inline]
3949     fn last(self) -> Option<Self::Item> {
3950         if self.v.is_empty() {
3951             None
3952         } else {
3953             let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
3954             Some(&mut self.v[start..])
3955         }
3956     }
3957 }
3958
3959 #[stable(feature = "rust1", since = "1.0.0")]
3960 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
3961     #[inline]
3962     fn next_back(&mut self) -> Option<&'a mut [T]> {
3963         if self.v.is_empty() {
3964             None
3965         } else {
3966             let remainder = self.v.len() % self.chunk_size;
3967             let sz = if remainder != 0 { remainder } else { self.chunk_size };
3968             let tmp = mem::replace(&mut self.v, &mut []);
3969             let tmp_len = tmp.len();
3970             let (head, tail) = tmp.split_at_mut(tmp_len - sz);
3971             self.v = head;
3972             Some(tail)
3973         }
3974     }
3975 }
3976
3977 #[stable(feature = "rust1", since = "1.0.0")]
3978 impl<T> ExactSizeIterator for ChunksMut<'_, T> {}
3979
3980 #[unstable(feature = "trusted_len", issue = "37572")]
3981 unsafe impl<T> TrustedLen for ChunksMut<'_, T> {}
3982
3983 #[stable(feature = "fused", since = "1.26.0")]
3984 impl<T> FusedIterator for ChunksMut<'_, T> {}
3985
3986 #[doc(hidden)]
3987 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
3988     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
3989         let start = i * self.chunk_size;
3990         let end = match start.checked_add(self.chunk_size) {
3991             None => self.v.len(),
3992             Some(end) => cmp::min(end, self.v.len()),
3993         };
3994         from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start)
3995     }
3996     fn may_have_side_effect() -> bool { false }
3997 }
3998
3999 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4000 /// time), starting at the beginning of the slice.
4001 ///
4002 /// When the slice len is not evenly divided by the chunk size, the last
4003 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
4004 /// the [`remainder`] function from the iterator.
4005 ///
4006 /// This struct is created by the [`chunks_exact`] method on [slices].
4007 ///
4008 /// [`chunks_exact`]: ../../std/primitive.slice.html#method.chunks_exact
4009 /// [`remainder`]: ../../std/slice/struct.ChunksExact.html#method.remainder
4010 /// [slices]: ../../std/primitive.slice.html
4011 #[derive(Debug)]
4012 #[stable(feature = "chunks_exact", since = "1.31.0")]
4013 pub struct ChunksExact<'a, T:'a> {
4014     v: &'a [T],
4015     rem: &'a [T],
4016     chunk_size: usize
4017 }
4018
4019 impl<'a, T> ChunksExact<'a, T> {
4020     /// Return the remainder of the original slice that is not going to be
4021     /// returned by the iterator. The returned slice has at most `chunk_size-1`
4022     /// elements.
4023     #[stable(feature = "chunks_exact", since = "1.31.0")]
4024     pub fn remainder(&self) -> &'a [T] {
4025         self.rem
4026     }
4027 }
4028
4029 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4030 #[stable(feature = "chunks_exact", since = "1.31.0")]
4031 impl<T> Clone for ChunksExact<'_, T> {
4032     fn clone(&self) -> Self {
4033         ChunksExact {
4034             v: self.v,
4035             rem: self.rem,
4036             chunk_size: self.chunk_size,
4037         }
4038     }
4039 }
4040
4041 #[stable(feature = "chunks_exact", since = "1.31.0")]
4042 impl<'a, T> Iterator for ChunksExact<'a, T> {
4043     type Item = &'a [T];
4044
4045     #[inline]
4046     fn next(&mut self) -> Option<&'a [T]> {
4047         if self.v.len() < self.chunk_size {
4048             None
4049         } else {
4050             let (fst, snd) = self.v.split_at(self.chunk_size);
4051             self.v = snd;
4052             Some(fst)
4053         }
4054     }
4055
4056     #[inline]
4057     fn size_hint(&self) -> (usize, Option<usize>) {
4058         let n = self.v.len() / self.chunk_size;
4059         (n, Some(n))
4060     }
4061
4062     #[inline]
4063     fn count(self) -> usize {
4064         self.len()
4065     }
4066
4067     #[inline]
4068     fn nth(&mut self, n: usize) -> Option<Self::Item> {
4069         let (start, overflow) = n.overflowing_mul(self.chunk_size);
4070         if start >= self.v.len() || overflow {
4071             self.v = &[];
4072             None
4073         } else {
4074             let (_, snd) = self.v.split_at(start);
4075             self.v = snd;
4076             self.next()
4077         }
4078     }
4079
4080     #[inline]
4081     fn last(mut self) -> Option<Self::Item> {
4082         self.next_back()
4083     }
4084 }
4085
4086 #[stable(feature = "chunks_exact", since = "1.31.0")]
4087 impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> {
4088     #[inline]
4089     fn next_back(&mut self) -> Option<&'a [T]> {
4090         if self.v.len() < self.chunk_size {
4091             None
4092         } else {
4093             let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
4094             self.v = fst;
4095             Some(snd)
4096         }
4097     }
4098 }
4099
4100 #[stable(feature = "chunks_exact", since = "1.31.0")]
4101 impl<T> ExactSizeIterator for ChunksExact<'_, T> {
4102     fn is_empty(&self) -> bool {
4103         self.v.is_empty()
4104     }
4105 }
4106
4107 #[unstable(feature = "trusted_len", issue = "37572")]
4108 unsafe impl<T> TrustedLen for ChunksExact<'_, T> {}
4109
4110 #[stable(feature = "chunks_exact", since = "1.31.0")]
4111 impl<T> FusedIterator for ChunksExact<'_, T> {}
4112
4113 #[doc(hidden)]
4114 #[stable(feature = "chunks_exact", since = "1.31.0")]
4115 unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> {
4116     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4117         let start = i * self.chunk_size;
4118         from_raw_parts(self.v.as_ptr().add(start), self.chunk_size)
4119     }
4120     fn may_have_side_effect() -> bool { false }
4121 }
4122
4123 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4124 /// elements at a time), starting at the beginning of the slice.
4125 ///
4126 /// When the slice len is not evenly divided by the chunk size, the last up to
4127 /// `chunk_size-1` elements will be omitted but can be retrieved from the
4128 /// [`into_remainder`] function from the iterator.
4129 ///
4130 /// This struct is created by the [`chunks_exact_mut`] method on [slices].
4131 ///
4132 /// [`chunks_exact_mut`]: ../../std/primitive.slice.html#method.chunks_exact_mut
4133 /// [`into_remainder`]: ../../std/slice/struct.ChunksExactMut.html#method.into_remainder
4134 /// [slices]: ../../std/primitive.slice.html
4135 #[derive(Debug)]
4136 #[stable(feature = "chunks_exact", since = "1.31.0")]
4137 pub struct ChunksExactMut<'a, T:'a> {
4138     v: &'a mut [T],
4139     rem: &'a mut [T],
4140     chunk_size: usize
4141 }
4142
4143 impl<'a, T> ChunksExactMut<'a, T> {
4144     /// Return the remainder of the original slice that is not going to be
4145     /// returned by the iterator. The returned slice has at most `chunk_size-1`
4146     /// elements.
4147     #[stable(feature = "chunks_exact", since = "1.31.0")]
4148     pub fn into_remainder(self) -> &'a mut [T] {
4149         self.rem
4150     }
4151 }
4152
4153 #[stable(feature = "chunks_exact", since = "1.31.0")]
4154 impl<'a, T> Iterator for ChunksExactMut<'a, T> {
4155     type Item = &'a mut [T];
4156
4157     #[inline]
4158     fn next(&mut self) -> Option<&'a mut [T]> {
4159         if self.v.len() < self.chunk_size {
4160             None
4161         } else {
4162             let tmp = mem::replace(&mut self.v, &mut []);
4163             let (head, tail) = tmp.split_at_mut(self.chunk_size);
4164             self.v = tail;
4165             Some(head)
4166         }
4167     }
4168
4169     #[inline]
4170     fn size_hint(&self) -> (usize, Option<usize>) {
4171         let n = self.v.len() / self.chunk_size;
4172         (n, Some(n))
4173     }
4174
4175     #[inline]
4176     fn count(self) -> usize {
4177         self.len()
4178     }
4179
4180     #[inline]
4181     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4182         let (start, overflow) = n.overflowing_mul(self.chunk_size);
4183         if start >= self.v.len() || overflow {
4184             self.v = &mut [];
4185             None
4186         } else {
4187             let tmp = mem::replace(&mut self.v, &mut []);
4188             let (_, snd) = tmp.split_at_mut(start);
4189             self.v = snd;
4190             self.next()
4191         }
4192     }
4193
4194     #[inline]
4195     fn last(mut self) -> Option<Self::Item> {
4196         self.next_back()
4197     }
4198 }
4199
4200 #[stable(feature = "chunks_exact", since = "1.31.0")]
4201 impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
4202     #[inline]
4203     fn next_back(&mut self) -> Option<&'a mut [T]> {
4204         if self.v.len() < self.chunk_size {
4205             None
4206         } else {
4207             let tmp = mem::replace(&mut self.v, &mut []);
4208             let tmp_len = tmp.len();
4209             let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
4210             self.v = head;
4211             Some(tail)
4212         }
4213     }
4214 }
4215
4216 #[stable(feature = "chunks_exact", since = "1.31.0")]
4217 impl<T> ExactSizeIterator for ChunksExactMut<'_, T> {
4218     fn is_empty(&self) -> bool {
4219         self.v.is_empty()
4220     }
4221 }
4222
4223 #[unstable(feature = "trusted_len", issue = "37572")]
4224 unsafe impl<T> TrustedLen for ChunksExactMut<'_, T> {}
4225
4226 #[stable(feature = "chunks_exact", since = "1.31.0")]
4227 impl<T> FusedIterator for ChunksExactMut<'_, T> {}
4228
4229 #[doc(hidden)]
4230 #[stable(feature = "chunks_exact", since = "1.31.0")]
4231 unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> {
4232     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4233         let start = i * self.chunk_size;
4234         from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size)
4235     }
4236     fn may_have_side_effect() -> bool { false }
4237 }
4238
4239 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4240 /// time), starting at the end of the slice.
4241 ///
4242 /// When the slice len is not evenly divided by the chunk size, the last slice
4243 /// of the iteration will be the remainder.
4244 ///
4245 /// This struct is created by the [`rchunks`] method on [slices].
4246 ///
4247 /// [`rchunks`]: ../../std/primitive.slice.html#method.rchunks
4248 /// [slices]: ../../std/primitive.slice.html
4249 #[derive(Debug)]
4250 #[stable(feature = "rchunks", since = "1.31.0")]
4251 pub struct RChunks<'a, T:'a> {
4252     v: &'a [T],
4253     chunk_size: usize
4254 }
4255
4256 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4257 #[stable(feature = "rchunks", since = "1.31.0")]
4258 impl<'a, T> Clone for RChunks<'a, T> {
4259     fn clone(&self) -> RChunks<'a, T> {
4260         RChunks {
4261             v: self.v,
4262             chunk_size: self.chunk_size,
4263         }
4264     }
4265 }
4266
4267 #[stable(feature = "rchunks", since = "1.31.0")]
4268 impl<'a, T> Iterator for RChunks<'a, T> {
4269     type Item = &'a [T];
4270
4271     #[inline]
4272     fn next(&mut self) -> Option<&'a [T]> {
4273         if self.v.is_empty() {
4274             None
4275         } else {
4276             let chunksz = cmp::min(self.v.len(), self.chunk_size);
4277             let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
4278             self.v = fst;
4279             Some(snd)
4280         }
4281     }
4282
4283     #[inline]
4284     fn size_hint(&self) -> (usize, Option<usize>) {
4285         if self.v.is_empty() {
4286             (0, Some(0))
4287         } else {
4288             let n = self.v.len() / self.chunk_size;
4289             let rem = self.v.len() % self.chunk_size;
4290             let n = if rem > 0 { n+1 } else { n };
4291             (n, Some(n))
4292         }
4293     }
4294
4295     #[inline]
4296     fn count(self) -> usize {
4297         self.len()
4298     }
4299
4300     #[inline]
4301     fn nth(&mut self, n: usize) -> Option<Self::Item> {
4302         let (end, overflow) = n.overflowing_mul(self.chunk_size);
4303         if end >= self.v.len() || overflow {
4304             self.v = &[];
4305             None
4306         } else {
4307             // Can't underflow because of the check above
4308             let end = self.v.len() - end;
4309             let start = match end.checked_sub(self.chunk_size) {
4310                 Some(sum) => sum,
4311                 None => 0,
4312             };
4313             let nth = &self.v[start..end];
4314             self.v = &self.v[0..start];
4315             Some(nth)
4316         }
4317     }
4318
4319     #[inline]
4320     fn last(self) -> Option<Self::Item> {
4321         if self.v.is_empty() {
4322             None
4323         } else {
4324             let rem = self.v.len() % self.chunk_size;
4325             let end = if rem == 0 { self.chunk_size } else { rem };
4326             Some(&self.v[0..end])
4327         }
4328     }
4329 }
4330
4331 #[stable(feature = "rchunks", since = "1.31.0")]
4332 impl<'a, T> DoubleEndedIterator for RChunks<'a, T> {
4333     #[inline]
4334     fn next_back(&mut self) -> Option<&'a [T]> {
4335         if self.v.is_empty() {
4336             None
4337         } else {
4338             let remainder = self.v.len() % self.chunk_size;
4339             let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
4340             let (fst, snd) = self.v.split_at(chunksz);
4341             self.v = snd;
4342             Some(fst)
4343         }
4344     }
4345 }
4346
4347 #[stable(feature = "rchunks", since = "1.31.0")]
4348 impl<'a, T> ExactSizeIterator for RChunks<'a, T> {}
4349
4350 #[unstable(feature = "trusted_len", issue = "37572")]
4351 unsafe impl<'a, T> TrustedLen for RChunks<'a, T> {}
4352
4353 #[stable(feature = "rchunks", since = "1.31.0")]
4354 impl<'a, T> FusedIterator for RChunks<'a, T> {}
4355
4356 #[doc(hidden)]
4357 #[stable(feature = "rchunks", since = "1.31.0")]
4358 unsafe impl<'a, T> TrustedRandomAccess for RChunks<'a, T> {
4359     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4360         let end = self.v.len() - i * self.chunk_size;
4361         let start = match end.checked_sub(self.chunk_size) {
4362             None => 0,
4363             Some(start) => start,
4364         };
4365         from_raw_parts(self.v.as_ptr().add(start), end - start)
4366     }
4367     fn may_have_side_effect() -> bool { false }
4368 }
4369
4370 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4371 /// elements at a time), starting at the end of the slice.
4372 ///
4373 /// When the slice len is not evenly divided by the chunk size, the last slice
4374 /// of the iteration will be the remainder.
4375 ///
4376 /// This struct is created by the [`rchunks_mut`] method on [slices].
4377 ///
4378 /// [`rchunks_mut`]: ../../std/primitive.slice.html#method.rchunks_mut
4379 /// [slices]: ../../std/primitive.slice.html
4380 #[derive(Debug)]
4381 #[stable(feature = "rchunks", since = "1.31.0")]
4382 pub struct RChunksMut<'a, T:'a> {
4383     v: &'a mut [T],
4384     chunk_size: usize
4385 }
4386
4387 #[stable(feature = "rchunks", since = "1.31.0")]
4388 impl<'a, T> Iterator for RChunksMut<'a, T> {
4389     type Item = &'a mut [T];
4390
4391     #[inline]
4392     fn next(&mut self) -> Option<&'a mut [T]> {
4393         if self.v.is_empty() {
4394             None
4395         } else {
4396             let sz = cmp::min(self.v.len(), self.chunk_size);
4397             let tmp = mem::replace(&mut self.v, &mut []);
4398             let tmp_len = tmp.len();
4399             let (head, tail) = tmp.split_at_mut(tmp_len - sz);
4400             self.v = head;
4401             Some(tail)
4402         }
4403     }
4404
4405     #[inline]
4406     fn size_hint(&self) -> (usize, Option<usize>) {
4407         if self.v.is_empty() {
4408             (0, Some(0))
4409         } else {
4410             let n = self.v.len() / self.chunk_size;
4411             let rem = self.v.len() % self.chunk_size;
4412             let n = if rem > 0 { n + 1 } else { n };
4413             (n, Some(n))
4414         }
4415     }
4416
4417     #[inline]
4418     fn count(self) -> usize {
4419         self.len()
4420     }
4421
4422     #[inline]
4423     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4424         let (end, overflow) = n.overflowing_mul(self.chunk_size);
4425         if end >= self.v.len() || overflow {
4426             self.v = &mut [];
4427             None
4428         } else {
4429             // Can't underflow because of the check above
4430             let end = self.v.len() - end;
4431             let start = match end.checked_sub(self.chunk_size) {
4432                 Some(sum) => sum,
4433                 None => 0,
4434             };
4435             let tmp = mem::replace(&mut self.v, &mut []);
4436             let (head, tail) = tmp.split_at_mut(start);
4437             let (nth, _) = tail.split_at_mut(end - start);
4438             self.v = head;
4439             Some(nth)
4440         }
4441     }
4442
4443     #[inline]
4444     fn last(self) -> Option<Self::Item> {
4445         if self.v.is_empty() {
4446             None
4447         } else {
4448             let rem = self.v.len() % self.chunk_size;
4449             let end = if rem == 0 { self.chunk_size } else { rem };
4450             Some(&mut self.v[0..end])
4451         }
4452     }
4453 }
4454
4455 #[stable(feature = "rchunks", since = "1.31.0")]
4456 impl<'a, T> DoubleEndedIterator for RChunksMut<'a, T> {
4457     #[inline]
4458     fn next_back(&mut self) -> Option<&'a mut [T]> {
4459         if self.v.is_empty() {
4460             None
4461         } else {
4462             let remainder = self.v.len() % self.chunk_size;
4463             let sz = if remainder != 0 { remainder } else { self.chunk_size };
4464             let tmp = mem::replace(&mut self.v, &mut []);
4465             let (head, tail) = tmp.split_at_mut(sz);
4466             self.v = tail;
4467             Some(head)
4468         }
4469     }
4470 }
4471
4472 #[stable(feature = "rchunks", since = "1.31.0")]
4473 impl<'a, T> ExactSizeIterator for RChunksMut<'a, T> {}
4474
4475 #[unstable(feature = "trusted_len", issue = "37572")]
4476 unsafe impl<'a, T> TrustedLen for RChunksMut<'a, T> {}
4477
4478 #[stable(feature = "rchunks", since = "1.31.0")]
4479 impl<'a, T> FusedIterator for RChunksMut<'a, T> {}
4480
4481 #[doc(hidden)]
4482 #[stable(feature = "rchunks", since = "1.31.0")]
4483 unsafe impl<'a, T> TrustedRandomAccess for RChunksMut<'a, T> {
4484     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4485         let end = self.v.len() - i * self.chunk_size;
4486         let start = match end.checked_sub(self.chunk_size) {
4487             None => 0,
4488             Some(start) => start,
4489         };
4490         from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start)
4491     }
4492     fn may_have_side_effect() -> bool { false }
4493 }
4494
4495 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4496 /// time), starting at the end of the slice.
4497 ///
4498 /// When the slice len is not evenly divided by the chunk size, the last
4499 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
4500 /// the [`remainder`] function from the iterator.
4501 ///
4502 /// This struct is created by the [`rchunks_exact`] method on [slices].
4503 ///
4504 /// [`rchunks_exact`]: ../../std/primitive.slice.html#method.rchunks_exact
4505 /// [`remainder`]: ../../std/slice/struct.ChunksExact.html#method.remainder
4506 /// [slices]: ../../std/primitive.slice.html
4507 #[derive(Debug)]
4508 #[stable(feature = "rchunks", since = "1.31.0")]
4509 pub struct RChunksExact<'a, T:'a> {
4510     v: &'a [T],
4511     rem: &'a [T],
4512     chunk_size: usize
4513 }
4514
4515 impl<'a, T> RChunksExact<'a, T> {
4516     /// Return the remainder of the original slice that is not going to be
4517     /// returned by the iterator. The returned slice has at most `chunk_size-1`
4518     /// elements.
4519     #[stable(feature = "rchunks", since = "1.31.0")]
4520     pub fn remainder(&self) -> &'a [T] {
4521         self.rem
4522     }
4523 }
4524
4525 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4526 #[stable(feature = "rchunks", since = "1.31.0")]
4527 impl<'a, T> Clone for RChunksExact<'a, T> {
4528     fn clone(&self) -> RChunksExact<'a, T> {
4529         RChunksExact {
4530             v: self.v,
4531             rem: self.rem,
4532             chunk_size: self.chunk_size,
4533         }
4534     }
4535 }
4536
4537 #[stable(feature = "rchunks", since = "1.31.0")]
4538 impl<'a, T> Iterator for RChunksExact<'a, T> {
4539     type Item = &'a [T];
4540
4541     #[inline]
4542     fn next(&mut self) -> Option<&'a [T]> {
4543         if self.v.len() < self.chunk_size {
4544             None
4545         } else {
4546             let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
4547             self.v = fst;
4548             Some(snd)
4549         }
4550     }
4551
4552     #[inline]
4553     fn size_hint(&self) -> (usize, Option<usize>) {
4554         let n = self.v.len() / self.chunk_size;
4555         (n, Some(n))
4556     }
4557
4558     #[inline]
4559     fn count(self) -> usize {
4560         self.len()
4561     }
4562
4563     #[inline]
4564     fn nth(&mut self, n: usize) -> Option<Self::Item> {
4565         let (end, overflow) = n.overflowing_mul(self.chunk_size);
4566         if end >= self.v.len() || overflow {
4567             self.v = &[];
4568             None
4569         } else {
4570             let (fst, _) = self.v.split_at(self.v.len() - end);
4571             self.v = fst;
4572             self.next()
4573         }
4574     }
4575
4576     #[inline]
4577     fn last(mut self) -> Option<Self::Item> {
4578         self.next_back()
4579     }
4580 }
4581
4582 #[stable(feature = "rchunks", since = "1.31.0")]
4583 impl<'a, T> DoubleEndedIterator for RChunksExact<'a, T> {
4584     #[inline]
4585     fn next_back(&mut self) -> Option<&'a [T]> {
4586         if self.v.len() < self.chunk_size {
4587             None
4588         } else {
4589             let (fst, snd) = self.v.split_at(self.chunk_size);
4590             self.v = snd;
4591             Some(fst)
4592         }
4593     }
4594 }
4595
4596 #[stable(feature = "rchunks", since = "1.31.0")]
4597 impl<'a, T> ExactSizeIterator for RChunksExact<'a, T> {
4598     fn is_empty(&self) -> bool {
4599         self.v.is_empty()
4600     }
4601 }
4602
4603 #[unstable(feature = "trusted_len", issue = "37572")]
4604 unsafe impl<'a, T> TrustedLen for RChunksExact<'a, T> {}
4605
4606 #[stable(feature = "rchunks", since = "1.31.0")]
4607 impl<'a, T> FusedIterator for RChunksExact<'a, T> {}
4608
4609 #[doc(hidden)]
4610 #[stable(feature = "rchunks", since = "1.31.0")]
4611 unsafe impl<'a, T> TrustedRandomAccess for RChunksExact<'a, T> {
4612     unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4613         let end = self.v.len() - i * self.chunk_size;
4614         let start = end - self.chunk_size;
4615         from_raw_parts(self.v.as_ptr().add(start), self.chunk_size)
4616     }
4617     fn may_have_side_effect() -> bool { false }
4618 }
4619
4620 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4621 /// elements at a time), starting at the end of the slice.
4622 ///
4623 /// When the slice len is not evenly divided by the chunk size, the last up to
4624 /// `chunk_size-1` elements will be omitted but can be retrieved from the
4625 /// [`into_remainder`] function from the iterator.
4626 ///
4627 /// This struct is created by the [`rchunks_exact_mut`] method on [slices].
4628 ///
4629 /// [`rchunks_exact_mut`]: ../../std/primitive.slice.html#method.rchunks_exact_mut
4630 /// [`into_remainder`]: ../../std/slice/struct.ChunksExactMut.html#method.into_remainder
4631 /// [slices]: ../../std/primitive.slice.html
4632 #[derive(Debug)]
4633 #[stable(feature = "rchunks", since = "1.31.0")]
4634 pub struct RChunksExactMut<'a, T:'a> {
4635     v: &'a mut [T],
4636     rem: &'a mut [T],
4637     chunk_size: usize
4638 }
4639
4640 impl<'a, T> RChunksExactMut<'a, T> {
4641     /// Return the remainder of the original slice that is not going to be
4642     /// returned by the iterator. The returned slice has at most `chunk_size-1`
4643     /// elements.
4644     #[stable(feature = "rchunks", since = "1.31.0")]
4645     pub fn into_remainder(self) -> &'a mut [T] {
4646         self.rem
4647     }
4648 }
4649
4650 #[stable(feature = "rchunks", since = "1.31.0")]
4651 impl<'a, T> Iterator for RChunksExactMut<'a, T> {
4652     type Item = &'a mut [T];
4653
4654     #[inline]
4655     fn next(&mut self) -> Option<&'a mut [T]> {
4656         if self.v.len() < self.chunk_size {
4657             None
4658         } else {
4659             let tmp = mem::replace(&mut self.v, &mut []);
4660             let tmp_len = tmp.len();
4661             let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
4662             self.v = head;
4663             Some(tail)
4664         }
4665     }
4666
4667     #[inline]
4668     fn size_hint(&self) -> (usize, Option<usize>) {
4669         let n = self.v.len() / self.chunk_size;
4670         (n, Some(n))
4671     }
4672
4673     #[inline]
4674     fn count(self) -> usize {
4675         self.len()
4676     }
4677
4678     #[inline]
4679     fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4680         let (end, overflow) = n.overflowing_mul(self.chunk_size);
4681         if end >= self.v.len() || overflow {
4682             self.v = &mut [];
4683             None
4684         } else {
4685             let tmp = mem::replace(&mut self.v, &mut []);
4686             let tmp_len = tmp.len();
4687             let (fst, _) = tmp.split_at_mut(tmp_len - end);
4688             self.v = fst;
4689             self.next()
4690         }
4691     }
4692
4693     #[inline]
4694     fn last(mut self) -> Option<Self::Item> {
4695         self.next_back()
4696     }
4697 }
4698
4699 #[stable(feature = "rchunks", since = "1.31.0")]
4700 impl<'a, T> DoubleEndedIterator for RChunksExactMut<'a, T> {
4701     #[inline]
4702     fn next_back(&mut self) -> Option<&'a mut [T]> {
4703         if self.v.len() < self.chunk_size {
4704             None
4705         } else {
4706             let tmp = mem::replace(&mut self.v, &mut []);
4707             let (head, tail) = tmp.split_at_mut(self.chunk_size);
4708             self.v = tail;
4709             Some(head)
4710         }
4711     }
4712 }
4713
4714 #[stable(feature = "rchunks", since = "1.31.0")]
4715 impl<'a, T> ExactSizeIterator for RChunksExactMut<'a, T> {
4716     fn is_empty(&self) -> bool {
4717         self.v.is_empty()
4718     }
4719 }
4720
4721 #[unstable(feature = "trusted_len", issue = "37572")]
4722 unsafe impl<'a, T> TrustedLen for RChunksExactMut<'a, T> {}
4723
4724 #[stable(feature = "rchunks", since = "1.31.0")]
4725 impl<'a, T> FusedIterator for RChunksExactMut<'a, T> {}
4726
4727 #[doc(hidden)]
4728 #[stable(feature = "rchunks", since = "1.31.0")]
4729 unsafe impl<'a, T> TrustedRandomAccess for RChunksExactMut<'a, T> {
4730     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4731         let end = self.v.len() - i * self.chunk_size;
4732         let start = end - self.chunk_size;
4733         from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size)
4734     }
4735     fn may_have_side_effect() -> bool { false }
4736 }
4737
4738 //
4739 // Free functions
4740 //
4741
4742 /// Forms a slice from a pointer and a length.
4743 ///
4744 /// The `len` argument is the number of **elements**, not the number of bytes.
4745 ///
4746 /// # Safety
4747 ///
4748 /// This function is unsafe as there is no guarantee that the given pointer is
4749 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
4750 /// lifetime for the returned slice.
4751 ///
4752 /// `data` must be non-null and aligned, even for zero-length slices. One
4753 /// reason for this is that enum layout optimizations may rely on references
4754 /// (including slices of any length) being aligned and non-null to distinguish
4755 /// them from other data. You can obtain a pointer that is usable as `data`
4756 /// for zero-length slices using [`NonNull::dangling()`].
4757 ///
4758 /// The total size of the slice must be no larger than `isize::MAX` **bytes**
4759 /// in memory. See the safety documentation of [`pointer::offset`].
4760 ///
4761 /// # Caveat
4762 ///
4763 /// The lifetime for the returned slice is inferred from its usage. To
4764 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
4765 /// source lifetime is safe in the context, such as by providing a helper
4766 /// function taking the lifetime of a host value for the slice, or by explicit
4767 /// annotation.
4768 ///
4769 /// # Examples
4770 ///
4771 /// ```
4772 /// use std::slice;
4773 ///
4774 /// // manifest a slice for a single element
4775 /// let x = 42;
4776 /// let ptr = &x as *const _;
4777 /// let slice = unsafe { slice::from_raw_parts(ptr, 1) };
4778 /// assert_eq!(slice[0], 42);
4779 /// ```
4780 ///
4781 /// [`NonNull::dangling()`]: ../../std/ptr/struct.NonNull.html#method.dangling
4782 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
4783 #[inline]
4784 #[stable(feature = "rust1", since = "1.0.0")]
4785 pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
4786     debug_assert!(data as usize % mem::align_of::<T>() == 0, "attempt to create unaligned slice");
4787     debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
4788                   "attempt to create slice covering half the address space");
4789     Repr { raw: FatPtr { data, len } }.rust
4790 }
4791
4792 /// Performs the same functionality as [`from_raw_parts`], except that a
4793 /// mutable slice is returned.
4794 ///
4795 /// This function is unsafe for the same reasons as [`from_raw_parts`], as well
4796 /// as not being able to provide a non-aliasing guarantee of the returned
4797 /// mutable slice. `data` must be non-null and aligned even for zero-length
4798 /// slices as with [`from_raw_parts`]. The total size of the slice must be no
4799 /// larger than `isize::MAX` **bytes** in memory.
4800 ///
4801 /// See the documentation of [`from_raw_parts`] for more details.
4802 ///
4803 /// [`from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
4804 #[inline]
4805 #[stable(feature = "rust1", since = "1.0.0")]
4806 pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
4807     debug_assert!(data as usize % mem::align_of::<T>() == 0, "attempt to create unaligned slice");
4808     debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
4809                   "attempt to create slice covering half the address space");
4810     Repr { raw: FatPtr { data, len } }.rust_mut
4811 }
4812
4813 /// Converts a reference to T into a slice of length 1 (without copying).
4814 #[stable(feature = "from_ref", since = "1.28.0")]
4815 pub fn from_ref<T>(s: &T) -> &[T] {
4816     unsafe {
4817         from_raw_parts(s, 1)
4818     }
4819 }
4820
4821 /// Converts a reference to T into a slice of length 1 (without copying).
4822 #[stable(feature = "from_ref", since = "1.28.0")]
4823 pub fn from_mut<T>(s: &mut T) -> &mut [T] {
4824     unsafe {
4825         from_raw_parts_mut(s, 1)
4826     }
4827 }
4828
4829 // This function is public only because there is no other way to unit test heapsort.
4830 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "0")]
4831 #[doc(hidden)]
4832 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
4833     where F: FnMut(&T, &T) -> bool
4834 {
4835     sort::heapsort(v, &mut is_less);
4836 }
4837
4838 //
4839 // Comparison traits
4840 //
4841
4842 extern {
4843     /// Calls implementation provided memcmp.
4844     ///
4845     /// Interprets the data as u8.
4846     ///
4847     /// Returns 0 for equal, < 0 for less than and > 0 for greater
4848     /// than.
4849     // FIXME(#32610): Return type should be c_int
4850     fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
4851 }
4852
4853 #[stable(feature = "rust1", since = "1.0.0")]
4854 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
4855     fn eq(&self, other: &[B]) -> bool {
4856         SlicePartialEq::equal(self, other)
4857     }
4858
4859     fn ne(&self, other: &[B]) -> bool {
4860         SlicePartialEq::not_equal(self, other)
4861     }
4862 }
4863
4864 #[stable(feature = "rust1", since = "1.0.0")]
4865 impl<T: Eq> Eq for [T] {}
4866
4867 /// Implements comparison of vectors lexicographically.
4868 #[stable(feature = "rust1", since = "1.0.0")]
4869 impl<T: Ord> Ord for [T] {
4870     fn cmp(&self, other: &[T]) -> Ordering {
4871         SliceOrd::compare(self, other)
4872     }
4873 }
4874
4875 /// Implements comparison of vectors lexicographically.
4876 #[stable(feature = "rust1", since = "1.0.0")]
4877 impl<T: PartialOrd> PartialOrd for [T] {
4878     fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
4879         SlicePartialOrd::partial_compare(self, other)
4880     }
4881 }
4882
4883 #[doc(hidden)]
4884 // intermediate trait for specialization of slice's PartialEq
4885 trait SlicePartialEq<B> {
4886     fn equal(&self, other: &[B]) -> bool;
4887
4888     fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
4889 }
4890
4891 // Generic slice equality
4892 impl<A, B> SlicePartialEq<B> for [A]
4893     where A: PartialEq<B>
4894 {
4895     default fn equal(&self, other: &[B]) -> bool {
4896         if self.len() != other.len() {
4897             return false;
4898         }
4899
4900         for i in 0..self.len() {
4901             if !self[i].eq(&other[i]) {
4902                 return false;
4903             }
4904         }
4905
4906         true
4907     }
4908 }
4909
4910 // Use memcmp for bytewise equality when the types allow
4911 impl<A> SlicePartialEq<A> for [A]
4912     where A: PartialEq<A> + BytewiseEquality
4913 {
4914     fn equal(&self, other: &[A]) -> bool {
4915         if self.len() != other.len() {
4916             return false;
4917         }
4918         if self.as_ptr() == other.as_ptr() {
4919             return true;
4920         }
4921         unsafe {
4922             let size = mem::size_of_val(self);
4923             memcmp(self.as_ptr() as *const u8,
4924                    other.as_ptr() as *const u8, size) == 0
4925         }
4926     }
4927 }
4928
4929 #[doc(hidden)]
4930 // intermediate trait for specialization of slice's PartialOrd
4931 trait SlicePartialOrd<B> {
4932     fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
4933 }
4934
4935 impl<A> SlicePartialOrd<A> for [A]
4936     where A: PartialOrd
4937 {
4938     default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
4939         let l = cmp::min(self.len(), other.len());
4940
4941         // Slice to the loop iteration range to enable bound check
4942         // elimination in the compiler
4943         let lhs = &self[..l];
4944         let rhs = &other[..l];
4945
4946         for i in 0..l {
4947             match lhs[i].partial_cmp(&rhs[i]) {
4948                 Some(Ordering::Equal) => (),
4949                 non_eq => return non_eq,
4950             }
4951         }
4952
4953         self.len().partial_cmp(&other.len())
4954     }
4955 }
4956
4957 impl<A> SlicePartialOrd<A> for [A]
4958     where A: Ord
4959 {
4960     default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
4961         Some(SliceOrd::compare(self, other))
4962     }
4963 }
4964
4965 #[doc(hidden)]
4966 // intermediate trait for specialization of slice's Ord
4967 trait SliceOrd<B> {
4968     fn compare(&self, other: &[B]) -> Ordering;
4969 }
4970
4971 impl<A> SliceOrd<A> for [A]
4972     where A: Ord
4973 {
4974     default fn compare(&self, other: &[A]) -> Ordering {
4975         let l = cmp::min(self.len(), other.len());
4976
4977         // Slice to the loop iteration range to enable bound check
4978         // elimination in the compiler
4979         let lhs = &self[..l];
4980         let rhs = &other[..l];
4981
4982         for i in 0..l {
4983             match lhs[i].cmp(&rhs[i]) {
4984                 Ordering::Equal => (),
4985                 non_eq => return non_eq,
4986             }
4987         }
4988
4989         self.len().cmp(&other.len())
4990     }
4991 }
4992
4993 // memcmp compares a sequence of unsigned bytes lexicographically.
4994 // this matches the order we want for [u8], but no others (not even [i8]).
4995 impl SliceOrd<u8> for [u8] {
4996     #[inline]
4997     fn compare(&self, other: &[u8]) -> Ordering {
4998         let order = unsafe {
4999             memcmp(self.as_ptr(), other.as_ptr(),
5000                    cmp::min(self.len(), other.len()))
5001         };
5002         if order == 0 {
5003             self.len().cmp(&other.len())
5004         } else if order < 0 {
5005             Less
5006         } else {
5007             Greater
5008         }
5009     }
5010 }
5011
5012 #[doc(hidden)]
5013 /// Trait implemented for types that can be compared for equality using
5014 /// their bytewise representation
5015 trait BytewiseEquality { }
5016
5017 macro_rules! impl_marker_for {
5018     ($traitname:ident, $($ty:ty)*) => {
5019         $(
5020             impl $traitname for $ty { }
5021         )*
5022     }
5023 }
5024
5025 impl_marker_for!(BytewiseEquality,
5026                  u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
5027
5028 #[doc(hidden)]
5029 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
5030     unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
5031         &*self.ptr.add(i)
5032     }
5033     fn may_have_side_effect() -> bool { false }
5034 }
5035
5036 #[doc(hidden)]
5037 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
5038     unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
5039         &mut *self.ptr.add(i)
5040     }
5041     fn may_have_side_effect() -> bool { false }
5042 }
5043
5044 trait SliceContains: Sized {
5045     fn slice_contains(&self, x: &[Self]) -> bool;
5046 }
5047
5048 impl<T> SliceContains for T where T: PartialEq {
5049     default fn slice_contains(&self, x: &[Self]) -> bool {
5050         x.iter().any(|y| *y == *self)
5051     }
5052 }
5053
5054 impl SliceContains for u8 {
5055     fn slice_contains(&self, x: &[Self]) -> bool {
5056         memchr::memchr(*self, x).is_some()
5057     }
5058 }
5059
5060 impl SliceContains for i8 {
5061     fn slice_contains(&self, x: &[Self]) -> bool {
5062         let byte = *self as u8;
5063         let bytes: &[u8] = unsafe { from_raw_parts(x.as_ptr() as *const u8, x.len()) };
5064         memchr::memchr(byte, bytes).is_some()
5065     }
5066 }