renfs 0.2.2

Bindings for ZenFS: A filesystem, anywhere
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
use std::{
    fs,
    io::{self, IoSlice, IoSliceMut},
    path::{Path, PathBuf},
    time::SystemTime,
};

use futures_lite::{
    future::block_on,
    io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt},
    stream::StreamExt,
};

use super::api::{
    Dirent, Metadata, OpenOptions, ReadStreamOptions, StatFs, WatchFileOptions, WatchOptions,
    WriteStreamOptions,
};

pub(crate) use super::common::{
    access_sync, app_dir, append_file_sync, append_text, copy_file_sync, cp_sync, create_dir,
    create_dir_all, exists_sync, glob_to_regex, invalid_path_error, link_sync, lstat_sync,
    metadata_parts, mkdir_sync, mkdtemp_disposable_sync, mkdtemp_sync, normalize_path, path_string,
    read_dir, read_file_sync, read_text, readdir_sync, readlink_sync, realpath_sync, remove_file,
    rename_sync, rm_sync, rmdir_sync, stat_sync, symlink_sync, truncate_sync, unlink_sync,
    write_file_sync, write_text,
};

pub struct ReadStream {
    file: async_fs::File,
    chunk_size: usize,
    remaining: Option<u64>,
}

pub fn create_read_stream(path: &str, options: ReadStreamOptions) -> io::Result<ReadStream> {
    if options.chunk_size == 0 || options.chunk_size > u32::MAX as usize {
        return Err(invalid_path_error(
            "stream chunk size must be between 1 and u32::MAX",
        ));
    }
    if options.end.is_some_and(|end| end < options.start) {
        return Err(invalid_path_error("stream end must not be before start"));
    }
    let mut file = async_fs::File::from(fs::File::open(path)?);
    if options.start != 0 {
        block_on(file.seek(io::SeekFrom::Start(options.start)))?;
    }
    Ok(ReadStream {
        file,
        chunk_size: options.chunk_size,
        remaining: options
            .end
            .map(|end| end.saturating_sub(options.start).saturating_add(1)),
    })
}

pub async fn stream_read(stream: &mut ReadStream) -> io::Result<Option<Vec<u8>>> {
    let size = stream.remaining.map_or(stream.chunk_size, |remaining| {
        stream
            .chunk_size
            .min(usize::try_from(remaining).unwrap_or(usize::MAX))
    });
    if size == 0 {
        return Ok(None);
    }
    let mut bytes = vec![0; size];
    let read = stream.file.read(&mut bytes).await?;
    if read == 0 {
        return Ok(None);
    }
    bytes.truncate(read);
    if let Some(remaining) = &mut stream.remaining {
        *remaining -= read as u64;
    }
    Ok(Some(bytes))
}

pub fn read_stream_destroy(_stream: &ReadStream) -> io::Result<()> {
    Ok(())
}

pub struct WriteStream {
    file: async_fs::File,
}

pub fn create_write_stream(path: &str, options: WriteStreamOptions) -> io::Result<WriteStream> {
    let mut open = fs::OpenOptions::new();
    open.write(true).create(true).truncate(true);
    let mut file = async_fs::File::from(open.open(path)?);
    if let Some(start) = options.start {
        block_on(file.seek(io::SeekFrom::Start(start)))?;
    }
    Ok(WriteStream { file })
}

pub async fn stream_write(stream: &mut WriteStream, bytes: &[u8]) -> io::Result<()> {
    stream.file.write_all(bytes).await
}

pub async fn stream_end(stream: &mut WriteStream) -> io::Result<()> {
    stream.file.close().await
}

pub fn write_stream_destroy(_stream: &WriteStream) -> io::Result<()> {
    Ok(())
}

pub struct Watcher(std::sync::Mutex<Option<notify::RecommendedWatcher>>);

type WatchListener = Box<dyn FnMut(&str, &str) + Send>;

pub fn watch(
    path: &str,
    options: WatchOptions,
    mut listener: WatchListener,
) -> io::Result<Watcher> {
    use notify::Watcher as _;
    let watched = PathBuf::from(path);
    let mut watcher = notify::recommended_watcher(move |event: notify::Result<notify::Event>| {
        let Ok(event) = event else {
            return;
        };
        let kind = match event.kind {
            notify::EventKind::Create(_)
            | notify::EventKind::Remove(_)
            | notify::EventKind::Modify(notify::event::ModifyKind::Name(_)) => "rename",
            notify::EventKind::Modify(_) => "change",
            _ => return,
        };
        for changed in event.paths {
            let name = changed
                .file_name()
                .and_then(|name| name.to_str())
                .or_else(|| watched.file_name().and_then(|name| name.to_str()))
                .unwrap_or("");
            listener(kind, name);
        }
    })
    .map_err(io::Error::other)?;
    watcher
        .watch(
            Path::new(path),
            if options.recursive {
                notify::RecursiveMode::Recursive
            } else {
                notify::RecursiveMode::NonRecursive
            },
        )
        .map_err(io::Error::other)?;
    Ok(Watcher(std::sync::Mutex::new(Some(watcher))))
}

pub fn watch_close(watcher: &Watcher) -> io::Result<()> {
    watcher
        .0
        .lock()
        .map_err(|_| io::Error::other("watcher lock was poisoned"))?
        .take();
    Ok(())
}

struct FileWatch {
    id: u64,
    stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
    thread: std::thread::Thread,
}

fn file_watches() -> &'static std::sync::Mutex<std::collections::HashMap<String, Vec<FileWatch>>> {
    static WATCHES: std::sync::OnceLock<
        std::sync::Mutex<std::collections::HashMap<String, Vec<FileWatch>>>,
    > = std::sync::OnceLock::new();
    WATCHES.get_or_init(Default::default)
}

fn watch_snapshot(path: &str) -> io::Result<Option<fs::Metadata>> {
    match fs::metadata(path) {
        Ok(metadata) => Ok(Some(metadata)),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
        Err(error) => Err(error),
    }
}

fn watched_metadata(metadata: Option<&fs::Metadata>) -> Metadata {
    metadata
        .cloned()
        .map(metadata_parts)
        .unwrap_or_else(|| Metadata::from_parts(0, false, false, false))
}

fn snapshot_changed(before: Option<&fs::Metadata>, after: Option<&fs::Metadata>) -> bool {
    match (before, after) {
        (None, None) => false,
        (Some(a), Some(b)) => {
            a.len() != b.len()
                || a.modified().ok() != b.modified().ok()
                || a.accessed().ok() != b.accessed().ok()
                || a.permissions().readonly() != b.permissions().readonly()
        }
        _ => true,
    }
}

pub fn watch_file(
    path: &str,
    options: WatchFileOptions,
    mut listener: Box<dyn FnMut(Metadata, Metadata) + Send>,
) -> io::Result<u64> {
    use std::sync::{
        Arc,
        atomic::{AtomicBool, AtomicU64, Ordering},
    };
    static NEXT_ID: AtomicU64 = AtomicU64::new(1);
    if options.interval.is_zero() {
        return Err(invalid_path_error("watch interval must be positive"));
    }
    let mut before = watch_snapshot(path)?;
    let stop = Arc::new(AtomicBool::new(false));
    let cancel = Arc::clone(&stop);
    let path_owned = path.to_owned();
    let handle = std::thread::Builder::new()
        .name("renfs-watch-file".to_owned())
        .spawn(move || {
            loop {
                std::thread::park_timeout(options.interval);
                if cancel.load(Ordering::Acquire) {
                    break;
                }
                let Ok(after) = watch_snapshot(&path_owned) else {
                    continue;
                };
                if snapshot_changed(before.as_ref(), after.as_ref()) {
                    listener(
                        watched_metadata(after.as_ref()),
                        watched_metadata(before.as_ref()),
                    );
                }
                before = after;
            }
        })?;
    let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
    let watch = FileWatch {
        id,
        stop,
        thread: handle.thread().clone(),
    };
    file_watches()
        .lock()
        .map_err(|_| io::Error::other("file watcher lock was poisoned"))?
        .entry(path.to_owned())
        .or_default()
        .push(watch);
    Ok(id)
}

