Crates.io | mmap-wrapper |
lib.rs | mmap-wrapper |
version | 2.0.1 |
source | src |
created_at | 2024-08-02 22:18:23.869894 |
updated_at | 2024-09-08 23:45:27.145132 |
description | a simple wrapper for the memmap2 crate to cast mmap backed pointers to structs |
homepage | https://github.com/mostlymaxi/mmap-wrapper |
repository | https://github.com/mostlymaxi/mmap-wrapper |
max_upload_size | |
id | 1323819 |
size | 15,983 |
A common use case for mmap
in C is to cast the mmap backed region to a struct:
MyStruct* mmap_backed_mystruct;
int fd;
fd = open(path, O_RDWR | O_CREAT, 0644);
ftruncate(fd, sizeof(MyStruct));
mmap_backed_mystruct = (MyStruct*)mmap(0, sizeof(MyStruct), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
This is a helpful wrapper for the same usecase:
use mmap_wrapper::MmapWrapper;
// Your struct MUST have a consistent memory layout.
// Use either #[repr(transparent)] or #[repr(C)].
#[repr(C)]
struct MyStruct {
thing1: i32,
thing2: f64,
}
let f = std::fs::File::options()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open("/tmp/mystruct-mmap-test.bin")
.unwrap();
let _ = f.set_len(std::mem::size_of::<MyStruct>() as u64);
let m = unsafe {
memmap2::Mmap::map(&f).unwrap()
};
let m_wrapper = unsafe { MmapWrapper::<MyStruct>::new(m) };
let mmap_backed_mystruct = m_wrapper.get_inner();
no_std
Exampleuse mmap_wrapper::MmapWrapper;
// Your struct MUST have a consistent memory layout.
// Use either #[repr(transparent)] or #[repr(C)].
#[repr(C)]
struct MyStruct {
thing1: i32,
thing2: f64,
}
let m_wrapper = unsafe { MmapWrapper::<MyStruct>::new(c"/tmp/mystruct-mmap-test.bin").unwrap() };
let mmap_backed_mystruct = m_wrapper.get_inner();