symqtt 0.1.1

Synchronous MQTT 3.1.1/5.0 client — blocking API, no async runtime
Documentation
//! Protocol-agnostic byte-stream transport layer.
//!
//! Defines the [`Transport`] trait for splittable read/write streams.

use std::io;
use std::time::Duration;

use bytes::BytesMut;

/// Ability to dynamically set write timeout and shut down the stream
pub trait WriteTimeout {
    /// Set the write timeout; `None` means wait indefinitely
    fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()>;

    /// Close the underlying connection, unblocking any pending reads on the peer side
    fn shutdown(&self) -> io::Result<()>;
}

/// Byte-stream transport that can be split into independent read/write halves
pub trait Transport: Send + 'static {
    /// Read half after [`Transport::split`]
    type Read: io::Read + Send + 'static;
    /// Write half after [`Transport::split`]
    type Write: io::Write + WriteTimeout + Send + 'static;

    /// Consume self, return independent read half and write half
    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::*;

    /// Mock writer implementing WriteTimeout for testing.
    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");
    }
}