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