Zig 0.17.0-dev (Split by item)

Shortcut keys
?
Show these tips
S
Focus search field
Esc
Clear focus & close tips
U
Jump to source code
↑
Move up in search results
↓
Move down in search results
↵
Go to active search result
This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig standard library. Public Struct

Dir

Public Struct

Fields

handle: Handle

Namespaces

Structs

Types

Values

Functions

pub fn assert(ok: bool) void

Invokes detectable illegal behavior when ok is false.

In debug and safe modes, calls to this function are always generated, and the unreachable statement triggers a panic.

In fast and small modes, calls to this function are optimized away, and in fact the optimizer is able to use the assertion in its heuristics.

Inside a test block, it is best to use the testing module rather than this function, because this function may not detect a test failure in fast and small mode. Outside of a test block, this assert function is the correct function to use.

pub fn cwd() Dir

Returns a handle to the current working directory.

It is not opened with iteration capability. Iterating over the result is illegal behavior.

Closing the returned Dir is checked illegal behavior.

On POSIX targets, this function is comptime-callable.

This function is overridable via std.Options.cwd.

pub fn iterate(dir: Dir) Iterator
pub fn iterateAssumeFirstIteration(dir: Dir) Iterator

Like iterate, but will not reset the directory cursor before the first iteration. This should only be used in cases where it is known that the Dir has not had its cursor modified yet (e.g. it was just opened).

pub fn walkSelectively(dir: Dir, allocator: Allocator) !SelectiveWalker

Recursively iterates over a directory, but requires the user to opt-in to recursing into each directory entry.

dir must have been opened with OpenOptions.iterate set to true.

Walker.deinit releases allocated memory and directory handles.

The order of returned file system entries is undefined.

dir will not be closed after walking it.

See also walk.

pub fn walk(dir: Dir, allocator: Allocator) Allocator.Error!Walker

Recursively iterates over a directory.

dir must have been opened with OpenOptions.iterate set to true.

Walker.deinit releases allocated memory and directory handles.

The order of returned file system entries is undefined.

dir will not be closed after walking it.

See also:

pub fn access(dir: Dir, io: Io, sub_path: []const u8, options: AccessOptions) AccessError!void

Test accessing sub_path.

On Windows, sub_path should be encoded as WTF-8. On WASI, sub_path should be encoded as valid UTF-8. On other platforms, sub_path is an opaque sequence of bytes with no particular encoding.

Be careful of Time-Of-Check-Time-Of-Use race conditions when using this function. For example, instead of testing if a file exists and then opening it, just open it and handle the error for file not found.

pub fn accessAbsolute(io: Io, absolute_path: []const u8, options: AccessOptions) AccessError!void
pub fn openDir(dir: Dir, io: Io, sub_path: []const u8, options: OpenOptions) OpenError!Dir

Opens a directory at the given path. The directory is a system resource that remains open until close is called on the result.

The directory cannot be iterated unless the iterate option is set to true.

On Windows, sub_path should be encoded as WTF-8. On WASI, sub_path should be encoded as valid UTF-8. On other platforms, sub_path is an opaque sequence of bytes with no particular encoding.

pub fn openDirAbsolute(io: Io, absolute_path: []const u8, options: OpenOptions) OpenError!Dir
pub fn close(dir: Dir, io: Io) void
pub fn closeMany(io: Io, dirs: []const Dir) void
pub fn openFile(dir: Dir, io: Io, sub_path: []const u8, options: OpenFileOptions) File.OpenError!File

Opens a file for reading or writing, without attempting to create a new file.

To create a new file, see createFile.

Allocates a resource to be released with File.close.

On Windows, sub_path should be encoded as WTF-8. On WASI, sub_path should be encoded as valid UTF-8. On other platforms, sub_path is an opaque sequence of bytes with no particular encoding.

pub fn openFileAbsolute(io: Io, absolute_path: []const u8, options: OpenFileOptions) File.OpenError!File
pub fn createFile(dir: Dir, io: Io, sub_path: []const u8, flags: CreateFileOptions) File.OpenError!File

Creates, opens, or overwrites a file with write access.

Allocates a resource to be dellocated with File.close.

On Windows, sub_path should be encoded as WTF-8. On WASI, sub_path should be encoded as valid UTF-8. On other platforms, sub_path is an opaque sequence of bytes with no particular encoding.

pub fn createFileAbsolute(io: Io, absolute_path: []const u8, flags: CreateFileOptions) File.OpenError!File
pub fn writeFile(dir: Dir, io: Io, options: WriteFileOptions) WriteFileError!void

Writes content to the file system, using the file creation flags provided.

