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