rustyfit 0.4.1

This project hosts the Rust implementation for The Flexible and Interoperable Data Transfer (FIT) Protocol
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
#![warn(missing_docs)]

use std::{error, fmt};

use crate::profile::{
    ProfileType,
    typedef::{FitBaseType, MesgNum},
};

/// Mask for determining if the message type is a message definition.
pub(crate) const MESG_DEFINITION_MASK: u8 = 0b01000000;

/// Mask for determining if the message type is a normal message data .
pub(crate) const MESG_NORMAL_HEADER_MASK: u8 = 0b00000000;

/// Mask for determining if the message type is a compressed timestamp message data.
pub(crate) const MESG_COMPRESSED_HEADER_MASK: u8 = 0b10000000;

/// Mask for determining if the message's header is a message definition or is it
/// actually a message data with compressed timestamp and multiple local message type.
///
/// For compressed timestamp, message data's header bit 5-6 is the local message type.
/// Bit 6 overlap with MESG_DEFINITION_MASK, it's a message definition only if Bit 7 is zero.
pub(crate) const MESG_HEADER_MASK: u8 = MESG_COMPRESSED_HEADER_MASK | MESG_DEFINITION_MASK;

/// Mask for mapping normal message data to the message definition.
pub(crate) const LOCAL_MESG_NUM_MASK: u8 = 0b00001111;

/// Mask for mapping compressed timestamp message data to the message definition. Used with CompressedBitShift.
pub(crate) const COMPRESSED_LOCAL_MESG_NUM_MASK: u8 = 0b01100000;

/// Mask for measuring time offset value from header. Compressed timestamp is using 5 least significant bits (lsb) of header
pub(crate) const COMPRESSED_TIME_MASK: u8 = 0b00011111;

/// Mask for determining if a message contains developer fields.
pub(crate) const DEV_DATA_MASK: u8 = 0b00100000;

/// Used for right-shifting the 5 least significant bits (lsb) of compressed time.
pub(crate) const COMPRESSED_BIT_SHIFT: u8 = 5;

/// Field's number for timestamp across all defined messages in the profile.
/// Exception: Course Point and Set message.
pub(crate) const FIELD_NUM_TIMESTAMP: u8 = 253;

/// FileHeader's data_type.
pub(crate) static DATA_TYPE: &str = ".FIT";

/// Defined errors returned from proto module.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Error {
    /// Protocol Validator's error when Protocol Version 1.0 constains developer data.
    ProtocolViolationDeveloperData,
    /// Protocol Validator's error when Protocol Version 1.0 has base_type number more than byte number.
    ProtocolViolationUnsupportedBaseType(FitBaseType),
    /// Marshal error when Value is invalid.
    InvalidValue,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {
            Error::ProtocolViolationDeveloperData => {
                write!(f, "protocol version 1.0 do not support developer data")
            }
            Error::ProtocolViolationUnsupportedBaseType(base_type) => {
                write!(f, "protocol version 1.0 do not support type {}", base_type)
            }
            Error::InvalidValue => write!(f, "invalid proto::Value"),
        }
    }
}

impl error::Error for Error {}

/// FIT is FIT protocol data representative.
#[derive(Default, Debug)]
pub struct FIT {
    /// File Header contains either 12 or 14 bytes
    pub file_header: FileHeader,
    /// Messages
    pub messages: Vec<Message>,
    /// Cyclic Redundancy Check 16-bit value to ensure the integrity of the messages.
    pub crc: u16,
}

/// FileHeader is a FIT's FileHeader with either 12 bytes size without CRC or a 14 bytes size with CRC,
/// while 14 bytes size is the preferred size.
#[derive(Debug, Default, Clone, Copy)]
pub struct FileHeader {
    /// File header size either 12 (legacy) or 14.
    pub size: u8,
    /// The FIT Protocol version which is being used to encode the FIT file.
    pub protocol_version: ProtocolVersion,
    /// The FIT Profile Version (associated with data defined in Global FIT Profile).
    pub profile_version: u16,
    /// The size of the messages in bytes (this field will be automatically updated by the encoder)
    pub data_size: u32,
    /// ".FIT" (an immutable string constant)
    pub data_type: &'static str,
    /// Cyclic Redundancy Check 16-bit value to ensure the integrity of the file header.
    /// (this field will be automatically updated by the encoder)
    pub crc: u16,
}

impl FileHeader {
    pub(crate) fn marshal_append(&self, vec: &mut Vec<u8>) {
        vec.push(self.size);
        vec.push(self.protocol_version.0);
        vec.extend_from_slice(&self.profile_version.to_le_bytes());
        vec.extend_from_slice(&self.data_size.to_le_bytes());
        vec.extend_from_slice(DATA_TYPE.as_bytes());
        if self.size >= 14 {
            vec.extend_from_slice(&self.crc.to_le_bytes());
        }
    }
}

/// MessageDefinition is the definition of the upcoming data messages.
#[derive(Debug, Default, Clone)]
pub struct MessageDefinition {
    /// The message definition header with mask 0b01000000.
    pub header: u8,
    /// Currently undetermined; the default value is 0.
    pub reserved: u8,
    /// The Byte Order to be used to decode the values of both this message definition and the upcoming message. (0: Little-Endian, 1: Big-Endian)
    pub arch: u8,
    /// Global Message Number defined by factory (retrieved from Profile.xslx). (endianness of this 2 Byte value is defined in the Architecture byte)
    pub mesg_num: MesgNum,
    /// List of the field definition
    pub field_definitions: Vec<FieldDefinition>,
    /// List of the developer field definition (only if Developer Data Flag is set in Header)
    pub developer_field_definitions: Vec<DeveloperFieldDefinition>,
}

/// FieldDefinition is the definition of the upcoming field within the message's structure.
#[derive(Debug, Default, Clone, Copy)]
pub struct FieldDefinition {
    /// The field definition number
    pub num: u8,
    /// The size of the upcoming value
    pub size: u8,
    /// The type of the upcoming value to be represented
    pub base_type: FitBaseType,
}

/// FieldDefinition is the definition of the upcoming developer field within the message's structure.
#[derive(Debug, Default, Clone, Copy)]
pub struct DeveloperFieldDefinition {
    /// Maps to `field_definition_number` of a `field_description` message.
    pub num: u8,
    /// Size (in bytes) of the specified FIT message’s field
    pub size: u8,
    /// Maps to `developer_data_index` of a `developer_data_id` and a `field_description` messages.
    pub developer_data_index: u8,
}

/// Message is a FIT protocol message containing the data defined in the Message Definition
#[derive(Default, Debug, Clone, PartialEq)]
pub struct Message {
    /// Message Header serves to distinguish whether the message is a Normal Data or a Compressed Timestamp Data.
    /// Unlike MessageDefinition, Message's Header should not contain Developer Data Flag.
    pub header: u8,
    /// Global Message Number defined in Global FIT Profile, except number within range 0xFF00 - 0xFFFE are manufacturer specific number.
    pub num: MesgNum,
    /// List of Field
    pub fields: Vec<Field>,
    /// List of DeveloperField
    pub developer_fields: Vec<DeveloperField>,
}

impl Message {
    /// SubFieldSubstitution returns any sub-field that can substitute
    /// the properties interpretation of the parent Field (Dynamic Field).
    pub fn sub_field_substitution<'a>(
        &self,
        field_ref: &FieldReference<'a>,
    ) -> Option<&'a SubField<'a>> {
        for sub_field in field_ref.sub_fields {
            for sub_field_map in sub_field.maps {
                for field in &self.fields {
                    if field.num != sub_field_map.ref_field_num {
                        continue;
                    }
                    if field.value.cast_i64() == sub_field_map.ref_field_value {
                        return Some(sub_field);
                    }
                }
            }
        }
        None
    }

    pub(crate) fn marshal_append(&self, vec: &mut Vec<u8>, arch: u8) -> Result<(), Error> {
        vec.push(self.header);
        for field in &self.fields {
            field.value.marshal_append(vec, arch)?;
        }
        for dev_field in &self.developer_fields {
            dev_field.value.marshal_append(vec, arch)?;
        }
        Ok(())
    }
}

