File: NonBlockingFileIO.swift

package info (click to toggle)
swiftlang 6.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,791,532 kB
  • sloc: cpp: 9,901,743; ansic: 2,201,431; asm: 1,091,827; python: 308,252; objc: 82,166; f90: 80,126; lisp: 38,358; pascal: 25,559; sh: 20,429; ml: 5,058; perl: 4,745; makefile: 4,484; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (1106 lines) | stat: -rw-r--r-- 55,626 bytes parent folder | download
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

import NIOCore
import NIOConcurrencyHelpers

/// ``NonBlockingFileIO`` is a helper that allows you to read files without blocking the calling thread.
///
/// It is worth noting that `kqueue`, `epoll` or `poll` returning claiming a file is readable does not mean that the
/// data is already available in the kernel's memory. In other words, a `read` from a file can still block even if
/// reported as readable. This behaviour is also documented behaviour:
///
///  - [`poll`](http://pubs.opengroup.org/onlinepubs/009695399/functions/poll.html): "Regular files shall always poll TRUE for reading and writing."
///  - [`epoll`](http://man7.org/linux/man-pages/man7/epoll.7.html): "epoll is simply a faster poll(2), and can be used wherever the latter is used since it shares the same semantics."
///  - [`kqueue`](https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2): "Returns when the file pointer is not at the end of file."
///
/// ``NonBlockingFileIO`` helps to work around this issue by maintaining its own thread pool that is used to read the data
/// from the files into memory. It will then hand the (in-memory) data back which makes it available without the possibility
/// of blocking.
public struct NonBlockingFileIO: Sendable {
    /// The default and recommended size for ``NonBlockingFileIO``'s thread pool.
    public static let defaultThreadPoolSize = 2

    /// The default and recommended chunk size.
    public static let defaultChunkSize = 128*1024

    /// ``NonBlockingFileIO`` errors.
    public enum Error: Swift.Error {
        /// ``NonBlockingFileIO`` is meant to be used with file descriptors that are set to the default (blocking) mode.
        /// It doesn't make sense to use it with a file descriptor where `O_NONBLOCK` is set therefore this error is
        /// raised when that was requested.
        case descriptorSetToNonBlocking
    }

    private let threadPool: NIOThreadPool

    /// Initialize a ``NonBlockingFileIO`` which uses the `NIOThreadPool`.
    ///
    /// - parameters:
    ///   - threadPool: The `NIOThreadPool` that will be used for all the IO.
    public init(threadPool: NIOThreadPool) {
        self.threadPool = threadPool
    }

    /// Read a `FileRegion` in chunks of `chunkSize` bytes on ``NonBlockingFileIO``'s private thread
    /// pool which is separate from any `EventLoop` thread.
    ///
    /// `chunkHandler` will be called on `eventLoop` for every chunk that was read. Assuming `fileRegion.readableBytes` is greater than
    /// zero and there are enough bytes available `chunkHandler` will be called `1 + |_ fileRegion.readableBytes / chunkSize _|`
    /// times, delivering `chunkSize` bytes each time. If less than `fileRegion.readableBytes` bytes can be read from the file,
    /// `chunkHandler` will be called less often with the last invocation possibly being of less than `chunkSize` bytes.
    ///
    /// The allocation and reading of a subsequent chunk will only be attempted when `chunkHandler` succeeds.
    ///
    /// This method will not use the file descriptor's seek pointer which means there is no danger of reading from the
    /// same `FileRegion` in multiple threads.
    ///
    /// - parameters:
    ///   - fileRegion: The file region to read.
    ///   - chunkSize: The size of the individual chunks to deliver.
    ///   - allocator: A `ByteBufferAllocator` used to allocate space for the chunks.
    ///   - eventLoop: The `EventLoop` to call `chunkHandler` on.
    ///   - chunkHandler: Called for every chunk read. The next chunk will be read upon successful completion of the returned `EventLoopFuture`. If the returned `EventLoopFuture` fails, the overall operation is aborted.
    /// - returns: An `EventLoopFuture` which is the result of the overall operation. If either the reading of `fileHandle` or `chunkHandler` fails, the `EventLoopFuture` will fail too. If the reading of `fileHandle` as well as `chunkHandler` always succeeded, the `EventLoopFuture` will succeed too.
    @preconcurrency
    public func readChunked(fileRegion: FileRegion,
                            chunkSize: Int = NonBlockingFileIO.defaultChunkSize,
                            allocator: ByteBufferAllocator,
                            eventLoop: EventLoop,
                            chunkHandler: @escaping @Sendable (ByteBuffer) -> EventLoopFuture<Void>) -> EventLoopFuture<Void> {
        let readableBytes = fileRegion.readableBytes
        return self.readChunked(fileHandle: fileRegion.fileHandle,
                                fromOffset: Int64(fileRegion.readerIndex),
                                byteCount: readableBytes,
                                chunkSize: chunkSize,
                                allocator: allocator,
                                eventLoop: eventLoop,
                                chunkHandler: chunkHandler)
    }

