aws-s3-transfer 1.0.0

Transfer Manager for Amazon S3 - a high-performance data plane client for uploading and downloading objects and directories.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

//! Positioned filesystem operations used by transfer data paths.
//!
//! Reads and writes operate at explicit offsets so disjoint ranges of one
//! open file can progress concurrently without coordinating on a shared
//! cursor. The cursor is left unchanged on Unix and WASI; on Windows it ends
//! after the last byte transferred, as a side effect of `ReadFile` /
//! `WriteFile` with `OVERLAPPED` on a synchronous handle. Callers that rely on
//! cursor state for other I/O must restore it themselves after these calls.
//! The read facade initializes pooled writable runs, while the write facade
//! preserves segmented buffers for vectored I/O where the platform supports
//! it. Preallocation prepares an output file for later writes but does not
//! flush data or provide a durability boundary.
//!
//! [`is_append_only`] reports whether a handle's positioned writes would land
//! at their offsets, and [`create_first_new`] creates the first of several
//! candidate paths that does not exist yet, without opening any existing entry.
//! [`Handle`] identifies the file a path names, so that two paths can be
//! compared. [`open_without_blocking`] opens a file without waiting for a
//! FIFO writer, and [`restore_blocking`] clears that mode on the handle.
//!
//! The `_async` helpers keep blocking filesystem calls off async worker
//! threads: natively through `tokio::fs` or tokio's blocking pool, and inline
//! on wasm targets, which have no blocking pool.

use bytes::Buf;
use std::fs::File;
use std::io;
#[cfg(any(unix, windows, target_os = "wasi"))]
use std::mem::MaybeUninit;
use std::path::{Path, PathBuf};

use crate::io::PartBuffer;

/// Repeats positioned reads until every byte of `dst` is initialized.
///
/// `read` receives the uninitialized remainder of `dst` and the file offset of
/// its first byte, and returns how many leading bytes it initialized. It may
/// initialize a prefix, return [`io::ErrorKind::Interrupted`], or report end of
/// file with a zero-length read. Offsets advance only by bytes `read` reports
/// initialized, so a successful return initializes all of `dst` provided `read`
/// reports no byte it did not write.
#[cfg(any(unix, windows, target_os = "wasi"))]
fn read_exact_at_loop(
    mut dst: &mut [MaybeUninit<u8>],
    mut offset: u64,
    mut read: impl FnMut(&mut [MaybeUninit<u8>], u64) -> io::Result<usize>,
) -> io::Result<()> {
    while !dst.is_empty() {
        match read(dst, offset) {
            Ok(0) => {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "positioned read reached end of file",
                ));
            }
            Ok(count) if count <= dst.len() => {
                offset = offset
                    .checked_add(count as u64)
                    .ok_or_else(|| io::Error::other("file read offset overflowed"))?;
                let current = dst;
                dst = &mut current[count..];
            }
            Ok(_) => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "positioned read reported more bytes than requested",
                ));
            }
            Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
            Err(error) => return Err(error),
        }
    }
    Ok(())
}

/// Repeats positioned writes until `buf` is empty.
///
/// The callback observes the buffer at its current cursor. A successful
/// partial write advances both the buffer and absolute file offset. Interrupted
/// calls are retried without advancement; zero progress is [`io::ErrorKind::WriteZero`].
#[cfg(any(unix, windows, target_os = "wasi"))]
fn write_all_at_loop<B>(
    buf: &mut B,
    mut offset: u64,
    mut write: impl FnMut(&B, u64) -> io::Result<usize>,
) -> io::Result<()>
where
    B: Buf,
{
    while buf.has_remaining() {
        let remaining = buf.remaining();
        match write(buf, offset) {
            Ok(0) => {
                return Err(io::Error::new(
                    io::ErrorKind::WriteZero,
                    "positioned write made no progress",
                ));
            }
            Ok(count) if count <= remaining => {
                buf.advance(count);
                offset = offset
                    .checked_add(count as u64)
                    .ok_or_else(|| io::Error::other("file write offset overflowed"))?;
            }
            Ok(_) => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "positioned write reported more bytes than provided",
                ));
            }
            Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
            Err(error) => return Err(error),
        }
    }
    Ok(())
}

/// Rejects a range whose last byte exceeds `max`, or whose length exceeds
/// `max_len` (a tighter count limit, e.g. `SSIZE_MAX` on 32-bit Unix).
/// `len == 0` is always accepted.
#[cfg(any(unix, windows, target_os = "wasi"))]
fn validate_range(offset: u64, len: usize, max: u64, max_len: usize) -> io::Result<()> {
    if len == 0 {
        return Ok(());
    }
    if len > max_len {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "file range exceeds the platform count limit",
        ));
    }
    // usize is at most 64 bits on all supported Rust targets, so this cast is lossless.
    let last = offset
        .checked_add(len as u64 - 1)
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "file range overflowed"))?;
    if last > max {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "file range exceeds the platform offset limit",
        ));
    }
    Ok(())
}

/// Rejects a range whose last byte exceeds `off_t::MAX` for this platform,
/// and on Unix also rejects a chunk whose byte count exceeds `SSIZE_MAX`
/// (the maximum `pread` count on 32-bit targets with `_FILE_OFFSET_BITS=64`,
/// where `off_t` is `i64` but `ssize_t` remains `i32`).
/// On WASI, `rustix` uses `i64` for positioned I/O offsets.
#[cfg(any(unix, target_os = "wasi"))]
fn validate_off_t_range(offset: u64, len: usize) -> io::Result<()> {
    #[cfg(unix)]
    let off_t_max: u64 = libc::off_t::MAX as u64;
    #[cfg(not(unix))] // WASI: rustix uses i64 for pread/pwrite offsets
    let off_t_max: u64 = i64::MAX as u64;
    // On Unix, pread's count is bounded by SSIZE_MAX regardless of off_t width;
    // a >2 GB chunk on 32-bit + LFS would get EINVAL from the kernel.
    #[cfg(unix)]
    let max_len: usize = libc::ssize_t::MAX as usize;
    #[cfg(not(unix))]
    let max_len: usize = usize::MAX;
    validate_range(offset, len, off_t_max, max_len)
}

