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