use core::fmt;
#[cfg(feature = "embedded-io")]
use embedded_io as io;
#[cfg(not(feature = "embedded-io"))]
use embedded_io_async as io;
#[derive(Debug)]
pub struct EmbeddedIo<W>(pub W);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum EmbeddedIoError<E> {
Io(E),
PastTheEnd,
}
impl<E> From<E> for EmbeddedIoError<E> {
fn from(e: E) -> Self {
Self::Io(e)
}
}
impl<E: fmt::Display> fmt::Display for EmbeddedIoError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(e) => e.fmt(f),
Self::PastTheEnd => f.write_str("a patch past the end of what was written"),
}
}
}
impl<E: core::error::Error> core::error::Error for EmbeddedIoError<E> {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::Io(e) => e.source(),
Self::PastTheEnd => None,
}
}
}
impl<E: io::Error> io::Error for EmbeddedIoError<E> {
fn kind(&self) -> io::ErrorKind {
match self {
Self::Io(e) => e.kind(),
Self::PastTheEnd => io::ErrorKind::InvalidInput,
}
}
}
fn patch_seeks<E>(back: u32, bytes: &[u8]) -> Result<(i64, i64), EmbeddedIoError<E>> {
let len = u32::try_from(bytes.len()).ok().filter(|&n| n <= back);
let len = len.ok_or(EmbeddedIoError::PastTheEnd)?;
Ok((0i64.saturating_sub(i64::from(back)), i64::from(back.saturating_sub(len))))
}
#[cfg(feature = "embedded-io")]
mod blocking {
use embedded_io::{Seek, SeekFrom, Write};
use super::{patch_seeks, EmbeddedIo, EmbeddedIoError};
use crate::{PatchSink, Sink};
impl<W: Write> Sink for EmbeddedIo<W> {
type Error = EmbeddedIoError<W::Error>;
fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
Ok(self.0.write_all(bytes)?)
}
}
impl<W: Write + Seek> PatchSink for EmbeddedIo<W> {
fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), Self::Error> {
let (to, past) = patch_seeks(back, bytes)?;
self.0.seek(SeekFrom::Current(to))?;
self.0.write_all(bytes)?;
self.0.seek(SeekFrom::Current(past))?;
Ok(())
}
}
}
#[cfg(feature = "embedded-io-async")]
mod asynch {
use embedded_io_async::{Seek, SeekFrom, Write};
use super::{patch_seeks, EmbeddedIo, EmbeddedIoError};
use crate::{AsyncPatchSink, AsyncSink};
impl<W: Write> AsyncSink for EmbeddedIo<W> {
type Error = EmbeddedIoError<W::Error>;
async fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
Ok(self.0.write_all(bytes).await?)
}
}
impl<W: Write + Seek> AsyncPatchSink for EmbeddedIo<W> {
async fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), Self::Error> {
let (to, past) = patch_seeks(back, bytes)?;
self.0.seek(SeekFrom::Current(to)).await?;
self.0.write_all(bytes).await?;
self.0.seek(SeekFrom::Current(past)).await?;
Ok(())
}
}
}
#[cfg(test)]
mod tests;