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