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