Skip to content

Commit

Permalink
feat: add read method to Read trait for embedded traits
Browse files Browse the repository at this point in the history
  • Loading branch information
kusstas committed Dec 24, 2024
1 parent b18d43c commit e481084
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
4 changes: 4 additions & 0 deletions mavlink-core/src/embedded.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ const _: () = panic!("Only one of 'embedded' and 'embedded-hal-02' features can

/// Replacement for std::io::Read + byteorder::ReadBytesExt in no_std envs
pub trait Read {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, MessageReadError> {
self.read_exact(buf).map(|_| buf.len())
}

fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), MessageReadError>;
}

Expand Down
9 changes: 9 additions & 0 deletions mavlink-core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,15 @@ pub enum MessageReadError {
Parse(ParserError),
}

impl MessageReadError {
pub fn eof() -> Self {
#[cfg(feature = "std")]
return Self::Io(std::io::ErrorKind::UnexpectedEof.into());
#[cfg(any(feature = "embedded", feature = "embedded-hal-02"))]
return Self::Io;
}
}

impl Display for MessageReadError {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
match self {
Expand Down
4 changes: 1 addition & 3 deletions mavlink-core/src/peek_reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,9 +135,7 @@ impl<R: Read, const BUFFER_SIZE: usize> PeekReader<R, BUFFER_SIZE> {
let bytes_read = self.reader.read(&mut buf[..bytes_to_read])?;

if bytes_read == 0 {
return Err(MessageReadError::Io(
std::io::ErrorKind::UnexpectedEof.into(),
));
return Err(MessageReadError::eof());
}

// if some bytes were read, add them to the buffer
Expand Down

0 comments on commit e481084

Please sign in to comment.