fit-encoder 0.1.0

Write FIT activity files (the Flexible and Interoperable Data Transfer format) as a stream: file header first, CRC last, sizes known in advance. no_std, no allocation. Independent; not affiliated with Garmin
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! Developer fields: values for fields the FIT profile does not define, described in the file
//! itself by a `developer_data_id` and a `field_description` each.

use core::fmt;
use core::marker::PhantomData;

use crate::messages::{base, field, FieldDef, FieldOut, Lap, Message, Session, RECORD_GLOBAL};
use crate::raw::RawField;
use crate::types::{Manufacturer, Timestamp};

/// The most developers one file declares.
pub const DEVELOPERS_MAX: usize = 8;
/// The most developer fields one file declares, across its developers.
pub const DEVELOPER_FIELDS_MAX: usize = 32;
/// The most bytes the lap and session developer fields of one file take together.
pub const SUMMARY_BYTES_MAX: usize = 128;
/// The longest field name, in UTF-8 bytes.
pub const FIELD_NAME_MAX: usize = 63;
/// The longest units, in UTF-8 bytes.
pub const UNITS_MAX: usize = 15;

/// An application that adds developer fields, identified by its 16-byte application ID: a UUID
/// it keeps across every file it writes.
///
/// ```
/// use fit_encoder::{Developer, Manufacturer};
///
/// let app = Developer::new(*b"\x6a\x1e\x00\x9d\x3b\x55\x4c\x10\x8f\x0e\x2d\x41\x7a\x93\x01\x5c")
///     .manufacturer(Manufacturer::DEVELOPMENT)
///     .application_version(110); // 1.10
/// # let _ = app;
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Developer {
    application_id: [u8; 16],
    manufacturer: Option<Manufacturer>,
    application_version: Option<u32>,
}

impl Developer {
    /// An application by its ID; all `0xFF` is FIT's "none", which declaring refuses.
    #[must_use]
    pub const fn new(application_id: [u8; 16]) -> Self {
        Self { application_id, manufacturer: None, application_version: None }
    }

    /// The application's manufacturer.
    #[must_use]
    pub const fn manufacturer(mut self, manufacturer: Manufacturer) -> Self {
        self.manufacturer = Some(manufacturer);
        self
    }

    /// The application's version, in hundredths by convention: 110 is 1.10.
    #[must_use]
    pub const fn application_version(mut self, version: u32) -> Self {
        self.application_version = Some(version);
        self
    }

    pub(crate) const fn application_id(&self) -> [u8; 16] {
        self.application_id
    }

    /// Its `developer_data_id` as `developer_data_index` `index`.
    pub(crate) const fn message(&self, index: u8) -> DeveloperDataId {
        DeveloperDataId { developer: *self, index }
    }
}

/// A developer [`Writer::developer`](crate::Writer::developer) declared, from which its fields
/// are described.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Dev {
    pub(crate) index: u8,
    /// The file that declared it.
    pub(crate) file: u32,
}

impl Dev {
    /// A field of a number type `T` in messages of kind `K`, numbered `num` among this
    /// developer's fields.
    #[must_use]
    pub const fn field<T: Scalar, K: Kind>(
        self,
        num: u8,
        name: &str,
    ) -> FieldDescription<'_, T, K> {
        FieldDescription::new(self, num, name, T::SIZE)
    }

    /// A string field of up to `max_len` UTF-8 bytes, from 1 to 254, with no NUL, in messages of
    /// kind `K`.
    #[must_use]
    pub const fn string<K: Kind>(
        self,
        num: u8,
        name: &str,
        max_len: u8,
    ) -> FieldDescription<'_, str, K> {
        let size = match max_len.checked_add(1) {
            Some(size) => size,
            None => 0,
        };
        FieldDescription::new(self, num, name, size)
    }
}

/// A developer field's description, given to [`Writer::declare`](crate::Writer::declare).
///
/// A value is written as given; `scale` and `offset` only tell readers how to read it, and not
/// all of them do, so a physical value in a type that holds it exactly, or a float, reads the
/// same everywhere.
pub struct FieldDescription<'a, T: ?Sized, K> {
    pub(crate) dev: Dev,
    pub(crate) num: u8,
    pub(crate) name: &'a str,
    pub(crate) units: &'a str,
    pub(crate) scale: Option<u8>,
    pub(crate) offset: Option<i8>,
    pub(crate) native: Option<u8>,
    pub(crate) size: u8,
    kind: Marker<T, K>,
}

impl<'a, T: ?Sized, K> FieldDescription<'a, T, K> {
    const fn new(dev: Dev, num: u8, name: &'a str, size: u8) -> Self {
        Self {
            dev,
            num,
            name,
            units: "",
            scale: None,
            offset: None,
            native: None,
            size,
            kind: PhantomData,
        }
    }

    /// Its units for display, up to [`UNITS_MAX`] bytes.
    #[must_use]
    pub const fn units(mut self, units: &'a str) -> Self {
        self.units = units;
        self
    }

