oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
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
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
//! Files, directories and their metadata.
//!
//! [`open`] returns an [`OwnedHandle`], which the functions of
//! [`io`](crate::io) read, write and seek, and which is closed when dropped.
//! The functions here cover what is specific to files: metadata, size,
//! durability, locks, and the directory tree.
//!
//! Paths are byte strings ([`AsPath`]): see that trait for their encoding.
//! A relative path is relative to the current directory of the process. The
//! functions that return a path write it into a buffer the caller provides,
//! and fail with [`ErrorKind::BufferTooSmall`] when it does not fit; with
//! the `alloc` feature, a `_vec` variant returns a `Vec<u8>` of the right
//! size instead.
//!
//! # Long paths on Windows
//!
//! Win32 refuses a path of 260 UTF-16 units or more (248 for a directory),
//! unless it is written in the extended form: absolute, with `\` alone as
//! its separator, no `.` or `..`, and `\\?\` in front. oscall does what
//! `std` does: a path that is too long once made absolute is passed to the
//! system in that form (`GetFullPathNameW`), so that long paths work as
//! they do elsewhere, and a path that is already in that form is left
//! alone. This holds for every function of this module that takes a path,
//! except [`set_current_dir`], as the current directory itself cannot be
//! that long, and the target of [`symlink`], which is stored as given.
//! Paths longer than 511 bytes need the `alloc` feature, on every system.
//!
//! # Working under a directory
//!
//! The functions whose name ends in `_at` ([`open_at`], [`metadata_at`],
//! [`rename_at`]...) take an open directory and a path relative to it,
//! instead of a path relative to the current directory. The directory is
//! any handle open on one: a [`Dir`], or what [`open`] returns with
//! [`OpenOptions::directory`]. A handle keeps naming the same directory
//! whatever is renamed or replaced above it, so a tree can be walked, filled
//! or removed without ever looking a whole path up again: that is what
//! makes these functions free of the races paths have.
//!
//! The path must be relative, and must have no `..` component:
//! [`ErrorKind::InvalidInput`] otherwise, on every system (`.` components
//! are fine, and `.` alone names the directory itself). That is the part
//! that can be promised everywhere. It does **not** confine the lookup to
//! the directory: a symbolic link found on the way is followed wherever it
//! leads, except in the last component where the function says so.
//!
//! `openat`, `statx`, `mkdirat`, `unlinkat`... on Linux, the same family on
//! macOS, and the native model of WASI. On Windows, `NtCreateFile` with a
//! root directory, which takes the path as the kernel does: oscall turns
//! `/` into `\` and drops the `.` components, and a path that starts with
//! a drive (`C:`) is refused like an absolute one.
//!
//! # WebAssembly
//!
//! On WASI, a path is resolved against the directories the host preopened
//! for the program, the way `wasi-libc` does: the preopened directory whose
//! name is the longest prefix of the path is used, and a relative path is
//! looked up in the one named `.`. WASI has no permissions, no file locks
//! and no current directory: the functions that need them fail with
//! [`ErrorKind::Unsupported`], as said in each. Without WASI, every
//! function fails with that error.

use core::fmt;

use crate::time::Timestamp;
use crate::{AsHandle, AsPath, BorrowedHandle, ErrorKind, OwnedHandle, Result, sys};

/// How to open a file: see [`open`].
///
/// ```
/// use oscall::fs::OpenOptions;
///
/// // What `std::fs::File::create` does.
/// const CREATE: OpenOptions = OpenOptions::new().write(true).create(true).truncate(true);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct OpenOptions {
    pub(crate) read: bool,
    pub(crate) write: bool,
    pub(crate) append: bool,
    pub(crate) create: bool,
    pub(crate) create_new: bool,
    pub(crate) truncate: bool,
    pub(crate) no_follow: bool,
    pub(crate) directory: bool,
    pub(crate) mode: u32,
    /// Set by `windows::OpenOptionsExt`.
    #[cfg(windows)]
    pub(crate) execute: bool,
}

impl OpenOptions {
    /// Options that open nothing yet: at least one of [`read`](Self::read),
    /// [`write`](Self::write) and [`append`](Self::append) must be set.
    #[inline]
    pub const fn new() -> Self {
        Self {
            read: false,
            write: false,
            append: false,
            create: false,
            create_new: false,
            truncate: false,
            no_follow: false,
            directory: false,
            mode: 0o666,
            #[cfg(windows)]
            execute: false,
        }
    }

    /// Opens the file for reading.
    #[inline]
    pub const fn read(mut self, read: bool) -> Self {
        self.read = read;
        self
    }

    /// Opens the file for writing.
    #[inline]
    pub const fn write(mut self, write: bool) -> Self {
        self.write = write;
        self
    }

    /// Opens the file for appending: every write goes to the end of the
    /// file, atomically, wherever the handle's position is. Implies write
    /// access, and cannot be combined with [`truncate`](Self::truncate).
    #[inline]
    pub const fn append(mut self, append: bool) -> Self {
        self.append = append;
        self
    }

    /// Creates the file if it does not exist. Needs write or append access.
    #[inline]
    pub const fn create(mut self, create: bool) -> Self {
        self.create = create;
        self
    }

    /// Creates the file, and fails with [`ErrorKind::AlreadyExists`] if
    /// anything has that name already, a symbolic link included. The check
    /// and the creation are one atomic step. Needs write or append access;
    /// [`create`](Self::create) and [`truncate`](Self::truncate) are then
    /// ignored.
    #[inline]
    pub const fn create_new(mut self, create_new: bool) -> Self {
        self.create_new = create_new;
        self
    }

    /// Empties the file if it exists. Needs write access.
    #[inline]
    pub const fn truncate(mut self, truncate: bool) -> Self {
        self.truncate = truncate;
        self
    }

    /// Fails with [`ErrorKind::FilesystemLoop`] if the last component of the
    /// path is a symbolic link, instead of opening what it points to. Links
    /// in the directories leading to it are still followed.
    ///
    /// `O_NOFOLLOW` on Linux and macOS. On Windows the link itself is opened
    /// (`FILE_FLAG_OPEN_REPARSE_POINT`), recognised and refused. On WASI the
    /// path is looked at before it is opened, as not every host refuses a
    /// link by itself: the check and the open are two steps there.
    #[inline]
    pub const fn no_follow(mut self, no_follow: bool) -> Self {
        self.no_follow = no_follow;
        self
    }

    /// Opens a directory, and fails with [`ErrorKind::NotADirectory`] if the
    /// path names anything else. Only read access may be asked for.
    ///
    /// The handle can be listed ([`Dir::from_handle`]), described
    /// ([`handle_metadata`]) and synchronised, not read or written.
    /// `O_DIRECTORY` on Linux, macOS and WASI, `FILE_FLAG_BACKUP_SEMANTICS`
    /// on Windows.
    ///
    /// Without this option a directory is opened for reading by Linux,
    /// macOS and WASI all the same, and refused by Windows
    /// ([`ErrorKind::IsADirectory`]). Opening one for writing fails with
    /// [`ErrorKind::IsADirectory`] everywhere.
    #[inline]
    pub const fn directory(mut self, directory: bool) -> Self {
        self.directory = directory;
        self
    }

    /// The Unix permission bits a file is created with, if it is created;
    /// `0o666` by default. The process's `umask` is applied to them.
    ///
    /// Windows and WASI have no such permissions and ignore it.
    #[inline]
    pub const fn mode(mut self, mode: u32) -> Self {
        self.mode = mode;
        self
    }

    /// The checks that are the same on every platform.
    pub(crate) fn check(&self) -> Result<()> {
        let writes = self.write || self.append;
        let truncate = self.truncate && !self.create_new;
        let valid = if self.directory {
            self.read && !writes && !self.create && !self.create_new && !self.truncate
        } else {
            (self.read || writes)
                && (writes || !(self.create || self.create_new || self.truncate))
                && !(truncate && (self.append || !self.write))
        };
        if valid {
            Ok(())
        } else {
            Err(ErrorKind::InvalidInput.into())
        }
    }
}

impl Default for OpenOptions {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

/// Opens a file, or a directory, and returns a handle to it.
///
/// The handle is private to the process (close-on-exec, not inheritable).
/// On Windows the file is opened with every sharing mode, like `std` does:
/// it can be opened again, renamed and deleted while the handle is open.
///
/// `openat` on Linux, `open` on macOS, `CreateFileW` on Windows,
/// `path_open` on WASI.
///
/// # Errors
///
/// [`ErrorKind::InvalidInput`] if the options make no sense together: no
/// access at all, creating or truncating without write access, truncating
/// when appending, or more than read access to a directory. Otherwise what
/// the system reports, [`ErrorKind::NotFound`], [`ErrorKind::AlreadyExists`]
/// and [`ErrorKind::PermissionDenied`] being the common ones.
#[inline]
pub fn open<P: AsPath + ?Sized>(path: &P, options: &OpenOptions) -> Result<OwnedHandle> {
    options.check()?;
    sys::fs::open(path.as_path_bytes(), options)
}

/// Checks the path given to one of the `_at` functions: relative, and
/// without `..`.
fn relative(path: &[u8]) -> Result<&[u8]> {
    // As everywhere else: the empty path names nothing.
    let Some(&first) = path.first() else {
        return Err(ErrorKind::NotFound.into());
    };
    if path.contains(&0)
        || sys::fs::is_separator(first)
        || path
            .split(|&c| sys::fs::is_separator(c))
            .any(|component| component == b"..")
    {
        return Err(ErrorKind::InvalidInput.into());
    }
    Ok(path)
}

/// As [`open`], with `path` relative to the open directory `dir`: see
/// [the module's documentation](self#working-under-a-directory) for what
/// the path may be.
///
/// With [`OpenOptions::no_follow`], or a name `dir` was just listed to
/// have, what is opened is what `dir` holds: this is how a tree is walked
/// without following a link out of it.
///
/// `openat` on Linux and macOS, `path_open` on WASI, `NtCreateFile` on
/// Windows.
///
/// # Errors
///
/// As [`open`], and [`ErrorKind::InvalidInput`] for a path that is absolute
/// or has a `..` component.
#[inline]
pub fn open_at<P: AsPath + ?Sized>(
    dir: impl AsHandle,
    path: &P,
    options: &OpenOptions,
) -> Result<OwnedHandle> {
    options.check()?;
    sys::fs::open_at(dir.as_handle(), relative(path.as_path_bytes())?, options)
}

/// What kind of object a path or a handle names.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FileType {
    /// A regular file.
    File,
    /// A directory.
    Directory,
    /// A symbolic link. On Windows, a junction is one too.
    Symlink,
    /// A block device.
    BlockDevice,
    /// A character device: a terminal, `/dev/null`, a Windows console.
    CharDevice,
    /// A pipe or a FIFO.
    Fifo,
    /// A socket.
    Socket,
    /// Something else, or something the system did not identify.
    Unknown,
}

/// The permissions of a file, as Unix permission bits.
///
/// Linux and macOS store these twelve bits (`rwxrwxrwx`, and set-user-ID,
/// set-group-ID and sticky above them) with each file. Windows only has a
/// read-only attribute: a file's permissions read as `0o666`, or `0o444`
/// when it is read-only (`0o777` and `0o555` for a directory), and setting
/// permissions makes the file read-only when no write bit is set. WASI has
/// no permissions at all: they read as `0o666` or `0o777`, and cannot be
/// set.
///
/// [`readonly`](Self::readonly) is the part every system agrees on.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Permissions(u32);

impl Permissions {
    /// Permissions from Unix permission bits; other bits are dropped.
    #[inline]
    pub const fn from_mode(mode: u32) -> Self {
        Self(mode & 0o7777)
    }

    /// The Unix permission bits.
    #[inline]
    pub const fn mode(self) -> u32 {
        self.0
    }

    /// Whether nobody is allowed to write: no write bit is set.
    ///
    /// The system may still let this process write (the superuser on Unix),
    /// or stop it for other reasons.
    #[inline]
    pub const fn readonly(self) -> bool {
        self.0 & 0o222 == 0
    }

    /// Removes every write bit (`true`), or gives the owner the right to
    /// write (`false`). The other bits are kept.
    #[inline]
    pub const fn set_readonly(&mut self, readonly: bool) {
        if readonly {
            self.0 &= !0o222;
        } else {
            self.0 |= 0o200;
        }
    }
}

impl fmt::Debug for Permissions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Permissions({:#o})", self.0)
    }
}

/// What the system knows about a file: see [`metadata`],
/// [`symlink_metadata`] and [`handle_metadata`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Metadata {
    pub(crate) file_type: FileType,
    pub(crate) len: u64,
    pub(crate) mode: u32,
    pub(crate) modified: Timestamp,
    pub(crate) accessed: Timestamp,
    pub(crate) created: Option<Timestamp>,
    pub(crate) links: u64,
    pub(crate) device: u64,
    pub(crate) inode: u64,
    /// What the system has that is not portable: the whole `st_mode` on
    /// Linux and macOS, the file attributes on Windows.
    pub(crate) raw: u32,
    /// What only Linux and macOS have: see `unix::MetadataExt`. Zero
    /// elsewhere.
    pub(crate) unix: UnixMetadata,
}

/// The part of the metadata that only Linux and macOS have.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub(crate) struct UnixMetadata {
    pub(crate) uid: u32,
    pub(crate) gid: u32,
    pub(crate) rdev: u64,
    pub(crate) blocks: u64,
    pub(crate) block_size: u32,
}

impl Metadata {
    /// The kind of object.
    #[inline]
    pub const fn file_type(&self) -> FileType {
        self.file_type
    }

    /// Whether it is a regular file.
    #[inline]
    pub const fn is_file(&self) -> bool {
        matches!(self.file_type, FileType::File)
    }

    /// Whether it is a directory.
    #[inline]
    pub const fn is_dir(&self) -> bool {
        matches!(self.file_type, FileType::Directory)
    }

    /// Whether it is a symbolic link, which only [`symlink_metadata`]
    /// reports.
    #[inline]
    pub const fn is_symlink(&self) -> bool {
        matches!(self.file_type, FileType::Symlink)
    }

    /// The size of a file in bytes. For anything else the value is the
    /// system's own and means little.
    #[inline]
    #[allow(clippy::len_without_is_empty)]
    pub const fn len(&self) -> u64 {
        self.len
    }

    /// The permissions.
    #[inline]
    pub const fn permissions(&self) -> Permissions {
        Permissions(self.mode)
    }

    /// When the content was last modified.
    #[inline]
    pub const fn modified(&self) -> Timestamp {
        self.modified
    }

    /// When the content was last read. Most systems update it lazily, or
    /// not at all.
    #[inline]
    pub const fn accessed(&self) -> Timestamp {
        self.accessed
    }

    /// When the file was created, if the system and the filesystem record
    /// it: always on Windows and macOS, on most filesystems on Linux, never
    /// on WASI.
    #[inline]
    pub const fn created(&self) -> Option<Timestamp> {
        self.created
    }

    /// The number of hard links to the file: of names it has.
    #[inline]
    pub const fn links(&self) -> u64 {
        self.links
    }

    /// The identifier of the filesystem or volume the file is on: `st_dev`
    /// on Linux and macOS (as `std` reports it), the volume serial number
    /// on Windows.
    #[inline]
    pub const fn device(&self) -> u64 {
        self.device
    }

    /// The identifier of the file within its [`device`](Self::device): the
    /// inode number on Linux, macOS and WASI, the file index on Windows.
    /// Two paths or handles with the same device and inode are the same
    /// file.
    #[inline]
    pub const fn inode(&self) -> u64 {
        self.inode
    }
}

/// The metadata of what `path` names, following symbolic links.
///
/// `statx` on Linux, `stat` on macOS, `path_filestat_get` on WASI. On
/// Windows the file is opened to be queried (`GetFileInformationByHandle`).
#[inline]
pub fn metadata<P: AsPath + ?Sized>(path: &P) -> Result<Metadata> {
    sys::fs::metadata(path.as_path_bytes(), true)
}

/// The metadata of what `path` names, without following a symbolic link in
/// its last component: a link is described itself.
#[inline]
pub fn symlink_metadata<P: AsPath + ?Sized>(path: &P) -> Result<Metadata> {
    sys::fs::metadata(path.as_path_bytes(), false)
}

/// As [`metadata`], with `path` relative to the open directory `dir`: see
/// [the module's documentation](self#working-under-a-directory).
///
/// `statx` on Linux, `fstatat` on macOS, `path_filestat_get` on WASI. On
/// Windows the file is opened (`NtCreateFile`) to be queried.
#[inline]
pub fn metadata_at<P: AsPath + ?Sized>(dir: impl AsHandle, path: &P) -> Result<Metadata> {
    sys::fs::metadata_at(dir.as_handle(), relative(path.as_path_bytes())?, true)
}

/// As [`symlink_metadata`], with `path` relative to the open directory
/// `dir`: see [the module's documentation](self#working-under-a-directory).
#[inline]
pub fn symlink_metadata_at<P: AsPath + ?Sized>(dir: impl AsHandle, path: &P) -> Result<Metadata> {
    sys::fs::metadata_at(dir.as_handle(), relative(path.as_path_bytes())?, false)
}

/// The metadata of an open file or directory.
///
/// A pipe or a terminal is described too, as far as its type goes.
#[inline]
pub fn handle_metadata(handle: impl AsHandle) -> Result<Metadata> {
    sys::fs::handle_metadata(handle.as_handle())
}

/// Sets the size of an open file: it is cut, or extended with zeroes. The
/// handle must be open for writing; its position does not move.
///
/// `ftruncate` on Linux and macOS, `SetFileInformationByHandle` on Windows,
/// `fd_filestat_set_size` on WASI.
#[inline]
pub fn set_len(handle: impl AsHandle, len: u64) -> Result<()> {
    if len > i64::MAX as u64 {
        return Err(ErrorKind::InvalidInput.into());
    }
    sys::fs::set_len(handle.as_handle(), len)
}

/// Waits until the content and the metadata of an open file are on the
/// storage device.
///
/// `fsync` on Linux, `FlushFileBuffers` on Windows, `fd_sync` on WASI. On
/// macOS, `fcntl(F_FULLFSYNC)`, as `fsync` there does not ask the device to
/// flush its cache; `fsync` is the fallback for the filesystems that lack
/// it.
#[inline]
pub fn sync_all(handle: impl AsHandle) -> Result<()> {
    sys::fs::sync(handle.as_handle(), false)
}

/// As [`sync_all`], but metadata that is not needed to read the content
/// back (the timestamps) may be left for later, which can save a write.
///
/// `fdatasync` on Linux, `fd_datasync` on WASI. The same as [`sync_all`] on
/// macOS and Windows.
#[inline]
pub fn sync_data(handle: impl AsHandle) -> Result<()> {
    sys::fs::sync(handle.as_handle(), true)
}

/// Reserves storage for an open file: after the call the file is at least
/// `len` bytes long, and the filesystem has set aside the space those bytes
/// take, so that writing them later does not fail for lack of space.
///
/// The file is never made shorter and its content is kept; bytes added to
/// it read as zeroes. The handle must be open for writing; its position
/// does not move. Unlike [`set_len`], which only records a size and leaves
/// a hole where the filesystem can, this fails with
/// [`ErrorKind::StorageFull`] when the space is not there.
///
/// - Linux: `fallocate`. A filesystem that cannot reserve space fails with
///   [`ErrorKind::Unsupported`] (ZFS, NFS before 4.2, some FUSE ones).
/// - macOS: `fcntl(F_PREALLOCATE)` for what the file lacks beyond the
///   space it already has, then `ftruncate`. Holes that are already inside
///   the file stay holes.
/// - Windows: `SetFileInformationByHandle` (`FileAllocationInfo`, then
///   `FileEndOfFileInfo`). A sparse file may keep its holes.
/// - WASI: `fd_allocate`, which hosts implement as they can: one may fail
///   with [`ErrorKind::Unsupported`], another only make the file longer
///   without reserving anything.
#[inline]
pub fn allocate(handle: impl AsHandle, len: u64) -> Result<()> {
    if len > i64::MAX as u64 {
        return Err(ErrorKind::InvalidInput.into());
    }
    let handle = handle.as_handle();
    if len == 0 {
        // Nothing to reserve, which some systems refuse to be asked: only
        // the handle is checked.
        return sys::fs::handle_metadata(handle).map(drop);
    }
    sys::fs::allocate(handle, len)
}

/// Sets the permissions of what `path` names, following symbolic links.
///
/// `fchmodat` on Linux, `chmod` on macOS. On Windows only the read-only
/// attribute is changed: see [`Permissions`].
///
/// WASI has no permissions: fails with [`ErrorKind::Unsupported`].
#[inline]
pub fn set_permissions<P: AsPath + ?Sized>(path: &P, permissions: Permissions) -> Result<()> {
    sys::fs::set_permissions(path.as_path_bytes(), permissions.0)
}

/// As [`set_permissions`], with `path` relative to the open directory
/// `dir`: see [the module's documentation](self#working-under-a-directory).
///
/// `fchmodat` on Linux and macOS. On Windows the file is opened
/// (`NtCreateFile`) to have its read-only attribute changed.
///
/// WASI has no permissions: fails with [`ErrorKind::Unsupported`].
#[inline]
pub fn set_permissions_at<P: AsPath + ?Sized>(
    dir: impl AsHandle,
    path: &P,
    permissions: Permissions,
) -> Result<()> {
    sys::fs::set_permissions_at(
        dir.as_handle(),
        relative(path.as_path_bytes())?,
        permissions.0,
    )
}

/// Sets the permissions of an open file.
///
/// `fchmod` on Linux and macOS. On Windows only the read-only attribute is
/// changed (see [`Permissions`]), and the handle must be open for writing.
///
/// WASI has no permissions: fails with [`ErrorKind::Unsupported`].
#[inline]
pub fn set_handle_permissions(handle: impl AsHandle, permissions: Permissions) -> Result<()> {
    sys::fs::set_handle_permissions(handle.as_handle(), permissions.0)
}

/// The timestamps to give a file: see [`set_times`]. Those that are not
/// set are left as they are.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct FileTimes {
    pub(crate) accessed: Option<Timestamp>,
    pub(crate) modified: Option<Timestamp>,
}

impl FileTimes {
    /// No timestamp to change.
    #[inline]
    pub const fn new() -> Self {
        Self {
            accessed: None,
            modified: None,
        }
    }

    /// Sets the time of last access.
    #[inline]
    pub const fn accessed(mut self, time: Timestamp) -> Self {
        self.accessed = Some(time);
        self
    }

    /// Sets the time of last modification.
    #[inline]
    pub const fn modified(mut self, time: Timestamp) -> Self {
        self.modified = Some(time);
        self
    }

    fn check(&self) -> Result<()> {
        for time in [self.accessed, self.modified].into_iter().flatten() {
            if time.nanos >= 1_000_000_000 {
                return Err(ErrorKind::InvalidInput.into());
            }
        }
        Ok(())
    }
}

/// Sets the access and modification times of what `path` names, following
/// symbolic links.
///
/// The filesystem keeps what precision it has: 100 ns on NTFS, one
/// nanosecond on most others, two seconds on FAT. A time the system cannot
/// represent (before 1601 on Windows, before 1970 on WASI) fails with
/// [`ErrorKind::InvalidInput`], as does a [`Timestamp`] whose nanoseconds
/// are not below one second.
///
/// `utimensat` on Linux and macOS, `SetFileTime` on Windows,
/// `path_filestat_set_times` on WASI.
#[inline]
pub fn set_times<P: AsPath + ?Sized>(path: &P, times: FileTimes) -> Result<()> {
    times.check()?;
    sys::fs::set_times(path.as_path_bytes(), &times)
}

/// As [`set_times`], with `path` relative to the open directory `dir`: see
/// [the module's documentation](self#working-under-a-directory).
#[inline]
pub fn set_times_at<P: AsPath + ?Sized>(
    dir: impl AsHandle,
    path: &P,
    times: FileTimes,
) -> Result<()> {
    times.check()?;
    sys::fs::set_times_at(dir.as_handle(), relative(path.as_path_bytes())?, &times)
}

/// Sets the access and modification times of an open file: see
/// [`set_times`]. On Windows the handle must be open for writing.
#[inline]
pub fn set_handle_times(handle: impl AsHandle, times: FileTimes) -> Result<()> {
    times.check()?;
    sys::fs::set_handle_times(handle.as_handle(), &times)
}

/// The kind of a file lock: see [`lock`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LockKind {
    /// A lock any number of holders can share, as long as nobody holds an
    /// exclusive one.
    Shared,
    /// A lock only one holder can have, and only when nobody holds a shared
    /// one.
    Exclusive,
}

/// Locks an open file as a whole, waiting for as long as other holders
/// are in the way.
///
/// The lock belongs to the open file: to this handle and to its
/// [duplicates](crate::io::duplicate). It conflicts with the locks taken
/// through any other open of the same file, in this process or in another,
/// and is released by [`unlock`] or when the last of those handles is
/// closed.
///
/// `flock` on Linux and macOS, `LockFileEx` on Windows. They differ in
/// what could not be hidden:
///
/// - On Linux and macOS the lock is advisory: it only stops other lockers,
///   and reads and writes ignore it. On Windows it is mandatory: reading or
///   writing the file through another handle fails with
///   [`ErrorKind::ResourceBusy`] while it is locked (writing only, under a
///   shared lock).
/// - On Linux and macOS, locking a handle that holds a lock already
///   converts the lock to the kind asked. On Windows a second lock is
///   stacked on the first, or waits for it forever if they conflict: unlock
///   before locking again.
///
/// WASI has no file locks: fails with [`ErrorKind::Unsupported`].
#[inline]
pub fn lock(handle: impl AsHandle, kind: LockKind) -> Result<()> {
    sys::fs::lock(handle.as_handle(), kind, true).map(drop)
}

/// As [`lock`], without waiting: returns `false` when the lock is held by
/// someone else in a way that conflicts, and `true` once the lock is taken.
#[inline]
pub fn try_lock(handle: impl AsHandle, kind: LockKind) -> Result<bool> {
    sys::fs::lock(handle.as_handle(), kind, false)
}

/// Releases the lock taken on an open file with [`lock`] or [`try_lock`].
/// Unlocking a file that is not locked does nothing.
///
/// WASI has no file locks: fails with [`ErrorKind::Unsupported`].
#[inline]
pub fn unlock(handle: impl AsHandle) -> Result<()> {
    sys::fs::unlock(handle.as_handle())
}

/// Creates a directory. Its parent must exist; fails with
/// [`ErrorKind::AlreadyExists`] if anything has that name already.
///
/// On Linux and macOS the directory gets the permissions `0o777` less the
/// process's `umask`: see [`create_dir_with_mode`].
#[inline]
pub fn create_dir<P: AsPath + ?Sized>(path: &P) -> Result<()> {
    sys::fs::create_dir(path.as_path_bytes(), 0o777)
}

/// As [`create_dir`], with the Unix permission bits of the new directory
/// (the process's `umask` is applied to them): `0o700` makes it private to
/// its owner from the start.
///
/// Windows and WASI have no such permissions and ignore `mode`.
#[inline]
pub fn create_dir_with_mode<P: AsPath + ?Sized>(path: &P, mode: u32) -> Result<()> {
    sys::fs::create_dir(path.as_path_bytes(), mode)
}

/// As [`create_dir`], with `path` relative to the open directory `dir`: see
/// [the module's documentation](self#working-under-a-directory).
///
/// `mkdirat` on Linux and macOS, `path_create_directory` on WASI,
/// `NtCreateFile` on Windows.
#[inline]
pub fn create_dir_at<P: AsPath + ?Sized>(dir: impl AsHandle, path: &P) -> Result<()> {
    sys::fs::create_dir_at(dir.as_handle(), relative(path.as_path_bytes())?, 0o777)
}

/// As [`create_dir_at`], with the Unix permission bits of the new
/// directory: see [`create_dir_with_mode`].
#[inline]
pub fn create_dir_at_with_mode<P: AsPath + ?Sized>(
    dir: impl AsHandle,
    path: &P,
    mode: u32,
) -> Result<()> {
    sys::fs::create_dir_at(dir.as_handle(), relative(path.as_path_bytes())?, mode)
}

/// Removes an empty directory.
///
/// Fails with [`ErrorKind::DirectoryNotEmpty`] if it has entries, and with
/// [`ErrorKind::NotADirectory`] if the path names something else. On
/// Windows, a symbolic link to a directory is removed with this function,
/// not with [`remove_file`].
#[inline]
pub fn remove_dir<P: AsPath + ?Sized>(path: &P) -> Result<()> {
    sys::fs::remove_dir(path.as_path_bytes())
}

/// As [`remove_dir`], with `path` relative to the open directory `dir`: see
/// [the module's documentation](self#working-under-a-directory).
///
/// `unlinkat` on Linux and macOS, `path_remove_directory` on WASI. On
/// Windows the directory is opened (`NtCreateFile`) and marked for deletion.
#[inline]
pub fn remove_dir_at<P: AsPath + ?Sized>(dir: impl AsHandle, path: &P) -> Result<()> {
    sys::fs::remove_dir_at(dir.as_handle(), relative(path.as_path_bytes())?)
}

/// Removes a file: the name, and the file itself once it has no other name
/// and nothing has it open. A symbolic link is removed itself, not what it
/// points to.
///
/// Fails with [`ErrorKind::IsADirectory`] if the path names a directory.
///
/// On Windows a file with the read-only attribute cannot be removed
/// ([`ErrorKind::PermissionDenied`]), while Linux and macOS only look at
/// the permissions of the directory.
#[inline]
pub fn remove_file<P: AsPath + ?Sized>(path: &P) -> Result<()> {
    sys::fs::remove_file(path.as_path_bytes())
}

/// As [`remove_file`], with `path` relative to the open directory `dir`:
/// see [the module's documentation](self#working-under-a-directory).
///
/// `unlinkat` on Linux and macOS, `path_unlink_file` on WASI. On Windows
/// the file is opened (`NtCreateFile`) and marked for deletion.
#[inline]
pub fn remove_file_at<P: AsPath + ?Sized>(dir: impl AsHandle, path: &P) -> Result<()> {
    sys::fs::remove_file_at(dir.as_handle(), relative(path.as_path_bytes())?)
}

/// Renames a file or a directory, moving it between directories of the same
/// filesystem if need be.
///
/// If `to` exists and is a file, it is replaced, atomically: at every
/// moment `to` names either the old file or the new one. On Linux and macOS
/// an empty directory can be replaced by a directory in the same way;
/// Windows refuses to replace a directory.
///
/// Fails with [`ErrorKind::CrossesDevices`] if the two paths are not on the
/// same filesystem.
///
/// `renameat2` on Linux, `rename` on macOS, `MoveFileExW` with
/// `MOVEFILE_REPLACE_EXISTING` on Windows, `path_rename` on WASI.
#[inline]
pub fn rename<P: AsPath + ?Sized, Q: AsPath + ?Sized>(from: &P, to: &Q) -> Result<()> {
    sys::fs::rename(from.as_path_bytes(), to.as_path_bytes())
}

/// As [`rename`], with `from` relative to the open directory `from_dir` and
/// `to` to the open directory `to_dir`, which may be the same: see
/// [the module's documentation](self#working-under-a-directory).
///
/// `renameat2` on Linux, `renameat` on macOS, `path_rename` on WASI. On
/// Windows, `from` is opened (`NtCreateFile`) and renamed with
/// `NtSetInformationFile` (`FileRenameInformation`), which is what
/// `MoveFileExW` does.
#[inline]
pub fn rename_at<P: AsPath + ?Sized, Q: AsPath + ?Sized>(
    from_dir: impl AsHandle,
    from: &P,
    to_dir: impl AsHandle,
    to: &Q,
) -> Result<()> {
    sys::fs::rename_at(
        from_dir.as_handle(),
        relative(from.as_path_bytes())?,
        to_dir.as_handle(),
        relative(to.as_path_bytes())?,
    )
}

/// Copies the content of the file `from` to the file `to`, which is created
/// if it does not exist and overwritten if it does, and returns the number
/// of bytes copied. Symbolic links are followed, in both paths. A file
/// that exists is written in place: it stays the same file, and its other
/// names see the new content.
///
/// The permissions of `from` are given to `to`. What else comes along
/// depends on the system: nothing on Linux and WASI; on macOS and Windows
/// also the modification time and the extended attributes or alternate
/// streams.
///
/// This is one of the few functions of oscall that is not one system call:
/// it is here because the system can copy a file in ways a program cannot
/// with reads and writes of its own. Blocks are shared instead of copied
/// where the filesystem can (Btrfs, XFS, APFS, ReFS), and a network
/// filesystem copies on the server.
///
/// - Linux: `copy_file_range` until the end of the file, and reads and
///   writes where it does not apply (across filesystems on old kernels, on
///   special files).
/// - macOS: `fclonefileat` when `to` does not exist, `fcopyfile` otherwise
///   or where a file cannot be cloned.
/// - Windows: `CopyFileExW`.
/// - WASI: reads and writes.
///
/// Since it loops, a call interrupted by a signal is resumed, not reported.
/// If it fails half way, `to` is left with what was copied so far.
///
/// # Errors
///
/// [`ErrorKind::IsADirectory`] if `from` is a directory, and
/// [`ErrorKind::InvalidInput`] if `from` and `to` are the same file, which
/// is left as it is.
#[inline]
pub fn copy<P: AsPath + ?Sized, Q: AsPath + ?Sized>(from: &P, to: &Q) -> Result<u64> {
    sys::fs::copy(from.as_path_bytes(), to.as_path_bytes())
}

/// Copies what remains to be read from `from` to `to`, with reads and
/// writes: what the backends without a call for it use, or fall back to.
#[allow(dead_code)]
pub(crate) fn copy_loop(from: BorrowedHandle<'_>, to: BorrowedHandle<'_>) -> Result<u64> {
    let interrupted = |error: &crate::Error| error.kind() == ErrorKind::Interrupted;
    let mut buf = [0u8; 16 * 1024];
    let mut total = 0u64;
    loop {
        let len = match sys::io::read(from, &mut buf) {
            Ok(0) => return Ok(total),
            Ok(len) => len,
            Err(error) if interrupted(&error) => continue,
            Err(error) => return Err(error),
        };
        let mut data = &buf[..len];
        while !data.is_empty() {
            match sys::io::write(to, data) {
                // A destination that takes nothing more, and does not say
                // why.
                Ok(0) => return Err(ErrorKind::StorageFull.into()),
                Ok(written) => data = &data[written.min(data.len())..],
                Err(error) if interrupted(&error) => {}
                Err(error) => return Err(error),
            }
        }
        total += len as u64;
    }
}

/// How much room a filesystem has: see [`space`] and [`handle_space`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Space {
    pub(crate) total: u64,
    pub(crate) free: u64,
    pub(crate) available: u64,
}

impl Space {
    /// The size of the filesystem, in bytes.
    #[inline]
    pub const fn total(&self) -> u64 {
        self.total
    }

    /// The bytes nothing uses. Not all of them may be for this process to
    /// use: see [`available`](Self::available).
    #[inline]
    pub const fn free(&self) -> u64 {
        self.free
    }

    /// The bytes this process may still use: the free ones less those kept
    /// for the superuser (Linux, macOS), or what the quota of the user
    /// leaves (Windows).
    #[inline]
    pub const fn available(&self) -> u64 {
        self.available
    }
}

/// The room on the filesystem that holds what `path` names: a file or a
/// directory, anywhere on it.
///
/// `statfs` on Linux and macOS. On Windows the path is opened to be asked
/// (`NtQueryVolumeInformationFile`), as `GetDiskFreeSpaceExW` only takes a
/// directory.
///
/// WASI cannot tell: fails with [`ErrorKind::Unsupported`].
#[inline]
pub fn space<P: AsPath + ?Sized>(path: &P) -> Result<Space> {
    sys::fs::space(path.as_path_bytes())
}

/// The room on the filesystem an open file or directory is on: see
/// [`space`].
///
/// `fstatfs` on Linux and macOS, `NtQueryVolumeInformationFile` on Windows.
///
/// WASI cannot tell: fails with [`ErrorKind::Unsupported`].
#[inline]
pub fn handle_space(handle: impl AsHandle) -> Result<Space> {
    sys::fs::handle_space(handle.as_handle())
}

/// Gives the file `original` a second name, `link`, on the same filesystem.
/// The two names are then equals: the file lives until both are removed.
///
/// A symbolic link is not followed on Linux, macOS and WASI: the new name
/// is another name for the link itself.
#[inline]
pub fn hard_link<P: AsPath + ?Sized, Q: AsPath + ?Sized>(original: &P, link: &Q) -> Result<()> {
    sys::fs::hard_link(original.as_path_bytes(), link.as_path_bytes())
}

/// As [`hard_link`], with `original` relative to the open directory
/// `original_dir` and `link` to the open directory `link_dir`, which may be
/// the same: see [the module's documentation](self#working-under-a-directory).
///
/// `linkat` on Linux and macOS, `path_link` on WASI. On Windows, `original`
/// is opened (`NtCreateFile`) and named again with `NtSetInformationFile`
/// (`FileLinkInformation`).
#[inline]
pub fn hard_link_at<P: AsPath + ?Sized, Q: AsPath + ?Sized>(
    original_dir: impl AsHandle,
    original: &P,
    link_dir: impl AsHandle,
    link: &Q,
) -> Result<()> {
    sys::fs::hard_link_at(
        original_dir.as_handle(),
        relative(original.as_path_bytes())?,
        link_dir.as_handle(),
        relative(link.as_path_bytes())?,
    )
}

/// Creates the symbolic link `link`, which points to `target`.
///
/// `target` is stored as it is given and need not exist; a relative one is
/// relative to the directory `link` is in.
///
/// Windows has two kinds of symbolic links, for files and for directories,
/// and a link of the wrong kind does not work. The kind is chosen by
/// looking at `target` when the link is created: a directory link if it is
/// a directory at that moment, a file link otherwise (so also when it does
/// not exist yet). Creating a link there also needs a privilege, or the
/// developer mode of Windows: without it the call fails with
/// [`ErrorKind::PermissionDenied`]. And `target` should use `\` as its
/// separator: Windows does not translate `/` in what a link holds.
///
/// On WASI, hosts refuse absolute targets, and some of them any target
/// that goes up to a parent directory.
#[inline]
pub fn symlink<P: AsPath + ?Sized, Q: AsPath + ?Sized>(target: &P, link: &Q) -> Result<()> {
    sys::fs::symlink(target.as_path_bytes(), link.as_path_bytes())
}

/// As [`symlink`], with `link` relative to the open directory `dir`: see
/// [the module's documentation](self#working-under-a-directory). `target`
/// is stored as it is given, whatever it is: only `link` is checked.
///
/// `symlinkat` on Linux and macOS, `path_symlink` on WASI. Windows has no
/// call for this: the link is created as an empty file or directory
/// (`NtCreateFile`), then made a link (`FSCTL_SET_REPARSE_POINT`), and
/// removed again if that fails. What [`symlink`] says of Windows holds
/// here too: the kind of the link is chosen by looking at `target`, and a
/// privilege or the developer mode is needed.
#[inline]
pub fn symlink_at<P: AsPath + ?Sized, Q: AsPath + ?Sized>(
    target: &P,
    dir: impl AsHandle,
    link: &Q,
) -> Result<()> {
    sys::fs::symlink_at(
        target.as_path_bytes(),
        dir.as_handle(),
        relative(link.as_path_bytes())?,
    )
}

