Skip to main content

system_interface/fs/
file_io_ext.rs

1//! The `FileIoExt` trait, and related utilities and impls.
2
3use crate::io::IoExt;
4use io_lifetimes::AsFilelike;
5#[cfg(not(any(
6    windows,
7    target_vendor = "apple",
8    target_os = "netbsd",
9    target_os = "openbsd",
10    target_os = "redox",
11)))]
12use rustix::fs::fadvise;
13#[cfg(target_vendor = "apple")]
14use rustix::fs::fcntl_rdadvise;
15#[cfg(not(any(
16    windows,
17    target_os = "netbsd",
18    target_os = "redox",
19    target_os = "openbsd"
20)))]
21use rustix::fs::{fallocate, FallocateFlags};
22#[cfg(not(any(windows, target_vendor = "apple", target_os = "redox")))]
23use rustix::io::{preadv, pwritev};
24use std::io::{self, IoSlice, IoSliceMut, Seek, SeekFrom};
25use std::slice;
26#[cfg(windows)]
27use {cap_fs_ext::Reopen, std::fs, std::os::windows::fs::FileExt};
28#[cfg(not(windows))]
29use {rustix::fs::tell, rustix::fs::FileExt};
30
31/// Advice to pass to `FileIoExt::advise`.
32#[cfg(not(any(
33    windows,
34    target_vendor = "apple",
35    target_os = "netbsd",
36    target_os = "openbsd",
37    target_os = "redox"
38)))]
39#[derive(Debug, Eq, PartialEq, Hash)]
40#[repr(i32)]
41pub enum Advice {
42    /// No advice; default heuristics apply.
43    Normal = rustix::fs::Advice::Normal as i32,
44    /// Data will be accessed sequentially at ascending offsets.
45    Sequential = rustix::fs::Advice::Sequential as i32,
46    /// Data will be accessed with an irregular access pattern.
47    Random = rustix::fs::Advice::Random as i32,
48    /// Data will be accessed soon.
49    WillNeed = rustix::fs::Advice::WillNeed as i32,
50    /// Data will not be accessed soon.
51    DontNeed = rustix::fs::Advice::DontNeed as i32,
52    /// Data will be accessed exactly once.
53    NoReuse = rustix::fs::Advice::NoReuse as i32,
54}
55
56/// Advice to pass to `FileIoExt::advise`.
57#[cfg(any(
58    windows,
59    target_vendor = "apple",
60    target_os = "netbsd",
61    target_os = "openbsd",
62    target_os = "redox"
63))]
64#[derive(Debug, Eq, PartialEq, Hash)]
65pub enum Advice {
66    /// No advice; default heuristics apply.
67    Normal,
68    /// Data will be accessed sequentially at ascending offsets.
69    Sequential,
70    /// Data will be accessed with an irregular access pattern.
71    Random,
72    /// Data will be accessed soon.
73    WillNeed,
74    /// Data will not be accessed soon.
75    DontNeed,
76    /// Data will be accessed exactly once.
77    NoReuse,
78}
79
80/// Extension trait for `std::fs::File` and `cap_std::fs::File`.
81pub trait FileIoExt: IoExt {
82    /// Announce the expected access pattern of the data at the given offset.
83    fn advise(&self, offset: u64, len: u64, advice: Advice) -> io::Result<()>;
84
85    /// Allocate space in the file, increasing the file size as needed, and
86    /// ensuring that there are no holes under the given range.
87    fn allocate(&self, offset: u64, len: u64) -> io::Result<()>;
88
89    /// Reads a number of bytes starting from a given offset.
90    ///
91    /// This is similar to [`std::os::unix::fs::FileExt::read_at`], except it
92    /// takes `self` by immutable reference since the entire side effect is
93    /// I/O, and it's supported on non-Unix platforms including Windows.
94    ///
95    /// [`std::os::unix::fs::FileExt::read_at`]: https://doc.rust-lang.org/std/os/unix/fs/trait.FileExt.html#tymethod.read_at
96    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize>;
97
98    /// Reads the exact number of byte required to fill buf from the given
99    /// offset.
100    ///
101    /// This is similar to [`std::os::unix::fs::FileExt::read_exact_at`],
102    /// except it takes `self` by immutable reference since the entire side
103    /// effect is I/O, and it's supported on non-Unix platforms including
104    /// Windows.
105    ///
106    /// [`std::os::unix::fs::FileExt::read_exact_at`]: https://doc.rust-lang.org/std/os/unix/fs/trait.FileExt.html#tymethod.read_exact_at
107    fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()>;
108
109    /// Is to `read_vectored` what `read_at` is to `read`.
110    fn read_vectored_at(&self, bufs: &mut [IoSliceMut], offset: u64) -> io::Result<usize> {
111        // By default, just read into the first non-empty slice.
112        let buf = bufs
113            .iter_mut()
114            .find(|b| !b.is_empty())
115            .map_or(&mut [][..], |b| &mut **b);
116        self.read_at(buf, offset)
117    }
118
119    /// Is to `read_exact_vectored` what `read_exact_at` is to `read_exact`.
120    fn read_exact_vectored_at(
121        &self,
122        mut bufs: &mut [IoSliceMut],
123        mut offset: u64,
124    ) -> io::Result<()> {
125        bufs = skip_leading_empties(bufs);
126        while !bufs.is_empty() {
127            match self.read_vectored_at(bufs, offset) {
128                Ok(0) => {
129                    return Err(io::Error::new(
130                        io::ErrorKind::UnexpectedEof,
131                        "failed to fill whole buffer",
132                    ))
133                }
134                Ok(nread) => {
135                    offset = offset
136                        .checked_add(nread.try_into().unwrap())
137                        .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "offset overflow"))?;
138                    bufs = advance_mut(bufs, nread);
139                }
140                Err(ref e) if e.kind() == io::ErrorKind::Interrupted => (),
141                Err(e) => return Err(e),
142            }
143            bufs = skip_leading_empties(bufs);
144        }
145        Ok(())
146    }
147
148    /// Determines if this `FileIoExt` implementation has an efficient
149    /// `read_vectored_at` implementation.
150    #[inline]
151    fn is_read_vectored_at(&self) -> bool {
152        false
153    }
154
155    /// Read all bytes, starting at `offset`, until EOF in this source, placing
156    /// them into `buf`.
157    fn read_to_end_at(&self, buf: &mut Vec<u8>, offset: u64) -> io::Result<usize>;
158
159    /// Read all bytes, starting at `offset`, until EOF in this source,
160    /// appending them to `buf`.
161    fn read_to_string_at(&self, buf: &mut String, offset: u64) -> io::Result<usize>;
162
163    /// Writes a number of bytes starting from a given offset.
164    ///
165    /// This is similar to [`std::os::unix::fs::FileExt::write_at`], except it
166    /// takes `self` by immutable reference since the entire side effect is
167    /// I/O, and it's supported on non-Unix platforms including Windows.
168    ///
169    /// A write past the end of the file extends the file with zero bytes until
170    /// the point where the write starts.
171    ///
172    /// Contrary to POSIX, on many popular platforms including Linux and
173    /// FreeBSD, if the file is opened in append mode, this ignores the offset
174    /// appends the data to the end of the file.
175    ///
176    /// [`std::os::unix::fs::FileExt::write_at`]: https://doc.rust-lang.org/std/os/unix/fs/trait.FileExt.html#tymethod.write_at
177    fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize>;
178
179    /// Attempts to write an entire buffer starting from a given offset.
180    ///
181    /// This is similar to [`std::os::unix::fs::FileExt::write_all_at`], except
182    /// it takes `self` by immutable reference since the entire side effect is
183    /// I/O, and it's supported on non-Unix platforms including Windows.
184    ///
185    /// A write past the end of the file extends the file with zero bytes until
186    /// the point where the write starts.
187    ///
188    /// Contrary to POSIX, on many popular platforms including Linux and
189    /// FreeBSD, if the file is opened in append mode, this ignores the offset
190    /// appends the data to the end of the file.
191    ///
192    /// [`std::os::unix::fs::FileExt::write_all_at`]: https://doc.rust-lang.org/std/os/unix/fs/trait.FileExt.html#tymethod.write_all_at
193    fn write_all_at(&self, mut buf: &[u8], mut offset: u64) -> io::Result<()> {
194        while !buf.is_empty() {
195            match self.write_at(buf, offset) {
196                Ok(nwritten) => {
197                    buf = &buf[nwritten..];
198                    offset += nwritten as u64;
199                }
200                Err(ref e) if e.kind() == io::ErrorKind::Interrupted => (),
201                Err(e) => return Err(e),
202            }
203        }
204        Ok(())
205    }
206
207    /// Is to `write_vectored` what `write_at` is to `write`.
208    fn write_vectored_at(&self, bufs: &[IoSlice], offset: u64) -> io::Result<usize> {
209        // By default, just write the first non-empty slice.
210        let buf = bufs
211            .iter()
212            .find(|b| !b.is_empty())
213            .map_or(&[][..], |b| &**b);
214        self.write_at(buf, offset)
215    }
216
217    /// Is to `write_all_vectored` what `write_all_at` is to `write_all`.
218    fn write_all_vectored_at(&self, mut bufs: &mut [IoSlice], mut offset: u64) -> io::Result<()> {
219        while !bufs.is_empty() {
220            match self.write_vectored_at(bufs, offset) {
221                Ok(nwritten) => {
222                    offset = offset
223                        .checked_add(nwritten.try_into().unwrap())
224                        .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "offset overflow"))?;
225                    bufs = advance(bufs, nwritten);
226                }
227                Err(ref e) if e.kind() == io::ErrorKind::Interrupted => (),
228                Err(e) => return Err(e),
229            }
230        }
231        Ok(())
232    }
233
234    /// Determines if this `FileIoExt` implementation has an efficient
235    /// `write_vectored_at` implementation.
236    #[inline]
237    fn is_write_vectored_at(&self) -> bool {
238        false
239    }
240
241    /// Writes a number of bytes at the end of a file.
242    ///
243    /// This leaves the current position of the file unmodified.
244    ///
245    /// This operation is not guaranteed to be atomic with respect to other
246    /// users of the same open file description.
247    ///
248    /// This operation is less efficient on some platforms than opening the
249    /// file in append mode and doing regular writes.
250    fn append(&self, buf: &[u8]) -> io::Result<usize>;
251
252    /// Attempts to write an entire buffer at the end of a file.
253    ///
254    /// This leaves the current position of the file unmodified.
255    ///
256    /// This operation is not guaranteed to be atomic with respect to other
257    /// users of the same open file description.
258    ///
259    /// This operation is less efficient on some platforms than opening the
260    /// file in append mode and doing regular writes.
261    fn append_all(&self, mut buf: &[u8]) -> io::Result<()> {
262        while !buf.is_empty() {
263            match self.append(buf) {
264                Ok(nwritten) => {
265                    buf = &buf[nwritten..];
266                }
267                Err(ref e) if e.kind() == io::ErrorKind::Interrupted => (),
268                Err(e) => return Err(e),
269            }
270        }
271        Ok(())
272    }
273
274    /// Is to `append` what `write_vectored` is to `write`.
275    fn append_vectored(&self, bufs: &[IoSlice]) -> io::Result<usize> {
276        // By default, just append the first non-empty slice.
277        let buf = bufs
278            .iter()
279            .find(|b| !b.is_empty())
280            .map_or(&[][..], |b| &**b);
281        self.append(buf)
282    }
283
284    /// Is to `append_all` what `write_all_vectored` is to `write_all`.
285    fn append_all_vectored(&self, mut bufs: &mut [IoSlice]) -> io::Result<()> {
286        while !bufs.is_empty() {
287            match self.append_vectored(bufs) {
288                Ok(nwritten) => {
289                    bufs = advance(bufs, nwritten);
290                }
291                Err(ref e) if e.kind() == io::ErrorKind::Interrupted => (),
292                Err(e) => return Err(e),
293            }
294        }
295        Ok(())
296    }
297
298    /// Determines if this `FileIoExt` implementation has an efficient
299    /// `append_vectored` implementation.
300    #[inline]
301    fn is_append_vectored(&self) -> bool {
302        false
303    }
304
305    /// Seek to an offset, in bytes, in a stream.
306    ///
307    /// This is similar to [`std::io::Seek::seek`], except it takes `self` by
308    /// immutable reference since the entire side effect is I/O.
309    ///
310    /// [`std::io::Seek::seek`]: https://doc.rust-lang.org/std/io/trait.Seek.html#tymethod.seek
311    fn seek(&self, pos: SeekFrom) -> io::Result<u64>;
312
313    /// Returns the current seek position from the start of the stream.
314    ///
315    /// This is similar to [`std::io::Seek::stream_position`], except it's
316    /// available on Rust stable.
317    ///
318    /// This may eventually be implemented by [rust-lang/rust#62726].
319    ///
320    /// [`std::io::Seek::stream_position`]: https://doc.rust-lang.org/std/io/trait.Seek.html#method.stream_position
321    /// [rust-lang/rust#62726]: https://github.com/rust-lang/rust/issues/59359.
322    fn stream_position(&self) -> io::Result<u64>;
323}
324
325/// Skip any leading elements in `bufs` which are empty buffers.
326fn skip_leading_empties<'a, 'b>(mut bufs: &'b mut [IoSliceMut<'a>]) -> &'b mut [IoSliceMut<'a>] {
327    while !bufs.is_empty() {
328        if !bufs[0].is_empty() {
329            break;
330        }
331        bufs = &mut bufs[1..];
332    }
333    bufs
334}
335
336/// This will be obviated by [rust-lang/rust#62726].
337///
338/// [rust-lang/rust#62726]: https://github.com/rust-lang/rust/issues/62726.
339fn advance<'a, 'b>(bufs: &'b mut [IoSlice<'a>], n: usize) -> &'b mut [IoSlice<'a>] {
340    // Number of buffers to remove.
341    let mut remove = 0;
342    // Total length of all the to be removed buffers.
343    let mut accumulated_len = 0;
344    for buf in bufs.iter() {
345        if accumulated_len + buf.len() > n {
346            break;
347        } else {
348            accumulated_len += buf.len();
349            remove += 1;
350        }
351    }
352
353    #[allow(clippy::indexing_slicing)]
354    let bufs = &mut bufs[remove..];
355    if let Some(first) = bufs.first_mut() {
356        let advance_by = n - accumulated_len;
357        let mut ptr = first.as_ptr();
358        let mut len = first.len();
359        unsafe {
360            ptr = ptr.add(advance_by);
361            len -= advance_by;
362            *first = IoSlice::<'a>::new(slice::from_raw_parts::<'a>(ptr, len));
363        }
364    }
365    bufs
366}
367
368/// This will be obviated by [rust-lang/rust#62726].
369///
370/// [rust-lang/rust#62726]: https://github.com/rust-lang/rust/issues/62726.
371fn advance_mut<'a, 'b>(bufs: &'b mut [IoSliceMut<'a>], n: usize) -> &'b mut [IoSliceMut<'a>] {
372    // Number of buffers to remove.
373    let mut remove = 0;
374    // Total length of all the to be removed buffers.
375    let mut accumulated_len = 0;
376    for buf in bufs.iter() {
377        if accumulated_len + buf.len() > n {
378            break;
379        } else {
380            accumulated_len += buf.len();
381            remove += 1;
382        }
383    }
384
385    #[allow(clippy::indexing_slicing)]
386    let bufs = &mut bufs[remove..];
387    if let Some(first) = bufs.first_mut() {
388        let advance_by = n - accumulated_len;
389        let mut ptr = first.as_mut_ptr();
390        let mut len = first.len();
391        unsafe {
392            ptr = ptr.add(advance_by);
393            len -= advance_by;
394            *first = IoSliceMut::<'a>::new(slice::from_raw_parts_mut::<'a>(ptr, len));
395        }
396    }
397    bufs
398}
399
400/// Implement `FileIoExt` for any type which implements `AsRawFd`.
401#[cfg(not(windows))]
402impl<T: AsFilelike + IoExt> FileIoExt for T {
403    #[cfg(not(any(
404        target_vendor = "apple",
405        target_os = "netbsd",
406        target_os = "openbsd",
407        target_os = "redox"
408    )))]
409    #[inline]
410    fn advise(&self, offset: u64, len: u64, advice: Advice) -> io::Result<()> {
411        let advice = match advice {
412            Advice::WillNeed => rustix::fs::Advice::WillNeed,
413            Advice::Normal => rustix::fs::Advice::Normal,
414            Advice::Sequential => rustix::fs::Advice::Sequential,
415            Advice::NoReuse => rustix::fs::Advice::NoReuse,
416            Advice::Random => rustix::fs::Advice::Random,
417            Advice::DontNeed => rustix::fs::Advice::DontNeed,
418        };
419        Ok(fadvise(self, offset, len, advice)?)
420    }
421
422    #[cfg(target_vendor = "apple")]
423    #[inline]
424    fn advise(&self, offset: u64, len: u64, advice: Advice) -> io::Result<()> {
425        // Darwin lacks `posix_fadvise`, but does have an `fcntl_rdadvise`
426        // feature which roughly corresponds to `WillNeed`. This is not yet
427        // tuned.
428        match advice {
429            Advice::WillNeed => (),
430            Advice::Normal
431            | Advice::Sequential
432            | Advice::NoReuse
433            | Advice::Random
434            | Advice::DontNeed => return Ok(()),
435        }
436
437        Ok(fcntl_rdadvise(self, offset, len)?)
438    }
439
440    #[cfg(any(target_os = "netbsd", target_os = "redox", target_os = "openbsd"))]
441    #[inline]
442    fn advise(&self, _offset: u64, _len: u64, _advice: Advice) -> io::Result<()> {
443        // Netbsd lacks `posix_fadvise` and doesn't have an obvious replacement,
444        // so just ignore the advice.
445        Ok(())
446    }
447
448    #[cfg(not(any(target_os = "netbsd", target_os = "redox", target_os = "openbsd")))]
449    #[inline]
450    fn allocate(&self, offset: u64, len: u64) -> io::Result<()> {
451        Ok(fallocate(self, FallocateFlags::empty(), offset, len)?)
452    }
453
454    #[cfg(target_os = "netbsd")]
455    fn allocate(&self, _offset: u64, _len: u64) -> io::Result<()> {
456        todo!("NetBSD 7.0 supports posix_fallocate; add bindings for it")
457    }
458
459    #[cfg(target_os = "openbsd")]
460    fn allocate(&self, _offset: u64, _len: u64) -> io::Result<()> {
461        todo!("OpenBSD does not support posix_fallocate; figure out what to do")
462    }
463
464    #[cfg(target_os = "redox")]
465    fn allocate(&self, _offset: u64, _len: u64) -> io::Result<()> {
466        todo!("figure out what to do on redox for posix_fallocate")
467    }
468
469    #[inline]
470    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
471        FileExt::read_at(&*self.as_filelike_view::<std::fs::File>(), buf, offset)
472    }
473
474    #[inline]
475    fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
476        FileExt::read_exact_at(&*self.as_filelike_view::<std::fs::File>(), buf, offset)
477    }
478
479    #[cfg(not(any(target_vendor = "apple", target_os = "redox")))]
480    #[inline]
481    fn read_vectored_at(&self, bufs: &mut [IoSliceMut], offset: u64) -> io::Result<usize> {
482        Ok(preadv(self, bufs, offset)?)
483    }
484
485    #[cfg(not(any(target_vendor = "apple", target_os = "redox")))]
486    #[inline]
487    fn is_read_vectored_at(&self) -> bool {
488        true
489    }
490
491    #[inline]
492    fn read_to_end_at(&self, buf: &mut Vec<u8>, offset: u64) -> io::Result<usize> {
493        read_to_end_at(&self.as_filelike_view::<std::fs::File>(), buf, offset)
494    }
495
496    #[inline]
497    fn read_to_string_at(&self, buf: &mut String, offset: u64) -> io::Result<usize> {
498        read_to_string_at(&self.as_filelike_view::<std::fs::File>(), buf, offset)
499    }
500
501    #[inline]
502    fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
503        FileExt::write_at(&*self.as_filelike_view::<std::fs::File>(), buf, offset)
504    }
505
506    #[inline]
507    fn write_all_at(&self, buf: &[u8], offset: u64) -> io::Result<()> {
508        FileExt::write_all_at(&*self.as_filelike_view::<std::fs::File>(), buf, offset)
509    }
510
511    #[cfg(not(any(target_vendor = "apple", target_os = "redox")))]
512    #[inline]
513    fn write_vectored_at(&self, bufs: &[IoSlice], offset: u64) -> io::Result<usize> {
514        Ok(pwritev(self, bufs, offset)?)
515    }
516
517    #[cfg(not(any(target_vendor = "apple", target_os = "redox")))]
518    #[inline]
519    fn is_write_vectored_at(&self) -> bool {
520        true
521    }
522
523    fn append(&self, buf: &[u8]) -> io::Result<usize> {
524        use rustix::fs::{fcntl_getfl, fcntl_setfl, seek, OFlags, SeekFrom};
525        use rustix::io::write;
526
527        // On Linux, use `pwritev2`.
528        #[cfg(any(target_os = "android", target_os = "linux"))]
529        {
530            use rustix::io::{pwritev2, Errno, ReadWriteFlags};
531
532            let iovs = [IoSlice::new(buf)];
533            match pwritev2(self, &iovs, 0, ReadWriteFlags::APPEND) {
534                Err(Errno::NOSYS) | Err(Errno::NOTSUP) => {}
535                otherwise => return Ok(otherwise?),
536            }
537        }
538
539        // Otherwise use `F_SETFL` to switch the file description to append
540        // mode, do the write, and switch back. This is not atomic with
541        // respect to other users of the file description, but this is
542        // possibility is documented in the trait.
543        //
544        // Optimization idea: some users don't care about the current position,
545        // changing, so perhaps we could add a `append_relaxed` etc. API which
546        // doesn't preserve positions.
547        let old_flags = fcntl_getfl(self)?;
548        let old_pos = tell(self)?;
549        fcntl_setfl(self, old_flags | OFlags::APPEND)?;
550        let result = write(self, buf);
551        fcntl_setfl(self, old_flags).unwrap();
552        seek(self, SeekFrom::Start(old_pos)).unwrap();
553        Ok(result?)
554    }
555
556    fn append_vectored(&self, bufs: &[IoSlice]) -> io::Result<usize> {
557        use rustix::fs::{fcntl_getfl, fcntl_setfl, seek, OFlags, SeekFrom};
558        use rustix::io::writev;
559
560        // On Linux, use `pwritev2`.
561        #[cfg(any(target_os = "android", target_os = "linux"))]
562        {
563            use rustix::io::{pwritev2, Errno, ReadWriteFlags};
564
565            match pwritev2(self, bufs, 0, ReadWriteFlags::APPEND) {
566                Err(Errno::NOSYS) | Err(Errno::NOTSUP) => {}
567                otherwise => return Ok(otherwise?),
568            }
569        }
570
571        // Otherwise use `F_SETFL` to switch the file description to append
572        // mode, do the write, and switch back. This is not atomic with
573        // respect to other users of the file description, but this is
574        // possibility is documented in the trait.
575        let old_flags = fcntl_getfl(self)?;
576        let old_pos = tell(self)?;
577        fcntl_setfl(self, old_flags | OFlags::APPEND)?;
578        let result = writev(self, bufs);
579        fcntl_setfl(self, old_flags).unwrap();
580        seek(self, SeekFrom::Start(old_pos)).unwrap();
581        Ok(result?)
582    }
583
584    #[inline]
585    fn is_append_vectored(&self) -> bool {
586        true
587    }
588
589    #[inline]
590    fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
591        Seek::seek(&mut &*self.as_filelike_view::<std::fs::File>(), pos)
592    }
593
594    #[inline]
595    fn stream_position(&self) -> io::Result<u64> {
596        // This may eventually be obsoleted by [rust-lang/rust#59359].
597        // [rust-lang/rust#59359]: https://github.com/rust-lang/rust/issues/59359.
598        Ok(tell(self)?)
599    }
600}
601
602#[cfg(windows)]
603impl FileIoExt for std::fs::File {
604    #[inline]
605    fn advise(&self, _offset: u64, _len: u64, _advice: Advice) -> io::Result<()> {
606        // TODO: Do something with the advice.
607        Ok(())
608    }
609
610    #[inline]
611    fn allocate(&self, _offset: u64, _len: u64) -> io::Result<()> {
612        // We can't faithfully support allocate on Windows without exposing race
613        // conditions. Instead, refuse:
614        Err(io::Error::new(
615            io::ErrorKind::PermissionDenied,
616            "file allocate is not supported on Windows",
617        ))
618    }
619
620    #[inline]
621    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
622        // Windows' `seek_read` modifies the current position in the file, so
623        // re-open the file to leave the original open file unmodified.
624        //
625        // Optimization idea: some users don't care about the current position,
626        // changing, so perhaps we could add a `read_at_relaxed` etc. API which
627        // doesn't do the `reopen`.
628        let reopened = reopen(self)?;
629        reopened.seek_read(buf, offset)
630    }
631
632    #[inline]
633    fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
634        // Similar to `read_at`, re-open the file so that we can do a seek and
635        // leave the original file unmodified.
636        let reopened = loop {
637            match reopen(self) {
638                Ok(file) => break file,
639                Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
640                Err(err) => return Err(err),
641            }
642        };
643        loop {
644            match reopened.seek(SeekFrom::Start(offset)) {
645                Ok(_) => break,
646                Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
647                Err(err) => return Err(err),
648            }
649        }
650        reopened.read_exact(buf)
651    }
652
653    #[inline]
654    fn read_vectored_at(&self, bufs: &mut [IoSliceMut], offset: u64) -> io::Result<usize> {
655        // Similar to `read_at`, re-open the file so that we can do a seek and
656        // leave the original file unmodified.
657        let reopened = reopen(self)?;
658        reopened.seek(SeekFrom::Start(offset))?;
659        reopened.read_vectored(bufs)
660    }
661
662    #[inline]
663    fn read_exact_vectored_at(&self, bufs: &mut [IoSliceMut], offset: u64) -> io::Result<()> {
664        // Similar to `read_vectored_at`, re-open the file so that we can do a seek and
665        // leave the original file unmodified.
666        let reopened = loop {
667            match reopen(self) {
668                Ok(file) => break file,
669                Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
670                Err(err) => return Err(err),
671            }
672        };
673        loop {
674            match reopened.seek(SeekFrom::Start(offset)) {
675                Ok(_) => break,
676                Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
677                Err(err) => return Err(err),
678            }
679        }
680        reopened.read_exact_vectored(bufs)
681    }
682
683    #[inline]
684    fn is_read_vectored_at(&self) -> bool {
685        true
686    }
687
688    #[inline]
689    fn read_to_end_at(&self, buf: &mut Vec<u8>, offset: u64) -> io::Result<usize> {
690        read_to_end_at(&self.as_filelike_view::<std::fs::File>(), buf, offset)
691    }
692
693    #[inline]
694    fn read_to_string_at(&self, buf: &mut String, offset: u64) -> io::Result<usize> {
695        read_to_string_at(&self.as_filelike_view::<std::fs::File>(), buf, offset)
696    }
697
698    #[inline]
699    fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
700        // Windows' `seek_write` modifies the current position in the file, so
701        // re-open the file to leave the original open file unmodified.
702        reopen_write(self)?.seek_write(buf, offset)
703    }
704
705    #[inline]
706    fn write_all_at(&self, mut buf: &[u8], mut offset: u64) -> io::Result<()> {
707        // Similar to `read_exact_at`, re-open the file so that we can do a seek
708        // and leave the original file unmodified.
709        let reopened = reopen_write(self)?;
710        while buf.len() > 0 {
711            let n = reopened.seek_write(buf, offset)?;
712            offset += u64::try_from(n).unwrap();
713            buf = &buf[n..];
714        }
715        Ok(())
716    }
717
718    #[inline]
719    fn write_vectored_at(&self, bufs: &[IoSlice], offset: u64) -> io::Result<usize> {
720        // Windows doesn't have a vectored write for files, so pick the first
721        // non-empty slice and write that.
722        match bufs.iter().find(|p| p.len() > 0) {
723            Some(buf) => self.write_at(buf, offset),
724            None => Ok(0),
725        }
726    }
727
728    #[inline]
729    fn write_all_vectored_at(&self, bufs: &mut [IoSlice], mut offset: u64) -> io::Result<()> {
730        for buf in bufs {
731            self.write_all_at(buf, offset)?;
732            offset += u64::try_from(buf.len()).unwrap();
733        }
734        Ok(())
735    }
736
737    #[inline]
738    fn is_write_vectored_at(&self) -> bool {
739        true
740    }
741
742    fn append(&self, buf: &[u8]) -> io::Result<usize> {
743        // Re-open the file for appending.
744        let reopened = reopen_append(self)?;
745        reopened.write(buf)
746    }
747
748    fn append_vectored(&self, bufs: &[IoSlice]) -> io::Result<usize> {
749        // Re-open the file for appending.
750        let reopened = reopen_append(self)?;
751        reopened.write_vectored(bufs)
752    }
753
754    #[inline]
755    fn is_append_vectored(&self) -> bool {
756        true
757    }
758
759    #[inline]
760    fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
761        Seek::seek(&mut &*self.as_filelike_view::<std::fs::File>(), pos)
762    }
763
764    #[inline]
765    fn stream_position(&self) -> io::Result<u64> {
766        // This may eventually be obsoleted by [rust-lang/rust#59359].
767        // [rust-lang/rust#59359]: https://github.com/rust-lang/rust/issues/59359.
768        Seek::seek(
769            &mut &*self.as_filelike_view::<std::fs::File>(),
770            SeekFrom::Current(0),
771        )
772    }
773}
774
775#[cfg(windows)]
776#[cfg(feature = "cap_std_impls")]
777impl FileIoExt for cap_std::fs::File {
778    #[inline]
779    fn advise(&self, offset: u64, len: u64, advice: Advice) -> io::Result<()> {
780        self.as_filelike_view::<std::fs::File>()
781            .advise(offset, len, advice)
782    }
783
784    #[inline]
785    fn allocate(&self, offset: u64, len: u64) -> io::Result<()> {
786        self.as_filelike_view::<std::fs::File>()
787            .allocate(offset, len)
788    }
789
790    #[inline]
791    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
792        self.as_filelike_view::<std::fs::File>()
793            .read_at(buf, offset)
794    }
795
796    #[inline]
797    fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
798        self.as_filelike_view::<std::fs::File>()
799            .read_exact_at(buf, offset)
800    }
801
802    #[inline]
803    fn read_vectored_at(&self, bufs: &mut [IoSliceMut], offset: u64) -> io::Result<usize> {
804        self.as_filelike_view::<std::fs::File>()
805            .read_vectored_at(bufs, offset)
806    }
807
808    #[inline]
809    fn read_exact_vectored_at(&self, bufs: &mut [IoSliceMut], offset: u64) -> io::Result<()> {
810        self.as_filelike_view::<std::fs::File>()
811            .read_exact_vectored_at(bufs, offset)
812    }
813
814    #[inline]
815    fn is_read_vectored_at(&self) -> bool {
816        self.as_filelike_view::<std::fs::File>()
817            .is_read_vectored_at()
818    }
819
820    #[inline]
821    fn read_to_end_at(&self, buf: &mut Vec<u8>, offset: u64) -> io::Result<usize> {
822        self.as_filelike_view::<std::fs::File>()
823            .read_to_end_at(buf, offset)
824    }
825
826    #[inline]
827    fn read_to_string_at(&self, buf: &mut String, offset: u64) -> io::Result<usize> {
828        self.as_filelike_view::<std::fs::File>()
829            .read_to_string_at(buf, offset)
830    }
831
832    #[inline]
833    fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
834        self.as_filelike_view::<std::fs::File>()
835            .write_at(buf, offset)
836    }
837
838    #[inline]
839    fn write_all_at(&self, buf: &[u8], offset: u64) -> io::Result<()> {
840        self.as_filelike_view::<std::fs::File>()
841            .write_all_at(buf, offset)
842    }
843
844    #[inline]
845    fn write_vectored_at(&self, bufs: &[IoSlice], offset: u64) -> io::Result<usize> {
846        self.as_filelike_view::<std::fs::File>()
847            .write_vectored_at(bufs, offset)
848    }
849
850    #[inline]
851    fn write_all_vectored_at(&self, bufs: &mut [IoSlice], offset: u64) -> io::Result<()> {
852        self.as_filelike_view::<std::fs::File>()
853            .write_all_vectored_at(bufs, offset)
854    }
855
856    #[inline]
857    fn is_write_vectored_at(&self) -> bool {
858        self.as_filelike_view::<std::fs::File>()
859            .is_write_vectored_at()
860    }
861
862    fn append(&self, buf: &[u8]) -> io::Result<usize> {
863        self.as_filelike_view::<std::fs::File>().append(buf)
864    }
865
866    fn append_vectored(&self, bufs: &[IoSlice]) -> io::Result<usize> {
867        self.as_filelike_view::<std::fs::File>()
868            .append_vectored(bufs)
869    }
870
871    #[inline]
872    fn is_append_vectored(&self) -> bool {
873        true
874    }
875
876    #[inline]
877    fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
878        self.as_filelike_view::<std::fs::File>().seek(pos)
879    }
880
881    #[inline]
882    fn stream_position(&self) -> io::Result<u64> {
883        self.as_filelike_view::<std::fs::File>().stream_position()
884    }
885}
886
887#[cfg(windows)]
888#[cfg(feature = "cap_std_impls_fs_utf8")]
889impl FileIoExt for cap_std::fs_utf8::File {
890    #[inline]
891    fn advise(&self, offset: u64, len: u64, advice: Advice) -> io::Result<()> {
892        self.as_filelike_view::<std::fs::File>()
893            .advise(offset, len, advice)
894    }
895
896    #[inline]
897    fn allocate(&self, offset: u64, len: u64) -> io::Result<()> {
898        self.as_filelike_view::<std::fs::File>()
899            .allocate(offset, len)
900    }
901
902    #[inline]
903    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
904        self.as_filelike_view::<std::fs::File>()
905            .read_at(buf, offset)
906    }
907
908    #[inline]
909    fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
910        self.as_filelike_view::<std::fs::File>()
911            .read_exact_at(buf, offset)
912    }
913
914    #[inline]
915    fn read_vectored_at(&self, bufs: &mut [IoSliceMut], offset: u64) -> io::Result<usize> {
916        self.as_filelike_view::<std::fs::File>()
917            .read_vectored_at(bufs, offset)
918    }
919
920    #[inline]
921    fn read_exact_vectored_at(&self, bufs: &mut [IoSliceMut], offset: u64) -> io::Result<()> {
922        self.as_filelike_view::<std::fs::File>()
923            .read_exact_vectored_at(bufs, offset)
924    }
925
926    #[inline]
927    fn is_read_vectored_at(&self) -> bool {
928        self.as_filelike_view::<std::fs::File>()
929            .is_read_vectored_at()
930    }
931
932    #[inline]
933    fn read_to_end_at(&self, buf: &mut Vec<u8>, offset: u64) -> io::Result<usize> {
934        self.as_filelike_view::<std::fs::File>()
935            .read_to_end_at(buf, offset)
936    }
937
938    #[inline]
939    fn read_to_string_at(&self, buf: &mut String, offset: u64) -> io::Result<usize> {
940        self.as_filelike_view::<std::fs::File>()
941            .read_to_string_at(buf, offset)
942    }
943
944    #[inline]
945    fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
946        self.as_filelike_view::<std::fs::File>()
947            .write_at(buf, offset)
948    }
949
950    #[inline]
951    fn write_all_at(&self, buf: &[u8], offset: u64) -> io::Result<()> {
952        self.as_filelike_view::<std::fs::File>()
953            .write_all_at(buf, offset)
954    }
955
956    #[inline]
957    fn write_vectored_at(&self, bufs: &[IoSlice], offset: u64) -> io::Result<usize> {
958        self.as_filelike_view::<std::fs::File>()
959            .write_vectored_at(bufs, offset)
960    }
961
962    #[inline]
963    fn write_all_vectored_at(&self, bufs: &mut [IoSlice], offset: u64) -> io::Result<()> {
964        self.as_filelike_view::<std::fs::File>()
965            .write_all_vectored_at(bufs, offset)
966    }
967
968    #[inline]
969    fn is_write_vectored_at(&self) -> bool {
970        self.as_filelike_view::<std::fs::File>()
971            .is_write_vectored_at()
972    }
973
974    fn append(&self, buf: &[u8]) -> io::Result<usize> {
975        self.as_filelike_view::<std::fs::File>().append(buf)
976    }
977
978    fn append_vectored(&self, bufs: &[IoSlice]) -> io::Result<usize> {
979        self.as_filelike_view::<std::fs::File>()
980            .append_vectored(bufs)
981    }
982
983    #[inline]
984    fn is_append_vectored(&self) -> bool {
985        true
986    }
987
988    #[inline]
989    fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
990        self.as_filelike_view::<std::fs::File>().seek(pos)
991    }
992
993    #[inline]
994    fn stream_position(&self) -> io::Result<u64> {
995        self.as_filelike_view::<std::fs::File>().stream_position()
996    }
997}
998
999#[cfg(windows)]
1000#[inline]
1001fn reopen<Filelike: AsFilelike>(filelike: &Filelike) -> io::Result<fs::File> {
1002    let file = filelike.as_filelike_view::<std::fs::File>();
1003    unsafe { _reopen(&file) }
1004}
1005
1006#[cfg(windows)]
1007unsafe fn _reopen(file: &fs::File) -> io::Result<fs::File> {
1008    file.reopen(cap_fs_ext::OpenOptions::new().read(true))
1009}
1010
1011#[cfg(windows)]
1012#[inline]
1013fn reopen_write<Filelike: AsFilelike>(filelike: &Filelike) -> io::Result<fs::File> {
1014    let file = filelike.as_filelike_view::<std::fs::File>();
1015    unsafe { _reopen_write(&file) }
1016}
1017
1018#[cfg(windows)]
1019unsafe fn _reopen_write(file: &fs::File) -> io::Result<fs::File> {
1020    file.reopen(cap_fs_ext::OpenOptions::new().write(true))
1021}
1022
1023#[cfg(windows)]
1024#[inline]
1025fn reopen_append<Filelike: AsFilelike>(filelike: &Filelike) -> io::Result<fs::File> {
1026    let file = filelike.as_filelike_view::<std::fs::File>();
1027    unsafe { _reopen_append(&file) }
1028}
1029
1030#[cfg(windows)]
1031unsafe fn _reopen_append(file: &fs::File) -> io::Result<fs::File> {
1032    file.reopen(cap_fs_ext::OpenOptions::new().append(true))
1033}
1034
1035fn read_to_end_at(file: &std::fs::File, buf: &mut Vec<u8>, offset: u64) -> io::Result<usize> {
1036    let len = match file.metadata()?.len().checked_sub(offset) {
1037        None => return Ok(0),
1038        Some(len) => len,
1039    };
1040
1041    // This initializes the buffer with zeros which is theoretically
1042    // unnecessary, but current alternatives involve tricky `unsafe` code.
1043    buf.resize(
1044        (buf.len() as u64)
1045            .saturating_add(len)
1046            .try_into()
1047            .unwrap_or(usize::MAX),
1048        0_u8,
1049    );
1050    FileIoExt::read_exact_at(file, buf, offset)?;
1051    Ok(len as usize)
1052}
1053
1054fn read_to_string_at(file: &std::fs::File, buf: &mut String, offset: u64) -> io::Result<usize> {
1055    let len = match file.metadata()?.len().checked_sub(offset) {
1056        None => return Ok(0),
1057        Some(len) => len,
1058    };
1059
1060    // This temporary buffer is theoretically unnecessary, but eliminating it
1061    // currently involves a bunch of `unsafe`.
1062    let mut tmp = vec![0_u8; len.try_into().unwrap_or(usize::MAX)];
1063    FileIoExt::read_exact_at(file, &mut tmp, offset)?;
1064    let s = String::from_utf8(tmp).map_err(|_| {
1065        io::Error::new(
1066            io::ErrorKind::InvalidData,
1067            "stream did not contain valid UTF-8",
1068        )
1069    })?;
1070    buf.push_str(&s);
1071    Ok(len as usize)
1072}
1073
1074fn _file_io_ext_can_be_trait_object(_: &dyn FileIoExt) {}