Skip to main content

torrust_tracker_deployer_lib/presentation/cli/views/sinks/
standard.rs

1//! Standard output sink implementation
2
3use std::io::Write;
4
5use super::super::{Channel, OutputMessage, OutputSink};
6use super::writers::{StderrWriter, StdoutWriter};
7
8// ============================================================================
9// Output Sink Implementations
10// ============================================================================
11
12/// Standard sink writing to stdout/stderr
13///
14/// This is the default sink that maintains backward compatibility with the
15/// existing console output behavior. It routes messages to stdout or stderr
16/// based on the message's channel.
17///
18/// # Type Safety
19///
20/// Uses `StdoutWriter` and `StderrWriter` wrappers for compile-time channel safety.
21///
22/// # Examples
23///
24/// ```rust,ignore
25/// use torrust_tracker_deployer_lib::presentation::cli::views::StandardSink;
26///
27/// let sink = StandardSink::new(
28///     Box::new(std::io::stdout()),
29///     Box::new(std::io::stderr())
30/// );
31/// ```
32pub struct StandardSink {
33    stdout: StdoutWriter,
34    stderr: StderrWriter,
35}
36
37impl StandardSink {
38    /// Create a new standard sink with the given writers
39    ///
40    /// This is useful for testing or when you need custom writers.
41    #[must_use]
42    pub fn new(stdout: Box<dyn Write + Send + Sync>, stderr: Box<dyn Write + Send + Sync>) -> Self {
43        Self {
44            stdout: StdoutWriter::new(stdout),
45            stderr: StderrWriter::new(stderr),
46        }
47    }
48
49    /// Create a standard sink using default stdout/stderr
50    ///
51    /// This is the default console sink that writes to the standard
52    /// output and error streams.
53    #[must_use]
54    pub fn default_console() -> Self {
55        Self::new(Box::new(std::io::stdout()), Box::new(std::io::stderr()))
56    }
57}
58
59impl OutputSink for StandardSink {
60    fn write_message(&mut self, message: &dyn OutputMessage, formatted: &str) {
61        match message.channel() {
62            Channel::Stdout => {
63                self.stdout.write_line(formatted);
64            }
65            Channel::Stderr => {
66                self.stderr.write_line(formatted);
67            }
68        }
69    }
70}