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