Skip to main content

fit_encoder/
types.rs

1//! Values that FIT messages carry: times, sports and identities.
2
3/// Seconds from the Unix epoch to the FIT epoch, 1989-12-31T00:00:00Z
4/// (<https://developer.garmin.com/fit/cookbook/datetime/>).
5pub const FIT_EPOCH_UNIX: i64 = 631_065_600;
6
7/// A FIT `date_time`: whole seconds since 1989-12-31T00:00:00Z.
8///
9/// ```
10/// use fit_encoder::Timestamp;
11///
12/// let t = Timestamp::from_unix(1_764_547_200).unwrap(); // 2025-12-01T00:00:00Z
13/// assert_eq!(t.fit(), 1_133_481_600);
14/// assert_eq!(t.unix(), 1_764_547_200);
15/// assert_eq!(Timestamp::from_unix(0), None);
16/// ```
17#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
18pub struct Timestamp(u32);
19
20impl Timestamp {
21    /// The first FIT second read as a date; readers take any earlier one as seconds since the
22    /// device started (Garmin, "Working with Date Time Values").
23    pub const FIRST_DATE: Self = Self(0x1000_0000);
24
25    /// A time as FIT seconds: a date from [`Timestamp::FIRST_DATE`], or seconds since the
26    /// device started before it. `u32::MAX` is FIT's "none", which writing refuses.
27    #[must_use]
28    pub const fn from_fit(seconds: u32) -> Self {
29        Self(seconds)
30    }
31
32    /// A Unix time in seconds, or `None` before [`Timestamp::FIRST_DATE`]
33    /// (1998-07-03T21:24:16Z) or from 2126-02-06T06:28:15Z, when FIT seconds reach `u32::MAX`.
34    #[must_use]
35    pub const fn from_unix(seconds: i64) -> Option<Self> {
36        let Some(fit) = seconds.checked_sub(FIT_EPOCH_UNIX) else {
37            return None;
38        };
39        if fit < Self::FIRST_DATE.0 as i64 || fit >= u32::MAX as i64 {
40            return None;
41        }
42        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
43        Some(Self(fit as u32))
44    }
45
46    /// A system time, to the second below it, or `None` outside [`Timestamp::from_unix`]'s
47    /// range.
48    #[cfg(feature = "std")]
49    #[must_use]
50    pub fn from_system_time(t: std::time::SystemTime) -> Option<Self> {
51        let unix = t.duration_since(std::time::UNIX_EPOCH).ok()?.as_secs();
52        Self::from_unix(i64::try_from(unix).ok()?)
53    }
54
55    /// The time as FIT seconds.
56    #[must_use]
57    pub const fn fit(self) -> u32 {
58        self.0
59    }
60
61    /// The time as Unix seconds.
62    #[must_use]
63    pub const fn unix(self) -> i64 {
64        (self.0 as i64).wrapping_add(FIT_EPOCH_UNIX)
65    }
66
67    /// The time `seconds` later, or `None` if that reaches `u32::MAX`, the invalid value.
68    #[must_use]
69    pub const fn checked_add(self, seconds: u32) -> Option<Self> {
70        match self.0.checked_add(seconds) {
71            Some(t) if t != u32::MAX => Some(Self(t)),
72            _ => None,
73        }
74    }
75}
76
77/// A place on Earth as FIT holds it: latitude and longitude in semicircles, 2³¹ to 180°.
78#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
79pub struct Position {
80    lat: i32,
81    long: i32,
82}
83
84const SEMICIRCLES_PER_DEGREE: f64 = 2_147_483_648.0 / 180.0;
85
86impl Position {
87    /// Latitude and longitude in degrees, north and east positive, or `None` beyond ±90° and
88    /// ±180°. 180° east is 180° west.
89    #[must_use]
90    pub fn from_degrees(lat: f64, long: f64) -> Option<Self> {
91        if !((-90.0..=90.0).contains(&lat) && (-180.0..=180.0).contains(&long)) {
92            return None;
93        }
94        Self::from_semicircles(
95            round(lat * SEMICIRCLES_PER_DEGREE)?,
96            // 180° and just short of it round to i32::MAX, FIT's none, or past it; all are 180°.
97            round(long * SEMICIRCLES_PER_DEGREE).filter(|&l| l != i32::MAX).unwrap_or(i32::MIN),
98        )
99    }
100
101    /// Latitude and longitude in semicircles, or `None` for `i32::MAX`, FIT's "none", or a
102    /// latitude beyond ±90°.
103    #[must_use]
104    pub const fn from_semicircles(lat: i32, long: i32) -> Option<Self> {
105        const QUARTER: i32 = 1 << 30;
106        if lat == i32::MAX || long == i32::MAX || lat > QUARTER || lat < -QUARTER {
107            return None;
108        }
109        Some(Self { lat, long })
110    }
111
112    /// Latitude and longitude in semicircles.
113    #[must_use]
114    pub const fn semicircles(self) -> (i32, i32) {
115        (self.lat, self.long)
116    }
117
118    /// Latitude and longitude in degrees.
119    #[must_use]
120    pub fn degrees(self) -> (f64, f64) {
121        (
122            f64::from(self.lat) / SEMICIRCLES_PER_DEGREE,
123            f64::from(self.long) / SEMICIRCLES_PER_DEGREE,
124        )
125    }
126}
127
128/// `x` to the nearest whole number, halves away from zero, if it is an `i32`.
129fn round(x: f64) -> Option<i32> {
130    let m = i64::try_from(half_up(x.abs())?).ok()?;
131    i32::try_from(if x.is_sign_negative() { m.wrapping_neg() } else { m }).ok()
132}
133
134/// `x` to the nearest whole number, halves up, saturating at `u64::MAX`; `None` for NaN or
135/// below -0.5.
136pub(crate) fn half_up(x: f64) -> Option<u64> {
137    if x.is_nan() || x < -0.5 {
138        return None;
139    }
140    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
141    let whole = x as u64;
142    #[allow(clippy::cast_precision_loss)]
143    let up = x - whole as f64 >= 0.5;
144    Some(whole.saturating_add(u64::from(up)))
145}
146
147/// A manufacturer ID, the FIT profile's `manufacturer` type.
148#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
149pub struct Manufacturer(u16);
150
151impl Manufacturer {
152    /// `development` (255), for devices without an assigned ID; any other must be one assigned
153    /// to you.
154    pub const DEVELOPMENT: Self = Self(255);
155
156    /// Any manufacturer ID.
157    #[must_use]
158    pub const fn new(id: u16) -> Self {
159        Self(id)
160    }
161
162    /// The ID.
163    #[must_use]
164    pub const fn get(self) -> u16 {
165        self.0
166    }
167}
168
169/// A FIT base type, from Table 7 of the FIT Protocol page: how a field's bytes are read.
170#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
171pub struct BaseType(u8);
172
173impl BaseType {
174    /// `enum`, one byte.
175    pub const ENUM: Self = Self(0x00);
176    /// `sint8`.
177    pub const SINT8: Self = Self(0x01);
178    /// `uint8`.
179    pub const UINT8: Self = Self(0x02);
180    /// `string`, UTF-8 ending in a NUL unless it fills its field.
181    pub const STRING: Self = Self(0x07);
182    /// `uint8z`, whose "none" is 0.
183    pub const UINT8Z: Self = Self(0x0A);
184    /// `byte`, a byte array whose "none" is all `0xFF`.
185    pub const BYTE: Self = Self(0x0D);
186    /// `sint16`.
187    pub const SINT16: Self = Self(0x83);
188    /// `uint16`.
189    pub const UINT16: Self = Self(0x84);
190    /// `sint32`.
191    pub const SINT32: Self = Self(0x85);
192    /// `uint32`.
193    pub const UINT32: Self = Self(0x86);
194    /// `float32`.
195    pub const FLOAT32: Self = Self(0x88);
196    /// `float64`.
197    pub const FLOAT64: Self = Self(0x89);
198    /// `uint16z`.
199    pub const UINT16Z: Self = Self(0x8B);
200    /// `uint32z`.
201    pub const UINT32Z: Self = Self(0x8C);
202    /// `sint64`.
203    pub const SINT64: Self = Self(0x8E);
204    /// `uint64`.
205    pub const UINT64: Self = Self(0x8F);
206    /// `uint64z`.
207    pub const UINT64Z: Self = Self(0x90);
208
209    pub(crate) const fn from_byte(base: u8) -> Self {
210        Self(base)
211    }
212
213    /// The base type field byte.
214    #[must_use]
215    pub const fn get(self) -> u8 {
216        self.0
217    }
218
219    /// The bytes one value takes; a field holds one, or an array of them.
220    #[must_use]
221    pub const fn size(self) -> u8 {
222        // The low five bits number the type; the high bit marks those wider than a byte.
223        match self.0 & 0x1F {
224            0x03 | 0x04 | 0x0B => 2,
225            0x05 | 0x06 | 0x08 | 0x0C => 4,
226            0x09 | 0x0E | 0x0F | 0x10 => 8,
227            _ => 1,
228        }
229    }
230}
231
232/// Defines a FIT enum type as its value, with names for the values this crate knows.
233macro_rules! profile_enum {
234    ($(#[$doc:meta])* $ty:ident { $($name:ident = $value:literal, $profile:literal;)* }) => {
235        profile_enum! { $(#[$doc])* $ty(u8) { $($name = $value, $profile;)* } }
236    };
237    ($(#[$doc:meta])* $ty:ident($repr:ty) { $($name:ident = $value:literal, $profile:literal;)* }) => {
238        $(#[$doc])*
239        #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
240        pub struct $ty($repr);
241
242        #[allow(dead_code, reason = "FileType is not exported")]
243        impl $ty {
244            $(
245                #[doc = concat!("`", $profile, "` (", stringify!($value), ").")]
246                pub const $name: Self = Self($value);
247            )*
248
249            #[doc = concat!("Any value. ", stringify!($repr), "::MAX is FIT's \"none\", which the encoder refuses to write.")]
250            #[must_use]
251            pub const fn new(value: $repr) -> Self {
252                Self(value)
253            }
254
255            /// The value.
256            #[must_use]
257            pub const fn get(self) -> $repr {
258                self.0
259            }
260
261            /// The profile's name for a value this crate names.
262            #[must_use]
263            pub const fn name(self) -> Option<&'static str> {
264                match self.0 {
265                    $($value => Some($profile),)*
266                    _ => None,
267                }
268            }
269        }
270
271        impl core::fmt::Display for $ty {
272            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
273                match self.name() {
274                    Some(name) => f.write_str(name),
275                    None => write!(f, "{}", self.0),
276                }
277            }
278        }
279    };
280}
281
282profile_enum! {
283    /// What a file holds, the FIT profile's `file` type.
284    FileType {
285        ACTIVITY = 4, "activity";
286    }
287}
288
289profile_enum! {
290    /// A sport, the FIT profile's `sport` type.
291    Sport {
292        GENERIC = 0, "generic";
293        RUNNING = 1, "running";
294        CYCLING = 2, "cycling";
295        TRANSITION = 3, "transition";
296        FITNESS_EQUIPMENT = 4, "fitness_equipment";
297        SWIMMING = 5, "swimming";
298        TRAINING = 10, "training";
299        WALKING = 11, "walking";
300        ROWING = 15, "rowing";
301        HIKING = 17, "hiking";
302        HIIT = 62, "hiit";
303    }
304}
305
306profile_enum! {
307    /// A sport's variant, the FIT profile's `sub_sport` type.
308    SubSport {
309        GENERIC = 0, "generic";
310        TREADMILL = 1, "treadmill";
311        STREET = 2, "street";
312        TRAIL = 3, "trail";
313        TRACK = 4, "track";
314        SPIN = 5, "spin";
315        INDOOR_CYCLING = 6, "indoor_cycling";
316        ROAD = 7, "road";
317        MOUNTAIN = 8, "mountain";
318        INDOOR_ROWING = 14, "indoor_rowing";
319        ELLIPTICAL = 15, "elliptical";
320        STAIR_CLIMBING = 16, "stair_climbing";
321        LAP_SWIMMING = 17, "lap_swimming";
322        OPEN_WATER = 18, "open_water";
323        STRENGTH_TRAINING = 20, "strength_training";
324        CARDIO_TRAINING = 26, "cardio_training";
325        INDOOR_WALKING = 27, "indoor_walking";
326        BIKE_TO_RUN_TRANSITION = 32, "bike_to_run_transition";
327        RUN_TO_BIKE_TRANSITION = 33, "run_to_bike_transition";
328        SWIM_TO_BIKE_TRANSITION = 34, "swim_to_bike_transition";
329        INDOOR_RUNNING = 45, "indoor_running";
330    }
331}
332
333profile_enum! {
334    /// A swimming stroke, the FIT profile's `swim_stroke` type.
335    SwimStroke {
336        FREESTYLE = 0, "freestyle";
337        BACKSTROKE = 1, "backstroke";
338        BREASTSTROKE = 2, "breaststroke";
339        BUTTERFLY = 3, "butterfly";
340        DRILL = 4, "drill";
341        MIXED = 5, "mixed";
342        IM = 6, "im";
343    }
344}
345
346profile_enum! {
347    /// A strength exercise's category, the FIT profile's `exercise_category` type. Each has
348    /// its own list of exercise names, `bench_press_exercise_name` and so on.
349    ExerciseCategory(u16) {
350        BENCH_PRESS = 0, "bench_press";
351        CALF_RAISE = 1, "calf_raise";
352        CARDIO = 2, "cardio";
353        CARRY = 3, "carry";
354        CHOP = 4, "chop";
355        CORE = 5, "core";
356        CRUNCH = 6, "crunch";
357        CURL = 7, "curl";
358        DEADLIFT = 8, "deadlift";
359        FLYE = 9, "flye";
360        HIP_RAISE = 10, "hip_raise";
361        HIP_STABILITY = 11, "hip_stability";
362        HIP_SWING = 12, "hip_swing";
363        HYPEREXTENSION = 13, "hyperextension";
364        LATERAL_RAISE = 14, "lateral_raise";
365        LEG_CURL = 15, "leg_curl";
366        LEG_RAISE = 16, "leg_raise";
367        LUNGE = 17, "lunge";
368        OLYMPIC_LIFT = 18, "olympic_lift";
369        PLANK = 19, "plank";
370        PLYO = 20, "plyo";
371        PULL_UP = 21, "pull_up";
372        PUSH_UP = 22, "push_up";
373        ROW = 23, "row";
374        SHOULDER_PRESS = 24, "shoulder_press";
375        SHOULDER_STABILITY = 25, "shoulder_stability";
376        SHRUG = 26, "shrug";
377        SIT_UP = 27, "sit_up";
378        SQUAT = 28, "squat";
379        TOTAL_BODY = 29, "total_body";
380        TRICEPS_EXTENSION = 30, "triceps_extension";
381        WARM_UP = 31, "warm_up";
382        RUN = 32, "run";
383        BIKE = 33, "bike";
384        CARDIO_SENSORS = 34, "cardio_sensors";
385        MOVE = 35, "move";
386        POSE = 36, "pose";
387        BANDED_EXERCISES = 37, "banded_exercises";
388        BATTLE_ROPE = 38, "battle_rope";
389        ELLIPTICAL = 39, "elliptical";
390        FLOOR_CLIMB = 40, "floor_climb";
391        INDOOR_BIKE = 41, "indoor_bike";
392        INDOOR_ROW = 42, "indoor_row";
393        LADDER = 43, "ladder";
394        SANDBAG = 44, "sandbag";
395        SLED = 45, "sled";
396        SLEDGE_HAMMER = 46, "sledge_hammer";
397        STAIR_STEPPER = 47, "stair_stepper";
398        SUSPENSION = 49, "suspension";
399        TIRE = 50, "tire";
400        RUN_INDOOR = 52, "run_indoor";
401        BIKE_OUTDOOR = 53, "bike_outdoor";
402        UNKNOWN = 65534, "unknown";
403    }
404}
405
406#[cfg(test)]
407mod tests {
408    use super::*;
409    use std::string::ToString;
410
411    #[test]
412    fn unix_and_fit_epochs() {
413        let first = FIT_EPOCH_UNIX + 0x1000_0000;
414        assert_eq!(first, 899_501_056, "1998-07-03T21:24:16Z");
415        assert_eq!(Timestamp::from_unix(first), Some(Timestamp::FIRST_DATE));
416        assert_eq!(Timestamp::from_unix(first - 1), None, "a time since the device started");
417        assert_eq!(Timestamp::from_unix(FIT_EPOCH_UNIX), None);
418        assert_eq!(Timestamp::from_unix(FIT_EPOCH_UNIX - 1), None);
419        assert_eq!(Timestamp::from_unix(i64::MIN), None);
420        let last = FIT_EPOCH_UNIX + i64::from(u32::MAX - 1);
421        assert_eq!(Timestamp::from_unix(last), Some(Timestamp::from_fit(u32::MAX - 1)));
422        assert_eq!(Timestamp::from_unix(last + 1), None);
423        assert_eq!(Timestamp::from_fit(u32::MAX).unix(), last + 1);
424        assert_eq!(Timestamp::from_fit(7).fit(), 7);
425    }
426
427    #[test]
428    fn system_times() {
429        use std::time::{Duration, UNIX_EPOCH};
430        let t = UNIX_EPOCH + Duration::from_millis(1_764_547_200_999);
431        assert_eq!(Timestamp::from_system_time(t), Timestamp::from_unix(1_764_547_200));
432        assert_eq!(Timestamp::from_system_time(UNIX_EPOCH), None);
433        let first = UNIX_EPOCH + Duration::from_secs(899_501_056);
434        assert_eq!(Timestamp::from_system_time(first), Some(Timestamp::FIRST_DATE));
435        assert_eq!(Timestamp::from_system_time(first - Duration::from_millis(1)), None);
436        assert_eq!(Timestamp::from_system_time(UNIX_EPOCH - Duration::from_secs(1)), None);
437    }
438
439    #[test]
440    fn checked_add_stops_at_the_end() {
441        assert_eq!(Timestamp::from_fit(1).checked_add(2), Some(Timestamp::from_fit(3)));
442        assert_eq!(Timestamp::from_fit(u32::MAX).checked_add(1), None);
443        assert_eq!(Timestamp::from_fit(u32::MAX - 1).checked_add(1), None);
444        assert_eq!(
445            Timestamp::from_fit(u32::MAX - 2).checked_add(1),
446            Some(Timestamp::from_fit(u32::MAX - 1))
447        );
448    }
449
450    #[test]
451    fn positions() {
452        let p = Position::from_degrees(45.0, -75.5).unwrap();
453        assert_eq!(p.semicircles(), (536_870_912, -900_750_086));
454        let (lat, long) = p.degrees();
455        assert!((lat - 45.0).abs() < 1e-7 && (long + 75.5).abs() < 1e-7);
456        assert_eq!(Position::from_degrees(90.0, 0.0).unwrap().semicircles(), (1 << 30, 0));
457        assert_eq!(
458            Position::from_degrees(-90.0, 180.0).unwrap().semicircles(),
459            (-(1 << 30), i32::MIN)
460        );
461        let east = |long| Position::from_degrees(0.0, long).map(|p| p.semicircles().1);
462        assert_eq!(east(179.999_999_85), Some(i32::MAX - 1));
463        assert_eq!(east(179.999_999_9), Some(i32::MIN));
464        assert_eq!(east(179.999_999_99), Some(i32::MIN));
465        assert_eq!(Position::from_degrees(90.1, 0.0), None);
466        assert_eq!(Position::from_degrees(0.0, -180.1), None);
467        assert_eq!(Position::from_degrees(0.0, 200.0), None);
468        assert_eq!(Position::from_degrees(-91.0, 0.0), None);
469        assert_eq!(Position::from_degrees(f64::NAN, 0.0), None);
470        assert_eq!(Position::from_degrees(0.0, f64::INFINITY), None);
471        assert_eq!(Position::from_semicircles(i32::MAX, 0), None);
472        assert_eq!(Position::from_semicircles(0, i32::MAX), None);
473        assert_eq!(Position::from_semicircles((1 << 30) + 1, 0), None);
474        assert_eq!(Position::from_semicircles(-(1 << 30) - 1, 0), None);
475        assert!(Position::from_semicircles(-(1 << 30), i32::MAX - 1).is_some());
476        assert_eq!(round(-0.5), Some(-1));
477        assert_eq!(round(0.49), Some(0));
478        assert_eq!(round(2_147_483_647.4), Some(i32::MAX));
479        assert_eq!(round(2_147_483_647.5), None);
480        assert_eq!(round(-2_147_483_648.4), Some(i32::MIN));
481        assert_eq!(round(-2_147_483_648.5), None);
482        assert_eq!(round(f64::NAN), None);
483        assert_eq!(round(0.499_999_999_999_999_94), Some(0));
484        assert_eq!(round(-0.499_999_999_999_999_94), Some(0));
485    }
486
487    #[test]
488    fn halves_go_up_once() {
489        assert_eq!(half_up(0.499_999_999_999_999_94), Some(0));
490        assert_eq!(half_up(0.5), Some(1));
491        assert_eq!(half_up(2.5), Some(3));
492        assert_eq!(half_up(4_503_599_627_370_497.0), Some(4_503_599_627_370_497));
493        assert_eq!(half_up(-0.5), Some(0));
494        assert_eq!(half_up(-0.500_000_000_000_000_1), None);
495        assert_eq!(half_up(f64::NAN), None);
496        assert_eq!(half_up(f64::INFINITY), Some(u64::MAX));
497    }
498
499    #[test]
500    fn base_type_sizes() {
501        let sizes = [
502            (BaseType::ENUM, 1),
503            (BaseType::SINT8, 1),
504            (BaseType::UINT8, 1),
505            (BaseType::STRING, 1),
506            (BaseType::UINT8Z, 1),
507            (BaseType::BYTE, 1),
508            (BaseType::SINT16, 2),
509            (BaseType::UINT16, 2),
510            (BaseType::SINT32, 4),
511            (BaseType::UINT32, 4),
512            (BaseType::FLOAT32, 4),
513            (BaseType::FLOAT64, 8),
514            (BaseType::UINT16Z, 2),
515            (BaseType::UINT32Z, 4),
516            (BaseType::SINT64, 8),
517            (BaseType::UINT64, 8),
518            (BaseType::UINT64Z, 8),
519        ];
520        for (base, size) in sizes {
521            assert_eq!(base.size(), size, "{:#x}", base.get());
522            assert_eq!(BaseType::from_byte(base.get()), base);
523        }
524    }
525
526    #[test]
527    fn identities() {
528        assert_eq!(Manufacturer::DEVELOPMENT.get(), 255);
529        assert_eq!(Manufacturer::new(1).get(), 1);
530        assert_eq!(FileType::ACTIVITY.get(), 4);
531        assert_eq!(FileType::new(9).get(), 9);
532        assert_eq!(Sport::new(1), Sport::RUNNING);
533        assert_eq!(SubSport::new(58).get(), 58);
534        assert_eq!((Sport::RUNNING.name(), Sport::new(30).name()), (Some("running"), None));
535        assert_eq!([Sport::CYCLING.to_string(), SubSport::new(58).to_string()], ["cycling", "58"]);
536    }
537}