Skip to main content

fit_encoder/
messages.rs

1//! The messages this crate writes, each a fixed table of fields.
2
3use crate::types::{
4    ExerciseCategory, FileType, Manufacturer, Position, Sport, SubSport, SwimStroke, Timestamp,
5};
6
7/// Base types, from Table 7 of the FIT Protocol page: the base type field byte.
8pub(crate) mod base {
9    pub const ENUM: u8 = 0x00;
10    pub const SINT8: u8 = 0x01;
11    pub const UINT8: u8 = 0x02;
12    pub const STRING: u8 = 0x07;
13    pub const UINT8Z: u8 = 0x0A;
14    pub const BYTE: u8 = 0x0D;
15    pub const SINT16: u8 = 0x83;
16    pub const UINT16: u8 = 0x84;
17    pub const SINT32: u8 = 0x85;
18    pub const UINT32: u8 = 0x86;
19    pub const FLOAT32: u8 = 0x88;
20    pub const FLOAT64: u8 = 0x89;
21    pub const UINT16Z: u8 = 0x8B;
22    pub const UINT32Z: u8 = 0x8C;
23    pub const SINT64: u8 = 0x8E;
24    pub const UINT64: u8 = 0x8F;
25    pub const UINT64Z: u8 = 0x90;
26}
27
28/// Invalid values, from the same table.
29const INVALID_U8: u8 = 0xFF;
30const INVALID_U32: u32 = 0xFFFF_FFFF;
31
32/// The `timestamp` field number, which every message with a timestamp shares
33/// (<https://developer.garmin.com/fit/cookbook/decoding-activity-files/>).
34pub(crate) const TIMESTAMP: u8 = 253;
35/// The `message_index` field number, shared by the summary messages.
36const MESSAGE_INDEX: u8 = 254;
37
38/// One field definition: field number, size in bytes, base type.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub(crate) struct FieldDef {
41    pub num: u8,
42    pub size: u8,
43    pub base: u8,
44}
45
46pub(crate) const fn field(num: u8, size: u8, base: u8) -> FieldDef {
47    FieldDef { num, size, base }
48}
49
50/// Where a message's field values go, in table order.
51pub(crate) trait FieldOut {
52    fn u8(&mut self, v: u8);
53    fn u16(&mut self, v: u16);
54    fn u32(&mut self, v: u32);
55    fn i8(&mut self, v: i8);
56    fn i32(&mut self, v: i32);
57    fn str(&mut self, v: &str);
58    /// An array field's values, the rest of it none; an empty one is none.
59    fn u16s(&mut self, v: &[u16]);
60    /// Bytes exactly as wide as the field.
61    fn bytes(&mut self, v: &[u8]);
62    /// The field's "none": its base type's invalid value.
63    fn none(&mut self);
64
65    fn opt_u8(&mut self, v: Option<u8>) {
66        match v {
67            Some(v) => self.u8(v),
68            None => self.none(),
69        }
70    }
71
72    fn opt_u16(&mut self, v: Option<u16>) {
73        match v {
74            Some(v) => self.u16(v),
75            None => self.none(),
76        }
77    }
78
79    fn opt_i8(&mut self, v: Option<i8>) {
80        match v {
81            Some(v) => self.i8(v),
82            None => self.none(),
83        }
84    }
85
86    /// Two fields, latitude then longitude.
87    fn position(&mut self, v: Option<Position>) {
88        if let Some((lat, long)) = v.map(Position::semicircles) {
89            self.i32(lat);
90            self.i32(long);
91        } else {
92            self.none();
93            self.none();
94        }
95    }
96
97    fn opt_u32(&mut self, v: Option<u32>) {
98        match v {
99            Some(v) => self.u32(v),
100            None => self.none(),
101        }
102    }
103}
104
105/// A value a field cannot hold.
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107pub(crate) enum FieldError {
108    StringTooLong,
109    OutOfRange,
110}
111
112/// Bytes on their way to the sink.
113pub(crate) trait Put {
114    fn put(&mut self, bytes: &[u8]);
115}
116
117/// A set of a table's fields by position; a definition holds at most 255.
118#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
119pub(crate) struct Mask([u64; 4]);
120
121impl Mask {
122    pub(crate) const ALL: Self = Self([u64::MAX; 4]);
123    const EMPTY: Self = Self([0; 4]);
124
125    fn word_bit(i: usize) -> (usize, u64) {
126        let shift = u32::try_from(i % 64).unwrap_or(u32::MAX);
127        (i / 64, 1u64.checked_shl(shift).unwrap_or(0))
128    }
129
130    pub(crate) fn contains(self, i: usize) -> bool {
131        let (word, bit) = Self::word_bit(i);
132        self.0.get(word).is_some_and(|w| w & bit != 0)
133    }
134
135    fn insert(&mut self, i: usize) {
136        let (word, bit) = Self::word_bit(i);
137        if let Some(w) = self.0.get_mut(word) {
138            *w |= bit;
139        }
140    }
141
142    fn without(self, other: Self) -> Self {
143        let mut words = self.0;
144        for (word, out) in words.iter_mut().zip(other.0) {
145            *word &= !out;
146        }
147        Self(words)
148    }
149}
150
151/// `table`'s fields that `keep` holds.
152pub(crate) fn kept<I: Iterator<Item = FieldDef> + Clone>(
153    table: I,
154    keep: Mask,
155) -> impl Iterator<Item = FieldDef> + Clone {
156    table.enumerate().filter(move |(i, _)| keep.contains(*i)).map(|(_, f)| f)
157}
158
159/// Lays field values out against a table, writing the fields `keep` holds.
160pub(crate) struct Fields<'a, I> {
161    defs: I,
162    out: Option<&'a mut dyn Put>,
163    refused: Option<FieldError>,
164    keep: Mask,
165    /// The position of the next field, and whether the current one is written.
166    next: usize,
167    writing: bool,
168    nones: Mask,
169}
170
171/// Byte `i` of a `size`-byte field's "none", little-endian.
172pub(crate) const fn none_byte(base: u8, i: usize, size: usize) -> u8 {
173    match base {
174        base::STRING | base::UINT8Z | base::UINT16Z | base::UINT32Z | base::UINT64Z => 0,
175        base::SINT8 | base::SINT16 | base::SINT32 | base::SINT64 if i.saturating_add(1) == size => {
176            0x7F
177        }
178        _ => INVALID_U8,
179    }
180}
181
182/// Whether `value` is its field's "none".
183pub(crate) fn is_none(base: u8, value: &[u8]) -> bool {
184    value.iter().enumerate().all(|(i, &b)| b == none_byte(base, i, value.len()))
185}
186
187impl<'a, I: Iterator<Item = FieldDef>> Fields<'a, I> {
188    /// With no `out`, it only checks the values.
189    pub(crate) fn new(defs: I, out: Option<&'a mut dyn Put>) -> Self {
190        Self {
191            defs,
192            out,
193            refused: None,
194            keep: Mask::ALL,
195            next: 0,
196            writing: false,
197            nones: Mask::EMPTY,
198        }
199    }
200
201    /// Writes only the fields `keep` holds.
202    pub(crate) const fn keep(mut self, keep: Mask) -> Self {
203        self.keep = keep;
204        self
205    }
206
207    /// The first value refused, if any.
208    pub(crate) const fn refused(&self) -> Option<FieldError> {
209        self.refused
210    }
211
212    /// The fields given a value other than none, after [`Fields::finish`] would have run.
213    pub(crate) fn present(mut self) -> Mask {
214        while self.field().is_some() {
215            self.nones.insert(self.next.saturating_sub(1));
216        }
217        Mask::ALL.without(self.nones)
218    }
219
220    /// The next field's definition, which the bytes that follow are written for.
221    fn field(&mut self) -> Option<FieldDef> {
222        let def = self.defs.next()?;
223        self.writing = self.keep.contains(self.next);
224        self.next = self.next.saturating_add(1);
225        Some(def)
226    }
227
228    fn put(&mut self, bytes: &[u8]) {
229        if let (true, Some(out)) = (self.writing, self.out.as_deref_mut()) {
230            out.put(bytes);
231        }
232    }
233
234    fn refuse(&mut self, e: FieldError) {
235        self.refused.get_or_insert(e);
236    }
237
238    fn fill(&mut self, def: FieldDef) {
239        self.nones.insert(self.next.saturating_sub(1));
240        let size = usize::from(def.size);
241        for i in 0..size {
242            self.put(&[none_byte(def.base, i, size)]);
243        }
244    }
245
246    fn number(&mut self, le: &[u8]) {
247        let Some(def) = self.field() else { return };
248        let size = usize::from(def.size);
249        let (value, rest) = le.split_at(size.min(le.len()));
250        let is_none = value.len() == size && is_none(def.base, value);
251        if rest.iter().any(|&b| b != 0) || is_none {
252            self.refuse(FieldError::OutOfRange);
253        }
254        self.put(value);
255        for _ in value.len()..size {
256            self.put(&[0]);
257        }
258    }
259
260    /// Writes every field not yet written as none.
261    pub(crate) fn finish(mut self) {
262        while let Some(def) = self.field() {
263            self.fill(def);
264        }
265    }
266}
267
268impl<I: Iterator<Item = FieldDef>> FieldOut for Fields<'_, I> {
269    fn u8(&mut self, v: u8) {
270        self.number(&[v]);
271    }
272
273    fn u16(&mut self, v: u16) {
274        self.number(&v.to_le_bytes());
275    }
276
277    fn u32(&mut self, v: u32) {
278        self.number(&v.to_le_bytes());
279    }
280
281    fn i8(&mut self, v: i8) {
282        self.number(&v.to_le_bytes());
283    }
284
285    fn i32(&mut self, v: i32) {
286        self.number(&v.to_le_bytes());
287    }
288
289    /// An empty string is the string's none; a NUL inside one would end it early, so is
290    /// refused.
291    fn str(&mut self, v: &str) {
292        let Some(def) = self.field() else { return };
293        let bytes = v.as_bytes();
294        if bytes.is_empty() {
295            self.fill(def);
296            return;
297        }
298        if bytes.contains(&0) {
299            self.refuse(FieldError::OutOfRange);
300            return;
301        }
302        if bytes.len() >= usize::from(def.size) {
303            self.refuse(FieldError::StringTooLong);
304            return;
305        }
306        self.put(bytes);
307        for _ in bytes.len()..usize::from(def.size) {
308            self.put(&[0]);
309        }
310    }
311
312    fn u16s(&mut self, v: &[u16]) {
313        let Some(def) = self.field() else { return };
314        let size = usize::from(def.size);
315        let len = v.len().saturating_mul(2);
316        if len > size || v.contains(&u16::MAX) {
317            self.refuse(FieldError::OutOfRange);
318        }
319        if v.is_empty() {
320            self.fill(def);
321            return;
322        }
323        for x in v {
324            self.put(&x.to_le_bytes());
325        }
326        for _ in len..size {
327            self.put(&[INVALID_U8]);
328        }
329    }
330
331    fn bytes(&mut self, v: &[u8]) {
332        let Some(def) = self.field() else { return };
333        if v.len() != usize::from(def.size) || is_none(def.base, v) {
334            self.refuse(FieldError::OutOfRange);
335            return;
336        }
337        self.put(v);
338    }
339
340    fn none(&mut self) {
341        if let Some(def) = self.field() {
342            self.fill(def);
343        }
344    }
345}
346
347/// The sum of a table's sizes: a data message's length, without its header.
348pub(crate) fn data_len(fields: impl Iterator<Item = FieldDef>) -> u32 {
349    fields.map(|f| u32::from(f.size)).fold(0, u32::wrapping_add)
350}
351
352/// A message with one fixed table.
353pub(crate) trait Message {
354    const GLOBAL: u16;
355    const FIELDS: &'static [FieldDef];
356    /// The message's time in field 253, which compressed timestamps count from.
357    fn timestamp(&self) -> Option<Timestamp>;
358    /// Writes the fields in table order. `index` is the message's `message_index`, for those
359    /// that have one.
360    fn encode(&self, out: &mut dyn FieldOut, index: u16);
361}
362
363/// Identifies the file; the first message of every FIT file.
364#[derive(Clone, Copy, Debug, PartialEq, Eq)]
365pub(crate) struct FileId {
366    file_type: FileType,
367    manufacturer: Manufacturer,
368    product: u16,
369    serial_number: Option<u32>,
370    time_created: Timestamp,
371}
372
373impl FileId {
374    /// A file of `file_type`, made by `manufacturer`'s `product` at `time_created`.
375    #[must_use]
376    pub const fn new(
377        file_type: FileType,
378        manufacturer: Manufacturer,
379        product: u16,
380        time_created: Timestamp,
381    ) -> Self {
382        Self { file_type, manufacturer, product, serial_number: None, time_created }
383    }
384
385    /// The device's serial number, not 0, which is "none".
386    #[must_use]
387    pub const fn serial_number(mut self, serial_number: u32) -> Self {
388        self.serial_number = Some(serial_number);
389        self
390    }
391}
392
393impl Message for FileId {
394    const GLOBAL: u16 = 0;
395    const FIELDS: &'static [FieldDef] = &[
396        field(0, 1, base::ENUM),    // type
397        field(1, 2, base::UINT16),  // manufacturer
398        field(2, 2, base::UINT16),  // product
399        field(3, 4, base::UINT32Z), // serial_number
400        field(4, 4, base::UINT32),  // time_created
401    ];
402
403    fn timestamp(&self) -> Option<Timestamp> {
404        None
405    }
406
407    fn encode(&self, out: &mut dyn FieldOut, _: u16) {
408        out.u8(self.file_type.get());
409        out.u16(self.manufacturer.get());
410        out.u16(self.product);
411        out.opt_u32(self.serial_number);
412        out.u32(self.time_created.fit());
413    }
414}
415
416/// The longest `product_name`, in UTF-8 bytes; one more byte holds its terminating NUL.
417pub const PRODUCT_NAME_MAX: usize = 19;
418
419/// A device: the one that recorded the file, or a sensor it used.
420///
421/// The creator, given to [`Writer::start`](crate::Writer::start), is the file's `file_id` and
422/// its first `device_info`.
423///
424/// ```
425/// use fit_encoder::{Device, Manufacturer};
426///
427/// let watch = Device::new(Manufacturer::DEVELOPMENT, 1)
428///     .serial_number(42)
429///     .software_version(123) // 1.23
430///     .product_name("My watch");
431/// # let _ = watch;
432/// ```
433#[derive(Clone, Copy, Debug, PartialEq, Eq)]
434pub struct Device<'a> {
435    pub(crate) manufacturer: Manufacturer,
436    pub(crate) product: u16,
437    pub(crate) serial_number: Option<u32>,
438    pub(crate) software_version: Option<u16>,
439    pub(crate) product_name: &'a str,
440}
441
442impl<'a> Device<'a> {
443    /// A device by its manufacturer and the manufacturer's product number.
444    #[must_use]
445    pub const fn new(manufacturer: Manufacturer, product: u16) -> Self {
446        Self {
447            manufacturer,
448            product,
449            serial_number: None,
450            software_version: None,
451            product_name: "",
452        }
453    }
454
455    /// Its serial number, not 0, which is "none".
456    #[must_use]
457    pub const fn serial_number(mut self, serial_number: u32) -> Self {
458        self.serial_number = Some(serial_number);
459        self
460    }
461
462    /// Its software version in hundredths: 123 is 1.23.
463    #[must_use]
464    pub const fn software_version(mut self, hundredths: u16) -> Self {
465        self.software_version = Some(hundredths);
466        self
467    }
468
469    /// Its name for display, up to [`PRODUCT_NAME_MAX`] bytes, with no NUL.
470    #[must_use]
471    pub const fn product_name(mut self, name: &'a str) -> Self {
472        self.product_name = name;
473        self
474    }
475
476    /// Its `device_info` at `timestamp` as device `index`.
477    pub(crate) const fn info(&self, timestamp: Timestamp, index: u8) -> DeviceInfo<'a> {
478        DeviceInfo {
479            timestamp,
480            device_index: index,
481            manufacturer: Some(self.manufacturer),
482            serial_number: self.serial_number,
483            product: Some(self.product),
484            software_version: self.software_version,
485            product_name: self.product_name,
486        }
487    }
488}
489
490#[derive(Clone, Copy, Debug, PartialEq, Eq)]
491pub(crate) struct DeviceInfo<'a> {
492    timestamp: Timestamp,
493    device_index: u8,
494    manufacturer: Option<Manufacturer>,
495    serial_number: Option<u32>,
496    product: Option<u16>,
497    software_version: Option<u16>,
498    product_name: &'a str,
499}
500
501#[cfg(test)]
502impl<'a> DeviceInfo<'a> {
503    pub(crate) const fn new(timestamp: Timestamp) -> Self {
504        Self {
505            timestamp,
506            device_index: 0,
507            manufacturer: None,
508            serial_number: None,
509            product: None,
510            software_version: None,
511            product_name: "",
512        }
513    }
514
515    pub(crate) const fn device_index(mut self, device_index: u8) -> Self {
516        self.device_index = device_index;
517        self
518    }
519
520    pub(crate) const fn manufacturer(mut self, manufacturer: Manufacturer) -> Self {
521        self.manufacturer = Some(manufacturer);
522        self
523    }
524
525    /// Its serial number; 0, the default, is "none".
526    pub(crate) const fn serial_number(mut self, serial_number: u32) -> Self {
527        self.serial_number = Some(serial_number);
528        self
529    }
530
531    pub(crate) const fn product(mut self, product: u16) -> Self {
532        self.product = Some(product);
533        self
534    }
535
536    /// Its software version in hundredths: 123 is 1.23.
537    pub(crate) const fn software_version(mut self, hundredths: u16) -> Self {
538        self.software_version = Some(hundredths);
539        self
540    }
541
542    /// A display name of up to [`PRODUCT_NAME_MAX`] UTF-8 bytes; a longer one fails the write.
543    pub(crate) const fn product_name(mut self, name: &'a str) -> Self {
544        self.product_name = name;
545        self
546    }
547}
548
549impl Message for DeviceInfo<'_> {
550    const GLOBAL: u16 = 23;
551    #[allow(clippy::cast_possible_truncation)]
552    const FIELDS: &'static [FieldDef] = &[
553        field(TIMESTAMP, 4, base::UINT32),
554        field(0, 1, base::UINT8),                            // device_index
555        field(2, 2, base::UINT16),                           // manufacturer
556        field(3, 4, base::UINT32Z),                          // serial_number
557        field(4, 2, base::UINT16),                           // product
558        field(5, 2, base::UINT16),                           // software_version, scale 100
559        field(27, PRODUCT_NAME_MAX as u8 + 1, base::STRING), // product_name
560    ];
561
562    fn timestamp(&self) -> Option<Timestamp> {
563        Some(self.timestamp)
564    }
565
566    fn encode(&self, out: &mut dyn FieldOut, _: u16) {
567        out.u32(self.timestamp.fit());
568        out.u8(self.device_index);
569        out.opt_u16(self.manufacturer.map(Manufacturer::get));
570        out.opt_u32(self.serial_number);
571        out.opt_u16(self.product);
572        out.opt_u16(self.software_version);
573        out.str(self.product_name);
574    }
575}
576
577/// `event` values (the profile's `event` type) and `event_type` values used here.
578pub(crate) mod event {
579    pub const TIMER: u8 = 0;
580    pub const SESSION: u8 = 8;
581    pub const LAP: u8 = 9;
582    pub const LENGTH: u8 = 28;
583    pub const ACTIVITY: u8 = 26;
584    pub const START: u8 = 0;
585    pub const STOP: u8 = 1;
586    pub const STOP_ALL: u8 = 4;
587}
588
589/// Something that happened at a moment: here, the timer starting or stopping.
590#[derive(Clone, Copy, Debug, PartialEq, Eq)]
591#[allow(clippy::struct_field_names)]
592pub(crate) struct Event {
593    timestamp: Timestamp,
594    event: u8,
595    event_type: u8,
596}
597
598impl Event {
599    /// The timer starts, or resumes after a pause.
600    #[must_use]
601    pub const fn timer_start(timestamp: Timestamp) -> Self {
602        Self { timestamp, event: event::TIMER, event_type: event::START }
603    }
604
605    /// The timer stops: a pause.
606    #[must_use]
607    pub const fn timer_stop(timestamp: Timestamp) -> Self {
608        Self { timestamp, event: event::TIMER, event_type: event::STOP }
609    }
610
611    /// Every timer stops: the end of the recording.
612    #[must_use]
613    pub const fn timer_stop_all(timestamp: Timestamp) -> Self {
614        Self { timestamp, event: event::TIMER, event_type: event::STOP_ALL }
615    }
616}
617
618impl Message for Event {
619    const GLOBAL: u16 = 21;
620    const FIELDS: &'static [FieldDef] = &[
621        field(TIMESTAMP, 4, base::UINT32),
622        field(0, 1, base::ENUM), // event
623        field(1, 1, base::ENUM), // event_type
624    ];
625
626    fn timestamp(&self) -> Option<Timestamp> {
627        Some(self.timestamp)
628    }
629
630    fn encode(&self, out: &mut dyn FieldOut, _: u16) {
631        out.u32(self.timestamp.fit());
632        out.u8(self.event);
633        out.u8(self.event_type);
634    }
635}
636
637/// The fields a record has values for besides its timestamp, one bit each: its layout.
638#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
639pub(crate) struct RecordFields(pub(crate) u32);
640
641impl RecordFields {
642    pub(crate) const POSITION: Self = Self(1);
643    pub(crate) const ALTITUDE: Self = Self(1 << 1);
644    pub(crate) const HEART_RATE: Self = Self(1 << 2);
645    pub(crate) const CADENCE: Self = Self(1 << 3);
646    pub(crate) const DISTANCE: Self = Self(1 << 4);
647    pub(crate) const SPEED: Self = Self(1 << 5);
648    pub(crate) const POWER: Self = Self(1 << 6);
649    pub(crate) const TEMPERATURE: Self = Self(1 << 7);
650
651    pub(crate) const fn contains(self, other: Self) -> bool {
652        self.0 & other.0 == other.0
653    }
654}
655/// The record fields after the timestamp, in table order, with their bits.
656const RECORD_FIELDS: [(RecordFields, FieldDef); 9] = [
657    (RecordFields::POSITION, field(0, 4, base::SINT32)), // position_lat
658    (RecordFields::POSITION, field(1, 4, base::SINT32)), // position_long
659    (RecordFields::ALTITUDE, field(2, 2, base::UINT16)), // altitude, scale 5, offset 500
660    (RecordFields::HEART_RATE, field(3, 1, base::UINT8)),
661    (RecordFields::CADENCE, field(4, 1, base::UINT8)),
662    (RecordFields::DISTANCE, field(5, 4, base::UINT32)), // distance, scale 100
663    (RecordFields::SPEED, field(6, 2, base::UINT16)),    // speed, scale 1000
664    (RecordFields::POWER, field(7, 2, base::UINT16)),
665    (RecordFields::TEMPERATURE, field(13, 1, base::SINT8)),
666];
667
668pub(crate) const RECORD_GLOBAL: u16 = 20;
669pub(crate) const RECORD_TIMESTAMP: FieldDef = field(TIMESTAMP, 4, base::UINT32);
670
671/// Whether a record's field `num` is one the encoder writes, or an alternative form of one:
672/// `compressed_speed_distance` (8), `enhanced_speed` (73) and `enhanced_altitude` (78).
673pub(crate) fn record_owns(num: u8) -> bool {
674    num == TIMESTAMP
675        || [8, 73, 78].contains(&num)
676        || RECORD_FIELDS.iter().any(|(_, f)| f.num == num)
677}
678
679/// The record definition's fields for `layout`, in order, without the timestamp.
680pub(crate) fn record_fields(layout: RecordFields) -> impl Iterator<Item = FieldDef> + Clone {
681    RECORD_FIELDS.into_iter().filter(move |(bit, _)| layout.contains(*bit)).map(|(_, f)| f)
682}
683
684/// One moment's samples.
685///
686/// A record needs a value besides its timestamp; the encoder does not check that one is set.
687///
688/// ```
689/// use fit_encoder::{Record, Timestamp};
690///
691/// let r = Record::new(Timestamp::from_fit(1_133_481_600)).heart_rate(128);
692/// # let _ = r;
693/// ```
694#[derive(Clone, Copy, Debug, PartialEq, Eq)]
695pub struct Record {
696    pub(crate) timestamp: Timestamp,
697    pub(crate) position: Option<Position>,
698    pub(crate) altitude: Option<Altitude>,
699    pub(crate) heart_rate: Option<u8>,
700    pub(crate) cadence: Option<u8>,
701    pub(crate) distance_input: Option<Distance>,
702    /// The activity's distance after this record, in centimetres, which the writer works out.
703    pub(crate) distance: Option<u32>,
704    pub(crate) speed: Option<u16>,
705    pub(crate) power: Option<u16>,
706    pub(crate) temperature: Option<i8>,
707}
708
709/// How a record gives its distance: an increment in micrometres, or a total in centimetres;
710/// the type's maximum is out of range.
711#[derive(Clone, Copy, Debug, PartialEq, Eq)]
712pub(crate) enum Distance {
713    Advanced(u64),
714    Total(u32),
715}
716
717/// Records averaged before the ascent filter, unless the caller smoothed them.
718pub(crate) const SMOOTHING: u8 = 5;
719
720/// An altitude, with where it came from, which sets how it is smoothed and how far it must
721/// climb or fall before ascent and descent count it.
722///
723/// ```
724/// use fit_encoder::Altitude;
725///
726/// let summit = Altitude::barometric_meters(312.4);
727/// # let _ = summit;
728/// ```
729#[derive(Clone, Copy, Debug, PartialEq, Eq)]
730pub struct Altitude {
731    /// Fifths of a metre above 500 m below sea level; `u16::MAX` is out of range.
732    pub(crate) fifths: u16,
733    /// Fifths of a metre, at least one.
734    pub(crate) threshold: u16,
735    /// The records averaged before the threshold applies.
736    pub(crate) window: u8,
737}
738
739impl Altitude {
740    /// From a barometric altimeter: averaged over five records, a change counts once it
741    /// passes 2 m.
742    #[must_use]
743    pub fn barometric_meters(meters: f64) -> Self {
744        Self::meters_with_threshold(meters, 2.0)
745    }
746
747    /// From satellite positioning: averaged over five records, a change counts once it passes
748    /// 10 m.
749    #[must_use]
750    pub fn gnss_meters(meters: f64) -> Self {
751        Self::meters_with_threshold(meters, 10.0)
752    }
753
754    /// Already smoothed by the caller: taken as it is, every change counts.
755    #[must_use]
756    pub fn smoothed_meters(meters: f64) -> Self {
757        Self { window: 1, ..Self::meters_with_threshold(meters, 0.0) }
758    }
759
760    /// From 500 m below sea level to 12,606.8 m above it, to a fifth of a metre: averaged
761    /// over five records, a change counts once it passes `threshold` metres, at least a fifth
762    /// of one.
763    #[must_use]
764    pub fn meters_with_threshold(meters: f64, threshold: f64) -> Self {
765        let none = u32::from(u16::MAX);
766        let fifths = u16::try_from(scaled(meters + 500.0, 5.0, none)).unwrap_or(u16::MAX);
767        let threshold = u16::try_from(scaled(threshold, 5.0, none)).unwrap_or(u16::MAX);
768        // A threshold out of range makes the altitude out of range, so it is refused.
769        let fifths = if threshold == u16::MAX { u16::MAX } else { fifths };
770        Self { fifths, threshold: threshold.max(1), window: SMOOTHING }
771    }
772}
773
774/// `x` scaled and rounded to the nearest whole number, if it is below `none`, the field's
775/// "none"; otherwise `none`, which writing refuses.
776fn scaled(x: f64, scale: f64, none: u32) -> u32 {
777    let v = x * scale + 0.5;
778    if v.is_nan() || v.is_sign_negative() {
779        return none;
780    }
781    // Saturates at u32::MAX.
782    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
783    (v as u32).min(none)
784}
785
786impl Record {
787    /// A record at `timestamp` with no samples yet.
788    #[must_use]
789    pub const fn new(timestamp: Timestamp) -> Self {
790        Self {
791            timestamp,
792            position: None,
793            altitude: None,
794            heart_rate: None,
795            cadence: None,
796            distance_input: None,
797            distance: None,
798            speed: None,
799            power: None,
800            temperature: None,
801        }
802    }
803
804    /// Where it was.
805    #[must_use]
806    pub const fn position(mut self, position: Position) -> Self {
807        self.position = Some(position);
808        self
809    }
810
811    /// The altitude, which with its source sets what ascent and descent count.
812    #[must_use]
813    pub const fn altitude(mut self, altitude: Altitude) -> Self {
814        self.altitude = Some(altitude);
815        self
816    }
817
818    /// The heart rate in beats per minute, up to 254.
819    #[must_use]
820    pub const fn heart_rate(mut self, bpm: u8) -> Self {
821        self.heart_rate = Some(bpm);
822        self
823    }
824
825    /// The cadence in revolutions, or strides, a minute, up to 254.
826    #[must_use]
827    pub const fn cadence_rpm(mut self, rpm: u8) -> Self {
828        self.cadence = Some(rpm);
829        self
830    }
831
832    /// The distance covered since the last record that gave one, to the micrometre; the
833    /// writer keeps the activity's total, up to
834    /// [`DISTANCE_METERS_MAX`](crate::DISTANCE_METERS_MAX).
835    #[must_use]
836    pub fn distance_advanced_meters(mut self, meters: f64) -> Self {
837        let v = meters * 1e6 + 0.5;
838        // Saturates at u64::MAX, which writing refuses.
839        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
840        let um = if v.is_nan() || v.is_sign_negative() { u64::MAX } else { v as u64 };
841        self.distance_input = Some(Distance::Advanced(um));
842        self
843    }
844
845    /// The distance covered since the activity started, up to
846    /// [`DISTANCE_METERS_MAX`](crate::DISTANCE_METERS_MAX), to the centimetre; less than a
847    /// total already written is refused.
848    #[must_use]
849    pub fn distance_meters(mut self, meters: f64) -> Self {
850        self.distance_input = Some(Distance::Total(scaled(meters, 100.0, u32::MAX)));
851        self
852    }
853
854    /// The speed, up to 65.534 m/s, to the millimetre a second.
855    #[must_use]
856    pub fn speed_meters_per_second(mut self, speed: f64) -> Self {
857        let raw = scaled(speed, 1000.0, u32::from(u16::MAX));
858        self.speed = Some(u16::try_from(raw).unwrap_or(u16::MAX));
859        self
860    }
861
862    /// The power in watts, up to 65,534.
863    #[must_use]
864    pub const fn power_watts(mut self, watts: u16) -> Self {
865        self.power = Some(watts);
866        self
867    }
868
869    /// The temperature in degrees Celsius, from -128 to 126.
870    #[must_use]
871    pub const fn temperature_celsius(mut self, celsius: i8) -> Self {
872        self.temperature = Some(celsius);
873        self
874    }
875
876    /// The fields this record has values for, which are its layout.
877    pub(crate) fn fields(self) -> RecordFields {
878        let bits = [
879            (self.position.is_some(), RecordFields::POSITION),
880            (self.altitude.is_some(), RecordFields::ALTITUDE),
881            (self.heart_rate.is_some(), RecordFields::HEART_RATE),
882            (self.cadence.is_some(), RecordFields::CADENCE),
883            (self.distance.is_some(), RecordFields::DISTANCE),
884            (self.speed.is_some(), RecordFields::SPEED),
885            (self.power.is_some(), RecordFields::POWER),
886            (self.temperature.is_some(), RecordFields::TEMPERATURE),
887        ];
888        RecordFields(bits.iter().filter(|(set, _)| *set).map(|(_, bit)| bit.0).sum())
889    }
890
891    /// Writes the fields it has values for, in table order.
892    pub(crate) fn encode(self, out: &mut dyn FieldOut) {
893        if self.position.is_some() {
894            out.position(self.position);
895        }
896        if let Some(v) = self.altitude.map(|a| a.fifths) {
897            out.u16(v);
898        }
899        if let Some(v) = self.heart_rate {
900            out.u8(v);
901        }
902        if let Some(v) = self.cadence {
903            out.u8(v);
904        }
905        if let Some(v) = self.distance {
906            out.u32(v);
907        }
908        if let Some(v) = self.speed {
909            out.u16(v);
910        }
911        if let Some(v) = self.power {
912            out.u16(v);
913        }
914        if let Some(v) = self.temperature {
915            out.i8(v);
916        }
917    }
918}
919
920/// The times every summary message (lap, session) requires.
921#[derive(Clone, Copy, Debug, PartialEq, Eq)]
922pub(crate) struct Span {
923    pub start_time: Timestamp,
924    pub timestamp: Timestamp,
925    pub total_elapsed_ms: u32,
926    pub total_timer_ms: u32,
927}
928
929/// Heart rate and sport, which lap and session both summarise.
930#[derive(Clone, Copy, Debug, PartialEq, Eq)]
931struct Summary {
932    avg_heart_rate: Option<u8>,
933    max_heart_rate: Option<u8>,
934    sport: Option<Sport>,
935    sub_sport: Option<SubSport>,
936}
937
938impl Summary {
939    const NONE: Self =
940        Self { avg_heart_rate: None, max_heart_rate: None, sport: None, sub_sport: None };
941}
942
943/// What a lap or session covered, from its records; in FIT's units, as [`Record`] holds them.
944#[derive(Clone, Copy, Debug, PartialEq, Eq)]
945pub(crate) struct Totals {
946    pub start: Option<Position>,
947    pub end: Option<Position>,
948    pub north_east: Option<Position>,
949    pub south_west: Option<Position>,
950    pub distance: Option<u32>,
951    pub avg_speed: Option<u16>,
952    pub max_speed: Option<u16>,
953    pub avg_cadence: Option<u8>,
954    pub max_cadence: Option<u8>,
955    pub avg_power: Option<u16>,
956    pub max_power: Option<u16>,
957    /// In metres.
958    pub ascent: Option<u16>,
959    pub descent: Option<u16>,
960    pub avg_temperature: Option<i8>,
961    pub max_temperature: Option<i8>,
962    /// Strokes in a pool swim, repetitions in a strength session.
963    pub cycles: Option<u32>,
964    pub lengths: Option<u16>,
965    pub active_lengths: Option<u16>,
966    /// In centimetres.
967    pub stroke_distance: Option<u16>,
968    pub swim_stroke: Option<SwimStroke>,
969}
970
971impl Totals {
972    pub(crate) const NONE: Self = Self {
973        start: None,
974        end: None,
975        north_east: None,
976        south_west: None,
977        distance: None,
978        avg_speed: None,
979        max_speed: None,
980        avg_cadence: None,
981        max_cadence: None,
982        avg_power: None,
983        max_power: None,
984        ascent: None,
985        descent: None,
986        avg_temperature: None,
987        max_temperature: None,
988        cycles: None,
989        lengths: None,
990        active_lengths: None,
991        stroke_distance: None,
992        swim_stroke: None,
993    };
994
995    /// Writes the totals, in the order of [`with_totals`].
996    fn encode(&self, out: &mut dyn FieldOut) {
997        out.position(self.start);
998        out.position(self.end);
999        out.opt_u32(self.distance);
1000        out.opt_u16(self.avg_speed);
1001        out.opt_u16(self.max_speed);
1002        out.opt_u8(self.avg_cadence);
1003        out.opt_u8(self.max_cadence);
1004        out.opt_u16(self.avg_power);
1005        out.opt_u16(self.max_power);
1006        out.opt_u16(self.ascent);
1007        out.opt_u16(self.descent);
1008        out.position(self.north_east);
1009        out.position(self.south_west);
1010        out.opt_i8(self.avg_temperature);
1011        out.opt_i8(self.max_temperature);
1012        out.opt_u32(self.cycles);
1013        out.opt_u16(self.lengths);
1014        out.opt_u16(self.active_lengths);
1015        out.opt_u16(self.stroke_distance);
1016        out.opt_u8(self.swim_stroke.map(SwimStroke::get));
1017    }
1018}
1019
1020/// A lap or session table: its own fields, then the totals', given their field numbers, which
1021/// differ between the two.
1022macro_rules! with_totals {
1023    (
1024        [$($head:expr),* $(,)?],
1025        $start_lat:literal, $start_long:literal, $end_lat:literal, $end_long:literal,
1026        $distance:literal, $avg_speed:literal, $max_speed:literal, $avg_cadence:literal,
1027        $max_cadence:literal, $avg_power:literal, $max_power:literal, $ascent:literal,
1028        $descent:literal, $nec_lat:literal, $nec_long:literal, $swc_lat:literal,
1029        $swc_long:literal, $avg_temperature:literal, $max_temperature:literal,
1030        $cycles:literal, $lengths:literal, $active_lengths:literal, $stroke_distance:literal,
1031        $swim_stroke:literal, [$($tail:expr),* $(,)?]
1032    ) => {
1033        &[
1034            $($head,)*
1035            field($start_lat, 4, base::SINT32),
1036            field($start_long, 4, base::SINT32),
1037            field($end_lat, 4, base::SINT32),
1038            field($end_long, 4, base::SINT32),
1039            field($distance, 4, base::UINT32), // scale 100
1040            field($avg_speed, 2, base::UINT16), // scale 1000
1041            field($max_speed, 2, base::UINT16), // scale 1000
1042            field($avg_cadence, 1, base::UINT8),
1043            field($max_cadence, 1, base::UINT8),
1044            field($avg_power, 2, base::UINT16),
1045            field($max_power, 2, base::UINT16),
1046            field($ascent, 2, base::UINT16),
1047            field($descent, 2, base::UINT16),
1048            field($nec_lat, 4, base::SINT32),
1049            field($nec_long, 4, base::SINT32),
1050            field($swc_lat, 4, base::SINT32),
1051            field($swc_long, 4, base::SINT32),
1052            field($avg_temperature, 1, base::SINT8),
1053            field($max_temperature, 1, base::SINT8),
1054            field($cycles, 4, base::UINT32),
1055            field($lengths, 2, base::UINT16),
1056            field($active_lengths, 2, base::UINT16),
1057            field($stroke_distance, 2, base::UINT16), // scale 100
1058            field($swim_stroke, 1, base::ENUM),
1059            $($tail,)*
1060        ]
1061    };
1062}
1063
1064/// One lap of a session.
1065#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1066pub(crate) struct Lap {
1067    span: Span,
1068    summary: Summary,
1069    totals: Totals,
1070    first_length_index: Option<u16>,
1071    trigger: u8,
1072}
1073
1074impl Lap {
1075    /// A lap from `start_time` to `timestamp`, lasting `total_elapsed_ms` of which the timer ran
1076    /// `total_timer_ms` (the elapsed time less pauses).
1077    #[must_use]
1078    pub const fn new(
1079        start_time: Timestamp,
1080        timestamp: Timestamp,
1081        total_elapsed_ms: u32,
1082        total_timer_ms: u32,
1083    ) -> Self {
1084        Self {
1085            span: Span { start_time, timestamp, total_elapsed_ms, total_timer_ms },
1086            summary: Summary::NONE,
1087            totals: Totals::NONE,
1088            first_length_index: None,
1089            trigger: lap_trigger::MANUAL,
1090        }
1091    }
1092
1093    /// What ended it, a [`lap_trigger`] value; [`lap_trigger::MANUAL`] unless given.
1094    #[must_use]
1095    pub const fn trigger(mut self, trigger: u8) -> Self {
1096        self.trigger = trigger;
1097        self
1098    }
1099
1100    /// The index of its first length, in a pool swim.
1101    #[must_use]
1102    pub const fn first_length(mut self, index: u16) -> Self {
1103        self.first_length_index = Some(index);
1104        self
1105    }
1106
1107    #[must_use]
1108    pub const fn totals(mut self, totals: Totals) -> Self {
1109        self.totals = totals;
1110        self
1111    }
1112
1113    /// Average and maximum heart rate, in beats per minute.
1114    #[must_use]
1115    pub const fn heart_rate(mut self, avg: u8, max: u8) -> Self {
1116        self.summary.avg_heart_rate = Some(avg);
1117        self.summary.max_heart_rate = Some(max);
1118        self
1119    }
1120
1121    /// The sport and its variant.
1122    #[must_use]
1123    pub const fn sport(mut self, sport: Sport, sub_sport: SubSport) -> Self {
1124        self.summary.sport = Some(sport);
1125        self.summary.sub_sport = Some(sub_sport);
1126        self
1127    }
1128}
1129
1130impl Message for Lap {
1131    const GLOBAL: u16 = 19;
1132    const FIELDS: &'static [FieldDef] = with_totals!(
1133        [
1134            field(MESSAGE_INDEX, 2, base::UINT16),
1135            field(TIMESTAMP, 4, base::UINT32),
1136            field(0, 1, base::ENUM),   // event
1137            field(1, 1, base::ENUM),   // event_type
1138            field(2, 4, base::UINT32), // start_time
1139            field(7, 4, base::UINT32), // total_elapsed_time, scale 1000
1140            field(8, 4, base::UINT32), // total_timer_time, scale 1000
1141            field(15, 1, base::UINT8), // avg_heart_rate
1142            field(16, 1, base::UINT8), // max_heart_rate
1143            field(25, 1, base::ENUM),  // sport
1144            field(39, 1, base::ENUM),  // sub_sport
1145            field(24, 1, base::ENUM),  // lap_trigger
1146        ],
1147        3,
1148        4,
1149        5,
1150        6,
1151        9,
1152        13,
1153        14,
1154        17,
1155        18,
1156        19,
1157        20,
1158        21,
1159        22,
1160        27,
1161        28,
1162        29,
1163        30,
1164        50,
1165        51,
1166        10,
1167        32,
1168        40,
1169        37,
1170        38,
1171        [field(35, 2, base::UINT16)] // first_length_index
1172    );
1173
1174    fn timestamp(&self) -> Option<Timestamp> {
1175        Some(self.span.timestamp)
1176    }
1177
1178    fn encode(&self, out: &mut dyn FieldOut, index: u16) {
1179        let (span, summary) = (&self.span, &self.summary);
1180        out.u16(index);
1181        out.u32(span.timestamp.fit());
1182        out.u8(event::LAP);
1183        out.u8(event::STOP);
1184        out.u32(span.start_time.fit());
1185        out.u32(span.total_elapsed_ms);
1186        out.u32(span.total_timer_ms);
1187        out.opt_u8(summary.avg_heart_rate);
1188        out.opt_u8(summary.max_heart_rate);
1189        out.opt_u8(summary.sport.map(Sport::get));
1190        out.opt_u8(summary.sub_sport.map(SubSport::get));
1191        out.u8(self.trigger);
1192        self.totals.encode(out);
1193        out.opt_u16(self.first_length_index);
1194    }
1195}
1196
1197/// One sport's part of the activity; one, for a single-sport activity.
1198#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1199pub(crate) struct Session {
1200    span: Span,
1201    summary: Summary,
1202    totals: Totals,
1203    first_lap_index: u16,
1204    num_laps: u16,
1205    pool: Option<Pool>,
1206    trigger: u8,
1207}
1208
1209impl Session {
1210    /// A session from `start_time` to `timestamp`, lasting `total_elapsed_ms` of which the
1211    /// timer ran `total_timer_ms`. It covers one lap, the first, until [`Session::laps`] says
1212    /// otherwise.
1213    #[must_use]
1214    pub const fn new(
1215        start_time: Timestamp,
1216        timestamp: Timestamp,
1217        total_elapsed_ms: u32,
1218        total_timer_ms: u32,
1219    ) -> Self {
1220        Self {
1221            span: Span { start_time, timestamp, total_elapsed_ms, total_timer_ms },
1222            summary: Summary::NONE,
1223            totals: Totals::NONE,
1224            first_lap_index: 0,
1225            num_laps: 1,
1226            pool: None,
1227            trigger: trigger::ACTIVITY_END,
1228        }
1229    }
1230
1231    /// What ended it, one of [`trigger`]'s; the activity's end until said otherwise.
1232    #[must_use]
1233    pub const fn trigger(mut self, trigger: u8) -> Self {
1234        self.trigger = trigger;
1235        self
1236    }
1237
1238    /// The pool it swam in.
1239    #[must_use]
1240    pub const fn pool(mut self, pool: Pool) -> Self {
1241        self.pool = Some(pool);
1242        self
1243    }
1244
1245    #[must_use]
1246    pub const fn totals(mut self, totals: Totals) -> Self {
1247        self.totals = totals;
1248        self
1249    }
1250
1251    /// Average and maximum heart rate, in beats per minute.
1252    #[must_use]
1253    pub const fn heart_rate(mut self, avg: u8, max: u8) -> Self {
1254        self.summary.avg_heart_rate = Some(avg);
1255        self.summary.max_heart_rate = Some(max);
1256        self
1257    }
1258
1259    /// The sport and its variant.
1260    #[must_use]
1261    pub const fn sport(mut self, sport: Sport, sub_sport: SubSport) -> Self {
1262        self.summary.sport = Some(sport);
1263        self.summary.sub_sport = Some(sub_sport);
1264        self
1265    }
1266
1267    /// The laps it covers: `count` laps from the lap with `message_index` `first`.
1268    #[must_use]
1269    pub const fn laps(mut self, first: u16, count: u16) -> Self {
1270        self.first_lap_index = first;
1271        self.num_laps = count;
1272        self
1273    }
1274}
1275
1276impl Message for Session {
1277    const GLOBAL: u16 = 18;
1278    const FIELDS: &'static [FieldDef] = with_totals!(
1279        [
1280            field(MESSAGE_INDEX, 2, base::UINT16),
1281            field(TIMESTAMP, 4, base::UINT32),
1282            field(0, 1, base::ENUM),    // event
1283            field(1, 1, base::ENUM),    // event_type
1284            field(2, 4, base::UINT32),  // start_time
1285            field(5, 1, base::ENUM),    // sport
1286            field(6, 1, base::ENUM),    // sub_sport
1287            field(7, 4, base::UINT32),  // total_elapsed_time, scale 1000
1288            field(8, 4, base::UINT32),  // total_timer_time, scale 1000
1289            field(16, 1, base::UINT8),  // avg_heart_rate
1290            field(17, 1, base::UINT8),  // max_heart_rate
1291            field(25, 2, base::UINT16), // first_lap_index
1292            field(26, 2, base::UINT16), // num_laps
1293        ],
1294        3,
1295        4,
1296        38,
1297        39,
1298        9,
1299        14,
1300        15,
1301        18,
1302        19,
1303        20,
1304        21,
1305        22,
1306        23,
1307        29,
1308        30,
1309        31,
1310        32,
1311        57,
1312        58,
1313        10,
1314        33,
1315        47,
1316        42,
1317        43,
1318        [
1319            field(44, 2, base::UINT16), // pool_length, scale 100
1320            field(46, 1, base::ENUM),   // pool_length_unit
1321            field(28, 1, base::ENUM),   // trigger
1322        ]
1323    );
1324
1325    fn timestamp(&self) -> Option<Timestamp> {
1326        Some(self.span.timestamp)
1327    }
1328
1329    fn encode(&self, out: &mut dyn FieldOut, index: u16) {
1330        let (span, summary) = (&self.span, &self.summary);
1331        out.u16(index);
1332        out.u32(span.timestamp.fit());
1333        out.u8(event::SESSION);
1334        out.u8(event::STOP);
1335        out.u32(span.start_time.fit());
1336        out.opt_u8(summary.sport.map(Sport::get));
1337        out.opt_u8(summary.sub_sport.map(SubSport::get));
1338        out.u32(span.total_elapsed_ms);
1339        out.u32(span.total_timer_ms);
1340        out.opt_u8(summary.avg_heart_rate);
1341        out.opt_u8(summary.max_heart_rate);
1342        out.u16(self.first_lap_index);
1343        out.u16(self.num_laps);
1344        self.totals.encode(out);
1345        out.opt_u16(self.pool.map(|p| p.centimetres));
1346        out.opt_u8(self.pool.map(|p| p.unit));
1347        out.u8(self.trigger);
1348    }
1349}
1350
1351/// `lap_trigger` values: what ended a lap.
1352pub(crate) mod lap_trigger {
1353    pub const MANUAL: u8 = 0;
1354    pub const SESSION_END: u8 = 7;
1355}
1356
1357/// What ended a lap, for [`Writer::lap_by`](crate::Writer::lap_by): the profile's
1358/// `lap_trigger`, less `session_end`, which the encoder writes on each session's last lap.
1359#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1360#[non_exhaustive]
1361pub enum LapTrigger {
1362    /// The wearer.
1363    Manual,
1364    /// A lap time.
1365    Time,
1366    /// A lap distance.
1367    Distance,
1368    /// Reaching the start position.
1369    PositionStart,
1370    /// Reaching a lap position.
1371    PositionLap,
1372    /// Reaching a waypoint.
1373    PositionWaypoint,
1374    /// Reaching a marked position.
1375    PositionMarked,
1376    /// Fitness equipment.
1377    FitnessEquipment,
1378}
1379
1380impl LapTrigger {
1381    /// Its value in the profile.
1382    pub(crate) const fn get(self) -> u8 {
1383        match self {
1384            Self::Manual => lap_trigger::MANUAL,
1385            Self::Time => 1,
1386            Self::Distance => 2,
1387            Self::PositionStart => 3,
1388            Self::PositionLap => 4,
1389            Self::PositionWaypoint => 5,
1390            Self::PositionMarked => 6,
1391            Self::FitnessEquipment => 8,
1392        }
1393    }
1394
1395    /// The profile's name for it.
1396    #[must_use]
1397    pub const fn name(self) -> &'static str {
1398        match self {
1399            Self::Manual => "manual",
1400            Self::Time => "time",
1401            Self::Distance => "distance",
1402            Self::PositionStart => "position_start",
1403            Self::PositionLap => "position_lap",
1404            Self::PositionWaypoint => "position_waypoint",
1405            Self::PositionMarked => "position_marked",
1406            Self::FitnessEquipment => "fitness_equipment",
1407        }
1408    }
1409}
1410
1411impl core::fmt::Display for LapTrigger {
1412    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1413        f.write_str(self.name())
1414    }
1415}
1416
1417/// `session_trigger` values: what ended a session.
1418pub(crate) mod trigger {
1419    pub const ACTIVITY_END: u8 = 0;
1420    pub const MANUAL: u8 = 1;
1421    pub const AUTO_MULTI_SPORT: u8 = 2;
1422}
1423
1424/// The longest sport name, in UTF-8 bytes; one more byte holds its terminating NUL.
1425pub const SPORT_NAME_MAX: usize = 23;
1426
1427/// A `sport` message: the sport of the session it starts, and the name of its profile.
1428#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1429pub(crate) struct SportMsg<'a> {
1430    pub sport: Sport,
1431    pub sub_sport: SubSport,
1432    pub name: &'a str,
1433}
1434
1435impl Message for SportMsg<'_> {
1436    const GLOBAL: u16 = 12;
1437    #[allow(clippy::cast_possible_truncation, reason = "a short name")]
1438    const FIELDS: &'static [FieldDef] = &[
1439        field(0, 1, base::ENUM),                          // sport
1440        field(1, 1, base::ENUM),                          // sub_sport
1441        field(3, SPORT_NAME_MAX as u8 + 1, base::STRING), // name
1442    ];
1443
1444    fn timestamp(&self) -> Option<Timestamp> {
1445        None
1446    }
1447
1448    fn encode(&self, out: &mut dyn FieldOut, _: u16) {
1449        out.u8(self.sport.get());
1450        out.u8(self.sub_sport.get());
1451        out.str(self.name);
1452    }
1453}
1454
1455/// A session for [`Writer::leg`](crate::Writer::leg) to start: its sport, the pool of a pool
1456/// swim, the name of its profile, and whether the wearer moved to it by hand.
1457///
1458/// ```
1459/// use fit_encoder::{Leg, Pool, Sport, SubSport};
1460///
1461/// let run = Leg::new(Sport::RUNNING, SubSport::TRAIL).named("Trail Run");
1462/// let swim = Leg::pool_swim(Pool::meters(25.0)).by_hand();
1463/// # let _ = (run, swim);
1464/// ```
1465#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1466pub struct Leg<'a> {
1467    pub(crate) sport: SportMsg<'a>,
1468    pub(crate) pool: Option<Pool>,
1469    pub(crate) by_hand: bool,
1470}
1471
1472impl<'a> Leg<'a> {
1473    /// A session of `sport`; not `lap_swimming`, which [`Leg::pool_swim`] starts.
1474    #[must_use]
1475    pub const fn new(sport: Sport, sub_sport: SubSport) -> Self {
1476        Self { sport: SportMsg { sport, sub_sport, name: "" }, pool: None, by_hand: false }
1477    }
1478
1479    /// A pool swim in `pool`, whose lengths give its distance.
1480    #[must_use]
1481    pub const fn pool_swim(pool: Pool) -> Self {
1482        let sport =
1483            SportMsg { sport: Sport::SWIMMING, sub_sport: SubSport::LAP_SWIMMING, name: "" };
1484        Self { sport, pool: Some(pool), by_hand: false }
1485    }
1486
1487    /// The name of the sport's profile on the device, such as "Open Water", up to
1488    /// [`SPORT_NAME_MAX`] bytes.
1489    #[must_use]
1490    pub const fn named(mut self, name: &'a str) -> Self {
1491        self.sport.name = name;
1492        self
1493    }
1494
1495    /// The wearer moved to it by hand, in an activity whose profile otherwise moves on by
1496    /// itself ([`Options::auto_multisport`](crate::Options::auto_multisport)): the session
1497    /// before it was ended `manual`. Without that option every session is. Not a first leg.
1498    #[must_use]
1499    pub const fn by_hand(mut self) -> Self {
1500        self.by_hand = true;
1501        self
1502    }
1503}
1504
1505/// A swimming pool's length, which every length of a pool swim covers.
1506///
1507/// ```
1508/// use fit_encoder::Pool;
1509///
1510/// let pool = Pool::yards(25.0);
1511/// # let _ = pool;
1512/// ```
1513#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1514pub struct Pool {
1515    /// `u16::MAX` and 0 are out of range.
1516    pub(crate) centimetres: u16,
1517    /// The profile's `display_measure`: metric or statute.
1518    pub(crate) unit: u8,
1519}
1520
1521impl Pool {
1522    /// A pool measured in metres, up to 655.34, to the centimetre.
1523    #[must_use]
1524    pub fn meters(meters: f64) -> Self {
1525        Self::of(meters, 0)
1526    }
1527
1528    /// A pool measured in yards, up to 716.68, kept to the centimetre; 25 yd is 22.86 m.
1529    #[must_use]
1530    pub fn yards(yards: f64) -> Self {
1531        Self::of(yards * 0.9144, 1)
1532    }
1533
1534    fn of(meters: f64, unit: u8) -> Self {
1535        let cm = scaled(meters, 100.0, u32::from(u16::MAX));
1536        Self { centimetres: u16::try_from(cm).unwrap_or(u16::MAX), unit }
1537    }
1538}
1539
1540/// One length of a pool swum: its stroke and stroke count, or a drill.
1541///
1542/// ```
1543/// use fit_encoder::{Length, SwimStroke};
1544///
1545/// let length = Length::swum(SwimStroke::FREESTYLE, 18);
1546/// # let _ = length;
1547/// ```
1548#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1549pub struct Length {
1550    pub(crate) stroke: SwimStroke,
1551    pub(crate) strokes: Option<u16>,
1552}
1553
1554impl Length {
1555    /// A length swum in `stroke`, taking `strokes` strokes, up to 65,534; a drill's strokes
1556    /// are not counted, as [`Length::drill`].
1557    #[must_use]
1558    pub const fn swum(stroke: SwimStroke, strokes: u16) -> Self {
1559        if stroke.get() == SwimStroke::DRILL.get() {
1560            return Self::drill();
1561        }
1562        Self { stroke, strokes: Some(strokes) }
1563    }
1564
1565    /// A length of drill, whose strokes are not counted.
1566    #[must_use]
1567    pub const fn drill() -> Self {
1568        Self { stroke: SwimStroke::DRILL, strokes: None }
1569    }
1570}
1571
1572/// A strength exercise: its category and, optionally, its name within the category, the
1573/// number from that category's list of names (`bench_press_exercise_name` and so on).
1574///
1575/// ```
1576/// use fit_encoder::{Exercise, ExerciseCategory};
1577///
1578/// let squat = Exercise::new(ExerciseCategory::SQUAT);
1579/// let goblet_squat = squat.name(37);
1580/// # let _ = goblet_squat;
1581/// ```
1582#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1583pub struct Exercise {
1584    pub(crate) category: ExerciseCategory,
1585    pub(crate) name: Option<u16>,
1586}
1587
1588impl Exercise {
1589    /// An exercise of `category`, not named further.
1590    #[must_use]
1591    pub const fn new(category: ExerciseCategory) -> Self {
1592        Self { category, name: None }
1593    }
1594
1595    /// Its name's number in its category's list, up to 65,534.
1596    #[must_use]
1597    pub const fn name(mut self, name: u16) -> Self {
1598        self.name = Some(name);
1599        self
1600    }
1601}
1602
1603/// A strength set as it ended: what was lifted, how many times.
1604///
1605/// ```
1606/// use fit_encoder::{Exercise, ExerciseCategory, Set};
1607///
1608/// let set = Set::new()
1609///     .exercise(Exercise::new(ExerciseCategory::BENCH_PRESS))
1610///     .repetitions(8)
1611///     .weight_kilograms(60.0);
1612/// # let _ = set;
1613/// ```
1614#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1615pub struct Set {
1616    pub(crate) exercise: Option<Exercise>,
1617    pub(crate) repetitions: Option<u16>,
1618    /// Sixteenths of a kilogram; `u16::MAX` is out of range.
1619    pub(crate) weight: Option<u16>,
1620    /// The profile's `fit_base_unit`: kilogram or pound.
1621    pub(crate) weight_unit: Option<u16>,
1622}
1623
1624impl Set {
1625    /// A set with nothing known of it but its time.
1626    #[must_use]
1627    pub const fn new() -> Self {
1628        Self { exercise: None, repetitions: None, weight: None, weight_unit: None }
1629    }
1630
1631    /// The exercise.
1632    #[must_use]
1633    pub const fn exercise(mut self, exercise: Exercise) -> Self {
1634        self.exercise = Some(exercise);
1635        self
1636    }
1637
1638    /// The repetitions, up to 65,534.
1639    #[must_use]
1640    pub const fn repetitions(mut self, repetitions: u16) -> Self {
1641        self.repetitions = Some(repetitions);
1642        self
1643    }
1644
1645    /// The weight lifted in kilograms, up to 4,095.875, to a sixteenth; shown in kilograms.
1646    #[must_use]
1647    pub fn weight_kilograms(self, kilograms: f64) -> Self {
1648        self.weight(kilograms, KILOGRAM)
1649    }
1650
1651    /// The weight lifted in pounds, up to 9,029.8, kept to a sixteenth of a kilogram; shown in
1652    /// pounds.
1653    #[must_use]
1654    pub fn weight_pounds(self, pounds: f64) -> Self {
1655        self.weight(pounds * 0.453_592_37, POUND)
1656    }
1657
1658    fn weight(mut self, kilograms: f64, unit: u16) -> Self {
1659        let raw = scaled(kilograms, 16.0, u32::from(u16::MAX));
1660        self.weight = Some(u16::try_from(raw).unwrap_or(u16::MAX));
1661        self.weight_unit = Some(unit);
1662        self
1663    }
1664}
1665
1666/// `fit_base_unit` values.
1667const KILOGRAM: u16 = 1;
1668const POUND: u16 = 2;
1669
1670/// A `length` message: one length of a pool, swum or rested.
1671#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1672pub(crate) struct LengthMsg {
1673    pub span: Span,
1674    /// None for a rest, an idle length.
1675    pub swum: Option<Length>,
1676    pub avg_speed: Option<u16>,
1677    pub cadence: Option<u8>,
1678}
1679
1680impl LengthMsg {
1681    /// The fields only a swum length has: strokes, speed, stroke and stroke rate.
1682    pub const SWUM: &'static [u8] = &[5, 6, 7, 9];
1683}
1684
1685impl Message for LengthMsg {
1686    const GLOBAL: u16 = 101;
1687    const FIELDS: &'static [FieldDef] = &[
1688        field(MESSAGE_INDEX, 2, base::UINT16),
1689        field(TIMESTAMP, 4, base::UINT32),
1690        field(0, 1, base::ENUM),   // event
1691        field(1, 1, base::ENUM),   // event_type
1692        field(2, 4, base::UINT32), // start_time
1693        field(3, 4, base::UINT32), // total_elapsed_time, scale 1000
1694        field(4, 4, base::UINT32), // total_timer_time, scale 1000
1695        field(5, 2, base::UINT16), // total_strokes
1696        field(6, 2, base::UINT16), // avg_speed, scale 1000
1697        field(7, 1, base::ENUM),   // swim_stroke
1698        field(9, 1, base::UINT8),  // avg_swimming_cadence
1699        field(12, 1, base::ENUM),  // length_type
1700    ];
1701
1702    fn timestamp(&self) -> Option<Timestamp> {
1703        Some(self.span.timestamp)
1704    }
1705
1706    fn encode(&self, out: &mut dyn FieldOut, index: u16) {
1707        const IDLE: u8 = 0;
1708        const ACTIVE: u8 = 1;
1709        let span = &self.span;
1710        out.u16(index);
1711        out.u32(span.timestamp.fit());
1712        out.u8(event::LENGTH);
1713        out.u8(event::STOP);
1714        out.u32(span.start_time.fit());
1715        out.u32(span.total_elapsed_ms);
1716        out.u32(span.total_timer_ms);
1717        out.opt_u16(self.swum.and_then(|l| l.strokes));
1718        out.opt_u16(self.avg_speed);
1719        out.opt_u8(self.swum.map(|l| l.stroke.get()));
1720        out.opt_u8(self.cadence);
1721        out.u8(if self.swum.is_some() { ACTIVE } else { IDLE });
1722    }
1723}
1724
1725/// A `set` message: one strength set, or a rest between sets.
1726#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1727pub(crate) struct SetMsg {
1728    pub start_time: Timestamp,
1729    pub timestamp: Timestamp,
1730    pub duration_ms: u32,
1731    /// None for a rest.
1732    pub set: Option<Set>,
1733}
1734
1735impl SetMsg {
1736    /// The fields only an active set has: repetitions, weight, exercise and weight unit.
1737    pub const ACTIVE: &'static [u8] = &[3, 4, 7, 8, 9];
1738}
1739
1740impl Message for SetMsg {
1741    const GLOBAL: u16 = 225;
1742    const FIELDS: &'static [FieldDef] = &[
1743        field(254, 4, base::UINT32), // timestamp, at 254 in this message
1744        field(0, 4, base::UINT32),   // duration, scale 1000
1745        field(3, 2, base::UINT16),   // repetitions
1746        field(4, 2, base::UINT16),   // weight, scale 16
1747        field(5, 1, base::UINT8),    // set_type
1748        field(6, 4, base::UINT32),   // start_time
1749        field(7, 2, base::UINT16),   // category, an array
1750        field(8, 2, base::UINT16),   // category_subtype, an array
1751        field(9, 2, base::UINT16),   // weight_display_unit
1752        field(10, 2, base::UINT16),  // message_index, at 10 in this message
1753    ];
1754
1755    fn timestamp(&self) -> Option<Timestamp> {
1756        None
1757    }
1758
1759    fn encode(&self, out: &mut dyn FieldOut, index: u16) {
1760        const REST: u8 = 0;
1761        const ACTIVE: u8 = 1;
1762        let set = self.set.unwrap_or_default();
1763        let exercise = set.exercise;
1764        out.u32(self.timestamp.fit());
1765        out.u32(self.duration_ms);
1766        out.opt_u16(set.repetitions);
1767        out.opt_u16(set.weight);
1768        out.u8(if self.set.is_some() { ACTIVE } else { REST });
1769        out.u32(self.start_time.fit());
1770        out.u16s(exercise.as_ref().map(|e| e.category.get()).as_slice());
1771        out.u16s(exercise.and_then(|e| e.name).as_slice());
1772        out.opt_u16(set.weight_unit);
1773        out.u16(index);
1774    }
1775}
1776
1777/// Beat intervals a `hrv` message holds.
1778pub(crate) const HRV_BEATS: usize = 5;
1779
1780/// A `hrv` message: up to five beat intervals, in milliseconds, the rest "none".
1781#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1782pub(crate) struct Hrv<'a>(pub &'a [u16]);
1783
1784impl Message for Hrv<'_> {
1785    const GLOBAL: u16 = 78;
1786    #[allow(clippy::cast_possible_truncation, reason = "five two-byte values")]
1787    const FIELDS: &'static [FieldDef] = &[field(0, HRV_BEATS as u8 * 2, base::UINT16)]; // time, scale 1000
1788
1789    fn timestamp(&self) -> Option<Timestamp> {
1790        None
1791    }
1792
1793    fn encode(&self, out: &mut dyn FieldOut, _: u16) {
1794        out.u16s(self.0);
1795    }
1796}
1797
1798/// The whole activity; exactly one per activity file, usually last.
1799#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1800pub(crate) struct Activity {
1801    timestamp: Timestamp,
1802    total_timer_ms: u32,
1803    num_sessions: u16,
1804    utc_offset: Option<i32>,
1805    auto_multisport: bool,
1806}
1807
1808impl Activity {
1809    /// An activity ending at `timestamp` whose timer ran `total_timer_ms`, of one session.
1810    #[must_use]
1811    pub const fn new(timestamp: Timestamp, total_timer_ms: u32) -> Self {
1812        Self {
1813            timestamp,
1814            total_timer_ms,
1815            num_sessions: 1,
1816            utc_offset: None,
1817            auto_multisport: false,
1818        }
1819    }
1820
1821    /// Whether a multisport profile moved it from one session to the next, rather than its
1822    /// user.
1823    #[must_use]
1824    pub const fn auto_multisport(mut self, auto: bool) -> Self {
1825        self.auto_multisport = auto;
1826        self
1827    }
1828
1829    /// How many sessions it has.
1830    #[must_use]
1831    pub const fn sessions(mut self, num_sessions: u16) -> Self {
1832        self.num_sessions = num_sessions;
1833        self
1834    }
1835
1836    /// The local time zone's offset from UTC in seconds, written as `local_timestamp`. One that
1837    /// takes the local time out of range is refused.
1838    #[must_use]
1839    pub const fn utc_offset(mut self, seconds: i32) -> Self {
1840        self.utc_offset = Some(seconds);
1841        self
1842    }
1843
1844    /// Out of range is "none", which writing refuses.
1845    fn local_timestamp(&self) -> Option<u32> {
1846        let offset = self.utc_offset?;
1847        Some(self.timestamp.fit().checked_add_signed(offset).unwrap_or(INVALID_U32))
1848    }
1849}
1850
1851impl Message for Activity {
1852    const GLOBAL: u16 = 34;
1853    const FIELDS: &'static [FieldDef] = &[
1854        field(TIMESTAMP, 4, base::UINT32),
1855        field(0, 4, base::UINT32), // total_timer_time, scale 1000
1856        field(1, 2, base::UINT16), // num_sessions
1857        field(2, 1, base::ENUM),   // type
1858        field(3, 1, base::ENUM),   // event
1859        field(4, 1, base::ENUM),   // event_type
1860        field(5, 4, base::UINT32), // local_timestamp
1861    ];
1862
1863    fn timestamp(&self) -> Option<Timestamp> {
1864        Some(self.timestamp)
1865    }
1866
1867    fn encode(&self, out: &mut dyn FieldOut, _: u16) {
1868        const MANUAL: u8 = 0;
1869        const AUTO_MULTI_SPORT: u8 = 1;
1870        out.u32(self.timestamp.fit());
1871        out.u32(self.total_timer_ms);
1872        out.u16(self.num_sessions);
1873        out.u8(if self.auto_multisport { AUTO_MULTI_SPORT } else { MANUAL });
1874        out.u8(event::ACTIVITY);
1875        out.u8(event::STOP);
1876        out.opt_u32(self.local_timestamp());
1877    }
1878}
1879
1880#[cfg(test)]
1881mod tests {
1882    use super::*;
1883    use crate::types::{
1884        ExerciseCategory, FileType, Manufacturer, Sport, SubSport, SwimStroke, Timestamp,
1885    };
1886    use std::vec;
1887
1888    struct VecPut(std::vec::Vec<u8>);
1889
1890    impl Put for VecPut {
1891        fn put(&mut self, bytes: &[u8]) {
1892            self.0.extend_from_slice(bytes);
1893        }
1894    }
1895
1896    /// Counts the values a message gives, so a table and its `encode` cannot drift apart.
1897    struct Count(usize);
1898
1899    impl FieldOut for Count {
1900        fn u8(&mut self, _: u8) {
1901            self.0 += 1;
1902        }
1903        fn u16(&mut self, _: u16) {
1904            self.0 += 1;
1905        }
1906        fn u32(&mut self, _: u32) {
1907            self.0 += 1;
1908        }
1909        fn i8(&mut self, _: i8) {
1910            self.0 += 1;
1911        }
1912        fn i32(&mut self, _: i32) {
1913            self.0 += 1;
1914        }
1915        fn str(&mut self, _: &str) {
1916            self.0 += 1;
1917        }
1918        fn u16s(&mut self, _: &[u16]) {
1919            self.0 += 1;
1920        }
1921        fn bytes(&mut self, _: &[u8]) {
1922            self.0 += 1;
1923        }
1924        fn none(&mut self) {
1925            self.0 += 1;
1926        }
1927    }
1928
1929    fn refused<M: Message>(msg: &M, index: u16) -> Option<FieldError> {
1930        let mut fields = Fields::new(M::FIELDS.iter().copied(), None);
1931        msg.encode(&mut fields, index);
1932        fields.refused()
1933    }
1934
1935    fn bytes<M: Message>(msg: &M, index: u16) -> std::vec::Vec<u8> {
1936        let mut count = Count(0);
1937        msg.encode(&mut count, index);
1938        assert_eq!(count.0, M::FIELDS.len(), "{}: a value per field", M::GLOBAL);
1939        let mut out = VecPut(vec![]);
1940        let mut fields = Fields::new(M::FIELDS.iter().copied(), Some(&mut out));
1941        msg.encode(&mut fields, index);
1942        assert_eq!(fields.refused(), None);
1943        fields.finish();
1944        assert_eq!(u32::try_from(out.0.len()).unwrap(), data_len(M::FIELDS.iter().copied()));
1945        out.0
1946    }
1947
1948    const T: Timestamp = Timestamp::from_fit(0x1122_3344);
1949    const T2: Timestamp = Timestamp::from_fit(0x1122_3380);
1950
1951    /// Totals left unset: "none" for each, signed ones with a clear top bit.
1952    #[rustfmt::skip]
1953    const NO_TOTALS: [u8; 63] = [
1954        0xFF, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0x7F, // start
1955        0xFF, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0x7F, // end
1956        0xFF, 0xFF, 0xFF, 0xFF, // distance
1957        0xFF, 0xFF, 0xFF, 0xFF, // speeds
1958        0xFF, 0xFF, // cadences
1959        0xFF, 0xFF, 0xFF, 0xFF, // powers
1960        0xFF, 0xFF, 0xFF, 0xFF, // ascent, descent
1961        0xFF, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0x7F, // north-east
1962        0xFF, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0x7F, // south-west
1963        0x7F, 0x7F, // temperatures
1964        0xFF, 0xFF, 0xFF, 0xFF, // cycles
1965        0xFF, 0xFF, 0xFF, 0xFF, // lengths
1966        0xFF, 0xFF, 0xFF, // stroke distance, swim stroke
1967    ];
1968
1969    fn totals() -> Totals {
1970        let p = |lat, long| Position::from_semicircles(lat, long);
1971        Totals {
1972            start: p(1, -2),
1973            end: p(3, -4),
1974            north_east: p(5, -6),
1975            south_west: p(7, -8),
1976            distance: Some(0x0102_0304),
1977            avg_speed: Some(0x0506),
1978            max_speed: Some(0x0708),
1979            avg_cadence: Some(9),
1980            max_cadence: Some(10),
1981            avg_power: Some(0x0B0C),
1982            max_power: Some(0x0D0E),
1983            ascent: Some(0x0F10),
1984            descent: Some(0x1112),
1985            avg_temperature: Some(-13),
1986            max_temperature: Some(14),
1987            cycles: Some(0x1314_1516),
1988            lengths: Some(0x1718),
1989            active_lengths: Some(0x191A),
1990            stroke_distance: Some(0x1B1C),
1991            swim_stroke: Some(SwimStroke::new(0x1D)),
1992        }
1993    }
1994
1995    #[rustfmt::skip]
1996    const TOTALS: [u8; 63] = [
1997        1, 0, 0, 0, 0xFE, 0xFF, 0xFF, 0xFF,
1998        3, 0, 0, 0, 0xFC, 0xFF, 0xFF, 0xFF,
1999        0x04, 0x03, 0x02, 0x01,
2000        0x06, 0x05, 0x08, 0x07,
2001        9, 10,
2002        0x0C, 0x0B, 0x0E, 0x0D,
2003        0x10, 0x0F, 0x12, 0x11,
2004        5, 0, 0, 0, 0xFA, 0xFF, 0xFF, 0xFF,
2005        7, 0, 0, 0, 0xF8, 0xFF, 0xFF, 0xFF,
2006        0xF3, 14,
2007        0x16, 0x15, 0x14, 0x13,
2008        0x18, 0x17, 0x1A, 0x19,
2009        0x1C, 0x1B, 0x1D,
2010    ];
2011
2012    #[test]
2013    fn file_id() {
2014        let id = FileId::new(FileType::ACTIVITY, Manufacturer::DEVELOPMENT, 0x0102, T)
2015            .serial_number(0xAABB_CCDD);
2016        assert_eq!(
2017            bytes(&id, 0),
2018            [4, 0xFF, 0x00, 0x02, 0x01, 0xDD, 0xCC, 0xBB, 0xAA, 0x44, 0x33, 0x22, 0x11]
2019        );
2020        let no_serial = FileId::new(FileType::new(9), Manufacturer::new(1), 2, T);
2021        assert_eq!(bytes(&no_serial, 0), [9, 1, 0, 2, 0, 0, 0, 0, 0, 0x44, 0x33, 0x22, 0x11]);
2022        assert_eq!(id.timestamp(), None);
2023    }
2024
2025    #[test]
2026    fn device_info() {
2027        let info = DeviceInfo::new(T)
2028            .device_index(2)
2029            .manufacturer(Manufacturer::new(0x0304))
2030            .serial_number(7)
2031            .product(0x0506)
2032            .software_version(123)
2033            .product_name("Watch");
2034        let mut want = vec![0x44, 0x33, 0x22, 0x11, 2, 0x04, 0x03, 7, 0, 0, 0, 0x06, 0x05, 123, 0];
2035        want.extend_from_slice(b"Watch");
2036        want.resize(want.len() + 15, 0);
2037        assert_eq!(bytes(&info, 0), want);
2038        assert_eq!(info.timestamp(), Some(T));
2039
2040        let mut empty =
2041            vec![0x44, 0x33, 0x22, 0x11, 0, 0xFF, 0xFF, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF];
2042        empty.resize(empty.len() + 20, 0);
2043        assert_eq!(bytes(&DeviceInfo::new(T), 0), empty);
2044    }
2045
2046    #[test]
2047    fn product_name_limit() {
2048        let longest = "0123456789abcdefghi";
2049        assert_eq!(longest.len(), PRODUCT_NAME_MAX);
2050        let out = bytes(&DeviceInfo::new(T).product_name(longest), 0);
2051        assert_eq!(out.last(), Some(&0));
2052        let long = DeviceInfo::new(T).product_name("0123456789abcdefghij");
2053        assert_eq!(refused(&long, 0), Some(FieldError::StringTooLong));
2054    }
2055
2056    #[test]
2057    fn events() {
2058        let t = [0x44, 0x33, 0x22, 0x11];
2059        assert_eq!(bytes(&Event::timer_start(T), 0), [&t[..], &[0, 0]].concat());
2060        assert_eq!(bytes(&Event::timer_stop(T), 0), [&t[..], &[0, 1]].concat());
2061        assert_eq!(bytes(&Event::timer_stop_all(T), 0), [&t[..], &[0, 4]].concat());
2062        assert_eq!(Event::timer_start(T).timestamp(), Some(T));
2063    }
2064
2065    #[test]
2066    fn lap() {
2067        let lap = Lap::new(T, T2, 0x0001_0203, 0x0004_0506)
2068            .heart_rate(120, 150)
2069            .sport(Sport::RUNNING, SubSport::TREADMILL);
2070        let out = bytes(&lap, 0x0102);
2071        assert_eq!(
2072            out[..24],
2073            [
2074                0x02, 0x01, 0x80, 0x33, 0x22, 0x11, 9, 1, 0x44, 0x33, 0x22, 0x11, 0x03, 0x02, 0x01,
2075                0x00, 0x06, 0x05, 0x04, 0x00, 120, 150, 1, 1
2076            ]
2077        );
2078        assert_eq!(out[24], lap_trigger::MANUAL);
2079        assert_eq!(out[25..88], NO_TOTALS);
2080        assert_eq!(out[88..], [0xFF, 0xFF]);
2081        let ended = bytes(&lap.trigger(lap_trigger::SESSION_END), 0x0102);
2082        assert_eq!(ended[24], 7);
2083        let bare = bytes(&Lap::new(T, T2, 0, 0), 0);
2084        assert_eq!(bare.get(20..24), Some(&[0xFF; 4][..]));
2085        let full = bytes(&lap.totals(totals()).first_length(0x1E1F), 0x0102);
2086        assert_eq!((&full[25..88], &full[88..]), (&TOTALS[..], &[0x1F, 0x1E][..]));
2087        assert_eq!(lap.timestamp(), Some(T2));
2088    }
2089
2090    #[test]
2091    fn session() {
2092        let session = Session::new(T, T2, 0x0001_0203, 0x0004_0506)
2093            .heart_rate(121, 151)
2094            .sport(Sport::TRAINING, SubSport::CARDIO_TRAINING)
2095            .laps(3, 4);
2096        let out = bytes(&session, 5);
2097        assert_eq!(
2098            out[..28],
2099            [
2100                5, 0, 0x80, 0x33, 0x22, 0x11, 8, 1, 0x44, 0x33, 0x22, 0x11, 10, 26, 0x03, 0x02,
2101                0x01, 0x00, 0x06, 0x05, 0x04, 0x00, 121, 151, 3, 0, 4, 0
2102            ]
2103        );
2104        assert_eq!(out[28..91], NO_TOTALS);
2105        assert_eq!(out[91..], [0xFF, 0xFF, 0xFF, trigger::ACTIVITY_END]);
2106        let bare = bytes(&Session::new(T, T2, 0, 0), 0);
2107        assert_eq!(bare.get(12..14), Some(&[0xFF; 2][..]));
2108        assert_eq!(bare.get(22..28), Some(&[0xFF, 0xFF, 0, 0, 1, 0][..]));
2109        let full = session.totals(totals()).pool(Pool::yards(25.0)).trigger(trigger::MANUAL);
2110        let full = bytes(&full, 5);
2111        assert_eq!((&full[28..91], &full[91..]), (&TOTALS[..], &[0xEE, 0x08, 1, 1][..]));
2112        assert_eq!(session.timestamp(), Some(T2));
2113    }
2114
2115    #[test]
2116    fn activity() {
2117        let a = Activity::new(T2, 0x0004_0506).sessions(2).utc_offset(-0x80);
2118        assert_eq!(
2119            bytes(&a, 0),
2120            [
2121                0x80, 0x33, 0x22, 0x11, 0x06, 0x05, 0x04, 0x00, 2, 0, 0, 26, 1, 0x00, 0x33, 0x22,
2122                0x11
2123            ]
2124        );
2125        let none = bytes(&Activity::new(T2, 0), 0);
2126        assert_eq!(none.get(8..11), Some(&[1, 0, 0][..]), "one session, manual");
2127        let auto = bytes(&Activity::new(T2, 0).auto_multisport(true), 0);
2128        assert_eq!(auto.get(10), Some(&1), "auto_multi_sport");
2129        assert_eq!(none.get(13..), Some(&[0xFF; 4][..]));
2130        assert_eq!(a.timestamp(), Some(T2));
2131    }
2132
2133    #[test]
2134    fn sports() {
2135        let named = SportMsg { sport: Sport::new(5), sub_sport: SubSport::new(18), name: "Swim" };
2136        let mut want = [0u8; 26];
2137        want[..6].copy_from_slice(&[5, 18, b'S', b'w', b'i', b'm']);
2138        assert_eq!(bytes(&named, 0), want);
2139        let unnamed = bytes(&SportMsg { name: "", ..named }, 0);
2140        assert_eq!(unnamed, [&[5, 18][..], &[0; 24]].concat(), "a string's none");
2141        let long = "a name of twenty-four by";
2142        assert_eq!(long.len(), SPORT_NAME_MAX + 1);
2143        assert_eq!(refused(&SportMsg { name: long, ..named }, 0), Some(FieldError::StringTooLong));
2144        assert_eq!(named.timestamp(), None);
2145    }
2146
2147    #[test]
2148    fn local_timestamp_out_of_range_is_refused() {
2149        let at = |t: u32, offset: i32| Activity::new(Timestamp::from_fit(t), 0).utc_offset(offset);
2150        assert_eq!(at(10, -11).local_timestamp(), Some(INVALID_U32));
2151        assert_eq!(at(10, -10).local_timestamp(), Some(0));
2152        assert_eq!(at(u32::MAX - 1, 1).local_timestamp(), Some(INVALID_U32));
2153        assert_eq!(at(u32::MAX - 2, 1).local_timestamp(), Some(u32::MAX - 1));
2154        assert_eq!(at(100, 3600).local_timestamp(), Some(3700));
2155        assert_eq!(Activity::new(T, 0).local_timestamp(), None);
2156        assert_eq!(refused(&at(10, -11), 0), Some(FieldError::OutOfRange));
2157    }
2158
2159    #[test]
2160    fn record_layouts() {
2161        assert_eq!(Record::new(T).heart_rate(99).fields(), RecordFields::HEART_RATE);
2162        assert_eq!(Record::new(T).fields(), RecordFields(0));
2163        assert_eq!(record_fields(RecordFields(0)).count(), 0);
2164        let mut all = Record::new(T)
2165            .position(Position::from_semicircles(1, 2).unwrap())
2166            .altitude(Altitude::smoothed_meters(0.0))
2167            .heart_rate(3)
2168            .cadence_rpm(4)
2169            .speed_meters_per_second(6.0)
2170            .power_watts(7)
2171            .temperature_celsius(-8);
2172        all.distance = Some(500);
2173        let defs: std::vec::Vec<FieldDef> = record_fields(all.fields()).collect();
2174        assert_eq!(defs.len(), 9);
2175        let mut out = VecPut(vec![]);
2176        let mut fields = Fields::new(defs.into_iter(), Some(&mut out));
2177        all.encode(&mut fields);
2178        assert_eq!(fields.refused(), None);
2179        fields.finish();
2180        #[rustfmt::skip]
2181        let want = [
2182            1, 0, 0, 0, 2, 0, 0, 0, // position
2183            0xC4, 0x09, // altitude: (0 + 500) * 5
2184            3, 4,
2185            0xF4, 0x01, 0, 0, // distance: 500 cm
2186            0x70, 0x17, // speed: 6000 mm/s
2187            7, 0,
2188            0xF8, // -8 °C
2189        ];
2190        assert_eq!(out.0, want);
2191        assert_eq!(
2192            record_fields(RecordFields::HEART_RATE).collect::<std::vec::Vec<_>>(),
2193            [field(3, 1, base::UINT8)]
2194        );
2195        assert!(!RecordFields(0).contains(RecordFields::HEART_RATE));
2196        assert!(RecordFields::HEART_RATE.contains(RecordFields(0)));
2197    }
2198
2199    #[test]
2200    fn values_fill_their_fields_exactly() {
2201        let defs = [
2202            field(0, 2, base::UINT16),
2203            field(1, 1, base::UINT8),
2204            field(2, 3, base::STRING),
2205            field(3, 4, base::UINT32Z),
2206            field(4, 2, base::UINT16),
2207            field(5, 1, base::ENUM),
2208        ];
2209        let mut out = VecPut(vec![]);
2210        let mut fields = Fields::new(defs.into_iter(), Some(&mut out));
2211        // Short and widened, a string, a none, then two left unwritten.
2212        fields.u8(7);
2213        fields.u32(9);
2214        fields.str("ab");
2215        fields.none();
2216        fields.finish();
2217        assert_eq!(
2218            fields_refused(&defs, |f| {
2219                f.u8(7);
2220                f.u32(9);
2221            }),
2222            None
2223        );
2224        assert_eq!(out.0, [7, 0, 9, b'a', b'b', 0, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF]);
2225
2226        let mut out = VecPut(vec![]);
2227        let mut fields = Fields::new([field(0, 1, base::UINT8)].into_iter(), Some(&mut out));
2228        fields.u8(1);
2229        fields.u8(2);
2230        fields.str("x");
2231        fields.none();
2232        fields.finish();
2233        assert_eq!(out.0, [1], "values past the table are dropped");
2234    }
2235
2236    fn fields_refused(
2237        defs: &[FieldDef],
2238        f: impl Fn(&mut Fields<'_, core::iter::Copied<core::slice::Iter<'_, FieldDef>>>),
2239    ) -> Option<FieldError> {
2240        let mut fields = Fields::new(defs.iter().copied(), None);
2241        f(&mut fields);
2242        fields.refused()
2243    }
2244
2245    #[test]
2246    fn a_value_that_is_none_or_too_wide_is_refused() {
2247        let s8 = [field(0, 1, base::SINT8)];
2248        let s32 = [field(0, 4, base::SINT32)];
2249        assert_eq!(fields_refused(&s8, |f| f.i8(i8::MAX)), Some(FieldError::OutOfRange));
2250        assert_eq!(fields_refused(&s8, |f| f.i8(-1)), None);
2251        assert_eq!(fields_refused(&s32, |f| f.i32(i32::MAX)), Some(FieldError::OutOfRange));
2252        assert_eq!(fields_refused(&s32, |f| f.i32(-1)), None);
2253        let u8_ = [field(0, 1, base::UINT8)];
2254        let u16_ = [field(0, 2, base::UINT16)];
2255        let z = [field(0, 4, base::UINT32Z)];
2256        let e = Some(FieldError::OutOfRange);
2257        assert_eq!(fields_refused(&u8_, |f| f.u8(0xFF)), e);
2258        assert_eq!(fields_refused(&u8_, |f| f.u8(0xFE)), None);
2259        assert_eq!(fields_refused(&u8_, |f| f.u16(0x0100)), e);
2260        assert_eq!(fields_refused(&u8_, |f| f.u16(0x00FE)), None);
2261        assert_eq!(fields_refused(&u16_, |f| f.u16(0xFFFF)), e);
2262        assert_eq!(fields_refused(&u16_, |f| f.u8(0xFF)), None, "widened, it is 0x00FF");
2263        assert_eq!(fields_refused(&z, |f| f.u32(0)), e);
2264        assert_eq!(fields_refused(&z, |f| f.u32(u32::MAX)), None);
2265        assert_eq!(fields_refused(&z, |f| f.none()), None);
2266        // The first refusal is the one kept.
2267        let two = [field(0, 1, base::STRING), field(1, 1, base::UINT8)];
2268        assert_eq!(
2269            fields_refused(&two, |f| {
2270                f.str("x");
2271                f.u8(0xFF);
2272            }),
2273            Some(FieldError::StringTooLong)
2274        );
2275    }
2276
2277    #[test]
2278    fn messages_refuse_none_as_a_value() {
2279        let e = Some(FieldError::OutOfRange);
2280        let id = |t| FileId::new(t, Manufacturer::DEVELOPMENT, 1, T);
2281        assert_eq!(refused(&id(FileType::new(255)), 0), e);
2282        assert_eq!(refused(&id(FileType::ACTIVITY).serial_number(0), 0), e);
2283        assert_eq!(
2284            refused(&FileId::new(FileType::ACTIVITY, Manufacturer::new(0xFFFF), 1, T), 0),
2285            e
2286        );
2287        assert_eq!(refused(&DeviceInfo::new(T).product(0xFFFF), 0), e);
2288        assert_eq!(refused(&Event::timer_start(Timestamp::from_fit(u32::MAX)), 0), e);
2289        let lap = Lap::new(T, T2, 0, 0);
2290        assert_eq!(refused(&lap.heart_rate(255, 255), 0), e);
2291        assert_eq!(refused(&lap.sport(Sport::new(255), SubSport::GENERIC), 0), e);
2292        assert_eq!(refused(&Lap::new(T, T2, u32::MAX, 0), 0), e);
2293        assert_eq!(
2294            refused(&Session::new(T, T2, 0, 0).sport(Sport::RUNNING, SubSport::new(255)), 0),
2295            e
2296        );
2297        assert_eq!(
2298            refused(&lap.heart_rate(254, 254).sport(Sport::new(254), SubSport::new(254)), 0),
2299            None
2300        );
2301    }
2302
2303    #[test]
2304    fn masks_hold_any_field_of_a_definition() {
2305        let mut m = Mask::EMPTY;
2306        for i in [0, 63, 64, 200, 255] {
2307            assert!(!m.contains(i));
2308            m.insert(i);
2309            assert!(m.contains(i));
2310        }
2311        assert!(!m.contains(1) && !m.contains(65) && !m.contains(256));
2312        m.insert(256);
2313        assert!(!m.contains(256), "past a definition's last field");
2314        let rest = Mask::ALL.without(m);
2315        assert!(!rest.contains(64) && rest.contains(65) && rest.contains(254));
2316        let defs = [field(1, 1, base::UINT8), field(2, 2, base::UINT16), field(3, 1, base::UINT8)];
2317        let mut keep = Mask::EMPTY;
2318        keep.insert(0);
2319        keep.insert(2);
2320        assert_eq!(
2321            kept(defs.into_iter(), keep).map(|f| f.num).collect::<std::vec::Vec<_>>(),
2322            [1, 3]
2323        );
2324    }
2325
2326    #[test]
2327    fn a_message_keeps_the_fields_it_has_values_for() {
2328        let mut fields = Fields::new(DeviceInfo::FIELDS.iter().copied(), None);
2329        DeviceInfo::new(T).product_name("Watch").encode(&mut fields, 0);
2330        let present = fields.present();
2331        let kept: std::vec::Vec<u8> =
2332            kept(DeviceInfo::FIELDS.iter().copied(), present).map(|f| f.num).collect();
2333        assert_eq!(kept, [TIMESTAMP, 0, 27], "timestamp, device_index and product_name");
2334        let mut out = VecPut(vec![]);
2335        let mut fields =
2336            Fields::new(DeviceInfo::FIELDS.iter().copied(), Some(&mut out)).keep(present);
2337        DeviceInfo::new(T).product_name("Watch").encode(&mut fields, 0);
2338        fields.finish();
2339        assert_eq!(out.0.len(), 4 + 1 + 20);
2340    }
2341
2342    #[test]
2343    fn lengths() {
2344        let span = Span {
2345            start_time: T,
2346            timestamp: T2,
2347            total_elapsed_ms: 0x0001_0203,
2348            total_timer_ms: 0x0004_0506,
2349        };
2350        let swum = LengthMsg {
2351            span,
2352            swum: Some(Length::swum(SwimStroke::BACKSTROKE, 0x0708)),
2353            avg_speed: Some(0x090A),
2354            cadence: Some(11),
2355        };
2356        #[rustfmt::skip]
2357        let want = [
2358            3, 0, 0x80, 0x33, 0x22, 0x11, 28, 1, 0x44, 0x33, 0x22, 0x11,
2359            0x03, 0x02, 0x01, 0x00, 0x06, 0x05, 0x04, 0x00,
2360            0x08, 0x07, 0x0A, 0x09, 1, 11, 1,
2361        ];
2362        assert_eq!(bytes(&swum, 3), want);
2363        let idle = LengthMsg { span, swum: None, avg_speed: None, cadence: None };
2364        let out = bytes(&idle, 3);
2365        assert_eq!((&out[20..26], out[26]), (&[0xFF; 6][..], 0));
2366        let drill = LengthMsg { swum: Some(Length::drill()), ..idle };
2367        assert_eq!(&bytes(&drill, 3)[20..], [0xFF, 0xFF, 0xFF, 0xFF, 4, 0xFF, 1]);
2368        assert_eq!(idle.timestamp(), Some(T2));
2369    }
2370
2371    #[test]
2372    fn sets() {
2373        let set = Set::new()
2374            .exercise(Exercise::new(ExerciseCategory::SQUAT).name(0x0102))
2375            .repetitions(10)
2376            .weight_pounds(100.0);
2377        let msg = SetMsg { start_time: T, timestamp: T2, duration_ms: 0x0004_0506, set: Some(set) };
2378        #[rustfmt::skip]
2379        let want = [
2380            0x80, 0x33, 0x22, 0x11, 0x06, 0x05, 0x04, 0x00,
2381            10, 0, 0xD6, 0x02, // 45.359 kg in sixteenths: 726
2382            1, 0x44, 0x33, 0x22, 0x11, 28, 0, 0x02, 0x01, 2, 0, 7, 0,
2383        ];
2384        assert_eq!(bytes(&msg, 7), want);
2385        let rest = SetMsg { set: None, ..msg };
2386        let out = bytes(&rest, 7);
2387        assert_eq!((&out[8..12], out[12]), (&[0xFF; 4][..], 0));
2388        assert_eq!(&out[17..23], &[0xFF; 6][..]);
2389        let unnamed = SetMsg {
2390            set: Some(Set::new().exercise(Exercise::new(ExerciseCategory::new(1)))),
2391            ..msg
2392        };
2393        assert_eq!(&bytes(&unnamed, 7)[17..21], [1, 0, 0xFF, 0xFF]);
2394        assert_eq!(Set::new().weight_kilograms(60.0).weight, Some(960));
2395        assert_eq!(Set::new().weight_kilograms(60.0).weight_unit, Some(1));
2396        assert_eq!(Set::new().weight_kilograms(4095.875).weight, Some(65_534));
2397        assert_eq!(Set::new().weight_kilograms(-1.0).weight, Some(u16::MAX));
2398    }
2399
2400    #[test]
2401    fn pools() {
2402        assert_eq!(Pool::meters(25.0), Pool { centimetres: 2500, unit: 0 });
2403        assert_eq!(Pool::yards(25.0), Pool { centimetres: 2286, unit: 1 });
2404        assert_eq!(Pool::meters(33.333), Pool { centimetres: 3333, unit: 0 });
2405        assert_eq!(Pool::meters(1000.0).centimetres, u16::MAX);
2406    }
2407
2408    #[test]
2409    fn beat_intervals_fill_five_slots() {
2410        let out = bytes(&Hrv(&[0x0102, 0x0304]), 0);
2411        assert_eq!(out, [0x02, 0x01, 0x04, 0x03, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
2412        assert_eq!(bytes(&Hrv(&[1, 2, 3, 4, 5]), 0), [1, 0, 2, 0, 3, 0, 4, 0, 5, 0]);
2413        assert_eq!(refused(&Hrv(&[1, 2, 3, 4, 5, 6]), 0), Some(FieldError::OutOfRange));
2414        assert_eq!(refused(&Hrv(&[1, u16::MAX]), 0), Some(FieldError::OutOfRange));
2415        assert_eq!(bytes(&Hrv(&[]), 0), [0xFF; 10], "none");
2416        assert_eq!(Hrv(&[]).timestamp(), None);
2417    }
2418
2419    #[test]
2420    fn bytes_fill_their_field_exactly() {
2421        let defs = [field(0, 2, base::BYTE)];
2422        let e = Some(FieldError::OutOfRange);
2423        assert_eq!(fields_refused(&defs, |f| f.bytes(&[1, 2, 3])), e);
2424        assert_eq!(fields_refused(&defs, |f| f.bytes(&[1])), e);
2425        assert_eq!(fields_refused(&defs, |f| f.bytes(&[0xFF, 0xFF])), e);
2426        assert_eq!(fields_refused(&defs, |f| f.bytes(&[0xFF, 0])), None);
2427    }
2428
2429    #[test]
2430    fn strings_need_room_for_their_nul() {
2431        let defs = [field(0, 3, base::STRING)];
2432        let mut fields = Fields::new(defs.into_iter(), None);
2433        fields.str("abc");
2434        assert_eq!(fields.refused(), Some(FieldError::StringTooLong));
2435        let mut fields = Fields::new(defs.into_iter(), None);
2436        fields.str("ab");
2437        assert_eq!(fields.refused(), None);
2438    }
2439
2440    #[test]
2441    fn strings_hold_no_nul() {
2442        let defs = [field(0, 8, base::STRING)];
2443        for s in ["a\0b", "\0", "ab\0"] {
2444            let mut fields = Fields::new(defs.into_iter(), None);
2445            fields.str(s);
2446            assert_eq!(fields.refused(), Some(FieldError::OutOfRange), "{s:?}");
2447        }
2448    }
2449}