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