tokio-rs / loom

Concurrency permutation testing tool for Rust.
MIT License
2.13k stars 111 forks source link

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

Open sporksmith opened 1 year ago

sporksmith commented 1 year ago

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