pub fn updateFile(source_dir: Dir, io: Io, source_path: []const u8, dest_dir: Dir, /// If directories in this path do not exist, they are created. dest_path: []const u8, options: CopyFileOptions) !PrevStatus

Check the file size, mtime, and permissions of source_path and dest_path. If they are equal, does nothing. Otherwise, atomically copies source_path to dest_path, creating the parent directory hierarchy as needed. The destination file gains the mtime, atime, and permissions of the source file so that the next call to updateFile will not need a copy.

Returns the previous status of the file before updating.

  • On Windows, both paths should be encoded as WTF-8.
  • On WASI, both paths should be encoded as valid UTF-8.
  • On other platforms, both paths are an opaque sequence of bytes with no particular encoding.
pub fn readFile(dir: Dir, io: Io, file_path: []const u8, buffer: []u8) ReadFileError![]u8

Read all of file contents using a preallocated buffer.

The returned slice has the same pointer as buffer. If the length matches buffer.len the situation is ambiguous. It could either mean that the entire file was read, and it exactly fits the buffer, or it could mean the buffer was not big enough for the entire file.

  • On Windows, file_path should be encoded as WTF-8.
  • On WASI, file_path should be encoded as valid UTF-8.
  • On other platforms, file_path is an opaque sequence of bytes with no particular encoding.
pub fn createDir(dir: Dir, io: Io, sub_path: []const u8, permissions: Permissions) CreateDirError!void

Creates a single directory with a relative or absolute path.

  • On Windows, sub_path should be encoded as WTF-8.
  • On WASI, sub_path should be encoded as valid UTF-8.
  • On other platforms, sub_path is an opaque sequence of bytes with no particular encoding.

Related:

pub fn createDirAbsolute(io: Io, absolute_path: []const u8, permissions: Permissions) CreateDirError!void

Create a new directory, based on an absolute path.

Asserts that the path is absolute. See createDir for a function that operates on both absolute and relative paths.

On Windows, absolute_path should be encoded as WTF-8. On WASI, absolute_path should be encoded as valid UTF-8. On other platforms, absolute_path is an opaque sequence of bytes with no particular encoding.

pub fn createDirPath(dir: Dir, io: Io, sub_path: []const u8) CreateDirPathError!void

Creates parent directories with default permissions as necessary to ensure sub_path exists as a directory.

Returns success if the path already exists and is a directory.

This function may not be atomic. If it returns an error, the file system may have been modified.

Fails on an empty path with error.BadPathName as that is not a path that can be created.

On Windows, sub_path should be encoded as WTF-8. On WASI, sub_path should be encoded as valid UTF-8. On other platforms, sub_path is an opaque sequence of bytes with no particular encoding.

Paths containing .. components are handled differently depending on the platform:

  • On Windows, .. are resolved before the path is passed to NtCreateFile, meaning a sub_path like "first/../second" will resolve to "second" and only a ./second directory will be created.
  • On other platforms, .. are not resolved before the path is passed to mkdirat, meaning a sub_path like "first/../second" will create both a ./first and a ./second directory.

See also:

pub fn createDirPathStatus(dir: Dir, io: Io, sub_path: []const u8, permissions: Permissions) CreateDirPathError!CreatePathStatus

Same as createDirPath except returns whether the path already existed or was successfully created.

pub fn createDirPathOpen(dir: Dir, io: Io, sub_path: []const u8, options: CreateDirPathOpenOptions) CreateDirPathOpenError!Dir

Performs the equivalent of createDirPath followed by openDir, atomically if possible.

When this operation is canceled, it may leave the file system in a partially modified state.

On Windows, sub_path should be encoded as WTF-8. On WASI, sub_path should be encoded as valid UTF-8. On other platforms, sub_path is an opaque sequence of bytes with no particular encoding.

pub fn stat(dir: Dir, io: Io) StatError!Stat
pub fn statFile(dir: Dir, io: Io, sub_path: []const u8, options: StatFileOptions) StatFileError!Stat

Returns metadata for a file inside the directory.

On Windows, this requires three syscalls. On other operating systems, it only takes one.

Symlinks are followed.

sub_path may be absolute, in which case self is ignored.

  • On Windows, sub_path should be encoded as WTF-8.
  • On WASI, sub_path should be encoded as valid UTF-8.
  • On other platforms, sub_path is an opaque sequence of bytes with no particular encoding.
pub fn realPath(dir: Dir, io: Io, out_buffer: []u8) RealPathError!usize

Obtains the canonicalized absolute path name of sub_path relative to this Dir. If sub_path is absolute, ignores this Dir handle and obtains the canonicalized absolute pathname of sub_path argument.

This function has limited platform support, and using it can lead to unnecessary failures and race conditions. It is generally advisable to avoid this function entirely.

pub fn realPathFile(dir: Dir, io: Io, sub_path: []const u8, out_buffer: []u8) RealPathFileError!usize

Obtains the canonicalized absolute path name of sub_path relative to this Dir. If sub_path is absolute, ignores this Dir handle and obtains the canonicalized absolute pathname of sub_path argument.

This function has limited platform support, and using it can lead to unnecessary failures and race conditions. It is generally advisable to avoid this function entirely.

See also:

pub fn realPathFileAlloc(dir: Dir, io: Io, sub_path: []const u8, allocator: Allocator) RealPathFileAllocError![: 0]u8

Same as realPathFile except allocates result.

This function has limited platform support, and using it can lead to unnecessary failures and race conditions. It is generally advisable to avoid this function entirely.

See also:

pub fn realPathFileAbsolute(io: Io, absolute_path: []const u8, out_buffer: []u8) RealPathFileError!usize

Same as realPathFile except absolute_path is asserted to be an absolute path.

This function has limited platform support, and using it can lead to unnecessary failures and race conditions. It is generally advisable to avoid this function entirely.

See also:

pub fn realPathFileAbsoluteAlloc(io: Io, absolute_path: []const u8, allocator: Allocator) RealPathFileAllocError![: 0]u8

Same as realPathFileAbsolute except allocates result.

This function has limited platform support, and using it can lead to unnecessary failures and race conditions. It is generally advisable to avoid this function entirely.

See also:

pub fn deleteFile(dir: Dir, io: Io, sub_path: []const u8) DeleteFileError!void

Delete a file name and possibly the file it refers to, based on an open directory handle.

On Windows, sub_path should be encoded as WTF-8. On WASI, sub_path should be encoded as valid UTF-8. On other platforms, sub_path is an opaque sequence of bytes with no particular encoding.

Asserts that the path parameter has no null bytes.

pub fn deleteFileAbsolute(io: Io, absolute_path: []const u8) DeleteFileError!void
pub fn deleteDir(dir: Dir, io: Io, sub_path: []const u8) DeleteDirError!void

Returns error.DirNotEmpty if the directory is not empty.

To delete a directory recursively, see deleteTree.

On Windows, sub_path should be encoded as WTF-8. On WASI, sub_path should be encoded as valid UTF-8. On other platforms, sub_path is an opaque sequence of bytes with no particular encoding.

pub fn deleteDirAbsolute(io: Io, absolute_path: []const u8) DeleteDirError!void

Same as deleteDir except the path is absolute.

On Windows, dir_path should be encoded as WTF-8. On WASI, dir_path should be encoded as valid UTF-8. On other platforms, dir_path is an opaque sequence of bytes with no particular encoding.

pub fn rename(old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8, io: Io) RenameError!void

Change the name or location of a file or directory.

If new_sub_path already exists, it will be replaced.

Renaming a file over an existing directory or a directory over an existing file will fail with error.IsDir or error.NotDir

  • On Windows, both paths should be encoded as WTF-8.
  • On WASI, both paths should be encoded as valid UTF-8.
  • On other platforms, both paths are an opaque sequence of bytes with no particular encoding.
pub fn renameAbsolute(old_path: []const u8, new_path: []const u8, io: Io) RenameError!void
pub fn renamePreserve(old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8, io: Io) RenamePreserveError!void

Change the name or location of a file or directory.

If new_sub_path already exists, error.PathAlreadyExists will be returned.

  • On Windows, both paths should be encoded as WTF-8.
  • On WASI, both paths should be encoded as valid UTF-8.
  • On other platforms, both paths are an opaque sequence of bytes with no particular encoding.
pub fn hardLink(old_dir: Dir, old_sub_path: []const u8, new_dir: Dir, new_sub_path: []const u8, io: Io, options: HardLinkOptions) HardLinkError!void
pub fn symLink(dir: Dir, io: Io, target_path: []const u8, sym_link_path: []const u8, flags: SymLinkFlags) SymLinkError!void

Creates a symbolic link named sym_link_path which contains the string target_path.

A symbolic link (also known as a soft link) may point to an existing file or to a nonexistent one; the latter case is known as a dangling link.

If sym_link_path exists, it will not be overwritten.

On Windows, both paths should be encoded as WTF-8. On WASI, both paths should be encoded as valid UTF-8. On other platforms, both paths are an opaque sequence of bytes with no particular encoding.

pub fn symLinkAbsolute(io: Io, target_path: []const u8, sym_link_path: []const u8, flags: SymLinkFlags) SymLinkError!void
pub fn symLinkAtomic(dir: Dir, io: Io, target_path: []const u8, sym_link_path: []const u8, flags: SymLinkFlags) !void

Same as symLink, except tries to create the symbolic link until it succeeds or encounters an error other than error.PathAlreadyExists.

  • On Windows, both paths should be encoded as WTF-8.
  • On WASI, both paths should be encoded as valid UTF-8.
  • On other platforms, both paths are an opaque sequence of bytes with no particular encoding.
pub fn readLink(dir: Dir, io: Io, sub_path: []const u8, buffer: []u8) ReadLinkError!usize

Obtain target of a symbolic link.

Returns how many bytes of buffer are populated.

Asserts that the path parameter has no null bytes.

On Windows, sub_path should be encoded as WTF-8. On WASI, sub_path should be encoded as valid UTF-8. On other platforms, sub_path is an opaque sequence of bytes with no particular encoding.

pub fn readLinkAbsolute(io: Io, absolute_path: []const u8, buffer: []u8) ReadLinkError!usize

Same as readLink, except it asserts the path is absolute.

On Windows, path should be encoded as WTF-8. On WASI, path should be encoded as valid UTF-8. On other platforms, path is an opaque sequence of bytes with no particular encoding.

pub fn readFileAlloc(dir: Dir, io: Io, /// On Windows, should be encoded as [WTF-8](https://wtf-8.codeberg.page/). /// On WASI, should be encoded as valid UTF-8. /// On other platforms, an opaque sequence of bytes with no particular encoding. sub_path: []const u8, /// Used to allocate the result. gpa: Allocator, /// If reached or exceeded, `error.StreamTooLong` is returned instead. limit: Io.Limit) ReadFileAllocError![]u8

Reads all the bytes from the named file. On success, caller owns returned buffer.

If the file size is already known, a better alternative is to initialize a File.Reader.

If the file size cannot be obtained, an error is returned. If this is a realistic possibility, a better alternative is to initialize a File.Reader which handles this seamlessly.

pub fn readFileAllocOptions(dir: Dir, io: Io, /// On Windows, should be encoded as [WTF-8](https://wtf-8.codeberg.page/). /// On WASI, should be encoded as valid UTF-8. /// On other platforms, an opaque sequence of bytes with no particular encoding. sub_path: []const u8, /// Used to allocate the result. gpa: Allocator, /// If reached or exceeded, `error.StreamTooLong` is returned instead. limit: Io.Limit, comptime alignment: std.mem.Alignment, comptime sentinel: ?u8) ReadFileAllocError!(if(sentinel) | s | [: s]align(alignment.toByteUnits()) u8 else []align(alignment.toByteUnits()) u8)

Reads all the bytes from the named file. On success, caller owns returned buffer.

If the file size is already known, a better alternative is to initialize a File.Reader.

pub fn deleteTree(dir: Dir, io: Io, sub_path: []const u8) DeleteTreeError!void

Whether sub_path describes a symlink, file, or directory, this function removes it. If it cannot be removed because it is a non-empty directory, this function recursively removes its entries and then tries again.

This operation is not atomic on most file systems.

On Windows, sub_path should be encoded as WTF-8. On WASI, sub_path should be encoded as valid UTF-8. On other platforms, sub_path is an opaque sequence of bytes with no particular encoding.

pub fn deleteTreeMinStackSize(dir: Dir, io: Io, sub_path: []const u8) DeleteTreeError!void

Like deleteTree, but only keeps one Iterator active at a time to minimize the function's stack size. This is slower than deleteTree but uses less stack space. On Windows, sub_path should be encoded as WTF-8. On WASI, sub_path should be encoded as valid UTF-8. On other platforms, sub_path is an opaque sequence of bytes with no particular encoding.

fn deleteTreeMinStackSizeWithKindHint(parent: Dir, io: Io, sub_path: []const u8, kind_hint: File.Kind) DeleteTreeError!void
fn deleteTreeOpenInitialSubpath(dir: Dir, io: Io, sub_path: []const u8, kind_hint: File.Kind) !?Dir

On successful delete, returns null.

pub fn copyFile(source_dir: Dir, source_path: []const u8, dest_dir: Dir, dest_path: []const u8, io: Io, options: CopyFileOptions) CopyFileError!void

Atomically creates a new file at dest_path within dest_dir with the same contents as source_path within source_dir.

Whether to overwrite the existing file is determined by options.

On Linux, until https://patchwork.kernel.org/patch/9636735/ is merged and readily available, there is a possibility of power loss or application termination leaving temporary files present in the same directory as dest_path.

On Windows, both paths should be encoded as WTF-8. On WASI, both paths should be encoded as valid UTF-8. On other platforms, both paths are an opaque sequence of bytes with no particular encoding.

pub fn copyFileAbsolute(source_path: []const u8, dest_path: []const u8, io: Io, options: CopyFileOptions) !void

Same as copyFile, except asserts that both source_path and dest_path are absolute.

On Windows, both paths should be encoded as WTF-8. On WASI, both paths should be encoded as valid UTF-8. On other platforms, both paths are an opaque sequence of bytes with no particular encoding.

pub fn createFileAtomic(dir: Dir, io: Io, sub_path: []const u8, options: CreateFileAtomicOptions) CreateFileAtomicError!File.Atomic

Create an unnamed ephemeral file that can eventually be atomically materialized into sub_path.

The returned File.Atomic provides API to emulate the behavior in case it is not directly supported by the underlying operating system.

  • On Windows, sub_path should be encoded as WTF-8.
  • On WASI, sub_path should be encoded as valid UTF-8.
  • On other platforms, sub_path is an opaque sequence of bytes with no particular encoding.
pub fn setPermissions(dir: Dir, io: Io, new_permissions: File.Permissions) SetPermissionsError!void

Also known as "chmod".

The process must have the correct privileges in order to do this successfully, or must have the effective user ID matching the owner of the directory. Additionally, the directory must have been opened with OpenOptions.iterate set to true.

pub fn setFilePermissions(dir: Dir, io: Io, sub_path: []const u8, new_permissions: File.Permissions, options: SetFilePermissionsOptions) SetFilePermissionsError!void

Also known as "fchmodat".

pub fn setOwner(dir: Dir, io: Io, owner: ?File.Uid, group: ?File.Gid) SetOwnerError!void

Also known as "chown".

The process must have the correct privileges in order to do this successfully. The group may be changed by the owner of the directory to any group of which the owner is a member. Additionally, the directory must have been opened with OpenOptions.iterate set to true. If the owner or group is specified as null, the ID is not changed.

pub fn setFileOwner(dir: Dir, io: Io, sub_path: []const u8, owner: ?File.Uid, group: ?File.Gid, options: SetFileOwnerOptions) SetFileOwnerError!void

Also known as "fchownat".

pub fn setTimestamps(dir: Dir, io: Io, sub_path: []const u8, options: SetTimestampsOptions) SetTimestampsError!void

The granularity that ultimately is stored depends on the combination of operating system and file system. When a value as provided that exceeds this range, the value is clamped to the maximum.

pub fn setTimestampsNow(dir: Dir, io: Io, sub_path: []const u8, options: SetTimestampsNowOptions) SetTimestampsError!void

Sets the accessed and modification timestamps of the provided path to the current wall clock time.

The granularity that ultimately is stored depends on the combination of operating system and file system.

File

Io/Dir.zig
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
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
const Dir = @This();
const root = @import("root");

const builtin = @import("builtin");
const native_os = builtin.os.tag;

const std = @import("../std.zig");
const Io = std.Io;
const File = Io.File;
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;

handle: Handle,

pub const Handle = std.posix.fd_t;

pub const path = std.fs.path;

/// The maximum length of a file path that the operating system will accept.
///
/// Paths, including those returned from file system operations, may be longer
/// than this length, but such paths cannot be successfully passed back in
/// other file system operations. However, all path components returned by file
/// system operations are assumed to fit into a `u8` array of this length.
///
/// The byte count includes room for a null sentinel byte.
///
/// * On Windows, `[]u8` file paths are encoded as
///   [WTF-8](https://wtf-8.codeberg.page/).
/// * On WASI, `[]u8` file paths are encoded as valid UTF-8.
/// * On other platforms, `[]u8` file paths are opaque sequences of bytes with
///   no particular encoding.
pub const max_path_bytes = switch (native_os) {
    .linux, .driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos, .freebsd, .openbsd, .netbsd, .dragonfly, .haiku, .illumos, .plan9, .emscripten, .wasi, .serenity => std.posix.PATH_MAX,
    // Each WTF-16LE code unit may be expanded to 3 WTF-8 bytes.
    // If it would require 4 WTF-8 bytes, then there would be a surrogate
    // pair in the WTF-16LE, and we (over)account 3 bytes for it that way.
    // +1 for the null byte at the end, which can be encoded in 1 byte.
    .windows => std.os.windows.PATH_MAX_WIDE * 3 + 1,
    else => if (@hasDecl(root, "os") and @hasDecl(root.os, "PATH_MAX"))
        root.os.PATH_MAX
    else
        @compileError("PATH_MAX not implemented for " ++ @tagName(native_os)),
};

/// This represents the maximum size of a `[]u8` file name component that
/// the platform's common file systems support. File name components returned by file system
/// operations are likely to fit into a `u8` array of this length, but
/// (depending on the platform) this assumption may not hold for every configuration.
/// The byte count does not include a null sentinel byte.
/// On Windows, `[]u8` file name components are encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// On WASI, file name components are encoded as valid UTF-8.
/// On other platforms, `[]u8` components are an opaque sequence of bytes with no particular encoding.
pub const max_name_bytes = switch (native_os) {
    .linux, .driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos, .freebsd, .openbsd, .netbsd, .dragonfly, .illumos, .serenity, .psp => std.posix.NAME_MAX,
    // Haiku's NAME_MAX includes the null terminator, so subtract one.
    .haiku => std.posix.NAME_MAX - 1,
    // Each WTF-16LE character may be expanded to 3 WTF-8 bytes.
    // If it would require 4 WTF-8 bytes, then there would be a surrogate
    // pair in the WTF-16LE, and we (over)account 3 bytes for it that way.
    .windows => std.os.windows.NAME_MAX * 3,
    // For WASI, the MAX_NAME will depend on the host OS, so it needs to be
    // as large as the largest max_name_bytes (Windows) in order to work on any host OS.
    // TODO determine if this is a reasonable approach
    .wasi => std.os.windows.NAME_MAX * 3,
    else => if (@hasDecl(root, "os") and @hasDecl(root.os, "NAME_MAX"))
        root.os.NAME_MAX
    else
        @compileError("NAME_MAX not implemented for " ++ @tagName(native_os)),
};

pub const Entry = struct {
    name: []const u8,
    kind: File.Kind,
    inode: File.INode,
};

/// Returns a handle to the current working directory.
///
/// It is not opened with iteration capability. Iterating over the result is
/// illegal behavior.
///
/// Closing the returned `Dir` is checked illegal behavior.
///
/// On POSIX targets, this function is comptime-callable.
///
/// This function is overridable via `std.Options.cwd`.
pub fn cwd() Dir {
    const cwdFn = std.Options.cwd orelse return switch (native_os) {
        .windows => .{ .handle = std.os.windows.peb().ProcessParameters.CurrentDirectory.Handle },
        .wasi => .{ .handle = 3 }, // Expect the first preopen to be current working directory.
        else => .{ .handle = std.posix.AT.FDCWD },
    };
    return cwdFn();
}

pub const Reader = struct {
    dir: Dir,
    state: State,
    /// Stores I/O implementation specific data.
    buffer: []align(@alignOf(usize)) u8,
    /// Index of next entry in `buffer`.
    index: usize,
    /// Fill position of `buffer`.
    end: usize,

    /// A length for `buffer` that allows all implementations to function.
    pub const min_buffer_len = switch (native_os) {
        .linux => std.mem.alignForward(usize, @sizeOf(std.os.linux.dirent64), 8) +
            std.mem.alignForward(usize, max_name_bytes, 8),
        .windows => len: {
            const max_info_len = @sizeOf(std.os.windows.FILE_BOTH_DIR_INFORMATION) + std.os.windows.NAME_MAX * 2;
            const info_align = @alignOf(std.os.windows.FILE_BOTH_DIR_INFORMATION);
            const reserved_len = std.mem.alignForward(usize, max_name_bytes, info_align) - max_info_len;
            break :len std.mem.alignForward(usize, reserved_len, info_align) + max_info_len;
        },
        .wasi => @sizeOf(std.os.wasi.dirent_t) +
            std.mem.alignForward(usize, max_name_bytes, @alignOf(std.os.wasi.dirent_t)),
        .openbsd => std.c.S.BLKSIZE,
        else => if (builtin.link_libc) @sizeOf(std.c.dirent) else std.mem.alignForward(usize, max_name_bytes, @alignOf(usize)),
    };

    pub const State = enum {
        /// Indicates the next call to `read` should rewind and start over the
        /// directory listing.
        reset,
        reading,
        finished,
    };

    pub const Error = error{
        AccessDenied,
        PermissionDenied,
        SystemResources,
    } || Io.UnexpectedError || Io.Cancelable;

    /// Asserts that `buffer` has length at least `min_buffer_len`.
    pub fn init(dir: Dir, buffer: []align(@alignOf(usize)) u8) Reader {
        assert(buffer.len >= min_buffer_len);
        return .{
            .dir = dir,
            .state = .reset,
            .index = 0,
            .end = 0,
            .buffer = buffer,
        };
    }

    /// All `Entry.name` are invalidated with the next call to `read` or
    /// `next`.
    pub fn read(r: *Reader, io: Io, buffer: []Entry) Error!usize {
        return io.vtable.dirRead(io.userdata, r, buffer);
    }

    /// `Entry.name` is invalidated with the next call to `read` or `next`.
    pub fn next(r: *Reader, io: Io) Error!?Entry {
        var buffer: [1]Entry = undefined;
        while (true) {
            const n = try read(r, io, &buffer);
            if (n == 1) return buffer[0];
            if (r.state == .finished) return null;
        }
    }

    pub fn reset(r: *Reader) void {
        r.state = .reset;
        r.index = 0;
        r.end = 0;
    }
};

/// This API is designed for convenience rather than performance:
/// * It chooses a buffer size rather than allowing the user to provide one.
/// * It is movable by only requesting one `Entry` at a time from the `Io`
///   implementation rather than doing batch operations.
///
/// Still, it will do a decent job of minimizing syscall overhead. For a
/// lower level abstraction, see `Reader`. For a higher level abstraction,
/// see `Walker`.
pub const Iterator = struct {
    reader: Reader,
    reader_buffer: [reader_buffer_len]u8 align(@alignOf(usize)),

    pub const reader_buffer_len = 2048;

    comptime {
        assert(reader_buffer_len >= Reader.min_buffer_len);
    }

    pub const Error = Reader.Error;

    pub fn init(dir: Dir, reader_state: Reader.State) Iterator {
        return .{
            .reader = .{
                .dir = dir,
                .state = reader_state,
                .index = 0,
                .end = 0,
                .buffer = undefined,
            },
            .reader_buffer = undefined,
        };
    }

    pub fn next(it: *Iterator, io: Io) Error!?Entry {
        it.reader.buffer = &it.reader_buffer;
        return it.reader.next(io);
    }
};

pub fn iterate(dir: Dir) Iterator {
    return .init(dir, .reset);
}

/// Like `iterate`, but will not reset the directory cursor before the first
/// iteration. This should only be used in cases where it is known that the
/// `Dir` has not had its cursor modified yet (e.g. it was just opened).
pub fn iterateAssumeFirstIteration(dir: Dir) Iterator {
    return .init(dir, .reading);
}

pub const SelectiveWalker = struct {
    stack: std.ArrayList(StackItem),
    name_buffer: std.ArrayList(u8),
    allocator: Allocator,

    pub const Error = Iterator.Error || Allocator.Error;

    const StackItem = struct {
        iter: Iterator,
        dirname_len: usize,
    };

    /// After each call to this function, and on deinit(), the memory returned
    /// from this function becomes invalid. A copy must be made in order to keep
    /// a reference to the path.
    pub fn next(self: *SelectiveWalker, io: Io) Error!?Walker.Entry {
        while (self.stack.items.len > 0) {
            const top = &self.stack.items[self.stack.items.len - 1];
            var dirname_len = top.dirname_len;
            if (top.iter.next(io) catch |err| {
                // If we get an error, then we want the user to be able to continue
                // walking if they want, which means that we need to pop the directory
                // that errored from the stack. Otherwise, all future `next` calls would
                // likely just fail with the same error.
                var item = self.stack.pop().?;
                if (self.stack.items.len != 0) {
                    item.iter.reader.dir.close(io);
                }
                return err;
            }) |entry| {
                self.name_buffer.shrinkRetainingCapacity(dirname_len);
                if (self.name_buffer.items.len != 0) {
                    try self.name_buffer.append(self.allocator, path.sep);
                    dirname_len += 1;
                }
                try self.name_buffer.ensureUnusedCapacity(self.allocator, entry.name.len + 1);
                self.name_buffer.appendSliceAssumeCapacity(entry.name);
                self.name_buffer.appendAssumeCapacity(0);
                const walker_entry: Walker.Entry = .{
                    .dir = top.iter.reader.dir,
                    .basename = self.name_buffer.items[dirname_len .. self.name_buffer.items.len - 1 :0],
                    .path = self.name_buffer.items[0 .. self.name_buffer.items.len - 1 :0],
                    .kind = entry.kind,
                };
                return walker_entry;
            } else {
                var item = self.stack.pop().?;
                if (self.stack.items.len != 0) {
                    item.iter.reader.dir.close(io);
                }
            }
        }
        return null;
    }

    /// Traverses into the directory, continuing walking one level down.
    pub fn enter(self: *SelectiveWalker, io: Io, entry: Walker.Entry) !void {
        if (entry.kind != .directory) {
            @branchHint(.cold);
            return;
        }

        var new_dir = entry.dir.openDir(io, entry.basename, .{ .iterate = true }) catch |err| {
            switch (err) {
                error.NameTooLong => unreachable,
                else => |e| return e,
            }
        };
        errdefer new_dir.close(io);

        try self.stack.append(self.allocator, .{
            .iter = new_dir.iterateAssumeFirstIteration(),
            .dirname_len = self.name_buffer.items.len - 1,
        });
    }

    pub fn deinit(self: *SelectiveWalker) void {
        self.name_buffer.deinit(self.allocator);
        self.stack.deinit(self.allocator);
    }

    /// Leaves the current directory, continuing walking one level up.
    /// If the current entry is a directory entry, then the "current directory"
    /// will pertain to that entry if `enter` is called before `leave`.
    pub fn leave(self: *SelectiveWalker, io: Io) void {
        var item = self.stack.pop().?;
        if (self.stack.items.len != 0) {
            @branchHint(.likely);
            item.iter.reader.dir.close(io);
        }
    }
};

/// Recursively iterates over a directory, but requires the user to
/// opt-in to recursing into each directory entry.
///
/// `dir` must have been opened with `OpenOptions.iterate` set to `true`.
///
/// `Walker.deinit` releases allocated memory and directory handles.
///
/// The order of returned file system entries is undefined.
///
/// `dir` will not be closed after walking it.
///
/// See also `walk`.
pub fn walkSelectively(dir: Dir, allocator: Allocator) !SelectiveWalker {
    var stack: std.ArrayList(SelectiveWalker.StackItem) = .empty;

    try stack.append(allocator, .{
        .iter = dir.iterate(),
        .dirname_len = 0,
    });

    return .{
        .stack = stack,
        .name_buffer = .empty,
        .allocator = allocator,
    };
}

pub const Walker = struct {
    inner: SelectiveWalker,

    pub const Entry = struct {
        /// The containing directory. This can be used to operate directly on `basename`
        /// rather than `path`, avoiding `error.NameTooLong` for deeply nested paths.
        /// The directory remains open until `next` or `deinit` is called.
        dir: Dir,
        basename: [:0]const u8,
        path: [:0]const u8,
        kind: File.Kind,

        /// Returns the depth of the entry relative to the initial directory.
        /// Returns 1 for a direct child of the initial directory, 2 for an entry
        /// within a direct child of the initial directory, etc.
        pub fn depth(self: Walker.Entry) usize {
            return std.mem.countScalar(u8, self.path, path.sep) + 1;
        }
    };

    /// After each call to this function, and on deinit(), the memory returned
    /// from this function becomes invalid. A copy must be made in order to keep
    /// a reference to the path.
    pub fn next(self: *Walker, io: Io) !?Walker.Entry {
        const entry = try self.inner.next(io);
        if (entry != null and entry.?.kind == .directory) {
            try self.inner.enter(io, entry.?);
        }
        return entry;
    }

    pub fn deinit(self: *Walker) void {
        self.inner.deinit();
    }

    /// Leaves the current directory, continuing walking one level up.
    /// If the current entry is a directory entry, then the "current directory"
    /// is the directory pertaining to the current entry.
    pub fn leave(self: *Walker, io: Io) void {
        self.inner.leave(io);
    }
};

/// Recursively iterates over a directory.
///
/// `dir` must have been opened with `OpenOptions.iterate` set to `true`.
///
/// `Walker.deinit` releases allocated memory and directory handles.
///
/// The order of returned file system entries is undefined.
///
/// `dir` will not be closed after walking it.
///
/// See also:
/// * `walkSelectively`
pub fn walk(dir: Dir, allocator: Allocator) Allocator.Error!Walker {
    return .{ .inner = try walkSelectively(dir, allocator) };
}

pub const PathNameError = error{
    /// Returned when an insufficient buffer is provided that cannot fit the
    /// path name.
    NameTooLong,
    /// File system cannot encode the requested file name bytes.
    /// Could be due to invalid WTF-8 on Windows, invalid UTF-8 on WASI,
    /// invalid characters on Windows, etc. Filesystem and operating specific.
    BadPathName,
};

pub const AccessError = error{
    /// The requested `AccessOptions` would be denied to the file, or search
    /// permission is denied for one of the directories in the path prefix.
    AccessDenied,
    /// Write permission was requested but the file is immutable.
    PermissionDenied,
    FileNotFound,
    InputOutput,
    SystemResources,
    FileBusy,
    SymLinkLoop,
    ReadOnlyFileSystem,
} || PathNameError || Io.Cancelable || Io.UnexpectedError;

pub const AccessOptions = packed struct {
    follow_symlinks: bool = true,
    read: bool = false,
    write: bool = false,
    execute: bool = false,
};

/// Test accessing `sub_path`.
///
/// On Windows, `sub_path` should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// On WASI, `sub_path` should be encoded as valid UTF-8.
/// On other platforms, `sub_path` is an opaque sequence of bytes with no particular encoding.
///
/// Be careful of Time-Of-Check-Time-Of-Use race conditions when using this
/// function. For example, instead of testing if a file exists and then opening
/// it, just open it and handle the error for file not found.
pub fn access(dir: Dir, io: Io, sub_path: []const u8, options: AccessOptions) AccessError!void {
    return io.vtable.dirAccess(io.userdata, dir, sub_path, options);
}

pub fn accessAbsolute(io: Io, absolute_path: []const u8, options: AccessOptions) AccessError!void {
    assert(path.isAbsolute(absolute_path));
    return access(.cwd(), io, absolute_path, options);
}

pub const OpenError = error{
    FileNotFound,
    NotDir,
    AccessDenied,
    PermissionDenied,
    SymLinkLoop,
    ProcessFdQuotaExceeded,
    SystemFdQuotaExceeded,
    NoDevice,
    SystemResources,
    /// On Windows, `\\server` or `\\server\share` was not found.
    NetworkNotFound,
} || PathNameError || Io.Cancelable || Io.UnexpectedError;

pub const OpenOptions = struct {
    /// `true` means the opened directory can be used as the `Dir` parameter
    /// for functions which operate based on an open directory handle. When `false`,
    /// such operations are Illegal Behavior.
    access_sub_paths: bool = true,
    /// `true` means the opened directory can be scanned for the files and sub-directories
    /// of the result. It means the `iterate` function can be called.
    iterate: bool = false,
    /// `false` means it won't dereference the symlinks.
    follow_symlinks: bool = true,
};

/// Opens a directory at the given path. The directory is a system resource that remains
/// open until `close` is called on the result.
///
/// The directory cannot be iterated unless the `iterate` option is set to `true`.
///
/// On Windows, `sub_path` should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// On WASI, `sub_path` should be encoded as valid UTF-8.
/// On other platforms, `sub_path` is an opaque sequence of bytes with no particular encoding.
pub fn openDir(dir: Dir, io: Io, sub_path: []const u8, options: OpenOptions) OpenError!Dir {
    return io.vtable.dirOpenDir(io.userdata, dir, sub_path, options);
}

pub fn openDirAbsolute(io: Io, absolute_path: []const u8, options: OpenOptions) OpenError!Dir {
    assert(path.isAbsolute(absolute_path));
    return openDir(.cwd(), io, absolute_path, options);
}

pub fn close(dir: Dir, io: Io) void {
    return io.vtable.dirClose(io.userdata, (&dir)[0..1]);
}

pub fn closeMany(io: Io, dirs: []const Dir) void {
    return io.vtable.dirClose(io.userdata, dirs);
}

pub const OpenFileOptions = struct {
    mode: Mode = .read_only,
    /// Determines the behavior when opening a path that refers to a directory.
    ///
    /// If set to true, directories may be opened, but `error.IsDir` is still
    /// possible in certain scenarios, e.g. attempting to open a directory with
    /// write permissions.
    ///
    /// If set to false, `error.IsDir` will always be returned when opening a directory.
    ///
    /// When set to false:
    /// * On Windows, the behavior is implemented without any extra syscalls.
    /// * On other operating systems, the behavior is implemented with an additional
    ///   `fstat` syscall.
    allow_directory: bool = true,
    /// Indicates intent for only some operations to be performed on this
    /// opened file:
    /// * `close`
    /// * `stat`
    /// On Linux and FreeBSD, this corresponds to `std.posix.O.PATH`.
    path_only: bool = false,
    /// Open the file with an advisory lock to coordinate with other processes
    /// accessing it at the same time. An exclusive lock will prevent other
    /// processes from acquiring a lock. A shared lock will prevent other
    /// processes from acquiring a exclusive lock, but does not prevent
    /// other process from getting their own shared locks.
    ///
    /// The lock is advisory, except on Linux in very specific circumstances[1].
    /// This means that a process that does not respect the locking API can still get access
    /// to the file, despite the lock.
    ///
    /// On these operating systems, the lock is acquired atomically with
    /// opening the file:
    /// * Darwin
    /// * DragonFlyBSD
    /// * FreeBSD
    /// * Haiku
    /// * NetBSD
    /// * OpenBSD
    /// On these operating systems, the lock is acquired via a separate syscall
    /// after opening the file:
    /// * Linux
    /// * Windows
    ///
    /// [1]: https://www.kernel.org/doc/Documentation/filesystems/mandatory-locking.txt
    lock: File.Lock = .none,
    /// Sets whether or not to wait until the file is locked to return. If set to true,
    /// `error.WouldBlock` will be returned. Otherwise, the file will wait until the file
    /// is available to proceed.
    lock_nonblocking: bool = false,
    /// Set this to allow the opened file to automatically become the
    /// controlling TTY for the current process.
    allow_ctty: bool = false,
    follow_symlinks: bool = true,
    /// If supported by the operating system, attempted path resolution that
    /// would escape the directory instead returns `error.AccessDenied`. If
    /// unsupported, this option is ignored.
    resolve_beneath: bool = false,

    pub const Mode = enum { read_only, write_only, read_write };

    pub fn isRead(self: OpenFileOptions) bool {
        return self.mode != .write_only;
    }

    pub fn isWrite(self: OpenFileOptions) bool {
        return self.mode != .read_only;
    }
};

/// Opens a file for reading or writing, without attempting to create a new file.
///
/// To create a new file, see `createFile`.
///
/// Allocates a resource to be released with `File.close`.
///
/// On Windows, `sub_path` should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// On WASI, `sub_path` should be encoded as valid UTF-8.
/// On other platforms, `sub_path` is an opaque sequence of bytes with no particular encoding.
pub fn openFile(dir: Dir, io: Io, sub_path: []const u8, options: OpenFileOptions) File.OpenError!File {
    return io.vtable.dirOpenFile(io.userdata, dir, sub_path, options);
}

pub fn openFileAbsolute(io: Io, absolute_path: []const u8, options: OpenFileOptions) File.OpenError!File {
    assert(path.isAbsolute(absolute_path));
    return openFile(.cwd(), io, absolute_path, options);
}

pub const CreateFileOptions = struct {
    /// Whether the file will be created with read access.
    read: bool = false,
    /// If the file already exists, and is a regular file, and the access
    /// mode allows writing, it will be truncated to length 0.
    truncate: bool = true,
    /// Ensures that this open call creates the file, otherwise causes
    /// `error.PathAlreadyExists` to be returned.
    exclusive: bool = false,
    /// Open the file with an advisory lock to coordinate with other processes
    /// accessing it at the same time. An exclusive lock will prevent other
    /// processes from acquiring a lock. A shared lock will prevent other
    /// processes from acquiring a exclusive lock, but does not prevent
    /// other process from getting their own shared locks.
    ///
    /// The lock is advisory, except on Linux in very specific circumstances[1].
    /// This means that a process that does not respect the locking API can still get access
    /// to the file, despite the lock.
    ///
    /// On these operating systems, the lock is acquired atomically with
    /// opening the file:
    /// * Darwin
    /// * DragonFlyBSD
    /// * FreeBSD
    /// * Haiku
    /// * NetBSD
    /// * OpenBSD
    /// On these operating systems, the lock is acquired via a separate syscall
    /// after opening the file:
    /// * Linux
    /// * Windows
    ///
    /// [1]: https://www.kernel.org/doc/Documentation/filesystems/mandatory-locking.txt
    lock: File.Lock = .none,
    /// Sets whether or not to wait until the file is locked to return. If set to true,
    /// `error.WouldBlock` will be returned. Otherwise, the file will wait until the file
    /// is available to proceed.
    lock_nonblocking: bool = false,
    permissions: Permissions = .default_file,
    /// If supported by the operating system, attempted path resolution that
    /// would escape the directory instead returns `error.AccessDenied`. If
    /// unsupported, this option is ignored.
    resolve_beneath: bool = false,
};

/// Creates, opens, or overwrites a file with write access.
///
/// Allocates a resource to be dellocated with `File.close`.
///
/// On Windows, `sub_path` should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// On WASI, `sub_path` should be encoded as valid UTF-8.
/// On other platforms, `sub_path` is an opaque sequence of bytes with no particular encoding.
pub fn createFile(dir: Dir, io: Io, sub_path: []const u8, flags: CreateFileOptions) File.OpenError!File {
    return io.vtable.dirCreateFile(io.userdata, dir, sub_path, flags);
}

pub fn createFileAbsolute(io: Io, absolute_path: []const u8, flags: CreateFileOptions) File.OpenError!File {
    return createFile(.cwd(), io, absolute_path, flags);
}

pub const WriteFileOptions = struct {
    /// On Windows, `sub_path` should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
    /// On WASI, `sub_path` should be encoded as valid UTF-8.
    /// On other platforms, `sub_path` is an opaque sequence of bytes with no particular encoding.
    sub_path: []const u8,
    data: []const u8,
    flags: CreateFileOptions = .{},
};

pub const WriteFileError = File.Writer.Error || File.OpenError;

/// Writes content to the file system, using the file creation flags provided.
pub fn writeFile(dir: Dir, io: Io, options: WriteFileOptions) WriteFileError!void {
    var file = try dir.createFile(io, options.sub_path, options.flags);
    defer file.close(io);
    try file.writeStreamingAll(io, options.data);
}

pub const PrevStatus = enum {
    stale,
    fresh,
};

pub const UpdateFileError = File.OpenError;

/// Check the file size, mtime, and permissions of `source_path` and `dest_path`. If
/// they are equal, does nothing. Otherwise, atomically copies `source_path` to
/// `dest_path`, creating the parent directory hierarchy as needed. The
/// destination file gains the mtime, atime, and permissions of the source file so
/// that the next call to `updateFile` will not need a copy.
///
/// Returns the previous status of the file before updating.
///
/// * On Windows, both paths should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// * On WASI, both paths should be encoded as valid UTF-8.
/// * On other platforms, both paths are an opaque sequence of bytes with no particular encoding.
pub fn updateFile(
    source_dir: Dir,
    io: Io,
    source_path: []const u8,
    dest_dir: Dir,
    /// If directories in this path do not exist, they are created.
    dest_path: []const u8,
    options: CopyFileOptions,
) !PrevStatus {
    var src_file = try source_dir.openFile(io, source_path, .{});
    defer src_file.close(io);

    const src_stat = try src_file.stat(io);
    const actual_permissions = options.permissions orelse src_stat.permissions;
    check_dest_stat: {
        const dest_stat = blk: {
            var dest_file = dest_dir.openFile(io, dest_path, .{}) catch |err| switch (err) {
                error.FileNotFound => break :check_dest_stat,
                else => |e| return e,
            };
            defer dest_file.close(io);

            break :blk try dest_file.stat(io);
        };

        if (src_stat.size == dest_stat.size and
            src_stat.mtime.nanoseconds == dest_stat.mtime.nanoseconds and
            actual_permissions == dest_stat.permissions)
        {
            return .fresh;
        }
    }

    var atomic_file = try dest_dir.createFileAtomic(io, dest_path, .{
        .permissions = actual_permissions,
        .make_path = true,
        .replace = true,
    });
    defer atomic_file.deinit(io);

    var buffer: [1024]u8 = undefined; // Used only when direct fd-to-fd is not available.
    var file_writer = atomic_file.file.writer(io, &buffer);

    var src_reader: File.Reader = .initSize(src_file, io, &.{}, src_stat.size);
    const dest_writer = &file_writer.interface;

    _ = dest_writer.sendFileAll(&src_reader, .unlimited) catch |err| switch (err) {
        error.ReadFailed => return src_reader.err.?,
        error.WriteFailed => return file_writer.err.?,
    };
    try file_writer.flush();
    try file_writer.file.setTimestamps(io, .{
        .access_timestamp = .init(src_stat.atime),
        .modify_timestamp = .init(src_stat.mtime),
    });
    try atomic_file.replace(io);
    return .stale;
}

pub const ReadFileError = File.OpenError || File.Reader.Error;

/// Read all of file contents using a preallocated buffer.
///
/// The returned slice has the same pointer as `buffer`. If the length matches `buffer.len`
/// the situation is ambiguous. It could either mean that the entire file was read, and
/// it exactly fits the buffer, or it could mean the buffer was not big enough for the
/// entire file.
///
/// * On Windows, `file_path` should be encoded as [WTF-8](https://simonsapin.github.io/wtf-8/).
/// * On WASI, `file_path` should be encoded as valid UTF-8.
/// * On other platforms, `file_path` is an opaque sequence of bytes with no particular encoding.
pub fn readFile(dir: Dir, io: Io, file_path: []const u8, buffer: []u8) ReadFileError![]u8 {
    var file = try dir.openFile(io, file_path, .{
        // We can take advantage of this on Windows since it doesn't involve any extra syscalls,
        // so we can get error.IsDir during open rather than during the read.
        .allow_directory = if (native_os == .windows) false else true,
    });
    defer file.close(io);

    var reader = file.reader(io, &.{});
    const n = reader.interface.readSliceShort(buffer) catch |err| switch (err) {
        error.ReadFailed => return reader.err.?,
    };

    return buffer[0..n];
}

pub const CreateDirError = error{
    /// In WASI, this error may occur when the file descriptor does
    /// not hold the required rights to create a new directory relative to it.
    AccessDenied,
    PermissionDenied,
    DiskQuota,
    PathAlreadyExists,
    SymLinkLoop,
    LinkQuotaExceeded,
    FileNotFound,
    SystemResources,
    NoSpaceLeft,
    NotDir,
    ReadOnlyFileSystem,
    NoDevice,
    /// On Windows, `\\server` or `\\server\share` was not found.
    NetworkNotFound,
} || PathNameError || Io.Cancelable || Io.UnexpectedError;

/// Creates a single directory with a relative or absolute path.
///
/// * On Windows, `sub_path` should be encoded as [WTF-8](https://simonsapin.github.io/wtf-8/).
/// * On WASI, `sub_path` should be encoded as valid UTF-8.
/// * On other platforms, `sub_path` is an opaque sequence of bytes with no particular encoding.
///
/// Related:
/// * `createDirPath`
/// * `createDirAbsolute`
pub fn createDir(dir: Dir, io: Io, sub_path: []const u8, permissions: Permissions) CreateDirError!void {
    return io.vtable.dirCreateDir(io.userdata, dir, sub_path, permissions);
}

/// Create a new directory, based on an absolute path.
///
/// Asserts that the path is absolute. See `createDir` for a function that
/// operates on both absolute and relative paths.
///
/// On Windows, `absolute_path` should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// On WASI, `absolute_path` should be encoded as valid UTF-8.
/// On other platforms, `absolute_path` is an opaque sequence of bytes with no particular encoding.
pub fn createDirAbsolute(io: Io, absolute_path: []const u8, permissions: Permissions) CreateDirError!void {
    assert(path.isAbsolute(absolute_path));
    return createDir(.cwd(), io, absolute_path, permissions);
}

test createDirAbsolute {}

pub const CreateDirPathError = CreateDirError || StatFileError;

/// Creates parent directories with default permissions as necessary to ensure
/// `sub_path` exists as a directory.
///
/// Returns success if the path already exists and is a directory.
///
/// This function may not be atomic. If it returns an error, the file system
/// may have been modified.
///
/// Fails on an empty path with `error.BadPathName` as that is not a path that
/// can be created.
///
/// On Windows, `sub_path` should be encoded as [WTF-8](https://simonsapin.github.io/wtf-8/).
/// On WASI, `sub_path` should be encoded as valid UTF-8.
/// On other platforms, `sub_path` is an opaque sequence of bytes with no particular encoding.
///
/// Paths containing `..` components are handled differently depending on the platform:
/// - On Windows, `..` are resolved before the path is passed to NtCreateFile, meaning
///   a `sub_path` like "first/../second" will resolve to "second" and only a
///   `./second` directory will be created.
/// - On other platforms, `..` are not resolved before the path is passed to `mkdirat`,
///   meaning a `sub_path` like "first/../second" will create both a `./first`
///   and a `./second` directory.
///
/// See also:
/// * `createDirPathStatus`
pub fn createDirPath(dir: Dir, io: Io, sub_path: []const u8) CreateDirPathError!void {
    _ = try io.vtable.dirCreateDirPath(io.userdata, dir, sub_path, .default_dir);
}

pub const CreatePathStatus = enum { existed, created };

/// Same as `createDirPath` except returns whether the path already existed or was
/// successfully created.
pub fn createDirPathStatus(dir: Dir, io: Io, sub_path: []const u8, permissions: Permissions) CreateDirPathError!CreatePathStatus {
    return io.vtable.dirCreateDirPath(io.userdata, dir, sub_path, permissions);
}

pub const CreateDirPathOpenError = CreateDirError || OpenError || StatFileError;

pub const CreateDirPathOpenOptions = struct {
    open_options: OpenOptions = .{},
    permissions: Permissions = .default_dir,
};

/// Performs the equivalent of `createDirPath` followed by `openDir`, atomically if possible.
///
/// When this operation is canceled, it may leave the file system in a
/// partially modified state.
///
/// On Windows, `sub_path` should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// On WASI, `sub_path` should be encoded as valid UTF-8.
/// On other platforms, `sub_path` is an opaque sequence of bytes with no particular encoding.
pub fn createDirPathOpen(dir: Dir, io: Io, sub_path: []const u8, options: CreateDirPathOpenOptions) CreateDirPathOpenError!Dir {
    return io.vtable.dirCreateDirPathOpen(io.userdata, dir, sub_path, options.permissions, options.open_options);
}

pub const Stat = File.Stat;
pub const StatError = File.StatError;

pub fn stat(dir: Dir, io: Io) StatError!Stat {
    return io.vtable.dirStat(io.userdata, dir);
}

pub const StatFileError = File.OpenError || File.StatError;

pub const StatFileOptions = struct {
    follow_symlinks: bool = true,
};

/// Returns metadata for a file inside the directory.
///
/// On Windows, this requires three syscalls. On other operating systems, it
/// only takes one.
///
/// Symlinks are followed.
///
/// `sub_path` may be absolute, in which case `self` is ignored.
///
/// * On Windows, `sub_path` should be encoded as [WTF-8](https://simonsapin.github.io/wtf-8/).
/// * On WASI, `sub_path` should be encoded as valid UTF-8.
/// * On other platforms, `sub_path` is an opaque sequence of bytes with no particular encoding.
pub fn statFile(dir: Dir, io: Io, sub_path: []const u8, options: StatFileOptions) StatFileError!Stat {
    return io.vtable.dirStatFile(io.userdata, dir, sub_path, options);
}

pub const RealPathError = File.RealPathError;

/// Obtains the canonicalized absolute path name of `sub_path` relative to this
/// `Dir`. If `sub_path` is absolute, ignores this `Dir` handle and obtains the
/// canonicalized absolute pathname of `sub_path` argument.
///
/// This function has limited platform support, and using it can lead to
/// unnecessary failures and race conditions. It is generally advisable to
/// avoid this function entirely.
pub fn realPath(dir: Dir, io: Io, out_buffer: []u8) RealPathError!usize {
    return io.vtable.dirRealPath(io.userdata, dir, out_buffer);
}

pub const RealPathFileError = RealPathError || PathNameError;

/// Obtains the canonicalized absolute path name of `sub_path` relative to this
/// `Dir`. If `sub_path` is absolute, ignores this `Dir` handle and obtains the
/// canonicalized absolute pathname of `sub_path` argument.
///
/// This function has limited platform support, and using it can lead to
/// unnecessary failures and race conditions. It is generally advisable to
/// avoid this function entirely.
///
/// See also:
/// * `realPathFileAlloc`.
/// * `realPathFileAbsolute`.
pub fn realPathFile(dir: Dir, io: Io, sub_path: []const u8, out_buffer: []u8) RealPathFileError!usize {
    return io.vtable.dirRealPathFile(io.userdata, dir, sub_path, out_buffer);
}

pub const RealPathFileAllocError = RealPathFileError || Allocator.Error;

/// Same as `realPathFile` except allocates result.
///
/// This function has limited platform support, and using it can lead to
/// unnecessary failures and race conditions. It is generally advisable to
/// avoid this function entirely.
///
/// See also:
/// * `realPathFile`.
/// * `realPathFileAbsolute`.
pub fn realPathFileAlloc(dir: Dir, io: Io, sub_path: []const u8, allocator: Allocator) RealPathFileAllocError![:0]u8 {
    var buffer: [max_path_bytes]u8 = undefined;
    const n = try realPathFile(dir, io, sub_path, &buffer);
    return allocator.dupeSentinel(u8, buffer[0..n], 0);
}

/// Same as `realPathFile` except `absolute_path` is asserted to be an absolute
/// path.
///
/// This function has limited platform support, and using it can lead to
/// unnecessary failures and race conditions. It is generally advisable to
/// avoid this function entirely.
///
/// See also:
/// * `realPathFile`.
/// * `realPathFileAlloc`.
pub fn realPathFileAbsolute(io: Io, absolute_path: []const u8, out_buffer: []u8) RealPathFileError!usize {
    assert(path.isAbsolute(absolute_path));
    return io.vtable.dirRealPathFile(io.userdata, .cwd(), absolute_path, out_buffer);
}

/// Same as `realPathFileAbsolute` except allocates result.
///
/// This function has limited platform support, and using it can lead to
/// unnecessary failures and race conditions. It is generally advisable to
/// avoid this function entirely.
///
/// See also:
/// * `realPathFileAbsolute`.
/// * `realPathFile`.
pub fn realPathFileAbsoluteAlloc(io: Io, absolute_path: []const u8, allocator: Allocator) RealPathFileAllocError![:0]u8 {
    var buffer: [max_path_bytes]u8 = undefined;
    const n = try realPathFileAbsolute(io, absolute_path, &buffer);
    return allocator.dupeSentinel(u8, buffer[0..n], 0);
}

pub const DeleteFileError = error{
    FileNotFound,
    /// In WASI, this error may occur when the file descriptor does
    /// not hold the required rights to unlink a resource by path relative to it.
    AccessDenied,
    PermissionDenied,
    FileBusy,
    FileSystem,
    IsDir,
    SymLinkLoop,
    NotDir,
    SystemResources,
    ReadOnlyFileSystem,
    /// On Windows, `\\server` or `\\server\share` was not found.
    NetworkNotFound,
} || PathNameError || Io.Cancelable || Io.UnexpectedError;

/// Delete a file name and possibly the file it refers to, based on an open directory handle.
///
/// On Windows, `sub_path` should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// On WASI, `sub_path` should be encoded as valid UTF-8.
/// On other platforms, `sub_path` is an opaque sequence of bytes with no particular encoding.
///
/// Asserts that the path parameter has no null bytes.
pub fn deleteFile(dir: Dir, io: Io, sub_path: []const u8) DeleteFileError!void {
    return io.vtable.dirDeleteFile(io.userdata, dir, sub_path);
}

pub fn deleteFileAbsolute(io: Io, absolute_path: []const u8) DeleteFileError!void {
    assert(path.isAbsolute(absolute_path));
    return deleteFile(.cwd(), io, absolute_path);
}

test deleteFileAbsolute {}

pub const DeleteDirError = error{
    DirNotEmpty,
    FileNotFound,
    AccessDenied,
    PermissionDenied,
    FileBusy,
    FileSystem,
    SymLinkLoop,
    NotDir,
    SystemResources,
    ReadOnlyFileSystem,
    /// On Windows, `\\server` or `\\server\share` was not found.
    NetworkNotFound,
} || PathNameError || Io.Cancelable || Io.UnexpectedError;

/// Returns `error.DirNotEmpty` if the directory is not empty.
///
/// To delete a directory recursively, see `deleteTree`.
///
/// On Windows, `sub_path` should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// On WASI, `sub_path` should be encoded as valid UTF-8.
/// On other platforms, `sub_path` is an opaque sequence of bytes with no particular encoding.
pub fn deleteDir(dir: Dir, io: Io, sub_path: []const u8) DeleteDirError!void {
    return io.vtable.dirDeleteDir(io.userdata, dir, sub_path);
}

/// Same as `deleteDir` except the path is absolute.
///
/// On Windows, `dir_path` should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// On WASI, `dir_path` should be encoded as valid UTF-8.
/// On other platforms, `dir_path` is an opaque sequence of bytes with no particular encoding.
pub fn deleteDirAbsolute(io: Io, absolute_path: []const u8) DeleteDirError!void {
    assert(path.isAbsolute(absolute_path));
    return deleteDir(.cwd(), io, absolute_path);
}

pub const RenameError = error{
    /// In WASI, this error may occur when the file descriptor does
    /// not hold the required rights to rename a resource by path relative to it.
    AccessDenied,
    /// Attempted to replace a nonempty directory.
    DirNotEmpty,
    PermissionDenied,
    /// The file attempted to be moved or replaced is a running executable.
    FileBusy,
    DiskQuota,
    IsDir,
    SymLinkLoop,
    LinkQuotaExceeded,
    FileNotFound,
    NotDir,
    SystemResources,
    NoSpaceLeft,
    ReadOnlyFileSystem,
    CrossDevice,
    NoDevice,
    PipeBusy,
    /// On Windows, `\\server` or `\\server\share` was not found.
    NetworkNotFound,
    /// On Windows, antivirus software is enabled by default. It can be
    /// disabled, but Windows Update sometimes ignores the user's preference
    /// and re-enables it. When enabled, antivirus software on Windows
    /// intercepts file system operations and makes them significantly slower
    /// in addition to possibly failing with this error code.
    AntivirusInterference,
    HardwareFailure,
} || PathNameError || Io.Cancelable || Io.UnexpectedError;

/// Change the name or location of a file or directory.
///
/// If `new_sub_path` already exists, it will be replaced.
///
/// Renaming a file over an existing directory or a directory over an existing
/// file will fail with `error.IsDir` or `error.NotDir`
///
/// * On Windows, both paths should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// * On WASI, both paths should be encoded as valid UTF-8.
/// * On other platforms, both paths are an opaque sequence of bytes with no particular encoding.
pub fn rename(
    old_dir: Dir,
    old_sub_path: []const u8,
    new_dir: Dir,
    new_sub_path: []const u8,
    io: Io,
) RenameError!void {
    return io.vtable.dirRename(io.userdata, old_dir, old_sub_path, new_dir, new_sub_path);
}

pub fn renameAbsolute(old_path: []const u8, new_path: []const u8, io: Io) RenameError!void {
    assert(path.isAbsolute(old_path));
    assert(path.isAbsolute(new_path));
    const my_cwd = cwd();
    return io.vtable.dirRename(io.userdata, my_cwd, old_path, my_cwd, new_path);
}

pub const RenamePreserveError = error{
    /// In WASI, this error may occur when the file descriptor does
    /// not hold the required rights to rename a resource by path relative to it.
    ///
    /// On Windows, this error may be returned instead of PathAlreadyExists when
    /// renaming a directory over an existing directory.
    ///
    /// On Darwin, this error may be returned when a component of either pathname
    /// refers to a "dataless" directory that requires materialization, and the I/O
    /// policy of the current thread or process disallows dataless directory materialization.
    AccessDenied,
    PathAlreadyExists,
    /// Operating system or file system does not support atomic nonreplacing
    /// rename.
    OperationUnsupported,
} || RenameError;

/// Change the name or location of a file or directory.
///
/// If `new_sub_path` already exists, `error.PathAlreadyExists` will be returned.
///
/// * On Windows, both paths should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// * On WASI, both paths should be encoded as valid UTF-8.
/// * On other platforms, both paths are an opaque sequence of bytes with no particular encoding.
pub fn renamePreserve(
    old_dir: Dir,
    old_sub_path: []const u8,
    new_dir: Dir,
    new_sub_path: []const u8,
    io: Io,
) RenamePreserveError!void {
    return io.vtable.dirRenamePreserve(io.userdata, old_dir, old_sub_path, new_dir, new_sub_path);
}

pub const HardLinkOptions = File.HardLinkOptions;

pub const HardLinkError = File.HardLinkError;

pub fn hardLink(
    old_dir: Dir,
    old_sub_path: []const u8,
    new_dir: Dir,
    new_sub_path: []const u8,
    io: Io,
    options: HardLinkOptions,
) HardLinkError!void {
    return io.vtable.dirHardLink(io.userdata, old_dir, old_sub_path, new_dir, new_sub_path, options);
}

/// Use with `symLink`, `symLinkAtomic`, and `symLinkAbsolute` to
/// specify whether the symlink will point to a file or a directory. This value
/// is ignored on all hosts except Windows where creating symlinks to different
/// resource types, requires different flags. By default, `symLinkAbsolute` is
/// assumed to point to a file.
pub const SymLinkFlags = struct {
    is_directory: bool = false,
};

pub const SymLinkError = error{
    /// In WASI, this error may occur when the file descriptor does
    /// not hold the required rights to create a new symbolic link relative to it.
    AccessDenied,
    PermissionDenied,
    DiskQuota,
    PathAlreadyExists,
    FileSystem,
    SymLinkLoop,
    FileNotFound,
    SystemResources,
    NoSpaceLeft,
    /// On Windows, `\\server` or `\\server\share` was not found.
    NetworkNotFound,
    ReadOnlyFileSystem,
    NotDir,
} || PathNameError || Io.Cancelable || Io.UnexpectedError;

/// Creates a symbolic link named `sym_link_path` which contains the string `target_path`.
///
/// A symbolic link (also known as a soft link) may point to an existing file or to a nonexistent
/// one; the latter case is known as a dangling link.
///
/// If `sym_link_path` exists, it will not be overwritten.
///
/// On Windows, both paths should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// On WASI, both paths should be encoded as valid UTF-8.
/// On other platforms, both paths are an opaque sequence of bytes with no particular encoding.
pub fn symLink(
    dir: Dir,
    io: Io,
    target_path: []const u8,
    sym_link_path: []const u8,
    flags: SymLinkFlags,
) SymLinkError!void {
    return io.vtable.dirSymLink(io.userdata, dir, target_path, sym_link_path, flags);
}

pub fn symLinkAbsolute(
    io: Io,
    target_path: []const u8,
    sym_link_path: []const u8,
    flags: SymLinkFlags,
) SymLinkError!void {
    assert(path.isAbsolute(target_path));
    assert(path.isAbsolute(sym_link_path));
    return symLink(.cwd(), io, target_path, sym_link_path, flags);
}

/// Same as `symLink`, except tries to create the symbolic link until it
/// succeeds or encounters an error other than `error.PathAlreadyExists`.
///
/// * On Windows, both paths should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// * On WASI, both paths should be encoded as valid UTF-8.
/// * On other platforms, both paths are an opaque sequence of bytes with no particular encoding.
pub fn symLinkAtomic(
    dir: Dir,
    io: Io,
    target_path: []const u8,
    sym_link_path: []const u8,
    flags: SymLinkFlags,
) !void {
    if (dir.symLink(io, target_path, sym_link_path, flags)) {
        return;
    } else |err| switch (err) {
        error.PathAlreadyExists => {},
        else => |e| return e,
    }

    const dirname = path.dirname(sym_link_path) orelse ".";

    const rand_len = @sizeOf(u64) * 2;
    const temp_path_len = dirname.len + 1 + rand_len;
    var temp_path_buf: [max_path_bytes]u8 = undefined;

    if (temp_path_len > temp_path_buf.len) return error.NameTooLong;
    @memcpy(temp_path_buf[0..dirname.len], dirname);
    temp_path_buf[dirname.len] = path.sep;

    const temp_path = temp_path_buf[0..temp_path_len];

    var random_integer: u64 = undefined;

    while (true) {
        io.random(@ptrCast(&random_integer));
        temp_path[dirname.len + 1 ..][0..rand_len].* = std.fmt.hex(random_integer);

        if (dir.symLink(io, target_path, temp_path, flags)) {
            return dir.rename(temp_path, dir, sym_link_path, io);
        } else |err| switch (err) {
            error.PathAlreadyExists => continue,
            else => |e| return e,
        }
    }
}

pub const ReadLinkError = error{
    /// In WASI, this error may occur when the file descriptor does
    /// not hold the required rights to read value of a symbolic link relative to it.
    AccessDenied,
    PermissionDenied,
    FileSystem,
    SymLinkLoop,
    FileNotFound,
    SystemResources,
    NotLink,
    NotDir,
    /// Windows-only. This error may occur if the opened reparse point is
    /// of unsupported type.
    UnsupportedReparsePointType,
    /// On Windows, `\\server` or `\\server\share` was not found.
    NetworkNotFound,
    /// On Windows, antivirus software is enabled by default. It can be
    /// disabled, but Windows Update sometimes ignores the user's preference
    /// and re-enables it. When enabled, antivirus software on Windows
    /// intercepts file system operations and makes them significantly slower
    /// in addition to possibly failing with this error code.
    AntivirusInterference,
    /// File attempted to be opened is a running executable.
    FileBusy,
} || PathNameError || Io.Cancelable || Io.UnexpectedError;

/// Obtain target of a symbolic link.
///
/// Returns how many bytes of `buffer` are populated.
///
/// Asserts that the path parameter has no null bytes.
///
/// On Windows, `sub_path` should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// On WASI, `sub_path` should be encoded as valid UTF-8.
/// On other platforms, `sub_path` is an opaque sequence of bytes with no particular encoding.
pub fn readLink(dir: Dir, io: Io, sub_path: []const u8, buffer: []u8) ReadLinkError!usize {
    return io.vtable.dirReadLink(io.userdata, dir, sub_path, buffer);
}

/// Same as `readLink`, except it asserts the path is absolute.
///
/// On Windows, `path` should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// On WASI, `path` should be encoded as valid UTF-8.
/// On other platforms, `path` is an opaque sequence of bytes with no particular encoding.
pub fn readLinkAbsolute(io: Io, absolute_path: []const u8, buffer: []u8) ReadLinkError!usize {
    assert(path.isAbsolute(absolute_path));
    return io.vtable.dirReadLink(io.userdata, .cwd(), absolute_path, buffer);
}

pub const ReadFileAllocError = File.OpenError || File.Reader.Error || Allocator.Error || error{
    /// File size reached or exceeded the provided limit.
    StreamTooLong,
};

/// Reads all the bytes from the named file. On success, caller owns returned
/// buffer.
///
/// If the file size is already known, a better alternative is to initialize a
/// `File.Reader`.
///
/// If the file size cannot be obtained, an error is returned. If
/// this is a realistic possibility, a better alternative is to initialize a
/// `File.Reader` which handles this seamlessly.
pub fn readFileAlloc(
    dir: Dir,
    io: Io,
    /// On Windows, should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
    /// On WASI, should be encoded as valid UTF-8.
    /// On other platforms, an opaque sequence of bytes with no particular encoding.
    sub_path: []const u8,
    /// Used to allocate the result.
    gpa: Allocator,
    /// If reached or exceeded, `error.StreamTooLong` is returned instead.
    limit: Io.Limit,
) ReadFileAllocError![]u8 {
    return readFileAllocOptions(dir, io, sub_path, gpa, limit, .of(u8), null);
}

/// Reads all the bytes from the named file. On success, caller owns returned
/// buffer.
///
/// If the file size is already known, a better alternative is to initialize a
/// `File.Reader`.
pub fn readFileAllocOptions(
    dir: Dir,
    io: Io,
    /// On Windows, should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
    /// On WASI, should be encoded as valid UTF-8.
    /// On other platforms, an opaque sequence of bytes with no particular encoding.
    sub_path: []const u8,
    /// Used to allocate the result.
    gpa: Allocator,
    /// If reached or exceeded, `error.StreamTooLong` is returned instead.
    limit: Io.Limit,
    comptime alignment: std.mem.Alignment,
    comptime sentinel: ?u8,
) ReadFileAllocError!(if (sentinel) |s| [:s]align(alignment.toByteUnits()) u8 else []align(alignment.toByteUnits()) u8) {
    var file = try dir.openFile(io, sub_path, .{
        // We can take advantage of this on Windows since it doesn't involve any extra syscalls,
        // so we can get error.IsDir during open rather than during the read.
        .allow_directory = if (native_os == .windows) false else true,
    });
    defer file.close(io);
    var file_reader = file.reader(io, &.{});
    return file_reader.interface.allocRemainingAlignedSentinel(gpa, limit, alignment, sentinel) catch |err| switch (err) {
        error.ReadFailed => return file_reader.err.?,
        error.OutOfMemory, error.StreamTooLong => |e| return e,
    };
}

pub const DeleteTreeError = error{
    AccessDenied,
    PermissionDenied,
    FileTooBig,
    SymLinkLoop,
    ProcessFdQuotaExceeded,
    SystemFdQuotaExceeded,
    NoDevice,
    SystemResources,
    ReadOnlyFileSystem,
    FileSystem,
    FileBusy,
    /// One of the path components was not a directory.
    /// This error is unreachable if `sub_path` does not contain a path separator.
    NotDir,
    /// On Windows, `\\server` or `\\server\share` was not found.
    NetworkNotFound,
} || PathNameError || Io.Cancelable || Io.UnexpectedError;

/// Whether `sub_path` describes a symlink, file, or directory, this function
/// removes it. If it cannot be removed because it is a non-empty directory,
/// this function recursively removes its entries and then tries again.
///
/// This operation is not atomic on most file systems.
///
/// On Windows, `sub_path` should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// On WASI, `sub_path` should be encoded as valid UTF-8.
/// On other platforms, `sub_path` is an opaque sequence of bytes with no particular encoding.
pub fn deleteTree(dir: Dir, io: Io, sub_path: []const u8) DeleteTreeError!void {
    var initial_iterable_dir = (try dir.deleteTreeOpenInitialSubpath(io, sub_path, .file)) orelse return;

    const StackItem = struct {
        name: []const u8,
        parent_dir: Dir,
        iter: Iterator,

        fn closeAll(inner_io: Io, items: []@This()) void {
            for (items) |*item| item.iter.reader.dir.close(inner_io);
        }
    };

    var stack_buffer: [16]StackItem = undefined;
    var stack = std.ArrayList(StackItem).initBuffer(&stack_buffer);
    defer StackItem.closeAll(io, stack.items);

    stack.appendAssumeCapacity(.{
        .name = sub_path,
        .parent_dir = dir,
        .iter = initial_iterable_dir.iterateAssumeFirstIteration(),
    });

    process_stack: while (stack.items.len != 0) {
        var top = &stack.items[stack.items.len - 1];
        while (try top.iter.next(io)) |entry| {
            var treat_as_dir = entry.kind == .directory;
            handle_entry: while (true) {
                if (treat_as_dir) {
                    if (stack.unusedCapacitySlice().len >= 1) {
                        var iterable_dir = top.iter.reader.dir.openDir(io, entry.name, .{
                            .follow_symlinks = false,
                            .iterate = true,
                        }) catch |err| switch (err) {
                            error.NotDir => {
                                treat_as_dir = false;
                                continue :handle_entry;
                            },
                            error.FileNotFound => {
                                // That's fine, we were trying to remove this directory anyway.
                                break :handle_entry;
                            },

                            error.AccessDenied,
                            error.PermissionDenied,
                            error.SymLinkLoop,
                            error.ProcessFdQuotaExceeded,
                            error.NameTooLong,
                            error.SystemFdQuotaExceeded,
                            error.NoDevice,
                            error.SystemResources,
                            error.Unexpected,
                            error.BadPathName,
                            error.NetworkNotFound,
                            error.Canceled,
                            => |e| return e,
                        };
                        stack.appendAssumeCapacity(.{
                            .name = entry.name,
                            .parent_dir = top.iter.reader.dir,
                            .iter = iterable_dir.iterateAssumeFirstIteration(),
                        });
                        continue :process_stack;
                    } else {
                        try top.iter.reader.dir.deleteTreeMinStackSizeWithKindHint(io, entry.name, entry.kind);
                        break :handle_entry;
                    }
                } else {
                    if (top.iter.reader.dir.deleteFile(io, entry.name)) {
                        break :handle_entry;
                    } else |err| switch (err) {
                        error.FileNotFound => break :handle_entry,

                        // Impossible because we do not pass any path separators.
                        error.NotDir => unreachable,

                        error.IsDir => {
                            treat_as_dir = true;
                            continue :handle_entry;
                        },

                        error.AccessDenied,
                        error.PermissionDenied,
                        error.SymLinkLoop,
                        error.NameTooLong,
                        error.SystemResources,
                        error.ReadOnlyFileSystem,
                        error.FileSystem,
                        error.FileBusy,
                        error.BadPathName,
                        error.NetworkNotFound,
                        error.Canceled,
                        error.Unexpected,
                        => |e| return e,
                    }
                }
            }
        }

        // On Windows, we can't delete until the dir's handle has been closed, so
        // close it before we try to delete.
        top.iter.reader.dir.close(io);

        // In order to avoid double-closing the directory when cleaning up
        // the stack in the case of an error, we save the relevant portions and
        // pop the value from the stack.
        const parent_dir = top.parent_dir;
        const name = top.name;
        stack.items.len -= 1;

        var need_to_retry: bool = false;
        parent_dir.deleteDir(io, name) catch |err| switch (err) {
            error.FileNotFound => {},
            error.DirNotEmpty => need_to_retry = true,
            else => |e| return e,
        };

        if (need_to_retry) {
            // Since we closed the handle that the previous iterator used, we
            // need to re-open the dir and re-create the iterator.
            var iterable_dir = iterable_dir: {
                var treat_as_dir = true;
                handle_entry: while (true) {
                    if (treat_as_dir) {
                        break :iterable_dir parent_dir.openDir(io, name, .{
                            .follow_symlinks = false,
                            .iterate = true,
                        }) catch |err| switch (err) {
                            error.NotDir => {
                                treat_as_dir = false;
                                continue :handle_entry;
                            },
                            error.FileNotFound => {
                                // That's fine, we were trying to remove this directory anyway.
                                continue :process_stack;
                            },

                            error.AccessDenied,
                            error.PermissionDenied,
                            error.SymLinkLoop,
                            error.ProcessFdQuotaExceeded,
                            error.NameTooLong,
                            error.SystemFdQuotaExceeded,
                            error.NoDevice,
                            error.SystemResources,
                            error.Unexpected,
                            error.BadPathName,
                            error.NetworkNotFound,
                            error.Canceled,
                            => |e| return e,
                        };
                    } else {
                        if (parent_dir.deleteFile(io, name)) {
                            continue :process_stack;
                        } else |err| switch (err) {
                            error.FileNotFound => continue :process_stack,

                            // Impossible because we do not pass any path separators.
                            error.NotDir => unreachable,

                            error.IsDir => {
                                treat_as_dir = true;
                                continue :handle_entry;
                            },

                            error.AccessDenied,
                            error.PermissionDenied,
                            error.SymLinkLoop,
                            error.NameTooLong,
                            error.SystemResources,
                            error.ReadOnlyFileSystem,
                            error.FileSystem,
                            error.FileBusy,
                            error.BadPathName,
                            error.NetworkNotFound,
                            error.Canceled,
                            error.Unexpected,
                            => |e| return e,
                        }
                    }
                }
            };
            // We know there is room on the stack since we are just re-adding
            // the StackItem that we previously popped.
            stack.appendAssumeCapacity(.{
                .name = name,
                .parent_dir = parent_dir,
                .iter = iterable_dir.iterateAssumeFirstIteration(),
            });
            continue :process_stack;
        }
    }
}

/// Like `deleteTree`, but only keeps one `Iterator` active at a time to minimize the function's stack size.
/// This is slower than `deleteTree` but uses less stack space.
/// On Windows, `sub_path` should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// On WASI, `sub_path` should be encoded as valid UTF-8.
/// On other platforms, `sub_path` is an opaque sequence of bytes with no particular encoding.
pub fn deleteTreeMinStackSize(dir: Dir, io: Io, sub_path: []const u8) DeleteTreeError!void {
    return dir.deleteTreeMinStackSizeWithKindHint(io, sub_path, .file);
}

fn deleteTreeMinStackSizeWithKindHint(parent: Dir, io: Io, sub_path: []const u8, kind_hint: File.Kind) DeleteTreeError!void {
    start_over: while (true) {
        var dir = (try parent.deleteTreeOpenInitialSubpath(io, sub_path, kind_hint)) orelse return;
        var cleanup_dir_parent: ?Dir = null;
        defer if (cleanup_dir_parent) |*d| d.close(io);

        var cleanup_dir = true;
        defer if (cleanup_dir) dir.close(io);

        // Valid use of max_path_bytes because dir_name_buf will only
        // ever store a single path component that was returned from the
        // filesystem.
        var dir_name_buf: [max_path_bytes]u8 = undefined;
        var dir_name: []const u8 = sub_path;

        // Here we must avoid recursion, in order to provide O(1) memory guarantee of this function.
        // Go through each entry and if it is not a directory, delete it. If it is a directory,
        // open it, and close the original directory. Repeat. Then start the entire operation over.

        scan_dir: while (true) {
            var dir_it = dir.iterateAssumeFirstIteration();
            dir_it: while (try dir_it.next(io)) |entry| {
                var treat_as_dir = entry.kind == .directory;
                handle_entry: while (true) {
                    if (treat_as_dir) {
                        const new_dir = dir.openDir(io, entry.name, .{
                            .follow_symlinks = false,
                            .iterate = true,
                        }) catch |err| switch (err) {
                            error.NotDir => {
                                treat_as_dir = false;
                                continue :handle_entry;
                            },
                            error.FileNotFound => {
                                // That's fine, we were trying to remove this directory anyway.
                                continue :dir_it;
                            },

                            error.AccessDenied,
                            error.PermissionDenied,
                            error.SymLinkLoop,
                            error.ProcessFdQuotaExceeded,
                            error.NameTooLong,
                            error.SystemFdQuotaExceeded,
                            error.NoDevice,
                            error.SystemResources,
                            error.Unexpected,
                            error.BadPathName,
                            error.NetworkNotFound,
                            error.Canceled,
                            => |e| return e,
                        };
                        if (cleanup_dir_parent) |*d| d.close(io);
                        cleanup_dir_parent = dir;
                        dir = new_dir;
                        const result = dir_name_buf[0..entry.name.len];
                        @memcpy(result, entry.name);
                        dir_name = result;
                        continue :scan_dir;
                    } else {
                        if (dir.deleteFile(io, entry.name)) {
                            continue :dir_it;
                        } else |err| switch (err) {
                            error.FileNotFound => continue :dir_it,

                            // Impossible because we do not pass any path separators.
                            error.NotDir => unreachable,

                            error.IsDir => {
                                treat_as_dir = true;
                                continue :handle_entry;
                            },

                            error.AccessDenied,
                            error.PermissionDenied,
                            error.SymLinkLoop,
                            error.NameTooLong,
                            error.SystemResources,
                            error.ReadOnlyFileSystem,
                            error.FileSystem,
                            error.FileBusy,
                            error.BadPathName,
                            error.NetworkNotFound,
                            error.Canceled,
                            error.Unexpected,
                            => |e| return e,
                        }
                    }
                }
            }
            // Reached the end of the directory entries, which means we successfully deleted all of them.
            // Now to remove the directory itself.
            dir.close(io);
            cleanup_dir = false;

            if (cleanup_dir_parent) |d| {
                d.deleteDir(io, dir_name) catch |err| switch (err) {
                    // These two things can happen due to file system race conditions.
                    error.FileNotFound, error.DirNotEmpty => continue :start_over,
                    else => |e| return e,
                };
                continue :start_over;
            } else {
                parent.deleteDir(io, sub_path) catch |err| switch (err) {
                    error.FileNotFound => return,
                    error.DirNotEmpty => continue :start_over,
                    else => |e| return e,
                };
                return;
            }
        }
    }
}

/// On successful delete, returns null.
fn deleteTreeOpenInitialSubpath(dir: Dir, io: Io, sub_path: []const u8, kind_hint: File.Kind) !?Dir {
    return iterable_dir: {
        // Treat as a file by default
        var treat_as_dir = kind_hint == .directory;

        handle_entry: while (true) {
            if (treat_as_dir) {
                break :iterable_dir dir.openDir(io, sub_path, .{
                    .follow_symlinks = false,
                    .iterate = true,
                }) catch |err| switch (err) {
                    error.NotDir => {
                        treat_as_dir = false;
                        continue :handle_entry;
                    },
                    error.FileNotFound => {
                        // That's fine, we were trying to remove this directory anyway.
                        return null;
                    },

                    error.AccessDenied,
                    error.PermissionDenied,
                    error.SymLinkLoop,
                    error.ProcessFdQuotaExceeded,
                    error.NameTooLong,
                    error.SystemFdQuotaExceeded,
                    error.NoDevice,
                    error.SystemResources,
                    error.Unexpected,
                    error.BadPathName,
                    error.NetworkNotFound,
                    error.Canceled,
                    => |e| return e,
                };
            } else {
                if (dir.deleteFile(io, sub_path)) {
                    return null;
                } else |err| switch (err) {
                    error.FileNotFound => return null,

                    error.IsDir => {
                        treat_as_dir = true;
                        continue :handle_entry;
                    },

                    error.AccessDenied,
                    error.PermissionDenied,
                    error.SymLinkLoop,
                    error.NameTooLong,
                    error.SystemResources,
                    error.ReadOnlyFileSystem,
                    error.NotDir,
                    error.FileSystem,
                    error.FileBusy,
                    error.BadPathName,
                    error.NetworkNotFound,
                    error.Canceled,
                    error.Unexpected,
                    => |e| return e,
                }
            }
        }
    };
}

pub const CopyFileOptions = struct {
    /// When this is `null` the permissions are copied from the source file.
    permissions: ?File.Permissions = null,
    make_path: bool = false,
    replace: bool = true,
};

pub const CopyFileError = File.OpenError || File.StatError ||
    CreateFileAtomicError || File.Atomic.ReplaceError || File.Atomic.LinkError ||
    File.Reader.Error || File.Writer.Error || error{InvalidFileName};

/// Atomically creates a new file at `dest_path` within `dest_dir` with the
/// same contents as `source_path` within `source_dir`.
///
/// Whether to overwrite the existing file is determined by `options`.
///
/// On Linux, until https://patchwork.kernel.org/patch/9636735/ is merged and
/// readily available, there is a possibility of power loss or application
/// termination leaving temporary files present in the same directory as
/// dest_path.
///
/// On Windows, both paths should be encoded as
/// [WTF-8](https://wtf-8.codeberg.page/). On WASI, both paths should be
/// encoded as valid UTF-8. On other platforms, both paths are an opaque
/// sequence of bytes with no particular encoding.
pub fn copyFile(
    source_dir: Dir,
    source_path: []const u8,
    dest_dir: Dir,
    dest_path: []const u8,
    io: Io,
    options: CopyFileOptions,
) CopyFileError!void {
    const file = try source_dir.openFile(io, source_path, .{});
    var file_reader: File.Reader = .init(file, io, &.{});
    defer file_reader.file.close(io);

    const permissions = options.permissions orelse blk: {
        const st = try file_reader.file.stat(io);
        file_reader.size = st.size;
        break :blk st.permissions;
    };

    var atomic_file = try dest_dir.createFileAtomic(io, dest_path, .{
        .permissions = permissions,
        .make_path = options.make_path,
        .replace = options.replace,
    });
    defer atomic_file.deinit(io);

    var buffer: [1024]u8 = undefined; // Used only when direct fd-to-fd is not available.
    var file_writer = atomic_file.file.writer(io, &buffer);

    _ = file_writer.interface.sendFileAll(&file_reader, .unlimited) catch |err| switch (err) {
        error.ReadFailed => return file_reader.err.?,
        error.WriteFailed => return file_writer.err.?,
    };

    try file_writer.flush();

    switch (options.replace) {
        true => try atomic_file.replace(io),
        false => try atomic_file.link(io),
    }
}

/// Same as `copyFile`, except asserts that both `source_path` and `dest_path`
/// are absolute.
///
/// On Windows, both paths should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// On WASI, both paths should be encoded as valid UTF-8.
/// On other platforms, both paths are an opaque sequence of bytes with no particular encoding.
pub fn copyFileAbsolute(
    source_path: []const u8,
    dest_path: []const u8,
    io: Io,
    options: CopyFileOptions,
) !void {
    assert(path.isAbsolute(source_path));
    assert(path.isAbsolute(dest_path));
    const my_cwd = cwd();
    return copyFile(my_cwd, source_path, my_cwd, dest_path, io, options);
}

test copyFileAbsolute {}

pub const CreateFileAtomicOptions = struct {
    permissions: File.Permissions = .default_file,
    make_path: bool = false,
    /// Tells whether the unnamed file will be ultimately created with
    /// `File.Atomic.link` or `File.Atomic.replace`.
    ///
    /// If this value is incorrect it will cause an assertion failure in
    /// `File.Atomic.replace`.
    replace: bool = false,
};

pub const CreateFileAtomicError = error{
    NoDevice,
    /// On Windows, `\\server` or `\\server\share` was not found.
    NetworkNotFound,
    /// On Windows, antivirus software is enabled by default. It can be
    /// disabled, but Windows Update sometimes ignores the user's preference
    /// and re-enables it. When enabled, antivirus software on Windows
    /// intercepts file system operations and makes them significantly slower
    /// in addition to possibly failing with this error code.
    AntivirusInterference,
    /// In WASI, this error may occur when the file descriptor does
    /// not hold the required rights to open a new resource relative to it.
    AccessDenied,
    PermissionDenied,
    SymLinkLoop,
    ProcessFdQuotaExceeded,
    SystemFdQuotaExceeded,
    /// Either:
    /// * One of the path components does not exist.
    /// * Cwd was used, but cwd has been deleted.
    /// * The path associated with the open directory handle has been deleted.
    FileNotFound,
    /// Insufficient kernel memory was available.
    SystemResources,
    /// A new path cannot be created because the device has no room for the new file.
    NoSpaceLeft,
    /// A component used as a directory in the path was not, in fact, a directory.
    NotDir,
    WouldBlock,
    ReadOnlyFileSystem,
    /// The file attempted to be created is a running executable.
    FileBusy,
} || Io.Dir.PathNameError || Io.Cancelable || Io.UnexpectedError;

/// Create an unnamed ephemeral file that can eventually be atomically
/// materialized into `sub_path`.
///
/// The returned `File.Atomic` provides API to emulate the behavior in case it
/// is not directly supported by the underlying operating system.
///
/// * On Windows, `sub_path` should be encoded as [WTF-8](https://wtf-8.codeberg.page/).
/// * On WASI, `sub_path` should be encoded as valid UTF-8.
/// * On other platforms, `sub_path` is an opaque sequence of bytes with no particular encoding.
pub fn createFileAtomic(
    dir: Dir,
    io: Io,
    sub_path: []const u8,
    options: CreateFileAtomicOptions,
) CreateFileAtomicError!File.Atomic {
    return io.vtable.dirCreateFileAtomic(io.userdata, dir, sub_path, options);
}

pub const SetPermissionsError = File.SetPermissionsError;
pub const Permissions = File.Permissions;

/// Also known as "chmod".
///
/// The process must have the correct privileges in order to do this
/// successfully, or must have the effective user ID matching the owner
/// of the directory. Additionally, the directory must have been opened
/// with `OpenOptions.iterate` set to `true`.
pub fn setPermissions(dir: Dir, io: Io, new_permissions: File.Permissions) SetPermissionsError!void {
    return io.vtable.dirSetPermissions(io.userdata, dir, new_permissions);
}

pub const SetFilePermissionsError = PathNameError || SetPermissionsError || error{
    ProcessFdQuotaExceeded,
    SystemFdQuotaExceeded,
    /// `SetFilePermissionsOptions.follow_symlinks` was set to false, which is
    /// not allowed by the file system or operating system.
    OperationUnsupported,
};

pub const SetFilePermissionsOptions = struct {
    follow_symlinks: bool = true,
};

/// Also known as "fchmodat".
pub fn setFilePermissions(
    dir: Dir,
    io: Io,
    sub_path: []const u8,
    new_permissions: File.Permissions,
    options: SetFilePermissionsOptions,
) SetFilePermissionsError!void {
    return io.vtable.dirSetFilePermissions(io.userdata, dir, sub_path, new_permissions, options);
}

pub const SetOwnerError = File.SetOwnerError;

/// Also known as "chown".
///
/// The process must have the correct privileges in order to do this
/// successfully. The group may be changed by the owner of the directory to
/// any group of which the owner is a member. Additionally, the directory
/// must have been opened with `OpenOptions.iterate` set to `true`. If the
/// owner or group is specified as `null`, the ID is not changed.
pub fn setOwner(dir: Dir, io: Io, owner: ?File.Uid, group: ?File.Gid) SetOwnerError!void {
    return io.vtable.dirSetOwner(io.userdata, dir, owner, group);
}

pub const SetFileOwnerError = PathNameError || SetOwnerError;

pub const SetFileOwnerOptions = struct {
    follow_symlinks: bool = true,
};

/// Also known as "fchownat".
pub fn setFileOwner(
    dir: Dir,
    io: Io,
    sub_path: []const u8,
    owner: ?File.Uid,
    group: ?File.Gid,
    options: SetFileOwnerOptions,
) SetFileOwnerError!void {
    return io.vtable.dirSetFileOwner(io.userdata, dir, sub_path, owner, group, options);
}

pub const SetTimestampsError = File.SetTimestampsError || PathNameError;

pub const SetTimestampsOptions = struct {
    follow_symlinks: bool = true,
    access_timestamp: File.SetTimestamp = .unchanged,
    modify_timestamp: File.SetTimestamp = .unchanged,
};

/// The granularity that ultimately is stored depends on the combination of
/// operating system and file system. When a value as provided that exceeds
/// this range, the value is clamped to the maximum.
pub fn setTimestamps(
    dir: Dir,
    io: Io,
    sub_path: []const u8,
    options: SetTimestampsOptions,
) SetTimestampsError!void {
    return io.vtable.dirSetTimestamps(io.userdata, dir, sub_path, options);
}

pub const SetTimestampsNowOptions = struct {
    follow_symlinks: bool = true,
};

/// Sets the accessed and modification timestamps of the provided path to the
/// current wall clock time.
///
/// The granularity that ultimately is stored depends on the combination of
/// operating system and file system.
pub fn setTimestampsNow(
    dir: Dir,
    io: Io,
    sub_path: []const u8,
    options: SetTimestampsNowOptions,
) SetTimestampsError!void {
    return io.vtable.dirSetTimestamps(io.userdata, dir, sub_path, .{
        .follow_symlinks = options.follow_symlinks,
        .access_timestamp = .now,
        .modify_timestamp = .now,
    });
}

test {
    _ = &setFileOwner;
    _ = &setTimestampsNow;
}