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