Skip to content

Why do copy_from_slice and clone_from_slice require equal size? #49769

Closed
@RandomInsano

Description

@RandomInsano

Would you like to fix this issue? Here's how!


I'm dealing with a case where I have to send a byte array buffer to a destructive function multiple times. This function requires the buffer to start with an initialization sequence that I have to set.

I want to be able to efficiently reset the header bytes but the size of the initialization sequence is less than the total buffer and so I hit the destination and source slices have different lengths error.

The real question is, why is this required? Here's the current code:

    #[inline]
    fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
        assert!(self.len() == src.len(),
                "destination and source slices have different lengths");
        unsafe {
            ptr::copy_nonoverlapping(
                src.as_ptr(), self.as_mut_ptr(), self.len());
        }
    }

In theory, if self is big enough to hold src shouldn't that be enough? The adjusted call should be this then:

    #[inline]
    fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
        assert!(self.len() >= src.len(),
                "destination slice must be large enough to hold source");
        unsafe {
            ptr::copy_nonoverlapping(
                src.as_ptr(), self.as_mut_ptr(), src.len());
        }
    }

I think the same should be done for clone_from_slice.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsC-enhancementCategory: An issue proposing an enhancement or a PR with one.E-easyCall for participation: Easy difficulty. Experience needed to fix: Not much. Good first issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions