fit-encoder 0.1.1

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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! Values that FIT messages carry: times, sports and identities.

/// Seconds from the Unix epoch to the FIT epoch, 1989-12-31T00:00:00Z
/// (<https://developer.garmin.com/fit/cookbook/datetime/>).
pub const FIT_EPOCH_UNIX: i64 = 631_065_600;

/// A FIT `date_time`: whole seconds since 1989-12-31T00:00:00Z.
///
/// ```
/// use fit_encoder::Timestamp;
///
/// let t = Timestamp::from_unix(1_764_547_200).unwrap(); // 2025-12-01T00:00:00Z
/// assert_eq!(t.fit(), 1_133_481_600);
/// assert_eq!(t.unix(), 1_764_547_200);
/// assert_eq!(Timestamp::from_unix(0), None);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Timestamp(u32);

impl Timestamp {
    /// The first FIT second read as a date; readers take any earlier one as seconds since the
    /// device started (Garmin, "Working with Date Time Values").
    pub const FIRST_DATE: Self = Self(0x1000_0000);

    /// A time as FIT seconds: a date from [`Timestamp::FIRST_DATE`], or seconds since the
    /// device started before it. `u32::MAX` is FIT's "none", which writing refuses.
    #[must_use]
    pub const fn from_fit(seconds: u32) -> Self {
        Self(seconds)
    }

    /// A Unix time in seconds, or `None` before [`Timestamp::FIRST_DATE`]
    /// (1998-07-03T21:24:16Z) or from 2126-02-06T06:28:15Z, when FIT seconds reach `u32::MAX`.
    #[must_use]
    pub const fn from_unix(seconds: i64) -> Option<Self> {
        let Some(fit) = seconds.checked_sub(FIT_EPOCH_UNIX) else {
            return None;
        };
        if fit < Self::FIRST_DATE.0 as i64 || fit >= u32::MAX as i64 {
            return None;
        }
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        Some(Self(fit as u32))
    }

    /// A system time, to the second below it, or `None` outside [`Timestamp::from_unix`]'s
    /// range.
    #[cfg(feature = "std")]
    #[must_use]
    pub fn from_system_time(t: std::time::SystemTime) -> Option<Self> {
        let unix = t.duration_since(std::time::UNIX_EPOCH).ok()?.as_secs();
        Self::from_unix(i64::try_from(unix).ok()?)
    }

    /// The time as FIT seconds.
    #[must_use]
    pub const fn fit(self) -> u32 {
        self.0
    }

    /// The time as Unix seconds.
    #[must_use]
    pub const fn unix(self) -> i64 {
        (self.0 as i64).wrapping_add(FIT_EPOCH_UNIX)
    }

    /// The time `seconds` later, or `None` if that reaches `u32::MAX`, the invalid value.
    #[must_use]
    pub const fn checked_add(self, seconds: u32) -> Option<Self> {
        match self.0.checked_add(seconds) {
            Some(t) if t != u32::MAX => Some(Self(t)),
            _ => None,
        }
    }
}

/// A place on Earth as FIT holds it: latitude and longitude in semicircles, 2³¹ to 180°.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Position {
    lat: i32,
    long: i32,
}

const SEMICIRCLES_PER_DEGREE: f64 = 2_147_483_648.0 / 180.0;

impl Position {
    /// Latitude and longitude in degrees, north and east positive, or `None` beyond ±90° and
    /// ±180°. 180° east is 180° west.
    #[must_use]
    pub fn from_degrees(lat: f64, long: f64) -> Option<Self> {
        if !((-90.0..=90.0).contains(&lat) && (-180.0..=180.0).contains(&long)) {
            return None;
        }
        Self::from_semicircles(
            round(lat * SEMICIRCLES_PER_DEGREE)?,
            // 180° and just short of it round to i32::MAX, FIT's none, or past it; all are 180°.
            round(long * SEMICIRCLES_PER_DEGREE).filter(|&l| l != i32::MAX).unwrap_or(i32::MIN),
        )
    }

    /// Latitude and longitude in semicircles, or `None` for `i32::MAX`, FIT's "none", or a
    /// latitude beyond ±90°.
    #[must_use]
    pub const fn from_semicircles(lat: i32, long: i32) -> Option<Self> {
        const QUARTER: i32 = 1 << 30;
        if lat == i32::MAX || long == i32::MAX || lat > QUARTER || lat < -QUARTER {
            return None;
        }
        Some(Self { lat, long })
    }