    /// Read `byteCount` bytes in chunks of `chunkSize` bytes from `fileHandle` in ``NonBlockingFileIO``'s private thread
    /// pool which is separate from any `EventLoop` thread.
    ///
    /// `chunkHandler` will be called on `eventLoop` for every chunk that was read. Assuming `byteCount` is greater than
    /// zero and there are enough bytes available `chunkHandler` will be called `1 + |_ byteCount / chunkSize _|`
    /// times, delivering `chunkSize` bytes each time. If less than `byteCount` bytes can be read from `descriptor`,
    /// `chunkHandler` will be called less often with the last invocation possibly being of less than `chunkSize` bytes.
    ///
    /// The allocation and reading of a subsequent chunk will only be attempted when `chunkHandler` succeeds.
    ///
    /// - note: `readChunked(fileRegion:chunkSize:allocator:eventLoop:chunkHandler:)` should be preferred as it uses
    ///         `FileRegion` object instead of raw `NIOFileHandle`s. In case you do want to use raw `NIOFileHandle`s,
    ///         please consider using `readChunked(fileHandle:fromOffset:chunkSize:allocator:eventLoop:chunkHandler:)`
    ///         because it doesn't use the file descriptor's seek pointer (which may be shared with other file
    ///         descriptors and even across processes.)
    ///
    /// - parameters:
    ///   - fileHandle: The `NIOFileHandle` to read from.
    ///   - byteCount: The number of bytes to read from `fileHandle`.
    ///   - chunkSize: The size of the individual chunks to deliver.
    ///   - allocator: A `ByteBufferAllocator` used to allocate space for the chunks.
    ///   - eventLoop: The `EventLoop` to call `chunkHandler` on.
    ///   - chunkHandler: Called for every chunk read. The next chunk will be read upon successful completion of the returned `EventLoopFuture`. If the returned `EventLoopFuture` fails, the overall operation is aborted.
    /// - returns: An `EventLoopFuture` which is the result of the overall operation. If either the reading of `fileHandle` or `chunkHandler` fails, the `EventLoopFuture` will fail too. If the reading of `fileHandle` as well as `chunkHandler` always succeeded, the `EventLoopFuture` will succeed too.
    @preconcurrency
    public func readChunked(fileHandle: NIOFileHandle,
                            byteCount: Int,
                            chunkSize: Int = NonBlockingFileIO.defaultChunkSize,
                            allocator: ByteBufferAllocator,
                            eventLoop: EventLoop, chunkHandler: @escaping @Sendable (ByteBuffer) -> EventLoopFuture<Void>) -> EventLoopFuture<Void> {
        return self.readChunked0(fileHandle: fileHandle,
                                fromOffset: nil,
                                byteCount: byteCount,
                                chunkSize: chunkSize,
                                allocator: allocator,
                                eventLoop: eventLoop,
                                chunkHandler: chunkHandler)
    }

    /// Read `byteCount` bytes from offset `fileOffset` in chunks of `chunkSize` bytes from `fileHandle` in ``NonBlockingFileIO``'s private thread
    /// pool which is separate from any `EventLoop` thread.
    ///
    /// `chunkHandler` will be called on `eventLoop` for every chunk that was read. Assuming `byteCount` is greater than
    /// zero and there are enough bytes available `chunkHandler` will be called `1 + |_ byteCount / chunkSize _|`
    /// times, delivering `chunkSize` bytes each time. If less than `byteCount` bytes can be read from `descriptor`,
    /// `chunkHandler` will be called less often with the last invocation possibly being of less than `chunkSize` bytes.
    ///
    /// The allocation and reading of a subsequent chunk will only be attempted when `chunkHandler` succeeds.
    ///
    /// This method will not use the file descriptor's seek pointer which means there is no danger of reading from the
    /// same `NIOFileHandle` in multiple threads.
    ///
    /// - note: `readChunked(fileRegion:chunkSize:allocator:eventLoop:chunkHandler:)` should be preferred as it uses
    ///         `FileRegion` object instead of raw `NIOFileHandle`s.
    ///
    /// - parameters:
    ///   - fileHandle: The `NIOFileHandle` to read from.
    ///   - byteCount: The number of bytes to read from `fileHandle`.
    ///   - chunkSize: The size of the individual chunks to deliver.
    ///   - allocator: A `ByteBufferAllocator` used to allocate space for the chunks.
    ///   - eventLoop: The `EventLoop` to call `chunkHandler` on.
    ///   - chunkHandler: Called for every chunk read. The next chunk will be read upon successful completion of the returned `EventLoopFuture`. If the returned `EventLoopFuture` fails, the overall operation is aborted.
    /// - returns: An `EventLoopFuture` which is the result of the overall operation. If either the reading of `fileHandle` or `chunkHandler` fails, the `EventLoopFuture` will fail too. If the reading of `fileHandle` as well as `chunkHandler` always succeeded, the `EventLoopFuture` will succeed too.
    @preconcurrency
    public func readChunked(fileHandle: NIOFileHandle,
                            fromOffset fileOffset: Int64,
                            byteCount: Int,
                            chunkSize: Int = NonBlockingFileIO.defaultChunkSize,
                            allocator: ByteBufferAllocator,
                            eventLoop: EventLoop,
                            chunkHandler: @escaping @Sendable (ByteBuffer) -> EventLoopFuture<Void>) -> EventLoopFuture<Void> {
        return self.readChunked0(fileHandle: fileHandle,
                                 fromOffset: fileOffset,
                                 byteCount: byteCount,
                                 chunkSize: chunkSize,
                                 allocator: allocator,
                                 eventLoop: eventLoop,
                                 chunkHandler: chunkHandler)
    }

    private typealias ReadChunkHandler = @Sendable (ByteBuffer) -> EventLoopFuture<Void>

    private func readChunked0(fileHandle: NIOFileHandle,
                              fromOffset: Int64?,
                              byteCount: Int,
                              chunkSize: Int,
                              allocator: ByteBufferAllocator,
                              eventLoop: EventLoop, chunkHandler: @escaping ReadChunkHandler) -> EventLoopFuture<Void> {
        precondition(chunkSize > 0, "chunkSize must be > 0 (is \(chunkSize))")
        let remainingReads = 1 + (byteCount / chunkSize)
        let lastReadSize = byteCount % chunkSize

        let promise = eventLoop.makePromise(of: Void.self)

        func _read(remainingReads: Int, bytesReadSoFar: Int64) {
            if remainingReads > 1 || (remainingReads == 1 && lastReadSize > 0) {
                let readSize = remainingReads > 1 ? chunkSize : lastReadSize
                assert(readSize > 0)
                let readFuture = self.read0(fileHandle: fileHandle,
                                            fromOffset: fromOffset.map { $0 + bytesReadSoFar },
                                            byteCount: readSize,
                                            allocator: allocator,
                                            eventLoop: eventLoop)
                readFuture.whenComplete { (result) in
                    switch result {
                    case .success(let buffer):
                        guard buffer.readableBytes > 0 else {
                            // EOF, call `chunkHandler` one more time.
                            let handlerFuture = chunkHandler(buffer)
                            handlerFuture.cascade(to: promise)
                            return
                        }
                        let bytesRead = Int64(buffer.readableBytes)
                        chunkHandler(buffer).hop(to: eventLoop).whenComplete { result in
                            switch result {
                            case .success(_):
                                eventLoop.assertInEventLoop()
                                _read(remainingReads: remainingReads - 1,
                                      bytesReadSoFar: bytesReadSoFar + bytesRead)
                            case .failure(let error):
                                promise.fail(error)
                            }
                        }
                  case .failure(let error):
                      promise.fail(error)
                  }
              }
            } else {
                promise.succeed(())
            }
        }
        _read(remainingReads: remainingReads, bytesReadSoFar: 0)

        return promise.futureResult
    }

