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
use std::io::Write;
use std::thread::JoinHandle;
use std::{io, thread};

use crossbeam_channel::{bounded, RecvError, Sender};
use thiserror::Error as ThisError;

use crate::util::buf::constants::BUF_COUNT;

pub type ConsumerResult<T> = Result<T, ConsumerError>;

#[derive(ThisError, Debug)]
pub enum ConsumerError {
    #[error(transparent)]
    Io(#[from] io::Error),
    #[error(transparent)]
    Recv(#[from] RecvError),
}

pub enum Command {
    Write(Vec<u8>),
    Flush,
    Drop,
}

pub fn spawn_consumer<W: 'static + Write + Send>(
    mut writer: W,
) -> (JoinHandle<ConsumerResult<()>>, Sender<Command>) {
    let (sender, receiver) = bounded::<Command>(BUF_COUNT);

    let handle = thread::spawn(move || {
        while let Ok(command) = receiver.recv() {
            match command {
                Command::Write(buf) => writer.write_all(buf.as_ref())?,
                Command::Flush => writer.flush()?,
                Command::Drop => break,
            }
        }
        writer.flush()?;
        Ok(())
    });

    (handle, sender)
}