use std::{fmt, 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(())
}
fn close(&mut self) -> io::Result<()> {
self.flush()
}
fn drain(&mut self) -> Option<Drain> {
None
}
}
pub struct Drain(Box<dyn FnOnce() + Send>);
impl Drain {
#[must_use]
pub fn new(wait: impl FnOnce() + Send + 'static) -> Self {
Self(Box::new(wait))
}
pub fn wait(self) {
(self.0)();
}
}
impl fmt::Debug for Drain {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Drain").finish_non_exhaustive()
}
}
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>,
write_at: usize,
}
impl<W: Write> Framed<W> {
#[must_use]
pub fn new(writer: W, framing: Framing) -> Self {
Self {
writer,
framing,
out: Vec::new(),
write_at: WRITE_AT,
}
}
#[must_use]
pub fn with_flush_threshold(mut self, bytes: usize) -> Self {
self.write_at = bytes.max(1);
self
}
#[inline]
#[must_use]
pub const fn flush_threshold(&self) -> usize {
self.write_at
}
#[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();
if self.out.capacity() > self.write_at.saturating_mul(2) {
self.out.shrink_to(self.write_at);
}
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() >= self.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_framed_releases_a_buffer_grown_by_one_large_message() {
let mut framed = Framed::new(io::sink(), Framing::ContentLength);
let big = "x".repeat(10 * WRITE_AT);
assert!(framed.send(&big).is_ok());
assert!(framed.out.capacity() <= 2 * WRITE_AT);
assert!(framed.send("{}").is_ok() && framed.flush().is_ok());
assert!(framed.out.capacity() <= 2 * WRITE_AT);
}
#[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));
}
}