    /// Read a `FileRegion` in ``NonBlockingFileIO``'s private thread pool which is separate from any `EventLoop` thread.
    ///
    /// The returned `ByteBuffer` will not have less than `fileRegion.readableBytes` unless we hit end-of-file in which
    /// case the `ByteBuffer` will contain the bytes available to read.
    ///
    /// This method will not use the file descriptor's seek pointer which means there is no danger of reading from the
    /// same `FileRegion` in multiple threads.
    ///
    /// - note: Only use this function for small enough `FileRegion`s as it will need to allocate enough memory to hold `fileRegion.readableBytes` bytes.
    /// - note: In most cases you should prefer one of the `readChunked` functions.
    ///
    /// - parameters:
    ///   - fileRegion: The file region to read.
    ///   - allocator: A `ByteBufferAllocator` used to allocate space for the returned `ByteBuffer`.
    ///   - eventLoop: The `EventLoop` to create the returned `EventLoopFuture` from.
    /// - returns: An `EventLoopFuture` which delivers a `ByteBuffer` if the read was successful or a failure on error.
    public func read(fileRegion: FileRegion, allocator: ByteBufferAllocator, eventLoop: EventLoop) -> EventLoopFuture<ByteBuffer> {
        let readableBytes = fileRegion.readableBytes
        return self.read(fileHandle: fileRegion.fileHandle,
                         fromOffset: Int64(fileRegion.readerIndex),
                         byteCount: readableBytes,
                         allocator: allocator,
                         eventLoop: eventLoop)
    }

    /// Read `byteCount` bytes from `fileHandle` in ``NonBlockingFileIO``'s private thread pool which is separate from any `EventLoop` thread.
    ///
    /// The returned `ByteBuffer` will not have less than `byteCount` bytes unless we hit end-of-file in which
    /// case the `ByteBuffer` will contain the bytes available to read.
    ///
    /// - note: Only use this function for small enough `byteCount`s as it will need to allocate enough memory to hold `byteCount` bytes.
    /// - note: ``read(fileRegion:allocator:eventLoop:)`` should be preferred as it uses `FileRegion` object instead of
    ///         raw `NIOFileHandle`s. In case you do want to use raw `NIOFileHandle`s,
    ///         please consider using ``read(fileHandle:fromOffset:byteCount:allocator:eventLoop:)``
    ///         because it doesn't use the file descriptor's seek pointer (which may be shared with other file
    ///         descriptors and even across processes.)
    ///
    /// - parameters:
    ///   - fileHandle: The `NIOFileHandle` to read.
    ///   - byteCount: The number of bytes to read from `fileHandle`.
    ///   - allocator: A `ByteBufferAllocator` used to allocate space for the returned `ByteBuffer`.
    ///   - eventLoop: The `EventLoop` to create the returned `EventLoopFuture` from.
    /// - returns: An `EventLoopFuture` which delivers a `ByteBuffer` if the read was successful or a failure on error.
    public func read(fileHandle: NIOFileHandle,
                     byteCount: Int,
                     allocator: ByteBufferAllocator,
                     eventLoop: EventLoop) -> EventLoopFuture<ByteBuffer> {
        return self.read0(fileHandle: fileHandle,
                         fromOffset: nil,
                         byteCount: byteCount,
                         allocator: allocator,
                         eventLoop: eventLoop)
    }

    /// Read `byteCount` bytes starting at `fileOffset` from `fileHandle` in ``NonBlockingFileIO``'s private thread pool
    /// which is separate from any `EventLoop` thread.
    ///
    /// The returned `ByteBuffer` will not have less than `byteCount` bytes unless we hit end-of-file in which
    /// case the `ByteBuffer` will contain the bytes available to read.
    ///
    /// This method will not use the file descriptor's seek pointer which means there is no danger of reading from the
    /// same `fileHandle` in multiple threads.
    ///
    /// - note: Only use this function for small enough `byteCount`s as it will need to allocate enough memory to hold `byteCount` bytes.
    /// - note: ``read(fileRegion:allocator:eventLoop:)`` should be preferred as it uses `FileRegion` object instead of raw `NIOFileHandle`s.
    ///
    /// - parameters:
    ///   - fileHandle: The `NIOFileHandle` to read.
    ///   - fileOffset: The offset to read from.
    ///   - byteCount: The number of bytes to read from `fileHandle`.
    ///   - allocator: A `ByteBufferAllocator` used to allocate space for the returned `ByteBuffer`.
    ///   - eventLoop: The `EventLoop` to create the returned `EventLoopFuture` from.
    /// - returns: An `EventLoopFuture` which delivers a `ByteBuffer` if the read was successful or a failure on error.
    public func read(fileHandle: NIOFileHandle,
                     fromOffset fileOffset: Int64,
                     byteCount: Int,
                     allocator: ByteBufferAllocator,
                     eventLoop: EventLoop) -> EventLoopFuture<ByteBuffer> {
        return self.read0(fileHandle: fileHandle,
                          fromOffset: fileOffset,
                          byteCount: byteCount,
                          allocator: allocator,
                          eventLoop: eventLoop)
    }

    private func read0(fileHandle: NIOFileHandle,
                       fromOffset: Int64?, // > 2 GB offset is reasonable on 32-bit systems
                       byteCount rawByteCount: Int,
                       allocator: ByteBufferAllocator,
                       eventLoop: EventLoop) -> EventLoopFuture<ByteBuffer> {
        guard rawByteCount > 0 else {
            return eventLoop.makeSucceededFuture(allocator.buffer(capacity: 0))
        }
        let byteCount = rawByteCount < Int32.max ? rawByteCount : size_t(Int32.max)

        return self.threadPool.runIfActive(eventLoop: eventLoop) { () -> ByteBuffer in
            try self.readSync(fileHandle: fileHandle, fromOffset: fromOffset, byteCount: byteCount, allocator: allocator)
        }
    }

