1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
pub const fn split_at_checked(&self, mid: usize) -> Option<(&[T], &[T])> {
if mid <= self.len() {
// SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which
// fulfills the requirements of `split_at_unchecked`.
Some(unsafe { self.split_at_unchecked(mid) })
} else {
None
}
}
pub const fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
match self.split_at_mut_checked(mid) {
Some(pair) => pair,
None => panic!("mid > len"),
}
}
pub const unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T]) {
// FIXME(const-hack): the const function `from_raw_parts` is used to make this
// function const; previously the implementation used
// `(self.get_unchecked(..mid), self.get_unchecked(mid..))`
let len = self.len();
let ptr = self.as_ptr();
assert_unsafe_precondition!(
check_library_ub,
"slice::split_at_unchecked requires the index to be within the slice",
(mid: usize = mid, len: usize = len) => mid <= len,
);
// SAFETY: Caller has to check that `0 <= mid <= self.len()`
unsafe { (from_raw_parts(ptr, mid), from_raw_parts(ptr.add(mid), unchecked_sub(len, mid))) }
} |
Partager