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