fit-encoder 0.1.1

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//! The async drivers. A call on the writer stages its bytes, and the stage goes to the sink each
//! time it fills, so a sink is awaited between calls and never inside one.

use core::fmt;

use super::{
    header, Counter, Error, FinishError, Options, Out, State, WriteError, Writer, HEADER_LEN,
};
use crate::developer::{Dev, DevField, DevType, Developer, Extra, FieldDescription, Kind, Summary};
use crate::messages::{Device, LapTrigger, Leg, Length, Pool, Record, Set};
use crate::raw::RawField;
use crate::types::{Sport, SubSport, Timestamp};

/// How many bytes an async sink takes at a time: every write but a file's last is this long.
pub const ASYNC_WRITE_LEN: usize = 256;

/// Where an async file's bytes go: [`Sink`](crate::Sink), awaited.
#[allow(async_fn_in_trait, reason = "a Send bound would shut out single-threaded executors")]
pub trait AsyncSink {
    /// Why a write failed.
    type Error;

    /// The whole file's length, as [`Sink::begin`](crate::Sink::begin) has it: only
    /// [`write_async`] calls this.
    ///
    /// # Errors
    ///
    /// Whatever stops the sink taking a file of that length.
    async fn begin(&mut self, _file_size: u32) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Writes all of `bytes`, or fails.
    ///
    /// # Errors
    ///
    /// Whatever the sink cannot write.
    async fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error>;
}

impl<S: AsyncSink + ?Sized> AsyncSink for &mut S {
    type Error = S::Error;

    async fn begin(&mut self, file_size: u32) -> Result<(), S::Error> {
        (**self).begin(file_size).await
    }

    async fn write(&mut self, bytes: &[u8]) -> Result<(), S::Error> {
        (**self).write(bytes).await
    }
}

/// An [`AsyncSink`] that can overwrite bytes it already took, for [`AsyncOnePass`], as
/// [`PatchSink`](crate::PatchSink) has it.
#[allow(async_fn_in_trait, reason = "a Send bound would shut out single-threaded executors")]
pub trait AsyncPatchSink: AsyncSink {
    /// Overwrites the bytes starting `back` bytes before the end of what was written, as
    /// [`PatchSink::patch`](crate::PatchSink::patch) does.
    ///
    /// # Errors
    ///
    /// Whatever stops the sink rewriting them.
    async fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), Self::Error>;
}

impl<S: AsyncPatchSink + ?Sized> AsyncPatchSink for &mut S {
    async fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), S::Error> {
        (**self).patch(back, bytes).await
    }
}

/// The most beat intervals one call gives the writer: their `hrv` messages take less than a
/// stage.
const BEATS_AT_ONCE: usize = 100;

/// A sink and the bytes staged for it.
struct Staged<S: AsyncSink> {
    sink: S,
    stage: [u8; ASYNC_WRITE_LEN],
    len: usize,
    /// How much of `stage` is used; less only in tests.
    cap: usize,
    /// The error a call met, which the call could only report as [`Error::Sink`].
    error: Option<S::Error>,
    /// A write was dropped before it finished, so what the sink holds is unknown.
    torn: bool,
    /// The most bytes one call wrote on a copy of the state.
    #[cfg(test)]
    longest_spill: usize,
}

impl<S: AsyncSink> Staged<S> {
    fn new(sink: S, header: &[u8; HEADER_LEN as usize]) -> Self {
        let mut stage = [0; ASYNC_WRITE_LEN];
        let mut window = Window::new(&mut stage, None);
        window.write(header);
        Self {
            sink,
            stage,
            len: header.len(),
            cap: ASYNC_WRITE_LEN,
            error: None,
            torn: false,
            #[cfg(test)]
            longest_spill: 0,
        }
    }