    /// Latitude and longitude in semicircles.
    #[must_use]
    pub const fn semicircles(self) -> (i32, i32) {
        (self.lat, self.long)
    }

    /// Latitude and longitude in degrees.
    #[must_use]
    pub fn degrees(self) -> (f64, f64) {
        (
            f64::from(self.lat) / SEMICIRCLES_PER_DEGREE,
            f64::from(self.long) / SEMICIRCLES_PER_DEGREE,
        )
    }
}

/// `x` to the nearest whole number, halves away from zero, if it is an `i32`.
fn round(x: f64) -> Option<i32> {
    let r = if x.is_sign_negative() { x - 0.5 } else { x + 0.5 };
    if !(r > -2_147_483_649.0 && r < 2_147_483_648.0) {
        return None;
    }
    #[allow(clippy::cast_possible_truncation)]
    Some(r as i32)
}

/// A manufacturer ID, the FIT profile's `manufacturer` type.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Manufacturer(u16);

impl Manufacturer {
    /// `development` (255), for devices without an assigned ID; any other must be one assigned
    /// to you.
    pub const DEVELOPMENT: Self = Self(255);

    /// Any manufacturer ID.
    #[must_use]
    pub const fn new(id: u16) -> Self {
        Self(id)
    }

    /// The ID.
    #[must_use]
    pub const fn get(self) -> u16 {
        self.0
    }
}

/// A FIT base type, from Table 7 of the FIT Protocol page: how a field's bytes are read.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct BaseType(u8);

impl BaseType {
    /// `enum`, one byte.
    pub const ENUM: Self = Self(0x00);
    /// `sint8`.
    pub const SINT8: Self = Self(0x01);
    /// `uint8`.
    pub const UINT8: Self = Self(0x02);
    /// `string`, UTF-8 ending in a NUL unless it fills its field.
    pub const STRING: Self = Self(0x07);
    /// `uint8z`, whose "none" is 0.
    pub const UINT8Z: Self = Self(0x0A);
    /// `byte`, a byte array whose "none" is all `0xFF`.
    pub const BYTE: Self = Self(0x0D);
    /// `sint16`.
    pub const SINT16: Self = Self(0x83);
    /// `uint16`.
    pub const UINT16: Self = Self(0x84);
    /// `sint32`.
    pub const SINT32: Self = Self(0x85);
    /// `uint32`.
    pub const UINT32: Self = Self(0x86);
    /// `float32`.
    pub const FLOAT32: Self = Self(0x88);
    /// `float64`.
    pub const FLOAT64: Self = Self(0x89);
    /// `uint16z`.
    pub const UINT16Z: Self = Self(0x8B);
    /// `uint32z`.
    pub const UINT32Z: Self = Self(0x8C);
    /// `sint64`.
    pub const SINT64: Self = Self(0x8E);
    /// `uint64`.
    pub const UINT64: Self = Self(0x8F);
    /// `uint64z`.
    pub const UINT64Z: Self = Self(0x90);

    pub(crate) const fn from_byte(base: u8) -> Self {
        Self(base)
    }

    /// The base type field byte.
    #[must_use]
    pub const fn get(self) -> u8 {
        self.0
    }

    /// The bytes one value takes; a field holds one, or an array of them.
    #[must_use]
    pub const fn size(self) -> u8 {
        // The low five bits number the type; the high bit marks those wider than a byte.
        match self.0 & 0x1F {
            0x03 | 0x04 | 0x0B => 2,
            0x05 | 0x06 | 0x08 | 0x0C => 4,
            0x09 | 0x0E | 0x0F | 0x10 => 8,
            _ => 1,
        }
    }
}