    /// The value readers divide by, from 1 to 254.
    #[must_use]
    pub const fn scale(mut self, scale: u8) -> Self {
        self.scale = Some(scale);
        self
    }

    /// The value readers subtract after scaling, from -128 to 126.
    #[must_use]
    pub const fn offset(mut self, offset: i8) -> Self {
        self.offset = Some(offset);
        self
    }

    /// The profile field of `K`'s message this field stands in for, which some readers then
    /// show as that field. Its units are the native field's, without its scale and offset.
    #[must_use]
    pub const fn native_field(mut self, num: u8) -> Self {
        self.native = Some(num);
        self
    }
}

impl<T: ?Sized, K> fmt::Debug for FieldDescription<'_, T, K> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FieldDescription")
            .field("num", &self.num)
            .field("name", &self.name)
            .finish_non_exhaustive()
    }
}

/// Ties a handle or description to its value type and kind, owning neither.
type Marker<T, K> = PhantomData<(fn() -> *const T, fn() -> K)>;

/// What the encoder needs of a value type or a kind, on traits other crates cannot name and with
/// no methods, so that neither a glob import nor a bound adds any to the number types.
mod sealed {
    use super::{Encoded, KindId};

    pub trait Encode {
        const BASE: u8;
        fn encode(v: <Self as super::DevType>::Value<'_>) -> Encoded<'_>
        where
            Self: super::DevType;
    }

    pub trait Number: Encode {
        const SIZE: u8;
        /// Little-endian; NaN as all `0xFF`, the floats' "none", so that it is refused.
        fn le(v: Self) -> [u8; 8];
    }

    pub trait Belongs {
        const KIND: KindId;
    }
}

/// The type of a developer field's values: one of the number types, or `str`.
pub trait DevType: sealed::Encode {
    /// A value as the caller gives it.
    type Value<'a>: Copy;
}

/// A number type a developer field can hold.
pub trait Scalar: DevType + sealed::Number {}

/// A value's bytes, before they meet their field.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Encoded<'a>(pub(crate) Repr<'a>);

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Repr<'a> {
    /// Little-endian, as wide as the type.
    Number([u8; 8]),
    Str(&'a str),
}

macro_rules! scalar {
    ($($ty:ty => $base:ident, $nan:expr;)*) => {$(
        impl DevType for $ty {
            type Value<'a> = $ty;
        }

        impl sealed::Encode for $ty {
            const BASE: u8 = base::$base;

            fn encode(v: <Self as DevType>::Value<'_>) -> Encoded<'_> {
                Encoded(Repr::Number(sealed::Number::le(v)))
            }
        }

        impl Scalar for $ty {}

        impl sealed::Number for $ty {
            #[allow(clippy::cast_possible_truncation, reason = "a number type is at most 8 bytes")]
            const SIZE: u8 = core::mem::size_of::<$ty>() as u8;

            fn le(v: Self) -> [u8; 8] {
                let mut le = [0xFF; 8];
                let is_nan: fn($ty) -> bool = $nan;
                if !is_nan(v) {
                    for (slot, byte) in le.iter_mut().zip(v.to_le_bytes()) {
                        *slot = byte;
                    }
                }
                le
            }
        }
    )*};
}

scalar! {
    u8 => UINT8, |_| false;
    i8 => SINT8, |_| false;
    u16 => UINT16, |_| false;
    i16 => SINT16, |_| false;
    u32 => UINT32, |_| false;
    i32 => SINT32, |_| false;
    u64 => UINT64, |_| false;
    i64 => SINT64, |_| false;
    f32 => FLOAT32, f32::is_nan;
    f64 => FLOAT64, f64::is_nan;
}

impl DevType for str {
    type Value<'a> = &'a str;
}

impl sealed::Encode for str {
    const BASE: u8 = base::STRING;

    fn encode(v: <Self as DevType>::Value<'_>) -> Encoded<'_> {
        Encoded(Repr::Str(v))
    }
}

/// The messages a developer field belongs to: [`InRecord`], [`InLap`] or [`InSession`].
pub trait Kind: sealed::Belongs {}

/// A [`Kind`] whose message closes over time: its fields are set while it is open, with
/// [`Writer::developer_value`](crate::Writer::developer_value).
pub trait Summary: Kind {}

/// Fields of records.
#[derive(Debug)]
pub enum InRecord {}
/// Fields of laps.
#[derive(Debug)]
pub enum InLap {}
/// Fields of sessions.
#[derive(Debug)]
pub enum InSession {}

impl Kind for InRecord {}
impl Kind for InLap {}
impl Kind for InSession {}

impl sealed::Belongs for InRecord {
    const KIND: KindId = KindId::Record;
}
impl sealed::Belongs for InLap {
    const KIND: KindId = KindId::Lap;
}
impl sealed::Belongs for InSession {
    const KIND: KindId = KindId::Session;
}
impl Summary for InLap {}
impl Summary for InSession {}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KindId {
    Record,
    Lap,
    Session,
}

impl KindId {
    /// Its message's global number.
    pub(crate) const fn global(self) -> u16 {
        match self {
            Self::Record => RECORD_GLOBAL,
            Self::Lap => Lap::GLOBAL,
            Self::Session => Session::GLOBAL,
        }
    }
}

/// A declared field, as the file holds it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Handle {
    /// Its place among the file's developer fields.
    pub slot: u8,
    pub dev: u8,
    pub num: u8,
    pub base: u8,
    pub size: u8,
    pub kind: KindId,
    /// The file that declared it.
    pub file: u32,
}

/// A developer field [`Writer::declare`](crate::Writer::declare) declared, of values `T` in
/// messages of kind `K`. It is good only for the file that declared it, and only in the pass
/// that declared it; any other refuses it.
pub struct DevField<T: ?Sized, K> {
    pub(crate) handle: Handle,
    kind: Marker<T, K>,
}

/// A developer field of records.
pub type RecordField<T> = DevField<T, InRecord>;
/// A developer field of laps.
pub type LapField<T> = DevField<T, InLap>;
/// A developer field of sessions.
pub type SessionField<T> = DevField<T, InSession>;

impl<T: ?Sized, K> DevField<T, K> {
    pub(crate) const fn new(handle: Handle) -> Self {
        Self { handle, kind: PhantomData }
    }
}

impl<T: ?Sized, K> Clone for DevField<T, K> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T: ?Sized, K> Copy for DevField<T, K> {}

impl<T: ?Sized, K> PartialEq for DevField<T, K> {
    fn eq(&self, other: &Self) -> bool {
        self.handle == other.handle
    }
}

impl<T: ?Sized, K> Eq for DevField<T, K> {}

impl<T: ?Sized, K> fmt::Debug for DevField<T, K> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DevField")
            .field("developer_data_index", &self.handle.dev)
            .field("field_definition_number", &self.handle.num)
            .finish_non_exhaustive()
    }
}

