fit-encoder 0.1.1

Write FIT activity files (the Flexible and Interoperable Data Transfer format) as a stream: file header first, CRC last, sizes known in advance. no_std, no allocation. Independent; not affiliated with Garmin
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
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
use core::fmt;

use crate::crc::Crc;
use crate::developer::{Extra, KindId};
use crate::messages::{
    data_len, kept, record_fields, Activity, DeviceInfo, Event, FieldDef, FieldError, FieldOut,
    Fields, FileId, Lap, Mask, Message, Put, Record, RecordFields, Session, RECORD_GLOBAL,
    RECORD_TIMESTAMP,
};
use crate::types::Timestamp;
use extra::Extras;

const HEADER_LEN: u8 = 14;
/// The header and the file CRC: what a file holds besides its messages.
const FRAMING: u32 = HEADER_LEN as u32 + 2;
/// The most bytes of messages a file can hold: its length must fit the header's u32.
const LIMIT: u32 = u32::MAX - FRAMING;
const PROTOCOL_VERSION: u8 = 0x20;

/// Where a file's bytes go. With the `embedded-io` feature, `EmbeddedIo` makes one of an
/// `embedded_io::Write`.
pub trait Sink {
    /// Why a write failed.
    type Error;

    /// The whole file's length, for a sink that announces it, such as a transfer over a radio
    /// link. Only [`write()`] knows it in advance and calls this, once, before the first byte;
    /// [`OnePass`] never does.
    ///
    /// # Errors
    ///
    /// Whatever stops the sink taking a file of that length.
    fn begin(&mut self, _file_size: u32) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Writes all of `bytes`, or fails.
    ///
    /// # Errors
    ///
    /// Whatever the sink cannot write.
    fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error>;
}

impl<S: Sink + ?Sized> Sink for &mut S {
    type Error = S::Error;

    fn begin(&mut self, file_size: u32) -> Result<(), S::Error> {
        (**self).begin(file_size)
    }

    fn write(&mut self, bytes: &[u8]) -> Result<(), S::Error> {
        (**self).write(bytes)
    }
}

/// A [`Sink`] that can overwrite bytes it already took, for [`OnePass`]: a file, or memory.
pub trait PatchSink: Sink {
    /// Overwrites the bytes starting `back` bytes before the end of what was written. A call
    /// that would reach before the start or past the end must change nothing, and fails if
    /// the sink's error can say so; [`OnePass`] never makes one.
    ///
    /// # Errors
    ///
    /// Whatever stops the sink rewriting them.
    fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), Self::Error>;
}

impl<S: PatchSink + ?Sized> PatchSink for &mut S {
    fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), S::Error> {
        (**self).patch(back, bytes)
    }
}

/// A closure as a [`Sink`].
///
/// ```
/// use fit_encoder::{FnSink, Sink};
///
/// let mut seen = 0;
/// let mut sink = FnSink(|bytes: &[u8]| -> Result<(), ()> {
///     seen += bytes.len();
///     Ok(())
/// });
/// sink.write(b"abc").unwrap();
/// drop(sink);
/// assert_eq!(seen, 3);
/// ```
pub struct FnSink<F>(pub F);

impl<F> fmt::Debug for FnSink<F> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("FnSink").finish_non_exhaustive()
    }
}

impl<F: FnMut(&[u8]) -> Result<(), E>, E> Sink for FnSink<F> {
    type Error = E;

    fn write(&mut self, bytes: &[u8]) -> Result<(), E> {
        (self.0)(bytes)
    }
}

/// A [`Sink`] into a byte slice.
#[derive(Debug)]
pub struct SliceSink<'a> {
    buf: &'a mut [u8],
    len: usize,
}

/// A [`SliceSink`] had no room for the file, or was asked to patch outside what it holds.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Full;

impl fmt::Display for Full {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("no room in the slice, or a patch outside what it holds")
    }
}

impl core::error::Error for Full {}

impl<'a> SliceSink<'a> {
    /// Writes into `buf` from its start.
    pub fn new(buf: &'a mut [u8]) -> Self {
        Self { buf, len: 0 }
    }

    /// The bytes written so far.
    #[must_use]
    pub fn written(&self) -> &[u8] {
        self.buf.get(..self.len).unwrap_or(&[])
    }
}

impl Sink for SliceSink<'_> {
    type Error = Full;

    fn begin(&mut self, file_size: u32) -> Result<(), Full> {
        let room = self.buf.len().saturating_sub(self.len);
        if usize::try_from(file_size).map_or(true, |n| n > room) {
            return Err(Full);
        }
        Ok(())
    }

    fn write(&mut self, bytes: &[u8]) -> Result<(), Full> {
        let end = self.len.checked_add(bytes.len()).ok_or(Full)?;
        let dst = self.buf.get_mut(self.len..end).ok_or(Full)?;
        dst.copy_from_slice(bytes);
        self.len = end;
        Ok(())
    }
}

impl PatchSink for SliceSink<'_> {
    fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), Full> {
        let start = usize::try_from(back).ok().and_then(|b| self.len.checked_sub(b)).ok_or(Full)?;
        let end = start.checked_add(bytes.len()).filter(|&e| e <= self.len).ok_or(Full)?;
        self.buf.get_mut(start..end).ok_or(Full)?.copy_from_slice(bytes);
        Ok(())
    }
}

/// A `std::io::Write` as a [`Sink`], and with `Seek` a [`PatchSink`].
#[cfg(feature = "std")]
#[derive(Debug)]
pub struct IoSink<W>(pub W);

#[cfg(feature = "std")]
impl<W: std::io::Write> Sink for IoSink<W> {
    type Error = std::io::Error;

    fn write(&mut self, bytes: &[u8]) -> std::io::Result<()> {
        self.0.write_all(bytes)
    }
}

#[cfg(feature = "std")]
impl<W: std::io::Write + std::io::Seek> PatchSink for IoSink<W> {
    fn patch(&mut self, back: u32, bytes: &[u8]) -> std::io::Result<()> {
        use std::io::{Error, ErrorKind, SeekFrom};
        let len = u32::try_from(bytes.len())
            .ok()
            .filter(|&n| n <= back)
            .ok_or_else(|| Error::from(ErrorKind::InvalidInput))?;
        let start = self.0.seek(SeekFrom::Current(0i64.saturating_sub(i64::from(back))))?;
        self.0.write_all(bytes)?;
        // A file opened to append writes at its end whatever the position.
        if self.0.stream_position()? != start.saturating_add(u64::from(len)) {
            return Err(Error::from(ErrorKind::Unsupported));
        }
        self.0.seek(SeekFrom::Current(i64::from(back.saturating_sub(len))))?;
        Ok(())
    }
}

/// A [`PatchSink`] that appends to a `Vec<u8>`; for a whole file at once, [`to_vec`] is
/// shorter.
///
/// ```
/// use fit_encoder::*;
///
/// let t = Timestamp::FIRST_DATE;
/// let mut file = OnePass::new(VecSink::default(), Options::new()).unwrap();
/// let mut w = file.writer();
/// w.start(t, &Device::new(Manufacturer::DEVELOPMENT, 1)).unwrap();
/// w.session(t, Sport::RUNNING, SubSport::GENERIC).unwrap();
/// w.record(&Record::new(t).heart_rate(60)).unwrap();
/// w.end(t).unwrap();
/// let VecSink(bytes) = file.finish().unwrap();
/// assert_eq!(&bytes[8..12], b".FIT");
/// ```
#[cfg(feature = "alloc")]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct VecSink(pub alloc::vec::Vec<u8>);

#[cfg(feature = "alloc")]
impl Sink for VecSink {
    type Error = core::convert::Infallible;

    fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
        self.0.extend_from_slice(bytes);
        Ok(())
    }
}

#[cfg(feature = "alloc")]
impl PatchSink for VecSink {
    fn patch(&mut self, back: u32, bytes: &[u8]) -> Result<(), Self::Error> {
        let len = self.0.len();
        let start = usize::try_from(back).ok().and_then(|b| len.checked_sub(b));
        let end = start.and_then(|s| s.checked_add(bytes.len())).filter(|&e| e <= len);
        if let Some(dst) = start.zip(end).and_then(|(s, e)| self.0.get_mut(s..e)) {
            dst.copy_from_slice(bytes);
        }
        Ok(())
    }
}

/// Why a message was not written.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
    /// The sink failed; [`write()`] returns its error. Nothing more can be written.
    Sink,
    /// The source wrote different messages the second time from those the first pass sized
    /// the file for. Nothing of the message was written.
    SourceChanged,
    /// The file would be 4 GiB or more, counting the bytes kept for the activity's end.
    /// Nothing was written.
    TooLarge,
    /// A string is too long for its field. Nothing of the message was written.
    StringTooLong,
    /// A value does not fit its field, or is the value FIT reserves for "none", such as a
    /// heart rate of 255, or a string holds a NUL; a time past [`DURATION_SECONDS_MAX`] or a
    /// distance past [`DISTANCE_METERS_MAX`]; or a leg [`Leg::check`](crate::Leg::check)
    /// refuses. Nothing of the message was written.
    OutOfRange,
    /// A lap, session, length, set or sensor past its limit, such as [`LAPS_MAX`]: its index
    /// has no value left for it.
    IndexFull,
    /// A call the activity is not ready for: anything before [`Writer::start`] or after
    /// [`Writer::end`], a record, lap, set, rest, pause or resume before the first session, a
    /// pause while paused, a resume while running, an end with no session, a length outside a
    /// pool swim, a set outside a training or HIIT session, a rest outside those and pool swims,
    /// a length or set during a rest, a lap during a rest in a pool swim, a rest during a rest,
    /// an end of a rest outside one, or a first leg moved to by hand. Nothing was written.
    OutOfOrder,
    /// A time before one already written. Nothing was written.
    TimeWentBack,
    /// A record, length or set while the timer is paused. Nothing was written.
    Paused,
    /// A total distance less than one already written. Nothing was written.
    DistanceWentBack,
    /// The source returned without [`Writer::end`], so the file has no activity.
    Unfinished,
    /// A record's distance, speed or cadence in a pool swim, whose lengths give them. Nothing
    /// was written.
    GivenByLengths,
    /// A developer or field this file did not declare: one from another file, or one the
    /// second pass did not declare again. Nothing was written.
    Undeclared,
    /// A developer, field or value given twice where it may appear once. Nothing was written.
    Duplicate,
    /// A raw message or field the encoder writes itself, or another form of one; see
    /// [`Writer::raw_message`] and [`Writer::record_with`]. Nothing was written.
    Reserved,
    /// More developers or fields than the encoder holds; see
    /// [`DEVELOPERS_MAX`](crate::DEVELOPERS_MAX) and its neighbours. Nothing was written.
    TooMany,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Sink => "the sink failed",
            Self::SourceChanged => "the source wrote different messages on the second pass",
            Self::TooLarge => "the file would be 4 GiB or more",
            Self::StringTooLong => "string longer than its field",
            Self::OutOfRange => "value out of its field's range",
            Self::IndexFull => "no message_index left for another lap or session",
            Self::OutOfOrder => "the activity is not ready for that call",
            Self::TimeWentBack => "a time before one already written",
            Self::Paused => "a record, length or set while the timer is paused",
            Self::DistanceWentBack => "a total distance less than one already written",
            Self::Unfinished => "the activity was not ended",
            Self::GivenByLengths => "a distance, speed or cadence that a pool swim's lengths give",
            Self::Undeclared => "a developer or field this file did not declare",
            Self::Duplicate => "given twice",
            Self::Reserved => "a message or field the encoder writes itself",
            Self::TooMany => "more developers or fields than the encoder holds",
        })
    }
}

