Skip to content

Lifetime bounds in as_slice and as_slice_mut in MemMap #209

Description

@vikramnitin9

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)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions