sos-vfs 0.3.2

Virtual file system same as tokio::fs.
Documentation
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
//! File system backed by in-memory buffers.
use super::{File, Metadata, Permissions};
use async_recursion::async_recursion;
use bitflags::bitflags;
use parking_lot::Mutex as SyncMutex;
use std::{
    collections::BTreeMap,
    ffi::{OsStr, OsString},
    fmt,
    io::{self, Cursor, Error, ErrorKind, Result},
    iter::Enumerate,
    path::MAIN_SEPARATOR,
    path::{Component, Path, PathBuf},
    sync::{Arc, LazyLock},
    vec::IntoIter,
};
use tokio::{
    io::{AsyncReadExt, AsyncWriteExt},
    sync::{Mutex, RwLock},
};

#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
use super::meta_data::FileTime;

bitflags! {
    /// Bit flags for a file descriptor.
    #[derive(Default, Debug, Copy, Clone, Eq, PartialEq)]
    pub(crate) struct FileFlags: u8 {
        /// Descriptor is a directory.
        const DIR               =        0b00000001;
        /// Descriptor is a file.
        const FILE              =        0b00000010;
        /// Descriptor is a symbolic link.
        const SYM_LINK          =        0b00000100;
    }
}

type FileSystem = BTreeMap<OsString, Fd>;
pub(super) type Fd = Arc<RwLock<MemoryFd>>;
pub(super) type FileContent = Arc<SyncMutex<Cursor<Vec<u8>>>>;
pub(super) type RootDir = Arc<RwLock<MemoryDir>>;

// File system contents.
static ROOT_DIR: LazyLock<RootDir> =
    LazyLock::new(|| Arc::new(RwLock::new(MemoryDir::new_root())));

// Lock for when we need to modify the file system by adding
// or removing paths.
static FS_LOCK: LazyLock<tokio::sync::Mutex<()>> =
    LazyLock::new(|| tokio::sync::Mutex::new(()));

/*
#[cfg(debug_assertions)]
/// Debug the root of the file system.
pub(super) fn debug_root() {
    eprintln!("{:#?}", root_fs());
}
*/

pub(super) fn root_fs() -> RootDir {
    Arc::clone(&ROOT_DIR)
}

/// Result of a path lookup.
pub(super) enum PathTarget {
    Root(RootDir),
    Descriptor(Fd),
}

impl From<Parent> for PathTarget {
    fn from(value: Parent) -> Self {
        match value {
            Parent::Root(fs) => PathTarget::Root(fs),
            Parent::Folder(fd) => PathTarget::Descriptor(fd),
        }
    }
}

/// Parent reference for a file descriptor.
#[derive(Debug)]
pub(super) enum Parent {
    Root(RootDir),
    Folder(Fd),
}

impl Clone for Parent {
    fn clone(&self) -> Self {
        match self {
            Self::Root(root) => Self::Root(Arc::clone(root)),
            Self::Folder(fd) => Self::Folder(Arc::clone(fd)),
        }
    }
}

impl Parent {
    /// Get the name of this parent.
    pub async fn name(&self) -> OsString {
        match self {
            Self::Root(fs) => {
                let fs = fs.read().await;
                fs.name.clone()
            }
            Self::Folder(fd) => {
                let fd = fd.read().await;
                fd.name().clone()
            }
        }
    }

    /// Create a directory in this parent.
    pub async fn mkdir(&mut self, name: OsString) -> Result<Fd> {
        let fd = MemoryFd::Dir(MemoryDir::new_parent(
            name.clone(),
            Some(self.clone()),
        ));
        let dir = Arc::new(RwLock::new(fd));
        self.insert(name, Arc::clone(&dir)).await?;
        Ok(dir)
    }

    /// Remove a child file or directory.
    pub async fn unlink(
        &mut self,
        path: impl AsRef<Path>,
    ) -> Result<Option<Fd>> {
        match self {
            Self::Root(fs) => {
                let mut fs = fs.write().await;
                Ok(fs.remove(path).await)
            }
            Self::Folder(fd) => {
                let mut fd = fd.write().await;
                match &mut *fd {
                    MemoryFd::Dir(dir) => Ok(dir.remove(path).await),
                    _ => Err(ErrorKind::PermissionDenied.into()),
                }
            }
        }
    }

    /// Insert a child node into this parent.
    ///
    /// If a child already exists with the same name it is replaced.
    pub async fn insert(&mut self, name: OsString, child: Fd) -> Result<()> {
        match self {
            Self::Root(fs) => {
                let mut fs = fs.write().await;
                fs.insert(name, child).await;
                Ok(())
            }
            Self::Folder(fd) => {
                let mut fd = fd.write().await;
                match &mut *fd {
                    MemoryFd::Dir(dir) => {
                        dir.insert(name, child).await;
                        Ok(())
                    }
                    _ => Err(ErrorKind::PermissionDenied.into()),
                }
            }
        }
    }

    /// Find a child that is a directory.
    async fn find_dir(&self, name: &OsStr) -> Option<Fd> {
        match self {
            Self::Root(fs) => {
                let fs = fs.read().await;
                fs.find_dir(name).await
            }
            Self::Folder(fd) => {
                let mut fd = fd.write().await;
                match &mut *fd {
                    MemoryFd::Dir(dir) => dir.find_dir(name).await,
                    _ => None,
                }
            }
        }
    }
}

/// Directory file descriptor.
#[derive(Default)]
pub(super) struct MemoryDir {
    name: OsString,
    parent: Option<Parent>,
    permissions: Permissions,
    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
    time: FileTime,
    files: FileSystem,
}

impl fmt::Debug for MemoryDir {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MemoryDir")
            .field("name", &self.name)
            .field("permissions", &self.permissions)
            .field("files", &self.files)
            .finish()
    }
}

impl MemoryDir {
    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
    fn new_root() -> Self {
        Self {
            name: OsString::from(MAIN_SEPARATOR.to_string()),
            parent: None,
            permissions: Default::default(),
            time: Default::default(),
            files: Default::default(),
        }
    }

    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
    fn new_root() -> Self {
        Self {
            name: OsString::from(MAIN_SEPARATOR.to_string()),
            parent: None,
            permissions: Default::default(),
            files: Default::default(),
        }
    }

    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
    pub(super) fn new_parent(name: OsString, parent: Option<Parent>) -> Self {
        Self {
            name,
            parent,
            permissions: Default::default(),
            time: Default::default(),
            files: Default::default(),
        }
    }

    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
    pub(super) fn new_parent(name: OsString, parent: Option<Parent>) -> Self {
        Self {
            name,
            parent,
            permissions: Default::default(),
            files: Default::default(),
        }
    }

    /// Files in this directory.
    pub fn files(&self) -> &FileSystem {
        &self.files
    }

    /// Remove a child file or directory.
    pub async fn remove(&mut self, path: impl AsRef<Path>) -> Option<Fd> {
        let _ = FS_LOCK.lock().await;
        if let Some(name) = path.as_ref().file_name() {
            self.files.remove(name)
        } else {
            None
        }
    }

    /// Insert a child node into this directory.
    pub async fn insert(&mut self, name: OsString, fd: Fd) {
        let _ = FS_LOCK.lock().await;
        self.files.insert(name, fd);
    }

    /// Find a child that is a dir.
    pub async fn find_dir(&self, name: &OsStr) -> Option<Fd> {
        if let Some(child) = self.files.get(name) {
            let is_dir = {
                let fd = child.read().await;
                matches!(&*fd, MemoryFd::Dir(_))
            };
            if is_dir {
                Some(Arc::clone(child))
            } else {
                None
            }
        } else {
            None
        }
    }
}

/// File content.
pub(super) struct MemoryFile {
    name: OsString,
    parent: Option<Parent>,
    permissions: Permissions,
    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
    time: FileTime,
    pub(super) contents: FileContent,
}