impl core::error::Error for Error {}

/// Why [`write()`] failed. The sink may hold part of a file.
///
/// As an error, `Sink` says the sink failed and gives the sink's error as its source, and
/// `Source` stands for the source's error itself, so a report of the chain names each cause
/// once. A sink error that is not an `Error` is only in the variant.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WriteError<S, E> {
    /// The sink's own error.
    Sink(S),
    /// The source's error, or an encoder [`Error`] the source passed on.
    Source(E),
}

impl<S, E: fmt::Display> fmt::Display for WriteError<S, E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Sink(_) => f.write_str("the sink failed"),
            Self::Source(e) => e.fmt(f),
        }
    }
}

impl<S, E> core::error::Error for WriteError<S, E>
where
    S: core::error::Error + 'static,
    E: core::error::Error + 'static,
{
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::Sink(e) => Some(e),
            Self::Source(e) => e.source(),
        }
    }
}

/// How a file is written.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Options {
    compressed_timestamps: bool,
    profile_version: u16,
    utc_offset: Option<i32>,
    auto_multisport: bool,
}

impl Options {
    /// Normal record headers, profile version 21.00, no time zone, sessions started by hand.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            compressed_timestamps: false,
            profile_version: 2100,
            utc_offset: None,
            auto_multisport: false,
        }
    }

    /// Whether a multisport profile moved the activity from each session to the next, as a
    /// watch's triathlon mode does, rather than its user. The activity's `type` and each
    /// session's `trigger` say which; the last session's trigger is the activity's end.
    #[must_use]
    pub const fn auto_multisport(mut self, on: bool) -> Self {
        self.auto_multisport = on;
        self
    }

    /// Whether records less than 32 s after the previous timestamp put their time in the
    /// record header (FIT Protocol page, "Compressed Timestamp Header"). Off by default, as
    /// some readers refuse such headers.
    #[must_use]
    pub const fn compressed_timestamps(mut self, on: bool) -> Self {
        self.compressed_timestamps = on;
        self
    }

    /// The local time zone's offset from UTC in seconds, so readers can show the activity's
    /// local times. One that takes the end's local time out of range is refused.
    #[must_use]
    pub const fn utc_offset(mut self, seconds: i32) -> Self {
        self.utc_offset = Some(seconds);
        self
    }

    /// The profile version the header claims, as the header holds it: 2100 is 21.00.
    #[must_use]
    pub const fn profile_version(mut self, version: u16) -> Self {
        self.profile_version = version;
        self
    }
}

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

