1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use super::*;
use crate::{FileType, FsError, Metadata, OpenOptionsConfig, Result, VirtualFile};
use std::io::{self, Seek};
use std::path::Path;

/// The type that is responsible to open a file.
#[derive(Debug, Clone)]
pub struct FileOpener {
    pub(super) filesystem: FileSystem,
}

impl crate::FileOpener for FileOpener {
    fn open(
        &mut self,
        path: &Path,
        conf: &OpenOptionsConfig,
    ) -> Result<Box<dyn VirtualFile + Send + Sync + 'static>> {
        let read = conf.read();
        let mut write = conf.write();
        let append = conf.append();
        let mut truncate = conf.truncate();
        let mut create = conf.create();
        let create_new = conf.create_new();

        // If `create_new` is used, `create` and `truncate ` are ignored.
        if create_new {
            create = false;
            truncate = false;
        }

        // To truncate a file, `write` must be used.
        if truncate && !write {
            return Err(FsError::PermissionDenied);
        }

        // `append` is semantically equivalent to `write` + `append`
        // but let's keep them exclusive.
        if append {
            write = false;
        }

        let (inode_of_parent, maybe_inode_of_file, name_of_file) = {
            // Read lock.
            let fs = self
                .filesystem
                .inner
                .try_read()
                .map_err(|_| FsError::Lock)?;

            // Check the path has a parent.
            let parent_of_path = path.parent().ok_or(FsError::BaseNotDirectory)?;

            // Check the file name.
            let name_of_file = path
                .file_name()
                .ok_or(FsError::InvalidInput)?
                .to_os_string();

            // Find the parent inode.
            let inode_of_parent = fs.inode_of_parent(parent_of_path)?;

            // Find the inode of the file if it exists.
            let maybe_inode_of_file = fs
                .as_parent_get_position_and_inode_of_file(inode_of_parent, &name_of_file)?
                .map(|(_nth, inode)| inode);

            (inode_of_parent, maybe_inode_of_file, name_of_file)
        };

        let inode_of_file = match maybe_inode_of_file {
            // The file already exists, and a _new_ one _must_ be
            // created; it's not OK.
            Some(_inode_of_file) if create_new => return Err(FsError::AlreadyExists),

            // The file already exists; it's OK.
            Some(inode_of_file) => {
                // Write lock.
                let mut fs = self
                    .filesystem
                    .inner
                    .try_write()
                    .map_err(|_| FsError::Lock)?;

                let inode = fs.storage.get_mut(inode_of_file);
                match inode {
                    Some(Node::File { metadata, file, .. }) => {
                        // Update the accessed time.
                        metadata.accessed = time();

                        // Truncate if needed.
                        if truncate {
                            file.truncate();
                            metadata.len = 0;
                        }

                        // Move the cursor to the end if needed.
                        if append {
                            file.seek(io::SeekFrom::End(0))?;
                        }
                        // Otherwise, move the cursor to the start.
                        else {
                            file.seek(io::SeekFrom::Start(0))?;
                        }
                    }

                    _ => return Err(FsError::NotAFile),
                }

                inode_of_file
            }

            // The file doesn't already exist; it's OK to create it if:
            // 1. `create_new` is used with `write` or `append`,
            // 2. `create` is used with `write` or `append`.
            None if (create_new || create) && (write || append) => {
                // Write lock.
                let mut fs = self
                    .filesystem
                    .inner
                    .try_write()
                    .map_err(|_| FsError::Lock)?;

                let file = File::new();

                // Creating the file in the storage.
                let inode_of_file = fs.storage.vacant_entry().key();
                let real_inode_of_file = fs.storage.insert(Node::File {
                    inode: inode_of_file,
                    name: name_of_file,
                    file,
                    metadata: {
                        let time = time();

                        Metadata {
                            ft: FileType {
                                file: true,
                                ..Default::default()
                            },
                            accessed: time,
                            created: time,
                            modified: time,
                            len: 0,
                        }
                    },
                });

                assert_eq!(
                    inode_of_file, real_inode_of_file,
                    "new file inode should have been correctly calculated",
                );

                // Adding the new directory to its parent.
                fs.add_child_to_node(inode_of_parent, inode_of_file)?;

                inode_of_file
            }

            None => return Err(FsError::PermissionDenied),
        };

        Ok(Box::new(FileHandle::new(
            inode_of_file,
            self.filesystem.clone(),
            read,
            write || append || truncate,
            append,
        )))
    }
}

#[cfg(test)]
mod test_file_opener {
    use crate::{mem_fs::*, FileSystem as FS, FsError};
    use std::io;

    macro_rules! path {
        ($path:expr) => {
            std::path::Path::new($path)
        };
    }