/// Field represents the full representation of a field, as specified in the Global FIT Profile.
#[derive(Default, Debug, Clone, PartialEq)]
pub struct Field {
    /// Defined in the Global FIT profile for the specified FIT message, otherwise
    /// its a manufaturer specific number (defined by manufacturer). (255 == invalid)
    pub num: u8,
    /// BaseType is the base of the ProfileType. E.g. ProfileType::DateTime -> FitBaseType::Uint32.
    pub profile_type: ProfileType,
    /// Value
    pub value: Value,
    /// A flag to detect whether this field is generated through component expansion.
    pub is_expanded: bool,
}

/// FieldReference acts as a representation of a field as defined in the Global FIT Profile.
#[derive(Debug, Clone, Copy)]
pub struct FieldReference<'a> {
    /// Defined in the Global FIT profile for the specified FIT message, otherwise
    /// its a manufaturer specific number (defined by manufacturer). (255 == invalid)
    pub num: u8,
    /// Defined in the Global FIT profile for the specified FIT message, otherwise
    /// its a manufaturer specific name (defined by manufacturer).
    pub name: &'a str,
    /// Type is defined type that serves as an abstraction layer above base types (primitive-types),
    /// e.g. DateTime is a time representation in uint32.
    pub base_type: FitBaseType,
    /// ProfileType represents more than just a type of Value. E.g. ProfileType::DateTime -> FitBaseType::Uint32.
    /// When an u32 value having ProfileType::DateTime as type, the value represents time.
    pub profile_type: ProfileType,
    /// Flag whether the value of this field is an array
    pub array: bool,
    /// Flag to indicate if the value of the field is accumulable.
    pub accumulate: bool,
    /// A scale or offset specified in the FIT profile for binary fields (sint/uint etc.) only.
    /// The binary quantity is divided by the scale factor and then the offset is subtracted. (default: 1)
    pub scale: f64,
    /// A scale or offset specified in the FIT profile for binary fields (sint/uint etc.) only.
    /// The binary quantity is divided by the scale factor and then the offset is subtracted. (default: 0)
    pub offset: f64,
    /// Units of the value, such as m (meter), m/s (meter per second), s (second), etc.
    pub units: &'a str,
    /// List of component
    pub components: &'a [Component],
    /// List of sub-field
    pub sub_fields: &'a [SubField<'a>],
}

/// DeveloperField is a way to add custom data fields to existing messages. Developer Data Fields can be added
/// to any message at runtime by providing a self-describing FieldDefinition messages prior to that message.
/// The combination of the DeveloperDataIndex and FieldDefinitionNumber create a unique id for each FieldDescription.
/// Developer Data Fields are also used by the Connect IQ FIT Contributor library, allowing Connect IQ apps
/// and data fields to include custom data in FIT Activity files during the recording of activities.
///
/// NOTE: If DeveloperField contains a valid NativeMesgNum and NativeFieldNum, the value should be treated as
/// native value (scale, offset, etc shall apply). [Added since protocol version 2.0]
#[derive(Debug, Clone, PartialEq)]
pub struct DeveloperField {
    /// Maps to `field_definition_number` of a `field_description` message.
    pub num: u8,
    /// Maps to `developer_data_index` of a `developer_data_id` and a `field_description` messages.
    pub developer_data_index: u8,
    /// Value
    pub value: Value,
}

/// Component is a way of compressing one or more fields into a bit field expressed in a single containing field.
/// The component can be expanded as a main Field in a Message or to update the value of the destination main Field.
#[derive(Debug)]
pub struct Component {
    /// Refer to Field's Number.
    pub field_num: u8,
    /// A flag whether this component should be accumulated.
    pub accumulate: bool,
    /// The size of data of this component in bits  
    pub bits: u8,
    /// Similar to FieldReference's scale, but for this component.
    pub scale: f64,
    /// Similar to FieldReference's offset, but for this component.
    pub offset: f64,
}

/// SubField is a dynamic interpretation of the main Field in a Message when the SubFieldMap mapping match. See SubFieldMap's docs.
#[derive(Debug)]
pub struct SubField<'a> {
    /// Name
    pub name: &'a str,
    /// ProfileType
    pub profile_type: ProfileType,
    /// Scale
    pub scale: f64,
    /// Offset
    pub offset: f64,
    /// Units
    pub units: &'a str,
    /// List of SubFieldMap
    pub maps: &'a [SubFieldMap],
    /// List of Component
    pub components: &'a [Component],
}

/// SubFieldMap is the mapping between SubField and the corresponding main Field in a Message.
/// When any Field in a Message has Field.Num == RefFieldNum and Field.Value == RefFieldValue, then the SubField containing
/// this mapping can be interpreted as the main Field's properties (name, scale, type etc.)
#[derive(Debug)]
pub struct SubFieldMap {
    /// Mapping reference to targeted Field's Number.
    pub ref_field_num: u8,
    /// Mapping reference to targeted Field's Value.
    pub ref_field_value: i64,
}

/// Value representation of Message's Field.
#[allow(missing_docs)]
#[derive(Debug, Clone, Default, PartialEq)]
pub enum Value {
    #[default]
    Invalid,
    Int8(i8),
    Uint8(u8),
    Int16(i16),
    Uint16(u16),
    Int32(i32),
    Uint32(u32),
    String(String),
    Float32(f32),
    Float64(f64),
    Int64(i64),
    Uint64(u64),
    VecInt8(Vec<i8>),
    VecUint8(Vec<u8>),
    VecInt16(Vec<i16>),
    VecUint16(Vec<u16>),
    VecInt32(Vec<i32>),
    VecUint32(Vec<u32>),
    VecString(Vec<String>),
    VecFloat32(Vec<f32>),
    VecFloat64(Vec<f64>),
    VecInt64(Vec<i64>),
    VecUint64(Vec<u64>),
}

