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