use crate::file_io::sys::cvt;
use crate::file_io::sys_common::AsInner;
use crate::io::{self, Initializer, Read};
use core::cmp;
use core::mem;
use core::sync::atomic::{AtomicBool, Ordering};
use crate::libc;
use alloc::vec::Vec;
use libc::{c_int, c_void, ssize_t};
#[derive(Debug)]
pub struct FileDesc {
fd: c_int,
}
fn max_len() -> usize {
if cfg!(target_os = "macos") {
<c_int>::max_value() as usize - 1
} else {
<ssize_t>::max_value() as usize
}
}
impl FileDesc {
pub fn new(fd: c_int) -> FileDesc {
FileDesc { fd }
}
pub fn raw(&self) -> c_int {
self.fd
}
pub fn into_raw(self) -> c_int {
let fd = self.fd;
mem::forget(self);
fd
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
let ret = cvt(unsafe {
libc::read(
self.fd,
buf.as_mut_ptr() as *mut c_void,
cmp::min(buf.len(), max_len()),
)
})?;
Ok(ret as usize)
}
pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
let mut me = self;
(&mut me).read_to_end(buf)
}
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
let ret = cvt(unsafe {
libc::write(
self.fd,
buf.as_ptr() as *const c_void,
cmp::min(buf.len(), max_len()),
)
})?;
Ok(ret as usize)
}
pub fn set_cloexec(&self) -> io::Result<()> {
unsafe {
let previous = cvt(libc::fcntl(self.fd, libc::F_GETFD))?;
let new = previous | libc::FD_CLOEXEC;
if new != previous {
cvt(libc::fcntl(self.fd, libc::F_SETFD, new))?;
}
Ok(())
}
}
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
unsafe {
let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?;
let new = if nonblocking {
previous | libc::O_NONBLOCK
} else {
previous & !libc::O_NONBLOCK
};
if new != previous {
cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?;
}
Ok(())
}
}
pub fn duplicate(&self) -> io::Result<FileDesc> {
use libc::F_DUPFD as F_DUPFD_CLOEXEC;
let make_filedesc = |fd| {
let fd = FileDesc::new(fd);
fd.set_cloexec()?;
Ok(fd)
};
static TRY_CLOEXEC: AtomicBool = AtomicBool::new(!cfg!(target_os = "android"));
let fd = self.raw();
if TRY_CLOEXEC.load(Ordering::Relaxed) {
match cvt(unsafe { libc::fcntl(fd, F_DUPFD_CLOEXEC, 0) }) {
Ok(fd) => {
return Ok(if cfg!(target_os = "linux") {
make_filedesc(fd)?
} else {
FileDesc::new(fd)
})
}
Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {
TRY_CLOEXEC.store(false, Ordering::Relaxed);
}
Err(e) => return Err(e),
}
}
cvt(unsafe { libc::fcntl(fd, libc::F_DUPFD, 0) }).and_then(make_filedesc)
}
}
impl<'a> Read for &'a FileDesc {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
(**self).read(buf)
}
#[inline]
unsafe fn initializer(&self) -> Initializer {
Initializer::nop()
}
}
impl AsInner<c_int> for FileDesc {
fn as_inner(&self) -> &c_int {
&self.fd
}
}
impl Drop for FileDesc {
fn drop(&mut self) {
let _ = unsafe { libc::close(self.fd) };
}
}