/// Value that can hold FIT's value.
impl Value {
    /// Unmarshal bytes into Value.
    //
    // This is hotpath. We intentionally avoid using chunks_exact() iterator, as
    // it introduces a slight performance overhead compared to using a standard loop.
    pub(crate) fn unmarshal(buf: &[u8], array: bool, base_type: FitBaseType, arch: u8) -> Value {
        match base_type {
            FitBaseType::SINT8 => match array {
                true => Value::VecInt8({
                    let mut vals: Vec<i8> = Vec::with_capacity(buf.len());
                    for &v in buf {
                        vals.push(v as i8);
                    }
                    vals
                }),
                false => Value::Int8(buf[0] as i8),
            },
            FitBaseType::ENUM | FitBaseType::BYTE | FitBaseType::UINT8 | FitBaseType::UINT8Z => {
                match array {
                    true => Value::VecUint8(buf.to_vec()),
                    false => Value::Uint8(buf[0]),
                }
            }
            FitBaseType::SINT16 => match array {
                true => Value::VecInt16({
                    let mut vals: Vec<i16> = Vec::with_capacity(buf.len() / 2);
                    let mut buf = buf;
                    while buf.len() >= 2 {
                        vals.push(match arch {
                            0 => i16::from_le_bytes(buf[..2].try_into().unwrap()),
                            _ => i16::from_be_bytes(buf[..2].try_into().unwrap()),
                        });
                        buf = &buf[2..];
                    }
                    vals
                }),
                false => match arch {
                    0 => Value::Int16(i16::from_le_bytes(buf[..2].try_into().unwrap())),
                    _ => Value::Int16(i16::from_be_bytes(buf[..2].try_into().unwrap())),
                },
            },
            FitBaseType::UINT16 | FitBaseType::UINT16Z => match array {
                true => Value::VecUint16({
                    let mut vals: Vec<u16> = Vec::with_capacity(buf.len() / 2);
                    let mut buf = buf;
                    while buf.len() >= 2 {
                        vals.push(match arch {
                            0 => u16::from_le_bytes(buf[..2].try_into().unwrap()),
                            _ => u16::from_be_bytes(buf[..2].try_into().unwrap()),
                        });
                        buf = &buf[2..];
                    }
                    vals
                }),
                false => match arch {
                    0 => Value::Uint16(u16::from_le_bytes(buf[..2].try_into().unwrap())),
                    _ => Value::Uint16(u16::from_be_bytes(buf[..2].try_into().unwrap())),
                },
            },
            FitBaseType::SINT32 => match array {
                true => Value::VecInt32({
                    let mut vals: Vec<i32> = Vec::with_capacity(buf.len() / 4);
                    let mut buf = buf;
                    while buf.len() >= 4 {
                        vals.push(match arch {
                            0 => i32::from_le_bytes(buf[..4].try_into().unwrap()),
                            _ => i32::from_be_bytes(buf[..4].try_into().unwrap()),
                        });
                        buf = &buf[4..];
                    }
                    vals
                }),
                false => match arch {
                    0 => Value::Int32(i32::from_le_bytes(buf[..4].try_into().unwrap())),
                    _ => Value::Int32(i32::from_be_bytes(buf[..4].try_into().unwrap())),
                },
            },
            FitBaseType::UINT32 | FitBaseType::UINT32Z => match array {
                true => Value::VecUint32({
                    let mut vals: Vec<u32> = Vec::with_capacity(buf.len() / 4);
                    let mut buf = buf;
                    while buf.len() >= 4 {
                        vals.push(match arch {
                            0 => u32::from_le_bytes(buf[..4].try_into().unwrap()),
                            _ => u32::from_be_bytes(buf[..4].try_into().unwrap()),
                        });
                        buf = &buf[4..];
                    }
                    vals
                }),
                false => match arch {
                    0 => Value::Uint32(u32::from_le_bytes(buf[..4].try_into().unwrap())),
                    _ => Value::Uint32(u32::from_be_bytes(buf[..4].try_into().unwrap())),
                },
            },
            FitBaseType::STRING => match array {
                true => Value::String(String::from_utf8_lossy(buf).to_string()),
                false => Value::VecString({
                    let mut vals = Vec::with_capacity(strcount(buf) as usize);
                    let mut last = 0usize;
                    for (i, &v) in buf.iter().enumerate() {
                        if v != 0 {
                            continue;
                        }
                        if last != i {
                            vals.push(String::from_utf8_lossy(&buf[last..i]).into_owned());
                        }
                        last = i + 1
                    }
                    vals
                }),
            },
            FitBaseType::FLOAT32 => match array {
                true => Value::VecFloat32({
                    let mut vals: Vec<f32> = Vec::with_capacity(buf.len() / 4);
                    let mut buf = buf;
                    while buf.len() >= 4 {
                        vals.push(match arch {
                            0 => f32::from_le_bytes(buf[..4].try_into().unwrap()),
                            _ => f32::from_be_bytes(buf[..4].try_into().unwrap()),
                        });
                        buf = &buf[4..];
                    }
                    vals
                }),
                false => match arch {
                    0 => Value::Float32(f32::from_le_bytes(buf[..4].try_into().unwrap())),
                    _ => Value::Float32(f32::from_be_bytes(buf[..4].try_into().unwrap())),
                },
            },
            FitBaseType::FLOAT64 => match array {
                true => Value::VecFloat64({
                    let mut vals: Vec<f64> = Vec::with_capacity(buf.len() / 8);
                    let mut buf = buf;
                    while buf.len() >= 2 {
                        vals.push(match arch {
                            0 => f64::from_le_bytes(buf[..8].try_into().unwrap()),
                            _ => f64::from_be_bytes(buf[..8].try_into().unwrap()),
                        });
                        buf = &buf[8..];
                    }
                    vals
                }),
                false => match arch {
                    0 => Value::Float64(f64::from_le_bytes(buf[..8].try_into().unwrap())),
                    _ => Value::Float64(f64::from_be_bytes(buf[..8].try_into().unwrap())),
                },
            },
            FitBaseType::SINT64 => match array {
                true => Value::VecInt64({
                    let mut vals: Vec<i64> = Vec::with_capacity(buf.len() / 8);
                    let mut buf = buf;
                    while buf.len() >= 8 {
                        vals.push(match arch {
                            0 => i64::from_le_bytes(buf[..8].try_into().unwrap()),
                            _ => i64::from_be_bytes(buf[..8].try_into().unwrap()),
                        });
                        buf = &buf[8..];
                    }
                    vals
                }),
                false => match arch {
                    0 => Value::Int64(i64::from_le_bytes(buf[..8].try_into().unwrap())),
                    _ => Value::Int64(i64::from_be_bytes(buf[..8].try_into().unwrap())),
                },
            },
            FitBaseType::UINT64 | FitBaseType::UINT64Z => match array {
                true => Value::VecUint64({
                    let mut vals: Vec<u64> = Vec::with_capacity(buf.len() / 8);
                    let mut buf = buf;
                    while buf.len() >= 8 {
                        vals.push(match arch {
                            0 => u64::from_le_bytes(buf[..8].try_into().unwrap()),
                            _ => u64::from_be_bytes(buf[..8].try_into().unwrap()),
                        });
                        buf = &buf[8..];
                    }
                    vals
                }),
                false => match arch {
                    0 => Value::Uint64(u64::from_le_bytes(buf[..8].try_into().unwrap())),
                    _ => Value::Uint64(u64::from_be_bytes(buf[..8].try_into().unwrap())),
                },
            },
            _ => Value::Invalid,
        }
    }

