//! Whole-file reads and writes for `std/file`: blocking externs, run on //! the blocking pool while their actor is parked (see `blocking.rs`). //! //! Every failure is an `Error` value with the OS's message: a blocking //! extern must not panic. use crate::abi::{Ctx, UNIT, Value, int}; use crate::prims::boolean; use crate::values::{bytes_from, bytes_of, error, list, ok, string, text}; /// `read_bytes(path)`: the file's contents, or `Error` with the OS's /// message. /// /// # Safety /// `path` must be a live string; `ctx` the calling actor's context. The /// result is built with the allocation functions of `louise_rt.h`, which /// work on any thread, as a blocking extern requires. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_file_read(ctx: *mut Ctx, path: Value) -> Value { // SAFETY: caller guarantees a live string. match std::fs::read(unsafe { text(path) }) { Ok(bytes) => { let b = bytes_from(ctx, &bytes); ok(ctx, b) } Err(e) => error(ctx, &e.to_string()), } } /// `write(path, content)`: the file created or truncated, or `Error` with /// the OS's message. /// /// # Safety /// `path` must be a live string and `content` live `Bytes`; `ctx` the /// calling actor's context. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_file_write(ctx: *mut Ctx, path: Value, content: Value) -> Value { // SAFETY: caller guarantees a live string and live Bytes. let (path, content) = unsafe { (text(path), bytes_of(content)) }; match std::fs::write(path, content) { Ok(()) => ok(ctx, UNIT), Err(e) => error(ctx, &e.to_string()), } } /// Whether a file (not a directory) exists at `path`. /// /// # Safety /// `path` must be a live string. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_file_exists(_ctx: *mut Ctx, path: Value) -> Value { // SAFETY: caller guarantees a live string. boolean(std::path::Path::is_file(std::path::Path::new(unsafe { text(path) }))) } /// The file's size in bytes, or `Error` with the OS's message. /// /// # Safety /// `path` must be a live string; `ctx` the calling actor's context. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_file_size(ctx: *mut Ctx, path: Value) -> Value { // SAFETY: caller guarantees a live string. match std::fs::metadata(unsafe { text(path) }) { Ok(meta) => ok(ctx, int(i64::try_from(meta.len()).unwrap_or(i64::MAX))), Err(e) => error(ctx, &e.to_string()), } } /// The names of the directory's entries (not full paths, never `.` or /// `..`, in the OS's order), or `Error` with the OS's message. A name /// that is not valid UTF-8 is lossy-decoded. /// /// # Safety /// `path` must be a live string; `ctx` the calling actor's context. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_file_list_dir(ctx: *mut Ctx, path: Value) -> Value { // SAFETY: caller guarantees a live string. let entries = match std::fs::read_dir(unsafe { text(path) }) { Ok(entries) => entries, Err(e) => return error(ctx, &e.to_string()), }; let mut names = Vec::new(); for entry in entries { match entry { Ok(e) => names.push(string(ctx, &e.file_name().to_string_lossy())), Err(e) => return error(ctx, &e.to_string()), } } ok(ctx, list(ctx, names.into_iter())) } #[cfg(test)] mod tests { use super::*; use crate::abi::{Block, int_get}; use crate::heap::drop_value; use crate::values::{list_items, string, string_bytes, text}; /// (tag, first field) of a constructor value (`Ok` is tag 0). unsafe fn ctor(v: Value) -> (u16, Value) { // SAFETY: a live constructor cell. unsafe { let b = v as *mut Block; ((*b).header.tag, Block::fields_ptr(b).read()) } } extern "C" fn roundtrip(ctx: *mut Ctx) -> Value { // SAFETY: the test follows the generated-code convention: fresh // values are dropped once, arguments of the externs are borrowed. unsafe { let path = std::env::temp_dir().join("louise_rt_fs_test.bin"); let path = path.to_str().unwrap(); let p = string(ctx, path); std::fs::remove_file(path).ok(); assert_eq!(tl_file_exists(ctx, p), int(0)); let content = bytes_from(ctx, b"hello"); let wrote = tl_file_write(ctx, p, content); assert_eq!(ctor(wrote).0, 0, "Ok expected"); assert_eq!(tl_file_exists(ctx, p), int(1)); let size = tl_file_size(ctx, p); let (tag, n) = ctor(size); assert_eq!(tag, 0, "Ok expected"); assert_eq!(int_get(n), 5); let read = tl_file_read(ctx, p); let (tag, bytes) = ctor(read); assert_eq!(tag, 0, "Ok expected"); assert_eq!(string_bytes(bytes), b"hello"); // A missing file is an `Error`, not a panic. std::fs::remove_file(path).unwrap(); let missing = tl_file_read(ctx, p); assert_eq!(ctor(missing).0, 1, "Error expected"); for v in [wrote, size, read, missing, content, p] { drop_value(ctx, v); } assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0); UNIT } } #[test] fn write_read_exists_size_and_errors() { // SAFETY: the test actor follows the generated-code convention. assert_eq!(unsafe { crate::sched::run_test_actor(roundtrip) }, 0); } extern "C" fn lists_dir(ctx: *mut Ctx) -> Value { // SAFETY: the test follows the generated-code convention: fresh // values are dropped once, arguments of the externs are borrowed. unsafe { let p = string(ctx, "."); let listed = tl_file_list_dir(ctx, p); let (tag, entries) = ctor(listed); assert_eq!(tag, 0, "Ok expected"); let names: Vec<&str> = list_items(entries).map(|e| text(e)).collect(); assert!(names.contains(&"Cargo.toml"), "{names:?}"); assert!(!names.contains(&"."), "{names:?}"); // A missing directory is an `Error`, not a panic. let np = string(ctx, "/definitely/not/here"); let missing = tl_file_list_dir(ctx, np); assert_eq!(ctor(missing).0, 1, "Error expected"); for v in [listed, missing, p, np] { drop_value(ctx, v); } assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0); UNIT } } #[test] fn list_dir_lists_and_errors() { // SAFETY: the test actor follows the generated-code convention. assert_eq!(unsafe { crate::sched::run_test_actor(lists_dir) }, 0); } }