    private func readSync(
        fileHandle: NIOFileHandle,
        fromOffset: Int64?, // > 2 GB offset is reasonable on 32-bit systems
        byteCount: Int,
        allocator: ByteBufferAllocator
    ) throws -> ByteBuffer {
        var bytesRead = 0
        var buf = allocator.buffer(capacity: byteCount)
        while bytesRead < byteCount {
            let n = try buf.writeWithUnsafeMutableBytes(minimumWritableBytes: byteCount - bytesRead) { ptr in
                let res = try fileHandle.withUnsafeFileDescriptor { descriptor -> IOResult<ssize_t> in
                    if let offset = fromOffset {
                        return try Posix.pread(descriptor: descriptor,
                                                pointer: ptr.baseAddress!,
                                                size: byteCount - bytesRead,
                                                offset: off_t(offset) + off_t(bytesRead))
                    } else {
                        return try Posix.read(descriptor: descriptor,
                                                pointer: ptr.baseAddress!,
                                                size: byteCount - bytesRead)
                    }
                }
                switch res {
                case .processed(let n):
                    assert(n >= 0, "read claims to have read a negative number of bytes \(n)")
                    return n
                case .wouldBlock:
                    throw Error.descriptorSetToNonBlocking
                }
            }
            if n == 0 {
                // EOF
                break
            } else {
                bytesRead += n
            }
        }
        return buf
    }

    /// Changes the file size of `fileHandle` to `size`.
    ///
    /// If `size` is smaller than the current file size, the remaining bytes will be truncated and are lost. If `size`
    /// is larger than the current file size, the gap will be filled with zero bytes.
    ///
    /// - parameters:
    ///   - fileHandle: The `NIOFileHandle` to write to.
    ///   - size: The new file size in bytes to write.
    ///   - eventLoop: The `EventLoop` to create the returned `EventLoopFuture` from.
    /// - returns: An `EventLoopFuture` which is fulfilled if the write was successful or fails on error.
    public func changeFileSize(fileHandle: NIOFileHandle,
                               size: Int64,
                               eventLoop: EventLoop) -> EventLoopFuture<()> {
        return self.threadPool.runIfActive(eventLoop: eventLoop) {
            try fileHandle.withUnsafeFileDescriptor { descriptor -> Void in
                try Posix.ftruncate(descriptor: descriptor, size: off_t(size))
            }
        }
    }

    /// Returns the length of the file in bytes associated with `fileHandle`.
    ///
    /// - parameters:
    ///   - fileHandle: The `NIOFileHandle` to read from.
    ///   - eventLoop: The `EventLoop` to create the returned `EventLoopFuture` from.
    /// - returns: An `EventLoopFuture` which is fulfilled with the length of the file in bytes if the write was successful or fails on error.
    public func readFileSize(fileHandle: NIOFileHandle,
                             eventLoop: EventLoop) -> EventLoopFuture<Int64> {
        return self.threadPool.runIfActive(eventLoop: eventLoop) {
            return try fileHandle.withUnsafeFileDescriptor { descriptor in
                let curr = try Posix.lseek(descriptor: descriptor, offset: 0, whence: SEEK_CUR)
                let eof = try Posix.lseek(descriptor: descriptor, offset: 0, whence: SEEK_END)
                try Posix.lseek(descriptor: descriptor, offset: curr, whence: SEEK_SET)
                return Int64(eof)
            }
        }
    }

    /// Write `buffer` to `fileHandle` in ``NonBlockingFileIO``'s private thread pool which is separate from any `EventLoop` thread.
    ///
    /// - parameters:
    ///   - fileHandle: The `NIOFileHandle` to write to.
    ///   - buffer: The `ByteBuffer` to write.
    ///   - eventLoop: The `EventLoop` to create the returned `EventLoopFuture` from.
    /// - returns: An `EventLoopFuture` which is fulfilled if the write was successful or fails on error.
    public func write(fileHandle: NIOFileHandle,
                      buffer: ByteBuffer,
                      eventLoop: EventLoop) -> EventLoopFuture<()> {
        return self.write0(fileHandle: fileHandle, toOffset: nil, buffer: buffer, eventLoop: eventLoop)
    }

    /// Write `buffer` starting from `toOffset` to `fileHandle` in ``NonBlockingFileIO``'s private thread pool which is separate from any `EventLoop` thread.
    ///
    /// - parameters:
    ///   - fileHandle: The `NIOFileHandle` to write to.
    ///   - toOffset: The file offset to write to.
    ///   - buffer: The `ByteBuffer` to write.
    ///   - eventLoop: The `EventLoop` to create the returned `EventLoopFuture` from.
    /// - returns: An `EventLoopFuture` which is fulfilled if the write was successful or fails on error.
    public func write(fileHandle: NIOFileHandle,
                      toOffset: Int64,
                      buffer: ByteBuffer,
                      eventLoop: EventLoop) -> EventLoopFuture<()> {
        return self.write0(fileHandle: fileHandle, toOffset: toOffset, buffer: buffer, eventLoop: eventLoop)
    }

    private func write0(fileHandle: NIOFileHandle,
                        toOffset: Int64?,
                        buffer: ByteBuffer,
                        eventLoop: EventLoop) -> EventLoopFuture<()> {
        let byteCount = buffer.readableBytes

        guard byteCount > 0 else {
            return eventLoop.makeSucceededFuture(())
        }

        return self.threadPool.runIfActive(eventLoop: eventLoop) {
            try self.writeSync(fileHandle: fileHandle, byteCount: byteCount, toOffset: toOffset, buffer: buffer)
        }
    }

    private func writeSync(
        fileHandle: NIOFileHandle,
        byteCount: Int,
        toOffset: Int64?,
        buffer: ByteBuffer
    ) throws {
        var buf = buffer

        var offsetAccumulator: Int = 0
        repeat {
            let n = try buf.readWithUnsafeReadableBytes { ptr in
                precondition(ptr.count == byteCount - offsetAccumulator)
                let res: IOResult<ssize_t> = try fileHandle.withUnsafeFileDescriptor { descriptor in
                    if let toOffset = toOffset {
                        return try Posix.pwrite(descriptor: descriptor,
                                                pointer: ptr.baseAddress!,
                                                size: byteCount - offsetAccumulator,
                                                offset: off_t(toOffset + Int64(offsetAccumulator)))
                    } else {
                        return try Posix.write(descriptor: descriptor,
                                                pointer: ptr.baseAddress!,
                                                size: byteCount - offsetAccumulator)
                    }
                }
                switch res {
                case .processed(let n):
                    assert(n >= 0, "write claims to have written a negative number of bytes \(n)")
                    return n
                case .wouldBlock:
                    throw Error.descriptorSetToNonBlocking
                }
            }
            offsetAccumulator += n
        } while offsetAccumulator < byteCount
    }

