#![cfg(unix)]
extern crate libc;
use libc::{F_GETFL, F_SETFL, O_APPEND, c_int, fcntl};
use std::io;
use std::os::unix::io::{AsRawFd, IntoRawFd, RawFd};
mod pipe;
mod splice;
pub use splice::splice_loop;
pub use pipe::Pipe;
#[derive(Debug)]
pub struct FileDesc {
fd: RawFd,
close_on_drop: bool,
}
impl FileDesc {
pub fn new(fd: RawFd, close_on_drop: bool) -> FileDesc {
FileDesc {
fd: fd,
close_on_drop: close_on_drop,
}
}
pub fn dup(&self) -> io::Result<FileDesc> {
Ok(FileDesc {
fd: match unsafe { ::libc::dup(self.fd) } {
-1 => return Err(io::Error::last_os_error()),
n => n,
},
close_on_drop: self.close_on_drop,
})
}
}
impl Drop for FileDesc {
fn drop(&mut self) {
if self.close_on_drop {
unsafe { ::libc::close(self.fd); }
}
}
}
impl AsRawFd for FileDesc {
fn as_raw_fd(&self) -> RawFd {
self.fd
}
}
impl IntoRawFd for FileDesc {
fn into_raw_fd(mut self) -> RawFd {
self.close_on_drop = false;
self.fd
}
}
pub fn unset_append_flag(fd: RawFd) -> io::Result<Option<c_int>> {
let status = unsafe { fcntl(fd, F_GETFL) };
if status == -1 {
return Err(io::Error::last_os_error());
}
if status & O_APPEND == 0 {
return Ok(None);
}
try!(set_flags(fd, status & !O_APPEND));
Ok(Some(status))
}
pub fn set_flags(fd: RawFd, status: c_int) -> io::Result<()> {
let ret = unsafe { fcntl(fd, F_SETFL, status) };
if ret == -1 {
return Err(io::Error::last_os_error());
}
Ok(())
}