rustyfit 0.10.0

The #![no_std] Rust implementation of The Flexible and Interoperable Data Transfer (FIT) Protocol for decoding and encoding Garmin FIT files, supporting FIT Protocol V2.
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
// Code generated by fitgen/main.go. DO NOT EDIT.

// Copyright 2025 The RustyFIT Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

use crate::profile::typedef::{self, FitBaseType};
use crate::proto::*;
use alloc::vec::Vec;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize, Serializer, ser::SerializeStruct};

/// Set message.
#[cfg_attr(feature = "serde", derive(Deserialize), serde(from = "De"))]
#[derive(Debug, Clone)]
pub struct Set {
    /// Timestamp of the set
    pub timestamp: typedef::DateTime,
    /// Scale: 1000; Units: s
    pub duration: u32,
    /// # of repitions of the movement
    pub repetitions: u16,
    /// Scale: 16; Units: kg; Amount of weight applied for the set
    pub weight: u16,
    pub set_type: typedef::SetType,
    /// Start time of the set
    pub start_time: typedef::DateTime,
    pub category: Vec<typedef::ExerciseCategory>,
    /// Based on the associated category, see \[category\]_exercise_names
    pub category_subtype: Vec<u16>,
    pub weight_display_unit: typedef::FitBaseUnit,
    pub message_index: typedef::MessageIndex,
    pub wkt_step_index: typedef::MessageIndex,
    /// unknown_fields are fields that are exist but they are not defined in Profile.xlsx
    pub unknown_fields: Vec<Field>,
    /// developer_fields are custom data fields (Added since protocol version 2.0)
    pub developer_fields: Vec<DeveloperField>,
}

impl Set {
    /// Value's type: `u32`; FitBaseType::UINT32; ProfileType::DateTime
    pub const TIMESTAMP: u8 = 254;
    /// Value's type: `u32`; FitBaseType::UINT32; ProfileType::Uint32; Scale: `1000`; Units: `s`
    pub const DURATION: u8 = 0;
    /// Value's type: `u16`; FitBaseType::UINT16; ProfileType::Uint16
    pub const REPETITIONS: u8 = 3;
    /// Value's type: `u16`; FitBaseType::UINT16; ProfileType::Uint16; Scale: `16`; Units: `kg`
    pub const WEIGHT: u8 = 4;
    /// Value's type: `u8`; FitBaseType::UINT8; ProfileType::SetType
    pub const SET_TYPE: u8 = 5;
    /// Value's type: `u32`; FitBaseType::UINT32; ProfileType::DateTime
    pub const START_TIME: u8 = 6;
    /// Value's type: `Vec<u16>`; FitBaseType::UINT16; ProfileType::ExerciseCategory
    pub const CATEGORY: u8 = 7;
    /// Value's type: `Vec<u16>`; FitBaseType::UINT16; ProfileType::Uint16
    pub const CATEGORY_SUBTYPE: u8 = 8;
    /// Value's type: `u16`; FitBaseType::UINT16; ProfileType::FitBaseUnit
    pub const WEIGHT_DISPLAY_UNIT: u8 = 9;
    /// Value's type: `u16`; FitBaseType::UINT16; ProfileType::MessageIndex
    pub const MESSAGE_INDEX: u8 = 10;
    /// Value's type: `u16`; FitBaseType::UINT16; ProfileType::MessageIndex
    pub const WKT_STEP_INDEX: u8 = 11;

    /// Create new Set with all fields being set to its corresponding invalid value.
    pub const fn new() -> Self {
        Self {
            timestamp: typedef::DateTime(u32::MAX),
            duration: u32::MAX,
            repetitions: u16::MAX,
            weight: u16::MAX,
            set_type: typedef::SetType(u8::MAX),
            start_time: typedef::DateTime(u32::MAX),
            category: Vec::new(),
            category_subtype: Vec::new(),
            weight_display_unit: typedef::FitBaseUnit(u16::MAX),
            message_index: typedef::MessageIndex(u16::MAX),
            wkt_step_index: typedef::MessageIndex(u16::MAX),
            unknown_fields: Vec::new(),
            developer_fields: Vec::new(),
        }
    }

    /// Returns `duration` in its scaled value. It returns `None` when value is invalid.
    ///
    /// Units: s
    pub fn duration_scaled(&self) -> Option<f64> {
        if self.duration == u32::MAX {
            return None;
        }
        Some(self.duration as f64 / 1000.0 - 0.0)
    }

    /// Set `duration` with scaled value, it will automatically be converted to its corresponding integer value.
    pub fn set_duration_scaled(&mut self, v: f64) -> &mut Self {
        let unscaled = (v + 0.0) * 1000.0;
        if unscaled.is_nan() || unscaled.is_infinite() || unscaled > u32::MAX as f64 {
            self.duration = u32::MAX;
            return self;
        }
        self.duration = unscaled as u32;
        self
    }

    /// Returns `weight` in its scaled value. It returns `None` when value is invalid.
    ///
    /// Units: kg
    pub fn weight_scaled(&self) -> Option<f64> {
        if self.weight == u16::MAX {
            return None;
        }
        Some(self.weight as f64 / 16.0 - 0.0)
    }

    /// Set `weight` with scaled value, it will automatically be converted to its corresponding integer value.
    pub fn set_weight_scaled(&mut self, v: f64) -> &mut Self {
        let unscaled = (v + 0.0) * 16.0;
        if unscaled.is_nan() || unscaled.is_infinite() || unscaled > u16::MAX as f64 {
            self.weight = u16::MAX;
            return self;
        }
        self.weight = unscaled as u16;
        self
    }

    fn count_valid_fields(&self) -> usize {
        (self.timestamp.0 != u32::MAX) as usize
            + (self.duration != u32::MAX) as usize
            + (self.repetitions != u16::MAX) as usize
            + (self.weight != u16::MAX) as usize
            + (self.set_type.0 != u8::MAX) as usize
            + (self.start_time.0 != u32::MAX) as usize
            + (!self.category.is_empty()) as usize
            + (!self.category_subtype.is_empty()) as usize
            + (self.weight_display_unit.0 != u16::MAX) as usize
            + (self.message_index.0 != u16::MAX) as usize
            + (self.wkt_step_index.0 != u16::MAX) as usize
    }
}

impl Default for Set {
    fn default() -> Self {
        Self::new()
    }
}

impl From<&Message> for Set {
    /// from creates new Set struct based on given mesg.
    fn from(mesg: &Message) -> Self {
        const KNOWN_NUMS: [u64; 4] = [4089, 0, 0, 4611686018427387904];
        let mut n = 0u64;
        for field in &mesg.fields {
            n += (KNOWN_NUMS[field.num as usize >> 6] >> (field.num & 63)) & 1 ^ 1
        }

        let mut v = Self::new();
        v.unknown_fields = Vec::<Field>::with_capacity(n as usize);
        v.developer_fields = mesg.developer_fields.clone();

        for field in &mesg.fields {
            match field.num {
                254 => v.timestamp = typedef::DateTime(field.value.as_u32()),
                0 => v.duration = field.value.as_u32(),
                3 => v.repetitions = field.value.as_u16(),
                4 => v.weight = field.value.as_u16(),
                5 => v.set_type = typedef::SetType(field.value.as_u8()),
                6 => v.start_time = typedef::DateTime(field.value.as_u32()),
                7 => {
                    v.category = match &field.value {
                        Value::VecUint16(v) => {
                            let mut vs = Vec::with_capacity(v.len());
                            vs.extend(v.iter().map(|&x| typedef::ExerciseCategory(x)));
                            vs
                        }
                        _ => Vec::new(),
                    }
                }
                8 => v.category_subtype = field.value.to_vec_u16(),
                9 => v.weight_display_unit = typedef::FitBaseUnit(field.value.as_u16()),
                10 => v.message_index = typedef::MessageIndex(field.value.as_u16()),
                11 => v.wkt_step_index = typedef::MessageIndex(field.value.as_u16()),
                _ => v.unknown_fields.push(field.clone()),
            };
        }

        v
    }
}

