waft_embedder/files.rs
1//! A host's file system: a path read whole, written whole, opened to read and write at an
2//! offset and streamed, its metadata, a folder listed, and paths renamed and deleted. The shape
3//! is dart:io's `File` and `RandomAccessFile`, with Rust names: a path names a file here, and an
4//! opened one is a [`File`] the app reads through a future, as a picked file's handle is read.
5//!
6//! A platform answers [`Platform::files`](crate::Platform::files) with its file system, or `None`
7//! where it has none, as a web page has none and a WebAssembly component has the one its host
8//! grants. Apple's hosts run `std` on their own threads; a platform whose system has asynchronous
9//! file IO awaits the system's.
10
11use std::future::Future;
12use std::io;
13use std::path::{Path, PathBuf};
14use std::pin::Pin;
15
16pub use crate::file_dialogs::{FileReadFuture, FileSizeFuture, FileWriteFuture};
17
18/// The host's file system.
19pub trait Files {
20 /// The whole file at `path`, as Flutter's `XFile.readAsBytes` reads it.
21 fn read(&self, path: &Path) -> ReadFileFuture;
22
23 /// Writes `bytes` as the whole file at `path`, making it or replacing it.
24 fn write(&self, path: &Path, bytes: &[u8]) -> WriteFileFuture;
25
26 /// Opens `path` as `mode` says; the file reads and writes at an offset and streams.
27 fn open(&self, path: &Path, mode: OpenMode) -> OpenFileFuture;
28
29 /// What the file or folder at `path` is.
30 fn metadata(&self, path: &Path) -> FileMetadataFuture;
31
32 /// What is in the folder at `path`, in no particular order.
33 fn list(&self, path: &Path) -> ListFilesFuture;
34
35 /// Makes an empty folder at `path`, and the folders above it where they are missing, as
36 /// Dart's `Directory.create(recursive: true)` does. A folder already there is left as it is.
37 fn create_folder(&self, path: &Path) -> FileOperationFuture;
38
39 /// Renames `from` to `to`, which may be in another folder.
40 fn rename(&self, from: &Path, to: &Path) -> FileOperationFuture;
41
42 /// Deletes the file or folder at `path`. A folder is deleted with what is in it, as Dart's
43 /// `Directory.delete(recursive: true)` on macOS and Linux does; a system that refuses a
44 /// non-empty folder answers that refusal.
45 fn delete(&self, path: &Path) -> FileOperationFuture;
46}
47
48/// A file opened through [`Files::open`], read and written at an offset and streamed.
49///
50/// The cursor methods advance where the file reads and writes next; the offset methods leave it
51/// alone. A platform whose file system has no cursor of its own keeps one here.
52pub trait File {
53 /// The file's length in bytes.
54 fn size(&self) -> FileSizeFuture;
55
56 /// Reads into `buf` from the cursor, advancing it by what it read; answers how many bytes,
57 /// `0` at the end.
58 fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> FileReadFuture<'a>;
59
60 /// Reads into `buf` from `offset`, leaving the cursor alone.
61 fn read_at<'a>(&'a self, offset: u64, buf: &'a mut [u8]) -> FileReadFuture<'a>;
62
63 /// Writes `bytes` at the cursor, advancing it by their length.
64 fn write<'a>(&'a mut self, bytes: &'a [u8]) -> FileWriteFuture<'a>;
65
66 /// Writes `bytes` at `offset`, leaving the cursor alone.
67 fn write_at<'a>(&'a mut self, offset: u64, bytes: &'a [u8]) -> FileWriteFuture<'a>;
68
69 /// Cuts the file short at `len`, or fills it with zeroes to that length.
70 fn set_len(&mut self, len: u64) -> FileWriteFuture<'_>;
71
72 /// Hands what was written to the system, so that it survives the process that wrote it.
73 fn flush(&mut self) -> FileWriteFuture<'_>;
74}
75
76/// Dart `FileMode`: what an opened file may do, and where it starts.
77#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
78pub enum OpenMode {
79 /// Read only.
80 #[default]
81 Read,
82 /// Read and write, cut short at the start.
83 Write,
84 /// Read and write, starting at the end.
85 Append,
86 /// Write only, cut short at the start.
87 WriteOnly,
88 /// Write only, starting at the end.
89 WriteOnlyAppend,
90}
91
92impl OpenMode {
93 /// Whether the file may be read.
94 pub fn readable(self) -> bool {
95 matches!(self, OpenMode::Read | OpenMode::Write | OpenMode::Append)
96 }
97
98 /// Whether the file may be written.
99 pub fn writable(self) -> bool {
100 !matches!(self, OpenMode::Read)
101 }
102
103 /// Whether the file starts at its end, so that the first write appends.
104 pub fn appends(self) -> bool {
105 matches!(self, OpenMode::Append | OpenMode::WriteOnlyAppend)
106 }
107
108 /// Whether opening cuts the file short.
109 pub fn truncates(self) -> bool {
110 matches!(self, OpenMode::Write | OpenMode::WriteOnly)
111 }
112}
113
114/// What a path is.
115#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
116pub enum FileKind {
117 /// A file.
118 File,
119 /// A folder.
120 Folder,
121 /// A symbolic link, which a listing reports as itself where the system does.
122 Link,
123 /// A device, a socket, a pipe, or something else this interface does not name.
124 Other,
125}
126
127/// What the file or folder at a path is, as Dart's `FileStat`.
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129pub struct Metadata {
130 /// A file, a folder, a link or something else.
131 pub kind: FileKind,
132 /// The file's length in bytes; zero for a folder or a link.
133 pub size: u64,
134 /// When the system last changed it, where the system says.
135 pub modified: Option<std::time::SystemTime>,
136}
137
138/// One thing in a folder, as Dart's `FileSystemEntity`.
139#[derive(Clone, Debug, PartialEq, Eq)]
140pub struct ListedEntry {
141 /// The entry's full path, as the folder's was given, joined with its name.
142 pub path: PathBuf,
143 /// The entry's name alone.
144 pub name: String,
145 /// A file, a folder, a link or something else.
146 pub kind: FileKind,
147}
148
149/// A whole file read.
150pub type ReadFileFuture = Pin<Box<dyn Future<Output = io::Result<Vec<u8>>>>>;
151
152/// A whole file written.
153pub type WriteFileFuture = Pin<Box<dyn Future<Output = io::Result<()>>>>;
154
155/// A file opened.
156pub type OpenFileFuture = Pin<Box<dyn Future<Output = io::Result<Box<dyn File>>>>>;
157
158/// What a path is.
159pub type FileMetadataFuture = Pin<Box<dyn Future<Output = io::Result<Metadata>>>>;
160
161/// What a folder holds.
162pub type ListFilesFuture = Pin<Box<dyn Future<Output = io::Result<Vec<ListedEntry>>>>>;
163
164/// A rename or a delete.
165pub type FileOperationFuture = Pin<Box<dyn Future<Output = io::Result<()>>>>;
166
167#[cfg(test)]
168mod tests {
169 use super::*;
170
171 #[test]
172 fn a_mode_says_what_an_opened_file_may_do() {
173 assert!(OpenMode::Read.readable());
174 assert!(!OpenMode::Read.writable());
175 assert!(!OpenMode::Read.truncates());
176 assert!(OpenMode::Write.readable());
177 assert!(OpenMode::Write.writable());
178 assert!(OpenMode::Write.truncates());
179 assert!(!OpenMode::Write.appends());
180 assert!(OpenMode::Append.appends());
181 assert!(!OpenMode::Append.truncates());
182 assert!(!OpenMode::WriteOnly.readable());
183 assert!(OpenMode::WriteOnlyAppend.appends());
184 assert_eq!(OpenMode::default(), OpenMode::Read);
185 }
186
187 #[test]
188 fn metadata_of_a_file_names_it() {
189 let metadata = Metadata {
190 kind: FileKind::File,
191 size: 12,
192 modified: None,
193 };
194 assert_eq!(metadata.kind, FileKind::File);
195 assert_eq!(metadata.size, 12);
196 }
197}