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
use std::{
    io::{self, BufReader},
    path::PathBuf,
    process::{ChildStderr, ChildStdout},
    rc::Rc,
};

use mio::{event::Source, unix::pipe, Interest, Token};

use crate::Pid;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FdTag {
    Stderr,
    Stdout,
}

#[derive(Debug)]
pub struct ChildOut {
    pub pid: Pid,
    pub prog_path: Rc<PathBuf>,
    pub tag: FdTag,
    pub buf: String,
    pub fd: BufReader<pipe::Receiver>,
}

impl ChildOut {
    pub(crate) fn from_pipe<T: Into<pipe::Receiver> + TaggedFd>(
        value: T,
        pid: Pid,
        prog_path: Rc<PathBuf>,
    ) -> Self {
        let pipe: pipe::Receiver = value.into();
        pipe.set_nonblocking(true)
            .expect("setting nonblocking to succeed");
        ChildOut {
            pid,
            prog_path,
            tag: T::fdtag(),
            buf: String::with_capacity(1024),
            fd: BufReader::with_capacity(8192, pipe),
        }
    }
}

impl Source for ChildOut {
    fn register(
        &mut self,
        registry: &mio::Registry,
        token: Token,
        interests: Interest,
    ) -> io::Result<()> {
        self.fd.get_mut().register(registry, token, interests)
    }

    fn reregister(
        &mut self,
        registry: &mio::Registry,
        token: Token,
        interests: Interest,
    ) -> io::Result<()> {
        self.fd.get_mut().reregister(registry, token, interests)
    }

    fn deregister(&mut self, registry: &mio::Registry) -> io::Result<()> {
        self.fd.get_mut().deregister(registry)
    }
}

pub(crate) trait TaggedFd {
    fn fdtag() -> FdTag;
}

impl TaggedFd for ChildStdout {
    fn fdtag() -> FdTag {
        FdTag::Stdout
    }
}

impl TaggedFd for ChildStderr {
    fn fdtag() -> FdTag {
        FdTag::Stderr
    }
}