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