Skip to main content

fit_encoder/
developer.rs

1//! Developer fields: values for fields the FIT profile does not define, described in the file
2//! itself by a `developer_data_id` and a `field_description` each.
3
4use core::fmt;
5use core::marker::PhantomData;
6
7use crate::messages::{base, field, FieldDef, FieldOut, Lap, Message, Session, RECORD_GLOBAL};
8use crate::raw::RawField;
9use crate::types::{Manufacturer, Timestamp};
10
11/// The most developers one file declares.
12pub const DEVELOPERS_MAX: usize = 8;
13/// The most developer fields one file declares, across its developers.
14pub const DEVELOPER_FIELDS_MAX: usize = 32;
15/// The most bytes the lap and session developer fields of one file take together.
16pub const SUMMARY_BYTES_MAX: usize = 128;
17/// The longest field name, in UTF-8 bytes.
18pub const FIELD_NAME_MAX: usize = 63;
19/// The longest units, in UTF-8 bytes.
20pub const UNITS_MAX: usize = 15;
21
22/// An application that adds developer fields, identified by its 16-byte application ID: a UUID
23/// it keeps across every file it writes.
24///
25/// ```
26/// use fit_encoder::{Developer, Manufacturer};
27///
28/// let app = Developer::new(*b"\x6a\x1e\x00\x9d\x3b\x55\x4c\x10\x8f\x0e\x2d\x41\x7a\x93\x01\x5c")
29///     .manufacturer(Manufacturer::DEVELOPMENT)
30///     .application_version(110); // 1.10
31/// # let _ = app;
32/// ```
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub struct Developer {
35    application_id: [u8; 16],
36    manufacturer: Option<Manufacturer>,
37    application_version: Option<u32>,
38}
39
40impl Developer {
41    /// An application by its ID; all `0xFF` is FIT's "none", which declaring refuses.
42    #[must_use]
43    pub const fn new(application_id: [u8; 16]) -> Self {
44        Self { application_id, manufacturer: None, application_version: None }
45    }
46
47    /// The application's manufacturer.
48    #[must_use]
49    pub const fn manufacturer(mut self, manufacturer: Manufacturer) -> Self {
50        self.manufacturer = Some(manufacturer);
51        self
52    }
53
54    /// The application's version, in hundredths by convention: 110 is 1.10.
55    #[must_use]
56    pub const fn application_version(mut self, version: u32) -> Self {
57        self.application_version = Some(version);
58        self
59    }
60
61    pub(crate) const fn application_id(&self) -> [u8; 16] {
62        self.application_id
63    }
64
65    /// Its `developer_data_id` as `developer_data_index` `index`.
66    pub(crate) const fn message(&self, index: u8) -> DeveloperDataId {
67        DeveloperDataId { developer: *self, index }
68    }
69}
70
71/// A developer [`Writer::developer`](crate::Writer::developer) declared, from which its fields
72/// are described.
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub struct Dev {
75    pub(crate) index: u8,
76    /// The file that declared it.
77    pub(crate) file: u32,
78}
79
80impl Dev {
81    /// A field of a number type `T` in messages of kind `K`, numbered `num` among this
82    /// developer's fields.
83    #[must_use]
84    pub const fn field<T: Scalar, K: Kind>(
85        self,
86        num: u8,
87        name: &str,
88    ) -> FieldDescription<'_, T, K> {
89        FieldDescription::new(self, num, name, T::SIZE)
90    }
91
92    /// A string field of up to `max_len` UTF-8 bytes, from 1 to 254, with no NUL, in messages of
93    /// kind `K`.
94    #[must_use]
95    pub const fn string<K: Kind>(
96        self,
97        num: u8,
98        name: &str,
99        max_len: u8,
100    ) -> FieldDescription<'_, str, K> {
101        let size = match max_len.checked_add(1) {
102            Some(size) => size,
103            None => 0,
104        };
105        FieldDescription::new(self, num, name, size)
106    }
107}
108
109/// A developer field's description, given to [`Writer::declare`](crate::Writer::declare).
110///
111/// A value is written as given; `scale` and `offset` only tell readers how to read it, and not
112/// all of them do, so a physical value in a type that holds it exactly, or a float, reads the
113/// same everywhere.
114pub struct FieldDescription<'a, T: ?Sized, K> {
115    pub(crate) dev: Dev,
116    pub(crate) num: u8,
117    pub(crate) name: &'a str,
118    pub(crate) units: &'a str,
119    pub(crate) scale: Option<u8>,
120    pub(crate) offset: Option<i8>,
121    pub(crate) native: Option<u8>,
122    pub(crate) size: u8,
123    kind: Marker<T, K>,
124}
125
126impl<'a, T: ?Sized, K> FieldDescription<'a, T, K> {
127    const fn new(dev: Dev, num: u8, name: &'a str, size: u8) -> Self {
128        Self {
129            dev,
130            num,
131            name,
132            units: "",
133            scale: None,
134            offset: None,
135            native: None,
136            size,
137            kind: PhantomData,
138        }
139    }
140
141    /// Its units for display, up to [`UNITS_MAX`] bytes.
142    #[must_use]
143    pub const fn units(mut self, units: &'a str) -> Self {
144        self.units = units;
145        self
146    }
147
148    /// The value readers divide by, from 1 to 254.
149    #[must_use]
150    pub const fn scale(mut self, scale: u8) -> Self {
151        self.scale = Some(scale);
152        self
153    }
154
155    /// The value readers subtract after scaling, from -128 to 126.
156    #[must_use]
157    pub const fn offset(mut self, offset: i8) -> Self {
158        self.offset = Some(offset);
159        self
160    }
161
162    /// The profile field of `K`'s message this field stands in for, which some readers then
163    /// show as that field. Its units are the native field's, without its scale and offset.
164    #[must_use]
165    pub const fn native_field(mut self, num: u8) -> Self {
166        self.native = Some(num);
167        self
168    }
169}
170
171impl<T: ?Sized, K> fmt::Debug for FieldDescription<'_, T, K> {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        f.debug_struct("FieldDescription")
174            .field("num", &self.num)
175            .field("name", &self.name)
176            .finish_non_exhaustive()
177    }
178}
179
180/// Ties a handle or description to its value type and kind, owning neither.
181type Marker<T, K> = PhantomData<(fn() -> *const T, fn() -> K)>;
182
183/// What the encoder needs of a value type or a kind, on traits other crates cannot name and with
184/// no methods, so that neither a glob import nor a bound adds any to the number types.
185mod sealed {
186    use super::{Encoded, KindId};
187
188    pub trait Encode {
189        const BASE: u8;
190        fn encode(v: <Self as super::DevType>::Value<'_>) -> Encoded<'_>
191        where
192            Self: super::DevType;
193    }
194
195    pub trait Number: Encode {
196        const SIZE: u8;
197        /// Little-endian; NaN as all `0xFF`, the floats' "none", so that it is refused.
198        fn le(v: Self) -> [u8; 8];
199    }
200
201    pub trait Belongs {
202        const KIND: KindId;
203    }
204}
205
206/// The type of a developer field's values: one of the number types, or `str`.
207pub trait DevType: sealed::Encode {
208    /// A value as the caller gives it.
209    type Value<'a>: Copy;
210}
211
212/// A number type a developer field can hold.
213pub trait Scalar: DevType + sealed::Number {}
214
215/// A value's bytes, before they meet their field.
216#[derive(Clone, Copy, Debug, PartialEq, Eq)]
217pub struct Encoded<'a>(pub(crate) Repr<'a>);
218
219#[derive(Clone, Copy, Debug, PartialEq, Eq)]
220pub(crate) enum Repr<'a> {
221    /// Little-endian, as wide as the type.
222    Number([u8; 8]),
223    Str(&'a str),
224}
225
226macro_rules! scalar {
227    ($($ty:ty => $base:ident, $nan:expr;)*) => {$(
228        impl DevType for $ty {
229            type Value<'a> = $ty;
230        }
231
232        impl sealed::Encode for $ty {
233            const BASE: u8 = base::$base;
234
235            fn encode(v: <Self as DevType>::Value<'_>) -> Encoded<'_> {
236                Encoded(Repr::Number(sealed::Number::le(v)))
237            }
238        }
239
240        impl Scalar for $ty {}
241
242        impl sealed::Number for $ty {
243            #[allow(clippy::cast_possible_truncation, reason = "a number type is at most 8 bytes")]
244            const SIZE: u8 = core::mem::size_of::<$ty>() as u8;
245
246            fn le(v: Self) -> [u8; 8] {
247                let mut le = [0xFF; 8];
248                let is_nan: fn($ty) -> bool = $nan;
249                if !is_nan(v) {
250                    for (slot, byte) in le.iter_mut().zip(v.to_le_bytes()) {
251                        *slot = byte;
252                    }
253                }
254                le
255            }
256        }
257    )*};
258}
259
260scalar! {
261    u8 => UINT8, |_| false;
262    i8 => SINT8, |_| false;
263    u16 => UINT16, |_| false;
264    i16 => SINT16, |_| false;
265    u32 => UINT32, |_| false;
266    i32 => SINT32, |_| false;
267    u64 => UINT64, |_| false;
268    i64 => SINT64, |_| false;
269    f32 => FLOAT32, f32::is_nan;
270    f64 => FLOAT64, f64::is_nan;
271}
272
273impl DevType for str {
274    type Value<'a> = &'a str;
275}
276
277impl sealed::Encode for str {
278    const BASE: u8 = base::STRING;
279
280    fn encode(v: <Self as DevType>::Value<'_>) -> Encoded<'_> {
281        Encoded(Repr::Str(v))
282    }
283}
284
285/// The messages a developer field belongs to: [`InRecord`], [`InLap`] or [`InSession`].
286pub trait Kind: sealed::Belongs {}
287
288/// A [`Kind`] whose message closes over time: its fields are set while it is open, with
289/// [`Writer::developer_value`](crate::Writer::developer_value).
290pub trait Summary: Kind {}
291
292/// Fields of records.
293#[derive(Debug)]
294pub enum InRecord {}
295/// Fields of laps.
296#[derive(Debug)]
297pub enum InLap {}
298/// Fields of sessions.
299#[derive(Debug)]
300pub enum InSession {}
301
302impl Kind for InRecord {}
303impl Kind for InLap {}
304impl Kind for InSession {}
305
306impl sealed::Belongs for InRecord {
307    const KIND: KindId = KindId::Record;
308}
309impl sealed::Belongs for InLap {
310    const KIND: KindId = KindId::Lap;
311}
312impl sealed::Belongs for InSession {
313    const KIND: KindId = KindId::Session;
314}
315impl Summary for InLap {}
316impl Summary for InSession {}
317
318#[derive(Clone, Copy, Debug, PartialEq, Eq)]
319pub enum KindId {
320    Record,
321    Lap,
322    Session,
323}
324
325impl KindId {
326    /// Its message's global number.
327    pub(crate) const fn global(self) -> u16 {
328        match self {
329            Self::Record => RECORD_GLOBAL,
330            Self::Lap => Lap::GLOBAL,
331            Self::Session => Session::GLOBAL,
332        }
333    }
334}
335
336/// A declared field, as the file holds it.
337#[derive(Clone, Copy, Debug, PartialEq, Eq)]
338pub(crate) struct Handle {
339    /// Its place among the file's developer fields.
340    pub slot: u8,
341    pub dev: u8,
342    pub num: u8,
343    pub base: u8,
344    pub size: u8,
345    pub kind: KindId,
346    /// The file that declared it.
347    pub file: u32,
348}
349
350/// A developer field [`Writer::declare`](crate::Writer::declare) declared, of values `T` in
351/// messages of kind `K`. It is good only for the file that declared it, and only in the pass
352/// that declared it; any other refuses it.
353pub struct DevField<T: ?Sized, K> {
354    pub(crate) handle: Handle,
355    kind: Marker<T, K>,
356}
357
358/// A developer field of records.
359pub type RecordField<T> = DevField<T, InRecord>;
360/// A developer field of laps.
361pub type LapField<T> = DevField<T, InLap>;
362/// A developer field of sessions.
363pub type SessionField<T> = DevField<T, InSession>;
364
365impl<T: ?Sized, K> DevField<T, K> {
366    pub(crate) const fn new(handle: Handle) -> Self {
367        Self { handle, kind: PhantomData }
368    }
369}
370
371impl<T: ?Sized, K> Clone for DevField<T, K> {
372    fn clone(&self) -> Self {
373        *self
374    }
375}
376
377impl<T: ?Sized, K> Copy for DevField<T, K> {}
378
379impl<T: ?Sized, K> PartialEq for DevField<T, K> {
380    fn eq(&self, other: &Self) -> bool {
381        self.handle == other.handle
382    }
383}
384
385impl<T: ?Sized, K> Eq for DevField<T, K> {}
386
387impl<T: ?Sized, K> fmt::Debug for DevField<T, K> {
388    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389        f.debug_struct("DevField")
390            .field("developer_data_index", &self.handle.dev)
391            .field("field_definition_number", &self.handle.num)
392            .finish_non_exhaustive()
393    }
394}
395
396impl<T: DevType + ?Sized> RecordField<T> {
397    /// This field's `value`, for [`Writer::record_with`](crate::Writer::record_with).
398    #[must_use]
399    pub fn value<'a>(&self, value: T::Value<'a>) -> Extra<'a> {
400        Extra(ExtraRepr::Dev(self.handle, T::encode(value)))
401    }
402}
403
404/// A field a record carries besides those [`Record`](crate::Record) models.
405#[derive(Clone, Copy, Debug, PartialEq, Eq)]
406pub struct Extra<'a>(pub(crate) ExtraRepr<'a>);
407
408#[derive(Clone, Copy, Debug, PartialEq, Eq)]
409pub(crate) enum ExtraRepr<'a> {
410    Dev(Handle, Encoded<'a>),
411    Raw(RawField<'a>),
412}
413
414/// The `developer_data_id` message.
415#[derive(Clone, Copy, Debug, PartialEq, Eq)]
416pub(crate) struct DeveloperDataId {
417    developer: Developer,
418    index: u8,
419}
420
421impl Message for DeveloperDataId {
422    const GLOBAL: u16 = 207;
423    const FIELDS: &'static [FieldDef] = &[
424        field(1, 16, base::BYTE),  // application_id
425        field(2, 2, base::UINT16), // manufacturer_id
426        field(3, 1, base::UINT8),  // developer_data_index
427        field(4, 4, base::UINT32), // application_version
428    ];
429
430    fn timestamp(&self) -> Option<Timestamp> {
431        None
432    }
433
434    fn encode(&self, out: &mut dyn FieldOut, _: u16) {
435        let d = &self.developer;
436        out.bytes(&d.application_id);
437        out.opt_u16(d.manufacturer.map(Manufacturer::get));
438        out.u8(self.index);
439        out.opt_u32(d.application_version);
440    }
441}
442
443/// The `field_description` message.
444#[derive(Clone, Copy, Debug, PartialEq, Eq)]
445pub(crate) struct Description<'a> {
446    pub handle: Handle,
447    pub name: &'a str,
448    pub units: &'a str,
449    pub scale: Option<u8>,
450    pub offset: Option<i8>,
451    pub native: Option<u8>,
452}
453
454impl Message for Description<'_> {
455    const GLOBAL: u16 = 206;
456    #[allow(clippy::cast_possible_truncation, reason = "both fit a byte")]
457    const FIELDS: &'static [FieldDef] = &[
458        field(0, 1, base::UINT8),                         // developer_data_index
459        field(1, 1, base::UINT8),                         // field_definition_number
460        field(2, 1, base::UINT8),                         // fit_base_type_id
461        field(3, FIELD_NAME_MAX as u8 + 1, base::STRING), // field_name
462        field(6, 1, base::UINT8),                         // scale
463        field(7, 1, base::SINT8),                         // offset
464        field(8, UNITS_MAX as u8 + 1, base::STRING),      // units
465        field(14, 2, base::UINT16),                       // native_mesg_num
466        field(15, 1, base::UINT8),                        // native_field_num
467    ];
468
469    fn timestamp(&self) -> Option<Timestamp> {
470        None
471    }
472
473    fn encode(&self, out: &mut dyn FieldOut, _: u16) {
474        let h = &self.handle;
475        out.u8(h.dev);
476        out.u8(h.num);
477        out.u8(h.base);
478        out.str(self.name);
479        out.opt_u8(self.scale);
480        out.opt_i8(self.offset);
481        out.str(self.units);
482        out.u16(h.kind.global());
483        out.opt_u8(self.native);
484    }
485}