/// The whole file's length in bytes, from a pass over `source` that writes nothing.
///
/// # Errors
///
/// The source's error, or [`Error::TooLarge`].
pub fn size<E, F>(options: Options, mut source: F) -> Result<u32, E>
where
    E: From<Error>,
    F: FnMut(&mut Writer<'_>) -> Result<(), E>,
{
    Ok(plan(options, &mut source, true)?.file_size)
}

/// Writes the file `source` describes to `sink`, header first and CRC last, without seeking.
///
/// The header holds the length of what follows, so `source` runs twice: once to size the file,
/// then to write it. It must write the same messages both times, as a source reading a stored
/// log does; if it does not, the second pass fails with [`Error::SourceChanged`].
///
/// ```
/// use fit_encoder::*;
///
/// let start = Timestamp::from_unix(1_764_547_200).unwrap();
/// let watch = Device::new(Manufacturer::DEVELOPMENT, 1).product_name("My watch");
/// let mut buf = [0u8; 2048];
/// let sink = write(SliceSink::new(&mut buf), Options::new(), |w| -> Result<(), Error> {
///     w.start(start, &watch)?;
///     w.session(start, Sport::RUNNING, SubSport::TREADMILL)?;
///     for s in 0..60 {
///         w.record(&Record::new(start.checked_add(s).unwrap()).heart_rate(140))?;
///     }
///     w.end(start.checked_add(60).unwrap())
/// })
/// .unwrap();
/// assert_eq!(&sink.written()[8..12], b".FIT");
/// ```
///
/// # Errors
///
/// [`WriteError::Sink`] with the sink's error, or [`WriteError::Source`] with the source's,
/// which includes the [`Error`]s it passed on.
pub fn write<S, E, F>(sink: S, options: Options, source: F) -> Result<S, WriteError<S::Error, E>>
where
    S: Sink,
    E: From<Error>,
    F: FnMut(&mut Writer<'_>) -> Result<(), E>,
{
    write_with(sink, options, source, true)
}

/// [`write()`], with or without an activity ended.
fn write_with<S, E, F>(
    sink: S,
    options: Options,
    mut source: F,
    require_end: bool,
) -> Result<S, WriteError<S::Error, E>>
where
    S: Sink,
    E: From<Error>,
    F: FnMut(&mut Writer<'_>) -> Result<(), E>,
{
    let plan = plan(options, &mut source, require_end).map_err(WriteError::Source)?;
    let mut out = SinkOut { sink, error: None };
    out.sink.begin(plan.file_size).map_err(WriteError::Sink)?;
    let header = header(options, plan.data_size);
    out.sink.write(&header).map_err(WriteError::Sink)?;

    let mut st = State::new(options, Some(plan));
    st.require_end = require_end;
    let result = source(&mut Writer { out: &mut out, st: &mut st });
    let end = Writer { out: &mut out, st: &mut st }.close();
    if let Some(e) = out.error.take() {
        return Err(WriteError::Sink(e));
    }
    result.map_err(WriteError::Source)?;
    end.map_err(|e| WriteError::Source(E::from(e)))?;
    out.sink.write(&file_crc(&header, &st)).map_err(WriteError::Sink)?;
    Ok(out.sink)
}

/// Writes a file as its messages arrive, in one pass: the header goes first with no length,
/// and [`OnePass::finish`] patches the length in. For sources that cannot run twice, such as a
/// live recording or a conversion read once; the bytes are those [`write()`] would write.
///
/// ```
/// use fit_encoder::*;
///
/// let start = Timestamp::from_unix(1_764_547_200).unwrap();
/// let mut buf = [0u8; 2048];
/// let mut file = OnePass::new(SliceSink::new(&mut buf), Options::new()).unwrap();
/// let mut w = file.writer();
/// w.start(start, &Device::new(Manufacturer::DEVELOPMENT, 1)).unwrap();
/// w.session(start, Sport::WALKING, SubSport::GENERIC).unwrap();
/// for s in 0..10 {
///     w.record(&Record::new(start.checked_add(s).unwrap()).heart_rate(100)).unwrap();
/// }
/// w.end(start.checked_add(10).unwrap()).unwrap();
/// let sink = file.finish().unwrap();
/// assert_eq!(&sink.written()[8..12], b".FIT");
/// ```
pub struct OnePass<S: PatchSink> {
    out: SinkOut<S>,
    st: State,
}

impl<S: PatchSink> fmt::Debug for OnePass<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OnePass").field("written", &self.st.written).finish_non_exhaustive()
    }
}

impl<S: PatchSink> OnePass<S> {
    /// Writes the header, its length to come.
    ///
    /// # Errors
    ///
    /// The sink's.
    pub fn new(mut sink: S, options: Options) -> Result<Self, S::Error> {
        sink.write(&header(options, 0))?;
        Ok(Self { out: SinkOut { sink, error: None }, st: State::new(options, None) })
    }

    /// The writer for the next messages.
    pub fn writer(&mut self) -> Writer<'_> {
        Writer { out: &mut self.out, st: &mut self.st }
    }

    /// Patches the header's length in and writes the file CRC. On failure the file comes back
    /// with the error, so an activity not yet ended can be ended and finished again; after a
    /// sink error, finishing fails again.
    ///
    /// # Errors
    ///
    /// [`WriteError::Sink`] with the sink's error, including one a message met, or
    /// [`WriteError::Source`] with [`Error::Unfinished`] if the activity was not ended.
    #[allow(clippy::result_large_err, reason = "the error holds the file, to finish again")]
    pub fn finish(mut self) -> Result<S, FinishError<Self, S::Error>> {
        match self.try_finish() {
            Ok(()) => Ok(self.out.sink),
            Err(error) => Err(FinishError { error, file: self }),
        }
    }

    /// The sink, giving up on the file: its header still claims no messages, so readers
    /// refuse it.
    pub fn into_sink(self) -> S {
        self.out.sink
    }

    fn try_finish(&mut self) -> Result<(), WriteError<S::Error, Error>> {
        let ended = Writer { out: &mut self.out, st: &mut self.st }.close();
        if let Some(e) = self.out.error.take() {
            return Err(WriteError::Sink(e));
        }
        ended.map_err(WriteError::Source)?;
        let (header, back, crc) = self.st.trailer().map_err(WriteError::Source)?;
        // The CRC goes first, so a file it fails on keeps a header claiming no messages.
        let written = self.out.sink.write(&crc).and_then(|()| self.out.sink.patch(back, &header));
        written.map_err(|e| {
            self.st.failed = true;
            WriteError::Sink(e)
        })
    }
}

/// Finishing failed, with the sink's error type `E`; the file `F` is here to end and finish
/// again, or to give up on.
pub struct FinishError<F, E> {
    error: WriteError<E, Error>,
    file: F,
}

impl<F, E> FinishError<F, E> {
    /// Why it failed.
    pub const fn error(&self) -> &WriteError<E, Error> {
        &self.error
    }

    /// The file, as it was.
    pub fn into_inner(self) -> F {
        self.file
    }

    /// Why it failed, and the file.
    pub fn into_parts(self) -> (WriteError<E, Error>, F) {
        (self.error, self.file)
    }
}

impl<F, E: fmt::Debug> fmt::Debug for FinishError<F, E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FinishError").field("error", &self.error).finish_non_exhaustive()
    }
}

impl<F, E> fmt::Display for FinishError<F, E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.error.fmt(f)
    }
}

impl<F, E: core::error::Error + 'static> core::error::Error for FinishError<F, E> {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        self.error.source()
    }
}

