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