Is there a vector `insert_slice_at` or equivalent?

Searching around I found this question from 4 years ago; "inserting multiple items into a vec efficiently" which also links a very small discussion from 9 years ago; "add vec insert slice at...", and another post on reddit, also from 4 years ago, "vec prepend insert from slice".

I would like to ask the following:

  • Since I can't find any other discussions since, has there been any developments on such a method?
  • If I'm to implement this functionality myself, am I safe to assume that the (unsafe) code from the 9 year old post "add vec insert slice at...", linked here is sound, and a good implementation (by your interpretation of "good")?

This is Vec::splice – it’s a lot more general than just “insert_slice_at” but that use case should be optimal according to the doc.

2 Likes

Another way without the iterator dance is to use extend_from_slice() and rotate_right(): Playground

fn insert_slice<T: Clone>(vec: &mut Vec<T>, index: usize, slice: &[T]) {
    assert!(index <= vec.len());
    vec.extend_from_slice(slice);
    vec[index..].rotate_right(slice.len());
}
1 Like

Unfortuantly this replaces the prior elements rather than shifting them to the positions after the insert length. My expected output would be something like the following:

let mut v = vec![1, 2, 3, 7, 8, 9];
let new = [4, 5, 6];
let u: Vec<_> = v.insert_slice(1, new).collect();
assert_eq!(v, &[1, 2, 3, 4, 5, 6, 7, 8, 9]);

Or the equivalent but mutating the vector v.

Splice does that. You provide an empty range, so no element will be removed.

No, you simply use a zero-length range as the insert location: playground

My mistake. Thanks for the clarification. I will mark your answer as the correct one as it is the std approach, however I'm definitely going to benchmark it against paramagnetics approach.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.