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