ocl icon indicating copy to clipboard operation
ocl copied to clipboard

Lifetime bounds in as_slice and as_slice_mut in MemMap

Open vikramnitin9 opened this issue 2 years ago • 1 comments

The lifetime bounds in the methods as_slice and as_slice_mut in types::abs::MemMap (link) are currently

#[inline(always)]
pub unsafe fn as_slice<'a>(&self, len: usize) -> &'a [T] {
    slice::from_raw_parts(self.0, len)
}

#[inline(always)]
pub unsafe fn as_slice_mut<'a>(&mut self, len: usize) -> &'a mut [T] {
    slice::from_raw_parts_mut(self.0, len)
}

The borrows to self and [T] have different lifetimes (implicit and 'a), and the implicit input lifetime will be assigned a different lifetime (not 'a). This means that one could create two mutable references, or a combination of immutable and mutable references, to the same underlying T.

I understand that this is an unsafe function, but this could be a quick fix that addresses one potential memory safety issue. If the lifetimes were instead as follows, this would not allow multiple slice references to the same MemMap.

#[inline(always)]
pub unsafe fn as_slice(&self, len: usize) -> &'_ [T] {
    slice::from_raw_parts(self.0, len)
}

#[inline(always)]
pub unsafe fn as_slice_mut(&mut self, len: usize) -> &'_ mut [T] {
    slice::from_raw_parts_mut(self.0, len)
}

vikramnitin9 avatar Aug 30 '22 14:08 vikramnitin9

You're probably right. I'll have to try this out at some point. There may be some odd reason I did it that way and failed to document it.

Thanks!

c0gent avatar Nov 06 '22 20:11 c0gent