pub fn unwatch_file(path: &str, id: Option<u64>) -> io::Result<()> {
    let mut watches = file_watches()
        .lock()
        .map_err(|_| io::Error::other("file watcher lock was poisoned"))?;
    if let Some(list) = watches.get_mut(path) {
        list.retain(|watch| {
            if id.is_none_or(|id| id == watch.id) {
                watch.stop.store(true, std::sync::atomic::Ordering::Release);
                watch.thread.unpark();
                false
            } else {
                true
            }
        });
        if list.is_empty() {
            watches.remove(path);
        }
    }
    Ok(())
}

pub type File = async_fs::File;
pub type Dir = async_fs::ReadDir;

#[cfg(test)]
fn app_dir_in(base: &Path, name: &str) -> io::Result<String> {
    let name_path = Path::new(name);
    if name.contains('/')
        || name.contains('\\')
        || !matches!(
            name_path.components().next(),
            Some(std::path::Component::Normal(_))
        )
        || name_path.components().count() != 1
    {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "application name must be a single path component",
        ));
    }

    let path = base.join(name_path);
    fs::create_dir_all(&path)?;
    path.into_os_string().into_string().map_err(|_| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            "application data directory path is not valid UTF-8",
        )
    })
}

pub async fn exists(path: &str) -> io::Result<bool> {
    match async_fs::metadata(path).await {
        Ok(_) => Ok(true),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
        Err(error) => Err(error),
    }
}

pub async fn access(path: &str, mode: u32) -> io::Result<()> {
    super::common::check_access(&async_fs::metadata(path).await?, mode)
}

pub async fn append_file(path: &str, contents: &[u8]) -> io::Result<()> {
    let mut options = async_fs::OpenOptions::new();
    options.create(true).append(true);
    options.open(path).await?.write_all(contents).await
}

pub async fn read_file(path: &str) -> io::Result<Vec<u8>> {
    async_fs::read(path).await
}

pub async fn write_file(path: &str, contents: &[u8]) -> io::Result<()> {
    async_fs::write(path, contents).await
}

pub async fn copy_file(from: &str, to: &str) -> io::Result<()> {
    async_fs::copy(from, to).await.map(|_| ())
}

fn create_symlink(from: &Path, to: &Path) -> io::Result<()> {
    let target = fs::read_link(from)?;
    #[cfg(unix)]
    {
        std::os::unix::fs::symlink(target, to)
    }
    #[cfg(windows)]
    {
        if fs::metadata(from)?.is_dir() {
            std::os::windows::fs::symlink_dir(target, to)
        } else {
            std::os::windows::fs::symlink_file(target, to)
        }
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = target;
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "copying symbolic links is unsupported on this platform",
        ))
    }
}

pub async fn cp(from: &str, to: &str) -> io::Result<()> {
    let mut pending = vec![(PathBuf::from(from), PathBuf::from(to))];
    let mut directory_permissions = Vec::new();

    while let Some((source, destination)) = pending.pop() {
        let metadata = async_fs::symlink_metadata(&source).await?;
        if metadata.is_dir() {
            async_fs::create_dir_all(&destination).await?;
            let mut entries = async_fs::read_dir(&source).await?;
            while let Some(entry) = entries.next().await {
                let entry = entry?;
                pending.push((entry.path(), destination.join(entry.file_name())));
            }
            directory_permissions.push((destination, metadata.permissions()));
        } else if metadata.file_type().is_symlink() {
            create_symlink(&source, &destination)?;
        } else if metadata.is_file() {
            async_fs::copy(&source, &destination).await?;
        } else {
            return Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "copying this filesystem entry type is unsupported",
            ));
        }
    }

    for (path, permissions) in directory_permissions.into_iter().rev() {
        async_fs::set_permissions(path, permissions).await?;
    }
    Ok(())
}

pub fn open_sync(path: &str, options: &OpenOptions) -> io::Result<File> {
    let mut open_options = fs::OpenOptions::new();
    open_options
        .read(options.read)
        .write(options.write)
        .append(options.append)
        .truncate(options.truncate)
        .create(options.create)
        .create_new(options.create_new);
    open_options.open(path).map(File::from)
}

pub async fn open(path: &str, options: &OpenOptions) -> io::Result<File> {
    let mut open_options = async_fs::OpenOptions::new();
    open_options
        .read(options.read)
        .write(options.write)
        .append(options.append)
        .truncate(options.truncate)
        .create(options.create)
        .create_new(options.create_new);
    open_options.open(path).await
}

pub async fn open_as_blob(path: &str) -> io::Result<Vec<u8>> {
    async_fs::read(path).await
}

pub fn close_sync(file: File) -> io::Result<()> {
    drop(file);
    Ok(())
}

pub async fn close(file: &mut File) -> io::Result<()> {
    file.close().await
}

pub fn read_sync(file: &mut File, buffer: &mut [u8]) -> io::Result<usize> {
    block_on(AsyncReadExt::read(file, buffer))
}

pub async fn read(file: &mut File, buffer: &mut [u8]) -> io::Result<usize> {
    file.read(buffer).await
}

pub fn write_sync(file: &mut File, buffer: &[u8]) -> io::Result<usize> {
    block_on(AsyncWriteExt::write(file, buffer))
}

pub async fn write(file: &mut File, buffer: &[u8]) -> io::Result<usize> {
    file.write(buffer).await
}

pub fn readv_sync(file: &mut File, buffers: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
    block_on(async {
        let mut read = 0;
        for buffer in buffers {
            if buffer.is_empty() {
                continue;
            }
            let count = file.read(&mut buffer[..]).await?;
            read += count;
            if count < buffer.len() {
                break;
            }
        }
        Ok(read)
    })
}

pub async fn readv(file: &mut File, buffers: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
    let mut read = 0;
    for buffer in buffers {
        if buffer.is_empty() {
            continue;
        }
        let count = file.read(&mut buffer[..]).await?;
        read += count;
        if count < buffer.len() {
            break;
        }
    }
    Ok(read)
}

pub fn writev_sync(file: &mut File, buffers: &[IoSlice<'_>]) -> io::Result<usize> {
    block_on(async {
        let mut written = 0;
        for buffer in buffers {
            if buffer.is_empty() {
                continue;
            }
            let count = file.write(buffer).await?;
            written += count;
            if count < buffer.len() {
                break;
            }
        }
        Ok(written)
    })
}

pub async fn writev(file: &mut File, buffers: &[IoSlice<'_>]) -> io::Result<usize> {
    let mut written = 0;
    for buffer in buffers {
        if buffer.is_empty() {
            continue;
        }
        let count = file.write(buffer).await?;
        written += count;
        if count < buffer.len() {
            break;
        }
    }
    Ok(written)
}

pub fn fstat_sync(file: &File) -> io::Result<Metadata> {
    let metadata = block_on(file.metadata())?;
    Ok(metadata_parts(metadata))
}

pub async fn fstat(file: &File) -> io::Result<Metadata> {
    Ok(metadata_parts(file.metadata().await?))
}

pub async fn stat(path: &str) -> io::Result<Metadata> {
    async_fs::metadata(path).await.map(metadata_parts)
}
pub async fn lstat(path: &str) -> io::Result<Metadata> {
    async_fs::symlink_metadata(path).await.map(metadata_parts)
}

#[cfg(unix)]
fn c_path(path: &str) -> io::Result<std::ffi::CString> {
    std::ffi::CString::new(path.as_bytes())
        .map_err(|_| invalid_path_error("path contains a NUL byte"))
}

#[cfg(unix)]
pub fn statfs_sync(path: &str) -> io::Result<StatFs> {
    let path = c_path(path)?;
    let mut stat: libc::statvfs = unsafe { std::mem::zeroed() };
    if unsafe { libc::statvfs(path.as_ptr(), &mut stat) } != 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(StatFs {
        block_size: stat.f_bsize as u64,
        blocks: stat.f_blocks as f64,
        blocks_free: stat.f_bfree as f64,
        blocks_available: stat.f_bavail as f64,
        files: stat.f_files as f64,
        files_free: stat.f_ffree as f64,
    })
}

#[cfg(not(unix))]
pub fn statfs_sync(_path: &str) -> io::Result<StatFs> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "statfs is unsupported on this platform",
    ))
}
pub async fn statfs(path: &str) -> io::Result<StatFs> {
    statfs_sync(path)
}

#[cfg(unix)]
fn permissions(mode: u32) -> fs::Permissions {
    use std::os::unix::fs::PermissionsExt;
    fs::Permissions::from_mode(mode)
}
#[cfg(not(unix))]
fn permissions(mode: u32, mut permissions: fs::Permissions) -> fs::Permissions {
    permissions.set_readonly(mode & 0o222 == 0);
    permissions
}

pub fn chmod_sync(path: &str, mode: u32) -> io::Result<()> {
    #[cfg(unix)]
    {
        fs::set_permissions(path, permissions(mode))
    }
    #[cfg(not(unix))]
    {
        let permissions = permissions(mode, fs::metadata(path)?.permissions());
        fs::set_permissions(path, permissions)
    }
}
pub async fn chmod(path: &str, mode: u32) -> io::Result<()> {
    #[cfg(unix)]
    {
        async_fs::set_permissions(path, permissions(mode)).await
    }
    #[cfg(not(unix))]
    {
        let current = async_fs::metadata(path).await?.permissions();
        async_fs::set_permissions(path, permissions(mode, current)).await
    }
}
pub fn fchmod_sync(file: &File, mode: u32) -> io::Result<()> {
    #[cfg(unix)]
    {
        block_on(file.set_permissions(permissions(mode)))
    }
    #[cfg(not(unix))]
    {
        let current = block_on(file.metadata())?.permissions();
        block_on(file.set_permissions(permissions(mode, current)))
    }
}
pub async fn fchmod(file: &File, mode: u32) -> io::Result<()> {
    #[cfg(unix)]
    {
        file.set_permissions(permissions(mode)).await
    }
    #[cfg(not(unix))]
    {
        let current = file.metadata().await?.permissions();
        file.set_permissions(permissions(mode, current)).await
    }
}

#[cfg(unix)]
pub fn lchmod_sync(path: &str, mode: u32) -> io::Result<()> {
    let path = c_path(path)?;
    if unsafe {
        libc::fchmodat(
            libc::AT_FDCWD,
            path.as_ptr(),
            mode as libc::mode_t,
            libc::AT_SYMLINK_NOFOLLOW,
        )
    } == 0
    {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}
#[cfg(not(unix))]
pub fn lchmod_sync(_path: &str, _mode: u32) -> io::Result<()> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "lchmod is unsupported on this platform",
    ))
}
pub async fn lchmod(path: &str, mode: u32) -> io::Result<()> {
    lchmod_sync(path, mode)
}

#[cfg(unix)]
fn set_owner(path: &str, uid: u32, gid: u32, flags: libc::c_int) -> io::Result<()> {
    let path = c_path(path)?;
    if unsafe { libc::fchownat(libc::AT_FDCWD, path.as_ptr(), uid, gid, flags) } == 0 {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}
#[cfg(unix)]
pub fn chown_sync(path: &str, uid: u32, gid: u32) -> io::Result<()> {
    set_owner(path, uid, gid, 0)
}
#[cfg(unix)]
pub fn lchown_sync(path: &str, uid: u32, gid: u32) -> io::Result<()> {
    set_owner(path, uid, gid, libc::AT_SYMLINK_NOFOLLOW)
}
#[cfg(not(unix))]
pub fn chown_sync(_path: &str, _uid: u32, _gid: u32) -> io::Result<()> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "chown is unsupported on this platform",
    ))
}
#[cfg(not(unix))]
pub fn lchown_sync(_path: &str, _uid: u32, _gid: u32) -> io::Result<()> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "lchown is unsupported on this platform",
    ))
}
pub async fn chown(path: &str, uid: u32, gid: u32) -> io::Result<()> {
    chown_sync(path, uid, gid)
}
pub async fn lchown(path: &str, uid: u32, gid: u32) -> io::Result<()> {
    lchown_sync(path, uid, gid)
}

