1use std::cell::RefCell;
5use std::collections::BTreeMap;
6use std::io;
7use std::path::{Path, PathBuf};
8use std::rc::Rc;
9
10use waft_embedder::{
11 File, FileKind, FileMetadataFuture, FileOperationFuture, FileReadFuture, FileSizeFuture,
12 FileWriteFuture, Files, ListFilesFuture, ListedEntry, Metadata, OpenFileFuture, OpenMode,
13 ReadFileFuture, WriteFileFuture,
14};
15
16#[derive(Clone, Default)]
18pub struct MemoryFiles(Rc<RefCell<Tree>>);
19
20#[derive(Default)]
21struct Tree {
22 entries: BTreeMap<PathBuf, Entry>,
23}
24
25struct Entry {
26 kind: FileKind,
27 bytes: Vec<u8>,
28}
29
30impl MemoryFiles {
31 pub fn new() -> MemoryFiles {
33 let files = MemoryFiles::default();
34 files.0.borrow_mut().entries.insert(
35 PathBuf::from("/"),
36 Entry {
37 kind: FileKind::Folder,
38 bytes: Vec::new(),
39 },
40 );
41 files
42 }
43
44 pub fn with_file(self, path: impl Into<PathBuf>, bytes: impl Into<Vec<u8>>) -> MemoryFiles {
46 self.put_file(path.into(), bytes.into());
47 self
48 }
49
50 pub fn with_folder(self, path: impl Into<PathBuf>) -> MemoryFiles {
52 self.make_folder(&path.into());
53 self
54 }
55
56 pub fn file(&self, path: impl AsRef<Path>) -> Option<Vec<u8>> {
58 let tree = self.0.borrow();
59 let entry = tree.entries.get(path.as_ref())?;
60 (entry.kind == FileKind::File).then(|| entry.bytes.clone())
61 }
62
63 pub fn kind(&self, path: impl AsRef<Path>) -> Option<FileKind> {
65 self.0
66 .borrow()
67 .entries
68 .get(path.as_ref())
69 .map(|entry| entry.kind)
70 }
71
72 pub fn set_file(&self, path: impl Into<PathBuf>, bytes: impl Into<Vec<u8>>) {
74 self.put_file(path.into(), bytes.into());
75 }
76
77 fn put_file(&self, path: PathBuf, bytes: Vec<u8>) {
78 self.make_parents(&path);
79 self.0.borrow_mut().entries.insert(
80 path,
81 Entry {
82 kind: FileKind::File,
83 bytes,
84 },
85 );
86 }
87
88 fn make_folder(&self, path: &Path) {
89 self.make_parents(path);
90 self.0.borrow_mut().entries.insert(
91 path.to_owned(),
92 Entry {
93 kind: FileKind::Folder,
94 bytes: Vec::new(),
95 },
96 );
97 }
98
99 fn make_parents(&self, path: &Path) {
100 let mut tree = self.0.borrow_mut();
101 for parent in path.ancestors().skip(1) {
102 if parent.as_os_str().is_empty() {
103 continue;
104 }
105 tree.entries.entry(parent.to_owned()).or_insert(Entry {
106 kind: FileKind::Folder,
107 bytes: Vec::new(),
108 });
109 }
110 }
111
112 fn bytes(&self, path: &Path) -> io::Result<Vec<u8>> {
113 let tree = self.0.borrow();
114 match tree.entries.get(path) {
115 Some(entry) if entry.kind == FileKind::File => Ok(entry.bytes.clone()),
116 Some(_) => Err(io::Error::new(
117 io::ErrorKind::IsADirectory,
118 "it is a folder",
119 )),
120 None => Err(not_found(path)),
121 }
122 }
123}
124
125fn not_found(path: &Path) -> io::Error {
126 io::Error::new(
127 io::ErrorKind::NotFound,
128 format!("{} does not exist", path.display()),
129 )
130}
131
132impl Files for MemoryFiles {
133 fn read(&self, path: &Path) -> ReadFileFuture {
134 let bytes = self.bytes(path);
135 Box::pin(std::future::ready(bytes))
136 }
137
138 fn write(&self, path: &Path, bytes: &[u8]) -> WriteFileFuture {
139 self.put_file(path.to_owned(), bytes.to_vec());
140 Box::pin(std::future::ready(Ok(())))
141 }
142
143 fn open(&self, path: &Path, mode: OpenMode) -> OpenFileFuture {
144 let mut tree = self.0.borrow_mut();
145 let exists = tree
146 .entries
147 .get(path)
148 .is_some_and(|entry| entry.kind == FileKind::File);
149 if !exists && !mode.writable() {
150 return Box::pin(std::future::ready(Err(not_found(path))));
151 }
152 if !exists {
153 drop(tree);
154 self.make_parents(path);
155 tree = self.0.borrow_mut();
156 tree.entries.insert(
157 path.to_owned(),
158 Entry {
159 kind: FileKind::File,
160 bytes: Vec::new(),
161 },
162 );
163 }
164 if mode.truncates() {
165 tree.entries.get_mut(path).unwrap().bytes.clear();
166 }
167 let cursor = if mode.appends() {
168 tree.entries.get(path).unwrap().bytes.len() as u64
169 } else {
170 0
171 };
172 drop(tree);
173 let file = MemoryFile {
174 tree: Rc::clone(&self.0),
175 path: path.to_owned(),
176 mode,
177 cursor,
178 };
179 Box::pin(std::future::ready(Ok(Box::new(file) as Box<dyn File>)))
180 }
181
182 fn metadata(&self, path: &Path) -> FileMetadataFuture {
183 let tree = self.0.borrow();
184 let metadata = tree.entries.get(path).map(|entry| Metadata {
185 kind: entry.kind,
186 size: entry.bytes.len() as u64,
187 modified: None,
188 });
189 Box::pin(std::future::ready(metadata.ok_or_else(|| not_found(path))))
190 }
191
192 fn list(&self, path: &Path) -> ListFilesFuture {
193 let tree = self.0.borrow();
194 match tree.entries.get(path) {
195 None => return Box::pin(std::future::ready(Err(not_found(path)))),
196 Some(entry) if entry.kind != FileKind::Folder => {
197 return Box::pin(std::future::ready(Err(io::Error::new(
198 io::ErrorKind::NotADirectory,
199 "it is not a folder",
200 ))));
201 }
202 Some(_) => {}
203 }
204 let mut listed: Vec<ListedEntry> = tree
205 .entries
206 .iter()
207 .filter(|(entry_path, _)| entry_path.parent() == Some(path))
208 .map(|(entry_path, entry)| ListedEntry {
209 path: entry_path.clone(),
210 name: entry_path
211 .file_name()
212 .map(|name| name.to_string_lossy().into_owned())
213 .unwrap_or_default(),
214 kind: entry.kind,
215 })
216 .collect();
217 listed.sort_by(|left, right| left.name.cmp(&right.name));
218 Box::pin(std::future::ready(Ok(listed)))
219 }
220
221 fn create_folder(&self, path: &Path) -> FileOperationFuture {
222 let tree = self.0.borrow();
223 match tree.entries.get(path) {
224 Some(entry) if entry.kind != FileKind::Folder => {
225 return Box::pin(std::future::ready(Err(io::Error::new(
226 io::ErrorKind::AlreadyExists,
227 "a file is there",
228 ))));
229 }
230 Some(_) => return Box::pin(std::future::ready(Ok(()))),
231 None => {}
232 }
233 drop(tree);
234 self.make_folder(path);
235 Box::pin(std::future::ready(Ok(())))
236 }
237
238 fn rename(&self, from: &Path, to: &Path) -> FileOperationFuture {
239 let mut tree = self.0.borrow_mut();
240 if !tree.entries.contains_key(from) {
241 return Box::pin(std::future::ready(Err(not_found(from))));
242 }
243 let moved: Vec<(PathBuf, PathBuf)> = tree
244 .entries
245 .keys()
246 .filter(|entry_path| entry_path.starts_with(from))
247 .map(|entry_path| {
248 let rest = entry_path.strip_prefix(from).expect("a path under `from`");
249 (entry_path.clone(), to.join(rest))
250 })
251 .collect();
252 for (old, new) in moved {
253 let entry = tree.entries.remove(&old).expect("the entry just seen");
254 tree.entries.insert(new, entry);
255 }
256 Box::pin(std::future::ready(Ok(())))
257 }
258
259 fn delete(&self, path: &Path) -> FileOperationFuture {
260 let mut tree = self.0.borrow_mut();
261 if !tree.entries.contains_key(path) {
262 return Box::pin(std::future::ready(Err(not_found(path))));
263 }
264 tree.entries
265 .retain(|entry, _| entry.as_path() != path && !entry.starts_with(path));
266 Box::pin(std::future::ready(Ok(())))
267 }
268}
269
270struct MemoryFile {
272 tree: Rc<RefCell<Tree>>,
273 path: PathBuf,
274 mode: OpenMode,
275 cursor: u64,
276}
277
278impl MemoryFile {
279 fn bytes(&self) -> Vec<u8> {
280 self.tree
281 .borrow()
282 .entries
283 .get(&self.path)
284 .map(|entry| entry.bytes.clone())
285 .unwrap_or_default()
286 }
287
288 fn update(&mut self, f: impl FnOnce(&mut Vec<u8>)) {
289 if let Some(entry) = self.tree.borrow_mut().entries.get_mut(&self.path) {
290 f(&mut entry.bytes);
291 }
292 }
293}
294
295fn refused(mode: OpenMode, reading: bool) -> io::Result<()> {
296 if (reading && !mode.readable()) || (!reading && !mode.writable()) {
297 return Err(io::Error::new(
298 io::ErrorKind::PermissionDenied,
299 "the file was opened for the other use",
300 ));
301 }
302 Ok(())
303}
304
305impl File for MemoryFile {
306 fn size(&self) -> FileSizeFuture {
307 let size = self.bytes().len() as u64;
308 Box::pin(std::future::ready(Ok(size)))
309 }
310
311 fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> FileReadFuture<'a> {
312 if let Err(error) = refused(self.mode, true) {
313 return Box::pin(std::future::ready(Err(error)));
314 }
315 let bytes = self.bytes();
316 let start = usize::try_from(self.cursor)
317 .unwrap_or(usize::MAX)
318 .min(bytes.len());
319 let read = (bytes.len() - start).min(buf.len());
320 buf[..read].copy_from_slice(&bytes[start..start + read]);
321 self.cursor += read as u64;
322 Box::pin(std::future::ready(Ok(read)))
323 }
324
325 fn read_at<'a>(&'a self, offset: u64, buf: &'a mut [u8]) -> FileReadFuture<'a> {
326 if let Err(error) = refused(self.mode, true) {
327 return Box::pin(std::future::ready(Err(error)));
328 }
329 let bytes = self.bytes();
330 let start = usize::try_from(offset)
331 .unwrap_or(usize::MAX)
332 .min(bytes.len());
333 let read = (bytes.len() - start).min(buf.len());
334 buf[..read].copy_from_slice(&bytes[start..start + read]);
335 Box::pin(std::future::ready(Ok(read)))
336 }
337
338 fn write<'a>(&'a mut self, bytes: &'a [u8]) -> FileWriteFuture<'a> {
339 if let Err(error) = refused(self.mode, false) {
340 return Box::pin(std::future::ready(Err(error)));
341 }
342 let at = self.cursor;
343 self.update(|whole| write_at(whole, at, bytes));
344 self.cursor = at + bytes.len() as u64;
345 Box::pin(std::future::ready(Ok(())))
346 }
347
348 fn write_at<'a>(&'a mut self, offset: u64, bytes: &'a [u8]) -> FileWriteFuture<'a> {
349 if let Err(error) = refused(self.mode, false) {
350 return Box::pin(std::future::ready(Err(error)));
351 }
352 self.update(|whole| write_at(whole, offset, bytes));
353 Box::pin(std::future::ready(Ok(())))
354 }
355
356 fn set_len(&mut self, len: u64) -> FileWriteFuture<'_> {
357 if let Err(error) = refused(self.mode, false) {
358 return Box::pin(std::future::ready(Err(error)));
359 }
360 let len = usize::try_from(len).unwrap_or(usize::MAX);
361 self.update(|whole| whole.resize(len, 0));
362 Box::pin(std::future::ready(Ok(())))
363 }
364
365 fn flush(&mut self) -> FileWriteFuture<'_> {
366 Box::pin(std::future::ready(Ok(())))
367 }
368}
369
370fn write_at(whole: &mut Vec<u8>, offset: u64, bytes: &[u8]) {
371 let start = usize::try_from(offset).unwrap_or(usize::MAX);
372 let end = start.saturating_add(bytes.len());
373 if whole.len() < end {
374 whole.resize(end, 0);
375 }
376 whole[start..end].copy_from_slice(bytes);
377}
378
379#[cfg(test)]
380mod tests {
381 use super::*;
382 use std::future::Future;
383
384 fn now<T>(future: impl Future<Output = T>) -> T {
385 let mut future = std::pin::pin!(future);
386 let mut context = std::task::Context::from_waker(std::task::Waker::noop());
387 loop {
388 if let std::task::Poll::Ready(value) = future.as_mut().poll(&mut context) {
389 return value;
390 }
391 }
392 }
393
394 #[test]
395 fn a_file_written_is_read_whole_and_listed() {
396 let files = MemoryFiles::new().with_folder("/photos");
397 now(files.write(Path::new("/photos/a.png"), b"pixels")).unwrap();
398 assert_eq!(files.file("/photos/a.png").unwrap(), b"pixels");
399 assert_eq!(
400 now(files.read(Path::new("/photos/a.png"))).unwrap(),
401 b"pixels"
402 );
403 let listed = now(files.list(Path::new("/photos"))).unwrap();
404 assert_eq!(listed.len(), 1);
405 assert_eq!(listed[0].name, "a.png");
406 assert_eq!(
407 now(files.metadata(Path::new("/photos/a.png")))
408 .unwrap()
409 .size,
410 6
411 );
412 }
413
414 #[test]
415 fn an_opened_file_reads_and_writes_at_an_offset() {
416 let files = MemoryFiles::new().with_file("/a", b"12345");
417 let mut file = now(files.open(Path::new("/a"), OpenMode::Append)).unwrap();
418 let mut buf = [0u8; 2];
419 assert_eq!(now(file.read_at(2, &mut buf)).unwrap(), 2);
420 assert_eq!(&buf, b"34");
421 now(file.write_at(1, b"ab")).unwrap();
422 assert_eq!(files.file("/a").unwrap(), b"1ab45");
423 now(file.set_len(4)).unwrap();
424 assert_eq!(files.file("/a").unwrap(), b"1ab4");
425 }
426
427 #[test]
428 fn a_read_only_open_refuses_writes_and_a_missing_file_refuses_reading() {
429 let files = MemoryFiles::new().with_file("/a", b"x");
430 let mut file = now(files.open(Path::new("/a"), OpenMode::Read)).unwrap();
431 assert!(now(file.write(b"y")).is_err());
432 assert!(now(files.open(Path::new("/none"), OpenMode::Read)).is_err());
433 }
434
435 #[test]
436 fn a_folder_made_with_its_parents_is_listed() {
437 let files = MemoryFiles::new();
438 now(files.create_folder(Path::new("/photos/2026"))).unwrap();
439 assert_eq!(files.kind("/photos/2026"), Some(FileKind::Folder));
440 let listed = now(files.list(Path::new("/photos"))).unwrap();
441 assert_eq!(listed.len(), 1);
442 assert_eq!(listed[0].name, "2026");
443 assert_eq!(
444 now(files.metadata(Path::new("/photos/2026"))).unwrap().kind,
445 FileKind::Folder
446 );
447 now(files.create_folder(Path::new("/photos/2026"))).unwrap();
448 files.set_file("/photos/2026/a.png", b"x");
449 assert!(now(files.create_folder(Path::new("/photos/2026/a.png"))).is_err());
450 }
451
452 #[test]
453 fn a_folder_renamed_and_deleted_takes_what_is_in_it() {
454 let files = MemoryFiles::new()
455 .with_file("/one/a", b"a")
456 .with_file("/one/b", b"b");
457 now(files.rename(Path::new("/one"), Path::new("/two"))).unwrap();
458 assert_eq!(files.file("/two/a").unwrap(), b"a");
459 now(files.delete(Path::new("/two"))).unwrap();
460 assert_eq!(files.kind("/two"), None);
461 assert_eq!(files.kind("/two/a"), None);
462 }
463}