/// The file `source` describes, in memory, in one pass.
///
/// # Errors
///
/// The source's error, or an encoder [`Error`] it passed on.
#[cfg(feature = "alloc")]
pub fn to_vec<E, F>(options: Options, source: F) -> Result<alloc::vec::Vec<u8>, E>
where
    E: From<Error>,
    F: FnOnce(&mut Writer<'_>) -> Result<(), E>,
{
    let Ok(mut file) = OnePass::new(VecSink::default(), options);
    source(&mut file.writer())?;
    match file.finish().map_err(FinishError::into_parts) {
        Ok(VecSink(bytes)) => Ok(bytes),
        Err((WriteError::Source(e), _)) => Err(E::from(e)),
        Err((WriteError::Sink(never), _)) => match never {},
    }
}

/// What the first pass learned.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Plan {
    data_size: u32,
    file_size: u32,
    data_crc: u16,
}

fn plan<E, F>(options: Options, source: &mut F, require_end: bool) -> Result<Plan, E>
where
    E: From<Error>,
    F: FnMut(&mut Writer<'_>) -> Result<(), E>,
{
    let mut st = State::new(options, None);
    st.require_end = require_end;
    source(&mut Writer { out: &mut Counter, st: &mut st })?;
    Ok(st.plan()?)
}

fn file_crc(header: &[u8], st: &State) -> [u8; 2] {
    let mut crc = Crc::new();
    crc.update(header);
    crc.then(st.data_crc, st.written).value().to_le_bytes()
}

fn header(options: Options, data_size: u32) -> [u8; HEADER_LEN as usize] {
    let mut h = [0u8; HEADER_LEN as usize];
    let [h0, h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11, h12, h13] = &mut h;
    *h0 = HEADER_LEN;
    *h1 = PROTOCOL_VERSION;
    [*h2, *h3] = options.profile_version.to_le_bytes();
    [*h4, *h5, *h6, *h7] = data_size.to_le_bytes();
    [*h8, *h9, *h10, *h11] = *b".FIT";
    let mut crc = Crc::new();
    crc.update(&[*h0, *h1, *h2, *h3, *h4, *h5, *h6, *h7, *h8, *h9, *h10, *h11]);
    [*h12, *h13] = crc.value().to_le_bytes();
    h
}

trait Out {
    /// Whether the bytes were written.
    fn write(&mut self, bytes: &[u8]) -> bool;

    /// Whether a call may go on to write `size` more bytes. Every call asks before it writes
    /// or changes anything, so one refused can be made again elsewhere.
    fn fits(&mut self, _size: u32) -> bool {
        true
    }
}

struct Counter;

impl Out for Counter {
    fn write(&mut self, _: &[u8]) -> bool {
        true
    }
}

struct SinkOut<S: Sink> {
    sink: S,
    error: Option<S::Error>,
}

impl<S: Sink> Out for SinkOut<S> {
    fn write(&mut self, bytes: &[u8]) -> bool {
        match self.sink.write(bytes) {
            Ok(()) => true,
            Err(e) => {
                self.error = Some(e);
                false
            }
        }
    }
}

/// A local message type's layout: which global message, with which fields.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Layout {
    global: u16,
    shape: Shape,
    /// Raw fields, after the modelled ones.
    raw: extra::RawDefs,
    /// The developer fields, by their places among the file's.
    dev: u32,
}

/// The fields of a layout that the crate models.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Shape {
    Message { fields: &'static [FieldDef], keep: Mask },
    Record { fields: RecordFields, compressed: bool },
}

/// The local message types and the layout each holds; records take 0 to 3, which compressed
/// timestamp headers can name.
#[derive(Clone, Debug)]
struct Locals {
    held: [Option<(Layout, u32)>; 16],
    clock: u32,
}

impl Locals {
    const fn new() -> Self {
        Self { held: [None; 16], clock: 0 }
    }

    /// The local type for `layout`, and whether it needs a definition first.
    fn find(&self, layout: Layout) -> (u8, bool) {
        let (first, group) = match layout.shape {
            Shape::Record { .. } => (0u8, self.held.get(..4)),
            Shape::Message { .. } => (4u8, self.held.get(4..)),
        };
        let group = group.unwrap_or(&[]);
        let local = |i: usize| first.saturating_add(u8::try_from(i).unwrap_or(u8::MAX));
        if let Some(i) = group.iter().position(|h| h.is_some_and(|(l, _)| l == layout)) {
            return (local(i), false);
        }
        if let Some(i) = group.iter().position(Option::is_none) {
            return (local(i), true);
        }
        let oldest = group
            .iter()
            .enumerate()
            .min_by_key(|(_, h)| h.map_or(0, |(_, used)| used))
            .map_or(0, |(i, _)| i);
        (local(oldest), true)
    }

    fn hold(&mut self, local: u8, layout: Layout) {
        self.clock = self.clock.wrapping_add(1);
        if let Some(h) = self.held.get_mut(usize::from(local)) {
            *h = Some((layout, self.clock));
        }
    }
}

/// The layout of a message with a fixed table, all its fields kept.
const fn fixed_layout<M: Message>() -> Layout {
    let shape = Shape::Message { fields: M::FIELDS, keep: Mask::ALL };
    Layout { global: M::GLOBAL, shape, raw: extra::RawDefs::NONE, dev: 0 }
}

/// How a data message's header names its time.
#[derive(Clone, Copy)]
enum Header {
    Normal,
    /// A compressed timestamp header, with the time's low five bits.
    Compressed(u8),
}

/// How a data message would be written.
#[derive(Clone, Copy)]
pub(crate) struct Planned {
    layout: Layout,
    keep: Mask,
    local: u8,
    count: u8,
    /// The definition's bytes, 0 when its layout is held already.
    definition: u32,
    /// The data message's bytes, with its header.
    body: u32,
}

