Open vigna opened 1 year ago
Having StableDeref
implemented for Mmap
definitely sounds interesting. A PR would definitely be welcome.
It does seem to impose some limitations, namely that Deref
(and DerefMut
) must always return the same pointer, and that this pointer must remain valid even when calling methods on &self
until the object is dropped, but this restriction does not apply to methods on &mut self
(other than DerefMut
), if I understand this correctly at least. Assuming that my understanding is correct, I think it should be sound to implement StableDeref
for both Mmap
and MmapMut
.
Mmap::split_to()
introduced by PR #18 as part of the API to split Mmap
objects, does change the underlying pointer, but should meet those conditions, as it requires &mut self
.
Similarly, it is also possible to use Mmap::make_none()
to restrict the access, such that the pointer returned by Deref
can no longer be dereferenced. However, since Mmap::make_none()
takes ownership of Mmap
to return MmapNone
, that should also meet those conditions (and MmapNone
doesn't implement Deref
anyway).
Assuming that this is correct, there shouldn't be any issues with soundness as far as I can tell, but I am just mentioning this to be sure.
The StableDeref marker trait (https://crates.io/crates/stable_deref_trait) has been designed to mark structures whose deref is stable, exactly like the case of memory mapping. Yoke (https://crates.io/crates/yoke) uses the trait to make it possible to attach in a safe way anything implementing the trait and providing a reference. It would be very useful (for us, at least) if Mmap would implement StableDeref as we could yoke the reference of an Mmap to the backing Mmap. We are using a newtype for that presently, but it would be nice if Mmap would provide the feature directly. I can create a pull request if there's interest.