#[cfg(unix)]
pub fn fchown_sync(file: &File, uid: u32, gid: u32) -> io::Result<()> {
    use std::os::fd::AsRawFd;
    if unsafe { libc::fchown(file.as_raw_fd(), uid, gid) } == 0 {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}
#[cfg(not(unix))]
pub fn fchown_sync(_file: &File, _uid: u32, _gid: u32) -> io::Result<()> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "fchown is unsupported on this platform",
    ))
}
pub async fn fchown(file: &File, uid: u32, gid: u32) -> io::Result<()> {
    fchown_sync(file, uid, gid)
}

fn file_times(atime: SystemTime, mtime: SystemTime) -> (filetime::FileTime, filetime::FileTime) {
    (
        filetime::FileTime::from_system_time(atime),
        filetime::FileTime::from_system_time(mtime),
    )
}
pub fn utimes_sync(path: &str, atime: SystemTime, mtime: SystemTime) -> io::Result<()> {
    let (atime, mtime) = file_times(atime, mtime);
    filetime::set_file_times(path, atime, mtime)
}
pub async fn utimes(path: &str, atime: SystemTime, mtime: SystemTime) -> io::Result<()> {
    utimes_sync(path, atime, mtime)
}
pub fn lutimes_sync(path: &str, atime: SystemTime, mtime: SystemTime) -> io::Result<()> {
    let (atime, mtime) = file_times(atime, mtime);
    filetime::set_symlink_file_times(path, atime, mtime)
}
pub async fn lutimes(path: &str, atime: SystemTime, mtime: SystemTime) -> io::Result<()> {
    lutimes_sync(path, atime, mtime)
}

#[cfg(unix)]
pub fn futimes_sync(file: &File, atime: SystemTime, mtime: SystemTime) -> io::Result<()> {
    use std::os::fd::AsRawFd;
    let (atime, mtime) = file_times(atime, mtime);
    let times = [
        libc::timespec {
            tv_sec: atime.unix_seconds() as _,
            tv_nsec: atime.nanoseconds() as _,
        },
        libc::timespec {
            tv_sec: mtime.unix_seconds() as _,
            tv_nsec: mtime.nanoseconds() as _,
        },
    ];
    if unsafe { libc::futimens(file.as_raw_fd(), times.as_ptr()) } == 0 {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}
#[cfg(not(unix))]
pub fn futimes_sync(_file: &File, _atime: SystemTime, _mtime: SystemTime) -> io::Result<()> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "futimes is unsupported on this platform",
    ))
}
pub async fn futimes(file: &File, atime: SystemTime, mtime: SystemTime) -> io::Result<()> {
    futimes_sync(file, atime, mtime)
}

pub fn fsync_sync(file: &File) -> io::Result<()> {
    block_on(file.sync_all())
}

pub async fn fsync(file: &File) -> io::Result<()> {
    file.sync_all().await
}

pub fn fdatasync_sync(file: &File) -> io::Result<()> {
    block_on(file.sync_data())
}

pub async fn fdatasync(file: &File) -> io::Result<()> {
    file.sync_data().await
}

pub fn ftruncate_sync(file: &File, size: u64) -> io::Result<()> {
    block_on(file.set_len(size))
}

pub async fn ftruncate(file: &File, size: u64) -> io::Result<()> {
    file.set_len(size).await
}

pub async fn truncate(path: &str, len: u64) -> io::Result<()> {
    let mut options = async_fs::OpenOptions::new();
    options.write(true);
    options.open(path).await?.set_len(len).await
}

pub async fn mkdir(path: &str, recursive: bool) -> io::Result<()> {
    if recursive {
        async_fs::create_dir_all(path).await
    } else {
        async_fs::create_dir(path).await
    }
}

pub async fn mkdtemp(prefix: &str) -> io::Result<String> {
    mkdtemp_sync(prefix)
}

pub async fn readdir(path: &str) -> io::Result<Vec<String>> {
    let mut entries = async_fs::read_dir(path).await?;
    let mut names = Vec::new();
    while let Some(entry) = entries.next().await {
        names.push(entry?.file_name().into_string().map_err(|_| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                "directory entry name is not valid UTF-8",
            )
        })?);
    }
    Ok(names)
}