impl Planned {
    /// Its bytes, with the definition it needs.
    pub(crate) const fn size(&self) -> u32 {
        self.definition.saturating_add(self.body)
    }

    /// Its bytes when written straight after `before`, whose definition may take its local
    /// type.
    pub(crate) fn after(&self, before: &Self) -> u32 {
        if before.definition > 0 && before.local == self.local && self.definition == 0 {
            self.definition_len().saturating_add(self.body)
        } else {
            self.size()
        }
    }

    fn definition_len(&self) -> u32 {
        definition_len(u32::from(self.count), self.layout.dev.count_ones())
    }
}

/// A definition's bytes: its header, three for each field, and with developer fields, their
/// count and three for each.
const fn definition_len(fields: u32, dev_fields: u32) -> u32 {
    let dev = match dev_fields {
        0 => 0,
        n => n.saturating_mul(3).saturating_add(1),
    };
    fields.saturating_mul(3).saturating_add(6).saturating_add(dev)
}

const STAGE: usize = 32;

/// What a file's writing has come to: its bytes, layouts and counts so far.
#[derive(Clone)]
struct State {
    options: Options,
    plan: Option<Plan>,
    stage: [u8; STAGE],
    staged: usize,
    data_crc: Crc,
    written: u32,
    locals: Locals,
    last_timestamp: Option<Timestamp>,
    laps: u16,
    sessions: u16,
    failed: bool,
    act: activity::Act,
    require_end: bool,
    dev: extra::DevTable,
}

impl State {
    fn new(options: Options, plan: Option<Plan>) -> Self {
        Self {
            options,
            plan,
            stage: [0; STAGE],
            staged: 0,
            data_crc: Crc::new(),
            written: 0,
            locals: Locals::new(),
            last_timestamp: None,
            laps: 0,
            sessions: 0,
            failed: false,
            act: activity::Act::new(),
            require_end: true,
            dev: extra::DevTable::new(),
        }
    }

    /// What a sizing pass that has run its source learned.
    fn plan(mut self) -> Result<Plan, Error> {
        Writer { out: &mut Counter, st: &mut self }.close()?;
        let file_size = self.written.checked_add(FRAMING).ok_or(Error::TooLarge)?;
        Ok(Plan { data_size: self.written, file_size, data_crc: self.data_crc.value() })
    }

    /// A one-pass file's ending: its header, how far back from the end of the file that
    /// starts once the CRC is written, and the CRC.
    fn trailer(&self) -> Result<([u8; HEADER_LEN as usize], u32, [u8; 2]), Error> {
        let header = header(self.options, self.written);
        let back = self.written.checked_add(FRAMING).ok_or(Error::TooLarge)?;
        let crc = file_crc(&header, self);
        Ok((header, back, crc))
    }
}

/// Writes the messages of one file, in order. [`write()`] and [`size()`] hand one to the
/// source; [`OnePass::writer`] gives one too, so a function taking a `&mut Writer` serves both.
pub struct Writer<'a> {
    out: &'a mut dyn Out,
    st: &'a mut State,
}

impl fmt::Debug for Writer<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Writer").field("written", &self.st.written).finish_non_exhaustive()
    }
}

