new-home-application 0.1.3

New Home iot application framework. Meant to build application for the New Home Core
Documentation
use std::io::{BufWriter, Error, Write};
use std::net::TcpStream;

/// Implements the `TcpWriter` with a `BufWriter` which is wrapping around a `std::net::TcpStream`
pub struct TcpWriterImpl {
    /// The writer which is called when the `write_line`, `write` and flush methods are called
    /// Is supplied in the constructor as already created `BufWriter`
    writer: BufWriter<TcpStream>
}

/// The `TcpWriter` trait is meant to abstract some kind of a stream writer
/// This is useful in unit tests where a writer type is required as dependency in other classes
pub trait TcpWriter {
    /// Writes a line and flushes the connected `std::net::BufWriter`
    fn write_line(&mut self, message: &String) -> Result<(), Error>;

    /// Writes characters to the connected `std::net::BufWriter`
    /// This requires a manual flush or line breaks if wanted
    fn write(&mut self, message: &String) -> Result<usize, Error>;

    /// Flushes the connected `std::net::BufWriter` and sends data from the buffer to the client
    fn flush(&mut self) -> Result<(), Error>;
}

impl TcpWriterImpl {
    pub fn new(writer: BufWriter<TcpStream>) -> Self {
        Self {
            writer
        }
    }
}

impl TcpWriter for TcpWriterImpl {
    fn write_line(&mut self, message: &String) -> Result<(), Error> {
        self.writer.write_all(format!("{}\n", message).as_bytes())?;
        self.writer.write_all("\n".to_string().as_bytes())?;
        self.writer.flush()
    }

    fn write(&mut self, message: &String) -> Result<usize, Error> {
        self.writer.write(message.as_bytes())
    }

    fn flush(&mut self) -> Result<(), Error> {
        self.writer.flush()
    }
}