    /// Open the file at `path` for reading on a private thread pool which is separate from any `EventLoop` thread.
    ///
    /// This function will return (a future) of the `NIOFileHandle` associated with the file opened and a `FileRegion`
    /// comprising of the whole file. The caller must close the returned `NIOFileHandle` when it's no longer needed.
    ///
    /// - note: The reason this returns the `NIOFileHandle` and the `FileRegion` is that both the opening of a file as well as the querying of its size are blocking.
    ///
    /// - parameters:
    ///     - path: The path of the file to be opened for reading.
    ///     - eventLoop: The `EventLoop` on which the returned `EventLoopFuture` will fire.
    /// - returns: An `EventLoopFuture` containing the `NIOFileHandle` and the `FileRegion` comprising the whole file.
    public func openFile(path: String, eventLoop: EventLoop) -> EventLoopFuture<(NIOFileHandle, FileRegion)> {
        return self.threadPool.runIfActive(eventLoop: eventLoop) {
            let fh = try NIOFileHandle(path: path)
            do {
                let fr = try FileRegion(fileHandle: fh)
                return (fh, fr)
            } catch {
                _ = try? fh.close()
                throw error
            }
        }
    }

    /// Open the file at `path` with specified access mode and POSIX flags on a private thread pool which is separate from any `EventLoop` thread.
    ///
    /// This function will return (a future) of the `NIOFileHandle` associated with the file opened.
    /// The caller must close the returned `NIOFileHandle` when it's no longer needed.
    ///
    /// - parameters:
    ///     - path: The path of the file to be opened for writing.
    ///     - mode: File access mode.
    ///     - flags: Additional POSIX flags.
    ///     - eventLoop: The `EventLoop` on which the returned `EventLoopFuture` will fire.
    /// - returns: An `EventLoopFuture` containing the `NIOFileHandle`.
    public func openFile(path: String, mode: NIOFileHandle.Mode, flags: NIOFileHandle.Flags = .default, eventLoop: EventLoop) -> EventLoopFuture<NIOFileHandle> {
        return self.threadPool.runIfActive(eventLoop: eventLoop) {
            return try NIOFileHandle(path: path, mode: mode, flags: flags)
        }
    }

#if !os(Windows)
    /// Returns information about a file at `path` on a private thread pool which is separate from any `EventLoop` thread.
    ///
    /// - note: If `path` is a symlink, information about the link, not the file it points to.
    ///
    /// - parameters:
    ///     - path: The path of the file to get information about.
    ///     - eventLoop: The `EventLoop` on which the returned `EventLoopFuture` will fire.
    /// - returns: An `EventLoopFuture` containing file information.
    public func lstat(path: String, eventLoop: EventLoop) -> EventLoopFuture<stat> {
        return self.threadPool.runIfActive(eventLoop: eventLoop) {
            var s = stat()
            try Posix.lstat(pathname: path, outStat: &s)
            return s
        }
    }

    /// Creates a symbolic link to a  `destination` file  at `path` on a private thread pool which is separate from any `EventLoop` thread.
    ///
    /// - parameters:
    ///     - path: The path of the link.
    ///     - destination: Target path where this link will point to.
    ///     - eventLoop: The `EventLoop` on which the returned `EventLoopFuture` will fire.
    /// - returns: An `EventLoopFuture` which is fulfilled if the rename was successful or fails on error.
    public func symlink(path: String, to destination: String, eventLoop: EventLoop) -> EventLoopFuture<Void> {
        return self.threadPool.runIfActive(eventLoop: eventLoop) {
            try Posix.symlink(pathname: path, destination: destination)
        }
    }

    /// Returns target of the symbolic link at `path` on a private thread pool which is separate from any `EventLoop` thread.
    ///
    /// - parameters:
    ///     - path: The path of the link to read.
    ///     - eventLoop: The `EventLoop` on which the returned `EventLoopFuture` will fire.
    /// - returns: An `EventLoopFuture` containing link target.
    public func readlink(path: String, eventLoop: EventLoop) -> EventLoopFuture<String> {
        return self.threadPool.runIfActive(eventLoop: eventLoop) {
            let maxLength = Int(PATH_MAX)
            let pointer = UnsafeMutableBufferPointer<CChar>.allocate(capacity: maxLength)
            defer {
                pointer.deallocate()
            }
            let length = try Posix.readlink(pathname: path, outPath: pointer.baseAddress!, outPathSize: maxLength)
            return String(decoding: UnsafeRawBufferPointer(pointer).prefix(length), as: UTF8.self)
        }
    }

    /// Removes symbolic link at `path` on a private thread pool which is separate from any `EventLoop` thread.
    ///
    /// - parameters:
    ///     - path: The path of the link to remove.
    ///     - eventLoop: The `EventLoop` on which the returned `EventLoopFuture` will fire.
    /// - returns: An `EventLoopFuture` which is fulfilled if the rename was successful or fails on error.
    public func unlink(path: String, eventLoop: EventLoop) -> EventLoopFuture<Void> {
        return self.threadPool.runIfActive(eventLoop: eventLoop) {
            try Posix.unlink(pathname: path)
        }
    }

