tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

184 lignes · 6773 octetsBrut · Historique
1//! Whole-file reads and writes for `std/file`: blocking externs, run on
2//! the blocking pool while their actor is parked (see `blocking.rs`).
3//!
4//! Every failure is an `Error` value with the OS's message: a blocking
5//! extern must not panic.
6
7use crate::abi::{Ctx, UNIT, Value, int};
8use crate::prims::boolean;
9use crate::values::{bytes_from, bytes_of, error, list, ok, string, text};
10
11/// `read_bytes(path)`: the file's contents, or `Error` with the OS's
12/// message.
13///
14/// # Safety
15/// `path` must be a live string; `ctx` the calling actor's context. The
16/// result is built with the allocation functions of `louise_rt.h`, which
17/// work on any thread, as a blocking extern requires.
18#[unsafe(no_mangle)]
19pub unsafe extern "C" fn tl_file_read(ctx: *mut Ctx, path: Value) -> Value {
20 // SAFETY: caller guarantees a live string.
21 match std::fs::read(unsafe { text(path) }) {
22 Ok(bytes) => {
23 let b = bytes_from(ctx, &bytes);
24 ok(ctx, b)
25 }
26 Err(e) => error(ctx, &e.to_string()),
27 }
28}
29
30/// `write(path, content)`: the file created or truncated, or `Error` with
31/// the OS's message.
32///
33/// # Safety
34/// `path` must be a live string and `content` live `Bytes`; `ctx` the
35/// calling actor's context.
36#[unsafe(no_mangle)]
37pub unsafe extern "C" fn tl_file_write(ctx: *mut Ctx, path: Value, content: Value) -> Value {
38 // SAFETY: caller guarantees a live string and live Bytes.
39 let (path, content) = unsafe { (text(path), bytes_of(content)) };
40 match std::fs::write(path, content) {
41 Ok(()) => ok(ctx, UNIT),
42 Err(e) => error(ctx, &e.to_string()),
43 }
44}
45
46/// Whether a file (not a directory) exists at `path`.
47///
48/// # Safety
49/// `path` must be a live string.
50#[unsafe(no_mangle)]
51pub unsafe extern "C" fn tl_file_exists(_ctx: *mut Ctx, path: Value) -> Value {
52 // SAFETY: caller guarantees a live string.
53 boolean(std::path::Path::is_file(std::path::Path::new(unsafe {
54 text(path)
55 })))
56}
57
58/// The file's size in bytes, or `Error` with the OS's message.
59///
60/// # Safety
61/// `path` must be a live string; `ctx` the calling actor's context.
62#[unsafe(no_mangle)]
63pub unsafe extern "C" fn tl_file_size(ctx: *mut Ctx, path: Value) -> Value {
64 // SAFETY: caller guarantees a live string.
65 match std::fs::metadata(unsafe { text(path) }) {
66 Ok(meta) => ok(ctx, int(i64::try_from(meta.len()).unwrap_or(i64::MAX))),
67 Err(e) => error(ctx, &e.to_string()),
68 }
69}
70
71/// The names of the directory's entries (not full paths, never `.` or
72/// `..`, in the OS's order), or `Error` with the OS's message. A name
73/// that is not valid UTF-8 is lossy-decoded.
74///
75/// # Safety
76/// `path` must be a live string; `ctx` the calling actor's context.
77#[unsafe(no_mangle)]
78pub unsafe extern "C" fn tl_file_list_dir(ctx: *mut Ctx, path: Value) -> Value {
79 // SAFETY: caller guarantees a live string.
80 let entries = match std::fs::read_dir(unsafe { text(path) }) {
81 Ok(entries) => entries,
82 Err(e) => return error(ctx, &e.to_string()),
83 };
84 let mut names = Vec::new();
85 for entry in entries {
86 match entry {
87 Ok(e) => names.push(string(ctx, &e.file_name().to_string_lossy())),
88 Err(e) => return error(ctx, &e.to_string()),
89 }
90 }
91 ok(ctx, list(ctx, names.into_iter()))
92}
93
94#[cfg(test)]
95mod tests {
96 use super::*;
97 use crate::abi::{Block, int_get};
98 use crate::heap::drop_value;
99 use crate::values::{list_items, string, string_bytes, text};
100
101 /// (tag, first field) of a constructor value (`Ok` is tag 0).
102 unsafe fn ctor(v: Value) -> (u16, Value) {
103 // SAFETY: a live constructor cell.
104 unsafe {
105 let b = v as *mut Block;
106 ((*b).header.tag, Block::fields_ptr(b).read())
107 }
108 }
109
110 extern "C" fn roundtrip(ctx: *mut Ctx) -> Value {
111 // SAFETY: the test follows the generated-code convention: fresh
112 // values are dropped once, arguments of the externs are borrowed.
113 unsafe {
114 let path = std::env::temp_dir().join("louise_rt_fs_test.bin");
115 let path = path.to_str().unwrap();
116 let p = string(ctx, path);
117 std::fs::remove_file(path).ok();
118 assert_eq!(tl_file_exists(ctx, p), int(0));
119
120 let content = bytes_from(ctx, b"hello");
121 let wrote = tl_file_write(ctx, p, content);
122 assert_eq!(ctor(wrote).0, 0, "Ok expected");
123 assert_eq!(tl_file_exists(ctx, p), int(1));
124
125 let size = tl_file_size(ctx, p);
126 let (tag, n) = ctor(size);
127 assert_eq!(tag, 0, "Ok expected");
128 assert_eq!(int_get(n), 5);
129
130 let read = tl_file_read(ctx, p);
131 let (tag, bytes) = ctor(read);
132 assert_eq!(tag, 0, "Ok expected");
133 assert_eq!(string_bytes(bytes), b"hello");
134
135 // A missing file is an `Error`, not a panic.
136 std::fs::remove_file(path).unwrap();
137 let missing = tl_file_read(ctx, p);
138 assert_eq!(ctor(missing).0, 1, "Error expected");
139
140 for v in [wrote, size, read, missing, content, p] {
141 drop_value(ctx, v);
142 }
143 assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0);
144 UNIT
145 }
146 }
147
148 #[test]
149 fn write_read_exists_size_and_errors() {
150 // SAFETY: the test actor follows the generated-code convention.
151 assert_eq!(unsafe { crate::sched::run_test_actor(roundtrip) }, 0);
152 }
153
154 extern "C" fn lists_dir(ctx: *mut Ctx) -> Value {
155 // SAFETY: the test follows the generated-code convention: fresh
156 // values are dropped once, arguments of the externs are borrowed.
157 unsafe {
158 let p = string(ctx, ".");
159 let listed = tl_file_list_dir(ctx, p);
160 let (tag, entries) = ctor(listed);
161 assert_eq!(tag, 0, "Ok expected");
162 let names: Vec<&str> = list_items(entries).map(|e| text(e)).collect();
163 assert!(names.contains(&"Cargo.toml"), "{names:?}");
164 assert!(!names.contains(&"."), "{names:?}");
165
166 // A missing directory is an `Error`, not a panic.
167 let np = string(ctx, "/definitely/not/here");
168 let missing = tl_file_list_dir(ctx, np);
169 assert_eq!(ctor(missing).0, 1, "Error expected");
170
171 for v in [listed, missing, p, np] {
172 drop_value(ctx, v);
173 }
174 assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0);
175 UNIT
176 }
177 }
178
179 #[test]
180 fn list_dir_lists_and_errors() {
181 // SAFETY: the test actor follows the generated-code convention.
182 assert_eq!(unsafe { crate::sched::run_test_actor(lists_dir) }, 0);
183 }
184}