fit-encoder 0.1.0

Write FIT activity files (the Flexible and Interoperable Data Transfer format) as a stream: file header first, CRC last, sizes known in advance. no_std, no allocation. Independent; not affiliated with Garmin
Documentation
//! `embedded-io` and `embedded-io-async` writers as sinks.

use core::fmt;

#[cfg(feature = "embedded-io")]
use embedded_io as io;
#[cfg(not(feature = "embedded-io"))]
use embedded_io_async as io;

/// An `embedded-io` writer as a sink: a [`Sink`](crate::Sink) for `embedded_io::Write`, and
/// with `Seek` a [`PatchSink`](crate::PatchSink); with `embedded-io-async`, likewise an
/// `AsyncSink` and `AsyncPatchSink`.
#[derive(Debug)]
pub struct EmbeddedIo<W>(pub W);

/// Why an [`EmbeddedIo`] failed; an `embedded_io::Error` itself.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum EmbeddedIoError<E> {
    /// The writer's error.
    Io(E),
    /// A patch longer than how far back it starts, which would run past the end.
    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,
        }
    }
}

/// How far to seek back for a patch, and then forward past it.
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;