// SPDX-License-Identifier: AGPL-3.0-or-later /// Test data and functions to help with testing. use btserde::{Error, Result}; use fuse_backend_rs::{ api::filesystem::{ZeroCopyReader, ZeroCopyWriter}, file_buf::FileVolatileSlice, file_traits::FileReadWriteVolatile, }; use std::{ cell::RefCell, fmt::Write as FmtWrite, fs::File, io::{Cursor, Write}, }; use vm_memory::bytes::Bytes; use super::*; use crate::{crypto::*, sectored_buf::SectoredBuf, Cursor as PioCursor}; /// A smaller default sector size for use in tests. pub const SECTOR_SZ_DEFAULT: usize = 4096; pub const PRINCIPAL: [u8; 32] = [ 0x75, 0x28, 0xA9, 0xE0, 0x9D, 0x24, 0xBA, 0xB3, 0x79, 0x56, 0x15, 0x68, 0xFD, 0xA4, 0xE2, 0xA4, 0xCF, 0xB2, 0xC0, 0xE3, 0x96, 0xAE, 0xA2, 0x6E, 0x45, 0x15, 0x50, 0xED, 0xA6, 0xBE, 0x6D, 0xEC, ]; pub const PRINCIPAL2: [u8; 32] = [ 0x6E, 0x8A, 0x76, 0x1D, 0xC7, 0x3B, 0x50, 0x90, 0x51, 0x9E, 0x73, 0x9B, 0xEE, 0x7B, 0x02, 0xF9, 0xB9, 0x17, 0x7C, 0xF6, 0xBB, 0xC8, 0xD5, 0x30, 0xBF, 0x2A, 0xB4, 0xDE, 0x1B, 0x38, 0xCC, 0xF6, ]; pub const SIGNATURE: [u8; 384] = [ 0x12, 0xB1, 0x09, 0x2F, 0x2B, 0x3C, 0x53, 0xE8, 0x1B, 0x2B, 0x6A, 0xE7, 0x97, 0x42, 0x9D, 0x83, 0x71, 0x75, 0x65, 0x25, 0xFD, 0xB0, 0x0E, 0x2F, 0xAB, 0x53, 0xB7, 0x03, 0x03, 0x39, 0xEE, 0xE9, 0x15, 0x19, 0xAB, 0x1A, 0xF1, 0x2C, 0x3C, 0xAB, 0x5C, 0x02, 0xEA, 0xD6, 0xF6, 0x94, 0x36, 0x80, 0x5F, 0xD1, 0x8E, 0xC4, 0xB9, 0xB5, 0x04, 0x73, 0xBB, 0x77, 0x2C, 0x9C, 0xAF, 0xE6, 0x38, 0xB7, 0xD8, 0xC1, 0xA3, 0x1B, 0xAD, 0xFB, 0xB2, 0x5E, 0x77, 0xBD, 0x79, 0xDC, 0x4E, 0xEC, 0xEA, 0xFA, 0x80, 0x9F, 0x12, 0x60, 0xC4, 0xB3, 0x71, 0xAF, 0x1C, 0x28, 0xEE, 0x91, 0x1D, 0x6A, 0x69, 0x31, 0xA4, 0x5A, 0xAA, 0xBE, 0x0B, 0x20, 0x6A, 0xE1, 0x61, 0x0E, 0x0B, 0x9F, 0x60, 0x73, 0xBE, 0x29, 0x1F, 0x11, 0x0A, 0x8F, 0x42, 0x8F, 0x80, 0xC1, 0x06, 0x40, 0x29, 0xE9, 0xF1, 0x74, 0x44, 0x69, 0xCC, 0xD3, 0x05, 0x22, 0x24, 0x87, 0x94, 0x49, 0x4B, 0x5B, 0x62, 0x48, 0x01, 0x7B, 0x05, 0x28, 0xBE, 0x4D, 0x50, 0x06, 0xE5, 0x67, 0xA8, 0xFB, 0x9A, 0x19, 0x52, 0x57, 0x4B, 0xC4, 0xBB, 0x6A, 0xF5, 0x0D, 0x67, 0xD0, 0x08, 0x93, 0x81, 0xD2, 0x9E, 0xE2, 0xC8, 0xFA, 0x25, 0xEE, 0x9D, 0xC5, 0xD8, 0xF4, 0xD5, 0x17, 0xE4, 0xEF, 0xFC, 0x09, 0xB0, 0x09, 0xCA, 0xCA, 0x71, 0x36, 0x61, 0xBE, 0xC1, 0xD0, 0x53, 0x6D, 0x0C, 0x0A, 0x4D, 0xF1, 0xE0, 0xAB, 0x2C, 0x89, 0x98, 0x81, 0xED, 0x25, 0xF8, 0x81, 0x8E, 0x2C, 0x46, 0x74, 0x57, 0xCF, 0x5B, 0xE2, 0x14, 0xA5, 0xBF, 0x56, 0xED, 0xD3, 0x11, 0xE7, 0xB4, 0x8D, 0x89, 0x3A, 0xB2, 0x78, 0xF1, 0xA9, 0x82, 0x9D, 0x3B, 0xE5, 0x6B, 0xD2, 0xA5, 0xB6, 0xFB, 0x71, 0x0F, 0x98, 0x52, 0x54, 0x1E, 0x98, 0xD2, 0x3B, 0x78, 0x51, 0xD1, 0xE2, 0x57, 0xAE, 0xB3, 0x34, 0x0E, 0x20, 0x26, 0xCF, 0x4B, 0x1F, 0x12, 0xCA, 0xB1, 0xD5, 0x67, 0x55, 0xF9, 0xE2, 0xA9, 0x7B, 0xAE, 0x35, 0x35, 0x67, 0xA3, 0xCA, 0xBD, 0xF2, 0x41, 0x4E, 0x3F, 0x7E, 0x20, 0x72, 0xC2, 0xCC, 0xE4, 0x90, 0x00, 0x04, 0x5D, 0xF7, 0xD9, 0xC7, 0x0C, 0x2C, 0xF8, 0x80, 0xCB, 0xF2, 0x3E, 0x1A, 0xE9, 0x43, 0x23, 0xAF, 0x62, 0x57, 0xD1, 0x4C, 0xFD, 0x05, 0xB6, 0xB6, 0x86, 0xB9, 0x86, 0x40, 0xC2, 0x56, 0x45, 0x52, 0xE2, 0x93, 0x62, 0x65, 0x23, 0xE7, 0x1D, 0x89, 0xCA, 0x40, 0x23, 0x44, 0xDB, 0x56, 0x90, 0x4A, 0x0E, 0xB1, 0xB1, 0xE1, 0x9B, 0x5A, 0x5D, 0x53, 0xEF, 0x4E, 0xE1, 0x0E, 0x12, 0xA9, 0x7C, 0x11, 0x0B, 0x6A, 0x4C, 0x3A, 0x8F, 0x2B, 0x9F, 0xC6, 0x42, 0xD7, 0xFE, 0x7D, 0x10, 0x02, 0xBD, 0x31, 0x21, 0xCD, 0xD1, 0x32, 0x04, 0x22, 0xE2, 0x36, ]; /// The key of the parent of test blocks. pub static PARENT_KEY: SymKey = { let key = [ 0x35, 0x3D, 0x8C, 0x95, 0x6C, 0x8D, 0xE6, 0xC0, 0xB0, 0xD5, 0x1C, 0xE9, 0x94, 0xB0, 0x58, 0xD3, 0x80, 0x46, 0x12, 0x1C, 0xF3, 0x9B, 0x8A, 0xEC, 0x38, 0xD5, 0x8B, 0x05, 0x92, 0x8D, 0xA1, 0x18, ]; let iv = [ 0xDA, 0x96, 0x0E, 0xF5, 0x00, 0xDB, 0xC8, 0x4E, 0xFB, 0x83, 0x59, 0x99, 0x6C, 0x18, 0xD1, 0x27, ]; SymKey::Aes256Cbc { key, iv } }; lazy_static! { static ref INHERIT: Ciphertext = PARENT_KEY .ser_encrypt(&BLOCK_KEY) .expect("failed to encrypt block key"); } /// The key used to encrypt test blocks. pub static BLOCK_KEY: SymKey = { let key = [ 0xB2, 0xB3, 0xDA, 0x5A, 0x1A, 0xF6, 0xB3, 0x78, 0x30, 0xAB, 0x1D, 0x33, 0x33, 0xE7, 0xE3, 0x5B, 0xBB, 0xF9, 0xFE, 0xD0, 0xC1, 0xF7, 0x90, 0x34, 0x69, 0xB7, 0xE7, 0xC6, 0x1C, 0x46, 0x85, 0x48, ]; let iv = [ 0xEC, 0x19, 0x59, 0x3A, 0x1D, 0x1E, 0x4A, 0x58, 0x66, 0xC1, 0xD1, 0x9A, 0x61, 0x6E, 0xBA, 0x16, ]; SymKey::Aes256Cbc { key, iv } }; lazy_static! { pub static ref ROOT_CREDS: ConcreteCreds = ConcreteCreds::generate().expect("root cred generation failed"); pub static ref NODE_CREDS: ConcreteCreds = { let mut node_creds = ConcreteCreds::generate().expect("node cred generation failed"); let expires = Epoch::now() + Duration::from_secs(3600); let writecap = ROOT_CREDS .issue_writecap(node_creds.principal(), vec![], expires) .expect("failed to issue writecap to test_helpers::NODE_CREDS"); node_creds.set_writecap(writecap); node_creds }; } pub fn node_creds() -> &'static ConcreteCreds { &NODE_CREDS } pub fn root_creds() -> &'static ConcreteCreds { &ROOT_CREDS } /// Converts the given error to a serde_block_tree error by turning it into a message. fn convert_err(err: E) -> Error { Error::Message(err.to_string()) } pub fn make_principal() -> Principal { Principal(VarHash::Sha2_256(PRINCIPAL.into())) } pub fn make_path_with_root(root: Principal, rel_components: Vec<&str>) -> BlockPath { let mut components = Vec::with_capacity(rel_components.len()); for component in rel_components { components.push(component.to_string()); } BlockPath::new(root, components) } pub fn make_path(rel_components: Vec<&str>) -> BlockPath { make_path_with_root(make_principal(), rel_components) } pub fn make_writecap_and_creds(rel_components: Vec<&str>) -> (Writecap, impl Creds) { let (root_writecap, root_key) = make_self_signed_writecap(); let issued_to = Principal(VarHash::Sha2_256(PRINCIPAL.into())); ( make_writecap_trusted_by(root_writecap, &root_key, issued_to, rel_components), root_key, ) } pub fn make_writecap(rel_components: Vec<&str>) -> Writecap { let (writecap, ..) = make_writecap_and_creds(rel_components); writecap } pub fn make_writecap_trusted_by( next: Writecap, trusting_creds: &C, issued_to: Principal, path_components: Vec<&str>, ) -> Writecap { let hour_hence = Epoch::now() + Duration::from_secs(3600); let mut writecap = Writecap { body: WritecapBody { issued_to, path: make_path_with_root(next.body.path.root().clone(), path_components), expires: hour_hence, signing_key: trusting_creds.public_sign().clone(), }, signature: Signature::empty(Sign::RSA_PSS_3072_SHA_256), next: Some(Box::from(next)), }; trusting_creds .sign_writecap(&mut writecap) .map_err(convert_err) .expect("failed to sign writecap"); writecap } pub fn make_key_pair() -> impl Creds { NODE_CREDS.clone() } pub fn make_self_signed_writecap() -> (Writecap, impl Creds) { let key = make_key_pair(); (make_self_signed_writecap_with(&key), key) } pub fn make_self_signed_writecap_with(key: &C) -> Writecap { let root_principal = key.principal(); let hour_hence = Epoch::now() + Duration::from_secs(3600); let mut writecap = Writecap { body: WritecapBody { issued_to: root_principal.clone(), path: make_path_with_root(root_principal, vec![]), expires: hour_hence, signing_key: key.public_sign().clone(), }, signature: Signature::empty(Sign::RSA_PSS_3072_SHA_256), next: None, }; key.sign_writecap(&mut writecap) .map_err(convert_err) .expect("failed to sign writecap"); writecap } pub fn make_block_with() -> SectoredBuf>> { let block_key = SymKey::generate(SymKeyKind::default()).unwrap(); // Notice that the writecap path contains the block path. If this were not the case, the block // would be invalid. let (writecap, creds) = make_writecap_and_creds(vec!["apps"]); let root_writecap = writecap.next.as_ref().unwrap(); let path = make_path_with_root(root_writecap.body.issued_to.clone(), vec!["apps", "verse"]); let header = BlockMetaBody::new(&creds).unwrap(); let sig = Signature::copy_from(Sign::RSA_PSS_3072_SHA_256, &SIGNATURE); let mut stream = BlockStream::new( SectoredCursor::new(Vec::new(), SECTOR_SZ_DEFAULT).require_sect_sz(false), creds, None, path, ) .expect("create block stream failed"); stream.meta.body = header; stream.meta.sig = sig; let stream = MerkleStream::new(stream).expect("create merkle stream failed"); let stream = SecretStream::new(block_key) .try_compose(PioCursor::new(stream)) .expect("create secret stream failed"); SectoredBuf::new(stream).expect("failed to compose with SectoredBuf") } /// This function can be run as a test to write a new RSA key pair, as two Rust arrays, /// out to a file. #[allow(dead_code)] fn write_test_keys() -> Result<()> { write_rsa_keys_to_file("test_keys.rs") } struct NamedSlice<'a> { name: &'a str, slice: &'a [u8], } impl<'a> NamedSlice<'a> { fn new(name: &'a str, slice: &'a [u8]) -> NamedSlice<'a> { NamedSlice { name, slice } } } fn write_rsa_keys_to_file(path: &str) -> Result<()> { use openssl::rsa::Rsa; let rsa = Rsa::generate(3072).map_err(convert_err)?; let public_der = rsa.public_key_to_der().map_err(convert_err)?; let private_der = rsa.private_key_to_der().map_err(convert_err)?; let slices = [ NamedSlice::new("PUBLIC", public_der.as_slice()), NamedSlice::new("PRIVATE", private_der.as_slice()), ]; write_to_file(path, slices.into_iter()) } fn write_to_file<'a, I: Iterator>>(path: &str, slices: I) -> Result<()> { let path = std::path::Path::new(path); let mut file = File::create(path).map_err(Error::Io)?; for NamedSlice { name, slice } in slices { write_slice(&mut file, name, slice)?; } Ok(()) } fn write_slice(output: &mut W, name: &str, slice: &[u8]) -> Result<()> { const LINE_LEN: usize = 100; let mut line = String::with_capacity(LINE_LEN); write!(line, " ").map_err(Error::Format)?; writeln!(output, "pub const {}: [u8; {}] = [", name, slice.len()).map_err(Error::Io)?; for byte in slice { if line.len() + 6 > LINE_LEN { writeln!(output, "{}", line).map_err(Error::Io)?; line.clear(); write!(line, " ").map_err(Error::Format)?; } write!(line, "0x{:02X?}, ", byte).map_err(Error::Format)?; } writeln!(output, "{}", line).map_err(Error::Io)?; writeln!(output, "];").map_err(Error::Io)?; writeln!(output).map_err(Error::Io)?; Ok(()) } /// A naive randomizer implementation that is intended only for testing. pub struct Randomizer { state: [u8; Self::HASH.len()], buf: [u8; Self::HASH.len()], } impl Randomizer { pub const HASH: HashKind = HashKind::Sha2_256; pub fn new(seed: [u8; Self::HASH.len()]) -> Randomizer { Randomizer { state: seed, buf: [0u8; Self::HASH.len()], } } } impl Iterator for Randomizer { type Item = usize; fn next(&mut self) -> Option { const BYTES: usize = usize::BITS as usize / 8; Self::HASH .digest(&mut self.buf, std::iter::once(self.state.as_slice())) .expect("digest failed"); self.state.copy_from_slice(&self.buf); let int_bytes = self.buf.as_slice()[..BYTES] .try_into() .expect("failed to convert to array"); Some(usize::from_ne_bytes(int_bytes)) } } pub fn write_sector(mut buf: &mut [u8], sect_index: usize) { let data = (sect_index + 1).to_ne_bytes(); for chunk in std::iter::repeat(data).take(buf.len() / data.len()) { (&mut buf[..chunk.len()]).copy_from_slice(chunk.as_slice()); buf = &mut buf[chunk.len()..]; } } pub fn write_fill(mut write: W, sect_sz: usize, sect_ct: usize) { let mut buf = vec![0u8; sect_sz]; for sect_index in 0..sect_ct { write_sector(&mut buf, sect_index); write.write_all(&mut buf).expect("write failed"); } write.flush().expect("flush failed"); } pub fn read_check(mut read: R, sect_sz: usize, sect_ct: usize) { let mut actual = vec![0u8; sect_sz]; let mut expected = vec![0u8; sect_sz]; for sect_index in 0..sect_ct { write_sector(&mut expected, sect_index); read.read_exact(&mut actual).expect("read failed"); assert_eq!(expected, actual); } } #[allow(dead_code)] pub fn write_indices>( mut write: W, sect_sz: usize, indices: I, ) { let mut buf = vec![0u8; sect_sz]; for sect_index in indices { let offset = sect_index * sect_sz; write .seek(SeekFrom::Start(offset as u64)) .expect("seek failed"); write_sector(&mut buf, sect_index); write.write_all(&mut buf).expect("write failed"); } write.flush().expect("flush failed"); } #[allow(dead_code)] pub fn read_indices>( mut read: R, sect_sz: usize, indices: I, ) { let mut actual = vec![0u8; sect_sz]; let mut expected = vec![0u8; sect_sz]; for sect_index in indices { let offset = sect_index * sect_sz; read.seek(SeekFrom::Start(offset as u64)) .expect("seek failed"); write_sector(&mut expected, sect_index); read.read_exact(&mut actual).expect("read failed"); assert_eq!(expected, actual); } } #[allow(dead_code)] pub fn random_indices<'a>( rando: &'a mut Randomizer, sect_ct: usize, ) -> impl Iterator + 'a { rando.take(sect_ct).map(move |e| e % sect_ct) } /// Returns an integer array starting at the given value and increasing by one for each subsequent /// entry. pub const fn integer_array(start: u8) -> [u8; N] { let mut array = [0u8; N]; let mut k = 0usize; while k < N { array[k] = start.wrapping_add(k as u8); k += 1; } array } /// Trait for types which can be referenced as slices and which support conversion from `Vec`. pub trait FromVec: AsRef<[u8]> { fn from_vec(vec: Vec) -> Self; } impl FromVec for Vec { fn from_vec(vec: Vec) -> Self { vec } } impl FromVec for [u8; N] { fn from_vec(vec: Vec) -> Self { assert_eq!(N, vec.len()); let mut buf = [0u8; N]; buf.copy_from_slice(&vec); buf } } /// Module containing functions for serializing and deserializing buffers in `SectoredCursor`. mod serde_cursor { use super::FromVec; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::{ cell::RefCell, io::{Cursor, Read}, result::Result, }; pub fn serialize, S: Serializer>( cursor: &RefCell>, ser: S, ) -> Result { let mut cursor = cursor.borrow_mut(); let pos = cursor.position(); cursor.set_position(0); let mut data = Vec::new(); cursor .read_to_end(&mut data) .expect("reading from cursor failed"); cursor.set_position(pos); data.serialize(ser) } pub fn deserialize<'de, T: FromVec, D: Deserializer<'de>>( de: D, ) -> Result>, D::Error> { let data = Vec::::deserialize(de)?; Ok(RefCell::new(Cursor::new(T::from_vec(data)))) } } /// A wrapper for `Cursor` which implements additional traits. #[derive(Debug, PartialEq, Serialize, Deserialize)] pub struct BtCursor { #[serde(with = "serde_cursor")] cursor: RefCell>, } impl BtCursor { pub fn new(inner: T) -> BtCursor { BtCursor { cursor: RefCell::new(Cursor::new(inner)), } } } impl Decompose for BtCursor { fn into_inner(self) -> T { self.cursor.into_inner().into_inner() } } impl> BtCursor { /// Access the data in this cursor as a mutable slice of bytes. The callback which access the /// bytes is expected to return the number of bytes to advance the cursor position by. fn access_advance u64>(&mut self, limit: usize, accessor: F) -> u64 { let mut cursor = self.cursor.borrow_mut(); let pos = cursor.position(); let byte_slice = cursor.get_mut().as_mut(); let max = byte_slice.len().max(limit); let pos_usize: usize = pos.try_into().unwrap(); let byte_slice = &mut byte_slice[pos_usize..max]; let advance_by = accessor(byte_slice); cursor.set_position(pos + advance_by); advance_by } /// Gives a `accessor` access to a slice containing all of the data in this cursor. fn access_whole U>(&mut self, accessor: F) -> U { let mut cursor = self.cursor.borrow_mut(); let byte_slice = cursor.get_mut().as_mut(); accessor(byte_slice) } fn write_from_impl( &mut self, f: &mut dyn FileReadWriteVolatile, count: usize, off: u64, ) -> io::Result { let read = self.access_advance(count, |byte_slice| { let slice = unsafe { FileVolatileSlice::from_raw_ptr(byte_slice.as_mut_ptr(), byte_slice.len()) }; let read = f.read_at_volatile(slice, off).expect("read failed"); read.try_into().unwrap() }); Ok(read.try_into().unwrap()) } } impl Write for BtCursor> { fn write(&mut self, buf: &[u8]) -> io::Result { self.cursor.get_mut().write(buf) } fn flush(&mut self) -> io::Result<()> { self.cursor.get_mut().flush() } } impl Write for BtCursor<[u8; N]> { fn write(&mut self, buf: &[u8]) -> io::Result { self.cursor.get_mut().write(buf) } fn flush(&mut self) -> io::Result<()> { self.cursor.get_mut().flush() } } impl WriteAt for BtCursor> { fn write_at(&mut self, pos: u64, buf: &[u8]) -> io::Result { let pos: usize = pos.try_into().box_err()?; let vec = self.cursor.get_mut().get_mut(); let end = pos + buf.len(); if end > vec.len() { vec.resize(end, 0); } let slice = &mut vec[pos..end]; slice.copy_from_slice(buf); Ok(end - pos) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl WriteAt for BtCursor<[u8; N]> { fn write_at(&mut self, pos: u64, buf: &[u8]) -> io::Result { let pos: usize = pos.try_into().box_err()?; let slice = self.cursor.get_mut().get_mut().as_mut(); let end = pos + buf.len(); let slice = &mut slice[pos..end]; slice.copy_from_slice(buf); Ok(end - pos) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl Read for BtCursor { fn read(&mut self, buf: &mut [u8]) -> io::Result { self.cursor.get_mut().read(buf) } } impl ReadAt for BtCursor { fn read_at(&self, pos: u64, buf: &mut [u8]) -> io::Result { let pos: usize = pos.try_into().box_err()?; let borrow = self.cursor.try_borrow().box_err()?; let slice: &[u8] = borrow.get_ref().as_ref(); let end = slice.len().min(pos + buf.len()); let buf = &mut buf[..(end - pos)]; buf.copy_from_slice(&slice[pos..end]); Ok(end - pos) } } impl Seek for BtCursor { fn seek(&mut self, pos: SeekFrom) -> io::Result { self.cursor.get_mut().seek(pos) } } impl WriteInteg for BtCursor> { fn flush_integ(&mut self, _: &[u8]) -> io::Result<()> { Ok(()) } } impl WriteInteg for BtCursor<[u8; N]> { fn flush_integ(&mut self, _: &[u8]) -> io::Result<()> { Ok(()) } } impl + FromVec> FileReadWriteVolatile for BtCursor { fn read_volatile( &mut self, slice: fuse_backend_rs::file_buf::FileVolatileSlice, ) -> io::Result { let read = self.access_advance(usize::MAX, |byte_slice| { let written = slice.as_volatile_slice().write(byte_slice, 0).unwrap(); written.try_into().unwrap() }); Ok(read.try_into().unwrap()) } fn write_volatile( &mut self, slice: fuse_backend_rs::file_buf::FileVolatileSlice, ) -> io::Result { let written = self.access_advance(usize::MAX, |byte_slice| { let read = slice.as_volatile_slice().read(byte_slice, 0).unwrap(); read.try_into().unwrap() }); Ok(written.try_into().unwrap()) } fn read_at_volatile( &mut self, slice: fuse_backend_rs::file_buf::FileVolatileSlice, offset: u64, ) -> io::Result { Ok(self.access_whole(|byte_slice| { let offset = offset.try_into().unwrap(); let byte_slice = &mut byte_slice[offset..]; slice.as_volatile_slice().write(byte_slice, 0).unwrap() })) } fn write_at_volatile( &mut self, slice: fuse_backend_rs::file_buf::FileVolatileSlice, offset: u64, ) -> io::Result { Ok(self.access_whole(|byte_slice| { let offset = offset.try_into().unwrap(); let byte_slice = &mut byte_slice[offset..]; slice.as_volatile_slice().read(byte_slice, 0).unwrap() })) } } impl + FromVec> ZeroCopyReader for BtCursor { fn read_to( &mut self, f: &mut dyn FileReadWriteVolatile, count: usize, off: u64, ) -> io::Result { let written = self.access_advance(count, |byte_slice| { // Safety: The mut borrow of cursor is guaranteed to be the only one in existence // because this method takes &mut self. let slice = unsafe { FileVolatileSlice::from_raw_ptr(byte_slice.as_mut_ptr(), byte_slice.len()) }; let written = f.write_at_volatile(slice, off).expect("write failed"); let written_u64: u64 = written.try_into().unwrap(); written_u64 }); Ok(written.try_into().unwrap()) } } impl ZeroCopyWriter for BtCursor> { fn write_from( &mut self, f: &mut dyn FileReadWriteVolatile, count: usize, off: u64, ) -> io::Result { self.write_from_impl(f, count, off) } } impl ZeroCopyWriter for BtCursor<[u8; N]> { fn write_from( &mut self, f: &mut dyn FileReadWriteVolatile, count: usize, off: u64, ) -> io::Result { self.write_from_impl(f, count, off) } } impl Size for BtCursor { fn size(&self) -> io::Result> { let borrow = self.cursor.borrow(); let slice: &[u8] = borrow.get_ref().as_ref(); Ok(Some(slice.len() as u64)) } } #[derive(Debug, PartialEq, Serialize, Deserialize)] pub struct SectoredCursor { cursor: BtCursor, sect_sz: usize, meta: BlockMeta, require_sect_sz: bool, } impl SectoredCursor { pub fn new(inner: T, sect_sz: usize) -> SectoredCursor { SectoredCursor { cursor: BtCursor::new(inner), sect_sz, meta: BlockMeta::new(&*NODE_CREDS).unwrap(), require_sect_sz: true, } } pub fn require_sect_sz(mut self, require: bool) -> Self { self.require_sect_sz = require; self } } impl Sectored for SectoredCursor { fn sector_sz(&self) -> usize { self.sect_sz } } impl Decompose for SectoredCursor { fn into_inner(self) -> T { self.cursor.into_inner() } } impl Write for SectoredCursor> { fn write(&mut self, buf: &[u8]) -> io::Result { if self.require_sect_sz { self.assert_sector_sz(buf.len())?; } self.cursor.write(buf) } fn flush(&mut self) -> io::Result<()> { Write::flush(&mut self.cursor) } } impl Write for SectoredCursor<[u8; N]> { fn write(&mut self, buf: &[u8]) -> io::Result { if self.require_sect_sz { self.assert_sector_sz(buf.len())?; } self.cursor.write(buf) } fn flush(&mut self) -> io::Result<()> { Write::flush(&mut self.cursor) } } impl WriteAt for SectoredCursor> { fn write_at(&mut self, pos: u64, buf: &[u8]) -> io::Result { self.cursor.write_at(pos, buf) } fn flush(&mut self) -> io::Result<()> { Write::flush(&mut self.cursor) } } impl WriteAt for SectoredCursor<[u8; N]> { fn write_at(&mut self, pos: u64, buf: &[u8]) -> io::Result { self.cursor.write_at(pos, buf) } fn flush(&mut self) -> io::Result<()> { Write::flush(&mut self.cursor) } } impl SectoredCursor { fn flush_integ_impl(&mut self, integrity: &[u8]) -> io::Result<()> { let dest = self .meta .body .integrity .get_or_insert_with(::default); dest.as_mut_slice().copy_from_slice(integrity); Ok(()) } } impl WriteInteg for SectoredCursor> { fn flush_integ(&mut self, integrity: &[u8]) -> io::Result<()> { self.flush_integ_impl(integrity) } } impl WriteInteg for SectoredCursor<[u8; N]> { fn flush_integ(&mut self, integrity: &[u8]) -> io::Result<()> { self.flush_integ_impl(integrity) } } impl Read for SectoredCursor { fn read(&mut self, buf: &mut [u8]) -> io::Result { if self.require_sect_sz { self.assert_sector_sz(buf.len())?; } self.cursor.read(buf) } } impl ReadAt for SectoredCursor { fn read_at(&self, pos: u64, buf: &mut [u8]) -> io::Result { if self.require_sect_sz { self.assert_sector_sz(buf.len())?; } self.cursor.read_at(pos, buf) } } impl Seek for SectoredCursor { fn seek(&mut self, pos: SeekFrom) -> io::Result { self.cursor.seek(pos) } } impl AsRef for SectoredCursor { fn as_ref(&self) -> &BlockMeta { &self.meta } } impl AsMut for SectoredCursor { fn as_mut(&mut self) -> &mut BlockMeta { &mut self.meta } } impl Size for SectoredCursor { fn size(&self) -> io::Result> { self.cursor.size() } }