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
mod common;
mod sendfile;
mod splice;
mod tee;

use std::{ io, slice };
use std::marker::PhantomData;
use std::os::unix::io::{ AsRawFd, RawFd };
use nix::unistd;
use nix::sys::uio;
use nix::fcntl::{ fcntl, vmsplice, FcntlArg, OFlag, SpliceFFlags };
use tokio::prelude::*;
use tokio::io::{ AsyncRead, AsyncWrite };
use bytes::Buf;
use iovec::IoVec;
use crate::common::io_err;
pub use crate::sendfile::*;
pub use crate::splice::*;
pub use crate::tee::*;


#[derive(Debug)]
pub enum R {}

#[derive(Debug)]
pub enum W {}

#[derive(Debug)]
pub struct Pipe<T>(pub RawFd, PhantomData<T>);

pub fn pipe() -> io::Result<(Pipe<R>, Pipe<W>)> {
    let (pr, pw) = unistd::pipe().map_err(io_err)?;
    Ok((Pipe(pr, PhantomData), Pipe(pw, PhantomData)))
}

impl<T> Pipe<T> {
    pub fn set_nonblocking(&self, flag: bool) -> io::Result<()> {
        let mut oflag = fcntl(self.0, FcntlArg::F_GETFL)
            .map(OFlag::from_bits_truncate)
            .map_err(io_err)?;

        if flag {
            oflag.insert(OFlag::O_NONBLOCK);
        } else {
            oflag.remove(OFlag::O_NONBLOCK);
        }

        fcntl(self.0, FcntlArg::F_SETFL(oflag))
            .map(drop)
            .map_err(io_err)
    }
}

macro_rules! try_async {
    ( $e:expr ) => {
        match $e {
            Ok(n) => Ok(Async::Ready(n)),
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock =>
                Ok(Async::NotReady),
            Err(e) => Err(e)
        }
    }
}

impl io::Read for Pipe<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        unistd::read(self.0, buf).map_err(io_err)
    }
}

impl io::Write for Pipe<W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        unistd::write(self.0, buf).map_err(io_err)
    }

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

impl AsyncRead for Pipe<R> {
    unsafe fn prepare_uninitialized_buffer(&self, _: &mut [u8]) -> bool {
        false
    }
}

impl AsyncWrite for Pipe<W> {
    fn write_buf<B: Buf>(&mut self, buf: &mut B) -> Poll<usize, io::Error> {
        static DUMMY: &[u8] = &[0];
        let iovec = <&IoVec>::from(DUMMY);
        let mut bufs = [iovec; 64];
        let n = buf.bytes_vec(&mut bufs);
        let bufs = unsafe {
            slice::from_raw_parts(
                bufs[..n].as_ptr() as *const uio::IoVec<&[u8]>,
                n
            )
        };

        try_async!(vmsplice(self.0, bufs, SpliceFFlags::SPLICE_F_NONBLOCK)
            .map_err(io_err))
    }

    fn shutdown(&mut self) -> Poll<(), io::Error> {
        try_async!(unistd::close(self.0).map_err(io_err))
    }
}

impl<T> AsRawFd for Pipe<T> {
    fn as_raw_fd(&self) -> RawFd {
        self.0
    }
}

impl<T> Drop for Pipe<T> {
    fn drop(&mut self) {
        let _ = unistd::close(self.0);
    }
}