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
//! A module implementing an io type backed by the C runtime's file descriptors, i.e. what's
//! returned from libc::open, even on windows.

use std::{cmp, ffi, io};

#[cfg(windows)]
use libc::commit as fsync;
#[cfg(windows)]
extern "C" {
    #[link_name = "_chsize_s"]
    fn ftruncate(fd: i32, len: i64) -> i32;
}
#[cfg(not(windows))]
use libc::{fsync, ftruncate};

// this is basically what CPython has for Py_off_t; windows uses long long
// for offsets, other platforms just use off_t
#[cfg(not(windows))]
pub type Offset = libc::off_t;
#[cfg(windows)]
pub type Offset = libc::c_longlong;

#[inline]
fn cvt<T, I: num_traits::PrimInt>(ret: I, f: impl FnOnce(I) -> T) -> io::Result<T> {
    if ret < I::zero() {
        Err(crate::os::errno())
    } else {
        Ok(f(ret))
    }
}

const MAX_RW: usize = if cfg!(any(windows, target_vendor = "apple")) {
    i32::MAX as usize
} else {
    isize::MAX as usize
};

#[derive(Copy, Clone, PartialEq, Eq)]
#[repr(transparent)]
pub struct Fd(pub i32);

impl Fd {
    pub fn open(path: &ffi::CStr, flags: i32, mode: i32) -> io::Result<Self> {
        cvt(unsafe { libc::open(path.as_ptr(), flags, mode) }, Fd)
    }

    #[cfg(windows)]
    pub fn wopen(path: &widestring::WideCStr, flags: i32, mode: i32) -> io::Result<Self> {
        cvt(
            unsafe { suppress_iph!(libc::wopen(path.as_ptr(), flags, mode)) },
            Fd,
        )
    }

    #[cfg(all(any(unix, target_os = "wasi"), not(target_os = "redox")))]
    pub fn openat(&self, path: &ffi::CStr, flags: i32, mode: i32) -> io::Result<Self> {
        cvt(
            unsafe { libc::openat(self.0, path.as_ptr(), flags, mode) },
            Fd,
        )
    }

    pub fn fsync(&self) -> io::Result<()> {
        cvt(unsafe { suppress_iph!(fsync(self.0)) }, drop)
    }

    pub fn close(&self) -> io::Result<()> {
        cvt(unsafe { suppress_iph!(libc::close(self.0)) }, drop)
    }

    pub fn ftruncate(&self, len: Offset) -> io::Result<()> {
        cvt(unsafe { suppress_iph!(ftruncate(self.0, len)) }, drop)
    }

    #[cfg(windows)]
    pub fn to_raw_handle(&self) -> io::Result<std::os::windows::io::RawHandle> {
        extern "C" {
            fn _get_osfhandle(fd: i32) -> libc::intptr_t;
        }
        let handle = unsafe { suppress_iph!(_get_osfhandle(self.0)) };
        if handle == -1 {
            Err(io::Error::last_os_error())
        } else {
            Ok(handle as _)
        }
    }
}

impl io::Write for &Fd {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let count = cmp::min(buf.len(), MAX_RW);
        cvt(
            unsafe { suppress_iph!(libc::write(self.0, buf.as_ptr() as _, count as _)) },
            |i| i as usize,
        )
    }

    #[inline]
    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

impl io::Write for Fd {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        (&*self).write(buf)
    }

    #[inline]
    fn flush(&mut self) -> io::Result<()> {
        (&*self).flush()
    }
}

impl io::Read for &Fd {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let count = cmp::min(buf.len(), MAX_RW);
        cvt(
            unsafe { suppress_iph!(libc::read(self.0, buf.as_mut_ptr() as _, count as _)) },
            |i| i as usize,
        )
    }
}

impl io::Read for Fd {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        (&*self).read(buf)
    }
}