//! Populate one unpublished read-only page from a borrowed, validated file. //! Logical EOF is authoritative even when the final disk sector has other data. use super::turkfs_reader::{File,BlockReader,BLOCK_BYTES}; use super::page_tables::descriptor::Permissions; pub const PAGE:usize=4096; #[derive(Clone,Copy,Debug,PartialEq,Eq)] pub enum Error{Offset,Alignment,ReadFailed,Backing} #[derive(Debug)] pub struct Page<'a>{source:Source<'a>,offset:usize,bytes:usize} #[derive(Debug)] enum Source<'a>{Extents(&'a File),Contiguous(&'a Contiguous)} /// A bounded contiguous file descriptor. The filesystem adapter must bind /// this descriptor to the validated inode before creating a mapping plan. #[derive(Debug)] pub struct Contiguous{first:u64,size:usize,blocks:u64} impl Contiguous{ pub fn new(first:u64,size:usize,disk_blocks:u64)->Result{ let blocks=u64::try_from(size).ok().and_then(|n|n.checked_add(BLOCK_BYTES as u64-1)).map(|n|n/BLOCK_BYTES as u64).ok_or(Error::Backing)?; if first==0||size==0||first.checked_add(blocks).is_none_or(|end|end>disk_blocks){return Err(Error::Backing);} Ok(Self{first,size,blocks}) } pub fn size(&self)->usize{self.size} } impl<'a> Page<'a>{ pub fn new(file:&'a File,offset:usize)->Result{ Self::checked(Source::Extents(file),file.size(),offset) } pub fn contiguous(file:&'a Contiguous,offset:usize)->Result{ Self::checked(Source::Contiguous(file),file.size,offset) } fn checked(source:Source<'a>,size:usize,offset:usize)->Result{ if offset>=size{return Err(Error::Offset);} if offset%PAGE!=0{return Err(Error::Alignment);} Ok(Self{source,offset,bytes:(size-offset).min(PAGE)}) } pub fn file_bytes(&self)->usize{self.bytes} pub fn offset(&self)->usize{self.offset} pub fn permissions(&self)->Permissions{Permissions{user:true,write:false,execute:false}} fn block(&self,mut logical:usize)->Result{ let file=match self.source{ Source::Contiguous(file)=>return if (logical as u64)file, }; for extent in file.extents(){ let count=usize::try_from(extent.block_count).map_err(|_|Error::Backing)?; if logical(&self,reader:&mut R,destination:&mut[u8;PAGE])->Result<(),Error>{ destination.fill(0); let result=(||{ let mut copied=0; while copied