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