//! File-host implementation. IO runs only on the shared worker, never the guest lane. use prometeu_hal::memcard::{MemcardIoError as Error, MemcardStorage}; use std::fs::{File, OpenOptions}; use std::io::{Read, Seek, SeekFrom, Write}; use std::path::Path; pub struct FileMemcard { file: File, length: u64, read_only: bool, } fn io_error(e: std::io::Error) -> Error { use std::io::ErrorKind as K; match e.kind() { K::NotFound => Error::Unavailable, K::PermissionDenied => Error::ReadOnly, K::StorageFull => Error::NoSpace, K::InvalidInput | K::UnexpectedEof => Error::InvalidRange, K::Unsupported => Error::Unsupported, _ => Error::IoError, } } impl FileMemcard { pub fn open(path: &Path, read_only: bool) -> Result { let file = OpenOptions::new().read(true).write(!read_only).open(path).map_err(io_error)?; let length = file.metadata().map_err(io_error)?.len(); Ok(Self { file, length, read_only }) } /// Write every byte and verify allocated blocks before formatting/publication. /// The initializer supplies the runtime-owned format. Existing files are never replaced. #[cfg(unix)] pub fn create( path: &Path, length: u64, initialize: impl FnOnce(&mut dyn MemcardStorage, [u8; 16]) -> Result<(), Error>, ) -> Result { use std::os::unix::fs::MetadataExt; let mut id = [0; 16]; File::open("/dev/urandom").and_then(|mut f| f.read_exact(&mut id)).map_err(io_error)?; let parent = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")); let suffix: String = id.iter().map(|b| format!("{b:02x}")).collect(); let temporary = parent.join(format!(".memcard-{suffix}.tmp")); let file = OpenOptions::new() .read(true) .write(true) .create_new(true) .open(&temporary) .map_err(io_error)?; let result = (|| { let mut card = Self { file, length, read_only: false }; let zeros = [0u8; 65_536]; let mut offset = 0; while offset < length { let n = (length - offset).min(zeros.len() as u64) as usize; card.file.write_all(&zeros[..n]).map_err(io_error)?; offset += n as u64; } card.sync()?; if card.file.metadata().map_err(io_error)?.blocks().saturating_mul(512) < length { return Err(Error::Unsupported); } initialize(&mut card, id)?; card.sync()?; // hard_link publishes without replacing a user file; parent sync makes the name durable. std::fs::hard_link(&temporary, path).map_err(io_error)?; File::open(parent).and_then(|f| f.sync_all()).map_err(io_error)?; Ok(card) })(); let cleanup = std::fs::remove_file(&temporary).and_then(|()| File::open(parent)?.sync_all()); match result { Ok(card) => { cleanup.map_err(io_error)?; Ok(card) } Err(e) => Err(e), } } #[cfg(not(unix))] pub fn create( _path: &Path, _length: u64, _initialize: impl FnOnce(&mut dyn MemcardStorage, [u8; 16]) -> Result<(), Error>, ) -> Result { Err(Error::Unsupported) } fn check(&self, offset: u64, length: usize) -> Result<(), Error> { if length > 65_536 || offset.checked_add(length as u64).is_none_or(|end| end > self.length) { return Err(Error::InvalidRange); } Ok(()) } } impl MemcardStorage for FileMemcard { fn len(&self) -> Result { Ok(self.length) } fn read_only(&self) -> bool { self.read_only } fn read_at(&mut self, offset: u64, target: &mut [u8]) -> Result<(), Error> { self.check(offset, target.len())?; self.file.seek(SeekFrom::Start(offset)).map_err(io_error)?; self.file.read_exact(target).map_err(io_error) } fn write_at(&mut self, offset: u64, source: &[u8]) -> Result<(), Error> { if self.read_only { return Err(Error::ReadOnly); } self.check(offset, source.len())?; self.file.seek(SeekFrom::Start(offset)).map_err(io_error)?; self.file.write_all(source).map_err(io_error) } fn sync(&mut self) -> Result<(), Error> { self.file.sync_all().map_err(io_error) } }