use std::path::{Path, PathBuf};
use crate::error::Error;
thread_local! {
static RECORDING: std::cell::RefCell<Option<Vec<PathBuf>>> =
const { std::cell::RefCell::new(None) };
}
#[cfg(target_arch = "wasm32")]
thread_local! {
static PRELOADED: std::cell::RefCell<std::collections::HashMap<PathBuf, Vec<u8>>> =
std::cell::RefCell::new(std::collections::HashMap::new());
}
#[cfg(target_arch = "wasm32")]
pub fn preload(path: impl Into<PathBuf>, bytes: Vec<u8>) {
PRELOADED.with(|map| map.borrow_mut().insert(path.into(), bytes));
}
#[doc(hidden)]
pub fn start_recording() {
RECORDING.with(|slot| *slot.borrow_mut() = Some(Vec::new()));
}
#[doc(hidden)]
pub fn stop_recording() -> Vec<PathBuf> {
RECORDING.with(|slot| slot.borrow_mut().take().unwrap_or_default())
}
fn record(path: &Path) {
RECORDING.with(|slot| {
if let Some(paths) = slot.borrow_mut().as_mut() {
paths.push(path.to_path_buf());
}
});
}
pub(crate) fn read(path: &Path) -> Result<Vec<u8>, Error> {
record(path);
read_inner(path)
}
pub(crate) fn read_to_string(path: &Path) -> Result<String, Error> {
let bytes = read(path)?;
String::from_utf8(bytes).map_err(|error| {
Error::io(
path,
std::io::Error::new(std::io::ErrorKind::InvalidData, error.utf8_error()),
)
})
}
#[cfg(not(target_arch = "wasm32"))]
fn read_inner(path: &Path) -> Result<Vec<u8>, Error> {
std::fs::read(path).map_err(|error| Error::io(path, error))
}
#[cfg(target_arch = "wasm32")]
fn read_inner(path: &Path) -> Result<Vec<u8>, Error> {
PRELOADED
.with(|map| map.borrow().get(path).cloned())
.ok_or_else(|| {
Error::io(
path,
std::io::Error::new(
std::io::ErrorKind::NotFound,
"not preloaded: no three_rs::io::preload() for this path",
),
)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn not_recording_by_default() {
assert!(stop_recording().is_empty());
}
#[test]
fn records_every_read_in_order() {
start_recording();
let _ = read(Path::new("/nowhere/a.png"));
let _ = read(Path::new("/nowhere/b.png"));
let _ = read(Path::new("/nowhere/a.png"));
assert_eq!(
stop_recording(),
vec![
PathBuf::from("/nowhere/a.png"),
PathBuf::from("/nowhere/b.png"),
PathBuf::from("/nowhere/a.png"),
]
);
let _ = read(Path::new("/nowhere/c.png"));
assert!(stop_recording().is_empty());
}
#[test]
fn a_miss_is_not_found() {
let error = read(Path::new("/nowhere/at/all.png")).unwrap_err();
match error {
Error::Io { source, .. } => {
assert_eq!(source.kind(), std::io::ErrorKind::NotFound)
}
other => panic!("expected Error::Io, got {other:?}"),
}
}
}