Skip to main content

fit_encoder/encoder/
embedded_io.rs

1//! `embedded-io` and `embedded-io-async` writers as sinks.
2
3use core::fmt;
4
5#[cfg(feature = "embedded-io")]
6use embedded_io as io;
7#[cfg(not(feature = "embedded-io"))]
8use embedded_io_async as io;
9
10/// An `embedded-io` writer as a sink: a [`Sink`](crate::Sink) for `embedded_io::Write`, and
11/// with `Seek` a [`PatchSink`](crate::PatchSink); with `embedded-io-async`, likewise an
12/// `AsyncSink` and `AsyncPatchSink`.
13#[derive(Debug)]
14pub struct EmbeddedIo<W>(pub W);
15
16/// Why an [`EmbeddedIo`] failed; an `embedded_io::Error` itself.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18#[non_exhaustive]
19pub enum EmbeddedIoError<E> {
20    /// The writer's error.
21    Io(E),
22    /// A patch longer than how far back it starts, which would run past the end.
23    PastTheEnd,
24}
25
26impl<E> From<E> for EmbeddedIoError<E> {
27    fn from(e: E) -> Self {
28        Self::Io(e)
29    }
30}
31
32impl<E: fmt::Display> fmt::Display for EmbeddedIoError<E> {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            Self::Io(e) => e.fmt(f),
36            Self::PastTheEnd => f.write_str("a patch past the end of what was written"),
37        }
38    }
39}
40
41impl<E: core::error::Error> core::error::Error for EmbeddedIoError<E> {
42    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
43        match self {
44            Self::Io(e) => e.source(),
45            Self::PastTheEnd => None,
46        }
47    }
48}
49
50impl<E: io::Error> io::Error for EmbeddedIoError<E> {
51    fn kind(&self) -> io::ErrorKind {
52        match self {
53            Self::Io(e) => e.kind(),
54            Self::PastTheEnd => io::ErrorKind::InvalidInput,
55        }
56    }
57}
58
59/// How far to seek back for a patch, and then forward past it.
60fn patch_seeks<E>(back: u32, bytes: &[u8]) -> Result<(i64, i64), EmbeddedIoError<E>> {
61    let len = u32::try_from(bytes.len()).ok().filter(|&n| n <= back);
62    let len = len.ok_or(EmbeddedIoError::PastTheEnd)?;
63    Ok((0i64.saturating_sub(i64::from(back)), i64::from(back.saturating_sub(len))))
64}
65
66#[cfg(feature = "embedded-io")]
67mod blocking {
68    use embedded_io::{Seek, SeekFrom, Write};
69
70    use super::{patch_seeks, EmbeddedIo, EmbeddedIoError};
71    use crate::{PatchSink, Sink};
72
73    impl<W: Write> Sink for EmbeddedIo<W> {
74        type Error = EmbeddedIoError<W::Error>;
75
76        fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
77            Ok(self.0.write_all(bytes)?)
78        }
79    }
80
81    impl<W: Write + Seek> PatchSink for EmbeddedIo<W> {
82        fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), Self::Error> {
83            let (to, past) = patch_seeks(back, bytes)?;
84            self.0.seek(SeekFrom::Current(to))?;
85            self.0.write_all(bytes)?;
86            self.0.seek(SeekFrom::Current(past))?;
87            Ok(())
88        }
89    }
90}
91
92#[cfg(feature = "embedded-io-async")]
93mod asynch {
94    use embedded_io_async::{Seek, SeekFrom, Write};
95
96    use super::{patch_seeks, EmbeddedIo, EmbeddedIoError};
97    use crate::{AsyncPatchSink, AsyncSink};
98
99    impl<W: Write> AsyncSink for EmbeddedIo<W> {
100        type Error = EmbeddedIoError<W::Error>;
101
102        async fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
103            Ok(self.0.write_all(bytes).await?)
104        }
105    }
106
107    impl<W: Write + Seek> AsyncPatchSink for EmbeddedIo<W> {
108        async fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), Self::Error> {
109            let (to, past) = patch_seeks(back, bytes)?;
110            self.0.seek(SeekFrom::Current(to)).await?;
111            self.0.write_all(bytes).await?;
112            self.0.seek(SeekFrom::Current(past)).await?;
113            Ok(())
114        }
115    }
116}
117
118#[cfg(test)]
119mod tests;