    pub(crate) fn marshal_append(&self, vec: &mut Vec<u8>, arch: u8) -> Result<(), Error> {
        match self {
            Value::Int8(v) => vec.push(*v as u8),
            Value::Uint8(v) => vec.push(*v),
            Value::Int16(v) => vec.extend_from_slice(&match arch {
                0 => v.to_le_bytes(),
                _ => v.to_be_bytes(),
            }),
            Value::Uint16(v) => vec.extend_from_slice(&match arch {
                0 => v.to_le_bytes(),
                _ => v.to_be_bytes(),
            }),
            Value::Int32(v) => vec.extend_from_slice(&match arch {
                0 => v.to_le_bytes(),
                _ => v.to_be_bytes(),
            }),
            Value::Uint32(v) => vec.extend_from_slice(&match arch {
                0 => v.to_le_bytes(),
                _ => v.to_be_bytes(),
            }),
            Value::String(v) => {
                let b = v.as_bytes();
                vec.extend_from_slice(b);
                if v.is_empty() || b[b.len() - 1] != 0 {
                    vec.push(0);
                }
            }
            Value::Float32(v) => vec.extend_from_slice(&match arch {
                0 => v.to_le_bytes(),
                _ => v.to_be_bytes(),
            }),
            Value::Float64(v) => vec.extend_from_slice(&match arch {
                0 => v.to_le_bytes(),
                _ => v.to_be_bytes(),
            }),
            Value::Int64(v) => vec.extend_from_slice(&match arch {
                0 => v.to_le_bytes(),
                _ => v.to_be_bytes(),
            }),
            Value::Uint64(v) => vec.extend_from_slice(&match arch {
                0 => v.to_le_bytes(),
                _ => v.to_be_bytes(),
            }),
            Value::VecInt8(v) => {
                for &x in v {
                    vec.push(x as u8);
                }
            }
            Value::VecUint8(v) => {
                for &x in v {
                    vec.push(x);
                }
            }
            Value::VecInt16(v) => match arch {
                0 => {
                    for x in v {
                        vec.extend_from_slice(&x.to_le_bytes());
                    }
                }
                _ => {
                    for x in v {
                        vec.extend_from_slice(&x.to_be_bytes());
                    }
                }
            },
            Value::VecUint16(v) => match arch {
                0 => {
                    for x in v {
                        vec.extend_from_slice(&x.to_le_bytes());
                    }
                }
                _ => {
                    for x in v {
                        vec.extend_from_slice(&x.to_be_bytes());
                    }
                }
            },
            Value::VecInt32(v) => match arch {
                0 => {
                    for x in v {
                        vec.extend_from_slice(&x.to_le_bytes());
                    }
                }
                _ => {
                    for x in v {
                        vec.extend_from_slice(&x.to_be_bytes());
                    }
                }
            },
            Value::VecUint32(v) => match arch {
                0 => {
                    for x in v {
                        vec.extend_from_slice(&x.to_le_bytes());
                    }
                }
                _ => {
                    for x in v {
                        vec.extend_from_slice(&x.to_be_bytes());
                    }
                }
            },
            Value::VecString(v) => {
                for x in v {
                    let b = x.as_bytes();
                    vec.extend_from_slice(b);
                    if x.is_empty() || b[b.len() - 1] != 0 {
                        vec.push(0);
                    }
                }
            }
            Value::VecFloat32(v) => match arch {
                0 => {
                    for x in v {
                        vec.extend_from_slice(&x.to_le_bytes());
                    }
                }
                _ => {
                    for x in v {
                        vec.extend_from_slice(&x.to_be_bytes());
                    }
                }
            },
            Value::VecFloat64(v) => match arch {
                0 => {
                    for x in v {
                        vec.extend_from_slice(&x.to_le_bytes());
                    }
                }
                _ => {
                    for x in v {
                        vec.extend_from_slice(&x.to_be_bytes());
                    }
                }
            },
            Value::VecInt64(v) => match arch {
                0 => {
                    for x in v {
                        vec.extend_from_slice(&x.to_le_bytes());
                    }
                }
                _ => {
                    for x in v {
                        vec.extend_from_slice(&x.to_be_bytes());
                    }
                }
            },
            Value::VecUint64(v) => match arch {
                0 => {
                    for x in v {
                        vec.extend_from_slice(&x.to_le_bytes());
                    }
                }
                _ => {
                    for x in v {
                        vec.extend_from_slice(&x.to_be_bytes());
                    }
                }
            },
            Value::Invalid => return Err(Error::InvalidValue),
        };
        Ok(())
    }

    /// cast_i64 converts any integer value into i64. If the value is not an integer, this returns i64::MAX.
    pub(crate) fn cast_i64(&self) -> i64 {
        match self {
            Value::Uint8(v) => *v as i64,
            Value::Int8(v) => *v as i64,
            Value::Int16(v) => *v as i64,
            Value::Uint16(v) => *v as i64,
            Value::Int32(v) => *v as i64,
            Value::Uint32(v) => *v as i64,
            Value::Int64(v) => *v,
            Value::Uint64(v) => *v as i64,
            _ => i64::MAX,
        }
    }

    /// Returns i8 or its invalid value when it's not an i8 value.
    pub fn as_i8(&self) -> i8 {
        if let Value::Int8(v) = self {
            return *v;
        }
        i8::MAX
    }

    /// Returns u8 or its invalid value when it's not an u8 value.
    pub fn as_u8(&self) -> u8 {
        if let Value::Uint8(v) = self {
            return *v;
        }
        u8::MAX
    }

    /// Returns u8z or its invalid value when it's not an u8z value.
    pub fn as_u8z(&self) -> u8 {
        if let Value::Uint8(v) = self {
            return *v;
        }
        0
    }

    /// Returns i16 or its invalid value when it's not an i16 value.
    pub fn as_i16(&self) -> i16 {
        if let Value::Int16(v) = self {
            return *v;
        }
        i16::MAX
    }

    /// Returns u16 or its invalid value when it's not an u16 value.
    pub fn as_u16(&self) -> u16 {
        if let Value::Uint16(v) = self {
            return *v;
        }
        u16::MAX
    }

    /// Returns u16z or its invalid value when it's not an u16z value.
    pub fn as_u16z(&self) -> u16 {
        if let Value::Uint16(v) = self {
            return *v;
        }
        0
    }

    /// Returns i32 or its invalid value when it's not an i32 value.
    pub fn as_i32(&self) -> i32 {
        if let Value::Int32(v) = self {
            return *v;
        }
        i32::MAX
    }

    /// Returns u32 or its invalid value when it's not an u32 value.
    pub fn as_u32(&self) -> u32 {
        if let Value::Uint32(v) = self {
            return *v;
        }
        u32::MAX
    }

    /// Returns u32z or its invalid value when it's not an u32z value.
    pub fn as_u32z(&self) -> u32 {
        if let Value::Uint32(v) = self {
            return *v;
        }
        0
    }

    /// Returns string (clone) or empty string when it's not a string.
    pub fn as_string(&self) -> String {
        if let Value::String(v) = self {
            return v.clone();
        }
        String::new()
    }

    /// Returns f32 or its invalid value when it's not a f32 value.
    pub fn as_f32(&self) -> f32 {
        if let Value::Float32(v) = self {
            return *v;
        }
        f32::MAX
    }

    /// Returns f64 or its invalid value when it's not a f64 value.
    pub fn as_f64(&self) -> f64 {
        if let Value::Float64(v) = self {
            return *v;
        }
        f64::MAX
    }

    /// Returns i64 or its invalid value when it's not an i64 value.
    pub fn as_i64(&self) -> i64 {
        if let Value::Int64(v) = self {
            return *v;
        }
        i64::MAX
    }

    /// Returns u64 or its invalid value when it's not an u64 value.
    pub fn as_u64(&self) -> u64 {
        if let Value::Uint64(v) = self {
            return *v;
        }
        u64::MAX
    }

    /// Returns u64z or its invalid value when it's not an u64z value.
    pub fn as_u64z(&self) -> u64 {
        if let Value::Uint64(v) = self {
            return *v;
        }
        0
    }

    /// Returns Vec<i8> (clone) or empty vector when it's not a Vec<i8> value.
    pub fn as_vec_i8(&self) -> Vec<i8> {
        if let Value::VecInt8(v) = self {
            return v.clone();
        }
        Vec::new()
    }

    /// Returns Vec<u8> (clone) or empty vector when it's not a Vec<u8> value.
    pub fn as_vec_u8(&self) -> Vec<u8> {
        if let Value::VecUint8(v) = self {
            return v.clone();
        }
        Vec::new()
    }

    /// Returns Vec<i16> (clone) or empty vector when it's not a Vec<i16> value.
    pub fn as_vec_i16(&self) -> Vec<i16> {
        if let Value::VecInt16(v) = self {
            return v.clone();
        }
        Vec::new()
    }

    /// Returns Vec<u16> (clone) or empty vector when it's not a Vec<u16> value.
    pub fn as_vec_u16(&self) -> Vec<u16> {
        if let Value::VecUint16(v) = self {
            return v.clone();
        }
        Vec::new()
    }