impl Writer<'_> {
    /// Writes a `file_id`, which belongs first.
    pub(crate) fn raw_file_id(&mut self, msg: &FileId) -> Result<(), Error> {
        self.fixed(msg, 0)
    }

    pub(crate) fn raw_device_info(&mut self, msg: &DeviceInfo<'_>) -> Result<(), Error> {
        self.fixed(msg, 0)
    }

    pub(crate) fn raw_event(&mut self, msg: Event) -> Result<(), Error> {
        self.fixed(&msg, 0)
    }

    #[cfg(test)]
    pub(crate) fn raw_record(&mut self, msg: Record) -> Result<(), Error> {
        self.raw_record_with(msg, &[])
    }

    fn raw_record_with(&mut self, msg: Record, extras: &[Extra<'_>]) -> Result<(), Error> {
        let (layout, defs, header, compressed) = self.record_parts(&msg);
        let t = msg.timestamp;
        self.message(layout, defs, header, Some(t), Extras::Values(extras), |out| {
            if !compressed {
                out.u32(t.fit());
            }
            msg.encode(out);
        })
    }

    /// The bytes `msg` would take as the next record.
    pub(crate) fn record_cost(&self, msg: &Record, extras: &[Extra<'_>]) -> Result<u32, Error> {
        let (layout, defs, _, compressed) = self.record_parts(msg);
        let t = msg.timestamp;
        let planned =
            self.plan(layout, defs, Extras::Values(extras), &|out: &mut dyn FieldOut| {
                if !compressed {
                    out.u32(t.fit());
                }
                msg.encode(out);
            })?;
        Ok(planned.size())
    }

    /// A record's layout, fields and header, and whether its time is in the header.
    fn record_parts(
        &self,
        msg: &Record,
    ) -> (Layout, impl Iterator<Item = FieldDef> + Clone, Header, bool) {
        let t = msg.timestamp;
        let compressed = self.st.options.compressed_timestamps
            && self
                .st
                .last_timestamp
                .and_then(|last| t.fit().checked_sub(last.fit()))
                .is_some_and(|gap| gap < 32);
        let shape = Shape::Record { fields: msg.fields(), compressed };
        let layout = Layout { global: RECORD_GLOBAL, shape, raw: extra::RawDefs::NONE, dev: 0 };
        let defs = core::iter::once(RECORD_TIMESTAMP)
            .filter(move |_| !compressed)
            .chain(record_fields(msg.fields()));
        let header = if compressed {
            #[allow(clippy::cast_possible_truncation)]
            Header::Compressed((t.fit() & 0x1F) as u8)
        } else {
            Header::Normal
        };
        (layout, defs, header, compressed)
    }

    /// Writes a `lap`, numbered after the laps before it.
    pub(crate) fn raw_lap(&mut self, msg: &Lap) -> Result<(), Error> {
        self.fixed_with(msg, next_index(self.st.laps, LAPS_MAX)?, Extras::Staged(KindId::Lap))?;
        self.st.laps = self.st.laps.wrapping_add(1);
        self.st.dev.unstage(KindId::Lap);
        Ok(())
    }

    /// Writes a `session`, numbered after the sessions before it.
    pub(crate) fn raw_session(&mut self, msg: &Session) -> Result<(), Error> {
        let index = next_index(self.st.sessions, SESSIONS_MAX)?;
        self.fixed_with(msg, index, Extras::Staged(KindId::Session))?;
        self.st.sessions = self.st.sessions.wrapping_add(1);
        self.st.dev.unstage(KindId::Session);
        Ok(())
    }

    /// Writes the `activity`, which belongs last.
    pub(crate) fn raw_activity(&mut self, msg: &Activity) -> Result<(), Error> {
        self.fixed(msg, 0)
    }

    fn fixed<M: Message>(&mut self, msg: &M, index: u16) -> Result<(), Error> {
        self.fixed_with(msg, index, Extras::Values(&[]))
    }

    fn fixed_with<M: Message>(
        &mut self,
        msg: &M,
        index: u16,
        extras: Extras<'_>,
    ) -> Result<(), Error> {
        let (layout, defs) = (fixed_layout::<M>(), M::FIELDS.iter().copied());
        self.message(layout, defs, Header::Normal, msg.timestamp(), extras, |out| {
            msg.encode(out, index);
        })
    }

    /// What `msg` would take as the next message, as the first of its layout and as one after.
    pub(crate) fn cost<M: Message>(&self, msg: &M) -> Result<Planned, Error> {
        self.cost_with(msg, Extras::Values(&[]))
    }

    /// [`Writer::cost`], with the fields beyond its table that `extras` adds.
    fn cost_with<M: Message>(&self, msg: &M, extras: Extras<'_>) -> Result<Planned, Error> {
        let (layout, defs) = (fixed_layout::<M>(), M::FIELDS.iter().copied());
        self.plan(layout, defs, extras, &|out: &mut dyn FieldOut| msg.encode(out, 0))
    }

    /// How one data message would be written, refusing values it cannot hold; nothing is
    /// written.
    fn plan<I>(
        &self,
        mut layout: Layout,
        table: I,
        extras: Extras<'_>,
        encode: &dyn Fn(&mut dyn FieldOut),
    ) -> Result<Planned, Error>
    where
        I: Iterator<Item = FieldDef> + Clone,
    {
        let mut check = Fields::new(table.clone(), None);
        encode(&mut check);
        refusal(check.refused())?;
        // A message leaves out the fields it has no value for, so its layout says which.
        let keep = check.present();
        if let Shape::Message { keep: k, .. } = &mut layout.shape {
            *k = keep;
        }
        let defs = kept(table, keep);
        layout.raw = extra::raw_defs(extras)?;
        layout.dev = self.dev_fields(extras)?;
        let (local, define) = self.st.locals.find(layout);
        let count = defs.clone().count().saturating_add(layout.raw.defs().count());
        let count = u8::try_from(count).map_err(|_| Error::TooLarge)?;
        let planned = Planned { layout, keep, local, count, definition: 0, body: 0 };
        let definition = if define { planned.definition_len() } else { 0 };
        let body = data_len(defs)
            .saturating_add(data_len(layout.raw.defs()))
            .saturating_add(self.st.dev.size(layout.dev))
            .saturating_add(1);
        Ok(Planned { definition, body, ..planned })
    }

    /// Writes one data message; nothing is written unless all of it can be.
    fn message<I>(
        &mut self,
        layout: Layout,
        table: I,
        header: Header,
        timestamp: Option<Timestamp>,
        extras: Extras<'_>,
        encode: impl Fn(&mut dyn FieldOut),
    ) -> Result<(), Error>
    where
        I: Iterator<Item = FieldDef> + Clone,
    {
        if self.st.failed {
            return Err(Error::Sink);
        }
        let planned = self.plan(layout, table.clone(), extras, &encode)?;
        self.reserve(planned.size())?;
        let Planned { layout, keep, local, count, definition, .. } = planned;
        self.st.locals.hold(local, layout);

        if definition > 0 {
            let [g0, g1] = layout.global.to_le_bytes();
            let flag = if layout.dev == 0 { 0 } else { 0x20 };
            self.put(&[0x40 | flag | local, 0, 0, g0, g1, count]);
            for f in kept(table.clone(), keep).chain(layout.raw.defs()) {
                self.put(&[f.num, f.size, f.base]);
            }
            if layout.dev != 0 {
                self.put_dev_definitions(layout.dev);
            }
        }
        match header {
            Header::Normal => self.put(&[local]),
            Header::Compressed(low) => self.put(&[0x80 | local << 5 | low]),
        }
        let mut fields = Fields::new(table, Some(self)).keep(keep);
        encode(&mut fields);
        fields.finish();
        self.put_raw_fields(extras);
        self.put_dev_fields(extras, layout.dev);
        self.flush();
        if self.st.failed {
            return Err(Error::Sink);
        }
        if let Some(t) = timestamp {
            self.st.last_timestamp = Some(t);
        }
        Ok(())
    }

    fn reserve(&mut self, size: u32) -> Result<(), Error> {
        let end = self.room(size)?;
        if self.st.plan.is_some_and(|plan| end > plan.data_size) {
            return Err(Error::SourceChanged);
        }
        self.st.written = end;
        Ok(())
    }

    /// Where `size` more bytes would end, if they leave the activity room to end and the
    /// output takes them.
    fn room(&mut self, size: u32) -> Result<u32, Error> {
        let end = self.st.written.checked_add(size).ok_or(Error::TooLarge)?;
        match end.checked_add(self.st.act.kept_for_end()) {
            Some(n) if n <= LIMIT => {
                self.ahead(size)?;
                Ok(end)
            }
            _ => Err(Error::TooLarge),
        }
    }

    /// Refuses a call of `size` more bytes than the output takes.
    fn ahead(&mut self, size: u32) -> Result<(), Error> {
        if self.out.fits(size) {
            Ok(())
        } else {
            Err(Error::Sink)
        }
    }

    fn flush(&mut self) {
        if let Some(bytes) = self.st.stage.get(..self.st.staged) {
            if !self.st.failed && !bytes.is_empty() && !self.out.write(bytes) {
                self.st.failed = true;
            }
        }
        self.st.staged = 0;
    }

    /// Ends the messages, which must have ended an activity; on a second pass, checks they are
    /// what the first pass sized.
    fn close(&mut self) -> Result<(), Error> {
        self.flush();
        if self.st.failed {
            return Err(Error::Sink);
        }
        if self.st.require_end && !self.st.act.ended() {
            return Err(Error::Unfinished);
        }
        match self.st.plan {
            Some(plan)
                if plan.data_size != self.st.written
                    || plan.data_crc != self.st.data_crc.value() =>
            {
                Err(Error::SourceChanged)
            }
            _ => Ok(()),
        }
    }
}

impl Put for Writer<'_> {
    fn put(&mut self, bytes: &[u8]) {
        self.st.data_crc.update(bytes);
        for &byte in bytes {
            if let Some(slot) = self.st.stage.get_mut(self.st.staged) {
                *slot = byte;
                self.st.staged = self.st.staged.saturating_add(1);
            }
            if self.st.staged == STAGE {
                self.flush();
            }
        }
    }
}