impl From<Set> for Message {
    fn from(m: Set) -> Self {
        let mut fields =
            Vec::<Field>::with_capacity(m.count_valid_fields() + m.unknown_fields.len());

        if m.timestamp.0 != u32::MAX {
            fields.push(Field {
                num: 254,
                base_type: FitBaseType::UINT32,
                value: Value::Uint32(m.timestamp.0),
                is_expanded: false,
            });
        };
        if m.duration != u32::MAX {
            fields.push(Field {
                num: 0,
                base_type: FitBaseType::UINT32,
                value: Value::Uint32(m.duration),
                is_expanded: false,
            });
        };
        if m.repetitions != u16::MAX {
            fields.push(Field {
                num: 3,
                base_type: FitBaseType::UINT16,
                value: Value::Uint16(m.repetitions),
                is_expanded: false,
            });
        };
        if m.weight != u16::MAX {
            fields.push(Field {
                num: 4,
                base_type: FitBaseType::UINT16,
                value: Value::Uint16(m.weight),
                is_expanded: false,
            });
        };
        if m.set_type.0 != u8::MAX {
            fields.push(Field {
                num: 5,
                base_type: FitBaseType::UINT8,
                value: Value::Uint8(m.set_type.0),
                is_expanded: false,
            });
        };
        if m.start_time.0 != u32::MAX {
            fields.push(Field {
                num: 6,
                base_type: FitBaseType::UINT32,
                value: Value::Uint32(m.start_time.0),
                is_expanded: false,
            });
        };
        if !m.category.is_empty() {
            fields.push(Field {
                num: 7,
                base_type: FitBaseType::UINT16,
                value: Value::VecUint16({
                    let (ptr, len, capacity) = m.category.into_raw_parts();
                    unsafe { Vec::from_raw_parts(ptr.cast::<u16>(), len, capacity) }
                }),
                is_expanded: false,
            });
        };
        if !m.category_subtype.is_empty() {
            fields.push(Field {
                num: 8,
                base_type: FitBaseType::UINT16,
                value: Value::VecUint16(m.category_subtype),
                is_expanded: false,
            });
        };
        if m.weight_display_unit.0 != u16::MAX {
            fields.push(Field {
                num: 9,
                base_type: FitBaseType::UINT16,
                value: Value::Uint16(m.weight_display_unit.0),
                is_expanded: false,
            });
        };
        if m.message_index.0 != u16::MAX {
            fields.push(Field {
                num: 10,
                base_type: FitBaseType::UINT16,
                value: Value::Uint16(m.message_index.0),
                is_expanded: false,
            });
        };
        if m.wkt_step_index.0 != u16::MAX {
            fields.push(Field {
                num: 11,
                base_type: FitBaseType::UINT16,
                value: Value::Uint16(m.wkt_step_index.0),
                is_expanded: false,
            });
        };

        fields.extend_from_slice(&m.unknown_fields);

        Self {
            header: 0,
            num: typedef::MesgNum::SET,
            fields,
            developer_fields: m.developer_fields,
        }
    }
}

#[cfg(feature = "serde")]
impl Serialize for Set {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let n = self.count_valid_fields() + 2;
        let mut state = serializer.serialize_struct("Set", n)?;
        if let Some(v) = self.timestamp.unix_timestamp() {
            state.serialize_field("timestamp", &v)?;
        }
        if let Some(v) = self.duration_scaled() {
            state.serialize_field("duration", &v)?;
        }
        if self.repetitions != u16::MAX {
            state.serialize_field("repetitions", &self.repetitions)?;
        }
        if let Some(v) = self.weight_scaled() {
            state.serialize_field("weight", &v)?;
        }
        if self.set_type.0 != u8::MAX {
            state.serialize_field("set_type", &self.set_type)?;
        }
        if let Some(v) = self.start_time.unix_timestamp() {
            state.serialize_field("start_time", &v)?;
        }
        if !self.category.is_empty() {
            state.serialize_field("category", &self.category)?;
        }
        if !self.category_subtype.is_empty() {
            state.serialize_field("category_subtype", &self.category_subtype)?;
        }
        if self.weight_display_unit.0 != u16::MAX {
            state.serialize_field("weight_display_unit", &self.weight_display_unit)?;
        }
        if self.message_index.0 != u16::MAX {
            state.serialize_field("message_index", &self.message_index)?;
        }
        if self.wkt_step_index.0 != u16::MAX {
            state.serialize_field("wkt_step_index", &self.wkt_step_index)?;
        }
        if !self.unknown_fields.is_empty() {
            state.serialize_field("unknown_fields", &self.unknown_fields)?;
        }
        if !self.developer_fields.is_empty() {
            state.serialize_field("developer_fields", &self.developer_fields)?;
        }
        state.end()
    }
}

#[cfg(feature = "serde")]
#[cfg_attr(feature = "serde", derive(Deserialize), serde(default))]
struct De {
    timestamp: Option<i64>,
    duration: f64,
    repetitions: u16,
    weight: f64,
    set_type: typedef::SetType,
    start_time: Option<i64>,
    category: Vec<typedef::ExerciseCategory>,
    category_subtype: Vec<u16>,
    weight_display_unit: typedef::FitBaseUnit,
    message_index: typedef::MessageIndex,
    wkt_step_index: typedef::MessageIndex,
    unknown_fields: Vec<Field>,
    developer_fields: Vec<DeveloperField>,
}

#[cfg(feature = "serde")]
impl From<De> for Set {
    fn from(m: De) -> Self {
        Self {
            timestamp: m.timestamp.map_or_else(
                || typedef::DateTime(u32::MAX),
                typedef::DateTime::from_unix_timestamp,
            ),
            duration: {
                let unscaled = (m.duration + 0.0) * 1000.0;
                if unscaled.is_nan() || unscaled.is_infinite() || unscaled > u32::MAX as f64 {
                    u32::MAX
                } else {
                    unscaled as u32
                }
            },
            repetitions: m.repetitions,
            weight: {
                let unscaled = (m.weight + 0.0) * 16.0;
                if unscaled.is_nan() || unscaled.is_infinite() || unscaled > u16::MAX as f64 {
                    u16::MAX
                } else {
                    unscaled as u16
                }
            },
            set_type: m.set_type,
            start_time: m.start_time.map_or_else(
                || typedef::DateTime(u32::MAX),
                typedef::DateTime::from_unix_timestamp,
            ),
            category: m.category,
            category_subtype: m.category_subtype,
            weight_display_unit: m.weight_display_unit,
            message_index: m.message_index,
            wkt_step_index: m.wkt_step_index,
            unknown_fields: m.unknown_fields,
            developer_fields: m.developer_fields,
        }
    }
}

#[cfg(feature = "serde")]
impl Default for De {
    fn default() -> Self {
        Self {
            timestamp: None,
            duration: f64::from_bits(u64::MAX),
            repetitions: u16::MAX,
            weight: f64::from_bits(u64::MAX),
            set_type: typedef::SetType(u8::MAX),
            start_time: None,
            category: Vec::new(),
            category_subtype: Vec::new(),
            weight_display_unit: typedef::FitBaseUnit(u16::MAX),
            message_index: typedef::MessageIndex(u16::MAX),
            wkt_step_index: typedef::MessageIndex(u16::MAX),
            unknown_fields: Vec::new(),
            developer_fields: Vec::new(),
        }
    }
}