    /// Returns Vec<i32> (clone) or empty vector when it's not a Vec<i32> value.
    pub fn as_vec_i32(&self) -> Vec<i32> {
        if let Value::VecInt32(v) = self {
            return v.clone();
        }
        Vec::new()
    }

    /// Returns Vec<u32> (clone) or empty vector when it's not a Vec<u32> value.
    pub fn as_vec_u32(&self) -> Vec<u32> {
        if let Value::VecUint32(v) = self {
            return v.clone();
        }
        Vec::new()
    }

    /// Returns Vec<String> (clone) or empty vector when it's not a Vec<String> value.
    pub fn as_vec_string(&self) -> Vec<String> {
        if let Value::VecString(v) = self {
            return v.clone();
        }
        Vec::new()
    }

    /// Returns Vec<f32> (clone) or empty vector when it's not a Vec<f32> value.
    pub fn as_vec_f32(&self) -> Vec<f32> {
        if let Value::VecFloat32(v) = self {
            return v.clone();
        }
        Vec::new()
    }

    /// Returns Vec<f64> (clone) or empty vector when it's not a Vec<f64> value.
    pub fn as_vec_f64(&self) -> Vec<f64> {
        if let Value::VecFloat64(v) = self {
            return v.clone();
        }
        Vec::new()
    }

    /// Returns Vec<i64> (clone) or empty vector when it's not a Vec<i64> value.
    pub fn as_vec_i64(&self) -> Vec<i64> {
        if let Value::VecInt64(v) = self {
            return v.clone();
        }
        Vec::new()
    }

    /// Returns Vec<u64> (clone) or empty vector when it's not a Vec<u64> value.
    pub fn as_vec_u64(&self) -> Vec<u64> {
        if let Value::VecUint64(v) = self {
            return v.clone();
        }
        Vec::new()
    }

    /// Checks whether Value holds any representation of invalid value based on base_type.
    /// An array is invalid when all elements represent invalid value.
    pub(crate) fn is_valid(&self, base_type: FitBaseType) -> bool {
        match self {
            Value::Int8(v) => *v != i8::MAX,
            Value::Uint8(v) => match base_type {
                FitBaseType::UINT8 | FitBaseType::ENUM | FitBaseType::BYTE => *v != u8::MAX,
                FitBaseType::UINT8Z => *v != 0,
                _ => false,
            },
            Value::Int16(v) => *v != i16::MAX,
            Value::Uint16(v) => match base_type {
                FitBaseType::UINT16 => *v != u16::MAX,
                FitBaseType::UINT16Z => *v != 0,
                _ => false,
            },
            Value::Int32(v) => *v != i32::MAX,
            Value::Uint32(v) => match base_type {
                FitBaseType::UINT32 => *v != u32::MAX,
                FitBaseType::UINT32Z => *v != 0,
                _ => false,
            },
            Value::String(v) => !v.is_empty() && v.as_str() != "\x00",
            Value::Float32(v) => f32::to_bits(*v) != u32::MAX,
            Value::Float64(v) => f64::to_bits(*v) != u64::MAX,
            Value::Int64(v) => *v != i64::MAX,
            Value::Uint64(v) => match base_type {
                FitBaseType::UINT64 => *v != u64::MAX,
                FitBaseType::UINT64Z => *v != 0,
                _ => false,
            },
            Value::VecInt8(v) => {
                for &x in v {
                    if x != i8::MAX {
                        return true;
                    }
                }
                false
            }
            Value::VecUint8(v) => match base_type {
                FitBaseType::UINT8 => {
                    for &x in v {
                        if x != u8::MAX {
                            return true;
                        }
                    }
                    false
                }
                FitBaseType::UINT8Z => {
                    for &x in v {
                        if x != u8::MIN {
                            return true;
                        }
                    }
                    false
                }
                _ => false,
            },
            Value::VecInt16(v) => {
                for &x in v {
                    if x != i16::MAX {
                        return true;
                    }
                }
                false
            }
            Value::VecUint16(v) => match base_type {
                FitBaseType::UINT16 => {
                    for &x in v {
                        if x != u16::MAX {
                            return true;
                        }
                    }
                    false
                }
                FitBaseType::UINT16Z => {
                    for &x in v {
                        if x != u16::MIN {
                            return true;
                        }
                    }
                    false
                }
                _ => false,
            },
            Value::VecInt32(v) => {
                for &x in v {
                    if x != i32::MAX {
                        return true;
                    }
                }
                false
            }
            Value::VecUint32(v) => match base_type {
                FitBaseType::UINT32 => {
                    for &x in v {
                        if x != u32::MAX {
                            return true;
                        }
                    }
                    false
                }
                FitBaseType::UINT32Z => {
                    for &x in v {
                        if x != u32::MIN {
                            return true;
                        }
                    }
                    false
                }
                _ => false,
            },
            Value::VecString(v) => {
                for x in v {
                    if !x.is_empty() && x.as_str() != "\x00" {
                        return true;
                    }
                }
                false
            }
            Value::VecFloat32(v) => {
                for &x in v {
                    if x.to_bits() != u32::MAX {
                        return true;
                    }
                }
                false
            }
            Value::VecFloat64(v) => {
                for &x in v {
                    if x.to_bits() != u64::MAX {
                        return true;
                    }
                }
                false
            }
            Value::VecInt64(v) => {
                for &x in v {
                    if x != i64::MAX {
                        return true;
                    }
                }
                false
            }
            Value::VecUint64(v) => match base_type {
                FitBaseType::UINT64 => {
                    for &x in v {
                        if x != u64::MAX {
                            return true;
                        }
                    }
                    false
                }
                FitBaseType::UINT64Z => {
                    for &x in v {
                        if x != u64::MIN {
                            return true;
                        }
                    }
                    false
                }
                _ => false,
            },
            Value::Invalid => false,
        }
    }

    /// Checks whether Value's type is align with given basetype.
    pub(crate) fn is_align(&self, base_type: FitBaseType) -> bool {
        match self {
            Value::Int8(_) => base_type == FitBaseType::SINT8,
            Value::Uint8(_) => {
                base_type == FitBaseType::ENUM
                    || base_type == FitBaseType::UINT8
                    || base_type == FitBaseType::UINT8Z
                    || base_type == FitBaseType::BYTE
            }
            Value::Int16(_) => base_type == FitBaseType::SINT16,
            Value::Uint16(_) => {
                base_type == FitBaseType::UINT16 || base_type == FitBaseType::UINT16Z
            }
            Value::Int32(_) => base_type == FitBaseType::SINT32,
            Value::Uint32(_) => {
                base_type == FitBaseType::UINT32 || base_type == FitBaseType::UINT32Z
            }
            Value::String(_) => base_type == FitBaseType::STRING,
            Value::Float32(_) => base_type == FitBaseType::FLOAT32,
            Value::Float64(_) => base_type == FitBaseType::FLOAT64,
            Value::Int64(_) => base_type == FitBaseType::SINT64,
            Value::Uint64(_) => {
                base_type == FitBaseType::UINT64 || base_type == FitBaseType::UINT64Z
            }
            Value::VecInt8(_) => base_type == FitBaseType::SINT8,
            Value::VecUint8(_) => {
                base_type == FitBaseType::ENUM
                    || base_type == FitBaseType::UINT8
                    || base_type == FitBaseType::UINT8Z
                    || base_type == FitBaseType::BYTE
            }
            Value::VecInt16(_) => base_type == FitBaseType::SINT16,
            Value::VecUint16(_) => {
                base_type == FitBaseType::UINT16 || base_type == FitBaseType::UINT16Z
            }
            Value::VecInt32(_) => base_type == FitBaseType::SINT32,
            Value::VecUint32(_) => {
                base_type == FitBaseType::UINT32 || base_type == FitBaseType::UINT32Z
            }
            Value::VecString(_) => base_type == FitBaseType::STRING,
            Value::VecFloat32(_) => base_type == FitBaseType::FLOAT32,
            Value::VecFloat64(_) => base_type == FitBaseType::FLOAT64,
            Value::VecInt64(_) => base_type == FitBaseType::SINT64,
            Value::VecUint64(_) => {
                base_type == FitBaseType::UINT64 || base_type == FitBaseType::UINT64Z
            }
            _ => false,
        }
    }

    /// Returns the size of Value in binary from. For every string in Value,
    /// if the last index of the string is not '\x00', size += 1.
    pub(crate) fn size(&self) -> usize {
        match self {
            Value::Int8(_) | Value::Uint8(_) => 1,
            Value::Int16(_) | Value::Uint16(_) => 2,
            Value::Int32(_) | Value::Uint32(_) | Value::Float32(_) => 4,
            Value::Int64(_) | Value::Uint64(_) | Value::Float64(_) => 8,
            Value::String(v) => {
                let n = v.len();
                if n == 0 || v.as_bytes()[n - 1] != 0 {
                    return n + 1;
                }
                n
            }
            Value::VecInt8(v) => v.len(),
            Value::VecUint8(v) => v.len(),
            Value::VecInt16(v) => v.len() * 2,
            Value::VecUint16(v) => v.len() * 2,
            Value::VecInt32(v) => v.len() * 4,
            Value::VecUint32(v) => v.len() * 4,
            Value::VecFloat32(v) => v.len() * 4,
            Value::VecFloat64(v) => v.len() * 8,
            Value::VecInt64(v) => v.len() * 8,
            Value::VecUint64(v) => v.len() * 8,
            Value::VecString(v) => {
                let mut size = 0usize;
                for x in v {
                    let mut n = x.len();
                    if n == 0 || x.as_bytes()[n - 1] != 0 {
                        n += 1;
                    }
                    size += n;
                }
                size
            }
            Value::Invalid => 0,
        }
    }
}

/// Protocol Version representation.
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct ProtocolVersion(pub u8);

#[allow(missing_docs)]
impl ProtocolVersion {
    pub const V1: ProtocolVersion = ProtocolVersion(1 << 4);
    pub const V2: ProtocolVersion = ProtocolVersion(2 << 4);

    /// Returns major version.
    pub fn major(self) -> u8 {
        self.0 >> 4
    }

    /// Returns minor version.
    pub fn minor(self) -> u8 {
        self.0 | ((1 << 4) - 1)
    }
}

/// Validates whether the message contains unsupported data for the targeted protocol version.
pub(crate) fn validate_message(
    mesg: &Message,
    protocol_version: ProtocolVersion,
) -> Result<(), Error> {
    if protocol_version == ProtocolVersion::V1 {
        if !mesg.developer_fields.is_empty() {
            return Err(Error::ProtocolViolationDeveloperData);
        }
        for field in &mesg.fields {
            if field.profile_type.base_type().0 & FitBaseType::NUM_MASK
                > FitBaseType::BYTE.0 & FitBaseType::NUM_MASK
            {
                return Err(Error::ProtocolViolationUnsupportedBaseType(
                    field.profile_type.base_type(),
                ));
            }
        }
    }
    Ok(())
}

/// Counts how many valid utf-8 string in s.
pub(crate) fn strcount(s: &[u8]) -> u8 {
    let mut last = 0usize;
    let mut size = 0u8;
    for (i, &v) in s.iter().enumerate() {
        if v != 0 {
            continue;
        }
        if last != i {
            size += 1
        }
        last = i + 1
    }
    if size == 0 && !s.is_empty() {
        return 1; // Allow string without utf-8 null termination.
    }
    size
}

#[cfg(test)]
mod tests {
    use crate::{
        profile::typedef::FitBaseType,
        proto::{Error, Value, strcount},
    };

    #[test]
    fn test_strcount() {
        #[derive(Default, Clone, Copy)]
        struct Case {
            input: &'static str,
            expected: u8,
        }

        let tt = [
            Case {
                input: "Open Water",
                expected: 1,
            },
            Case {
                input: "Open Water\x00",
                expected: 1,
            },
            Case {
                input: "Open Water\x00\x00",
                expected: 1,
            },
            Case {
                input: "Open\x00Water\x00",
                expected: 2,
            },
        ];

        for (i, tc) in tt.iter().enumerate() {
            let v = strcount(tc.input.as_bytes());
            assert_eq!(v, tc.expected, "index {} input \"{}\"", i, tc.input);
        }
    }

    #[test]
    fn test_value_is_valid() {
        struct Case {
            value: Value,
            base_type: FitBaseType,
            is_valid: bool,
        }

        let tt = [
            Case {
                value: Value::Int8(i8::MIN),
                base_type: FitBaseType::SINT8,
                is_valid: true,
            },
            Case {
                value: Value::Int8(i8::MAX),
                base_type: FitBaseType::SINT8,
                is_valid: false,
            },
            Case {
                value: Value::Uint8(u8::MIN),
                base_type: FitBaseType::UINT8,
                is_valid: true,
            },
            Case {
                value: Value::Uint8(u8::MAX),
                base_type: FitBaseType::UINT8,
                is_valid: false,
            },
            Case {
                value: Value::Uint8(u8::MIN),
                base_type: FitBaseType::UINT8Z,
                is_valid: false,
            },
            Case {
                value: Value::Uint8(u8::MAX),
                base_type: FitBaseType::UINT8Z,
                is_valid: true,
            },
            Case {
                value: Value::Int16(i16::MIN),
                base_type: FitBaseType::SINT16,
                is_valid: true,
            },
            Case {
                value: Value::Int16(i16::MAX),
                base_type: FitBaseType::SINT16,
                is_valid: false,
            },
            Case {
                value: Value::Uint16(u16::MIN),
                base_type: FitBaseType::UINT16,
                is_valid: true,
            },
            Case {
                value: Value::Uint16(u16::MAX),
                base_type: FitBaseType::UINT16,
                is_valid: false,
            },
            Case {
                value: Value::Uint16(u16::MIN),
                base_type: FitBaseType::UINT16Z,
                is_valid: false,
            },
            Case {
                value: Value::Uint16(u16::MAX),
                base_type: FitBaseType::UINT16Z,
                is_valid: true,
            },
            Case {
                value: Value::Int32(i32::MIN),
                base_type: FitBaseType::SINT32,
                is_valid: true,
            },
            Case {
                value: Value::Int32(i32::MAX),
                base_type: FitBaseType::SINT32,
                is_valid: false,
            },
            Case {
                value: Value::Uint32(u32::MIN),
                base_type: FitBaseType::UINT32,
                is_valid: true,
            },
            Case {
                value: Value::Uint32(u32::MAX),
                base_type: FitBaseType::UINT32,
                is_valid: false,
            },
            Case {
                value: Value::Uint32(u32::MIN),
                base_type: FitBaseType::UINT32Z,
                is_valid: false,
            },
            Case {
                value: Value::Uint32(u32::MAX),
                base_type: FitBaseType::UINT32Z,
                is_valid: true,
            },
            Case {
                value: Value::Float32(f32::MIN),
                base_type: FitBaseType::FLOAT32,
                is_valid: true,
            },
            Case {
                value: Value::Float32(f32::from_bits(u32::MAX)),
                base_type: FitBaseType::FLOAT32,
                is_valid: false,
            },
            Case {
                value: Value::Float64(f64::MIN),
                base_type: FitBaseType::FLOAT64,
                is_valid: true,
            },
            Case {
                value: Value::Float64(f64::from_bits(u64::MAX)),
                base_type: FitBaseType::FLOAT64,
                is_valid: false,
            },
            Case {
                value: Value::Int64(i64::MIN),
                base_type: FitBaseType::SINT64,
                is_valid: true,
            },
            Case {
                value: Value::Int64(i64::MAX),
                base_type: FitBaseType::SINT64,
                is_valid: false,
            },
            Case {
                value: Value::Uint64(u64::MIN),
                base_type: FitBaseType::UINT64,
                is_valid: true,
            },
            Case {
                value: Value::Uint64(u64::MAX),
                base_type: FitBaseType::UINT64,
                is_valid: false,
            },
            Case {
                value: Value::Uint64(u64::MIN),
                base_type: FitBaseType::UINT64Z,
                is_valid: false,
            },
            Case {
                value: Value::Uint64(u64::MAX),
                base_type: FitBaseType::UINT64Z,
                is_valid: true,
            },
            Case {
                value: Value::String("rustyfit".to_string()),
                base_type: FitBaseType::STRING,
                is_valid: true,
            },
            Case {
                value: Value::String("".to_string()),
                base_type: FitBaseType::STRING,
                is_valid: false,
            },
            Case {
                value: Value::String("\x00".to_string()),
                base_type: FitBaseType::STRING,
                is_valid: false,
            },
            Case {
                value: Value::VecInt8(vec![0i8, 1i8]),
                base_type: FitBaseType::SINT8,
                is_valid: true,
            },
            Case {
                value: Value::VecInt8(vec![i8::MAX, i8::MAX]),
                base_type: FitBaseType::SINT8,
                is_valid: false,
            },
            Case {
                value: Value::VecUint8(vec![0u8, 1u8]),
                base_type: FitBaseType::UINT8,
                is_valid: true,
            },
            Case {
                value: Value::VecUint8(vec![0u8, 1u8]),
                base_type: FitBaseType::UINT8Z,
                is_valid: true,
            },
            Case {
                value: Value::VecUint8(vec![u8::MAX, u8::MAX]),
                base_type: FitBaseType::UINT8,
                is_valid: false,
            },
            Case {
                value: Value::VecUint8(vec![u8::MIN, u8::MIN]),
                base_type: FitBaseType::UINT8Z,
                is_valid: false,
            },
            Case {
                value: Value::VecInt16(vec![0i16, 1i16]),
                base_type: FitBaseType::SINT16,
                is_valid: true,
            },
            Case {
                value: Value::VecInt16(vec![i16::MAX, i16::MAX]),
                base_type: FitBaseType::SINT16,
                is_valid: false,
            },
            Case {
                value: Value::VecUint16(vec![0u16, 1u16]),
                base_type: FitBaseType::UINT16,
                is_valid: true,
            },
            Case {
                value: Value::VecUint16(vec![0u16, 1u16]),
                base_type: FitBaseType::UINT16Z,
                is_valid: true,
            },
            Case {
                value: Value::VecUint16(vec![u16::MAX, u16::MAX]),
                base_type: FitBaseType::UINT16,
                is_valid: false,
            },
            Case {
                value: Value::VecUint16(vec![u16::MIN, u16::MIN]),
                base_type: FitBaseType::UINT16Z,
                is_valid: false,
            },
            Case {
                value: Value::VecInt32(vec![0i32, 1i32]),
                base_type: FitBaseType::SINT32,
                is_valid: true,
            },
            Case {
                value: Value::VecInt32(vec![i32::MAX, i32::MAX]),
                base_type: FitBaseType::SINT32,
                is_valid: false,
            },
            Case {
                value: Value::VecUint32(vec![0u32, 1u32]),
                base_type: FitBaseType::UINT32,
                is_valid: true,
            },
            Case {
                value: Value::VecUint32(vec![0u32, 1u32]),
                base_type: FitBaseType::UINT32Z,
                is_valid: true,
            },
            Case {
                value: Value::VecUint32(vec![u32::MAX, u32::MAX]),
                base_type: FitBaseType::UINT32,
                is_valid: false,
            },
            Case {
                value: Value::VecUint32(vec![u32::MIN, u32::MIN]),
                base_type: FitBaseType::UINT32Z,
                is_valid: false,
            },
            Case {
                value: Value::VecFloat32(vec![0f32, 1f32]),
                base_type: FitBaseType::FLOAT32,
                is_valid: true,
            },
            Case {
                value: Value::VecFloat32(vec![f32::from_bits(u32::MAX), f32::from_bits(u32::MAX)]),
                base_type: FitBaseType::FLOAT32,
                is_valid: false,
            },
            Case {
                value: Value::VecFloat64(vec![0f64, 1f64]),
                base_type: FitBaseType::FLOAT64,
                is_valid: true,
            },
            Case {
                value: Value::VecFloat64(vec![f64::from_bits(u64::MAX), f64::from_bits(u64::MAX)]),
                base_type: FitBaseType::FLOAT64,
                is_valid: false,
            },
            Case {
                value: Value::VecInt64(vec![0i64, 1i64]),
                base_type: FitBaseType::SINT64,
                is_valid: true,
            },
            Case {
                value: Value::VecInt64(vec![i64::MAX, i64::MAX]),
                base_type: FitBaseType::SINT64,
                is_valid: false,
            },
            Case {
                value: Value::VecUint64(vec![0u64, 1u64]),
                base_type: FitBaseType::UINT64,
                is_valid: true,
            },
            Case {
                value: Value::VecUint64(vec![0u64, 1u64]),
                base_type: FitBaseType::UINT64Z,
                is_valid: true,
            },
            Case {
                value: Value::VecUint64(vec![u64::MAX, u64::MAX]),
                base_type: FitBaseType::UINT64,
                is_valid: false,
            },
            Case {
                value: Value::VecUint64(vec![u64::MIN, u64::MIN]),
                base_type: FitBaseType::UINT64Z,
                is_valid: false,
            },
            Case {
                value: Value::VecString(vec!["rustyfit".to_string(), "rustyfit".to_string()]),
                base_type: FitBaseType::STRING,
                is_valid: true,
            },
            Case {
                value: Value::VecString(vec!["\x00".to_string(), "\x00".to_string()]),
                base_type: FitBaseType::STRING,
                is_valid: false,
            },
        ];

        for (i, tc) in tt.iter().enumerate() {
            let is_valid = tc.value.is_valid(tc.base_type);
            assert_eq!(
                tc.is_valid, is_valid,
                "{}: {:?} | {}",
                i, tc.value, tc.base_type,
            );
        }
    }

