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

cell::MutPtr doesn't provide a way to directly get an immutable reference #293

Open
sporksmith opened this issue Nov 23, 2022 · 0 comments

Comments

@sporksmith
Copy link

sporksmith commented Nov 23, 2022

MutPtr provides deref, which returns a &mut T, but nothing that returns a &T.

I'm working around it by calling MutPtr::with, dereferencing the pointer myself, and "smuggling" it out of the closure. Looking at the implementation of MutPtr I don't think I'm missing any validation by doing this, but it's not obvious from the API.

Ideally the current method would be called deref_mut and you could add deref, but I suppose if you don't want to make a breaking change, maybe you could add deref_const?

All of this is for a guard for a mutex that I'm testing; the guard stores a MutPtr from the mutex's UnsafeCell, and I'm currently implementing Deref and DerefMut roughly like so:

impl<'a, T> std::ops::Deref for SelfContainedMutexGuard<'a, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.ptr.with(|p| unsafe { &*p })
    }
}

impl<'a, T> std::ops::DerefMut for SelfContainedMutexGuard<'a, T>
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { self.ptr.deref() }
    }
}
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

1 participant