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.
834    #[must_use]
835    pub fn distance_advanced_meters(mut self, meters: f64) -> Self {
836        let v = meters * 1e6 + 0.5;
837        // Saturates at u64::MAX, which writing refuses.
838        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
839        let um = if v.is_nan() || v.is_sign_negative() { u64::MAX } else { v as u64 };
840        self.distance_input = Some(Distance::Advanced(um));
841        self
842    }
843
844    /// The distance covered since the activity started, up to 42,949,672.94 m, to the
845    /// centimetre; less than a total already written is refused.
846    #[must_use]
847    pub fn distance_meters(mut self, meters: f64) -> Self {
848        self.distance_input = Some(Distance::Total(scaled(meters, 100.0, u32::MAX)));
849        self
850    }
851
852    /// The speed, up to 65.534 m/s, to the millimetre a second.
853    #[must_use]
854    pub fn speed_meters_per_second(mut self, speed: f64) -> Self {
855        let raw = scaled(speed, 1000.0, u32::from(u16::MAX));
856        self.speed = Some(u16::try_from(raw).unwrap_or(u16::MAX));
857        self
858    }
859
860    /// The power in watts, up to 65,534.
861    #[must_use]
862    pub const fn power_watts(mut self, watts: u16) -> Self {
863        self.power = Some(watts);
864        self
865    }
866
867    /// The temperature in degrees Celsius, from -128 to 126.
868    #[must_use]
869    pub const fn temperature_celsius(mut self, celsius: i8) -> Self {
870        self.temperature = Some(celsius);
871        self
872    }
873
874    /// The fields this record has values for, which are its layout.
875    pub(crate) fn fields(self) -> RecordFields {
876        let bits = [
877            (self.position.is_some(), RecordFields::POSITION),
878            (self.altitude.is_some(), RecordFields::ALTITUDE),
879            (self.heart_rate.is_some(), RecordFields::HEART_RATE),
880            (self.cadence.is_some(), RecordFields::CADENCE),
881            (self.distance.is_some(), RecordFields::DISTANCE),
882            (self.speed.is_some(), RecordFields::SPEED),
883            (self.power.is_some(), RecordFields::POWER),
884            (self.temperature.is_some(), RecordFields::TEMPERATURE),
885        ];
886        RecordFields(bits.iter().filter(|(set, _)| *set).map(|(_, bit)| bit.0).sum())
887    }
888
889    /// Writes the fields it has values for, in table order.
890    pub(crate) fn encode(self, out: &mut dyn FieldOut) {
891        if self.position.is_some() {
892            out.position(self.position);
893        }
894        if let Some(v) = self.altitude.map(|a| a.fifths) {
895            out.u16(v);
896        }
897        if let Some(v) = self.heart_rate {
898            out.u8(v);
899        }
900        if let Some(v) = self.cadence {
901            out.u8(v);
902        }
903        if let Some(v) = self.distance {
904            out.u32(v);
905        }
906        if let Some(v) = self.speed {
907            out.u16(v);
908        }
909        if let Some(v) = self.power {
910            out.u16(v);
911        }
912        if let Some(v) = self.temperature {
913            out.i8(v);
914        }
915    }
916}
917
918/// The times every summary message (lap, session) requires.
919#[derive(Clone, Copy, Debug, PartialEq, Eq)]
920pub(crate) struct Span {
921    pub start_time: Timestamp,
922    pub timestamp: Timestamp,
923    pub total_elapsed_ms: u32,
924    pub total_timer_ms: u32,
925}
926
927/// Heart rate and sport, which lap and session both summarise.
928#[derive(Clone, Copy, Debug, PartialEq, Eq)]
929struct Summary {
930    avg_heart_rate: Option<u8>,
931    max_heart_rate: Option<u8>,
932    sport: Option<Sport>,
933    sub_sport: Option<SubSport>,
934}
935
936impl Summary {
937    const NONE: Self =
938        Self { avg_heart_rate: None, max_heart_rate: None, sport: None, sub_sport: None };
939}
940
941/// What a lap or session covered, from its records; in FIT's units, as [`Record`] holds them.
942#[derive(Clone, Copy, Debug, PartialEq, Eq)]
943pub(crate) struct Totals {
944    pub start: Option<Position>,
945    pub end: Option<Position>,
946    pub north_east: Option<Position>,
947    pub south_west: Option<Position>,
948    pub distance: Option<u32>,
949    pub avg_speed: Option<u16>,
950    pub max_speed: Option<u16>,
951    pub avg_cadence: Option<u8>,
952    pub max_cadence: Option<u8>,
953    pub avg_power: Option<u16>,
954    pub max_power: Option<u16>,
955    /// In metres.
956    pub ascent: Option<u16>,
957    pub descent: Option<u16>,
958    pub avg_temperature: Option<i8>,
959    pub max_temperature: Option<i8>,
960    /// Strokes in a pool swim, repetitions in a strength session.
961    pub cycles: Option<u32>,
962    pub lengths: Option<u16>,
963    pub active_lengths: Option<u16>,
964    /// In centimetres.
965    pub stroke_distance: Option<u16>,
966    pub swim_stroke: Option<SwimStroke>,
967}
968
969impl Totals {
970    pub(crate) const NONE: Self = Self {
971        start: None,
972        end: None,
973        north_east: None,
974        south_west: None,
975        distance: None,
976        avg_speed: None,
977        max_speed: None,
978        avg_cadence: None,
979        max_cadence: None,
980        avg_power: None,
981        max_power: None,
982        ascent: None,
983        descent: None,
984        avg_temperature: None,
985        max_temperature: None,
986        cycles: None,
987        lengths: None,
988        active_lengths: None,
989        stroke_distance: None,
990        swim_stroke: None,
991    };
992
993    /// Writes the totals, in the order of [`with_totals`].
994    fn encode(&self, out: &mut dyn FieldOut) {
995        out.position(self.start);
996        out.position(self.end);
997        out.opt_u32(self.distance);
998        out.opt_u16(self.avg_speed);
999        out.opt_u16(self.max_speed);
1000        out.opt_u8(self.avg_cadence);
1001        out.opt_u8(self.max_cadence);
1002        out.opt_u16(self.avg_power);
1003        out.opt_u16(self.max_power);
1004        out.opt_u16(self.ascent);
1005        out.opt_u16(self.descent);
1006        out.position(self.north_east);
1007        out.position(self.south_west);
1008        out.opt_i8(self.avg_temperature);
1009        out.opt_i8(self.max_temperature);
1010        out.opt_u32(self.cycles);
1011        out.opt_u16(self.lengths);
1012        out.opt_u16(self.active_lengths);
1013        out.opt_u16(self.stroke_distance);
1014        out.opt_u8(self.swim_stroke.map(SwimStroke::get));
1015    }
1016}
1017
1018/// A lap or session table: its own fields, then the totals', given their field numbers, which
1019/// differ between the two.
1020macro_rules! with_totals {
1021    (
1022        [$($head:expr),* $(,)?],
1023        $start_lat:literal, $start_long:literal, $end_lat:literal, $end_long:literal,
1024        $distance:literal, $avg_speed:literal, $max_speed:literal, $avg_cadence:literal,
1025        $max_cadence:literal, $avg_power:literal, $max_power:literal, $ascent:literal,
1026        $descent:literal, $nec_lat:literal, $nec_long:literal, $swc_lat:literal,
1027        $swc_long:literal, $avg_temperature:literal, $max_temperature:literal,
1028        $cycles:literal, $lengths:literal, $active_lengths:literal, $stroke_distance:literal,
1029        $swim_stroke:literal, [$($tail:expr),* $(,)?]
1030    ) => {
1031        &[
1032            $($head,)*
1033            field($start_lat, 4, base::SINT32),
1034            field($start_long, 4, base::SINT32),
1035            field($end_lat, 4, base::SINT32),
1036            field($end_long, 4, base::SINT32),
1037            field($distance, 4, base::UINT32), // scale 100
1038            field($avg_speed, 2, base::UINT16), // scale 1000
1039            field($max_speed, 2, base::UINT16), // scale 1000
1040            field($avg_cadence, 1, base::UINT8),
1041            field($max_cadence, 1, base::UINT8),
1042            field($avg_power, 2, base::UINT16),
1043            field($max_power, 2, base::UINT16),
1044            field($ascent, 2, base::UINT16),
1045            field($descent, 2, base::UINT16),
1046            field($nec_lat, 4, base::SINT32),
1047            field($nec_long, 4, base::SINT32),
1048            field($swc_lat, 4, base::SINT32),
1049            field($swc_long, 4, base::SINT32),
1050            field($avg_temperature, 1, base::SINT8),
1051            field($max_temperature, 1, base::SINT8),
1052            field($cycles, 4, base::UINT32),
1053            field($lengths, 2, base::UINT16),
1054            field($active_lengths, 2, base::UINT16),
1055            field($stroke_distance, 2, base::UINT16), // scale 100
1056            field($swim_stroke, 1, base::ENUM),
1057            $($tail,)*
1058        ]
1059    };
1060}
1061
1062/// One lap of a session.
1063#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1064pub(crate) struct Lap {
1065    span: Span,
1066    summary: Summary,
1067    totals: Totals,
1068    first_length_index: Option<u16>,
1069    trigger: u8,
1070}
1071
1072impl Lap {
1073    /// A lap from `start_time` to `timestamp`, lasting `total_elapsed_ms` of which the timer ran
1074    /// `total_timer_ms` (the elapsed time less pauses).
1075    #[must_use]
1076    pub const fn new(
1077        start_time: Timestamp,
1078        timestamp: Timestamp,
1079        total_elapsed_ms: u32,
1080        total_timer_ms: u32,
1081    ) -> Self {
1082        Self {
1083            span: Span { start_time, timestamp, total_elapsed_ms, total_timer_ms },
1084            summary: Summary::NONE,
1085            totals: Totals::NONE,
1086            first_length_index: None,
1087            trigger: lap_trigger::MANUAL,
1088        }
1089    }
1090
1091    /// What ended it, a [`lap_trigger`] value; [`lap_trigger::MANUAL`] unless given.
1092    #[must_use]
1093    pub const fn trigger(mut self, trigger: u8) -> Self {
1094        self.trigger = trigger;
1095        self
1096    }
1097
1098    /// The index of its first length, in a pool swim.
1099    #[must_use]
1100    pub const fn first_length(mut self, index: u16) -> Self {
1101        self.first_length_index = Some(index);
1102        self
1103    }
1104
1105    #[must_use]
1106    pub const fn totals(mut self, totals: Totals) -> Self {
1107        self.totals = totals;
1108        self
1109    }
1110
1111    /// Average and maximum heart rate, in beats per minute.
1112    #[must_use]
1113    pub const fn heart_rate(mut self, avg: u8, max: u8) -> Self {
1114        self.summary.avg_heart_rate = Some(avg);
1115        self.summary.max_heart_rate = Some(max);
1116        self
1117    }
1118
1119    /// The sport and its variant.
1120    #[must_use]
1121    pub const fn sport(mut self, sport: Sport, sub_sport: SubSport) -> Self {
1122        self.summary.sport = Some(sport);
1123        self.summary.sub_sport = Some(sub_sport);
1124        self
1125    }
1126}
1127
1128impl Message for Lap {
1129    const GLOBAL: u16 = 19;
1130    const FIELDS: &'static [FieldDef] = with_totals!(
1131        [
1132            field(MESSAGE_INDEX, 2, base::UINT16),
1133            field(TIMESTAMP, 4, base::UINT32),
1134            field(0, 1, base::ENUM),   // event
1135            field(1, 1, base::ENUM),   // event_type
1136            field(2, 4, base::UINT32), // start_time
1137            field(7, 4, base::UINT32), // total_elapsed_time, scale 1000
1138            field(8, 4, base::UINT32), // total_timer_time, scale 1000
1139            field(15, 1, base::UINT8), // avg_heart_rate
1140            field(16, 1, base::UINT8), // max_heart_rate
1141            field(25, 1, base::ENUM),  // sport
1142            field(39, 1, base::ENUM),  // sub_sport
1143            field(24, 1, base::ENUM),  // lap_trigger
1144        ],
1145        3,
1146        4,
1147        5,
1148        6,
1149        9,
1150        13,
1151        14,
1152        17,
1153        18,
1154        19,
1155        20,
1156        21,
1157        22,
1158        27,
1159        28,
1160        29,
1161        30,
1162        50,
1163        51,
1164        10,
1165        32,
1166        40,
1167        37,
1168        38,
1169        [field(35, 2, base::UINT16)] // first_length_index
1170    );
1171
1172    fn timestamp(&self) -> Option<Timestamp> {
1173        Some(self.span.timestamp)
1174    }
1175
1176    fn encode(&self, out: &mut dyn FieldOut, index: u16) {
1177        let (span, summary) = (&self.span, &self.summary);
1178        out.u16(index);
1179        out.u32(span.timestamp.fit());
1180        out.u8(event::LAP);
1181        out.u8(event::STOP);
1182        out.u32(span.start_time.fit());
1183        out.u32(span.total_elapsed_ms);
1184        out.u32(span.total_timer_ms);
1185        out.opt_u8(summary.avg_heart_rate);
1186        out.opt_u8(summary.max_heart_rate);
1187        out.opt_u8(summary.sport.map(Sport::get));
1188        out.opt_u8(summary.sub_sport.map(SubSport::get));
1189        out.u8(self.trigger);
1190        self.totals.encode(out);
1191        out.opt_u16(self.first_length_index);
1192    }
1193}
1194
1195/// One sport's part of the activity; one, for a single-sport activity.
1196#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1197pub(crate) struct Session {
1198    span: Span,
1199    summary: Summary,
1200    totals: Totals,
1201    first_lap_index: u16,
1202    num_laps: u16,
1203    pool: Option<Pool>,
1204    trigger: u8,
1205}
1206
1207impl Session {
1208    /// A session from `start_time` to `timestamp`, lasting `total_elapsed_ms` of which the
1209    /// timer ran `total_timer_ms`. It covers one lap, the first, until [`Session::laps`] says
1210    /// otherwise.
1211    #[must_use]
1212    pub const fn new(
1213        start_time: Timestamp,
1214        timestamp: Timestamp,
1215        total_elapsed_ms: u32,
1216        total_timer_ms: u32,
1217    ) -> Self {
1218        Self {
1219            span: Span { start_time, timestamp, total_elapsed_ms, total_timer_ms },
1220            summary: Summary::NONE,
1221            totals: Totals::NONE,
1222            first_lap_index: 0,
1223            num_laps: 1,
1224            pool: None,
1225            trigger: trigger::ACTIVITY_END,
1226        }
1227    }
1228
1229    /// What ended it, one of [`trigger`]'s; the activity's end until said otherwise.
1230    #[must_use]
1231    pub const fn trigger(mut self, trigger: u8) -> Self {
1232        self.trigger = trigger;
1233        self
1234    }
1235
1236    /// The pool it swam in.
1237    #[must_use]
1238    pub const fn pool(mut self, pool: Pool) -> Self {
1239        self.pool = Some(pool);
1240        self
1241    }
1242
1243    #[must_use]
1244    pub const fn totals(mut self, totals: Totals) -> Self {
1245        self.totals = totals;
1246        self
1247    }
1248
1249    /// Average and maximum heart rate, in beats per minute.
1250    #[must_use]
1251    pub const fn heart_rate(mut self, avg: u8, max: u8) -> Self {
1252        self.summary.avg_heart_rate = Some(avg);
1253        self.summary.max_heart_rate = Some(max);
1254        self
1255    }
1256
1257    /// The sport and its variant.
1258    #[must_use]
1259    pub const fn sport(mut self, sport: Sport, sub_sport: SubSport) -> Self {
1260        self.summary.sport = Some(sport);
1261        self.summary.sub_sport = Some(sub_sport);
1262        self
1263    }
1264
1265    /// The laps it covers: `count` laps from the lap with `message_index` `first`.
1266    #[must_use]
1267    pub const fn laps(mut self, first: u16, count: u16) -> Self {
1268        self.first_lap_index = first;
1269        self.num_laps = count;
1270        self
1271    }
1272}
1273
1274impl Message for Session {
1275    const GLOBAL: u16 = 18;
1276    const FIELDS: &'static [FieldDef] = with_totals!(
1277        [
1278            field(MESSAGE_INDEX, 2, base::UINT16),
1279            field(TIMESTAMP, 4, base::UINT32),
1280            field(0, 1, base::ENUM),    // event
1281            field(1, 1, base::ENUM),    // event_type
1282            field(2, 4, base::UINT32),  // start_time
1283            field(5, 1, base::ENUM),    // sport
1284            field(6, 1, base::ENUM),    // sub_sport
1285            field(7, 4, base::UINT32),  // total_elapsed_time, scale 1000
1286            field(8, 4, base::UINT32),  // total_timer_time, scale 1000
1287            field(16, 1, base::UINT8),  // avg_heart_rate
1288            field(17, 1, base::UINT8),  // max_heart_rate
1289            field(25, 2, base::UINT16), // first_lap_index
1290            field(26, 2, base::UINT16), // num_laps
1291        ],
1292        3,
1293        4,
1294        38,
1295        39,
1296        9,
1297        14,
1298        15,
1299        18,
1300        19,
1301        20,
1302        21,
1303        22,
1304        23,
1305        29,
1306        30,
1307        31,
1308        32,
1309        57,
1310        58,
1311        10,
1312        33,
1313        47,
1314        42,
1315        43,
1316        [
1317            field(44, 2, base::UINT16), // pool_length, scale 100
1318            field(46, 1, base::ENUM),   // pool_length_unit
1319            field(28, 1, base::ENUM),   // trigger
1320        ]
1321    );
1322
1323    fn timestamp(&self) -> Option<Timestamp> {
1324        Some(self.span.timestamp)
1325    }
1326
1327    fn encode(&self, out: &mut dyn FieldOut, index: u16) {
1328        let (span, summary) = (&self.span, &self.summary);
1329        out.u16(index);
1330        out.u32(span.timestamp.fit());
1331        out.u8(event::SESSION);
1332        out.u8(event::STOP);
1333        out.u32(span.start_time.fit());
1334        out.opt_u8(summary.sport.map(Sport::get));
1335        out.opt_u8(summary.sub_sport.map(SubSport::get));
1336        out.u32(span.total_elapsed_ms);
1337        out.u32(span.total_timer_ms);
1338        out.opt_u8(summary.avg_heart_rate);
1339        out.opt_u8(summary.max_heart_rate);
1340        out.u16(self.first_lap_index);
1341        out.u16(self.num_laps);
1342        self.totals.encode(out);
1343        out.opt_u16(self.pool.map(|p| p.centimetres));
1344        out.opt_u8(self.pool.map(|p| p.unit));
1345        out.u8(self.trigger);
1346    }
1347}
1348
1349/// `lap_trigger` values: what ended a lap.
1350pub(crate) mod lap_trigger {
1351    pub const MANUAL: u8 = 0;
1352    pub const SESSION_END: u8 = 7;
1353}
1354
1355/// What ended a lap, for [`Writer::lap_by`](crate::Writer::lap_by): the profile's
1356/// `lap_trigger`, less `session_end`, which the encoder writes on each session's last lap.
1357#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1358#[non_exhaustive]
1359pub enum LapTrigger {
1360    /// The wearer.
1361    Manual,
1362    /// A lap time.
1363    Time,
1364    /// A lap distance.
1365    Distance,
1366    /// Reaching the start position.
1367    PositionStart,
1368    /// Reaching a lap position.
1369    PositionLap,
1370    /// Reaching a waypoint.
1371    PositionWaypoint,
1372    /// Reaching a marked position.
1373    PositionMarked,
1374    /// Fitness equipment.
1375    FitnessEquipment,
1376}
1377
1378impl LapTrigger {
1379    /// Its value in the profile.
1380    pub(crate) const fn get(self) -> u8 {
1381        match self {
1382            Self::Manual => lap_trigger::MANUAL,
1383            Self::Time => 1,
1384            Self::Distance => 2,
1385            Self::PositionStart => 3,
1386            Self::PositionLap => 4,
1387            Self::PositionWaypoint => 5,
1388            Self::PositionMarked => 6,
1389            Self::FitnessEquipment => 8,
1390        }
1391    }
1392
1393    /// The profile's name for it.
1394    #[must_use]
1395    pub const fn name(self) -> &'static str {
1396        match self {
1397            Self::Manual => "manual",
1398            Self::Time => "time",
1399            Self::Distance => "distance",
1400            Self::PositionStart => "position_start",
1401            Self::PositionLap => "position_lap",
1402            Self::PositionWaypoint => "position_waypoint",
1403            Self::PositionMarked => "position_marked",
1404            Self::FitnessEquipment => "fitness_equipment",
1405        }
1406    }
1407}
1408
1409impl core::fmt::Display for LapTrigger {
1410    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1411        f.write_str(self.name())
1412    }
1413}
1414
1415/// `session_trigger` values: what ended a session.
1416pub(crate) mod trigger {
1417    pub const ACTIVITY_END: u8 = 0;
1418    pub const MANUAL: u8 = 1;
1419    pub const AUTO_MULTI_SPORT: u8 = 2;
1420}
1421
1422/// The longest sport name, in UTF-8 bytes; one more byte holds its terminating NUL.
1423pub const SPORT_NAME_MAX: usize = 23;
1424
1425/// A `sport` message: the sport of the session it starts, and the name of its profile.
1426#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1427pub(crate) struct SportMsg<'a> {
1428    pub sport: Sport,
1429    pub sub_sport: SubSport,
1430    pub name: &'a str,
1431}
1432
1433impl Message for SportMsg<'_> {
1434    const GLOBAL: u16 = 12;
1435    #[allow(clippy::cast_possible_truncation, reason = "a short name")]
1436    const FIELDS: &'static [FieldDef] = &[
1437        field(0, 1, base::ENUM),                          // sport
1438        field(1, 1, base::ENUM),                          // sub_sport
1439        field(3, SPORT_NAME_MAX as u8 + 1, base::STRING), // name
1440    ];
1441
1442    fn timestamp(&self) -> Option<Timestamp> {
1443        None
1444    }
1445
1446    fn encode(&self, out: &mut dyn FieldOut, _: u16) {
1447        out.u8(self.sport.get());
1448        out.u8(self.sub_sport.get());
1449        out.str(self.name);
1450    }
1451}
1452
1453/// A session for [`Writer::leg`](crate::Writer::leg) to start: its sport, the pool of a pool
1454/// swim, the name of its profile, and whether the wearer moved to it by hand.
1455///
1456/// ```
1457/// use fit_encoder::{Leg, Pool, Sport, SubSport};
1458///
1459/// let run = Leg::new(Sport::RUNNING, SubSport::TRAIL).named("Trail Run");
1460/// let swim = Leg::pool_swim(Pool::meters(25.0)).by_hand();
1461/// # let _ = (run, swim);
1462/// ```
1463#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1464pub struct Leg<'a> {
1465    pub(crate) sport: SportMsg<'a>,
1466    pub(crate) pool: Option<Pool>,
1467    pub(crate) by_hand: bool,
1468}
1469
1470impl<'a> Leg<'a> {
1471    /// A session of `sport`; not `lap_swimming`, which [`Leg::pool_swim`] starts.
1472    #[must_use]
1473    pub const fn new(sport: Sport, sub_sport: SubSport) -> Self {
1474        Self { sport: SportMsg { sport, sub_sport, name: "" }, pool: None, by_hand: false }
1475    }
1476
1477    /// A pool swim in `pool`, whose lengths give its distance.
1478    #[must_use]
1479    pub const fn pool_swim(pool: Pool) -> Self {
1480        let sport =
1481            SportMsg { sport: Sport::SWIMMING, sub_sport: SubSport::LAP_SWIMMING, name: "" };
1482        Self { sport, pool: Some(pool), by_hand: false }
1483    }
1484
1485    /// The name of the sport's profile on the device, such as "Open Water", up to
1486    /// [`SPORT_NAME_MAX`] bytes.
1487    #[must_use]
1488    pub const fn named(mut self, name: &'a str) -> Self {
1489        self.sport.name = name;
1490        self
1491    }
1492
1493    /// The wearer moved to it by hand, in an activity whose profile otherwise moves on by
1494    /// itself ([`Options::auto_multisport`](crate::Options::auto_multisport)): the session
1495    /// before it was ended `manual`. Without that option every session is. Not a first leg.
1496    #[must_use]
1497    pub const fn by_hand(mut self) -> Self {
1498        self.by_hand = true;
1499        self
1500    }
1501}
1502
1503/// A swimming pool's length, which every length of a pool swim covers.
1504///
1505/// ```
1506/// use fit_encoder::Pool;
1507///
1508/// let pool = Pool::yards(25.0);
1509/// # let _ = pool;
1510/// ```
1511#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1512pub struct Pool {
1513    /// `u16::MAX` and 0 are out of range.
1514    pub(crate) centimetres: u16,
1515    /// The profile's `display_measure`: metric or statute.
1516    pub(crate) unit: u8,
1517}
1518
1519impl Pool {
1520    /// A pool measured in metres, up to 655.34, to the centimetre.
1521    #[must_use]
1522    pub fn meters(meters: f64) -> Self {
1523        Self::of(meters, 0)
1524    }
1525
1526    /// A pool measured in yards, up to 716.68, kept to the centimetre; 25 yd is 22.86 m.
1527    #[must_use]
1528    pub fn yards(yards: f64) -> Self {
1529        Self::of(yards * 0.9144, 1)
1530    }
1531
1532    fn of(meters: f64, unit: u8) -> Self {
1533        let cm = scaled(meters, 100.0, u32::from(u16::MAX));
1534        Self { centimetres: u16::try_from(cm).unwrap_or(u16::MAX), unit }
1535    }
1536}
1537
1538/// One length of a pool swum: its stroke and stroke count, or a drill.
1539///
1540/// ```
1541/// use fit_encoder::{Length, SwimStroke};
1542///
1543/// let length = Length::swum(SwimStroke::FREESTYLE, 18);
1544/// # let _ = length;
1545/// ```
1546#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1547pub struct Length {
1548    pub(crate) stroke: SwimStroke,
1549    pub(crate) strokes: Option<u16>,
1550}
1551
1552impl Length {
1553    /// A length swum in `stroke`, taking `strokes` strokes, up to 65,534; a drill's strokes
1554    /// are not counted, as [`Length::drill`].
1555    #[must_use]
1556    pub const fn swum(stroke: SwimStroke, strokes: u16) -> Self {
1557        if stroke.get() == SwimStroke::DRILL.get() {
1558            return Self::drill();
1559        }
1560        Self { stroke, strokes: Some(strokes) }
1561    }
1562
1563    /// A length of drill, whose strokes are not counted.
1564    #[must_use]
1565    pub const fn drill() -> Self {
1566        Self { stroke: SwimStroke::DRILL, strokes: None }
1567    }
1568}
1569
1570/// A strength exercise: its category and, optionally, its name within the category, the
1571/// number from that category's list of names (`bench_press_exercise_name` and so on).
1572///
1573/// ```
1574/// use fit_encoder::{Exercise, ExerciseCategory};
1575///
1576/// let squat = Exercise::new(ExerciseCategory::SQUAT);
1577/// let goblet_squat = squat.name(37);
1578/// # let _ = goblet_squat;
1579/// ```
1580#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1581pub struct Exercise {
1582    pub(crate) category: ExerciseCategory,
1583    pub(crate) name: Option<u16>,
1584}
1585
1586impl Exercise {
1587    /// An exercise of `category`, not named further.
1588    #[must_use]
1589    pub const fn new(category: ExerciseCategory) -> Self {
1590        Self { category, name: None }
1591    }
1592
1593    /// Its name's number in its category's list, up to 65,534.
1594    #[must_use]
1595    pub const fn name(mut self, name: u16) -> Self {
1596        self.name = Some(name);
1597        self
1598    }
1599}
1600
1601/// A strength set as it ended: what was lifted, how many times.
1602///
1603/// ```
1604/// use fit_encoder::{Exercise, ExerciseCategory, Set};
1605///
1606/// let set = Set::new()
1607///     .exercise(Exercise::new(ExerciseCategory::BENCH_PRESS))
1608///     .repetitions(8)
1609///     .weight_kilograms(60.0);
1610/// # let _ = set;
1611/// ```
1612#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1613pub struct Set {
1614    pub(crate) exercise: Option<Exercise>,
1615    pub(crate) repetitions: Option<u16>,
1616    /// Sixteenths of a kilogram; `u16::MAX` is out of range.
1617    pub(crate) weight: Option<u16>,
1618    /// The profile's `fit_base_unit`: kilogram or pound.
1619    pub(crate) weight_unit: Option<u16>,
1620}
1621
1622impl Set {
1623    /// A set with nothing known of it but its time.
1624    #[must_use]
1625    pub const fn new() -> Self {
1626        Self { exercise: None, repetitions: None, weight: None, weight_unit: None }
1627    }
1628
1629    /// The exercise.
1630    #[must_use]
1631    pub const fn exercise(mut self, exercise: Exercise) -> Self {
1632        self.exercise = Some(exercise);
1633        self
1634    }
1635
1636    /// The repetitions, up to 65,534.
1637    #[must_use]
1638    pub const fn repetitions(mut self, repetitions: u16) -> Self {
1639        self.repetitions = Some(repetitions);
1640        self
1641    }
1642
1643    /// The weight lifted in kilograms, up to 4,095.875, to a sixteenth; shown in kilograms.
1644    #[must_use]
1645    pub fn weight_kilograms(self, kilograms: f64) -> Self {
1646        self.weight(kilograms, KILOGRAM)
1647    }
1648
1649    /// The weight lifted in pounds, up to 9,029.8, kept to a sixteenth of a kilogram; shown in
1650    /// pounds.
1651    #[must_use]
1652    pub fn weight_pounds(self, pounds: f64) -> Self {
1653        self.weight(pounds * 0.453_592_37, POUND)
1654    }
1655
1656    fn weight(mut self, kilograms: f64, unit: u16) -> Self {
1657        let raw = scaled(kilograms, 16.0, u32::from(u16::MAX));
1658        self.weight = Some(u16::try_from(raw).unwrap_or(u16::MAX));
1659        self.weight_unit = Some(unit);
1660        self
1661    }
1662}
1663
1664/// `fit_base_unit` values.
1665const KILOGRAM: u16 = 1;
1666const POUND: u16 = 2;
1667
1668/// A `length` message: one length of a pool, swum or rested.
1669#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1670pub(crate) struct LengthMsg {
1671    pub span: Span,
1672    /// None for a rest, an idle length.
1673    pub swum: Option<Length>,
1674    pub avg_speed: Option<u16>,
1675    pub cadence: Option<u8>,
1676}
1677
1678impl LengthMsg {
1679    /// The fields only a swum length has: strokes, speed, stroke and stroke rate.
1680    pub const SWUM: &'static [u8] = &[5, 6, 7, 9];
1681}
1682
1683impl Message for LengthMsg {
1684    const GLOBAL: u16 = 101;
1685    const FIELDS: &'static [FieldDef] = &[
1686        field(MESSAGE_INDEX, 2, base::UINT16),
1687        field(TIMESTAMP, 4, base::UINT32),
1688        field(0, 1, base::ENUM),   // event
1689        field(1, 1, base::ENUM),   // event_type
1690        field(2, 4, base::UINT32), // start_time
1691        field(3, 4, base::UINT32), // total_elapsed_time, scale 1000
1692        field(4, 4, base::UINT32), // total_timer_time, scale 1000
1693        field(5, 2, base::UINT16), // total_strokes
1694        field(6, 2, base::UINT16), // avg_speed, scale 1000
1695        field(7, 1, base::ENUM),   // swim_stroke
1696        field(9, 1, base::UINT8),  // avg_swimming_cadence
1697        field(12, 1, base::ENUM),  // length_type
1698    ];
1699
1700    fn timestamp(&self) -> Option<Timestamp> {
1701        Some(self.span.timestamp)
1702    }
1703
1704    fn encode(&self, out: &mut dyn FieldOut, index: u16) {
1705        const IDLE: u8 = 0;
1706        const ACTIVE: u8 = 1;
1707        let span = &self.span;
1708        out.u16(index);
1709        out.u32(span.timestamp.fit());
1710        out.u8(event::LENGTH);
1711        out.u8(event::STOP);
1712        out.u32(span.start_time.fit());
1713        out.u32(span.total_elapsed_ms);
1714        out.u32(span.total_timer_ms);
1715        out.opt_u16(self.swum.and_then(|l| l.strokes));
1716        out.opt_u16(self.avg_speed);
1717        out.opt_u8(self.swum.map(|l| l.stroke.get()));
1718        out.opt_u8(self.cadence);
1719        out.u8(if self.swum.is_some() { ACTIVE } else { IDLE });
1720    }
1721}
1722
1723/// A `set` message: one strength set, or a rest between sets.
1724#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1725pub(crate) struct SetMsg {
1726    pub start_time: Timestamp,
1727    pub timestamp: Timestamp,
1728    pub duration_ms: u32,
1729    /// None for a rest.
1730    pub set: Option<Set>,
1731}
1732
1733impl SetMsg {
1734    /// The fields only an active set has: repetitions, weight, exercise and weight unit.
1735    pub const ACTIVE: &'static [u8] = &[3, 4, 7, 8, 9];
1736}
1737
1738impl Message for SetMsg {
1739    const GLOBAL: u16 = 225;
1740    const FIELDS: &'static [FieldDef] = &[
1741        field(254, 4, base::UINT32), // timestamp, at 254 in this message
1742        field(0, 4, base::UINT32),   // duration, scale 1000
1743        field(3, 2, base::UINT16),   // repetitions
1744        field(4, 2, base::UINT16),   // weight, scale 16
1745        field(5, 1, base::UINT8),    // set_type
1746        field(6, 4, base::UINT32),   // start_time
1747        field(7, 2, base::UINT16),   // category, an array
1748        field(8, 2, base::UINT16),   // category_subtype, an array
1749        field(9, 2, base::UINT16),   // weight_display_unit
1750        field(10, 2, base::UINT16),  // message_index, at 10 in this message
1751    ];
1752
1753    fn timestamp(&self) -> Option<Timestamp> {
1754        None
1755    }
1756
1757    fn encode(&self, out: &mut dyn FieldOut, index: u16) {
1758        const REST: u8 = 0;
1759        const ACTIVE: u8 = 1;
1760        let set = self.set.unwrap_or_default();
1761        let exercise = set.exercise;
1762        out.u32(self.timestamp.fit());
1763        out.u32(self.duration_ms);
1764        out.opt_u16(set.repetitions);
1765        out.opt_u16(set.weight);
1766        out.u8(if self.set.is_some() { ACTIVE } else { REST });
1767        out.u32(self.start_time.fit());
1768        out.u16s(exercise.as_ref().map(|e| e.category.get()).as_slice());
1769        out.u16s(exercise.and_then(|e| e.name).as_slice());
1770        out.opt_u16(set.weight_unit);
1771        out.u16(index);
1772    }
1773}
1774
1775/// Beat intervals a `hrv` message holds.
1776pub(crate) const HRV_BEATS: usize = 5;
1777
1778/// A `hrv` message: up to five beat intervals, in milliseconds, the rest "none".
1779#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1780pub(crate) struct Hrv<'a>(pub &'a [u16]);
1781
1782impl Message for Hrv<'_> {
1783    const GLOBAL: u16 = 78;
1784    #[allow(clippy::cast_possible_truncation, reason = "five two-byte values")]
1785    const FIELDS: &'static [FieldDef] = &[field(0, HRV_BEATS as u8 * 2, base::UINT16)]; // time, scale 1000
1786
1787    fn timestamp(&self) -> Option<Timestamp> {
1788        None
1789    }
1790
1791    fn encode(&self, out: &mut dyn FieldOut, _: u16) {
1792        out.u16s(self.0);
1793    }
1794}
1795
1796/// The whole activity; exactly one per activity file, usually last.
1797#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1798pub(crate) struct Activity {
1799    timestamp: Timestamp,
1800    total_timer_ms: u32,
1801    num_sessions: u16,
1802    utc_offset: Option<i32>,
1803    auto_multisport: bool,
1804}
1805
1806impl Activity {
1807    /// An activity ending at `timestamp` whose timer ran `total_timer_ms`, of one session.
1808    #[must_use]
1809    pub const fn new(timestamp: Timestamp, total_timer_ms: u32) -> Self {
1810        Self {
1811            timestamp,
1812            total_timer_ms,
1813            num_sessions: 1,
1814            utc_offset: None,
1815            auto_multisport: false,
1816        }
1817    }
1818
1819    /// Whether a multisport profile moved it from one session to the next, rather than its
1820    /// user.
1821    #[must_use]
1822    pub const fn auto_multisport(mut self, auto: bool) -> Self {
1823        self.auto_multisport = auto;
1824        self
1825    }
1826
1827    /// How many sessions it has.
1828    #[must_use]
1829    pub const fn sessions(mut self, num_sessions: u16) -> Self {
1830        self.num_sessions = num_sessions;
1831        self
1832    }
1833
1834    /// The local time zone's offset from UTC in seconds, written as `local_timestamp`. One that
1835    /// takes the local time out of range is refused.
1836    #[must_use]
1837    pub const fn utc_offset(mut self, seconds: i32) -> Self {
1838        self.utc_offset = Some(seconds);
1839        self
1840    }
1841
1842    /// Out of range is "none", which writing refuses.
1843    fn local_timestamp(&self) -> Option<u32> {
1844        let offset = self.utc_offset?;
1845        Some(self.timestamp.fit().checked_add_signed(offset).unwrap_or(INVALID_U32))
1846    }
1847}
1848
1849impl Message for Activity {
1850    const GLOBAL: u16 = 34;
1851    const FIELDS: &'static [FieldDef] = &[
1852        field(TIMESTAMP, 4, base::UINT32),
1853        field(0, 4, base::UINT32), // total_timer_time, scale 1000
1854        field(1, 2, base::UINT16), // num_sessions
1855        field(2, 1, base::ENUM),   // type
1856        field(3, 1, base::ENUM),   // event
1857        field(4, 1, base::ENUM),   // event_type
1858        field(5, 4, base::UINT32), // local_timestamp
1859    ];
1860
1861    fn timestamp(&self) -> Option<Timestamp> {
1862        Some(self.timestamp)
1863    }
1864
1865    fn encode(&self, out: &mut dyn FieldOut, _: u16) {
1866        const MANUAL: u8 = 0;
1867        const AUTO_MULTI_SPORT: u8 = 1;
1868        out.u32(self.timestamp.fit());
1869        out.u32(self.total_timer_ms);
1870        out.u16(self.num_sessions);
1871        out.u8(if self.auto_multisport { AUTO_MULTI_SPORT } else { MANUAL });
1872        out.u8(event::ACTIVITY);
1873        out.u8(event::STOP);
1874        out.opt_u32(self.local_timestamp());
1875    }
1876}
1877
1878#[cfg(test)]
1879mod tests {
1880    use super::*;
1881    use crate::types::{
1882        ExerciseCategory, FileType, Manufacturer, Sport, SubSport, SwimStroke, Timestamp,
1883    };
1884    use std::vec;
1885
1886    struct VecPut(std::vec::Vec<u8>);
1887
1888    impl Put for VecPut {
1889        fn put(&mut self, bytes: &[u8]) {
1890            self.0.extend_from_slice(bytes);
1891        }
1892    }
1893
1894    /// Counts the values a message gives, so a table and its `encode` cannot drift apart.
1895    struct Count(usize);
1896
1897    impl FieldOut for Count {
1898        fn u8(&mut self, _: u8) {
1899            self.0 += 1;
1900        }
1901        fn u16(&mut self, _: u16) {
1902            self.0 += 1;
1903        }
1904        fn u32(&mut self, _: u32) {
1905            self.0 += 1;
1906        }
1907        fn i8(&mut self, _: i8) {
1908            self.0 += 1;
1909        }
1910        fn i32(&mut self, _: i32) {
1911            self.0 += 1;
1912        }
1913        fn str(&mut self, _: &str) {
1914            self.0 += 1;
1915        }
1916        fn u16s(&mut self, _: &[u16]) {
1917            self.0 += 1;
1918        }
1919        fn bytes(&mut self, _: &[u8]) {
1920            self.0 += 1;
1921        }
1922        fn none(&mut self) {
1923            self.0 += 1;
1924        }
1925    }
1926
1927    fn refused<M: Message>(msg: &M, index: u16) -> Option<FieldError> {
1928        let mut fields = Fields::new(M::FIELDS.iter().copied(), None);
1929        msg.encode(&mut fields, index);
1930        fields.refused()
1931    }
1932
1933    fn bytes<M: Message>(msg: &M, index: u16) -> std::vec::Vec<u8> {
1934        let mut count = Count(0);
1935        msg.encode(&mut count, index);
1936        assert_eq!(count.0, M::FIELDS.len(), "{}: a value per field", M::GLOBAL);
1937        let mut out = VecPut(vec![]);
1938        let mut fields = Fields::new(M::FIELDS.iter().copied(), Some(&mut out));
1939        msg.encode(&mut fields, index);
1940        assert_eq!(fields.refused(), None);
1941        fields.finish();
1942        assert_eq!(u32::try_from(out.0.len()).unwrap(), data_len(M::FIELDS.iter().copied()));
1943        out.0
1944    }
1945
1946    const T: Timestamp = Timestamp::from_fit(0x1122_3344);
1947    const T2: Timestamp = Timestamp::from_fit(0x1122_3380);
1948
1949    /// Totals left unset: "none" for each, signed ones with a clear top bit.
1950    #[rustfmt::skip]
1951    const NO_TOTALS: [u8; 63] = [
1952        0xFF, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0x7F, // start
1953        0xFF, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0x7F, // end
1954        0xFF, 0xFF, 0xFF, 0xFF, // distance
1955        0xFF, 0xFF, 0xFF, 0xFF, // speeds
1956        0xFF, 0xFF, // cadences
1957        0xFF, 0xFF, 0xFF, 0xFF, // powers
1958        0xFF, 0xFF, 0xFF, 0xFF, // ascent, descent
1959        0xFF, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0x7F, // north-east
1960        0xFF, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0x7F, // south-west
1961        0x7F, 0x7F, // temperatures
1962        0xFF, 0xFF, 0xFF, 0xFF, // cycles
1963        0xFF, 0xFF, 0xFF, 0xFF, // lengths
1964        0xFF, 0xFF, 0xFF, // stroke distance, swim stroke
1965    ];
1966
1967    fn totals() -> Totals {
1968        let p = |lat, long| Position::from_semicircles(lat, long);
1969        Totals {
1970            start: p(1, -2),
1971            end: p(3, -4),
1972            north_east: p(5, -6),
1973            south_west: p(7, -8),
1974            distance: Some(0x0102_0304),
1975            avg_speed: Some(0x0506),
1976            max_speed: Some(0x0708),
1977            avg_cadence: Some(9),
1978            max_cadence: Some(10),
1979            avg_power: Some(0x0B0C),
1980            max_power: Some(0x0D0E),
1981            ascent: Some(0x0F10),
1982            descent: Some(0x1112),
1983            avg_temperature: Some(-13),
1984            max_temperature: Some(14),
1985            cycles: Some(0x1314_1516),
1986            lengths: Some(0x1718),
1987            active_lengths: Some(0x191A),
1988            stroke_distance: Some(0x1B1C),
1989            swim_stroke: Some(SwimStroke::new(0x1D)),
1990        }
1991    }
1992
1993    #[rustfmt::skip]
1994    const TOTALS: [u8; 63] = [
1995        1, 0, 0, 0, 0xFE, 0xFF, 0xFF, 0xFF,
1996        3, 0, 0, 0, 0xFC, 0xFF, 0xFF, 0xFF,
1997        0x04, 0x03, 0x02, 0x01,
1998        0x06, 0x05, 0x08, 0x07,
1999        9, 10,
2000        0x0C, 0x0B, 0x0E, 0x0D,
2001        0x10, 0x0F, 0x12, 0x11,
2002        5, 0, 0, 0, 0xFA, 0xFF, 0xFF, 0xFF,
2003        7, 0, 0, 0, 0xF8, 0xFF, 0xFF, 0xFF,
2004        0xF3, 14,
2005        0x16, 0x15, 0x14, 0x13,
2006        0x18, 0x17, 0x1A, 0x19,
2007        0x1C, 0x1B, 0x1D,
2008    ];
2009
2010    #[test]
2011    fn file_id() {
2012        let id = FileId::new(FileType::ACTIVITY, Manufacturer::DEVELOPMENT, 0x0102, T)
2013            .serial_number(0xAABB_CCDD);
2014        assert_eq!(
2015            bytes(&id, 0),
2016            [4, 0xFF, 0x00, 0x02, 0x01, 0xDD, 0xCC, 0xBB, 0xAA, 0x44, 0x33, 0x22, 0x11]
2017        );
2018        let no_serial = FileId::new(FileType::new(9), Manufacturer::new(1), 2, T);
2019        assert_eq!(bytes(&no_serial, 0), [9, 1, 0, 2, 0, 0, 0, 0, 0, 0x44, 0x33, 0x22, 0x11]);
2020        assert_eq!(id.timestamp(), None);
2021    }
2022
2023    #[test]
2024    fn device_info() {
2025        let info = DeviceInfo::new(T)
2026            .device_index(2)
2027            .manufacturer(Manufacturer::new(0x0304))
2028            .serial_number(7)
2029            .product(0x0506)
2030            .software_version(123)
2031            .product_name("Watch");
2032        let mut want = vec![0x44, 0x33, 0x22, 0x11, 2, 0x04, 0x03, 7, 0, 0, 0, 0x06, 0x05, 123, 0];
2033        want.extend_from_slice(b"Watch");
2034        want.resize(want.len() + 15, 0);
2035        assert_eq!(bytes(&info, 0), want);
2036        assert_eq!(info.timestamp(), Some(T));
2037
2038        let mut empty =
2039            vec![0x44, 0x33, 0x22, 0x11, 0, 0xFF, 0xFF, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF];
2040        empty.resize(empty.len() + 20, 0);
2041        assert_eq!(bytes(&DeviceInfo::new(T), 0), empty);
2042    }
2043
2044    #[test]
2045    fn product_name_limit() {
2046        let longest = "0123456789abcdefghi";
2047        assert_eq!(longest.len(), PRODUCT_NAME_MAX);
2048        let out = bytes(&DeviceInfo::new(T).product_name(longest), 0);
2049        assert_eq!(out.last(), Some(&0));
2050        let long = DeviceInfo::new(T).product_name("0123456789abcdefghij");
2051        assert_eq!(refused(&long, 0), Some(FieldError::StringTooLong));
2052    }
2053
2054    #[test]
2055    fn events() {
2056        let t = [0x44, 0x33, 0x22, 0x11];
2057        assert_eq!(bytes(&Event::timer_start(T), 0), [&t[..], &[0, 0]].concat());
2058        assert_eq!(bytes(&Event::timer_stop(T), 0), [&t[..], &[0, 1]].concat());
2059        assert_eq!(bytes(&Event::timer_stop_all(T), 0), [&t[..], &[0, 4]].concat());
2060        assert_eq!(Event::timer_start(T).timestamp(), Some(T));
2061    }
2062
2063    #[test]
2064    fn lap() {
2065        let lap = Lap::new(T, T2, 0x0001_0203, 0x0004_0506)
2066            .heart_rate(120, 150)
2067            .sport(Sport::RUNNING, SubSport::TREADMILL);
2068        let out = bytes(&lap, 0x0102);
2069        assert_eq!(
2070            out[..24],
2071            [
2072                0x02, 0x01, 0x80, 0x33, 0x22, 0x11, 9, 1, 0x44, 0x33, 0x22, 0x11, 0x03, 0x02, 0x01,
2073                0x00, 0x06, 0x05, 0x04, 0x00, 120, 150, 1, 1
2074            ]
2075        );
2076        assert_eq!(out[24], lap_trigger::MANUAL);
2077        assert_eq!(out[25..88], NO_TOTALS);
2078        assert_eq!(out[88..], [0xFF, 0xFF]);
2079        let ended = bytes(&lap.trigger(lap_trigger::SESSION_END), 0x0102);
2080        assert_eq!(ended[24], 7);
2081        let bare = bytes(&Lap::new(T, T2, 0, 0), 0);
2082        assert_eq!(bare.get(20..24), Some(&[0xFF; 4][..]));
2083        let full = bytes(&lap.totals(totals()).first_length(0x1E1F), 0x0102);
2084        assert_eq!((&full[25..88], &full[88..]), (&TOTALS[..], &[0x1F, 0x1E][..]));
2085        assert_eq!(lap.timestamp(), Some(T2));
2086    }
2087
2088    #[test]
2089    fn session() {
2090        let session = Session::new(T, T2, 0x0001_0203, 0x0004_0506)
2091            .heart_rate(121, 151)
2092            .sport(Sport::TRAINING, SubSport::CARDIO_TRAINING)
2093            .laps(3, 4);
2094        let out = bytes(&session, 5);
2095        assert_eq!(
2096            out[..28],
2097            [
2098                5, 0, 0x80, 0x33, 0x22, 0x11, 8, 1, 0x44, 0x33, 0x22, 0x11, 10, 26, 0x03, 0x02,
2099                0x01, 0x00, 0x06, 0x05, 0x04, 0x00, 121, 151, 3, 0, 4, 0
2100            ]
2101        );
2102        assert_eq!(out[28..91], NO_TOTALS);
2103        assert_eq!(out[91..], [0xFF, 0xFF, 0xFF, trigger::ACTIVITY_END]);
2104        let bare = bytes(&Session::new(T, T2, 0, 0), 0);
2105        assert_eq!(bare.get(12..14), Some(&[0xFF; 2][..]));
2106        assert_eq!(bare.get(22..28), Some(&[0xFF, 0xFF, 0, 0, 1, 0][..]));
2107        let full = session.totals(totals()).pool(Pool::yards(25.0)).trigger(trigger::MANUAL);
2108        let full = bytes(&full, 5);
2109        assert_eq!((&full[28..91], &full[91..]), (&TOTALS[..], &[0xEE, 0x08, 1, 1][..]));
2110        assert_eq!(session.timestamp(), Some(T2));
2111    }
2112
2113    #[test]
2114    fn activity() {
2115        let a = Activity::new(T2, 0x0004_0506).sessions(2).utc_offset(-0x80);
2116        assert_eq!(
2117            bytes(&a, 0),
2118            [
2119                0x80, 0x33, 0x22, 0x11, 0x06, 0x05, 0x04, 0x00, 2, 0, 0, 26, 1, 0x00, 0x33, 0x22,
2120                0x11
2121            ]
2122        );
2123        let none = bytes(&Activity::new(T2, 0), 0);
2124        assert_eq!(none.get(8..11), Some(&[1, 0, 0][..]), "one session, manual");
2125        let auto = bytes(&Activity::new(T2, 0).auto_multisport(true), 0);
2126        assert_eq!(auto.get(10), Some(&1), "auto_multi_sport");
2127        assert_eq!(none.get(13..), Some(&[0xFF; 4][..]));
2128        assert_eq!(a.timestamp(), Some(T2));
2129    }
2130
2131    #[test]
2132    fn sports() {
2133        let named = SportMsg { sport: Sport::new(5), sub_sport: SubSport::new(18), name: "Swim" };
2134        let mut want = [0u8; 26];
2135        want[..6].copy_from_slice(&[5, 18, b'S', b'w', b'i', b'm']);
2136        assert_eq!(bytes(&named, 0), want);
2137        let unnamed = bytes(&SportMsg { name: "", ..named }, 0);
2138        assert_eq!(unnamed, [&[5, 18][..], &[0; 24]].concat(), "a string's none");
2139        let long = "a name of twenty-four by";
2140        assert_eq!(long.len(), SPORT_NAME_MAX + 1);
2141        assert_eq!(refused(&SportMsg { name: long, ..named }, 0), Some(FieldError::StringTooLong));
2142        assert_eq!(named.timestamp(), None);
2143    }
2144
2145    #[test]
2146    fn local_timestamp_out_of_range_is_refused() {
2147        let at = |t: u32, offset: i32| Activity::new(Timestamp::from_fit(t), 0).utc_offset(offset);
2148        assert_eq!(at(10, -11).local_timestamp(), Some(INVALID_U32));
2149        assert_eq!(at(10, -10).local_timestamp(), Some(0));
2150        assert_eq!(at(u32::MAX - 1, 1).local_timestamp(), Some(INVALID_U32));
2151        assert_eq!(at(u32::MAX - 2, 1).local_timestamp(), Some(u32::MAX - 1));
2152        assert_eq!(at(100, 3600).local_timestamp(), Some(3700));
2153        assert_eq!(Activity::new(T, 0).local_timestamp(), None);
2154        assert_eq!(refused(&at(10, -11), 0), Some(FieldError::OutOfRange));
2155    }
2156
2157    #[test]
2158    fn record_layouts() {
2159        assert_eq!(Record::new(T).heart_rate(99).fields(), RecordFields::HEART_RATE);
2160        assert_eq!(Record::new(T).fields(), RecordFields(0));
2161        assert_eq!(record_fields(RecordFields(0)).count(), 0);
2162        let mut all = Record::new(T)
2163            .position(Position::from_semicircles(1, 2).unwrap())
2164            .altitude(Altitude::smoothed_meters(0.0))
2165            .heart_rate(3)
2166            .cadence_rpm(4)
2167            .speed_meters_per_second(6.0)
2168            .power_watts(7)
2169            .temperature_celsius(-8);
2170        all.distance = Some(500);
2171        let defs: std::vec::Vec<FieldDef> = record_fields(all.fields()).collect();
2172        assert_eq!(defs.len(), 9);
2173        let mut out = VecPut(vec![]);
2174        let mut fields = Fields::new(defs.into_iter(), Some(&mut out));
2175        all.encode(&mut fields);
2176        assert_eq!(fields.refused(), None);
2177        fields.finish();
2178        #[rustfmt::skip]
2179        let want = [
2180            1, 0, 0, 0, 2, 0, 0, 0, // position
2181            0xC4, 0x09, // altitude: (0 + 500) * 5
2182            3, 4,
2183            0xF4, 0x01, 0, 0, // distance: 500 cm
2184            0x70, 0x17, // speed: 6000 mm/s
2185            7, 0,
2186            0xF8, // -8 °C
2187        ];
2188        assert_eq!(out.0, want);
2189        assert_eq!(
2190            record_fields(RecordFields::HEART_RATE).collect::<std::vec::Vec<_>>(),
2191            [field(3, 1, base::UINT8)]
2192        );
2193        assert!(!RecordFields(0).contains(RecordFields::HEART_RATE));
2194        assert!(RecordFields::HEART_RATE.contains(RecordFields(0)));
2195    }
2196
2197    #[test]
2198    fn values_fill_their_fields_exactly() {
2199        let defs = [
2200            field(0, 2, base::UINT16),
2201            field(1, 1, base::UINT8),
2202            field(2, 3, base::STRING),
2203            field(3, 4, base::UINT32Z),
2204            field(4, 2, base::UINT16),
2205            field(5, 1, base::ENUM),
2206        ];
2207        let mut out = VecPut(vec![]);
2208        let mut fields = Fields::new(defs.into_iter(), Some(&mut out));
2209        // Short and widened, a string, a none, then two left unwritten.
2210        fields.u8(7);
2211        fields.u32(9);
2212        fields.str("ab");
2213        fields.none();
2214        fields.finish();
2215        assert_eq!(
2216            fields_refused(&defs, |f| {
2217                f.u8(7);
2218                f.u32(9);
2219            }),
2220            None
2221        );
2222        assert_eq!(out.0, [7, 0, 9, b'a', b'b', 0, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF]);
2223
2224        let mut out = VecPut(vec![]);
2225        let mut fields = Fields::new([field(0, 1, base::UINT8)].into_iter(), Some(&mut out));
2226        fields.u8(1);
2227        fields.u8(2);
2228        fields.str("x");
2229        fields.none();
2230        fields.finish();
2231        assert_eq!(out.0, [1], "values past the table are dropped");
2232    }
2233
2234    fn fields_refused(
2235        defs: &[FieldDef],
2236        f: impl Fn(&mut Fields<'_, core::iter::Copied<core::slice::Iter<'_, FieldDef>>>),
2237    ) -> Option<FieldError> {
2238        let mut fields = Fields::new(defs.iter().copied(), None);
2239        f(&mut fields);
2240        fields.refused()
2241    }
2242
2243    #[test]
2244    fn a_value_that_is_none_or_too_wide_is_refused() {
2245        let s8 = [field(0, 1, base::SINT8)];
2246        let s32 = [field(0, 4, base::SINT32)];
2247        assert_eq!(fields_refused(&s8, |f| f.i8(i8::MAX)), Some(FieldError::OutOfRange));
2248        assert_eq!(fields_refused(&s8, |f| f.i8(-1)), None);
2249        assert_eq!(fields_refused(&s32, |f| f.i32(i32::MAX)), Some(FieldError::OutOfRange));
2250        assert_eq!(fields_refused(&s32, |f| f.i32(-1)), None);
2251        let u8_ = [field(0, 1, base::UINT8)];
2252        let u16_ = [field(0, 2, base::UINT16)];
2253        let z = [field(0, 4, base::UINT32Z)];
2254        let e = Some(FieldError::OutOfRange);
2255        assert_eq!(fields_refused(&u8_, |f| f.u8(0xFF)), e);
2256        assert_eq!(fields_refused(&u8_, |f| f.u8(0xFE)), None);
2257        assert_eq!(fields_refused(&u8_, |f| f.u16(0x0100)), e);
2258        assert_eq!(fields_refused(&u8_, |f| f.u16(0x00FE)), None);
2259        assert_eq!(fields_refused(&u16_, |f| f.u16(0xFFFF)), e);
2260        assert_eq!(fields_refused(&u16_, |f| f.u8(0xFF)), None, "widened, it is 0x00FF");
2261        assert_eq!(fields_refused(&z, |f| f.u32(0)), e);
2262        assert_eq!(fields_refused(&z, |f| f.u32(u32::MAX)), None);
2263        assert_eq!(fields_refused(&z, |f| f.none()), None);
2264        // The first refusal is the one kept.
2265        let two = [field(0, 1, base::STRING), field(1, 1, base::UINT8)];
2266        assert_eq!(
2267            fields_refused(&two, |f| {
2268                f.str("x");
2269                f.u8(0xFF);
2270            }),
2271            Some(FieldError::StringTooLong)
2272        );
2273    }
2274
2275    #[test]
2276    fn messages_refuse_none_as_a_value() {
2277        let e = Some(FieldError::OutOfRange);
2278        let id = |t| FileId::new(t, Manufacturer::DEVELOPMENT, 1, T);
2279        assert_eq!(refused(&id(FileType::new(255)), 0), e);
2280        assert_eq!(refused(&id(FileType::ACTIVITY).serial_number(0), 0), e);
2281        assert_eq!(
2282            refused(&FileId::new(FileType::ACTIVITY, Manufacturer::new(0xFFFF), 1, T), 0),
2283            e
2284        );
2285        assert_eq!(refused(&DeviceInfo::new(T).product(0xFFFF), 0), e);
2286        assert_eq!(refused(&Event::timer_start(Timestamp::from_fit(u32::MAX)), 0), e);
2287        let lap = Lap::new(T, T2, 0, 0);
2288        assert_eq!(refused(&lap.heart_rate(255, 255), 0), e);
2289        assert_eq!(refused(&lap.sport(Sport::new(255), SubSport::GENERIC), 0), e);
2290        assert_eq!(refused(&Lap::new(T, T2, u32::MAX, 0), 0), e);
2291        assert_eq!(
2292            refused(&Session::new(T, T2, 0, 0).sport(Sport::RUNNING, SubSport::new(255)), 0),
2293            e
2294        );
2295        assert_eq!(
2296            refused(&lap.heart_rate(254, 254).sport(Sport::new(254), SubSport::new(254)), 0),
2297            None
2298        );
2299    }
2300
2301    #[test]
2302    fn masks_hold_any_field_of_a_definition() {
2303        let mut m = Mask::EMPTY;
2304        for i in [0, 63, 64, 200, 255] {
2305            assert!(!m.contains(i));
2306            m.insert(i);
2307            assert!(m.contains(i));
2308        }
2309        assert!(!m.contains(1) && !m.contains(65) && !m.contains(256));
2310        m.insert(256);
2311        assert!(!m.contains(256), "past a definition's last field");
2312        let rest = Mask::ALL.without(m);
2313        assert!(!rest.contains(64) && rest.contains(65) && rest.contains(254));
2314        let defs = [field(1, 1, base::UINT8), field(2, 2, base::UINT16), field(3, 1, base::UINT8)];
2315        let mut keep = Mask::EMPTY;
2316        keep.insert(0);
2317        keep.insert(2);
2318        assert_eq!(
2319            kept(defs.into_iter(), keep).map(|f| f.num).collect::<std::vec::Vec<_>>(),
2320            [1, 3]
2321        );
2322    }
2323
2324    #[test]
2325    fn a_message_keeps_the_fields_it_has_values_for() {
2326        let mut fields = Fields::new(DeviceInfo::FIELDS.iter().copied(), None);
2327        DeviceInfo::new(T).product_name("Watch").encode(&mut fields, 0);
2328        let present = fields.present();
2329        let kept: std::vec::Vec<u8> =
2330            kept(DeviceInfo::FIELDS.iter().copied(), present).map(|f| f.num).collect();
2331        assert_eq!(kept, [TIMESTAMP, 0, 27], "timestamp, device_index and product_name");
2332        let mut out = VecPut(vec![]);
2333        let mut fields =
2334            Fields::new(DeviceInfo::FIELDS.iter().copied(), Some(&mut out)).keep(present);
2335        DeviceInfo::new(T).product_name("Watch").encode(&mut fields, 0);
2336        fields.finish();
2337        assert_eq!(out.0.len(), 4 + 1 + 20);
2338    }
2339
2340    #[test]
2341    fn lengths() {
2342        let span = Span {
2343            start_time: T,
2344            timestamp: T2,
2345            total_elapsed_ms: 0x0001_0203,
2346            total_timer_ms: 0x0004_0506,
2347        };
2348        let swum = LengthMsg {
2349            span,
2350            swum: Some(Length::swum(SwimStroke::BACKSTROKE, 0x0708)),
2351            avg_speed: Some(0x090A),
2352            cadence: Some(11),
2353        };
2354        #[rustfmt::skip]
2355        let want = [
2356            3, 0, 0x80, 0x33, 0x22, 0x11, 28, 1, 0x44, 0x33, 0x22, 0x11,
2357            0x03, 0x02, 0x01, 0x00, 0x06, 0x05, 0x04, 0x00,
2358            0x08, 0x07, 0x0A, 0x09, 1, 11, 1,
2359        ];
2360        assert_eq!(bytes(&swum, 3), want);
2361        let idle = LengthMsg { span, swum: None, avg_speed: None, cadence: None };
2362        let out = bytes(&idle, 3);
2363        assert_eq!((&out[20..26], out[26]), (&[0xFF; 6][..], 0));
2364        let drill = LengthMsg { swum: Some(Length::drill()), ..idle };
2365        assert_eq!(&bytes(&drill, 3)[20..], [0xFF, 0xFF, 0xFF, 0xFF, 4, 0xFF, 1]);
2366        assert_eq!(idle.timestamp(), Some(T2));
2367    }
2368
2369    #[test]
2370    fn sets() {
2371        let set = Set::new()
2372            .exercise(Exercise::new(ExerciseCategory::SQUAT).name(0x0102))
2373            .repetitions(10)
2374            .weight_pounds(100.0);
2375        let msg = SetMsg { start_time: T, timestamp: T2, duration_ms: 0x0004_0506, set: Some(set) };
2376        #[rustfmt::skip]
2377        let want = [
2378            0x80, 0x33, 0x22, 0x11, 0x06, 0x05, 0x04, 0x00,
2379            10, 0, 0xD6, 0x02, // 45.359 kg in sixteenths: 726
2380            1, 0x44, 0x33, 0x22, 0x11, 28, 0, 0x02, 0x01, 2, 0, 7, 0,
2381        ];
2382        assert_eq!(bytes(&msg, 7), want);
2383        let rest = SetMsg { set: None, ..msg };
2384        let out = bytes(&rest, 7);
2385        assert_eq!((&out[8..12], out[12]), (&[0xFF; 4][..], 0));
2386        assert_eq!(&out[17..23], &[0xFF; 6][..]);
2387        let unnamed = SetMsg {
2388            set: Some(Set::new().exercise(Exercise::new(ExerciseCategory::new(1)))),
2389            ..msg
2390        };
2391        assert_eq!(&bytes(&unnamed, 7)[17..21], [1, 0, 0xFF, 0xFF]);
2392        assert_eq!(Set::new().weight_kilograms(60.0).weight, Some(960));
2393        assert_eq!(Set::new().weight_kilograms(60.0).weight_unit, Some(1));
2394        assert_eq!(Set::new().weight_kilograms(4095.875).weight, Some(65_534));
2395        assert_eq!(Set::new().weight_kilograms(-1.0).weight, Some(u16::MAX));
2396    }
2397
2398    #[test]
2399    fn pools() {
2400        assert_eq!(Pool::meters(25.0), Pool { centimetres: 2500, unit: 0 });
2401        assert_eq!(Pool::yards(25.0), Pool { centimetres: 2286, unit: 1 });
2402        assert_eq!(Pool::meters(33.333), Pool { centimetres: 3333, unit: 0 });
2403        assert_eq!(Pool::meters(1000.0).centimetres, u16::MAX);
2404    }
2405
2406    #[test]
2407    fn beat_intervals_fill_five_slots() {
2408        let out = bytes(&Hrv(&[0x0102, 0x0304]), 0);
2409        assert_eq!(out, [0x02, 0x01, 0x04, 0x03, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
2410        assert_eq!(bytes(&Hrv(&[1, 2, 3, 4, 5]), 0), [1, 0, 2, 0, 3, 0, 4, 0, 5, 0]);
2411        assert_eq!(refused(&Hrv(&[1, 2, 3, 4, 5, 6]), 0), Some(FieldError::OutOfRange));
2412        assert_eq!(refused(&Hrv(&[1, u16::MAX]), 0), Some(FieldError::OutOfRange));
2413        assert_eq!(bytes(&Hrv(&[]), 0), [0xFF; 10], "none");
2414        assert_eq!(Hrv(&[]).timestamp(), None);
2415    }
2416
2417    #[test]
2418    fn bytes_fill_their_field_exactly() {
2419        let defs = [field(0, 2, base::BYTE)];
2420        let e = Some(FieldError::OutOfRange);
2421        assert_eq!(fields_refused(&defs, |f| f.bytes(&[1, 2, 3])), e);
2422        assert_eq!(fields_refused(&defs, |f| f.bytes(&[1])), e);
2423        assert_eq!(fields_refused(&defs, |f| f.bytes(&[0xFF, 0xFF])), e);
2424        assert_eq!(fields_refused(&defs, |f| f.bytes(&[0xFF, 0])), None);
2425    }
2426
2427    #[test]
2428    fn strings_need_room_for_their_nul() {
2429        let defs = [field(0, 3, base::STRING)];
2430        let mut fields = Fields::new(defs.into_iter(), None);
2431        fields.str("abc");
2432        assert_eq!(fields.refused(), Some(FieldError::StringTooLong));
2433        let mut fields = Fields::new(defs.into_iter(), None);
2434        fields.str("ab");
2435        assert_eq!(fields.refused(), None);
2436    }
2437
2438    #[test]
2439    fn strings_hold_no_nul() {
2440        let defs = [field(0, 8, base::STRING)];
2441        for s in ["a\0b", "\0", "ab\0"] {
2442            let mut fields = Fields::new(defs.into_iter(), None);
2443            fields.str(s);
2444            assert_eq!(fields.refused(), Some(FieldError::OutOfRange), "{s:?}");
2445        }
2446    }
2447}