pub struct CliMessageChannel { /* private fields */ }Expand description
A command-line message channel: prints messages to the terminal and reads one line from stdin as the reply.
Binds to standard input / standard output by default; alternatively, inject custom read/write sources
with CliMessageChannel::with_io (files, network, in-memory buffers — common in tests).
Messages travel line by line: each message gets its own line on output (a newline is appended
automatically); ask reads one line from the input, trims leading and trailing whitespace,
and returns it as the reply.
All operations are serialized through an internal mutex: ask presents only one request at a time,
and other ask / notify calls queue while it waits for the reply; input is read asynchronously,
yielding while waiting, so other tasks are not blocked on a single-threaded runtime.
§Example
use molo::{CliMessageChannel, MessageChannel};
use tokio::io::{AsyncWriteExt, BufReader};
// Inject in-memory read/write sources instead of touching a real terminal.
let (mut seed, rx) = tokio::io::duplex(64);
seed.write_all("yes\n".as_bytes()).await?;
let channel = CliMessageChannel::with_io(
Box::new(BufReader::new(rx)),
Box::new(tokio::io::sink()),
);
let answer = channel.ask("continue? [y/n]").await?;
assert_eq!(answer, "yes");§Notes
- when input reaches end-of-file (Ctrl-D / EOF),
askreturnsChannelError::Closed; - replies are read line by line and trimmed: an empty line still counts as a valid reply (an empty string).
Implementations§
Source§impl CliMessageChannel
impl CliMessageChannel
Sourcepub fn with_io(
reader: Box<dyn AsyncBufRead + Unpin + Send>,
writer: Box<dyn AsyncWrite + Unpin + Send>,
) -> Self
pub fn with_io( reader: Box<dyn AsyncBufRead + Unpin + Send>, writer: Box<dyn AsyncWrite + Unpin + Send>, ) -> Self
Binds custom read/write sources.
reader supplies the reply input (read line by line), and writer receives the output messages
(written line by line and flushed). Tests can inject an in-memory buffer, or the channel can be
attached to a file or the network.