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