/// Initializes every byte of `dst` from `file`, starting at `offset`, without
/// changing the file cursor.
///
/// Calls `pread64` with the destination's raw pointer, so no `&mut [u8]` is
/// formed over uninitialized memory. `pread64` takes a 64-bit offset even where
/// `off_t` is 32 bits; targets whose `pread` already takes a 64-bit `off_t` use
/// `pread`.
#[cfg(unix)]
fn read_exact_at_unix(file: &File, dst: &mut [MaybeUninit<u8>], offset: u64) -> io::Result<()> {
    #[cfg(any(
        all(target_os = "linux", not(target_env = "musl")),
        target_os = "android"
    ))]
    use libc::{off64_t, pread64};
    #[cfg(not(any(
        all(target_os = "linux", not(target_env = "musl")),
        target_os = "android"
    )))]
    use libc::{off_t as off64_t, pread as pread64};
    use std::os::unix::io::AsRawFd;

    // `pread`'s count is bounded by SSIZE_MAX regardless of off_t width; a
    // >2 GB chunk on 32-bit + LFS would get EINVAL from the kernel.
    validate_range(
        offset,
        dst.len(),
        off64_t::MAX as u64,
        libc::ssize_t::MAX as usize,
    )?;
    let fd = file.as_raw_fd();
    read_exact_at_loop(dst, offset, |dst, offset| {
        // `validate_range` bounds every offset in the range by `off64_t::MAX`,
        // and intermediate offsets stay within that range.
        let offset = offset as off64_t;
        // SAFETY: `dst` is valid for writes of `dst.len()` bytes, and `pread64`
        // writes only within the count it is given.
        let n = unsafe { pread64(fd, dst.as_mut_ptr().cast(), dst.len(), offset) };
        match n {
            0 => Ok(0),
            n if n > 0 => Ok(n as usize),
            _ => Err(io::Error::last_os_error()),
        }
    })
}

/// Reads exactly enough bytes to fill every writable run in `dst`.
///
/// The first byte is read from `offset`; subsequent runs continue from the end
/// of the preceding run. The file cursor is unchanged on Unix and WASI; on
/// Windows it ends after the last byte read.
///
/// A run is published to [`PartBuffer`] only after the positioned read has
/// initialized that complete run. If a later read fails, earlier completed
/// runs remain initialized, but the failing run remains unpublished. Callers
/// must discard the complete buffer on error rather than freezing a partial
/// upload payload.
///
/// Returns [`io::ErrorKind::UnexpectedEof`] when the requested range extends
/// beyond the file and an error when the range offset cannot be represented.
pub(crate) fn read_exact_at(file: &File, dst: &mut PartBuffer, mut offset: u64) -> io::Result<()> {
    while dst.writable() != 0 {
        // SAFETY: the returned slice remains `MaybeUninit<u8>` until the
        // positioned read initializes the complete range.
        let uninitialized = unsafe { dst.chunk_mut().as_uninit_slice_mut() };
        let count = uninitialized.len();
        if count == 0 {
            return Err(io::Error::other(
                "pooled file buffer exposed no writable range",
            ));
        }

        sys::read_exact_at(file, uninitialized, offset)?;
        // SAFETY: `sys::read_exact_at` returned `Ok`, so it initialized all
        // `count` bytes of the run.
        unsafe {
            dst.advance_mut(count);
        }
        offset = offset
            .checked_add(count as u64)
            .ok_or_else(|| io::Error::other("file read offset overflowed"))?;
    }
    Ok(())
}

/// Writes all remaining bytes from `buf` beginning at `offset`.
///
/// Each call writes at its own offset, so disjoint calls on the same open file
/// may progress concurrently without coordinating on a shared cursor. The
/// cursor is unchanged on Unix and WASI; on Windows it ends after the last
/// byte written, as a side effect of `WriteFile` with `OVERLAPPED` on a
/// synchronous handle. The buffer is advanced after each successful write; an
/// error leaves it positioned after the bytes already written so the caller
/// can observe partial progress.
///
/// Unix uses vectored positioned writes to preserve segment boundaries.
/// Windows and WASI write one segment per call. Platforms without
/// positioned-write support return [`io::ErrorKind::Unsupported`].
pub(crate) fn write_all_at(file: &File, buf: &mut impl Buf, offset: u64) -> io::Result<()> {
    sys::write_all_at(file, buf, offset)
}

/// Prepares `file` for an expected final length of `len` bytes.
///
/// Linux reserves the range with `posix_fallocate`, allowing allocation
/// failures to surface before transfer writes begin. Other Unix systems,
/// Windows, and WASI set the logical file length without guaranteeing physical
/// space; unsupported platforms treat the request as a no-op.
///
/// This operation does not flush file data or metadata. Successful return is
/// not a durability guarantee.
pub(crate) fn preallocate(file: &File, len: u64) -> io::Result<()> {
    sys::preallocate(file, len)
}

/// Reports whether `file`'s handle is in append mode, so that positioned
/// writes through it would not land at their offsets.
///
/// - On Unix, true when the open file description has `O_APPEND` set. Linux
///   and Android append every positioned write to such a file regardless of
///   its offset.
/// - On Windows, true when the handle was granted `FILE_APPEND_DATA` without
///   `FILE_WRITE_DATA`, as [`OpenOptions::append`](std::fs::OpenOptions::append)
///   opens it. Every write through such a handle goes to the end of the file
///   regardless of its offset.
/// - On WASI, true when wasi-libc reports `O_APPEND` in the descriptor's status
///   flags.
/// - Under Miri, and on other targets, the handle is not inspected and the
///   result is `Ok(false)`.
///
/// The result describes the handle at the time of the call. An error means
/// the handle's mode could not be read.
pub(crate) fn is_append_only(file: &File) -> io::Result<bool> {
    sys::is_append_only(file)
}

