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