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 prefix and suffix removed.
2813 ///
2814 /// If the slice starts with `prefix` and ends with `suffix`, returns the subslice after the
2815 /// prefix and before the suffix, wrapped in `Some`.
2816 ///
2817 /// If the slice does not start with `prefix` or does not end with `suffix`, returns `None`.
2818 ///
2819 /// # Examples
2820 ///
2821 /// ```
2822 /// #![feature(strip_circumfix)]
2823 ///
2824 /// let v = &[10, 50, 40, 30];
2825 /// assert_eq!(v.strip_circumfix(&[10], &[30]), Some(&[50, 40][..]));
2826 /// assert_eq!(v.strip_circumfix(&[10], &[40, 30]), Some(&[50][..]));
2827 /// assert_eq!(v.strip_circumfix(&[10, 50], &[40, 30]), Some(&[][..]));
2828 /// assert_eq!(v.strip_circumfix(&[50], &[30]), None);
2829 /// assert_eq!(v.strip_circumfix(&[10], &[40]), None);
2830 /// assert_eq!(v.strip_circumfix(&[], &[40, 30]), Some(&[10, 50][..]));
2831 /// assert_eq!(v.strip_circumfix(&[10, 50], &[]), Some(&[40, 30][..]));
2832 /// ```
2833 #[must_use = "returns the subslice without modifying the original"]
2834 #[unstable(feature = "strip_circumfix", issue = "147946")]
2835 #[cfg(not(feature = "ferrocene_certified"))]
2836 pub fn strip_circumfix<S, P>(&self, prefix: &P, suffix: &S) -> Option<&[T]>
2837 where
2838 T: PartialEq,
2839 S: SlicePattern<Item = T> + ?Sized,
2840 P: SlicePattern<Item = T> + ?Sized,
2841 {
2842 self.strip_prefix(prefix)?.strip_suffix(suffix)
2843 }
2844
2845 /// Returns a subslice with the optional prefix removed.
2846 ///
2847 /// If the slice starts with `prefix`, returns the subslice after the prefix. If `prefix`
2848 /// is empty or the slice does not start with `prefix`, simply returns the original slice.
2849 /// If `prefix` is equal to the original slice, returns an empty slice.
2850 ///
2851 /// # Examples
2852 ///
2853 /// ```
2854 /// #![feature(trim_prefix_suffix)]
2855 ///
2856 /// let v = &[10, 40, 30];
2857 ///
2858 /// // Prefix present - removes it
2859 /// assert_eq!(v.trim_prefix(&[10]), &[40, 30][..]);
2860 /// assert_eq!(v.trim_prefix(&[10, 40]), &[30][..]);
2861 /// assert_eq!(v.trim_prefix(&[10, 40, 30]), &[][..]);
2862 ///
2863 /// // Prefix absent - returns original slice
2864 /// assert_eq!(v.trim_prefix(&[50]), &[10, 40, 30][..]);
2865 /// assert_eq!(v.trim_prefix(&[10, 50]), &[10, 40, 30][..]);
2866 ///
2867 /// let prefix : &str = "he";
2868 /// assert_eq!(b"hello".trim_prefix(prefix.as_bytes()), b"llo".as_ref());
2869 /// ```
2870 #[must_use = "returns the subslice without modifying the original"]
2871 #[unstable(feature = "trim_prefix_suffix", issue = "142312")]
2872 #[cfg(not(feature = "ferrocene_certified"))]
2873 pub fn trim_prefix<P: SlicePattern<Item = T> + ?Sized>(&self, prefix: &P) -> &[T]
2874 where
2875 T: PartialEq,
2876 {
2877 // This function will need rewriting if and when SlicePattern becomes more sophisticated.
2878 let prefix = prefix.as_slice();
2879 let n = prefix.len();
2880 if n <= self.len() {
2881 let (head, tail) = self.split_at(n);
2882 if head == prefix {
2883 return tail;
2884 }
2885 }
2886 self
2887 }
2888
2889 /// Returns a subslice with the optional suffix removed.
2890 ///
2891 /// If the slice ends with `suffix`, returns the subslice before the suffix. If `suffix`
2892 /// is empty or the slice does not end with `suffix`, simply returns the original slice.
2893 /// If `suffix` is equal to the original slice, returns an empty slice.
2894 ///
2895 /// # Examples
2896 ///
2897 /// ```
2898 /// #![feature(trim_prefix_suffix)]
2899 ///
2900 /// let v = &[10, 40, 30];
2901 ///
2902 /// // Suffix present - removes it
2903 /// assert_eq!(v.trim_suffix(&[30]), &[10, 40][..]);
2904 /// assert_eq!(v.trim_suffix(&[40, 30]), &[10][..]);
2905 /// assert_eq!(v.trim_suffix(&[10, 40, 30]), &[][..]);
2906 ///
2907 /// // Suffix absent - returns original slice
2908 /// assert_eq!(v.trim_suffix(&[50]), &[10, 40, 30][..]);
2909 /// assert_eq!(v.trim_suffix(&[50, 30]), &[10, 40, 30][..]);
2910 /// ```
2911 #[must_use = "returns the subslice without modifying the original"]
2912 #[unstable(feature = "trim_prefix_suffix", issue = "142312")]
2913 #[cfg(not(feature = "ferrocene_certified"))]
2914 pub fn trim_suffix<P: SlicePattern<Item = T> + ?Sized>(&self, suffix: &P) -> &[T]
2915 where
2916 T: PartialEq,
2917 {
2918 // This function will need rewriting if and when SlicePattern becomes more sophisticated.
2919 let suffix = suffix.as_slice();
2920 let (len, n) = (self.len(), suffix.len());
2921 if n <= len {
2922 let (head, tail) = self.split_at(len - n);
2923 if tail == suffix {
2924 return head;
2925 }
2926 }
2927 self
2928 }
2929
2930 /// Binary searches this slice for a given element.
2931 /// If the slice is not sorted, the returned result is unspecified and
2932 /// meaningless.
2933 ///
2934 /// If the value is found then [`Result::Ok`] is returned, containing the
2935 /// index of the matching element. If there are multiple matches, then any
2936 /// one of the matches could be returned. The index is chosen
2937 /// deterministically, but is subject to change in future versions of Rust.
2938 /// If the value is not found then [`Result::Err`] is returned, containing
2939 /// the index where a matching element could be inserted while maintaining
2940 /// sorted order.
2941 ///
2942 /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
2943 ///
2944 /// [`binary_search_by`]: slice::binary_search_by
2945 /// [`binary_search_by_key`]: slice::binary_search_by_key
2946 /// [`partition_point`]: slice::partition_point
2947 ///
2948 /// # Examples
2949 ///
2950 /// Looks up a series of four elements. The first is found, with a
2951 /// uniquely determined position; the second and third are not
2952 /// found; the fourth could match any position in `[1, 4]`.
2953 ///
2954 /// ```
2955 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2956 ///
2957 /// assert_eq!(s.binary_search(&13), Ok(9));
2958 /// assert_eq!(s.binary_search(&4), Err(7));
2959 /// assert_eq!(s.binary_search(&100), Err(13));
2960 /// let r = s.binary_search(&1);
2961 /// assert!(match r { Ok(1..=4) => true, _ => false, });
2962 /// ```
2963 ///
2964 /// If you want to find that whole *range* of matching items, rather than
2965 /// an arbitrary matching one, that can be done using [`partition_point`]:
2966 /// ```
2967 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2968 ///
2969 /// let low = s.partition_point(|x| x < &1);
2970 /// assert_eq!(low, 1);
2971 /// let high = s.partition_point(|x| x <= &1);
2972 /// assert_eq!(high, 5);
2973 /// let r = s.binary_search(&1);
2974 /// assert!((low..high).contains(&r.unwrap()));
2975 ///
2976 /// assert!(s[..low].iter().all(|&x| x < 1));
2977 /// assert!(s[low..high].iter().all(|&x| x == 1));
2978 /// assert!(s[high..].iter().all(|&x| x > 1));
2979 ///
2980 /// // For something not found, the "range" of equal items is empty
2981 /// assert_eq!(s.partition_point(|x| x < &11), 9);
2982 /// assert_eq!(s.partition_point(|x| x <= &11), 9);
2983 /// assert_eq!(s.binary_search(&11), Err(9));
2984 /// ```
2985 ///
2986 /// If you want to insert an item to a sorted vector, while maintaining
2987 /// sort order, consider using [`partition_point`]:
2988 ///
2989 /// ```
2990 /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
2991 /// let num = 42;
2992 /// let idx = s.partition_point(|&x| x <= num);
2993 /// // If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to
2994 /// // `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` will allow `insert`
2995 /// // to shift less elements.
2996 /// s.insert(idx, num);
2997 /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2998 /// ```
2999 #[stable(feature = "rust1", since = "1.0.0")]
3000 #[cfg(not(feature = "ferrocene_certified"))]
3001 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
3002 where
3003 T: Ord,
3004 {
3005 self.binary_search_by(|p| p.cmp(x))
3006 }
3007
3008 /// Binary searches this slice with a comparator function.
3009 ///
3010 /// The comparator function should return an order code that indicates
3011 /// whether its argument is `Less`, `Equal` or `Greater` the desired
3012 /// target.
3013 /// If the slice is not sorted or if the comparator function does not
3014 /// implement an order consistent with the sort order of the underlying
3015 /// slice, the returned result is unspecified and meaningless.
3016 ///
3017 /// If the value is found then [`Result::Ok`] is returned, containing the
3018 /// index of the matching element. If there are multiple matches, then any
3019 /// one of the matches could be returned. The index is chosen
3020 /// deterministically, but is subject to change in future versions of Rust.
3021 /// If the value is not found then [`Result::Err`] is returned, containing
3022 /// the index where a matching element could be inserted while maintaining
3023 /// sorted order.
3024 ///
3025 /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
3026 ///
3027 /// [`binary_search`]: slice::binary_search
3028 /// [`binary_search_by_key`]: slice::binary_search_by_key
3029 /// [`partition_point`]: slice::partition_point
3030 ///
3031 /// # Examples
3032 ///
3033 /// Looks up a series of four elements. The first is found, with a
3034 /// uniquely determined position; the second and third are not
3035 /// found; the fourth could match any position in `[1, 4]`.
3036 ///
3037 /// ```
3038 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
3039 ///
3040 /// let seek = 13;
3041 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
3042 /// let seek = 4;
3043 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
3044 /// let seek = 100;
3045 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
3046 /// let seek = 1;
3047 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
3048 /// assert!(match r { Ok(1..=4) => true, _ => false, });
3049 /// ```
3050 #[stable(feature = "rust1", since = "1.0.0")]
3051 #[inline]
3052 #[cfg(not(feature = "ferrocene_certified"))]
3053 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
3054 where
3055 F: FnMut(&'a T) -> Ordering,
3056 {
3057 let mut size = self.len();
3058 if size == 0 {
3059 return Err(0);
3060 }
3061 let mut base = 0usize;
3062
3063 // This loop intentionally doesn't have an early exit if the comparison
3064 // returns Equal. We want the number of loop iterations to depend *only*
3065 // on the size of the input slice so that the CPU can reliably predict
3066 // the loop count.
3067 while size > 1 {
3068 let half = size / 2;
3069 let mid = base + half;
3070
3071 // SAFETY: the call is made safe by the following invariants:
3072 // - `mid >= 0`: by definition
3073 // - `mid < size`: `mid = size / 2 + size / 4 + size / 8 ...`
3074 let cmp = f(unsafe { self.get_unchecked(mid) });
3075
3076 // Binary search interacts poorly with branch prediction, so force
3077 // the compiler to use conditional moves if supported by the target
3078 // architecture.
3079 base = hint::select_unpredictable(cmp == Greater, base, mid);
3080
3081 // This is imprecise in the case where `size` is odd and the
3082 // comparison returns Greater: the mid element still gets included
3083 // by `size` even though it's known to be larger than the element
3084 // being searched for.
3085 //
3086 // This is fine though: we gain more performance by keeping the
3087 // loop iteration count invariant (and thus predictable) than we
3088 // lose from considering one additional element.
3089 size -= half;
3090 }
3091
3092 // SAFETY: base is always in [0, size) because base <= mid.
3093 let cmp = f(unsafe { self.get_unchecked(base) });
3094 if cmp == Equal {
3095 // SAFETY: same as the `get_unchecked` above.
3096 unsafe { hint::assert_unchecked(base < self.len()) };
3097 Ok(base)
3098 } else {
3099 let result = base + (cmp == Less) as usize;
3100 // SAFETY: same as the `get_unchecked` above.
3101 // Note that this is `<=`, unlike the assume in the `Ok` path.
3102 unsafe { hint::assert_unchecked(result <= self.len()) };
3103 Err(result)
3104 }
3105 }
3106
3107 /// Binary searches this slice with a key extraction function.
3108 ///
3109 /// Assumes that the slice is sorted by the key, for instance with
3110 /// [`sort_by_key`] using the same key extraction function.
3111 /// If the slice is not sorted by the key, the returned result is
3112 /// unspecified and meaningless.
3113 ///
3114 /// If the value is found then [`Result::Ok`] is returned, containing the
3115 /// index of the matching element. If there are multiple matches, then any
3116 /// one of the matches could be returned. The index is chosen
3117 /// deterministically, but is subject to change in future versions of Rust.
3118 /// If the value is not found then [`Result::Err`] is returned, containing
3119 /// the index where a matching element could be inserted while maintaining
3120 /// sorted order.
3121 ///
3122 /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
3123 ///
3124 /// [`sort_by_key`]: slice::sort_by_key
3125 /// [`binary_search`]: slice::binary_search
3126 /// [`binary_search_by`]: slice::binary_search_by
3127 /// [`partition_point`]: slice::partition_point
3128 ///
3129 /// # Examples
3130 ///
3131 /// Looks up a series of four elements in a slice of pairs sorted by
3132 /// their second elements. The first is found, with a uniquely
3133 /// determined position; the second and third are not found; the
3134 /// fourth could match any position in `[1, 4]`.
3135 ///
3136 /// ```
3137 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
3138 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
3139 /// (1, 21), (2, 34), (4, 55)];
3140 ///
3141 /// assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
3142 /// assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b), Err(7));
3143 /// assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
3144 /// let r = s.binary_search_by_key(&1, |&(a, b)| b);
3145 /// assert!(match r { Ok(1..=4) => true, _ => false, });
3146 /// ```
3147 // Lint rustdoc::broken_intra_doc_links is allowed as `slice::sort_by_key` is
3148 // in crate `alloc`, and as such doesn't exists yet when building `core`: #74481.
3149 // This breaks links when slice is displayed in core, but changing it to use relative links
3150 // would break when the item is re-exported. So allow the core links to be broken for now.
3151 #[allow(rustdoc::broken_intra_doc_links)]
3152 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
3153 #[inline]
3154 #[cfg(not(feature = "ferrocene_certified"))]
3155 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
3156 where
3157 F: FnMut(&'a T) -> B,
3158 B: Ord,
3159 {
3160 self.binary_search_by(|k| f(k).cmp(b))
3161 }
3162
3163 /// Sorts the slice in ascending order **without** preserving the initial order of equal elements.
3164 ///
3165 /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not
3166 /// allocate), and *O*(*n* \* log(*n*)) worst-case.
3167 ///
3168 /// If the implementation of [`Ord`] for `T` does not implement a [total order], the function
3169 /// may panic; even if the function exits normally, the resulting order of elements in the slice
3170 /// is unspecified. See also the note on panicking below.
3171 ///
3172 /// For example `|a, b| (a - b).cmp(a)` is a comparison function that is neither transitive nor
3173 /// reflexive nor total, `a < b < c < a` with `a = 1, b = 2, c = 3`. For more information and
3174 /// examples see the [`Ord`] documentation.
3175 ///
3176 ///
3177 /// All original elements will remain in the slice and any possible modifications via interior
3178 /// mutability are observed in the input. Same is true if the implementation of [`Ord`] for `T` panics.
3179 ///
3180 /// Sorting types that only implement [`PartialOrd`] such as [`f32`] and [`f64`] require
3181 /// additional precautions. For example, `f32::NAN != f32::NAN`, which doesn't fulfill the
3182 /// reflexivity requirement of [`Ord`]. By using an alternative comparison function with
3183 /// `slice::sort_unstable_by` such as [`f32::total_cmp`] or [`f64::total_cmp`] that defines a
3184 /// [total order] users can sort slices containing floating-point values. Alternatively, if all
3185 /// values in the slice are guaranteed to be in a subset for which [`PartialOrd::partial_cmp`]
3186 /// forms a [total order], it's possible to sort the slice with `sort_unstable_by(|a, b|
3187 /// a.partial_cmp(b).unwrap())`.
3188 ///
3189 /// # Current implementation
3190 ///
3191 /// The current implementation is based on [ipnsort] by Lukas Bergdoll and Orson Peters, which
3192 /// combines the fast average case of quicksort with the fast worst case of heapsort, achieving
3193 /// linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the
3194 /// expected time to sort the data is *O*(*n* \* log(*k*)).
3195 ///
3196 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
3197 /// slice is partially sorted.
3198 ///
3199 /// # Panics
3200 ///
3201 /// May panic if the implementation of [`Ord`] for `T` does not implement a [total order], or if
3202 /// the [`Ord`] implementation panics.
3203 ///
3204 /// # Examples
3205 ///
3206 /// ```
3207 /// let mut v = [4, -5, 1, -3, 2];
3208 ///
3209 /// v.sort_unstable();
3210 /// assert_eq!(v, [-5, -3, 1, 2, 4]);
3211 /// ```
3212 ///
3213 /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort
3214 /// [total order]: https://en.wikipedia.org/wiki/Total_order
3215 #[stable(feature = "sort_unstable", since = "1.20.0")]
3216 #[inline]
3217 #[cfg(not(feature = "ferrocene_certified"))]
3218 pub fn sort_unstable(&mut self)
3219 where
3220 T: Ord,
3221 {
3222 sort::unstable::sort(self, &mut T::lt);
3223 }
3224
3225 /// Sorts the slice in ascending order with a comparison function, **without** preserving the
3226 /// initial order of equal elements.
3227 ///
3228 /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not
3229 /// allocate), and *O*(*n* \* log(*n*)) worst-case.
3230 ///
3231 /// If the comparison function `compare` does not implement a [total order], the function
3232 /// may panic; even if the function exits normally, the resulting order of elements in the slice
3233 /// is unspecified. See also the note on panicking below.
3234 ///
3235 /// For example `|a, b| (a - b).cmp(a)` is a comparison function that is neither transitive nor
3236 /// reflexive nor total, `a < b < c < a` with `a = 1, b = 2, c = 3`. For more information and
3237 /// examples see the [`Ord`] documentation.
3238 ///
3239 /// All original elements will remain in the slice and any possible modifications via interior
3240 /// mutability are observed in the input. Same is true if `compare` panics.
3241 ///
3242 /// # Current implementation
3243 ///
3244 /// The current implementation is based on [ipnsort] by Lukas Bergdoll and Orson Peters, which
3245 /// combines the fast average case of quicksort with the fast worst case of heapsort, achieving
3246 /// linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the
3247 /// expected time to sort the data is *O*(*n* \* log(*k*)).
3248 ///
3249 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
3250 /// slice is partially sorted.
3251 ///
3252 /// # Panics
3253 ///
3254 /// May panic if the `compare` does not implement a [total order], or if
3255 /// the `compare` itself panics.
3256 ///
3257 /// # Examples
3258 ///
3259 /// ```
3260 /// let mut v = [4, -5, 1, -3, 2];
3261 /// v.sort_unstable_by(|a, b| a.cmp(b));
3262 /// assert_eq!(v, [-5, -3, 1, 2, 4]);
3263 ///
3264 /// // reverse sorting
3265 /// v.sort_unstable_by(|a, b| b.cmp(a));
3266 /// assert_eq!(v, [4, 2, 1, -3, -5]);
3267 /// ```
3268 ///
3269 /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort
3270 /// [total order]: https://en.wikipedia.org/wiki/Total_order
3271 #[stable(feature = "sort_unstable", since = "1.20.0")]
3272 #[inline]
3273 #[cfg(not(feature = "ferrocene_certified"))]
3274 pub fn sort_unstable_by<F>(&mut self, mut compare: F)
3275 where
3276 F: FnMut(&T, &T) -> Ordering,
3277 {
3278 sort::unstable::sort(self, &mut |a, b| compare(a, b) == Ordering::Less);
3279 }
3280
3281 /// Sorts the slice in ascending order with a key extraction function, **without** preserving
3282 /// the initial order of equal elements.
3283 ///
3284 /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not
3285 /// allocate), and *O*(*n* \* log(*n*)) worst-case.
3286 ///
3287 /// If the implementation of [`Ord`] for `K` does not implement a [total order], the function
3288 /// may panic; even if the function exits normally, the resulting order of elements in the slice
3289 /// is unspecified. See also the note on panicking below.
3290 ///
3291 /// For example `|a, b| (a - b).cmp(a)` is a comparison function that is neither transitive nor
3292 /// reflexive nor total, `a < b < c < a` with `a = 1, b = 2, c = 3`. For more information and
3293 /// examples see the [`Ord`] documentation.
3294 ///
3295 /// All original elements will remain in the slice and any possible modifications via interior
3296 /// mutability are observed in the input. Same is true if the implementation of [`Ord`] for `K` panics.
3297 ///
3298 /// # Current implementation
3299 ///
3300 /// The current implementation is based on [ipnsort] by Lukas Bergdoll and Orson Peters, which
3301 /// combines the fast average case of quicksort with the fast worst case of heapsort, achieving
3302 /// linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the
3303 /// expected time to sort the data is *O*(*n* \* log(*k*)).
3304 ///
3305 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
3306 /// slice is partially sorted.
3307 ///
3308 /// # Panics
3309 ///
3310 /// May panic if the implementation of [`Ord`] for `K` does not implement a [total order], or if
3311 /// the [`Ord`] implementation panics.
3312 ///
3313 /// # Examples
3314 ///
3315 /// ```
3316 /// let mut v = [4i32, -5, 1, -3, 2];
3317 ///
3318 /// v.sort_unstable_by_key(|k| k.abs());
3319 /// assert_eq!(v, [1, 2, -3, 4, -5]);
3320 /// ```
3321 ///
3322 /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort
3323 /// [total order]: https://en.wikipedia.org/wiki/Total_order
3324 #[stable(feature = "sort_unstable", since = "1.20.0")]
3325 #[inline]
3326 #[cfg(not(feature = "ferrocene_certified"))]
3327 pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
3328 where
3329 F: FnMut(&T) -> K,
3330 K: Ord,
3331 {
3332 sort::unstable::sort(self, &mut |a, b| f(a).lt(&f(b)));
3333 }
3334
3335 /// Reorders the slice such that the element at `index` is at a sort-order position. All
3336 /// elements before `index` will be `<=` to this value, and all elements after will be `>=` to
3337 /// it.
3338 ///
3339 /// This reordering is unstable (i.e. any element that compares equal to the nth element may end
3340 /// up at that position), in-place (i.e. does not allocate), and runs in *O*(*n*) time. This
3341 /// function is also known as "kth element" in other libraries.
3342 ///
3343 /// Returns a triple that partitions the reordered slice:
3344 ///
3345 /// * The unsorted subslice before `index`, whose elements all satisfy `x <= self[index]`.
3346 ///
3347 /// * The element at `index`.
3348 ///
3349 /// * The unsorted subslice after `index`, whose elements all satisfy `x >= self[index]`.
3350 ///
3351 /// # Current implementation
3352 ///
3353 /// The current algorithm is an introselect implementation based on [ipnsort] by Lukas Bergdoll
3354 /// and Orson Peters, which is also the basis for [`sort_unstable`]. The fallback algorithm is
3355 /// Median of Medians using Tukey's Ninther for pivot selection, which guarantees linear runtime
3356 /// for all inputs.
3357 ///
3358 /// [`sort_unstable`]: slice::sort_unstable
3359 ///
3360 /// # Panics
3361 ///
3362 /// Panics when `index >= len()`, and so always panics on empty slices.
3363 ///
3364 /// May panic if the implementation of [`Ord`] for `T` does not implement a [total order].
3365 ///
3366 /// # Examples
3367 ///
3368 /// ```
3369 /// let mut v = [-5i32, 4, 2, -3, 1];
3370 ///
3371 /// // Find the items `<=` to the median, the median itself, and the items `>=` to it.
3372 /// let (lesser, median, greater) = v.select_nth_unstable(2);
3373 ///
3374 /// assert!(lesser == [-3, -5] || lesser == [-5, -3]);
3375 /// assert_eq!(median, &mut 1);
3376 /// assert!(greater == [4, 2] || greater == [2, 4]);
3377 ///
3378 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
3379 /// // about the specified index.
3380 /// assert!(v == [-3, -5, 1, 2, 4] ||
3381 /// v == [-5, -3, 1, 2, 4] ||
3382 /// v == [-3, -5, 1, 4, 2] ||
3383 /// v == [-5, -3, 1, 4, 2]);
3384 /// ```
3385 ///
3386 /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort
3387 /// [total order]: https://en.wikipedia.org/wiki/Total_order
3388 #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
3389 #[inline]
3390 #[cfg(not(feature = "ferrocene_certified"))]
3391 pub fn select_nth_unstable(&mut self, index: usize) -> (&mut [T], &mut T, &mut [T])
3392 where
3393 T: Ord,
3394 {
3395 sort::select::partition_at_index(self, index, T::lt)
3396 }
3397
3398 /// Reorders the slice with a comparator function such that the element at `index` is at a
3399 /// sort-order position. All elements before `index` will be `<=` to this value, and all
3400 /// elements after will be `>=` to it, according to the comparator function.
3401 ///
3402 /// This reordering is unstable (i.e. any element that compares equal to the nth element may end
3403 /// up at that position), in-place (i.e. does not allocate), and runs in *O*(*n*) time. This
3404 /// function is also known as "kth element" in other libraries.
3405 ///
3406 /// Returns a triple partitioning the reordered slice:
3407 ///
3408 /// * The unsorted subslice before `index`, whose elements all satisfy
3409 /// `compare(x, self[index]).is_le()`.
3410 ///
3411 /// * The element at `index`.
3412 ///
3413 /// * The unsorted subslice after `index`, whose elements all satisfy
3414 /// `compare(x, self[index]).is_ge()`.
3415 ///
3416 /// # Current implementation
3417 ///
3418 /// The current algorithm is an introselect implementation based on [ipnsort] by Lukas Bergdoll
3419 /// and Orson Peters, which is also the basis for [`sort_unstable`]. The fallback algorithm is
3420 /// Median of Medians using Tukey's Ninther for pivot selection, which guarantees linear runtime
3421 /// for all inputs.
3422 ///
3423 /// [`sort_unstable`]: slice::sort_unstable
3424 ///
3425 /// # Panics
3426 ///
3427 /// Panics when `index >= len()`, and so always panics on empty slices.
3428 ///
3429 /// May panic if `compare` does not implement a [total order].
3430 ///
3431 /// # Examples
3432 ///
3433 /// ```
3434 /// let mut v = [-5i32, 4, 2, -3, 1];
3435 ///
3436 /// // Find the items `>=` to the median, the median itself, and the items `<=` to it, by using
3437 /// // a reversed comparator.
3438 /// let (before, median, after) = v.select_nth_unstable_by(2, |a, b| b.cmp(a));
3439 ///
3440 /// assert!(before == [4, 2] || before == [2, 4]);
3441 /// assert_eq!(median, &mut 1);
3442 /// assert!(after == [-3, -5] || after == [-5, -3]);
3443 ///
3444 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
3445 /// // about the specified index.
3446 /// assert!(v == [2, 4, 1, -5, -3] ||
3447 /// v == [2, 4, 1, -3, -5] ||
3448 /// v == [4, 2, 1, -5, -3] ||
3449 /// v == [4, 2, 1, -3, -5]);
3450 /// ```
3451 ///
3452 /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort
3453 /// [total order]: https://en.wikipedia.org/wiki/Total_order
3454 #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
3455 #[inline]
3456 #[cfg(not(feature = "ferrocene_certified"))]
3457 pub fn select_nth_unstable_by<F>(
3458 &mut self,
3459 index: usize,
3460 mut compare: F,
3461 ) -> (&mut [T], &mut T, &mut [T])
3462 where
3463 F: FnMut(&T, &T) -> Ordering,
3464 {
3465 sort::select::partition_at_index(self, index, |a: &T, b: &T| compare(a, b) == Less)
3466 }
3467
3468 /// Reorders the slice with a key extraction function such that the element at `index` is at a
3469 /// sort-order position. All elements before `index` will have keys `<=` to the key at `index`,
3470 /// and all elements after will have keys `>=` to it.
3471 ///
3472 /// This reordering is unstable (i.e. any element that compares equal to the nth element may end
3473 /// up at that position), in-place (i.e. does not allocate), and runs in *O*(*n*) time. This
3474 /// function is also known as "kth element" in other libraries.
3475 ///
3476 /// Returns a triple partitioning the reordered slice:
3477 ///
3478 /// * The unsorted subslice before `index`, whose elements all satisfy `f(x) <= f(self[index])`.
3479 ///
3480 /// * The element at `index`.
3481 ///
3482 /// * The unsorted subslice after `index`, whose elements all satisfy `f(x) >= f(self[index])`.
3483 ///
3484 /// # Current implementation
3485 ///
3486 /// The current algorithm is an introselect implementation based on [ipnsort] by Lukas Bergdoll
3487 /// and Orson Peters, which is also the basis for [`sort_unstable`]. The fallback algorithm is
3488 /// Median of Medians using Tukey's Ninther for pivot selection, which guarantees linear runtime
3489 /// for all inputs.
3490 ///
3491 /// [`sort_unstable`]: slice::sort_unstable
3492 ///
3493 /// # Panics
3494 ///
3495 /// Panics when `index >= len()`, meaning it always panics on empty slices.
3496 ///
3497 /// May panic if `K: Ord` does not implement a total order.
3498 ///
3499 /// # Examples
3500 ///
3501 /// ```
3502 /// let mut v = [-5i32, 4, 1, -3, 2];
3503 ///
3504 /// // Find the items `<=` to the absolute median, the absolute median itself, and the items
3505 /// // `>=` to it.
3506 /// let (lesser, median, greater) = v.select_nth_unstable_by_key(2, |a| a.abs());
3507 ///
3508 /// assert!(lesser == [1, 2] || lesser == [2, 1]);
3509 /// assert_eq!(median, &mut -3);
3510 /// assert!(greater == [4, -5] || greater == [-5, 4]);
3511 ///
3512 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
3513 /// // about the specified index.
3514 /// assert!(v == [1, 2, -3, 4, -5] ||
3515 /// v == [1, 2, -3, -5, 4] ||
3516 /// v == [2, 1, -3, 4, -5] ||
3517 /// v == [2, 1, -3, -5, 4]);
3518 /// ```
3519 ///
3520 /// [ipnsort]: https://github.com/Voultapher/sort-research-rs/tree/main/ipnsort
3521 /// [total order]: https://en.wikipedia.org/wiki/Total_order
3522 #[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
3523 #[inline]
3524 #[cfg(not(feature = "ferrocene_certified"))]
3525 pub fn select_nth_unstable_by_key<K, F>(
3526 &mut self,
3527 index: usize,
3528 mut f: F,
3529 ) -> (&mut [T], &mut T, &mut [T])
3530 where
3531 F: FnMut(&T) -> K,
3532 K: Ord,
3533 {
3534 sort::select::partition_at_index(self, index, |a: &T, b: &T| f(a).lt(&f(b)))
3535 }
3536
3537 /// Moves all consecutive repeated elements to the end of the slice according to the
3538 /// [`PartialEq`] trait implementation.
3539 ///
3540 /// Returns two slices. The first contains no consecutive repeated elements.
3541 /// The second contains all the duplicates in no specified order.
3542 ///
3543 /// If the slice is sorted, the first returned slice contains no duplicates.
3544 ///
3545 /// # Examples
3546 ///
3547 /// ```
3548 /// #![feature(slice_partition_dedup)]
3549 ///
3550 /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
3551 ///
3552 /// let (dedup, duplicates) = slice.partition_dedup();
3553 ///
3554 /// assert_eq!(dedup, [1, 2, 3, 2, 1]);
3555 /// assert_eq!(duplicates, [2, 3, 1]);
3556 /// ```
3557 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
3558 #[inline]
3559 #[cfg(not(feature = "ferrocene_certified"))]
3560 pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
3561 where
3562 T: PartialEq,
3563 {
3564 self.partition_dedup_by(|a, b| a == b)
3565 }
3566
3567 /// Moves all but the first of consecutive elements to the end of the slice satisfying
3568 /// a given equality relation.
3569 ///
3570 /// Returns two slices. The first contains no consecutive repeated elements.
3571 /// The second contains all the duplicates in no specified order.
3572 ///
3573 /// The `same_bucket` function is passed references to two elements from the slice and
3574 /// must determine if the elements compare equal. The elements are passed in opposite order
3575 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved
3576 /// at the end of the slice.
3577 ///
3578 /// If the slice is sorted, the first returned slice contains no duplicates.
3579 ///
3580 /// # Examples
3581 ///
3582 /// ```
3583 /// #![feature(slice_partition_dedup)]
3584 ///
3585 /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
3586 ///
3587 /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
3588 ///
3589 /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
3590 /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
3591 /// ```
3592 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
3593 #[inline]
3594 #[cfg(not(feature = "ferrocene_certified"))]
3595 pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])
3596 where
3597 F: FnMut(&mut T, &mut T) -> bool,
3598 {
3599 // Although we have a mutable reference to `self`, we cannot make
3600 // *arbitrary* changes. The `same_bucket` calls could panic, so we
3601 // must ensure that the slice is in a valid state at all times.
3602 //
3603 // The way that we handle this is by using swaps; we iterate
3604 // over all the elements, swapping as we go so that at the end
3605 // the elements we wish to keep are in the front, and those we
3606 // wish to reject are at the back. We can then split the slice.
3607 // This operation is still `O(n)`.
3608 //
3609 // Example: We start in this state, where `r` represents "next
3610 // read" and `w` represents "next_write".
3611 //
3612 // r
3613 // +---+---+---+---+---+---+
3614 // | 0 | 1 | 1 | 2 | 3 | 3 |
3615 // +---+---+---+---+---+---+
3616 // w
3617 //
3618 // Comparing self[r] against self[w-1], this is not a duplicate, so
3619 // we swap self[r] and self[w] (no effect as r==w) and then increment both
3620 // r and w, leaving us with:
3621 //
3622 // r
3623 // +---+---+---+---+---+---+
3624 // | 0 | 1 | 1 | 2 | 3 | 3 |
3625 // +---+---+---+---+---+---+
3626 // w
3627 //
3628 // Comparing self[r] against self[w-1], this value is a duplicate,
3629 // so we increment `r` but leave everything else unchanged:
3630 //
3631 // r
3632 // +---+---+---+---+---+---+
3633 // | 0 | 1 | 1 | 2 | 3 | 3 |
3634 // +---+---+---+---+---+---+
3635 // w
3636 //
3637 // Comparing self[r] against self[w-1], this is not a duplicate,
3638 // so swap self[r] and self[w] and advance r and w:
3639 //
3640 // r
3641 // +---+---+---+---+---+---+
3642 // | 0 | 1 | 2 | 1 | 3 | 3 |
3643 // +---+---+---+---+---+---+
3644 // w
3645 //
3646 // Not a duplicate, repeat:
3647 //
3648 // r
3649 // +---+---+---+---+---+---+
3650 // | 0 | 1 | 2 | 3 | 1 | 3 |
3651 // +---+---+---+---+---+---+
3652 // w
3653 //
3654 // Duplicate, advance r. End of slice. Split at w.
3655
3656 let len = self.len();
3657 if len <= 1 {
3658 return (self, &mut []);
3659 }
3660
3661 let ptr = self.as_mut_ptr();
3662 let mut next_read: usize = 1;
3663 let mut next_write: usize = 1;
3664
3665 // SAFETY: the `while` condition guarantees `next_read` and `next_write`
3666 // are less than `len`, thus are inside `self`. `prev_ptr_write` points to
3667 // one element before `ptr_write`, but `next_write` starts at 1, so
3668 // `prev_ptr_write` is never less than 0 and is inside the slice.
3669 // This fulfils the requirements for dereferencing `ptr_read`, `prev_ptr_write`
3670 // and `ptr_write`, and for using `ptr.add(next_read)`, `ptr.add(next_write - 1)`
3671 // and `prev_ptr_write.offset(1)`.
3672 //
3673 // `next_write` is also incremented at most once per loop at most meaning
3674 // no element is skipped when it may need to be swapped.
3675 //
3676 // `ptr_read` and `prev_ptr_write` never point to the same element. This
3677 // is required for `&mut *ptr_read`, `&mut *prev_ptr_write` to be safe.
3678 // The explanation is simply that `next_read >= next_write` is always true,
3679 // thus `next_read > next_write - 1` is too.
3680 unsafe {
3681 // Avoid bounds checks by using raw pointers.
3682 while next_read < len {
3683 let ptr_read = ptr.add(next_read);
3684 let prev_ptr_write = ptr.add(next_write - 1);
3685 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
3686 if next_read != next_write {
3687 let ptr_write = prev_ptr_write.add(1);
3688 mem::swap(&mut *ptr_read, &mut *ptr_write);
3689 }
3690 next_write += 1;
3691 }
3692 next_read += 1;
3693 }
3694 }
3695
3696 self.split_at_mut(next_write)
3697 }
3698
3699 /// Moves all but the first of consecutive elements to the end of the slice that resolve
3700 /// to the same key.
3701 ///
3702 /// Returns two slices. The first contains no consecutive repeated elements.
3703 /// The second contains all the duplicates in no specified order.
3704 ///
3705 /// If the slice is sorted, the first returned slice contains no duplicates.
3706 ///
3707 /// # Examples
3708 ///
3709 /// ```
3710 /// #![feature(slice_partition_dedup)]
3711 ///
3712 /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
3713 ///
3714 /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
3715 ///
3716 /// assert_eq!(dedup, [10, 20, 30, 20, 11]);
3717 /// assert_eq!(duplicates, [21, 30, 13]);
3718 /// ```
3719 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
3720 #[inline]
3721 #[cfg(not(feature = "ferrocene_certified"))]
3722 pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])
3723 where
3724 F: FnMut(&mut T) -> K,
3725 K: PartialEq,
3726 {
3727 self.partition_dedup_by(|a, b| key(a) == key(b))
3728 }
3729
3730 /// Rotates the slice in-place such that the first `mid` elements of the
3731 /// slice move to the end while the last `self.len() - mid` elements move to
3732 /// the front.
3733 ///
3734 /// After calling `rotate_left`, the element previously at index `mid` will
3735 /// become the first element in the slice.
3736 ///
3737 /// # Panics
3738 ///
3739 /// This function will panic if `mid` is greater than the length of the
3740 /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
3741 /// rotation.
3742 ///
3743 /// # Complexity
3744 ///
3745 /// Takes linear (in `self.len()`) time.
3746 ///
3747 /// # Examples
3748 ///
3749 /// ```
3750 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3751 /// a.rotate_left(2);
3752 /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
3753 /// ```
3754 ///
3755 /// Rotating a subslice:
3756 ///
3757 /// ```
3758 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3759 /// a[1..5].rotate_left(1);
3760 /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
3761 /// ```
3762 #[stable(feature = "slice_rotate", since = "1.26.0")]
3763 #[rustc_const_stable(feature = "const_slice_rotate", since = "1.92.0")]
3764 #[cfg(not(feature = "ferrocene_certified"))]
3765 pub const fn rotate_left(&mut self, mid: usize) {
3766 assert!(mid <= self.len());
3767 let k = self.len() - mid;
3768 let p = self.as_mut_ptr();
3769
3770 // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
3771 // valid for reading and writing, as required by `ptr_rotate`.
3772 unsafe {
3773 rotate::ptr_rotate(mid, p.add(mid), k);
3774 }
3775 }
3776
3777 /// Rotates the slice in-place such that the first `self.len() - k`
3778 /// elements of the slice move to the end while the last `k` elements move
3779 /// to the front.
3780 ///
3781 /// After calling `rotate_right`, the element previously at index
3782 /// `self.len() - k` will become the first element in the slice.
3783 ///
3784 /// # Panics
3785 ///
3786 /// This function will panic if `k` is greater than the length of the
3787 /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
3788 /// rotation.
3789 ///
3790 /// # Complexity
3791 ///
3792 /// Takes linear (in `self.len()`) time.
3793 ///
3794 /// # Examples
3795 ///
3796 /// ```
3797 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3798 /// a.rotate_right(2);
3799 /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
3800 /// ```
3801 ///
3802 /// Rotating a subslice:
3803 ///
3804 /// ```
3805 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3806 /// a[1..5].rotate_right(1);
3807 /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
3808 /// ```
3809 #[stable(feature = "slice_rotate", since = "1.26.0")]
3810 #[rustc_const_stable(feature = "const_slice_rotate", since = "1.92.0")]
3811 #[cfg(not(feature = "ferrocene_certified"))]
3812 pub const fn rotate_right(&mut self, k: usize) {
3813 assert!(k <= self.len());
3814 let mid = self.len() - k;
3815 let p = self.as_mut_ptr();
3816
3817 // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
3818 // valid for reading and writing, as required by `ptr_rotate`.
3819 unsafe {
3820 rotate::ptr_rotate(mid, p.add(mid), k);
3821 }
3822 }
3823
3824 /// Fills `self` with elements by cloning `value`.
3825 ///
3826 /// # Examples
3827 ///
3828 /// ```
3829 /// let mut buf = vec![0; 10];
3830 /// buf.fill(1);
3831 /// assert_eq!(buf, vec![1; 10]);
3832 /// ```
3833 #[doc(alias = "memset")]
3834 #[stable(feature = "slice_fill", since = "1.50.0")]
3835 #[cfg(not(feature = "ferrocene_certified"))]
3836 pub fn fill(&mut self, value: T)
3837 where
3838 T: Clone,
3839 {
3840 specialize::SpecFill::spec_fill(self, value);
3841 }
3842
3843 /// Fills `self` with elements returned by calling a closure repeatedly.
3844 ///
3845 /// This method uses a closure to create new values. If you'd rather
3846 /// [`Clone`] a given value, use [`fill`]. If you want to use the [`Default`]
3847 /// trait to generate values, you can pass [`Default::default`] as the
3848 /// argument.
3849 ///
3850 /// [`fill`]: slice::fill
3851 ///
3852 /// # Examples
3853 ///
3854 /// ```
3855 /// let mut buf = vec![1; 10];
3856 /// buf.fill_with(Default::default);
3857 /// assert_eq!(buf, vec![0; 10]);
3858 /// ```
3859 #[stable(feature = "slice_fill_with", since = "1.51.0")]
3860 #[cfg(not(feature = "ferrocene_certified"))]
3861 pub fn fill_with<F>(&mut self, mut f: F)
3862 where
3863 F: FnMut() -> T,
3864 {
3865 for el in self {
3866 *el = f();
3867 }
3868 }
3869
3870 /// Copies the elements from `src` into `self`.
3871 ///
3872 /// The length of `src` must be the same as `self`.
3873 ///
3874 /// # Panics
3875 ///
3876 /// This function will panic if the two slices have different lengths.
3877 ///
3878 /// # Examples
3879 ///
3880 /// Cloning two elements from a slice into another:
3881 ///
3882 /// ```
3883 /// let src = [1, 2, 3, 4];
3884 /// let mut dst = [0, 0];
3885 ///
3886 /// // Because the slices have to be the same length,
3887 /// // we slice the source slice from four elements
3888 /// // to two. It will panic if we don't do this.
3889 /// dst.clone_from_slice(&src[2..]);
3890 ///
3891 /// assert_eq!(src, [1, 2, 3, 4]);
3892 /// assert_eq!(dst, [3, 4]);
3893 /// ```
3894 ///
3895 /// Rust enforces that there can only be one mutable reference with no
3896 /// immutable references to a particular piece of data in a particular
3897 /// scope. Because of this, attempting to use `clone_from_slice` on a
3898 /// single slice will result in a compile failure:
3899 ///
3900 /// ```compile_fail
3901 /// let mut slice = [1, 2, 3, 4, 5];
3902 ///
3903 /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
3904 /// ```
3905 ///
3906 /// To work around this, we can use [`split_at_mut`] to create two distinct
3907 /// sub-slices from a slice:
3908 ///
3909 /// ```
3910 /// let mut slice = [1, 2, 3, 4, 5];
3911 ///
3912 /// {
3913 /// let (left, right) = slice.split_at_mut(2);
3914 /// left.clone_from_slice(&right[1..]);
3915 /// }
3916 ///
3917 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
3918 /// ```
3919 ///
3920 /// [`copy_from_slice`]: slice::copy_from_slice
3921 /// [`split_at_mut`]: slice::split_at_mut
3922 #[stable(feature = "clone_from_slice", since = "1.7.0")]
3923 #[track_caller]
3924 #[cfg(not(feature = "ferrocene_certified"))]
3925 pub fn clone_from_slice(&mut self, src: &[T])
3926 where
3927 T: Clone,
3928 {
3929 self.spec_clone_from(src);
3930 }
3931
3932 /// Copies all elements from `src` into `self`, using a memcpy.
3933 ///
3934 /// The length of `src` must be the same as `self`.
3935 ///
3936 /// If `T` does not implement `Copy`, use [`clone_from_slice`].
3937 ///
3938 /// # Panics
3939 ///
3940 /// This function will panic if the two slices have different lengths.
3941 ///
3942 /// # Examples
3943 ///
3944 /// Copying two elements from a slice into another:
3945 ///
3946 /// ```
3947 /// let src = [1, 2, 3, 4];
3948 /// let mut dst = [0, 0];
3949 ///
3950 /// // Because the slices have to be the same length,
3951 /// // we slice the source slice from four elements
3952 /// // to two. It will panic if we don't do this.
3953 /// dst.copy_from_slice(&src[2..]);
3954 ///
3955 /// assert_eq!(src, [1, 2, 3, 4]);
3956 /// assert_eq!(dst, [3, 4]);
3957 /// ```
3958 ///
3959 /// Rust enforces that there can only be one mutable reference with no
3960 /// immutable references to a particular piece of data in a particular
3961 /// scope. Because of this, attempting to use `copy_from_slice` on a
3962 /// single slice will result in a compile failure:
3963 ///
3964 /// ```compile_fail
3965 /// let mut slice = [1, 2, 3, 4, 5];
3966 ///
3967 /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
3968 /// ```
3969 ///
3970 /// To work around this, we can use [`split_at_mut`] to create two distinct
3971 /// sub-slices from a slice:
3972 ///
3973 /// ```
3974 /// let mut slice = [1, 2, 3, 4, 5];
3975 ///
3976 /// {
3977 /// let (left, right) = slice.split_at_mut(2);
3978 /// left.copy_from_slice(&right[1..]);
3979 /// }
3980 ///
3981 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
3982 /// ```
3983 ///
3984 /// [`clone_from_slice`]: slice::clone_from_slice
3985 /// [`split_at_mut`]: slice::split_at_mut
3986 #[doc(alias = "memcpy")]
3987 #[inline]
3988 #[stable(feature = "copy_from_slice", since = "1.9.0")]
3989 #[rustc_const_stable(feature = "const_copy_from_slice", since = "1.87.0")]
3990 #[track_caller]
3991 pub const fn copy_from_slice(&mut self, src: &[T])
3992 where
3993 T: Copy,
3994 {
3995 // The panic code path was put into a cold function to not bloat the
3996 // call site.
3997 #[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)]
3998 #[cfg_attr(panic = "immediate-abort", inline)]
3999 #[track_caller]
4000 const fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! {
4001 const_panic!(
4002 "copy_from_slice: source slice length does not match destination slice length",
4003 "copy_from_slice: source slice length ({src_len}) does not match destination slice length ({dst_len})",
4004 src_len: usize,
4005 dst_len: usize,
4006 )
4007 }
4008
4009 if self.len() != src.len() {
4010 len_mismatch_fail(self.len(), src.len());
4011 }
4012
4013 // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
4014 // checked to have the same length. The slices cannot overlap because
4015 // mutable references are exclusive.
4016 unsafe {
4017 ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len());
4018 }
4019 }
4020
4021 /// Copies elements from one part of the slice to another part of itself,
4022 /// using a memmove.
4023 ///
4024 /// `src` is the range within `self` to copy from. `dest` is the starting
4025 /// index of the range within `self` to copy to, which will have the same
4026 /// length as `src`. The two ranges may overlap. The ends of the two ranges
4027 /// must be less than or equal to `self.len()`.
4028 ///
4029 /// # Panics
4030 ///
4031 /// This function will panic if either range exceeds the end of the slice,
4032 /// or if the end of `src` is before the start.
4033 ///
4034 /// # Examples
4035 ///
4036 /// Copying four bytes within a slice:
4037 ///
4038 /// ```
4039 /// let mut bytes = *b"Hello, World!";
4040 ///
4041 /// bytes.copy_within(1..5, 8);
4042 ///
4043 /// assert_eq!(&bytes, b"Hello, Wello!");
4044 /// ```
4045 #[stable(feature = "copy_within", since = "1.37.0")]
4046 #[track_caller]
4047 #[cfg(not(feature = "ferrocene_certified"))]
4048 pub fn copy_within<R: RangeBounds<usize>>(&mut self, src: R, dest: usize)
4049 where
4050 T: Copy,
4051 {
4052 let Range { start: src_start, end: src_end } = slice::range(src, ..self.len());
4053 let count = src_end - src_start;
4054 assert!(dest <= self.len() - count, "dest is out of bounds");
4055 // SAFETY: the conditions for `ptr::copy` have all been checked above,
4056 // as have those for `ptr::add`.
4057 unsafe {
4058 // Derive both `src_ptr` and `dest_ptr` from the same loan
4059 let ptr = self.as_mut_ptr();
4060 let src_ptr = ptr.add(src_start);
4061 let dest_ptr = ptr.add(dest);
4062 ptr::copy(src_ptr, dest_ptr, count);
4063 }
4064 }
4065
4066 /// Swaps all elements in `self` with those in `other`.
4067 ///
4068 /// The length of `other` must be the same as `self`.
4069 ///
4070 /// # Panics
4071 ///
4072 /// This function will panic if the two slices have different lengths.
4073 ///
4074 /// # Example
4075 ///
4076 /// Swapping two elements across slices:
4077 ///
4078 /// ```
4079 /// let mut slice1 = [0, 0];
4080 /// let mut slice2 = [1, 2, 3, 4];
4081 ///
4082 /// slice1.swap_with_slice(&mut slice2[2..]);
4083 ///
4084 /// assert_eq!(slice1, [3, 4]);
4085 /// assert_eq!(slice2, [1, 2, 0, 0]);
4086 /// ```
4087 ///
4088 /// Rust enforces that there can only be one mutable reference to a
4089 /// particular piece of data in a particular scope. Because of this,
4090 /// attempting to use `swap_with_slice` on a single slice will result in
4091 /// a compile failure:
4092 ///
4093 /// ```compile_fail
4094 /// let mut slice = [1, 2, 3, 4, 5];
4095 /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
4096 /// ```
4097 ///
4098 /// To work around this, we can use [`split_at_mut`] to create two distinct
4099 /// mutable sub-slices from a slice:
4100 ///
4101 /// ```
4102 /// let mut slice = [1, 2, 3, 4, 5];
4103 ///
4104 /// {
4105 /// let (left, right) = slice.split_at_mut(2);
4106 /// left.swap_with_slice(&mut right[1..]);
4107 /// }
4108 ///
4109 /// assert_eq!(slice, [4, 5, 3, 1, 2]);
4110 /// ```
4111 ///
4112 /// [`split_at_mut`]: slice::split_at_mut
4113 #[stable(feature = "swap_with_slice", since = "1.27.0")]
4114 #[rustc_const_unstable(feature = "const_swap_with_slice", issue = "142204")]
4115 #[track_caller]
4116 #[cfg(not(feature = "ferrocene_certified"))]
4117 pub const fn swap_with_slice(&mut self, other: &mut [T]) {
4118 assert!(self.len() == other.len(), "destination and source slices have different lengths");
4119 // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
4120 // checked to have the same length. The slices cannot overlap because
4121 // mutable references are exclusive.
4122 unsafe {
4123 ptr::swap_nonoverlapping(self.as_mut_ptr(), other.as_mut_ptr(), self.len());
4124 }
4125 }
4126
4127 /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
4128
4129 #[cfg(not(feature = "ferrocene_certified"))]
4130 fn align_to_offsets<U>(&self) -> (usize, usize) {
4131 // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
4132 // lowest number of `T`s. And how many `T`s we need for each such "multiple".
4133 //
4134 // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
4135 // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
4136 // place of every 3 Ts in the `rest` slice. A bit more complicated.
4137 //
4138 // Formula to calculate this is:
4139 //
4140 // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
4141 // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
4142 //
4143 // Expanded and simplified:
4144 //
4145 // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
4146 // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
4147 //
4148 // Luckily since all this is constant-evaluated... performance here matters not!
4149 const fn gcd(a: usize, b: usize) -> usize {
4150 if b == 0 { a } else { gcd(b, a % b) }
4151 }
4152
4153 // Explicitly wrap the function call in a const block so it gets
4154 // constant-evaluated even in debug mode.
4155 let gcd: usize = const { gcd(size_of::<T>(), size_of::<U>()) };
4156 let ts: usize = size_of::<U>() / gcd;
4157 let us: usize = size_of::<T>() / gcd;
4158
4159 // Armed with this knowledge, we can find how many `U`s we can fit!
4160 let us_len = self.len() / ts * us;
4161 // And how many `T`s will be in the trailing slice!
4162 let ts_len = self.len() % ts;
4163 (us_len, ts_len)
4164 }
4165
4166 /// Transmutes the slice to a slice of another type, ensuring alignment of the types is
4167 /// maintained.
4168 ///
4169 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
4170 /// slice of a new type, and the suffix slice. The middle part will be as big as possible under
4171 /// the given alignment constraint and element size.
4172 ///
4173 /// This method has no purpose when either input element `T` or output element `U` are
4174 /// zero-sized and will return the original slice without splitting anything.
4175 ///
4176 /// # Safety
4177 ///
4178 /// This method is essentially a `transmute` with respect to the elements in the returned
4179 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
4180 ///
4181 /// # Examples
4182 ///
4183 /// Basic usage:
4184 ///
4185 /// ```
4186 /// unsafe {
4187 /// let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
4188 /// let (prefix, shorts, suffix) = bytes.align_to::<u16>();
4189 /// // less_efficient_algorithm_for_bytes(prefix);
4190 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
4191 /// // less_efficient_algorithm_for_bytes(suffix);
4192 /// }
4193 /// ```
4194 #[stable(feature = "slice_align_to", since = "1.30.0")]
4195 #[must_use]
4196 #[cfg(not(feature = "ferrocene_certified"))]
4197 pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
4198 // Note that most of this function will be constant-evaluated,
4199 if U::IS_ZST || T::IS_ZST {
4200 // handle ZSTs specially, which is – don't handle them at all.
4201 return (self, &[], &[]);
4202 }
4203
4204 // First, find at what point do we split between the first and 2nd slice. Easy with
4205 // ptr.align_offset.
4206 let ptr = self.as_ptr();
4207 // SAFETY: See the `align_to_mut` method for the detailed safety comment.
4208 let offset = unsafe { crate::ptr::align_offset(ptr, align_of::<U>()) };
4209 if offset > self.len() {
4210 (self, &[], &[])
4211 } else {
4212 let (left, rest) = self.split_at(offset);
4213 let (us_len, ts_len) = rest.align_to_offsets::<U>();
4214 // Inform Miri that we want to consider the "middle" pointer to be suitably aligned.
4215 #[cfg(miri)]
4216 crate::intrinsics::miri_promise_symbolic_alignment(
4217 rest.as_ptr().cast(),
4218 align_of::<U>(),
4219 );
4220 // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay,
4221 // since the caller guarantees that we can transmute `T` to `U` safely.
4222 unsafe {
4223 (
4224 left,
4225 from_raw_parts(rest.as_ptr() as *const U, us_len),
4226 from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len),
4227 )
4228 }
4229 }
4230 }
4231
4232 /// Transmutes the mutable slice to a mutable slice of another type, ensuring alignment of the
4233 /// types is maintained.
4234 ///
4235 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
4236 /// slice of a new type, and the suffix slice. The middle part will be as big as possible under
4237 /// the given alignment constraint and element size.
4238 ///
4239 /// This method has no purpose when either input element `T` or output element `U` are
4240 /// zero-sized and will return the original slice without splitting anything.
4241 ///
4242 /// # Safety
4243 ///
4244 /// This method is essentially a `transmute` with respect to the elements in the returned
4245 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
4246 ///
4247 /// # Examples
4248 ///
4249 /// Basic usage:
4250 ///
4251 /// ```
4252 /// unsafe {
4253 /// let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
4254 /// let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
4255 /// // less_efficient_algorithm_for_bytes(prefix);
4256 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
4257 /// // less_efficient_algorithm_for_bytes(suffix);
4258 /// }
4259 /// ```
4260 #[stable(feature = "slice_align_to", since = "1.30.0")]
4261 #[must_use]
4262 #[cfg(not(feature = "ferrocene_certified"))]
4263 pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
4264 // Note that most of this function will be constant-evaluated,
4265 if U::IS_ZST || T::IS_ZST {
4266 // handle ZSTs specially, which is – don't handle them at all.
4267 return (self, &mut [], &mut []);
4268 }
4269
4270 // First, find at what point do we split between the first and 2nd slice. Easy with
4271 // ptr.align_offset.
4272 let ptr = self.as_ptr();
4273 // SAFETY: Here we are ensuring we will use aligned pointers for U for the
4274 // rest of the method. This is done by passing a pointer to &[T] with an
4275 // alignment targeted for U.
4276 // `crate::ptr::align_offset` is called with a correctly aligned and
4277 // valid pointer `ptr` (it comes from a reference to `self`) and with
4278 // a size that is a power of two (since it comes from the alignment for U),
4279 // satisfying its safety constraints.
4280 let offset = unsafe { crate::ptr::align_offset(ptr, align_of::<U>()) };
4281 if offset > self.len() {
4282 (self, &mut [], &mut [])
4283 } else {
4284 let (left, rest) = self.split_at_mut(offset);
4285 let (us_len, ts_len) = rest.align_to_offsets::<U>();
4286 let rest_len = rest.len();
4287 let mut_ptr = rest.as_mut_ptr();
4288 // Inform Miri that we want to consider the "middle" pointer to be suitably aligned.
4289 #[cfg(miri)]
4290 crate::intrinsics::miri_promise_symbolic_alignment(
4291 mut_ptr.cast() as *const (),
4292 align_of::<U>(),
4293 );
4294 // We can't use `rest` again after this, that would invalidate its alias `mut_ptr`!
4295 // SAFETY: see comments for `align_to`.
4296 unsafe {
4297 (
4298 left,
4299 from_raw_parts_mut(mut_ptr as *mut U, us_len),
4300 from_raw_parts_mut(mut_ptr.add(rest_len - ts_len), ts_len),
4301 )
4302 }
4303 }
4304 }
4305
4306 /// Splits a slice into a prefix, a middle of aligned SIMD types, and a suffix.
4307 ///
4308 /// This is a safe wrapper around [`slice::align_to`], so inherits the same
4309 /// guarantees as that method.
4310 ///
4311 /// # Panics
4312 ///
4313 /// This will panic if the size of the SIMD type is different from
4314 /// `LANES` times that of the scalar.
4315 ///
4316 /// At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps
4317 /// that from ever happening, as only power-of-two numbers of lanes are
4318 /// supported. It's possible that, in the future, those restrictions might
4319 /// be lifted in a way that would make it possible to see panics from this
4320 /// method for something like `LANES == 3`.
4321 ///
4322 /// # Examples
4323 ///
4324 /// ```
4325 /// #![feature(portable_simd)]
4326 /// use core::simd::prelude::*;
4327 ///
4328 /// let short = &[1, 2, 3];
4329 /// let (prefix, middle, suffix) = short.as_simd::<4>();
4330 /// assert_eq!(middle, []); // Not enough elements for anything in the middle
4331 ///
4332 /// // They might be split in any possible way between prefix and suffix
4333 /// let it = prefix.iter().chain(suffix).copied();
4334 /// assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);
4335 ///
4336 /// fn basic_simd_sum(x: &[f32]) -> f32 {
4337 /// use std::ops::Add;
4338 /// let (prefix, middle, suffix) = x.as_simd();
4339 /// let sums = f32x4::from_array([
4340 /// prefix.iter().copied().sum(),
4341 /// 0.0,
4342 /// 0.0,
4343 /// suffix.iter().copied().sum(),
4344 /// ]);
4345 /// let sums = middle.iter().copied().fold(sums, f32x4::add);
4346 /// sums.reduce_sum()
4347 /// }
4348 ///
4349 /// let numbers: Vec<f32> = (1..101).map(|x| x as _).collect();
4350 /// assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);
4351 /// ```
4352 #[unstable(feature = "portable_simd", issue = "86656")]
4353 #[must_use]
4354 #[cfg(not(feature = "ferrocene_certified"))]
4355 pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])
4356 where
4357 Simd<T, LANES>: AsRef<[T; LANES]>,
4358 T: simd::SimdElement,
4359 simd::LaneCount<LANES>: simd::SupportedLaneCount,
4360 {
4361 // These are expected to always match, as vector types are laid out like
4362 // arrays per <https://llvm.org/docs/LangRef.html#vector-type>, but we
4363 // might as well double-check since it'll optimize away anyhow.
4364 assert_eq!(size_of::<Simd<T, LANES>>(), size_of::<[T; LANES]>());
4365
4366 // SAFETY: The simd types have the same layout as arrays, just with
4367 // potentially-higher alignment, so the de-facto transmutes are sound.
4368 unsafe { self.align_to() }
4369 }
4370
4371 /// Splits a mutable slice into a mutable prefix, a middle of aligned SIMD types,
4372 /// and a mutable suffix.
4373 ///
4374 /// This is a safe wrapper around [`slice::align_to_mut`], so inherits the same
4375 /// guarantees as that method.
4376 ///
4377 /// This is the mutable version of [`slice::as_simd`]; see that for examples.
4378 ///
4379 /// # Panics
4380 ///
4381 /// This will panic if the size of the SIMD type is different from
4382 /// `LANES` times that of the scalar.
4383 ///
4384 /// At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps
4385 /// that from ever happening, as only power-of-two numbers of lanes are
4386 /// supported. It's possible that, in the future, those restrictions might
4387 /// be lifted in a way that would make it possible to see panics from this
4388 /// method for something like `LANES == 3`.
4389 #[unstable(feature = "portable_simd", issue = "86656")]
4390 #[must_use]
4391 #[cfg(not(feature = "ferrocene_certified"))]
4392 pub fn as_simd_mut<const LANES: usize>(&mut self) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])
4393 where
4394 Simd<T, LANES>: AsMut<[T; LANES]>,
4395 T: simd::SimdElement,
4396 simd::LaneCount<LANES>: simd::SupportedLaneCount,
4397 {
4398 // These are expected to always match, as vector types are laid out like
4399 // arrays per <https://llvm.org/docs/LangRef.html#vector-type>, but we
4400 // might as well double-check since it'll optimize away anyhow.
4401 assert_eq!(size_of::<Simd<T, LANES>>(), size_of::<[T; LANES]>());
4402
4403 // SAFETY: The simd types have the same layout as arrays, just with
4404 // potentially-higher alignment, so the de-facto transmutes are sound.
4405 unsafe { self.align_to_mut() }
4406 }
4407
4408 /// Checks if the elements of this slice are sorted.
4409 ///
4410 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
4411 /// slice yields exactly zero or one element, `true` is returned.
4412 ///
4413 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
4414 /// implies that this function returns `false` if any two consecutive items are not
4415 /// comparable.
4416 ///
4417 /// # Examples
4418 ///
4419 /// ```
4420 /// let empty: [i32; 0] = [];
4421 ///
4422 /// assert!([1, 2, 2, 9].is_sorted());
4423 /// assert!(![1, 3, 2, 4].is_sorted());
4424 /// assert!([0].is_sorted());
4425 /// assert!(empty.is_sorted());
4426 /// assert!(![0.0, 1.0, f32::NAN].is_sorted());
4427 /// ```
4428 #[inline]
4429 #[stable(feature = "is_sorted", since = "1.82.0")]
4430 #[must_use]
4431 #[cfg(not(feature = "ferrocene_certified"))]
4432 pub fn is_sorted(&self) -> bool
4433 where
4434 T: PartialOrd,
4435 {
4436 // This odd number works the best. 32 + 1 extra due to overlapping chunk boundaries.
4437 const CHUNK_SIZE: usize = 33;
4438 if self.len() < CHUNK_SIZE {
4439 return self.windows(2).all(|w| w[0] <= w[1]);
4440 }
4441 let mut i = 0;
4442 // Check in chunks for autovectorization.
4443 while i < self.len() - CHUNK_SIZE {
4444 let chunk = &self[i..i + CHUNK_SIZE];
4445 if !chunk.windows(2).fold(true, |acc, w| acc & (w[0] <= w[1])) {
4446 return false;
4447 }
4448 // We need to ensure that chunk boundaries are also sorted.
4449 // Overlap the next chunk with the last element of our last chunk.
4450 i += CHUNK_SIZE - 1;
4451 }
4452 self[i..].windows(2).all(|w| w[0] <= w[1])
4453 }
4454
4455 /// Checks if the elements of this slice are sorted using the given comparator function.
4456 ///
4457 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
4458 /// function to determine whether two elements are to be considered in sorted order.
4459 ///
4460 /// # Examples
4461 ///
4462 /// ```
4463 /// assert!([1, 2, 2, 9].is_sorted_by(|a, b| a <= b));
4464 /// assert!(![1, 2, 2, 9].is_sorted_by(|a, b| a < b));
4465 ///
4466 /// assert!([0].is_sorted_by(|a, b| true));
4467 /// assert!([0].is_sorted_by(|a, b| false));
4468 ///
4469 /// let empty: [i32; 0] = [];
4470 /// assert!(empty.is_sorted_by(|a, b| false));
4471 /// assert!(empty.is_sorted_by(|a, b| true));
4472 /// ```
4473 #[stable(feature = "is_sorted", since = "1.82.0")]
4474 #[must_use]
4475 #[cfg(not(feature = "ferrocene_certified"))]
4476 pub fn is_sorted_by<'a, F>(&'a self, mut compare: F) -> bool
4477 where
4478 F: FnMut(&'a T, &'a T) -> bool,
4479 {
4480 self.array_windows().all(|[a, b]| compare(a, b))
4481 }
4482
4483 /// Checks if the elements of this slice are sorted using the given key extraction function.
4484 ///
4485 /// Instead of comparing the slice's elements directly, this function compares the keys of the
4486 /// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its
4487 /// documentation for more information.
4488 ///
4489 /// [`is_sorted`]: slice::is_sorted
4490 ///
4491 /// # Examples
4492 ///
4493 /// ```
4494 /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
4495 /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
4496 /// ```
4497 #[inline]
4498 #[stable(feature = "is_sorted", since = "1.82.0")]
4499 #[must_use]
4500 #[cfg(not(feature = "ferrocene_certified"))]
4501 pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> bool
4502 where
4503 F: FnMut(&'a T) -> K,
4504 K: PartialOrd,
4505 {
4506 self.iter().is_sorted_by_key(f)
4507 }
4508
4509 /// Returns the index of the partition point according to the given predicate
4510 /// (the index of the first element of the second partition).
4511 ///
4512 /// The slice is assumed to be partitioned according to the given predicate.
4513 /// This means that all elements for which the predicate returns true are at the start of the slice
4514 /// and all elements for which the predicate returns false are at the end.
4515 /// For example, `[7, 15, 3, 5, 4, 12, 6]` is partitioned under the predicate `x % 2 != 0`
4516 /// (all odd numbers are at the start, all even at the end).
4517 ///
4518 /// If this slice is not partitioned, the returned result is unspecified and meaningless,
4519 /// as this method performs a kind of binary search.
4520 ///
4521 /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
4522 ///
4523 /// [`binary_search`]: slice::binary_search
4524 /// [`binary_search_by`]: slice::binary_search_by
4525 /// [`binary_search_by_key`]: slice::binary_search_by_key
4526 ///
4527 /// # Examples
4528 ///
4529 /// ```
4530 /// let v = [1, 2, 3, 3, 5, 6, 7];
4531 /// let i = v.partition_point(|&x| x < 5);
4532 ///
4533 /// assert_eq!(i, 4);
4534 /// assert!(v[..i].iter().all(|&x| x < 5));
4535 /// assert!(v[i..].iter().all(|&x| !(x < 5)));
4536 /// ```
4537 ///
4538 /// If all elements of the slice match the predicate, including if the slice
4539 /// is empty, then the length of the slice will be returned:
4540 ///
4541 /// ```
4542 /// let a = [2, 4, 8];
4543 /// assert_eq!(a.partition_point(|x| x < &100), a.len());
4544 /// let a: [i32; 0] = [];
4545 /// assert_eq!(a.partition_point(|x| x < &100), 0);
4546 /// ```
4547 ///
4548 /// If you want to insert an item to a sorted vector, while maintaining
4549 /// sort order:
4550 ///
4551 /// ```
4552 /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
4553 /// let num = 42;
4554 /// let idx = s.partition_point(|&x| x <= num);
4555 /// s.insert(idx, num);
4556 /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
4557 /// ```
4558 #[stable(feature = "partition_point", since = "1.52.0")]
4559 #[must_use]
4560 #[cfg(not(feature = "ferrocene_certified"))]
4561 pub fn partition_point<P>(&self, mut pred: P) -> usize
4562 where
4563 P: FnMut(&T) -> bool,
4564 {
4565 self.binary_search_by(|x| if pred(x) { Less } else { Greater }).unwrap_or_else(|i| i)
4566 }
4567
4568 /// Removes the subslice corresponding to the given range
4569 /// and returns a reference to it.
4570 ///
4571 /// Returns `None` and does not modify the slice if the given
4572 /// range is out of bounds.
4573 ///
4574 /// Note that this method only accepts one-sided ranges such as
4575 /// `2..` or `..6`, but not `2..6`.
4576 ///
4577 /// # Examples
4578 ///
4579 /// Splitting off the first three elements of a slice:
4580 ///
4581 /// ```
4582 /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
4583 /// let mut first_three = slice.split_off(..3).unwrap();
4584 ///
4585 /// assert_eq!(slice, &['d']);
4586 /// assert_eq!(first_three, &['a', 'b', 'c']);
4587 /// ```
4588 ///
4589 /// Splitting off a slice starting with the third element:
4590 ///
4591 /// ```
4592 /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
4593 /// let mut tail = slice.split_off(2..).unwrap();
4594 ///
4595 /// assert_eq!(slice, &['a', 'b']);
4596 /// assert_eq!(tail, &['c', 'd']);
4597 /// ```
4598 ///
4599 /// Getting `None` when `range` is out of bounds:
4600 ///
4601 /// ```
4602 /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
4603 ///
4604 /// assert_eq!(None, slice.split_off(5..));
4605 /// assert_eq!(None, slice.split_off(..5));
4606 /// assert_eq!(None, slice.split_off(..=4));
4607 /// let expected: &[char] = &['a', 'b', 'c', 'd'];
4608 /// assert_eq!(Some(expected), slice.split_off(..4));
4609 /// ```
4610 #[inline]
4611 #[must_use = "method does not modify the slice if the range is out of bounds"]
4612 #[stable(feature = "slice_take", since = "1.87.0")]
4613 #[cfg(not(feature = "ferrocene_certified"))]
4614 pub fn split_off<'a, R: OneSidedRange<usize>>(
4615 self: &mut &'a Self,
4616 range: R,
4617 ) -> Option<&'a Self> {
4618 let (direction, split_index) = split_point_of(range)?;
4619 if split_index > self.len() {
4620 return None;
4621 }
4622 let (front, back) = self.split_at(split_index);
4623 match direction {
4624 Direction::Front => {
4625 *self = back;
4626 Some(front)
4627 }
4628 Direction::Back => {
4629 *self = front;
4630 Some(back)
4631 }
4632 }
4633 }
4634
4635 /// Removes the subslice corresponding to the given range
4636 /// and returns a mutable reference to it.
4637 ///
4638 /// Returns `None` and does not modify the slice if the given
4639 /// range is out of bounds.
4640 ///
4641 /// Note that this method only accepts one-sided ranges such as
4642 /// `2..` or `..6`, but not `2..6`.
4643 ///
4644 /// # Examples
4645 ///
4646 /// Splitting off the first three elements of a slice:
4647 ///
4648 /// ```
4649 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
4650 /// let mut first_three = slice.split_off_mut(..3).unwrap();
4651 ///
4652 /// assert_eq!(slice, &mut ['d']);
4653 /// assert_eq!(first_three, &mut ['a', 'b', 'c']);
4654 /// ```
4655 ///
4656 /// Splitting off a slice starting with the third element:
4657 ///
4658 /// ```
4659 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
4660 /// let mut tail = slice.split_off_mut(2..).unwrap();
4661 ///
4662 /// assert_eq!(slice, &mut ['a', 'b']);
4663 /// assert_eq!(tail, &mut ['c', 'd']);
4664 /// ```
4665 ///
4666 /// Getting `None` when `range` is out of bounds:
4667 ///
4668 /// ```
4669 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
4670 ///
4671 /// assert_eq!(None, slice.split_off_mut(5..));
4672 /// assert_eq!(None, slice.split_off_mut(..5));
4673 /// assert_eq!(None, slice.split_off_mut(..=4));
4674 /// let expected: &mut [_] = &mut ['a', 'b', 'c', 'd'];
4675 /// assert_eq!(Some(expected), slice.split_off_mut(..4));
4676 /// ```
4677 #[inline]
4678 #[must_use = "method does not modify the slice if the range is out of bounds"]
4679 #[stable(feature = "slice_take", since = "1.87.0")]
4680 #[cfg(not(feature = "ferrocene_certified"))]
4681 pub fn split_off_mut<'a, R: OneSidedRange<usize>>(
4682 self: &mut &'a mut Self,
4683 range: R,
4684 ) -> Option<&'a mut Self> {
4685 let (direction, split_index) = split_point_of(range)?;
4686 if split_index > self.len() {
4687 return None;
4688 }
4689 let (front, back) = mem::take(self).split_at_mut(split_index);
4690 match direction {
4691 Direction::Front => {
4692 *self = back;
4693 Some(front)
4694 }
4695 Direction::Back => {
4696 *self = front;
4697 Some(back)
4698 }
4699 }
4700 }
4701
4702 /// Removes the first element of the slice and returns a reference
4703 /// to it.
4704 ///
4705 /// Returns `None` if the slice is empty.
4706 ///
4707 /// # Examples
4708 ///
4709 /// ```
4710 /// let mut slice: &[_] = &['a', 'b', 'c'];
4711 /// let first = slice.split_off_first().unwrap();
4712 ///
4713 /// assert_eq!(slice, &['b', 'c']);
4714 /// assert_eq!(first, &'a');
4715 /// ```
4716 #[inline]
4717 #[stable(feature = "slice_take", since = "1.87.0")]
4718 #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]
4719 #[cfg(not(feature = "ferrocene_certified"))]
4720 pub const fn split_off_first<'a>(self: &mut &'a Self) -> Option<&'a T> {
4721 // FIXME(const-hack): Use `?` when available in const instead of `let-else`.
4722 let Some((first, rem)) = self.split_first() else { return None };
4723 *self = rem;
4724 Some(first)
4725 }
4726
4727 /// Removes the first element of the slice and returns a mutable
4728 /// reference to it.
4729 ///
4730 /// Returns `None` if the slice is empty.
4731 ///
4732 /// # Examples
4733 ///
4734 /// ```
4735 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
4736 /// let first = slice.split_off_first_mut().unwrap();
4737 /// *first = 'd';
4738 ///
4739 /// assert_eq!(slice, &['b', 'c']);
4740 /// assert_eq!(first, &'d');
4741 /// ```
4742 #[inline]
4743 #[stable(feature = "slice_take", since = "1.87.0")]
4744 #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]
4745 #[cfg(not(feature = "ferrocene_certified"))]
4746 pub const fn split_off_first_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {
4747 // FIXME(const-hack): Use `mem::take` and `?` when available in const.
4748 // Original: `mem::take(self).split_first_mut()?`
4749 let Some((first, rem)) = mem::replace(self, &mut []).split_first_mut() else { return None };
4750 *self = rem;
4751 Some(first)
4752 }
4753
4754 /// Removes the last element of the slice and returns a reference
4755 /// to it.
4756 ///
4757 /// Returns `None` if the slice is empty.
4758 ///
4759 /// # Examples
4760 ///
4761 /// ```
4762 /// let mut slice: &[_] = &['a', 'b', 'c'];
4763 /// let last = slice.split_off_last().unwrap();
4764 ///
4765 /// assert_eq!(slice, &['a', 'b']);
4766 /// assert_eq!(last, &'c');
4767 /// ```
4768 #[inline]
4769 #[stable(feature = "slice_take", since = "1.87.0")]
4770 #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]
4771 #[cfg(not(feature = "ferrocene_certified"))]
4772 pub const fn split_off_last<'a>(self: &mut &'a Self) -> Option<&'a T> {
4773 // FIXME(const-hack): Use `?` when available in const instead of `let-else`.
4774 let Some((last, rem)) = self.split_last() else { return None };
4775 *self = rem;
4776 Some(last)
4777 }
4778
4779 /// Removes the last element of the slice and returns a mutable
4780 /// reference to it.
4781 ///
4782 /// Returns `None` if the slice is empty.
4783 ///
4784 /// # Examples
4785 ///
4786 /// ```
4787 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
4788 /// let last = slice.split_off_last_mut().unwrap();
4789 /// *last = 'd';
4790 ///
4791 /// assert_eq!(slice, &['a', 'b']);
4792 /// assert_eq!(last, &'d');
4793 /// ```
4794 #[inline]
4795 #[stable(feature = "slice_take", since = "1.87.0")]
4796 #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]
4797 #[cfg(not(feature = "ferrocene_certified"))]
4798 pub const fn split_off_last_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {
4799 // FIXME(const-hack): Use `mem::take` and `?` when available in const.
4800 // Original: `mem::take(self).split_last_mut()?`
4801 let Some((last, rem)) = mem::replace(self, &mut []).split_last_mut() else { return None };
4802 *self = rem;
4803 Some(last)
4804 }
4805
4806 /// Returns mutable references to many indices at once, without doing any checks.
4807 ///
4808 /// An index can be either a `usize`, a [`Range`] or a [`RangeInclusive`]. Note
4809 /// that this method takes an array, so all indices must be of the same type.
4810 /// If passed an array of `usize`s this method gives back an array of mutable references
4811 /// to single elements, while if passed an array of ranges it gives back an array of
4812 /// mutable references to slices.
4813 ///
4814 /// For a safe alternative see [`get_disjoint_mut`].
4815 ///
4816 /// # Safety
4817 ///
4818 /// Calling this method with overlapping or out-of-bounds indices is *[undefined behavior]*
4819 /// even if the resulting references are not used.
4820 ///
4821 /// # Examples
4822 ///
4823 /// ```
4824 /// let x = &mut [1, 2, 4];
4825 ///
4826 /// unsafe {
4827 /// let [a, b] = x.get_disjoint_unchecked_mut([0, 2]);
4828 /// *a *= 10;
4829 /// *b *= 100;
4830 /// }
4831 /// assert_eq!(x, &[10, 2, 400]);
4832 ///
4833 /// unsafe {
4834 /// let [a, b] = x.get_disjoint_unchecked_mut([0..1, 1..3]);
4835 /// a[0] = 8;
4836 /// b[0] = 88;
4837 /// b[1] = 888;
4838 /// }
4839 /// assert_eq!(x, &[8, 88, 888]);
4840 ///
4841 /// unsafe {
4842 /// let [a, b] = x.get_disjoint_unchecked_mut([1..=2, 0..=0]);
4843 /// a[0] = 11;
4844 /// a[1] = 111;
4845 /// b[0] = 1;
4846 /// }
4847 /// assert_eq!(x, &[1, 11, 111]);
4848 /// ```
4849 ///
4850 /// [`get_disjoint_mut`]: slice::get_disjoint_mut
4851 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
4852 #[stable(feature = "get_many_mut", since = "1.86.0")]
4853 #[inline]
4854 #[track_caller]
4855 #[cfg(not(feature = "ferrocene_certified"))]
4856 pub unsafe fn get_disjoint_unchecked_mut<I, const N: usize>(
4857 &mut self,
4858 indices: [I; N],
4859 ) -> [&mut I::Output; N]
4860 where
4861 I: GetDisjointMutIndex + SliceIndex<Self>,
4862 {
4863 // NB: This implementation is written as it is because any variation of
4864 // `indices.map(|i| self.get_unchecked_mut(i))` would make miri unhappy,
4865 // or generate worse code otherwise. This is also why we need to go
4866 // through a raw pointer here.
4867 let slice: *mut [T] = self;
4868 let mut arr: MaybeUninit<[&mut I::Output; N]> = MaybeUninit::uninit();
4869 let arr_ptr = arr.as_mut_ptr();
4870
4871 // SAFETY: We expect `indices` to contain disjunct values that are
4872 // in bounds of `self`.
4873 unsafe {
4874 for i in 0..N {
4875 let idx = indices.get_unchecked(i).clone();
4876 arr_ptr.cast::<&mut I::Output>().add(i).write(&mut *slice.get_unchecked_mut(idx));
4877 }
4878 arr.assume_init()
4879 }
4880 }
4881
4882 /// Returns mutable references to many indices at once.
4883 ///
4884 /// An index can be either a `usize`, a [`Range`] or a [`RangeInclusive`]. Note
4885 /// that this method takes an array, so all indices must be of the same type.
4886 /// If passed an array of `usize`s this method gives back an array of mutable references
4887 /// to single elements, while if passed an array of ranges it gives back an array of
4888 /// mutable references to slices.
4889 ///
4890 /// Returns an error if any index is out-of-bounds, or if there are overlapping indices.
4891 /// An empty range is not considered to overlap if it is located at the beginning or at
4892 /// the end of another range, but is considered to overlap if it is located in the middle.
4893 ///
4894 /// This method does a O(n^2) check to check that there are no overlapping indices, so be careful
4895 /// when passing many indices.
4896 ///
4897 /// # Examples
4898 ///
4899 /// ```
4900 /// let v = &mut [1, 2, 3];
4901 /// if let Ok([a, b]) = v.get_disjoint_mut([0, 2]) {
4902 /// *a = 413;
4903 /// *b = 612;
4904 /// }
4905 /// assert_eq!(v, &[413, 2, 612]);
4906 ///
4907 /// if let Ok([a, b]) = v.get_disjoint_mut([0..1, 1..3]) {
4908 /// a[0] = 8;
4909 /// b[0] = 88;
4910 /// b[1] = 888;
4911 /// }
4912 /// assert_eq!(v, &[8, 88, 888]);
4913 ///
4914 /// if let Ok([a, b]) = v.get_disjoint_mut([1..=2, 0..=0]) {
4915 /// a[0] = 11;
4916 /// a[1] = 111;
4917 /// b[0] = 1;
4918 /// }
4919 /// assert_eq!(v, &[1, 11, 111]);
4920 /// ```
4921 #[stable(feature = "get_many_mut", since = "1.86.0")]
4922 #[inline]
4923 #[cfg(not(feature = "ferrocene_certified"))]
4924 pub fn get_disjoint_mut<I, const N: usize>(
4925 &mut self,
4926 indices: [I; N],
4927 ) -> Result<[&mut I::Output; N], GetDisjointMutError>
4928 where
4929 I: GetDisjointMutIndex + SliceIndex<Self>,
4930 {
4931 get_disjoint_check_valid(&indices, self.len())?;
4932 // SAFETY: The `get_disjoint_check_valid()` call checked that all indices
4933 // are disjunct and in bounds.
4934 unsafe { Ok(self.get_disjoint_unchecked_mut(indices)) }
4935 }
4936
4937 /// Returns the index that an element reference points to.
4938 ///
4939 /// Returns `None` if `element` does not point to the start of an element within the slice.
4940 ///
4941 /// This method is useful for extending slice iterators like [`slice::split`].
4942 ///
4943 /// Note that this uses pointer arithmetic and **does not compare elements**.
4944 /// To find the index of an element via comparison, use
4945 /// [`.iter().position()`](crate::iter::Iterator::position) instead.
4946 ///
4947 /// # Panics
4948 /// Panics if `T` is zero-sized.
4949 ///
4950 /// # Examples
4951 /// Basic usage:
4952 /// ```
4953 /// #![feature(substr_range)]
4954 ///
4955 /// let nums: &[u32] = &[1, 7, 1, 1];
4956 /// let num = &nums[2];
4957 ///
4958 /// assert_eq!(num, &1);
4959 /// assert_eq!(nums.element_offset(num), Some(2));
4960 /// ```
4961 /// Returning `None` with an unaligned element:
4962 /// ```
4963 /// #![feature(substr_range)]
4964 ///
4965 /// let arr: &[[u32; 2]] = &[[0, 1], [2, 3]];
4966 /// let flat_arr: &[u32] = arr.as_flattened();
4967 ///
4968 /// let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap();
4969 /// let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap();
4970 ///
4971 /// assert_eq!(ok_elm, &[0, 1]);
4972 /// assert_eq!(weird_elm, &[1, 2]);
4973 ///
4974 /// assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0
4975 /// assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1
4976 /// ```
4977 #[must_use]
4978 #[unstable(feature = "substr_range", issue = "126769")]
4979 #[cfg(not(feature = "ferrocene_certified"))]
4980 pub fn element_offset(&self, element: &T) -> Option<usize> {
4981 if T::IS_ZST {
4982 panic!("elements are zero-sized");
4983 }
4984
4985 let self_start = self.as_ptr().addr();
4986 let elem_start = ptr::from_ref(element).addr();
4987
4988 let byte_offset = elem_start.wrapping_sub(self_start);
4989
4990 if !byte_offset.is_multiple_of(size_of::<T>()) {
4991 return None;
4992 }
4993
4994 let offset = byte_offset / size_of::<T>();
4995
4996 if offset < self.len() { Some(offset) } else { None }
4997 }
4998
4999 /// Returns the range of indices that a subslice points to.
5000 ///
5001 /// Returns `None` if `subslice` does not point within the slice or if it is not aligned with the
5002 /// elements in the slice.
5003 ///
5004 /// This method **does not compare elements**. Instead, this method finds the location in the slice that
5005 /// `subslice` was obtained from. To find the index of a subslice via comparison, instead use
5006 /// [`.windows()`](slice::windows)[`.position()`](crate::iter::Iterator::position).
5007 ///
5008 /// This method is useful for extending slice iterators like [`slice::split`].
5009 ///
5010 /// Note that this may return a false positive (either `Some(0..0)` or `Some(self.len()..self.len())`)
5011 /// if `subslice` has a length of zero and points to the beginning or end of another, separate, slice.
5012 ///
5013 /// # Panics
5014 /// Panics if `T` is zero-sized.
5015 ///
5016 /// # Examples
5017 /// Basic usage:
5018 /// ```
5019 /// #![feature(substr_range)]
5020 ///
5021 /// let nums = &[0, 5, 10, 0, 0, 5];
5022 ///
5023 /// let mut iter = nums
5024 /// .split(|t| *t == 0)
5025 /// .map(|n| nums.subslice_range(n).unwrap());
5026 ///
5027 /// assert_eq!(iter.next(), Some(0..0));
5028 /// assert_eq!(iter.next(), Some(1..3));
5029 /// assert_eq!(iter.next(), Some(4..4));
5030 /// assert_eq!(iter.next(), Some(5..6));
5031 /// ```
5032 #[must_use]
5033 #[unstable(feature = "substr_range", issue = "126769")]
5034 #[cfg(not(feature = "ferrocene_certified"))]
5035 pub fn subslice_range(&self, subslice: &[T]) -> Option<Range<usize>> {
5036 if T::IS_ZST {
5037 panic!("elements are zero-sized");
5038 }
5039
5040 let self_start = self.as_ptr().addr();
5041 let subslice_start = subslice.as_ptr().addr();
5042
5043 let byte_start = subslice_start.wrapping_sub(self_start);
5044
5045 if !byte_start.is_multiple_of(size_of::<T>()) {
5046 return None;
5047 }
5048
5049 let start = byte_start / size_of::<T>();
5050 let end = start.wrapping_add(subslice.len());
5051
5052 if start <= self.len() && end <= self.len() { Some(start..end) } else { None }
5053 }
5054}
5055
5056#[cfg(not(feature = "ferrocene_certified"))]
5057impl<T> [MaybeUninit<T>] {
5058 /// Transmutes the mutable uninitialized slice to a mutable uninitialized slice of
5059 /// another type, ensuring alignment of the types is maintained.
5060 ///
5061 /// This is a safe wrapper around [`slice::align_to_mut`], so inherits the same
5062 /// guarantees as that method.
5063 ///
5064 /// # Examples
5065 ///
5066 /// ```
5067 /// #![feature(align_to_uninit_mut)]
5068 /// use std::mem::MaybeUninit;
5069 ///
5070 /// pub struct BumpAllocator<'scope> {
5071 /// memory: &'scope mut [MaybeUninit<u8>],
5072 /// }
5073 ///
5074 /// impl<'scope> BumpAllocator<'scope> {
5075 /// pub fn new(memory: &'scope mut [MaybeUninit<u8>]) -> Self {
5076 /// Self { memory }
5077 /// }
5078 /// pub fn try_alloc_uninit<T>(&mut self) -> Option<&'scope mut MaybeUninit<T>> {
5079 /// let first_end = self.memory.as_ptr().align_offset(align_of::<T>()) + size_of::<T>();
5080 /// let prefix = self.memory.split_off_mut(..first_end)?;
5081 /// Some(&mut prefix.align_to_uninit_mut::<T>().1[0])
5082 /// }
5083 /// pub fn try_alloc_u32(&mut self, value: u32) -> Option<&'scope mut u32> {
5084 /// let uninit = self.try_alloc_uninit()?;
5085 /// Some(uninit.write(value))
5086 /// }
5087 /// }
5088 ///
5089 /// let mut memory = [MaybeUninit::<u8>::uninit(); 10];
5090 /// let mut allocator = BumpAllocator::new(&mut memory);
5091 /// let v = allocator.try_alloc_u32(42);
5092 /// assert_eq!(v, Some(&mut 42));
5093 /// ```
5094 #[unstable(feature = "align_to_uninit_mut", issue = "139062")]
5095 #[inline]
5096 #[must_use]
5097 pub fn align_to_uninit_mut<U>(&mut self) -> (&mut Self, &mut [MaybeUninit<U>], &mut Self) {
5098 // SAFETY: `MaybeUninit` is transparent. Correct size and alignment are guaranteed by
5099 // `align_to_mut` itself. Therefore the only thing that we have to ensure for a safe
5100 // `transmute` is that the values are valid for the types involved. But for `MaybeUninit`
5101 // any values are valid, so this operation is safe.
5102 unsafe { self.align_to_mut() }
5103 }
5104}
5105
5106#[cfg(not(feature = "ferrocene_certified"))]
5107impl<T, const N: usize> [[T; N]] {
5108 /// Takes a `&[[T; N]]`, and flattens it to a `&[T]`.
5109 ///
5110 /// For the opposite operation, see [`as_chunks`] and [`as_rchunks`].
5111 ///
5112 /// [`as_chunks`]: slice::as_chunks
5113 /// [`as_rchunks`]: slice::as_rchunks
5114 ///
5115 /// # Panics
5116 ///
5117 /// This panics if the length of the resulting slice would overflow a `usize`.
5118 ///
5119 /// This is only possible when flattening a slice of arrays of zero-sized
5120 /// types, and thus tends to be irrelevant in practice. If
5121 /// `size_of::<T>() > 0`, this will never panic.
5122 ///
5123 /// # Examples
5124 ///
5125 /// ```
5126 /// assert_eq!([[1, 2, 3], [4, 5, 6]].as_flattened(), &[1, 2, 3, 4, 5, 6]);
5127 ///
5128 /// assert_eq!(
5129 /// [[1, 2, 3], [4, 5, 6]].as_flattened(),
5130 /// [[1, 2], [3, 4], [5, 6]].as_flattened(),
5131 /// );
5132 ///
5133 /// let slice_of_empty_arrays: &[[i32; 0]] = &[[], [], [], [], []];
5134 /// assert!(slice_of_empty_arrays.as_flattened().is_empty());
5135 ///
5136 /// let empty_slice_of_arrays: &[[u32; 10]] = &[];
5137 /// assert!(empty_slice_of_arrays.as_flattened().is_empty());
5138 /// ```
5139 #[stable(feature = "slice_flatten", since = "1.80.0")]
5140 #[rustc_const_stable(feature = "const_slice_flatten", since = "1.87.0")]
5141 pub const fn as_flattened(&self) -> &[T] {
5142 let len = if T::IS_ZST {
5143 self.len().checked_mul(N).expect("slice len overflow")
5144 } else {
5145 // SAFETY: `self.len() * N` cannot overflow because `self` is
5146 // already in the address space.
5147 unsafe { self.len().unchecked_mul(N) }
5148 };
5149 // SAFETY: `[T]` is layout-identical to `[T; N]`
5150 unsafe { from_raw_parts(self.as_ptr().cast(), len) }
5151 }
5152
5153 /// Takes a `&mut [[T; N]]`, and flattens it to a `&mut [T]`.
5154 ///
5155 /// For the opposite operation, see [`as_chunks_mut`] and [`as_rchunks_mut`].
5156 ///
5157 /// [`as_chunks_mut`]: slice::as_chunks_mut
5158 /// [`as_rchunks_mut`]: slice::as_rchunks_mut
5159 ///
5160 /// # Panics
5161 ///
5162 /// This panics if the length of the resulting slice would overflow a `usize`.
5163 ///
5164 /// This is only possible when flattening a slice of arrays of zero-sized
5165 /// types, and thus tends to be irrelevant in practice. If
5166 /// `size_of::<T>() > 0`, this will never panic.
5167 ///
5168 /// # Examples
5169 ///
5170 /// ```
5171 /// fn add_5_to_all(slice: &mut [i32]) {
5172 /// for i in slice {
5173 /// *i += 5;
5174 /// }
5175 /// }
5176 ///
5177 /// let mut array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
5178 /// add_5_to_all(array.as_flattened_mut());
5179 /// assert_eq!(array, [[6, 7, 8], [9, 10, 11], [12, 13, 14]]);
5180 /// ```
5181 #[stable(feature = "slice_flatten", since = "1.80.0")]
5182 #[rustc_const_stable(feature = "const_slice_flatten", since = "1.87.0")]
5183 pub const fn as_flattened_mut(&mut self) -> &mut [T] {
5184 let len = if T::IS_ZST {
5185 self.len().checked_mul(N).expect("slice len overflow")
5186 } else {
5187 // SAFETY: `self.len() * N` cannot overflow because `self` is
5188 // already in the address space.
5189 unsafe { self.len().unchecked_mul(N) }
5190 };
5191 // SAFETY: `[T]` is layout-identical to `[T; N]`
5192 unsafe { from_raw_parts_mut(self.as_mut_ptr().cast(), len) }
5193 }
5194}
5195
5196#[cfg(not(feature = "ferrocene_certified"))]
5197impl [f32] {
5198 /// Sorts the slice of floats.
5199 ///
5200 /// This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses
5201 /// the ordering defined by [`f32::total_cmp`].
5202 ///
5203 /// # Current implementation
5204 ///
5205 /// This uses the same sorting algorithm as [`sort_unstable_by`](slice::sort_unstable_by).
5206 ///
5207 /// # Examples
5208 ///
5209 /// ```
5210 /// #![feature(sort_floats)]
5211 /// let mut v = [2.6, -5e-8, f32::NAN, 8.29, f32::INFINITY, -1.0, 0.0, -f32::INFINITY, -0.0];
5212 ///
5213 /// v.sort_floats();
5214 /// let sorted = [-f32::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f32::INFINITY, f32::NAN];
5215 /// assert_eq!(&v[..8], &sorted[..8]);
5216 /// assert!(v[8].is_nan());
5217 /// ```
5218 #[unstable(feature = "sort_floats", issue = "93396")]
5219 #[inline]
5220 pub fn sort_floats(&mut self) {
5221 self.sort_unstable_by(f32::total_cmp);
5222 }
5223}
5224
5225#[cfg(not(feature = "ferrocene_certified"))]
5226impl [f64] {
5227 /// Sorts the slice of floats.
5228 ///
5229 /// This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses
5230 /// the ordering defined by [`f64::total_cmp`].
5231 ///
5232 /// # Current implementation
5233 ///
5234 /// This uses the same sorting algorithm as [`sort_unstable_by`](slice::sort_unstable_by).
5235 ///
5236 /// # Examples
5237 ///
5238 /// ```
5239 /// #![feature(sort_floats)]
5240 /// let mut v = [2.6, -5e-8, f64::NAN, 8.29, f64::INFINITY, -1.0, 0.0, -f64::INFINITY, -0.0];
5241 ///
5242 /// v.sort_floats();
5243 /// let sorted = [-f64::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f64::INFINITY, f64::NAN];
5244 /// assert_eq!(&v[..8], &sorted[..8]);
5245 /// assert!(v[8].is_nan());
5246 /// ```
5247 #[unstable(feature = "sort_floats", issue = "93396")]
5248 #[inline]
5249 pub fn sort_floats(&mut self) {
5250 self.sort_unstable_by(f64::total_cmp);
5251 }
5252}
5253
5254#[cfg(not(feature = "ferrocene_certified"))]
5255trait CloneFromSpec<T> {
5256 fn spec_clone_from(&mut self, src: &[T]);
5257}
5258
5259#[cfg(not(feature = "ferrocene_certified"))]
5260impl<T> CloneFromSpec<T> for [T]
5261where
5262 T: Clone,
5263{
5264 #[track_caller]
5265 default fn spec_clone_from(&mut self, src: &[T]) {
5266 assert!(self.len() == src.len(), "destination and source slices have different lengths");
5267 // NOTE: We need to explicitly slice them to the same length
5268 // to make it easier for the optimizer to elide bounds checking.
5269 // But since it can't be relied on we also have an explicit specialization for T: Copy.
5270 let len = self.len();
5271 let src = &src[..len];
5272 for i in 0..len {
5273 self[i].clone_from(&src[i]);
5274 }
5275 }
5276}
5277
5278#[cfg(not(feature = "ferrocene_certified"))]
5279impl<T> CloneFromSpec<T> for [T]
5280where
5281 T: Copy,
5282{
5283 #[track_caller]
5284 fn spec_clone_from(&mut self, src: &[T]) {
5285 self.copy_from_slice(src);
5286 }
5287}
5288
5289#[stable(feature = "rust1", since = "1.0.0")]
5290#[rustc_const_unstable(feature = "const_default", issue = "143894")]
5291#[cfg(not(feature = "ferrocene_certified"))]
5292impl<T> const Default for &[T] {
5293 /// Creates an empty slice.
5294 fn default() -> Self {
5295 &[]
5296 }
5297}
5298
5299#[stable(feature = "mut_slice_default", since = "1.5.0")]
5300#[rustc_const_unstable(feature = "const_default", issue = "143894")]
5301#[cfg(not(feature = "ferrocene_certified"))]
5302impl<T> const Default for &mut [T] {
5303 /// Creates a mutable empty slice.
5304 fn default() -> Self {
5305 &mut []
5306 }
5307}
5308
5309#[unstable(feature = "slice_pattern", reason = "stopgap trait for slice patterns", issue = "56345")]
5310/// Patterns in slices - currently, only used by `strip_prefix` and `strip_suffix`. At a future
5311/// point, we hope to generalise `core::str::Pattern` (which at the time of writing is limited to
5312/// `str`) to slices, and then this trait will be replaced or abolished.
5313#[cfg(not(feature = "ferrocene_certified"))]
5314pub trait SlicePattern {
5315 /// The element type of the slice being matched on.
5316 type Item;
5317
5318 /// Currently, the consumers of `SlicePattern` need a slice.
5319 fn as_slice(&self) -> &[Self::Item];
5320}
5321
5322#[stable(feature = "slice_strip", since = "1.51.0")]
5323#[cfg(not(feature = "ferrocene_certified"))]
5324impl<T> SlicePattern for [T] {
5325 type Item = T;
5326
5327 #[inline]
5328 fn as_slice(&self) -> &[Self::Item] {
5329 self
5330 }
5331}
5332
5333#[stable(feature = "slice_strip", since = "1.51.0")]
5334#[cfg(not(feature = "ferrocene_certified"))]
5335impl<T, const N: usize> SlicePattern for [T; N] {
5336 type Item = T;
5337
5338 #[inline]
5339 fn as_slice(&self) -> &[Self::Item] {
5340 self
5341 }
5342}
5343
5344/// This checks every index against each other, and against `len`.
5345///
5346/// This will do `binomial(N + 1, 2) = N * (N + 1) / 2 = 0, 1, 3, 6, 10, ..`
5347/// comparison operations.
5348#[inline]
5349#[cfg(not(feature = "ferrocene_certified"))]
5350fn get_disjoint_check_valid<I: GetDisjointMutIndex, const N: usize>(
5351 indices: &[I; N],
5352 len: usize,
5353) -> Result<(), GetDisjointMutError> {
5354 // NB: The optimizer should inline the loops into a sequence
5355 // of instructions without additional branching.
5356 for (i, idx) in indices.iter().enumerate() {
5357 if !idx.is_in_bounds(len) {
5358 return Err(GetDisjointMutError::IndexOutOfBounds);
5359 }
5360 for idx2 in &indices[..i] {
5361 if idx.is_overlapping(idx2) {
5362 return Err(GetDisjointMutError::OverlappingIndices);
5363 }
5364 }
5365 }
5366 Ok(())
5367}
5368
5369/// The error type returned by [`get_disjoint_mut`][`slice::get_disjoint_mut`].
5370///
5371/// It indicates one of two possible errors:
5372/// - An index is out-of-bounds.
5373/// - The same index appeared multiple times in the array
5374/// (or different but overlapping indices when ranges are provided).
5375///
5376/// # Examples
5377///
5378/// ```
5379/// use std::slice::GetDisjointMutError;
5380///
5381/// let v = &mut [1, 2, 3];
5382/// assert_eq!(v.get_disjoint_mut([0, 999]), Err(GetDisjointMutError::IndexOutOfBounds));
5383/// assert_eq!(v.get_disjoint_mut([1, 1]), Err(GetDisjointMutError::OverlappingIndices));
5384/// ```
5385#[stable(feature = "get_many_mut", since = "1.86.0")]
5386#[derive(Debug, Clone, PartialEq, Eq)]
5387#[cfg(not(feature = "ferrocene_certified"))]
5388pub enum GetDisjointMutError {
5389 /// An index provided was out-of-bounds for the slice.
5390 IndexOutOfBounds,
5391 /// Two indices provided were overlapping.
5392 OverlappingIndices,
5393}
5394
5395#[stable(feature = "get_many_mut", since = "1.86.0")]
5396#[cfg(not(feature = "ferrocene_certified"))]
5397impl fmt::Display for GetDisjointMutError {
5398 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5399 let msg = match self {
5400 GetDisjointMutError::IndexOutOfBounds => "an index is out of bounds",
5401 GetDisjointMutError::OverlappingIndices => "there were overlapping indices",
5402 };
5403 fmt::Display::fmt(msg, f)
5404 }
5405}
5406
5407#[cfg(not(feature = "ferrocene_certified"))]
5408mod private_get_disjoint_mut_index {
5409 use super::{Range, RangeInclusive, range};
5410
5411 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5412 pub trait Sealed {}
5413
5414 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5415 impl Sealed for usize {}
5416 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5417 impl Sealed for Range<usize> {}
5418 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5419 impl Sealed for RangeInclusive<usize> {}
5420 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5421 impl Sealed for range::Range<usize> {}
5422 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5423 impl Sealed for range::RangeInclusive<usize> {}
5424}
5425
5426/// A helper trait for `<[T]>::get_disjoint_mut()`.
5427///
5428/// # Safety
5429///
5430/// If `is_in_bounds()` returns `true` and `is_overlapping()` returns `false`,
5431/// it must be safe to index the slice with the indices.
5432#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5433#[cfg(not(feature = "ferrocene_certified"))]
5434pub unsafe trait GetDisjointMutIndex:
5435 Clone + private_get_disjoint_mut_index::Sealed
5436{
5437 /// Returns `true` if `self` is in bounds for `len` slice elements.
5438 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5439 fn is_in_bounds(&self, len: usize) -> bool;
5440
5441 /// Returns `true` if `self` overlaps with `other`.
5442 ///
5443 /// Note that we don't consider zero-length ranges to overlap at the beginning or the end,
5444 /// but do consider them to overlap in the middle.
5445 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5446 fn is_overlapping(&self, other: &Self) -> bool;
5447}
5448
5449#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5450// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5451#[cfg(not(feature = "ferrocene_certified"))]
5452unsafe impl GetDisjointMutIndex for usize {
5453 #[inline]
5454 fn is_in_bounds(&self, len: usize) -> bool {
5455 *self < len
5456 }
5457
5458 #[inline]
5459 fn is_overlapping(&self, other: &Self) -> bool {
5460 *self == *other
5461 }
5462}
5463
5464#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5465// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5466#[cfg(not(feature = "ferrocene_certified"))]
5467unsafe impl GetDisjointMutIndex for Range<usize> {
5468 #[inline]
5469 fn is_in_bounds(&self, len: usize) -> bool {
5470 (self.start <= self.end) & (self.end <= len)
5471 }
5472
5473 #[inline]
5474 fn is_overlapping(&self, other: &Self) -> bool {
5475 (self.start < other.end) & (other.start < self.end)
5476 }
5477}
5478
5479#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5480// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5481#[cfg(not(feature = "ferrocene_certified"))]
5482unsafe impl GetDisjointMutIndex for RangeInclusive<usize> {
5483 #[inline]
5484 fn is_in_bounds(&self, len: usize) -> bool {
5485 (self.start <= self.end) & (self.end < len)
5486 }
5487
5488 #[inline]
5489 fn is_overlapping(&self, other: &Self) -> bool {
5490 (self.start <= other.end) & (other.start <= self.end)
5491 }
5492}
5493
5494#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5495// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5496#[cfg(not(feature = "ferrocene_certified"))]
5497unsafe impl GetDisjointMutIndex for range::Range<usize> {
5498 #[inline]
5499 fn is_in_bounds(&self, len: usize) -> bool {
5500 Range::from(*self).is_in_bounds(len)
5501 }
5502
5503 #[inline]
5504 fn is_overlapping(&self, other: &Self) -> bool {
5505 Range::from(*self).is_overlapping(&Range::from(*other))
5506 }
5507}
5508
5509#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5510// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5511#[cfg(not(feature = "ferrocene_certified"))]
5512unsafe impl GetDisjointMutIndex for range::RangeInclusive<usize> {
5513 #[inline]
5514 fn is_in_bounds(&self, len: usize) -> bool {
5515 RangeInclusive::from(*self).is_in_bounds(len)
5516 }
5517
5518 #[inline]
5519 fn is_overlapping(&self, other: &Self) -> bool {
5520 RangeInclusive::from(*self).is_overlapping(&RangeInclusive::from(*other))
5521 }
5522}