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