pub fn opendir_sync(path: &str) -> io::Result<super::api::Dir> {
    block_on(async_fs::read_dir(path)).map(super::api::Dir::from_inner)
}
pub async fn opendir(path: &str) -> io::Result<super::api::Dir> {
    async_fs::read_dir(path)
        .await
        .map(super::api::Dir::from_inner)
}

async fn dirent(entry: async_fs::DirEntry) -> io::Result<Dirent> {
    let name = entry.file_name().into_string().map_err(|_| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            "directory entry name is not valid UTF-8",
        )
    })?;
    let kind = entry.file_type().await?;
    Ok(Dirent::from_parts(
        name,
        kind.is_file(),
        kind.is_dir(),
        kind.is_symlink(),
    ))
}

pub fn dir_read_sync(dir: &mut Dir) -> io::Result<Option<Dirent>> {
    block_on(dir_read(dir))
}

pub async fn dir_read(dir: &mut Dir) -> io::Result<Option<Dirent>> {
    match dir.next().await.transpose()? {
        Some(entry) => dirent(entry).await.map(Some),
        None => Ok(None),
    }
}

pub fn dir_close_sync(_dir: &Dir) -> io::Result<()> {
    Ok(())
}

pub async fn dir_close(_dir: &Dir) -> io::Result<()> {
    Ok(())
}

pub async fn rmdir(path: &str) -> io::Result<()> {
    async_fs::remove_dir(path).await
}

pub async fn rm(path: &str, recursive: bool, force: bool) -> io::Result<()> {
    let result = match async_fs::symlink_metadata(path).await {
        Ok(metadata) if metadata.is_dir() => {
            if recursive {
                async_fs::remove_dir_all(path).await
            } else {
                async_fs::remove_dir(path).await
            }
        }
        Ok(_) => async_fs::remove_file(path).await,
        Err(error) => Err(error),
    };
    if force
        && result
            .as_ref()
            .is_err_and(|error| error.kind() == io::ErrorKind::NotFound)
    {
        Ok(())
    } else {
        result
    }
}

pub async fn realpath(path: &str) -> io::Result<String> {
    path_string(async_fs::canonicalize(path).await?)
}

pub fn glob_sync(pattern: &str) -> io::Result<Vec<String>> {
    glob::glob(pattern)
        .map_err(|error| invalid_path_error(&error.to_string()))?
        .map(|entry| {
            let path = path_string(entry.map_err(io::Error::other)?)?;
            Ok(if Path::new(pattern).is_absolute() {
                path.trim_start_matches('/').to_owned()
            } else {
                path
            })
        })
        .collect()
}

pub async fn glob(pattern: &str) -> io::Result<Vec<String>> {
    glob_sync(pattern)
}

pub async fn rename(from: &str, to: &str) -> io::Result<()> {
    async_fs::rename(from, to).await
}

pub async fn link(original: &str, link: &str) -> io::Result<()> {
    async_fs::hard_link(original, link).await
}

pub async fn symlink(target: &str, link: &str) -> io::Result<()> {
    symlink_sync(target, link)
}

pub async fn readlink(path: &str) -> io::Result<String> {
    path_string(async_fs::read_link(path).await?)
}

pub async fn unlink(path: &str) -> io::Result<()> {
    async_fs::remove_file(path).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    #[test]
    fn app_dir_creates_a_named_directory_under_the_data_directory() {
        let temp = tempdir().unwrap();

        let path = app_dir_in(temp.path(), "example-app").unwrap();

        assert_eq!(path, temp.path().join("example-app").to_str().unwrap());
        assert!(Path::new(&path).is_dir());
    }

    #[test]
    fn app_dir_rejects_path_components() {
        let temp = tempdir().unwrap();

        assert_eq!(
            app_dir_in(temp.path(), "../outside").unwrap_err().kind(),
            io::ErrorKind::InvalidInput
        );
        assert_eq!(
            app_dir_in(temp.path(), "").unwrap_err().kind(),
            io::ErrorKind::InvalidInput
        );
    }
}

#[cfg(test)]
#[path = "implementation_tests.rs"]
mod shared_tests;