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