macro_rules! len_check (
($slice:expr, $start:ident, $len:ident) => {
assert!(
$start.checked_add($len)
.expect(concat!("Overflow evaluating ", stringify!($start + $len)))
<= $slice.len(), "Length {} starting at {} is out of bounds (slice len {}).", $len, $start, $slice.len()
)
}
);
/// Copy `len` elements from `src_idx` to `dest_idx`. Ranges may overlap. /// /// Safe wrapper for `memmove()`/`std::ptr::copy()`. /// /// ###Panics /// * If either `src_idx` or `dest_idx` are out of bounds, or if either of these plus `len` is out of /// bounds. /// * If `src_idx + len` or `dest_idx + len` overflows. pubfn copy_over<T: Copy>(slice: &mut [T], src_idx: usize, dest_idx: usize, len: usize) { if slice.len() == 0 { return; }
// At any point a Rust reference exists, the compiler is free to do this. // So we explicitely add it to be caught by miri. #[cfg(miri)]
slice.iter().copied().for_each(drop);
let ptr = slice.as_mut_ptr();
unsafe {
ptr::copy(ptr.offset(src_idx as isize), ptr.offset(dest_idx as isize), len);
}
}
/// Prepend `elems` to `vec`, resizing if necessary. /// /// ### Panics /// /// If `vec.len() + elems.len()` overflows. #[cfg(feature = "std")] pubfn prepend<T: Copy>(elems: &[T], vec: &mut Vec<T>) { let elems_len = elems.len(); // `<= isize::MAX as usize` if elems_len == 0 { return; }
let old_len = vec.len(); // `<= isize::MAX as usize` if old_len == 0 { // Prepend = append: delegate to Rust's stdlib implementation.
vec.extend_from_slice(elems);
} else { // Our overflow check occurs here, no need to do it ourselves.
vec.reserve(elems_len); let ptr = vec.as_mut_ptr(); unsafe { // Move the old elements down to the end.
ptr::copy(
ptr,
ptr.offset(elems_len as isize),
old_len,
); // Copy the input elements to the start
ptr::copy_nonoverlapping(
elems.as_ptr(),
ptr,
elems_len,
); // Set the len *after* having initialized the elements.
vec.set_len(old_len + elems_len);
}
}
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.