diff --git a/Cargo.toml b/Cargo.toml index 5b1b4bc65..c2832ce3e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,8 @@ version = "0.1.2" [dependencies.nb] version = "0.1.1" +git = "https://github.com/Nemo157/nb" +branch = "io-traits" [dev-dependencies] stm32f30x = "0.6.0" diff --git a/src/serial.rs b/src/serial.rs index 484bb2967..a4430a349 100644 --- a/src/serial.rs +++ b/src/serial.rs @@ -25,3 +25,87 @@ pub trait Write { /// Ensures that none of the previously written words are still buffered fn flush(&mut self) -> nb::Result<(), Self::Error>; } + +#[cfg(feature = "unproven")] +/// TODO +pub mod io { + use nb; + use super::{Read, Write}; + + /// TODO + pub struct Reader where R: Read { + reader: R, + } + + /// TODO + pub struct Writer where W: Write { + writer: W, + } + + /// TODO + pub fn reader(reader: R) -> Reader where R: Read { + Reader { reader } + } + + /// TODO + pub fn writer(writer: W) -> Writer where W: Write { + Writer { writer } + } + + impl nb::io::Read for Reader where R: Read { + type Error = R::Error; + + fn read(&mut self, buf: &mut [u8]) -> nb::Result { + let mut count = 0; + while count < buf.len() { + match self.reader.read() { + Ok(byte) => { + buf[count] = byte; + count += 1; + } + Err(nb::Error::WouldBlock) => { + if count > 0 { + return Ok(count); + } else { + return Err(nb::Error::WouldBlock); + } + } + Err(error) => { + return Err(error); + } + } + } + return Ok(count); + } + } + + impl nb::io::Write for Writer where W: Write { + type Error = W::Error; + + fn write(&mut self, buf: &[u8]) -> nb::Result { + let mut count = 0; + while count < buf.len() { + match self.writer.write(buf[count]) { + Ok(()) => { + count += 1; + } + Err(nb::Error::WouldBlock) => { + if count > 0 { + return Ok(count); + } else { + return Err(nb::Error::WouldBlock); + } + } + Err(error) => { + return Err(error); + } + } + } + return Ok(count); + } + + fn flush(&mut self) -> nb::Result<(), Self::Error> { + self.writer.flush() + } + } +}