    #[test]
    fn test_value_marshal_append() {
        struct Case {
            value: Value,
            expected: Result<Vec<u8>, Error>,
            arch: u8,
        }

        let tt = [
            Case {
                value: Value::Int8(1),
                expected: Ok(1i8.to_le_bytes().to_vec()),
                arch: 0,
            },
            Case {
                value: Value::Uint8(2),
                expected: Ok(2u8.to_le_bytes().to_vec()),
                arch: 0,
            },
            Case {
                value: Value::Int16(3),
                expected: Ok(3i16.to_le_bytes().to_vec()),
                arch: 0,
            },
            Case {
                value: Value::Uint16(4),
                expected: Ok(4i16.to_le_bytes().to_vec()),
                arch: 0,
            },
            Case {
                value: Value::Int32(5),
                expected: Ok(5i32.to_le_bytes().to_vec()),
                arch: 0,
            },
            Case {
                value: Value::Uint32(6),
                expected: Ok(6u32.to_le_bytes().to_vec()),
                arch: 0,
            },
            Case {
                value: Value::Int64(7),
                expected: Ok(7i64.to_le_bytes().to_vec()),
                arch: 0,
            },
            Case {
                value: Value::Uint64(8),
                expected: Ok(8u64.to_le_bytes().to_vec()),
                arch: 0,
            },
            Case {
                value: Value::String("FIT".to_owned()),
                expected: Ok("FIT\x00".as_bytes().to_vec()),
                arch: 0,
            },
            Case {
                value: Value::String("".to_owned()),
                expected: Ok("\x00".as_bytes().to_vec()),
                arch: 0,
            },
            Case {
                value: Value::Float32(9.0),
                expected: Ok(9.0f32.to_le_bytes().to_vec()),
                arch: 0,
            },
            Case {
                value: Value::Float64(10.0),
                expected: Ok(10.0f64.to_le_bytes().to_vec()),
                arch: 0,
            },
            Case {
                value: Value::VecInt8(vec![1, 1]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(1u8.to_le_bytes());
                    v.extend(1i8.to_le_bytes());
                    v
                }),
                arch: 0,
            },
            Case {
                value: Value::VecUint8(vec![2, 2]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(2u8.to_le_bytes());
                    v.extend(2u8.to_le_bytes());
                    v
                }),
                arch: 0,
            },
            Case {
                value: Value::VecInt16(vec![3, 3]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(3i16.to_le_bytes());
                    v.extend(3i16.to_le_bytes());
                    v
                }),
                arch: 0,
            },
            Case {
                value: Value::VecUint16(vec![4, 4]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(4u16.to_le_bytes());
                    v.extend(4u16.to_le_bytes());
                    v
                }),
                arch: 0,
            },
            Case {
                value: Value::VecInt32(vec![5, 5]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(5i32.to_le_bytes());
                    v.extend(5i32.to_le_bytes());
                    v
                }),
                arch: 0,
            },
            Case {
                value: Value::VecUint32(vec![6, 6]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(6u32.to_le_bytes());
                    v.extend(6u32.to_le_bytes());
                    v
                }),
                arch: 0,
            },
            Case {
                value: Value::VecInt64(vec![7, 7]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(7i64.to_le_bytes());
                    v.extend(7i64.to_le_bytes());
                    v
                }),
                arch: 0,
            },
            Case {
                value: Value::VecUint64(vec![8, 8]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(8u64.to_le_bytes());
                    v.extend(8u64.to_le_bytes());
                    v
                }),
                arch: 0,
            },
            Case {
                value: Value::VecString(vec!["FIT".to_owned(), "SDK".to_owned()]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend("FIT\x00".as_bytes());
                    v.extend("SDK\x00".as_bytes());
                    v
                }),
                arch: 0,
            },
            Case {
                value: Value::VecString(vec!["".to_owned(), "SDK\x00".to_owned()]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend("\x00".as_bytes());
                    v.extend("SDK\x00".as_bytes());
                    v
                }),
                arch: 0,
            },
            Case {
                value: Value::VecFloat32(vec![9.0, 9.0]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(9.0f32.to_le_bytes());
                    v.extend(9.0f32.to_le_bytes());
                    v
                }),
                arch: 0,
            },
            Case {
                value: Value::VecFloat64(vec![10.0, 10.0]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(10.0f64.to_le_bytes());
                    v.extend(10.0f64.to_le_bytes());
                    v
                }),
                arch: 0,
            },
            Case {
                value: Value::Int8(1),
                expected: Ok(1i8.to_be_bytes().to_vec()),
                arch: 1,
            },
            Case {
                value: Value::Uint8(2),
                expected: Ok(2u8.to_be_bytes().to_vec()),
                arch: 1,
            },
            Case {
                value: Value::Int16(3),
                expected: Ok(3i16.to_be_bytes().to_vec()),
                arch: 1,
            },
            Case {
                value: Value::Uint16(4),
                expected: Ok(4i16.to_be_bytes().to_vec()),
                arch: 1,
            },
            Case {
                value: Value::Int32(5),
                expected: Ok(5i32.to_be_bytes().to_vec()),
                arch: 1,
            },
            Case {
                value: Value::Uint32(6),
                expected: Ok(6u32.to_be_bytes().to_vec()),
                arch: 1,
            },
            Case {
                value: Value::Int64(7),
                expected: Ok(7i64.to_be_bytes().to_vec()),
                arch: 1,
            },
            Case {
                value: Value::Uint64(8),
                expected: Ok(8u64.to_be_bytes().to_vec()),
                arch: 1,
            },
            Case {
                value: Value::Float32(9.0),
                expected: Ok(9.0f32.to_be_bytes().to_vec()),
                arch: 1,
            },
            Case {
                value: Value::Float64(10.0),
                expected: Ok(10.0f64.to_be_bytes().to_vec()),
                arch: 1,
            },
            Case {
                value: Value::VecInt8(vec![1, 1]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(1u8.to_be_bytes());
                    v.extend(1i8.to_be_bytes());
                    v
                }),
                arch: 1,
            },
            Case {
                value: Value::VecUint8(vec![2, 2]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(2u8.to_be_bytes());
                    v.extend(2u8.to_be_bytes());
                    v
                }),
                arch: 1,
            },
            Case {
                value: Value::VecInt16(vec![3, 3]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(3i16.to_be_bytes());
                    v.extend(3i16.to_be_bytes());
                    v
                }),
                arch: 1,
            },
            Case {
                value: Value::VecUint16(vec![4, 4]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(4u16.to_be_bytes());
                    v.extend(4u16.to_be_bytes());
                    v
                }),
                arch: 1,
            },
            Case {
                value: Value::VecInt32(vec![5, 5]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(5i32.to_be_bytes());
                    v.extend(5i32.to_be_bytes());
                    v
                }),
                arch: 1,
            },
            Case {
                value: Value::VecUint32(vec![6, 6]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(6u32.to_be_bytes());
                    v.extend(6u32.to_be_bytes());
                    v
                }),
                arch: 1,
            },
            Case {
                value: Value::VecInt64(vec![7, 7]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(7i64.to_be_bytes());
                    v.extend(7i64.to_be_bytes());
                    v
                }),
                arch: 1,
            },
            Case {
                value: Value::VecUint64(vec![8, 8]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(8u64.to_be_bytes());
                    v.extend(8u64.to_be_bytes());
                    v
                }),
                arch: 1,
            },
            Case {
                value: Value::VecFloat32(vec![9.0, 9.0]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(9.0f32.to_be_bytes());
                    v.extend(9.0f32.to_be_bytes());
                    v
                }),
                arch: 1,
            },
            Case {
                value: Value::VecFloat64(vec![10.0, 10.0]),
                expected: Ok({
                    let mut v: Vec<u8> = Vec::new();
                    v.extend(10.0f64.to_be_bytes());
                    v.extend(10.0f64.to_be_bytes());
                    v
                }),
                arch: 1,
            },
            Case {
                value: Value::Invalid,
                expected: Err(Error::InvalidValue),
                arch: 0,
            },
        ];

        let mut got_ok: Vec<u8> = Vec::new();
        for tc in tt {
            got_ok.clear();
            let res = tc.value.marshal_append(&mut got_ok, tc.arch);
            match tc.expected {
                Ok(expected_ok) => match res {
                    Ok(()) => assert_eq!(expected_ok, got_ok, "input: {:?}", tc.value),
                    Err(got_err) => assert!(
                        false,
                        "expected ok, got err: {:?}, input: {:?}",
                        got_err, tc.value
                    ),
                },
                Err(expected_err) => match res {
                    Ok(()) => assert!(
                        false,
                        "expected err: {:?}, got ok: {:?}, input: {:?}",
                        expected_err, got_ok, tc.value
                    ),
                    Err(got_err) => assert_eq!(expected_err, got_err, "input: {:?}", tc.value),
                },
            };
        }
    }
}