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::clone::TrivialClone;
11#[cfg(not(feature = "ferrocene_certified"))]
12use crate::cmp::Ordering::{self, Equal, Greater, Less};
13#[cfg(not(feature = "ferrocene_certified"))]
14use crate::intrinsics::{exact_div, unchecked_sub};
15#[cfg(not(feature = "ferrocene_certified"))]
16use crate::mem::{self, MaybeUninit, SizedTypeProperties};
17use crate::num::NonZero;
18#[cfg(not(feature = "ferrocene_certified"))]
19use crate::ops::{OneSidedRange, OneSidedRangeBound, Range, RangeBounds, RangeInclusive};
20use crate::panic::const_panic;
21#[cfg(not(feature = "ferrocene_certified"))]
22use crate::simd::{self, Simd};
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::{intrinsics::unchecked_sub, 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;
57mod rotate;
58mod specialize;
59
60#[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
61#[cfg(not(feature = "ferrocene_certified"))]
62pub use ascii::EscapeAscii;
63#[unstable(feature = "str_internals", issue = "none")]
64#[doc(hidden)]
65#[cfg(not(feature = "ferrocene_certified"))]
66pub use ascii::is_ascii_simple;
67#[stable(feature = "slice_get_slice", since = "1.28.0")]
68pub use index::SliceIndex;
69#[unstable(feature = "slice_range", issue = "76393")]
70#[cfg(not(feature = "ferrocene_certified"))]
71pub use index::{range, try_range};
72#[unstable(feature = "array_windows", issue = "75027")]
73#[cfg(not(feature = "ferrocene_certified"))]
74pub use iter::ArrayWindows;
75#[stable(feature = "slice_group_by", since = "1.77.0")]
76#[cfg(not(feature = "ferrocene_certified"))]
77pub use iter::{ChunkBy, ChunkByMut};
78#[stable(feature = "rust1", since = "1.0.0")]
79#[cfg(not(feature = "ferrocene_certified"))]
80pub use iter::{Chunks, ChunksMut, Windows};
81#[stable(feature = "chunks_exact", since = "1.31.0")]
82#[cfg(not(feature = "ferrocene_certified"))]
83pub use iter::{ChunksExact, ChunksExactMut};
84#[stable(feature = "rust1", since = "1.0.0")]
85pub use iter::{Iter, IterMut};
86#[stable(feature = "rchunks", since = "1.31.0")]
87#[cfg(not(feature = "ferrocene_certified"))]
88pub use iter::{RChunks, RChunksExact, RChunksExactMut, RChunksMut};
89#[stable(feature = "slice_rsplit", since = "1.27.0")]
90#[cfg(not(feature = "ferrocene_certified"))]
91pub use iter::{RSplit, RSplitMut};
92#[stable(feature = "rust1", since = "1.0.0")]
93#[cfg(not(feature = "ferrocene_certified"))]
94pub use iter::{RSplitN, RSplitNMut, Split, SplitMut, SplitN, SplitNMut};
95#[stable(feature = "split_inclusive", since = "1.51.0")]
96#[cfg(not(feature = "ferrocene_certified"))]
97pub use iter::{SplitInclusive, SplitInclusiveMut};
98#[stable(feature = "from_ref", since = "1.28.0")]
99pub use raw::{from_mut, from_ref};
100#[unstable(feature = "slice_from_ptr_range", issue = "89792")]
101#[cfg(not(feature = "ferrocene_certified"))]
102pub use raw::{from_mut_ptr_range, from_ptr_range};
103#[stable(feature = "rust1", since = "1.0.0")]
104pub use raw::{from_raw_parts, from_raw_parts_mut};
105
106// Ferrocene addition: imports for certified subset
107#[stable(feature = "rust1", since = "1.0.0")]
108#[cfg(feature = "ferrocene_certified")]
109#[rustfmt::skip]
110pub use iter::{Chunks, Windows};
111
112/// Calculates the direction and split point of a one-sided range.
113///
114/// This is a helper function for `split_off` and `split_off_mut` that returns
115/// the direction of the split (front or back) as well as the index at
116/// which to split. Returns `None` if the split index would overflow.
117#[inline]
118#[cfg(not(feature = "ferrocene_certified"))]
119fn split_point_of(range: impl OneSidedRange<usize>) -> Option<(Direction, usize)> {
120 use OneSidedRangeBound::{End, EndInclusive, StartInclusive};
121
122 Some(match range.bound() {
123 (StartInclusive, i) => (Direction::Back, i),
124 (End, i) => (Direction::Front, i),
125 (EndInclusive, i) => (Direction::Front, i.checked_add(1)?),
126 })
127}
128
129#[cfg(not(feature = "ferrocene_certified"))]
130enum Direction {
131 Front,
132 Back,
133}
134
135impl<T> [T] {
136 /// Returns the number of elements in the slice.
137 ///
138 /// # Examples
139 ///
140 /// ```
141 /// let a = [1, 2, 3];
142 /// assert_eq!(a.len(), 3);
143 /// ```
144 #[lang = "slice_len_fn"]
145 #[stable(feature = "rust1", since = "1.0.0")]
146 #[rustc_const_stable(feature = "const_slice_len", since = "1.39.0")]
147 #[rustc_no_implicit_autorefs]
148 #[inline]
149 #[must_use]
150 pub const fn len(&self) -> usize {
151 ptr::metadata(self)
152 }
153
154 /// Returns `true` if the slice has a length of 0.
155 ///
156 /// # Examples
157 ///
158 /// ```
159 /// let a = [1, 2, 3];
160 /// assert!(!a.is_empty());
161 ///
162 /// let b: &[i32] = &[];
163 /// assert!(b.is_empty());
164 /// ```
165 #[stable(feature = "rust1", since = "1.0.0")]
166 #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.39.0")]
167 #[rustc_no_implicit_autorefs]
168 #[inline]
169 #[must_use]
170 pub const fn is_empty(&self) -> bool {
171 self.len() == 0
172 }
173
174 /// Returns the first element of the slice, or `None` if it is empty.
175 ///
176 /// # Examples
177 ///
178 /// ```
179 /// let v = [10, 40, 30];
180 /// assert_eq!(Some(&10), v.first());
181 ///
182 /// let w: &[i32] = &[];
183 /// assert_eq!(None, w.first());
184 /// ```
185 #[stable(feature = "rust1", since = "1.0.0")]
186 #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
187 #[inline]
188 #[must_use]
189 pub const fn first(&self) -> Option<&T> {
190 if let [first, ..] = self { Some(first) } else { None }
191 }
192
193 /// Returns a mutable reference to the first element of the slice, or `None` if it is empty.
194 ///
195 /// # Examples
196 ///
197 /// ```
198 /// let x = &mut [0, 1, 2];
199 ///
200 /// if let Some(first) = x.first_mut() {
201 /// *first = 5;
202 /// }
203 /// assert_eq!(x, &[5, 1, 2]);
204 ///
205 /// let y: &mut [i32] = &mut [];
206 /// assert_eq!(None, y.first_mut());
207 /// ```
208 #[stable(feature = "rust1", since = "1.0.0")]
209 #[rustc_const_stable(feature = "const_slice_first_last", since = "1.83.0")]
210 #[inline]
211 #[must_use]
212 pub const fn first_mut(&mut self) -> Option<&mut T> {
213 if let [first, ..] = self { Some(first) } else { None }
214 }
215
216 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
217 ///
218 /// # Examples
219 ///
220 /// ```
221 /// let x = &[0, 1, 2];
222 ///
223 /// if let Some((first, elements)) = x.split_first() {
224 /// assert_eq!(first, &0);
225 /// assert_eq!(elements, &[1, 2]);
226 /// }
227 /// ```
228 #[stable(feature = "slice_splits", since = "1.5.0")]
229 #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
230 #[inline]
231 #[must_use]
232 pub const fn split_first(&self) -> Option<(&T, &[T])> {
233 if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
234 }
235
236 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
237 ///
238 /// # Examples
239 ///
240 /// ```
241 /// let x = &mut [0, 1, 2];
242 ///
243 /// if let Some((first, elements)) = x.split_first_mut() {
244 /// *first = 3;
245 /// elements[0] = 4;
246 /// elements[1] = 5;
247 /// }
248 /// assert_eq!(x, &[3, 4, 5]);
249 /// ```
250 #[stable(feature = "slice_splits", since = "1.5.0")]
251 #[rustc_const_stable(feature = "const_slice_first_last", since = "1.83.0")]
252 #[inline]
253 #[must_use]
254 pub const fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
255 if let [first, tail @ ..] = self { Some((first, tail)) } else { None }
256 }
257
258 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
259 ///
260 /// # Examples
261 ///
262 /// ```
263 /// let x = &[0, 1, 2];
264 ///
265 /// if let Some((last, elements)) = x.split_last() {
266 /// assert_eq!(last, &2);
267 /// assert_eq!(elements, &[0, 1]);
268 /// }
269 /// ```
270 #[stable(feature = "slice_splits", since = "1.5.0")]
271 #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
272 #[inline]
273 #[must_use]
274 pub const fn split_last(&self) -> Option<(&T, &[T])> {
275 if let [init @ .., last] = self { Some((last, init)) } else { None }
276 }
277
278 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
279 ///
280 /// # Examples
281 ///
282 /// ```
283 /// let x = &mut [0, 1, 2];
284 ///
285 /// if let Some((last, elements)) = x.split_last_mut() {
286 /// *last = 3;
287 /// elements[0] = 4;
288 /// elements[1] = 5;
289 /// }
290 /// assert_eq!(x, &[4, 5, 3]);
291 /// ```
292 #[stable(feature = "slice_splits", since = "1.5.0")]
293 #[rustc_const_stable(feature = "const_slice_first_last", since = "1.83.0")]
294 #[inline]
295 #[must_use]
296 pub const fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
297 if let [init @ .., last] = self { Some((last, init)) } else { None }
298 }
299
300 /// Returns the last element of the slice, or `None` if it is empty.
301 ///
302 /// # Examples
303 ///
304 /// ```
305 /// let v = [10, 40, 30];
306 /// assert_eq!(Some(&30), v.last());
307 ///
308 /// let w: &[i32] = &[];
309 /// assert_eq!(None, w.last());
310 /// ```
311 #[stable(feature = "rust1", since = "1.0.0")]
312 #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")]
313 #[inline]
314 #[must_use]
315 pub const fn last(&self) -> Option<&T> {
316 if let [.., last] = self { Some(last) } else { None }
317 }
318
319 /// Returns a mutable reference to the last item in the slice, or `None` if it is empty.
320 ///
321 /// # Examples
322 ///
323 /// ```
324 /// let x = &mut [0, 1, 2];
325 ///
326 /// if let Some(last) = x.last_mut() {
327 /// *last = 10;
328 /// }
329 /// assert_eq!(x, &[0, 1, 10]);
330 ///
331 /// let y: &mut [i32] = &mut [];
332 /// assert_eq!(None, y.last_mut());
333 /// ```
334 #[stable(feature = "rust1", since = "1.0.0")]
335 #[rustc_const_stable(feature = "const_slice_first_last", since = "1.83.0")]
336 #[inline]
337 #[must_use]
338 pub const fn last_mut(&mut self) -> Option<&mut T> {
339 if let [.., last] = self { Some(last) } else { None }
340 }
341
342 /// Returns an array reference to the first `N` items in the slice.
343 ///
344 /// If the slice is not at least `N` in length, this will return `None`.
345 ///
346 /// # Examples
347 ///
348 /// ```
349 /// let u = [10, 40, 30];
350 /// assert_eq!(Some(&[10, 40]), u.first_chunk::<2>());
351 ///
352 /// let v: &[i32] = &[10];
353 /// assert_eq!(None, v.first_chunk::<2>());
354 ///
355 /// let w: &[i32] = &[];
356 /// assert_eq!(Some(&[]), w.first_chunk::<0>());
357 /// ```
358 #[inline]
359 #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]
360 #[rustc_const_stable(feature = "slice_first_last_chunk", since = "1.77.0")]
361 pub const fn first_chunk<const N: usize>(&self) -> Option<&[T; N]> {
362 if self.len() < N {
363 None
364 } else {
365 // SAFETY: We explicitly check for the correct number of elements,
366 // and do not let the reference outlive the slice.
367 Some(unsafe { &*(self.as_ptr().cast_array()) })
368 }
369 }
370
371 /// Returns a mutable array reference to the first `N` items in the slice.
372 ///
373 /// If the slice is not at least `N` in length, this will return `None`.
374 ///
375 /// # Examples
376 ///
377 /// ```
378 /// let x = &mut [0, 1, 2];
379 ///
380 /// if let Some(first) = x.first_chunk_mut::<2>() {
381 /// first[0] = 5;
382 /// first[1] = 4;
383 /// }
384 /// assert_eq!(x, &[5, 4, 2]);
385 ///
386 /// assert_eq!(None, x.first_chunk_mut::<4>());
387 /// ```
388 #[inline]
389 #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]
390 #[rustc_const_stable(feature = "const_slice_first_last_chunk", since = "1.83.0")]
391 pub const fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]> {
392 if self.len() < N {
393 None
394 } else {
395 // SAFETY: We explicitly check for the correct number of elements,
396 // do not let the reference outlive the slice,
397 // and require exclusive access to the entire slice to mutate the chunk.
398 Some(unsafe { &mut *(self.as_mut_ptr().cast_array()) })
399 }
400 }
401
402 /// Returns an array reference to the first `N` items in the slice and the remaining slice.
403 ///
404 /// If the slice is not at least `N` in length, this will return `None`.
405 ///
406 /// # Examples
407 ///
408 /// ```
409 /// let x = &[0, 1, 2];
410 ///
411 /// if let Some((first, elements)) = x.split_first_chunk::<2>() {
412 /// assert_eq!(first, &[0, 1]);
413 /// assert_eq!(elements, &[2]);
414 /// }
415 ///
416 /// assert_eq!(None, x.split_first_chunk::<4>());
417 /// ```
418 #[inline]
419 #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]
420 #[rustc_const_stable(feature = "slice_first_last_chunk", since = "1.77.0")]
421 #[cfg(not(feature = "ferrocene_certified"))]
422 pub const fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])> {
423 let Some((first, tail)) = self.split_at_checked(N) else { return None };
424
425 // SAFETY: We explicitly check for the correct number of elements,
426 // and do not let the references outlive the slice.
427 Some((unsafe { &*(first.as_ptr().cast_array()) }, tail))
428 }
429
430 /// Returns a mutable array reference to the first `N` items in the slice and the remaining
431 /// slice.
432 ///
433 /// If the slice is not at least `N` in length, this will return `None`.
434 ///
435 /// # Examples
436 ///
437 /// ```
438 /// let x = &mut [0, 1, 2];
439 ///
440 /// if let Some((first, elements)) = x.split_first_chunk_mut::<2>() {
441 /// first[0] = 3;
442 /// first[1] = 4;
443 /// elements[0] = 5;
444 /// }
445 /// assert_eq!(x, &[3, 4, 5]);
446 ///
447 /// assert_eq!(None, x.split_first_chunk_mut::<4>());
448 /// ```
449 #[inline]
450 #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]
451 #[rustc_const_stable(feature = "const_slice_first_last_chunk", since = "1.83.0")]
452 #[cfg(not(feature = "ferrocene_certified"))]
453 pub const fn split_first_chunk_mut<const N: usize>(
454 &mut self,
455 ) -> Option<(&mut [T; N], &mut [T])> {
456 let Some((first, tail)) = self.split_at_mut_checked(N) else { return None };
457
458 // SAFETY: We explicitly check for the correct number of elements,
459 // do not let the reference outlive the slice,
460 // and enforce exclusive mutability of the chunk by the split.
461 Some((unsafe { &mut *(first.as_mut_ptr().cast_array()) }, tail))
462 }
463
464 /// Returns an array reference to the last `N` items in the slice and the remaining slice.
465 ///
466 /// If the slice is not at least `N` in length, this will return `None`.
467 ///
468 /// # Examples
469 ///
470 /// ```
471 /// let x = &[0, 1, 2];
472 ///
473 /// if let Some((elements, last)) = x.split_last_chunk::<2>() {
474 /// assert_eq!(elements, &[0]);
475 /// assert_eq!(last, &[1, 2]);
476 /// }
477 ///
478 /// assert_eq!(None, x.split_last_chunk::<4>());
479 /// ```
480 #[inline]
481 #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]
482 #[rustc_const_stable(feature = "slice_first_last_chunk", since = "1.77.0")]
483 #[cfg(not(feature = "ferrocene_certified"))]
484 pub const fn split_last_chunk<const N: usize>(&self) -> Option<(&[T], &[T; N])> {
485 let Some(index) = self.len().checked_sub(N) else { return None };
486 let (init, last) = self.split_at(index);
487
488 // SAFETY: We explicitly check for the correct number of elements,
489 // and do not let the references outlive the slice.
490 Some((init, unsafe { &*(last.as_ptr().cast_array()) }))
491 }
492
493 /// Returns a mutable array reference to the last `N` items in the slice and the remaining
494 /// slice.
495 ///
496 /// If the slice is not at least `N` in length, this will return `None`.
497 ///
498 /// # Examples
499 ///
500 /// ```
501 /// let x = &mut [0, 1, 2];
502 ///
503 /// if let Some((elements, last)) = x.split_last_chunk_mut::<2>() {
504 /// last[0] = 3;
505 /// last[1] = 4;
506 /// elements[0] = 5;
507 /// }
508 /// assert_eq!(x, &[5, 3, 4]);
509 ///
510 /// assert_eq!(None, x.split_last_chunk_mut::<4>());
511 /// ```
512 #[inline]
513 #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]
514 #[rustc_const_stable(feature = "const_slice_first_last_chunk", since = "1.83.0")]
515 #[cfg(not(feature = "ferrocene_certified"))]
516 pub const fn split_last_chunk_mut<const N: usize>(
517 &mut self,
518 ) -> Option<(&mut [T], &mut [T; N])> {
519 let Some(index) = self.len().checked_sub(N) else { return None };
520 let (init, last) = self.split_at_mut(index);
521
522 // SAFETY: We explicitly check for the correct number of elements,
523 // do not let the reference outlive the slice,
524 // and enforce exclusive mutability of the chunk by the split.
525 Some((init, unsafe { &mut *(last.as_mut_ptr().cast_array()) }))
526 }
527
528 /// Returns an array reference to the last `N` items in the slice.
529 ///
530 /// If the slice is not at least `N` in length, this will return `None`.
531 ///
532 /// # Examples
533 ///
534 /// ```
535 /// let u = [10, 40, 30];
536 /// assert_eq!(Some(&[40, 30]), u.last_chunk::<2>());
537 ///
538 /// let v: &[i32] = &[10];
539 /// assert_eq!(None, v.last_chunk::<2>());
540 ///
541 /// let w: &[i32] = &[];
542 /// assert_eq!(Some(&[]), w.last_chunk::<0>());
543 /// ```
544 #[inline]
545 #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]
546 #[rustc_const_stable(feature = "const_slice_last_chunk", since = "1.80.0")]
547 #[cfg(not(feature = "ferrocene_certified"))]
548 pub const fn last_chunk<const N: usize>(&self) -> Option<&[T; N]> {
549 // FIXME(const-hack): Without const traits, we need this instead of `get`.
550 let Some(index) = self.len().checked_sub(N) else { return None };
551 let (_, last) = self.split_at(index);
552
553 // SAFETY: We explicitly check for the correct number of elements,
554 // and do not let the references outlive the slice.
555 Some(unsafe { &*(last.as_ptr().cast_array()) })
556 }
557
558 /// Returns a mutable array reference to the last `N` items in the slice.
559 ///
560 /// If the slice is not at least `N` in length, this will return `None`.
561 ///
562 /// # Examples
563 ///
564 /// ```
565 /// let x = &mut [0, 1, 2];
566 ///
567 /// if let Some(last) = x.last_chunk_mut::<2>() {
568 /// last[0] = 10;
569 /// last[1] = 20;
570 /// }
571 /// assert_eq!(x, &[0, 10, 20]);
572 ///
573 /// assert_eq!(None, x.last_chunk_mut::<4>());
574 /// ```
575 #[inline]
576 #[stable(feature = "slice_first_last_chunk", since = "1.77.0")]
577 #[rustc_const_stable(feature = "const_slice_first_last_chunk", since = "1.83.0")]
578 #[cfg(not(feature = "ferrocene_certified"))]
579 pub const fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]> {
580 // FIXME(const-hack): Without const traits, we need this instead of `get`.
581 let Some(index) = self.len().checked_sub(N) else { return None };
582 let (_, last) = self.split_at_mut(index);
583
584 // SAFETY: We explicitly check for the correct number of elements,
585 // do not let the reference outlive the slice,
586 // and require exclusive access to the entire slice to mutate the chunk.
587 Some(unsafe { &mut *(last.as_mut_ptr().cast_array()) })
588 }
589
590 /// Returns a reference to an element or subslice depending on the type of
591 /// index.
592 ///
593 /// - If given a position, returns a reference to the element at that
594 /// position or `None` if out of bounds.
595 /// - If given a range, returns the subslice corresponding to that range,
596 /// or `None` if out of bounds.
597 ///
598 /// # Examples
599 ///
600 /// ```
601 /// let v = [10, 40, 30];
602 /// assert_eq!(Some(&40), v.get(1));
603 /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
604 /// assert_eq!(None, v.get(3));
605 /// assert_eq!(None, v.get(0..4));
606 /// ```
607 #[stable(feature = "rust1", since = "1.0.0")]
608 #[rustc_no_implicit_autorefs]
609 #[inline]
610 #[must_use]
611 #[rustc_const_unstable(feature = "const_index", issue = "143775")]
612 pub const fn get<I>(&self, index: I) -> Option<&I::Output>
613 where
614 I: [const] SliceIndex<Self>,
615 {
616 index.get(self)
617 }
618
619 /// Returns a mutable reference to an element or subslice depending on the
620 /// type of index (see [`get`]) or `None` if the index is out of bounds.
621 ///
622 /// [`get`]: slice::get
623 ///
624 /// # Examples
625 ///
626 /// ```
627 /// let x = &mut [0, 1, 2];
628 ///
629 /// if let Some(elem) = x.get_mut(1) {
630 /// *elem = 42;
631 /// }
632 /// assert_eq!(x, &[0, 42, 2]);
633 /// ```
634 #[stable(feature = "rust1", since = "1.0.0")]
635 #[rustc_no_implicit_autorefs]
636 #[inline]
637 #[must_use]
638 #[rustc_const_unstable(feature = "const_index", issue = "143775")]
639 pub const fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
640 where
641 I: [const] SliceIndex<Self>,
642 {
643 index.get_mut(self)
644 }
645
646 /// Returns a reference to an element or subslice, without doing bounds
647 /// checking.
648 ///
649 /// For a safe alternative see [`get`].
650 ///
651 /// # Safety
652 ///
653 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
654 /// even if the resulting reference is not used.
655 ///
656 /// You can think of this like `.get(index).unwrap_unchecked()`. It's UB
657 /// to call `.get_unchecked(len)`, even if you immediately convert to a
658 /// pointer. And it's UB to call `.get_unchecked(..len + 1)`,
659 /// `.get_unchecked(..=len)`, or similar.
660 ///
661 /// [`get`]: slice::get
662 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
663 ///
664 /// # Examples
665 ///
666 /// ```
667 /// let x = &[1, 2, 4];
668 ///
669 /// unsafe {
670 /// assert_eq!(x.get_unchecked(1), &2);
671 /// }
672 /// ```
673 #[stable(feature = "rust1", since = "1.0.0")]
674 #[rustc_no_implicit_autorefs]
675 #[inline]
676 #[must_use]
677 #[track_caller]
678 #[rustc_const_unstable(feature = "const_index", issue = "143775")]
679 pub const unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
680 where
681 I: [const] SliceIndex<Self>,
682 {
683 // SAFETY: the caller must uphold most of the safety requirements for `get_unchecked`;
684 // the slice is dereferenceable because `self` is a safe reference.
685 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
686 unsafe { &*index.get_unchecked(self) }
687 }
688
689 /// Returns a mutable reference to an element or subslice, without doing
690 /// bounds checking.
691 ///
692 /// For a safe alternative see [`get_mut`].
693 ///
694 /// # Safety
695 ///
696 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
697 /// even if the resulting reference is not used.
698 ///
699 /// You can think of this like `.get_mut(index).unwrap_unchecked()`. It's
700 /// UB to call `.get_unchecked_mut(len)`, even if you immediately convert
701 /// to a pointer. And it's UB to call `.get_unchecked_mut(..len + 1)`,
702 /// `.get_unchecked_mut(..=len)`, or similar.
703 ///
704 /// [`get_mut`]: slice::get_mut
705 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
706 ///
707 /// # Examples
708 ///
709 /// ```
710 /// let x = &mut [1, 2, 4];
711 ///
712 /// unsafe {
713 /// let elem = x.get_unchecked_mut(1);
714 /// *elem = 13;
715 /// }
716 /// assert_eq!(x, &[1, 13, 4]);
717 /// ```
718 #[stable(feature = "rust1", since = "1.0.0")]
719 #[rustc_no_implicit_autorefs]
720 #[inline]
721 #[must_use]
722 #[track_caller]
723 #[rustc_const_unstable(feature = "const_index", issue = "143775")]
724 pub const unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
725 where
726 I: [const] SliceIndex<Self>,
727 {
728 // SAFETY: the caller must uphold the safety requirements for `get_unchecked_mut`;
729 // the slice is dereferenceable because `self` is a safe reference.
730 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
731 unsafe { &mut *index.get_unchecked_mut(self) }
732 }
733
734 /// Returns a raw pointer to the slice's buffer.
735 ///
736 /// The caller must ensure that the slice outlives the pointer this
737 /// function returns, or else it will end up dangling.
738 ///
739 /// The caller must also ensure that the memory the pointer (non-transitively) points to
740 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
741 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
742 ///
743 /// Modifying the container referenced by this slice may cause its buffer
744 /// to be reallocated, which would also make any pointers to it invalid.
745 ///
746 /// # Examples
747 ///
748 /// ```
749 /// let x = &[1, 2, 4];
750 /// let x_ptr = x.as_ptr();
751 ///
752 /// unsafe {
753 /// for i in 0..x.len() {
754 /// assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
755 /// }
756 /// }
757 /// ```
758 ///
759 /// [`as_mut_ptr`]: slice::as_mut_ptr
760 #[stable(feature = "rust1", since = "1.0.0")]
761 #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")]
762 #[rustc_never_returns_null_ptr]
763 #[rustc_as_ptr]
764 #[inline(always)]
765 #[must_use]
766 pub const fn as_ptr(&self) -> *const T {
767 self as *const [T] as *const T
768 }
769
770 /// Returns an unsafe mutable pointer to the slice's buffer.
771 ///
772 /// The caller must ensure that the slice outlives the pointer this
773 /// function returns, or else it will end up dangling.
774 ///
775 /// Modifying the container referenced by this slice may cause its buffer
776 /// to be reallocated, which would also make any pointers to it invalid.
777 ///
778 /// # Examples
779 ///
780 /// ```
781 /// let x = &mut [1, 2, 4];
782 /// let x_ptr = x.as_mut_ptr();
783 ///
784 /// unsafe {
785 /// for i in 0..x.len() {
786 /// *x_ptr.add(i) += 2;
787 /// }
788 /// }
789 /// assert_eq!(x, &[3, 4, 6]);
790 /// ```
791 #[stable(feature = "rust1", since = "1.0.0")]
792 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
793 #[rustc_never_returns_null_ptr]
794 #[rustc_as_ptr]
795 #[inline(always)]
796 #[must_use]
797 pub const fn as_mut_ptr(&mut self) -> *mut T {
798 self as *mut [T] as *mut T
799 }
800
801 /// Returns the two raw pointers spanning the slice.
802 ///
803 /// The returned range is half-open, which means that the end pointer
804 /// points *one past* the last element of the slice. This way, an empty
805 /// slice is represented by two equal pointers, and the difference between
806 /// the two pointers represents the size of the slice.
807 ///
808 /// See [`as_ptr`] for warnings on using these pointers. The end pointer
809 /// requires extra caution, as it does not point to a valid element in the
810 /// slice.
811 ///
812 /// This function is useful for interacting with foreign interfaces which
813 /// use two pointers to refer to a range of elements in memory, as is
814 /// common in C++.
815 ///
816 /// It can also be useful to check if a pointer to an element refers to an
817 /// element of this slice:
818 ///
819 /// ```
820 /// let a = [1, 2, 3];
821 /// let x = &a[1] as *const _;
822 /// let y = &5 as *const _;
823 ///
824 /// assert!(a.as_ptr_range().contains(&x));
825 /// assert!(!a.as_ptr_range().contains(&y));
826 /// ```
827 ///
828 /// [`as_ptr`]: slice::as_ptr
829 #[stable(feature = "slice_ptr_range", since = "1.48.0")]
830 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
831 #[inline]
832 #[must_use]
833 #[cfg(not(feature = "ferrocene_certified"))]
834 pub const fn as_ptr_range(&self) -> Range<*const T> {
835 let start = self.as_ptr();
836 // SAFETY: The `add` here is safe, because:
837 //
838 // - Both pointers are part of the same object, as pointing directly
839 // past the object also counts.
840 //
841 // - The size of the slice is never larger than `isize::MAX` bytes, as
842 // noted here:
843 // - https://github.com/rust-lang/unsafe-code-guidelines/issues/102#issuecomment-473340447
844 // - https://doc.rust-lang.org/reference/behavior-considered-undefined.html
845 // - https://doc.rust-lang.org/core/slice/fn.from_raw_parts.html#safety
846 // (This doesn't seem normative yet, but the very same assumption is
847 // made in many places, including the Index implementation of slices.)
848 //
849 // - There is no wrapping around involved, as slices do not wrap past
850 // the end of the address space.
851 //
852 // See the documentation of [`pointer::add`].
853 let end = unsafe { start.add(self.len()) };
854 start..end
855 }
856
857 /// Returns the two unsafe mutable pointers spanning the slice.
858 ///
859 /// The returned range is half-open, which means that the end pointer
860 /// points *one past* the last element of the slice. This way, an empty
861 /// slice is represented by two equal pointers, and the difference between
862 /// the two pointers represents the size of the slice.
863 ///
864 /// See [`as_mut_ptr`] for warnings on using these pointers. The end
865 /// pointer requires extra caution, as it does not point to a valid element
866 /// in the slice.
867 ///
868 /// This function is useful for interacting with foreign interfaces which
869 /// use two pointers to refer to a range of elements in memory, as is
870 /// common in C++.
871 ///
872 /// [`as_mut_ptr`]: slice::as_mut_ptr
873 #[stable(feature = "slice_ptr_range", since = "1.48.0")]
874 #[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")]
875 #[inline]
876 #[must_use]
877 #[cfg(not(feature = "ferrocene_certified"))]
878 pub const fn as_mut_ptr_range(&mut self) -> Range<*mut T> {
879 let start = self.as_mut_ptr();
880 // SAFETY: See as_ptr_range() above for why `add` here is safe.
881 let end = unsafe { start.add(self.len()) };
882 start..end
883 }
884
885 /// Gets a reference to the underlying array.
886 ///
887 /// If `N` is not exactly equal to the length of `self`, then this method returns `None`.
888 #[stable(feature = "core_slice_as_array", since = "CURRENT_RUSTC_VERSION")]
889 #[rustc_const_stable(feature = "core_slice_as_array", since = "CURRENT_RUSTC_VERSION")]
890 #[inline]
891 #[must_use]
892 pub const fn as_array<const N: usize>(&self) -> Option<&[T; N]> {
893 if self.len() == N {
894 let ptr = self.as_ptr().cast_array();
895
896 // 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.
897 let me = unsafe { &*ptr };
898 Some(me)
899 } else {
900 None
901 }
902 }
903
904 /// Gets a mutable reference to the slice's underlying array.
905 ///
906 /// If `N` is not exactly equal to the length of `self`, then this method returns `None`.
907 #[stable(feature = "core_slice_as_array", since = "CURRENT_RUSTC_VERSION")]
908 #[rustc_const_stable(feature = "core_slice_as_array", since = "CURRENT_RUSTC_VERSION")]
909 #[inline]
910 #[must_use]
911 pub const fn as_mut_array<const N: usize>(&mut self) -> Option<&mut [T; N]> {
912 if self.len() == N {
913 let ptr = self.as_mut_ptr().cast_array();
914
915 // 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.
916 let me = unsafe { &mut *ptr };
917 Some(me)
918 } else {
919 None
920 }
921 }
922
923 /// Swaps two elements in the slice.
924 ///
925 /// If `a` equals to `b`, it's guaranteed that elements won't change value.
926 ///
927 /// # Arguments
928 ///
929 /// * a - The index of the first element
930 /// * b - The index of the second element
931 ///
932 /// # Panics
933 ///
934 /// Panics if `a` or `b` are out of bounds.
935 ///
936 /// # Examples
937 ///
938 /// ```
939 /// let mut v = ["a", "b", "c", "d", "e"];
940 /// v.swap(2, 4);
941 /// assert!(v == ["a", "b", "e", "d", "c"]);
942 /// ```
943 #[stable(feature = "rust1", since = "1.0.0")]
944 #[rustc_const_stable(feature = "const_swap", since = "1.85.0")]
945 #[inline]
946 #[track_caller]
947 pub const fn swap(&mut self, a: usize, b: usize) {
948 // FIXME: use swap_unchecked here (https://github.com/rust-lang/rust/pull/88540#issuecomment-944344343)
949 // Can't take two mutable loans from one vector, so instead use raw pointers.
950 let pa = &raw mut self[a];
951 let pb = &raw mut self[b];
952 // SAFETY: `pa` and `pb` have been created from safe mutable references and refer
953 // to elements in the slice and therefore are guaranteed to be valid and aligned.
954 // Note that accessing the elements behind `a` and `b` is checked and will
955 // panic when out of bounds.
956 unsafe {
957 ptr::swap(pa, pb);
958 }
959 }
960
961 /// Swaps two elements in the slice, without doing bounds checking.
962 ///
963 /// For a safe alternative see [`swap`].
964 ///
965 /// # Arguments
966 ///
967 /// * a - The index of the first element
968 /// * b - The index of the second element
969 ///
970 /// # Safety
971 ///
972 /// Calling this method with an out-of-bounds index is *[undefined behavior]*.
973 /// The caller has to ensure that `a < self.len()` and `b < self.len()`.
974 ///
975 /// # Examples
976 ///
977 /// ```
978 /// #![feature(slice_swap_unchecked)]
979 ///
980 /// let mut v = ["a", "b", "c", "d"];
981 /// // SAFETY: we know that 1 and 3 are both indices of the slice
982 /// unsafe { v.swap_unchecked(1, 3) };
983 /// assert!(v == ["a", "d", "c", "b"]);
984 /// ```
985 ///
986 /// [`swap`]: slice::swap
987 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
988 #[unstable(feature = "slice_swap_unchecked", issue = "88539")]
989 #[track_caller]
990 #[cfg(not(feature = "ferrocene_certified"))]
991 pub const unsafe fn swap_unchecked(&mut self, a: usize, b: usize) {
992 assert_unsafe_precondition!(
993 check_library_ub,
994 "slice::swap_unchecked requires that the indices are within the slice",
995 (
996 len: usize = self.len(),
997 a: usize = a,
998 b: usize = b,
999 ) => a < len && b < len,
1000 );
1001
1002 let ptr = self.as_mut_ptr();
1003 // SAFETY: caller has to guarantee that `a < self.len()` and `b < self.len()`
1004 unsafe {
1005 ptr::swap(ptr.add(a), ptr.add(b));
1006 }
1007 }
1008
1009 /// Reverses the order of elements in the slice, in place.
1010 ///
1011 /// # Examples
1012 ///
1013 /// ```
1014 /// let mut v = [1, 2, 3];
1015 /// v.reverse();
1016 /// assert!(v == [3, 2, 1]);
1017 /// ```
1018 #[stable(feature = "rust1", since = "1.0.0")]
1019 #[rustc_const_stable(feature = "const_slice_reverse", since = "1.90.0")]
1020 #[inline]
1021 #[cfg(not(feature = "ferrocene_certified"))]
1022 pub const fn reverse(&mut self) {
1023 let half_len = self.len() / 2;
1024 let Range { start, end } = self.as_mut_ptr_range();
1025
1026 // These slices will skip the middle item for an odd length,
1027 // since that one doesn't need to move.
1028 let (front_half, back_half) =
1029 // SAFETY: Both are subparts of the original slice, so the memory
1030 // range is valid, and they don't overlap because they're each only
1031 // half (or less) of the original slice.
1032 unsafe {
1033 (
1034 slice::from_raw_parts_mut(start, half_len),
1035 slice::from_raw_parts_mut(end.sub(half_len), half_len),
1036 )
1037 };
1038
1039 // Introducing a function boundary here means that the two halves
1040 // get `noalias` markers, allowing better optimization as LLVM
1041 // knows that they're disjoint, unlike in the original slice.
1042 revswap(front_half, back_half, half_len);
1043
1044 #[inline]
1045 const fn revswap<T>(a: &mut [T], b: &mut [T], n: usize) {
1046 debug_assert!(a.len() == n);
1047 debug_assert!(b.len() == n);
1048
1049 // Because this function is first compiled in isolation,
1050 // this check tells LLVM that the indexing below is
1051 // in-bounds. Then after inlining -- once the actual
1052 // lengths of the slices are known -- it's removed.
1053 // FIXME(const_trait_impl) replace with let (a, b) = (&mut a[..n], &mut b[..n]);
1054 let (a, _) = a.split_at_mut(n);
1055 let (b, _) = b.split_at_mut(n);
1056
1057 let mut i = 0;
1058 while i < n {
1059 mem::swap(&mut a[i], &mut b[n - 1 - i]);
1060 i += 1;
1061 }
1062 }
1063 }
1064
1065 /// Returns an iterator over the slice.
1066 ///
1067 /// The iterator yields all items from start to end.
1068 ///
1069 /// # Examples
1070 ///
1071 /// ```
1072 /// let x = &[1, 2, 4];
1073 /// let mut iterator = x.iter();
1074 ///
1075 /// assert_eq!(iterator.next(), Some(&1));
1076 /// assert_eq!(iterator.next(), Some(&2));
1077 /// assert_eq!(iterator.next(), Some(&4));
1078 /// assert_eq!(iterator.next(), None);
1079 /// ```
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1082 #[inline]
1083 #[rustc_diagnostic_item = "slice_iter"]
1084 pub const fn iter(&self) -> Iter<'_, T> {
1085 Iter::new(self)
1086 }
1087
1088 /// Returns an iterator that allows modifying each value.
1089 ///
1090 /// The iterator yields all items from start to end.
1091 ///
1092 /// # Examples
1093 ///
1094 /// ```
1095 /// let x = &mut [1, 2, 4];
1096 /// for elem in x.iter_mut() {
1097 /// *elem += 2;
1098 /// }
1099 /// assert_eq!(x, &[3, 4, 6]);
1100 /// ```
1101 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1102 #[stable(feature = "rust1", since = "1.0.0")]
1103 #[inline]
1104 pub const fn iter_mut(&mut self) -> IterMut<'_, T> {
1105 IterMut::new(self)
1106 }
1107
1108 /// Returns an iterator over all contiguous windows of length
1109 /// `size`. The windows overlap. If the slice is shorter than
1110 /// `size`, the iterator returns no values.
1111 ///
1112 /// # Panics
1113 ///
1114 /// Panics if `size` is zero.
1115 ///
1116 /// # Examples
1117 ///
1118 /// ```
1119 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1120 /// let mut iter = slice.windows(3);
1121 /// assert_eq!(iter.next().unwrap(), &['l', 'o', 'r']);
1122 /// assert_eq!(iter.next().unwrap(), &['o', 'r', 'e']);
1123 /// assert_eq!(iter.next().unwrap(), &['r', 'e', 'm']);
1124 /// assert!(iter.next().is_none());
1125 /// ```
1126 ///
1127 /// If the slice is shorter than `size`:
1128 ///
1129 /// ```
1130 /// let slice = ['f', 'o', 'o'];
1131 /// let mut iter = slice.windows(4);
1132 /// assert!(iter.next().is_none());
1133 /// ```
1134 ///
1135 /// Because the [Iterator] trait cannot represent the required lifetimes,
1136 /// there is no `windows_mut` analog to `windows`;
1137 /// `[0,1,2].windows_mut(2).collect()` would violate [the rules of references]
1138 /// (though a [LendingIterator] analog is possible). You can sometimes use
1139 /// [`Cell::as_slice_of_cells`](crate::cell::Cell::as_slice_of_cells) in
1140 /// conjunction with `windows` instead:
1141 ///
1142 /// [the rules of references]: https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#the-rules-of-references
1143 /// [LendingIterator]: https://blog.rust-lang.org/2022/10/28/gats-stabilization.html
1144 /// ```
1145 /// use std::cell::Cell;
1146 ///
1147 /// let mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5'];
1148 /// let slice = &mut array[..];
1149 /// let slice_of_cells: &[Cell<char>] = Cell::from_mut(slice).as_slice_of_cells();
1150 /// for w in slice_of_cells.windows(3) {
1151 /// Cell::swap(&w[0], &w[2]);
1152 /// }
1153 /// assert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']);
1154 /// ```
1155 #[stable(feature = "rust1", since = "1.0.0")]
1156 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1157 #[inline]
1158 #[track_caller]
1159 pub const fn windows(&self, size: usize) -> Windows<'_, T> {
1160 let size = NonZero::new(size).expect("window size must be non-zero");
1161 Windows::new(self, size)
1162 }
1163
1164 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
1165 /// beginning of the slice.
1166 ///
1167 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1168 /// slice, then the last chunk will not have length `chunk_size`.
1169 ///
1170 /// See [`chunks_exact`] for a variant of this iterator that returns chunks of always exactly
1171 /// `chunk_size` elements, and [`rchunks`] for the same iterator but starting at the end of the
1172 /// slice.
1173 ///
1174 /// If your `chunk_size` is a constant, consider using [`as_chunks`] instead, which will
1175 /// give references to arrays of exactly that length, rather than slices.
1176 ///
1177 /// # Panics
1178 ///
1179 /// Panics if `chunk_size` is zero.
1180 ///
1181 /// # Examples
1182 ///
1183 /// ```
1184 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1185 /// let mut iter = slice.chunks(2);
1186 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
1187 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
1188 /// assert_eq!(iter.next().unwrap(), &['m']);
1189 /// assert!(iter.next().is_none());
1190 /// ```
1191 ///
1192 /// [`chunks_exact`]: slice::chunks_exact
1193 /// [`rchunks`]: slice::rchunks
1194 /// [`as_chunks`]: slice::as_chunks
1195 #[stable(feature = "rust1", since = "1.0.0")]
1196 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1197 #[inline]
1198 #[track_caller]
1199 pub const fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> {
1200 assert!(chunk_size != 0, "chunk size must be non-zero");
1201 Chunks::new(self, chunk_size)
1202 }
1203
1204 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
1205 /// beginning of the slice.
1206 ///
1207 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1208 /// length of the slice, then the last chunk will not have length `chunk_size`.
1209 ///
1210 /// See [`chunks_exact_mut`] for a variant of this iterator that returns chunks of always
1211 /// exactly `chunk_size` elements, and [`rchunks_mut`] for the same iterator but starting at
1212 /// the end of the slice.
1213 ///
1214 /// If your `chunk_size` is a constant, consider using [`as_chunks_mut`] instead, which will
1215 /// give references to arrays of exactly that length, rather than slices.
1216 ///
1217 /// # Panics
1218 ///
1219 /// Panics if `chunk_size` is zero.
1220 ///
1221 /// # Examples
1222 ///
1223 /// ```
1224 /// let v = &mut [0, 0, 0, 0, 0];
1225 /// let mut count = 1;
1226 ///
1227 /// for chunk in v.chunks_mut(2) {
1228 /// for elem in chunk.iter_mut() {
1229 /// *elem += count;
1230 /// }
1231 /// count += 1;
1232 /// }
1233 /// assert_eq!(v, &[1, 1, 2, 2, 3]);
1234 /// ```
1235 ///
1236 /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1237 /// [`rchunks_mut`]: slice::rchunks_mut
1238 /// [`as_chunks_mut`]: slice::as_chunks_mut
1239 #[stable(feature = "rust1", since = "1.0.0")]
1240 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1241 #[inline]
1242 #[track_caller]
1243 #[cfg(not(feature = "ferrocene_certified"))]
1244 pub const fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> {
1245 assert!(chunk_size != 0, "chunk size must be non-zero");
1246 ChunksMut::new(self, chunk_size)
1247 }
1248
1249 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
1250 /// beginning of the slice.
1251 ///
1252 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1253 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
1254 /// from the `remainder` function of the iterator.
1255 ///
1256 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1257 /// resulting code better than in the case of [`chunks`].
1258 ///
1259 /// See [`chunks`] for a variant of this iterator that also returns the remainder as a smaller
1260 /// chunk, and [`rchunks_exact`] for the same iterator but starting at the end of the slice.
1261 ///
1262 /// If your `chunk_size` is a constant, consider using [`as_chunks`] instead, which will
1263 /// give references to arrays of exactly that length, rather than slices.
1264 ///
1265 /// # Panics
1266 ///
1267 /// Panics if `chunk_size` is zero.
1268 ///
1269 /// # Examples
1270 ///
1271 /// ```
1272 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1273 /// let mut iter = slice.chunks_exact(2);
1274 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
1275 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
1276 /// assert!(iter.next().is_none());
1277 /// assert_eq!(iter.remainder(), &['m']);
1278 /// ```
1279 ///
1280 /// [`chunks`]: slice::chunks
1281 /// [`rchunks_exact`]: slice::rchunks_exact
1282 /// [`as_chunks`]: slice::as_chunks
1283 #[stable(feature = "chunks_exact", since = "1.31.0")]
1284 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1285 #[inline]
1286 #[track_caller]
1287 #[cfg(not(feature = "ferrocene_certified"))]
1288 pub const fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> {
1289 assert!(chunk_size != 0, "chunk size must be non-zero");
1290 ChunksExact::new(self, chunk_size)
1291 }
1292
1293 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
1294 /// beginning of the slice.
1295 ///
1296 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1297 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
1298 /// retrieved from the `into_remainder` function of the iterator.
1299 ///
1300 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1301 /// resulting code better than in the case of [`chunks_mut`].
1302 ///
1303 /// See [`chunks_mut`] for a variant of this iterator that also returns the remainder as a
1304 /// smaller chunk, and [`rchunks_exact_mut`] for the same iterator but starting at the end of
1305 /// the slice.
1306 ///
1307 /// If your `chunk_size` is a constant, consider using [`as_chunks_mut`] instead, which will
1308 /// give references to arrays of exactly that length, rather than slices.
1309 ///
1310 /// # Panics
1311 ///
1312 /// Panics if `chunk_size` is zero.
1313 ///
1314 /// # Examples
1315 ///
1316 /// ```
1317 /// let v = &mut [0, 0, 0, 0, 0];
1318 /// let mut count = 1;
1319 ///
1320 /// for chunk in v.chunks_exact_mut(2) {
1321 /// for elem in chunk.iter_mut() {
1322 /// *elem += count;
1323 /// }
1324 /// count += 1;
1325 /// }
1326 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
1327 /// ```
1328 ///
1329 /// [`chunks_mut`]: slice::chunks_mut
1330 /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
1331 /// [`as_chunks_mut`]: slice::as_chunks_mut
1332 #[stable(feature = "chunks_exact", since = "1.31.0")]
1333 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1334 #[inline]
1335 #[track_caller]
1336 #[cfg(not(feature = "ferrocene_certified"))]
1337 pub const fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> {
1338 assert!(chunk_size != 0, "chunk size must be non-zero");
1339 ChunksExactMut::new(self, chunk_size)
1340 }
1341
1342 /// Splits the slice into a slice of `N`-element arrays,
1343 /// assuming that there's no remainder.
1344 ///
1345 /// This is the inverse operation to [`as_flattened`].
1346 ///
1347 /// [`as_flattened`]: slice::as_flattened
1348 ///
1349 /// As this is `unsafe`, consider whether you could use [`as_chunks`] or
1350 /// [`as_rchunks`] instead, perhaps via something like
1351 /// `if let (chunks, []) = slice.as_chunks()` or
1352 /// `let (chunks, []) = slice.as_chunks() else { unreachable!() };`.
1353 ///
1354 /// [`as_chunks`]: slice::as_chunks
1355 /// [`as_rchunks`]: slice::as_rchunks
1356 ///
1357 /// # Safety
1358 ///
1359 /// This may only be called when
1360 /// - The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).
1361 /// - `N != 0`.
1362 ///
1363 /// # Examples
1364 ///
1365 /// ```
1366 /// let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!'];
1367 /// let chunks: &[[char; 1]] =
1368 /// // SAFETY: 1-element chunks never have remainder
1369 /// unsafe { slice.as_chunks_unchecked() };
1370 /// assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]);
1371 /// let chunks: &[[char; 3]] =
1372 /// // SAFETY: The slice length (6) is a multiple of 3
1373 /// unsafe { slice.as_chunks_unchecked() };
1374 /// assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]);
1375 ///
1376 /// // These would be unsound:
1377 /// // let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5
1378 /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed
1379 /// ```
1380 #[stable(feature = "slice_as_chunks", since = "1.88.0")]
1381 #[rustc_const_stable(feature = "slice_as_chunks", since = "1.88.0")]
1382 #[inline]
1383 #[must_use]
1384 #[track_caller]
1385 #[cfg(not(feature = "ferrocene_certified"))]
1386 pub const unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]] {
1387 assert_unsafe_precondition!(
1388 check_language_ub,
1389 "slice::as_chunks_unchecked requires `N != 0` and the slice to split exactly into `N`-element chunks",
1390 (n: usize = N, len: usize = self.len()) => n != 0 && len.is_multiple_of(n),
1391 );
1392 // SAFETY: Caller must guarantee that `N` is nonzero and exactly divides the slice length
1393 let new_len = unsafe { exact_div(self.len(), N) };
1394 // SAFETY: We cast a slice of `new_len * N` elements into
1395 // a slice of `new_len` many `N` elements chunks.
1396 unsafe { from_raw_parts(self.as_ptr().cast(), new_len) }
1397 }
1398
1399 /// Splits the slice into a slice of `N`-element arrays,
1400 /// starting at the beginning of the slice,
1401 /// and a remainder slice with length strictly less than `N`.
1402 ///
1403 /// The remainder is meaningful in the division sense. Given
1404 /// `let (chunks, remainder) = slice.as_chunks()`, then:
1405 /// - `chunks.len()` equals `slice.len() / N`,
1406 /// - `remainder.len()` equals `slice.len() % N`, and
1407 /// - `slice.len()` equals `chunks.len() * N + remainder.len()`.
1408 ///
1409 /// You can flatten the chunks back into a slice-of-`T` with [`as_flattened`].
1410 ///
1411 /// [`as_flattened`]: slice::as_flattened
1412 ///
1413 /// # Panics
1414 ///
1415 /// Panics if `N` is zero.
1416 ///
1417 /// Note that this check is against a const generic parameter, not a runtime
1418 /// value, and thus a particular monomorphization will either always panic
1419 /// or it will never panic.
1420 ///
1421 /// # Examples
1422 ///
1423 /// ```
1424 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1425 /// let (chunks, remainder) = slice.as_chunks();
1426 /// assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);
1427 /// assert_eq!(remainder, &['m']);
1428 /// ```
1429 ///
1430 /// If you expect the slice to be an exact multiple, you can combine
1431 /// `let`-`else` with an empty slice pattern:
1432 /// ```
1433 /// let slice = ['R', 'u', 's', 't'];
1434 /// let (chunks, []) = slice.as_chunks::<2>() else {
1435 /// panic!("slice didn't have even length")
1436 /// };
1437 /// assert_eq!(chunks, &[['R', 'u'], ['s', 't']]);
1438 /// ```
1439 #[stable(feature = "slice_as_chunks", since = "1.88.0")]
1440 #[rustc_const_stable(feature = "slice_as_chunks", since = "1.88.0")]
1441 #[inline]
1442 #[track_caller]
1443 #[must_use]
1444 #[cfg(not(feature = "ferrocene_certified"))]
1445 pub const fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T]) {
1446 assert!(N != 0, "chunk size must be non-zero");
1447 let len_rounded_down = self.len() / N * N;
1448 // SAFETY: The rounded-down value is always the same or smaller than the
1449 // original length, and thus must be in-bounds of the slice.
1450 let (multiple_of_n, remainder) = unsafe { self.split_at_unchecked(len_rounded_down) };
1451 // SAFETY: We already panicked for zero, and ensured by construction
1452 // that the length of the subslice is a multiple of N.
1453 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() };
1454 (array_slice, remainder)
1455 }
1456
1457 /// Splits the slice into a slice of `N`-element arrays,
1458 /// starting at the end of the slice,
1459 /// and a remainder slice with length strictly less than `N`.
1460 ///
1461 /// The remainder is meaningful in the division sense. Given
1462 /// `let (remainder, chunks) = slice.as_rchunks()`, then:
1463 /// - `remainder.len()` equals `slice.len() % N`,
1464 /// - `chunks.len()` equals `slice.len() / N`, and
1465 /// - `slice.len()` equals `chunks.len() * N + remainder.len()`.
1466 ///
1467 /// You can flatten the chunks back into a slice-of-`T` with [`as_flattened`].
1468 ///
1469 /// [`as_flattened`]: slice::as_flattened
1470 ///
1471 /// # Panics
1472 ///
1473 /// Panics if `N` is zero.
1474 ///
1475 /// Note that this check is against a const generic parameter, not a runtime
1476 /// value, and thus a particular monomorphization will either always panic
1477 /// or it will never panic.
1478 ///
1479 /// # Examples
1480 ///
1481 /// ```
1482 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1483 /// let (remainder, chunks) = slice.as_rchunks();
1484 /// assert_eq!(remainder, &['l']);
1485 /// assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
1486 /// ```
1487 #[stable(feature = "slice_as_chunks", since = "1.88.0")]
1488 #[rustc_const_stable(feature = "slice_as_chunks", since = "1.88.0")]
1489 #[inline]
1490 #[track_caller]
1491 #[must_use]
1492 #[cfg(not(feature = "ferrocene_certified"))]
1493 pub const fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]]) {
1494 assert!(N != 0, "chunk size must be non-zero");
1495 let len = self.len() / N;
1496 let (remainder, multiple_of_n) = self.split_at(self.len() - len * N);
1497 // SAFETY: We already panicked for zero, and ensured by construction
1498 // that the length of the subslice is a multiple of N.
1499 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked() };
1500 (remainder, array_slice)
1501 }
1502
1503 /// Splits the slice into a slice of `N`-element arrays,
1504 /// assuming that there's no remainder.
1505 ///
1506 /// This is the inverse operation to [`as_flattened_mut`].
1507 ///
1508 /// [`as_flattened_mut`]: slice::as_flattened_mut
1509 ///
1510 /// As this is `unsafe`, consider whether you could use [`as_chunks_mut`] or
1511 /// [`as_rchunks_mut`] instead, perhaps via something like
1512 /// `if let (chunks, []) = slice.as_chunks_mut()` or
1513 /// `let (chunks, []) = slice.as_chunks_mut() else { unreachable!() };`.
1514 ///
1515 /// [`as_chunks_mut`]: slice::as_chunks_mut
1516 /// [`as_rchunks_mut`]: slice::as_rchunks_mut
1517 ///
1518 /// # Safety
1519 ///
1520 /// This may only be called when
1521 /// - The slice splits exactly into `N`-element chunks (aka `self.len() % N == 0`).
1522 /// - `N != 0`.
1523 ///
1524 /// # Examples
1525 ///
1526 /// ```
1527 /// let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!'];
1528 /// let chunks: &mut [[char; 1]] =
1529 /// // SAFETY: 1-element chunks never have remainder
1530 /// unsafe { slice.as_chunks_unchecked_mut() };
1531 /// chunks[0] = ['L'];
1532 /// assert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]);
1533 /// let chunks: &mut [[char; 3]] =
1534 /// // SAFETY: The slice length (6) is a multiple of 3
1535 /// unsafe { slice.as_chunks_unchecked_mut() };
1536 /// chunks[1] = ['a', 'x', '?'];
1537 /// assert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']);
1538 ///
1539 /// // These would be unsound:
1540 /// // let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 5
1541 /// // let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed
1542 /// ```
1543 #[stable(feature = "slice_as_chunks", since = "1.88.0")]
1544 #[rustc_const_stable(feature = "slice_as_chunks", since = "1.88.0")]
1545 #[inline]
1546 #[must_use]
1547 #[track_caller]
1548 #[cfg(not(feature = "ferrocene_certified"))]
1549 pub const unsafe fn as_chunks_unchecked_mut<const N: usize>(&mut self) -> &mut [[T; N]] {
1550 assert_unsafe_precondition!(
1551 check_language_ub,
1552 "slice::as_chunks_unchecked requires `N != 0` and the slice to split exactly into `N`-element chunks",
1553 (n: usize = N, len: usize = self.len()) => n != 0 && len.is_multiple_of(n)
1554 );
1555 // SAFETY: Caller must guarantee that `N` is nonzero and exactly divides the slice length
1556 let new_len = unsafe { exact_div(self.len(), N) };
1557 // SAFETY: We cast a slice of `new_len * N` elements into
1558 // a slice of `new_len` many `N` elements chunks.
1559 unsafe { from_raw_parts_mut(self.as_mut_ptr().cast(), new_len) }
1560 }
1561
1562 /// Splits the slice into a slice of `N`-element arrays,
1563 /// starting at the beginning of the slice,
1564 /// and a remainder slice with length strictly less than `N`.
1565 ///
1566 /// The remainder is meaningful in the division sense. Given
1567 /// `let (chunks, remainder) = slice.as_chunks_mut()`, then:
1568 /// - `chunks.len()` equals `slice.len() / N`,
1569 /// - `remainder.len()` equals `slice.len() % N`, and
1570 /// - `slice.len()` equals `chunks.len() * N + remainder.len()`.
1571 ///
1572 /// You can flatten the chunks back into a slice-of-`T` with [`as_flattened_mut`].
1573 ///
1574 /// [`as_flattened_mut`]: slice::as_flattened_mut
1575 ///
1576 /// # Panics
1577 ///
1578 /// Panics if `N` is zero.
1579 ///
1580 /// Note that this check is against a const generic parameter, not a runtime
1581 /// value, and thus a particular monomorphization will either always panic
1582 /// or it will never panic.
1583 ///
1584 /// # Examples
1585 ///
1586 /// ```
1587 /// let v = &mut [0, 0, 0, 0, 0];
1588 /// let mut count = 1;
1589 ///
1590 /// let (chunks, remainder) = v.as_chunks_mut();
1591 /// remainder[0] = 9;
1592 /// for chunk in chunks {
1593 /// *chunk = [count; 2];
1594 /// count += 1;
1595 /// }
1596 /// assert_eq!(v, &[1, 1, 2, 2, 9]);
1597 /// ```
1598 #[stable(feature = "slice_as_chunks", since = "1.88.0")]
1599 #[rustc_const_stable(feature = "slice_as_chunks", since = "1.88.0")]
1600 #[inline]
1601 #[track_caller]
1602 #[must_use]
1603 #[cfg(not(feature = "ferrocene_certified"))]
1604 pub const fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T]) {
1605 assert!(N != 0, "chunk size must be non-zero");
1606 let len_rounded_down = self.len() / N * N;
1607 // SAFETY: The rounded-down value is always the same or smaller than the
1608 // original length, and thus must be in-bounds of the slice.
1609 let (multiple_of_n, remainder) = unsafe { self.split_at_mut_unchecked(len_rounded_down) };
1610 // SAFETY: We already panicked for zero, and ensured by construction
1611 // that the length of the subslice is a multiple of N.
1612 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };
1613 (array_slice, remainder)
1614 }
1615
1616 /// Splits the slice into a slice of `N`-element arrays,
1617 /// starting at the end of the slice,
1618 /// and a remainder slice with length strictly less than `N`.
1619 ///
1620 /// The remainder is meaningful in the division sense. Given
1621 /// `let (remainder, chunks) = slice.as_rchunks_mut()`, then:
1622 /// - `remainder.len()` equals `slice.len() % N`,
1623 /// - `chunks.len()` equals `slice.len() / N`, and
1624 /// - `slice.len()` equals `chunks.len() * N + remainder.len()`.
1625 ///
1626 /// You can flatten the chunks back into a slice-of-`T` with [`as_flattened_mut`].
1627 ///
1628 /// [`as_flattened_mut`]: slice::as_flattened_mut
1629 ///
1630 /// # Panics
1631 ///
1632 /// Panics if `N` is zero.
1633 ///
1634 /// Note that this check is against a const generic parameter, not a runtime
1635 /// value, and thus a particular monomorphization will either always panic
1636 /// or it will never panic.
1637 ///
1638 /// # Examples
1639 ///
1640 /// ```
1641 /// let v = &mut [0, 0, 0, 0, 0];
1642 /// let mut count = 1;
1643 ///
1644 /// let (remainder, chunks) = v.as_rchunks_mut();
1645 /// remainder[0] = 9;
1646 /// for chunk in chunks {
1647 /// *chunk = [count; 2];
1648 /// count += 1;
1649 /// }
1650 /// assert_eq!(v, &[9, 1, 1, 2, 2]);
1651 /// ```
1652 #[stable(feature = "slice_as_chunks", since = "1.88.0")]
1653 #[rustc_const_stable(feature = "slice_as_chunks", since = "1.88.0")]
1654 #[inline]
1655 #[track_caller]
1656 #[must_use]
1657 #[cfg(not(feature = "ferrocene_certified"))]
1658 pub const fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]]) {
1659 assert!(N != 0, "chunk size must be non-zero");
1660 let len = self.len() / N;
1661 let (remainder, multiple_of_n) = self.split_at_mut(self.len() - len * N);
1662 // SAFETY: We already panicked for zero, and ensured by construction
1663 // that the length of the subslice is a multiple of N.
1664 let array_slice = unsafe { multiple_of_n.as_chunks_unchecked_mut() };
1665 (remainder, array_slice)
1666 }
1667
1668 /// Returns an iterator over overlapping windows of `N` elements of a slice,
1669 /// starting at the beginning of the slice.
1670 ///
1671 /// This is the const generic equivalent of [`windows`].
1672 ///
1673 /// If `N` is greater than the size of the slice, it will return no windows.
1674 ///
1675 /// # Panics
1676 ///
1677 /// Panics if `N` is zero. This check will most probably get changed to a compile time
1678 /// error before this method gets stabilized.
1679 ///
1680 /// # Examples
1681 ///
1682 /// ```
1683 /// #![feature(array_windows)]
1684 /// let slice = [0, 1, 2, 3];
1685 /// let mut iter = slice.array_windows();
1686 /// assert_eq!(iter.next().unwrap(), &[0, 1]);
1687 /// assert_eq!(iter.next().unwrap(), &[1, 2]);
1688 /// assert_eq!(iter.next().unwrap(), &[2, 3]);
1689 /// assert!(iter.next().is_none());
1690 /// ```
1691 ///
1692 /// [`windows`]: slice::windows
1693 #[unstable(feature = "array_windows", issue = "75027")]
1694 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1695 #[inline]
1696 #[track_caller]
1697 #[cfg(not(feature = "ferrocene_certified"))]
1698 pub const fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N> {
1699 assert!(N != 0, "window size must be non-zero");
1700 ArrayWindows::new(self)
1701 }
1702
1703 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1704 /// of the slice.
1705 ///
1706 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1707 /// slice, then the last chunk will not have length `chunk_size`.
1708 ///
1709 /// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always exactly
1710 /// `chunk_size` elements, and [`chunks`] for the same iterator but starting at the beginning
1711 /// of the slice.
1712 ///
1713 /// If your `chunk_size` is a constant, consider using [`as_rchunks`] instead, which will
1714 /// give references to arrays of exactly that length, rather than slices.
1715 ///
1716 /// # Panics
1717 ///
1718 /// Panics if `chunk_size` is zero.
1719 ///
1720 /// # Examples
1721 ///
1722 /// ```
1723 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1724 /// let mut iter = slice.rchunks(2);
1725 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1726 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1727 /// assert_eq!(iter.next().unwrap(), &['l']);
1728 /// assert!(iter.next().is_none());
1729 /// ```
1730 ///
1731 /// [`rchunks_exact`]: slice::rchunks_exact
1732 /// [`chunks`]: slice::chunks
1733 /// [`as_rchunks`]: slice::as_rchunks
1734 #[stable(feature = "rchunks", since = "1.31.0")]
1735 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1736 #[inline]
1737 #[track_caller]
1738 #[cfg(not(feature = "ferrocene_certified"))]
1739 pub const fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> {
1740 assert!(chunk_size != 0, "chunk size must be non-zero");
1741 RChunks::new(self, chunk_size)
1742 }
1743
1744 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1745 /// of the slice.
1746 ///
1747 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1748 /// length of the slice, then the last chunk will not have length `chunk_size`.
1749 ///
1750 /// See [`rchunks_exact_mut`] for a variant of this iterator that returns chunks of always
1751 /// exactly `chunk_size` elements, and [`chunks_mut`] for the same iterator but starting at the
1752 /// beginning of the slice.
1753 ///
1754 /// If your `chunk_size` is a constant, consider using [`as_rchunks_mut`] instead, which will
1755 /// give references to arrays of exactly that length, rather than slices.
1756 ///
1757 /// # Panics
1758 ///
1759 /// Panics if `chunk_size` is zero.
1760 ///
1761 /// # Examples
1762 ///
1763 /// ```
1764 /// let v = &mut [0, 0, 0, 0, 0];
1765 /// let mut count = 1;
1766 ///
1767 /// for chunk in v.rchunks_mut(2) {
1768 /// for elem in chunk.iter_mut() {
1769 /// *elem += count;
1770 /// }
1771 /// count += 1;
1772 /// }
1773 /// assert_eq!(v, &[3, 2, 2, 1, 1]);
1774 /// ```
1775 ///
1776 /// [`rchunks_exact_mut`]: slice::rchunks_exact_mut
1777 /// [`chunks_mut`]: slice::chunks_mut
1778 /// [`as_rchunks_mut`]: slice::as_rchunks_mut
1779 #[stable(feature = "rchunks", since = "1.31.0")]
1780 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1781 #[inline]
1782 #[track_caller]
1783 #[cfg(not(feature = "ferrocene_certified"))]
1784 pub const fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> {
1785 assert!(chunk_size != 0, "chunk size must be non-zero");
1786 RChunksMut::new(self, chunk_size)
1787 }
1788
1789 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
1790 /// end of the slice.
1791 ///
1792 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
1793 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
1794 /// from the `remainder` function of the iterator.
1795 ///
1796 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1797 /// resulting code better than in the case of [`rchunks`].
1798 ///
1799 /// See [`rchunks`] for a variant of this iterator that also returns the remainder as a smaller
1800 /// chunk, and [`chunks_exact`] for the same iterator but starting at the beginning of the
1801 /// slice.
1802 ///
1803 /// If your `chunk_size` is a constant, consider using [`as_rchunks`] instead, which will
1804 /// give references to arrays of exactly that length, rather than slices.
1805 ///
1806 /// # Panics
1807 ///
1808 /// Panics if `chunk_size` is zero.
1809 ///
1810 /// # Examples
1811 ///
1812 /// ```
1813 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1814 /// let mut iter = slice.rchunks_exact(2);
1815 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
1816 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
1817 /// assert!(iter.next().is_none());
1818 /// assert_eq!(iter.remainder(), &['l']);
1819 /// ```
1820 ///
1821 /// [`chunks`]: slice::chunks
1822 /// [`rchunks`]: slice::rchunks
1823 /// [`chunks_exact`]: slice::chunks_exact
1824 /// [`as_rchunks`]: slice::as_rchunks
1825 #[stable(feature = "rchunks", since = "1.31.0")]
1826 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1827 #[inline]
1828 #[track_caller]
1829 #[cfg(not(feature = "ferrocene_certified"))]
1830 pub const fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> {
1831 assert!(chunk_size != 0, "chunk size must be non-zero");
1832 RChunksExact::new(self, chunk_size)
1833 }
1834
1835 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
1836 /// of the slice.
1837 ///
1838 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
1839 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
1840 /// retrieved from the `into_remainder` function of the iterator.
1841 ///
1842 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
1843 /// resulting code better than in the case of [`chunks_mut`].
1844 ///
1845 /// See [`rchunks_mut`] for a variant of this iterator that also returns the remainder as a
1846 /// smaller chunk, and [`chunks_exact_mut`] for the same iterator but starting at the beginning
1847 /// of the slice.
1848 ///
1849 /// If your `chunk_size` is a constant, consider using [`as_rchunks_mut`] instead, which will
1850 /// give references to arrays of exactly that length, rather than slices.
1851 ///
1852 /// # Panics
1853 ///
1854 /// Panics if `chunk_size` is zero.
1855 ///
1856 /// # Examples
1857 ///
1858 /// ```
1859 /// let v = &mut [0, 0, 0, 0, 0];
1860 /// let mut count = 1;
1861 ///
1862 /// for chunk in v.rchunks_exact_mut(2) {
1863 /// for elem in chunk.iter_mut() {
1864 /// *elem += count;
1865 /// }
1866 /// count += 1;
1867 /// }
1868 /// assert_eq!(v, &[0, 2, 2, 1, 1]);
1869 /// ```
1870 ///
1871 /// [`chunks_mut`]: slice::chunks_mut
1872 /// [`rchunks_mut`]: slice::rchunks_mut
1873 /// [`chunks_exact_mut`]: slice::chunks_exact_mut
1874 /// [`as_rchunks_mut`]: slice::as_rchunks_mut
1875 #[stable(feature = "rchunks", since = "1.31.0")]
1876 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1877 #[inline]
1878 #[track_caller]
1879 #[cfg(not(feature = "ferrocene_certified"))]
1880 pub const fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> {
1881 assert!(chunk_size != 0, "chunk size must be non-zero");
1882 RChunksExactMut::new(self, chunk_size)
1883 }
1884
1885 /// Returns an iterator over the slice producing non-overlapping runs
1886 /// of elements using the predicate to separate them.
1887 ///
1888 /// The predicate is called for every pair of consecutive elements,
1889 /// meaning that it is called on `slice[0]` and `slice[1]`,
1890 /// followed by `slice[1]` and `slice[2]`, and so on.
1891 ///
1892 /// # Examples
1893 ///
1894 /// ```
1895 /// let slice = &[1, 1, 1, 3, 3, 2, 2, 2];
1896 ///
1897 /// let mut iter = slice.chunk_by(|a, b| a == b);
1898 ///
1899 /// assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
1900 /// assert_eq!(iter.next(), Some(&[3, 3][..]));
1901 /// assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
1902 /// assert_eq!(iter.next(), None);
1903 /// ```
1904 ///
1905 /// This method can be used to extract the sorted subslices:
1906 ///
1907 /// ```
1908 /// let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];
1909 ///
1910 /// let mut iter = slice.chunk_by(|a, b| a <= b);
1911 ///
1912 /// assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));
1913 /// assert_eq!(iter.next(), Some(&[2, 3][..]));
1914 /// assert_eq!(iter.next(), Some(&[2, 3, 4][..]));
1915 /// assert_eq!(iter.next(), None);
1916 /// ```
1917 #[stable(feature = "slice_group_by", since = "1.77.0")]
1918 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1919 #[inline]
1920 #[cfg(not(feature = "ferrocene_certified"))]
1921 pub const fn chunk_by<F>(&self, pred: F) -> ChunkBy<'_, T, F>
1922 where
1923 F: FnMut(&T, &T) -> bool,
1924 {
1925 ChunkBy::new(self, pred)
1926 }
1927
1928 /// Returns an iterator over the slice producing non-overlapping mutable
1929 /// runs of elements using the predicate to separate them.
1930 ///
1931 /// The predicate is called for every pair of consecutive elements,
1932 /// meaning that it is called on `slice[0]` and `slice[1]`,
1933 /// followed by `slice[1]` and `slice[2]`, and so on.
1934 ///
1935 /// # Examples
1936 ///
1937 /// ```
1938 /// let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2];
1939 ///
1940 /// let mut iter = slice.chunk_by_mut(|a, b| a == b);
1941 ///
1942 /// assert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));
1943 /// assert_eq!(iter.next(), Some(&mut [3, 3][..]));
1944 /// assert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));
1945 /// assert_eq!(iter.next(), None);
1946 /// ```
1947 ///
1948 /// This method can be used to extract the sorted subslices:
1949 ///
1950 /// ```
1951 /// let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4];
1952 ///
1953 /// let mut iter = slice.chunk_by_mut(|a, b| a <= b);
1954 ///
1955 /// assert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..]));
1956 /// assert_eq!(iter.next(), Some(&mut [2, 3][..]));
1957 /// assert_eq!(iter.next(), Some(&mut [2, 3, 4][..]));
1958 /// assert_eq!(iter.next(), None);
1959 /// ```
1960 #[stable(feature = "slice_group_by", since = "1.77.0")]
1961 #[rustc_const_unstable(feature = "const_slice_make_iter", issue = "137737")]
1962 #[inline]
1963 #[cfg(not(feature = "ferrocene_certified"))]
1964 pub const fn chunk_by_mut<F>(&mut self, pred: F) -> ChunkByMut<'_, T, F>
1965 where
1966 F: FnMut(&T, &T) -> bool,
1967 {
1968 ChunkByMut::new(self, pred)
1969 }
1970
1971 /// Divides one slice into two at an index.
1972 ///
1973 /// The first will contain all indices from `[0, mid)` (excluding
1974 /// the index `mid` itself) and the second will contain all
1975 /// indices from `[mid, len)` (excluding the index `len` itself).
1976 ///
1977 /// # Panics
1978 ///
1979 /// Panics if `mid > len`. For a non-panicking alternative see
1980 /// [`split_at_checked`](slice::split_at_checked).
1981 ///
1982 /// # Examples
1983 ///
1984 /// ```
1985 /// let v = ['a', 'b', 'c'];
1986 ///
1987 /// {
1988 /// let (left, right) = v.split_at(0);
1989 /// assert_eq!(left, []);
1990 /// assert_eq!(right, ['a', 'b', 'c']);
1991 /// }
1992 ///
1993 /// {
1994 /// let (left, right) = v.split_at(2);
1995 /// assert_eq!(left, ['a', 'b']);
1996 /// assert_eq!(right, ['c']);
1997 /// }
1998 ///
1999 /// {
2000 /// let (left, right) = v.split_at(3);
2001 /// assert_eq!(left, ['a', 'b', 'c']);
2002 /// assert_eq!(right, []);
2003 /// }
2004 /// ```
2005 #[stable(feature = "rust1", since = "1.0.0")]
2006 #[rustc_const_stable(feature = "const_slice_split_at_not_mut", since = "1.71.0")]
2007 #[inline]
2008 #[track_caller]
2009 #[must_use]
2010 pub const fn split_at(&self, mid: usize) -> (&[T], &[T]) {
2011 match self.split_at_checked(mid) {
2012 Some(pair) => pair,
2013 None => panic!("mid > len"),
2014 }
2015 }
2016
2017 /// Divides one mutable slice into two at an index.
2018 ///
2019 /// The first will contain all indices from `[0, mid)` (excluding
2020 /// the index `mid` itself) and the second will contain all
2021 /// indices from `[mid, len)` (excluding the index `len` itself).
2022 ///
2023 /// # Panics
2024 ///
2025 /// Panics if `mid > len`. For a non-panicking alternative see
2026 /// [`split_at_mut_checked`](slice::split_at_mut_checked).
2027 ///
2028 /// # Examples
2029 ///
2030 /// ```
2031 /// let mut v = [1, 0, 3, 0, 5, 6];
2032 /// let (left, right) = v.split_at_mut(2);
2033 /// assert_eq!(left, [1, 0]);
2034 /// assert_eq!(right, [3, 0, 5, 6]);
2035 /// left[1] = 2;
2036 /// right[1] = 4;
2037 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
2038 /// ```
2039 #[stable(feature = "rust1", since = "1.0.0")]
2040 #[inline]
2041 #[track_caller]
2042 #[must_use]
2043 #[rustc_const_stable(feature = "const_slice_split_at_mut", since = "1.83.0")]
2044 #[cfg(not(feature = "ferrocene_certified"))]
2045 pub const fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
2046 match self.split_at_mut_checked(mid) {
2047 Some(pair) => pair,
2048 None => panic!("mid > len"),
2049 }
2050 }
2051
2052 /// Divides one slice into two at an index, without doing bounds checking.
2053 ///
2054 /// The first will contain all indices from `[0, mid)` (excluding
2055 /// the index `mid` itself) and the second will contain all
2056 /// indices from `[mid, len)` (excluding the index `len` itself).
2057 ///
2058 /// For a safe alternative see [`split_at`].
2059 ///
2060 /// # Safety
2061 ///
2062 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
2063 /// even if the resulting reference is not used. The caller has to ensure that
2064 /// `0 <= mid <= self.len()`.
2065 ///
2066 /// [`split_at`]: slice::split_at
2067 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2068 ///
2069 /// # Examples
2070 ///
2071 /// ```
2072 /// let v = ['a', 'b', 'c'];
2073 ///
2074 /// unsafe {
2075 /// let (left, right) = v.split_at_unchecked(0);
2076 /// assert_eq!(left, []);
2077 /// assert_eq!(right, ['a', 'b', 'c']);
2078 /// }
2079 ///
2080 /// unsafe {
2081 /// let (left, right) = v.split_at_unchecked(2);
2082 /// assert_eq!(left, ['a', 'b']);
2083 /// assert_eq!(right, ['c']);
2084 /// }
2085 ///
2086 /// unsafe {
2087 /// let (left, right) = v.split_at_unchecked(3);
2088 /// assert_eq!(left, ['a', 'b', 'c']);
2089 /// assert_eq!(right, []);
2090 /// }
2091 /// ```
2092 #[stable(feature = "slice_split_at_unchecked", since = "1.79.0")]
2093 #[rustc_const_stable(feature = "const_slice_split_at_unchecked", since = "1.77.0")]
2094 #[inline]
2095 #[must_use]
2096 #[track_caller]
2097 pub const unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T]) {
2098 // FIXME(const-hack): the const function `from_raw_parts` is used to make this
2099 // function const; previously the implementation used
2100 // `(self.get_unchecked(..mid), self.get_unchecked(mid..))`
2101
2102 let len = self.len();
2103 let ptr = self.as_ptr();
2104
2105 assert_unsafe_precondition!(
2106 check_library_ub,
2107 "slice::split_at_unchecked requires the index to be within the slice",
2108 (mid: usize = mid, len: usize = len) => mid <= len,
2109 );
2110
2111 // SAFETY: Caller has to check that `0 <= mid <= self.len()`
2112 unsafe { (from_raw_parts(ptr, mid), from_raw_parts(ptr.add(mid), unchecked_sub(len, mid))) }
2113 }
2114
2115 /// Divides one mutable slice into two at an index, without doing bounds checking.
2116 ///
2117 /// The first will contain all indices from `[0, mid)` (excluding
2118 /// the index `mid` itself) and the second will contain all
2119 /// indices from `[mid, len)` (excluding the index `len` itself).
2120 ///
2121 /// For a safe alternative see [`split_at_mut`].
2122 ///
2123 /// # Safety
2124 ///
2125 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
2126 /// even if the resulting reference is not used. The caller has to ensure that
2127 /// `0 <= mid <= self.len()`.
2128 ///
2129 /// [`split_at_mut`]: slice::split_at_mut
2130 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2131 ///
2132 /// # Examples
2133 ///
2134 /// ```
2135 /// let mut v = [1, 0, 3, 0, 5, 6];
2136 /// // scoped to restrict the lifetime of the borrows
2137 /// unsafe {
2138 /// let (left, right) = v.split_at_mut_unchecked(2);
2139 /// assert_eq!(left, [1, 0]);
2140 /// assert_eq!(right, [3, 0, 5, 6]);
2141 /// left[1] = 2;
2142 /// right[1] = 4;
2143 /// }
2144 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
2145 /// ```
2146 #[stable(feature = "slice_split_at_unchecked", since = "1.79.0")]
2147 #[rustc_const_stable(feature = "const_slice_split_at_mut", since = "1.83.0")]
2148 #[inline]
2149 #[must_use]
2150 #[track_caller]
2151 #[cfg(not(feature = "ferrocene_certified"))]
2152 pub const unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
2153 let len = self.len();
2154 let ptr = self.as_mut_ptr();
2155
2156 assert_unsafe_precondition!(
2157 check_library_ub,
2158 "slice::split_at_mut_unchecked requires the index to be within the slice",
2159 (mid: usize = mid, len: usize = len) => mid <= len,
2160 );
2161
2162 // SAFETY: Caller has to check that `0 <= mid <= self.len()`.
2163 //
2164 // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference
2165 // is fine.
2166 unsafe {
2167 (
2168 from_raw_parts_mut(ptr, mid),
2169 from_raw_parts_mut(ptr.add(mid), unchecked_sub(len, mid)),
2170 )
2171 }
2172 }
2173
2174 /// Divides one slice into two at an index, returning `None` if the slice is
2175 /// too short.
2176 ///
2177 /// If `mid ≤ len` returns a pair of slices where the first will contain all
2178 /// indices from `[0, mid)` (excluding the index `mid` itself) and the
2179 /// second will contain all indices from `[mid, len)` (excluding the index
2180 /// `len` itself).
2181 ///
2182 /// Otherwise, if `mid > len`, returns `None`.
2183 ///
2184 /// # Examples
2185 ///
2186 /// ```
2187 /// let v = [1, -2, 3, -4, 5, -6];
2188 ///
2189 /// {
2190 /// let (left, right) = v.split_at_checked(0).unwrap();
2191 /// assert_eq!(left, []);
2192 /// assert_eq!(right, [1, -2, 3, -4, 5, -6]);
2193 /// }
2194 ///
2195 /// {
2196 /// let (left, right) = v.split_at_checked(2).unwrap();
2197 /// assert_eq!(left, [1, -2]);
2198 /// assert_eq!(right, [3, -4, 5, -6]);
2199 /// }
2200 ///
2201 /// {
2202 /// let (left, right) = v.split_at_checked(6).unwrap();
2203 /// assert_eq!(left, [1, -2, 3, -4, 5, -6]);
2204 /// assert_eq!(right, []);
2205 /// }
2206 ///
2207 /// assert_eq!(None, v.split_at_checked(7));
2208 /// ```
2209 #[stable(feature = "split_at_checked", since = "1.80.0")]
2210 #[rustc_const_stable(feature = "split_at_checked", since = "1.80.0")]
2211 #[inline]
2212 #[must_use]
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 pub const fn rotate_left(&mut self, mid: usize) {
3765 assert!(mid <= self.len());
3766 let k = self.len() - mid;
3767 let p = self.as_mut_ptr();
3768
3769 // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
3770 // valid for reading and writing, as required by `ptr_rotate`.
3771 unsafe {
3772 rotate::ptr_rotate(mid, p.add(mid), k);
3773 }
3774 }
3775
3776 /// Rotates the slice in-place such that the first `self.len() - k`
3777 /// elements of the slice move to the end while the last `k` elements move
3778 /// to the front.
3779 ///
3780 /// After calling `rotate_right`, the element previously at index
3781 /// `self.len() - k` will become the first element in the slice.
3782 ///
3783 /// # Panics
3784 ///
3785 /// This function will panic if `k` is greater than the length of the
3786 /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
3787 /// rotation.
3788 ///
3789 /// # Complexity
3790 ///
3791 /// Takes linear (in `self.len()`) time.
3792 ///
3793 /// # Examples
3794 ///
3795 /// ```
3796 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3797 /// a.rotate_right(2);
3798 /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
3799 /// ```
3800 ///
3801 /// Rotating a subslice:
3802 ///
3803 /// ```
3804 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
3805 /// a[1..5].rotate_right(1);
3806 /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
3807 /// ```
3808 #[stable(feature = "slice_rotate", since = "1.26.0")]
3809 #[rustc_const_stable(feature = "const_slice_rotate", since = "1.92.0")]
3810 pub const fn rotate_right(&mut self, k: usize) {
3811 assert!(k <= self.len());
3812 let mid = self.len() - k;
3813 let p = self.as_mut_ptr();
3814
3815 // SAFETY: The range `[p.add(mid) - mid, p.add(mid) + k)` is trivially
3816 // valid for reading and writing, as required by `ptr_rotate`.
3817 unsafe {
3818 rotate::ptr_rotate(mid, p.add(mid), k);
3819 }
3820 }
3821
3822 /// Fills `self` with elements by cloning `value`.
3823 ///
3824 /// # Examples
3825 ///
3826 /// ```
3827 /// let mut buf = vec![0; 10];
3828 /// buf.fill(1);
3829 /// assert_eq!(buf, vec![1; 10]);
3830 /// ```
3831 #[doc(alias = "memset")]
3832 #[stable(feature = "slice_fill", since = "1.50.0")]
3833 pub fn fill(&mut self, value: T)
3834 where
3835 T: Clone,
3836 {
3837 specialize::SpecFill::spec_fill(self, value);
3838 }
3839
3840 /// Fills `self` with elements returned by calling a closure repeatedly.
3841 ///
3842 /// This method uses a closure to create new values. If you'd rather
3843 /// [`Clone`] a given value, use [`fill`]. If you want to use the [`Default`]
3844 /// trait to generate values, you can pass [`Default::default`] as the
3845 /// argument.
3846 ///
3847 /// [`fill`]: slice::fill
3848 ///
3849 /// # Examples
3850 ///
3851 /// ```
3852 /// let mut buf = vec![1; 10];
3853 /// buf.fill_with(Default::default);
3854 /// assert_eq!(buf, vec![0; 10]);
3855 /// ```
3856 #[stable(feature = "slice_fill_with", since = "1.51.0")]
3857 #[cfg(not(feature = "ferrocene_certified"))]
3858 pub fn fill_with<F>(&mut self, mut f: F)
3859 where
3860 F: FnMut() -> T,
3861 {
3862 for el in self {
3863 *el = f();
3864 }
3865 }
3866
3867 /// Copies the elements from `src` into `self`.
3868 ///
3869 /// The length of `src` must be the same as `self`.
3870 ///
3871 /// # Panics
3872 ///
3873 /// This function will panic if the two slices have different lengths.
3874 ///
3875 /// # Examples
3876 ///
3877 /// Cloning two elements from a slice into another:
3878 ///
3879 /// ```
3880 /// let src = [1, 2, 3, 4];
3881 /// let mut dst = [0, 0];
3882 ///
3883 /// // Because the slices have to be the same length,
3884 /// // we slice the source slice from four elements
3885 /// // to two. It will panic if we don't do this.
3886 /// dst.clone_from_slice(&src[2..]);
3887 ///
3888 /// assert_eq!(src, [1, 2, 3, 4]);
3889 /// assert_eq!(dst, [3, 4]);
3890 /// ```
3891 ///
3892 /// Rust enforces that there can only be one mutable reference with no
3893 /// immutable references to a particular piece of data in a particular
3894 /// scope. Because of this, attempting to use `clone_from_slice` on a
3895 /// single slice will result in a compile failure:
3896 ///
3897 /// ```compile_fail
3898 /// let mut slice = [1, 2, 3, 4, 5];
3899 ///
3900 /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
3901 /// ```
3902 ///
3903 /// To work around this, we can use [`split_at_mut`] to create two distinct
3904 /// sub-slices from a slice:
3905 ///
3906 /// ```
3907 /// let mut slice = [1, 2, 3, 4, 5];
3908 ///
3909 /// {
3910 /// let (left, right) = slice.split_at_mut(2);
3911 /// left.clone_from_slice(&right[1..]);
3912 /// }
3913 ///
3914 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
3915 /// ```
3916 ///
3917 /// [`copy_from_slice`]: slice::copy_from_slice
3918 /// [`split_at_mut`]: slice::split_at_mut
3919 #[stable(feature = "clone_from_slice", since = "1.7.0")]
3920 #[track_caller]
3921 #[cfg(not(feature = "ferrocene_certified"))]
3922 pub fn clone_from_slice(&mut self, src: &[T])
3923 where
3924 T: Clone,
3925 {
3926 self.spec_clone_from(src);
3927 }
3928
3929 /// Copies all elements from `src` into `self`, using a memcpy.
3930 ///
3931 /// The length of `src` must be the same as `self`.
3932 ///
3933 /// If `T` does not implement `Copy`, use [`clone_from_slice`].
3934 ///
3935 /// # Panics
3936 ///
3937 /// This function will panic if the two slices have different lengths.
3938 ///
3939 /// # Examples
3940 ///
3941 /// Copying two elements from a slice into another:
3942 ///
3943 /// ```
3944 /// let src = [1, 2, 3, 4];
3945 /// let mut dst = [0, 0];
3946 ///
3947 /// // Because the slices have to be the same length,
3948 /// // we slice the source slice from four elements
3949 /// // to two. It will panic if we don't do this.
3950 /// dst.copy_from_slice(&src[2..]);
3951 ///
3952 /// assert_eq!(src, [1, 2, 3, 4]);
3953 /// assert_eq!(dst, [3, 4]);
3954 /// ```
3955 ///
3956 /// Rust enforces that there can only be one mutable reference with no
3957 /// immutable references to a particular piece of data in a particular
3958 /// scope. Because of this, attempting to use `copy_from_slice` on a
3959 /// single slice will result in a compile failure:
3960 ///
3961 /// ```compile_fail
3962 /// let mut slice = [1, 2, 3, 4, 5];
3963 ///
3964 /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
3965 /// ```
3966 ///
3967 /// To work around this, we can use [`split_at_mut`] to create two distinct
3968 /// sub-slices from a slice:
3969 ///
3970 /// ```
3971 /// let mut slice = [1, 2, 3, 4, 5];
3972 ///
3973 /// {
3974 /// let (left, right) = slice.split_at_mut(2);
3975 /// left.copy_from_slice(&right[1..]);
3976 /// }
3977 ///
3978 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
3979 /// ```
3980 ///
3981 /// [`clone_from_slice`]: slice::clone_from_slice
3982 /// [`split_at_mut`]: slice::split_at_mut
3983 #[doc(alias = "memcpy")]
3984 #[inline]
3985 #[stable(feature = "copy_from_slice", since = "1.9.0")]
3986 #[rustc_const_stable(feature = "const_copy_from_slice", since = "1.87.0")]
3987 #[track_caller]
3988 pub const fn copy_from_slice(&mut self, src: &[T])
3989 where
3990 T: Copy,
3991 {
3992 // SAFETY: `T` implements `Copy`.
3993 unsafe { copy_from_slice_impl(self, src) }
3994 }
3995
3996 /// Copies elements from one part of the slice to another part of itself,
3997 /// using a memmove.
3998 ///
3999 /// `src` is the range within `self` to copy from. `dest` is the starting
4000 /// index of the range within `self` to copy to, which will have the same
4001 /// length as `src`. The two ranges may overlap. The ends of the two ranges
4002 /// must be less than or equal to `self.len()`.
4003 ///
4004 /// # Panics
4005 ///
4006 /// This function will panic if either range exceeds the end of the slice,
4007 /// or if the end of `src` is before the start.
4008 ///
4009 /// # Examples
4010 ///
4011 /// Copying four bytes within a slice:
4012 ///
4013 /// ```
4014 /// let mut bytes = *b"Hello, World!";
4015 ///
4016 /// bytes.copy_within(1..5, 8);
4017 ///
4018 /// assert_eq!(&bytes, b"Hello, Wello!");
4019 /// ```
4020 #[stable(feature = "copy_within", since = "1.37.0")]
4021 #[track_caller]
4022 #[cfg(not(feature = "ferrocene_certified"))]
4023 pub fn copy_within<R: RangeBounds<usize>>(&mut self, src: R, dest: usize)
4024 where
4025 T: Copy,
4026 {
4027 let Range { start: src_start, end: src_end } = slice::range(src, ..self.len());
4028 let count = src_end - src_start;
4029 assert!(dest <= self.len() - count, "dest is out of bounds");
4030 // SAFETY: the conditions for `ptr::copy` have all been checked above,
4031 // as have those for `ptr::add`.
4032 unsafe {
4033 // Derive both `src_ptr` and `dest_ptr` from the same loan
4034 let ptr = self.as_mut_ptr();
4035 let src_ptr = ptr.add(src_start);
4036 let dest_ptr = ptr.add(dest);
4037 ptr::copy(src_ptr, dest_ptr, count);
4038 }
4039 }
4040
4041 /// Swaps all elements in `self` with those in `other`.
4042 ///
4043 /// The length of `other` must be the same as `self`.
4044 ///
4045 /// # Panics
4046 ///
4047 /// This function will panic if the two slices have different lengths.
4048 ///
4049 /// # Example
4050 ///
4051 /// Swapping two elements across slices:
4052 ///
4053 /// ```
4054 /// let mut slice1 = [0, 0];
4055 /// let mut slice2 = [1, 2, 3, 4];
4056 ///
4057 /// slice1.swap_with_slice(&mut slice2[2..]);
4058 ///
4059 /// assert_eq!(slice1, [3, 4]);
4060 /// assert_eq!(slice2, [1, 2, 0, 0]);
4061 /// ```
4062 ///
4063 /// Rust enforces that there can only be one mutable reference to a
4064 /// particular piece of data in a particular scope. Because of this,
4065 /// attempting to use `swap_with_slice` on a single slice will result in
4066 /// a compile failure:
4067 ///
4068 /// ```compile_fail
4069 /// let mut slice = [1, 2, 3, 4, 5];
4070 /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
4071 /// ```
4072 ///
4073 /// To work around this, we can use [`split_at_mut`] to create two distinct
4074 /// mutable sub-slices from a slice:
4075 ///
4076 /// ```
4077 /// let mut slice = [1, 2, 3, 4, 5];
4078 ///
4079 /// {
4080 /// let (left, right) = slice.split_at_mut(2);
4081 /// left.swap_with_slice(&mut right[1..]);
4082 /// }
4083 ///
4084 /// assert_eq!(slice, [4, 5, 3, 1, 2]);
4085 /// ```
4086 ///
4087 /// [`split_at_mut`]: slice::split_at_mut
4088 #[stable(feature = "swap_with_slice", since = "1.27.0")]
4089 #[rustc_const_unstable(feature = "const_swap_with_slice", issue = "142204")]
4090 #[track_caller]
4091 #[cfg(not(feature = "ferrocene_certified"))]
4092 pub const fn swap_with_slice(&mut self, other: &mut [T]) {
4093 assert!(self.len() == other.len(), "destination and source slices have different lengths");
4094 // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
4095 // checked to have the same length. The slices cannot overlap because
4096 // mutable references are exclusive.
4097 unsafe {
4098 ptr::swap_nonoverlapping(self.as_mut_ptr(), other.as_mut_ptr(), self.len());
4099 }
4100 }
4101
4102 /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
4103
4104 #[cfg(not(feature = "ferrocene_certified"))]
4105 fn align_to_offsets<U>(&self) -> (usize, usize) {
4106 // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
4107 // lowest number of `T`s. And how many `T`s we need for each such "multiple".
4108 //
4109 // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
4110 // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
4111 // place of every 3 Ts in the `rest` slice. A bit more complicated.
4112 //
4113 // Formula to calculate this is:
4114 //
4115 // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
4116 // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
4117 //
4118 // Expanded and simplified:
4119 //
4120 // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
4121 // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
4122 //
4123 // Luckily since all this is constant-evaluated... performance here matters not!
4124 const fn gcd(a: usize, b: usize) -> usize {
4125 if b == 0 { a } else { gcd(b, a % b) }
4126 }
4127
4128 // Explicitly wrap the function call in a const block so it gets
4129 // constant-evaluated even in debug mode.
4130 let gcd: usize = const { gcd(size_of::<T>(), size_of::<U>()) };
4131 let ts: usize = size_of::<U>() / gcd;
4132 let us: usize = size_of::<T>() / gcd;
4133
4134 // Armed with this knowledge, we can find how many `U`s we can fit!
4135 let us_len = self.len() / ts * us;
4136 // And how many `T`s will be in the trailing slice!
4137 let ts_len = self.len() % ts;
4138 (us_len, ts_len)
4139 }
4140
4141 /// Transmutes the slice to a slice of another type, ensuring alignment of the types is
4142 /// maintained.
4143 ///
4144 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
4145 /// slice of a new type, and the suffix slice. The middle part will be as big as possible under
4146 /// the given alignment constraint and element size.
4147 ///
4148 /// This method has no purpose when either input element `T` or output element `U` are
4149 /// zero-sized and will return the original slice without splitting anything.
4150 ///
4151 /// # Safety
4152 ///
4153 /// This method is essentially a `transmute` with respect to the elements in the returned
4154 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
4155 ///
4156 /// # Examples
4157 ///
4158 /// Basic usage:
4159 ///
4160 /// ```
4161 /// unsafe {
4162 /// let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
4163 /// let (prefix, shorts, suffix) = bytes.align_to::<u16>();
4164 /// // less_efficient_algorithm_for_bytes(prefix);
4165 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
4166 /// // less_efficient_algorithm_for_bytes(suffix);
4167 /// }
4168 /// ```
4169 #[stable(feature = "slice_align_to", since = "1.30.0")]
4170 #[must_use]
4171 #[cfg(not(feature = "ferrocene_certified"))]
4172 pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
4173 // Note that most of this function will be constant-evaluated,
4174 if U::IS_ZST || T::IS_ZST {
4175 // handle ZSTs specially, which is – don't handle them at all.
4176 return (self, &[], &[]);
4177 }
4178
4179 // First, find at what point do we split between the first and 2nd slice. Easy with
4180 // ptr.align_offset.
4181 let ptr = self.as_ptr();
4182 // SAFETY: See the `align_to_mut` method for the detailed safety comment.
4183 let offset = unsafe { crate::ptr::align_offset(ptr, align_of::<U>()) };
4184 if offset > self.len() {
4185 (self, &[], &[])
4186 } else {
4187 let (left, rest) = self.split_at(offset);
4188 let (us_len, ts_len) = rest.align_to_offsets::<U>();
4189 // Inform Miri that we want to consider the "middle" pointer to be suitably aligned.
4190 #[cfg(miri)]
4191 crate::intrinsics::miri_promise_symbolic_alignment(
4192 rest.as_ptr().cast(),
4193 align_of::<U>(),
4194 );
4195 // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay,
4196 // since the caller guarantees that we can transmute `T` to `U` safely.
4197 unsafe {
4198 (
4199 left,
4200 from_raw_parts(rest.as_ptr() as *const U, us_len),
4201 from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len),
4202 )
4203 }
4204 }
4205 }
4206
4207 /// Transmutes the mutable slice to a mutable slice of another type, ensuring alignment of the
4208 /// types is maintained.
4209 ///
4210 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
4211 /// slice of a new type, and the suffix slice. The middle part will be as big as possible under
4212 /// the given alignment constraint and element size.
4213 ///
4214 /// This method has no purpose when either input element `T` or output element `U` are
4215 /// zero-sized and will return the original slice without splitting anything.
4216 ///
4217 /// # Safety
4218 ///
4219 /// This method is essentially a `transmute` with respect to the elements in the returned
4220 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
4221 ///
4222 /// # Examples
4223 ///
4224 /// Basic usage:
4225 ///
4226 /// ```
4227 /// unsafe {
4228 /// let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
4229 /// let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
4230 /// // less_efficient_algorithm_for_bytes(prefix);
4231 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
4232 /// // less_efficient_algorithm_for_bytes(suffix);
4233 /// }
4234 /// ```
4235 #[stable(feature = "slice_align_to", since = "1.30.0")]
4236 #[must_use]
4237 #[cfg(not(feature = "ferrocene_certified"))]
4238 pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
4239 // Note that most of this function will be constant-evaluated,
4240 if U::IS_ZST || T::IS_ZST {
4241 // handle ZSTs specially, which is – don't handle them at all.
4242 return (self, &mut [], &mut []);
4243 }
4244
4245 // First, find at what point do we split between the first and 2nd slice. Easy with
4246 // ptr.align_offset.
4247 let ptr = self.as_ptr();
4248 // SAFETY: Here we are ensuring we will use aligned pointers for U for the
4249 // rest of the method. This is done by passing a pointer to &[T] with an
4250 // alignment targeted for U.
4251 // `crate::ptr::align_offset` is called with a correctly aligned and
4252 // valid pointer `ptr` (it comes from a reference to `self`) and with
4253 // a size that is a power of two (since it comes from the alignment for U),
4254 // satisfying its safety constraints.
4255 let offset = unsafe { crate::ptr::align_offset(ptr, align_of::<U>()) };
4256 if offset > self.len() {
4257 (self, &mut [], &mut [])
4258 } else {
4259 let (left, rest) = self.split_at_mut(offset);
4260 let (us_len, ts_len) = rest.align_to_offsets::<U>();
4261 let rest_len = rest.len();
4262 let mut_ptr = rest.as_mut_ptr();
4263 // Inform Miri that we want to consider the "middle" pointer to be suitably aligned.
4264 #[cfg(miri)]
4265 crate::intrinsics::miri_promise_symbolic_alignment(
4266 mut_ptr.cast() as *const (),
4267 align_of::<U>(),
4268 );
4269 // We can't use `rest` again after this, that would invalidate its alias `mut_ptr`!
4270 // SAFETY: see comments for `align_to`.
4271 unsafe {
4272 (
4273 left,
4274 from_raw_parts_mut(mut_ptr as *mut U, us_len),
4275 from_raw_parts_mut(mut_ptr.add(rest_len - ts_len), ts_len),
4276 )
4277 }
4278 }
4279 }
4280
4281 /// Splits a slice into a prefix, a middle of aligned SIMD types, and a suffix.
4282 ///
4283 /// This is a safe wrapper around [`slice::align_to`], so inherits the same
4284 /// guarantees as that method.
4285 ///
4286 /// # Panics
4287 ///
4288 /// This will panic if the size of the SIMD type is different from
4289 /// `LANES` times that of the scalar.
4290 ///
4291 /// At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps
4292 /// that from ever happening, as only power-of-two numbers of lanes are
4293 /// supported. It's possible that, in the future, those restrictions might
4294 /// be lifted in a way that would make it possible to see panics from this
4295 /// method for something like `LANES == 3`.
4296 ///
4297 /// # Examples
4298 ///
4299 /// ```
4300 /// #![feature(portable_simd)]
4301 /// use core::simd::prelude::*;
4302 ///
4303 /// let short = &[1, 2, 3];
4304 /// let (prefix, middle, suffix) = short.as_simd::<4>();
4305 /// assert_eq!(middle, []); // Not enough elements for anything in the middle
4306 ///
4307 /// // They might be split in any possible way between prefix and suffix
4308 /// let it = prefix.iter().chain(suffix).copied();
4309 /// assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);
4310 ///
4311 /// fn basic_simd_sum(x: &[f32]) -> f32 {
4312 /// use std::ops::Add;
4313 /// let (prefix, middle, suffix) = x.as_simd();
4314 /// let sums = f32x4::from_array([
4315 /// prefix.iter().copied().sum(),
4316 /// 0.0,
4317 /// 0.0,
4318 /// suffix.iter().copied().sum(),
4319 /// ]);
4320 /// let sums = middle.iter().copied().fold(sums, f32x4::add);
4321 /// sums.reduce_sum()
4322 /// }
4323 ///
4324 /// let numbers: Vec<f32> = (1..101).map(|x| x as _).collect();
4325 /// assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);
4326 /// ```
4327 #[unstable(feature = "portable_simd", issue = "86656")]
4328 #[must_use]
4329 #[cfg(not(feature = "ferrocene_certified"))]
4330 pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])
4331 where
4332 Simd<T, LANES>: AsRef<[T; LANES]>,
4333 T: simd::SimdElement,
4334 simd::LaneCount<LANES>: simd::SupportedLaneCount,
4335 {
4336 // These are expected to always match, as vector types are laid out like
4337 // arrays per <https://llvm.org/docs/LangRef.html#vector-type>, but we
4338 // might as well double-check since it'll optimize away anyhow.
4339 assert_eq!(size_of::<Simd<T, LANES>>(), size_of::<[T; LANES]>());
4340
4341 // SAFETY: The simd types have the same layout as arrays, just with
4342 // potentially-higher alignment, so the de-facto transmutes are sound.
4343 unsafe { self.align_to() }
4344 }
4345
4346 /// Splits a mutable slice into a mutable prefix, a middle of aligned SIMD types,
4347 /// and a mutable suffix.
4348 ///
4349 /// This is a safe wrapper around [`slice::align_to_mut`], so inherits the same
4350 /// guarantees as that method.
4351 ///
4352 /// This is the mutable version of [`slice::as_simd`]; see that for examples.
4353 ///
4354 /// # Panics
4355 ///
4356 /// This will panic if the size of the SIMD type is different from
4357 /// `LANES` times that of the scalar.
4358 ///
4359 /// At the time of writing, the trait restrictions on `Simd<T, LANES>` keeps
4360 /// that from ever happening, as only power-of-two numbers of lanes are
4361 /// supported. It's possible that, in the future, those restrictions might
4362 /// be lifted in a way that would make it possible to see panics from this
4363 /// method for something like `LANES == 3`.
4364 #[unstable(feature = "portable_simd", issue = "86656")]
4365 #[must_use]
4366 #[cfg(not(feature = "ferrocene_certified"))]
4367 pub fn as_simd_mut<const LANES: usize>(&mut self) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])
4368 where
4369 Simd<T, LANES>: AsMut<[T; LANES]>,
4370 T: simd::SimdElement,
4371 simd::LaneCount<LANES>: simd::SupportedLaneCount,
4372 {
4373 // These are expected to always match, as vector types are laid out like
4374 // arrays per <https://llvm.org/docs/LangRef.html#vector-type>, but we
4375 // might as well double-check since it'll optimize away anyhow.
4376 assert_eq!(size_of::<Simd<T, LANES>>(), size_of::<[T; LANES]>());
4377
4378 // SAFETY: The simd types have the same layout as arrays, just with
4379 // potentially-higher alignment, so the de-facto transmutes are sound.
4380 unsafe { self.align_to_mut() }
4381 }
4382
4383 /// Checks if the elements of this slice are sorted.
4384 ///
4385 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
4386 /// slice yields exactly zero or one element, `true` is returned.
4387 ///
4388 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
4389 /// implies that this function returns `false` if any two consecutive items are not
4390 /// comparable.
4391 ///
4392 /// # Examples
4393 ///
4394 /// ```
4395 /// let empty: [i32; 0] = [];
4396 ///
4397 /// assert!([1, 2, 2, 9].is_sorted());
4398 /// assert!(![1, 3, 2, 4].is_sorted());
4399 /// assert!([0].is_sorted());
4400 /// assert!(empty.is_sorted());
4401 /// assert!(![0.0, 1.0, f32::NAN].is_sorted());
4402 /// ```
4403 #[inline]
4404 #[stable(feature = "is_sorted", since = "1.82.0")]
4405 #[must_use]
4406 #[cfg(not(feature = "ferrocene_certified"))]
4407 pub fn is_sorted(&self) -> bool
4408 where
4409 T: PartialOrd,
4410 {
4411 // This odd number works the best. 32 + 1 extra due to overlapping chunk boundaries.
4412 const CHUNK_SIZE: usize = 33;
4413 if self.len() < CHUNK_SIZE {
4414 return self.windows(2).all(|w| w[0] <= w[1]);
4415 }
4416 let mut i = 0;
4417 // Check in chunks for autovectorization.
4418 while i < self.len() - CHUNK_SIZE {
4419 let chunk = &self[i..i + CHUNK_SIZE];
4420 if !chunk.windows(2).fold(true, |acc, w| acc & (w[0] <= w[1])) {
4421 return false;
4422 }
4423 // We need to ensure that chunk boundaries are also sorted.
4424 // Overlap the next chunk with the last element of our last chunk.
4425 i += CHUNK_SIZE - 1;
4426 }
4427 self[i..].windows(2).all(|w| w[0] <= w[1])
4428 }
4429
4430 /// Checks if the elements of this slice are sorted using the given comparator function.
4431 ///
4432 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
4433 /// function to determine whether two elements are to be considered in sorted order.
4434 ///
4435 /// # Examples
4436 ///
4437 /// ```
4438 /// assert!([1, 2, 2, 9].is_sorted_by(|a, b| a <= b));
4439 /// assert!(![1, 2, 2, 9].is_sorted_by(|a, b| a < b));
4440 ///
4441 /// assert!([0].is_sorted_by(|a, b| true));
4442 /// assert!([0].is_sorted_by(|a, b| false));
4443 ///
4444 /// let empty: [i32; 0] = [];
4445 /// assert!(empty.is_sorted_by(|a, b| false));
4446 /// assert!(empty.is_sorted_by(|a, b| true));
4447 /// ```
4448 #[stable(feature = "is_sorted", since = "1.82.0")]
4449 #[must_use]
4450 #[cfg(not(feature = "ferrocene_certified"))]
4451 pub fn is_sorted_by<'a, F>(&'a self, mut compare: F) -> bool
4452 where
4453 F: FnMut(&'a T, &'a T) -> bool,
4454 {
4455 self.array_windows().all(|[a, b]| compare(a, b))
4456 }
4457
4458 /// Checks if the elements of this slice are sorted using the given key extraction function.
4459 ///
4460 /// Instead of comparing the slice's elements directly, this function compares the keys of the
4461 /// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its
4462 /// documentation for more information.
4463 ///
4464 /// [`is_sorted`]: slice::is_sorted
4465 ///
4466 /// # Examples
4467 ///
4468 /// ```
4469 /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
4470 /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
4471 /// ```
4472 #[inline]
4473 #[stable(feature = "is_sorted", since = "1.82.0")]
4474 #[must_use]
4475 #[cfg(not(feature = "ferrocene_certified"))]
4476 pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> bool
4477 where
4478 F: FnMut(&'a T) -> K,
4479 K: PartialOrd,
4480 {
4481 self.iter().is_sorted_by_key(f)
4482 }
4483
4484 /// Returns the index of the partition point according to the given predicate
4485 /// (the index of the first element of the second partition).
4486 ///
4487 /// The slice is assumed to be partitioned according to the given predicate.
4488 /// This means that all elements for which the predicate returns true are at the start of the slice
4489 /// and all elements for which the predicate returns false are at the end.
4490 /// For example, `[7, 15, 3, 5, 4, 12, 6]` is partitioned under the predicate `x % 2 != 0`
4491 /// (all odd numbers are at the start, all even at the end).
4492 ///
4493 /// If this slice is not partitioned, the returned result is unspecified and meaningless,
4494 /// as this method performs a kind of binary search.
4495 ///
4496 /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
4497 ///
4498 /// [`binary_search`]: slice::binary_search
4499 /// [`binary_search_by`]: slice::binary_search_by
4500 /// [`binary_search_by_key`]: slice::binary_search_by_key
4501 ///
4502 /// # Examples
4503 ///
4504 /// ```
4505 /// let v = [1, 2, 3, 3, 5, 6, 7];
4506 /// let i = v.partition_point(|&x| x < 5);
4507 ///
4508 /// assert_eq!(i, 4);
4509 /// assert!(v[..i].iter().all(|&x| x < 5));
4510 /// assert!(v[i..].iter().all(|&x| !(x < 5)));
4511 /// ```
4512 ///
4513 /// If all elements of the slice match the predicate, including if the slice
4514 /// is empty, then the length of the slice will be returned:
4515 ///
4516 /// ```
4517 /// let a = [2, 4, 8];
4518 /// assert_eq!(a.partition_point(|x| x < &100), a.len());
4519 /// let a: [i32; 0] = [];
4520 /// assert_eq!(a.partition_point(|x| x < &100), 0);
4521 /// ```
4522 ///
4523 /// If you want to insert an item to a sorted vector, while maintaining
4524 /// sort order:
4525 ///
4526 /// ```
4527 /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
4528 /// let num = 42;
4529 /// let idx = s.partition_point(|&x| x <= num);
4530 /// s.insert(idx, num);
4531 /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
4532 /// ```
4533 #[stable(feature = "partition_point", since = "1.52.0")]
4534 #[must_use]
4535 #[cfg(not(feature = "ferrocene_certified"))]
4536 pub fn partition_point<P>(&self, mut pred: P) -> usize
4537 where
4538 P: FnMut(&T) -> bool,
4539 {
4540 self.binary_search_by(|x| if pred(x) { Less } else { Greater }).unwrap_or_else(|i| i)
4541 }
4542
4543 /// Removes the subslice corresponding to the given range
4544 /// and returns a reference to it.
4545 ///
4546 /// Returns `None` and does not modify the slice if the given
4547 /// range is out of bounds.
4548 ///
4549 /// Note that this method only accepts one-sided ranges such as
4550 /// `2..` or `..6`, but not `2..6`.
4551 ///
4552 /// # Examples
4553 ///
4554 /// Splitting off the first three elements of a slice:
4555 ///
4556 /// ```
4557 /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
4558 /// let mut first_three = slice.split_off(..3).unwrap();
4559 ///
4560 /// assert_eq!(slice, &['d']);
4561 /// assert_eq!(first_three, &['a', 'b', 'c']);
4562 /// ```
4563 ///
4564 /// Splitting off a slice starting with the third element:
4565 ///
4566 /// ```
4567 /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
4568 /// let mut tail = slice.split_off(2..).unwrap();
4569 ///
4570 /// assert_eq!(slice, &['a', 'b']);
4571 /// assert_eq!(tail, &['c', 'd']);
4572 /// ```
4573 ///
4574 /// Getting `None` when `range` is out of bounds:
4575 ///
4576 /// ```
4577 /// let mut slice: &[_] = &['a', 'b', 'c', 'd'];
4578 ///
4579 /// assert_eq!(None, slice.split_off(5..));
4580 /// assert_eq!(None, slice.split_off(..5));
4581 /// assert_eq!(None, slice.split_off(..=4));
4582 /// let expected: &[char] = &['a', 'b', 'c', 'd'];
4583 /// assert_eq!(Some(expected), slice.split_off(..4));
4584 /// ```
4585 #[inline]
4586 #[must_use = "method does not modify the slice if the range is out of bounds"]
4587 #[stable(feature = "slice_take", since = "1.87.0")]
4588 #[cfg(not(feature = "ferrocene_certified"))]
4589 pub fn split_off<'a, R: OneSidedRange<usize>>(
4590 self: &mut &'a Self,
4591 range: R,
4592 ) -> Option<&'a Self> {
4593 let (direction, split_index) = split_point_of(range)?;
4594 if split_index > self.len() {
4595 return None;
4596 }
4597 let (front, back) = self.split_at(split_index);
4598 match direction {
4599 Direction::Front => {
4600 *self = back;
4601 Some(front)
4602 }
4603 Direction::Back => {
4604 *self = front;
4605 Some(back)
4606 }
4607 }
4608 }
4609
4610 /// Removes the subslice corresponding to the given range
4611 /// and returns a mutable reference to it.
4612 ///
4613 /// Returns `None` and does not modify the slice if the given
4614 /// range is out of bounds.
4615 ///
4616 /// Note that this method only accepts one-sided ranges such as
4617 /// `2..` or `..6`, but not `2..6`.
4618 ///
4619 /// # Examples
4620 ///
4621 /// Splitting off the first three elements of a slice:
4622 ///
4623 /// ```
4624 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
4625 /// let mut first_three = slice.split_off_mut(..3).unwrap();
4626 ///
4627 /// assert_eq!(slice, &mut ['d']);
4628 /// assert_eq!(first_three, &mut ['a', 'b', 'c']);
4629 /// ```
4630 ///
4631 /// Splitting off a slice starting with the third element:
4632 ///
4633 /// ```
4634 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
4635 /// let mut tail = slice.split_off_mut(2..).unwrap();
4636 ///
4637 /// assert_eq!(slice, &mut ['a', 'b']);
4638 /// assert_eq!(tail, &mut ['c', 'd']);
4639 /// ```
4640 ///
4641 /// Getting `None` when `range` is out of bounds:
4642 ///
4643 /// ```
4644 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
4645 ///
4646 /// assert_eq!(None, slice.split_off_mut(5..));
4647 /// assert_eq!(None, slice.split_off_mut(..5));
4648 /// assert_eq!(None, slice.split_off_mut(..=4));
4649 /// let expected: &mut [_] = &mut ['a', 'b', 'c', 'd'];
4650 /// assert_eq!(Some(expected), slice.split_off_mut(..4));
4651 /// ```
4652 #[inline]
4653 #[must_use = "method does not modify the slice if the range is out of bounds"]
4654 #[stable(feature = "slice_take", since = "1.87.0")]
4655 #[cfg(not(feature = "ferrocene_certified"))]
4656 pub fn split_off_mut<'a, R: OneSidedRange<usize>>(
4657 self: &mut &'a mut Self,
4658 range: R,
4659 ) -> Option<&'a mut Self> {
4660 let (direction, split_index) = split_point_of(range)?;
4661 if split_index > self.len() {
4662 return None;
4663 }
4664 let (front, back) = mem::take(self).split_at_mut(split_index);
4665 match direction {
4666 Direction::Front => {
4667 *self = back;
4668 Some(front)
4669 }
4670 Direction::Back => {
4671 *self = front;
4672 Some(back)
4673 }
4674 }
4675 }
4676
4677 /// Removes the first element of the slice and returns a reference
4678 /// to it.
4679 ///
4680 /// Returns `None` if the slice is empty.
4681 ///
4682 /// # Examples
4683 ///
4684 /// ```
4685 /// let mut slice: &[_] = &['a', 'b', 'c'];
4686 /// let first = slice.split_off_first().unwrap();
4687 ///
4688 /// assert_eq!(slice, &['b', 'c']);
4689 /// assert_eq!(first, &'a');
4690 /// ```
4691 #[inline]
4692 #[stable(feature = "slice_take", since = "1.87.0")]
4693 #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]
4694 #[cfg(not(feature = "ferrocene_certified"))]
4695 pub const fn split_off_first<'a>(self: &mut &'a Self) -> Option<&'a T> {
4696 // FIXME(const-hack): Use `?` when available in const instead of `let-else`.
4697 let Some((first, rem)) = self.split_first() else { return None };
4698 *self = rem;
4699 Some(first)
4700 }
4701
4702 /// Removes the first element of the slice and returns a mutable
4703 /// reference to it.
4704 ///
4705 /// Returns `None` if the slice is empty.
4706 ///
4707 /// # Examples
4708 ///
4709 /// ```
4710 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
4711 /// let first = slice.split_off_first_mut().unwrap();
4712 /// *first = 'd';
4713 ///
4714 /// assert_eq!(slice, &['b', 'c']);
4715 /// assert_eq!(first, &'d');
4716 /// ```
4717 #[inline]
4718 #[stable(feature = "slice_take", since = "1.87.0")]
4719 #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]
4720 #[cfg(not(feature = "ferrocene_certified"))]
4721 pub const fn split_off_first_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {
4722 // FIXME(const-hack): Use `mem::take` and `?` when available in const.
4723 // Original: `mem::take(self).split_first_mut()?`
4724 let Some((first, rem)) = mem::replace(self, &mut []).split_first_mut() else { return None };
4725 *self = rem;
4726 Some(first)
4727 }
4728
4729 /// Removes the last element of the slice and returns a reference
4730 /// to it.
4731 ///
4732 /// Returns `None` if the slice is empty.
4733 ///
4734 /// # Examples
4735 ///
4736 /// ```
4737 /// let mut slice: &[_] = &['a', 'b', 'c'];
4738 /// let last = slice.split_off_last().unwrap();
4739 ///
4740 /// assert_eq!(slice, &['a', 'b']);
4741 /// assert_eq!(last, &'c');
4742 /// ```
4743 #[inline]
4744 #[stable(feature = "slice_take", since = "1.87.0")]
4745 #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]
4746 #[cfg(not(feature = "ferrocene_certified"))]
4747 pub const fn split_off_last<'a>(self: &mut &'a Self) -> Option<&'a T> {
4748 // FIXME(const-hack): Use `?` when available in const instead of `let-else`.
4749 let Some((last, rem)) = self.split_last() else { return None };
4750 *self = rem;
4751 Some(last)
4752 }
4753
4754 /// Removes the last element of the slice and returns a mutable
4755 /// reference to it.
4756 ///
4757 /// Returns `None` if the slice is empty.
4758 ///
4759 /// # Examples
4760 ///
4761 /// ```
4762 /// let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
4763 /// let last = slice.split_off_last_mut().unwrap();
4764 /// *last = 'd';
4765 ///
4766 /// assert_eq!(slice, &['a', 'b']);
4767 /// assert_eq!(last, &'d');
4768 /// ```
4769 #[inline]
4770 #[stable(feature = "slice_take", since = "1.87.0")]
4771 #[rustc_const_unstable(feature = "const_split_off_first_last", issue = "138539")]
4772 #[cfg(not(feature = "ferrocene_certified"))]
4773 pub const fn split_off_last_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {
4774 // FIXME(const-hack): Use `mem::take` and `?` when available in const.
4775 // Original: `mem::take(self).split_last_mut()?`
4776 let Some((last, rem)) = mem::replace(self, &mut []).split_last_mut() else { return None };
4777 *self = rem;
4778 Some(last)
4779 }
4780
4781 /// Returns mutable references to many indices at once, without doing any checks.
4782 ///
4783 /// An index can be either a `usize`, a [`Range`] or a [`RangeInclusive`]. Note
4784 /// that this method takes an array, so all indices must be of the same type.
4785 /// If passed an array of `usize`s this method gives back an array of mutable references
4786 /// to single elements, while if passed an array of ranges it gives back an array of
4787 /// mutable references to slices.
4788 ///
4789 /// For a safe alternative see [`get_disjoint_mut`].
4790 ///
4791 /// # Safety
4792 ///
4793 /// Calling this method with overlapping or out-of-bounds indices is *[undefined behavior]*
4794 /// even if the resulting references are not used.
4795 ///
4796 /// # Examples
4797 ///
4798 /// ```
4799 /// let x = &mut [1, 2, 4];
4800 ///
4801 /// unsafe {
4802 /// let [a, b] = x.get_disjoint_unchecked_mut([0, 2]);
4803 /// *a *= 10;
4804 /// *b *= 100;
4805 /// }
4806 /// assert_eq!(x, &[10, 2, 400]);
4807 ///
4808 /// unsafe {
4809 /// let [a, b] = x.get_disjoint_unchecked_mut([0..1, 1..3]);
4810 /// a[0] = 8;
4811 /// b[0] = 88;
4812 /// b[1] = 888;
4813 /// }
4814 /// assert_eq!(x, &[8, 88, 888]);
4815 ///
4816 /// unsafe {
4817 /// let [a, b] = x.get_disjoint_unchecked_mut([1..=2, 0..=0]);
4818 /// a[0] = 11;
4819 /// a[1] = 111;
4820 /// b[0] = 1;
4821 /// }
4822 /// assert_eq!(x, &[1, 11, 111]);
4823 /// ```
4824 ///
4825 /// [`get_disjoint_mut`]: slice::get_disjoint_mut
4826 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
4827 #[stable(feature = "get_many_mut", since = "1.86.0")]
4828 #[inline]
4829 #[track_caller]
4830 #[cfg(not(feature = "ferrocene_certified"))]
4831 pub unsafe fn get_disjoint_unchecked_mut<I, const N: usize>(
4832 &mut self,
4833 indices: [I; N],
4834 ) -> [&mut I::Output; N]
4835 where
4836 I: GetDisjointMutIndex + SliceIndex<Self>,
4837 {
4838 // NB: This implementation is written as it is because any variation of
4839 // `indices.map(|i| self.get_unchecked_mut(i))` would make miri unhappy,
4840 // or generate worse code otherwise. This is also why we need to go
4841 // through a raw pointer here.
4842 let slice: *mut [T] = self;
4843 let mut arr: MaybeUninit<[&mut I::Output; N]> = MaybeUninit::uninit();
4844 let arr_ptr = arr.as_mut_ptr();
4845
4846 // SAFETY: We expect `indices` to contain disjunct values that are
4847 // in bounds of `self`.
4848 unsafe {
4849 for i in 0..N {
4850 let idx = indices.get_unchecked(i).clone();
4851 arr_ptr.cast::<&mut I::Output>().add(i).write(&mut *slice.get_unchecked_mut(idx));
4852 }
4853 arr.assume_init()
4854 }
4855 }
4856
4857 /// Returns mutable references to many indices at once.
4858 ///
4859 /// An index can be either a `usize`, a [`Range`] or a [`RangeInclusive`]. Note
4860 /// that this method takes an array, so all indices must be of the same type.
4861 /// If passed an array of `usize`s this method gives back an array of mutable references
4862 /// to single elements, while if passed an array of ranges it gives back an array of
4863 /// mutable references to slices.
4864 ///
4865 /// Returns an error if any index is out-of-bounds, or if there are overlapping indices.
4866 /// An empty range is not considered to overlap if it is located at the beginning or at
4867 /// the end of another range, but is considered to overlap if it is located in the middle.
4868 ///
4869 /// This method does a O(n^2) check to check that there are no overlapping indices, so be careful
4870 /// when passing many indices.
4871 ///
4872 /// # Examples
4873 ///
4874 /// ```
4875 /// let v = &mut [1, 2, 3];
4876 /// if let Ok([a, b]) = v.get_disjoint_mut([0, 2]) {
4877 /// *a = 413;
4878 /// *b = 612;
4879 /// }
4880 /// assert_eq!(v, &[413, 2, 612]);
4881 ///
4882 /// if let Ok([a, b]) = v.get_disjoint_mut([0..1, 1..3]) {
4883 /// a[0] = 8;
4884 /// b[0] = 88;
4885 /// b[1] = 888;
4886 /// }
4887 /// assert_eq!(v, &[8, 88, 888]);
4888 ///
4889 /// if let Ok([a, b]) = v.get_disjoint_mut([1..=2, 0..=0]) {
4890 /// a[0] = 11;
4891 /// a[1] = 111;
4892 /// b[0] = 1;
4893 /// }
4894 /// assert_eq!(v, &[1, 11, 111]);
4895 /// ```
4896 #[stable(feature = "get_many_mut", since = "1.86.0")]
4897 #[inline]
4898 #[cfg(not(feature = "ferrocene_certified"))]
4899 pub fn get_disjoint_mut<I, const N: usize>(
4900 &mut self,
4901 indices: [I; N],
4902 ) -> Result<[&mut I::Output; N], GetDisjointMutError>
4903 where
4904 I: GetDisjointMutIndex + SliceIndex<Self>,
4905 {
4906 get_disjoint_check_valid(&indices, self.len())?;
4907 // SAFETY: The `get_disjoint_check_valid()` call checked that all indices
4908 // are disjunct and in bounds.
4909 unsafe { Ok(self.get_disjoint_unchecked_mut(indices)) }
4910 }
4911
4912 /// Returns the index that an element reference points to.
4913 ///
4914 /// Returns `None` if `element` does not point to the start of an element within the slice.
4915 ///
4916 /// This method is useful for extending slice iterators like [`slice::split`].
4917 ///
4918 /// Note that this uses pointer arithmetic and **does not compare elements**.
4919 /// To find the index of an element via comparison, use
4920 /// [`.iter().position()`](crate::iter::Iterator::position) instead.
4921 ///
4922 /// # Panics
4923 /// Panics if `T` is zero-sized.
4924 ///
4925 /// # Examples
4926 /// Basic usage:
4927 /// ```
4928 /// #![feature(substr_range)]
4929 ///
4930 /// let nums: &[u32] = &[1, 7, 1, 1];
4931 /// let num = &nums[2];
4932 ///
4933 /// assert_eq!(num, &1);
4934 /// assert_eq!(nums.element_offset(num), Some(2));
4935 /// ```
4936 /// Returning `None` with an unaligned element:
4937 /// ```
4938 /// #![feature(substr_range)]
4939 ///
4940 /// let arr: &[[u32; 2]] = &[[0, 1], [2, 3]];
4941 /// let flat_arr: &[u32] = arr.as_flattened();
4942 ///
4943 /// let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap();
4944 /// let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap();
4945 ///
4946 /// assert_eq!(ok_elm, &[0, 1]);
4947 /// assert_eq!(weird_elm, &[1, 2]);
4948 ///
4949 /// assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0
4950 /// assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1
4951 /// ```
4952 #[must_use]
4953 #[unstable(feature = "substr_range", issue = "126769")]
4954 #[cfg(not(feature = "ferrocene_certified"))]
4955 pub fn element_offset(&self, element: &T) -> Option<usize> {
4956 if T::IS_ZST {
4957 panic!("elements are zero-sized");
4958 }
4959
4960 let self_start = self.as_ptr().addr();
4961 let elem_start = ptr::from_ref(element).addr();
4962
4963 let byte_offset = elem_start.wrapping_sub(self_start);
4964
4965 if !byte_offset.is_multiple_of(size_of::<T>()) {
4966 return None;
4967 }
4968
4969 let offset = byte_offset / size_of::<T>();
4970
4971 if offset < self.len() { Some(offset) } else { None }
4972 }
4973
4974 /// Returns the range of indices that a subslice points to.
4975 ///
4976 /// Returns `None` if `subslice` does not point within the slice or if it is not aligned with the
4977 /// elements in the slice.
4978 ///
4979 /// This method **does not compare elements**. Instead, this method finds the location in the slice that
4980 /// `subslice` was obtained from. To find the index of a subslice via comparison, instead use
4981 /// [`.windows()`](slice::windows)[`.position()`](crate::iter::Iterator::position).
4982 ///
4983 /// This method is useful for extending slice iterators like [`slice::split`].
4984 ///
4985 /// Note that this may return a false positive (either `Some(0..0)` or `Some(self.len()..self.len())`)
4986 /// if `subslice` has a length of zero and points to the beginning or end of another, separate, slice.
4987 ///
4988 /// # Panics
4989 /// Panics if `T` is zero-sized.
4990 ///
4991 /// # Examples
4992 /// Basic usage:
4993 /// ```
4994 /// #![feature(substr_range)]
4995 ///
4996 /// let nums = &[0, 5, 10, 0, 0, 5];
4997 ///
4998 /// let mut iter = nums
4999 /// .split(|t| *t == 0)
5000 /// .map(|n| nums.subslice_range(n).unwrap());
5001 ///
5002 /// assert_eq!(iter.next(), Some(0..0));
5003 /// assert_eq!(iter.next(), Some(1..3));
5004 /// assert_eq!(iter.next(), Some(4..4));
5005 /// assert_eq!(iter.next(), Some(5..6));
5006 /// ```
5007 #[must_use]
5008 #[unstable(feature = "substr_range", issue = "126769")]
5009 #[cfg(not(feature = "ferrocene_certified"))]
5010 pub fn subslice_range(&self, subslice: &[T]) -> Option<Range<usize>> {
5011 if T::IS_ZST {
5012 panic!("elements are zero-sized");
5013 }
5014
5015 let self_start = self.as_ptr().addr();
5016 let subslice_start = subslice.as_ptr().addr();
5017
5018 let byte_start = subslice_start.wrapping_sub(self_start);
5019
5020 if !byte_start.is_multiple_of(size_of::<T>()) {
5021 return None;
5022 }
5023
5024 let start = byte_start / size_of::<T>();
5025 let end = start.wrapping_add(subslice.len());
5026
5027 if start <= self.len() && end <= self.len() { Some(start..end) } else { None }
5028 }
5029}
5030
5031#[cfg(not(feature = "ferrocene_certified"))]
5032impl<T> [MaybeUninit<T>] {
5033 /// Transmutes the mutable uninitialized slice to a mutable uninitialized slice of
5034 /// another type, ensuring alignment of the types is maintained.
5035 ///
5036 /// This is a safe wrapper around [`slice::align_to_mut`], so inherits the same
5037 /// guarantees as that method.
5038 ///
5039 /// # Examples
5040 ///
5041 /// ```
5042 /// #![feature(align_to_uninit_mut)]
5043 /// use std::mem::MaybeUninit;
5044 ///
5045 /// pub struct BumpAllocator<'scope> {
5046 /// memory: &'scope mut [MaybeUninit<u8>],
5047 /// }
5048 ///
5049 /// impl<'scope> BumpAllocator<'scope> {
5050 /// pub fn new(memory: &'scope mut [MaybeUninit<u8>]) -> Self {
5051 /// Self { memory }
5052 /// }
5053 /// pub fn try_alloc_uninit<T>(&mut self) -> Option<&'scope mut MaybeUninit<T>> {
5054 /// let first_end = self.memory.as_ptr().align_offset(align_of::<T>()) + size_of::<T>();
5055 /// let prefix = self.memory.split_off_mut(..first_end)?;
5056 /// Some(&mut prefix.align_to_uninit_mut::<T>().1[0])
5057 /// }
5058 /// pub fn try_alloc_u32(&mut self, value: u32) -> Option<&'scope mut u32> {
5059 /// let uninit = self.try_alloc_uninit()?;
5060 /// Some(uninit.write(value))
5061 /// }
5062 /// }
5063 ///
5064 /// let mut memory = [MaybeUninit::<u8>::uninit(); 10];
5065 /// let mut allocator = BumpAllocator::new(&mut memory);
5066 /// let v = allocator.try_alloc_u32(42);
5067 /// assert_eq!(v, Some(&mut 42));
5068 /// ```
5069 #[unstable(feature = "align_to_uninit_mut", issue = "139062")]
5070 #[inline]
5071 #[must_use]
5072 pub fn align_to_uninit_mut<U>(&mut self) -> (&mut Self, &mut [MaybeUninit<U>], &mut Self) {
5073 // SAFETY: `MaybeUninit` is transparent. Correct size and alignment are guaranteed by
5074 // `align_to_mut` itself. Therefore the only thing that we have to ensure for a safe
5075 // `transmute` is that the values are valid for the types involved. But for `MaybeUninit`
5076 // any values are valid, so this operation is safe.
5077 unsafe { self.align_to_mut() }
5078 }
5079}
5080
5081#[cfg(not(feature = "ferrocene_certified"))]
5082impl<T, const N: usize> [[T; N]] {
5083 /// Takes a `&[[T; N]]`, and flattens it to a `&[T]`.
5084 ///
5085 /// For the opposite operation, see [`as_chunks`] and [`as_rchunks`].
5086 ///
5087 /// [`as_chunks`]: slice::as_chunks
5088 /// [`as_rchunks`]: slice::as_rchunks
5089 ///
5090 /// # Panics
5091 ///
5092 /// This panics if the length of the resulting slice would overflow a `usize`.
5093 ///
5094 /// This is only possible when flattening a slice of arrays of zero-sized
5095 /// types, and thus tends to be irrelevant in practice. If
5096 /// `size_of::<T>() > 0`, this will never panic.
5097 ///
5098 /// # Examples
5099 ///
5100 /// ```
5101 /// assert_eq!([[1, 2, 3], [4, 5, 6]].as_flattened(), &[1, 2, 3, 4, 5, 6]);
5102 ///
5103 /// assert_eq!(
5104 /// [[1, 2, 3], [4, 5, 6]].as_flattened(),
5105 /// [[1, 2], [3, 4], [5, 6]].as_flattened(),
5106 /// );
5107 ///
5108 /// let slice_of_empty_arrays: &[[i32; 0]] = &[[], [], [], [], []];
5109 /// assert!(slice_of_empty_arrays.as_flattened().is_empty());
5110 ///
5111 /// let empty_slice_of_arrays: &[[u32; 10]] = &[];
5112 /// assert!(empty_slice_of_arrays.as_flattened().is_empty());
5113 /// ```
5114 #[stable(feature = "slice_flatten", since = "1.80.0")]
5115 #[rustc_const_stable(feature = "const_slice_flatten", since = "1.87.0")]
5116 pub const fn as_flattened(&self) -> &[T] {
5117 let len = if T::IS_ZST {
5118 self.len().checked_mul(N).expect("slice len overflow")
5119 } else {
5120 // SAFETY: `self.len() * N` cannot overflow because `self` is
5121 // already in the address space.
5122 unsafe { self.len().unchecked_mul(N) }
5123 };
5124 // SAFETY: `[T]` is layout-identical to `[T; N]`
5125 unsafe { from_raw_parts(self.as_ptr().cast(), len) }
5126 }
5127
5128 /// Takes a `&mut [[T; N]]`, and flattens it to a `&mut [T]`.
5129 ///
5130 /// For the opposite operation, see [`as_chunks_mut`] and [`as_rchunks_mut`].
5131 ///
5132 /// [`as_chunks_mut`]: slice::as_chunks_mut
5133 /// [`as_rchunks_mut`]: slice::as_rchunks_mut
5134 ///
5135 /// # Panics
5136 ///
5137 /// This panics if the length of the resulting slice would overflow a `usize`.
5138 ///
5139 /// This is only possible when flattening a slice of arrays of zero-sized
5140 /// types, and thus tends to be irrelevant in practice. If
5141 /// `size_of::<T>() > 0`, this will never panic.
5142 ///
5143 /// # Examples
5144 ///
5145 /// ```
5146 /// fn add_5_to_all(slice: &mut [i32]) {
5147 /// for i in slice {
5148 /// *i += 5;
5149 /// }
5150 /// }
5151 ///
5152 /// let mut array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
5153 /// add_5_to_all(array.as_flattened_mut());
5154 /// assert_eq!(array, [[6, 7, 8], [9, 10, 11], [12, 13, 14]]);
5155 /// ```
5156 #[stable(feature = "slice_flatten", since = "1.80.0")]
5157 #[rustc_const_stable(feature = "const_slice_flatten", since = "1.87.0")]
5158 pub const fn as_flattened_mut(&mut self) -> &mut [T] {
5159 let len = if T::IS_ZST {
5160 self.len().checked_mul(N).expect("slice len overflow")
5161 } else {
5162 // SAFETY: `self.len() * N` cannot overflow because `self` is
5163 // already in the address space.
5164 unsafe { self.len().unchecked_mul(N) }
5165 };
5166 // SAFETY: `[T]` is layout-identical to `[T; N]`
5167 unsafe { from_raw_parts_mut(self.as_mut_ptr().cast(), len) }
5168 }
5169}
5170
5171#[cfg(not(feature = "ferrocene_certified"))]
5172impl [f32] {
5173 /// Sorts the slice of floats.
5174 ///
5175 /// This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses
5176 /// the ordering defined by [`f32::total_cmp`].
5177 ///
5178 /// # Current implementation
5179 ///
5180 /// This uses the same sorting algorithm as [`sort_unstable_by`](slice::sort_unstable_by).
5181 ///
5182 /// # Examples
5183 ///
5184 /// ```
5185 /// #![feature(sort_floats)]
5186 /// let mut v = [2.6, -5e-8, f32::NAN, 8.29, f32::INFINITY, -1.0, 0.0, -f32::INFINITY, -0.0];
5187 ///
5188 /// v.sort_floats();
5189 /// let sorted = [-f32::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f32::INFINITY, f32::NAN];
5190 /// assert_eq!(&v[..8], &sorted[..8]);
5191 /// assert!(v[8].is_nan());
5192 /// ```
5193 #[unstable(feature = "sort_floats", issue = "93396")]
5194 #[inline]
5195 pub fn sort_floats(&mut self) {
5196 self.sort_unstable_by(f32::total_cmp);
5197 }
5198}
5199
5200#[cfg(not(feature = "ferrocene_certified"))]
5201impl [f64] {
5202 /// Sorts the slice of floats.
5203 ///
5204 /// This sort is in-place (i.e. does not allocate), *O*(*n* \* log(*n*)) worst-case, and uses
5205 /// the ordering defined by [`f64::total_cmp`].
5206 ///
5207 /// # Current implementation
5208 ///
5209 /// This uses the same sorting algorithm as [`sort_unstable_by`](slice::sort_unstable_by).
5210 ///
5211 /// # Examples
5212 ///
5213 /// ```
5214 /// #![feature(sort_floats)]
5215 /// let mut v = [2.6, -5e-8, f64::NAN, 8.29, f64::INFINITY, -1.0, 0.0, -f64::INFINITY, -0.0];
5216 ///
5217 /// v.sort_floats();
5218 /// let sorted = [-f64::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f64::INFINITY, f64::NAN];
5219 /// assert_eq!(&v[..8], &sorted[..8]);
5220 /// assert!(v[8].is_nan());
5221 /// ```
5222 #[unstable(feature = "sort_floats", issue = "93396")]
5223 #[inline]
5224 pub fn sort_floats(&mut self) {
5225 self.sort_unstable_by(f64::total_cmp);
5226 }
5227}
5228
5229/// Copies `src` to `dest`.
5230///
5231/// # Safety
5232/// `T` must implement one of `Copy` or `TrivialClone`.
5233#[track_caller]
5234const unsafe fn copy_from_slice_impl<T: Clone>(dest: &mut [T], src: &[T]) {
5235 // The panic code path was put into a cold function to not bloat the
5236 // call site.
5237 #[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)]
5238 #[cfg_attr(panic = "immediate-abort", inline)]
5239 #[track_caller]
5240 const fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! {
5241 const_panic!(
5242 "copy_from_slice: source slice length does not match destination slice length",
5243 "copy_from_slice: source slice length ({src_len}) does not match destination slice length ({dst_len})",
5244 src_len: usize,
5245 dst_len: usize,
5246 )
5247 }
5248
5249 if dest.len() != src.len() {
5250 len_mismatch_fail(dest.len(), src.len());
5251 }
5252
5253 // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was
5254 // checked to have the same length. The slices cannot overlap because
5255 // mutable references are exclusive.
5256 unsafe {
5257 ptr::copy_nonoverlapping(src.as_ptr(), dest.as_mut_ptr(), dest.len());
5258 }
5259}
5260
5261#[cfg(not(feature = "ferrocene_certified"))]
5262trait CloneFromSpec<T> {
5263 fn spec_clone_from(&mut self, src: &[T]);
5264}
5265
5266#[cfg(not(feature = "ferrocene_certified"))]
5267impl<T> CloneFromSpec<T> for [T]
5268where
5269 T: Clone,
5270{
5271 #[track_caller]
5272 default fn spec_clone_from(&mut self, src: &[T]) {
5273 assert!(self.len() == src.len(), "destination and source slices have different lengths");
5274 // NOTE: We need to explicitly slice them to the same length
5275 // to make it easier for the optimizer to elide bounds checking.
5276 // But since it can't be relied on we also have an explicit specialization for T: Copy.
5277 let len = self.len();
5278 let src = &src[..len];
5279 for i in 0..len {
5280 self[i].clone_from(&src[i]);
5281 }
5282 }
5283}
5284
5285#[cfg(not(feature = "ferrocene_certified"))]
5286impl<T> CloneFromSpec<T> for [T]
5287where
5288 T: TrivialClone,
5289{
5290 #[track_caller]
5291 fn spec_clone_from(&mut self, src: &[T]) {
5292 // SAFETY: `T` implements `TrivialClone`.
5293 unsafe {
5294 copy_from_slice_impl(self, src);
5295 }
5296 }
5297}
5298
5299#[stable(feature = "rust1", since = "1.0.0")]
5300#[rustc_const_unstable(feature = "const_default", issue = "143894")]
5301#[cfg(not(feature = "ferrocene_certified"))]
5302impl<T> const Default for &[T] {
5303 /// Creates an empty slice.
5304 fn default() -> Self {
5305 &[]
5306 }
5307}
5308
5309#[stable(feature = "mut_slice_default", since = "1.5.0")]
5310#[rustc_const_unstable(feature = "const_default", issue = "143894")]
5311#[cfg(not(feature = "ferrocene_certified"))]
5312impl<T> const Default for &mut [T] {
5313 /// Creates a mutable empty slice.
5314 fn default() -> Self {
5315 &mut []
5316 }
5317}
5318
5319#[unstable(feature = "slice_pattern", reason = "stopgap trait for slice patterns", issue = "56345")]
5320/// Patterns in slices - currently, only used by `strip_prefix` and `strip_suffix`. At a future
5321/// point, we hope to generalise `core::str::Pattern` (which at the time of writing is limited to
5322/// `str`) to slices, and then this trait will be replaced or abolished.
5323#[cfg(not(feature = "ferrocene_certified"))]
5324pub trait SlicePattern {
5325 /// The element type of the slice being matched on.
5326 type Item;
5327
5328 /// Currently, the consumers of `SlicePattern` need a slice.
5329 fn as_slice(&self) -> &[Self::Item];
5330}
5331
5332#[stable(feature = "slice_strip", since = "1.51.0")]
5333#[cfg(not(feature = "ferrocene_certified"))]
5334impl<T> SlicePattern for [T] {
5335 type Item = T;
5336
5337 #[inline]
5338 fn as_slice(&self) -> &[Self::Item] {
5339 self
5340 }
5341}
5342
5343#[stable(feature = "slice_strip", since = "1.51.0")]
5344#[cfg(not(feature = "ferrocene_certified"))]
5345impl<T, const N: usize> SlicePattern for [T; N] {
5346 type Item = T;
5347
5348 #[inline]
5349 fn as_slice(&self) -> &[Self::Item] {
5350 self
5351 }
5352}
5353
5354/// This checks every index against each other, and against `len`.
5355///
5356/// This will do `binomial(N + 1, 2) = N * (N + 1) / 2 = 0, 1, 3, 6, 10, ..`
5357/// comparison operations.
5358#[inline]
5359#[cfg(not(feature = "ferrocene_certified"))]
5360fn get_disjoint_check_valid<I: GetDisjointMutIndex, const N: usize>(
5361 indices: &[I; N],
5362 len: usize,
5363) -> Result<(), GetDisjointMutError> {
5364 // NB: The optimizer should inline the loops into a sequence
5365 // of instructions without additional branching.
5366 for (i, idx) in indices.iter().enumerate() {
5367 if !idx.is_in_bounds(len) {
5368 return Err(GetDisjointMutError::IndexOutOfBounds);
5369 }
5370 for idx2 in &indices[..i] {
5371 if idx.is_overlapping(idx2) {
5372 return Err(GetDisjointMutError::OverlappingIndices);
5373 }
5374 }
5375 }
5376 Ok(())
5377}
5378
5379/// The error type returned by [`get_disjoint_mut`][`slice::get_disjoint_mut`].
5380///
5381/// It indicates one of two possible errors:
5382/// - An index is out-of-bounds.
5383/// - The same index appeared multiple times in the array
5384/// (or different but overlapping indices when ranges are provided).
5385///
5386/// # Examples
5387///
5388/// ```
5389/// use std::slice::GetDisjointMutError;
5390///
5391/// let v = &mut [1, 2, 3];
5392/// assert_eq!(v.get_disjoint_mut([0, 999]), Err(GetDisjointMutError::IndexOutOfBounds));
5393/// assert_eq!(v.get_disjoint_mut([1, 1]), Err(GetDisjointMutError::OverlappingIndices));
5394/// ```
5395#[stable(feature = "get_many_mut", since = "1.86.0")]
5396#[derive(Debug, Clone, PartialEq, Eq)]
5397#[cfg(not(feature = "ferrocene_certified"))]
5398pub enum GetDisjointMutError {
5399 /// An index provided was out-of-bounds for the slice.
5400 IndexOutOfBounds,
5401 /// Two indices provided were overlapping.
5402 OverlappingIndices,
5403}
5404
5405#[stable(feature = "get_many_mut", since = "1.86.0")]
5406#[cfg(not(feature = "ferrocene_certified"))]
5407impl fmt::Display for GetDisjointMutError {
5408 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5409 let msg = match self {
5410 GetDisjointMutError::IndexOutOfBounds => "an index is out of bounds",
5411 GetDisjointMutError::OverlappingIndices => "there were overlapping indices",
5412 };
5413 fmt::Display::fmt(msg, f)
5414 }
5415}
5416
5417#[cfg(not(feature = "ferrocene_certified"))]
5418mod private_get_disjoint_mut_index {
5419 use super::{Range, RangeInclusive, range};
5420
5421 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5422 pub trait Sealed {}
5423
5424 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5425 impl Sealed for usize {}
5426 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5427 impl Sealed for Range<usize> {}
5428 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5429 impl Sealed for RangeInclusive<usize> {}
5430 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5431 impl Sealed for range::Range<usize> {}
5432 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5433 impl Sealed for range::RangeInclusive<usize> {}
5434}
5435
5436/// A helper trait for `<[T]>::get_disjoint_mut()`.
5437///
5438/// # Safety
5439///
5440/// If `is_in_bounds()` returns `true` and `is_overlapping()` returns `false`,
5441/// it must be safe to index the slice with the indices.
5442#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5443#[cfg(not(feature = "ferrocene_certified"))]
5444pub unsafe trait GetDisjointMutIndex:
5445 Clone + private_get_disjoint_mut_index::Sealed
5446{
5447 /// Returns `true` if `self` is in bounds for `len` slice elements.
5448 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5449 fn is_in_bounds(&self, len: usize) -> bool;
5450
5451 /// Returns `true` if `self` overlaps with `other`.
5452 ///
5453 /// Note that we don't consider zero-length ranges to overlap at the beginning or the end,
5454 /// but do consider them to overlap in the middle.
5455 #[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5456 fn is_overlapping(&self, other: &Self) -> bool;
5457}
5458
5459#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5460// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5461#[cfg(not(feature = "ferrocene_certified"))]
5462unsafe impl GetDisjointMutIndex for usize {
5463 #[inline]
5464 fn is_in_bounds(&self, len: usize) -> bool {
5465 *self < len
5466 }
5467
5468 #[inline]
5469 fn is_overlapping(&self, other: &Self) -> bool {
5470 *self == *other
5471 }
5472}
5473
5474#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5475// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5476#[cfg(not(feature = "ferrocene_certified"))]
5477unsafe impl GetDisjointMutIndex for Range<usize> {
5478 #[inline]
5479 fn is_in_bounds(&self, len: usize) -> bool {
5480 (self.start <= self.end) & (self.end <= len)
5481 }
5482
5483 #[inline]
5484 fn is_overlapping(&self, other: &Self) -> bool {
5485 (self.start < other.end) & (other.start < self.end)
5486 }
5487}
5488
5489#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5490// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5491#[cfg(not(feature = "ferrocene_certified"))]
5492unsafe impl GetDisjointMutIndex for RangeInclusive<usize> {
5493 #[inline]
5494 fn is_in_bounds(&self, len: usize) -> bool {
5495 (self.start <= self.end) & (self.end < len)
5496 }
5497
5498 #[inline]
5499 fn is_overlapping(&self, other: &Self) -> bool {
5500 (self.start <= other.end) & (other.start <= self.end)
5501 }
5502}
5503
5504#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5505// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5506#[cfg(not(feature = "ferrocene_certified"))]
5507unsafe impl GetDisjointMutIndex for range::Range<usize> {
5508 #[inline]
5509 fn is_in_bounds(&self, len: usize) -> bool {
5510 Range::from(*self).is_in_bounds(len)
5511 }
5512
5513 #[inline]
5514 fn is_overlapping(&self, other: &Self) -> bool {
5515 Range::from(*self).is_overlapping(&Range::from(*other))
5516 }
5517}
5518
5519#[unstable(feature = "get_disjoint_mut_helpers", issue = "none")]
5520// SAFETY: We implement `is_in_bounds()` and `is_overlapping()` correctly.
5521#[cfg(not(feature = "ferrocene_certified"))]
5522unsafe impl GetDisjointMutIndex for range::RangeInclusive<usize> {
5523 #[inline]
5524 fn is_in_bounds(&self, len: usize) -> bool {
5525 RangeInclusive::from(*self).is_in_bounds(len)
5526 }
5527
5528 #[inline]
5529 fn is_overlapping(&self, other: &Self) -> bool {
5530 RangeInclusive::from(*self).is_overlapping(&RangeInclusive::from(*other))
5531 }
5532}