    /// Writes what is staged.
    async fn drain(&mut self) -> Result<(), S::Error> {
        let len = core::mem::take(&mut self.len);
        self.torn = true;
        let written = match self.stage.get(..len) {
            Some(bytes) if !bytes.is_empty() => self.sink.write(bytes).await,
            _ => Ok(()),
        };
        self.torn = false;
        written
    }

    /// Stages `bytes`, writing the stage each time it fills.
    async fn put(&mut self, bytes: &[u8]) -> Result<(), S::Error> {
        let room = self.stage.get_mut(self.len..self.cap).unwrap_or_default();
        let (now, later) = bytes.split_at(room.len().min(bytes.len()));
        room.get_mut(..now.len()).unwrap_or_default().copy_from_slice(now);
        self.len = self.len.saturating_add(now.len());
        self.drain_full().await?;
        for chunk in later.chunks(self.cap.max(1)) {
            self.stage.get_mut(..chunk.len()).unwrap_or_default().copy_from_slice(chunk);
            self.len = chunk.len();
            self.drain_full().await?;
        }
        Ok(())
    }

    /// Stages what `call` writes to `st`, writing the stage each time it fills, and returns
    /// what it returned. A call that says its bytes fit what is left of the stage writes them
    /// there; one that would spill past it writes nothing, and runs instead on a copy of `st`
    /// for each stage its bytes fall in, keeping those, until the copy that wrote the last
    /// becomes `st`.
    async fn call<R>(
        &mut self,
        st: &mut State,
        call: impl Fn(&mut Writer<'_>) -> R,
    ) -> Result<R, S::Error> {
        let room = self.stage.get_mut(self.len..self.cap).unwrap_or_default();
        let mut window = Window::new(room, None);
        let result = call(&mut Writer { out: &mut window, st });
        if !window.refused {
            self.len = self.len.saturating_add(window.kept);
            self.drain_full().await?;
            return Ok(result);
        }
        let (mut result, seen, mut done) = self.spill(st, &call, 0);
        let rounds = seen.saturating_sub(done).div_ceil(self.cap.max(1));
        for _ in 0..rounds {
            self.drain().await?;
            let (again, _, kept) = self.spill(st, &call, done);
            (result, done) = (again, done.saturating_add(kept));
        }
        self.drain_full().await?;
        Ok(result)
    }

    /// Runs `call` on a copy of `st`, staging its bytes from `skip` on as far as the stage
    /// holds; the copy becomes `st` if they were its last. Returns what the call returned, the
    /// bytes it wrote, and those staged.
    fn spill<R>(
        &mut self,
        st: &mut State,
        call: &impl Fn(&mut Writer<'_>) -> R,
        skip: usize,
    ) -> (R, usize, usize) {
        let room = self.stage.get_mut(self.len..self.cap).unwrap_or_default();
        let mut window = Window::new(room, Some(skip));
        let mut copy = st.clone();
        let result = call(&mut Writer { out: &mut window, st: &mut copy });
        #[cfg(test)]
        {
            self.longest_spill = self.longest_spill.max(window.seen);
        }
        if skip.saturating_add(window.kept) >= window.seen {
            *st = copy;
        }
        self.len = self.len.saturating_add(window.kept);
        (result, window.seen, window.kept)
    }

    /// Writes the stage if it is full.
    async fn drain_full(&mut self) -> Result<(), S::Error> {
        if self.len >= self.cap {
            self.drain().await?;
        }
        Ok(())
    }
}

/// The bytes a call writes from `skip` on, as many as `room` holds. Without `skip`, the call
/// must say they all fit, or it is refused.
struct Window<'a> {
    room: &'a mut [u8],
    skip: Option<usize>,
    /// The bytes the call has written, and those of them kept.
    seen: usize,
    kept: usize,
    refused: bool,
}

impl<'a> Window<'a> {
    fn new(room: &'a mut [u8], skip: Option<usize>) -> Self {
        Self { room, skip, seen: 0, kept: 0, refused: false }
    }
}

impl Out for Window<'_> {
    fn write(&mut self, bytes: &[u8]) -> bool {
        let from = self.skip.unwrap_or(0).saturating_sub(self.seen);
        let src = bytes.get(from..).unwrap_or_default();
        let dst = self.room.get_mut(self.kept..).unwrap_or_default();
        let n = src.len().min(dst.len());
        if let Some((dst, src)) = dst.get_mut(..n).zip(src.get(..n)) {
            dst.copy_from_slice(src);
        }
        self.kept = self.kept.saturating_add(n);
        self.seen = self.seen.saturating_add(bytes.len());
        true
    }

    fn fits(&mut self, size: u32) -> bool {
        let fits = usize::try_from(size)
            .is_ok_and(|size| self.seen.saturating_add(size) <= self.room.len());
        self.refused |= self.skip.is_none() && !fits;
        !self.refused
    }
}

/// Writes the messages of one file to an async sink, as [`Writer`] does to a sink.
/// [`write_async`] hands one to the source, and [`AsyncOnePass::writer`] gives one, so a
/// function taking a `&mut AsyncWriter` serves both.
///
/// A call returns once its bytes are staged and each stage they filled has gone to the sink, so
/// the sink's error can surface as [`Error::Sink`] on a later call; [`write_async`] and
/// [`AsyncOnePass::finish`] return it.
pub struct AsyncWriter<'a, S: AsyncSink> {
    st: &'a mut State,
    /// `None` on [`write_async`]'s sizing pass.
    staged: Option<&'a mut Staged<S>>,
}

impl<S: AsyncSink> fmt::Debug for AsyncWriter<'_, S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AsyncWriter").field("written", &self.st.written).finish_non_exhaustive()
    }
}

/// Each call of [`Writer`], made through the stage.
macro_rules! calls {
    (@ok) => { () };
    (@ok $ok:ty) => { $ok };
    ($(
        $name:ident $([$($generics:tt)*])? ($($arg:ident: $ty:ty),*) $(-> $ok:ty)?;
    )*) => {$(
        #[doc = concat!("[`Writer::", stringify!($name), "`], awaiting the sink.")]
        ///
        /// # Errors
        ///
        #[doc = concat!("As [`Writer::", stringify!($name), "`].")]
        pub async fn $name $(<$($generics)*>)? (
            &mut self,
            $($arg: $ty),*
        ) -> Result<calls!(@ok $($ok)?), Error> {
            self.call(|w| w.$name($($arg),*)).await
        }
    )*};
}