/// Creates the first of `candidates` that does not exist yet and opens it for
/// writing.
///
/// Each candidate is opened with
/// [`create_new`](std::fs::OpenOptions::create_new), so it succeeds only if no
/// entry, including a dangling symbolic link, exists at that path. An existing
/// entry is never opened, truncated, or followed; the next candidate is tried
/// instead. The caller bounds the attempts by the candidates it passes.
///
/// Returns the open file and its path. Returns
/// [`io::ErrorKind::AlreadyExists`] when every candidate named an existing
/// entry, or there were none. Any other error from opening a candidate is
/// returned at once.
pub(crate) fn create_first_new(
    candidates: impl IntoIterator<Item = PathBuf>,
) -> io::Result<(File, PathBuf)> {
    let mut tried = 0;
    for path in candidates {
        tried += 1;
        match File::options().write(true).create_new(true).open(&path) {
            Ok(file) => return Ok((file, path)),
            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
            Err(error) => return Err(error),
        }
    }
    Err(io::Error::new(
        io::ErrorKind::AlreadyExists,
        format!("every candidate path already exists ({tried} tried)"),
    ))
}

/// Runs [`create_first_new`] on the blocking thread pool, or inline on wasm
/// targets.
///
/// Returns its result, or an error if the blocking task panics or is
/// cancelled.
#[cfg(any(unix, windows, target_os = "wasi"))]
pub(crate) async fn create_first_new_async(
    candidates: Vec<PathBuf>,
) -> io::Result<(File, PathBuf)> {
    run_blocking(move || create_first_new(candidates)).await
}

/// Whether `file` is a file on disk, rather than a pipe, a character device
/// (such as `NUL` or a console), or a socket.
#[cfg(windows)]
pub(crate) fn is_disk_file(file: &File) -> bool {
    use std::os::windows::io::AsRawHandle;
    use windows_sys::Win32::Storage::FileSystem::{GetFileType, FILE_TYPE_DISK};

    // SAFETY: the handle is borrowed from `file` and stays open for the call.
    unsafe { GetFileType(file.as_raw_handle()) == FILE_TYPE_DISK }
}

/// Opens `path` read-only with `O_NONBLOCK`, so opening a FIFO does not wait
/// for a writer.
#[cfg(all(unix, not(miri)))]
pub(crate) fn open_without_blocking(path: &Path) -> io::Result<File> {
    use std::os::unix::fs::OpenOptionsExt;

    File::options()
        .read(true)
        .custom_flags(libc::O_NONBLOCK)
        .open(path)
}

/// Clears the `O_NONBLOCK` status flag set by [`open_without_blocking`].
#[cfg(all(unix, not(miri)))]
pub(crate) fn restore_blocking(file: &File) -> io::Result<()> {
    use nix::fcntl::{fcntl, FcntlArg, OFlag};
    use std::os::unix::io::AsFd;

    let flags =
        OFlag::from_bits_truncate(fcntl(file.as_fd(), FcntlArg::F_GETFL).map_err(io::Error::from)?);
    fcntl(file.as_fd(), FcntlArg::F_SETFL(flags - OFlag::O_NONBLOCK)).map_err(io::Error::from)?;
    Ok(())
}

/// Opens `path` read-only.
#[cfg(not(all(unix, not(miri))))]
pub(crate) fn open_without_blocking(path: &Path) -> io::Result<File> {
    File::open(path)
}

/// Does nothing: [`open_without_blocking`] sets no status flags here.
#[cfg(not(all(unix, not(miri))))]
pub(crate) fn restore_blocking(_file: &File) -> io::Result<()> {
    Ok(())
}

/// Renames `from` to `to`.
///
/// Uses [`tokio::fs::rename`], or [`std::fs::rename`] on the calling thread on
/// wasm targets, where tokio's blocking pool is unavailable. Returns the
/// rename's result.
#[cfg(not(target_family = "wasm"))]
pub(crate) async fn rename_async(from: &Path, to: &Path) -> io::Result<()> {
    tokio::fs::rename(from, to).await
}

/// Renames `from` to `to`.
///
/// Uses [`tokio::fs::rename`], or [`std::fs::rename`] on the calling thread on
/// wasm targets, where tokio's blocking pool is unavailable. Returns the
/// rename's result.
#[cfg(target_family = "wasm")]
pub(crate) async fn rename_async(from: &Path, to: &Path) -> io::Result<()> {
    std::fs::rename(from, to)
}

/// Removes the file at `path`.
///
/// Uses [`tokio::fs::remove_file`], or [`std::fs::remove_file`] on the calling
/// thread on wasm targets, where tokio's blocking pool is unavailable. Returns
/// the removal's result.
#[cfg(not(target_family = "wasm"))]
pub(crate) async fn remove_file_async(path: &Path) -> io::Result<()> {
    tokio::fs::remove_file(path).await
}

/// Removes the file at `path`.
///
/// Uses [`tokio::fs::remove_file`], or [`std::fs::remove_file`] on the calling
/// thread on wasm targets, where tokio's blocking pool is unavailable. Returns
/// the removal's result.
#[cfg(target_family = "wasm")]
pub(crate) async fn remove_file_async(path: &Path) -> io::Result<()> {
    std::fs::remove_file(path)
}

/// Runs `operation` on tokio's blocking thread pool.
///
/// Returns its result, or an error if the blocking task panics or is
/// cancelled.
#[cfg(not(target_family = "wasm"))]
async fn run_blocking<T: Send + 'static>(
    operation: impl FnOnce() -> io::Result<T> + Send + 'static,
) -> io::Result<T> {
    tokio::task::spawn_blocking(operation).await?
}

/// Runs `operation` on the calling thread.
///
/// wasip1 and wasip2 cannot spawn the threads a blocking pool needs, and
/// wasip3's cooperative threads run one at a time.
#[cfg(all(target_family = "wasm", not(target_os = "unknown")))]
async fn run_blocking<T>(operation: impl FnOnce() -> io::Result<T>) -> io::Result<T> {
    operation()
}

#[cfg(not(target_os = "wasi"))]
pub(crate) use same_file::Handle;
#[cfg(target_os = "wasi")]
pub(crate) use sys::Handle;

#[cfg(all(unix, not(miri)))]
mod sys {
    //! Native Unix positioned I/O.

    use bytes::Buf;
    use std::fs::File;
    use std::io::{self, IoSlice};
    use std::os::unix::io::AsFd;

    /// Maximum number of I/O vector entries per system call.
    const MAX_IO_SLICES: usize = 128;

    pub(super) use super::read_exact_at_unix as read_exact_at;

