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
use crate::element::*;
use crate::error::Error;
use common::{MsgReceiver, MsgType, Pipeline};
use serde::Deserialize;
use std::io::{BufWriter, Write};

/// Emits received message to stdout.
pub struct StdoutSinkElement {
    stdout: BufWriter<std::io::Stdout>,
    conf: StdoutSinkElementConf,
}

/// Configuration type for `StdoutSinkElement`
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StdoutSinkElementConf {
    /// Separator text.
    pub separator: Option<String>,
    /// Buffer flush size.
    #[serde(default)]
    pub flush_size: usize,
}

impl ElementBuildable for StdoutSinkElement {
    type Config = StdoutSinkElementConf;

    const NAME: &'static str = "stdout-sink";

    const RECV_PORTS: Port = 1;

    fn acceptable_msg_types() -> Vec<Vec<MsgType>> {
        vec![vec![MsgType::any()]]
    }

    fn new(conf: Self::Config) -> Result<Self, Error> {
        Ok(StdoutSinkElement {
            conf,
            stdout: BufWriter::new(std::io::stdout()),
        })
    }

    fn next(&mut self, _pipeline: &mut Pipeline, receiver: &mut MsgReceiver) -> ElementResult {
        loop {
            let msg = receiver.recv(0)?;
            let bytes = msg.as_bytes();
            self.stdout.write_all(bytes)?;

            if let Some(separator) = self.conf.separator.as_ref() {
                self.stdout.write_all(separator.as_bytes())?;
            }

            if self.conf.flush_size == 0 || self.stdout.buffer().len() > self.conf.flush_size {
                self.stdout.flush()?;
            }
        }
    }
}