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