    /// Drains segmented input with as few positioned writes as the iovec limit permits.
    pub(super) fn write_all_at(file: &File, buf: &mut impl Buf, offset: u64) -> io::Result<()> {
        let fd = file.as_fd();
        super::validate_off_t_range(offset, buf.remaining())?;
        super::write_all_at_loop(buf, offset, |buf, offset| {
            let mut slices = [IoSlice::new(&[]); MAX_IO_SLICES];
            let n = buf.chunks_vectored(&mut slices);
            let offset = libc::off_t::try_from(offset)
                .expect("validated Unix file offset must fit in off_t");
            nix::sys::uio::pwritev(fd, &slices[..n], offset).map_err(io::Error::from)
        })
    }

    #[cfg(target_os = "linux")]
    pub(super) fn preallocate(file: &File, len: u64) -> io::Result<()> {
        if len == 0 {
            return file.set_len(0);
        }
        let len = libc::off_t::try_from(len).map_err(|_| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                "file length exceeds the platform limit",
            )
        })?;
        nix::fcntl::posix_fallocate(file.as_fd(), 0, len).map_err(io::Error::from)
    }

    #[cfg(not(target_os = "linux"))]
    pub(super) fn preallocate(file: &File, len: u64) -> io::Result<()> {
        file.set_len(len)
    }

    /// Reports whether the descriptor's status flags include `O_APPEND`.
    pub(super) fn is_append_only(file: &File) -> io::Result<bool> {
        use nix::fcntl::{fcntl, FcntlArg, OFlag};

        let flags = fcntl(file.as_fd(), FcntlArg::F_GETFL).map_err(io::Error::from)?;
        Ok(OFlag::from_bits_truncate(flags).contains(OFlag::O_APPEND))
    }
}

#[cfg(all(unix, miri))]
mod sys {
    //! Miri-compatible Unix operations.
    //!
    //! Scalar positioned writes replace unsupported `pwritev` FFI while
    //! retaining the same buffer advancement and offset behavior.

    use bytes::Buf;
    use std::fs::File;
    use std::io;
    use std::os::unix::fs::FileExt;

    pub(super) use super::read_exact_at_unix as read_exact_at;

    pub(super) fn write_all_at(file: &File, buf: &mut impl Buf, offset: u64) -> io::Result<()> {
        super::validate_off_t_range(offset, buf.remaining())?;
        super::write_all_at_loop(buf, offset, |buf, offset| {
            file.write_at(buf.chunk(), offset)
        })
    }

    pub(super) fn preallocate(file: &File, len: u64) -> io::Result<()> {
        file.set_len(len)
    }

    /// Does not inspect the handle: always `Ok(false)`.
    pub(super) fn is_append_only(_file: &File) -> io::Result<bool> {
        Ok(false)
    }
}

#[cfg(windows)]
mod sys {
    //! Windows positioned I/O.
    //!
    //! `seek_read` and `seek_write` read and write at explicit offsets; unlike
    //! Unix `pread`/`pwrite`, they leave the file cursor after the bytes
    //! transferred.

    use bytes::Buf;
    use std::fs::File;
    use std::io;
    use std::mem::MaybeUninit;
    use std::os::windows::fs::FileExt;

    /// Initializes every byte of `dst` from `file`, starting at `offset`.
    ///
    /// Calls `ReadFile` with the destination's raw pointer, so no `&mut [u8]`
    /// is formed over uninitialized memory. As with `seek_read`, the file
    /// cursor ends after the last byte read.
    pub(super) fn read_exact_at(
        file: &File,
        dst: &mut [MaybeUninit<u8>],
        offset: u64,
    ) -> io::Result<()> {
        use std::os::windows::io::AsRawHandle;
        use windows_sys::Win32::Foundation::ERROR_HANDLE_EOF;
        use windows_sys::Win32::Storage::FileSystem::ReadFile;
        use windows_sys::Win32::System::IO::{OVERLAPPED, OVERLAPPED_0, OVERLAPPED_0_0};

        // NTFS file sizes are stored as LARGE_INTEGER (i64); the last byte of
        // the range must not exceed i64::MAX or ReadFile hits the NTFS ceiling.
        super::validate_range(offset, dst.len(), i64::MAX as u64, usize::MAX)?;

        super::read_exact_at_loop(dst, offset, |dst, offset| {
            let count = dst.len().min(u32::MAX as usize) as u32;
            // `mut` required: ReadFile writes Internal and InternalHigh on
            // every synchronous completion.
            let mut overlapped = OVERLAPPED {
                Internal: 0,
                InternalHigh: 0,
                Anonymous: OVERLAPPED_0 {
                    Anonymous: OVERLAPPED_0_0 {
                        Offset: offset as u32,
                        OffsetHigh: (offset >> 32) as u32,
                    },
                },
                hEvent: std::ptr::null_mut(),
            };
            let mut bytes_read: u32 = 0;
            // SAFETY: `dst` is valid for writes of `count <= dst.len()` bytes,
            // and the handle is borrowed from `file` for the call. On a
            // synchronous handle, a non-null OVERLAPPED reads from its offset
            // and the call returns once the read completes.
            let ok = unsafe {
                ReadFile(
                    file.as_raw_handle(),
                    dst.as_mut_ptr().cast(),
                    count,
                    &mut bytes_read,
                    &mut overlapped,
                )
            };
            if ok == 0 {
                let err = io::Error::last_os_error();
                // On a synchronous handle with a non-null OVERLAPPED, EOF is
                // reported as FALSE + ERROR_HANDLE_EOF. Normalize to Ok(0)
                // so the loop emits UnexpectedEof like Unix.
                if err.raw_os_error() == Some(ERROR_HANDLE_EOF as i32) {
                    Ok(0)
                } else {
                    Err(err)
                }
            } else {
                Ok(bytes_read as usize)
            }
        })
    }

    pub(super) fn write_all_at(file: &File, buf: &mut impl Buf, offset: u64) -> io::Result<()> {
        super::write_all_at_loop(buf, offset, |buf, offset| {
            file.seek_write(buf.chunk(), offset)
        })
    }

    pub(super) fn preallocate(file: &File, len: u64) -> io::Result<()> {
        // Windows has no native fallocate equivalent. set_len calls
        // SetEndOfFile which extends the file logical size; matches the
        // macOS path. On both platforms preallocation is best-effort
        // length-setting without disk-space reservation; only Linux's
        // posix_fallocate guarantees ENOSPC at preallocate time.
        file.set_len(len)
    }

