| 1 | use std::ops::{Deref, DerefMut}; |
| 2 | use std::os::fd::{AsRawFd, OwnedFd}; |
| 3 | |
| 4 | use crate::{BinaryData, Error}; |
| 5 | |
| 6 | #[derive(Debug)] |
| 7 | pub struct SharedMemory { |
| 8 | memfd: OwnedFd, |
| 9 | pub mmap: memmap::MmapMut, |
| 10 | } |
| 11 | |
| 12 | impl SharedMemory { |
| 13 | pub fn new(size: u64) -> Result<Self, Error> { |
| 14 | let memfd = nix::sys::memfd::memfd_create( |
| 15 | c"glycin-frame", |
| 16 | nix::sys::memfd::MFdFlags::MFD_CLOEXEC | nix::sys::memfd::MFdFlags::MFD_ALLOW_SEALING, |
| 17 | ) |
| 18 | .expect("Failed to create memfd"); |
| 19 | |
| 20 | nix::unistd::ftruncate(&memfd, size.try_into().expect("Required memory too large")) |
| 21 | .expect("Failed to set memfd size"); |
| 22 | |
| 23 | let raw_fd = memfd.as_raw_fd(); |
| 24 | let mmap = unsafe { memmap::MmapMut::map_mut(raw_fd) }?; |
| 25 | |
| 26 | Ok(Self { mmap, memfd }) |
| 27 | } |
| 28 | |
| 29 | pub fn into_binary_data(self) -> BinaryData { |
| 30 | BinaryData::from(self.memfd) |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | impl SharedMemory { |
| 35 | fn from_data(value: impl AsRef<[u8]>) -> Result<Self, Error> { |
| 36 | let mut shared_memory = SharedMemory::new(u64::try_from(value.as_ref().len())?)?; |
| 37 | |
| 38 | shared_memory.copy_from_slice(value.as_ref()); |
| 39 | |
| 40 | Ok(shared_memory) |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | impl BinaryData { |
| 45 | pub fn from_data(value: impl AsRef<[u8]>) -> Result<Self, Error> { |
| 46 | Ok(SharedMemory::from_data(value)?.into_binary_data()) |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | impl Deref for SharedMemory { |
| 51 | type Target = [u8]; |
| 52 | |
| 53 | fn deref(&self) -> &[u8] { |
| 54 | self.mmap.deref() |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | impl DerefMut for SharedMemory { |
| 59 | fn deref_mut(&mut self) -> &mut [u8] { |
| 60 | self.mmap.deref_mut() |
| 61 | } |
| 62 | } |