/// Reads what the symbolic link `path` points to into `buf`, and returns
/// its length.
///
/// The target is returned as the link stores it. On Windows it is WTF-8,
/// a junction is read like a link, and the `\??\` prefix of an absolute
/// target is removed, as `std` does.
///
/// # Errors
///
/// [`ErrorKind::InvalidInput`] if `path` is not a symbolic link, and
/// [`ErrorKind::BufferTooSmall`] if the target does not fit in `buf`, which
/// on Linux, macOS and WASI needs one byte more than the target is long.
#[inline]
pub fn read_link<P: AsPath + ?Sized>(path: &P, buf: &mut [u8]) -> Result<usize> {
    sys::fs::read_link(path.as_path_bytes(), buf)
}

/// As [`read_link`], with `path` relative to the open directory `dir`: see
/// [the module's documentation](self#working-under-a-directory).
///
/// `readlinkat` on Linux and macOS, `path_readlink` on WASI. On Windows the
/// link is opened (`NtCreateFile`) to be read.
#[inline]
pub fn read_link_at<P: AsPath + ?Sized>(
    dir: impl AsHandle,
    path: &P,
    buf: &mut [u8],
) -> Result<usize> {
    sys::fs::read_link_at(dir.as_handle(), relative(path.as_path_bytes())?, buf)
}

/// Writes the absolute path of what `path` names into `buf`, with every
/// symbolic link resolved and no `.` or `..` left, and returns its length.
/// The path must exist.
///
/// On Windows the result is WTF-8 and in the extended form
/// (`\\?\C:\dir\file`), as with `std`: `GetFinalPathNameByHandleW`. macOS
/// uses `realpath`. Linux has no system call for this: the path is walked
/// with `readlinkat`, one component at a time, and may be up to 4095 bytes
/// long.
///
/// WASI has no absolute paths: fails with [`ErrorKind::Unsupported`].
///
/// # Errors
///
/// [`ErrorKind::BufferTooSmall`] if the result does not fit in `buf`.
#[inline]
pub fn canonicalize<P: AsPath + ?Sized>(path: &P, buf: &mut [u8]) -> Result<usize> {
    sys::fs::canonicalize(path.as_path_bytes(), buf)
}

/// Writes the current directory of the process into `buf`, as an absolute
/// path, and returns its length. On Windows it is WTF-8.
///
/// WASI has no current directory: fails with [`ErrorKind::Unsupported`].
///
/// # Errors
///
/// [`ErrorKind::BufferTooSmall`] if the path does not fit in `buf`, which
/// on Linux and macOS needs one byte more than the path is long.
#[inline]
pub fn current_dir(buf: &mut [u8]) -> Result<usize> {
    sys::fs::current_dir(buf)
}

/// Changes the current directory of the process, which relative paths are
/// relative to. It is shared by every thread.
///
/// WASI has no current directory: fails with [`ErrorKind::Unsupported`].
#[inline]
pub fn set_current_dir<P: AsPath + ?Sized>(path: &P) -> Result<()> {
    sys::fs::set_current_dir(path.as_path_bytes())
}

/// Calls `f` with larger and larger buffers until the path it returns fits.
#[cfg(feature = "alloc")]
fn to_vec(mut f: impl FnMut(&mut [u8]) -> Result<usize>) -> Result<alloc::vec::Vec<u8>> {
    // No path is anywhere near this long.
    const MAX: usize = 1 << 20;

    let mut buf = alloc::vec::Vec::new();
    let mut size = 256;
    loop {
        buf.try_reserve_exact(size - buf.len())
            .map_err(|_| ErrorKind::OutOfMemory)?;
        buf.resize(size, 0);
        match f(&mut buf) {
            Ok(len) => {
                buf.truncate(len);
                return Ok(buf);
            }
            Err(error) if error.kind() == ErrorKind::BufferTooSmall && size < MAX => size *= 2,
            Err(error) => return Err(error),
        }
    }
}

/// As [`read_link`], returning the target in a `Vec`.
#[cfg(feature = "alloc")]
pub fn read_link_vec<P: AsPath + ?Sized>(path: &P) -> Result<alloc::vec::Vec<u8>> {
    to_vec(|buf| read_link(path, buf))
}

/// As [`read_link_at`], returning the target in a `Vec`.
#[cfg(feature = "alloc")]
pub fn read_link_at_vec<P: AsPath + ?Sized>(
    dir: impl AsHandle,
    path: &P,
) -> Result<alloc::vec::Vec<u8>> {
    let dir = dir.as_handle();
    to_vec(|buf| read_link_at(dir, path, buf))
}

/// As [`canonicalize`], returning the path in a `Vec`.
#[cfg(feature = "alloc")]
pub fn canonicalize_vec<P: AsPath + ?Sized>(path: &P) -> Result<alloc::vec::Vec<u8>> {
    to_vec(|buf| canonicalize(path, buf))
}

/// As [`current_dir`], returning the path in a `Vec`.
#[cfg(feature = "alloc")]
pub fn current_dir_vec() -> Result<alloc::vec::Vec<u8>> {
    to_vec(current_dir)
}

/// An open directory, to list its entries.
///
/// It owns the directory's handle and a buffer the system fills with
/// several entries at a time, so that listing allocates nothing. The buffer
/// makes it a few kilobytes large: keep it in place rather than move it
/// around.
///
/// ```no_run
/// # fn main() -> oscall::Result<()> {
/// let mut dir = oscall::fs::Dir::open(".")?;
/// while let Some(entry) = dir.next()? {
///     println!("{}", String::from_utf8_lossy(entry.name()));
/// }
/// # Ok(())
/// # }
/// ```
///
/// `getdents64` on Linux, `getattrlistbulk` on macOS,
/// `NtQueryDirectoryFile` on Windows, `fd_readdir` on WASI.
pub struct Dir(sys::fs::Dir);

impl Dir {
    /// Opens the directory `path` to list it.
    ///
    /// Fails with [`ErrorKind::NotADirectory`] if it is something else.
    pub fn open<P: AsPath + ?Sized>(path: &P) -> Result<Self> {
        const OPTIONS: OpenOptions = OpenOptions::new().read(true).directory(true);
        Ok(Self::from_handle(open(path, &OPTIONS)?))
    }

    /// Opens the directory `path`, relative to the open directory `dir`, to
    /// list it: see [`open_at`].
    pub fn open_at<P: AsPath + ?Sized>(dir: impl AsHandle, path: &P) -> Result<Self> {
        const OPTIONS: OpenOptions = OpenOptions::new().read(true).directory(true);
        Ok(Self::from_handle(open_at(dir, path, &OPTIONS)?))
    }

    /// Lists the directory `handle` is open on: see
    /// [`OpenOptions::directory`].
    ///
    /// The listing goes on from wherever the handle's own position in the
    /// directory is, which is the start for a handle just opened. A handle
    /// that is not a directory makes [`next`](Self::next) fail.
    #[inline]
    pub fn from_handle(handle: OwnedHandle) -> Self {
        Self(sys::fs::Dir::new(handle))
    }

    /// The next entry of the directory, or `None` after the last one.
    ///
    /// The entries come in no particular order; `.` and `..` are not among
    /// them. Whether an entry created or removed while listing is seen is
    /// up to the system. The entry borrows from the `Dir`: copy what is to
    /// be kept before asking for the next one.
    ///
    /// After an error the listing may be continued, but entries may have
    /// been lost.
    #[allow(clippy::should_implement_trait)]
    pub fn next(&mut self) -> Result<Option<DirEntry<'_>>> {
        loop {
            let Some(raw) = self.0.next()? else {
                return Ok(None);
            };
            if !matches!(self.0.name(&raw), b"." | b"..") {
                return Ok(Some(DirEntry {
                    name: self.0.name(&raw),
                    file_type: raw.file_type,
                    inode: raw.inode,
                }));
            }
        }
    }
}

impl AsHandle for Dir {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        self.0.handle()
    }
}

impl fmt::Debug for Dir {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Dir").field(&self.0.handle()).finish()
    }
}

/// An entry of a directory, as the system lists it: see [`Dir::next`].
#[derive(Clone, Copy, Debug)]
pub struct DirEntry<'a> {
    name: &'a [u8],
    file_type: Option<FileType>,
    inode: u64,
}

impl<'a> DirEntry<'a> {
    /// The name of the entry: one path component, not a path. WTF-8 on
    /// Windows.
    #[inline]
    pub const fn name(&self) -> &'a [u8] {
        self.name
    }

    /// The kind of the entry, when the system tells it while listing:
    /// always on Windows and macOS, on most filesystems on Linux and WASI.
    /// A symbolic link is reported as one, not as what it points to.
    ///
    /// When it is `None`, ask [`symlink_metadata`].
    #[inline]
    pub const fn file_type(&self) -> Option<FileType> {
        self.file_type
    }

    /// The identifier of the file: see [`Metadata::inode`]. Zero when the
    /// system does not tell it while listing.
    #[inline]
    pub const fn inode(&self) -> u64 {
        self.inode
    }
}

/// What a backend returns for a directory entry: where its name is in the
/// backend's buffer, and what is known of it.
pub(crate) struct RawDirEntry {
    pub(crate) name: (usize, usize),
    pub(crate) file_type: Option<FileType>,
    pub(crate) inode: u64,
}

/// What only Windows has.
#[cfg(windows)]
pub mod windows {
    mod sealed {
        pub trait Sealed {}
        impl Sealed for crate::fs::OpenOptions {}
    }

    /// The options of [`open`](super::open) that only Windows has.
    ///
    /// It is implemented for [`OpenOptions`](super::OpenOptions) and for
    /// nothing else: methods may be added to it.
    pub trait OpenOptionsExt: sealed::Sealed + Sized {
        /// Asks for the right to execute what the file holds
        /// (`FILE_EXECUTE`), with the access the other options ask for:
        /// what a file must have been opened with to be mapped as code,
        /// [`mem::map_file`](crate::mem::map_file) with
        /// [`Protection::EXECUTE`](crate::mem::Protection::EXECUTE).
        /// Without it that mapping fails with
        /// [`ErrorKind::PermissionDenied`](crate::ErrorKind::PermissionDenied).
        ///
        /// The right is one more that the file must grant its opener: a
        /// file whose access list denies execution is not opened
        /// ([`ErrorKind::PermissionDenied`](crate::ErrorKind::PermissionDenied)).
        /// It is not an access by itself: reading, writing or appending
        /// must still be asked for.
        ///
        /// Linux and macOS have no such right to ask for when a file is
        /// opened: there, a file opened for reading is mapped as code if
        /// its filesystem allows programs at all.
        fn execute(self, execute: bool) -> Self;
    }

    impl OpenOptionsExt for super::OpenOptions {
        #[inline]
        fn execute(mut self, execute: bool) -> Self {
            self.execute = execute;
            self
        }
    }

    /// Windows-specific metadata.
    pub trait MetadataExt {
        /// The file attributes (`FILE_ATTRIBUTE_*`), as the system returned
        /// them. Zero for a handle that is not a file or a directory.
        fn file_attributes(&self) -> u32;
    }

    impl MetadataExt for super::Metadata {
        #[inline]
        fn file_attributes(&self) -> u32 {
            self.raw
        }
    }
}

#[cfg(any(target_os = "linux", target_os = "fullrust"))]
pub mod linux;

/// What Linux and macOS have in common and the other systems lack: the
/// owner of a file, FIFOs, and extended attributes ([`get_xattr`] says
/// what the two systems do not have in common about those).
///
/// [`get_xattr`]: unix::get_xattr
#[cfg(any(target_os = "linux", target_os = "fullrust", target_os = "macos"))]
pub mod unix {
    use crate::{AsHandle, AsPath, Result, sys};

    /// Unix-specific metadata.
    pub trait MetadataExt {
        /// The whole `st_mode`: the file type bits and the permission bits.
        fn raw_mode(&self) -> u32;

        /// The identifier of the user who owns the file.
        fn uid(&self) -> u32;

        /// The identifier of the group the file belongs to.
        fn gid(&self) -> u32;

        /// The device a block or character device file stands for
        /// (`st_rdev`, as `std` reports it); zero for other files, on most
        /// filesystems.
        fn rdev(&self) -> u64;

        /// The storage the file takes, in blocks of 512 bytes whatever the
        /// filesystem's own are: less than its size says for a file with
        /// holes.
        fn blocks(&self) -> u64;

        /// The size of the blocks the system suggests for I/O on the file.
        fn block_size(&self) -> u32;
    }

    impl MetadataExt for super::Metadata {
        #[inline]
        fn raw_mode(&self) -> u32 {
            self.raw
        }

        #[inline]
        fn uid(&self) -> u32 {
            self.unix.uid
        }

        #[inline]
        fn gid(&self) -> u32 {
            self.unix.gid
        }

        #[inline]
        fn rdev(&self) -> u64 {
            self.unix.rdev
        }

        #[inline]
        fn blocks(&self) -> u64 {
            self.unix.blocks
        }

        #[inline]
        fn block_size(&self) -> u32 {
            self.unix.block_size
        }
    }

    /// The identifier that leaves an owner as it is, for the system.
    const UNCHANGED: u32 = u32::MAX;

    /// Changes the user and the group that own what `path` names, following
    /// symbolic links. `None` leaves one as it is.
    ///
    /// Only the superuser can give a file away; its owner can change its
    /// group to one of their own. Anything else fails with
    /// [`ErrorKind::PermissionDenied`](crate::ErrorKind::PermissionDenied).
    ///
    /// `fchownat` on Linux, `chown` on macOS.
    #[inline]
    pub fn chown<P: AsPath + ?Sized>(path: &P, uid: Option<u32>, gid: Option<u32>) -> Result<()> {
        sys::fs::chown(
            path.as_path_bytes(),
            uid.unwrap_or(UNCHANGED),
            gid.unwrap_or(UNCHANGED),
            true,
        )
    }

    /// As [`chown`], without following a symbolic link in the last
    /// component of the path: the link itself changes owner.
    ///
    /// `fchownat` with `AT_SYMLINK_NOFOLLOW` on Linux, `lchown` on macOS.
    #[inline]
    pub fn lchown<P: AsPath + ?Sized>(path: &P, uid: Option<u32>, gid: Option<u32>) -> Result<()> {
        sys::fs::chown(
            path.as_path_bytes(),
            uid.unwrap_or(UNCHANGED),
            gid.unwrap_or(UNCHANGED),
            false,
        )
    }

    /// As [`chown`], for an open file.
    ///
    /// `fchownat` with `AT_EMPTY_PATH` on Linux, `fchown` on macOS.
    #[inline]
    pub fn fchown(handle: impl AsHandle, uid: Option<u32>, gid: Option<u32>) -> Result<()> {
        sys::fs::fchown(
            handle.as_handle(),
            uid.unwrap_or(UNCHANGED),
            gid.unwrap_or(UNCHANGED),
        )
    }

    /// Creates a FIFO, a pipe with a name, with the Unix permission bits
    /// `mode` (the process's `umask` is applied to them).
    ///
    /// It is opened like a file. Opening it for reading alone waits for a
    /// writer, and for writing alone for a reader.
    ///
    /// `mknodat` on Linux, `mkfifo` on macOS.
    #[inline]
    pub fn mkfifo<P: AsPath + ?Sized>(path: &P, mode: u32) -> Result<()> {
        sys::fs::mkfifo(path.as_path_bytes(), mode & 0o7777)
    }

    /// Whether [`set_xattr`] may create the attribute, or replace it.
    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
    #[non_exhaustive]
    pub enum XattrMode {
        /// Creates the attribute, or replaces its value.
        #[default]
        Any,
        /// Fails with [`AlreadyExists`](crate::ErrorKind::AlreadyExists) if
        /// the file has the attribute (`XATTR_CREATE`).
        Create,
        /// Fails if the file does not have the attribute
        /// (`XATTR_REPLACE`), with the error of the system for that: see
        /// the [extended attributes](get_xattr#what-differs).
        Replace,
    }

    /// Reads the extended attribute `name` of what `path` names, following
    /// symbolic links, into `buf`. Returns the length of the value, or
    /// `None` if there is no such attribute.
    ///
    /// An extended attribute is a value with a name, kept with a file next
    /// to its data: [`set_xattr`] writes one, [`remove_xattr`] removes it,
    /// [`list_xattr`] names those a file has. Each has a form that does
    /// not follow a symbolic link (`l`) and one for an open file (`f`).
    ///
    /// **An empty `buf` asks for the length**: nothing is written and the
    /// length of the value is returned. Otherwise a `buf` shorter than the
    /// value fails with
    /// [`BufferTooSmall`](crate::ErrorKind::BufferTooSmall). The value can
    /// change between two calls: read into a buffer of the length asked
    /// for, and ask again if that fails.
    ///
    /// # What differs
    ///
    /// The calls are the same on Linux and macOS; what an attribute may
    /// be called, and where it may be, are not.
    ///
    /// - **Names.** On Linux a name starts with a class and a dot, which
    ///   decide who may use it: `user.` (whoever may read or write the
    ///   file), `trusted.` (`CAP_SYS_ADMIN`), `security.` (the kernel's:
    ///   file capabilities are `security.capability`), `system.` (access
    ///   control lists). A name of no class fails with
    ///   [`Unsupported`](crate::ErrorKind::Unsupported). On macOS any name
    ///   that is valid UTF-8 will do, and reverse domain names are the
    ///   custom (`com.example.thing`). `user.something` is a name both
    ///   accept. A name is at most 255 bytes on Linux and 127 on macOS.
    /// - **What has them.** On Linux `user.` attributes are for regular
    ///   files and directories only: a symbolic link, a FIFO or a device
    ///   has none, and writing one fails with
    ///   [`PermissionDenied`](crate::ErrorKind::PermissionDenied). On
    ///   macOS a symbolic link has its own.
    /// - **Which filesystems.** Those that cannot store them answer
    ///   [`Unsupported`](crate::ErrorKind::Unsupported): on Linux, a
    ///   `tmpfs` before Linux 6.6 for `user.` attributes, and `/proc`.
    /// - **The size of a value.** At most 64 KiB on Linux, less on most
    ///   filesystems (what fits in a block, on ext4): `E2BIG` or
    ///   [`StorageFull`](crate::ErrorKind::StorageFull) beyond.
    /// - **No such attribute** is `None` here; where it is an error (to
    ///   remove or to replace one), it is `ENODATA` on Linux and `ENOATTR`
    ///   on macOS, two numbers no [`ErrorKind`](crate::ErrorKind) names.
    ///
    /// Windows has nothing of the kind: its alternate data streams are
    /// files within a file, with their own handles, not values.
    ///
    /// `getxattr` on both systems.
    pub fn get_xattr<P: AsPath + ?Sized>(
        path: &P,
        name: &str,
        buf: &mut [u8],
    ) -> Result<Option<usize>> {
        sys::fs::xattr::get(path.as_path_bytes(), name.as_bytes(), buf, true)
    }

    /// As [`get_xattr`], without following a symbolic link in the last
    /// component of the path: the attribute is the link's own.
    ///
    /// `lgetxattr` on Linux, `getxattr` with `XATTR_NOFOLLOW` on macOS.
    pub fn lget_xattr<P: AsPath + ?Sized>(
        path: &P,
        name: &str,
        buf: &mut [u8],
    ) -> Result<Option<usize>> {
        sys::fs::xattr::get(path.as_path_bytes(), name.as_bytes(), buf, false)
    }

    /// As [`get_xattr`], for an open file.
    ///
    /// `fgetxattr` on both systems.
    pub fn fget_xattr(handle: impl AsHandle, name: &str, buf: &mut [u8]) -> Result<Option<usize>> {
        sys::fs::xattr::fget(handle.as_handle(), name.as_bytes(), buf)
    }

    /// Sets the extended attribute `name` of what `path` names, following
    /// symbolic links, to `value`, which may be empty. See [`get_xattr`]
    /// for the names and the files that can have one.
    ///
    /// `setxattr` on both systems.
    pub fn set_xattr<P: AsPath + ?Sized>(
        path: &P,
        name: &str,
        value: &[u8],
        mode: XattrMode,
    ) -> Result<()> {
        sys::fs::xattr::set(path.as_path_bytes(), name.as_bytes(), value, mode, true)
    }

    /// As [`set_xattr`], without following a symbolic link in the last
    /// component of the path.
    ///
    /// `lsetxattr` on Linux, `setxattr` with `XATTR_NOFOLLOW` on macOS.
    pub fn lset_xattr<P: AsPath + ?Sized>(
        path: &P,
        name: &str,
        value: &[u8],
        mode: XattrMode,
    ) -> Result<()> {
        sys::fs::xattr::set(path.as_path_bytes(), name.as_bytes(), value, mode, false)
    }

    /// As [`set_xattr`], for an open file.
    ///
    /// `fsetxattr` on both systems.
    pub fn fset_xattr(
        handle: impl AsHandle,
        name: &str,
        value: &[u8],
        mode: XattrMode,
    ) -> Result<()> {
        sys::fs::xattr::fset(handle.as_handle(), name.as_bytes(), value, mode)
    }

    /// Removes the extended attribute `name` of what `path` names,
    /// following symbolic links.
    ///
    /// # Errors
    ///
    /// When there is no such attribute: `ENODATA` on Linux, `ENOATTR` on
    /// macOS (see [`get_xattr`]).
    ///
    /// `removexattr` on both systems.
    pub fn remove_xattr<P: AsPath + ?Sized>(path: &P, name: &str) -> Result<()> {
        sys::fs::xattr::remove(path.as_path_bytes(), name.as_bytes(), true)
    }

    /// As [`remove_xattr`], without following a symbolic link in the last
    /// component of the path.
    ///
    /// `lremovexattr` on Linux, `removexattr` with `XATTR_NOFOLLOW` on
    /// macOS.
    pub fn lremove_xattr<P: AsPath + ?Sized>(path: &P, name: &str) -> Result<()> {
        sys::fs::xattr::remove(path.as_path_bytes(), name.as_bytes(), false)
    }

    /// As [`remove_xattr`], for an open file.
    ///
    /// `fremovexattr` on both systems.
    pub fn fremove_xattr(handle: impl AsHandle, name: &str) -> Result<()> {
        sys::fs::xattr::fremove(handle.as_handle(), name.as_bytes())
    }

    /// Writes into `buf` the names of the extended attributes of what
    /// `path` names, following symbolic links: each name followed by a NUL
    /// byte, in no particular order. Returns the number of bytes written;
    /// `buf[..n].split(|&byte| byte == 0)` yields the names, and one empty
    /// slice after the last.
    ///
    /// As for [`get_xattr`], an empty `buf` asks for the length, and one
    /// that is too short fails with
    /// [`BufferTooSmall`](crate::ErrorKind::BufferTooSmall).
    ///
    /// On Linux the list has the names the caller may know of: the
    /// `trusted.` ones are left out for who lacks `CAP_SYS_ADMIN`.
    ///
    /// `listxattr` on both systems.
    pub fn list_xattr<P: AsPath + ?Sized>(path: &P, buf: &mut [u8]) -> Result<usize> {
        sys::fs::xattr::list(path.as_path_bytes(), buf, true)
    }

    /// As [`list_xattr`], without following a symbolic link in the last
    /// component of the path.
    ///
    /// `llistxattr` on Linux, `listxattr` with `XATTR_NOFOLLOW` on macOS.
    pub fn llist_xattr<P: AsPath + ?Sized>(path: &P, buf: &mut [u8]) -> Result<usize> {
        sys::fs::xattr::list(path.as_path_bytes(), buf, false)
    }

    /// As [`list_xattr`], for an open file.
    ///
    /// `flistxattr` on both systems.
    pub fn flist_xattr(handle: impl AsHandle, buf: &mut [u8]) -> Result<usize> {
        sys::fs::xattr::flist(handle.as_handle(), buf)
    }
}