    /// Reports whether `file`'s handle was granted `FILE_APPEND_DATA` without
    /// `FILE_WRITE_DATA`.
    ///
    /// Windows has no `O_APPEND` flag: append mode is a property of the
    /// access a handle was granted. std's `OpenOptions::append` requests
    /// `FILE_GENERIC_WRITE & !FILE_WRITE_DATA`, which keeps
    /// `FILE_APPEND_DATA`. Every write through a handle that has
    /// `FILE_APPEND_DATA` but not `FILE_WRITE_DATA` goes to the end of the
    /// file, whatever offset it names, and resizing the file through such a
    /// handle fails with access denied. A handle that has `FILE_WRITE_DATA`
    /// writes at the offsets it names, whether or not it also has
    /// `FILE_APPEND_DATA`.
    ///
    /// The granted access is read with `NtQueryInformationFile` for
    /// `FileAccessInformation`. A query that does not return
    /// `STATUS_SUCCESS` is reported as the equivalent Win32 error.
    pub(super) fn is_append_only(file: &File) -> io::Result<bool> {
        use std::mem::MaybeUninit;
        use std::os::windows::io::AsRawHandle;

        use windows_sys::Wdk::Storage::FileSystem::{
            FileAccessInformation, NtQueryInformationFile, FILE_ACCESS_INFORMATION,
        };
        use windows_sys::Win32::Foundation::{RtlNtStatusToDosError, STATUS_SUCCESS};
        use windows_sys::Win32::Storage::FileSystem::{FILE_APPEND_DATA, FILE_WRITE_DATA};
        use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;

        let mut io_status = MaybeUninit::<IO_STATUS_BLOCK>::uninit();
        let mut info = FILE_ACCESS_INFORMATION { AccessFlags: 0 };
        // SAFETY: the handle comes from `file`, which is borrowed for the
        // whole call, so it stays open and valid. `io_status` is writable
        // storage for one IO_STATUS_BLOCK. `info` is a local
        // FILE_ACCESS_INFORMATION, so it is properly sized and aligned for
        // the FileAccessInformation class, and the length passed is its size.
        let status = unsafe {
            NtQueryInformationFile(
                file.as_raw_handle(),
                io_status.as_mut_ptr(),
                std::ptr::from_mut(&mut info).cast(),
                std::mem::size_of::<FILE_ACCESS_INFORMATION>() as u32,
                FileAccessInformation,
            )
        };
        if status != STATUS_SUCCESS {
            // SAFETY: RtlNtStatusToDosError only maps its argument to a
            // Win32 error code.
            let code = unsafe { RtlNtStatusToDosError(status) };
            return Err(io::Error::from_raw_os_error(code as i32));
        }
        let access = info.AccessFlags;
        Ok((access & FILE_APPEND_DATA) != 0 && (access & FILE_WRITE_DATA) == 0)
    }
}

#[cfg(target_os = "wasi")]
mod sys {
    //! WASI positioned I/O and file identity through rustix.
    //!
    //! std's `FileExt` positioned reads and writes are unstable on WASI, and
    //! same-file supports only Unix and Windows.

    use bytes::Buf;
    use std::fs::File;
    use std::io;
    use std::mem::MaybeUninit;
    use std::path::Path;

    /// Identity of the file a path names.
    ///
    /// Opens the path, following symbolic links, and identifies the file by
    /// the device and inode `fstat` reports for the open descriptor. As with
    /// `same_file::Handle`, the descriptor stays open for the handle's
    /// lifetime, so the identity cannot be reused by another file while it is
    /// compared.
    #[derive(Debug)]
    pub(crate) struct Handle {
        _file: File,
        dev: u64,
        ino: u64,
    }

    impl PartialEq for Handle {
        fn eq(&self, other: &Self) -> bool {
            (self.dev, self.ino) == (other.dev, other.ino)
        }
    }

    impl Eq for Handle {}

    impl Handle {
        /// Opens `path` and reads the identity of the file it names.
        ///
        /// Returns the error from opening the path or from `fstat`.
        pub(crate) fn from_path(path: impl AsRef<Path>) -> io::Result<Self> {
            let file = File::open(path)?;
            let stat = rustix::fs::fstat(&file)?;
            Ok(Self {
                _file: file,
                dev: stat.st_dev,
                ino: stat.st_ino,
            })
        }
    }

    /// Initializes every byte of `dst` from `file`, starting at `offset`,
    /// without changing the file cursor.
    ///
    /// `rustix::io::pread` reads into `&mut [MaybeUninit<u8>]` and returns the
    /// initialized prefix.
    pub(super) fn read_exact_at(
        file: &File,
        dst: &mut [MaybeUninit<u8>],
        offset: u64,
    ) -> io::Result<()> {
        super::validate_off_t_range(offset, dst.len())?;
        super::read_exact_at_loop(dst, offset, |dst, offset| {
            let (initialized, _) = rustix::io::pread(file, dst, offset)?;
            Ok(initialized.len())
        })
    }

    pub(super) fn write_all_at(file: &File, buf: &mut impl Buf, offset: u64) -> io::Result<()> {
        super::validate_off_t_range(offset, buf.remaining())?;
        super::write_all_at_loop(buf, offset, |buf, offset| {
            Ok(rustix::io::pwrite(file, buf.chunk(), offset)?)
        })
    }

    pub(super) fn preallocate(file: &File, len: u64) -> io::Result<()> {
        file.set_len(len)
    }

    /// Reports whether the descriptor's status flags include `O_APPEND`.
    pub(super) fn is_append_only(file: &File) -> io::Result<bool> {
        let flags = rustix::fs::fcntl_getfl(file)?;
        Ok(flags.contains(rustix::fs::OFlags::APPEND))
    }
}

#[cfg(not(any(unix, windows, target_os = "wasi")))]
mod sys {
    //! Fallbacks for platforms without positioned filesystem operations.

    use bytes::Buf;
    use std::fs::File;
    use std::io;
    use std::mem::MaybeUninit;

