use std::sync::{Arc, Mutex};
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FsError {
NotFound,
BadPath,
Io(String),
Unsupported,
}
impl std::fmt::Display for FsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FsError::NotFound => write!(f, "not found"),
FsError::BadPath => write!(f, "bad path (relative, no `.`/`..` segments)"),
FsError::Io(m) => write!(f, "{m}"),
FsError::Unsupported => write!(f, "no file storage on this target"),
}
}
}
impl std::error::Error for FsError {}
fn check_path(path: &str) -> Result<(), FsError> {
if path.is_empty()
|| path.starts_with('/')
|| path.starts_with('\\')
|| path.contains(':')
|| path
.split(['/', '\\'])
.any(|seg| seg.is_empty() || seg == "." || seg == "..")
{
return Err(FsError::BadPath);
}
Ok(())
}
pub fn read(path: &str) -> Result<Vec<u8>, FsError> {
check_path(path)?;
imp::read(path)
}
#[cfg(not(target_arch = "wasm32"))]
pub fn open_read(path: &str) -> Result<std::fs::File, FsError> {
check_path(path)?;
imp::open_read(path)
}
pub fn write(path: &str, bytes: &[u8]) -> Result<(), FsError> {
check_path(path)?;
imp::write(path, bytes)
}
pub fn remove(path: &str) -> Result<(), FsError> {
check_path(path)?;
imp::remove(path)
}
pub fn list(dir: &str) -> Result<Vec<String>, FsError> {
if !dir.is_empty() {
check_path(dir)?;
}
imp::list(dir)
}
type BytesResult = Result<Vec<u8>, FsError>;
type UnitResult = Result<(), FsError>;
type ListResult = Result<Vec<String>, FsError>;
pub fn read_async(path: &str, on_done: impl FnOnce(BytesResult) + Send + 'static) {
if let Err(e) = check_path(path) {
on_done(Err(e));
return;
}
imp::read_async(path.to_string(), Box::new(on_done));
}
pub fn write_async(path: &str, bytes: Vec<u8>, on_done: impl FnOnce(UnitResult) + Send + 'static) {
if let Err(e) = check_path(path) {
on_done(Err(e));
return;
}
imp::write_async(path.to_string(), bytes, Box::new(on_done));
}
pub fn remove_async(path: &str, on_done: impl FnOnce(UnitResult) + Send + 'static) {
if let Err(e) = check_path(path) {
on_done(Err(e));
return;
}
imp::remove_async(path.to_string(), Box::new(on_done));
}
pub fn list_async(dir: &str, on_done: impl FnOnce(ListResult) + Send + 'static) {
if !dir.is_empty()
&& let Err(e) = check_path(dir)
{
on_done(Err(e));
return;
}
imp::list_async(dir.to_string(), Box::new(on_done));
}
struct FutureState<T> {
result: Option<T>,
waker: Option<std::task::Waker>,
}
impl<T> Default for FutureState<T> {
fn default() -> Self {
FutureState {
result: None,
waker: None,
}
}
}
pub struct FsFuture<T> {
shared: Arc<Mutex<FutureState<T>>>,
}
fn lock<T>(m: &Mutex<FutureState<T>>) -> std::sync::MutexGuard<'_, FutureState<T>> {
match m.lock() {
Ok(g) => g,
Err(poisoned) => poisoned.into_inner(),
}
}
impl<T> std::future::Future for FsFuture<T> {
type Output = T;
fn poll(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<T> {
let mut st = lock(&self.shared);
if let Some(r) = st.result.take() {
return std::task::Poll::Ready(r);
}
st.waker = Some(cx.waker().clone());
std::task::Poll::Pending
}
}
fn deliver<T>(shared: &Arc<Mutex<FutureState<T>>>, result: T) {
let waker = {
let mut st = lock(shared);
st.result = Some(result);
st.waker.take()
};
if let Some(w) = waker {
w.wake();
}
}
macro_rules! future_over {
($shared:ident, $call:expr) => {{
let $shared = Arc::new(Mutex::new(FutureState::default()));
let sink = $shared.clone();
$call;
FsFuture { shared: sink }
}};
}
#[must_use]
pub fn read_future(path: &str) -> FsFuture<BytesResult> {
future_over!(shared, {
let s = shared.clone();
read_async(path, move |r| deliver(&s, r));
})
}
#[must_use]
pub fn write_future(path: &str, bytes: Vec<u8>) -> FsFuture<UnitResult> {
future_over!(shared, {
let s = shared.clone();
write_async(path, bytes, move |r| deliver(&s, r));
})
}
#[must_use]
pub fn remove_future(path: &str) -> FsFuture<UnitResult> {
future_over!(shared, {
let s = shared.clone();
remove_async(path, move |r| deliver(&s, r));
})
}
#[must_use]
pub fn list_future(dir: &str) -> FsFuture<ListResult> {
future_over!(shared, {
let s = shared.clone();
list_async(dir, move |r| deliver(&s, r));
})
}
#[cfg(not(target_arch = "wasm32"))]
pub fn data_dir() -> Result<std::path::PathBuf, FsError> {
imp::data_dir()
}
#[cfg(not(target_arch = "wasm32"))]
pub fn platform_data_dir() -> Result<std::path::PathBuf, FsError> {
imp::platform_data_dir()
}
#[cfg(not(target_arch = "wasm32"))]
#[path = "native.rs"]
mod imp;
#[cfg(target_arch = "wasm32")]
#[path = "web.rs"]
mod imp;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn path_rules() {
for bad in [
"", "/abs", "a//b", "./x", "../x", "a/../b", "c:win", "a/./b",
] {
assert_eq!(check_path(bad), Err(FsError::BadPath), "{bad:?}");
}
for good in ["a", "a/b.txt", "notes/2026/07.md"] {
assert_eq!(check_path(good), Ok(()), "{good:?}");
}
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn round_trip_list_remove() {
let scratch = std::env::temp_dir().join(format!("day-part-fs-{}", std::process::id()));
unsafe { std::env::set_var("DAY_DATA_DIR", &scratch) };
write("t/hello.txt", b"hi").unwrap();
assert_eq!(read("t/hello.txt").unwrap(), b"hi");
{
use std::io::{Read, Seek, SeekFrom, Write};
let mut file = open_read("t/hello.txt").unwrap();
file.seek(SeekFrom::Start(1)).unwrap();
let mut byte = [0];
file.read_exact(&mut byte).unwrap();
assert_eq!(&byte, b"i");
assert!(file.write_all(b"x").is_err(), "handle must be read-only");
}
assert_eq!(open_read("t/missing.txt").unwrap_err(), FsError::NotFound);
assert_eq!(open_read("../outside").unwrap_err(), FsError::BadPath);
assert_eq!(list("t").unwrap(), vec!["hello.txt".to_string()]);
assert_eq!(read("t/missing.txt"), Err(FsError::NotFound));
remove("t/hello.txt").unwrap();
assert_eq!(remove("t/hello.txt"), Err(FsError::NotFound));
assert_eq!(list("t").unwrap(), Vec::<String>::new());
let _ = std::fs::remove_dir_all(&scratch);
}
}