Skip to main content

fit_encoder/encoder/
extra.rs

1//! Fields beyond those the crate models: developer fields, and raw fields and messages.
2
3use super::{Error, Header, Layout, Mask, Put, Shape, Writer};
4use crate::developer::{
5    Description, Dev, DevField, DevType, Developer, DeveloperDataId, Extra, ExtraRepr,
6    FieldDescription, Handle, Kind, KindId, Repr, Summary, DEVELOPERS_MAX, DEVELOPER_FIELDS_MAX,
7    SUMMARY_BYTES_MAX,
8};
9use crate::messages::{
10    base, event, is_none, record_owns, Activity, DeviceInfo, Event, FieldDef, FileId, Hrv, Lap,
11    LengthMsg, Message, Session, SetMsg, SportMsg, RECORD_GLOBAL, TIMESTAMP,
12};
13use crate::raw::{RawField, RawValue, RAW_FIELDS_MAX};
14use crate::types::Timestamp;
15
16/// Where a message's fields beyond its table come from.
17#[derive(Clone, Copy)]
18pub(super) enum Extras<'v> {
19    /// Given with a record.
20    Values(&'v [Extra<'v>]),
21    /// A raw message's fields.
22    Raw(&'v [RawField<'v>]),
23    /// Set on the open lap or session.
24    Staged(KindId),
25}
26
27/// The developers and fields a file has declared, and the values set on its open lap and
28/// session.
29#[derive(Clone, Debug)]
30pub(super) struct DevTable {
31    /// This file's identity, which its handles carry.
32    pub(super) file: u32,
33    /// Each developer's application ID, by `developer_data_index`.
34    developers: [Option<[u8; 16]>; DEVELOPERS_MAX],
35    /// Each field, with where its lap or session value is kept.
36    fields: [Option<(Handle, usize)>; DEVELOPER_FIELDS_MAX],
37    summary: [u8; SUMMARY_BYTES_MAX],
38    summary_used: usize,
39    /// The fields with a value set.
40    staged: u32,
41}
42
43const MAX_FIELD: usize = u8::MAX as usize;
44
45/// The identity of the next file, which no other live one shares unless 2^32 files have been
46/// made since.
47#[cfg(target_has_atomic = "32")]
48fn next_file() -> u32 {
49    use core::sync::atomic::{AtomicU32, Ordering};
50    static NEXT_FILE: AtomicU32 = AtomicU32::new(0);
51    NEXT_FILE.fetch_add(1, Ordering::Relaxed)
52}
53
54#[cfg(not(target_has_atomic = "32"))]
55use self::next_file_in_critical_section as next_file;
56
57/// The identity of the next file without compare-and-swap, taken in a critical section the
58/// application provides.
59#[cfg(any(test, not(target_has_atomic = "32")))]
60fn next_file_in_critical_section() -> u32 {
61    use core::cell::Cell;
62    use critical_section::Mutex;
63    static NEXT_FILE: Mutex<Cell<u32>> = Mutex::new(Cell::new(0));
64    critical_section::with(|cs| {
65        let next = NEXT_FILE.borrow(cs);
66        let file = next.get();
67        next.set(file.wrapping_add(1));
68        file
69    })
70}
71
72fn bit(slot: u8) -> u32 {
73    1u32.checked_shl(u32::from(slot)).unwrap_or(0)
74}
75
76impl DevTable {
77    /// A table for a file of its own identity.
78    pub(super) fn new() -> Self {
79        Self {
80            file: next_file(),
81            developers: [None; DEVELOPERS_MAX],
82            fields: [None; DEVELOPER_FIELDS_MAX],
83            summary: [0; SUMMARY_BYTES_MAX],
84            summary_used: 0,
85            staged: 0,
86        }
87    }
88
89    /// Where `h`'s lap or session value is kept, if this file declared it.
90    fn find(&self, h: Handle) -> Result<usize, Error> {
91        match self.fields.get(usize::from(h.slot)) {
92            Some(Some((held, at))) if *held == h => Ok(*at),
93            _ => Err(Error::Undeclared),
94        }
95    }
96
97    /// The declared fields `mask` holds, in order.
98    fn each(&self, mask: u32) -> impl Iterator<Item = (Handle, usize)> + '_ {
99        self.fields.iter().flatten().copied().filter(move |(h, _)| mask & bit(h.slot) != 0)
100    }
101
102    /// The bytes the fields `mask` holds take in a data message.
103    pub(super) fn size(&self, mask: u32) -> u32 {
104        self.each(mask).map(|(h, _)| u32::from(h.size)).sum()
105    }
106
107    /// Forgets the values set on the message of `kind` just written.
108    pub(super) fn unstage(&mut self, kind: KindId) {
109        for (h, _) in self.fields.iter().flatten() {
110            if h.kind == kind {
111                self.staged &= !bit(h.slot);
112            }
113        }
114    }
115}
116
117/// The raw fields of a layout, in order.
118#[derive(Clone, Copy, Debug, PartialEq, Eq)]
119pub(super) struct RawDefs {
120    defs: [FieldDef; RAW_FIELDS_MAX],
121    len: usize,
122}
123
124impl RawDefs {
125    pub(super) const NONE: Self =
126        Self { defs: [FieldDef { num: 0, size: 0, base: 0 }; RAW_FIELDS_MAX], len: 0 };
127
128    pub(super) fn defs(&self) -> impl Iterator<Item = FieldDef> + Clone + '_ {
129        self.defs.iter().take(self.len).copied()
130    }
131}
132
133/// The raw fields `extras` holds.
134fn raw_fields(extras: Extras<'_>) -> impl Iterator<Item = &RawField<'_>> {
135    let (values, raw): (&[Extra<'_>], &[RawField<'_>]) = match extras {
136        Extras::Values(values) => (values, &[]),
137        Extras::Raw(raw) => (&[], raw),
138        Extras::Staged(_) => (&[], &[]),
139    };
140    let given = values.iter().filter_map(|v| match &v.0 {
141        ExtraRepr::Raw(f) => Some(f),
142        ExtraRepr::Dev(..) => None,
143    });
144    given.chain(raw)
145}
146
147/// The raw fields a message carries, refusing any it cannot write.
148pub(super) fn raw_defs(extras: Extras<'_>) -> Result<RawDefs, Error> {
149    let mut out = RawDefs::NONE;
150    for f in raw_fields(extras) {
151        let owned = matches!(extras, Extras::Values(_)) && record_owns(f.num);
152        if owned {
153            return Err(Error::Reserved);
154        }
155        if out.defs().any(|d| d.num == f.num) {
156            return Err(Error::Duplicate);
157        }
158        render_raw(f, &mut [0; MAX_FIELD])?;
159        let def = FieldDef { num: f.num, size: f.size(), base: f.base.get() };
160        *out.defs.get_mut(out.len).ok_or(Error::TooMany)? = def;
161        out.len = out.len.saturating_add(1);
162    }
163    Ok(out)
164}
165
166/// A raw field's bytes, in `buf`.
167fn render_raw<'b>(f: &RawField<'_>, buf: &'b mut [u8; MAX_FIELD]) -> Result<&'b [u8], Error> {
168    let size = usize::from(f.size());
169    let element = usize::from(f.base.size());
170    let timestamp = f.num == TIMESTAMP && (f.base.get() != base::UINT32 || size != 4);
171    if size == 0 || size.checked_rem(element) != Some(0) || timestamp {
172        return Err(Error::OutOfRange);
173    }
174    let out = buf.get_mut(..size).unwrap_or_default();
175    match f.value {
176        RawValue::Number(le, _) => {
177            for (o, b) in out.iter_mut().zip(le) {
178                *o = b;
179            }
180        }
181        RawValue::Str(s, _) => {
182            let s = s.as_bytes();
183            if s.contains(&0) {
184                return Err(Error::OutOfRange);
185            }
186            if s.len() >= size {
187                return Err(Error::StringTooLong);
188            }
189            for (o, &b) in out.iter_mut().zip(s.iter().chain(core::iter::repeat(&0))) {
190                *o = b;
191            }
192        }
193        RawValue::Bytes(b) => {
194            // A string's first NUL ends it for readers.
195            let cut_short = b.iter().skip_while(|&&b| b != 0).any(|&b| b != 0);
196            if f.base.get() == base::STRING && cut_short {
197                return Err(Error::OutOfRange);
198            }
199            out.copy_from_slice(b);
200        }
201    }
202    if out.chunks(element).all(|value| is_none(f.base.get(), value)) {
203        return Err(Error::OutOfRange);
204    }
205    Ok(out)
206}
207
208/// Global messages the encoder writes itself, and 0xFFFF, which is no message.
209const RESERVED: [u16; 13] = [
210    FileId::GLOBAL,
211    DeviceInfo::GLOBAL,
212    SportMsg::GLOBAL,
213    RECORD_GLOBAL,
214    LengthMsg::GLOBAL,
215    SetMsg::GLOBAL,
216    Hrv::GLOBAL,
217    Lap::GLOBAL,
218    Session::GLOBAL,
219    Activity::GLOBAL,
220    DeveloperDataId::GLOBAL,
221    Description::GLOBAL,
222    u16::MAX,
223];
224/// `event` messages for the timer, sessions, laps and the activity, which the encoder writes.
225const RESERVED_EVENTS: [u8; 4] = [event::TIMER, event::SESSION, event::LAP, event::ACTIVITY];
226
227/// The time a raw message's fields give it, refusing one the encoder writes itself.
228fn raw_message_time(global: u16, fields: &[RawField<'_>]) -> Result<Option<Timestamp>, Error> {
229    let value = |num: u8| {
230        fields.iter().find(|f| f.num == num).and_then(|f| match f.value {
231            RawValue::Number(le, _) => Some(le),
232            RawValue::Str(..) | RawValue::Bytes(_) => None,
233        })
234    };
235    let event = value(0).map(|[e, ..]| e);
236    let reserved_event =
237        global == Event::GLOBAL && event.is_none_or(|e| RESERVED_EVENTS.contains(&e));
238    if RESERVED.contains(&global) || reserved_event {
239        return Err(Error::Reserved);
240    }
241    let Some(field) = fields.iter().find(|f| f.num == TIMESTAMP) else { return Ok(None) };
242    let mut buf = [0; MAX_FIELD];
243    let le = <[u8; 4]>::try_from(render_raw(field, &mut buf)?).map_err(|_| Error::OutOfRange)?;
244    Ok(Some(Timestamp::from_fit(u32::from_le_bytes(le))))
245}
246
247/// `value` as `h`'s bytes, in `buf`.
248fn render<'b>(h: Handle, value: Repr<'_>, buf: &'b mut [u8; MAX_FIELD]) -> Result<&'b [u8], Error> {
249    let out = buf.get_mut(..usize::from(h.size)).unwrap_or_default();
250    match value {
251        Repr::Number(le) => {
252            for (o, b) in out.iter_mut().zip(le) {
253                *o = b;
254            }
255        }
256        Repr::Str(s) => {
257            let s = s.as_bytes();
258            if s.contains(&0) {
259                return Err(Error::OutOfRange);
260            }
261            if s.len() >= out.len() {
262                return Err(Error::StringTooLong);
263            }
264            out.fill(0);
265            for (o, &b) in out.iter_mut().zip(s) {
266                *o = b;
267            }
268        }
269    }
270    if is_none(h.base, out) {
271        return Err(Error::OutOfRange);
272    }
273    Ok(out)
274}
275
276impl Writer<'_> {
277    /// Declares a developer, writing its `developer_data_id`; its fields are then described
278    /// with [`Writer::declare`]. The first is `developer_data_index` 0, the next 1, and so on.
279    ///
280    /// # Errors
281    ///
282    /// [`Error::OutOfOrder`] outside the activity, [`Error::Duplicate`] for an application
283    /// declared already, [`Error::TooMany`] past [`DEVELOPERS_MAX`]; see [`Error`].
284    pub fn developer(&mut self, developer: &Developer) -> Result<Dev, Error> {
285        self.st.act.open()?;
286        let app = developer.application_id();
287        let held = &self.st.dev.developers;
288        if held.iter().flatten().any(|a| *a == app) {
289            return Err(Error::Duplicate);
290        }
291        let index = held.iter().position(Option::is_none).ok_or(Error::TooMany)?;
292        let index = u8::try_from(index).map_err(|_| Error::TooMany)?;
293        self.fixed(&developer.message(index), 0)?;
294        if let Some(d) = self.st.dev.developers.get_mut(usize::from(index)) {
295            *d = Some(app);
296        }
297        Ok(Dev { index, file: self.st.dev.file })
298    }
299
300    /// Declares a developer field, writing its `field_description`; the handle then gives it
301    /// values.
302    ///
303    /// ```
304    /// use fit_encoder::*;
305    ///
306    /// # let start = Timestamp::from_unix(1_764_590_400).unwrap();
307    /// # let mut buf = [0u8; 1024];
308    /// # let mut file = OnePass::new(SliceSink::new(&mut buf), Options::new()).unwrap();
309    /// # let mut w = file.writer();
310    /// # w.start(start, &Device::new(Manufacturer::DEVELOPMENT, 1)).unwrap();
311    /// let app = w.developer(&Developer::new([7; 16])).unwrap();
312    /// let smo2: RecordField<u8> = w.declare(&app.field(0, "SmO2").units("%")).unwrap();
313    /// let note: SessionField<str> = w.declare(&app.string(1, "Note", 31)).unwrap();
314    /// # let _ = (smo2, note);
315    /// ```
316    ///
317    /// # Errors
318    ///
319    /// [`Error::OutOfOrder`] outside the activity; [`Error::Undeclared`] for a developer this
320    /// file did not declare; [`Error::Duplicate`] for a number the developer used already;
321    /// [`Error::TooMany`] past [`DEVELOPER_FIELDS_MAX`] fields, or past
322    /// [`SUMMARY_BYTES_MAX`] for lap and session fields; [`Error::OutOfRange`] for an empty
323    /// name, a scale of 0, or a string of no length; [`Error::StringTooLong`] for a name or
324    /// units too long.
325    pub fn declare<T: DevType + ?Sized, K: Kind>(
326        &mut self,
327        d: &FieldDescription<'_, T, K>,
328    ) -> Result<DevField<T, K>, Error> {
329        self.st.act.open()?;
330        let table = &self.st.dev;
331        let declared = table.developers.get(usize::from(d.dev.index)).is_some_and(Option::is_some);
332        if !declared || d.dev.file != table.file {
333            return Err(Error::Undeclared);
334        }
335        let shortest = if T::BASE == base::STRING { 2 } else { 1 };
336        if d.name.is_empty() || d.scale == Some(0) || d.size < shortest {
337            return Err(Error::OutOfRange);
338        }
339        if table.fields.iter().flatten().any(|(h, _)| h.dev == d.dev.index && h.num == d.num) {
340            return Err(Error::Duplicate);
341        }
342        let slot = table.fields.iter().position(Option::is_none).ok_or(Error::TooMany)?;
343        let at = table.summary_used;
344        let used = match K::KIND {
345            KindId::Record => at,
346            KindId::Lap | KindId::Session => at.saturating_add(usize::from(d.size)),
347        };
348        if used > SUMMARY_BYTES_MAX {
349            return Err(Error::TooMany);
350        }
351        let handle = Handle {
352            slot: u8::try_from(slot).map_err(|_| Error::TooMany)?,
353            dev: d.dev.index,
354            num: d.num,
355            base: T::BASE,
356            size: d.size,
357            kind: K::KIND,
358            file: table.file,
359        };
360        let msg = Description {
361            handle,
362            name: d.name,
363            units: d.units,
364            scale: d.scale,
365            offset: d.offset,
366            native: d.native,
367        };
368        self.fixed(&msg, 0)?;
369        if let Some(f) = self.st.dev.fields.get_mut(slot) {
370            *f = Some((msg.handle, at));
371        }
372        self.st.dev.summary_used = used;
373        Ok(DevField::new(msg.handle))
374    }
375
376    /// Gives the open lap or session the value of one of its developer fields, written when it
377    /// ends. A field given again keeps the last value; one not given is left out.
378    ///
379    /// # Errors
380    ///
381    /// [`Error::OutOfOrder`] outside a session; [`Error::Undeclared`] for a field this file
382    /// did not declare; [`Error::OutOfRange`] or [`Error::StringTooLong`] for a value its
383    /// field cannot hold.
384    pub fn developer_value<T: DevType + ?Sized, K: Summary>(
385        &mut self,
386        field: &DevField<T, K>,
387        value: T::Value<'_>,
388    ) -> Result<(), Error> {
389        self.st.act.in_session()?;
390        let h = field.handle;
391        let at = self.st.dev.find(h)?;
392        let mut buf = [0; MAX_FIELD];
393        let bytes = render(h, T::encode(value).0, &mut buf)?;
394        let end = at.saturating_add(bytes.len());
395        if let Some(kept) = self.st.dev.summary.get_mut(at..end) {
396            kept.copy_from_slice(bytes);
397        }
398        self.st.dev.staged |= bit(h.slot);
399        Ok(())
400    }
401
402    /// The developer fields a message carries, refusing any value it cannot write.
403    pub(super) fn dev_fields(&self, extras: Extras<'_>) -> Result<u32, Error> {
404        let table = &self.st.dev;
405        match extras {
406            Extras::Staged(kind) => Ok(table
407                .each(table.staged)
408                .filter(|(h, _)| h.kind == kind)
409                .map(|(h, _)| bit(h.slot))
410                .sum()),
411            Extras::Raw(_) => Ok(0),
412            Extras::Values(values) => {
413                let mut mask = 0;
414                for v in values {
415                    let ExtraRepr::Dev(h, value) = v.0 else { continue };
416                    table.find(h)?;
417                    if mask & bit(h.slot) != 0 {
418                        return Err(Error::Duplicate);
419                    }
420                    render(h, value.0, &mut [0; MAX_FIELD])?;
421                    mask |= bit(h.slot);
422                }
423                Ok(mask)
424            }
425        }
426    }
427
428    /// Writes a message the crate does not model, global message `global` with `fields`, as
429    /// its layout: the explicit way to add what the encoder does not write.
430    ///
431    /// It may not be one the encoder writes itself or derives from what it writes: `file_id`,
432    /// `device_info`, `sport`, `record`, `length`, `set`, `hrv`, `lap`, `session`, `activity`,
433    /// `developer_data_id`, `field_description`, or an `event` for the timer, a session, a lap
434    /// or the activity, or one with no `event`. Extra record fields go with
435    /// [`Writer::record_with`]. A `timestamp` (253) must be a `uint32` no earlier than the last
436    /// time written, and moves the activity on to it.
437    ///
438    /// ```
439    /// use fit_encoder::*;
440    ///
441    /// # let start = Timestamp::from_unix(1_764_590_400).unwrap();
442    /// # let mut buf = [0u8; 1024];
443    /// # let mut file = OnePass::new(SliceSink::new(&mut buf), Options::new()).unwrap();
444    /// # let mut w = file.writer();
445    /// # w.start(start, &Device::new(Manufacturer::DEVELOPMENT, 1)).unwrap();
446    /// # w.session(start, Sport::CYCLING, SubSport::ROAD).unwrap();
447    /// // An event (21): rear_gear_change (43), a marker (3), rear gear 7 with 28 teeth.
448    /// let t = RawField::number(253, start.checked_add(5).unwrap().fit());
449    /// w.raw_message(21, &[t, RawField::enumeration(0, 43), RawField::enumeration(1, 3),
450    ///     RawField::number(11, 7u8), RawField::number(12, 28u8)]).unwrap();
451    /// ```
452    ///
453    /// # Errors
454    ///
455    /// [`Error::Reserved`] for a message the encoder writes; [`Error::OutOfOrder`] outside
456    /// the activity; [`Error::TimeWentBack`] for a time before one already written;
457    /// [`Error::Duplicate`] for a field given twice; [`Error::TooMany`] past
458    /// [`RAW_FIELDS_MAX`] fields; [`Error::OutOfRange`] or [`Error::StringTooLong`] for a
459    /// value its field cannot hold.
460    pub fn raw_message(&mut self, global: u16, fields: &[RawField<'_>]) -> Result<(), Error> {
461        let t = raw_message_time(global, fields)?;
462        let now = self.st.act.now();
463        self.st.act.started(t.unwrap_or(now))?;
464        self.endable(t.unwrap_or(now), self.st.laps, self.st.sessions)?;
465        let shape = Shape::Message { fields: &[], keep: Mask::ALL };
466        let layout = Layout { global, shape, raw: RawDefs::NONE, dev: 0 };
467        let none = core::iter::empty();
468        self.message(layout, none, Header::Normal, t, Extras::Raw(fields), |_| {})?;
469        if let Some(t) = t {
470            self.st.act.move_to(t);
471        }
472        Ok(())
473    }
474
475    /// The raw values of a data message, checked already by [`raw_defs`].
476    pub(super) fn put_raw_fields(&mut self, extras: Extras<'_>) {
477        for f in raw_fields(extras) {
478            let mut buf = [0; MAX_FIELD];
479            self.put(render_raw(f, &mut buf).unwrap_or_default());
480        }
481    }
482
483    /// The developer part of a definition.
484    pub(super) fn put_dev_definitions(&mut self, mask: u32) {
485        #[allow(clippy::cast_possible_truncation, reason = "at most 32 fields")]
486        self.put(&[mask.count_ones() as u8]);
487        for slot in 0..DEVELOPER_FIELDS_MAX {
488            let Some(Some((h, _))) = self.st.dev.fields.get(slot).copied() else { continue };
489            if mask & bit(h.slot) != 0 {
490                self.put(&[h.num, h.size, h.dev]);
491            }
492        }
493    }
494
495    /// The developer values of a data message, checked already by [`Writer::dev_fields`].
496    pub(super) fn put_dev_fields(&mut self, extras: Extras<'_>, mask: u32) {
497        for slot in 0..DEVELOPER_FIELDS_MAX {
498            let Some(Some((h, at))) = self.st.dev.fields.get(slot).copied() else { continue };
499            if mask & bit(h.slot) == 0 {
500                continue;
501            }
502            let mut buf = [0; MAX_FIELD];
503            let bytes = match extras {
504                Extras::Staged(_) => {
505                    let end = at.saturating_add(usize::from(h.size));
506                    let kept = self.st.dev.summary.get(at..end).unwrap_or_default();
507                    let out = buf.get_mut(..kept.len()).unwrap_or_default();
508                    out.copy_from_slice(kept);
509                    &*out
510                }
511                Extras::Raw(_) => &[],
512                Extras::Values(values) => values
513                    .iter()
514                    .find_map(|v| match v.0 {
515                        ExtraRepr::Dev(vh, value) if vh == h => Some(value),
516                        ExtraRepr::Dev(..) | ExtraRepr::Raw(_) => None,
517                    })
518                    .and_then(|value| render(h, value.0, &mut buf).ok())
519                    .unwrap_or_default(),
520            };
521            self.put(bytes);
522        }
523    }
524}
525
526#[cfg(test)]
527mod tests;