    #[test]
    fn test_create_new_file() {
        let fs = FileSystem::default();

        assert!(
            matches!(
                fs.new_open_options()
                    .write(true)
                    .create_new(true)
                    .open(path!("/foo.txt")),
                Ok(_),
            ),
            "creating a new file",
        );

        {
            let fs_inner = fs.inner.read().unwrap();

            assert_eq!(fs_inner.storage.len(), 2, "storage has the new file");
            assert!(
                matches!(
                    fs_inner.storage.get(ROOT_INODE),
                    Some(Node::Directory {
                        inode: ROOT_INODE,
                        name,
                        children,
                        ..
                    }) if name == "/" && children == &[1]
                ),
                "`/` contains `foo.txt`",
            );
            assert!(
                matches!(
                    fs_inner.storage.get(1),
                    Some(Node::File {
                        inode: 1,
                        name,
                        ..
                    }) if name == "foo.txt"
                ),
                "`foo.txt` exists and is a file",
            );
        }

        assert!(
            matches!(
                fs.new_open_options()
                    .write(true)
                    .create_new(true)
                    .open(path!("/foo.txt")),
                Err(FsError::AlreadyExists)
            ),
            "creating a new file that already exist",
        );

        assert!(
            matches!(
                fs.new_open_options()
                    .write(true)
                    .create_new(true)
                    .open(path!("/foo/bar.txt")),
                Err(FsError::NotAFile),
            ),
            "creating a file in a directory that doesn't exist",
        );

        assert_eq!(fs.remove_file(path!("/foo.txt")), Ok(()), "removing a file");

        assert!(
            matches!(
                fs.new_open_options()
                    .write(false)
                    .create_new(true)
                    .open(path!("/foo.txt")),
                Err(FsError::PermissionDenied),
            ),
            "creating a file without the `write` option",
        );
    }

    #[test]
    fn test_truncate_a_read_only_file() {
        let fs = FileSystem::default();

        assert!(
            matches!(
                fs.new_open_options()
                    .write(false)
                    .truncate(true)
                    .open(path!("/foo.txt")),
                Err(FsError::PermissionDenied),
            ),
            "truncating a read-only file",
        );
    }

    #[test]
    fn test_truncate() {
        let fs = FileSystem::default();

        let mut file = fs
            .new_open_options()
            .write(true)
            .create_new(true)
            .open(path!("/foo.txt"))
            .expect("failed to create a new file");

        assert!(
            matches!(file.write(b"foobar"), Ok(6)),
            "writing `foobar` at the end of the file",
        );

        assert!(
            matches!(file.seek(io::SeekFrom::Current(0)), Ok(6)),
            "checking the current position is 6",
        );
        assert!(
            matches!(file.seek(io::SeekFrom::End(0)), Ok(6)),
            "checking the size is 6",
        );

        let mut file = fs
            .new_open_options()
            .write(true)
            .truncate(true)
            .open(path!("/foo.txt"))
            .expect("failed to open + truncate `foo.txt`");

        assert!(
            matches!(file.seek(io::SeekFrom::Current(0)), Ok(0)),
            "checking the current position is 0",
        );
        assert!(
            matches!(file.seek(io::SeekFrom::End(0)), Ok(0)),
            "checking the size is 0",
        );
    }

    #[test]
    fn test_append() {
        let fs = FileSystem::default();

        let mut file = fs
            .new_open_options()
            .write(true)
            .create_new(true)
            .open(path!("/foo.txt"))
            .expect("failed to create a new file");

        assert!(
            matches!(file.write(b"foobar"), Ok(6)),
            "writing `foobar` at the end of the file",
        );

        assert!(
            matches!(file.seek(io::SeekFrom::Current(0)), Ok(6)),
            "checking the current position is 6",
        );
        assert!(
            matches!(file.seek(io::SeekFrom::End(0)), Ok(6)),
            "checking the size is 6",
        );

        let mut file = fs
            .new_open_options()
            .append(true)
            .open(path!("/foo.txt"))
            .expect("failed to open `foo.txt`");

        assert!(
            matches!(file.seek(io::SeekFrom::Current(0)), Ok(0)),
            "checking the current position in append-mode is 0",
        );
        assert!(
            matches!(file.seek(io::SeekFrom::Start(0)), Ok(0)),
            "trying to rewind in append-mode",
        );
        assert!(matches!(file.write(b"baz"), Ok(3)), "writing `baz`");

        let mut file = fs
            .new_open_options()
            .read(true)
            .open(path!("/foo.txt"))
            .expect("failed to open `foo.txt");

        assert!(
            matches!(file.seek(io::SeekFrom::Current(0)), Ok(0)),
            "checking the current position is read-mode is 0",
        );

        let mut string = String::new();
        assert!(
            matches!(file.read_to_string(&mut string), Ok(9)),
            "reading the entire `foo.txt` file",
        );
        assert_eq!(
            string, "foobarbaz",
            "checking append-mode is ignoring seek operations",
        );
    }

    #[test]
    fn test_opening_a_file_that_already_exists() {
        let fs = FileSystem::default();

        assert!(
            matches!(
                fs.new_open_options()
                    .write(true)
                    .create_new(true)
                    .open(path!("/foo.txt")),
                Ok(_),
            ),
            "creating a _new_ file",
        );

        assert!(
            matches!(
                fs.new_open_options()
                    .create_new(true)
                    .open(path!("/foo.txt")),
                Err(FsError::AlreadyExists),
            ),
            "creating a _new_ file that already exists",
        );

        assert!(
            matches!(
                fs.new_open_options().read(true).open(path!("/foo.txt")),
                Ok(_),
            ),
            "opening a file that already exists",
        );
    }
}