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