use std::{io, io::Write, sync::mpsc};
use crate::framing::Framing;
pub trait Sink: Send + 'static {
fn send(&mut self, message: &str) -> io::Result<()>;
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl Sink for mpsc::Sender<String> {
fn send(&mut self, message: &str) -> io::Result<()> {
mpsc::Sender::send(self, message.to_owned()).map_err(|_| {
io::Error::new(
io::ErrorKind::BrokenPipe,
"the receiving end of the message channel is gone",
)
})
}
}
const WRITE_AT: usize = 64 * 1024;
#[derive(Debug)]
pub struct Framed<W> {
writer: W,
framing: Framing,
out: Vec<u8>,
}
impl<W: Write> Framed<W> {
#[must_use]
pub fn new(writer: W, framing: Framing) -> Self {
Self {
writer,
framing,
out: Vec::new(),
}
}
#[inline]
#[must_use]
pub const fn framing(&self) -> Framing {
self.framing
}
#[inline]
#[must_use]
pub const fn get_ref(&self) -> &W {
&self.writer
}
#[inline]
pub fn get_mut(&mut self) -> &mut W {
&mut self.writer
}
#[must_use]
pub fn into_inner(self) -> W {
self.writer
}
fn write_out(&mut self) -> io::Result<()> {
if self.out.is_empty() {
return Ok(());
}
let result = self.writer.write_all(&self.out);
self.out.clear();
result
}
}
impl<W: Write + Send + 'static> Sink for Framed<W> {
fn send(&mut self, message: &str) -> io::Result<()> {
self.framing.encode(message.as_bytes(), &mut self.out);
if self.out.len() >= WRITE_AT {
self.write_out()?;
}
Ok(())
}
fn flush(&mut self) -> io::Result<()> {
self.write_out()?;
self.writer.flush()
}
}
#[cfg(test)]
#[allow(clippy::panic)]
mod tests {
use super::*;
#[test]
fn test_framed_writes_large_turns_early() {
let mut framed = Framed::new(Vec::new(), Framing::Newline);
let big = "x".repeat(WRITE_AT);
assert!(framed.send(&big).is_ok());
assert_eq!(framed.get_ref().len(), WRITE_AT + 1);
assert!(framed.out.is_empty());
}
#[test]
fn test_channel_sink_reports_a_dropped_receiver() {
let (mut tx, rx) = mpsc::channel::<String>();
assert!(Sink::send(&mut tx, "a").is_ok());
assert_eq!(rx.recv().ok().as_deref(), Some("a"));
drop(rx);
let error = Sink::send(&mut tx, "b").err().map(|e| e.kind());
assert_eq!(error, Some(io::ErrorKind::BrokenPipe));
}
}