Skip to content

Commit

Permalink
feat: add adapters around embedded-io::{Read, Write} implementing Rea…
Browse files Browse the repository at this point in the history
…d, Write

Signed-off-by: Stanislav Ravas <[email protected]>
  • Loading branch information
elrafoon authored and rjzak committed Feb 17, 2024
1 parent 3d0b012 commit 30cff0e
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
4 changes: 4 additions & 0 deletions ciborium-io/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ is-it-maintained-open-issues = { repository = "enarx/ciborium" }
[features]
alloc = []
std = ["alloc"]
embedded-io = ["dep:embedded-io"]

[dependencies]
embedded-io = { version = "0.6.1", optional = true }

[package.metadata.docs.rs]
all-features = true
46 changes: 46 additions & 0 deletions ciborium-io/src/eio.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
use crate::{Read, Write};

/// Wrapper around W: embedded_io::Write implementing ciborium::Write
pub struct EIOWriter<'a, W>(&'a mut W);

impl<'a, W> EIOWriter<'a, W> {
/// construct EIOWriter for embedded_io::Write
pub fn from(writer: &'a mut W) -> Self {
Self(writer)
}
}

impl<'a, W> Write for EIOWriter<'a, W>
where W: embedded_io::Write
{
type Error = W::Error;

fn write_all(&mut self, data: &[u8]) -> Result<(), Self::Error> {
embedded_io::Write::write_all(self.0, data)
}

fn flush(&mut self) -> Result<(), Self::Error> {
embedded_io::Write::flush(self.0)
}
}


/// Wrapper around R: embedded_io::Read implementing ciborium::Read
pub struct EIOReader<'a, R>(&'a mut R);

impl<'a, R> EIOReader<'a, R> {
/// construct EIOReader for embedded_io::Read
pub fn from(reader: &'a mut R) -> Self {
Self(reader)
}
}

impl<'a, R> Read for EIOReader<'a, R>
where R: embedded_io::Read
{
type Error = embedded_io::ReadExactError<R::Error>;

fn read_exact(&mut self, data: &mut [u8]) -> Result<(), Self::Error> {
embedded_io::Read::read_exact(self.0, data)
}
}
4 changes: 4 additions & 0 deletions ciborium-io/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
#[cfg(feature = "alloc")]
extern crate alloc;

/// Adapters of embedded-io::{Read, Write} implementing ciborium::{Read, Write}
#[cfg(feature = "embedded-io")]
pub mod eio;

/// A trait indicating a type that can read bytes
///
/// Note that this is similar to `std::io::Read`, but simplified for use in a
Expand Down

0 comments on commit 30cff0e

Please sign in to comment.