]> git.lizzy.rs Git - rust.git/blob - library/core/src/slice/mod.rs
56d3ba0ff254d0d2be9378f97f42264a621c349d
[rust.git] / library / core / src / slice / mod.rs
1 // ignore-tidy-filelength
2
3 //! Slice management and manipulation.
4 //!
5 //! For more details see [`std::slice`].
6 //!
7 //! [`std::slice`]: ../../std/slice/index.html
8
9 #![stable(feature = "rust1", since = "1.0.0")]
10
11 use crate::cmp::Ordering::{self, Greater, Less};
12 use crate::marker::Copy;
13 use crate::mem;
14 use crate::num::NonZeroUsize;
15 use crate::ops::{FnMut, Range, RangeBounds};
16 use crate::option::Option;
17 use crate::option::Option::{None, Some};
18 use crate::ptr;
19 use crate::result::Result;
20 use crate::result::Result::{Err, Ok};
21 use crate::slice;
22
23 #[unstable(
24     feature = "slice_internals",
25     issue = "none",
26     reason = "exposed from core to be reused in std; use the memchr crate"
27 )]
28 /// Pure rust memchr implementation, taken from rust-memchr
29 pub mod memchr;
30
31 mod ascii;
32 mod cmp;
33 mod index;
34 mod iter;
35 mod raw;
36 mod rotate;
37 mod sort;
38 mod specialize;
39
40 #[stable(feature = "rust1", since = "1.0.0")]
41 pub use iter::{Chunks, ChunksMut, Windows};
42 #[stable(feature = "rust1", since = "1.0.0")]
43 pub use iter::{Iter, IterMut};
44 #[stable(feature = "rust1", since = "1.0.0")]
45 pub use iter::{RSplitN, RSplitNMut, Split, SplitMut, SplitN, SplitNMut};
46
47 #[stable(feature = "slice_rsplit", since = "1.27.0")]
48 pub use iter::{RSplit, RSplitMut};
49
50 #[stable(feature = "chunks_exact", since = "1.31.0")]
51 pub use iter::{ChunksExact, ChunksExactMut};
52
53 #[stable(feature = "rchunks", since = "1.31.0")]
54 pub use iter::{RChunks, RChunksExact, RChunksExactMut, RChunksMut};
55
56 #[unstable(feature = "array_chunks", issue = "74985")]
57 pub use iter::{ArrayChunks, ArrayChunksMut};
58
59 #[unstable(feature = "array_windows", issue = "75027")]
60 pub use iter::ArrayWindows;
61
62 #[unstable(feature = "slice_group_by", issue = "80552")]
63 pub use iter::{GroupBy, GroupByMut};
64
65 #[stable(feature = "split_inclusive", since = "1.51.0")]
66 pub use iter::{SplitInclusive, SplitInclusiveMut};
67
68 #[stable(feature = "rust1", since = "1.0.0")]
69 pub use raw::{from_raw_parts, from_raw_parts_mut};
70
71 #[stable(feature = "from_ref", since = "1.28.0")]
72 pub use raw::{from_mut, from_ref};
73
74 // This function is public only because there is no other way to unit test heapsort.
75 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "none")]
76 pub use sort::heapsort;
77
78 #[stable(feature = "slice_get_slice", since = "1.28.0")]
79 pub use index::SliceIndex;
80
81 #[unstable(feature = "slice_range", issue = "76393")]
82 pub use index::range;
83
84 #[lang = "slice"]
85 #[cfg(not(test))]
86 impl<T> [T] {
87     /// Returns the number of elements in the slice.
88     ///
89     /// # Examples
90     ///
91     /// ```
92     /// let a = [1, 2, 3];
93     /// assert_eq!(a.len(), 3);
94     /// ```
95     #[doc(alias = "length")]
96     #[stable(feature = "rust1", since = "1.0.0")]
97     #[rustc_const_stable(feature = "const_slice_len", since = "1.39.0")]
98     #[inline]
99     // SAFETY: const sound because we transmute out the length field as a usize (which it must be)
100     #[rustc_allow_const_fn_unstable(const_fn_union)]
101     pub const fn len(&self) -> usize {
102         #[cfg(bootstrap)]
103         {
104             // SAFETY: this is safe because `&[T]` and `FatPtr<T>` have the same layout.
105             // Only `std` can make this guarantee.
106             unsafe { crate::ptr::Repr { rust: self }.raw.len }
107         }
108         #[cfg(not(bootstrap))]
109         {
110             // FIXME: Replace with `crate::ptr::metadata(self)` when that is const-stable.
111             // As of this writing this causes a "Const-stable functions can only call other
112             // const-stable functions" error.
113
114             // SAFETY: Accessing the value from the `PtrRepr` union is safe since *const T
115             // and PtrComponents<T> have the same memory layouts. Only std can make this
116             // guarantee.
117             unsafe { crate::ptr::PtrRepr { const_ptr: self }.components.metadata }
118         }
119     }
120
121     /// Returns `true` if the slice has a length of 0.
122     ///
123     /// # Examples
124     ///
125     /// ```
126     /// let a = [1, 2, 3];
127     /// assert!(!a.is_empty());
128     /// ```
129     #[stable(feature = "rust1", since = "1.0.0")]
130     #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.39.0")]
131     #[inline]
132     pub const fn is_empty(&self) -> bool {
133         self.len() == 0
134     }
135
136     /// Returns the first element of the slice, or `None` if it is empty.
137     ///
138     /// # Examples
139     ///
140     /// ```
141     /// let v = [10, 40, 30];
142     /// assert_eq!(Some(&10), v.first());
143     ///
144     /// let w: &[i32] = &[];
145     /// assert_eq!(None, w.first());
146     /// ```
147     #[stable(feature = "rust1", since = "1.0.0")]
148     #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
149     #[inline]
150     pub const fn first(&self) -> Option<&T> {
151         if let [first, ..] = self { Some(first) } else { None }
152     }
153
154     /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
155     ///
156     /// # Examples
157     ///
158     /// ```
159     /// let x = &mut [0, 1, 2];
160     ///
161     /// if let Some(first) = x.first_mut() {
162     ///     *first = 5;
163     /// }
164     /// assert_eq!(x, &[5, 1, 2]);
165     /// ```
166     #[stable(feature = "rust1", since = "1.0.0")]
167     #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
168     #[inline]
169     pub const fn first_mut(&mut self) -> Option<&mut T> {
170         if let [first, ..] = self { Some(first) } else { None }
171     }
172
173     /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
174     ///
175     /// # Examples
176     ///
177     /// ```
178     /// let x = &[0, 1, 2];
179     ///
180     /// if let Some((first, elements)) = x.split_first() {
181     ///     assert_eq!(first, &0);
182     ///     assert_eq!(elements, &[1, 2]);
183     /// }
184     /// ```
185     #[stable(feature = "slice_splits", since = "1.5.0")]
186     #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
187     #[inline]
188     pub const fn split_first(&self) -> Option<(&T, &[T])> {
189         if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
190     }
191
192     /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
193     ///
194     /// # Examples
195     ///
196     /// ```
197     /// let x = &mut [0, 1, 2];
198     ///
199     /// if let Some((first, elements)) = x.split_first_mut() {
200     ///     *first = 3;
201     ///     elements[0] = 4;
202     ///     elements[1] = 5;
203     /// }
204     /// assert_eq!(x, &[3, 4, 5]);
205     /// ```
206     #[stable(feature = "slice_splits", since = "1.5.0")]
207     #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
208     #[inline]
209     pub const fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
210         if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
211     }
212
213     /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
214     ///
215     /// # Examples
216     ///
217     /// ```
218     /// let x = &[0, 1, 2];
219     ///
220     /// if let Some((last, elements)) = x.split_last() {
221     ///     assert_eq!(last, &2);
222     ///     assert_eq!(elements, &[0, 1]);
223     /// }
224     /// ```
225     #[stable(feature = "slice_splits", since = "1.5.0")]
226     #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
227     #[inline]
228     pub const fn split_last(&self) -> Option<(&T, &[T])> {
229         if let [init @ .., last] = self { Some((last, init)) } else { None }
230     }
231
232     /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
233     ///
234     /// # Examples
235     ///
236     /// ```
237     /// let x = &mut [0, 1, 2];
238     ///
239     /// if let Some((last, elements)) = x.split_last_mut() {
240     ///     *last = 3;
241     ///     elements[0] = 4;
242     ///     elements[1] = 5;
243     /// }
244     /// assert_eq!(x, &[4, 5, 3]);
245     /// ```
246     #[stable(feature = "slice_splits", since = "1.5.0")]
247     #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
248     #[inline]
249     pub const fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
250         if let [init @ .., last] = self { Some((last, init)) } else { None }
251     }
252
253     /// Returns the last element of the slice, or `None` if it is empty.
254     ///
255     /// # Examples
256     ///
257     /// ```
258     /// let v = [10, 40, 30];
259     /// assert_eq!(Some(&30), v.last());
260     ///
261     /// let w: &[i32] = &[];
262     /// assert_eq!(None, w.last());
263     /// ```
264     #[stable(feature = "rust1", since = "1.0.0")]
265     #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
266     #[inline]
267     pub const fn last(&self) -> Option<&T> {
268         if let [.., last] = self { Some(last) } else { None }
269     }
270
271     /// Returns a mutable pointer to the last item in the slice.
272     ///
273     /// # Examples
274     ///
275     /// ```
276     /// let x = &mut [0, 1, 2];
277     ///
278     /// if let Some(last) = x.last_mut() {
279     ///     *last = 10;
280     /// }
281     /// assert_eq!(x, &[0, 1, 10]);
282     /// ```
283     #[stable(feature = "rust1", since = "1.0.0")]
284     #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")]
285     #[inline]
286     pub const fn last_mut(&mut self) -> Option<&mut T> {
287         if let [.., last] = self { Some(last) } else { None }
288     }
289
290     /// Returns a reference to an element or subslice depending on the type of
291     /// index.
292     ///
293     /// - If given a position, returns a reference to the element at that
294     ///   position or `None` if out of bounds.
295     /// - If given a range, returns the subslice corresponding to that range,
296     ///   or `None` if out of bounds.
297     ///
298     /// # Examples
299     ///
300     /// ```
301     /// let v = [10, 40, 30];
302     /// assert_eq!(Some(&40), v.get(1));
303     /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
304     /// assert_eq!(None, v.get(3));
305     /// assert_eq!(None, v.get(0..4));
306     /// ```
307     #[stable(feature = "rust1", since = "1.0.0")]
308     #[inline]
309     pub fn get<I>(&self, index: I) -> Option<&I::Output>
310     where
311         I: SliceIndex<Self>,
312     {
313         index.get(self)
314     }
315
316     /// Returns a mutable reference to an element or subslice depending on the
317     /// type of index (see [`get`]) or `None` if the index is out of bounds.
318     ///
319     /// [`get`]: slice::get
320     ///
321     /// # Examples
322     ///
323     /// ```
324     /// let x = &mut [0, 1, 2];
325     ///
326     /// if let Some(elem) = x.get_mut(1) {
327     ///     *elem = 42;
328     /// }
329     /// assert_eq!(x, &[0, 42, 2]);
330     /// ```
331     #[stable(feature = "rust1", since = "1.0.0")]
332     #[inline]
333     pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
334     where
335         I: SliceIndex<Self>,
336     {
337         index.get_mut(self)
338     }
339
340     /// Returns a reference to an element or subslice, without doing bounds
341     /// checking.
342     ///
343     /// For a safe alternative see [`get`].
344     ///
345     /// # Safety
346     ///
347     /// Calling this method with an out-of-bounds index is *[undefined behavior]*
348     /// even if the resulting reference is not used.
349     ///
350     /// [`get`]: slice::get
351     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
352     ///
353     /// # Examples
354     ///
355     /// ```
356     /// let x = &[1, 2, 4];
357     ///
358     /// unsafe {
359     ///     assert_eq!(x.get_unchecked(1), &2);
360     /// }
361     /// ```
362     #[stable(feature = "rust1", since = "1.0.0")]
363     #[inline]
364     pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
365     where
366         I: SliceIndex<Self>,
367     {
368         // SAFETY: the caller must uphold most of the safety requirements for `get_unchecked`;
369         // the slice is dereferencable because `self` is a safe reference.
370         // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
371         unsafe { &*index.get_unchecked(self) }
372     }
373
374     /// Returns a mutable reference to an element or subslice, without doing
375     /// bounds checking.
376     ///
377     /// For a safe alternative see [`get_mut`].
378     ///
379     /// # Safety
380     ///
381     /// Calling this method with an out-of-bounds index is *[undefined behavior]*
382     /// even if the resulting reference is not used.
383     ///
384     /// [`get_mut`]: slice::get_mut
385     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
386     ///
387     /// # Examples
388     ///
389     /// ```
390     /// let x = &mut [1, 2, 4];
391     ///
392     /// unsafe {
393     ///     let elem = x.get_unchecked_mut(1);
394     ///     *elem = 13;
395     /// }
396     /// assert_eq!(x, &[1, 13, 4]);
397     /// ```
398     #[stable(feature = "rust1", since = "1.0.0")]
399     #[inline]
400     pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
401     where
402         I: SliceIndex<Self>,
403     {
404         // SAFETY: the caller must uphold the safety requirements for `get_unchecked_mut`;
405         // the slice is dereferencable because `self` is a safe reference.
406         // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
407         unsafe { &mut *index.get_unchecked_mut(self) }
408     }
409
410     /// Returns a raw pointer to the slice's buffer.
411     ///
412     /// The caller must ensure that the slice outlives the pointer this
413     /// function returns, or else it will end up pointing to garbage.
414     ///
415     /// The caller must also ensure that the memory the pointer (non-transitively) points to
416     /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
417     /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
418     ///
419     /// Modifying the container referenced by this slice may cause its buffer
420     /// to be reallocated, which would also make any pointers to it invalid.
421     ///
422     /// # Examples
423     ///
424     /// ```
425     /// let x = &[1, 2, 4];
426     /// let x_ptr = x.as_ptr();
427     ///
428     /// unsafe {
429     ///     for i in 0..x.len() {
430     ///         assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
431     ///     }
432     /// }
433     /// ```
434     ///
435     /// [`as_mut_ptr`]: slice::as_mut_ptr
436     #[stable(feature = "rust1", since = "1.0.0")]
437     #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")]
438     #[inline]
439     pub const fn as_ptr(&self) -> *const T {
440         self as *const [T] as *const T
441     }
442
443     /// Returns an unsafe mutable pointer to the slice's buffer.
444     ///
445     /// The caller must ensure that the slice outlives the pointer this
446     /// function returns, or else it will end up pointing to garbage.
447     ///
448     /// Modifying the container referenced by this slice may cause its buffer
449     /// to be reallocated, which would also make any pointers to it invalid.
450     ///
451     /// # Examples
452     ///
453     /// ```
454     /// let x = &mut [1, 2, 4];
455     /// let x_ptr = x.as_mut_ptr();
456     ///
457     /// unsafe {
458     ///     for i in 0..x.len() {
459     ///         *x_ptr.add(i) += 2;
460     ///     }
461     /// }
462     /// assert_eq!(x, &[3, 4, 6]);
463     /// ```
464     #[stable(feature = "rust1", since = "1.0.0")]
465     #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
466     #[inline]
467     pub const fn as_mut_ptr(&mut self) -> *mut T {
468         self as *mut [T] as *mut T
469     }
470
471     /// Returns the two raw pointers spanning the slice.
472     ///
473     /// The returned range is half-open, which means that the end pointer
474     /// points *one past* the last element of the slice. This way, an empty
475     /// slice is represented by two equal pointers, and the difference between
476     /// the two pointers represents the size of the slice.
477     ///
478     /// See [`as_ptr`] for warnings on using these pointers. The end pointer
479     /// requires extra caution, as it does not point to a valid element in the
480     /// slice.
481     ///
482     /// This function is useful for interacting with foreign interfaces which
483     /// use two pointers to refer to a range of elements in memory, as is
484     /// common in C++.
485     ///
486     /// It can also be useful to check if a pointer to an element refers to an
487     /// element of this slice:
488     ///
489     /// ```
490     /// let a = [1, 2, 3];
491     /// let x = &a[1] as *const _;
492     /// let y = &5 as *const _;
493     ///
494     /// assert!(a.as_ptr_range().contains(&x));
495     /// assert!(!a.as_ptr_range().contains(&y));
496     /// ```
497     ///
498     /// [`as_ptr`]: slice::as_ptr
499     #[stable(feature = "slice_ptr_range", since = "1.48.0")]
500     #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
501     #[inline]
502     pub const fn as_ptr_range(&self) -> Range<*const T> {
503         let start = self.as_ptr();
504         // SAFETY: The `add` here is safe, because:
505         //
506         //   - Both pointers are part of the same object, as pointing directly
507         //     past the object also counts.
508         //
509         //   - The size of the slice is never larger than isize::MAX bytes, as
510         //     noted here:
511         //       - https://github.com/rust-lang/unsafe-code-guidelines/issues/102#issuecomment-473340447
512         //       - https://doc.rust-lang.org/reference/behavior-considered-undefined.html
513         //       - https://doc.rust-lang.org/core/slice/fn.from_raw_parts.html#safety
514         //     (This doesn't seem normative yet, but the very same assumption is
515         //     made in many places, including the Index implementation of slices.)
516         //
517         //   - There is no wrapping around involved, as slices do not wrap past
518         //     the end of the address space.
519         //
520         // See the documentation of pointer::add.
521         let end = unsafe { start.add(self.len()) };
522         start..end
523     }
524
525     /// Returns the two unsafe mutable pointers spanning the slice.
526     ///
527     /// The returned range is half-open, which means that the end pointer
528     /// points *one past* the last element of the slice. This way, an empty
529     /// slice is represented by two equal pointers, and the difference between
530     /// the two pointers represents the size of the slice.
531     ///
532     /// See [`as_mut_ptr`] for warnings on using these pointers. The end
533     /// pointer requires extra caution, as it does not point to a valid element
534     /// in the slice.
535     ///
536     /// This function is useful for interacting with foreign interfaces which
537     /// use two pointers to refer to a range of elements in memory, as is
538     /// common in C++.
539     ///
540     /// [`as_mut_ptr`]: slice::as_mut_ptr
541     #[stable(feature = "slice_ptr_range", since = "1.48.0")]
542     #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
543     #[inline]
544     pub const fn as_mut_ptr_range(&mut self) -> Range<*mut T> {
545         let start = self.as_mut_ptr();
546         // SAFETY: See as_ptr_range() above for why `add` here is safe.
547         let end = unsafe { start.add(self.len()) };
548         start..end
549     }
550
551     /// Swaps two elements in the slice.
552     ///
553     /// # Arguments
554     ///
555     /// * a - The index of the first element
556     /// * b - The index of the second element
557     ///
558     /// # Panics
559     ///
560     /// Panics if `a` or `b` are out of bounds.
561     ///
562     /// # Examples
563     ///
564     /// ```
565     /// let mut v = ["a", "b", "c", "d"];
566     /// v.swap(1, 3);
567     /// assert!(v == ["a", "d", "c", "b"]);
568     /// ```
569     #[stable(feature = "rust1", since = "1.0.0")]
570     #[inline]
571     pub fn swap(&mut self, a: usize, b: usize) {
572         // Can't take two mutable loans from one vector, so instead use raw pointers.
573         let pa = ptr::addr_of_mut!(self[a]);
574         let pb = ptr::addr_of_mut!(self[b]);
575         // SAFETY: `pa` and `pb` have been created from safe mutable references and refer
576         // to elements in the slice and therefore are guaranteed to be valid and aligned.
577         // Note that accessing the elements behind `a` and `b` is checked and will
578         // panic when out of bounds.
579         unsafe {
580             ptr::swap(pa, pb);
581         }
582     }
583
584     /// Reverses the order of elements in the slice, in place.
585     ///
586     /// # Examples
587     ///
588     /// ```
589     /// let mut v = [1, 2, 3];
590     /// v.reverse();
591     /// assert!(v == [3, 2, 1]);
592     /// ```
593     #[stable(feature = "rust1", since = "1.0.0")]
594     #[inline]
595     pub fn reverse(&mut self) {
596         let mut i: usize = 0;
597         let ln = self.len();
598
599         // For very small types, all the individual reads in the normal
600         // path perform poorly.  We can do better, given efficient unaligned
601         // load/store, by loading a larger chunk and reversing a register.
602
603         // Ideally LLVM would do this for us, as it knows better than we do
604         // whether unaligned reads are efficient (since that changes between
605         // different ARM versions, for example) and what the best chunk size
606         // would be.  Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
607         // the loop, so we need to do this ourselves.  (Hypothesis: reverse
608         // is troublesome because the sides can be aligned differently --
609         // will be, when the length is odd -- so there's no way of emitting
610         // pre- and postludes to use fully-aligned SIMD in the middle.)
611
612         let fast_unaligned = cfg!(any(target_arch = "x86", target_arch = "x86_64"));
613
614         if fast_unaligned && mem::size_of::<T>() == 1 {
615             // Use the llvm.bswap intrinsic to reverse u8s in a usize
616             let chunk = mem::size_of::<usize>();
617             while i + chunk - 1 < ln / 2 {
618                 // SAFETY: There are several things to check here:
619                 //
620                 // - Note that `chunk` is either 4 or 8 due to the cfg check
621                 //   above. So `chunk - 1` is positive.
622                 // - Indexing with index `i` is fine as the loop check guarantees
623                 //   `i + chunk - 1 < ln / 2`
624                 //   <=> `i < ln / 2 - (chunk - 1) < ln / 2 < ln`.
625                 // - Indexing with index `ln - i - chunk = ln - (i + chunk)` is fine:
626                 //   - `i + chunk > 0` is trivially true.
627                 //   - The loop check guarantees:
628                 //     `i + chunk - 1 < ln / 2`
629                 //     <=> `i + chunk â‰¤ ln / 2 â‰¤ ln`, thus subtraction does not underflow.
630                 // - The `read_unaligned` and `write_unaligned` calls are fine:
631                 //   - `pa` points to index `i` where `i < ln / 2 - (chunk - 1)`
632                 //     (see above) and `pb` points to index `ln - i - chunk`, so
633                 //     both are at least `chunk`
634                 //     many bytes away from the end of `self`.
635                 //   - Any initialized memory is valid `usize`.
636                 unsafe {
637                     let ptr = self.as_mut_ptr();
638                     let pa = ptr.add(i);
639                     let pb = ptr.add(ln - i - chunk);
640                     let va = ptr::read_unaligned(pa as *mut usize);
641                     let vb = ptr::read_unaligned(pb as *mut usize);
642                     ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
643                     ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
644                 }
645                 i += chunk;
646             }
647         }
648
649         if fast_unaligned && mem::size_of::<T>() == 2 {
650             // Use rotate-by-16 to reverse u16s in a u32
651             let chunk = mem::size_of::<u32>() / 2;
652             while i + chunk - 1 < ln / 2 {
653                 // SAFETY: An unaligned u32 can be read from `i` if `i + 1 < ln`
654                 // (and obviously `i < ln`), because each element is 2 bytes and
655                 // we're reading 4.
656                 //
657                 // `i + chunk - 1 < ln / 2` # while condition
658                 // `i + 2 - 1 < ln / 2`
659                 // `i + 1 < ln / 2`
660                 //
661                 // Since it's less than the length divided by 2, then it must be
662                 // in bounds.
663                 //
664                 // This also means that the condition `0 < i + chunk <= ln` is
665                 // always respected, ensuring the `pb` pointer can be used
666                 // safely.
667                 unsafe {
668                     let ptr = self.as_mut_ptr();
669                     let pa = ptr.add(i);
670                     let pb = ptr.add(ln - i - chunk);
671                     let va = ptr::read_unaligned(pa as *mut u32);
672                     let vb = ptr::read_unaligned(pb as *mut u32);
673                     ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
674                     ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
675                 }
676                 i += chunk;
677             }
678         }
679
680         while i < ln / 2 {
681             // SAFETY: `i` is inferior to half the length of the slice so
682             // accessing `i` and `ln - i - 1` is safe (`i` starts at 0 and
683             // will not go further than `ln / 2 - 1`).
684             // The resulting pointers `pa` and `pb` are therefore valid and
685             // aligned, and can be read from and written to.
686             unsafe {
687                 // Unsafe swap to avoid the bounds check in safe swap.
688                 let ptr = self.as_mut_ptr();
689                 let pa = ptr.add(i);
690                 let pb = ptr.add(ln - i - 1);
691                 ptr::swap(pa, pb);
692             }
693             i += 1;
694         }
695     }
696
697     /// Returns an iterator over the slice.
698     ///
699     /// # Examples
700     ///
701     /// ```
702     /// let x = &[1, 2, 4];
703     /// let mut iterator = x.iter();
704     ///
705     /// assert_eq!(iterator.next(), Some(&1));
706     /// assert_eq!(iterator.next(), Some(&2));
707     /// assert_eq!(iterator.next(), Some(&4));
708     /// assert_eq!(iterator.next(), None);
709     /// ```
710     #[stable(feature = "rust1", since = "1.0.0")]
711     #[inline]
712     pub fn iter(&self) -> Iter<'_, T> {
713         Iter::new(self)
714     }
715
716     /// Returns an iterator that allows modifying each value.
717     ///
718     /// # Examples
719     ///
720     /// ```
721     /// let x = &mut [1, 2, 4];
722     /// for elem in x.iter_mut() {
723     ///     *elem += 2;
724     /// }
725     /// assert_eq!(x, &[3, 4, 6]);
726     /// ```
727     #[stable(feature = "rust1", since = "1.0.0")]
728     #[inline]
729     pub fn iter_mut(&mut self) -> IterMut<'_, T> {
730         IterMut::new(self)
731     }
732
733     /// Returns an iterator over all contiguous windows of length
734     /// `size`. The windows overlap. If the slice is shorter than
735     /// `size`, the iterator returns no values.
736     ///
737     /// # Panics
738     ///
739     /// Panics if `size` is 0.
740     ///
741     /// # Examples
742     ///
743     /// ```
744     /// let slice = ['r', 'u', 's', 't'];
745     /// let mut iter = slice.windows(2);
746     /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
747     /// assert_eq!(iter.next().unwrap(), &['u', 's']);
748     /// assert_eq!(iter.next().unwrap(), &['s', 't']);
749     /// assert!(iter.next().is_none());
750     /// ```
751     ///
752     /// If the slice is shorter than `size`:
753     ///
754     /// ```
755     /// let slice = ['f', 'o', 'o'];
756     /// let mut iter = slice.windows(4);
757     /// assert!(iter.next().is_none());
758     /// ```
759     #[stable(feature = "rust1", since = "1.0.0")]
760     #[inline]
761     pub fn windows(&self, size: usize) -> Windows<'_, T> {
762         let size = NonZeroUsize::new(size).expect("size is zero");
763         Windows::new(self, size)
764     }
765
766     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
767     /// beginning of the slice.
768     ///
769     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
770     /// slice, then the last chunk will not have length `chunk_size`.
771     ///
772     /// See [`chunks_exact`] for a variant of this iterator that returns chunks of always exactly
773     /// `chunk_size` elements, and [`rchunks`] for the same iterator but starting at the end of the
774     /// slice.
775     ///
776     /// # Panics
777     ///
778     /// Panics if `chunk_size` is 0.
779     ///
780     /// # Examples
781     ///
782     /// ```
783     /// let slice = ['l', 'o', 'r', 'e', 'm'];
784     /// let mut iter = slice.chunks(2);
785     /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
786     /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
787     /// assert_eq!(iter.next().unwrap(), &['m']);
788     /// assert!(iter.next().is_none());
789     /// ```
790     ///
791     /// [`chunks_exact`]: slice::chunks_exact
792     /// [`rchunks`]: slice::rchunks
793     #[stable(feature = "rust1", since = "1.0.0")]
794     #[inline]
795     pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> {
796         assert_ne!(chunk_size, 0);
797         Chunks::new(self, chunk_size)
798     }
799
800     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
801     /// beginning of the slice.
802     ///
803     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
804     /// length of the slice, then the last chunk will not have length `chunk_size`.
805     ///
806     /// See [`chunks_exact_mut`] for a variant of this iterator that returns chunks of always
807     /// exactly `chunk_size` elements, and [`rchunks_mut`] for the same iterator but starting at
808     /// the end of the slice.
809     ///
810     /// # Panics
811     ///
812     /// Panics if `chunk_size` is 0.
813     ///
814     /// # Examples
815     ///
816     /// ```
817     /// let v = &mut [0, 0, 0, 0, 0];
818     /// let mut count = 1;
819     ///
820     /// for chunk in v.chunks_mut(2) {
821     ///     for elem in chunk.iter_mut() {
822     ///         *elem += count;
823     ///     }
824     ///     count += 1;
825     /// }
826     /// assert_eq!(v, &[1, 1, 2, 2, 3]);
827     /// ```
828     ///
829     /// [`chunks_exact_mut`]: slice::chunks_exact_mut
830     /// [`rchunks_mut`]: slice::rchunks_mut
831     #[stable(feature = "rust1", since = "1.0.0")]
832     #[inline]
833     pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> {
834         assert_ne!(chunk_size, 0);
835         ChunksMut::new(self, chunk_size)
836     }
837
838     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
839     /// beginning of the slice.
840     ///
841     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
842     /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
843     /// from the `remainder` function of the iterator.
844     ///
845     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
846     /// resulting code better than in the case of [`chunks`].
847     ///
848     /// See [`chunks`] for a variant of this iterator that also returns the remainder as a smaller
849     /// chunk, and [`rchunks_exact`] for the same iterator but starting at the end of the slice.
850     ///
851     /// # Panics
852     ///
853     /// Panics if `chunk_size` is 0.
854     ///
855     /// # Examples
856     ///
857     /// ```
858     /// let slice = ['l', 'o', 'r', 'e', 'm'];
859     /// let mut iter = slice.chunks_exact(2);
860     /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
861     /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
862     /// assert!(iter.next().is_none());
863     /// assert_eq!(iter.remainder(), &['m']);
864     /// ```
865     ///
866     /// [`chunks`]: slice::chunks
867     /// [`rchunks_exact`]: slice::rchunks_exact
868     #[stable(feature = "chunks_exact", since = "1.31.0")]
869     #[inline]
870     pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> {
871         assert_ne!(chunk_size, 0);
872         ChunksExact::new(self, chunk_size)
873     }
874
875     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
876     /// beginning of the slice.
877     ///
878     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
879     /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
880     /// retrieved from the `into_remainder` function of the iterator.
881     ///
882     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
883     /// resulting code better than in the case of [`chunks_mut`].
884     ///
885     /// See [`chunks_mut`] for a variant of this iterator that also returns the remainder as a
886     /// smaller chunk, and [`rchunks_exact_mut`] for the same iterator but starting at the end of
887     /// the slice.
888     ///
889     /// # Panics
890     ///
891     /// Panics if `chunk_size` is 0.
892     ///
893     /// # Examples
894     ///
895     /// ```
896     /// let v = &mut [0, 0, 0, 0, 0];
897     /// let mut count = 1;
898     ///
899     /// for chunk in v.chunks_exact_mut(2) {
900     ///     for elem in chunk.iter_mut() {
901     ///         *elem += count;
902     ///     }
903     ///     count += 1;
904     /// }
905     /// assert_eq!(v, &[1, 1, 2, 2, 0]);
906     /// ```
907     ///
908     /// [`chunks_mut`]: slice::chunks_mut
909     /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
910     #[stable(feature = "chunks_exact", since = "1.31.0")]
911     #[inline]
912     pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> {
913         assert_ne!(chunk_size, 0);
914         ChunksExactMut::new(self, chunk_size)
915     }
916
917     /// Splits the slice into a slice of `N`-element arrays,
918     /// assuming that there's no remainder.
919     ///
920     /// # Safety
921     ///
922     /// This may only be called when
923     /// - The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).
924     /// - `N != 0`.
925     ///
926     /// # Examples
927     ///
928     /// ```
929     /// #![feature(slice_as_chunks)]
930     /// let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!'];
931     /// let chunks: &[[char; 1]] =
932     ///     // SAFETY: 1-element chunks never have remainder
933     ///     unsafe { slice.as_chunks_unchecked() };
934     /// assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]);
935     /// let chunks: &[[char; 3]] =
936     ///     // SAFETY: The slice length (6) is a multiple of 3
937     ///     unsafe { slice.as_chunks_unchecked() };
938     /// assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]);
939     ///
940     /// // These would be unsound:
941     /// // let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5
942     /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed
943     /// ```
944     #[unstable(feature = "slice_as_chunks", issue = "74985")]
945     #[inline]
946     pub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]] {
947         debug_assert_ne!(N, 0);
948         debug_assert_eq!(self.len() % N, 0);
949         let new_len =
950             // SAFETY: Our precondition is exactly what's needed to call this
951             unsafe { crate::intrinsics::exact_div(self.len(), N) };
952         // SAFETY: We cast a slice of `new_len * N` elements into
953         // a slice of `new_len` many `N` elements chunks.
954         unsafe { from_raw_parts(self.as_ptr().cast(), new_len) }
955     }
956
957     /// Splits the slice into a slice of `N`-element arrays,
958     /// starting at the beginning of the slice,
959     /// and a remainder slice with length strictly less than `N`.
960     ///
961     /// # Panics
962     ///
963     /// Panics if `N` is 0. This check will most probably get changed to a compile time
964     /// error before this method gets stabilized.
965     ///
966     /// # Examples
967     ///
968     /// ```
969     /// #![feature(slice_as_chunks)]
970     /// let slice = ['l', 'o', 'r', 'e', 'm'];
971     /// let (chunks, remainder) = slice.as_chunks();
972     /// assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);
973     /// assert_eq!(remainder, &['m']);
974     /// ```
975     #[unstable(feature = "slice_as_chunks", issue = "74985")]
976     #[inline]
977     pub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T]) {
978         assert_ne!(N, 0);
979         let len = self.len() / N;
980         let (multiple_of_n, remainder) = self.split_at(len * N);
981         // SAFETY: We already panicked for zero, and ensured by construction
982         // that the length of the subslice is a multiple of N.
983         let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() };
984         (array_slice, remainder)
985     }
986
987     /// Splits the slice into a slice of `N`-element arrays,
988     /// starting at the end of the slice,
989     /// and a remainder slice with length strictly less than `N`.
990     ///
991     /// # Panics
992     ///
993     /// Panics if `N` is 0. This check will most probably get changed to a compile time
994     /// error before this method gets stabilized.
995     ///
996     /// # Examples
997     ///
998     /// ```
999     /// #![feature(slice_as_chunks)]
1000     /// let slice = ['l', 'o', 'r', 'e', 'm'];
1001     /// let (remainder, chunks) = slice.as_rchunks();
1002     /// assert_eq!(remainder, &['l']);
1003     /// assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
1004     /// ```
1005     #[unstable(feature = "slice_as_chunks", issue = "74985")]
1006     #[inline]
1007     pub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]]) {
1008         assert_ne!(N, 0);
1009         let len = self.len() / N;
1010         let (remainder, multiple_of_n) = self.split_at(self.len() - len * N);
1011         // SAFETY: We already panicked for zero, and ensured by construction
1012         // that the length of the subslice is a multiple of N.
1013         let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() };
1014         (remainder, array_slice)
1015     }
1016
1017     /// Returns an iterator over `N` elements of the slice at a time, starting at the
1018     /// beginning of the slice.
1019     ///
1020     /// The chunks are array references and do not overlap. If `N` does not divide the
1021     /// length of the slice, then the last up to `N-1` elements will be omitted and can be
1022     /// retrieved from the `remainder` function of the iterator.
1023     ///
1024     /// This method is the const generic equivalent of [`chunks_exact`].
1025     ///
1026     /// # Panics
1027     ///
1028     /// Panics if `N` is 0. This check will most probably get changed to a compile time
1029     /// error before this method gets stabilized.
1030     ///
1031     /// # Examples
1032     ///
1033     /// ```
1034     /// #![feature(array_chunks)]
1035     /// let slice = ['l', 'o', 'r', 'e', 'm'];
1036     /// let mut iter = slice.array_chunks();
1037     /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
1038     /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
1039     /// assert!(iter.next().is_none());
1040     /// assert_eq!(iter.remainder(), &['m']);
1041     /// ```
1042     ///
1043     /// [`chunks_exact`]: slice::chunks_exact
1044     #[unstable(feature = "array_chunks", issue = "74985")]
1045     #[inline]
1046     pub fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N> {
1047         assert_ne!(N, 0);
1048         ArrayChunks::new(self)
1049     }
1050
1051     /// Splits the slice into a slice of `N`-element arrays,
1052     /// assuming that there's no remainder.
1053     ///
1054     /// # Safety
1055     ///
1056     /// This may only be called when
1057     /// - The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).
1058     /// - `N != 0`.
1059     ///
1060     /// # Examples
1061     ///
1062     /// ```
1063     /// #![feature(slice_as_chunks)]
1064     /// let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!'];
1065     /// let chunks: &mut [[char; 1]] =
1066     ///     // SAFETY: 1-element chunks never have remainder
1067     ///     unsafe { slice.as_chunks_unchecked_mut() };
1068     /// chunks[0] = ['L'];
1069     /// assert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]);
1070     /// let chunks: &mut [[char; 3]] =
1071     ///     // SAFETY: The slice length (6) is a multiple of 3
1072     ///     unsafe { slice.as_chunks_unchecked_mut() };
1073     /// chunks[1] = ['a', 'x', '?'];
1074     /// assert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']);
1075     ///
1076     /// // These would be unsound:
1077     /// // let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 5
1078     /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed
1079     /// ```
1080     #[unstable(feature = "slice_as_chunks", issue = "74985")]
1081     #[inline]
1082     pub unsafe fn as_chunks_unchecked_mut<const N: usize>(&mut self) -> &mut [[T; N]] {
1083         debug_assert_ne!(N, 0);
1084         debug_assert_eq!(self.len() % N, 0);
1085         let new_len =
1086             // SAFETY: Our precondition is exactly what's needed to call this
1087             unsafe { crate::intrinsics::exact_div(self.len(), N) };
1088         // SAFETY: We cast a slice of `new_len * N` elements into
1089         // a slice of `new_len` many `N` elements chunks.
1090         unsafe { from_raw_parts_mut(self.as_mut_ptr().cast(), new_len) }
1091     }
1092
1093     /// Splits the slice into a slice of `N`-element arrays,
1094     /// starting at the beginning of the slice,
1095     /// and a remainder slice with length strictly less than `N`.
1096     ///
1097     /// # Panics
1098     ///
1099     /// Panics if `N` is 0. This check will most probably get changed to a compile time
1100     /// error before this method gets stabilized.
1101     ///
1102     /// # Examples
1103     ///
1104     /// ```
1105     /// #![feature(slice_as_chunks)]
1106     /// let v = &mut [0, 0, 0, 0, 0];
1107     /// let mut count = 1;
1108     ///
1109     /// let (chunks, remainder) = v.as_chunks_mut();
1110     /// remainder[0] = 9;
1111     /// for chunk in chunks {
1112     ///     *chunk = [count; 2];
1113     ///     count += 1;
1114     /// }
1115     /// assert_eq!(v, &[1, 1, 2, 2, 9]);
1116     /// ```
1117     #[unstable(feature = "slice_as_chunks", issue = "74985")]
1118     #[inline]
1119     pub fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T]) {
1120         assert_ne!(N, 0);
1121         let len = self.len() / N;
1122         let (multiple_of_n, remainder) = self.split_at_mut(len * N);
1123         // SAFETY: We already panicked for zero, and ensured by construction
1124         // that the length of the subslice is a multiple of N.
1125         let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };
1126         (array_slice, remainder)
1127     }
1128
1129     /// Splits the slice into a slice of `N`-element arrays,
1130     /// starting at the end of the slice,
1131     /// and a remainder slice with length strictly less than `N`.
1132     ///
1133     /// # Panics
1134     ///
1135     /// Panics if `N` is 0. This check will most probably get changed to a compile time
1136     /// error before this method gets stabilized.
1137     ///
1138     /// # Examples
1139     ///
1140     /// ```
1141     /// #![feature(slice_as_chunks)]
1142     /// let v = &mut [0, 0, 0, 0, 0];
1143     /// let mut count = 1;
1144     ///
1145     /// let (remainder, chunks) = v.as_rchunks_mut();
1146     /// remainder[0] = 9;
1147     /// for chunk in chunks {
1148     ///     *chunk = [count; 2];
1149     ///     count += 1;
1150     /// }
1151     /// assert_eq!(v, &[9, 1, 1, 2, 2]);
1152     /// ```
1153     #[unstable(feature = "slice_as_chunks", issue = "74985")]
1154     #[inline]
1155     pub fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]]) {
1156         assert_ne!(N, 0);
1157         let len = self.len() / N;
1158         let (remainder, multiple_of_n) = self.split_at_mut(self.len() - len * N);
1159         // SAFETY: We already panicked for zero, and ensured by construction
1160         // that the length of the subslice is a multiple of N.
1161         let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };
1162         (remainder, array_slice)
1163     }
1164
1165     /// Returns an iterator over `N` elements of the slice at a time, starting at the
1166     /// beginning of the slice.
1167     ///
1168     /// The chunks are mutable array references and do not overlap. If `N` does not divide
1169     /// the length of the slice, then the last up to `N-1` elements will be omitted and
1170     /// can be retrieved from the `into_remainder` function of the iterator.
1171     ///
1172     /// This method is the const generic equivalent of [`chunks_exact_mut`].
1173     ///
1174     /// # Panics
1175     ///
1176     /// Panics if `N` is 0. This check will most probably get changed to a compile time
1177     /// error before this method gets stabilized.
1178     ///
1179     /// # Examples
1180     ///
1181     /// ```
1182     /// #![feature(array_chunks)]
1183     /// let v = &mut [0, 0, 0, 0, 0];
1184     /// let mut count = 1;
1185     ///
1186     /// for chunk in v.array_chunks_mut() {
1187     ///     *chunk = [count; 2];
1188     ///     count += 1;
1189     /// }
1190     /// assert_eq!(v, &[1, 1, 2, 2, 0]);
1191     /// ```
1192     ///
1193     /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1194     #[unstable(feature = "array_chunks", issue = "74985")]
1195     #[inline]
1196     pub fn array_chunks_mut<const N: usize>(&mut self) -> ArrayChunksMut<'_, T, N> {
1197         assert_ne!(N, 0);
1198         ArrayChunksMut::new(self)
1199     }
1200
1201     /// Returns an iterator over overlapping windows of `N` elements of  a slice,
1202     /// starting at the beginning of the slice.
1203     ///
1204     /// This is the const generic equivalent of [`windows`].
1205     ///
1206     /// If `N` is greater than the size of the slice, it will return no windows.
1207     ///
1208     /// # Panics
1209     ///
1210     /// Panics if `N` is 0. This check will most probably get changed to a compile time
1211     /// error before this method gets stabilized.
1212     ///
1213     /// # Examples
1214     ///
1215     /// ```
1216     /// #![feature(array_windows)]
1217     /// let slice = [0, 1, 2, 3];
1218     /// let mut iter = slice.array_windows();
1219     /// assert_eq!(iter.next().unwrap(), &[0, 1]);
1220     /// assert_eq!(iter.next().unwrap(), &[1, 2]);
1221     /// assert_eq!(iter.next().unwrap(), &[2, 3]);
1222     /// assert!(iter.next().is_none());
1223     /// ```
1224     ///
1225     /// [`windows`]: slice::windows
1226     #[unstable(feature = "array_windows", issue = "75027")]
1227     #[inline]
1228     pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N> {
1229         assert_ne!(N, 0);
1230         ArrayWindows::new(self)
1231     }
1232
1233     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1234     /// of the slice.
1235     ///
1236     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1237     /// slice, then the last chunk will not have length `chunk_size`.
1238     ///
1239     /// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always exactly
1240     /// `chunk_size` elements, and [`chunks`] for the same iterator but starting at the beginning
1241     /// of the slice.
1242     ///
1243     /// # Panics
1244     ///
1245     /// Panics if `chunk_size` is 0.
1246     ///
1247     /// # Examples
1248     ///
1249     /// ```
1250     /// let slice = ['l', 'o', 'r', 'e', 'm'];
1251     /// let mut iter = slice.rchunks(2);
1252     /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1253     /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1254     /// assert_eq!(iter.next().unwrap(), &['l']);
1255     /// assert!(iter.next().is_none());
1256     /// ```
1257     ///
1258     /// [`rchunks_exact`]: slice::rchunks_exact
1259     /// [`chunks`]: slice::chunks
1260     #[stable(feature = "rchunks", since = "1.31.0")]
1261     #[inline]
1262     pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> {
1263         assert!(chunk_size != 0);
1264         RChunks::new(self, chunk_size)
1265     }
1266
1267     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1268     /// of the slice.
1269     ///
1270     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1271     /// length of the slice, then the last chunk will not have length `chunk_size`.
1272     ///
1273     /// See [`rchunks_exact_mut`] for a variant of this iterator that returns chunks of always
1274     /// exactly `chunk_size` elements, and [`chunks_mut`] for the same iterator but starting at the
1275     /// beginning of the slice.
1276     ///
1277     /// # Panics
1278     ///
1279     /// Panics if `chunk_size` is 0.
1280     ///
1281     /// # Examples
1282     ///
1283     /// ```
1284     /// let v = &mut [0, 0, 0, 0, 0];
1285     /// let mut count = 1;
1286     ///
1287     /// for chunk in v.rchunks_mut(2) {
1288     ///     for elem in chunk.iter_mut() {
1289     ///         *elem += count;
1290     ///     }
1291     ///     count += 1;
1292     /// }
1293     /// assert_eq!(v, &[3, 2, 2, 1, 1]);
1294     /// ```
1295     ///
1296     /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
1297     /// [`chunks_mut`]: slice::chunks_mut
1298     #[stable(feature = "rchunks", since = "1.31.0")]
1299     #[inline]
1300     pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> {
1301         assert!(chunk_size != 0);
1302         RChunksMut::new(self, chunk_size)
1303     }
1304
1305     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
1306     /// end of the slice.
1307     ///
1308     /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1309     /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
1310     /// from the `remainder` function of the iterator.
1311     ///
1312     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1313     /// resulting code better than in the case of [`chunks`].
1314     ///
1315     /// See [`rchunks`] for a variant of this iterator that also returns the remainder as a smaller
1316     /// chunk, and [`chunks_exact`] for the same iterator but starting at the beginning of the
1317     /// slice.
1318     ///
1319     /// # Panics
1320     ///
1321     /// Panics if `chunk_size` is 0.
1322     ///
1323     /// # Examples
1324     ///
1325     /// ```
1326     /// let slice = ['l', 'o', 'r', 'e', 'm'];
1327     /// let mut iter = slice.rchunks_exact(2);
1328     /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1329     /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1330     /// assert!(iter.next().is_none());
1331     /// assert_eq!(iter.remainder(), &['l']);
1332     /// ```
1333     ///
1334     /// [`chunks`]: slice::chunks
1335     /// [`rchunks`]: slice::rchunks
1336     /// [`chunks_exact`]: slice::chunks_exact
1337     #[stable(feature = "rchunks", since = "1.31.0")]
1338     #[inline]
1339     pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> {
1340         assert!(chunk_size != 0);
1341         RChunksExact::new(self, chunk_size)
1342     }
1343
1344     /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1345     /// of the slice.
1346     ///
1347     /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1348     /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
1349     /// retrieved from the `into_remainder` function of the iterator.
1350     ///
1351     /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1352     /// resulting code better than in the case of [`chunks_mut`].
1353     ///
1354     /// See [`rchunks_mut`] for a variant of this iterator that also returns the remainder as a
1355     /// smaller chunk, and [`chunks_exact_mut`] for the same iterator but starting at the beginning
1356     /// of the slice.
1357     ///
1358     /// # Panics
1359     ///
1360     /// Panics if `chunk_size` is 0.
1361     ///
1362     /// # Examples
1363     ///
1364     /// ```
1365     /// let v = &mut [0, 0, 0, 0, 0];
1366     /// let mut count = 1;
1367     ///
1368     /// for chunk in v.rchunks_exact_mut(2) {
1369     ///     for elem in chunk.iter_mut() {
1370     ///         *elem += count;
1371     ///     }
1372     ///     count += 1;
1373     /// }
1374     /// assert_eq!(v, &[0, 2, 2, 1, 1]);
1375     /// ```
1376     ///
1377     /// [`chunks_mut`]: slice::chunks_mut
1378     /// [`rchunks_mut`]: slice::rchunks_mut
1379     /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1380     #[stable(feature = "rchunks", since = "1.31.0")]
1381     #[inline]
1382     pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> {
1383         assert!(chunk_size != 0);
1384         RChunksExactMut::new(self, chunk_size)
1385     }
1386
1387     /// Returns an iterator over the slice producing non-overlapping runs
1388     /// of elements using the predicate to separate them.
1389     ///
1390     /// The predicate is called on two elements following themselves,
1391     /// it means the predicate is called on `slice[0]` and `slice[1]`
1392     /// then on `slice[1]` and `slice[2]` and so on.
1393     ///
1394     /// # Examples
1395     ///
1396     /// ```
1397     /// #![feature(slice_group_by)]
1398     ///
1399     /// let slice = &[1, 1, 1, 3, 3, 2, 2, 2];
1400     ///
1401     /// let mut iter = slice.group_by(|a, b| a == b);
1402     ///
1403     /// assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
1404     /// assert_eq!(iter.next(), Some(&[3, 3][..]));
1405     /// assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
1406     /// assert_eq!(iter.next(), None);
1407     /// ```
1408     ///
1409     /// This method can be used to extract the sorted subslices:
1410     ///
1411     /// ```
1412     /// #![feature(slice_group_by)]
1413     ///
1414     /// let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];
1415     ///
1416     /// let mut iter = slice.group_by(|a, b| a <= b);
1417     ///
1418     /// assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));
1419     /// assert_eq!(iter.next(), Some(&[2, 3][..]));
1420     /// assert_eq!(iter.next(), Some(&[2, 3, 4][..]));
1421     /// assert_eq!(iter.next(), None);
1422     /// ```
1423     #[unstable(feature = "slice_group_by", issue = "80552")]
1424     #[inline]
1425     pub fn group_by<F>(&self, pred: F) -> GroupBy<'_, T, F>
1426     where
1427         F: FnMut(&T, &T) -> bool,
1428     {
1429         GroupBy::new(self, pred)
1430     }
1431
1432     /// Returns an iterator over the slice producing non-overlapping mutable
1433     /// runs of elements using the predicate to separate them.
1434     ///
1435     /// The predicate is called on two elements following themselves,
1436     /// it means the predicate is called on `slice[0]` and `slice[1]`
1437     /// then on `slice[1]` and `slice[2]` and so on.
1438     ///
1439     /// # Examples
1440     ///
1441     /// ```
1442     /// #![feature(slice_group_by)]
1443     ///
1444     /// let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2];
1445     ///
1446     /// let mut iter = slice.group_by_mut(|a, b| a == b);
1447     ///
1448     /// assert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));
1449     /// assert_eq!(iter.next(), Some(&mut [3, 3][..]));
1450     /// assert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));
1451     /// assert_eq!(iter.next(), None);
1452     /// ```
1453     ///
1454     /// This method can be used to extract the sorted subslices:
1455     ///
1456     /// ```
1457     /// #![feature(slice_group_by)]
1458     ///
1459     /// let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4];
1460     ///
1461     /// let mut iter = slice.group_by_mut(|a, b| a <= b);
1462     ///
1463     /// assert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..]));
1464     /// assert_eq!(iter.next(), Some(&mut [2, 3][..]));
1465     /// assert_eq!(iter.next(), Some(&mut [2, 3, 4][..]));
1466     /// assert_eq!(iter.next(), None);
1467     /// ```
1468     #[unstable(feature = "slice_group_by", issue = "80552")]
1469     #[inline]
1470     pub fn group_by_mut<F>(&mut self, pred: F) -> GroupByMut<'_, T, F>
1471     where
1472         F: FnMut(&T, &T) -> bool,
1473     {
1474         GroupByMut::new(self, pred)
1475     }
1476
1477     /// Divides one slice into two at an index.
1478     ///
1479     /// The first will contain all indices from `[0, mid)` (excluding
1480     /// the index `mid` itself) and the second will contain all
1481     /// indices from `[mid, len)` (excluding the index `len` itself).
1482     ///
1483     /// # Panics
1484     ///
1485     /// Panics if `mid > len`.
1486     ///
1487     /// # Examples
1488     ///
1489     /// ```
1490     /// let v = [1, 2, 3, 4, 5, 6];
1491     ///
1492     /// {
1493     ///    let (left, right) = v.split_at(0);
1494     ///    assert_eq!(left, []);
1495     ///    assert_eq!(right, [1, 2, 3, 4, 5, 6]);
1496     /// }
1497     ///
1498     /// {
1499     ///     let (left, right) = v.split_at(2);
1500     ///     assert_eq!(left, [1, 2]);
1501     ///     assert_eq!(right, [3, 4, 5, 6]);
1502     /// }
1503     ///
1504     /// {
1505     ///     let (left, right) = v.split_at(6);
1506     ///     assert_eq!(left, [1, 2, 3, 4, 5, 6]);
1507     ///     assert_eq!(right, []);
1508     /// }
1509     /// ```
1510     #[stable(feature = "rust1", since = "1.0.0")]
1511     #[inline]
1512     pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
1513         assert!(mid <= self.len());
1514         // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which
1515         // fulfills the requirements of `from_raw_parts_mut`.
1516         unsafe { self.split_at_unchecked(mid) }
1517     }
1518
1519     /// Divides one mutable slice into two at an index.
1520     ///
1521     /// The first will contain all indices from `[0, mid)` (excluding
1522     /// the index `mid` itself) and the second will contain all
1523     /// indices from `[mid, len)` (excluding the index `len` itself).
1524     ///
1525     /// # Panics
1526     ///
1527     /// Panics if `mid > len`.
1528     ///
1529     /// # Examples
1530     ///
1531     /// ```
1532     /// let mut v = [1, 0, 3, 0, 5, 6];
1533     /// let (left, right) = v.split_at_mut(2);
1534     /// assert_eq!(left, [1, 0]);
1535     /// assert_eq!(right, [3, 0, 5, 6]);
1536     /// left[1] = 2;
1537     /// right[1] = 4;
1538     /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1539     /// ```
1540     #[stable(feature = "rust1", since = "1.0.0")]
1541     #[inline]
1542     pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1543         assert!(mid <= self.len());
1544         // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which
1545         // fulfills the requirements of `from_raw_parts_mut`.
1546         unsafe { self.split_at_mut_unchecked(mid) }
1547     }
1548
1549     /// Divides one slice into two at an index, without doing bounds checking.
1550     ///
1551     /// The first will contain all indices from `[0, mid)` (excluding
1552     /// the index `mid` itself) and the second will contain all
1553     /// indices from `[mid, len)` (excluding the index `len` itself).
1554     ///
1555     /// For a safe alternative see [`split_at`].
1556     ///
1557     /// # Safety
1558     ///
1559     /// Calling this method with an out-of-bounds index is *[undefined behavior]*
1560     /// even if the resulting reference is not used. The caller has to ensure that
1561     /// `0 <= mid <= self.len()`.
1562     ///
1563     /// [`split_at`]: slice::split_at
1564     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1565     ///
1566     /// # Examples
1567     ///
1568     /// ```compile_fail
1569     /// #![feature(slice_split_at_unchecked)]
1570     ///
1571     /// let v = [1, 2, 3, 4, 5, 6];
1572     ///
1573     /// unsafe {
1574     ///    let (left, right) = v.split_at_unchecked(0);
1575     ///    assert_eq!(left, []);
1576     ///    assert_eq!(right, [1, 2, 3, 4, 5, 6]);
1577     /// }
1578     ///
1579     /// unsafe {
1580     ///     let (left, right) = v.split_at_unchecked(2);
1581     ///     assert_eq!(left, [1, 2]);
1582     ///     assert_eq!(right, [3, 4, 5, 6]);
1583     /// }
1584     ///
1585     /// unsafe {
1586     ///     let (left, right) = v.split_at_unchecked(6);
1587     ///     assert_eq!(left, [1, 2, 3, 4, 5, 6]);
1588     ///     assert_eq!(right, []);
1589     /// }
1590     /// ```
1591     #[unstable(feature = "slice_split_at_unchecked", reason = "new API", issue = "76014")]
1592     #[inline]
1593     unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T]) {
1594         // SAFETY: Caller has to check that `0 <= mid <= self.len()`
1595         unsafe { (self.get_unchecked(..mid), self.get_unchecked(mid..)) }
1596     }
1597
1598     /// Divides one mutable slice into two at an index, without doing bounds checking.
1599     ///
1600     /// The first will contain all indices from `[0, mid)` (excluding
1601     /// the index `mid` itself) and the second will contain all
1602     /// indices from `[mid, len)` (excluding the index `len` itself).
1603     ///
1604     /// For a safe alternative see [`split_at_mut`].
1605     ///
1606     /// # Safety
1607     ///
1608     /// Calling this method with an out-of-bounds index is *[undefined behavior]*
1609     /// even if the resulting reference is not used. The caller has to ensure that
1610     /// `0 <= mid <= self.len()`.
1611     ///
1612     /// [`split_at_mut`]: slice::split_at_mut
1613     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1614     ///
1615     /// # Examples
1616     ///
1617     /// ```compile_fail
1618     /// #![feature(slice_split_at_unchecked)]
1619     ///
1620     /// let mut v = [1, 0, 3, 0, 5, 6];
1621     /// // scoped to restrict the lifetime of the borrows
1622     /// unsafe {
1623     ///     let (left, right) = v.split_at_mut_unchecked(2);
1624     ///     assert_eq!(left, [1, 0]);
1625     ///     assert_eq!(right, [3, 0, 5, 6]);
1626     ///     left[1] = 2;
1627     ///     right[1] = 4;
1628     /// }
1629     /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1630     /// ```
1631     #[unstable(feature = "slice_split_at_unchecked", reason = "new API", issue = "76014")]
1632     #[inline]
1633     unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1634         let len = self.len();
1635         let ptr = self.as_mut_ptr();
1636
1637         // SAFETY: Caller has to check that `0 <= mid <= self.len()`.
1638         //
1639         // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference
1640         // is fine.
1641         unsafe { (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid)) }
1642     }
1643
1644     /// Returns an iterator over subslices separated by elements that match
1645     /// `pred`. The matched element is not contained in the subslices.
1646     ///
1647     /// # Examples
1648     ///
1649     /// ```
1650     /// let slice = [10, 40, 33, 20];
1651     /// let mut iter = slice.split(|num| num % 3 == 0);
1652     ///
1653     /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1654     /// assert_eq!(iter.next().unwrap(), &[20]);
1655     /// assert!(iter.next().is_none());
1656     /// ```
1657     ///
1658     /// If the first element is matched, an empty slice will be the first item
1659     /// returned by the iterator. Similarly, if the last element in the slice
1660     /// is matched, an empty slice will be the last item returned by the
1661     /// iterator:
1662     ///
1663     /// ```
1664     /// let slice = [10, 40, 33];
1665     /// let mut iter = slice.split(|num| num % 3 == 0);
1666     ///
1667     /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1668     /// assert_eq!(iter.next().unwrap(), &[]);
1669     /// assert!(iter.next().is_none());
1670     /// ```
1671     ///
1672     /// If two matched elements are directly adjacent, an empty slice will be
1673     /// present between them:
1674     ///
1675     /// ```
1676     /// let slice = [10, 6, 33, 20];
1677     /// let mut iter = slice.split(|num| num % 3 == 0);
1678     ///
1679     /// assert_eq!(iter.next().unwrap(), &[10]);
1680     /// assert_eq!(iter.next().unwrap(), &[]);
1681     /// assert_eq!(iter.next().unwrap(), &[20]);
1682     /// assert!(iter.next().is_none());
1683     /// ```
1684     #[stable(feature = "rust1", since = "1.0.0")]
1685     #[inline]
1686     pub fn split<F>(&self, pred: F) -> Split<'_, T, F>
1687     where
1688         F: FnMut(&T) -> bool,
1689     {
1690         Split::new(self, pred)
1691     }
1692
1693     /// Returns an iterator over mutable subslices separated by elements that
1694     /// match `pred`. The matched element is not contained in the subslices.
1695     ///
1696     /// # Examples
1697     ///
1698     /// ```
1699     /// let mut v = [10, 40, 30, 20, 60, 50];
1700     ///
1701     /// for group in v.split_mut(|num| *num % 3 == 0) {
1702     ///     group[0] = 1;
1703     /// }
1704     /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
1705     /// ```
1706     #[stable(feature = "rust1", since = "1.0.0")]
1707     #[inline]
1708     pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>
1709     where
1710         F: FnMut(&T) -> bool,
1711     {
1712         SplitMut::new(self, pred)
1713     }
1714
1715     /// Returns an iterator over subslices separated by elements that match
1716     /// `pred`. The matched element is contained in the end of the previous
1717     /// subslice as a terminator.
1718     ///
1719     /// # Examples
1720     ///
1721     /// ```
1722     /// let slice = [10, 40, 33, 20];
1723     /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1724     ///
1725     /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1726     /// assert_eq!(iter.next().unwrap(), &[20]);
1727     /// assert!(iter.next().is_none());
1728     /// ```
1729     ///
1730     /// If the last element of the slice is matched,
1731     /// that element will be considered the terminator of the preceding slice.
1732     /// That slice will be the last item returned by the iterator.
1733     ///
1734     /// ```
1735     /// let slice = [3, 10, 40, 33];
1736     /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1737     ///
1738     /// assert_eq!(iter.next().unwrap(), &[3]);
1739     /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1740     /// assert!(iter.next().is_none());
1741     /// ```
1742     #[stable(feature = "split_inclusive", since = "1.51.0")]
1743     #[inline]
1744     pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>
1745     where
1746         F: FnMut(&T) -> bool,
1747     {
1748         SplitInclusive::new(self, pred)
1749     }
1750
1751     /// Returns an iterator over mutable subslices separated by elements that
1752     /// match `pred`. The matched element is contained in the previous
1753     /// subslice as a terminator.
1754     ///
1755     /// # Examples
1756     ///
1757     /// ```
1758     /// let mut v = [10, 40, 30, 20, 60, 50];
1759     ///
1760     /// for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
1761     ///     let terminator_idx = group.len()-1;
1762     ///     group[terminator_idx] = 1;
1763     /// }
1764     /// assert_eq!(v, [10, 40, 1, 20, 1, 1]);
1765     /// ```
1766     #[stable(feature = "split_inclusive", since = "1.51.0")]
1767     #[inline]
1768     pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>
1769     where
1770         F: FnMut(&T) -> bool,
1771     {
1772         SplitInclusiveMut::new(self, pred)
1773     }
1774
1775     /// Returns an iterator over subslices separated by elements that match
1776     /// `pred`, starting at the end of the slice and working backwards.
1777     /// The matched element is not contained in the subslices.
1778     ///
1779     /// # Examples
1780     ///
1781     /// ```
1782     /// let slice = [11, 22, 33, 0, 44, 55];
1783     /// let mut iter = slice.rsplit(|num| *num == 0);
1784     ///
1785     /// assert_eq!(iter.next().unwrap(), &[44, 55]);
1786     /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
1787     /// assert_eq!(iter.next(), None);
1788     /// ```
1789     ///
1790     /// As with `split()`, if the first or last element is matched, an empty
1791     /// slice will be the first (or last) item returned by the iterator.
1792     ///
1793     /// ```
1794     /// let v = &[0, 1, 1, 2, 3, 5, 8];
1795     /// let mut it = v.rsplit(|n| *n % 2 == 0);
1796     /// assert_eq!(it.next().unwrap(), &[]);
1797     /// assert_eq!(it.next().unwrap(), &[3, 5]);
1798     /// assert_eq!(it.next().unwrap(), &[1, 1]);
1799     /// assert_eq!(it.next().unwrap(), &[]);
1800     /// assert_eq!(it.next(), None);
1801     /// ```
1802     #[stable(feature = "slice_rsplit", since = "1.27.0")]
1803     #[inline]
1804     pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>
1805     where
1806         F: FnMut(&T) -> bool,
1807     {
1808         RSplit::new(self, pred)
1809     }
1810
1811     /// Returns an iterator over mutable subslices separated by elements that
1812     /// match `pred`, starting at the end of the slice and working
1813     /// backwards. The matched element is not contained in the subslices.
1814     ///
1815     /// # Examples
1816     ///
1817     /// ```
1818     /// let mut v = [100, 400, 300, 200, 600, 500];
1819     ///
1820     /// let mut count = 0;
1821     /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
1822     ///     count += 1;
1823     ///     group[0] = count;
1824     /// }
1825     /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
1826     /// ```
1827     ///
1828     #[stable(feature = "slice_rsplit", since = "1.27.0")]
1829     #[inline]
1830     pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>
1831     where
1832         F: FnMut(&T) -> bool,
1833     {
1834         RSplitMut::new(self, pred)
1835     }
1836
1837     /// Returns an iterator over subslices separated by elements that match
1838     /// `pred`, limited to returning at most `n` items. The matched element is
1839     /// not contained in the subslices.
1840     ///
1841     /// The last element returned, if any, will contain the remainder of the
1842     /// slice.
1843     ///
1844     /// # Examples
1845     ///
1846     /// Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`,
1847     /// `[20, 60, 50]`):
1848     ///
1849     /// ```
1850     /// let v = [10, 40, 30, 20, 60, 50];
1851     ///
1852     /// for group in v.splitn(2, |num| *num % 3 == 0) {
1853     ///     println!("{:?}", group);
1854     /// }
1855     /// ```
1856     #[stable(feature = "rust1", since = "1.0.0")]
1857     #[inline]
1858     pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>
1859     where
1860         F: FnMut(&T) -> bool,
1861     {
1862         SplitN::new(self.split(pred), n)
1863     }
1864
1865     /// Returns an iterator over subslices separated by elements that match
1866     /// `pred`, limited to returning at most `n` items. The matched element is
1867     /// not contained in the subslices.
1868     ///
1869     /// The last element returned, if any, will contain the remainder of the
1870     /// slice.
1871     ///
1872     /// # Examples
1873     ///
1874     /// ```
1875     /// let mut v = [10, 40, 30, 20, 60, 50];
1876     ///
1877     /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
1878     ///     group[0] = 1;
1879     /// }
1880     /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
1881     /// ```
1882     #[stable(feature = "rust1", since = "1.0.0")]
1883     #[inline]
1884     pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>
1885     where
1886         F: FnMut(&T) -> bool,
1887     {
1888         SplitNMut::new(self.split_mut(pred), n)
1889     }
1890
1891     /// Returns an iterator over subslices separated by elements that match
1892     /// `pred` limited to returning at most `n` items. This starts at the end of
1893     /// the slice and works backwards. The matched element is not contained in
1894     /// the subslices.
1895     ///
1896     /// The last element returned, if any, will contain the remainder of the
1897     /// slice.
1898     ///
1899     /// # Examples
1900     ///
1901     /// Print the slice split once, starting from the end, by numbers divisible
1902     /// by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):
1903     ///
1904     /// ```
1905     /// let v = [10, 40, 30, 20, 60, 50];
1906     ///
1907     /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
1908     ///     println!("{:?}", group);
1909     /// }
1910     /// ```
1911     #[stable(feature = "rust1", since = "1.0.0")]
1912     #[inline]
1913     pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>
1914     where
1915         F: FnMut(&T) -> bool,
1916     {
1917         RSplitN::new(self.rsplit(pred), n)
1918     }
1919
1920     /// Returns an iterator over subslices separated by elements that match
1921     /// `pred` limited to returning at most `n` items. This starts at the end of
1922     /// the slice and works backwards. The matched element is not contained in
1923     /// the subslices.
1924     ///
1925     /// The last element returned, if any, will contain the remainder of the
1926     /// slice.
1927     ///
1928     /// # Examples
1929     ///
1930     /// ```
1931     /// let mut s = [10, 40, 30, 20, 60, 50];
1932     ///
1933     /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
1934     ///     group[0] = 1;
1935     /// }
1936     /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
1937     /// ```
1938     #[stable(feature = "rust1", since = "1.0.0")]
1939     #[inline]
1940     pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>
1941     where
1942         F: FnMut(&T) -> bool,
1943     {
1944         RSplitNMut::new(self.rsplit_mut(pred), n)
1945     }
1946
1947     /// Returns `true` if the slice contains an element with the given value.
1948     ///
1949     /// # Examples
1950     ///
1951     /// ```
1952     /// let v = [10, 40, 30];
1953     /// assert!(v.contains(&30));
1954     /// assert!(!v.contains(&50));
1955     /// ```
1956     ///
1957     /// If you do not have an `&T`, but just an `&U` such that `T: Borrow<U>`
1958     /// (e.g. `String: Borrow<str>`), you can use `iter().any`:
1959     ///
1960     /// ```
1961     /// let v = [String::from("hello"), String::from("world")]; // slice of `String`
1962     /// assert!(v.iter().any(|e| e == "hello")); // search with `&str`
1963     /// assert!(!v.iter().any(|e| e == "hi"));
1964     /// ```
1965     #[stable(feature = "rust1", since = "1.0.0")]
1966     #[inline]
1967     pub fn contains(&self, x: &T) -> bool
1968     where
1969         T: PartialEq,
1970     {
1971         cmp::SliceContains::slice_contains(x, self)
1972     }
1973
1974     /// Returns `true` if `needle` is a prefix of the slice.
1975     ///
1976     /// # Examples
1977     ///
1978     /// ```
1979     /// let v = [10, 40, 30];
1980     /// assert!(v.starts_with(&[10]));
1981     /// assert!(v.starts_with(&[10, 40]));
1982     /// assert!(!v.starts_with(&[50]));
1983     /// assert!(!v.starts_with(&[10, 50]));
1984     /// ```
1985     ///
1986     /// Always returns `true` if `needle` is an empty slice:
1987     ///
1988     /// ```
1989     /// let v = &[10, 40, 30];
1990     /// assert!(v.starts_with(&[]));
1991     /// let v: &[u8] = &[];
1992     /// assert!(v.starts_with(&[]));
1993     /// ```
1994     #[stable(feature = "rust1", since = "1.0.0")]
1995     pub fn starts_with(&self, needle: &[T]) -> bool
1996     where
1997         T: PartialEq,
1998     {
1999         let n = needle.len();
2000         self.len() >= n && needle == &self[..n]
2001     }
2002
2003     /// Returns `true` if `needle` is a suffix of the slice.
2004     ///
2005     /// # Examples
2006     ///
2007     /// ```
2008     /// let v = [10, 40, 30];
2009     /// assert!(v.ends_with(&[30]));
2010     /// assert!(v.ends_with(&[40, 30]));
2011     /// assert!(!v.ends_with(&[50]));
2012     /// assert!(!v.ends_with(&[50, 30]));
2013     /// ```
2014     ///
2015     /// Always returns `true` if `needle` is an empty slice:
2016     ///
2017     /// ```
2018     /// let v = &[10, 40, 30];
2019     /// assert!(v.ends_with(&[]));
2020     /// let v: &[u8] = &[];
2021     /// assert!(v.ends_with(&[]));
2022     /// ```
2023     #[stable(feature = "rust1", since = "1.0.0")]
2024     pub fn ends_with(&self, needle: &[T]) -> bool
2025     where
2026         T: PartialEq,
2027     {
2028         let (m, n) = (self.len(), needle.len());
2029         m >= n && needle == &self[m - n..]
2030     }
2031
2032     /// Returns a subslice with the prefix removed.
2033     ///
2034     /// If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`.
2035     /// If `prefix` is empty, simply returns the original slice.
2036     ///
2037     /// If the slice does not start with `prefix`, returns `None`.
2038     ///
2039     /// # Examples
2040     ///
2041     /// ```
2042     /// let v = &[10, 40, 30];
2043     /// assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
2044     /// assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
2045     /// assert_eq!(v.strip_prefix(&[50]), None);
2046     /// assert_eq!(v.strip_prefix(&[10, 50]), None);
2047     ///
2048     /// let prefix : &str = "he";
2049     /// assert_eq!(b"hello".strip_prefix(prefix.as_bytes()),
2050     ///            Some(b"llo".as_ref()));
2051     /// ```
2052     #[must_use = "returns the subslice without modifying the original"]
2053     #[stable(feature = "slice_strip", since = "1.51.0")]
2054     pub fn strip_prefix<P: SlicePattern<Item = T> + ?Sized>(&self, prefix: &P) -> Option<&[T]>
2055     where
2056         T: PartialEq,
2057     {
2058         // This function will need rewriting if and when SlicePattern becomes more sophisticated.
2059         let prefix = prefix.as_slice();
2060         let n = prefix.len();
2061         if n <= self.len() {
2062             let (head, tail) = self.split_at(n);
2063             if head == prefix {
2064                 return Some(tail);
2065             }
2066         }
2067         None
2068     }
2069
2070     /// Returns a subslice with the suffix removed.
2071     ///
2072     /// If the slice ends with `suffix`, returns the subslice before the suffix, wrapped in `Some`.
2073     /// If `suffix` is empty, simply returns the original slice.
2074     ///
2075     /// If the slice does not end with `suffix`, returns `None`.
2076     ///
2077     /// # Examples
2078     ///
2079     /// ```
2080     /// let v = &[10, 40, 30];
2081     /// assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
2082     /// assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
2083     /// assert_eq!(v.strip_suffix(&[50]), None);
2084     /// assert_eq!(v.strip_suffix(&[50, 30]), None);
2085     /// ```
2086     #[must_use = "returns the subslice without modifying the original"]
2087     #[stable(feature = "slice_strip", since = "1.51.0")]
2088     pub fn strip_suffix<P: SlicePattern<Item = T> + ?Sized>(&self, suffix: &P) -> Option<&[T]>
2089     where
2090         T: PartialEq,
2091     {
2092         // This function will need rewriting if and when SlicePattern becomes more sophisticated.
2093         let suffix = suffix.as_slice();
2094         let (len, n) = (self.len(), suffix.len());
2095         if n <= len {
2096             let (head, tail) = self.split_at(len - n);
2097             if tail == suffix {
2098                 return Some(head);
2099             }
2100         }
2101         None
2102     }
2103
2104     /// Binary searches this sorted slice for a given element.
2105     ///
2106     /// If the value is found then [`Result::Ok`] is returned, containing the
2107     /// index of the matching element. If there are multiple matches, then any
2108     /// one of the matches could be returned. If the value is not found then
2109     /// [`Result::Err`] is returned, containing the index where a matching
2110     /// element could be inserted while maintaining sorted order.
2111     ///
2112     /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
2113     ///
2114     /// [`binary_search_by`]: slice::binary_search_by
2115     /// [`binary_search_by_key`]: slice::binary_search_by_key
2116     /// [`partition_point`]: slice::partition_point
2117     ///
2118     /// # Examples
2119     ///
2120     /// Looks up a series of four elements. The first is found, with a
2121     /// uniquely determined position; the second and third are not
2122     /// found; the fourth could match any position in `[1, 4]`.
2123     ///
2124     /// ```
2125     /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2126     ///
2127     /// assert_eq!(s.binary_search(&13),  Ok(9));
2128     /// assert_eq!(s.binary_search(&4),   Err(7));
2129     /// assert_eq!(s.binary_search(&100), Err(13));
2130     /// let r = s.binary_search(&1);
2131     /// assert!(match r { Ok(1..=4) => true, _ => false, });
2132     /// ```
2133     ///
2134     /// If you want to insert an item to a sorted vector, while maintaining
2135     /// sort order:
2136     ///
2137     /// ```
2138     /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2139     /// let num = 42;
2140     /// let idx = s.binary_search(&num).unwrap_or_else(|x| x);
2141     /// s.insert(idx, num);
2142     /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2143     /// ```
2144     #[stable(feature = "rust1", since = "1.0.0")]
2145     pub fn binary_search(&self, x: &T) -> Result<usize, usize>
2146     where
2147         T: Ord,
2148     {
2149         self.binary_search_by(|p| p.cmp(x))
2150     }
2151
2152     /// Binary searches this sorted slice with a comparator function.
2153     ///
2154     /// The comparator function should implement an order consistent
2155     /// with the sort order of the underlying slice, returning an
2156     /// order code that indicates whether its argument is `Less`,
2157     /// `Equal` or `Greater` the desired target.
2158     ///
2159     /// If the value is found then [`Result::Ok`] is returned, containing the
2160     /// index of the matching element. If there are multiple matches, then any
2161     /// one of the matches could be returned. If the value is not found then
2162     /// [`Result::Err`] is returned, containing the index where a matching
2163     /// element could be inserted while maintaining sorted order.
2164     ///
2165     /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
2166     ///
2167     /// [`binary_search`]: slice::binary_search
2168     /// [`binary_search_by_key`]: slice::binary_search_by_key
2169     /// [`partition_point`]: slice::partition_point
2170     ///
2171     /// # Examples
2172     ///
2173     /// Looks up a series of four elements. The first is found, with a
2174     /// uniquely determined position; the second and third are not
2175     /// found; the fourth could match any position in `[1, 4]`.
2176     ///
2177     /// ```
2178     /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2179     ///
2180     /// let seek = 13;
2181     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
2182     /// let seek = 4;
2183     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
2184     /// let seek = 100;
2185     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
2186     /// let seek = 1;
2187     /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
2188     /// assert!(match r { Ok(1..=4) => true, _ => false, });
2189     /// ```
2190     #[stable(feature = "rust1", since = "1.0.0")]
2191     #[inline]
2192     pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
2193     where
2194         F: FnMut(&'a T) -> Ordering,
2195     {
2196         let mut size = self.len();
2197         let mut left = 0;
2198         let mut right = size;
2199         while left < right {
2200             let mid = left + size / 2;
2201
2202             // SAFETY: the call is made safe by the following invariants:
2203             // - `mid >= 0`
2204             // - `mid < size`: `mid` is limited by `[left; right)` bound.
2205             let cmp = f(unsafe { self.get_unchecked(mid) });
2206
2207             // The reason why we use if/else control flow rather than match
2208             // is because match reorders comparison operations, which is perf sensitive.
2209             // This is x86 asm for u8: https://rust.godbolt.org/z/8Y8Pra.
2210             if cmp == Less {
2211                 left = mid + 1;
2212             } else if cmp == Greater {
2213                 right = mid;
2214             } else {
2215                 return Ok(mid);
2216             }
2217
2218             size = right - left;
2219         }
2220         Err(left)
2221     }
2222
2223     /// Binary searches this sorted slice with a key extraction function.
2224     ///
2225     /// Assumes that the slice is sorted by the key, for instance with
2226     /// [`sort_by_key`] using the same key extraction function.
2227     ///
2228     /// If the value is found then [`Result::Ok`] is returned, containing the
2229     /// index of the matching element. If there are multiple matches, then any
2230     /// one of the matches could be returned. If the value is not found then
2231     /// [`Result::Err`] is returned, containing the index where a matching
2232     /// element could be inserted while maintaining sorted order.
2233     ///
2234     /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
2235     ///
2236     /// [`sort_by_key`]: slice::sort_by_key
2237     /// [`binary_search`]: slice::binary_search
2238     /// [`binary_search_by`]: slice::binary_search_by
2239     /// [`partition_point`]: slice::partition_point
2240     ///
2241     /// # Examples
2242     ///
2243     /// Looks up a series of four elements in a slice of pairs sorted by
2244     /// their second elements. The first is found, with a uniquely
2245     /// determined position; the second and third are not found; the
2246     /// fourth could match any position in `[1, 4]`.
2247     ///
2248     /// ```
2249     /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
2250     ///          (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
2251     ///          (1, 21), (2, 34), (4, 55)];
2252     ///
2253     /// assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b),  Ok(9));
2254     /// assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b),   Err(7));
2255     /// assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
2256     /// let r = s.binary_search_by_key(&1, |&(a, b)| b);
2257     /// assert!(match r { Ok(1..=4) => true, _ => false, });
2258     /// ```
2259     // Lint rustdoc::broken_intra_doc_links is allowed as `slice::sort_by_key` is
2260     // in crate `alloc`, and as such doesn't exists yet when building `core`.
2261     // links to downstream crate: #74481. Since primitives are only documented in
2262     // libstd (#73423), this never leads to broken links in practice.
2263     #[cfg_attr(not(bootstrap), allow(rustdoc::broken_intra_doc_links))]
2264     #[cfg_attr(bootstrap, allow(broken_intra_doc_links))]
2265     #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
2266     #[inline]
2267     pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
2268     where
2269         F: FnMut(&'a T) -> B,
2270         B: Ord,
2271     {
2272         self.binary_search_by(|k| f(k).cmp(b))
2273     }
2274
2275     /// Sorts the slice, but may not preserve the order of equal elements.
2276     ///
2277     /// This sort is unstable (i.e., may reorder equal elements), in-place
2278     /// (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.
2279     ///
2280     /// # Current implementation
2281     ///
2282     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
2283     /// which combines the fast average case of randomized quicksort with the fast worst case of
2284     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
2285     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
2286     /// deterministic behavior.
2287     ///
2288     /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
2289     /// slice consists of several concatenated sorted sequences.
2290     ///
2291     /// # Examples
2292     ///
2293     /// ```
2294     /// let mut v = [-5, 4, 1, -3, 2];
2295     ///
2296     /// v.sort_unstable();
2297     /// assert!(v == [-5, -3, 1, 2, 4]);
2298     /// ```
2299     ///
2300     /// [pdqsort]: https://github.com/orlp/pdqsort
2301     #[stable(feature = "sort_unstable", since = "1.20.0")]
2302     #[inline]
2303     pub fn sort_unstable(&mut self)
2304     where
2305         T: Ord,
2306     {
2307         sort::quicksort(self, |a, b| a.lt(b));
2308     }
2309
2310     /// Sorts the slice with a comparator function, but may not preserve the order of equal
2311     /// elements.
2312     ///
2313     /// This sort is unstable (i.e., may reorder equal elements), in-place
2314     /// (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.
2315     ///
2316     /// The comparator function must define a total ordering for the elements in the slice. If
2317     /// the ordering is not total, the order of the elements is unspecified. An order is a
2318     /// total order if it is (for all `a`, `b` and `c`):
2319     ///
2320     /// * total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true, and
2321     /// * transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
2322     ///
2323     /// For example, while [`f64`] doesn't implement [`Ord`] because `NaN != NaN`, we can use
2324     /// `partial_cmp` as our sort function when we know the slice doesn't contain a `NaN`.
2325     ///
2326     /// ```
2327     /// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
2328     /// floats.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
2329     /// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
2330     /// ```
2331     ///
2332     /// # Current implementation
2333     ///
2334     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
2335     /// which combines the fast average case of randomized quicksort with the fast worst case of
2336     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
2337     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
2338     /// deterministic behavior.
2339     ///
2340     /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
2341     /// slice consists of several concatenated sorted sequences.
2342     ///
2343     /// # Examples
2344     ///
2345     /// ```
2346     /// let mut v = [5, 4, 1, 3, 2];
2347     /// v.sort_unstable_by(|a, b| a.cmp(b));
2348     /// assert!(v == [1, 2, 3, 4, 5]);
2349     ///
2350     /// // reverse sorting
2351     /// v.sort_unstable_by(|a, b| b.cmp(a));
2352     /// assert!(v == [5, 4, 3, 2, 1]);
2353     /// ```
2354     ///
2355     /// [pdqsort]: https://github.com/orlp/pdqsort
2356     #[stable(feature = "sort_unstable", since = "1.20.0")]
2357     #[inline]
2358     pub fn sort_unstable_by<F>(&mut self, mut compare: F)
2359     where
2360         F: FnMut(&T, &T) -> Ordering,
2361     {
2362         sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
2363     }
2364
2365     /// Sorts the slice with a key extraction function, but may not preserve the order of equal
2366     /// elements.
2367     ///
2368     /// This sort is unstable (i.e., may reorder equal elements), in-place
2369     /// (i.e., does not allocate), and *O*(m \* *n* \* log(*n*)) worst-case, where the key function is
2370     /// *O*(*m*).
2371     ///
2372     /// # Current implementation
2373     ///
2374     /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
2375     /// which combines the fast average case of randomized quicksort with the fast worst case of
2376     /// heapsort, while achieving linear time on slices with certain patterns. It uses some
2377     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
2378     /// deterministic behavior.
2379     ///
2380     /// Due to its key calling strategy, [`sort_unstable_by_key`](#method.sort_unstable_by_key)
2381     /// is likely to be slower than [`sort_by_cached_key`](#method.sort_by_cached_key) in
2382     /// cases where the key function is expensive.
2383     ///
2384     /// # Examples
2385     ///
2386     /// ```
2387     /// let mut v = [-5i32, 4, 1, -3, 2];
2388     ///
2389     /// v.sort_unstable_by_key(|k| k.abs());
2390     /// assert!(v == [1, 2, -3, 4, -5]);
2391     /// ```
2392     ///
2393     /// [pdqsort]: https://github.com/orlp/pdqsort
2394     #[stable(feature = "sort_unstable", since = "1.20.0")]
2395     #[inline]
2396     pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
2397     where
2398         F: FnMut(&T) -> K,
2399         K: Ord,
2400     {
2401         sort::quicksort(self, |a, b| f(a).lt(&f(b)));
2402     }
2403
2404     /// Reorder the slice such that the element at `index` is at its final sorted position.
2405     #[unstable(feature = "slice_partition_at_index", issue = "55300")]
2406     #[rustc_deprecated(since = "1.49.0", reason = "use the select_nth_unstable() instead")]
2407     #[inline]
2408     pub fn partition_at_index(&mut self, index: usize) -> (&mut [T], &mut T, &mut [T])
2409     where
2410         T: Ord,
2411     {
2412         self.select_nth_unstable(index)
2413     }
2414
2415     /// Reorder the slice with a comparator function such that the element at `index` is at its
2416     /// final sorted position.
2417     #[unstable(feature = "slice_partition_at_index", issue = "55300")]
2418     #[rustc_deprecated(since = "1.49.0", reason = "use select_nth_unstable_by() instead")]
2419     #[inline]
2420     pub fn partition_at_index_by<F>(
2421         &mut self,
2422         index: usize,
2423         compare: F,
2424     ) -> (&mut [T], &mut T, &mut [T])
2425     where
2426         F: FnMut(&T, &T) -> Ordering,
2427     {
2428         self.select_nth_unstable_by(index, compare)
2429     }
2430
2431     /// Reorder the slice with a key extraction function such that the element at `index` is at its
2432     /// final sorted position.
2433     #[unstable(feature = "slice_partition_at_index", issue = "55300")]
2434     #[rustc_deprecated(since = "1.49.0", reason = "use the select_nth_unstable_by_key() instead")]
2435     #[inline]
2436     pub fn partition_at_index_by_key<K, F>(
2437         &mut self,
2438         index: usize,
2439         f: F,
2440     ) -> (&mut [T], &mut T, &mut [T])
2441     where
2442         F: FnMut(&T) -> K,
2443         K: Ord,
2444     {
2445         self.select_nth_unstable_by_key(index, f)
2446     }
2447
2448     /// Reorder the slice such that the element at `index` is at its final sorted position.
2449     ///
2450     /// This reordering has the additional property that any value at position `i < index` will be
2451     /// less than or equal to any value at a position `j > index`. Additionally, this reordering is
2452     /// unstable (i.e. any number of equal elements may end up at position `index`), in-place
2453     /// (i.e. does not allocate), and *O*(*n*) worst-case. This function is also/ known as "kth
2454     /// element" in other libraries. It returns a triplet of the following values: all elements less
2455     /// than the one at the given index, the value at the given index, and all elements greater than
2456     /// the one at the given index.
2457     ///
2458     /// # Current implementation
2459     ///
2460     /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2461     /// used for [`sort_unstable`].
2462     ///
2463     /// [`sort_unstable`]: slice::sort_unstable
2464     ///
2465     /// # Panics
2466     ///
2467     /// Panics when `index >= len()`, meaning it always panics on empty slices.
2468     ///
2469     /// # Examples
2470     ///
2471     /// ```
2472     /// let mut v = [-5i32, 4, 1, -3, 2];
2473     ///
2474     /// // Find the median
2475     /// v.select_nth_unstable(2);
2476     ///
2477     /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2478     /// // about the specified index.
2479     /// assert!(v == [-3, -5, 1, 2, 4] ||
2480     ///         v == [-5, -3, 1, 2, 4] ||
2481     ///         v == [-3, -5, 1, 4, 2] ||
2482     ///         v == [-5, -3, 1, 4, 2]);
2483     /// ```
2484     #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
2485     #[inline]
2486     pub fn select_nth_unstable(&mut self, index: usize) -> (&mut [T], &mut T, &mut [T])
2487     where
2488         T: Ord,
2489     {
2490         let mut f = |a: &T, b: &T| a.lt(b);
2491         sort::partition_at_index(self, index, &mut f)
2492     }
2493
2494     /// Reorder the slice with a comparator function such that the element at `index` is at its
2495     /// final sorted position.
2496     ///
2497     /// This reordering has the additional property that any value at position `i < index` will be
2498     /// less than or equal to any value at a position `j > index` using the comparator function.
2499     /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
2500     /// position `index`), in-place (i.e. does not allocate), and *O*(*n*) worst-case. This function
2501     /// is also known as "kth element" in other libraries. It returns a triplet of the following
2502     /// values: all elements less than the one at the given index, the value at the given index,
2503     /// and all elements greater than the one at the given index, using the provided comparator
2504     /// function.
2505     ///
2506     /// # Current implementation
2507     ///
2508     /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2509     /// used for [`sort_unstable`].
2510     ///
2511     /// [`sort_unstable`]: slice::sort_unstable
2512     ///
2513     /// # Panics
2514     ///
2515     /// Panics when `index >= len()`, meaning it always panics on empty slices.
2516     ///
2517     /// # Examples
2518     ///
2519     /// ```
2520     /// let mut v = [-5i32, 4, 1, -3, 2];
2521     ///
2522     /// // Find the median as if the slice were sorted in descending order.
2523     /// v.select_nth_unstable_by(2, |a, b| b.cmp(a));
2524     ///
2525     /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2526     /// // about the specified index.
2527     /// assert!(v == [2, 4, 1, -5, -3] ||
2528     ///         v == [2, 4, 1, -3, -5] ||
2529     ///         v == [4, 2, 1, -5, -3] ||
2530     ///         v == [4, 2, 1, -3, -5]);
2531     /// ```
2532     #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
2533     #[inline]
2534     pub fn select_nth_unstable_by<F>(
2535         &mut self,
2536         index: usize,
2537         mut compare: F,
2538     ) -> (&mut [T], &mut T, &mut [T])
2539     where
2540         F: FnMut(&T, &T) -> Ordering,
2541     {
2542         let mut f = |a: &T, b: &T| compare(a, b) == Less;
2543         sort::partition_at_index(self, index, &mut f)
2544     }
2545
2546     /// Reorder the slice with a key extraction function such that the element at `index` is at its
2547     /// final sorted position.
2548     ///
2549     /// This reordering has the additional property that any value at position `i < index` will be
2550     /// less than or equal to any value at a position `j > index` using the key extraction function.
2551     /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
2552     /// position `index`), in-place (i.e. does not allocate), and *O*(*n*) worst-case. This function
2553     /// is also known as "kth element" in other libraries. It returns a triplet of the following
2554     /// values: all elements less than the one at the given index, the value at the given index, and
2555     /// all elements greater than the one at the given index, using the provided key extraction
2556     /// function.
2557     ///
2558     /// # Current implementation
2559     ///
2560     /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
2561     /// used for [`sort_unstable`].
2562     ///
2563     /// [`sort_unstable`]: slice::sort_unstable
2564     ///
2565     /// # Panics
2566     ///
2567     /// Panics when `index >= len()`, meaning it always panics on empty slices.
2568     ///
2569     /// # Examples
2570     ///
2571     /// ```
2572     /// let mut v = [-5i32, 4, 1, -3, 2];
2573     ///
2574     /// // Return the median as if the array were sorted according to absolute value.
2575     /// v.select_nth_unstable_by_key(2, |a| a.abs());
2576     ///
2577     /// // We are only guaranteed the slice will be one of the following, based on the way we sort
2578     /// // about the specified index.
2579     /// assert!(v == [1, 2, -3, 4, -5] ||
2580     ///         v == [1, 2, -3, -5, 4] ||
2581     ///         v == [2, 1, -3, 4, -5] ||
2582     ///         v == [2, 1, -3, -5, 4]);
2583     /// ```
2584     #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
2585     #[inline]
2586     pub fn select_nth_unstable_by_key<K, F>(
2587         &mut self,
2588         index: usize,
2589         mut f: F,
2590     ) -> (&mut [T], &mut T, &mut [T])
2591     where
2592         F: FnMut(&T) -> K,
2593         K: Ord,
2594     {
2595         let mut g = |a: &T, b: &T| f(a).lt(&f(b));
2596         sort::partition_at_index(self, index, &mut g)
2597     }
2598
2599     /// Moves all consecutive repeated elements to the end of the slice according to the
2600     /// [`PartialEq`] trait implementation.
2601     ///
2602     /// Returns two slices. The first contains no consecutive repeated elements.
2603     /// The second contains all the duplicates in no specified order.
2604     ///
2605     /// If the slice is sorted, the first returned slice contains no duplicates.
2606     ///
2607     /// # Examples
2608     ///
2609     /// ```
2610     /// #![feature(slice_partition_dedup)]
2611     ///
2612     /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
2613     ///
2614     /// let (dedup, duplicates) = slice.partition_dedup();
2615     ///
2616     /// assert_eq!(dedup, [1, 2, 3, 2, 1]);
2617     /// assert_eq!(duplicates, [2, 3, 1]);
2618     /// ```
2619     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2620     #[inline]
2621     pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
2622     where
2623         T: PartialEq,
2624     {
2625         self.partition_dedup_by(|a, b| a == b)
2626     }
2627
2628     /// Moves all but the first of consecutive elements to the end of the slice satisfying
2629     /// a given equality relation.
2630     ///
2631     /// Returns two slices. The first contains no consecutive repeated elements.
2632     /// The second contains all the duplicates in no specified order.
2633     ///
2634     /// The `same_bucket` function is passed references to two elements from the slice and
2635     /// must determine if the elements compare equal. The elements are passed in opposite order
2636     /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved
2637     /// at the end of the slice.
2638     ///
2639     /// If the slice is sorted, the first returned slice contains no duplicates.
2640     ///
2641     /// # Examples
2642     ///
2643     /// ```
2644     /// #![feature(slice_partition_dedup)]
2645     ///
2646     /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
2647     ///
2648     /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
2649     ///
2650     /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
2651     /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
2652     /// ```
2653     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2654     #[inline]
2655     pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])
2656     where
2657         F: FnMut(&mut T, &mut T) -> bool,
2658     {
2659         // Although we have a mutable reference to `self`, we cannot make
2660         // *arbitrary* changes. The `same_bucket` calls could panic, so we
2661         // must ensure that the slice is in a valid state at all times.
2662         //
2663         // The way that we handle this is by using swaps; we iterate
2664         // over all the elements, swapping as we go so that at the end
2665         // the elements we wish to keep are in the front, and those we
2666         // wish to reject are at the back. We can then split the slice.
2667         // This operation is still `O(n)`.
2668         //
2669         // Example: We start in this state, where `r` represents "next
2670         // read" and `w` represents "next_write`.
2671         //
2672         //           r
2673         //     +---+---+---+---+---+---+
2674         //     | 0 | 1 | 1 | 2 | 3 | 3 |
2675         //     +---+---+---+---+---+---+
2676         //           w
2677         //
2678         // Comparing self[r] against self[w-1], this is not a duplicate, so
2679         // we swap self[r] and self[w] (no effect as r==w) and then increment both
2680         // r and w, leaving us with:
2681         //
2682         //               r
2683         //     +---+---+---+---+---+---+
2684         //     | 0 | 1 | 1 | 2 | 3 | 3 |
2685         //     +---+---+---+---+---+---+
2686         //               w
2687         //
2688         // Comparing self[r] against self[w-1], this value is a duplicate,
2689         // so we increment `r` but leave everything else unchanged:
2690         //
2691         //                   r
2692         //     +---+---+---+---+---+---+
2693         //     | 0 | 1 | 1 | 2 | 3 | 3 |
2694         //     +---+---+---+---+---+---+
2695         //               w
2696         //
2697         // Comparing self[r] against self[w-1], this is not a duplicate,
2698         // so swap self[r] and self[w] and advance r and w:
2699         //
2700         //                       r
2701         //     +---+---+---+---+---+---+
2702         //     | 0 | 1 | 2 | 1 | 3 | 3 |
2703         //     +---+---+---+---+---+---+
2704         //                   w
2705         //
2706         // Not a duplicate, repeat:
2707         //
2708         //                           r
2709         //     +---+---+---+---+---+---+
2710         //     | 0 | 1 | 2 | 3 | 1 | 3 |
2711         //     +---+---+---+---+---+---+
2712         //                       w
2713         //
2714         // Duplicate, advance r. End of slice. Split at w.
2715
2716         let len = self.len();
2717         if len <= 1 {
2718             return (self, &mut []);
2719         }
2720
2721         let ptr = self.as_mut_ptr();
2722         let mut next_read: usize = 1;
2723         let mut next_write: usize = 1;
2724
2725         // SAFETY: the `while` condition guarantees `next_read` and `next_write`
2726         // are less than `len`, thus are inside `self`. `prev_ptr_write` points to
2727         // one element before `ptr_write`, but `next_write` starts at 1, so
2728         // `prev_ptr_write` is never less than 0 and is inside the slice.
2729         // This fulfils the requirements for dereferencing `ptr_read`, `prev_ptr_write`
2730         // and `ptr_write`, and for using `ptr.add(next_read)`, `ptr.add(next_write - 1)`
2731         // and `prev_ptr_write.offset(1)`.
2732         //
2733         // `next_write` is also incremented at most once per loop at most meaning
2734         // no element is skipped when it may need to be swapped.
2735         //
2736         // `ptr_read` and `prev_ptr_write` never point to the same element. This
2737         // is required for `&mut *ptr_read`, `&mut *prev_ptr_write` to be safe.
2738         // The explanation is simply that `next_read >= next_write` is always true,
2739         // thus `next_read > next_write - 1` is too.
2740         unsafe {
2741             // Avoid bounds checks by using raw pointers.
2742             while next_read < len {
2743                 let ptr_read = ptr.add(next_read);
2744                 let prev_ptr_write = ptr.add(next_write - 1);
2745                 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
2746                     if next_read != next_write {
2747                         let ptr_write = prev_ptr_write.offset(1);
2748                         mem::swap(&mut *ptr_read, &mut *ptr_write);
2749                     }
2750                     next_write += 1;
2751                 }
2752                 next_read += 1;
2753             }
2754         }
2755
2756         self.split_at_mut(next_write)
2757     }
2758
2759     /// Moves all but the first of consecutive elements to the end of the slice that resolve
2760     /// to the same key.
2761     ///
2762     /// Returns two slices. The first contains no consecutive repeated elements.
2763     /// The second contains all the duplicates in no specified order.
2764     ///
2765     /// If the slice is sorted, the first returned slice contains no duplicates.
2766     ///
2767     /// # Examples
2768     ///
2769     /// ```
2770     /// #![feature(slice_partition_dedup)]
2771     ///
2772     /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
2773     ///
2774     /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
2775     ///
2776     /// assert_eq!(dedup, [10, 20, 30, 20, 11]);
2777     /// assert_eq!(duplicates, [21, 30, 13]);
2778     /// ```
2779     #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2780     #[inline]
2781     pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])
2782     where
2783         F: FnMut(&mut T) -> K,
2784         K: PartialEq,
2785     {
2786         self.partition_dedup_by(|a, b| key(a) == key(b))
2787     }
2788
2789     /// Rotates the slice in-place such that the first `mid` elements of the
2790     /// slice move to the end while the last `self.len() - mid` elements move to
2791     /// the front. After calling `rotate_left`, the element previously at index
2792     /// `mid` will become the first element in the slice.
2793     ///
2794     /// # Panics
2795     ///
2796     /// This function will panic if `mid` is greater than the length of the
2797     /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
2798     /// rotation.
2799     ///
2800     /// # Complexity
2801     ///
2802     /// Takes linear (in `self.len()`) time.
2803     ///
2804     /// # Examples
2805     ///
2806     /// ```
2807     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2808     /// a.rotate_left(2);
2809     /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
2810     /// ```
2811     ///
2812     /// Rotating a subslice:
2813     ///
2814     /// ```
2815     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2816     /// a[1..5].rotate_left(1);
2817     /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
2818     /// ```
2819     #[stable(feature = "slice_rotate", since = "1.26.0")]
2820     pub fn rotate_left(&mut self, mid: usize) {
2821         assert!(mid <= self.len());
2822         let k = self.len() - mid;
2823         let p = self.as_mut_ptr();
2824
2825         // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
2826         // valid for reading and writing, as required by `ptr_rotate`.
2827         unsafe {
2828             rotate::ptr_rotate(mid, p.add(mid), k);
2829         }
2830     }
2831
2832     /// Rotates the slice in-place such that the first `self.len() - k`
2833     /// elements of the slice move to the end while the last `k` elements move
2834     /// to the front. After calling `rotate_right`, the element previously at
2835     /// index `self.len() - k` will become the first element in the slice.
2836     ///
2837     /// # Panics
2838     ///
2839     /// This function will panic if `k` is greater than the length of the
2840     /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
2841     /// rotation.
2842     ///
2843     /// # Complexity
2844     ///
2845     /// Takes linear (in `self.len()`) time.
2846     ///
2847     /// # Examples
2848     ///
2849     /// ```
2850     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2851     /// a.rotate_right(2);
2852     /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
2853     /// ```
2854     ///
2855     /// Rotate a subslice:
2856     ///
2857     /// ```
2858     /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2859     /// a[1..5].rotate_right(1);
2860     /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
2861     /// ```
2862     #[stable(feature = "slice_rotate", since = "1.26.0")]
2863     pub fn rotate_right(&mut self, k: usize) {
2864         assert!(k <= self.len());
2865         let mid = self.len() - k;
2866         let p = self.as_mut_ptr();
2867
2868         // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
2869         // valid for reading and writing, as required by `ptr_rotate`.
2870         unsafe {
2871             rotate::ptr_rotate(mid, p.add(mid), k);
2872         }
2873     }
2874
2875     /// Fills `self` with elements by cloning `value`.
2876     ///
2877     /// # Examples
2878     ///
2879     /// ```
2880     /// let mut buf = vec![0; 10];
2881     /// buf.fill(1);
2882     /// assert_eq!(buf, vec![1; 10]);
2883     /// ```
2884     #[doc(alias = "memset")]
2885     #[stable(feature = "slice_fill", since = "1.50.0")]
2886     pub fn fill(&mut self, value: T)
2887     where
2888         T: Clone,
2889     {
2890         specialize::SpecFill::spec_fill(self, value);
2891     }
2892
2893     /// Fills `self` with elements returned by calling a closure repeatedly.
2894     ///
2895     /// This method uses a closure to create new values. If you'd rather
2896     /// [`Clone`] a given value, use [`fill`]. If you want to use the [`Default`]
2897     /// trait to generate values, you can pass [`Default::default`] as the
2898     /// argument.
2899     ///
2900     /// [`fill`]: slice::fill
2901     ///
2902     /// # Examples
2903     ///
2904     /// ```
2905     /// let mut buf = vec![1; 10];
2906     /// buf.fill_with(Default::default);
2907     /// assert_eq!(buf, vec![0; 10]);
2908     /// ```
2909     #[doc(alias = "memset")]
2910     #[stable(feature = "slice_fill_with", since = "1.51.0")]
2911     pub fn fill_with<F>(&mut self, mut f: F)
2912     where
2913         F: FnMut() -> T,
2914     {
2915         for el in self {
2916             *el = f();
2917         }
2918     }
2919
2920     /// Copies the elements from `src` into `self`.
2921     ///
2922     /// The length of `src` must be the same as `self`.
2923     ///
2924     /// If `T` implements `Copy`, it can be more performant to use
2925     /// [`copy_from_slice`].
2926     ///
2927     /// # Panics
2928     ///
2929     /// This function will panic if the two slices have different lengths.
2930     ///
2931     /// # Examples
2932     ///
2933     /// Cloning two elements from a slice into another:
2934     ///
2935     /// ```
2936     /// let src = [1, 2, 3, 4];
2937     /// let mut dst = [0, 0];
2938     ///
2939     /// // Because the slices have to be the same length,
2940     /// // we slice the source slice from four elements
2941     /// // to two. It will panic if we don't do this.
2942     /// dst.clone_from_slice(&src[2..]);
2943     ///
2944     /// assert_eq!(src, [1, 2, 3, 4]);
2945     /// assert_eq!(dst, [3, 4]);
2946     /// ```
2947     ///
2948     /// Rust enforces that there can only be one mutable reference with no
2949     /// immutable references to a particular piece of data in a particular
2950     /// scope. Because of this, attempting to use `clone_from_slice` on a
2951     /// single slice will result in a compile failure:
2952     ///
2953     /// ```compile_fail
2954     /// let mut slice = [1, 2, 3, 4, 5];
2955     ///
2956     /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
2957     /// ```
2958     ///
2959     /// To work around this, we can use [`split_at_mut`] to create two distinct
2960     /// sub-slices from a slice:
2961     ///
2962     /// ```
2963     /// let mut slice = [1, 2, 3, 4, 5];
2964     ///
2965     /// {
2966     ///     let (left, right) = slice.split_at_mut(2);
2967     ///     left.clone_from_slice(&right[1..]);
2968     /// }
2969     ///
2970     /// assert_eq!(slice, [4, 5, 3, 4, 5]);
2971     /// ```
2972     ///
2973     /// [`copy_from_slice`]: slice::copy_from_slice
2974     /// [`split_at_mut`]: slice::split_at_mut
2975     #[stable(feature = "clone_from_slice", since = "1.7.0")]
2976     pub fn clone_from_slice(&mut self, src: &[T])
2977     where
2978         T: Clone,
2979     {
2980         self.spec_clone_from(src);
2981     }
2982
2983     /// Copies all elements from `src` into `self`, using a memcpy.
2984     ///
2985     /// The length of `src` must be the same as `self`.
2986     ///
2987     /// If `T` does not implement `Copy`, use [`clone_from_slice`].
2988     ///
2989     /// # Panics
2990     ///
2991     /// This function will panic if the two slices have different lengths.
2992     ///
2993     /// # Examples
2994     ///
2995     /// Copying two elements from a slice into another:
2996     ///
2997     /// ```
2998     /// let src = [1, 2, 3, 4];
2999     /// let mut dst = [0, 0];
3000     ///
3001     /// // Because the slices have to be the same length,
3002     /// // we slice the source slice from four elements
3003     /// // to two. It will panic if we don't do this.
3004     /// dst.copy_from_slice(&src[2..]);
3005     ///
3006     /// assert_eq!(src, [1, 2, 3, 4]);
3007     /// assert_eq!(dst, [3, 4]);
3008     /// ```
3009     ///
3010     /// Rust enforces that there can only be one mutable reference with no
3011     /// immutable references to a particular piece of data in a particular
3012     /// scope. Because of this, attempting to use `copy_from_slice` on a
3013     /// single slice will result in a compile failure:
3014     ///
3015     /// ```compile_fail
3016     /// let mut slice = [1, 2, 3, 4, 5];
3017     ///
3018     /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
3019     /// ```
3020     ///
3021     /// To work around this, we can use [`split_at_mut`] to create two distinct
3022     /// sub-slices from a slice:
3023     ///
3024     /// ```
3025     /// let mut slice = [1, 2, 3, 4, 5];
3026     ///
3027     /// {
3028     ///     let (left, right) = slice.split_at_mut(2);
3029     ///     left.copy_from_slice(&right[1..]);
3030     /// }
3031     ///
3032     /// assert_eq!(slice, [4, 5, 3, 4, 5]);
3033     /// ```
3034     ///
3035     /// [`clone_from_slice`]: slice::clone_from_slice
3036     /// [`split_at_mut`]: slice::split_at_mut
3037     #[doc(alias = "memcpy")]
3038     #[stable(feature = "copy_from_slice", since = "1.9.0")]
3039     pub fn copy_from_slice(&mut self, src: &[T])
3040     where
3041         T: Copy,
3042     {
3043         // The panic code path was put into a cold function to not bloat the
3044         // call site.
3045         #[inline(never)]
3046         #[cold]
3047         #[track_caller]
3048         fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! {
3049             panic!(
3050                 "source slice length ({}) does not match destination slice length ({})",
3051                 src_len, dst_len,
3052             );
3053         }
3054
3055         if self.len() != src.len() {
3056             len_mismatch_fail(self.len(), src.len());
3057         }
3058
3059         // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
3060         // checked to have the same length. The slices cannot overlap because
3061         // mutable references are exclusive.
3062         unsafe {
3063             ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len());
3064         }
3065     }
3066
3067     /// Copies elements from one part of the slice to another part of itself,
3068     /// using a memmove.
3069     ///
3070     /// `src` is the range within `self` to copy from. `dest` is the starting
3071     /// index of the range within `self` to copy to, which will have the same
3072     /// length as `src`. The two ranges may overlap. The ends of the two ranges
3073     /// must be less than or equal to `self.len()`.
3074     ///
3075     /// # Panics
3076     ///
3077     /// This function will panic if either range exceeds the end of the slice,
3078     /// or if the end of `src` is before the start.
3079     ///
3080     /// # Examples
3081     ///
3082     /// Copying four bytes within a slice:
3083     ///
3084     /// ```
3085     /// let mut bytes = *b"Hello, World!";
3086     ///
3087     /// bytes.copy_within(1..5, 8);
3088     ///
3089     /// assert_eq!(&bytes, b"Hello, Wello!");
3090     /// ```
3091     #[stable(feature = "copy_within", since = "1.37.0")]
3092     #[track_caller]
3093     pub fn copy_within<R: RangeBounds<usize>>(&mut self, src: R, dest: usize)
3094     where
3095         T: Copy,
3096     {
3097         let Range { start: src_start, end: src_end } = slice::range(src, ..self.len());
3098         let count = src_end - src_start;
3099         assert!(dest <= self.len() - count, "dest is out of bounds");
3100         // SAFETY: the conditions for `ptr::copy` have all been checked above,
3101         // as have those for `ptr::add`.
3102         unsafe {
3103             ptr::copy(self.as_ptr().add(src_start), self.as_mut_ptr().add(dest), count);
3104         }
3105     }
3106
3107     /// Swaps all elements in `self` with those in `other`.
3108     ///
3109     /// The length of `other` must be the same as `self`.
3110     ///
3111     /// # Panics
3112     ///
3113     /// This function will panic if the two slices have different lengths.
3114     ///
3115     /// # Example
3116     ///
3117     /// Swapping two elements across slices:
3118     ///
3119     /// ```
3120     /// let mut slice1 = [0, 0];
3121     /// let mut slice2 = [1, 2, 3, 4];
3122     ///
3123     /// slice1.swap_with_slice(&mut slice2[2..]);
3124     ///
3125     /// assert_eq!(slice1, [3, 4]);
3126     /// assert_eq!(slice2, [1, 2, 0, 0]);
3127     /// ```
3128     ///
3129     /// Rust enforces that there can only be one mutable reference to a
3130     /// particular piece of data in a particular scope. Because of this,
3131     /// attempting to use `swap_with_slice` on a single slice will result in
3132     /// a compile failure:
3133     ///
3134     /// ```compile_fail
3135     /// let mut slice = [1, 2, 3, 4, 5];
3136     /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
3137     /// ```
3138     ///
3139     /// To work around this, we can use [`split_at_mut`] to create two distinct
3140     /// mutable sub-slices from a slice:
3141     ///
3142     /// ```
3143     /// let mut slice = [1, 2, 3, 4, 5];
3144     ///
3145     /// {
3146     ///     let (left, right) = slice.split_at_mut(2);
3147     ///     left.swap_with_slice(&mut right[1..]);
3148     /// }
3149     ///
3150     /// assert_eq!(slice, [4, 5, 3, 1, 2]);
3151     /// ```
3152     ///
3153     /// [`split_at_mut`]: slice::split_at_mut
3154     #[stable(feature = "swap_with_slice", since = "1.27.0")]
3155     pub fn swap_with_slice(&mut self, other: &mut [T]) {
3156         assert!(self.len() == other.len(), "destination and source slices have different lengths");
3157         // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
3158         // checked to have the same length. The slices cannot overlap because
3159         // mutable references are exclusive.
3160         unsafe {
3161             ptr::swap_nonoverlapping(self.as_mut_ptr(), other.as_mut_ptr(), self.len());
3162         }
3163     }
3164
3165     /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
3166     fn align_to_offsets<U>(&self) -> (usize, usize) {
3167         // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
3168         // lowest number of `T`s. And how many `T`s we need for each such "multiple".
3169         //
3170         // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
3171         // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
3172         // place of every 3 Ts in the `rest` slice. A bit more complicated.
3173         //
3174         // Formula to calculate this is:
3175         //
3176         // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
3177         // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
3178         //
3179         // Expanded and simplified:
3180         //
3181         // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
3182         // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
3183         //
3184         // Luckily since all this is constant-evaluated... performance here matters not!
3185         #[inline]
3186         fn gcd(a: usize, b: usize) -> usize {
3187             use crate::intrinsics;
3188             // iterative stein’s algorithm
3189             // We should still make this `const fn` (and revert to recursive algorithm if we do)
3190             // because relying on llvm to consteval all this is… well, it makes me uncomfortable.
3191
3192             // SAFETY: `a` and `b` are checked to be non-zero values.
3193             let (ctz_a, mut ctz_b) = unsafe {
3194                 if a == 0 {
3195                     return b;
3196                 }
3197                 if b == 0 {
3198                     return a;
3199                 }
3200                 (intrinsics::cttz_nonzero(a), intrinsics::cttz_nonzero(b))
3201             };
3202             let k = ctz_a.min(ctz_b);
3203             let mut a = a >> ctz_a;
3204             let mut b = b;
3205             loop {
3206                 // remove all factors of 2 from b
3207                 b >>= ctz_b;
3208                 if a > b {
3209                     mem::swap(&mut a, &mut b);
3210                 }
3211                 b = b - a;
3212                 // SAFETY: `b` is checked to be non-zero.
3213                 unsafe {
3214                     if b == 0 {
3215                         break;
3216                     }
3217                     ctz_b = intrinsics::cttz_nonzero(b);
3218                 }
3219             }
3220             a << k
3221         }
3222         let gcd: usize = gcd(mem::size_of::<T>(), mem::size_of::<U>());
3223         let ts: usize = mem::size_of::<U>() / gcd;
3224         let us: usize = mem::size_of::<T>() / gcd;
3225
3226         // Armed with this knowledge, we can find how many `U`s we can fit!
3227         let us_len = self.len() / ts * us;
3228         // And how many `T`s will be in the trailing slice!
3229         let ts_len = self.len() % ts;
3230         (us_len, ts_len)
3231     }
3232
3233     /// Transmute the slice to a slice of another type, ensuring alignment of the types is
3234     /// maintained.
3235     ///
3236     /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
3237     /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest
3238     /// length possible for a given type and input slice, but only your algorithm's performance
3239     /// should depend on that, not its correctness. It is permissible for all of the input data to
3240     /// be returned as the prefix or suffix slice.
3241     ///
3242     /// This method has no purpose when either input element `T` or output element `U` are
3243     /// zero-sized and will return the original slice without splitting anything.
3244     ///
3245     /// # Safety
3246     ///
3247     /// This method is essentially a `transmute` with respect to the elements in the returned
3248     /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
3249     ///
3250     /// # Examples
3251     ///
3252     /// Basic usage:
3253     ///
3254     /// ```
3255     /// unsafe {
3256     ///     let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
3257     ///     let (prefix, shorts, suffix) = bytes.align_to::<u16>();
3258     ///     // less_efficient_algorithm_for_bytes(prefix);
3259     ///     // more_efficient_algorithm_for_aligned_shorts(shorts);
3260     ///     // less_efficient_algorithm_for_bytes(suffix);
3261     /// }
3262     /// ```
3263     #[stable(feature = "slice_align_to", since = "1.30.0")]
3264     pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
3265         // Note that most of this function will be constant-evaluated,
3266         if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
3267             // handle ZSTs specially, which is â€“ don't handle them at all.
3268             return (self, &[], &[]);
3269         }
3270
3271         // First, find at what point do we split between the first and 2nd slice. Easy with
3272         // ptr.align_offset.
3273         let ptr = self.as_ptr();
3274         // SAFETY: See the `align_to_mut` method for the detailed safety comment.
3275         let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::<U>()) };
3276         if offset > self.len() {
3277             (self, &[], &[])
3278         } else {
3279             let (left, rest) = self.split_at(offset);
3280             let (us_len, ts_len) = rest.align_to_offsets::<U>();
3281             // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay,
3282             // since the caller guarantees that we can transmute `T` to `U` safely.
3283             unsafe {
3284                 (
3285                     left,
3286                     from_raw_parts(rest.as_ptr() as *const U, us_len),
3287                     from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len),
3288                 )
3289             }
3290         }
3291     }
3292
3293     /// Transmute the slice to a slice of another type, ensuring alignment of the types is
3294     /// maintained.
3295     ///
3296     /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
3297     /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest
3298     /// length possible for a given type and input slice, but only your algorithm's performance
3299     /// should depend on that, not its correctness. It is permissible for all of the input data to
3300     /// be returned as the prefix or suffix slice.
3301     ///
3302     /// This method has no purpose when either input element `T` or output element `U` are
3303     /// zero-sized and will return the original slice without splitting anything.
3304     ///
3305     /// # Safety
3306     ///
3307     /// This method is essentially a `transmute` with respect to the elements in the returned
3308     /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
3309     ///
3310     /// # Examples
3311     ///
3312     /// Basic usage:
3313     ///
3314     /// ```
3315     /// unsafe {
3316     ///     let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
3317     ///     let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
3318     ///     // less_efficient_algorithm_for_bytes(prefix);
3319     ///     // more_efficient_algorithm_for_aligned_shorts(shorts);
3320     ///     // less_efficient_algorithm_for_bytes(suffix);
3321     /// }
3322     /// ```
3323     #[stable(feature = "slice_align_to", since = "1.30.0")]
3324     pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
3325         // Note that most of this function will be constant-evaluated,
3326         if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
3327             // handle ZSTs specially, which is â€“ don't handle them at all.
3328             return (self, &mut [], &mut []);
3329         }
3330
3331         // First, find at what point do we split between the first and 2nd slice. Easy with
3332         // ptr.align_offset.
3333         let ptr = self.as_ptr();
3334         // SAFETY: Here we are ensuring we will use aligned pointers for U for the
3335         // rest of the method. This is done by passing a pointer to &[T] with an
3336         // alignment targeted for U.
3337         // `crate::ptr::align_offset` is called with a correctly aligned and
3338         // valid pointer `ptr` (it comes from a reference to `self`) and with
3339         // a size that is a power of two (since it comes from the alignement for U),
3340         // satisfying its safety constraints.
3341         let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::<U>()) };
3342         if offset > self.len() {
3343             (self, &mut [], &mut [])
3344         } else {
3345             let (left, rest) = self.split_at_mut(offset);
3346             let (us_len, ts_len) = rest.align_to_offsets::<U>();
3347             let rest_len = rest.len();
3348             let mut_ptr = rest.as_mut_ptr();
3349             // We can't use `rest` again after this, that would invalidate its alias `mut_ptr`!
3350             // SAFETY: see comments for `align_to`.
3351             unsafe {
3352                 (
3353                     left,
3354                     from_raw_parts_mut(mut_ptr as *mut U, us_len),
3355                     from_raw_parts_mut(mut_ptr.add(rest_len - ts_len), ts_len),
3356                 )
3357             }
3358         }
3359     }
3360
3361     /// Checks if the elements of this slice are sorted.
3362     ///
3363     /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3364     /// slice yields exactly zero or one element, `true` is returned.
3365     ///
3366     /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3367     /// implies that this function returns `false` if any two consecutive items are not
3368     /// comparable.
3369     ///
3370     /// # Examples
3371     ///
3372     /// ```
3373     /// #![feature(is_sorted)]
3374     /// let empty: [i32; 0] = [];
3375     ///
3376     /// assert!([1, 2, 2, 9].is_sorted());
3377     /// assert!(![1, 3, 2, 4].is_sorted());
3378     /// assert!([0].is_sorted());
3379     /// assert!(empty.is_sorted());
3380     /// assert!(![0.0, 1.0, f32::NAN].is_sorted());
3381     /// ```
3382     #[inline]
3383     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3384     pub fn is_sorted(&self) -> bool
3385     where
3386         T: PartialOrd,
3387     {
3388         self.is_sorted_by(|a, b| a.partial_cmp(b))
3389     }
3390
3391     /// Checks if the elements of this slice are sorted using the given comparator function.
3392     ///
3393     /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3394     /// function to determine the ordering of two elements. Apart from that, it's equivalent to
3395     /// [`is_sorted`]; see its documentation for more information.
3396     ///
3397     /// [`is_sorted`]: slice::is_sorted
3398     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3399     pub fn is_sorted_by<F>(&self, mut compare: F) -> bool
3400     where
3401         F: FnMut(&T, &T) -> Option<Ordering>,
3402     {
3403         self.iter().is_sorted_by(|a, b| compare(*a, *b))
3404     }
3405
3406     /// Checks if the elements of this slice are sorted using the given key extraction function.
3407     ///
3408     /// Instead of comparing the slice's elements directly, this function compares the keys of the
3409     /// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its
3410     /// documentation for more information.
3411     ///
3412     /// [`is_sorted`]: slice::is_sorted
3413     ///
3414     /// # Examples
3415     ///
3416     /// ```
3417     /// #![feature(is_sorted)]
3418     ///
3419     /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
3420     /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
3421     /// ```
3422     #[inline]
3423     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3424     pub fn is_sorted_by_key<F, K>(&self, f: F) -> bool
3425     where
3426         F: FnMut(&T) -> K,
3427         K: PartialOrd,
3428     {
3429         self.iter().is_sorted_by_key(f)
3430     }
3431
3432     /// Returns the index of the partition point according to the given predicate
3433     /// (the index of the first element of the second partition).
3434     ///
3435     /// The slice is assumed to be partitioned according to the given predicate.
3436     /// This means that all elements for which the predicate returns true are at the start of the slice
3437     /// and all elements for which the predicate returns false are at the end.
3438     /// For example, [7, 15, 3, 5, 4, 12, 6] is a partitioned under the predicate x % 2 != 0
3439     /// (all odd numbers are at the start, all even at the end).
3440     ///
3441     /// If this slice is not partitioned, the returned result is unspecified and meaningless,
3442     /// as this method performs a kind of binary search.
3443     ///
3444     /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
3445     ///
3446     /// [`binary_search`]: slice::binary_search
3447     /// [`binary_search_by`]: slice::binary_search_by
3448     /// [`binary_search_by_key`]: slice::binary_search_by_key
3449     ///
3450     /// # Examples
3451     ///
3452     /// ```
3453     /// let v = [1, 2, 3, 3, 5, 6, 7];
3454     /// let i = v.partition_point(|&x| x < 5);
3455     ///
3456     /// assert_eq!(i, 4);
3457     /// assert!(v[..i].iter().all(|&x| x < 5));
3458     /// assert!(v[i..].iter().all(|&x| !(x < 5)));
3459     /// ```
3460     #[stable(feature = "partition_point", since = "1.52.0")]
3461     pub fn partition_point<P>(&self, mut pred: P) -> usize
3462     where
3463         P: FnMut(&T) -> bool,
3464     {
3465         let mut left = 0;
3466         let mut right = self.len();
3467
3468         while left != right {
3469             let mid = left + (right - left) / 2;
3470             // SAFETY: When `left < right`, `left <= mid < right`.
3471             // Therefore `left` always increases and `right` always decreases,
3472             // and either of them is selected. In both cases `left <= right` is
3473             // satisfied. Therefore if `left < right` in a step, `left <= right`
3474             // is satisfied in the next step. Therefore as long as `left != right`,
3475             // `0 <= left < right <= len` is satisfied and if this case
3476             // `0 <= mid < len` is satisfied too.
3477             let value = unsafe { self.get_unchecked(mid) };
3478             if pred(value) {
3479                 left = mid + 1;
3480             } else {
3481                 right = mid;
3482             }
3483         }
3484
3485         left
3486     }
3487 }
3488
3489 trait CloneFromSpec<T> {
3490     fn spec_clone_from(&mut self, src: &[T]);
3491 }
3492
3493 impl<T> CloneFromSpec<T> for [T]
3494 where
3495     T: Clone,
3496 {
3497     default fn spec_clone_from(&mut self, src: &[T]) {
3498         assert!(self.len() == src.len(), "destination and source slices have different lengths");
3499         // NOTE: We need to explicitly slice them to the same length
3500         // to make it easier for the optimizer to elide bounds checking.
3501         // But since it can't be relied on we also have an explicit specialization for T: Copy.
3502         let len = self.len();
3503         let src = &src[..len];
3504         for i in 0..len {
3505             self[i].clone_from(&src[i]);
3506         }
3507     }
3508 }
3509
3510 impl<T> CloneFromSpec<T> for [T]
3511 where
3512     T: Copy,
3513 {
3514     fn spec_clone_from(&mut self, src: &[T]) {
3515         self.copy_from_slice(src);
3516     }
3517 }
3518
3519 #[stable(feature = "rust1", since = "1.0.0")]
3520 impl<T> Default for &[T] {
3521     /// Creates an empty slice.
3522     fn default() -> Self {
3523         &[]
3524     }
3525 }
3526
3527 #[stable(feature = "mut_slice_default", since = "1.5.0")]
3528 impl<T> Default for &mut [T] {
3529     /// Creates a mutable empty slice.
3530     fn default() -> Self {
3531         &mut []
3532     }
3533 }
3534
3535 #[unstable(feature = "slice_pattern", reason = "stopgap trait for slice patterns", issue = "56345")]
3536 /// Patterns in slices - currently, only used by `strip_prefix` and `strip_suffix`.  At a future
3537 /// point, we hope to generalise `core::str::Pattern` (which at the time of writing is limited to
3538 /// `str`) to slices, and then this trait will be replaced or abolished.
3539 pub trait SlicePattern {
3540     /// The element type of the slice being matched on.
3541     type Item;
3542
3543     /// Currently, the consumers of `SlicePattern` need a slice.
3544     fn as_slice(&self) -> &[Self::Item];
3545 }
3546
3547 #[stable(feature = "slice_strip", since = "1.51.0")]
3548 impl<T> SlicePattern for [T] {
3549     type Item = T;
3550
3551     #[inline]
3552     fn as_slice(&self) -> &[Self::Item] {
3553         self
3554     }
3555 }
3556
3557 #[stable(feature = "slice_strip", since = "1.51.0")]
3558 impl<T, const N: usize> SlicePattern for [T; N] {
3559     type Item = T;
3560
3561     #[inline]
3562     fn as_slice(&self) -> &[Self::Item] {
3563         self
3564     }
3565 }