Skip to content

WIP: Implement nb::io traits for serial traits #58

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
84 changes: 84 additions & 0 deletions src/serial.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,87 @@ pub trait Write<Word> {
/// 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<R> where R: Read<u8> {
reader: R,
}

/// TODO
pub struct Writer<W> where W: Write<u8> {
writer: W,
}

/// TODO
pub fn reader<R>(reader: R) -> Reader<R> where R: Read<u8> {
Reader { reader }
}

/// TODO
pub fn writer<W>(writer: W) -> Writer<W> where W: Write<u8> {
Writer { writer }
}

impl<R> nb::io::Read for Reader<R> where R: Read<u8> {
type Error = R::Error;

fn read(&mut self, buf: &mut [u8]) -> nb::Result<usize, Self::Error> {
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<W> nb::io::Write for Writer<W> where W: Write<u8> {
type Error = W::Error;

fn write(&mut self, buf: &[u8]) -> nb::Result<usize, Self::Error> {
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()
}
}
}