Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lifetime bounds in as_slice and as_slice_mut in MemMap #209

Open
vikramnitin9 opened this issue Aug 30, 2022 · 1 comment
Open

Lifetime bounds in as_slice and as_slice_mut in MemMap #209

vikramnitin9 opened this issue Aug 30, 2022 · 1 comment

Comments

@vikramnitin9
Copy link

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)
}
@c0gent
Copy link
Member

c0gent commented Nov 6, 2022

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants