Mmap and references to Mmap in same struct

I have a piece of code that parses a file from a &'a[u8] into a ParsedFile<'a> struct.
I now want to create a owned version:

struct ParsedFileOwned {
    mmap: memmap2::Mmap,
    parsed_file: ParsedFile<'a>,
}

This doesn't work of course as the struct is self referential. I know that the reason that is not allowed, is that a struct can move around and addresses might change. However, because this is an memory map, the address will never change and thus it's safe to keep a reference to it. How do I convince the compiler to allow me to do that?

Extra information:
The internal structure of a memory map in the memmap2 library is like this:

pub struct MmapInner {
    ptr: *mut libc::c_void,
    len: usize,
}

I also know that a memory map can cause undefined behaviour if the memory (if shared) or the file is modified by another process. In this use case that cannot happen.

Thanks in advance!

This is the general pattern that yoke attempts to provide. (ouroboros also handles it, but will enforce its own boxing to be safe for arbitrary borrowed types that might not be internally pointers.)

General caution: the history of self-referential-struct types is full of “oops, turns out this is unsound and needs a fix”. ouroboros and yoke are both actively maintained, though.

3 Likes

That looks exactly like what I need, thank you very much!
The caution is noted, I'll stay up to date on the dependencies and stay up to date on potential problems.