/// Defines a FIT enum type as its value, with names for the values this crate knows.
macro_rules! profile_enum {
    ($(#[$doc:meta])* $ty:ident { $($name:ident = $value:literal, $profile:literal;)* }) => {
        profile_enum! { $(#[$doc])* $ty(u8) { $($name = $value, $profile;)* } }
    };
    ($(#[$doc:meta])* $ty:ident($repr:ty) { $($name:ident = $value:literal, $profile:literal;)* }) => {
        $(#[$doc])*
        #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub struct $ty($repr);

        #[allow(dead_code, reason = "FileType is not exported")]
        impl $ty {
            $(
                #[doc = concat!("`", $profile, "` (", stringify!($value), ").")]
                pub const $name: Self = Self($value);
            )*

            #[doc = concat!("Any value. ", stringify!($repr), "::MAX is FIT's \"none\", which the encoder refuses to write.")]
            #[must_use]
            pub const fn new(value: $repr) -> Self {
                Self(value)
            }

            /// The value.
            #[must_use]
            pub const fn get(self) -> $repr {
                self.0
            }

            /// The profile's name for a value this crate names.
            #[must_use]
            pub const fn name(self) -> Option<&'static str> {
                match self.0 {
                    $($value => Some($profile),)*
                    _ => None,
                }
            }
        }

        impl core::fmt::Display for $ty {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                match self.name() {
                    Some(name) => f.write_str(name),
                    None => write!(f, "{}", self.0),
                }
            }
        }
    };
}

profile_enum! {
    /// What a file holds, the FIT profile's `file` type.
    FileType {
        ACTIVITY = 4, "activity";
    }
}

profile_enum! {
    /// A sport, the FIT profile's `sport` type.
    Sport {
        GENERIC = 0, "generic";
        RUNNING = 1, "running";
        CYCLING = 2, "cycling";
        TRANSITION = 3, "transition";
        FITNESS_EQUIPMENT = 4, "fitness_equipment";
        SWIMMING = 5, "swimming";
        TRAINING = 10, "training";
        WALKING = 11, "walking";
        ROWING = 15, "rowing";
        HIKING = 17, "hiking";
        HIIT = 62, "hiit";
    }
}

profile_enum! {
    /// A sport's variant, the FIT profile's `sub_sport` type.
    SubSport {
        GENERIC = 0, "generic";
        TREADMILL = 1, "treadmill";
        STREET = 2, "street";
        TRAIL = 3, "trail";
        TRACK = 4, "track";
        SPIN = 5, "spin";
        INDOOR_CYCLING = 6, "indoor_cycling";
        ROAD = 7, "road";
        MOUNTAIN = 8, "mountain";
        INDOOR_ROWING = 14, "indoor_rowing";
        ELLIPTICAL = 15, "elliptical";
        STAIR_CLIMBING = 16, "stair_climbing";
        LAP_SWIMMING = 17, "lap_swimming";
        OPEN_WATER = 18, "open_water";
        STRENGTH_TRAINING = 20, "strength_training";
        CARDIO_TRAINING = 26, "cardio_training";
        INDOOR_WALKING = 27, "indoor_walking";
        BIKE_TO_RUN_TRANSITION = 32, "bike_to_run_transition";
        RUN_TO_BIKE_TRANSITION = 33, "run_to_bike_transition";
        SWIM_TO_BIKE_TRANSITION = 34, "swim_to_bike_transition";
        INDOOR_RUNNING = 45, "indoor_running";
    }
}

profile_enum! {
    /// A swimming stroke, the FIT profile's `swim_stroke` type.
    SwimStroke {
        FREESTYLE = 0, "freestyle";
        BACKSTROKE = 1, "backstroke";
        BREASTSTROKE = 2, "breaststroke";
        BUTTERFLY = 3, "butterfly";
        DRILL = 4, "drill";
        MIXED = 5, "mixed";
        IM = 6, "im";
    }
}

profile_enum! {
    /// A strength exercise's category, the FIT profile's `exercise_category` type. Each has
    /// its own list of exercise names, `bench_press_exercise_name` and so on.
    ExerciseCategory(u16) {
        BENCH_PRESS = 0, "bench_press";
        CALF_RAISE = 1, "calf_raise";
        CARDIO = 2, "cardio";
        CARRY = 3, "carry";
        CHOP = 4, "chop";
        CORE = 5, "core";
        CRUNCH = 6, "crunch";
        CURL = 7, "curl";
        DEADLIFT = 8, "deadlift";
        FLYE = 9, "flye";
        HIP_RAISE = 10, "hip_raise";
        HIP_STABILITY = 11, "hip_stability";
        HIP_SWING = 12, "hip_swing";
        HYPEREXTENSION = 13, "hyperextension";
        LATERAL_RAISE = 14, "lateral_raise";
        LEG_CURL = 15, "leg_curl";
        LEG_RAISE = 16, "leg_raise";
        LUNGE = 17, "lunge";
        OLYMPIC_LIFT = 18, "olympic_lift";
        PLANK = 19, "plank";
        PLYO = 20, "plyo";
        PULL_UP = 21, "pull_up";
        PUSH_UP = 22, "push_up";
        ROW = 23, "row";
        SHOULDER_PRESS = 24, "shoulder_press";
        SHOULDER_STABILITY = 25, "shoulder_stability";
        SHRUG = 26, "shrug";
        SIT_UP = 27, "sit_up";
        SQUAT = 28, "squat";
        TOTAL_BODY = 29, "total_body";
        TRICEPS_EXTENSION = 30, "triceps_extension";
        WARM_UP = 31, "warm_up";
        RUN = 32, "run";
        BIKE = 33, "bike";
        CARDIO_SENSORS = 34, "cardio_sensors";
        MOVE = 35, "move";
        POSE = 36, "pose";
        BANDED_EXERCISES = 37, "banded_exercises";
        BATTLE_ROPE = 38, "battle_rope";
        ELLIPTICAL = 39, "elliptical";
        FLOOR_CLIMB = 40, "floor_climb";
        INDOOR_BIKE = 41, "indoor_bike";
        INDOOR_ROW = 42, "indoor_row";
        LADDER = 43, "ladder";
        SANDBAG = 44, "sandbag";
        SLED = 45, "sled";
        SLEDGE_HAMMER = 46, "sledge_hammer";
        STAIR_STEPPER = 47, "stair_stepper";
        SUSPENSION = 49, "suspension";
        TIRE = 50, "tire";
        RUN_INDOOR = 52, "run_indoor";
        BIKE_OUTDOOR = 53, "bike_outdoor";
        UNKNOWN = 65534, "unknown";
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::string::ToString;

    #[test]
    fn unix_and_fit_epochs() {
        let first = FIT_EPOCH_UNIX + 0x1000_0000;
        assert_eq!(first, 899_501_056, "1998-07-03T21:24:16Z");
        assert_eq!(Timestamp::from_unix(first), Some(Timestamp::FIRST_DATE));
        assert_eq!(Timestamp::from_unix(first - 1), None, "a time since the device started");
        assert_eq!(Timestamp::from_unix(FIT_EPOCH_UNIX), None);
        assert_eq!(Timestamp::from_unix(FIT_EPOCH_UNIX - 1), None);
        assert_eq!(Timestamp::from_unix(i64::MIN), None);
        let last = FIT_EPOCH_UNIX + i64::from(u32::MAX - 1);
        assert_eq!(Timestamp::from_unix(last), Some(Timestamp::from_fit(u32::MAX - 1)));
        assert_eq!(Timestamp::from_unix(last + 1), None);
        assert_eq!(Timestamp::from_fit(u32::MAX).unix(), last + 1);
        assert_eq!(Timestamp::from_fit(7).fit(), 7);
    }

    #[test]
    fn system_times() {
        use std::time::{Duration, UNIX_EPOCH};
        let t = UNIX_EPOCH + Duration::from_millis(1_764_547_200_999);
        assert_eq!(Timestamp::from_system_time(t), Timestamp::from_unix(1_764_547_200));
        assert_eq!(Timestamp::from_system_time(UNIX_EPOCH), None);
        let first = UNIX_EPOCH + Duration::from_secs(899_501_056);
        assert_eq!(Timestamp::from_system_time(first), Some(Timestamp::FIRST_DATE));
        assert_eq!(Timestamp::from_system_time(first - Duration::from_millis(1)), None);
        assert_eq!(Timestamp::from_system_time(UNIX_EPOCH - Duration::from_secs(1)), None);
    }

    #[test]
    fn checked_add_stops_at_the_end() {
        assert_eq!(Timestamp::from_fit(1).checked_add(2), Some(Timestamp::from_fit(3)));
        assert_eq!(Timestamp::from_fit(u32::MAX).checked_add(1), None);
        assert_eq!(Timestamp::from_fit(u32::MAX - 1).checked_add(1), None);
        assert_eq!(
            Timestamp::from_fit(u32::MAX - 2).checked_add(1),
            Some(Timestamp::from_fit(u32::MAX - 1))
        );
    }

    #[test]
    fn positions() {
        let p = Position::from_degrees(45.0, -75.5).unwrap();
        assert_eq!(p.semicircles(), (536_870_912, -900_750_086));
        let (lat, long) = p.degrees();
        assert!((lat - 45.0).abs() < 1e-7 && (long + 75.5).abs() < 1e-7);
        assert_eq!(Position::from_degrees(90.0, 0.0).unwrap().semicircles(), (1 << 30, 0));
        assert_eq!(
            Position::from_degrees(-90.0, 180.0).unwrap().semicircles(),
            (-(1 << 30), i32::MIN)
        );
        let east = |long| Position::from_degrees(0.0, long).map(|p| p.semicircles().1);
        assert_eq!(east(179.999_999_85), Some(i32::MAX - 1));
        assert_eq!(east(179.999_999_9), Some(i32::MIN));
        assert_eq!(east(179.999_999_99), Some(i32::MIN));
        assert_eq!(Position::from_degrees(90.1, 0.0), None);
        assert_eq!(Position::from_degrees(0.0, -180.1), None);
        assert_eq!(Position::from_degrees(0.0, 200.0), None);
        assert_eq!(Position::from_degrees(-91.0, 0.0), None);
        assert_eq!(Position::from_degrees(f64::NAN, 0.0), None);
        assert_eq!(Position::from_degrees(0.0, f64::INFINITY), None);
        assert_eq!(Position::from_semicircles(i32::MAX, 0), None);
        assert_eq!(Position::from_semicircles(0, i32::MAX), None);
        assert_eq!(Position::from_semicircles((1 << 30) + 1, 0), None);
        assert_eq!(Position::from_semicircles(-(1 << 30) - 1, 0), None);
        assert!(Position::from_semicircles(-(1 << 30), i32::MAX - 1).is_some());
        assert_eq!(round(-0.5), Some(-1));
        assert_eq!(round(0.49), Some(0));
        assert_eq!(round(2_147_483_647.4), Some(i32::MAX));
        assert_eq!(round(2_147_483_647.5), None);
        assert_eq!(round(-2_147_483_648.4), Some(i32::MIN));
        assert_eq!(round(-2_147_483_648.5), None);
        assert_eq!(round(f64::NAN), None);
    }

    #[test]
    fn base_type_sizes() {
        let sizes = [
            (BaseType::ENUM, 1),
            (BaseType::SINT8, 1),
            (BaseType::UINT8, 1),
            (BaseType::STRING, 1),
            (BaseType::UINT8Z, 1),
            (BaseType::BYTE, 1),
            (BaseType::SINT16, 2),
            (BaseType::UINT16, 2),
            (BaseType::SINT32, 4),
            (BaseType::UINT32, 4),
            (BaseType::FLOAT32, 4),
            (BaseType::FLOAT64, 8),
            (BaseType::UINT16Z, 2),
            (BaseType::UINT32Z, 4),
            (BaseType::SINT64, 8),
            (BaseType::UINT64, 8),
            (BaseType::UINT64Z, 8),
        ];
        for (base, size) in sizes {
            assert_eq!(base.size(), size, "{:#x}", base.get());
            assert_eq!(BaseType::from_byte(base.get()), base);
        }
    }

    #[test]
    fn identities() {
        assert_eq!(Manufacturer::DEVELOPMENT.get(), 255);
        assert_eq!(Manufacturer::new(1).get(), 1);
        assert_eq!(FileType::ACTIVITY.get(), 4);
        assert_eq!(FileType::new(9).get(), 9);
        assert_eq!(Sport::new(1), Sport::RUNNING);
        assert_eq!(SubSport::new(58).get(), 58);
        assert_eq!((Sport::RUNNING.name(), Sport::new(30).name()), (Some("running"), None));
        assert_eq!([Sport::CYCLING.to_string(), SubSport::new(58).to_string()], ["cycling", "58"]);
    }
}