RazrFalcon/memmap2-rs

Implement AsRawFd, IntoRawFd, AsRawHandle, IntoRawHandle and Into<Stdio> for MMap

dominik-korsa opened this issue · 2 comments

I would like to use memory mapped files to communicate with a child process stdin/stdout. I've already tested the idea with the crate memfile and the benchmark results are promising. However that crate does not offer Windows support, which is also something that I'm looking for.
To be able to use a the (anonymous) memory mapped file as stdin for a child process in the memfile crate I can use the From<MemFile> trait impl for Stdio. It would be great if this library added this impl too. There are multiple traits that can be implemented:

  • Into<Stdio>
  • AsRawFd / IntoRawFd
  • AsRawHandle / IntoRawHandle

Example usage with this feature implemented:

fn write_using_memmap2(buf: &[u8]) {
    let mut mmap = MmapOptions::new().len(buf.len()).map_anon().unwrap();
    mmap.copy_from_slice(buf);
    let mmap = mmap.make_read_only().unwrap();
    
    Command::new("nul")
        .stderr(Stdio::null())
        .stdout(Stdio::null())
        .stdin(Stdio::from(mmap)) // <-- Using the From<MMap> trait
        .spawn().unwrap()
        .wait().unwrap();
}

Patches are welcome.

I don't the example can work as it is: An anonymous mapping is not backed by a file descriptor (by definition as it is anonymous).

When a mapping is backed by a file, we take that file by reference, c.f. MmapAsRawDesc and hence you can use that for `Command´ directly.

memfile explicitly starts with a memory-backed file created via memfd_create (which is not available on Windows AFAIK), i.e. you could use a MemFile to back our Mmap, but an anonymous mapping does not necessarily have a file descriptor associated at all.