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
#![cfg(all(feature = "embedded-io", feature = "embedded-io-async"))]

use super::*;
use crate::{AsyncOnePass, AsyncPatchSink, OnePass, PatchSink};
use crate::{Device, Manufacturer, Options, Record, Sport, SubSport, Timestamp};
use embassy_futures::block_on;
use std::vec;
use std::vec::Vec;

/// Memory with a position, taking at most three bytes a write.
#[derive(Debug, Default)]
struct Cursor {
    bytes: Vec<u8>,
    at: usize,
}

#[derive(Debug, PartialEq, Eq)]
struct Bad;

impl core::fmt::Display for Bad {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("bad")
    }
}

impl core::error::Error for Bad {}

impl embedded_io::Error for Bad {
    fn kind(&self) -> embedded_io::ErrorKind {
        embedded_io::ErrorKind::Other
    }
}

impl embedded_io::ErrorType for Cursor {
    type Error = Bad;
}

impl Cursor {
    fn put(&mut self, buf: &[u8]) -> usize {
        let n = buf.len().min(3);
        let end = self.at + n;
        if self.bytes.len() < end {
            self.bytes.resize(end, 0);
        }
        self.bytes[self.at..end].copy_from_slice(&buf[..n]);
        self.at = end;
        n
    }

    fn go(&mut self, pos: embedded_io::SeekFrom) -> Result<u64, Bad> {
        let embedded_io::SeekFrom::Current(by) = pos else { return Err(Bad) };
        let at = i64::try_from(self.at).unwrap() + by;
        self.at = usize::try_from(at).map_err(|_| Bad)?;
        Ok(self.at as u64)
    }
}

impl embedded_io::Write for Cursor {
    fn write(&mut self, buf: &[u8]) -> Result<usize, Bad> {
        Ok(self.put(buf))
    }

    fn flush(&mut self) -> Result<(), Bad> {
        Ok(())
    }
}

impl embedded_io::Seek for Cursor {
    fn seek(&mut self, pos: embedded_io::SeekFrom) -> Result<u64, Bad> {
        self.go(pos)
    }
}

impl embedded_io_async::Write for Cursor {
    async fn write(&mut self, buf: &[u8]) -> Result<usize, Bad> {
        embassy_futures::yield_now().await;
        Ok(self.put(buf))
    }

    async fn flush(&mut self) -> Result<(), Bad> {
        embassy_futures::yield_now().await;
        Ok(())
    }
}

impl embedded_io_async::Seek for Cursor {
    async fn seek(&mut self, pos: embedded_io::SeekFrom) -> Result<u64, Bad> {
        embassy_futures::yield_now().await;
        self.go(pos)
    }
}

const T: Timestamp = Timestamp::from_fit(1_000_000_000);

fn source(w: &mut crate::Writer<'_>) -> Result<(), crate::Error> {
    w.start(T, &Device::new(Manufacturer::DEVELOPMENT, 1))?;
    w.session(T, Sport::RUNNING, SubSport::GENERIC)?;
    for s in 0..100 {
        w.record(&Record::new(T.checked_add(s).unwrap()).heart_rate(90))?;
    }
    w.end(T.checked_add(100).unwrap())
}

fn file() -> Vec<u8> {
    crate::to_vec(Options::new(), source).unwrap()
}

#[test]
fn sync() {
    let written = crate::write(EmbeddedIo(Cursor::default()), Options::new(), source).unwrap();
    assert_eq!(written.0.bytes, file());
    let mut one = OnePass::new(EmbeddedIo(Cursor::default()), Options::new()).unwrap();
    source(&mut one.writer()).unwrap();
    let cursor = one.finish().unwrap().0;
    assert_eq!((cursor.bytes, cursor.at), (file(), file().len()));

    let mut io = EmbeddedIo(Cursor { bytes: vec![0; 4], at: 4 });
    let past = PatchSink::patch(&mut io, 2, &[1, 2, 3]);
    assert_eq!(past, Err(EmbeddedIoError::PastTheEnd));
    assert_eq!((io.0.bytes.as_slice(), io.0.at), (&[0; 4][..], 4), "nothing written");
    PatchSink::patch(&mut io, 4, &[1, 2]).unwrap();
    assert_eq!((io.0.bytes.as_slice(), io.0.at), (&[1, 2, 0, 0][..], 4));
    assert_eq!(PatchSink::patch(&mut io, 5, &[1]), Err(EmbeddedIoError::Io(Bad)));
}

#[test]
fn asynch() {
    let mut one = AsyncOnePass::new(EmbeddedIo(Cursor::default()), Options::new());
    block_on(async {
        let mut w = one.writer();
        w.start(T, &Device::new(Manufacturer::DEVELOPMENT, 1)).await?;
        w.session(T, Sport::RUNNING, SubSport::GENERIC).await?;
        for s in 0..100 {
            w.record(&Record::new(T.checked_add(s).unwrap()).heart_rate(90)).await?;
        }
        w.end(T.checked_add(100).unwrap()).await
    })
    .unwrap();
    let cursor = block_on(one.finish()).unwrap().0;
    assert_eq!((cursor.bytes, cursor.at), (file(), file().len()));

    let mut io = EmbeddedIo(Cursor { bytes: vec![0; 4], at: 4 });
    let past = block_on(AsyncPatchSink::patch(&mut io, 2, &[1, 2, 3]));
    assert_eq!(past, Err(EmbeddedIoError::PastTheEnd));
    assert_eq!((io.0.bytes.as_slice(), io.0.at), (&[0; 4][..], 4), "nothing written");
    block_on(AsyncPatchSink::patch(&mut io, 4, &[1, 2])).unwrap();
    assert_eq!((io.0.bytes.as_slice(), io.0.at), (&[1, 2, 0, 0][..], 4));
    assert_eq!(block_on(AsyncPatchSink::patch(&mut io, 5, &[1])), Err(EmbeddedIoError::Io(Bad)));
}

#[test]
fn errors_say_what_failed_as_embedded_io_errors() {
    use embedded_io::{Error as _, ErrorKind};
    use std::string::ToString;
    let (io, past) = (EmbeddedIoError::Io(Bad), EmbeddedIoError::<Bad>::PastTheEnd);
    assert_eq!((io.to_string(), io.kind()), ("bad".to_string(), ErrorKind::Other));
    let said = "a patch past the end of what was written".to_string();
    assert_eq!((past.to_string(), past.kind()), (said, ErrorKind::InvalidInput));
    let _: &dyn core::error::Error = &io;
}

#[derive(Debug)]
struct Caused;

impl core::fmt::Display for Caused {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("caused")
    }
}

impl core::error::Error for Caused {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        Some(&Bad)
    }
}

impl embedded_io::Error for Caused {
    fn kind(&self) -> embedded_io::ErrorKind {
        embedded_io::ErrorKind::Other
    }
}

/// A writer that fails at once.
#[derive(Debug)]
struct Failing;

impl embedded_io::ErrorType for Failing {
    type Error = Caused;
}

impl embedded_io::Write for Failing {
    fn write(&mut self, _: &[u8]) -> Result<usize, Caused> {
        Err(Caused)
    }

    fn flush(&mut self) -> Result<(), Caused> {
        Ok(())
    }
}

#[test]
fn an_io_error_keeps_what_caused_it() {
    use core::error::Error as _;
    use std::string::ToString;
    let source = EmbeddedIoError::Io(Caused).source().map(ToString::to_string);
    assert_eq!(source.as_deref(), Some("bad"));
}

fn chain(e: &dyn core::error::Error) -> Vec<std::string::String> {
    use std::string::ToString;
    core::iter::successors(Some(e), |e| e.source()).map(ToString::to_string).collect()
}

#[test]
fn a_write_error_names_each_cause_once() {
    let failed = crate::write(EmbeddedIo(Failing), Options::new(), source).unwrap_err();
    assert_eq!(chain(&failed), ["the sink failed", "caused", "bad"]);
    let refused = crate::WriteError::<Caused, Caused>::Source(Caused);
    assert_eq!(chain(&refused), ["caused", "bad"]);
}