    private func createDirectory0(_ path: String, mode: NIOPOSIXFileMode) throws {
        let pathView = path.utf8
        if pathView.isEmpty {
            return
        }

        // Fail fast if not a directory or file exists
        do {
            var s = stat()
            try Posix.stat(pathname: path, outStat: &s)
            if (S_IFMT & s.st_mode) == S_IFDIR {
                return
            }
            throw IOError(errnoCode: ENOTDIR, reason: "Not a directory")
        } catch let error as IOError where error.errnoCode == ENOENT {
            // if directory does not exist we can proceed with creating it
        }

        // Slow path, check that all intermediate directories exist recursively

        // Trim any trailing path separators
        var index = pathView.index(before: pathView.endIndex)
        let pathSeparator = UInt8(ascii: "/")
        while index != pathView.startIndex && pathView[index] == pathSeparator {
            index = pathView.index(before: index)
        }

        // Find first non-trailing path separator if it exists
        while index != pathView.startIndex && pathView[index] != pathSeparator {
            index = pathView.index(before: index)
        }

        // If non-trailing path separator is found, create parent directory
        if index > pathView.startIndex {
            try self.createDirectory0(String(Substring(pathView.prefix(upTo: index))), mode: mode)
        }

        do {
            try Posix.mkdir(pathname: path, mode: mode)
        } catch {
            // If user tries to create a path like `/some/path/.` it may fail, as path will be created
            // by the recursive call. Checks if directory exists and re-throw the error if it does not
            do {
                var s = stat()
                try Posix.lstat(pathname: path, outStat: &s)
                if (S_IFMT & s.st_mode) == S_IFDIR {
                    return
                }
            } catch {
                // fallthrough
            }
            throw error
        }
    }

    /// Creates directory at `path` on a private thread pool which is separate from any `EventLoop` thread.
    ///
    /// - parameters:
    ///     - path: The path of the directory to be created.
    ///     - withIntermediateDirectories: Whether intermediate directories should be created.
    ///     - eventLoop: The `EventLoop` on which the returned `EventLoopFuture` will fire.
    /// - returns: An `EventLoopFuture` which is fulfilled if the rename was successful or fails on error.
    public func createDirectory(path: String, withIntermediateDirectories createIntermediates: Bool = false, mode: NIOPOSIXFileMode, eventLoop: EventLoop) -> EventLoopFuture<Void> {
        return self.threadPool.runIfActive(eventLoop: eventLoop) {
            if createIntermediates {
                #if canImport(Darwin)
                try Posix.mkpath_np(pathname: path, mode: mode)
                #else
                try self.createDirectory0(path, mode: mode)
                #endif
            } else {
                try Posix.mkdir(pathname: path, mode: mode)
            }
        }
    }

    /// List contents of the directory at `path` on a private thread pool which is separate from any `EventLoop` thread.
    ///
    /// - parameters:
    ///     - path: The path of the directory to list the content of.
    ///     - eventLoop: The `EventLoop` on which the returned `EventLoopFuture` will fire.
    /// - returns: An `EventLoopFuture` containing the directory entries.
    public func listDirectory(path: String, eventLoop: EventLoop) -> EventLoopFuture<[NIODirectoryEntry]> {
        return self.threadPool.runIfActive(eventLoop: eventLoop) {
            let dir = try Posix.opendir(pathname: path)
            var entries: [NIODirectoryEntry] = []
            do {
                while let entry = try Posix.readdir(dir: dir) {
                    let name = withUnsafeBytes(of: entry.pointee.d_name) { pointer -> String in
                        let ptr = pointer.baseAddress!.assumingMemoryBound(to: CChar.self)
                        return String(cString: ptr)
                    }
                    entries.append(NIODirectoryEntry(ino: UInt64(entry.pointee.d_ino), type: entry.pointee.d_type, name: name))
                }
                try? Posix.closedir(dir: dir)
            } catch {
                try? Posix.closedir(dir: dir)
                throw error
            }
            return entries
        }
    }

    /// Renames the file at `path` to `newName` on a private thread pool which is separate from any `EventLoop` thread.
    ///
    /// - parameters:
    ///     - path: The path of the file to be renamed.
    ///     - newName: New file name.
    ///     - eventLoop: The `EventLoop` on which the returned `EventLoopFuture` will fire.
    /// - returns: An `EventLoopFuture` which is fulfilled if the rename was successful or fails on error.
    public func rename(path: String, newName: String, eventLoop: EventLoop) -> EventLoopFuture<Void> {
        return self.threadPool.runIfActive(eventLoop: eventLoop) {
            try Posix.rename(pathname: path, newName: newName)
        }
    }

    /// Removes the file at `path` on a private thread pool which is separate from any `EventLoop` thread.
    ///
    /// - parameters:
    ///     - path: The path of the file to be removed.
    ///     - eventLoop: The `EventLoop` on which the returned `EventLoopFuture` will fire.
    /// - returns: An `EventLoopFuture` which is fulfilled if the remove was successful or fails on error.
    public func remove(path: String, eventLoop: EventLoop) -> EventLoopFuture<Void> {
        return self.threadPool.runIfActive(eventLoop: eventLoop) {
            try Posix.remove(pathname: path)
        }
    }
#endif
}

#if !os(Windows)
/// A `NIODirectoryEntry` represents a single directory entry.
public struct NIODirectoryEntry: Hashable {
    // File number of entry
    public var ino: UInt64
    // File type
    public var type: UInt8
    // File name
    public var name: String

    public init(ino: UInt64, type: UInt8, name: String) {
        self.ino = ino
        self.type = type
        self.name = name
    }
}
#endif

extension NonBlockingFileIO {
    /// Read a `FileRegion` in ``NonBlockingFileIO``'s private thread pool.
    ///
    /// The returned `ByteBuffer` will not have less than the minimum of `fileRegion.readableBytes` and `UInt32.max` unless we hit 
    /// end-of-file in which case the `ByteBuffer` will contain the bytes available to read.
    ///
    /// This method will not use the file descriptor's seek pointer which means there is no danger of reading from the
    /// same `FileRegion` in multiple threads.
    ///
    /// - note: Only use this function for small enough `FileRegion`s as it will need to allocate enough memory to hold `fileRegion.readableBytes` bytes.
    /// - note: In most cases you should prefer one of the `readChunked` functions.
    ///
    /// - parameters:
    ///   - fileRegion: The file region to read.
    ///   - allocator: A `ByteBufferAllocator` used to allocate space for the returned `ByteBuffer`.
    /// - returns: ByteBuffer.
    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    public func read(fileRegion: FileRegion, allocator: ByteBufferAllocator) async throws -> ByteBuffer {
        let readableBytes = fileRegion.readableBytes
        return try await self.read(
            fileHandle: fileRegion.fileHandle,
            fromOffset: Int64(fileRegion.readerIndex),
            byteCount: readableBytes,
            allocator: allocator
        )
    }

