arrayvec icon indicating copy to clipboard operation
arrayvec copied to clipboard

Implement copy_from_slice_at for ArrayVec

Open izissise opened this issue 11 months ago • 0 comments

Add copy_from_slice_at similar to copy_from_slice method in ArrayVec would make easier to copy an existing slice array into an ArrayVec.

It is similar to try_extend_from_slice but doesn't return a Result and panic if not enough capacity is left

We can also make sure that everything before the offset is initialized by checking it is smaller than the current len.

impl<T, const CAP: usize> ArrayVec<T, CAP> {
    pub fn copy_from_slice_at(&mut self, offset: usize, other: &[T])
    where
        T: Copy,
    {
        let (lo, hi) = (offset, offset + other.len());
        assert!(lo <= self.len())
        assert!(hi <= CAP);
        self.xs[lo..hi].copy_from_slice(other)
    }
}

Alternatives

Method that return a mutable ref on the full capacity inner array, then it is possible to call av.as_mut_slice_full()[2..4].copy_from_slice(inp) It wouldn't work as there is no way to update the len of the arrayvec

Also From<[T; LEN]> https://github.com/bluss/arrayvec/issues/232 is useful to init the arrayvec with the initial data but would not be able to let us do it at an offset

Stack overflow question that lead me here: https://stackoverflow.com/questions/79434542/return-a-subslice-of-a-const-size-slice

izissise avatar Feb 13 '25 23:02 izissise