impl fmt::Debug for MemoryFile {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MemoryFile")
            .field("name", &self.name)
            .field("permissions", &self.permissions)
            .field("contents", &self.contents)
            .finish()
    }
}

impl MemoryFile {
    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
    fn new(name: OsString, parent: Option<Parent>) -> Self {
        Self {
            name,
            parent,
            permissions: Default::default(),
            time: Default::default(),
            contents: Arc::new(SyncMutex::new(Cursor::new(Vec::new()))),
        }
    }

    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
    fn new(name: OsString, parent: Option<Parent>) -> Self {
        Self {
            name,
            parent,
            permissions: Default::default(),
            contents: Arc::new(SyncMutex::new(Cursor::new(Vec::new()))),
        }
    }

    pub fn truncate(&self) {
        let mut lock = self.contents.lock();
        *lock = Cursor::new(Vec::new());
    }

    pub fn contents(&self) -> FileContent {
        Arc::clone(&self.contents)
    }
}

/// File descriptor.
#[derive(Debug)]
pub(super) enum MemoryFd {
    /// File variant.
    File(MemoryFile),
    /// Directory variant.
    Dir(MemoryDir),
}

impl MemoryFd {
    pub fn parent(&self) -> Option<&Parent> {
        match self {
            Self::File(fd) => fd.parent.as_ref(),
            Self::Dir(fd) => fd.parent.as_ref(),
        }
    }

    pub fn parent_mut(&mut self) -> Option<&mut Parent> {
        match self {
            Self::File(fd) => fd.parent.as_mut(),
            Self::Dir(fd) => fd.parent.as_mut(),
        }
    }

    pub fn name(&self) -> &OsString {
        match self {
            Self::File(fd) => &fd.name,
            Self::Dir(fd) => &fd.name,
        }
    }

    pub fn set_name(&mut self, name: OsString) {
        match self {
            Self::File(fd) => fd.name = name,
            Self::Dir(fd) => fd.name = name,
        }
    }

    pub async fn path(&self) -> PathBuf {
        let mut parent = self.parent().cloned();
        let mut components = vec![self.name().clone()];
        while let Some(fd) = parent {
            let name = fd.name().await;
            components.push(name);
            parent = match fd {
                Parent::Root(_) => None,
                Parent::Folder(fd) => {
                    let fd = fd.read().await;
                    fd.parent().cloned()
                }
            };
        }
        components.reverse();
        let mut path = PathBuf::new();
        for part in components {
            path = path.join(part);
        }
        path
    }

    pub fn flags(&self) -> FileFlags {
        match self {
            Self::File(_) => FileFlags::FILE,
            Self::Dir(_) => FileFlags::DIR,
        }
    }

    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
    pub(crate) fn time(&self) -> &FileTime {
        match self {
            Self::File(fd) => &fd.time,
            Self::Dir(fd) => &fd.time,
        }
    }

    pub fn set_permissions(&mut self, perm: Permissions) {
        match self {
            Self::File(fd) => fd.permissions = perm,
            Self::Dir(fd) => fd.permissions = perm,
        }
    }

    pub fn permissions(&self) -> &Permissions {
        match self {
            Self::File(fd) => &fd.permissions,
            Self::Dir(fd) => &fd.permissions,
        }
    }
}