    pub(super) fn read_exact_at(
        _file: &File,
        _dst: &mut [MaybeUninit<u8>],
        _offset: u64,
    ) -> io::Result<()> {
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "positioned reads not supported on this platform",
        ))
    }

    pub(super) fn write_all_at(_file: &File, _buf: &mut impl Buf, _offset: u64) -> io::Result<()> {
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "positioned writes not supported on this platform",
        ))
    }

    pub(super) fn preallocate(_file: &File, _len: u64) -> io::Result<()> {
        Ok(())
    }

    /// Does not inspect the handle: always `Ok(false)`.
    pub(super) fn is_append_only(_file: &File) -> io::Result<bool> {
        Ok(false)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::ByteSize;
    use std::io::IoSlice;
    use std::path::Path;
    use std::task::{Context, Waker};

    use bytes::Bytes;
    use bytes_utils::SegmentedBuf;

    use crate::config::MemoryBudgetConfig;
    use crate::io::PartBuffer;
    use crate::memory::BufferPool;

    fn test_pool() -> BufferPool {
        BufferPool::builder()
            .memory_budget(MemoryBudgetConfig::Limit(ByteSize::new(1024 * 1024)))
            .build()
            .unwrap()
    }

    fn buf_prefix(buf: &impl Buf, limit: usize) -> Vec<u8> {
        let mut slices = [IoSlice::new(&[]); 8];
        let count = buf.chunks_vectored(&mut slices);
        let mut remaining = limit.min(buf.remaining());
        let mut out = Vec::with_capacity(remaining);
        for slice in &slices[..count] {
            let count = remaining.min(slice.len());
            out.extend_from_slice(&slice[..count]);
            remaining -= count;
            if remaining == 0 {
                break;
            }
        }
        out
    }

    #[test]
    fn read_exact_loop_retries_interrupts_and_short_reads() {
        let source = b"0123456789";
        let mut dst = [MaybeUninit::<u8>::uninit(); 5];
        let mut calls = 0usize;
        let mut offsets = Vec::new();

        read_exact_at_loop(&mut dst, 3, |dst, offset| {
            offsets.push(offset);
            calls += 1;
            if calls == 1 {
                return Err(io::Error::from(io::ErrorKind::Interrupted));
            }
            let count = match calls {
                2 => 2,
                3 => 1,
                _ => dst.len(),
            };
            let start = offset as usize;
            for (i, byte) in dst[..count].iter_mut().enumerate() {
                byte.write(source[start + i]);
            }
            Ok(count)
        })
        .unwrap();

        // SAFETY: the loop returned `Ok`, so every byte of `dst` was written.
        let read = dst.map(|byte| unsafe { byte.assume_init() });
        assert_eq!(&read, b"34567");
        assert_eq!(offsets, [3, 3, 5, 6]);
    }

    #[test]
    fn read_exact_loop_reports_unexpected_eof_after_partial_progress() {
        let mut dst = [MaybeUninit::<u8>::uninit(); 4];
        let mut calls = 0usize;

        let error = read_exact_at_loop(&mut dst, 0, |dst, _| {
            calls += 1;
            if calls == 1 {
                dst[0].write(b'a');
                dst[1].write(b'b');
                Ok(2)
            } else {
                Ok(0)
            }
        })
        .unwrap_err();

        assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof);
        assert_eq!(calls, 2);
        assert_eq!(unsafe { dst[0].assume_init() }, b'a');
        assert_eq!(unsafe { dst[1].assume_init() }, b'b');
    }

    #[test]
    fn write_all_loop_retries_interrupts_and_advances_segmented_input() {
        let mut input = SegmentedBuf::new();
        input.push(Bytes::from_static(b"ab"));
        input.push(Bytes::from_static(b"cdef"));
        input.push(Bytes::from_static(b"ghi"));
        let mut output = vec![0u8; 4];
        let mut calls = 0usize;
        let mut offsets = Vec::new();

        write_all_at_loop(&mut input, 4, |buf, offset| {
            offsets.push(offset);
            calls += 1;
            if calls == 1 {
                return Err(io::Error::from(io::ErrorKind::Interrupted));
            }
            let limit = match calls {
                2 => 2,
                3 => 3,
                _ => usize::MAX,
            };
            let bytes = buf_prefix(buf, limit);
            let start = offset as usize;
            output.resize(start + bytes.len(), 0);
            output[start..].copy_from_slice(&bytes);
            Ok(bytes.len())
        })
        .unwrap();

        assert_eq!(input.remaining(), 0);
        assert_eq!(&output[..4], &[0; 4]);
        assert_eq!(&output[4..], b"abcdefghi");
        assert_eq!(offsets, [4, 4, 6, 9]);
    }

    #[test]
    fn write_all_loop_preserves_partial_progress_on_error() {
        let mut input = Bytes::from_static(b"abcdef");
        let mut calls = 0usize;
        let mut offsets = Vec::new();

        let error = write_all_at_loop(&mut input, 10, |buf, offset| {
            offsets.push(offset);
            calls += 1;
            if calls == 1 {
                assert_eq!(buf_prefix(buf, 2), b"ab");
                Ok(2)
            } else {
                Err(io::Error::other("injected write failure"))
            }
        })
        .unwrap_err();

        assert_eq!(error.kind(), io::ErrorKind::Other);
        assert_eq!(input.as_ref(), b"cdef");
        assert_eq!(offsets, [10, 12]);
    }

    #[test]
    fn write_all_loop_rejects_zero_progress() {
        let mut input = Bytes::from_static(b"payload");
        let error = write_all_at_loop(&mut input, 0, |_, _| Ok(0)).unwrap_err();

        assert_eq!(error.kind(), io::ErrorKind::WriteZero);
        assert_eq!(input.as_ref(), b"payload");
    }

    #[cfg(unix)]
    #[test]
    fn write_all_at_rejects_unrepresentable_unix_offset() {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let mut input = Bytes::from_static(b"x");

        let error = write_all_at(tmp.as_file(), &mut input, u64::MAX).unwrap_err();

        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
        assert_eq!(input.as_ref(), b"x");
        assert_eq!(tmp.as_file().metadata().unwrap().len(), 0);
    }

    #[cfg(any(unix, windows))]
    #[cfg_attr(miri, ignore)] // the Miri build does not inspect the handle
    #[test]
    fn is_append_only_detects_append_mode() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("out.bin");

        let append = File::options()
            .append(true)
            .create(true)
            .open(&path)
            .unwrap();
        assert!(is_append_only(&append).unwrap());
        // `append(true)` already implies write access, so std ignores
        // `write(true)` beside it. The pair is checked because callers write
        // it, and must still be reported as append mode.
        let mut write_append = File::options();
        write_append.write(true);
        let write_append = write_append.append(true).open(&path).unwrap();
        assert!(is_append_only(&write_append).unwrap());
    }

    #[cfg(unix)]
    #[cfg_attr(miri, ignore)] // the Miri build does not inspect the handle
    #[test]
    fn is_append_only_detects_append_flag_set_after_open() {
        use nix::fcntl::{fcntl, FcntlArg, OFlag};
        use std::os::unix::io::AsFd;

        let dir = tempfile::tempdir().unwrap();
        let file = File::create(dir.path().join("out.bin")).unwrap();
        assert!(!is_append_only(&file).unwrap());

        let flags = OFlag::from_bits_truncate(fcntl(file.as_fd(), FcntlArg::F_GETFL).unwrap());
        fcntl(file.as_fd(), FcntlArg::F_SETFL(flags | OFlag::O_APPEND)).unwrap();

        assert!(is_append_only(&file).unwrap());
    }

    #[cfg(any(unix, windows))]
    #[cfg_attr(miri, ignore)] // the Miri build does not inspect the handle
    #[test]
    fn is_append_only_is_false_for_positional_handles() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("out.bin");

        let created = File::create(&path).unwrap();
        assert!(!is_append_only(&created).unwrap());
        let read_write = File::options().read(true).write(true).open(&path).unwrap();
        assert!(!is_append_only(&read_write).unwrap());
        let read_only = File::open(&path).unwrap();
        assert!(!is_append_only(&read_only).unwrap());
    }

    #[test]
    fn read_exact_at_initializes_pooled_runs() {
        let pool = test_pool();
        let part_size = pool.carrier_size() * 2 + 37;
        let data = (0..part_size)
            .map(|index| (index % 251) as u8)
            .collect::<Vec<_>>();
        let mut tmp = tempfile::NamedTempFile::new().unwrap();
        std::io::Write::write_all(&mut tmp, &data).unwrap();
        let mut buffer = PartBuffer::new(&pool, part_size);
        let waker = Waker::noop();
        let mut cx = Context::from_waker(waker);
        assert!(buffer.poll_acquire(&mut cx, part_size).is_ready());

        read_exact_at(tmp.as_file(), &mut buffer, 0).unwrap();
        let mut frozen = buffer.freeze();
        assert_eq!(frozen.copy_to_bytes(frozen.remaining()).as_ref(), data);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    /// Reads into memory that starts uninitialized, so Miri (with recursive
    /// validation) rejects any `&mut [u8]` formed over the destination before
    /// the read. Covers a read from a nonzero offset and a range that runs past
    /// the end of the file.
    // ref: RUST-1681
    #[cfg(any(unix, windows, target_os = "wasi"))]
    #[test]
    fn positioned_read_fills_uninitialized_memory_and_reports_eof() {
        let data = (0..64u8).collect::<Vec<_>>();
        let mut tmp = tempfile::NamedTempFile::new().unwrap();
        std::io::Write::write_all(&mut tmp, &data).unwrap();

        let mut dst = [MaybeUninit::<u8>::uninit(); 40];
        sys::read_exact_at(tmp.as_file(), &mut dst, 11).unwrap();
        // SAFETY: `read_exact_at` returned `Ok`, so every byte is initialized.
        let read = dst.map(|byte| unsafe { byte.assume_init() });
        assert_eq!(&read[..], &data[11..51]);

        // `sys::read_exact_at` returns `Ok` only once every byte of `dst` has
        // been written, and `read_exact_at` relies on that to publish the run
        // to the `PartBuffer` as initialized data. A file that ends before
        // `dst` is full must therefore be an error, not a short success:
        // a short `Ok` would publish the unwritten tail as file contents.
        //
        // 40 bytes are requested at offset 29 of the 64-byte file, so only 35
        // exist. The first `pread` returns those 35, the next returns 0 at end
        // of file, and the call fails with `UnexpectedEof`. `dst` is only
        // partly written, so the test does not read it.
        let mut dst = [MaybeUninit::<u8>::uninit(); 40];
        let error = sys::read_exact_at(tmp.as_file(), &mut dst, 29).unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof);
    }

    /// The Unix read path validates against `off64_t::MAX` before calling
    /// `pread64`. A `u64::MAX` offset exceeds that ceiling even on 64-bit
    /// targets and must be rejected without touching the file.
    #[cfg(unix)]
    #[test]
    fn read_exact_at_rejects_unrepresentable_unix_offset() {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let mut dst = [MaybeUninit::<u8>::uninit(); 1];

        let error = sys::read_exact_at(tmp.as_file(), &mut dst, u64::MAX).unwrap_err();

        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
    }

    /// The Windows read path validates against `i64::MAX` (the NTFS
    /// `LARGE_INTEGER` ceiling) before calling `ReadFile`. A `u64::MAX` offset
    /// sits above that ceiling and must be rejected.
    #[cfg(windows)]
    #[test]
    fn read_exact_at_rejects_unrepresentable_windows_offset() {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let mut dst = [MaybeUninit::<u8>::uninit(); 1];

        let error = sys::read_exact_at(tmp.as_file(), &mut dst, u64::MAX).unwrap_err();

        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
    }

    #[test]
    fn write_all_at_single_segment() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.bin");
        let file = File::create(&path).unwrap();

        let data = Bytes::from_static(b"hello world");
        let mut seg = SegmentedBuf::new();
        seg.push(data);

        write_all_at(&file, &mut seg, 0).unwrap();
        drop(file);

        let contents = std::fs::read(&path).unwrap();
        assert_eq!(contents, b"hello world");
    }

    #[test]
    fn write_all_at_multiple_segments() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.bin");
        let file = File::create(&path).unwrap();

        let mut seg = SegmentedBuf::new();
        seg.push(Bytes::from_static(b"aaa"));
        seg.push(Bytes::from_static(b"bbb"));
        seg.push(Bytes::from_static(b"ccc"));

        write_all_at(&file, &mut seg, 0).unwrap();
        drop(file);

        let contents = std::fs::read(&path).unwrap();
        assert_eq!(contents, b"aaabbbccc");
    }

    #[test]
    fn write_all_at_nonzero_offset() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.bin");
        let file = File::create(&path).unwrap();

        // Write at offset 0
        let mut seg0 = SegmentedBuf::new();
        seg0.push(Bytes::from_static(b"AAAA"));
        write_all_at(&file, &mut seg0, 0).unwrap();

        // Write at offset 4
        let mut seg1 = SegmentedBuf::new();
        seg1.push(Bytes::from_static(b"BBBB"));
        write_all_at(&file, &mut seg1, 4).unwrap();

        drop(file);

        let contents = std::fs::read(&path).unwrap();
        assert_eq!(contents, b"AAAABBBB");
    }

    #[test]
    fn write_all_at_out_of_order() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.bin");
        let file = File::create(&path).unwrap();

        // Write second chunk first
        let mut seg1 = SegmentedBuf::new();
        seg1.push(Bytes::from_static(b"BBBB"));
        write_all_at(&file, &mut seg1, 4).unwrap();

        // Write first chunk second
        let mut seg0 = SegmentedBuf::new();
        seg0.push(Bytes::from_static(b"AAAA"));
        write_all_at(&file, &mut seg0, 0).unwrap();

        drop(file);

        let contents = std::fs::read(&path).unwrap();
        assert_eq!(contents, b"AAAABBBB");
    }

    #[test]
    fn write_all_at_empty_buf() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.bin");
        let file = File::create(&path).unwrap();

        let mut seg = SegmentedBuf::<Bytes>::new();
        write_all_at(&file, &mut seg, 0).unwrap();
        drop(file);

        let contents = std::fs::read(&path).unwrap();
        assert!(contents.is_empty());
    }

    /// More segments than a single pwritev call can handle (128 IoSlice limit).
    /// Exercises the loop that issues multiple system calls.
    #[test]
    fn write_all_at_exceeds_io_slice_limit() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.bin");
        let file = File::create(&path).unwrap();

        let num_segments = 192;
        let segment_size = 4096;
        let mut seg = SegmentedBuf::new();
        let mut expected = Vec::with_capacity(num_segments * segment_size);
        for i in 0..num_segments {
            let byte = (i % 256) as u8;
            let data = vec![byte; segment_size];
            expected.extend_from_slice(&data);
            seg.push(Bytes::from(data));
        }

        write_all_at(&file, &mut seg, 0).unwrap();
        drop(file);

        let contents = std::fs::read(&path).unwrap();
        assert_eq!(contents.len(), expected.len());
        assert_eq!(contents, expected);
    }

    /// Two 8MB writes at different offsets, each composed of many small segments.
    #[cfg_attr(miri, ignore)] // 16MB through miri's interpreter is too slow
    #[test]
    fn write_all_at_large_parts_at_offsets() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.bin");
        let file = File::create(&path).unwrap();

        let part_size: usize = 8 * 1024 * 1024;
        let segment_size: usize = 16 * 1024;
        let num_segments = part_size / segment_size;

        let mut seg0 = SegmentedBuf::new();
        for _ in 0..num_segments {
            seg0.push(Bytes::from(vec![0xAA; segment_size]));
        }
        write_all_at(&file, &mut seg0, 0).unwrap();

        let mut seg1 = SegmentedBuf::new();
        for _ in 0..num_segments {
            seg1.push(Bytes::from(vec![0xBB; segment_size]));
        }
        write_all_at(&file, &mut seg1, part_size as u64).unwrap();

        drop(file);

        let contents = std::fs::read(&path).unwrap();
        assert_eq!(contents.len(), part_size * 2);
        assert!(contents[..part_size].iter().all(|&b| b == 0xAA));
        assert!(contents[part_size..].iter().all(|&b| b == 0xBB));
    }

    #[test]
    fn preallocate_sets_file_size() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("prealloc.bin");
        let file = File::create(&path).unwrap();

        let len = 1024 * 1024; // 1 MB
        preallocate(&file, len).unwrap();

        let meta = std::fs::metadata(&path).unwrap();
        assert_eq!(meta.len(), len);
    }

    /// Writes through the returned handle and checks the bytes land at the
    /// returned path, so the handle is known to refer to that file.
    fn assert_handle_writes_path(mut file: std::fs::File, path: &Path) {
        std::io::Write::write_all(&mut file, b"object").unwrap();
        drop(file);
        assert_eq!(std::fs::read(path).unwrap(), b"object");
    }

    #[test]
    fn create_first_new_leaves_existing_file_and_uses_next_candidate() {
        let dir = tempfile::tempdir().unwrap();
        let existing = dir.path().join("taken");
        std::fs::write(&existing, b"CUSTOMER").unwrap();
        let free = dir.path().join("free");

        let (file, path) =
            create_first_new([existing.clone(), existing.clone(), free.clone()]).unwrap();

        assert_eq!(path, free);
        assert_handle_writes_path(file, &path);
        assert_eq!(std::fs::read(&existing).unwrap(), b"CUSTOMER");
    }

    #[cfg(unix)]
    #[test]
    fn create_first_new_does_not_follow_symlink_at_candidate() {
        let dir = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let target = outside.path().join("victim.txt");
        std::fs::write(&target, b"VICTIM").unwrap();
        let link = dir.path().join("link");
        std::os::unix::fs::symlink(&target, &link).unwrap();
        let free = dir.path().join("free");

        let (file, path) = create_first_new([link.clone(), free.clone()]).unwrap();

        assert_eq!(path, free);
        assert_handle_writes_path(file, &path);
        assert_eq!(std::fs::read(&target).unwrap(), b"VICTIM");
        assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
    }

    #[test]
    fn create_first_new_fails_when_every_candidate_exists() {
        let dir = tempfile::tempdir().unwrap();
        let taken: Vec<PathBuf> = (0u8..3)
            .map(|i| {
                let path = dir.path().join(format!("taken-{i}"));
                std::fs::write(&path, [i]).unwrap();
                path
            })
            .collect();

        let error = create_first_new(taken.clone()).unwrap_err();

        assert_eq!(error.kind(), io::ErrorKind::AlreadyExists);
        assert!(error.to_string().contains("(3 tried)"), "{error}");
        for (i, path) in taken.iter().enumerate() {
            assert_eq!(std::fs::read(path).unwrap(), [i as u8]);
        }
    }
}