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 #[rustc_const_unstable(feature = "slice_as_chunks", issue = "74985")]
1291 #[inline]
1292 #[must_use]
1293 pub const unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]] {
1294 assert_unsafe_precondition!(
1295 check_language_ub,
1296 "slice::as_chunks_unchecked requires `N != 0` and the slice to split exactly into `N`-element chunks",
1297 (n: usize = N, len: usize = self.len()) => n != 0 && len % n == 0,
1298 );
1299 // SAFETY: Caller must guarantee that `N` is nonzero and exactly divides the slice length
1300 let new_len = unsafe { exact_div(self.len(), N) };
1301 // SAFETY: We cast a slice of `new_len * N` elements into
1302 // a slice of `new_len` many `N` elements chunks.
1303 unsafe { from_raw_parts(self.as_ptr().cast(), new_len) }
1304 }
1305
1306 /// Splits the slice into a slice of `N`-element arrays,
1307 /// starting at the beginning of the slice,
1308 /// and a remainder slice with length strictly less than `N`.
1309 ///
1310 /// # Panics
1311 ///
1312 /// Panics if `N` is zero. This check will most probably get changed to a compile time
1313 /// error before this method gets stabilized.
1314 ///
1315 /// # Examples
1316 ///
1317 /// ```
1318 /// #![feature(slice_as_chunks)]
1319 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1320 /// let (chunks, remainder) = slice.as_chunks();
1321 /// assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);
1322 /// assert_eq!(remainder, &['m']);
1323 /// ```
1324 ///
1325 /// If you expect the slice to be an exact multiple, you can combine
1326 /// `let`-`else` with an empty slice pattern:
1327 /// ```
1328 /// #![feature(slice_as_chunks)]
1329 /// let slice = ['R', 'u', 's', 't'];
1330 /// let (chunks, []) = slice.as_chunks::<2>() else {
1331 /// panic!("slice didn't have even length")
1332 /// };
1333 /// assert_eq!(chunks, &[['R', 'u'], ['s', 't']]);
1334 /// ```
1335 #[unstable(feature = "slice_as_chunks", issue = "74985")]
1336 #[rustc_const_unstable(feature = "slice_as_chunks", issue = "74985")]
1337 #[inline]
1338 #[track_caller]
1339 #[must_use]
1340 pub const fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T]) {
1341 assert!(N != 0, "chunk size must be non-zero");
1342 let len_rounded_down = self.len() / N * N;
1343 // SAFETY: The rounded-down value is always the same or smaller than the
1344 // original length, and thus must be in-bounds of the slice.
1345 let (multiple_of_n, remainder) = unsafe { self.split_at_unchecked(len_rounded_down) };
1346 // SAFETY: We already panicked for zero, and ensured by construction
1347 // that the length of the subslice is a multiple of N.
1348 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() };
1349 (array_slice, remainder)
1350 }
1351
1352 /// Splits the slice into a slice of `N`-element arrays,
1353 /// starting at the end of the slice,
1354 /// and a remainder slice with length strictly less than `N`.
1355 ///
1356 /// # Panics
1357 ///
1358 /// Panics if `N` is zero. This check will most probably get changed to a compile time
1359 /// error before this method gets stabilized.
1360 ///
1361 /// # Examples
1362 ///
1363 /// ```
1364 /// #![feature(slice_as_chunks)]
1365 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1366 /// let (remainder, chunks) = slice.as_rchunks();
1367 /// assert_eq!(remainder, &['l']);
1368 /// assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
1369 /// ```
1370 #[unstable(feature = "slice_as_chunks", issue = "74985")]
1371 #[rustc_const_unstable(feature = "slice_as_chunks", issue = "74985")]
1372 #[inline]
1373 #[track_caller]
1374 #[must_use]
1375 pub const fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]]) {
1376 assert!(N != 0, "chunk size must be non-zero");
1377 let len = self.len() / N;
1378 let (remainder, multiple_of_n) = self.split_at(self.len() - len * N);
1379 // SAFETY: We already panicked for zero, and ensured by construction
1380 // that the length of the subslice is a multiple of N.
1381 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() };
1382 (remainder, array_slice)
1383 }
1384
1385 /// Returns an iterator over `N` elements of the slice at a time, starting at the
1386 /// beginning of the slice.
1387 ///
1388 /// The chunks are array references and do not overlap. If `N` does not divide the
1389 /// length of the slice, then the last up to `N-1` elements will be omitted and can be
1390 /// retrieved from the `remainder` function of the iterator.
1391 ///
1392 /// This method is the const generic equivalent of [`chunks_exact`].
1393 ///
1394 /// # Panics
1395 ///
1396 /// Panics if `N` is zero. This check will most probably get changed to a compile time
1397 /// error before this method gets stabilized.
1398 ///
1399 /// # Examples
1400 ///
1401 /// ```
1402 /// #![feature(array_chunks)]
1403 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1404 /// let mut iter = slice.array_chunks();
1405 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
1406 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
1407 /// assert!(iter.next().is_none());
1408 /// assert_eq!(iter.remainder(), &['m']);
1409 /// ```
1410 ///
1411 /// [`chunks_exact`]: slice::chunks_exact
1412 #[unstable(feature = "array_chunks", issue = "74985")]
1413 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1414 #[inline]
1415 #[track_caller]
1416 pub const fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N> {
1417 assert!(N != 0, "chunk size must be non-zero");
1418 ArrayChunks::new(self)
1419 }
1420
1421 /// Splits the slice into a slice of `N`-element arrays,
1422 /// assuming that there's no remainder.
1423 ///
1424 /// # Safety
1425 ///
1426 /// This may only be called when
1427 /// - The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).
1428 /// - `N != 0`.
1429 ///
1430 /// # Examples
1431 ///
1432 /// ```
1433 /// #![feature(slice_as_chunks)]
1434 /// let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!'];
1435 /// let chunks: &mut [[char; 1]] =
1436 /// // SAFETY: 1-element chunks never have remainder
1437 /// unsafe { slice.as_chunks_unchecked_mut() };
1438 /// chunks[0] = ['L'];
1439 /// assert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]);
1440 /// let chunks: &mut [[char; 3]] =
1441 /// // SAFETY: The slice length (6) is a multiple of 3
1442 /// unsafe { slice.as_chunks_unchecked_mut() };
1443 /// chunks[1] = ['a', 'x', '?'];
1444 /// assert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']);
1445 ///
1446 /// // These would be unsound:
1447 /// // let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 5
1448 /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed
1449 /// ```
1450 #[unstable(feature = "slice_as_chunks", issue = "74985")]
1451 #[rustc_const_unstable(feature = "slice_as_chunks", issue = "74985")]
1452 #[inline]
1453 #[must_use]
1454 pub const unsafe fn as_chunks_unchecked_mut<const N: usize>(&mut self) -> &mut [[T; N]] {
1455 assert_unsafe_precondition!(
1456 check_language_ub,
1457 "slice::as_chunks_unchecked requires `N != 0` and the slice to split exactly into `N`-element chunks",
1458 (n: usize = N, len: usize = self.len()) => n != 0 && len % n == 0
1459 );
1460 // SAFETY: Caller must guarantee that `N` is nonzero and exactly divides the slice length
1461 let new_len = unsafe { exact_div(self.len(), N) };
1462 // SAFETY: We cast a slice of `new_len * N` elements into
1463 // a slice of `new_len` many `N` elements chunks.
1464 unsafe { from_raw_parts_mut(self.as_mut_ptr().cast(), new_len) }
1465 }
1466
1467 /// Splits the slice into a slice of `N`-element arrays,
1468 /// starting at the beginning of the slice,
1469 /// and a remainder slice with length strictly less than `N`.
1470 ///
1471 /// # Panics
1472 ///
1473 /// Panics if `N` is zero. This check will most probably get changed to a compile time
1474 /// error before this method gets stabilized.
1475 ///
1476 /// # Examples
1477 ///
1478 /// ```
1479 /// #![feature(slice_as_chunks)]
1480 /// let v = &mut [0, 0, 0, 0, 0];
1481 /// let mut count = 1;
1482 ///
1483 /// let (chunks, remainder) = v.as_chunks_mut();
1484 /// remainder[0] = 9;
1485 /// for chunk in chunks {
1486 /// *chunk = [count; 2];
1487 /// count += 1;
1488 /// }
1489 /// assert_eq!(v, &[1, 1, 2, 2, 9]);
1490 /// ```
1491 #[unstable(feature = "slice_as_chunks", issue = "74985")]
1492 #[rustc_const_unstable(feature = "slice_as_chunks", issue = "74985")]
1493 #[inline]
1494 #[track_caller]
1495 #[must_use]
1496 pub const fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T]) {
1497 assert!(N != 0, "chunk size must be non-zero");
1498 let len_rounded_down = self.len() / N * N;
1499 // SAFETY: The rounded-down value is always the same or smaller than the
1500 // original length, and thus must be in-bounds of the slice.
1501 let (multiple_of_n, remainder) = unsafe { self.split_at_mut_unchecked(len_rounded_down) };
1502 // SAFETY: We already panicked for zero, and ensured by construction
1503 // that the length of the subslice is a multiple of N.
1504 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };
1505 (array_slice, remainder)
1506 }
1507
1508 /// Splits the slice into a slice of `N`-element arrays,
1509 /// starting at the end of the slice,
1510 /// and a remainder slice with length strictly less than `N`.
1511 ///
1512 /// # Panics
1513 ///
1514 /// Panics if `N` is zero. This check will most probably get changed to a compile time
1515 /// error before this method gets stabilized.
1516 ///
1517 /// # Examples
1518 ///
1519 /// ```
1520 /// #![feature(slice_as_chunks)]
1521 /// let v = &mut [0, 0, 0, 0, 0];
1522 /// let mut count = 1;
1523 ///
1524 /// let (remainder, chunks) = v.as_rchunks_mut();
1525 /// remainder[0] = 9;
1526 /// for chunk in chunks {
1527 /// *chunk = [count; 2];
1528 /// count += 1;
1529 /// }
1530 /// assert_eq!(v, &[9, 1, 1, 2, 2]);
1531 /// ```
1532 #[unstable(feature = "slice_as_chunks", issue = "74985")]
1533 #[rustc_const_unstable(feature = "slice_as_chunks", issue = "74985")]
1534 #[inline]
1535 #[track_caller]
1536 #[must_use]
1537 pub const fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]]) {
1538 assert!(N != 0, "chunk size must be non-zero");
1539 let len = self.len() / N;
1540 let (remainder, multiple_of_n) = self.split_at_mut(self.len() - len * N);
1541 // SAFETY: We already panicked for zero, and ensured by construction
1542 // that the length of the subslice is a multiple of N.
1543 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };
1544 (remainder, array_slice)
1545 }
1546
1547 /// Returns an iterator over `N` elements of the slice at a time, starting at the
1548 /// beginning of the slice.
1549 ///
1550 /// The chunks are mutable array references and do not overlap. If `N` does not divide
1551 /// the length of the slice, then the last up to `N-1` elements will be omitted and
1552 /// can be retrieved from the `into_remainder` function of the iterator.
1553 ///
1554 /// This method is the const generic equivalent of [`chunks_exact_mut`].
1555 ///
1556 /// # Panics
1557 ///
1558 /// Panics if `N` is zero. This check will most probably get changed to a compile time
1559 /// error before this method gets stabilized.
1560 ///
1561 /// # Examples
1562 ///
1563 /// ```
1564 /// #![feature(array_chunks)]
1565 /// let v = &mut [0, 0, 0, 0, 0];
1566 /// let mut count = 1;
1567 ///
1568 /// for chunk in v.array_chunks_mut() {
1569 /// *chunk = [count; 2];
1570 /// count += 1;
1571 /// }
1572 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
1573 /// ```
1574 ///
1575 /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1576 #[unstable(feature = "array_chunks", issue = "74985")]
1577 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1578 #[inline]
1579 #[track_caller]
1580 pub const fn array_chunks_mut<const N: usize>(&mut self) -> ArrayChunksMut<'_, T, N> {
1581 assert!(N != 0, "chunk size must be non-zero");
1582 ArrayChunksMut::new(self)
1583 }
1584
1585 /// Returns an iterator over overlapping windows of `N` elements of a slice,
1586 /// starting at the beginning of the slice.
1587 ///
1588 /// This is the const generic equivalent of [`windows`].
1589 ///
1590 /// If `N` is greater than the size of the slice, it will return no windows.
1591 ///
1592 /// # Panics
1593 ///
1594 /// Panics if `N` is zero. This check will most probably get changed to a compile time
1595 /// error before this method gets stabilized.
1596 ///
1597 /// # Examples
1598 ///
1599 /// ```
1600 /// #![feature(array_windows)]
1601 /// let slice = [0, 1, 2, 3];
1602 /// let mut iter = slice.array_windows();
1603 /// assert_eq!(iter.next().unwrap(), &[0, 1]);
1604 /// assert_eq!(iter.next().unwrap(), &[1, 2]);
1605 /// assert_eq!(iter.next().unwrap(), &[2, 3]);
1606 /// assert!(iter.next().is_none());
1607 /// ```
1608 ///
1609 /// [`windows`]: slice::windows
1610 #[unstable(feature = "array_windows", issue = "75027")]
1611 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1612 #[inline]
1613 #[track_caller]
1614 pub const fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N> {
1615 assert!(N != 0, "window size must be non-zero");
1616 ArrayWindows::new(self)
1617 }
1618
1619 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1620 /// of the slice.
1621 ///
1622 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1623 /// slice, then the last chunk will not have length `chunk_size`.
1624 ///
1625 /// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always exactly
1626 /// `chunk_size` elements, and [`chunks`] for the same iterator but starting at the beginning
1627 /// of the slice.
1628 ///
1629 /// # Panics
1630 ///
1631 /// Panics if `chunk_size` is zero.
1632 ///
1633 /// # Examples
1634 ///
1635 /// ```
1636 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1637 /// let mut iter = slice.rchunks(2);
1638 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1639 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1640 /// assert_eq!(iter.next().unwrap(), &['l']);
1641 /// assert!(iter.next().is_none());
1642 /// ```
1643 ///
1644 /// [`rchunks_exact`]: slice::rchunks_exact
1645 /// [`chunks`]: slice::chunks
1646 #[stable(feature = "rchunks", since = "1.31.0")]
1647 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1648 #[inline]
1649 #[track_caller]
1650 pub const fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> {
1651 assert!(chunk_size != 0, "chunk size must be non-zero");
1652 RChunks::new(self, chunk_size)
1653 }
1654
1655 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1656 /// of the slice.
1657 ///
1658 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1659 /// length of the slice, then the last chunk will not have length `chunk_size`.
1660 ///
1661 /// See [`rchunks_exact_mut`] for a variant of this iterator that returns chunks of always
1662 /// exactly `chunk_size` elements, and [`chunks_mut`] for the same iterator but starting at the
1663 /// beginning of the slice.
1664 ///
1665 /// # Panics
1666 ///
1667 /// Panics if `chunk_size` is zero.
1668 ///
1669 /// # Examples
1670 ///
1671 /// ```
1672 /// let v = &mut [0, 0, 0, 0, 0];
1673 /// let mut count = 1;
1674 ///
1675 /// for chunk in v.rchunks_mut(2) {
1676 /// for elem in chunk.iter_mut() {
1677 /// *elem += count;
1678 /// }
1679 /// count += 1;
1680 /// }
1681 /// assert_eq!(v, &[3, 2, 2, 1, 1]);
1682 /// ```
1683 ///
1684 /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
1685 /// [`chunks_mut`]: slice::chunks_mut
1686 #[stable(feature = "rchunks", since = "1.31.0")]
1687 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1688 #[inline]
1689 #[track_caller]
1690 pub const fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> {
1691 assert!(chunk_size != 0, "chunk size must be non-zero");
1692 RChunksMut::new(self, chunk_size)
1693 }
1694
1695 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
1696 /// end of the slice.
1697 ///
1698 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1699 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
1700 /// from the `remainder` function of the iterator.
1701 ///
1702 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1703 /// resulting code better than in the case of [`rchunks`].
1704 ///
1705 /// See [`rchunks`] for a variant of this iterator that also returns the remainder as a smaller
1706 /// chunk, and [`chunks_exact`] for the same iterator but starting at the beginning of the
1707 /// slice.
1708 ///
1709 /// # Panics
1710 ///
1711 /// Panics if `chunk_size` is zero.
1712 ///
1713 /// # Examples
1714 ///
1715 /// ```
1716 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1717 /// let mut iter = slice.rchunks_exact(2);
1718 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1719 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1720 /// assert!(iter.next().is_none());
1721 /// assert_eq!(iter.remainder(), &['l']);
1722 /// ```
1723 ///
1724 /// [`chunks`]: slice::chunks
1725 /// [`rchunks`]: slice::rchunks
1726 /// [`chunks_exact`]: slice::chunks_exact
1727 #[stable(feature = "rchunks", since = "1.31.0")]
1728 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1729 #[inline]
1730 #[track_caller]
1731 pub const fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> {
1732 assert!(chunk_size != 0, "chunk size must be non-zero");
1733 RChunksExact::new(self, chunk_size)
1734 }
1735
1736 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1737 /// of the slice.
1738 ///
1739 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1740 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
1741 /// retrieved from the `into_remainder` function of the iterator.
1742 ///
1743 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1744 /// resulting code better than in the case of [`chunks_mut`].
1745 ///
1746 /// See [`rchunks_mut`] for a variant of this iterator that also returns the remainder as a
1747 /// smaller chunk, and [`chunks_exact_mut`] for the same iterator but starting at the beginning
1748 /// of the slice.
1749 ///
1750 /// # Panics
1751 ///
1752 /// Panics if `chunk_size` is zero.
1753 ///
1754 /// # Examples
1755 ///
1756 /// ```
1757 /// let v = &mut [0, 0, 0, 0, 0];
1758 /// let mut count = 1;
1759 ///
1760 /// for chunk in v.rchunks_exact_mut(2) {
1761 /// for elem in chunk.iter_mut() {
1762 /// *elem += count;
1763 /// }
1764 /// count += 1;
1765 /// }
1766 /// assert_eq!(v, &[0, 2, 2, 1, 1]);
1767 /// ```
1768 ///
1769 /// [`chunks_mut`]: slice::chunks_mut
1770 /// [`rchunks_mut`]: slice::rchunks_mut
1771 /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1772 #[stable(feature = "rchunks", since = "1.31.0")]
1773 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1774 #[inline]
1775 #[track_caller]
1776 pub const fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> {
1777 assert!(chunk_size != 0, "chunk size must be non-zero");
1778 RChunksExactMut::new(self, chunk_size)
1779 }
1780
1781 /// Returns an iterator over the slice producing non-overlapping runs
1782 /// of elements using the predicate to separate them.
1783 ///
1784 /// The predicate is called for every pair of consecutive elements,
1785 /// meaning that it is called on `slice[0]` and `slice[1]`,
1786 /// followed by `slice[1]` and `slice[2]`, and so on.
1787 ///
1788 /// # Examples
1789 ///
1790 /// ```
1791 /// let slice = &[1, 1, 1, 3, 3, 2, 2, 2];
1792 ///
1793 /// let mut iter = slice.chunk_by(|a, b| a == b);
1794 ///
1795 /// assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
1796 /// assert_eq!(iter.next(), Some(&[3, 3][..]));
1797 /// assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
1798 /// assert_eq!(iter.next(), None);
1799 /// ```
1800 ///
1801 /// This method can be used to extract the sorted subslices:
1802 ///
1803 /// ```
1804 /// let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];
1805 ///
1806 /// let mut iter = slice.chunk_by(|a, b| a <= b);
1807 ///
1808 /// assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));
1809 /// assert_eq!(iter.next(), Some(&[2, 3][..]));
1810 /// assert_eq!(iter.next(), Some(&[2, 3, 4][..]));
1811 /// assert_eq!(iter.next(), None);
1812 /// ```
1813 #[stable(feature = "slice_group_by", since = "1.77.0")]
1814 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1815 #[inline]
1816 pub const fn chunk_by<F>(&self, pred: F) -> ChunkBy<'_, T, F>
1817 where
1818 F: FnMut(&T, &T) -> bool,
1819 {
1820 ChunkBy::new(self, pred)
1821 }
1822
1823 /// Returns an iterator over the slice producing non-overlapping mutable
1824 /// runs of elements using the predicate to separate them.
1825 ///
1826 /// The predicate is called for every pair of consecutive elements,
1827 /// meaning that it is called on `slice[0]` and `slice[1]`,
1828 /// followed by `slice[1]` and `slice[2]`, and so on.
1829 ///
1830 /// # Examples
1831 ///
1832 /// ```
1833 /// let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2];
1834 ///
1835 /// let mut iter = slice.chunk_by_mut(|a, b| a == b);
1836 ///
1837 /// assert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));
1838 /// assert_eq!(iter.next(), Some(&mut [3, 3][..]));
1839 /// assert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));
1840 /// assert_eq!(iter.next(), None);
1841 /// ```
1842 ///
1843 /// This method can be used to extract the sorted subslices:
1844 ///
1845 /// ```
1846 /// let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4];
1847 ///
1848 /// let mut iter = slice.chunk_by_mut(|a, b| a <= b);
1849 ///
1850 /// assert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..]));
1851 /// assert_eq!(iter.next(), Some(&mut [2, 3][..]));
1852 /// assert_eq!(iter.next(), Some(&mut [2, 3, 4][..]));
1853 /// assert_eq!(iter.next(), None);
1854 /// ```
1855 #[stable(feature = "slice_group_by", since = "1.77.0")]
1856 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1857 #[inline]
1858 pub const fn chunk_by_mut<F>(&mut self, pred: F) -> ChunkByMut<'_, T, F>
1859 where
1860 F: FnMut(&T, &T) -> bool,
1861 {
1862 ChunkByMut::new(self, pred)
1863 }
1864
1865 /// Divides one slice into two at an index.
1866 ///
1867 /// The first will contain all indices from `[0, mid)` (excluding
1868 /// the index `mid` itself) and the second will contain all
1869 /// indices from `[mid, len)` (excluding the index `len` itself).
1870 ///
1871 /// # Panics
1872 ///
1873 /// Panics if `mid > len`. For a non-panicking alternative see
1874 /// [`split_at_checked`](slice::split_at_checked).
1875 ///
1876 /// # Examples
1877 ///
1878 /// ```
1879 /// let v = ['a', 'b', 'c'];
1880 ///
1881 /// {
1882 /// let (left, right) = v.split_at(0);
1883 /// assert_eq!(left, []);
1884 /// assert_eq!(right, ['a', 'b', 'c']);
1885 /// }
1886 ///
1887 /// {
1888 /// let (left, right) = v.split_at(2);
1889 /// assert_eq!(left, ['a', 'b']);
1890 /// assert_eq!(right, ['c']);
1891 /// }
1892 ///
1893 /// {
1894 /// let (left, right) = v.split_at(3);
1895 /// assert_eq!(left, ['a', 'b', 'c']);
1896 /// assert_eq!(right, []);
1897 /// }
1898 /// ```
1899 #[stable(feature = "rust1", since = "1.0.0")]
1900 #[rustc_const_stable(feature = "const_slice_split_at_not_mut", since = "1.71.0")]
1901 #[inline]
1902 #[track_caller]
1903 #[must_use]
1904 pub const fn split_at(&self, mid: usize) -> (&[T], &[T]) {
1905 match self.split_at_checked(mid) {
1906 Some(pair) => pair,
1907 None => panic!("mid > len"),
1908 }
1909 }
1910
1911 /// Divides one mutable slice into two at an index.
1912 ///
1913 /// The first will contain all indices from `[0, mid)` (excluding
1914 /// the index `mid` itself) and the second will contain all
1915 /// indices from `[mid, len)` (excluding the index `len` itself).
1916 ///
1917 /// # Panics
1918 ///
1919 /// Panics if `mid > len`. For a non-panicking alternative see
1920 /// [`split_at_mut_checked`](slice::split_at_mut_checked).
1921 ///
1922 /// # Examples
1923 ///
1924 /// ```
1925 /// let mut v = [1, 0, 3, 0, 5, 6];
1926 /// let (left, right) = v.split_at_mut(2);
1927 /// assert_eq!(left, [1, 0]);
1928 /// assert_eq!(right, [3, 0, 5, 6]);
1929 /// left[1] = 2;
1930 /// right[1] = 4;
1931 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1932 /// ```
1933 #[stable(feature = "rust1", since = "1.0.0")]
1934 #[inline]
1935 #[track_caller]
1936 #[must_use]
1937 #[rustc_const_stable(feature = "const_slice_split_at_mut", since = "1.83.0")]
1938 pub const fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1939 match self.split_at_mut_checked(mid) {
1940 Some(pair) => pair,
1941 None => panic!("mid > len"),
1942 }
1943 }
1944
1945 /// Divides one slice into two at an index, without doing bounds checking.
1946 ///
1947 /// The first will contain all indices from `[0, mid)` (excluding
1948 /// the index `mid` itself) and the second will contain all
1949 /// indices from `[mid, len)` (excluding the index `len` itself).
1950 ///
1951 /// For a safe alternative see [`split_at`].
1952 ///
1953 /// # Safety
1954 ///
1955 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
1956 /// even if the resulting reference is not used. The caller has to ensure that
1957 /// `0 <= mid <= self.len()`.
1958 ///
1959 /// [`split_at`]: slice::split_at
1960 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1961 ///
1962 /// # Examples
1963 ///
1964 /// ```
1965 /// let v = ['a', 'b', 'c'];
1966 ///
1967 /// unsafe {
1968 /// let (left, right) = v.split_at_unchecked(0);
1969 /// assert_eq!(left, []);
1970 /// assert_eq!(right, ['a', 'b', 'c']);
1971 /// }
1972 ///
1973 /// unsafe {
1974 /// let (left, right) = v.split_at_unchecked(2);
1975 /// assert_eq!(left, ['a', 'b']);
1976 /// assert_eq!(right, ['c']);
1977 /// }
1978 ///
1979 /// unsafe {
1980 /// let (left, right) = v.split_at_unchecked(3);
1981 /// assert_eq!(left, ['a', 'b', 'c']);
1982 /// assert_eq!(right, []);
1983 /// }
1984 /// ```
1985 #[stable(feature = "slice_split_at_unchecked", since = "1.79.0")]
1986 #[rustc_const_stable(feature = "const_slice_split_at_unchecked", since = "1.77.0")]
1987 #[inline]
1988 #[must_use]
1989 pub const unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T]) {
1990 // FIXME(const-hack): the const function `from_raw_parts` is used to make this
1991 // function const; previously the implementation used
1992 // `(self.get_unchecked(..mid), self.get_unchecked(mid..))`
1993
1994 let len = self.len();
1995 let ptr = self.as_ptr();
1996
1997 assert_unsafe_precondition!(
1998 check_library_ub,
1999 "slice::split_at_unchecked requires the index to be within the slice",
2000 (mid: usize = mid, len: usize = len) => mid <= len,
2001 );
2002
2003 // SAFETY: Caller has to check that `0 <= mid <= self.len()`
2004 unsafe { (from_raw_parts(ptr, mid), from_raw_parts(ptr.add(mid), unchecked_sub(len, mid))) }
2005 }
2006
2007 /// Divides one mutable slice into two at an index, without doing bounds checking.
2008 ///
2009 /// The first will contain all indices from `[0, mid)` (excluding
2010 /// the index `mid` itself) and the second will contain all
2011 /// indices from `[mid, len)` (excluding the index `len` itself).
2012 ///
2013 /// For a safe alternative see [`split_at_mut`].
2014 ///
2015 /// # Safety
2016 ///
2017 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
2018 /// even if the resulting reference is not used. The caller has to ensure that
2019 /// `0 <= mid <= self.len()`.
2020 ///
2021 /// [`split_at_mut`]: slice::split_at_mut
2022 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2023 ///
2024 /// # Examples
2025 ///
2026 /// ```
2027 /// let mut v = [1, 0, 3, 0, 5, 6];
2028 /// // scoped to restrict the lifetime of the borrows
2029 /// unsafe {
2030 /// let (left, right) = v.split_at_mut_unchecked(2);
2031 /// assert_eq!(left, [1, 0]);
2032 /// assert_eq!(right, [3, 0, 5, 6]);
2033 /// left[1] = 2;
2034 /// right[1] = 4;
2035 /// }
2036 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
2037 /// ```
2038 #[stable(feature = "slice_split_at_unchecked", since = "1.79.0")]
2039 #[rustc_const_stable(feature = "const_slice_split_at_mut", since = "1.83.0")]
2040 #[inline]
2041 #[must_use]
2042 pub const unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
2043 let len = self.len();
2044 let ptr = self.as_mut_ptr();
2045
2046 assert_unsafe_precondition!(
2047 check_library_ub,
2048 "slice::split_at_mut_unchecked requires the index to be within the slice",
2049 (mid: usize = mid, len: usize = len) => mid <= len,
2050 );
2051
2052 // SAFETY: Caller has to check that `0 <= mid <= self.len()`.
2053 //
2054 // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference
2055 // is fine.
2056 unsafe {
2057 (
2058 from_raw_parts_mut(ptr, mid),
2059 from_raw_parts_mut(ptr.add(mid), unchecked_sub(len, mid)),
2060 )
2061 }
2062 }
2063
2064 /// Divides one slice into two at an index, returning `None` if the slice is
2065 /// too short.
2066 ///
2067 /// If `mid ≤ len` returns a pair of slices where the first will contain all
2068 /// indices from `[0, mid)` (excluding the index `mid` itself) and the
2069 /// second will contain all indices from `[mid, len)` (excluding the index
2070 /// `len` itself).
2071 ///
2072 /// Otherwise, if `mid > len`, returns `None`.
2073 ///
2074 /// # Examples
2075 ///
2076 /// ```
2077 /// let v = [1, -2, 3, -4, 5, -6];
2078 ///
2079 /// {
2080 /// let (left, right) = v.split_at_checked(0).unwrap();
2081 /// assert_eq!(left, []);
2082 /// assert_eq!(right, [1, -2, 3, -4, 5, -6]);
2083 /// }
2084 ///
2085 /// {
2086 /// let (left, right) = v.split_at_checked(2).unwrap();
2087 /// assert_eq!(left, [1, -2]);
2088 /// assert_eq!(right, [3, -4, 5, -6]);
2089 /// }
2090 ///
2091 /// {
2092 /// let (left, right) = v.split_at_checked(6).unwrap();
2093 /// assert_eq!(left, [1, -2, 3, -4, 5, -6]);
2094 /// assert_eq!(right, []);
2095 /// }
2096 ///
2097 /// assert_eq!(None, v.split_at_checked(7));
2098 /// ```
2099 #[stable(feature = "split_at_checked", since = "1.80.0")]
2100 #[rustc_const_stable(feature = "split_at_checked", since = "1.80.0")]
2101 #[inline]
2102 #[must_use]
2103 pub const fn split_at_checked(&self, mid: usize) -> Option<(&[T], &[T])> {
2104 if mid <= self.len() {
2105 // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which
2106 // fulfills the requirements of `split_at_unchecked`.
2107 Some(unsafe { self.split_at_unchecked(mid) })
2108 } else {
2109 None
2110 }
2111 }
2112
2113 /// Divides one mutable slice into two at an index, returning `None` if the
2114 /// slice is too short.
2115 ///
2116 /// If `mid ≤ len` returns a pair of slices where the first will contain all
2117 /// indices from `[0, mid)` (excluding the index `mid` itself) and the
2118 /// second will contain all indices from `[mid, len)` (excluding the index
2119 /// `len` itself).
2120 ///
2121 /// Otherwise, if `mid > len`, returns `None`.
2122 ///
2123 /// # Examples
2124 ///
2125 /// ```
2126 /// let mut v = [1, 0, 3, 0, 5, 6];
2127 ///
2128 /// if let Some((left, right)) = v.split_at_mut_checked(2) {
2129 /// assert_eq!(left, [1, 0]);
2130 /// assert_eq!(right, [3, 0, 5, 6]);
2131 /// left[1] = 2;
2132 /// right[1] = 4;
2133 /// }
2134 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
2135 ///
2136 /// assert_eq!(None, v.split_at_mut_checked(7));
2137 /// ```
2138 #[stable(feature = "split_at_checked", since = "1.80.0")]
2139 #[rustc_const_stable(feature = "const_slice_split_at_mut", since = "1.83.0")]
2140 #[inline]
2141 #[must_use]
2142 pub const fn split_at_mut_checked(&mut self, mid: usize) -> Option<(&mut [T], &mut [T])> {
2143 if mid <= self.len() {
2144 // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which
2145 // fulfills the requirements of `split_at_unchecked`.
2146 Some(unsafe { self.split_at_mut_unchecked(mid) })
2147 } else {
2148 None
2149 }
2150 }
2151
2152 /// Returns an iterator over subslices separated by elements that match
2153 /// `pred`. The matched element is not contained in the subslices.
2154 ///
2155 /// # Examples
2156 ///
2157 /// ```
2158 /// let slice = [10, 40, 33, 20];
2159 /// let mut iter = slice.split(|num| num % 3 == 0);
2160 ///
2161 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
2162 /// assert_eq!(iter.next().unwrap(), &[20]);
2163 /// assert!(iter.next().is_none());
2164 /// ```
2165 ///
2166 /// If the first element is matched, an empty slice will be the first item
2167 /// returned by the iterator. Similarly, if the last element in the slice
2168 /// is matched, an empty slice will be the last item returned by the
2169 /// iterator:
2170 ///
2171 /// ```
2172 /// let slice = [10, 40, 33];
2173 /// let mut iter = slice.split(|num| num % 3 == 0);
2174 ///
2175 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
2176 /// assert_eq!(iter.next().unwrap(), &[]);
2177 /// assert!(iter.next().is_none());
2178 /// ```
2179 ///
2180 /// If two matched elements are directly adjacent, an empty slice will be
2181 /// present between them:
2182 ///
2183 /// ```
2184 /// let slice = [10, 6, 33, 20];
2185 /// let mut iter = slice.split(|num| num % 3 == 0);
2186 ///
2187 /// assert_eq!(iter.next().unwrap(), &[10]);
2188 /// assert_eq!(iter.next().unwrap(), &[]);
2189 /// assert_eq!(iter.next().unwrap(), &[20]);
2190 /// assert!(iter.next().is_none());
2191 /// ```
2192 #[stable(feature = "rust1", since = "1.0.0")]
2193 #[inline]
2194 pub fn split<F>(&self, pred: F) -> Split<'_, T, F>
2195 where
2196 F: FnMut(&T) -> bool,
2197 {
2198 Split::new(self, pred)
2199 }
2200
2201 /// Returns an iterator over mutable subslices separated by elements that
2202 /// match `pred`. The matched element is not contained in the subslices.
2203 ///
2204 /// # Examples
2205 ///
2206 /// ```
2207 /// let mut v = [10, 40, 30, 20, 60, 50];
2208 ///
2209 /// for group in v.split_mut(|num| *num % 3 == 0) {
2210 /// group[0] = 1;
2211 /// }
2212 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
2213 /// ```
2214 #[stable(feature = "rust1", since = "1.0.0")]
2215 #[inline]
2216 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>
2217 where
2218 F: FnMut(&T) -> bool,
2219 {
2220 SplitMut::new(self, pred)
2221 }
2222
2223 /// Returns an iterator over subslices separated by elements that match
2224 /// `pred`. The matched element is contained in the end of the previous
2225 /// subslice as a terminator.
2226 ///
2227 /// # Examples
2228 ///
2229 /// ```
2230 /// let slice = [10, 40, 33, 20];
2231 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
2232 ///
2233 /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
2234 /// assert_eq!(iter.next().unwrap(), &[20]);
2235 /// assert!(iter.next().is_none());
2236 /// ```
2237 ///
2238 /// If the last element of the slice is matched,
2239 /// that element will be considered the terminator of the preceding slice.
2240 /// That slice will be the last item returned by the iterator.
2241 ///
2242 /// ```
2243 /// let slice = [3, 10, 40, 33];
2244 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
2245 ///
2246 /// assert_eq!(iter.next().unwrap(), &[3]);
2247 /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
2248 /// assert!(iter.next().is_none());
2249 /// ```
2250 #[stable(feature = "split_inclusive", since = "1.51.0")]
2251 #[inline]
2252 pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>
2253 where
2254 F: FnMut(&T) -> bool,
2255 {
2256 SplitInclusive::new(self, pred)
2257 }
2258
2259 /// Returns an iterator over mutable subslices separated by elements that
2260 /// match `pred`. The matched element is contained in the previous
2261 /// subslice as a terminator.
2262 ///
2263 /// # Examples
2264 ///
2265 /// ```
2266 /// let mut v = [10, 40, 30, 20, 60, 50];
2267 ///
2268 /// for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
2269 /// let terminator_idx = group.len()-1;
2270 /// group[terminator_idx] = 1;
2271 /// }
2272 /// assert_eq!(v, [10, 40, 1, 20, 1, 1]);
2273 /// ```
2274 #[stable(feature = "split_inclusive", since = "1.51.0")]
2275 #[inline]
2276 pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>
2277 where
2278 F: FnMut(&T) -> bool,
2279 {
2280 SplitInclusiveMut::new(self, pred)
2281 }
2282
2283 /// Returns an iterator over subslices separated by elements that match
2284 /// `pred`, starting at the end of the slice and working backwards.
2285 /// The matched element is not contained in the subslices.
2286 ///
2287 /// # Examples
2288 ///
2289 /// ```
2290 /// let slice = [11, 22, 33, 0, 44, 55];
2291 /// let mut iter = slice.rsplit(|num| *num == 0);
2292 ///
2293 /// assert_eq!(iter.next().unwrap(), &[44, 55]);
2294 /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
2295 /// assert_eq!(iter.next(), None);
2296 /// ```
2297 ///
2298 /// As with `split()`, if the first or last element is matched, an empty
2299 /// slice will be the first (or last) item returned by the iterator.
2300 ///
2301 /// ```
2302 /// let v = &[0, 1, 1, 2, 3, 5, 8];
2303 /// let mut it = v.rsplit(|n| *n % 2 == 0);
2304 /// assert_eq!(it.next().unwrap(), &[]);
2305 /// assert_eq!(it.next().unwrap(), &[3, 5]);
2306 /// assert_eq!(it.next().unwrap(), &[1, 1]);
2307 /// assert_eq!(it.next().unwrap(), &[]);
2308 /// assert_eq!(it.next(), None);
2309 /// ```
2310 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2311 #[inline]
2312 pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>
2313 where
2314 F: FnMut(&T) -> bool,
2315 {
2316 RSplit::new(self, pred)
2317 }
2318
2319 /// Returns an iterator over mutable subslices separated by elements that
2320 /// match `pred`, starting at the end of the slice and working
2321 /// backwards. The matched element is not contained in the subslices.
2322 ///
2323 /// # Examples
2324 ///
2325 /// ```
2326 /// let mut v = [100, 400, 300, 200, 600, 500];
2327 ///
2328 /// let mut count = 0;
2329 /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
2330 /// count += 1;
2331 /// group[0] = count;
2332 /// }
2333 /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
2334 /// ```
2335 ///
2336 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2337 #[inline]
2338 pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>
2339 where
2340 F: FnMut(&T) -> bool,
2341 {
2342 RSplitMut::new(self, pred)
2343 }
2344
2345 /// Returns an iterator over subslices separated by elements that match
2346 /// `pred`, limited to returning at most `n` items. The matched element is
2347 /// not contained in the subslices.
2348 ///
2349 /// The last element returned, if any, will contain the remainder of the
2350 /// slice.
2351 ///
2352 /// # Examples
2353 ///
2354 /// Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`,
2355 /// `[20, 60, 50]`):
2356 ///
2357 /// ```
2358 /// let v = [10, 40, 30, 20, 60, 50];
2359 ///
2360 /// for group in v.splitn(2, |num| *num % 3 == 0) {
2361 /// println!("{group:?}");
2362 /// }
2363 /// ```
2364 #[stable(feature = "rust1", since = "1.0.0")]
2365 #[inline]
2366 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>
2367 where
2368 F: FnMut(&T) -> bool,
2369 {
2370 SplitN::new(self.split(pred), n)
2371 }
2372
2373 /// Returns an iterator over mutable subslices separated by elements that match
2374 /// `pred`, limited to returning at most `n` items. The matched element is
2375 /// not contained in the subslices.
2376 ///
2377 /// The last element returned, if any, will contain the remainder of the
2378 /// slice.
2379 ///
2380 /// # Examples
2381 ///
2382 /// ```
2383 /// let mut v = [10, 40, 30, 20, 60, 50];
2384 ///
2385 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
2386 /// group[0] = 1;
2387 /// }
2388 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
2389 /// ```
2390 #[stable(feature = "rust1", since = "1.0.0")]
2391 #[inline]
2392 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>
2393 where
2394 F: FnMut(&T) -> bool,
2395 {
2396 SplitNMut::new(self.split_mut(pred), n)
2397 }
2398
2399 /// Returns an iterator over subslices separated by elements that match
2400 /// `pred` limited to returning at most `n` items. This starts at the end of
2401 /// the slice and works backwards. The matched element is not contained in
2402 /// the subslices.
2403 ///
2404 /// The last element returned, if any, will contain the remainder of the
2405 /// slice.
2406 ///
2407 /// # Examples
2408 ///
2409 /// Print the slice split once, starting from the end, by numbers divisible
2410 /// by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):
2411 ///
2412 /// ```
2413 /// let v = [10, 40, 30, 20, 60, 50];
2414 ///
2415 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
2416 /// println!("{group:?}");
2417 /// }
2418 /// ```
2419 #[stable(feature = "rust1", since = "1.0.0")]
2420 #[inline]
2421 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>
2422 where
2423 F: FnMut(&T) -> bool,
2424 {
2425 RSplitN::new(self.rsplit(pred), n)
2426 }
2427
2428 /// Returns an iterator over subslices separated by elements that match
2429 /// `pred` limited to returning at most `n` items. This starts at the end of
2430 /// the slice and works backwards. The matched element is not contained in
2431 /// the subslices.
2432 ///
2433 /// The last element returned, if any, will contain the remainder of the
2434 /// slice.
2435 ///
2436 /// # Examples
2437 ///
2438 /// ```
2439 /// let mut s = [10, 40, 30, 20, 60, 50];
2440 ///
2441 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
2442 /// group[0] = 1;
2443 /// }
2444 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
2445 /// ```
2446 #[stable(feature = "rust1", since = "1.0.0")]
2447 #[inline]
2448 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>
2449 where
2450 F: FnMut(&T) -> bool,
2451 {
2452 RSplitNMut::new(self.rsplit_mut(pred), n)
2453 }
2454
2455 /// Splits the slice on the first element that matches the specified
2456 /// predicate.
2457 ///
2458 /// If any matching elements are present in the slice, returns the prefix
2459 /// before the match and suffix after. The matching element itself is not
2460 /// included. If no elements match, returns `None`.
2461 ///
2462 /// # Examples
2463 ///
2464 /// ```
2465 /// #![feature(slice_split_once)]
2466 /// let s = [1, 2, 3, 2, 4];
2467 /// assert_eq!(s.split_once(|&x| x == 2), Some((
2468 /// &[1][..],
2469 /// &[3, 2, 4][..]
2470 /// )));
2471 /// assert_eq!(s.split_once(|&x| x == 0), None);
2472 /// ```
2473 #[unstable(feature = "slice_split_once", reason = "newly added", issue = "112811")]
2474 #[inline]
2475 pub fn split_once<F>(&self, pred: F) -> Option<(&[T], &[T])>
2476 where
2477 F: FnMut(&T) -> bool,
2478 {
2479 let index = self.iter().position(pred)?;
2480 Some((&self[..index], &self[index + 1..]))
2481 }
2482
2483 /// Splits the slice on the last element that matches the specified
2484 /// predicate.
2485 ///
2486 /// If any matching elements are present in the slice, returns the prefix
2487 /// before the match and suffix after. The matching element itself is not
2488 /// included. If no elements match, returns `None`.
2489 ///
2490 /// # Examples
2491 ///
2492 /// ```
2493 /// #![feature(slice_split_once)]
2494 /// let s = [1, 2, 3, 2, 4];
2495 /// assert_eq!(s.rsplit_once(|&x| x == 2), Some((
2496 /// &[1, 2, 3][..],
2497 /// &[4][..]
2498 /// )));
2499 /// assert_eq!(s.rsplit_once(|&x| x == 0), None);
2500 /// ```
2501 #[unstable(feature = "slice_split_once", reason = "newly added", issue = "112811")]
2502 #[inline]
2503 pub fn rsplit_once<F>(&self, pred: F) -> Option<(&[T], &[T])>
2504 where
2505 F: FnMut(&T) -> bool,
2506 {
2507 let index = self.iter().rposition(pred)?;
2508 Some((&self[..index], &self[index + 1..]))
2509 }
2510
2511 /// Returns `true` if the slice contains an element with the given value.
2512 ///
2513 /// This operation is *O*(*n*).
2514 ///
2515 /// Note that if you have a sorted slice, [`binary_search`] may be faster.
2516 ///
2517 /// [`binary_search`]: slice::binary_search
2518 ///
2519 /// # Examples
2520 ///
2521 /// ```
2522 /// let v = [10, 40, 30];
2523 /// assert!(v.contains(&30));
2524 /// assert!(!v.contains(&50));
2525 /// ```
2526 ///
2527 /// If you do not have a `&T`, but some other value that you can compare
2528 /// with one (for example, `String` implements `PartialEq<str>`), you can
2529 /// use `iter().any`:
2530 ///
2531 /// ```
2532 /// let v = [String::from("hello"), String::from("world")]; // slice of `String`
2533 /// assert!(v.iter().any(|e| e == "hello")); // search with `&str`
2534 /// assert!(!v.iter().any(|e| e == "hi"));
2535 /// ```
2536 #[stable(feature = "rust1", since = "1.0.0")]
2537 #[inline]
2538 #[must_use]
2539 pub fn contains(&self, x: &T) -> bool
2540 where
2541 T: PartialEq,
2542 {
2543 cmp::SliceContains::slice_contains(x, self)
2544 }
2545
2546 /// Returns `true` if `needle` is a prefix of the slice or equal to the slice.
2547 ///
2548 /// # Examples
2549 ///
2550 /// ```
2551 /// let v = [10, 40, 30];
2552 /// assert!(v.starts_with(&[10]));
2553 /// assert!(v.starts_with(&[10, 40]));
2554 /// assert!(v.starts_with(&v));
2555 /// assert!(!v.starts_with(&[50]));
2556 /// assert!(!v.starts_with(&[10, 50]));
2557 /// ```
2558 ///
2559 /// Always returns `true` if `needle` is an empty slice:
2560 ///
2561 /// ```
2562 /// let v = &[10, 40, 30];
2563 /// assert!(v.starts_with(&[]));
2564 /// let v: &[u8] = &[];
2565 /// assert!(v.starts_with(&[]));
2566 /// ```
2567 #[stable(feature = "rust1", since = "1.0.0")]
2568 #[must_use]
2569 pub fn starts_with(&self, needle: &[T]) -> bool
2570 where
2571 T: PartialEq,
2572 {
2573 let n = needle.len();
2574 self.len() >= n && needle == &self[..n]
2575 }
2576
2577 /// Returns `true` if `needle` is a suffix of the slice or equal to the slice.
2578 ///
2579 /// # Examples
2580 ///
2581 /// ```
2582 /// let v = [10, 40, 30];
2583 /// assert!(v.ends_with(&[30]));
2584 /// assert!(v.ends_with(&[40, 30]));
2585 /// assert!(v.ends_with(&v));
2586 /// assert!(!v.ends_with(&[50]));
2587 /// assert!(!v.ends_with(&[50, 30]));
2588 /// ```
2589 ///
2590 /// Always returns `true` if `needle` is an empty slice:
2591 ///
2592 /// ```
2593 /// let v = &[10, 40, 30];
2594 /// assert!(v.ends_with(&[]));
2595 /// let v: &[u8] = &[];
2596 /// assert!(v.ends_with(&[]));
2597 /// ```
2598 #[stable(feature = "rust1", since = "1.0.0")]
2599 #[must_use]
2600 pub fn ends_with(&self, needle: &[T]) -> bool
2601 where
2602 T: PartialEq,
2603 {
2604 let (m, n) = (self.len(), needle.len());
2605 m >= n && needle == &self[m - n..]
2606 }
2607
2608 /// Returns a subslice with the prefix removed.
2609 ///
2610 /// If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`.
2611 /// If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the
2612 /// original slice, returns an empty slice.
2613 ///
2614 /// If the slice does not start with `prefix`, returns `None`.
2615 ///
2616 /// # Examples
2617 ///
2618 /// ```
2619 /// let v = &[10, 40, 30];
2620 /// assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
2621 /// assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
2622 /// assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..]));
2623 /// assert_eq!(v.strip_prefix(&[50]), None);
2624 /// assert_eq!(v.strip_prefix(&[10, 50]), None);
2625 ///
2626 /// let prefix : &str = "he";
2627 /// assert_eq!(b"hello".strip_prefix(prefix.as_bytes()),
2628 /// Some(b"llo".as_ref()));
2629 /// ```
2630 #[must_use = "returns the subslice without modifying the original"]
2631 #[stable(feature = "slice_strip", since = "1.51.0")]
2632 pub fn strip_prefix<P: SlicePattern<Item = T> + ?Sized>(&self, prefix: &P) -> Option<&[T]>
2633 where
2634 T: PartialEq,
2635 {
2636 // This function will need rewriting if and when SlicePattern becomes more sophisticated.
2637 let prefix = prefix.as_slice();
2638 let n = prefix.len();
2639 if n <= self.len() {
2640 let (head, tail) = self.split_at(n);
2641 if head == prefix {
2642 return Some(tail);
2643 }
2644 }
2645 None
2646 }
2647
2648 /// Returns a subslice with the suffix removed.
2649 ///
2650 /// If the slice ends with `suffix`, returns the subslice before the suffix, wrapped in `Some`.
2651 /// If `suffix` is empty, simply returns the original slice. If `suffix` is equal to the
2652 /// original slice, returns an empty slice.
2653 ///
2654 /// If the slice does not end with `suffix`, returns `None`.
2655 ///
2656 /// # Examples
2657 ///
2658 /// ```
2659 /// let v = &[10, 40, 30];
2660 /// assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
2661 /// assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
2662 /// assert_eq!(v.strip_suffix(&[10, 40, 30]), Some(&[][..]));
2663 /// assert_eq!(v.strip_suffix(&[50]), None);
2664 /// assert_eq!(v.strip_suffix(&[50, 30]), None);
2665 /// ```
2666 #[must_use = "returns the subslice without modifying the original"]
2667 #[stable(feature = "slice_strip", since = "1.51.0")]
2668 pub fn strip_suffix<P: SlicePattern<Item = T> + ?Sized>(&self, suffix: &P) -> Option<&[T]>
2669 where
2670 T: PartialEq,
2671 {
2672 // This function will need rewriting if and when SlicePattern becomes more sophisticated.
2673 let suffix = suffix.as_slice();
2674 let (len, n) = (self.len(), suffix.len());
2675 if n <= len {
2676 let (head, tail) = self.split_at(len - n);
2677 if tail == suffix {
2678 return Some(head);
2679 }
2680 }
2681 None
2682 }
2683
2684 /// Binary searches this slice for a given element.
2685 /// If the slice is not sorted, the returned result is unspecified and
2686 /// meaningless.
2687 ///
2688 /// If the value is found then [`Result::Ok`] is returned, containing the
2689 /// index of the matching element. If there are multiple matches, then any
2690 /// one of the matches could be returned. The index is chosen
2691 /// deterministically, but is subject to change in future versions of Rust.
2692 /// If the value is not found then [`Result::Err`] is returned, containing
2693 /// the index where a matching element could be inserted while maintaining
2694 /// sorted order.
2695 ///
2696 /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
2697 ///
2698 /// [`binary_search_by`]: slice::binary_search_by
2699 /// [`binary_search_by_key`]: slice::binary_search_by_key
2700 /// [`partition_point`]: slice::partition_point
2701 ///
2702 /// # Examples
2703 ///
2704 /// Looks up a series of four elements. The first is found, with a
2705 /// uniquely determined position; the second and third are not
2706 /// found; the fourth could match any position in `[1, 4]`.
2707 ///
2708 /// ```
2709 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2710 ///
2711 /// assert_eq!(s.binary_search(&13), Ok(9));
2712 /// assert_eq!(s.binary_search(&4), Err(7));
2713 /// assert_eq!(s.binary_search(&100), Err(13));
2714 /// let r = s.binary_search(&1);
2715 /// assert!(match r { Ok(1..=4) => true, _ => false, });
2716 /// ```
2717 ///
2718 /// If you want to find that whole *range* of matching items, rather than
2719 /// an arbitrary matching one, that can be done using [`partition_point`]:
2720 /// ```
2721 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2722 ///
2723 /// let low = s.partition_point(|x| x < &1);
2724 /// assert_eq!(low, 1);
2725 /// let high = s.partition_point(|x| x <= &1);
2726 /// assert_eq!(high, 5);
2727 /// let r = s.binary_search(&1);
2728 /// assert!((low..high).contains(&r.unwrap()));
2729 ///
2730 /// assert!(s[..low].iter().all(|&x| x < 1));
2731 /// assert!(s[low..high].iter().all(|&x| x == 1));
2732 /// assert!(s[high..].iter().all(|&x| x > 1));
2733 ///
2734 /// // For something not found, the "range" of equal items is empty
2735 /// assert_eq!(s.partition_point(|x| x < &11), 9);
2736 /// assert_eq!(s.partition_point(|x| x <= &11), 9);
2737 /// assert_eq!(s.binary_search(&11), Err(9));
2738 /// ```
2739 ///
2740 /// If you want to insert an item to a sorted vector, while maintaining
2741 /// sort order, consider using [`partition_point`]:
2742 ///
2743 /// ```
2744 /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2745 /// let num = 42;
2746 /// let idx = s.partition_point(|&x| x <= num);
2747 /// // If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to
2748 /// // `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` will allow `insert`
2749 /// // to shift less elements.
2750 /// s.insert(idx, num);
2751 /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2752 /// ```
2753 #[stable(feature = "rust1", since = "1.0.0")]
2754 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
2755 where
2756 T: Ord,
2757 {
2758 self.binary_search_by(|p| p.cmp(x))
2759 }
2760
2761 /// Binary searches this slice with a comparator function.
2762 ///
2763 /// The comparator function should return an order code that indicates
2764 /// whether its argument is `Less`, `Equal` or `Greater` the desired
2765 /// target.
2766 /// If the slice is not sorted or if the comparator function does not
2767 /// implement an order consistent with the sort order of the underlying
2768 /// slice, the returned result is unspecified and meaningless.
2769 ///
2770 /// If the value is found then [`Result::Ok`] is returned, containing the
2771 /// index of the matching element. If there are multiple matches, then any
2772 /// one of the matches could be returned. The index is chosen
2773 /// deterministically, but is subject to change in future versions of Rust.
2774 /// If the value is not found then [`Result::Err`] is returned, containing
2775 /// the index where a matching element could be inserted while maintaining
2776 /// sorted order.
2777 ///
2778 /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
2779 ///
2780 /// [`binary_search`]: slice::binary_search
2781 /// [`binary_search_by_key`]: slice::binary_search_by_key
2782 /// [`partition_point`]: slice::partition_point
2783 ///
2784 /// # Examples
2785 ///
2786 /// Looks up a series of four elements. The first is found, with a
2787 /// uniquely determined position; the second and third are not
2788 /// found; the fourth could match any position in `[1, 4]`.
2789 ///
2790 /// ```
2791 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2792 ///
2793 /// let seek = 13;
2794 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
2795 /// let seek = 4;
2796 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
2797 /// let seek = 100;
2798 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
2799 /// let seek = 1;
2800 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
2801 /// assert!(match r { Ok(1..=4) => true, _ => false, });
2802 /// ```
2803 #[stable(feature = "rust1", since = "1.0.0")]
2804 #[inline]
2805 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
2806 where
2807 F: FnMut(&'a T) -> Ordering,
2808 {
2809 let mut size = self.len();
2810 if size == 0 {
2811 return Err(0);
2812 }
2813 let mut base = 0usize;
2814
2815 // This loop intentionally doesn't have an early exit if the comparison
2816 // returns Equal. We want the number of loop iterations to depend *only*
2817 // on the size of the input slice so that the CPU can reliably predict
2818 // the loop count.
2819 while size > 1 {
2820 let half = size / 2;
2821 let mid = base + half;
2822
2823 // SAFETY: the call is made safe by the following inconstants:
2824 // - `mid >= 0`: by definition
2825 // - `mid < size`: `mid = size / 2 + size / 4 + size / 8 ...`
2826 let cmp = f(unsafe { self.get_unchecked(mid) });
2827
2828 // Binary search interacts poorly with branch prediction, so force
2829 // the compiler to use conditional moves if supported by the target
2830 // architecture.
2831 base = (cmp == Greater).select_unpredictable(base, mid);
2832
2833 // This is imprecise in the case where `size` is odd and the
2834 // comparison returns Greater: the mid element still gets included
2835 // by `size` even though it's known to be larger than the element
2836 // being searched for.
2837 //
2838 // This is fine though: we gain more performance by keeping the
2839 // loop iteration count invariant (and thus predictable) than we
2840 // lose from considering one additional element.
2841 size -= half;
2842 }
2843
2844 // SAFETY: base is always in [0, size) because base <= mid.
2845 let cmp = f(unsafe { self.get_unchecked(base) });
2846 if cmp == Equal {
2847 // SAFETY: same as the `get_unchecked` above.
2848 unsafe { hint::assert_unchecked(base < self.len()) };
2849 Ok(base)
2850 } else {
2851 let result = base + (cmp == Less) as usize;
2852 // SAFETY: same as the `get_unchecked` above.
2853 // Note that this is `<=`, unlike the assume in the `Ok` path.
2854 unsafe { hint::assert_unchecked(result <= self.len()) };
2855 Err(result)
2856 }
2857 }
2858
2859 /// Binary searches this slice with a key extraction function.
2860 ///
2861 /// Assumes that the slice is sorted by the key, for instance with
2862 /// [`sort_by_key`] using the same key extraction function.
2863 /// If the slice is not sorted by the key, the returned result is
2864 /// unspecified and meaningless.
2865 ///
2866 /// If the value is found then [`Result::Ok`] is returned, containing the
2867 /// index of the matching element. If there are multiple matches, then any
2868 /// one of the matches could be returned. The index is chosen
2869 /// deterministically, but is subject to change in future versions of Rust.
2870 /// If the value is not found then [`Result::Err`] is returned, containing
2871 /// the index where a matching element could be inserted while maintaining
2872 /// sorted order.
2873 ///
2874 /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
2875 ///
2876 /// [`sort_by_key`]: slice::sort_by_key
2877 /// [`binary_search`]: slice::binary_search
2878 /// [`binary_search_by`]: slice::binary_search_by
2879 /// [`partition_point`]: slice::partition_point
2880 ///
2881 /// # Examples
2882 ///
2883 /// Looks up a series of four elements in a slice of pairs sorted by
2884 /// their second elements. The first is found, with a uniquely
2885 /// determined position; the second and third are not found; the
2886 /// fourth could match any position in `[1, 4]`.
2887 ///
2888 /// ```
2889 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
2890 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
2891 /// (1, 21), (2, 34), (4, 55)];
2892 ///
2893 /// assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
2894 /// assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b), Err(7));
2895 /// assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
2896 /// let r = s.binary_search_by_key(&1, |&(a, b)| b);
2897 /// assert!(match r { Ok(1..=4) => true, _ => false, });
2898 /// ```
2899 // Lint rustdoc::broken_intra_doc_links is allowed as `slice::sort_by_key` is
2900 // in crate `alloc`, and as such doesn't exists yet when building `core`: #74481.
2901 // This breaks links when slice is displayed in core, but changing it to use relative links
2902 // would break when the item is re-exported. So allow the core links to be broken for now.
2903 #[allow(rustdoc::broken_intra_doc_links)]
2904 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
2905 #[inline]
2906 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
2907 where
2908 F: FnMut(&'a T) -> B,
2909 B: Ord,
2910 {
2911 self.binary_search_by(|k| f(k).cmp(b))
2912 }
2913
2914 /// Sorts the slice **without** preserving the initial order of equal elements.
2915 ///
2916 /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not
2917 /// allocate), and *O*(*n* \* log(*n*)) worst-case.
2918 ///
2919 /// If the implementation of [`Ord`] for `T` does not implement a [total order], the function
2920 /// may panic; even if the function exits normally, the resulting order of elements in the slice
2921 /// is unspecified. See also the note on panicking below.
2922 ///
2923 /// For example `|a, b| (a - b).cmp(a)` is a comparison function that is neither transitive nor
2924 /// reflexive nor total, `a < b < c < a` with `a = 1, b = 2, c = 3`. For more information and
2925 /// examples see the [`Ord`] documentation.
2926 ///
2927 ///
2928 /// All original elements will remain in the slice and any possible modifications via interior
2929 /// mutability are observed in the input. Same is true if the implementation of [`Ord`] for `T` panics.
2930 ///
2931 /// Sorting types that only implement [`PartialOrd`] such as [`f32`] and [`f64`] require
2932 /// additional precautions. For example, `f32::NAN != f32::NAN`, which doesn't fulfill the
2933 /// reflexivity requirement of [`Ord`]. By using an alternative comparison function with
2934 /// `slice::sort_unstable_by` such as [`f32::total_cmp`] or [`f64::total_cmp`] that defines a
2935 /// [total order] users can sort slices containing floating-point values. Alternatively, if all
2936 /// values in the slice are guaranteed to be in a subset for which [`PartialOrd::partial_cmp`]
2937 /// forms a [total order], it's possible to sort the slice with `sort_unstable_by(|a, b|
2938 /// a.partial_cmp(b).unwrap())`.
2939 ///
2940 /// # Current implementation
2941 ///
2942 /// The current implementation is based on [ipnsort] by Lukas Bergdoll and Orson Peters, which
2943 /// combines the fast average case of quicksort with the fast worst case of heapsort, achieving
2944 /// linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the
2945 /// expected time to sort the data is *O*(*n* \* log(*k*)).
2946 ///
2947 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
2948 /// slice is partially sorted.
2949 ///
2950 /// # Panics
2951 ///
2952 /// May panic if the implementation of [`Ord`] for `T` does not implement a [total order], or if
2953 /// the [`Ord`] implementation panics.
2954 ///
2955 /// # Examples
2956 ///
2957 /// ```
2958 /// let mut v = [4, -5, 1, -3, 2];
2959 ///
2960 /// v.sort_unstable();
2961 /// assert_eq!(v, [-5, -3, 1, 2, 4]);
2962 /// ```
2963 ///
2964 /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort
2965 /// [total order]: https://en.wikipedia.org/wiki/Total_order
2966 #[stable(feature = "sort_unstable", since = "1.20.0")]
2967 #[inline]
2968 pub fn sort_unstable(&mut self)
2969 where
2970 T: Ord,
2971 {
2972 sort::unstable::sort(self, &mut T::lt);
2973 }
2974
2975 /// Sorts the slice with a comparison function, **without** preserving the initial order of
2976 /// equal elements.
2977 ///
2978 /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not
2979 /// allocate), and *O*(*n* \* log(*n*)) worst-case.
2980 ///
2981 /// If the comparison function `compare` does not implement a [total order], the function
2982 /// may panic; even if the function exits normally, the resulting order of elements in the slice
2983 /// is unspecified. See also the note on panicking below.
2984 ///
2985 /// For example `|a, b| (a - b).cmp(a)` is a comparison function that is neither transitive nor
2986 /// reflexive nor total, `a < b < c < a` with `a = 1, b = 2, c = 3`. For more information and
2987 /// examples see the [`Ord`] documentation.
2988 ///
2989 /// All original elements will remain in the slice and any possible modifications via interior
2990 /// mutability are observed in the input. Same is true if `compare` panics.
2991 ///
2992 /// # Current implementation
2993 ///
2994 /// The current implementation is based on [ipnsort] by Lukas Bergdoll and Orson Peters, which
2995 /// combines the fast average case of quicksort with the fast worst case of heapsort, achieving
2996 /// linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the
2997 /// expected time to sort the data is *O*(*n* \* log(*k*)).
2998 ///
2999 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
3000 /// slice is partially sorted.
3001 ///
3002 /// # Panics
3003 ///
3004 /// May panic if the `compare` does not implement a [total order], or if
3005 /// the `compare` itself panics.
3006 ///
3007 /// # Examples
3008 ///
3009 /// ```
3010 /// let mut v = [4, -5, 1, -3, 2];
3011 /// v.sort_unstable_by(|a, b| a.cmp(b));
3012 /// assert_eq!(v, [-5, -3, 1, 2, 4]);
3013 ///
3014 /// // reverse sorting
3015 /// v.sort_unstable_by(|a, b| b.cmp(a));
3016 /// assert_eq!(v, [4, 2, 1, -3, -5]);
3017 /// ```
3018 ///
3019 /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort
3020 /// [total order]: https://en.wikipedia.org/wiki/Total_order
3021 #[stable(feature = "sort_unstable", since = "1.20.0")]
3022 #[inline]
3023 pub fn sort_unstable_by<F>(&mut self, mut compare: F)
3024 where
3025 F: FnMut(&T, &T) -> Ordering,
3026 {
3027 sort::unstable::sort(self, &mut |a, b| compare(a, b) == Ordering::Less);
3028 }
3029
3030 /// Sorts the slice with a key extraction function, **without** preserving the initial order of
3031 /// equal elements.
3032 ///
3033 /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not
3034 /// allocate), and *O*(*n* \* log(*n*)) worst-case.
3035 ///
3036 /// If the implementation of [`Ord`] for `K` does not implement a [total order], the function
3037 /// may panic; even if the function exits normally, the resulting order of elements in the slice
3038 /// is unspecified. See also the note on panicking below.
3039 ///
3040 /// For example `|a, b| (a - b).cmp(a)` is a comparison function that is neither transitive nor
3041 /// reflexive nor total, `a < b < c < a` with `a = 1, b = 2, c = 3`. For more information and
3042 /// examples see the [`Ord`] documentation.
3043 ///
3044 /// All original elements will remain in the slice and any possible modifications via interior
3045 /// mutability are observed in the input. Same is true if the implementation of [`Ord`] for `K` panics.
3046 ///
3047 /// # Current implementation
3048 ///
3049 /// The current implementation is based on [ipnsort] by Lukas Bergdoll and Orson Peters, which
3050 /// combines the fast average case of quicksort with the fast worst case of heapsort, achieving
3051 /// linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the
3052 /// expected time to sort the data is *O*(*n* \* log(*k*)).
3053 ///
3054 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
3055 /// slice is partially sorted.
3056 ///
3057 /// # Panics
3058 ///
3059 /// May panic if the implementation of [`Ord`] for `K` does not implement a [total order], or if
3060 /// the [`Ord`] implementation panics.
3061 ///
3062 /// # Examples
3063 ///
3064 /// ```
3065 /// let mut v = [4i32, -5, 1, -3, 2];
3066 ///
3067 /// v.sort_unstable_by_key(|k| k.abs());
3068 /// assert_eq!(v, [1, 2, -3, 4, -5]);
3069 /// ```
3070 ///
3071 /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort
3072 /// [total order]: https://en.wikipedia.org/wiki/Total_order
3073 #[stable(feature = "sort_unstable", since = "1.20.0")]
3074 #[inline]
3075 pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
3076 where
3077 F: FnMut(&T) -> K,
3078 K: Ord,
3079 {
3080 sort::unstable::sort(self, &mut |a, b| f(a).lt(&f(b)));
3081 }
3082
3083 /// Reorders the slice such that the element at `index` is at a sort-order position. All
3084 /// elements before `index` will be `<=` to this value, and all elements after will be `>=` to
3085 /// it.
3086 ///
3087 /// This reordering is unstable (i.e. any element that compares equal to the nth element may end
3088 /// up at that position), in-place (i.e. does not allocate), and runs in *O*(*n*) time. This
3089 /// function is also known as "kth element" in other libraries.
3090 ///
3091 /// Returns a triple that partitions the reordered slice:
3092 ///
3093 /// * The unsorted subslice before `index`, whose elements all satisfy `x <= self[index]`.
3094 ///
3095 /// * The element at `index`.
3096 ///
3097 /// * The unsorted subslice after `index`, whose elements all satisfy `x >= self[index]`.
3098 ///
3099 /// # Current implementation
3100 ///
3101 /// The current algorithm is an introselect implementation based on [ipnsort] by Lukas Bergdoll
3102 /// and Orson Peters, which is also the basis for [`sort_unstable`]. The fallback algorithm is
3103 /// Median of Medians using Tukey's Ninther for pivot selection, which guarantees linear runtime
3104 /// for all inputs.
3105 ///
3106 /// [`sort_unstable`]: slice::sort_unstable
3107 ///
3108 /// # Panics
3109 ///
3110 /// Panics when `index >= len()`, and so always panics on empty slices.
3111 ///
3112 /// May panic if the implementation of [`Ord`] for `T` does not implement a [total order].
3113 ///
3114 /// # Examples
3115 ///
3116 /// ```
3117 /// let mut v = [-5i32, 4, 2, -3, 1];
3118 ///
3119 /// // Find the items `<=` to the median, the median itself, and the items `>=` to it.
3120 /// let (lesser, median, greater) = v.select_nth_unstable(2);
3121 ///
3122 /// assert!(lesser == [-3, -5] || lesser == [-5, -3]);
3123 /// assert_eq!(median, &mut 1);
3124 /// assert!(greater == [4, 2] || greater == [2, 4]);
3125 ///
3126 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
3127 /// // about the specified index.
3128 /// assert!(v == [-3, -5, 1, 2, 4] ||
3129 /// v == [-5, -3, 1, 2, 4] ||
3130 /// v == [-3, -5, 1, 4, 2] ||
3131 /// v == [-5, -3, 1, 4, 2]);
3132 /// ```
3133 ///
3134 /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort
3135 /// [total order]: https://en.wikipedia.org/wiki/Total_order
3136 #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
3137 #[inline]
3138 pub fn select_nth_unstable(&mut self, index: usize) -> (&mut [T], &mut T, &mut [T])
3139 where
3140 T: Ord,
3141 {
3142 sort::select::partition_at_index(self, index, T::lt)
3143 }
3144
3145 /// Reorders the slice with a comparator function such that the element at `index` is at a
3146 /// sort-order position. All elements before `index` will be `<=` to this value, and all
3147 /// elements after will be `>=` to it, according to the comparator function.
3148 ///
3149 /// This reordering is unstable (i.e. any element that compares equal to the nth element may end
3150 /// up at that position), in-place (i.e. does not allocate), and runs in *O*(*n*) time. This
3151 /// function is also known as "kth element" in other libraries.
3152 ///
3153 /// Returns a triple partitioning the reordered slice:
3154 ///
3155 /// * The unsorted subslice before `index`, whose elements all satisfy
3156 /// `compare(x, self[index]).is_le()`.
3157 ///
3158 /// * The element at `index`.
3159 ///
3160 /// * The unsorted subslice after `index`, whose elements all satisfy
3161 /// `compare(x, self[index]).is_ge()`.
3162 ///
3163 /// # Current implementation
3164 ///
3165 /// The current algorithm is an introselect implementation based on [ipnsort] by Lukas Bergdoll
3166 /// and Orson Peters, which is also the basis for [`sort_unstable`]. The fallback algorithm is
3167 /// Median of Medians using Tukey's Ninther for pivot selection, which guarantees linear runtime
3168 /// for all inputs.
3169 ///
3170 /// [`sort_unstable`]: slice::sort_unstable
3171 ///
3172 /// # Panics
3173 ///
3174 /// Panics when `index >= len()`, and so always panics on empty slices.
3175 ///
3176 /// May panic if `compare` does not implement a [total order].
3177 ///
3178 /// # Examples
3179 ///
3180 /// ```
3181 /// let mut v = [-5i32, 4, 2, -3, 1];
3182 ///
3183 /// // Find the items `>=` to the median, the median itself, and the items `<=` to it, by using
3184 /// // a reversed comparator.
3185 /// let (before, median, after) = v.select_nth_unstable_by(2, |a, b| b.cmp(a));
3186 ///
3187 /// assert!(before == [4, 2] || before == [2, 4]);
3188 /// assert_eq!(median, &mut 1);
3189 /// assert!(after == [-3, -5] || after == [-5, -3]);
3190 ///
3191 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
3192 /// // about the specified index.
3193 /// assert!(v == [2, 4, 1, -5, -3] ||
3194 /// v == [2, 4, 1, -3, -5] ||
3195 /// v == [4, 2, 1, -5, -3] ||
3196 /// v == [4, 2, 1, -3, -5]);
3197 /// ```
3198 ///
3199 /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort
3200 /// [total order]: https://en.wikipedia.org/wiki/Total_order
3201 #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
3202 #[inline]
3203 pub fn select_nth_unstable_by<F>(
3204 &mut self,
3205 index: usize,
3206 mut compare: F,
3207 ) -> (&mut [T], &mut T, &mut [T])
3208 where
3209 F: FnMut(&T, &T) -> Ordering,
3210 {
3211 sort::select::partition_at_index(self, index, |a: &T, b: &T| compare(a, b) == Less)
3212 }
3213
3214 /// Reorders the slice with a key extraction function such that the element at `index` is at a
3215 /// sort-order position. All elements before `index` will have keys `<=` to the key at `index`,
3216 /// and all elements after will have keys `>=` to it.
3217 ///
3218 /// This reordering is unstable (i.e. any element that compares equal to the nth element may end
3219 /// up at that position), in-place (i.e. does not allocate), and runs in *O*(*n*) time. This
3220 /// function is also known as "kth element" in other libraries.
3221 ///
3222 /// Returns a triple partitioning the reordered slice:
3223 ///
3224 /// * The unsorted subslice before `index`, whose elements all satisfy `f(x) <= f(self[index])`.
3225 ///
3226 /// * The element at `index`.
3227 ///
3228 /// * The unsorted subslice after `index`, whose elements all satisfy `f(x) >= f(self[index])`.
3229 ///
3230 /// # Current implementation
3231 ///
3232 /// The current algorithm is an introselect implementation based on [ipnsort] by Lukas Bergdoll
3233 /// and Orson Peters, which is also the basis for [`sort_unstable`]. The fallback algorithm is
3234 /// Median of Medians using Tukey's Ninther for pivot selection, which guarantees linear runtime
3235 /// for all inputs.
3236 ///
3237 /// [`sort_unstable`]: slice::sort_unstable
3238 ///
3239 /// # Panics
3240 ///
3241 /// Panics when `index >= len()`, meaning it always panics on empty slices.
3242 ///
3243 /// May panic if `K: Ord` does not implement a total order.
3244 ///
3245 /// # Examples
3246 ///
3247 /// ```
3248 /// let mut v = [-5i32, 4, 1, -3, 2];
3249 ///
3250 /// // Find the items `<=` to the absolute median, the absolute median itself, and the items
3251 /// // `>=` to it.
3252 /// let (lesser, median, greater) = v.select_nth_unstable_by_key(2, |a| a.abs());
3253 ///
3254 /// assert!(lesser == [1, 2] || lesser == [2, 1]);
3255 /// assert_eq!(median, &mut -3);
3256 /// assert!(greater == [4, -5] || greater == [-5, 4]);
3257 ///
3258 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
3259 /// // about the specified index.
3260 /// assert!(v == [1, 2, -3, 4, -5] ||
3261 /// v == [1, 2, -3, -5, 4] ||
3262 /// v == [2, 1, -3, 4, -5] ||
3263 /// v == [2, 1, -3, -5, 4]);
3264 /// ```
3265 ///
3266 /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort
3267 /// [total order]: https://en.wikipedia.org/wiki/Total_order
3268 #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
3269 #[inline]
3270 pub fn select_nth_unstable_by_key<K, F>(
3271 &mut self,
3272 index: usize,
3273 mut f: F,
3274 ) -> (&mut [T], &mut T, &mut [T])
3275 where
3276 F: FnMut(&T) -> K,
3277 K: Ord,
3278 {
3279 sort::select::partition_at_index(self, index, |a: &T, b: &T| f(a).lt(&f(b)))
3280 }
3281
3282 /// Moves all consecutive repeated elements to the end of the slice according to the
3283 /// [`PartialEq`] trait implementation.
3284 ///
3285 /// Returns two slices. The first contains no consecutive repeated elements.
3286 /// The second contains all the duplicates in no specified order.
3287 ///
3288 /// If the slice is sorted, the first returned slice contains no duplicates.
3289 ///
3290 /// # Examples
3291 ///
3292 /// ```
3293 /// #![feature(slice_partition_dedup)]
3294 ///
3295 /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
3296 ///
3297 /// let (dedup, duplicates) = slice.partition_dedup();
3298 ///
3299 /// assert_eq!(dedup, [1, 2, 3, 2, 1]);
3300 /// assert_eq!(duplicates, [2, 3, 1]);
3301 /// ```
3302 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
3303 #[inline]
3304 pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
3305 where
3306 T: PartialEq,
3307 {
3308 self.partition_dedup_by(|a, b| a == b)
3309 }
3310
3311 /// Moves all but the first of consecutive elements to the end of the slice satisfying
3312 /// a given equality relation.
3313 ///
3314 /// Returns two slices. The first contains no consecutive repeated elements.
3315 /// The second contains all the duplicates in no specified order.
3316 ///
3317 /// The `same_bucket` function is passed references to two elements from the slice and
3318 /// must determine if the elements compare equal. The elements are passed in opposite order
3319 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved
3320 /// at the end of the slice.
3321 ///
3322 /// If the slice is sorted, the first returned slice contains no duplicates.
3323 ///
3324 /// # Examples
3325 ///
3326 /// ```
3327 /// #![feature(slice_partition_dedup)]
3328 ///
3329 /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
3330 ///
3331 /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
3332 ///
3333 /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
3334 /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
3335 /// ```
3336 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
3337 #[inline]
3338 pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])
3339 where
3340 F: FnMut(&mut T, &mut T) -> bool,
3341 {
3342 // Although we have a mutable reference to `self`, we cannot make
3343 // *arbitrary* changes. The `same_bucket` calls could panic, so we
3344 // must ensure that the slice is in a valid state at all times.
3345 //
3346 // The way that we handle this is by using swaps; we iterate
3347 // over all the elements, swapping as we go so that at the end
3348 // the elements we wish to keep are in the front, and those we
3349 // wish to reject are at the back. We can then split the slice.
3350 // This operation is still `O(n)`.
3351 //
3352 // Example: We start in this state, where `r` represents "next
3353 // read" and `w` represents "next_write".
3354 //
3355 // r
3356 // +---+---+---+---+---+---+
3357 // | 0 | 1 | 1 | 2 | 3 | 3 |
3358 // +---+---+---+---+---+---+
3359 // w
3360 //
3361 // Comparing self[r] against self[w-1], this is not a duplicate, so
3362 // we swap self[r] and self[w] (no effect as r==w) and then increment both
3363 // r and w, leaving us with:
3364 //
3365 // r
3366 // +---+---+---+---+---+---+
3367 // | 0 | 1 | 1 | 2 | 3 | 3 |
3368 // +---+---+---+---+---+---+
3369 // w
3370 //
3371 // Comparing self[r] against self[w-1], this value is a duplicate,
3372 // so we increment `r` but leave everything else unchanged:
3373 //
3374 // r
3375 // +---+---+---+---+---+---+
3376 // | 0 | 1 | 1 | 2 | 3 | 3 |
3377 // +---+---+---+---+---+---+
3378 // w
3379 //
3380 // Comparing self[r] against self[w-1], this is not a duplicate,
3381 // so swap self[r] and self[w] and advance r and w:
3382 //
3383 // r
3384 // +---+---+---+---+---+---+
3385 // | 0 | 1 | 2 | 1 | 3 | 3 |
3386 // +---+---+---+---+---+---+
3387 // w
3388 //
3389 // Not a duplicate, repeat:
3390 //
3391 // r
3392 // +---+---+---+---+---+---+
3393 // | 0 | 1 | 2 | 3 | 1 | 3 |
3394 // +---+---+---+---+---+---+
3395 // w
3396 //
3397 // Duplicate, advance r. End of slice. Split at w.
3398
3399 let len = self.len();
3400 if len <= 1 {
3401 return (self, &mut []);
3402 }
3403
3404 let ptr = self.as_mut_ptr();
3405 let mut next_read: usize = 1;
3406 let mut next_write: usize = 1;
3407
3408 // SAFETY: the `while` condition guarantees `next_read` and `next_write`
3409 // are less than `len`, thus are inside `self`. `prev_ptr_write` points to
3410 // one element before `ptr_write`, but `next_write` starts at 1, so
3411 // `prev_ptr_write` is never less than 0 and is inside the slice.
3412 // This fulfils the requirements for dereferencing `ptr_read`, `prev_ptr_write`
3413 // and `ptr_write`, and for using `ptr.add(next_read)`, `ptr.add(next_write - 1)`
3414 // and `prev_ptr_write.offset(1)`.
3415 //
3416 // `next_write` is also incremented at most once per loop at most meaning
3417 // no element is skipped when it may need to be swapped.
3418 //
3419 // `ptr_read` and `prev_ptr_write` never point to the same element. This
3420 // is required for `&mut *ptr_read`, `&mut *prev_ptr_write` to be safe.
3421 // The explanation is simply that `next_read >= next_write` is always true,
3422 // thus `next_read > next_write - 1` is too.
3423 unsafe {
3424 // Avoid bounds checks by using raw pointers.
3425 while next_read < len {
3426 let ptr_read = ptr.add(next_read);
3427 let prev_ptr_write = ptr.add(next_write - 1);
3428 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
3429 if next_read != next_write {
3430 let ptr_write = prev_ptr_write.add(1);
3431 mem::swap(&mut *ptr_read, &mut *ptr_write);
3432 }
3433 next_write += 1;
3434 }
3435 next_read += 1;
3436 }
3437 }
3438
3439 self.split_at_mut(next_write)
3440 }
3441
3442 /// Moves all but the first of consecutive elements to the end of the slice that resolve
3443 /// to the same key.
3444 ///
3445 /// Returns two slices. The first contains no consecutive repeated elements.
3446 /// The second contains all the duplicates in no specified order.
3447 ///
3448 /// If the slice is sorted, the first returned slice contains no duplicates.
3449 ///
3450 /// # Examples
3451 ///
3452 /// ```
3453 /// #![feature(slice_partition_dedup)]
3454 ///
3455 /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
3456 ///
3457 /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
3458 ///
3459 /// assert_eq!(dedup, [10, 20, 30, 20, 11]);
3460 /// assert_eq!(duplicates, [21, 30, 13]);
3461 /// ```
3462 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
3463 #[inline]
3464 pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])
3465 where
3466 F: FnMut(&mut T) -> K,
3467 K: PartialEq,
3468 {
3469 self.partition_dedup_by(|a, b| key(a) == key(b))
3470 }
3471
3472 /// Rotates the slice in-place such that the first `mid` elements of the
3473 /// slice move to the end while the last `self.len() - mid` elements move to
3474 /// the front.
3475 ///
3476 /// After calling `rotate_left`, the element previously at index `mid` will
3477 /// become the first element in the slice.
3478 ///
3479 /// # Panics
3480 ///
3481 /// This function will panic if `mid` is greater than the length of the
3482 /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
3483 /// rotation.
3484 ///
3485 /// # Complexity
3486 ///
3487 /// Takes linear (in `self.len()`) time.
3488 ///
3489 /// # Examples
3490 ///
3491 /// ```
3492 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3493 /// a.rotate_left(2);
3494 /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
3495 /// ```
3496 ///
3497 /// Rotating a subslice:
3498 ///
3499 /// ```
3500 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3501 /// a[1..5].rotate_left(1);
3502 /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
3503 /// ```
3504 #[stable(feature = "slice_rotate", since = "1.26.0")]
3505 pub fn rotate_left(&mut self, mid: usize) {
3506 assert!(mid <= self.len());
3507 let k = self.len() - mid;
3508 let p = self.as_mut_ptr();
3509
3510 // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
3511 // valid for reading and writing, as required by `ptr_rotate`.
3512 unsafe {
3513 rotate::ptr_rotate(mid, p.add(mid), k);
3514 }
3515 }
3516
3517 /// Rotates the slice in-place such that the first `self.len() - k`
3518 /// elements of the slice move to the end while the last `k` elements move
3519 /// to the front.
3520 ///
3521 /// After calling `rotate_right`, the element previously at index
3522 /// `self.len() - k` will become the first element in the slice.
3523 ///
3524 /// # Panics
3525 ///
3526 /// This function will panic if `k` is greater than the length of the
3527 /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
3528 /// rotation.
3529 ///
3530 /// # Complexity
3531 ///
3532 /// Takes linear (in `self.len()`) time.
3533 ///
3534 /// # Examples
3535 ///
3536 /// ```
3537 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3538 /// a.rotate_right(2);
3539 /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
3540 /// ```
3541 ///
3542 /// Rotating a subslice:
3543 ///
3544 /// ```
3545 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3546 /// a[1..5].rotate_right(1);
3547 /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
3548 /// ```
3549 #[stable(feature = "slice_rotate", since = "1.26.0")]
3550 pub fn rotate_right(&mut self, k: usize) {
3551 assert!(k <= self.len());
3552 let mid = self.len() - k;
3553 let p = self.as_mut_ptr();
3554
3555 // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
3556 // valid for reading and writing, as required by `ptr_rotate`.
3557 unsafe {
3558 rotate::ptr_rotate(mid, p.add(mid), k);
3559 }
3560 }
3561
3562 /// Fills `self` with elements by cloning `value`.
3563 ///
3564 /// # Examples
3565 ///
3566 /// ```
3567 /// let mut buf = vec![0; 10];
3568 /// buf.fill(1);
3569 /// assert_eq!(buf, vec![1; 10]);
3570 /// ```
3571 #[doc(alias = "memset")]
3572 #[stable(feature = "slice_fill", since = "1.50.0")]
3573 pub fn fill(&mut self, value: T)
3574 where
3575 T: Clone,
3576 {
3577 specialize::SpecFill::spec_fill(self, value);
3578 }
3579
3580 /// Fills `self` with elements returned by calling a closure repeatedly.
3581 ///
3582 /// This method uses a closure to create new values. If you'd rather
3583 /// [`Clone`] a given value, use [`fill`]. If you want to use the [`Default`]
3584 /// trait to generate values, you can pass [`Default::default`] as the
3585 /// argument.
3586 ///
3587 /// [`fill`]: slice::fill
3588 ///
3589 /// # Examples
3590 ///
3591 /// ```
3592 /// let mut buf = vec![1; 10];
3593 /// buf.fill_with(Default::default);
3594 /// assert_eq!(buf, vec![0; 10]);
3595 /// ```
3596 #[stable(feature = "slice_fill_with", since = "1.51.0")]
3597 pub fn fill_with<F>(&mut self, mut f: F)
3598 where
3599 F: FnMut() -> T,
3600 {
3601 for el in self {
3602 *el = f();
3603 }
3604 }
3605
3606 /// Copies the elements from `src` into `self`.
3607 ///
3608 /// The length of `src` must be the same as `self`.
3609 ///
3610 /// # Panics
3611 ///
3612 /// This function will panic if the two slices have different lengths.
3613 ///
3614 /// # Examples
3615 ///
3616 /// Cloning two elements from a slice into another:
3617 ///
3618 /// ```
3619 /// let src = [1, 2, 3, 4];
3620 /// let mut dst = [0, 0];
3621 ///
3622 /// // Because the slices have to be the same length,
3623 /// // we slice the source slice from four elements
3624 /// // to two. It will panic if we don't do this.
3625 /// dst.clone_from_slice(&src[2..]);
3626 ///
3627 /// assert_eq!(src, [1, 2, 3, 4]);
3628 /// assert_eq!(dst, [3, 4]);
3629 /// ```
3630 ///
3631 /// Rust enforces that there can only be one mutable reference with no
3632 /// immutable references to a particular piece of data in a particular
3633 /// scope. Because of this, attempting to use `clone_from_slice` on a
3634 /// single slice will result in a compile failure:
3635 ///
3636 /// ```compile_fail
3637 /// let mut slice = [1, 2, 3, 4, 5];
3638 ///
3639 /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
3640 /// ```
3641 ///
3642 /// To work around this, we can use [`split_at_mut`] to create two distinct
3643 /// sub-slices from a slice:
3644 ///
3645 /// ```
3646 /// let mut slice = [1, 2, 3, 4, 5];
3647 ///
3648 /// {
3649 /// let (left, right) = slice.split_at_mut(2);
3650 /// left.clone_from_slice(&right[1..]);
3651 /// }
3652 ///
3653 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
3654 /// ```
3655 ///
3656 /// [`copy_from_slice`]: slice::copy_from_slice
3657 /// [`split_at_mut`]: slice::split_at_mut
3658 #[stable(feature = "clone_from_slice", since = "1.7.0")]
3659 #[track_caller]
3660 pub fn clone_from_slice(&mut self, src: &[T])
3661 where
3662 T: Clone,
3663 {
3664 self.spec_clone_from(src);
3665 }
3666
3667 /// Copies all elements from `src` into `self`, using a memcpy.
3668 ///
3669 /// The length of `src` must be the same as `self`.
3670 ///
3671 /// If `T` does not implement `Copy`, use [`clone_from_slice`].
3672 ///
3673 /// # Panics
3674 ///
3675 /// This function will panic if the two slices have different lengths.
3676 ///
3677 /// # Examples
3678 ///
3679 /// Copying two elements from a slice into another:
3680 ///
3681 /// ```
3682 /// let src = [1, 2, 3, 4];
3683 /// let mut dst = [0, 0];
3684 ///
3685 /// // Because the slices have to be the same length,
3686 /// // we slice the source slice from four elements
3687 /// // to two. It will panic if we don't do this.
3688 /// dst.copy_from_slice(&src[2..]);
3689 ///
3690 /// assert_eq!(src, [1, 2, 3, 4]);
3691 /// assert_eq!(dst, [3, 4]);
3692 /// ```
3693 ///
3694 /// Rust enforces that there can only be one mutable reference with no
3695 /// immutable references to a particular piece of data in a particular
3696 /// scope. Because of this, attempting to use `copy_from_slice` on a
3697 /// single slice will result in a compile failure:
3698 ///
3699 /// ```compile_fail
3700 /// let mut slice = [1, 2, 3, 4, 5];
3701 ///
3702 /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
3703 /// ```
3704 ///
3705 /// To work around this, we can use [`split_at_mut`] to create two distinct
3706 /// sub-slices from a slice:
3707 ///
3708 /// ```
3709 /// let mut slice = [1, 2, 3, 4, 5];
3710 ///
3711 /// {
3712 /// let (left, right) = slice.split_at_mut(2);
3713 /// left.copy_from_slice(&right[1..]);
3714 /// }
3715 ///
3716 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
3717 /// ```
3718 ///
3719 /// [`clone_from_slice`]: slice::clone_from_slice
3720 /// [`split_at_mut`]: slice::split_at_mut
3721 #[doc(alias = "memcpy")]
3722 #[inline]
3723 #[stable(feature = "copy_from_slice", since = "1.9.0")]
3724 #[rustc_const_stable(feature = "const_copy_from_slice", since = "1.87.0")]
3725 #[track_caller]
3726 pub const fn copy_from_slice(&mut self, src: &[T])
3727 where
3728 T: Copy,
3729 {
3730 // The panic code path was put into a cold function to not bloat the
3731 // call site.
3732 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
3733 #[cfg_attr(feature = "panic_immediate_abort", inline)]
3734 #[track_caller]
3735 const fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! {
3736 const_panic!(
3737 "copy_from_slice: source slice length does not match destination slice length",
3738 "copy_from_slice: source slice length ({src_len}) does not match destination slice length ({dst_len})",
3739 src_len: usize,
3740 dst_len: usize,
3741 )
3742 }
3743
3744 if self.len() != src.len() {
3745 len_mismatch_fail(self.len(), src.len());
3746 }
3747
3748 // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
3749 // checked to have the same length. The slices cannot overlap because
3750 // mutable references are exclusive.
3751 unsafe {
3752 ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len());
3753 }
3754 }
3755
3756 /// Copies elements from one part of the slice to another part of itself,
3757 /// using a memmove.
3758 ///
3759 /// `src` is the range within `self` to copy from. `dest` is the starting
3760 /// index of the range within `self` to copy to, which will have the same
3761 /// length as `src`. The two ranges may overlap. The ends of the two ranges
3762 /// must be less than or equal to `self.len()`.
3763 ///
3764 /// # Panics
3765 ///
3766 /// This function will panic if either range exceeds the end of the slice,
3767 /// or if the end of `src` is before the start.
3768 ///
3769 /// # Examples
3770 ///
3771 /// Copying four bytes within a slice:
3772 ///
3773 /// ```
3774 /// let mut bytes = *b"Hello, World!";
3775 ///
3776 /// bytes.copy_within(1..5, 8);
3777 ///
3778 /// assert_eq!(&bytes, b"Hello, Wello!");
3779 /// ```
3780 #[stable(feature = "copy_within", since = "1.37.0")]
3781 #[track_caller]
3782 pub fn copy_within<R: RangeBounds<usize>>(&mut self, src: R, dest: usize)
3783 where
3784 T: Copy,
3785 {
3786 let Range { start: src_start, end: src_end } = slice::range(src, ..self.len());
3787 let count = src_end - src_start;
3788 assert!(dest <= self.len() - count, "dest is out of bounds");
3789 // SAFETY: the conditions for `ptr::copy` have all been checked above,
3790 // as have those for `ptr::add`.
3791 unsafe {
3792 // Derive both `src_ptr` and `dest_ptr` from the same loan
3793 let ptr = self.as_mut_ptr();
3794 let src_ptr = ptr.add(src_start);
3795 let dest_ptr = ptr.add(dest);
3796 ptr::copy(src_ptr, dest_ptr, count);
3797 }
3798 }
3799
3800 /// Swaps all elements in `self` with those in `other`.
3801 ///
3802 /// The length of `other` must be the same as `self`.
3803 ///
3804 /// # Panics
3805 ///
3806 /// This function will panic if the two slices have different lengths.
3807 ///
3808 /// # Example
3809 ///
3810 /// Swapping two elements across slices:
3811 ///
3812 /// ```
3813 /// let mut slice1 = [0, 0];
3814 /// let mut slice2 = [1, 2, 3, 4];
3815 ///
3816 /// slice1.swap_with_slice(&mut slice2[2..]);
3817 ///
3818 /// assert_eq!(slice1, [3, 4]);
3819 /// assert_eq!(slice2, [1, 2, 0, 0]);
3820 /// ```
3821 ///
3822 /// Rust enforces that there can only be one mutable reference to a
3823 /// particular piece of data in a particular scope. Because of this,
3824 /// attempting to use `swap_with_slice` on a single slice will result in
3825 /// a compile failure:
3826 ///
3827 /// ```compile_fail
3828 /// let mut slice = [1, 2, 3, 4, 5];
3829 /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
3830 /// ```
3831 ///
3832 /// To work around this, we can use [`split_at_mut`] to create two distinct
3833 /// mutable sub-slices from a slice:
3834 ///
3835 /// ```
3836 /// let mut slice = [1, 2, 3, 4, 5];
3837 ///
3838 /// {
3839 /// let (left, right) = slice.split_at_mut(2);
3840 /// left.swap_with_slice(&mut right[1..]);
3841 /// }
3842 ///
3843 /// assert_eq!(slice, [4, 5, 3, 1, 2]);
3844 /// ```
3845 ///
3846 /// [`split_at_mut`]: slice::split_at_mut
3847 #[stable(feature = "swap_with_slice", since = "1.27.0")]
3848 #[track_caller]
3849 pub fn swap_with_slice(&mut self, other: &mut [T]) {
3850 assert!(self.len() == other.len(), "destination and source slices have different lengths");
3851 // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
3852 // checked to have the same length. The slices cannot overlap because
3853 // mutable references are exclusive.
3854 unsafe {
3855 ptr::swap_nonoverlapping(self.as_mut_ptr(), other.as_mut_ptr(), self.len());
3856 }
3857 }
3858
3859 /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
3860 fn align_to_offsets<U>(&self) -> (usize, usize) {
3861 // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
3862 // lowest number of `T`s. And how many `T`s we need for each such "multiple".
3863 //
3864 // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
3865 // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
3866 // place of every 3 Ts in the `rest` slice. A bit more complicated.
3867 //
3868 // Formula to calculate this is:
3869 //
3870 // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
3871 // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
3872 //
3873 // Expanded and simplified:
3874 //
3875 // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
3876 // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
3877 //
3878 // Luckily since all this is constant-evaluated... performance here matters not!
3879 const fn gcd(a: usize, b: usize) -> usize {
3880 if b == 0 { a } else { gcd(b, a % b) }
3881 }
3882
3883 // Explicitly wrap the function call in a const block so it gets
3884 // constant-evaluated even in debug mode.
3885 let gcd: usize = const { gcd(size_of::<T>(), size_of::<U>()) };
3886 let ts: usize = size_of::<U>() / gcd;
3887 let us: usize = size_of::<T>() / gcd;
3888
3889 // Armed with this knowledge, we can find how many `U`s we can fit!
3890 let us_len = self.len() / ts * us;
3891 // And how many `T`s will be in the trailing slice!
3892 let ts_len = self.len() % ts;
3893 (us_len, ts_len)
3894 }
3895
3896 /// Transmutes the slice to a slice of another type, ensuring alignment of the types is
3897 /// maintained.
3898 ///
3899 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
3900 /// slice of a new type, and the suffix slice. The middle part will be as big as possible under
3901 /// the given alignment constraint and element size.
3902 ///
3903 /// This method has no purpose when either input element `T` or output element `U` are
3904 /// zero-sized and will return the original slice without splitting anything.
3905 ///
3906 /// # Safety
3907 ///
3908 /// This method is essentially a `transmute` with respect to the elements in the returned
3909 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
3910 ///
3911 /// # Examples
3912 ///
3913 /// Basic usage:
3914 ///
3915 /// ```
3916 /// unsafe {
3917 /// let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
3918 /// let (prefix, shorts, suffix) = bytes.align_to::<u16>();
3919 /// // less_efficient_algorithm_for_bytes(prefix);
3920 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
3921 /// // less_efficient_algorithm_for_bytes(suffix);
3922 /// }
3923 /// ```
3924 #[stable(feature = "slice_align_to", since = "1.30.0")]
3925 #[must_use]
3926 pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
3927 // Note that most of this function will be constant-evaluated,
3928 if U::IS_ZST || T::IS_ZST {
3929 // handle ZSTs specially, which is – don't handle them at all.
3930 return (self, &[], &[]);
3931 }
3932
3933 // First, find at what point do we split between the first and 2nd slice. Easy with
3934 // ptr.align_offset.
3935 let ptr = self.as_ptr();
3936 // SAFETY: See the `align_to_mut` method for the detailed safety comment.
3937 let offset = unsafe { crate::ptr::align_offset(ptr, align_of::<U>()) };
3938 if offset > self.len() {
3939 (self, &[], &[])
3940 } else {
3941 let (left, rest) = self.split_at(offset);
3942 let (us_len, ts_len) = rest.align_to_offsets::<U>();
3943 // Inform Miri that we want to consider the "middle" pointer to be suitably aligned.
3944 #[cfg(miri)]
3945 crate::intrinsics::miri_promise_symbolic_alignment(
3946 rest.as_ptr().cast(),
3947 align_of::<U>(),
3948 );
3949 // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay,
3950 // since the caller guarantees that we can transmute `T` to `U` safely.
3951 unsafe {
3952 (
3953 left,
3954 from_raw_parts(rest.as_ptr() as *const U, us_len),
3955 from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len),
3956 )
3957 }
3958 }
3959 }
3960
3961 /// Transmutes the mutable slice to a mutable slice of another type, ensuring alignment of the
3962 /// types is maintained.
3963 ///
3964 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
3965 /// slice of a new type, and the suffix slice. The middle part will be as big as possible under
3966 /// the given alignment constraint and element size.
3967 ///
3968 /// This method has no purpose when either input element `T` or output element `U` are
3969 /// zero-sized and will return the original slice without splitting anything.
3970 ///
3971 /// # Safety
3972 ///
3973 /// This method is essentially a `transmute` with respect to the elements in the returned
3974 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
3975 ///
3976 /// # Examples
3977 ///
3978 /// Basic usage:
3979 ///
3980 /// ```
3981 /// unsafe {
3982 /// let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
3983 /// let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
3984 /// // less_efficient_algorithm_for_bytes(prefix);
3985 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
3986 /// // less_efficient_algorithm_for_bytes(suffix);
3987 /// }
3988 /// ```
3989 #[stable(feature = "slice_align_to", since = "1.30.0")]
3990 #[must_use]
3991 pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
3992 // Note that most of this function will be constant-evaluated,
3993 if U::IS_ZST || T::IS_ZST {
3994 // handle ZSTs specially, which is – don't handle them at all.
3995 return (self, &mut [], &mut []);
3996 }
3997
3998 // First, find at what point do we split between the first and 2nd slice. Easy with
3999 // ptr.align_offset.
4000 let ptr = self.as_ptr();
4001 // SAFETY: Here we are ensuring we will use aligned pointers for U for the
4002 // rest of the method. This is done by passing a pointer to &[T] with an
4003 // alignment targeted for U.
4004 // `crate::ptr::align_offset` is called with a correctly aligned and
4005 // valid pointer `ptr` (it comes from a reference to `self`) and with
4006 // a size that is a power of two (since it comes from the alignment for U),
4007 // satisfying its safety constraints.
4008 let offset = unsafe { crate::ptr::align_offset(ptr, align_of::<U>()) };
4009 if offset > self.len() {
4010 (self, &mut [], &mut [])
4011 } else {
4012 let (left, rest) = self.split_at_mut(offset);
4013 let (us_len, ts_len) = rest.align_to_offsets::<U>();
4014 let rest_len = rest.len();
4015 let mut_ptr = rest.as_mut_ptr();
4016 // Inform Miri that we want to consider the "middle" pointer to be suitably aligned.
4017 #[cfg(miri)]
4018 crate::intrinsics::miri_promise_symbolic_alignment(
4019 mut_ptr.cast() as *const (),
4020 align_of::<U>(),
4021 );
4022 // We can't use `rest` again after this, that would invalidate its alias `mut_ptr`!
4023 // SAFETY: see comments for `align_to`.
4024 unsafe {
4025 (
4026 left,
4027 from_raw_parts_mut(mut_ptr as *mut U, us_len),
4028 from_raw_parts_mut(mut_ptr.add(rest_len - ts_len), ts_len),
4029 )
4030 }
4031 }
4032 }
4033
4034 /// Splits a slice into a prefix, a middle of aligned SIMD types, and a suffix.
4035 ///
4036 /// This is a safe wrapper around [`slice::align_to`], so inherits the same
4037 /// guarantees as that method.
4038 ///
4039 /// # Panics
4040 ///
4041 /// This will panic if the size of the SIMD type is different from
4042 /// `LANES` times that of the scalar.
4043 ///
4044 /// At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps
4045 /// that from ever happening, as only power-of-two numbers of lanes are
4046 /// supported. It's possible that, in the future, those restrictions might
4047 /// be lifted in a way that would make it possible to see panics from this
4048 /// method for something like `LANES == 3`.
4049 ///
4050 /// # Examples
4051 ///
4052 /// ```
4053 /// #![feature(portable_simd)]
4054 /// use core::simd::prelude::*;
4055 ///
4056 /// let short = &[1, 2, 3];
4057 /// let (prefix, middle, suffix) = short.as_simd::<4>();
4058 /// assert_eq!(middle, []); // Not enough elements for anything in the middle
4059 ///
4060 /// // They might be split in any possible way between prefix and suffix
4061 /// let it = prefix.iter().chain(suffix).copied();
4062 /// assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);
4063 ///
4064 /// fn basic_simd_sum(x: &[f32]) -> f32 {
4065 /// use std::ops::Add;
4066 /// let (prefix, middle, suffix) = x.as_simd();
4067 /// let sums = f32x4::from_array([
4068 /// prefix.iter().copied().sum(),
4069 /// 0.0,
4070 /// 0.0,
4071 /// suffix.iter().copied().sum(),
4072 /// ]);
4073 /// let sums = middle.iter().copied().fold(sums, f32x4::add);
4074 /// sums.reduce_sum()
4075 /// }
4076 ///
4077 /// let numbers: Vec<f32> = (1..101).map(|x| x as _).collect();
4078 /// assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);
4079 /// ```
4080 #[unstable(feature = "portable_simd", issue = "86656")]
4081 #[must_use]
4082 pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])
4083 where
4084 Simd<T, LANES>: AsRef<[T; LANES]>,
4085 T: simd::SimdElement,
4086 simd::LaneCount<LANES>: simd::SupportedLaneCount,
4087 {
4088 // These are expected to always match, as vector types are laid out like
4089 // arrays per <https://llvm.org/docs/LangRef.html#vector-type>, but we
4090 // might as well double-check since it'll optimize away anyhow.
4091 assert_eq!(size_of::<Simd<T, LANES>>(), size_of::<[T; LANES]>());
4092
4093 // SAFETY: The simd types have the same layout as arrays, just with
4094 // potentially-higher alignment, so the de-facto transmutes are sound.
4095 unsafe { self.align_to() }
4096 }
4097
4098 /// Splits a mutable slice into a mutable prefix, a middle of aligned SIMD types,
4099 /// and a mutable suffix.
4100 ///
4101 /// This is a safe wrapper around [`slice::align_to_mut`], so inherits the same
4102 /// guarantees as that method.
4103 ///
4104 /// This is the mutable version of [`slice::as_simd`]; see that for examples.
4105 ///
4106 /// # Panics
4107 ///
4108 /// This will panic if the size of the SIMD type is different from
4109 /// `LANES` times that of the scalar.
4110 ///
4111 /// At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps
4112 /// that from ever happening, as only power-of-two numbers of lanes are
4113 /// supported. It's possible that, in the future, those restrictions might
4114 /// be lifted in a way that would make it possible to see panics from this
4115 /// method for something like `LANES == 3`.
4116 #[unstable(feature = "portable_simd", issue = "86656")]
4117 #[must_use]
4118 pub fn as_simd_mut<const LANES: usize>(&mut self) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])
4119 where
4120 Simd<T, LANES>: AsMut<[T; LANES]>,
4121 T: simd::SimdElement,
4122 simd::LaneCount<LANES>: simd::SupportedLaneCount,
4123 {
4124 // These are expected to always match, as vector types are laid out like
4125 // arrays per <https://llvm.org/docs/LangRef.html#vector-type>, but we
4126 // might as well double-check since it'll optimize away anyhow.
4127 assert_eq!(size_of::<Simd<T, LANES>>(), size_of::<[T; LANES]>());
4128
4129 // SAFETY: The simd types have the same layout as arrays, just with
4130 // potentially-higher alignment, so the de-facto transmutes are sound.
4131 unsafe { self.align_to_mut() }
4132 }
4133
4134 /// Checks if the elements of this slice are sorted.
4135 ///
4136 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
4137 /// slice yields exactly zero or one element, `true` is returned.
4138 ///
4139 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
4140 /// implies that this function returns `false` if any two consecutive items are not
4141 /// comparable.
4142 ///
4143 /// # Examples
4144 ///
4145 /// ```
4146 /// let empty: [i32; 0] = [];
4147 ///
4148 /// assert!([1, 2, 2, 9].is_sorted());
4149 /// assert!(![1, 3, 2, 4].is_sorted());
4150 /// assert!([0].is_sorted());
4151 /// assert!(empty.is_sorted());
4152 /// assert!(![0.0, 1.0, f32::NAN].is_sorted());
4153 /// ```
4154 #[inline]
4155 #[stable(feature = "is_sorted", since = "1.82.0")]
4156 #[must_use]
4157 pub fn is_sorted(&self) -> bool
4158 where
4159 T: PartialOrd,
4160 {
4161 // This odd number works the best. 32 + 1 extra due to overlapping chunk boundaries.
4162 const CHUNK_SIZE: usize = 33;
4163 if self.len() < CHUNK_SIZE {
4164 return self.windows(2).all(|w| w[0] <= w[1]);
4165 }
4166 let mut i = 0;
4167 // Check in chunks for autovectorization.
4168 while i < self.len() - CHUNK_SIZE {
4169 let chunk = &self[i..i + CHUNK_SIZE];
4170 if !chunk.windows(2).fold(true, |acc, w| acc & (w[0] <= w[1])) {
4171 return false;
4172 }
4173 // We need to ensure that chunk boundaries are also sorted.
4174 // Overlap the next chunk with the last element of our last chunk.
4175 i += CHUNK_SIZE - 1;
4176 }
4177 self[i..].windows(2).all(|w| w[0] <= w[1])
4178 }
4179
4180 /// Checks if the elements of this slice are sorted using the given comparator function.
4181 ///
4182 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
4183 /// function to determine whether two elements are to be considered in sorted order.
4184 ///
4185 /// # Examples
4186 ///
4187 /// ```
4188 /// assert!([1, 2, 2, 9].is_sorted_by(|a, b| a <= b));
4189 /// assert!(![1, 2, 2, 9].is_sorted_by(|a, b| a < b));
4190 ///
4191 /// assert!([0].is_sorted_by(|a, b| true));
4192 /// assert!([0].is_sorted_by(|a, b| false));
4193 ///
4194 /// let empty: [i32; 0] = [];
4195 /// assert!(empty.is_sorted_by(|a, b| false));
4196 /// assert!(empty.is_sorted_by(|a, b| true));
4197 /// ```
4198 #[stable(feature = "is_sorted", since = "1.82.0")]
4199 #[must_use]
4200 pub fn is_sorted_by<'a, F>(&'a self, mut compare: F) -> bool
4201 where
4202 F: FnMut(&'a T, &'a T) -> bool,
4203 {
4204 self.array_windows().all(|[a, b]| compare(a, b))
4205 }
4206
4207 /// Checks if the elements of this slice are sorted using the given key extraction function.
4208 ///
4209 /// Instead of comparing the slice's elements directly, this function compares the keys of the
4210 /// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its
4211 /// documentation for more information.
4212 ///
4213 /// [`is_sorted`]: slice::is_sorted
4214 ///
4215 /// # Examples
4216 ///
4217 /// ```
4218 /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
4219 /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
4220 /// ```
4221 #[inline]
4222 #[stable(feature = "is_sorted", since = "1.82.0")]
4223 #[must_use]
4224 pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> bool
4225 where
4226 F: FnMut(&'a T) -> K,
4227 K: PartialOrd,
4228 {
4229 self.iter().is_sorted_by_key(f)
4230 }
4231
4232 /// Returns the index of the partition point according to the given predicate
4233 /// (the index of the first element of the second partition).
4234 ///
4235 /// The slice is assumed to be partitioned according to the given predicate.
4236 /// This means that all elements for which the predicate returns true are at the start of the slice
4237 /// and all elements for which the predicate returns false are at the end.
4238 /// For example, `[7, 15, 3, 5, 4, 12, 6]` is partitioned under the predicate `x % 2 != 0`
4239 /// (all odd numbers are at the start, all even at the end).
4240 ///
4241 /// If this slice is not partitioned, the returned result is unspecified and meaningless,
4242 /// as this method performs a kind of binary search.
4243 ///
4244 /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
4245 ///
4246 /// [`binary_search`]: slice::binary_search
4247 /// [`binary_search_by`]: slice::binary_search_by
4248 /// [`binary_search_by_key`]: slice::binary_search_by_key
4249 ///
4250 /// # Examples
4251 ///
4252 /// ```
4253 /// let v = [1, 2, 3, 3, 5, 6, 7];
4254 /// let i = v.partition_point(|&x| x < 5);
4255 ///
4256 /// assert_eq!(i, 4);
4257 /// assert!(v[..i].iter().all(|&x| x < 5));
4258 /// assert!(v[i..].iter().all(|&x| !(x < 5)));
4259 /// ```
4260 ///
4261 /// If all elements of the slice match the predicate, including if the slice
4262 /// is empty, then the length of the slice will be returned:
4263 ///
4264 /// ```
4265 /// let a = [2, 4, 8];
4266 /// assert_eq!(a.partition_point(|x| x < &100), a.len());
4267 /// let a: [i32; 0] = [];
4268 /// assert_eq!(a.partition_point(|x| x < &100), 0);
4269 /// ```
4270 ///
4271 /// If you want to insert an item to a sorted vector, while maintaining
4272 /// sort order:
4273 ///
4274 /// ```
4275 /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
4276 /// let num = 42;
4277 /// let idx = s.partition_point(|&x| x <= num);
4278 /// s.insert(idx, num);
4279 /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
4280 /// ```
4281 #[stable(feature = "partition_point", since = "1.52.0")]
4282 #[must_use]
4283 pub fn partition_point<P>(&self, mut pred: P) -> usize
4284 where
4285 P: FnMut(&T) -> bool,
4286 {
4287 self.binary_search_by(|x| if pred(x) { Less } else { Greater }).unwrap_or_else(|i| i)
4288 }
4289
4290 /// Removes the subslice corresponding to the given range
4291 /// and returns a reference to it.
4292 ///
4293 /// Returns `None` and does not modify the slice if the given
4294 /// range is out of bounds.
4295 ///
4296 /// Note that this method only accepts one-sided ranges such as
4297 /// `2..` or `..6`, but not `2..6`.
4298 ///
4299 /// # Examples
4300 ///
4301 /// Splitting off the first three elements of a slice:
4302 ///
4303 /// ```
4304 /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
4305 /// let mut first_three = slice.split_off(..3).unwrap();
4306 ///
4307 /// assert_eq!(slice, &['d']);
4308 /// assert_eq!(first_three, &['a', 'b', 'c']);
4309 /// ```
4310 ///
4311 /// Splitting off the last two elements of a slice:
4312 ///
4313 /// ```
4314 /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
4315 /// let mut tail = slice.split_off(2..).unwrap();
4316 ///
4317 /// assert_eq!(slice, &['a', 'b']);
4318 /// assert_eq!(tail, &['c', 'd']);
4319 /// ```
4320 ///
4321 /// Getting `None` when `range` is out of bounds:
4322 ///
4323 /// ```
4324 /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
4325 ///
4326 /// assert_eq!(None, slice.split_off(5..));
4327 /// assert_eq!(None, slice.split_off(..5));
4328 /// assert_eq!(None, slice.split_off(..=4));
4329 /// let expected: &[char] = &['a', 'b', 'c', 'd'];
4330 /// assert_eq!(Some(expected), slice.split_off(..4));
4331 /// ```
4332 #[inline]
4333 #[must_use = "method does not modify the slice if the range is out of bounds"]
4334 #[stable(feature = "slice_take", since = "1.87.0")]
4335 pub fn split_off<'a, R: OneSidedRange<usize>>(
4336 self: &mut &'a Self,
4337 range: R,
4338 ) -> Option<&'a Self> {
4339 let (direction, split_index) = split_point_of(range)?;
4340 if split_index > self.len() {
4341 return None;
4342 }
4343 let (front, back) = self.split_at(split_index);
4344 match direction {
4345 Direction::Front => {
4346 *self = back;
4347 Some(front)
4348 }
4349 Direction::Back => {
4350 *self = front;
4351 Some(back)
4352 }
4353 }
4354 }
4355
4356 /// Removes the subslice corresponding to the given range
4357 /// and returns a mutable reference to it.
4358 ///
4359 /// Returns `None` and does not modify the slice if the given
4360 /// range is out of bounds.
4361 ///
4362 /// Note that this method only accepts one-sided ranges such as
4363 /// `2..` or `..6`, but not `2..6`.
4364 ///
4365 /// # Examples
4366 ///
4367 /// Splitting off the first three elements of a slice:
4368 ///
4369 /// ```
4370 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
4371 /// let mut first_three = slice.split_off_mut(..3).unwrap();
4372 ///
4373 /// assert_eq!(slice, &mut ['d']);
4374 /// assert_eq!(first_three, &mut ['a', 'b', 'c']);
4375 /// ```
4376 ///
4377 /// Taking the last two elements of a slice:
4378 ///
4379 /// ```
4380 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
4381 /// let mut tail = slice.split_off_mut(2..).unwrap();
4382 ///
4383 /// assert_eq!(slice, &mut ['a', 'b']);
4384 /// assert_eq!(tail, &mut ['c', 'd']);
4385 /// ```
4386 ///
4387 /// Getting `None` when `range` is out of bounds:
4388 ///
4389 /// ```
4390 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
4391 ///
4392 /// assert_eq!(None, slice.split_off_mut(5..));
4393 /// assert_eq!(None, slice.split_off_mut(..5));
4394 /// assert_eq!(None, slice.split_off_mut(..=4));
4395 /// let expected: &mut [_] = &mut ['a', 'b', 'c', 'd'];
4396 /// assert_eq!(Some(expected), slice.split_off_mut(..4));
4397 /// ```
4398 #[inline]
4399 #[must_use = "method does not modify the slice if the range is out of bounds"]
4400 #[stable(feature = "slice_take", since = "1.87.0")]
4401 pub fn split_off_mut<'a, R: OneSidedRange<usize>>(
4402 self: &mut &'a mut Self,
4403 range: R,
4404 ) -> Option<&'a mut Self> {
4405 let (direction, split_index) = split_point_of(range)?;
4406 if split_index > self.len() {
4407 return None;
4408 }
4409 let (front, back) = mem::take(self).split_at_mut(split_index);
4410 match direction {
4411 Direction::Front => {
4412 *self = back;
4413 Some(front)
4414 }
4415 Direction::Back => {
4416 *self = front;
4417 Some(back)
4418 }
4419 }
4420 }
4421
4422 /// Removes the first element of the slice and returns a reference
4423 /// to it.
4424 ///
4425 /// Returns `None` if the slice is empty.
4426 ///
4427 /// # Examples
4428 ///
4429 /// ```
4430 /// let mut slice: &[_] = &['a', 'b', 'c'];
4431 /// let first = slice.split_off_first().unwrap();
4432 ///
4433 /// assert_eq!(slice, &['b', 'c']);
4434 /// assert_eq!(first, &'a');
4435 /// ```
4436 #[inline]
4437 #[stable(feature = "slice_take", since = "1.87.0")]
4438 #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]
4439 pub const fn split_off_first<'a>(self: &mut &'a Self) -> Option<&'a T> {
4440 // FIXME(const-hack): Use `?` when available in const instead of `let-else`.
4441 let Some((first, rem)) = self.split_first() else { return None };
4442 *self = rem;
4443 Some(first)
4444 }
4445
4446 /// Removes the first element of the slice and returns a mutable
4447 /// reference to it.
4448 ///
4449 /// Returns `None` if the slice is empty.
4450 ///
4451 /// # Examples
4452 ///
4453 /// ```
4454 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
4455 /// let first = slice.split_off_first_mut().unwrap();
4456 /// *first = 'd';
4457 ///
4458 /// assert_eq!(slice, &['b', 'c']);
4459 /// assert_eq!(first, &'d');
4460 /// ```
4461 #[inline]
4462 #[stable(feature = "slice_take", since = "1.87.0")]
4463 #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]
4464 pub const fn split_off_first_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {
4465 // FIXME(const-hack): Use `mem::take` and `?` when available in const.
4466 // Original: `mem::take(self).split_first_mut()?`
4467 let Some((first, rem)) = mem::replace(self, &mut []).split_first_mut() else { return None };
4468 *self = rem;
4469 Some(first)
4470 }
4471
4472 /// Removes the last element of the slice and returns a reference
4473 /// to it.
4474 ///
4475 /// Returns `None` if the slice is empty.
4476 ///
4477 /// # Examples
4478 ///
4479 /// ```
4480 /// let mut slice: &[_] = &['a', 'b', 'c'];
4481 /// let last = slice.split_off_last().unwrap();
4482 ///
4483 /// assert_eq!(slice, &['a', 'b']);
4484 /// assert_eq!(last, &'c');
4485 /// ```
4486 #[inline]
4487 #[stable(feature = "slice_take", since = "1.87.0")]
4488 #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]
4489 pub const fn split_off_last<'a>(self: &mut &'a Self) -> Option<&'a T> {
4490 // FIXME(const-hack): Use `?` when available in const instead of `let-else`.
4491 let Some((last, rem)) = self.split_last() else { return None };
4492 *self = rem;
4493 Some(last)
4494 }
4495
4496 /// Removes the last element of the slice and returns a mutable
4497 /// reference to it.
4498 ///
4499 /// Returns `None` if the slice is empty.
4500 ///
4501 /// # Examples
4502 ///
4503 /// ```
4504 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
4505 /// let last = slice.split_off_last_mut().unwrap();
4506 /// *last = 'd';
4507 ///
4508 /// assert_eq!(slice, &['a', 'b']);
4509 /// assert_eq!(last, &'d');
4510 /// ```
4511 #[inline]
4512 #[stable(feature = "slice_take", since = "1.87.0")]
4513 #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]
4514 pub const fn split_off_last_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {
4515 // FIXME(const-hack): Use `mem::take` and `?` when available in const.
4516 // Original: `mem::take(self).split_last_mut()?`
4517 let Some((last, rem)) = mem::replace(self, &mut []).split_last_mut() else { return None };
4518 *self = rem;
4519 Some(last)
4520 }
4521
4522 /// Returns mutable references to many indices at once, without doing any checks.
4523 ///
4524 /// An index can be either a `usize`, a [`Range`] or a [`RangeInclusive`]. Note
4525 /// that this method takes an array, so all indices must be of the same type.
4526 /// If passed an array of `usize`s this method gives back an array of mutable references
4527 /// to single elements, while if passed an array of ranges it gives back an array of
4528 /// mutable references to slices.
4529 ///
4530 /// For a safe alternative see [`get_disjoint_mut`].
4531 ///
4532 /// # Safety
4533 ///
4534 /// Calling this method with overlapping or out-of-bounds indices is *[undefined behavior]*
4535 /// even if the resulting references are not used.
4536 ///
4537 /// # Examples
4538 ///
4539 /// ```
4540 /// let x = &mut [1, 2, 4];
4541 ///
4542 /// unsafe {
4543 /// let [a, b] = x.get_disjoint_unchecked_mut([0, 2]);
4544 /// *a *= 10;
4545 /// *b *= 100;
4546 /// }
4547 /// assert_eq!(x, &[10, 2, 400]);
4548 ///
4549 /// unsafe {
4550 /// let [a, b] = x.get_disjoint_unchecked_mut([0..1, 1..3]);
4551 /// a[0] = 8;
4552 /// b[0] = 88;
4553 /// b[1] = 888;
4554 /// }
4555 /// assert_eq!(x, &[8, 88, 888]);
4556 ///
4557 /// unsafe {
4558 /// let [a, b] = x.get_disjoint_unchecked_mut([1..=2, 0..=0]);
4559 /// a[0] = 11;
4560 /// a[1] = 111;
4561 /// b[0] = 1;
4562 /// }
4563 /// assert_eq!(x, &[1, 11, 111]);
4564 /// ```
4565 ///
4566 /// [`get_disjoint_mut`]: slice::get_disjoint_mut
4567 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
4568 #[stable(feature = "get_many_mut", since = "1.86.0")]
4569 #[inline]
4570 pub unsafe fn get_disjoint_unchecked_mut<I, const N: usize>(
4571 &mut self,
4572 indices: [I; N],
4573 ) -> [&mut I::Output; N]
4574 where
4575 I: GetDisjointMutIndex + SliceIndex<Self>,
4576 {
4577 // NB: This implementation is written as it is because any variation of
4578 // `indices.map(|i| self.get_unchecked_mut(i))` would make miri unhappy,
4579 // or generate worse code otherwise. This is also why we need to go
4580 // through a raw pointer here.
4581 let slice: *mut [T] = self;
4582 let mut arr: MaybeUninit<[&mut I::Output; N]> = MaybeUninit::uninit();
4583 let arr_ptr = arr.as_mut_ptr();
4584
4585 // SAFETY: We expect `indices` to contain disjunct values that are
4586 // in bounds of `self`.
4587 unsafe {
4588 for i in 0..N {
4589 let idx = indices.get_unchecked(i).clone();
4590 arr_ptr.cast::<&mut I::Output>().add(i).write(&mut *slice.get_unchecked_mut(idx));
4591 }
4592 arr.assume_init()
4593 }
4594 }
4595
4596 /// Returns mutable references to many indices at once.
4597 ///
4598 /// An index can be either a `usize`, a [`Range`] or a [`RangeInclusive`]. Note
4599 /// that this method takes an array, so all indices must be of the same type.
4600 /// If passed an array of `usize`s this method gives back an array of mutable references
4601 /// to single elements, while if passed an array of ranges it gives back an array of
4602 /// mutable references to slices.
4603 ///
4604 /// Returns an error if any index is out-of-bounds, or if there are overlapping indices.
4605 /// An empty range is not considered to overlap if it is located at the beginning or at
4606 /// the end of another range, but is considered to overlap if it is located in the middle.
4607 ///
4608 /// This method does a O(n^2) check to check that there are no overlapping indices, so be careful
4609 /// when passing many indices.
4610 ///
4611 /// # Examples
4612 ///
4613 /// ```
4614 /// let v = &mut [1, 2, 3];
4615 /// if let Ok([a, b]) = v.get_disjoint_mut([0, 2]) {
4616 /// *a = 413;
4617 /// *b = 612;
4618 /// }
4619 /// assert_eq!(v, &[413, 2, 612]);
4620 ///
4621 /// if let Ok([a, b]) = v.get_disjoint_mut([0..1, 1..3]) {
4622 /// a[0] = 8;
4623 /// b[0] = 88;
4624 /// b[1] = 888;
4625 /// }
4626 /// assert_eq!(v, &[8, 88, 888]);
4627 ///
4628 /// if let Ok([a, b]) = v.get_disjoint_mut([1..=2, 0..=0]) {
4629 /// a[0] = 11;
4630 /// a[1] = 111;
4631 /// b[0] = 1;
4632 /// }
4633 /// assert_eq!(v, &[1, 11, 111]);
4634 /// ```
4635 #[stable(feature = "get_many_mut", since = "1.86.0")]
4636 #[inline]
4637 pub fn get_disjoint_mut<I, const N: usize>(
4638 &mut self,
4639 indices: [I; N],
4640 ) -> Result<[&mut I::Output; N], GetDisjointMutError>
4641 where
4642 I: GetDisjointMutIndex + SliceIndex<Self>,
4643 {
4644 get_disjoint_check_valid(&indices, self.len())?;
4645 // SAFETY: The `get_disjoint_check_valid()` call checked that all indices
4646 // are disjunct and in bounds.
4647 unsafe { Ok(self.get_disjoint_unchecked_mut(indices)) }
4648 }
4649
4650 /// Returns the index that an element reference points to.
4651 ///
4652 /// Returns `None` if `element` does not point to the start of an element within the slice.
4653 ///
4654 /// This method is useful for extending slice iterators like [`slice::split`].
4655 ///
4656 /// Note that this uses pointer arithmetic and **does not compare elements**.
4657 /// To find the index of an element via comparison, use
4658 /// [`.iter().position()`](crate::iter::Iterator::position) instead.
4659 ///
4660 /// # Panics
4661 /// Panics if `T` is zero-sized.
4662 ///
4663 /// # Examples
4664 /// Basic usage:
4665 /// ```
4666 /// #![feature(substr_range)]
4667 ///
4668 /// let nums: &[u32] = &[1, 7, 1, 1];
4669 /// let num = &nums[2];
4670 ///
4671 /// assert_eq!(num, &1);
4672 /// assert_eq!(nums.element_offset(num), Some(2));
4673 /// ```
4674 /// Returning `None` with an unaligned element:
4675 /// ```
4676 /// #![feature(substr_range)]
4677 ///
4678 /// let arr: &[[u32; 2]] = &[[0, 1], [2, 3]];
4679 /// let flat_arr: &[u32] = arr.as_flattened();
4680 ///
4681 /// let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap();
4682 /// let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap();
4683 ///
4684 /// assert_eq!(ok_elm, &[0, 1]);
4685 /// assert_eq!(weird_elm, &[1, 2]);
4686 ///
4687 /// assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0
4688 /// assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1
4689 /// ```
4690 #[must_use]
4691 #[unstable(feature = "substr_range", issue = "126769")]
4692 pub fn element_offset(&self, element: &T) -> Option<usize> {
4693 if T::IS_ZST {
4694 panic!("elements are zero-sized");
4695 }
4696
4697 let self_start = self.as_ptr().addr();
4698 let elem_start = ptr::from_ref(element).addr();
4699
4700 let byte_offset = elem_start.wrapping_sub(self_start);
4701
4702 if byte_offset % size_of::<T>() != 0 {
4703 return None;
4704 }
4705
4706 let offset = byte_offset / size_of::<T>();
4707
4708 if offset < self.len() { Some(offset) } else { None }
4709 }
4710
4711 /// Returns the range of indices that a subslice points to.
4712 ///
4713 /// Returns `None` if `subslice` does not point within the slice or if it is not aligned with the
4714 /// elements in the slice.
4715 ///
4716 /// This method **does not compare elements**. Instead, this method finds the location in the slice that
4717 /// `subslice` was obtained from. To find the index of a subslice via comparison, instead use
4718 /// [`.windows()`](slice::windows)[`.position()`](crate::iter::Iterator::position).
4719 ///
4720 /// This method is useful for extending slice iterators like [`slice::split`].
4721 ///
4722 /// Note that this may return a false positive (either `Some(0..0)` or `Some(self.len()..self.len())`)
4723 /// if `subslice` has a length of zero and points to the beginning or end of another, separate, slice.
4724 ///
4725 /// # Panics
4726 /// Panics if `T` is zero-sized.
4727 ///
4728 /// # Examples
4729 /// Basic usage:
4730 /// ```
4731 /// #![feature(substr_range)]
4732 ///
4733 /// let nums = &[0, 5, 10, 0, 0, 5];
4734 ///
4735 /// let mut iter = nums
4736 /// .split(|t| *t == 0)
4737 /// .map(|n| nums.subslice_range(n).unwrap());
4738 ///
4739 /// assert_eq!(iter.next(), Some(0..0));
4740 /// assert_eq!(iter.next(), Some(1..3));
4741 /// assert_eq!(iter.next(), Some(4..4));
4742 /// assert_eq!(iter.next(), Some(5..6));
4743 /// ```
4744 #[must_use]
4745 #[unstable(feature = "substr_range", issue = "126769")]
4746 pub fn subslice_range(&self, subslice: &[T]) -> Option<Range<usize>> {
4747 if T::IS_ZST {
4748 panic!("elements are zero-sized");
4749 }
4750
4751 let self_start = self.as_ptr().addr();
4752 let subslice_start = subslice.as_ptr().addr();
4753
4754 let byte_start = subslice_start.wrapping_sub(self_start);
4755
4756 if byte_start % size_of::<T>() != 0 {
4757 return None;
4758 }
4759
4760 let start = byte_start / size_of::<T>();
4761 let end = start.wrapping_add(subslice.len());
4762
4763 if start <= self.len() && end <= self.len() { Some(start..end) } else { None }
4764 }
4765}
4766
4767impl<T> [MaybeUninit<T>] {
4768 /// Transmutes the mutable uninitialized slice to a mutable uninitialized slice of
4769 /// another type, ensuring alignment of the types is maintained.
4770 ///
4771 /// This is a safe wrapper around [`slice::align_to_mut`], so inherits the same
4772 /// guarantees as that method.
4773 ///
4774 /// # Examples
4775 ///
4776 /// ```
4777 /// #![feature(align_to_uninit_mut)]
4778 /// use std::mem::MaybeUninit;
4779 ///
4780 /// pub struct BumpAllocator<'scope> {
4781 /// memory: &'scope mut [MaybeUninit<u8>],
4782 /// }
4783 ///
4784 /// impl<'scope> BumpAllocator<'scope> {
4785 /// pub fn new(memory: &'scope mut [MaybeUninit<u8>]) -> Self {
4786 /// Self { memory }
4787 /// }
4788 /// pub fn try_alloc_uninit<T>(&mut self) -> Option<&'scope mut MaybeUninit<T>> {
4789 /// let first_end = self.memory.as_ptr().align_offset(align_of::<T>()) + size_of::<T>();
4790 /// let prefix = self.memory.split_off_mut(..first_end)?;
4791 /// Some(&mut prefix.align_to_uninit_mut::<T>().1[0])
4792 /// }
4793 /// pub fn try_alloc_u32(&mut self, value: u32) -> Option<&'scope mut u32> {
4794 /// let uninit = self.try_alloc_uninit()?;
4795 /// Some(uninit.write(value))
4796 /// }
4797 /// }
4798 ///
4799 /// let mut memory = [MaybeUninit::<u8>::uninit(); 10];
4800 /// let mut allocator = BumpAllocator::new(&mut memory);
4801 /// let v = allocator.try_alloc_u32(42);
4802 /// assert_eq!(v, Some(&mut 42));
4803 /// ```
4804 #[unstable(feature = "align_to_uninit_mut", issue = "139062")]
4805 #[inline]
4806 #[must_use]
4807 pub fn align_to_uninit_mut<U>(&mut self) -> (&mut Self, &mut [MaybeUninit<U>], &mut Self) {
4808 // SAFETY: `MaybeUninit` is transparent. Correct size and alignment are guaranteed by
4809 // `align_to_mut` itself. Therefore the only thing that we have to ensure for a safe
4810 // `transmute` is that the values are valid for the types involved. But for `MaybeUninit`
4811 // any values are valid, so this operation is safe.
4812 unsafe { self.align_to_mut() }
4813 }
4814}
4815
4816impl<T, const N: usize> [[T; N]] {
4817 /// Takes a `&[[T; N]]`, and flattens it to a `&[T]`.
4818 ///
4819 /// # Panics
4820 ///
4821 /// This panics if the length of the resulting slice would overflow a `usize`.
4822 ///
4823 /// This is only possible when flattening a slice of arrays of zero-sized
4824 /// types, and thus tends to be irrelevant in practice. If
4825 /// `size_of::<T>() > 0`, this will never panic.
4826 ///
4827 /// # Examples
4828 ///
4829 /// ```
4830 /// assert_eq!([[1, 2, 3], [4, 5, 6]].as_flattened(), &[1, 2, 3, 4, 5, 6]);
4831 ///
4832 /// assert_eq!(
4833 /// [[1, 2, 3], [4, 5, 6]].as_flattened(),
4834 /// [[1, 2], [3, 4], [5, 6]].as_flattened(),
4835 /// );
4836 ///
4837 /// let slice_of_empty_arrays: &[[i32; 0]] = &[[], [], [], [], []];
4838 /// assert!(slice_of_empty_arrays.as_flattened().is_empty());
4839 ///
4840 /// let empty_slice_of_arrays: &[[u32; 10]] = &[];
4841 /// assert!(empty_slice_of_arrays.as_flattened().is_empty());
4842 /// ```
4843 #[stable(feature = "slice_flatten", since = "1.80.0")]
4844 #[rustc_const_stable(feature = "const_slice_flatten", since = "1.87.0")]
4845 pub const fn as_flattened(&self) -> &[T] {
4846 let len = if T::IS_ZST {
4847 self.len().checked_mul(N).expect("slice len overflow")
4848 } else {
4849 // SAFETY: `self.len() * N` cannot overflow because `self` is
4850 // already in the address space.
4851 unsafe { self.len().unchecked_mul(N) }
4852 };
4853 // SAFETY: `[T]` is layout-identical to `[T; N]`
4854 unsafe { from_raw_parts(self.as_ptr().cast(), len) }
4855 }
4856
4857 /// Takes a `&mut [[T; N]]`, and flattens it to a `&mut [T]`.
4858 ///
4859 /// # Panics
4860 ///
4861 /// This panics if the length of the resulting slice would overflow a `usize`.
4862 ///
4863 /// This is only possible when flattening a slice of arrays of zero-sized
4864 /// types, and thus tends to be irrelevant in practice. If
4865 /// `size_of::<T>() > 0`, this will never panic.
4866 ///
4867 /// # Examples
4868 ///
4869 /// ```
4870 /// fn add_5_to_all(slice: &mut [i32]) {
4871 /// for i in slice {
4872 /// *i += 5;
4873 /// }
4874 /// }
4875 ///
4876 /// let mut array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
4877 /// add_5_to_all(array.as_flattened_mut());
4878 /// assert_eq!(array, [[6, 7, 8], [9, 10, 11], [12, 13, 14]]);
4879 /// ```
4880 #[stable(feature = "slice_flatten", since = "1.80.0")]
4881 #[rustc_const_stable(feature = "const_slice_flatten", since = "1.87.0")]
4882 pub const fn as_flattened_mut(&mut self) -> &mut [T] {
4883 let len = if T::IS_ZST {
4884 self.len().checked_mul(N).expect("slice len overflow")
4885 } else {
4886 // SAFETY: `self.len() * N` cannot overflow because `self` is
4887 // already in the address space.
4888 unsafe { self.len().unchecked_mul(N) }
4889 };
4890 // SAFETY: `[T]` is layout-identical to `[T; N]`
4891 unsafe { from_raw_parts_mut(self.as_mut_ptr().cast(), len) }
4892 }
4893}
4894
4895impl [f32] {
4896 /// Sorts the slice of floats.
4897 ///
4898 /// This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses
4899 /// the ordering defined by [`f32::total_cmp`].
4900 ///
4901 /// # Current implementation
4902 ///
4903 /// This uses the same sorting algorithm as [`sort_unstable_by`](slice::sort_unstable_by).
4904 ///
4905 /// # Examples
4906 ///
4907 /// ```
4908 /// #![feature(sort_floats)]
4909 /// let mut v = [2.6, -5e-8, f32::NAN, 8.29, f32::INFINITY, -1.0, 0.0, -f32::INFINITY, -0.0];
4910 ///
4911 /// v.sort_floats();
4912 /// let sorted = [-f32::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f32::INFINITY, f32::NAN];
4913 /// assert_eq!(&v[..8], &sorted[..8]);
4914 /// assert!(v[8].is_nan());
4915 /// ```
4916 #[unstable(feature = "sort_floats", issue = "93396")]
4917 #[inline]
4918 pub fn sort_floats(&mut self) {
4919 self.sort_unstable_by(f32::total_cmp);
4920 }
4921}
4922
4923impl [f64] {
4924 /// Sorts the slice of floats.
4925 ///
4926 /// This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses
4927 /// the ordering defined by [`f64::total_cmp`].
4928 ///
4929 /// # Current implementation
4930 ///
4931 /// This uses the same sorting algorithm as [`sort_unstable_by`](slice::sort_unstable_by).
4932 ///
4933 /// # Examples
4934 ///
4935 /// ```
4936 /// #![feature(sort_floats)]
4937 /// let mut v = [2.6, -5e-8, f64::NAN, 8.29, f64::INFINITY, -1.0, 0.0, -f64::INFINITY, -0.0];
4938 ///
4939 /// v.sort_floats();
4940 /// let sorted = [-f64::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f64::INFINITY, f64::NAN];
4941 /// assert_eq!(&v[..8], &sorted[..8]);
4942 /// assert!(v[8].is_nan());
4943 /// ```
4944 #[unstable(feature = "sort_floats", issue = "93396")]
4945 #[inline]
4946 pub fn sort_floats(&mut self) {
4947 self.sort_unstable_by(f64::total_cmp);
4948 }
4949}
4950
4951trait CloneFromSpec<T> {
4952 fn spec_clone_from(&mut self, src: &[T]);
4953}
4954
4955impl<T> CloneFromSpec<T> for [T]
4956where
4957 T: Clone,
4958{
4959 #[track_caller]
4960 default fn spec_clone_from(&mut self, src: &[T]) {
4961 assert!(self.len() == src.len(), "destination and source slices have different lengths");
4962 // NOTE: We need to explicitly slice them to the same length
4963 // to make it easier for the optimizer to elide bounds checking.
4964 // But since it can't be relied on we also have an explicit specialization for T: Copy.
4965 let len = self.len();
4966 let src = &src[..len];
4967 for i in 0..len {
4968 self[i].clone_from(&src[i]);
4969 }
4970 }
4971}
4972
4973impl<T> CloneFromSpec<T> for [T]
4974where
4975 T: Copy,
4976{
4977 #[track_caller]
4978 fn spec_clone_from(&mut self, src: &[T]) {
4979 self.copy_from_slice(src);
4980 }
4981}
4982
4983#[stable(feature = "rust1", since = "1.0.0")]
4984impl<T> Default for &[T] {
4985 /// Creates an empty slice.
4986 fn default() -> Self {
4987 &[]
4988 }
4989}
4990
4991#[stable(feature = "mut_slice_default", since = "1.5.0")]
4992impl<T> Default for &mut [T] {
4993 /// Creates a mutable empty slice.
4994 fn default() -> Self {
4995 &mut []
4996 }
4997}
4998
4999#[unstable(feature = "slice_pattern", reason = "stopgap trait for slice patterns", issue = "56345")]
5000/// Patterns in slices - currently, only used by `strip_prefix` and `strip_suffix`. At a future
5001/// point, we hope to generalise `core::str::Pattern` (which at the time of writing is limited to
5002/// `str`) to slices, and then this trait will be replaced or abolished.
5003pub trait SlicePattern {
5004 /// The element type of the slice being matched on.
5005 type Item;
5006
5007 /// Currently, the consumers of `SlicePattern` need a slice.
5008 fn as_slice(&self) -> &[Self::Item];
5009}
5010
5011#[stable(feature = "slice_strip", since = "1.51.0")]
5012impl<T> SlicePattern for [T] {
5013 type Item = T;
5014
5015 #[inline]
5016 fn as_slice(&self) -> &[Self::Item] {
5017 self
5018 }
5019}
5020
5021#[stable(feature = "slice_strip", since = "1.51.0")]
5022impl<T, const N: usize> SlicePattern for [T; N] {
5023 type Item = T;
5024
5025 #[inline]
5026 fn as_slice(&self) -> &[Self::Item] {
5027 self
5028 }
5029}
5030
5031/// This checks every index against each other, and against `len`.
5032///
5033/// This will do `binomial(N + 1, 2) = N * (N + 1) / 2 = 0, 1, 3, 6, 10, ..`
5034/// comparison operations.
5035#[inline]
5036fn get_disjoint_check_valid<I: GetDisjointMutIndex, const N: usize>(
5037 indices: &[I; N],
5038 len: usize,
5039) -> Result<(), GetDisjointMutError> {
5040 // NB: The optimizer should inline the loops into a sequence
5041 // of instructions without additional branching.
5042 for (i, idx) in indices.iter().enumerate() {
5043 if !idx.is_in_bounds(len) {
5044 return Err(GetDisjointMutError::IndexOutOfBounds);
5045 }
5046 for idx2 in &indices[..i] {
5047 if idx.is_overlapping(idx2) {
5048 return Err(GetDisjointMutError::OverlappingIndices);
5049 }
5050 }
5051 }
5052 Ok(())
5053}
5054
5055/// The error type returned by [`get_disjoint_mut`][`slice::get_disjoint_mut`].
5056///
5057/// It indicates one of two possible errors:
5058/// - An index is out-of-bounds.
5059/// - The same index appeared multiple times in the array
5060/// (or different but overlapping indices when ranges are provided).
5061///
5062/// # Examples
5063///
5064/// ```
5065/// use std::slice::GetDisjointMutError;
5066///
5067/// let v = &mut [1, 2, 3];
5068/// assert_eq!(v.get_disjoint_mut([0, 999]), Err(GetDisjointMutError::IndexOutOfBounds));
5069/// assert_eq!(v.get_disjoint_mut([1, 1]), Err(GetDisjointMutError::OverlappingIndices));
5070/// ```
5071#[stable(feature = "get_many_mut", since = "1.86.0")]
5072#[derive(Debug, Clone, PartialEq, Eq)]
5073pub enum GetDisjointMutError {
5074 /// An index provided was out-of-bounds for the slice.
5075 IndexOutOfBounds,
5076 /// Two indices provided were overlapping.
5077 OverlappingIndices,
5078}
5079
5080#[stable(feature = "get_many_mut", since = "1.86.0")]
5081impl fmt::Display for GetDisjointMutError {
5082 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5083 let msg = match self {
5084 GetDisjointMutError::IndexOutOfBounds => "an index is out of bounds",
5085 GetDisjointMutError::OverlappingIndices => "there were overlapping indices",
5086 };
5087 fmt::Display::fmt(msg, f)
5088 }
5089}
5090
5091mod private_get_disjoint_mut_index {
5092 use super::{Range, RangeInclusive, range};
5093
5094 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5095 pub trait Sealed {}
5096
5097 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5098 impl Sealed for usize {}
5099 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5100 impl Sealed for Range<usize> {}
5101 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5102 impl Sealed for RangeInclusive<usize> {}
5103 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5104 impl Sealed for range::Range<usize> {}
5105 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5106 impl Sealed for range::RangeInclusive<usize> {}
5107}
5108
5109/// A helper trait for `<[T]>::get_disjoint_mut()`.
5110///
5111/// # Safety
5112///
5113/// If `is_in_bounds()` returns `true` and `is_overlapping()` returns `false`,
5114/// it must be safe to index the slice with the indices.
5115#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5116pub unsafe trait GetDisjointMutIndex:
5117 Clone + private_get_disjoint_mut_index::Sealed
5118{
5119 /// Returns `true` if `self` is in bounds for `len` slice elements.
5120 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5121 fn is_in_bounds(&self, len: usize) -> bool;
5122
5123 /// Returns `true` if `self` overlaps with `other`.
5124 ///
5125 /// Note that we don't consider zero-length ranges to overlap at the beginning or the end,
5126 /// but do consider them to overlap in the middle.
5127 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5128 fn is_overlapping(&self, other: &Self) -> bool;
5129}
5130
5131#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5132// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5133unsafe impl GetDisjointMutIndex for usize {
5134 #[inline]
5135 fn is_in_bounds(&self, len: usize) -> bool {
5136 *self < len
5137 }
5138
5139 #[inline]
5140 fn is_overlapping(&self, other: &Self) -> bool {
5141 *self == *other
5142 }
5143}
5144
5145#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5146// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5147unsafe impl GetDisjointMutIndex for Range<usize> {
5148 #[inline]
5149 fn is_in_bounds(&self, len: usize) -> bool {
5150 (self.start <= self.end) & (self.end <= len)
5151 }
5152
5153 #[inline]
5154 fn is_overlapping(&self, other: &Self) -> bool {
5155 (self.start < other.end) & (other.start < self.end)
5156 }
5157}
5158
5159#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5160// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5161unsafe impl GetDisjointMutIndex for RangeInclusive<usize> {
5162 #[inline]
5163 fn is_in_bounds(&self, len: usize) -> bool {
5164 (self.start <= self.end) & (self.end < len)
5165 }
5166
5167 #[inline]
5168 fn is_overlapping(&self, other: &Self) -> bool {
5169 (self.start <= other.end) & (other.start <= self.end)
5170 }
5171}
5172
5173#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5174// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5175unsafe impl GetDisjointMutIndex for range::Range<usize> {
5176 #[inline]
5177 fn is_in_bounds(&self, len: usize) -> bool {
5178 Range::from(*self).is_in_bounds(len)
5179 }
5180
5181 #[inline]
5182 fn is_overlapping(&self, other: &Self) -> bool {
5183 Range::from(*self).is_overlapping(&Range::from(*other))
5184 }
5185}
5186
5187#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5188// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5189unsafe impl GetDisjointMutIndex for range::RangeInclusive<usize> {
5190 #[inline]
5191 fn is_in_bounds(&self, len: usize) -> bool {
5192 RangeInclusive::from(*self).is_in_bounds(len)
5193 }
5194
5195 #[inline]
5196 fn is_overlapping(&self, other: &Self) -> bool {
5197 RangeInclusive::from(*self).is_overlapping(&RangeInclusive::from(*other))
5198 }
5199}