/// Whether `msg` would be written, as far as its values go.
fn check<M: Message>(msg: &M) -> Result<(), Error> {
    let mut fields = Fields::new(M::FIELDS.iter().copied(), None);
    msg.encode(&mut fields, 0);
    refusal(fields.refused())
}

fn refusal(refused: Option<FieldError>) -> Result<(), Error> {
    match refused {
        Some(FieldError::StringTooLong) => Err(Error::StringTooLong),
        Some(FieldError::OutOfRange) => Err(Error::OutOfRange),
        None => Ok(()),
    }
}

/// A `message_index` is its low 12 bits; all 12 set is the profile's mask.
const INDEXES: u16 = 0x0FFF;

/// The most laps an activity holds. Each session ends with a lap of its own, so in an activity
/// of one session [`Writer::lap`], [`Writer::lap_by`] and a pool swim's rests end at most
/// `LAPS_MAX - 1`.
pub const LAPS_MAX: u16 = INDEXES;
/// The most sessions an activity holds.
pub const SESSIONS_MAX: u16 = INDEXES;
/// The most lengths an activity holds, idle lengths included: a rest in a pool swim ends with
/// one.
pub const LENGTHS_MAX: u16 = INDEXES;
/// The most sets an activity holds, rests included: a rest in a training session ends with
/// one.
pub const SETS_MAX: u16 = INDEXES;
/// The most sensors [`Writer::device`] writes: their indexes follow the creator's 0 and stop
/// before 255, FIT's "none".
pub const SENSORS_MAX: u8 = 254;
/// The longest a lap, session, length or set may last, and the activity's timer run, in
/// seconds: the most whole seconds FIT's milliseconds hold, about 49.7 days.
pub const DURATION_SECONDS_MAX: u32 = u32::MAX / 1000;
/// The farthest an activity may go, in metres to the centimetre: the most FIT's centimetres
/// hold.
#[allow(clippy::cast_lossless, reason = "f64::from is not const")]
pub const DISTANCE_METERS_MAX: f64 = DISTANCE_CM_MAX as f64 / 100.0;
const DISTANCE_CM_MAX: u32 = u32::MAX - 1;

/// The index of the message after `count`, of at most `max`.
fn next_index(count: u16, max: u16) -> Result<u16, Error> {
    if count >= max {
        Err(Error::IndexFull)
    } else {
        Ok(count)
    }
}

mod activity;
#[cfg(feature = "async")]
mod asynch;
#[cfg(any(feature = "embedded-io", feature = "embedded-io-async"))]
mod embedded_io;
mod extra;
#[cfg(test)]
mod tests;

#[cfg(feature = "async")]
pub use asynch::{
    write_async, AsyncOnePass, AsyncPatchSink, AsyncSink, AsyncWriter, ASYNC_WRITE_LEN,
};
#[cfg(any(feature = "embedded-io", feature = "embedded-io-async"))]
pub use embedded_io::{EmbeddedIo, EmbeddedIoError};