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