impl<T: DevType + ?Sized> RecordField<T> {
    /// This field's `value`, for [`Writer::record_with`](crate::Writer::record_with).
    #[must_use]
    pub fn value<'a>(&self, value: T::Value<'a>) -> Extra<'a> {
        Extra(ExtraRepr::Dev(self.handle, T::encode(value)))
    }
}

/// A field a record carries besides those [`Record`](crate::Record) models.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Extra<'a>(pub(crate) ExtraRepr<'a>);

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ExtraRepr<'a> {
    Dev(Handle, Encoded<'a>),
    Raw(RawField<'a>),
}

/// The `developer_data_id` message.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct DeveloperDataId {
    developer: Developer,
    index: u8,
}

impl Message for DeveloperDataId {
    const GLOBAL: u16 = 207;
    const FIELDS: &'static [FieldDef] = &[
        field(1, 16, base::BYTE),  // application_id
        field(2, 2, base::UINT16), // manufacturer_id
        field(3, 1, base::UINT8),  // developer_data_index
        field(4, 4, base::UINT32), // application_version
    ];

    fn timestamp(&self) -> Option<Timestamp> {
        None
    }

    fn encode(&self, out: &mut dyn FieldOut, _: u16) {
        let d = &self.developer;
        out.bytes(&d.application_id);
        out.opt_u16(d.manufacturer.map(Manufacturer::get));
        out.u8(self.index);
        out.opt_u32(d.application_version);
    }
}

/// The `field_description` message.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Description<'a> {
    pub handle: Handle,
    pub name: &'a str,
    pub units: &'a str,
    pub scale: Option<u8>,
    pub offset: Option<i8>,
    pub native: Option<u8>,
}

impl Message for Description<'_> {
    const GLOBAL: u16 = 206;
    #[allow(clippy::cast_possible_truncation, reason = "both fit a byte")]
    const FIELDS: &'static [FieldDef] = &[
        field(0, 1, base::UINT8),                         // developer_data_index
        field(1, 1, base::UINT8),                         // field_definition_number
        field(2, 1, base::UINT8),                         // fit_base_type_id
        field(3, FIELD_NAME_MAX as u8 + 1, base::STRING), // field_name
        field(6, 1, base::UINT8),                         // scale
        field(7, 1, base::SINT8),                         // offset
        field(8, UNITS_MAX as u8 + 1, base::STRING),      // units
        field(14, 2, base::UINT16),                       // native_mesg_num
        field(15, 1, base::UINT8),                        // native_field_num
    ];

    fn timestamp(&self) -> Option<Timestamp> {
        None
    }

    fn encode(&self, out: &mut dyn FieldOut, _: u16) {
        let h = &self.handle;
        out.u8(h.dev);
        out.u8(h.num);
        out.u8(h.base);
        out.str(self.name);
        out.opt_u8(self.scale);
        out.opt_i8(self.offset);
        out.str(self.units);
        out.u16(h.kind.global());
        out.opt_u8(self.native);
    }
}