/// Copies the contents of one file to another.
pub async fn copy(
    from: impl AsRef<Path>,
    to: impl AsRef<Path>,
) -> Result<()> {
    // Copy the buffer and permissions to file descriptor.
    async fn copy_fd(
        fd: Fd,
        buffer: Vec<u8>,
        permissions: Permissions,
    ) -> Result<()> {
        let mut fd = fd.write().await;
        match &mut *fd {
            MemoryFd::File(file) => {
                let mut contents = file.contents.lock();
                let buf = contents.get_mut();
                *buf = buffer;
                file.permissions = permissions;
                Ok(())
            }
            _ => Err(ErrorKind::PermissionDenied.into()),
        }
    }

    // From file must exist.
    if let Some(target) = resolve(from.as_ref()).await {
        match target {
            PathTarget::Descriptor(fd) => {
                if from.as_ref() == to.as_ref() {
                    return Ok(());
                }

                let result: Option<(Vec<u8>, Permissions)> = {
                    let fd = fd.read().await;
                    match &*fd {
                        MemoryFd::File(file) => {
                            let permissions = file.permissions;
                            let contents = file.contents.lock();
                            let buffer = contents.get_ref().clone();
                            Some((buffer, permissions))
                        }
                        _ => None,
                    }
                };

                if let Some((buffer, permissions)) = result {
                    // File exists so overwrite it
                    if let Some(target) = resolve(to.as_ref()).await {
                        match target {
                            PathTarget::Descriptor(fd) => {
                                copy_fd(fd, buffer, permissions).await
                            }
                            PathTarget::Root(_) => {
                                Err(ErrorKind::PermissionDenied.into())
                            }
                        }
                    // Try to create in the parent
                    } else {
                        let fd = create_file(to, false).await?;
                        copy_fd(fd, buffer, permissions).await
                    }
                } else {
                    Err(ErrorKind::PermissionDenied.into())
                }
            }
            PathTarget::Root(_) => Err(ErrorKind::PermissionDenied.into()),
        }
    } else {
        Err(ErrorKind::NotFound.into())
    }
}

/// Creates a future that will open a file for writing
/// and write the entire contents to it.
pub async fn write(
    path: impl AsRef<Path>,
    contents: impl AsRef<[u8]>,
) -> Result<()> {
    let mut fd = File::create(&path).await?;
    fd.write_all(contents.as_ref()).await?;
    fd.flush().await?;
    Ok(())
}

/// Reads the entire contents of a file into a bytes vector.
pub async fn read(path: impl AsRef<Path>) -> Result<Vec<u8>> {
    let mut buffer = Vec::new();
    let mut fd = File::open(path.as_ref()).await?;
    fd.read_to_end(&mut buffer).await?;
    Ok(buffer)
}

/// Removes a file from the filesystem.
pub async fn remove_file(path: impl AsRef<Path>) -> Result<()> {
    let file = ensure_file(path.as_ref()).await?;
    let mut fd = file.write().await;
    if let Some(parent) = fd.parent_mut() {
        parent.unlink(path).await?;
        Ok(())
    } else {
        Err(ErrorKind::PermissionDenied.into())
    }
}

/// Removes an existing, empty directory.
pub async fn remove_dir(path: impl AsRef<Path>) -> Result<()> {
    let dir = ensure_dir(path.as_ref()).await?;
    let mut fd = dir.write().await;
    match &*fd {
        MemoryFd::Dir(dir) => {
            if dir.files().is_empty() {
                if let Some(parent) = fd.parent_mut() {
                    parent.unlink(path).await?;
                }
                Ok(())
            } else {
                Err(ErrorKind::PermissionDenied.into())
            }
        }
        _ => Err(ErrorKind::PermissionDenied.into()),
    }
}

/// Removes a directory at this path, after removing
/// all its contents. Use carefully!
pub async fn remove_dir_all(path: impl AsRef<Path>) -> Result<()> {
    let dir = ensure_dir(path.as_ref()).await?;
    let mut fd = dir.write().await;
    if let Some(parent) = fd.parent_mut() {
        parent.unlink(path).await?;
        Ok(())
    } else {
        Err(ErrorKind::PermissionDenied.into())
    }
}