impl<S: AsyncSink> AsyncWriter<'_, S> {
    calls! {
        start(t: Timestamp, creator: &Device<'_>);
        device(device: &Device<'_>);
        session(t: Timestamp, sport: Sport, sub_sport: SubSport);
        pool_swim(t: Timestamp, pool: Pool);
        leg(t: Timestamp, leg: &Leg<'_>);
        record(record: &Record);
        record_with(record: &Record, extras: &[Extra<'_>]);
        lap(t: Timestamp);
        lap_by(t: Timestamp, trigger: LapTrigger);
        pause(t: Timestamp);
        resume(t: Timestamp);
        length(t: Timestamp, length: &Length);
        set(t: Timestamp, set: &Set);
        rest(t: Timestamp);
        end_rest(t: Timestamp);
        developer(developer: &Developer) -> Dev;
        declare[T: DevType + ?Sized, K: Kind](
            description: &FieldDescription<'_, T, K>
        ) -> DevField<T, K>;
        developer_value[T: DevType + ?Sized, K: Summary](
            field: &DevField<T, K>,
            value: T::Value<'_>
        );
        raw_message(global: u16, fields: &[RawField<'_>]);
        end(t: Timestamp);
    }

    /// [`Writer::beat_intervals_ms`], awaiting the sink.
    ///
    /// # Errors
    ///
    /// As [`Writer::beat_intervals_ms`].
    pub async fn beat_intervals_ms(&mut self, intervals: &[u16]) -> Result<(), Error> {
        self.beats(intervals, true).await
    }

    /// [`Writer::beat_intervals_1024ths`], awaiting the sink.
    ///
    /// # Errors
    ///
    /// As [`Writer::beat_intervals_1024ths`].
    pub async fn beat_intervals_1024ths(&mut self, intervals: &[u16]) -> Result<(), Error> {
        self.beats(intervals, false).await
    }

    /// Refuses `intervals` whole, as the writer does, then gives them a few at a time, so no
    /// call spills past more than a stage or two; they make the same bytes, as they are written
    /// five at a time whatever the calls.
    async fn beats(&mut self, intervals: &[u16], ms: bool) -> Result<(), Error> {
        self.call(|w| w.beats_fit(intervals, ms)).await?;
        for part in intervals.chunks(BEATS_AT_ONCE) {
            self.call(
                |w| {
                    if ms {
                        w.beat_intervals_ms(part)
                    } else {
                        w.beat_intervals_1024ths(part)
                    }
                },
            )
            .await?;
        }
        Ok(())
    }

    /// Makes a call of [`Writer`] through the stage.
    async fn call<R>(
        &mut self,
        f: impl Fn(&mut Writer<'_>) -> Result<R, Error>,
    ) -> Result<R, Error> {
        let Some(staged) = self.staged.as_deref_mut() else {
            return f(&mut Writer { out: &mut Counter, st: self.st });
        };
        if staged.torn {
            return Err(Error::Sink);
        }
        match staged.call(self.st, f).await {
            Ok(result) => result,
            Err(e) => {
                staged.error = Some(e);
                self.st.failed = true;
                Err(Error::Sink)
            }
        }
    }
}

/// Writes the file `source` describes to an async `sink`, as [`write()`](crate::write) does to a
/// sink: header first and CRC last, without seeking, the source run twice.
///
/// ```
/// use fit_encoder::*;
///
/// struct Uart;
/// impl AsyncSink for Uart {
///     type Error = ();
///     async fn write(&mut self, bytes: &[u8]) -> Result<(), ()> {
///         Ok(()) // Await the UART here.
///     }
/// }
///
/// async fn send(start: Timestamp, hr: &[u8]) -> Result<(), WriteError<(), Error>> {
///     write_async(Uart, Options::new(), async |w| {
///         w.start(start, &Device::new(Manufacturer::DEVELOPMENT, 1)).await?;
///         w.session(start, Sport::RUNNING, SubSport::TREADMILL).await?;
///         for (s, &bpm) in (0..).zip(hr) {
///             w.record(&Record::new(start.checked_add(s).unwrap()).heart_rate(bpm)).await?;
///         }
///         w.end(start.checked_add(60).unwrap()).await
///     })
///     .await?;
///     Ok(())
/// }
/// # let _ = send;
/// ```
///
/// # Errors
///
/// As [`write()`](crate::write)'s.
pub async fn write_async<S, E, F>(
    sink: S,
    options: Options,
    mut source: F,
) -> Result<S, WriteError<S::Error, E>>
where
    S: AsyncSink,
    E: From<Error>,
    F: AsyncFnMut(&mut AsyncWriter<'_, S>) -> Result<(), E>,
{
    let mut st = State::new(options, None);
    source(&mut AsyncWriter { st: &mut st, staged: None }).await.map_err(WriteError::Source)?;
    let plan = st.plan().map_err(|e| WriteError::Source(E::from(e)))?;

    let mut sink = sink;
    sink.begin(plan.file_size).await.map_err(WriteError::Sink)?;
    let header = header(options, plan.data_size);
    let mut staged = Staged::new(sink, &header);
    let mut st = State::new(options, Some(plan));
    let mut w = AsyncWriter { st: &mut st, staged: Some(&mut staged) };
    let result = source(&mut w).await;
    #[allow(clippy::redundant_closure_for_method_calls, reason = "the path is not higher-ranked")]
    let end = w.call(|w| w.close()).await;
    if let Some(e) = staged.error.take() {
        return Err(WriteError::Sink(e));
    }
    result.map_err(WriteError::Source)?;
    end.map_err(|e| WriteError::Source(E::from(e)))?;
    let crc = super::file_crc(&header, &st);
    staged.put(&crc).await.map_err(WriteError::Sink)?;
    staged.drain().await.map_err(WriteError::Sink)?;
    Ok(staged.sink)
}

/// Writes a file to an async sink as its messages arrive, as [`OnePass`](crate::OnePass) does
/// to a sink.
///
/// ```
/// use fit_encoder::*;
///
/// async fn record(sink: impl AsyncPatchSink, start: Timestamp) -> Result<(), Error> {
///     let mut file = AsyncOnePass::new(sink, Options::new());
///     let mut w = file.writer();
///     w.start(start, &Device::new(Manufacturer::DEVELOPMENT, 1)).await?;
///     w.session(start, Sport::WALKING, SubSport::GENERIC).await?;
///     w.record(&Record::new(start).heart_rate(100)).await?;
///     w.end(start.checked_add(1).unwrap()).await?;
///     file.finish().await.map_err(|_| Error::Sink)?;
///     Ok(())
/// }
/// ```
pub struct AsyncOnePass<S: AsyncPatchSink> {
    staged: Staged<S>,
    st: State,
}

impl<S: AsyncPatchSink> fmt::Debug for AsyncOnePass<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AsyncOnePass").field("written", &self.st.written).finish_non_exhaustive()
    }
}

impl<S: AsyncPatchSink> AsyncOnePass<S> {
    /// Stages the header, its length to come.
    pub fn new(sink: S, options: Options) -> Self {
        Self { staged: Staged::new(sink, &header(options, 0)), st: State::new(options, None) }
    }

    /// The writer for the next messages.
    pub fn writer(&mut self) -> AsyncWriter<'_, S> {
        AsyncWriter { st: &mut self.st, staged: Some(&mut self.staged) }
    }

    /// Writes the file CRC and patches the header's length in, as
    /// [`OnePass::finish`](crate::OnePass::finish) does.
    ///
    /// # Errors
    ///
    /// As [`OnePass::finish`](crate::OnePass::finish)'s.
    #[allow(clippy::result_large_err, reason = "the error holds the file, to finish again")]
    pub async fn finish(mut self) -> Result<S, FinishError<Self, S::Error>> {
        match self.try_finish().await {
            Ok(()) => Ok(self.staged.sink),
            Err(error) => Err(FinishError { error, file: self }),
        }
    }

    /// The sink, giving up on the file: its header still claims no messages, so readers
    /// refuse it, and what was staged is never written.
    pub fn into_sink(self) -> S {
        self.staged.sink
    }

    async fn try_finish(&mut self) -> Result<(), WriteError<S::Error, Error>> {
        #[allow(
            clippy::redundant_closure_for_method_calls,
            reason = "the path is not higher-ranked"
        )]
        let ended = self.writer().call(|w| w.close()).await;
        if let Some(e) = self.staged.error.take() {
            return Err(WriteError::Sink(e));
        }
        ended.map_err(WriteError::Source)?;
        let (header, back, crc) = self.st.trailer().map_err(WriteError::Source)?;
        // The CRC goes first, so a file it fails on keeps a header claiming no messages.
        let staged = &mut self.staged;
        let written = match staged.put(&crc).await {
            Ok(()) => match staged.drain().await {
                Ok(()) => staged.sink.patch(back, &header).await,
                Err(e) => Err(e),
            },
            Err(e) => Err(e),
        };
        written.map_err(|e| {
            self.st.failed = true;
            WriteError::Sink(e)
        })
    }
}

#[cfg(test)]
mod tests;