Skip to main content

fit_encoder/encoder/
asynch.rs

1//! The async drivers. A call on the writer stages its bytes, and the stage goes to the sink each
2//! time it fills, so a sink is awaited between calls and never inside one.
3
4use core::fmt;
5
6use super::{
7    header, Counter, Error, FinishError, Options, Out, State, WriteError, Writer, HEADER_LEN,
8};
9use crate::developer::{Dev, DevField, DevType, Developer, Extra, FieldDescription, Kind, Summary};
10use crate::messages::{Device, LapTrigger, Leg, Length, Pool, Record, Set};
11use crate::raw::RawField;
12use crate::types::{Sport, SubSport, Timestamp};
13
14/// How many bytes an async sink takes at a time: every write but a file's last is this long.
15pub const ASYNC_WRITE_LEN: usize = 256;
16
17/// Where an async file's bytes go: [`Sink`](crate::Sink), awaited.
18#[allow(async_fn_in_trait, reason = "a Send bound would shut out single-threaded executors")]
19pub trait AsyncSink {
20    /// Why a write failed.
21    type Error;
22
23    /// The whole file's length, as [`Sink::begin`](crate::Sink::begin) has it: only
24    /// [`write_async`] calls this.
25    ///
26    /// # Errors
27    ///
28    /// Whatever stops the sink taking a file of that length.
29    async fn begin(&mut self, _file_size: u32) -> Result<(), Self::Error> {
30        Ok(())
31    }
32
33    /// Writes all of `bytes`, or fails.
34    ///
35    /// # Errors
36    ///
37    /// Whatever the sink cannot write.
38    async fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error>;
39}
40
41impl<S: AsyncSink + ?Sized> AsyncSink for &mut S {
42    type Error = S::Error;
43
44    async fn begin(&mut self, file_size: u32) -> Result<(), S::Error> {
45        (**self).begin(file_size).await
46    }
47
48    async fn write(&mut self, bytes: &[u8]) -> Result<(), S::Error> {
49        (**self).write(bytes).await
50    }
51}
52
53/// An [`AsyncSink`] that can overwrite bytes it already took, for [`AsyncOnePass`], as
54/// [`PatchSink`](crate::PatchSink) has it.
55#[allow(async_fn_in_trait, reason = "a Send bound would shut out single-threaded executors")]
56pub trait AsyncPatchSink: AsyncSink {
57    /// Overwrites the bytes starting `back` bytes before the end of what was written, as
58    /// [`PatchSink::patch`](crate::PatchSink::patch) does.
59    ///
60    /// # Errors
61    ///
62    /// Whatever stops the sink rewriting them.
63    async fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), Self::Error>;
64}
65
66impl<S: AsyncPatchSink + ?Sized> AsyncPatchSink for &mut S {
67    async fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), S::Error> {
68        (**self).patch(back, bytes).await
69    }
70}
71
72/// The most beat intervals one call gives the writer: their `hrv` messages take less than a
73/// stage.
74const BEATS_AT_ONCE: usize = 100;
75
76/// A sink and the bytes staged for it.
77struct Staged<S: AsyncSink> {
78    sink: S,
79    stage: [u8; ASYNC_WRITE_LEN],
80    len: usize,
81    /// How much of `stage` is used; less only in tests.
82    cap: usize,
83    /// The error a call met, which the call could only report as [`Error::Sink`].
84    error: Option<S::Error>,
85    /// A write was dropped before it finished, so what the sink holds is unknown.
86    torn: bool,
87    /// The most bytes one call wrote on a copy of the state.
88    #[cfg(test)]
89    longest_spill: usize,
90}
91
92impl<S: AsyncSink> Staged<S> {
93    fn new(sink: S, header: &[u8; HEADER_LEN as usize]) -> Self {
94        let mut stage = [0; ASYNC_WRITE_LEN];
95        let mut window = Window::new(&mut stage, None);
96        window.write(header);
97        Self {
98            sink,
99            stage,
100            len: header.len(),
101            cap: ASYNC_WRITE_LEN,
102            error: None,
103            torn: false,
104            #[cfg(test)]
105            longest_spill: 0,
106        }
107    }
108
109    /// Writes what is staged.
110    async fn drain(&mut self) -> Result<(), S::Error> {
111        let len = core::mem::take(&mut self.len);
112        self.torn = true;
113        let written = match self.stage.get(..len) {
114            Some(bytes) if !bytes.is_empty() => self.sink.write(bytes).await,
115            _ => Ok(()),
116        };
117        self.torn = false;
118        written
119    }
120
121    /// Stages `bytes`, writing the stage each time it fills.
122    async fn put(&mut self, bytes: &[u8]) -> Result<(), S::Error> {
123        let room = self.stage.get_mut(self.len..self.cap).unwrap_or_default();
124        let (now, later) = bytes.split_at(room.len().min(bytes.len()));
125        room.get_mut(..now.len()).unwrap_or_default().copy_from_slice(now);
126        self.len = self.len.saturating_add(now.len());
127        self.drain_full().await?;
128        for chunk in later.chunks(self.cap.max(1)) {
129            self.stage.get_mut(..chunk.len()).unwrap_or_default().copy_from_slice(chunk);
130            self.len = chunk.len();
131            self.drain_full().await?;
132        }
133        Ok(())
134    }
135
136    /// Stages what `call` writes to `st`, writing the stage each time it fills, and returns
137    /// what it returned. A call that says its bytes fit what is left of the stage writes them
138    /// there; one that would spill past it writes nothing, and runs instead on a copy of `st`
139    /// for each stage its bytes fall in, keeping those, until the copy that wrote the last
140    /// becomes `st`.
141    async fn call<R>(
142        &mut self,
143        st: &mut State,
144        call: impl Fn(&mut Writer<'_>) -> R,
145    ) -> Result<R, S::Error> {
146        let room = self.stage.get_mut(self.len..self.cap).unwrap_or_default();
147        let mut window = Window::new(room, None);
148        let result = call(&mut Writer { out: &mut window, st });
149        if !window.refused {
150            self.len = self.len.saturating_add(window.kept);
151            self.drain_full().await?;
152            return Ok(result);
153        }
154        let (mut result, seen, mut done) = self.spill(st, &call, 0);
155        let rounds = seen.saturating_sub(done).div_ceil(self.cap.max(1));
156        for _ in 0..rounds {
157            self.drain().await?;
158            let (again, _, kept) = self.spill(st, &call, done);
159            (result, done) = (again, done.saturating_add(kept));
160        }
161        self.drain_full().await?;
162        Ok(result)
163    }
164
165    /// Runs `call` on a copy of `st`, staging its bytes from `skip` on as far as the stage
166    /// holds; the copy becomes `st` if they were its last. Returns what the call returned, the
167    /// bytes it wrote, and those staged.
168    fn spill<R>(
169        &mut self,
170        st: &mut State,
171        call: &impl Fn(&mut Writer<'_>) -> R,
172        skip: usize,
173    ) -> (R, usize, usize) {
174        let room = self.stage.get_mut(self.len..self.cap).unwrap_or_default();
175        let mut window = Window::new(room, Some(skip));
176        let mut copy = st.clone();
177        let result = call(&mut Writer { out: &mut window, st: &mut copy });
178        #[cfg(test)]
179        {
180            self.longest_spill = self.longest_spill.max(window.seen);
181        }
182        if skip.saturating_add(window.kept) >= window.seen {
183            *st = copy;
184        }
185        self.len = self.len.saturating_add(window.kept);
186        (result, window.seen, window.kept)
187    }
188
189    /// Writes the stage if it is full.
190    async fn drain_full(&mut self) -> Result<(), S::Error> {
191        if self.len >= self.cap {
192            self.drain().await?;
193        }
194        Ok(())
195    }
196}
197
198/// The bytes a call writes from `skip` on, as many as `room` holds. Without `skip`, the call
199/// must say they all fit, or it is refused.
200struct Window<'a> {
201    room: &'a mut [u8],
202    skip: Option<usize>,
203    /// The bytes the call has written, and those of them kept.
204    seen: usize,
205    kept: usize,
206    refused: bool,
207}
208
209impl<'a> Window<'a> {
210    fn new(room: &'a mut [u8], skip: Option<usize>) -> Self {
211        Self { room, skip, seen: 0, kept: 0, refused: false }
212    }
213}
214
215impl Out for Window<'_> {
216    fn write(&mut self, bytes: &[u8]) -> bool {
217        let from = self.skip.unwrap_or(0).saturating_sub(self.seen);
218        let src = bytes.get(from..).unwrap_or_default();
219        let dst = self.room.get_mut(self.kept..).unwrap_or_default();
220        let n = src.len().min(dst.len());
221        if let Some((dst, src)) = dst.get_mut(..n).zip(src.get(..n)) {
222            dst.copy_from_slice(src);
223        }
224        self.kept = self.kept.saturating_add(n);
225        self.seen = self.seen.saturating_add(bytes.len());
226        true
227    }
228
229    fn fits(&mut self, size: u32) -> bool {
230        let fits = usize::try_from(size)
231            .is_ok_and(|size| self.seen.saturating_add(size) <= self.room.len());
232        self.refused |= self.skip.is_none() && !fits;
233        !self.refused
234    }
235}
236
237/// Writes the messages of one file to an async sink, as [`Writer`] does to a sink.
238/// [`write_async`] hands one to the source, and [`AsyncOnePass::writer`] gives one, so a
239/// function taking a `&mut AsyncWriter` serves both.
240///
241/// A call returns once its bytes are staged and each stage they filled has gone to the sink, so
242/// the sink's error can surface as [`Error::Sink`] on a later call; [`write_async`] and
243/// [`AsyncOnePass::finish`] return it.
244pub struct AsyncWriter<'a, S: AsyncSink> {
245    st: &'a mut State,
246    /// `None` on [`write_async`]'s sizing pass.
247    staged: Option<&'a mut Staged<S>>,
248}
249
250impl<S: AsyncSink> fmt::Debug for AsyncWriter<'_, S> {
251    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252        f.debug_struct("AsyncWriter").field("written", &self.st.written).finish_non_exhaustive()
253    }
254}
255
256/// Each call of [`Writer`], made through the stage.
257macro_rules! calls {
258    (@ok) => { () };
259    (@ok $ok:ty) => { $ok };
260    ($(
261        $name:ident $([$($generics:tt)*])? ($($arg:ident: $ty:ty),*) $(-> $ok:ty)?;
262    )*) => {$(
263        #[doc = concat!("[`Writer::", stringify!($name), "`], awaiting the sink.")]
264        ///
265        /// # Errors
266        ///
267        #[doc = concat!("As [`Writer::", stringify!($name), "`].")]
268        pub async fn $name $(<$($generics)*>)? (
269            &mut self,
270            $($arg: $ty),*
271        ) -> Result<calls!(@ok $($ok)?), Error> {
272            self.call(|w| w.$name($($arg),*)).await
273        }
274    )*};
275}
276
277impl<S: AsyncSink> AsyncWriter<'_, S> {
278    calls! {
279        start(t: Timestamp, creator: &Device<'_>);
280        device(device: &Device<'_>);
281        session(t: Timestamp, sport: Sport, sub_sport: SubSport);
282        pool_swim(t: Timestamp, pool: Pool);
283        leg(t: Timestamp, leg: &Leg<'_>);
284        record(record: &Record);
285        record_with(record: &Record, extras: &[Extra<'_>]);
286        lap(t: Timestamp);
287        lap_by(t: Timestamp, trigger: LapTrigger);
288        pause(t: Timestamp);
289        resume(t: Timestamp);
290        length(t: Timestamp, length: &Length);
291        set(t: Timestamp, set: &Set);
292        rest(t: Timestamp);
293        end_rest(t: Timestamp);
294        developer(developer: &Developer) -> Dev;
295        declare[T: DevType + ?Sized, K: Kind](
296            description: &FieldDescription<'_, T, K>
297        ) -> DevField<T, K>;
298        developer_value[T: DevType + ?Sized, K: Summary](
299            field: &DevField<T, K>,
300            value: T::Value<'_>
301        );
302        raw_message(global: u16, fields: &[RawField<'_>]);
303        end(t: Timestamp);
304    }
305
306    /// [`Writer::beat_intervals_ms`], awaiting the sink.
307    ///
308    /// # Errors
309    ///
310    /// As [`Writer::beat_intervals_ms`].
311    pub async fn beat_intervals_ms(&mut self, intervals: &[u16]) -> Result<(), Error> {
312        self.beats(intervals, true).await
313    }
314
315    /// [`Writer::beat_intervals_1024ths`], awaiting the sink.
316    ///
317    /// # Errors
318    ///
319    /// As [`Writer::beat_intervals_1024ths`].
320    pub async fn beat_intervals_1024ths(&mut self, intervals: &[u16]) -> Result<(), Error> {
321        self.beats(intervals, false).await
322    }
323
324    /// Refuses `intervals` whole, as the writer does, then gives them a few at a time, so no
325    /// call spills past more than a stage or two; they make the same bytes, as they are written
326    /// five at a time whatever the calls.
327    async fn beats(&mut self, intervals: &[u16], ms: bool) -> Result<(), Error> {
328        self.call(|w| w.beats_fit(intervals, ms)).await?;
329        for part in intervals.chunks(BEATS_AT_ONCE) {
330            self.call(
331                |w| {
332                    if ms {
333                        w.beat_intervals_ms(part)
334                    } else {
335                        w.beat_intervals_1024ths(part)
336                    }
337                },
338            )
339            .await?;
340        }
341        Ok(())
342    }
343
344    /// Makes a call of [`Writer`] through the stage.
345    async fn call<R>(
346        &mut self,
347        f: impl Fn(&mut Writer<'_>) -> Result<R, Error>,
348    ) -> Result<R, Error> {
349        let Some(staged) = self.staged.as_deref_mut() else {
350            return f(&mut Writer { out: &mut Counter, st: self.st });
351        };
352        if staged.torn {
353            return Err(Error::Sink);
354        }
355        match staged.call(self.st, f).await {
356            Ok(result) => result,
357            Err(e) => {
358                staged.error = Some(e);
359                self.st.failed = true;
360                Err(Error::Sink)
361            }
362        }
363    }
364}
365
366/// Writes the file `source` describes to an async `sink`, as [`write()`](crate::write) does to a
367/// sink: header first and CRC last, without seeking, the source run twice.
368///
369/// ```
370/// use fit_encoder::*;
371///
372/// struct Uart;
373/// impl AsyncSink for Uart {
374///     type Error = ();
375///     async fn write(&mut self, bytes: &[u8]) -> Result<(), ()> {
376///         Ok(()) // Await the UART here.
377///     }
378/// }
379///
380/// async fn send(start: Timestamp, hr: &[u8]) -> Result<(), WriteError<(), Error>> {
381///     write_async(Uart, Options::new(), async |w| {
382///         w.start(start, &Device::new(Manufacturer::DEVELOPMENT, 1)).await?;
383///         w.session(start, Sport::RUNNING, SubSport::TREADMILL).await?;
384///         for (s, &bpm) in (0..).zip(hr) {
385///             w.record(&Record::new(start.checked_add(s).unwrap()).heart_rate(bpm)).await?;
386///         }
387///         w.end(start.checked_add(60).unwrap()).await
388///     })
389///     .await?;
390///     Ok(())
391/// }
392/// # let _ = send;
393/// ```
394///
395/// # Errors
396///
397/// As [`write()`](crate::write)'s.
398pub async fn write_async<S, E, F>(
399    sink: S,
400    options: Options,
401    mut source: F,
402) -> Result<S, WriteError<S::Error, E>>
403where
404    S: AsyncSink,
405    E: From<Error>,
406    F: AsyncFnMut(&mut AsyncWriter<'_, S>) -> Result<(), E>,
407{
408    let mut st = State::new(options, None);
409    source(&mut AsyncWriter { st: &mut st, staged: None }).await.map_err(WriteError::Source)?;
410    let plan = st.plan().map_err(|e| WriteError::Source(E::from(e)))?;
411
412    let mut sink = sink;
413    sink.begin(plan.file_size).await.map_err(WriteError::Sink)?;
414    let header = header(options, plan.data_size);
415    let mut staged = Staged::new(sink, &header);
416    let mut st = State::new(options, Some(plan));
417    let mut w = AsyncWriter { st: &mut st, staged: Some(&mut staged) };
418    let result = source(&mut w).await;
419    #[allow(clippy::redundant_closure_for_method_calls, reason = "the path is not higher-ranked")]
420    let end = w.call(|w| w.close()).await;
421    if let Some(e) = staged.error.take() {
422        return Err(WriteError::Sink(e));
423    }
424    result.map_err(WriteError::Source)?;
425    end.map_err(|e| WriteError::Source(E::from(e)))?;
426    let crc = super::file_crc(&header, &st);
427    staged.put(&crc).await.map_err(WriteError::Sink)?;
428    staged.drain().await.map_err(WriteError::Sink)?;
429    Ok(staged.sink)
430}
431
432/// Writes a file to an async sink as its messages arrive, as [`OnePass`](crate::OnePass) does
433/// to a sink.
434///
435/// ```
436/// use fit_encoder::*;
437///
438/// async fn record(sink: impl AsyncPatchSink, start: Timestamp) -> Result<(), Error> {
439///     let mut file = AsyncOnePass::new(sink, Options::new());
440///     let mut w = file.writer();
441///     w.start(start, &Device::new(Manufacturer::DEVELOPMENT, 1)).await?;
442///     w.session(start, Sport::WALKING, SubSport::GENERIC).await?;
443///     w.record(&Record::new(start).heart_rate(100)).await?;
444///     w.end(start.checked_add(1).unwrap()).await?;
445///     file.finish().await.map_err(|_| Error::Sink)?;
446///     Ok(())
447/// }
448/// ```
449pub struct AsyncOnePass<S: AsyncPatchSink> {
450    staged: Staged<S>,
451    st: State,
452}
453
454impl<S: AsyncPatchSink> fmt::Debug for AsyncOnePass<S> {
455    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
456        f.debug_struct("AsyncOnePass").field("written", &self.st.written).finish_non_exhaustive()
457    }
458}
459
460impl<S: AsyncPatchSink> AsyncOnePass<S> {
461    /// Stages the header, its length to come.
462    pub fn new(sink: S, options: Options) -> Self {
463        Self { staged: Staged::new(sink, &header(options, 0)), st: State::new(options, None) }
464    }
465
466    /// The writer for the next messages.
467    pub fn writer(&mut self) -> AsyncWriter<'_, S> {
468        AsyncWriter { st: &mut self.st, staged: Some(&mut self.staged) }
469    }
470
471    /// Writes the file CRC and patches the header's length in, as
472    /// [`OnePass::finish`](crate::OnePass::finish) does.
473    ///
474    /// # Errors
475    ///
476    /// As [`OnePass::finish`](crate::OnePass::finish)'s.
477    #[allow(clippy::result_large_err, reason = "the error holds the file, to finish again")]
478    pub async fn finish(mut self) -> Result<S, FinishError<Self, S::Error>> {
479        match self.try_finish().await {
480            Ok(()) => Ok(self.staged.sink),
481            Err(error) => Err(FinishError { error, file: self }),
482        }
483    }
484
485    /// The sink, giving up on the file: its header still claims no messages, so readers
486    /// refuse it, and what was staged is never written.
487    pub fn into_sink(self) -> S {
488        self.staged.sink
489    }
490
491    async fn try_finish(&mut self) -> Result<(), WriteError<S::Error, Error>> {
492        #[allow(
493            clippy::redundant_closure_for_method_calls,
494            reason = "the path is not higher-ranked"
495        )]
496        let ended = self.writer().call(|w| w.close()).await;
497        if let Some(e) = self.staged.error.take() {
498            return Err(WriteError::Sink(e));
499        }
500        ended.map_err(WriteError::Source)?;
501        let (header, back, crc) = self.st.trailer().map_err(WriteError::Source)?;
502        // The CRC goes first, so a file it fails on keeps a header claiming no messages.
503        let staged = &mut self.staged;
504        let written = match staged.put(&crc).await {
505            Ok(()) => match staged.drain().await {
506                Ok(()) => staged.sink.patch(back, &header).await,
507                Err(e) => Err(e),
508            },
509            Err(e) => Err(e),
510        };
511        written.map_err(|e| {
512            self.st.failed = true;
513            WriteError::Sink(e)
514        })
515    }
516}
517
518#[cfg(test)]
519mod tests;