protoflow_blocks/blocks/sys/
write_stderr.rs1extern crate std;
4
5use crate::{prelude::Bytes, StdioConfig, StdioError, StdioSystem, System};
6use protoflow_core::{Block, BlockResult, BlockRuntime, InputPort};
7use protoflow_derive::Block;
8use simple_mermaid::mermaid;
9
10#[doc = mermaid!("../../../doc/sys/write_stderr.mmd")]
14#[doc = mermaid!("../../../doc/sys/write_stderr.seq.mmd" framed)]
17#[derive(Block, Clone)]
40pub struct WriteStderr {
41 #[input]
43 pub input: InputPort<Bytes>,
44}
45
46impl WriteStderr {
47 pub fn new(input: InputPort<Bytes>) -> Self {
48 Self { input }
49 }
50
51 pub fn with_system(system: &System) -> Self {
52 use crate::SystemBuilding;
53 Self::new(system.input())
54 }
55}
56
57impl Block for WriteStderr {
58 fn execute(&mut self, runtime: &dyn BlockRuntime) -> BlockResult {
59 let mut stderr = std::io::stderr().lock();
60
61 runtime.wait_for(&self.input)?;
62
63 while let Some(message) = self.input.recv()? {
64 std::io::Write::write_all(&mut stderr, &message)?;
65 }
66
67 self.input.close()?;
68 Ok(())
69 }
70}
71
72#[cfg(feature = "std")]
73impl StdioSystem for WriteStderr {
74 fn build_system(config: StdioConfig) -> Result<System, StdioError> {
75 use crate::SystemBuilding;
76
77 config.reject_any()?;
78
79 Ok(System::build(|s| {
80 let stdin = config.read_stdin(s);
81 let stderr = config.write_stderr(s);
82 s.connect(&stdin.output, &stderr.input);
83 }))
84 }
85}
86
87#[cfg(test)]
88mod tests {
89 use super::WriteStderr;
90 use crate::{System, SystemBuilding};
91
92 #[test]
93 fn instantiate_block() {
94 let _ = System::build(|s| {
96 let _ = s.block(WriteStderr::new(s.input()));
97 });
98 }
99}