Skip to main content

fit_encoder/
encoder.rs

1use core::fmt;
2
3use crate::crc::Crc;
4use crate::developer::{Extra, KindId};
5use crate::messages::{
6    data_len, kept, record_fields, Activity, DeviceInfo, Event, FieldDef, FieldError, FieldOut,
7    Fields, FileId, Lap, Mask, Message, Put, Record, RecordFields, Session, RECORD_GLOBAL,
8    RECORD_TIMESTAMP,
9};
10use crate::types::Timestamp;
11use extra::Extras;
12
13const HEADER_LEN: u8 = 14;
14/// The header and the file CRC: what a file holds besides its messages.
15const FRAMING: u32 = HEADER_LEN as u32 + 2;
16/// The most bytes of messages a file can hold: its length must fit the header's u32.
17const LIMIT: u32 = u32::MAX - FRAMING;
18const PROTOCOL_VERSION: u8 = 0x20;
19
20/// Where a file's bytes go. With the `embedded-io` feature, `EmbeddedIo` makes one of an
21/// `embedded_io::Write`.
22pub trait Sink {
23    /// Why a write failed.
24    type Error;
25
26    /// The whole file's length, for a sink that announces it, such as a transfer over a radio
27    /// link. Only [`write()`] knows it in advance and calls this, once, before the first byte;
28    /// [`OnePass`] never does.
29    ///
30    /// # Errors
31    ///
32    /// Whatever stops the sink taking a file of that length.
33    fn begin(&mut self, _file_size: u32) -> Result<(), Self::Error> {
34        Ok(())
35    }
36
37    /// Writes all of `bytes`, or fails.
38    ///
39    /// # Errors
40    ///
41    /// Whatever the sink cannot write.
42    fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error>;
43}
44
45impl<S: Sink + ?Sized> Sink for &mut S {
46    type Error = S::Error;
47
48    fn begin(&mut self, file_size: u32) -> Result<(), S::Error> {
49        (**self).begin(file_size)
50    }
51
52    fn write(&mut self, bytes: &[u8]) -> Result<(), S::Error> {
53        (**self).write(bytes)
54    }
55}
56
57/// A [`Sink`] that can overwrite bytes it already took, for [`OnePass`]: a file, or memory.
58pub trait PatchSink: Sink {
59    /// Overwrites the bytes starting `back` bytes before the end of what was written. A call
60    /// that would reach before the start or past the end must change nothing, and fails if
61    /// the sink's error can say so; [`OnePass`] never makes one.
62    ///
63    /// # Errors
64    ///
65    /// Whatever stops the sink rewriting them.
66    fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), Self::Error>;
67}
68
69impl<S: PatchSink + ?Sized> PatchSink for &mut S {
70    fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), S::Error> {
71        (**self).patch(back, bytes)
72    }
73}
74
75/// A closure as a [`Sink`].
76///
77/// ```
78/// use fit_encoder::{FnSink, Sink};
79///
80/// let mut seen = 0;
81/// let mut sink = FnSink(|bytes: &[u8]| -> Result<(), ()> {
82///     seen += bytes.len();
83///     Ok(())
84/// });
85/// sink.write(b"abc").unwrap();
86/// drop(sink);
87/// assert_eq!(seen, 3);
88/// ```
89pub struct FnSink<F>(pub F);
90
91impl<F> fmt::Debug for FnSink<F> {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        f.debug_tuple("FnSink").finish_non_exhaustive()
94    }
95}
96
97impl<F: FnMut(&[u8]) -> Result<(), E>, E> Sink for FnSink<F> {
98    type Error = E;
99
100    fn write(&mut self, bytes: &[u8]) -> Result<(), E> {
101        (self.0)(bytes)
102    }
103}
104
105/// A [`Sink`] into a byte slice.
106#[derive(Debug)]
107pub struct SliceSink<'a> {
108    buf: &'a mut [u8],
109    len: usize,
110}
111
112/// A [`SliceSink`] had no room for the file, or was asked to patch outside what it holds.
113#[derive(Clone, Copy, Debug, PartialEq, Eq)]
114pub struct Full;
115
116impl fmt::Display for Full {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.write_str("no room in the slice, or a patch outside what it holds")
119    }
120}
121
122impl core::error::Error for Full {}
123
124impl<'a> SliceSink<'a> {
125    /// Writes into `buf` from its start.
126    pub fn new(buf: &'a mut [u8]) -> Self {
127        Self { buf, len: 0 }
128    }
129
130    /// The bytes written so far.
131    #[must_use]
132    pub fn written(&self) -> &[u8] {
133        self.buf.get(..self.len).unwrap_or(&[])
134    }
135}
136
137impl Sink for SliceSink<'_> {
138    type Error = Full;
139
140    fn begin(&mut self, file_size: u32) -> Result<(), Full> {
141        let room = self.buf.len().saturating_sub(self.len);
142        if usize::try_from(file_size).map_or(true, |n| n > room) {
143            return Err(Full);
144        }
145        Ok(())
146    }
147
148    fn write(&mut self, bytes: &[u8]) -> Result<(), Full> {
149        let end = self.len.checked_add(bytes.len()).ok_or(Full)?;
150        let dst = self.buf.get_mut(self.len..end).ok_or(Full)?;
151        dst.copy_from_slice(bytes);
152        self.len = end;
153        Ok(())
154    }
155}
156
157impl PatchSink for SliceSink<'_> {
158    fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), Full> {
159        let start = usize::try_from(back).ok().and_then(|b| self.len.checked_sub(b)).ok_or(Full)?;
160        let end = start.checked_add(bytes.len()).filter(|&e| e <= self.len).ok_or(Full)?;
161        self.buf.get_mut(start..end).ok_or(Full)?.copy_from_slice(bytes);
162        Ok(())
163    }
164}
165
166/// A `std::io::Write` as a [`Sink`], and with `Seek` a [`PatchSink`].
167#[cfg(feature = "std")]
168#[derive(Debug)]
169pub struct IoSink<W>(pub W);
170
171#[cfg(feature = "std")]
172impl<W: std::io::Write> Sink for IoSink<W> {
173    type Error = std::io::Error;
174
175    fn write(&mut self, bytes: &[u8]) -> std::io::Result<()> {
176        self.0.write_all(bytes)
177    }
178}
179
180#[cfg(feature = "std")]
181impl<W: std::io::Write + std::io::Seek> PatchSink for IoSink<W> {
182    fn patch(&mut self, back: u32, bytes: &[u8]) -> std::io::Result<()> {
183        use std::io::{Error, ErrorKind, SeekFrom};
184        let len = u32::try_from(bytes.len())
185            .ok()
186            .filter(|&n| n <= back)
187            .ok_or_else(|| Error::from(ErrorKind::InvalidInput))?;
188        let start = self.0.seek(SeekFrom::Current(0i64.saturating_sub(i64::from(back))))?;
189        self.0.write_all(bytes)?;
190        // A file opened to append writes at its end whatever the position.
191        if self.0.stream_position()? != start.saturating_add(u64::from(len)) {
192            return Err(Error::from(ErrorKind::Unsupported));
193        }
194        self.0.seek(SeekFrom::Current(i64::from(back.saturating_sub(len))))?;
195        Ok(())
196    }
197}
198
199/// A [`PatchSink`] that appends to a `Vec<u8>`; for a whole file at once, [`to_vec`] is
200/// shorter.
201///
202/// ```
203/// use fit_encoder::*;
204///
205/// let t = Timestamp::FIRST_DATE;
206/// let mut file = OnePass::new(VecSink::default(), Options::new()).unwrap();
207/// let mut w = file.writer();
208/// w.start(t, &Device::new(Manufacturer::DEVELOPMENT, 1)).unwrap();
209/// w.session(t, Sport::RUNNING, SubSport::GENERIC).unwrap();
210/// w.record(&Record::new(t).heart_rate(60)).unwrap();
211/// w.end(t).unwrap();
212/// let VecSink(bytes) = file.finish().unwrap();
213/// assert_eq!(&bytes[8..12], b".FIT");
214/// ```
215#[cfg(feature = "alloc")]
216#[derive(Clone, Debug, Default, PartialEq, Eq)]
217pub struct VecSink(pub alloc::vec::Vec<u8>);
218
219#[cfg(feature = "alloc")]
220impl Sink for VecSink {
221    type Error = core::convert::Infallible;
222
223    fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
224        self.0.extend_from_slice(bytes);
225        Ok(())
226    }
227}
228
229#[cfg(feature = "alloc")]
230impl PatchSink for VecSink {
231    fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), Self::Error> {
232        let len = self.0.len();
233        let start = usize::try_from(back).ok().and_then(|b| len.checked_sub(b));
234        let end = start.and_then(|s| s.checked_add(bytes.len())).filter(|&e| e <= len);
235        if let Some(dst) = start.zip(end).and_then(|(s, e)| self.0.get_mut(s..e)) {
236            dst.copy_from_slice(bytes);
237        }
238        Ok(())
239    }
240}
241
242/// Why a message was not written.
243#[derive(Clone, Copy, Debug, PartialEq, Eq)]
244#[non_exhaustive]
245pub enum Error {
246    /// The sink failed; [`write()`] returns its error. Nothing more can be written.
247    Sink,
248    /// The source wrote different messages the second time from those the first pass sized
249    /// the file for. Nothing of the message was written.
250    SourceChanged,
251    /// The file would be 4 GiB or more, counting the bytes kept for the activity's end.
252    /// Nothing was written.
253    TooLarge,
254    /// A string is too long for its field. Nothing of the message was written.
255    StringTooLong,
256    /// A value does not fit its field, or is the value FIT reserves for "none", such as a
257    /// heart rate of 255, or a string holds a NUL; a time past [`DURATION_SECONDS_MAX`] or a
258    /// distance past [`DISTANCE_METERS_MAX`] as the field keeps it; or a leg
259    /// [`Leg::check`](crate::Leg::check) refuses. Nothing of the message was written.
260    OutOfRange,
261    /// A lap, session, length, set or sensor past its limit, such as [`LAPS_MAX`]: its index
262    /// has no value left for it.
263    IndexFull,
264    /// A call the activity is not ready for: anything before [`Writer::start`] or after
265    /// [`Writer::end`], a record, lap, set, rest, pause or resume before the first session, a
266    /// pause while paused, a resume while running, an end with no session, a length outside a
267    /// pool swim, a set outside a training or HIIT session, a rest outside those and pool swims,
268    /// a length or set during a rest, a lap during a rest in a pool swim, a rest during a rest,
269    /// an end of a rest outside one, or a first leg moved to by hand. Nothing was written.
270    OutOfOrder,
271    /// A time before one already written. Nothing was written.
272    TimeWentBack,
273    /// A record, length or set while the timer is paused. Nothing was written.
274    Paused,
275    /// A total distance less than one already written. Nothing was written.
276    DistanceWentBack,
277    /// The source returned without [`Writer::end`], so the file has no activity.
278    Unfinished,
279    /// A record's distance, speed or cadence in a pool swim, whose lengths give them. Nothing
280    /// was written.
281    GivenByLengths,
282    /// A developer or field this file did not declare: one from another file, or one the
283    /// second pass did not declare again. Nothing was written.
284    Undeclared,
285    /// A developer, field or value given twice where it may appear once. Nothing was written.
286    Duplicate,
287    /// A raw message or field the encoder writes itself, or another form of one; see
288    /// [`Writer::raw_message`] and [`Writer::record_with`]. Nothing was written.
289    Reserved,
290    /// More developers or fields than the encoder holds; see
291    /// [`DEVELOPERS_MAX`](crate::DEVELOPERS_MAX) and its neighbours. Nothing was written.
292    TooMany,
293}
294
295impl fmt::Display for Error {
296    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
297        f.write_str(match self {
298            Self::Sink => "the sink failed",
299            Self::SourceChanged => "the source wrote different messages on the second pass",
300            Self::TooLarge => "the file would be 4 GiB or more",
301            Self::StringTooLong => "string longer than its field",
302            Self::OutOfRange => "value out of its field's range",
303            Self::IndexFull => "no message_index left for another lap or session",
304            Self::OutOfOrder => "the activity is not ready for that call",
305            Self::TimeWentBack => "a time before one already written",
306            Self::Paused => "a record, length or set while the timer is paused",
307            Self::DistanceWentBack => "a total distance less than one already written",
308            Self::Unfinished => "the activity was not ended",
309            Self::GivenByLengths => "a distance, speed or cadence that a pool swim's lengths give",
310            Self::Undeclared => "a developer or field this file did not declare",
311            Self::Duplicate => "given twice",
312            Self::Reserved => "a message or field the encoder writes itself",
313            Self::TooMany => "more developers or fields than the encoder holds",
314        })
315    }
316}
317
318impl core::error::Error for Error {}
319
320/// Why [`write()`] failed. The sink may hold part of a file.
321///
322/// As an error, `Sink` says the sink failed and gives the sink's error as its source, and
323/// `Source` stands for the source's error itself, so a report of the chain names each cause
324/// once. A sink error that is not an `Error` is only in the variant.
325#[derive(Clone, Copy, Debug, PartialEq, Eq)]
326pub enum WriteError<S, E> {
327    /// The sink's own error.
328    Sink(S),
329    /// The source's error, or an encoder [`Error`] the source passed on.
330    Source(E),
331}
332
333impl<S, E: fmt::Display> fmt::Display for WriteError<S, E> {
334    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335        match self {
336            Self::Sink(_) => f.write_str("the sink failed"),
337            Self::Source(e) => e.fmt(f),
338        }
339    }
340}
341
342impl<S, E> core::error::Error for WriteError<S, E>
343where
344    S: core::error::Error + 'static,
345    E: core::error::Error + 'static,
346{
347    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
348        match self {
349            Self::Sink(e) => Some(e),
350            Self::Source(e) => e.source(),
351        }
352    }
353}
354
355/// How a file is written.
356#[derive(Clone, Copy, Debug, PartialEq, Eq)]
357pub struct Options {
358    compressed_timestamps: bool,
359    profile_version: u16,
360    utc_offset: Option<i32>,
361    auto_multisport: bool,
362}
363
364impl Options {
365    /// Normal record headers, profile version 21.00, no time zone, sessions started by hand.
366    #[must_use]
367    pub const fn new() -> Self {
368        Self {
369            compressed_timestamps: false,
370            profile_version: 2100,
371            utc_offset: None,
372            auto_multisport: false,
373        }
374    }
375
376    /// Whether a multisport profile moved the activity from each session to the next, as a
377    /// watch's triathlon mode does, rather than its user. The activity's `type` and each
378    /// session's `trigger` say which; the last session's trigger is the activity's end.
379    #[must_use]
380    pub const fn auto_multisport(mut self, on: bool) -> Self {
381        self.auto_multisport = on;
382        self
383    }
384
385    /// Whether records less than 32 s after the previous timestamp put their time in the
386    /// record header (FIT Protocol page, "Compressed Timestamp Header"). Off by default, as
387    /// some readers refuse such headers.
388    #[must_use]
389    pub const fn compressed_timestamps(mut self, on: bool) -> Self {
390        self.compressed_timestamps = on;
391        self
392    }
393
394    /// The local time zone's offset from UTC in seconds, so readers can show the activity's
395    /// local times. One that takes the end's local time out of range is refused.
396    #[must_use]
397    pub const fn utc_offset(mut self, seconds: i32) -> Self {
398        self.utc_offset = Some(seconds);
399        self
400    }
401
402    /// The profile version the header claims, as the header holds it: 2100 is 21.00.
403    #[must_use]
404    pub const fn profile_version(mut self, version: u16) -> Self {
405        self.profile_version = version;
406        self
407    }
408}
409
410impl Default for Options {
411    fn default() -> Self {
412        Self::new()
413    }
414}
415
416/// The whole file's length in bytes, from a pass over `source` that writes nothing.
417///
418/// # Errors
419///
420/// The source's error, or [`Error::TooLarge`].
421pub fn size<E, F>(options: Options, mut source: F) -> Result<u32, E>
422where
423    E: From<Error>,
424    F: FnMut(&mut Writer<'_>) -> Result<(), E>,
425{
426    Ok(plan(options, &mut source, true)?.file_size)
427}
428
429/// Writes the file `source` describes to `sink`, header first and CRC last, without seeking.
430///
431/// The header holds the length of what follows, so `source` runs twice: once to size the file,
432/// then to write it. It must write the same messages both times, as a source reading a stored
433/// log does; if it does not, the second pass fails with [`Error::SourceChanged`].
434///
435/// ```
436/// use fit_encoder::*;
437///
438/// let start = Timestamp::from_unix(1_764_547_200).unwrap();
439/// let watch = Device::new(Manufacturer::DEVELOPMENT, 1).product_name("My watch");
440/// let mut buf = [0u8; 2048];
441/// let sink = write(SliceSink::new(&mut buf), Options::new(), |w| -> Result<(), Error> {
442///     w.start(start, &watch)?;
443///     w.session(start, Sport::RUNNING, SubSport::TREADMILL)?;
444///     for s in 0..60 {
445///         w.record(&Record::new(start.checked_add(s).unwrap()).heart_rate(140))?;
446///     }
447///     w.end(start.checked_add(60).unwrap())
448/// })
449/// .unwrap();
450/// assert_eq!(&sink.written()[8..12], b".FIT");
451/// ```
452///
453/// # Errors
454///
455/// [`WriteError::Sink`] with the sink's error, or [`WriteError::Source`] with the source's,
456/// which includes the [`Error`]s it passed on.
457pub fn write<S, E, F>(sink: S, options: Options, source: F) -> Result<S, WriteError<S::Error, E>>
458where
459    S: Sink,
460    E: From<Error>,
461    F: FnMut(&mut Writer<'_>) -> Result<(), E>,
462{
463    write_with(sink, options, source, true)
464}
465
466/// [`write()`], with or without an activity ended.
467fn write_with<S, E, F>(
468    sink: S,
469    options: Options,
470    mut source: F,
471    require_end: bool,
472) -> Result<S, WriteError<S::Error, E>>
473where
474    S: Sink,
475    E: From<Error>,
476    F: FnMut(&mut Writer<'_>) -> Result<(), E>,
477{
478    let plan = plan(options, &mut source, require_end).map_err(WriteError::Source)?;
479    let mut out = SinkOut { sink, error: None };
480    out.sink.begin(plan.file_size).map_err(WriteError::Sink)?;
481    let header = header(options, plan.data_size);
482    out.sink.write(&header).map_err(WriteError::Sink)?;
483
484    let mut st = State::new(options, Some(plan));
485    st.require_end = require_end;
486    let result = source(&mut Writer { out: &mut out, st: &mut st });
487    let end = Writer { out: &mut out, st: &mut st }.close();
488    if let Some(e) = out.error.take() {
489        return Err(WriteError::Sink(e));
490    }
491    result.map_err(WriteError::Source)?;
492    end.map_err(|e| WriteError::Source(E::from(e)))?;
493    out.sink.write(&file_crc(&header, &st)).map_err(WriteError::Sink)?;
494    Ok(out.sink)
495}
496
497/// Writes a file as its messages arrive, in one pass: the header goes first with no length,
498/// and [`OnePass::finish`] patches the length in. For sources that cannot run twice, such as a
499/// live recording or a conversion read once; the bytes are those [`write()`] would write.
500///
501/// ```
502/// use fit_encoder::*;
503///
504/// let start = Timestamp::from_unix(1_764_547_200).unwrap();
505/// let mut buf = [0u8; 2048];
506/// let mut file = OnePass::new(SliceSink::new(&mut buf), Options::new()).unwrap();
507/// let mut w = file.writer();
508/// w.start(start, &Device::new(Manufacturer::DEVELOPMENT, 1)).unwrap();
509/// w.session(start, Sport::WALKING, SubSport::GENERIC).unwrap();
510/// for s in 0..10 {
511///     w.record(&Record::new(start.checked_add(s).unwrap()).heart_rate(100)).unwrap();
512/// }
513/// w.end(start.checked_add(10).unwrap()).unwrap();
514/// let sink = file.finish().unwrap();
515/// assert_eq!(&sink.written()[8..12], b".FIT");
516/// ```
517pub struct OnePass<S: PatchSink> {
518    out: SinkOut<S>,
519    st: State,
520}
521
522impl<S: PatchSink> fmt::Debug for OnePass<S> {
523    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
524        f.debug_struct("OnePass").field("written", &self.st.written).finish_non_exhaustive()
525    }
526}
527
528impl<S: PatchSink> OnePass<S> {
529    /// Writes the header, its length to come.
530    ///
531    /// # Errors
532    ///
533    /// The sink's.
534    pub fn new(mut sink: S, options: Options) -> Result<Self, S::Error> {
535        sink.write(&header(options, 0))?;
536        Ok(Self { out: SinkOut { sink, error: None }, st: State::new(options, None) })
537    }
538
539    /// The writer for the next messages.
540    pub fn writer(&mut self) -> Writer<'_> {
541        Writer { out: &mut self.out, st: &mut self.st }
542    }
543
544    /// Patches the header's length in and writes the file CRC. On failure the file comes back
545    /// with the error, so an activity not yet ended can be ended and finished again; after a
546    /// sink error, finishing fails again.
547    ///
548    /// # Errors
549    ///
550    /// [`WriteError::Sink`] with the sink's error, including one a message met, or
551    /// [`WriteError::Source`] with [`Error::Unfinished`] if the activity was not ended.
552    #[allow(clippy::result_large_err, reason = "the error holds the file, to finish again")]
553    pub fn finish(mut self) -> Result<S, FinishError<Self, S::Error>> {
554        match self.try_finish() {
555            Ok(()) => Ok(self.out.sink),
556            Err(error) => Err(FinishError { error, file: self }),
557        }
558    }
559
560    /// The sink, giving up on the file: its header still claims no messages, so readers
561    /// refuse it.
562    pub fn into_sink(self) -> S {
563        self.out.sink
564    }
565
566    fn try_finish(&mut self) -> Result<(), WriteError<S::Error, Error>> {
567        let ended = Writer { out: &mut self.out, st: &mut self.st }.close();
568        if let Some(e) = self.out.error.take() {
569            return Err(WriteError::Sink(e));
570        }
571        ended.map_err(WriteError::Source)?;
572        let (header, back, crc) = self.st.trailer().map_err(WriteError::Source)?;
573        // The CRC goes first, so a file it fails on keeps a header claiming no messages.
574        let written = self.out.sink.write(&crc).and_then(|()| self.out.sink.patch(back, &header));
575        written.map_err(|e| {
576            self.st.failed = true;
577            WriteError::Sink(e)
578        })
579    }
580}
581
582/// Finishing failed, with the sink's error type `E`; the file `F` is here to end and finish
583/// again, or to give up on.
584pub struct FinishError<F, E> {
585    error: WriteError<E, Error>,
586    file: F,
587}
588
589impl<F, E> FinishError<F, E> {
590    /// Why it failed.
591    pub const fn error(&self) -> &WriteError<E, Error> {
592        &self.error
593    }
594
595    /// The file, as it was.
596    pub fn into_inner(self) -> F {
597        self.file
598    }
599
600    /// Why it failed, and the file.
601    pub fn into_parts(self) -> (WriteError<E, Error>, F) {
602        (self.error, self.file)
603    }
604}
605
606impl<F, E: fmt::Debug> fmt::Debug for FinishError<F, E> {
607    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
608        f.debug_struct("FinishError").field("error", &self.error).finish_non_exhaustive()
609    }
610}
611
612impl<F, E> fmt::Display for FinishError<F, E> {
613    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
614        self.error.fmt(f)
615    }
616}
617
618impl<F, E: core::error::Error + 'static> core::error::Error for FinishError<F, E> {
619    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
620        self.error.source()
621    }
622}
623
624/// The file `source` describes, in memory, in one pass.
625///
626/// # Errors
627///
628/// The source's error, or an encoder [`Error`] it passed on.
629#[cfg(feature = "alloc")]
630pub fn to_vec<E, F>(options: Options, source: F) -> Result<alloc::vec::Vec<u8>, E>
631where
632    E: From<Error>,
633    F: FnOnce(&mut Writer<'_>) -> Result<(), E>,
634{
635    let Ok(mut file) = OnePass::new(VecSink::default(), options);
636    source(&mut file.writer())?;
637    match file.finish().map_err(FinishError::into_parts) {
638        Ok(VecSink(bytes)) => Ok(bytes),
639        Err((WriteError::Source(e), _)) => Err(E::from(e)),
640        Err((WriteError::Sink(never), _)) => match never {},
641    }
642}
643
644/// What the first pass learned.
645#[derive(Clone, Copy, Debug, PartialEq, Eq)]
646struct Plan {
647    data_size: u32,
648    file_size: u32,
649    data_crc: u16,
650}
651
652fn plan<E, F>(options: Options, source: &mut F, require_end: bool) -> Result<Plan, E>
653where
654    E: From<Error>,
655    F: FnMut(&mut Writer<'_>) -> Result<(), E>,
656{
657    let mut st = State::new(options, None);
658    st.require_end = require_end;
659    source(&mut Writer { out: &mut Counter, st: &mut st })?;
660    Ok(st.plan()?)
661}
662
663fn file_crc(header: &[u8], st: &State) -> [u8; 2] {
664    let mut crc = Crc::new();
665    crc.update(header);
666    crc.then(st.data_crc, st.written).value().to_le_bytes()
667}
668
669fn header(options: Options, data_size: u32) -> [u8; HEADER_LEN as usize] {
670    let mut h = [0u8; HEADER_LEN as usize];
671    let [h0, h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11, h12, h13] = &mut h;
672    *h0 = HEADER_LEN;
673    *h1 = PROTOCOL_VERSION;
674    [*h2, *h3] = options.profile_version.to_le_bytes();
675    [*h4, *h5, *h6, *h7] = data_size.to_le_bytes();
676    [*h8, *h9, *h10, *h11] = *b".FIT";
677    let mut crc = Crc::new();
678    crc.update(&[*h0, *h1, *h2, *h3, *h4, *h5, *h6, *h7, *h8, *h9, *h10, *h11]);
679    [*h12, *h13] = crc.value().to_le_bytes();
680    h
681}
682
683trait Out {
684    /// Whether the bytes were written.
685    fn write(&mut self, bytes: &[u8]) -> bool;
686
687    /// Whether a call may go on to write `size` more bytes. Every call asks before it writes
688    /// or changes anything, so one refused can be made again elsewhere.
689    fn fits(&mut self, _size: u32) -> bool {
690        true
691    }
692}
693
694struct Counter;
695
696impl Out for Counter {
697    fn write(&mut self, _: &[u8]) -> bool {
698        true
699    }
700}
701
702struct SinkOut<S: Sink> {
703    sink: S,
704    error: Option<S::Error>,
705}
706
707impl<S: Sink> Out for SinkOut<S> {
708    fn write(&mut self, bytes: &[u8]) -> bool {
709        match self.sink.write(bytes) {
710            Ok(()) => true,
711            Err(e) => {
712                self.error = Some(e);
713                false
714            }
715        }
716    }
717}
718
719/// A local message type's layout: which global message, with which fields.
720#[derive(Clone, Copy, Debug, PartialEq, Eq)]
721struct Layout {
722    global: u16,
723    shape: Shape,
724    /// Raw fields, after the modelled ones.
725    raw: extra::RawDefs,
726    /// The developer fields, by their places among the file's.
727    dev: u32,
728}
729
730/// The fields of a layout that the crate models.
731#[derive(Clone, Copy, Debug, PartialEq, Eq)]
732enum Shape {
733    Message { fields: &'static [FieldDef], keep: Mask },
734    Record { fields: RecordFields, compressed: bool },
735}
736
737/// The local message types and the layout each holds; records take 0 to 3, which compressed
738/// timestamp headers can name.
739#[derive(Clone, Debug)]
740struct Locals {
741    held: [Option<(Layout, u32)>; 16],
742    clock: u32,
743}
744
745impl Locals {
746    const fn new() -> Self {
747        Self { held: [None; 16], clock: 0 }
748    }
749
750    /// The local type for `layout`, and whether it needs a definition first.
751    fn find(&self, layout: Layout) -> (u8, bool) {
752        let (first, group) = match layout.shape {
753            Shape::Record { .. } => (0u8, self.held.get(..4)),
754            Shape::Message { .. } => (4u8, self.held.get(4..)),
755        };
756        let group = group.unwrap_or(&[]);
757        let local = |i: usize| first.saturating_add(u8::try_from(i).unwrap_or(u8::MAX));
758        if let Some(i) = group.iter().position(|h| h.is_some_and(|(l, _)| l == layout)) {
759            return (local(i), false);
760        }
761        if let Some(i) = group.iter().position(Option::is_none) {
762            return (local(i), true);
763        }
764        let oldest = group
765            .iter()
766            .enumerate()
767            .min_by_key(|(_, h)| h.map_or(0, |(_, used)| used))
768            .map_or(0, |(i, _)| i);
769        (local(oldest), true)
770    }
771
772    fn hold(&mut self, local: u8, layout: Layout) {
773        self.clock = self.clock.wrapping_add(1);
774        if let Some(h) = self.held.get_mut(usize::from(local)) {
775            *h = Some((layout, self.clock));
776        }
777    }
778}
779
780/// The layout of a message with a fixed table, all its fields kept.
781const fn fixed_layout<M: Message>() -> Layout {
782    let shape = Shape::Message { fields: M::FIELDS, keep: Mask::ALL };
783    Layout { global: M::GLOBAL, shape, raw: extra::RawDefs::NONE, dev: 0 }
784}
785
786/// How a data message's header names its time.
787#[derive(Clone, Copy)]
788enum Header {
789    Normal,
790    /// A compressed timestamp header, with the time's low five bits.
791    Compressed(u8),
792}
793
794/// How a data message would be written.
795#[derive(Clone, Copy)]
796pub(crate) struct Planned {
797    layout: Layout,
798    keep: Mask,
799    local: u8,
800    count: u8,
801    /// The definition's bytes, 0 when its layout is held already.
802    definition: u32,
803    /// The data message's bytes, with its header.
804    body: u32,
805}
806
807impl Planned {
808    /// Its bytes, with the definition it needs.
809    pub(crate) const fn size(&self) -> u32 {
810        self.definition.saturating_add(self.body)
811    }
812
813    /// Its bytes when written straight after `before`, whose definition may take its local
814    /// type.
815    pub(crate) fn after(&self, before: &Self) -> u32 {
816        if before.definition > 0 && before.local == self.local && self.definition == 0 {
817            self.definition_len().saturating_add(self.body)
818        } else {
819            self.size()
820        }
821    }
822
823    fn definition_len(&self) -> u32 {
824        definition_len(u32::from(self.count), self.layout.dev.count_ones())
825    }
826}
827
828/// A definition's bytes: its header, three for each field, and with developer fields, their
829/// count and three for each.
830const fn definition_len(fields: u32, dev_fields: u32) -> u32 {
831    let dev = match dev_fields {
832        0 => 0,
833        n => n.saturating_mul(3).saturating_add(1),
834    };
835    fields.saturating_mul(3).saturating_add(6).saturating_add(dev)
836}
837
838const STAGE: usize = 32;
839
840/// What a file's writing has come to: its bytes, layouts and counts so far.
841#[derive(Clone)]
842struct State {
843    options: Options,
844    plan: Option<Plan>,
845    stage: [u8; STAGE],
846    staged: usize,
847    data_crc: Crc,
848    written: u32,
849    locals: Locals,
850    last_timestamp: Option<Timestamp>,
851    laps: u16,
852    sessions: u16,
853    failed: bool,
854    act: activity::Act,
855    require_end: bool,
856    dev: extra::DevTable,
857}
858
859impl State {
860    fn new(options: Options, plan: Option<Plan>) -> Self {
861        Self {
862            options,
863            plan,
864            stage: [0; STAGE],
865            staged: 0,
866            data_crc: Crc::new(),
867            written: 0,
868            locals: Locals::new(),
869            last_timestamp: None,
870            laps: 0,
871            sessions: 0,
872            failed: false,
873            act: activity::Act::new(),
874            require_end: true,
875            dev: extra::DevTable::new(),
876        }
877    }
878
879    /// What a sizing pass that has run its source learned.
880    fn plan(mut self) -> Result<Plan, Error> {
881        Writer { out: &mut Counter, st: &mut self }.close()?;
882        let file_size = self.written.checked_add(FRAMING).ok_or(Error::TooLarge)?;
883        Ok(Plan { data_size: self.written, file_size, data_crc: self.data_crc.value() })
884    }
885
886    /// A one-pass file's ending: its header, how far back from the end of the file that
887    /// starts once the CRC is written, and the CRC.
888    fn trailer(&self) -> Result<([u8; HEADER_LEN as usize], u32, [u8; 2]), Error> {
889        let header = header(self.options, self.written);
890        let back = self.written.checked_add(FRAMING).ok_or(Error::TooLarge)?;
891        let crc = file_crc(&header, self);
892        Ok((header, back, crc))
893    }
894}
895
896/// Writes the messages of one file, in order. [`write()`] and [`size()`] hand one to the
897/// source; [`OnePass::writer`] gives one too, so a function taking a `&mut Writer` serves both.
898pub struct Writer<'a> {
899    out: &'a mut dyn Out,
900    st: &'a mut State,
901}
902
903impl fmt::Debug for Writer<'_> {
904    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
905        f.debug_struct("Writer").field("written", &self.st.written).finish_non_exhaustive()
906    }
907}
908
909impl Writer<'_> {
910    /// Writes a `file_id`, which belongs first.
911    pub(crate) fn raw_file_id(&mut self, msg: &FileId) -> Result<(), Error> {
912        self.fixed(msg, 0)
913    }
914
915    pub(crate) fn raw_device_info(&mut self, msg: &DeviceInfo<'_>) -> Result<(), Error> {
916        self.fixed(msg, 0)
917    }
918
919    pub(crate) fn raw_event(&mut self, msg: Event) -> Result<(), Error> {
920        self.fixed(&msg, 0)
921    }
922
923    #[cfg(test)]
924    pub(crate) fn raw_record(&mut self, msg: Record) -> Result<(), Error> {
925        self.raw_record_with(msg, &[])
926    }
927
928    fn raw_record_with(&mut self, msg: Record, extras: &[Extra<'_>]) -> Result<(), Error> {
929        let (layout, defs, header, compressed) = self.record_parts(&msg);
930        let t = msg.timestamp;
931        self.message(layout, defs, header, Some(t), Extras::Values(extras), |out| {
932            if !compressed {
933                out.u32(t.fit());
934            }
935            msg.encode(out);
936        })
937    }
938
939    /// The bytes `msg` would take as the next record.
940    pub(crate) fn record_cost(&self, msg: &Record, extras: &[Extra<'_>]) -> Result<u32, Error> {
941        let (layout, defs, _, compressed) = self.record_parts(msg);
942        let t = msg.timestamp;
943        let planned =
944            self.plan(layout, defs, Extras::Values(extras), &|out: &mut dyn FieldOut| {
945                if !compressed {
946                    out.u32(t.fit());
947                }
948                msg.encode(out);
949            })?;
950        Ok(planned.size())
951    }
952
953    /// A record's layout, fields and header, and whether its time is in the header.
954    fn record_parts(
955        &self,
956        msg: &Record,
957    ) -> (Layout, impl Iterator<Item = FieldDef> + Clone, Header, bool) {
958        let t = msg.timestamp;
959        let compressed = self.st.options.compressed_timestamps
960            && self
961                .st
962                .last_timestamp
963                .and_then(|last| t.fit().checked_sub(last.fit()))
964                .is_some_and(|gap| gap < 32);
965        let shape = Shape::Record { fields: msg.fields(), compressed };
966        let layout = Layout { global: RECORD_GLOBAL, shape, raw: extra::RawDefs::NONE, dev: 0 };
967        let defs = core::iter::once(RECORD_TIMESTAMP)
968            .filter(move |_| !compressed)
969            .chain(record_fields(msg.fields()));
970        let header = if compressed {
971            #[allow(clippy::cast_possible_truncation)]
972            Header::Compressed((t.fit() & 0x1F) as u8)
973        } else {
974            Header::Normal
975        };
976        (layout, defs, header, compressed)
977    }
978
979    /// Writes a `lap`, numbered after the laps before it.
980    pub(crate) fn raw_lap(&mut self, msg: &Lap) -> Result<(), Error> {
981        self.fixed_with(msg, next_index(self.st.laps, LAPS_MAX)?, Extras::Staged(KindId::Lap))?;
982        self.st.laps = self.st.laps.wrapping_add(1);
983        self.st.dev.unstage(KindId::Lap);
984        Ok(())
985    }
986
987    /// Writes a `session`, numbered after the sessions before it.
988    pub(crate) fn raw_session(&mut self, msg: &Session) -> Result<(), Error> {
989        let index = next_index(self.st.sessions, SESSIONS_MAX)?;
990        self.fixed_with(msg, index, Extras::Staged(KindId::Session))?;
991        self.st.sessions = self.st.sessions.wrapping_add(1);
992        self.st.dev.unstage(KindId::Session);
993        Ok(())
994    }
995
996    /// Writes the `activity`, which belongs last.
997    pub(crate) fn raw_activity(&mut self, msg: &Activity) -> Result<(), Error> {
998        self.fixed(msg, 0)
999    }
1000
1001    fn fixed<M: Message>(&mut self, msg: &M, index: u16) -> Result<(), Error> {
1002        self.fixed_with(msg, index, Extras::Values(&[]))
1003    }
1004
1005    fn fixed_with<M: Message>(
1006        &mut self,
1007        msg: &M,
1008        index: u16,
1009        extras: Extras<'_>,
1010    ) -> Result<(), Error> {
1011        let (layout, defs) = (fixed_layout::<M>(), M::FIELDS.iter().copied());
1012        self.message(layout, defs, Header::Normal, msg.timestamp(), extras, |out| {
1013            msg.encode(out, index);
1014        })
1015    }
1016
1017    /// What `msg` would take as the next message, as the first of its layout and as one after.
1018    pub(crate) fn cost<M: Message>(&self, msg: &M) -> Result<Planned, Error> {
1019        self.cost_with(msg, Extras::Values(&[]))
1020    }
1021
1022    /// [`Writer::cost`], with the fields beyond its table that `extras` adds.
1023    fn cost_with<M: Message>(&self, msg: &M, extras: Extras<'_>) -> Result<Planned, Error> {
1024        let (layout, defs) = (fixed_layout::<M>(), M::FIELDS.iter().copied());
1025        self.plan(layout, defs, extras, &|out: &mut dyn FieldOut| msg.encode(out, 0))
1026    }
1027
1028    /// How one data message would be written, refusing values it cannot hold; nothing is
1029    /// written.
1030    fn plan<I>(
1031        &self,
1032        mut layout: Layout,
1033        table: I,
1034        extras: Extras<'_>,
1035        encode: &dyn Fn(&mut dyn FieldOut),
1036    ) -> Result<Planned, Error>
1037    where
1038        I: Iterator<Item = FieldDef> + Clone,
1039    {
1040        let mut check = Fields::new(table.clone(), None);
1041        encode(&mut check);
1042        refusal(check.refused())?;
1043        // A message leaves out the fields it has no value for, so its layout says which.
1044        let keep = check.present();
1045        if let Shape::Message { keep: k, .. } = &mut layout.shape {
1046            *k = keep;
1047        }
1048        let defs = kept(table, keep);
1049        layout.raw = extra::raw_defs(extras)?;
1050        layout.dev = self.dev_fields(extras)?;
1051        let (local, define) = self.st.locals.find(layout);
1052        let count = defs.clone().count().saturating_add(layout.raw.defs().count());
1053        let count = u8::try_from(count).map_err(|_| Error::TooLarge)?;
1054        let planned = Planned { layout, keep, local, count, definition: 0, body: 0 };
1055        let definition = if define { planned.definition_len() } else { 0 };
1056        let body = data_len(defs)
1057            .saturating_add(data_len(layout.raw.defs()))
1058            .saturating_add(self.st.dev.size(layout.dev))
1059            .saturating_add(1);
1060        Ok(Planned { definition, body, ..planned })
1061    }
1062
1063    /// Writes one data message; nothing is written unless all of it can be.
1064    fn message<I>(
1065        &mut self,
1066        layout: Layout,
1067        table: I,
1068        header: Header,
1069        timestamp: Option<Timestamp>,
1070        extras: Extras<'_>,
1071        encode: impl Fn(&mut dyn FieldOut),
1072    ) -> Result<(), Error>
1073    where
1074        I: Iterator<Item = FieldDef> + Clone,
1075    {
1076        if self.st.failed {
1077            return Err(Error::Sink);
1078        }
1079        let planned = self.plan(layout, table.clone(), extras, &encode)?;
1080        self.reserve(planned.size())?;
1081        let Planned { layout, keep, local, count, definition, .. } = planned;
1082        self.st.locals.hold(local, layout);
1083
1084        if definition > 0 {
1085            let [g0, g1] = layout.global.to_le_bytes();
1086            let flag = if layout.dev == 0 { 0 } else { 0x20 };
1087            self.put(&[0x40 | flag | local, 0, 0, g0, g1, count]);
1088            for f in kept(table.clone(), keep).chain(layout.raw.defs()) {
1089                self.put(&[f.num, f.size, f.base]);
1090            }
1091            if layout.dev != 0 {
1092                self.put_dev_definitions(layout.dev);
1093            }
1094        }
1095        match header {
1096            Header::Normal => self.put(&[local]),
1097            Header::Compressed(low) => self.put(&[0x80 | local << 5 | low]),
1098        }
1099        let mut fields = Fields::new(table, Some(self)).keep(keep);
1100        encode(&mut fields);
1101        fields.finish();
1102        self.put_raw_fields(extras);
1103        self.put_dev_fields(extras, layout.dev);
1104        self.flush();
1105        if self.st.failed {
1106            return Err(Error::Sink);
1107        }
1108        if let Some(t) = timestamp {
1109            self.st.last_timestamp = Some(t);
1110        }
1111        Ok(())
1112    }
1113
1114    fn reserve(&mut self, size: u32) -> Result<(), Error> {
1115        let end = self.room(size)?;
1116        if self.st.plan.is_some_and(|plan| end > plan.data_size) {
1117            return Err(Error::SourceChanged);
1118        }
1119        self.st.written = end;
1120        Ok(())
1121    }
1122
1123    /// Where `size` more bytes would end, if they leave the activity room to end and the
1124    /// output takes them.
1125    fn room(&mut self, size: u32) -> Result<u32, Error> {
1126        let end = self.st.written.checked_add(size).ok_or(Error::TooLarge)?;
1127        match end.checked_add(self.st.act.kept_for_end()) {
1128            Some(n) if n <= LIMIT => {
1129                self.ahead(size)?;
1130                Ok(end)
1131            }
1132            _ => Err(Error::TooLarge),
1133        }
1134    }
1135
1136    /// Refuses a call of `size` more bytes than the output takes.
1137    fn ahead(&mut self, size: u32) -> Result<(), Error> {
1138        if self.out.fits(size) {
1139            Ok(())
1140        } else {
1141            Err(Error::Sink)
1142        }
1143    }
1144
1145    fn flush(&mut self) {
1146        if let Some(bytes) = self.st.stage.get(..self.st.staged) {
1147            if !self.st.failed && !bytes.is_empty() && !self.out.write(bytes) {
1148                self.st.failed = true;
1149            }
1150        }
1151        self.st.staged = 0;
1152    }
1153
1154    /// Ends the messages, which must have ended an activity; on a second pass, checks they are
1155    /// what the first pass sized.
1156    fn close(&mut self) -> Result<(), Error> {
1157        self.flush();
1158        if self.st.failed {
1159            return Err(Error::Sink);
1160        }
1161        if self.st.require_end && !self.st.act.ended() {
1162            return Err(Error::Unfinished);
1163        }
1164        match self.st.plan {
1165            Some(plan)
1166                if plan.data_size != self.st.written
1167                    || plan.data_crc != self.st.data_crc.value() =>
1168            {
1169                Err(Error::SourceChanged)
1170            }
1171            _ => Ok(()),
1172        }
1173    }
1174}
1175
1176impl Put for Writer<'_> {
1177    fn put(&mut self, bytes: &[u8]) {
1178        self.st.data_crc.update(bytes);
1179        for &byte in bytes {
1180            if let Some(slot) = self.st.stage.get_mut(self.st.staged) {
1181                *slot = byte;
1182                self.st.staged = self.st.staged.saturating_add(1);
1183            }
1184            if self.st.staged == STAGE {
1185                self.flush();
1186            }
1187        }
1188    }
1189}
1190
1191/// Whether `msg` would be written, as far as its values go.
1192fn check<M: Message>(msg: &M) -> Result<(), Error> {
1193    let mut fields = Fields::new(M::FIELDS.iter().copied(), None);
1194    msg.encode(&mut fields, 0);
1195    refusal(fields.refused())
1196}
1197
1198fn refusal(refused: Option<FieldError>) -> Result<(), Error> {
1199    match refused {
1200        Some(FieldError::StringTooLong) => Err(Error::StringTooLong),
1201        Some(FieldError::OutOfRange) => Err(Error::OutOfRange),
1202        None => Ok(()),
1203    }
1204}
1205
1206/// A `message_index` is its low 12 bits; all 12 set is the profile's mask.
1207const INDEXES: u16 = 0x0FFF;
1208
1209/// The most laps an activity holds. Each session ends with a lap of its own, so in an activity
1210/// of one session [`Writer::lap`], [`Writer::lap_by`] and a pool swim's rests end at most
1211/// `LAPS_MAX - 1`.
1212pub const LAPS_MAX: u16 = INDEXES;
1213/// The most sessions an activity holds.
1214pub const SESSIONS_MAX: u16 = INDEXES;
1215/// The most lengths an activity holds, idle lengths included: a rest in a pool swim ends with
1216/// one.
1217pub const LENGTHS_MAX: u16 = INDEXES;
1218/// The most sets an activity holds, rests included: a rest in a training session ends with
1219/// one.
1220pub const SETS_MAX: u16 = INDEXES;
1221/// The most sensors [`Writer::device`] writes: their indexes follow the creator's 0 and stop
1222/// before 255, FIT's "none".
1223pub const SENSORS_MAX: u8 = 254;
1224/// The longest a lap, session, length or set may last, and the activity's timer run, in
1225/// seconds: the most whole seconds FIT's milliseconds hold, about 49.7 days.
1226pub const DURATION_SECONDS_MAX: u32 = u32::MAX / 1000;
1227/// The farthest an activity may go, in metres to the centimetre: the most FIT's centimetres
1228/// hold.
1229#[allow(clippy::cast_lossless, reason = "f64::from is not const")]
1230pub const DISTANCE_METERS_MAX: f64 = DISTANCE_CM_MAX as f64 / 100.0;
1231const DISTANCE_CM_MAX: u32 = u32::MAX - 1;
1232
1233/// The index of the message after `count`, of at most `max`.
1234fn next_index(count: u16, max: u16) -> Result<u16, Error> {
1235    if count >= max {
1236        Err(Error::IndexFull)
1237    } else {
1238        Ok(count)
1239    }
1240}
1241
1242mod activity;
1243#[cfg(feature = "async")]
1244mod asynch;
1245#[cfg(any(feature = "embedded-io", feature = "embedded-io-async"))]
1246mod embedded_io;
1247mod extra;
1248#[cfg(test)]
1249mod tests;
1250
1251#[cfg(feature = "async")]
1252pub use asynch::{
1253    write_async, AsyncOnePass, AsyncPatchSink, AsyncSink, AsyncWriter, ASYNC_WRITE_LEN,
1254};
1255#[cfg(any(feature = "embedded-io", feature = "embedded-io-async"))]
1256pub use embedded_io::{EmbeddedIo, EmbeddedIoError};