    /// Read `byteCount` bytes from `fileHandle` in ``NonBlockingFileIO``'s private thread pool.
    ///
    /// The returned `ByteBuffer` will not have less than `byteCount` bytes unless we hit end-of-file in which
    /// case the `ByteBuffer` will contain the bytes available to read.
    ///
    /// - note: Only use this function for small enough `byteCount`s as it will need to allocate enough memory to hold `byteCount` bytes.
    /// - note: ``read(fileRegion:allocator:eventLoop:)`` should be preferred as it uses `FileRegion` object instead of
    ///         raw `NIOFileHandle`s. In case you do want to use raw `NIOFileHandle`s,
    ///         please consider using ``read(fileHandle:fromOffset:byteCount:allocator:eventLoop:)``
    ///         because it doesn't use the file descriptor's seek pointer (which may be shared with other file
    ///         descriptors and even across processes.)
    ///
    /// - parameters:
    ///   - fileHandle: The `NIOFileHandle` to read.
    ///   - byteCount: The number of bytes to read from `fileHandle`.
    ///   - allocator: A `ByteBufferAllocator` used to allocate space for the returned `ByteBuffer`.
    /// - returns: ByteBuffer.
    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    public func read(
        fileHandle: NIOFileHandle,
        byteCount: Int,
        allocator: ByteBufferAllocator
    ) async throws-> ByteBuffer {
        return try await self.read0(
            fileHandle: fileHandle,
            fromOffset: nil,
            byteCount: byteCount,
            allocator: allocator
        )
    }

    /// Read `byteCount` bytes starting at `fileOffset` from `fileHandle` in ``NonBlockingFileIO``'s private thread pool
    ///.
    ///
    /// The returned `ByteBuffer` will not have less than `byteCount` bytes unless we hit end-of-file in which
    /// case the `ByteBuffer` will contain the bytes available to read.
    ///
    /// This method will not use the file descriptor's seek pointer which means there is no danger of reading from the
    /// same `fileHandle` in multiple threads.
    ///
    /// - note: Only use this function for small enough `byteCount`s as it will need to allocate enough memory to hold `byteCount` bytes.
    /// - note: ``read(fileRegion:allocator:eventLoop:)`` should be preferred as it uses `FileRegion` object instead of raw `NIOFileHandle`s.
    ///
    /// - parameters:
    ///   - fileHandle: The `NIOFileHandle` to read.
    ///   - fileOffset: The offset to read from.
    ///   - byteCount: The number of bytes to read from `fileHandle`.
    ///   - allocator: A `ByteBufferAllocator` used to allocate space for the returned `ByteBuffer`.
    /// - returns: ByteBuffer.
    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    public func read(fileHandle: NIOFileHandle,
                     fromOffset fileOffset: Int64,
                     byteCount: Int,
                     allocator: ByteBufferAllocator) async throws -> ByteBuffer {
        return try await self.read0(fileHandle: fileHandle,
                          fromOffset: fileOffset,
                          byteCount: byteCount,
                          allocator: allocator)
    }

    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    private func read0(fileHandle: NIOFileHandle,
                       fromOffset: Int64?, // > 2 GB offset is reasonable on 32-bit systems
                       byteCount rawByteCount: Int,
                       allocator: ByteBufferAllocator) async throws -> ByteBuffer {
        guard rawByteCount > 0 else {
            return allocator.buffer(capacity: 0)
        }
        let byteCount = rawByteCount < Int32.max ? rawByteCount : size_t(Int32.max)

        return try await self.threadPool.runIfActive { () -> ByteBuffer in
            try self.readSync(fileHandle: fileHandle, fromOffset: fromOffset, byteCount: byteCount, allocator: allocator)
        }
    }

    /// Changes the file size of `fileHandle` to `size`.
    ///
    /// If `size` is smaller than the current file size, the remaining bytes will be truncated and are lost. If `size`
    /// is larger than the current file size, the gap will be filled with zero bytes.
    ///
    /// - parameters:
    ///   - fileHandle: The `NIOFileHandle` to write to.
    ///   - size: The new file size in bytes to write.
    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    public func changeFileSize(fileHandle: NIOFileHandle,
                               size: Int64) async throws {
        return try await self.threadPool.runIfActive {
            try fileHandle.withUnsafeFileDescriptor { descriptor -> Void in
                try Posix.ftruncate(descriptor: descriptor, size: off_t(size))
            }
        }
    }

    /// Returns the length of the file associated with `fileHandle`.
    ///
    /// - parameters:
    ///   - fileHandle: The `NIOFileHandle` to read from.
    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    public func readFileSize(fileHandle: NIOFileHandle) async throws -> Int64 {
        return try await self.threadPool.runIfActive {
            return try fileHandle.withUnsafeFileDescriptor { descriptor in
                let curr = try Posix.lseek(descriptor: descriptor, offset: 0, whence: SEEK_CUR)
                let eof = try Posix.lseek(descriptor: descriptor, offset: 0, whence: SEEK_END)
                try Posix.lseek(descriptor: descriptor, offset: curr, whence: SEEK_SET)
                return Int64(eof)
            }
        }
    }

    /// Write `buffer` to `fileHandle` in ``NonBlockingFileIO``'s private thread pool.
    ///
    /// - parameters:
    ///   - fileHandle: The `NIOFileHandle` to write to.
    ///   - buffer: The `ByteBuffer` to write.
    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    public func write(fileHandle: NIOFileHandle,
                      buffer: ByteBuffer) async throws {
        return try await self.write0(fileHandle: fileHandle, toOffset: nil, buffer: buffer)
    }

    /// Write `buffer` starting from `toOffset` to `fileHandle` in ``NonBlockingFileIO``'s private thread pool.
    ///
    /// - parameters:
    ///   - fileHandle: The `NIOFileHandle` to write to.
    ///   - toOffset: The file offset to write to.
    ///   - buffer: The `ByteBuffer` to write.
    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    public func write(fileHandle: NIOFileHandle,
                      toOffset: Int64,
                      buffer: ByteBuffer) async throws {
        return try await self.write0(fileHandle: fileHandle, toOffset: toOffset, buffer: buffer)
    }

    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    private func write0(fileHandle: NIOFileHandle,
                        toOffset: Int64?,
                        buffer: ByteBuffer) async throws {
        let byteCount = buffer.readableBytes

        guard byteCount > 0 else {
            return
        }

        return try await self.threadPool.runIfActive {
            try self.writeSync(fileHandle: fileHandle, byteCount: byteCount, toOffset: toOffset, buffer: buffer)
        }
    }

