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