/// Renames a file or directory to a new name, replacing
/// the original file if to already exists.
pub async fn rename(
    from: impl AsRef<Path>,
    to: impl AsRef<Path>,
) -> Result<()> {
    let file = resolve(from.as_ref()).await.ok_or_else(|| {
        let err: io::Error = ErrorKind::NotFound.into();
        err
    })?;

    let file = match file {
        PathTarget::Descriptor(fd) => fd,
        _ => return Err(ErrorKind::PermissionDenied.into()),
    };

    let mut fd = file.write().await;

    let from_name = from.as_ref().file_name().ok_or_else(|| {
        let err: io::Error = ErrorKind::PermissionDenied.into();
        err
    })?;

    let to_name = to.as_ref().file_name().ok_or_else(|| {
        let err: io::Error = ErrorKind::PermissionDenied.into();
        err
    })?;

    // Update the name first, while we have the write lock
    fd.set_name(to_name.to_owned());

    let source = {
        let parent = fd.parent_mut().ok_or_else(|| {
            let err: io::Error = ErrorKind::PermissionDenied.into();
            err
        })?;
        parent.unlink(from_name).await?
    };

    if let Some(source) = source {
        if let Some(target) = resolve(to.as_ref()).await {
            match target {
                PathTarget::Descriptor(to_fd) => {
                    let mut to_fd = to_fd.write().await;
                    // Overwrite existing file
                    if matches!(&*to_fd, MemoryFd::File(_)) {
                        if let Some(to_parent_fd) = to_fd.parent_mut() {
                            to_parent_fd
                                .insert(to_name.to_owned(), source)
                                .await?;
                        }
                        Ok(())
                    // Cannot overwrite a directory
                    } else {
                        Err(ErrorKind::PermissionDenied.into())
                    }
                }
                _ => Err(ErrorKind::PermissionDenied.into()),
            }
        } else {
            let has_parent = has_parent(to.as_ref());
            if has_parent {
                // To does not exist but it's parent must
                if let Some(target) = resolve_parent(to.as_ref()).await {
                    match target {
                        PathTarget::Descriptor(fd) => {
                            let mut to_parent_write = fd.write().await;
                            match &mut *to_parent_write {
                                MemoryFd::Dir(dir) => {
                                    dir.insert(to_name.to_owned(), source)
                                        .await;
                                }
                                _ => unreachable!(),
                            }
                        }
                        PathTarget::Root(dir) => {
                            let mut dir = dir.write().await;
                            dir.insert(to_name.to_owned(), source).await;
                        }
                    }
                    Ok(())
                } else {
                    Err(ErrorKind::NotFound.into())
                }

            // Moving to the root
            } else {
                let root = root_fs();
                let mut root = root.write().await;
                root.insert(to_name.to_owned(), source).await;
                Ok(())
            }
        }
    } else {
        Err(ErrorKind::NotFound.into())
    }
}

/// Creates a future which will open a file for reading
/// and read the entire contents into a string and return said string.
pub async fn read_to_string(path: impl AsRef<Path>) -> Result<String> {
    let contents = read(path).await?;
    String::from_utf8(contents).map_err(|_| {
        let err: Error = ErrorKind::InvalidData.into();
        err
    })
}

/// Given a path, queries the file system to get information about a file, directory, etc.
pub async fn metadata(path: impl AsRef<Path>) -> io::Result<Metadata> {
    if let Some(target) = resolve(path.as_ref().to_path_buf()).await {
        match target {
            PathTarget::Descriptor(fd) => {
                let len = {
                    let fd = fd.read().await;
                    match &*fd {
                        MemoryFd::File(file) => {
                            let data = file.contents();
                            let data = data.lock();
                            (*data).get_ref().len() as u64
                        }
                        _ => 0u64,
                    }
                };
                Ok(new_metadata(fd, len).await)
            }
            PathTarget::Root(_) => {
                unimplemented!("support root fs metadata");
            }
        }
    } else {
        Err(ErrorKind::NotFound.into())
    }
}

#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
async fn new_metadata(fd: Fd, len: u64) -> Metadata {
    let fd = fd.read().await;
    Metadata::new(*fd.permissions(), fd.flags(), len, *fd.time())
}

#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
async fn new_metadata(fd: Fd, len: u64) -> Metadata {
    let fd = fd.read().await;
    Metadata::new(fd.permissions().clone(), fd.flags(), len)
}

/// Changes the permissions found on a file or a directory.
pub async fn set_permissions(
    path: impl AsRef<Path>,
    perm: Permissions,
) -> Result<()> {
    if let Some(target) = resolve(path.as_ref()).await {
        match target {
            PathTarget::Descriptor(fd) => {
                let mut fd = fd.write().await;
                fd.set_permissions(perm);
                Ok(())
            }
            _ => Err(ErrorKind::PermissionDenied.into()),
        }
    } else {
        Err(ErrorKind::NotFound.into())
    }
}

/// Returns Ok(true) if the path points at an existing entity.
pub async fn try_exists(path: impl AsRef<Path>) -> Result<bool> {
    Ok(resolve(path).await.is_some())
}

/// Returns the canonical, absolute form of a path with
/// all intermediate components normalized and symbolic links resolved.
pub async fn canonicalize(path: impl AsRef<Path>) -> Result<PathBuf> {
    if let Some(target) = resolve(path.as_ref()).await {
        match target {
            PathTarget::Root(_) => {
                Ok(PathBuf::from(MAIN_SEPARATOR.to_string()))
            }
            PathTarget::Descriptor(fd) => {
                let fd = fd.read().await;
                Ok(fd.path().await)
            }
        }
    } else {
        Err(ErrorKind::NotFound.into())
    }
}

/// Create a new file.
///
/// The parent directory must exist.
pub(super) async fn create_file(
    path: impl AsRef<Path>,
    truncate: bool,
) -> Result<Fd> {
    let file_name = path.as_ref().file_name().ok_or_else(|| {
        let err: io::Error = ErrorKind::PermissionDenied.into();
        err
    })?;

    // File already exists
    if let Some(target) = resolve(path.as_ref()).await {
        match target {
            PathTarget::Descriptor(file) => {
                let mut file_fd = file.write().await;
                if file_fd.parent().is_some() {
                    match &mut *file_fd {
                        MemoryFd::Dir(_) => {
                            Err(ErrorKind::PermissionDenied.into())
                        }
                        MemoryFd::File(fd) => {
                            if truncate {
                                fd.truncate();
                            }
                            Ok(Arc::clone(&file))
                        }
                    }
                } else {
                    Err(ErrorKind::PermissionDenied.into())
                }
            }
            _ => Err(ErrorKind::PermissionDenied.into()),
        }
    // Try to create in parent
    } else if let Some(target) = resolve_parent(path.as_ref()).await {
        match target {
            PathTarget::Descriptor(fd) => {
                let mut parent_fd = fd.write().await;
                match &mut *parent_fd {
                    MemoryFd::Dir(dir) => {
                        let new_file = MemoryFd::File(MemoryFile::new(
                            file_name.to_owned(),
                            Some(Parent::Folder(Arc::clone(&fd))),
                        ));
                        dir.insert(
                            file_name.to_owned(),
                            Arc::new(RwLock::new(new_file)),
                        )
                        .await;

                        Ok(dir
                            .files()
                            .get(file_name)
                            .map(Arc::clone)
                            .unwrap())
                    }
                    MemoryFd::File(_) => {
                        Err(ErrorKind::PermissionDenied.into())
                    }
                }
            }
            _ => unreachable!(),
        }
    // Create at the root
    } else {
        let root = root_fs();
        let new_file = MemoryFd::File(MemoryFile::new(
            file_name.to_owned(),
            Some(Parent::Root(Arc::clone(&root))),
        ));
        {
            let mut dir = root.write().await;
            dir.insert(file_name.to_owned(), Arc::new(RwLock::new(new_file)))
                .await;
        }
        let dir = root.read().await;
        Ok(dir.files().get(file_name).map(Arc::clone).unwrap())
    }
}

/// Ensure a path is a file and exists.
async fn ensure_file(path: impl AsRef<Path>) -> Result<Fd> {
    if let Some(target) = resolve(path.as_ref().to_path_buf()).await {
        match target {
            PathTarget::Descriptor(fd) => {
                let is_file = {
                    let fd = fd.read().await;
                    matches!(&*fd, MemoryFd::File(_))
                };
                if is_file {
                    Ok(fd)
                } else {
                    Err(ErrorKind::PermissionDenied.into())
                }
            }
            _ => Err(ErrorKind::PermissionDenied.into()),
        }
    } else {
        Err(ErrorKind::NotFound.into())
    }
}

