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