diff --git a/ciborium-io/Cargo.toml b/ciborium-io/Cargo.toml index 6db6d04..e833242 100644 --- a/ciborium-io/Cargo.toml +++ b/ciborium-io/Cargo.toml @@ -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 diff --git a/ciborium-io/src/eio.rs b/ciborium-io/src/eio.rs new file mode 100644 index 0000000..ef7f052 --- /dev/null +++ b/ciborium-io/src/eio.rs @@ -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; + + fn read_exact(&mut self, data: &mut [u8]) -> Result<(), Self::Error> { + embedded_io::Read::read_exact(self.0, data) + } +} diff --git a/ciborium-io/src/lib.rs b/ciborium-io/src/lib.rs index fef5b70..30a484d 100644 --- a/ciborium-io/src/lib.rs +++ b/ciborium-io/src/lib.rs @@ -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