Skip to content

Instantly share code, notes, and snippets.

@frozolotl
Last active July 28, 2023 08:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frozolotl/22a051baa5153b92e0b0207ad462ec12 to your computer and use it in GitHub Desktop.
Save frozolotl/22a051baa5153b92e0b0207ad462ec12 to your computer and use it in GitHub Desktop.
Inserts a slice at a specific location in a vec.
/// Inserts a slice at a specific location in a vec.
pub fn insert_slice_at<T: Copy>(vec: &mut Vec<T>, index: usize, slice: &[T]) {
unsafe {
assert!(index <= vec.len());
vec.reserve(slice.len());
let insert_ptr = vec.as_mut_ptr().offset(index as isize);
std::ptr::copy(
insert_ptr,
insert_ptr.offset(slice.len() as isize),
vec.len() - index,
);
std::ptr::copy_nonoverlapping(slice.as_ptr(), insert_ptr, slice.len());
vec.set_len(vec.len() + slice.len());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment