rasio 0.1.1

The Rust Asynchronous IO System Interface
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
use bitmask_enum::bitmask;
use futures::{future::poll_fn, AsyncRead, AsyncSeek, AsyncWrite, Stream};
use std::{
    io::{Result, SeekFrom},
    ops::Deref,
    path::{Path, PathBuf},
    sync::{Arc, OnceLock},
    task::{Context, Poll},
};

pub use std::fs::{FileType, Metadata, Permissions};

/// A bitmask for open file.
///
/// See [`open_file`](FileSystem::open_file) for more information.
#[bitmask(u8)]
pub enum FileOpenMode {
    /// Configures the option for append mode.
    ///
    /// When set to true, this option means the file will be writable after opening
    /// and the file cursor will be moved to the end of file before every write operaiton.
    Append,
    /// Configures the option for write mode.
    /// If the file already exists, write calls on it will overwrite the previous contents without truncating it.
    Writable,
    /// Configures the option for read mode.
    /// When set to true, this option means the file will be readable after opening.
    Readable,

    /// Configures the option for creating a new file if it doesn’t exist.
    /// When set to true, this option means a new file will be created if it doesn’t exist.
    /// The file must be opened in [`Writable`](FileOpenMode::Writable)
    /// or [`Append`](FileOpenMode::Append) mode for file creation to work.
    Create,

    /// Configures the option for creating a new file or failing if it already exists.
    /// When set to true, this option means a new file will be created, or the open
    /// operation will fail if the file already exists.
    /// The file must be opened in [`Writable`](FileOpenMode::Writable)
    /// or [`Append`](FileOpenMode::Append) mode for file creation to work.
    CreateNew,

    /// Configures the option for truncating the previous file.
    /// When set to true, the file will be truncated to the length of 0 bytes.
    /// The file must be opened in [`Writable`](FileOpenMode::Writable)
    /// or [`Append`](FileOpenMode::Append) mode for file creation to work.
    Truncate,
}

#[cfg(any(windows, docrs))]
pub mod windows {

    use std::io::ErrorKind;

    use super::*;

    pub trait FSDNamedPipeListener: Sync + Send {
        fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<()>>;

        fn poll_next(&self, cx: &mut Context<'_>) -> Poll<Result<NamedPipeStream>>;
    }

    pub struct NamedPipeListener(Box<dyn FSDNamedPipeListener>);

    impl Deref for NamedPipeListener {
        type Target = dyn FSDNamedPipeListener;
        fn deref(&self) -> &Self::Target {
            &*self.0
        }
    }

    impl<F: FSDNamedPipeListener + 'static> From<F> for NamedPipeListener {
        fn from(value: F) -> Self {
            Self(Box::new(value))
        }
    }

    impl NamedPipeListener {
        /// Returns internal `FSDNamedPipeListener` object.
        pub fn as_raw_ptr(&self) -> &dyn FSDNamedPipeListener {
            &*self.0
        }

        pub async fn accept(&self) -> Result<NamedPipeStream> {
            poll_fn(|cx| self.as_raw_ptr().poll_next(cx)).await
        }
    }

    impl Stream for NamedPipeListener {
        type Item = Result<NamedPipeStream>;

        fn poll_next(
            self: std::pin::Pin<&mut Self>,
            cx: &mut Context<'_>,
        ) -> Poll<Option<Self::Item>> {
            match self.as_raw_ptr().poll_next(cx) {
                Poll::Ready(Ok(stream)) => Poll::Ready(Some(Ok(stream))),
                Poll::Ready(Err(err)) => {
                    if err.kind() == ErrorKind::BrokenPipe {
                        Poll::Ready(None)
                    } else {
                        Poll::Ready(Some(Err(err)))
                    }
                }
                Poll::Pending => Poll::Pending,
            }
        }
    }

    pub trait FSDNamedPipeStream: Sync + Send {
        fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<()>>;

        /// Write a buffer into this writer, returning how many bytes were written
        fn poll_write(&self, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize>>;

        /// Pull some bytes from this source into the specified buffer, returning how many bytes were read.
        fn poll_read(&self, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<Result<usize>>;

        fn poll_close(&self, cx: &mut Context<'_>) -> Poll<Result<()>>;
    }

    pub struct NamedPipeStream(Arc<Box<dyn FSDNamedPipeStream>>);

    impl Deref for NamedPipeStream {
        type Target = dyn FSDNamedPipeStream;
        fn deref(&self) -> &Self::Target {
            &**self.0
        }
    }

    impl<F: FSDNamedPipeStream + 'static> From<F> for NamedPipeStream {
        fn from(value: F) -> Self {
            Self(Arc::new(Box::new(value)))
        }
    }

    impl NamedPipeStream {
        /// Returns internal `FSDNamedPipeStream` object.
        pub fn as_raw_ptr(&self) -> &dyn FSDNamedPipeStream {
            &**self.0
        }
    }

    impl AsyncRead for NamedPipeStream {
        fn poll_read(
            self: std::pin::Pin<&mut Self>,
            cx: &mut Context<'_>,
            buf: &mut [u8],
        ) -> Poll<Result<usize>> {
            self.as_raw_ptr().poll_read(cx, buf)
        }
    }

    impl AsyncWrite for NamedPipeStream {
        fn poll_write(
            self: std::pin::Pin<&mut Self>,
            cx: &mut Context<'_>,
            buf: &[u8],
        ) -> Poll<Result<usize>> {
            self.as_raw_ptr().poll_write(cx, buf)
        }

        fn poll_flush(self: std::pin::Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<()>> {
            Poll::Ready(Ok(()))
        }

        fn poll_close(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
            self.as_raw_ptr().poll_close(cx)
        }
    }
}

/// A driver is the main entry to access asynchronously filesystem functions
pub trait FileSystemDriver: Sync + Send {
    /// Open new file with provided `mode`.
    fn open_file(&self, path: &Path, mode: FileOpenMode) -> Result<File>;

    /// Returns the canonical form of a path.
    /// The returned path is in absolute form with all intermediate components
    /// normalized and symbolic links resolved.
    /// This function is an async version of [`std::fs::canonicalize`].
    fn canonicalize(&self, path: &Path) -> Result<PathBuf>;

    /// Copies the contents and permissions of a file to a new location.
    /// On success, the total number of bytes copied is returned and equals
    /// the length of the to file after this operation.
    /// The old contents of to will be overwritten. If from and to both point
    /// to the same file, then the file will likely get truncated as a result of this operation.
    fn poll_copy(&self, cx: &mut Context<'_>, from: &Path, to: &Path) -> Poll<Result<u64>>;

    /// Creates a new directory.
    /// Note that this function will only create the final directory in path.
    /// If you want to create all of its missing parent directories too, use
    /// the [`create_dir_all`](FileSystem::create_dir_all) function instead.
    ///
    /// This function is an async version of [`std::fs::create_dir`].
    fn poll_create_dir(&self, cx: &mut Context<'_>, path: &Path) -> Poll<Result<()>>;

    /// Creates a new directory and all of its parents if they are missing.
    /// This function is an async version of [`std::fs::create_dir_all`].
    fn poll_create_dir_all(&self, cx: &mut Context<'_>, path: &Path) -> Poll<Result<()>>;

    /// Creates a hard link on the filesystem.
    /// The dst path will be a link pointing to the src path. Note that operating
    /// systems often require these two paths to be located on the same filesystem.
    ///
    /// This function is an async version of [`std::fs::hard_link`].
    fn poll_hard_link(&self, cx: &mut Context<'_>, from: &Path, to: &Path) -> Poll<Result<()>>;

    /// Reads metadata for a path.
    /// This function will traverse symbolic links to read metadata for the target
    /// file or directory. If you want to read metadata without following symbolic
    /// links, use symlink_metadata instead.
    ///
    /// This function is an async version of [`std::fs::metadata`].
    fn poll_metadata(&self, cx: &mut Context<'_>, path: &Path) -> Poll<Result<Metadata>>;

    /// Reads a symbolic link and returns the path it points to.
    ///
    /// This function is an async version of [`std::fs::read_link`].
    fn poll_read_link(&self, cx: &mut Context<'_>, path: &Path) -> Poll<Result<PathBuf>>;

    /// Removes an empty directory,
    /// if the `path` is not an empty directory, use the function
    /// [`remove_dir_all`](FileSystem::remove_dir_all) instead.
    ///
    /// This function is an async version of std::fs::remove_dir.
    fn poll_remove_dir(&self, cx: &mut Context<'_>, path: &Path) -> Poll<Result<()>>;

    /// Removes a directory and all of its contents.
    ///
    /// This function is an async version of [`std::fs::remove_dir_all`].
    fn poll_remove_dir_all(&self, cx: &mut Context<'_>, path: &Path) -> Poll<Result<()>>;

    /// Removes a file.
    /// This function is an async version of [`std::fs::remove_file`].
    fn poll_remove_file(&self, cx: &mut Context<'_>, path: &Path) -> Poll<Result<()>>;

    /// Renames a file or directory to a new location.
    /// If a file or directory already exists at the target location, it will be overwritten by this operation.
    /// This function is an async version of std::fs::rename.
    fn poll_rename(&self, cx: &mut Context<'_>, from: &Path, to: &Path) -> Poll<Result<()>>;

    /// Changes the permissions of a file or directory.
    /// This function is an async version of [`std::fs::set_permissions`].
    fn poll_set_permissions(
        &self,
        cx: &mut Context<'_>,
        path: &Path,
        perm: &Permissions,
    ) -> Poll<Result<()>>;

    /// Reads metadata for a path without following symbolic links.
    /// If you want to follow symbolic links before reading metadata of the target file or directory,
    /// use [`metadata`](FileSystem::metadata) instead.
    ///
    /// This function is an async version of [`std::fs::symlink_metadata`].
    fn poll_symlink_metadata(&self, cx: &mut Context<'_>, path: &Path) -> Poll<Result<Metadata>>;

    /// Returns a iterator handle of entries in a directory.
    ///
    /// See [`dir_entry_next`](FileSystem::dir_entry_next) for more information about iteration.
    fn read_dir(&self, path: &Path) -> Result<ReadDir>;

    #[cfg(any(windows))]
    /// Opens the named pipe identified by `addr`.
    fn named_pipe_client_open(&self, addr: &std::ffi::OsStr) -> Result<windows::NamedPipeStream>;

    #[cfg(any(windows))]
    /// Creates the named pipe identified by `addr` for use as a server.
    ///
    /// This uses the [`CreateNamedPipe`] function.
    fn named_pipe_server_create(
        &self,
        addr: &std::ffi::OsStr,
    ) -> Result<windows::NamedPipeListener>;
}

pub trait FSDDirEntry: Sync + Send {
    /// Returns the bare name of this entry without the leading path.
    fn name(&self) -> String;

    /// Returns the full path to this entry.
    /// The full path is created by joining the original path passed to [`read_dir`](FileSystemDriver::read_dir) with the name of this entry.
    fn path(&self) -> PathBuf;

    /// Reads the metadata for this entry.
    ///
    /// This function will traverse symbolic links to read the metadata.
    fn meta(&self) -> Result<Metadata>;

    /// eads the file type for this entry.
    /// This function will not traverse symbolic links if this entry points at one.
    /// If you want to read metadata with following symbolic links, use [`meta`](FSDDirEntry::meta) instead.
    fn file_type(&self) -> Result<FileType>;
}

pub struct DirEntry(Box<dyn FSDDirEntry>);

impl Deref for DirEntry {
    type Target = dyn FSDDirEntry;
    fn deref(&self) -> &Self::Target {
        &*self.0
    }
}

impl<F: FSDDirEntry + 'static> From<F> for DirEntry {
    fn from(value: F) -> Self {
        Self(Box::new(value))
    }
}

impl DirEntry {
    /// Returns internal `FSDDirEntry` object.
    pub fn as_raw_ptr(&self) -> &dyn FSDDirEntry {
        &*self.0
    }
}

pub trait FSDReadDir: Sync + Send {
    /// Get asynchronously opened event.
    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<()>>;

    fn poll_next(&self, cx: &mut Context<'_>) -> Poll<Option<Result<DirEntry>>>;
}

pub struct ReadDir(Box<dyn FSDReadDir>);

impl Deref for ReadDir {
    type Target = dyn FSDReadDir;
    fn deref(&self) -> &Self::Target {
        &*self.0
    }
}

impl<F: FSDReadDir + 'static> From<F> for ReadDir {
    fn from(value: F) -> Self {
        Self(Box::new(value))
    }
}

impl ReadDir {
    /// Returns internal `FSDReadDir` object.
    pub fn as_raw_ptr(&self) -> &dyn FSDReadDir {
        &*self.0
    }

    pub async fn new<P: AsRef<Path>>(path: P) -> Result<Self> {
        Self::new_with(path, get_fs_driver()).await
    }

    pub async fn new_with<P: AsRef<Path>>(path: P, driver: &dyn FileSystemDriver) -> Result<Self> {
        let readdir = driver.read_dir(path.as_ref())?;

        poll_fn(|cx| readdir.as_raw_ptr().poll_ready(cx))
            .await
            .map(|_| readdir)
    }
}

impl Stream for ReadDir {
    type Item = Result<DirEntry>;
    fn poll_next(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.as_raw_ptr().poll_next(cx)
    }
}

/// Driver-specific `File` object.
pub trait FSDFile: Sync + Send {
    /// Poll if the file object is actually opened.
    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<()>>;

    /// Write a buffer into this writer, returning how many bytes were written
    fn poll_write(&self, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize>>;

    /// Pull some bytes from this source into the specified buffer, returning how many bytes were read.
    fn poll_read(&self, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<Result<usize>>;

    /// Attempts to sync all OS-internal metadata to disk.
    ///
    /// This function will attempt to ensure that all in-memory data reaches the filesystem before returning.
    ///
    /// This can be used to handle errors that would otherwise only be caught when the File is closed.
    /// Dropping a file will ignore errors in synchronizing this in-memory data.
    fn poll_flush(&self, cx: &mut Context<'_>) -> Poll<Result<()>>;

    /// Seek to an offset, in bytes, in a stream.
    ///
    /// A seek beyond the end of a stream is allowed, but behavior is defined by the implementation.
    ///
    /// If the seek operation completed successfully, this method returns the new position from the
    /// start of the stream. That position can be used later with [`SeekFrom::Start`].
    ///
    /// # Errors
    /// Seeking can fail, for example because it might involve flushing a buffer.
    ///
    /// Seeking to a negative offset is considered an error.
    fn poll_seek(&self, cx: &mut Context<'_>, pos: SeekFrom) -> Poll<Result<u64>>;

    ///  Reads the file's metadata.
    fn poll_meta(&self, cx: &mut Context<'_>) -> Poll<Result<Metadata>>;

    /// Changes the permissions on the file.
    fn poll_set_permissions(&self, cx: &mut Context<'_>, perm: &Permissions) -> Poll<Result<()>>;

    /// Truncates or extends the file.
    ///
    /// If `size` is less than the current file size, then the file will be truncated. If it is
    /// greater than the current file size, then the file will be extended to `size` and have all
    /// intermediate data filled with zeros.
    ///
    /// The file's cursor stays at the same position, even if the cursor ends up being past the end
    /// of the file after this operation.
    ///
    fn poll_set_len(&self, cx: &mut Context<'_>, size: u64) -> Poll<Result<()>>;
}

/// An open file on the filesystem.
///
/// Depending on what options the file was opened with, this type can be used for reading and/or writing.
/// Files are automatically closed when they get dropped and any errors detected on closing are ignored.
/// Use the sync_all method before dropping a file if such errors need to be handled.
///
/// This type is an async version of std::fs::File.
pub struct File(Arc<Box<dyn FSDFile>>);

impl Deref for File {
    type Target = dyn FSDFile;
    fn deref(&self) -> &Self::Target {
        &**self.0
    }
}

impl<F: FSDFile + 'static> From<F> for File {
    fn from(value: F) -> Self {
        Self(Arc::new(Box::new(value)))
    }
}

impl File {
    /// Returns internal `FSDFile` object.
    pub fn as_raw_ptr(&self) -> &dyn FSDFile {
        &**self.0
    }

    /// Open a file with provided `FileOpenMode`.
    pub async fn open<P: AsRef<Path>>(path: P, mode: FileOpenMode) -> Result<Self> {
        Self::open_with(path, mode, get_fs_driver()).await
    }

    /// Use custom `FileSystemDriver` to open file.
    pub async fn open_with<P: AsRef<Path>>(
        path: P,
        mode: FileOpenMode,
        driver: &dyn FileSystemDriver,
    ) -> Result<Self> {
        let file = driver.open_file(path.as_ref(), mode)?;

        // Wait for file opened event.
        poll_fn(|cx| file.as_raw_ptr().poll_ready(cx)).await?;

        Ok(file)
    }

    pub async fn meta(&self) -> Result<Metadata> {
        poll_fn(|cx| self.as_raw_ptr().poll_meta(cx)).await
    }

    pub async fn set_permissions(&self, perm: &Permissions) -> Result<()> {
        poll_fn(|cx| self.as_raw_ptr().poll_set_permissions(cx, perm)).await
    }

    pub async fn set_len(&self, len: u64) -> Result<()> {
        poll_fn(|cx| self.as_raw_ptr().poll_set_len(cx, len)).await
    }
}

impl AsyncRead for File {
    fn poll_read(
        self: std::pin::Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<Result<usize>> {
        self.as_raw_ptr().poll_read(cx, buf)
    }
}

impl AsyncWrite for File {
    fn poll_write(
        self: std::pin::Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<Result<usize>> {
        self.as_raw_ptr().poll_write(cx, buf)
    }

    fn poll_flush(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
        self.as_raw_ptr().poll_flush(cx)
    }

    fn poll_close(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
        self.poll_flush(cx)
    }
}

impl AsyncSeek for File {
    fn poll_seek(
        self: std::pin::Pin<&mut Self>,
        cx: &mut Context<'_>,
        pos: SeekFrom,
    ) -> Poll<Result<u64>> {
        self.as_raw_ptr().poll_seek(cx, pos)
    }
}

/// Returns the canonical form of a path.
/// The returned path is in absolute form with all intermediate components
/// normalized and symbolic links resolved.
/// This function is an async version of [`std::fs::canonicalize`].
pub async fn canonicalize<P: AsRef<Path>>(path: P) -> Result<PathBuf> {
    get_fs_driver().canonicalize(path.as_ref())
}

/// Copies the contents and permissions of a file to a new location.
/// On success, the total number of bytes copied is returned and equals
/// the length of the to file after this operation.
/// The old contents of to will be overwritten. If from and to both point
/// to the same file, then the file will likely get truncated as a result of this operation.
pub async fn copy<F: AsRef<Path>, T: AsRef<Path>>(from: F, to: T) -> Result<u64> {
    poll_fn(|cx| get_fs_driver().poll_copy(cx, from.as_ref(), to.as_ref())).await
}

/// Creates a new directory.
/// Note that this function will only create the final directory in path.
/// If you want to create all of its missing parent directories too, use
/// the [`create_dir_all`](FileSystem::create_dir_all) function instead.
///
/// This function is an async version of [`std::fs::create_dir`].
pub async fn create_dir<P: AsRef<Path>>(path: P) -> Result<()> {
    poll_fn(|cx| get_fs_driver().poll_create_dir(cx, path.as_ref())).await
}

/// Creates a new directory and all of its parents if they are missing.
/// This function is an async version of [`std::fs::create_dir_all`].
pub async fn create_dir_all<P: AsRef<Path>>(path: P) -> Result<()> {
    poll_fn(|cx| get_fs_driver().poll_create_dir_all(cx, path.as_ref())).await
}

/// Creates a hard link on the filesystem.
/// The dst path will be a link pointing to the src path. Note that operating
/// systems often require these two paths to be located on the same filesystem.
///
/// This function is an async version of [`std::fs::hard_link`].
pub async fn hard_link<F: AsRef<Path>, T: AsRef<Path>>(from: F, to: T) -> Result<()> {
    poll_fn(|cx| get_fs_driver().poll_hard_link(cx, from.as_ref(), to.as_ref())).await
}

/// Reads metadata for a path.
/// This function will traverse symbolic links to read metadata for the target
/// file or directory. If you want to read metadata without following symbolic
/// links, use symlink_metadata instead.
///
/// This function is an async version of [`std::fs::metadata`].
pub async fn metadata<P: AsRef<Path>>(path: P) -> Result<Metadata> {
    poll_fn(|cx| get_fs_driver().poll_metadata(cx, path.as_ref())).await
}

/// Reads a symbolic link and returns the path it points to.
///
/// This function is an async version of [`std::fs::read_link`].
pub async fn read_link<P: AsRef<Path>>(path: P) -> Result<PathBuf> {
    poll_fn(|cx| get_fs_driver().poll_read_link(cx, path.as_ref())).await
}

/// Removes an empty directory,
/// if the `path` is not an empty directory, use the function
/// [`remove_dir_all`](FileSystem::remove_dir_all) instead.
///
/// This function is an async version of std::fs::remove_dir.
pub async fn remove_dir<P: AsRef<Path>>(path: P) -> Result<()> {
    poll_fn(|cx| get_fs_driver().poll_remove_dir(cx, path.as_ref())).await
}

/// Removes a directory and all of its contents.
///
/// This function is an async version of [`std::fs::remove_dir_all`].
pub async fn remove_dir_all<P: AsRef<Path>>(path: P) -> Result<()> {
    poll_fn(|cx| get_fs_driver().poll_remove_dir_all(cx, path.as_ref())).await
}

/// Removes a file.
/// This function is an async version of [`std::fs::remove_file`].
pub async fn remove_file<P: AsRef<Path>>(path: P) -> Result<()> {
    poll_fn(|cx| get_fs_driver().poll_remove_file(cx, path.as_ref())).await
}

/// Renames a file or directory to a new location.
/// If a file or directory already exists at the target location, it will be overwritten by this operation.
/// This function is an async version of std::fs::rename.
pub async fn rename<F: AsRef<Path>, T: AsRef<Path>>(from: F, to: T) -> Result<()> {
    poll_fn(|cx| get_fs_driver().poll_rename(cx, from.as_ref(), to.as_ref())).await
}

/// Changes the permissions of a file or directory.
/// This function is an async version of [`std::fs::set_permissions`].
pub async fn set_permissions<P: AsRef<Path>>(path: P, perm: &Permissions) -> Result<()> {
    poll_fn(|cx| get_fs_driver().poll_set_permissions(cx, path.as_ref(), perm)).await
}

/// Reads metadata for a path without following symbolic links.
/// If you want to follow symbolic links before reading metadata of the target file or directory,
/// use [`metadata`](FileSystem::metadata) instead.
///
/// This function is an async version of [`std::fs::symlink_metadata`].
pub async fn symlink_metadata<P: AsRef<Path>>(path: P) -> Result<Metadata> {
    poll_fn(|cx| get_fs_driver().poll_symlink_metadata(cx, path.as_ref())).await
}

/// Returns `true` if the path exists on disk and is pointing at a directory.
///
/// This function will traverse symbolic links to query information about the
/// destination file. In case of broken symbolic links this will return `false`.
///
/// If you cannot access the directory containing the file, e.g., because of a
/// permission error, this will return `false`.
///
/// # See Also
///
/// This is a convenience function that coerces errors to false. If you want to
/// check errors, call [fs::metadata] and handle its Result. Then call
/// [fs::Metadata::is_dir] if it was Ok.
///
/// [fs::metadata]: ../fs/fn.metadata.html
/// [fs::Metadata::is_dir]: ../fs/struct.Metadata.html#method.is_dir
pub async fn is_dir<P: AsRef<Path>>(path: P) -> bool {
    metadata(path).await.map(|m| m.is_dir()).unwrap_or(false)
}

pub struct FileSystem<'a> {
    driver: &'a dyn FileSystemDriver,
}

impl<'a> From<&'a dyn FileSystemDriver> for FileSystem<'a> {
    fn from(value: &'a dyn FileSystemDriver) -> Self {
        Self { driver: value }
    }
}

impl<'a> FileSystem<'a> {
    /// Returns `true` if the path exists on disk and is pointing at a directory.
    ///
    /// This function will traverse symbolic links to query information about the
    /// destination file. In case of broken symbolic links this will return `false`.
    ///
    /// If you cannot access the directory containing the file, e.g., because of a
    /// permission error, this will return `false`.
    ///
    ///
    /// # See Also
    ///
    /// This is a convenience function that coerces errors to false. If you want to
    /// check errors, call [fs::metadata] and handle its Result. Then call
    /// [fs::Metadata::is_dir] if it was Ok.
    ///
    /// [fs::metadata]: ../fs/fn.metadata.html
    /// [fs::Metadata::is_dir]: ../fs/struct.Metadata.html#method.is_dir
    pub async fn is_dir<P: AsRef<Path>>(&self, path: P) -> bool {
        self.metadata(path)
            .await
            .map(|m| m.is_dir())
            .unwrap_or(false)
    }

    /// Returns `true` if the path exists on disk and is pointing at a regular file.
    ///
    /// This function will traverse symbolic links to query information about the
    /// destination file. In case of broken symbolic links this will return `false`.
    ///
    /// If you cannot access the directory containing the file, e.g., because of a
    /// permission error, this will return `false`.
    ///
    /// # See Also
    ///
    /// This is a convenience function that coerces errors to false. If you want to
    /// check errors, call [fs::metadata] and handle its Result. Then call
    /// [fs::Metadata::is_file] if it was Ok.
    ///
    /// [fs::metadata]: ../fs/fn.metadata.html
    /// [fs::Metadata::is_file]: ../fs/struct.Metadata.html#method.is_file

    pub async fn is_file<P: AsRef<Path>>(&self, path: P) -> bool {
        self.metadata(path)
            .await
            .map(|m| m.is_file())
            .unwrap_or(false)
    }

    pub async fn open_file<P: AsRef<Path>>(&self, path: P, mode: FileOpenMode) -> Result<File> {
        File::open_with(path, mode, self.driver).await
    }

    /// Returns the canonical form of a path.
    /// The returned path is in absolute form with all intermediate components
    /// normalized and symbolic links resolved.
    /// This function is an async version of [`std::fs::canonicalize`].
    pub async fn canonicalize<P: AsRef<Path>>(&self, path: P) -> Result<PathBuf> {
        self.driver.canonicalize(path.as_ref())
    }

    /// Copies the contents and permissions of a file to a new location.
    /// On success, the total number of bytes copied is returned and equals
    /// the length of the to file after this operation.
    /// The old contents of to will be overwritten. If from and to both point
    /// to the same file, then the file will likely get truncated as a result of this operation.
    pub async fn copy<F: AsRef<Path>, T: AsRef<Path>>(&self, from: F, to: T) -> Result<u64> {
        poll_fn(|cx| self.driver.poll_copy(cx, from.as_ref(), to.as_ref())).await
    }

    /// Creates a new directory.
    /// Note that this function will only create the final directory in path.
    /// If you want to create all of its missing parent directories too, use
    /// the [`create_dir_all`](FileSystem::create_dir_all) function instead.
    ///
    /// This function is an async version of [`std::fs::create_dir`].
    pub async fn create_dir<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        poll_fn(|cx| self.driver.poll_create_dir(cx, path.as_ref())).await
    }

    /// Creates a new directory and all of its parents if they are missing.
    /// This function is an async version of [`std::fs::create_dir_all`].
    pub async fn create_dir_all<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        poll_fn(|cx| self.driver.poll_create_dir_all(cx, path.as_ref())).await
    }

    /// Creates a hard link on the filesystem.
    /// The dst path will be a link pointing to the src path. Note that operating
    /// systems often require these two paths to be located on the same filesystem.
    ///
    /// This function is an async version of [`std::fs::hard_link`].
    pub async fn hard_link<F: AsRef<Path>, T: AsRef<Path>>(&self, from: F, to: T) -> Result<()> {
        poll_fn(|cx| self.driver.poll_hard_link(cx, from.as_ref(), to.as_ref())).await
    }

    /// Reads metadata for a path.
    /// This function will traverse symbolic links to read metadata for the target
    /// file or directory. If you want to read metadata without following symbolic
    /// links, use symlink_metadata instead.
    ///
    /// This function is an async version of [`std::fs::metadata`].
    pub async fn metadata<P: AsRef<Path>>(&self, path: P) -> Result<Metadata> {
        poll_fn(|cx| self.driver.poll_metadata(cx, path.as_ref())).await
    }

    /// Reads a symbolic link and returns the path it points to.
    ///
    /// This function is an async version of [`std::fs::read_link`].
    pub async fn read_link<P: AsRef<Path>>(&self, path: P) -> Result<PathBuf> {
        poll_fn(|cx| self.driver.poll_read_link(cx, path.as_ref())).await
    }

    /// Removes an empty directory,
    /// if the `path` is not an empty directory, use the function
    /// [`remove_dir_all`](FileSystem::remove_dir_all) instead.
    ///
    /// This function is an async version of std::fs::remove_dir.
    pub async fn remove_dir<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        poll_fn(|cx| self.driver.poll_remove_dir(cx, path.as_ref())).await
    }

    /// Removes a directory and all of its contents.
    ///
    /// This function is an async version of [`std::fs::remove_dir_all`].
    pub async fn remove_dir_all<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        poll_fn(|cx| self.driver.poll_remove_dir_all(cx, path.as_ref())).await
    }

    /// Removes a file.
    /// This function is an async version of [`std::fs::remove_file`].
    pub async fn remove_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        poll_fn(|cx| self.driver.poll_remove_file(cx, path.as_ref())).await
    }

    /// Renames a file or directory to a new location.
    /// If a file or directory already exists at the target location, it will be overwritten by this operation.
    /// This function is an async version of std::fs::rename.
    pub async fn rename<F: AsRef<Path>, T: AsRef<Path>>(&self, from: F, to: T) -> Result<()> {
        poll_fn(|cx| self.driver.poll_rename(cx, from.as_ref(), to.as_ref())).await
    }

    /// Changes the permissions of a file or directory.
    /// This function is an async version of [`std::fs::set_permissions`].
    pub async fn set_permissions<P: AsRef<Path>>(&self, path: P, perm: &Permissions) -> Result<()> {
        poll_fn(|cx| self.driver.poll_set_permissions(cx, path.as_ref(), perm)).await
    }

    /// Reads metadata for a path without following symbolic links.
    /// If you want to follow symbolic links before reading metadata of the target file or directory,
    /// use [`metadata`](FileSystem::metadata) instead.
    ///
    /// This function is an async version of [`std::fs::symlink_metadata`].
    pub async fn symlink_metadata<P: AsRef<Path>>(&self, path: P) -> Result<Metadata> {
        poll_fn(|cx| self.driver.poll_symlink_metadata(cx, path.as_ref())).await
    }
}

static FIFLE_SYSTEM_DRIVER: OnceLock<Box<dyn FileSystemDriver>> = OnceLock::new();

/// Get global register `FileSystemDriver` instance.
pub fn get_fs_driver() -> &'static dyn FileSystemDriver {
    FIFLE_SYSTEM_DRIVER
        .get()
        .expect("Call register_network_driver first.")
        .as_ref()
}

/// Register provided [`FileSystemDriver`] as global network implementation.
///
/// # Panic
///
/// Multiple calls to this function are not permitted!!!
pub fn register_fs_driver<E: FileSystemDriver + 'static>(driver: E) {
    if FIFLE_SYSTEM_DRIVER.set(Box::new(driver)).is_err() {
        panic!("Multiple calls to register_network_driver are not permitted!!!");
    }
}