use std::path::{Path, PathBuf};
use crate::filesystem::{Filesystem, FilesystemError};
use async_trait::async_trait;
pub struct NativeFilesystem {
root_dir: PathBuf,
}
impl NativeFilesystem {
pub fn new<P: AsRef<Path>>(root_dir: P) -> Self {
Self {
root_dir: PathBuf::from(root_dir.as_ref()),
}
}
pub fn root_dir(&self) -> &Path {
&self.root_dir
}
}
#[async_trait]
impl Filesystem for NativeFilesystem {
async fn read_bytes(&self, asset_path: &str) -> Result<Vec<u8>, FilesystemError> {
let path = self.root_dir.join(asset_path);
if !path.is_file() {
return Err(FilesystemError::NotFound(asset_path.to_string()));
}
let bytes = std::fs::read(path).map_err(FilesystemError::from)?;
Ok(bytes)
}
}
#[cfg(test)]
mod test {
use super::*;
use std::sync::Arc;
#[test]
fn read_bytes() {
let tests_dir = Path::new(&env!("CARGO_MANIFEST_DIR")).join("tests");
let fs: Arc<dyn Filesystem> = Arc::new(NativeFilesystem::new(tests_dir));
let greeting = pollster::block_on(fs.read_bytes("test_data_0/hello.txt")).unwrap();
assert_eq!(greeting, b"Hello world\n");
}
}