/// Ensure a path is a directory and exists.
async fn ensure_dir(path: impl AsRef<Path>) -> Result<Fd> {
    if let Some(target) = resolve(path.as_ref().to_path_buf()).await {
        match target {
            PathTarget::Descriptor(fd) => {
                let is_dir = {
                    let fd = fd.read().await;
                    matches!(&*fd, MemoryFd::Dir(_))
                };
                if is_dir {
                    Ok(fd)
                } else {
                    Err(ErrorKind::PermissionDenied.into())
                }
            }
            _ => Err(ErrorKind::PermissionDenied.into()),
        }
    } else {
        Err(ErrorKind::NotFound.into())
    }
}

/// Determine if a path has a parent that is not the root.
pub(super) fn has_parent(path: impl AsRef<Path>) -> bool {
    if let Some(parent) = path.as_ref().parent() {
        !parent.as_os_str().is_empty()
    } else {
        false
    }
}

/// Recursive walk of the tree to find a target path.
#[async_recursion]
async fn walk(
    target: Parent,
    it: &mut Enumerate<IntoIter<Component>>,
    length: usize,
    parents: &mut Vec<Parent>,
) -> Option<PathTarget> {
    if let Some((index, part)) = it.next() {
        match part {
            Component::RootDir => {
                // Got a root request only
                if length == 1 {
                    return Some(PathTarget::Root(root_fs()));
                }
                let root = root_fs();
                parents.push(Parent::Root(Arc::clone(&root)));
                return walk(Parent::Root(root), it, length, parents).await;
            }
            Component::CurDir | Component::Prefix(_) => {
                return walk(target, it, length, parents).await;
            }
            Component::ParentDir => {
                if parents.pop().is_some() {
                    if index == length - 1 {
                        if let Some(target) = parents.pop() {
                            return Some(target.into());
                        } else {
                            return None;
                        }
                    } else if let Some(last) = parents.last() {
                        return walk(last.clone(), it, length, parents).await;
                    }
                } else {
                    return None;
                }
            }
            Component::Normal(name) => {
                if index == length - 1 {
                    return match target {
                        Parent::Root(fs) => {
                            let fs = fs.read().await;
                            fs.files().get(name).map(|fd| {
                                PathTarget::Descriptor(Arc::clone(fd))
                            })
                        }
                        Parent::Folder(fd) => {
                            let fd = fd.read().await;
                            match &*fd {
                                MemoryFd::Dir(dir) => {
                                    dir.files().get(name).map(|fd| {
                                        PathTarget::Descriptor(Arc::clone(fd))
                                    })
                                }
                                _ => None,
                            }
                        }
                    };
                } else if let Some(child) = target.find_dir(name).await {
                    parents.push(Parent::Folder(Arc::clone(&child)));
                    return walk(
                        Parent::Folder(Arc::clone(&child)),
                        it,
                        length,
                        parents,
                    )
                    .await;
                } else {
                    return None;
                }
            }
        }
    }
    None
}

/// Resolve relative to a parent.
async fn resolve_relative(
    parent: Parent,
    path: impl AsRef<Path>,
) -> Option<PathTarget> {
    let components: Vec<Component> = path.as_ref().components().collect();
    let length = components.len();
    let mut it = components.into_iter().enumerate();
    walk(parent.clone(), &mut it, length, &mut vec![parent]).await
}

/// Resolve relative to the root folder.
pub(super) async fn resolve(path: impl AsRef<Path>) -> Option<PathTarget> {
    resolve_relative(Parent::Root(root_fs()), path).await
}

/// Try to resolve the parent of a path.
pub(super) async fn resolve_parent(
    path: impl AsRef<Path>,
) -> Option<PathTarget> {
    if let Some(parent) = path.as_ref().parent() {
        resolve(parent).await
    } else {
        None
    }
}