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