use std::io;
use std::time::Duration;
use bytes::BytesMut;
pub trait WriteTimeout {
fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()>;
fn shutdown(&self) -> io::Result<()>;
}
pub trait Transport: Send + 'static {
type Read: io::Read + Send + 'static;
type Write: io::Write + WriteTimeout + Send + 'static;
fn split(self) -> (Self::Read, Self::Write);
}
pub(crate) struct Writer<W> {
pub stream: W,
pub buf: BytesMut,
}
impl<W: WriteTimeout> Writer<W> {
pub(crate) fn shutdown(&self) -> io::Result<()> {
self.stream.shutdown()
}
}
#[cfg(test)]
mod tests {
use std::io;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use super::*;
struct MockWrite {
shutdown_called: Arc<AtomicBool>,
}
impl MockWrite {
fn new() -> (Self, Arc<AtomicBool>) {
let flag = Arc::new(AtomicBool::new(false));
(
Self {
shutdown_called: flag.clone(),
},
flag,
)
}
}
impl io::Write for MockWrite {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl WriteTimeout for MockWrite {
fn set_write_timeout(&self, _timeout: Option<Duration>) -> io::Result<()> {
Ok(())
}
fn shutdown(&self) -> io::Result<()> {
self.shutdown_called.store(true, Ordering::Relaxed);
Ok(())
}
}
#[test]
fn writer_shutdown_delegates_to_stream() {
let (mock, flag) = MockWrite::new();
let writer = Writer {
stream: mock,
buf: BytesMut::new(),
};
assert!(!flag.load(Ordering::Relaxed));
writer.shutdown().unwrap();
assert!(flag.load(Ordering::Relaxed));
}
#[test]
fn writer_buf_initially_empty() {
let (mock, _) = MockWrite::new();
let writer = Writer {
stream: mock,
buf: BytesMut::new(),
};
assert!(writer.buf.is_empty());
}
#[test]
fn writer_buf_can_hold_data() {
let (mock, _) = MockWrite::new();
let mut writer = Writer {
stream: mock,
buf: BytesMut::with_capacity(64),
};
writer.buf.extend_from_slice(b"hello mqtt");
assert_eq!(&writer.buf[..], b"hello mqtt");
}
}