    /// Open file at `path` and query its size on a private thread pool, run an operation given 
    /// the resulting file region and then close the file handle.
    ///
    /// The will return the result of the operation.
    ///
    /// - note: This function opens a file and queries it size which are both blocking operations
    ///
    /// - parameters:
    ///     - path: The path of the file to be opened for reading.
    ///     - body: operation to run with file handle and region
    /// - returns: return value of operation
    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    public func withFileRegion<Result>(
        path: String, 
        _ body: (_ fileRegion: FileRegion) async throws -> Result
    ) async throws -> Result {
        let fileRegion = try await self.threadPool.runIfActive {
            let fh = try NIOFileHandle(path: path)
            do {
                let fr = try FileRegion(fileHandle: fh)
                return UnsafeTransfer(fr)
            } catch {
                _ = try? fh.close()
                throw error
            }
        }
        let result: Result
        do {
            result = try await body(fileRegion.wrappedValue)
        } catch {
            try fileRegion.wrappedValue.fileHandle.close()
            throw error
        }
        try fileRegion.wrappedValue.fileHandle.close()
        return result
    }

    /// Open file at `path` on a private thread pool, run an operation given the file handle and then close the file handle.
    ///
    /// This function will return the result of the operation.
    ///
    /// - parameters:
    ///     - path: The path of the file to be opened for writing.
    ///     - mode: File access mode.
    ///     - flags: Additional POSIX flags.
    /// - returns: return value of operation
    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    public func withFileHandle<Result>(
        path: String, 
        mode: NIOFileHandle.Mode, 
        flags: NIOFileHandle.Flags = .default, 
        _ body: (NIOFileHandle) async throws -> Result
    ) async throws -> Result {
        let fileHandle = try await self.threadPool.runIfActive {
            return try UnsafeTransfer(NIOFileHandle(path: path, mode: mode, flags: flags))
        }
        let result: Result
        do {
            result = try await body(fileHandle.wrappedValue)
        } catch {
            try fileHandle.wrappedValue.close()
            throw error
        }
        try fileHandle.wrappedValue.close()
        return result
    }

#if !os(Windows)

    /// Returns information about a file at `path` on a private thread pool.
    ///
    /// - note: If `path` is a symlink, information about the link, not the file it points to.
    ///
    /// - parameters:
    ///     - path: The path of the file to get information about.
    /// - returns: file information.
    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    public func lstat(path: String) async throws -> stat {
        return try await self.threadPool.runIfActive {
            var s = stat()
            try Posix.lstat(pathname: path, outStat: &s)
            return s
        }
    }

    /// Creates a symbolic link to a  `destination` file  at `path` on a private thread pool.
    ///
    /// - parameters:
    ///     - path: The path of the link.
    ///     - destination: Target path where this link will point to.
    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    public func symlink(path: String, to destination: String) async throws {
        return try await self.threadPool.runIfActive {
            try Posix.symlink(pathname: path, destination: destination)
        }
    }

    /// Returns target of the symbolic link at `path` on a private thread pool.
    ///
    /// - parameters:
    ///     - path: The path of the link to read.
    /// - returns: link target.
    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    public func readlink(path: String) async throws -> String {
        return try await self.threadPool.runIfActive {
            let maxLength = Int(PATH_MAX)
            let pointer = UnsafeMutableBufferPointer<CChar>.allocate(capacity: maxLength)
            defer {
                pointer.deallocate()
            }
            let length = try Posix.readlink(pathname: path, outPath: pointer.baseAddress!, outPathSize: maxLength)
            return String(decoding: UnsafeRawBufferPointer(pointer).prefix(length), as: UTF8.self)
        }
    }

    /// Removes symbolic link at `path` on a private thread pool which is separate from any `EventLoop` thread.
    ///
    /// - parameters:
    ///     - path: The path of the link to remove.
    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    public func unlink(path: String) async throws {
        return try await self.threadPool.runIfActive {
            try Posix.unlink(pathname: path)
        }
    }


    /// Creates directory at `path` on a private thread pool.
    ///
    /// - parameters:
    ///     - path: The path of the directory to be created.
    ///     - withIntermediateDirectories: Whether intermediate directories should be created.
    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    public func createDirectory(path: String, withIntermediateDirectories createIntermediates: Bool = false, mode: NIOPOSIXFileMode) async throws {
        return try await self.threadPool.runIfActive {
            if createIntermediates {
                #if canImport(Darwin)
                try Posix.mkpath_np(pathname: path, mode: mode)
                #else
                try self.createDirectory0(path, mode: mode)
                #endif
            } else {
                try Posix.mkdir(pathname: path, mode: mode)
            }
        }
    }

    /// List contents of the directory at `path` on a private thread pool.
    ///
    /// - parameters:
    ///     - path: The path of the directory to list the content of.
    /// - returns: The directory entries.
    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    public func listDirectory(path: String) async throws -> [NIODirectoryEntry] {
        return try await self.threadPool.runIfActive {
            let dir = try Posix.opendir(pathname: path)
            var entries: [NIODirectoryEntry] = []
            do {
                while let entry = try Posix.readdir(dir: dir) {
                    let name = withUnsafeBytes(of: entry.pointee.d_name) { pointer -> String in
                        let ptr = pointer.baseAddress!.assumingMemoryBound(to: CChar.self)
                        return String(cString: ptr)
                    }
                    entries.append(NIODirectoryEntry(ino: UInt64(entry.pointee.d_ino), type: entry.pointee.d_type, name: name))
                }
                try? Posix.closedir(dir: dir)
            } catch {
                try? Posix.closedir(dir: dir)
                throw error
            }
            return entries
        }
    }

    /// Renames the file at `path` to `newName` on a private thread pool.
    ///
    /// - parameters:
    ///     - path: The path of the file to be renamed.
    ///     - newName: New file name.
    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    public func rename(path: String, newName: String) async throws {
        return try await self.threadPool.runIfActive() {
            try Posix.rename(pathname: path, newName: newName)
        }
    }

    /// Removes the file at `path` on a private thread pool.
    ///
    /// - parameters:
    ///     - path: The path of the file to be removed.
    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    public func remove(path: String) async throws {
        return try await self.threadPool.runIfActive() {
            try Posix.remove(pathname: path)
        }
    }
#endif
}