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
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
//! An activity as timed calls: the encoder writes the summaries, numbers and counts.

use super::{
    check, definition_len, next_index, Error, Extras, Planned, Writer, DISTANCE_CM_MAX,
    DURATION_SECONDS_MAX, LAPS_MAX, LENGTHS_MAX, SENSORS_MAX, SESSIONS_MAX, SETS_MAX,
};
#[allow(unused_imports, reason = "for the docs")]
use crate::developer::RecordField;
use crate::developer::{Extra, KindId, DEVELOPER_FIELDS_MAX, SUMMARY_BYTES_MAX};
use crate::messages::{
    lap_trigger, trigger, Activity, Altitude, Device, Distance, Event, FieldDef, FileId, Hrv, Lap,
    LapTrigger, Leg, Length, LengthMsg, Message, Pool, Record, Session, Set, SetMsg, Span,
    SportMsg, Totals, HRV_BEATS,
};
use crate::types::{FileType, Position, Sport, SubSport, SwimStroke, Timestamp};
#[allow(unused_imports, reason = "for the docs")]
use crate::{raw::RawField, raw::RAW_FIELDS_MAX};

/// The most bytes the end writes: what ending a session writes, any beat intervals waiting, a
/// stop event and the activity.
const END: u32 = CLOSE
    .saturating_add(most(Hrv::FIELDS))
    .saturating_add(most(Event::FIELDS))
    .saturating_add(most(Activity::FIELDS));

/// The most bytes a session ending another writes: what ends that one, and its own sport.
const SWITCH: u32 = CLOSE.saturating_add(most(SportMsg::FIELDS));

/// The most bytes ending a session writes: what ends its rest, its last lap and itself, and
/// their developer fields.
const CLOSE: u32 = REST
    .saturating_add(most(Lap::FIELDS))
    .saturating_add(most(Session::FIELDS))
    .saturating_add(DEV);

/// The most bytes developer fields add to a lap and a session: the file's fields split between
/// their definitions, each with its count of them, and every byte their values may take.
#[allow(clippy::cast_possible_truncation, reason = "both are small")]
const DEV: u32 = {
    let none = definition_len(0, 0);
    let split = definition_len(0, (DEVELOPER_FIELDS_MAX as u32).saturating_sub(1))
        .saturating_add(definition_len(0, 1))
        .saturating_sub(none)
        .saturating_sub(none);
    split.saturating_add(SUMMARY_BYTES_MAX as u32)
};

/// The most bytes ending a rest writes: an idle length or a rest set.
const REST: u32 = {
    let length = most_without(LengthMsg::FIELDS, LengthMsg::SWUM);
    let set = most_without(SetMsg::FIELDS, SetMsg::ACTIVE);
    // The larger of the two; `Ord::max` is not const.
    length.saturating_add(set.saturating_sub(length))
};

/// The most bytes a message of `fields` takes: its definition, its header and every field.
const fn most(fields: &[FieldDef]) -> u32 {
    most_without(fields, &[])
}

/// [`most`], leaving out the fields numbered in `without`.
const fn most_without(fields: &[FieldDef], without: &[u8]) -> u32 {
    let (count, data) = kept_sizes(fields, without);
    definition_len(count, 0).saturating_add(1).saturating_add(data)
}

/// How many of `fields` are not numbered in `without`, and their bytes.
#[allow(clippy::cast_lossless, reason = "u32::from is not const")]
const fn kept_sizes(fields: &[FieldDef], without: &[u8]) -> (u32, u32) {
    match fields {
        [] => (0, 0),
        [f, rest @ ..] => {
            let (count, data) = kept_sizes(rest, without);
            if listed(f.num, without) {
                (count, data)
            } else {
                (count.saturating_add(1), data.saturating_add(f.size as u32))
            }
        }
    }
}

const fn listed(num: u8, list: &[u8]) -> bool {
    match list {
        [] => false,
        [n, rest @ ..] => *n == num || listed(num, rest),
    }
}

/// A length or set, ready to write.
#[derive(Clone, Copy, Debug)]
enum Piece {
    Length { msg: LengthMsg, index: u16, distance: u32, pool: Pool },
    Set { msg: SetMsg, index: u16 },
}

impl Piece {
    fn cost(&self, w: &Writer<'_>) -> Result<Planned, Error> {
        match self {
            Self::Length { msg, .. } => w.cost(msg),
            Self::Set { msg, .. } => w.cost(msg),
        }
    }

    /// Adds a length to what `session` and its lap have seen.
    fn add_to(&self, session: &mut OpenSession) {
        if let Self::Length { msg, index, distance, pool } = *self {
            let swum = msg.swum.map(|l| (l, pool.centimetres));
            session.span.seen.add_length(index, swum, distance, &msg);
            session.lap.seen.add_length(index, swum, distance, &msg);
        }
    }
}

/// Samples of one unsigned field.
#[derive(Clone, Copy, Debug, Default)]
struct Stat {
    sum: u64,
    count: u32,
    max: u32,
}

impl Stat {
    fn add(&mut self, v: u32) {
        self.sum = self.sum.saturating_add(u64::from(v));
        self.count = self.count.saturating_add(1);
        self.max = self.max.max(v);
    }

    /// The average, rounded half up, and the maximum; `None` without a sample.
    fn summary(self) -> Option<(u32, u32)> {
        let avg = per(self.sum, self.count)?;
        Some((u32::try_from(avg).unwrap_or(u32::MAX), self.max))
    }

    fn summary_u8(self) -> (Option<u8>, Option<u8>) {
        let s = self.summary();
        (s.and_then(|(a, _)| u8::try_from(a).ok()), s.and_then(|(_, m)| u8::try_from(m).ok()))
    }

    fn summary_u16(self) -> (Option<u16>, Option<u16>) {
        let s = self.summary();
        (s.and_then(|(a, _)| u16::try_from(a).ok()), s.and_then(|(_, m)| u16::try_from(m).ok()))
    }
}

/// Temperatures: their average, rounded half away from zero, and maximum.
#[derive(Clone, Copy, Debug, Default)]
struct Temperatures {
    sum: i64,
    count: u32,
    max: Option<i8>,
}

impl Temperatures {
    fn add(&mut self, v: i8) {
        self.sum = self.sum.saturating_add(i64::from(v));
        self.count = self.count.saturating_add(1);
        self.max = Some(self.max.map_or(v, |m| m.max(v)));
    }

    fn average(self) -> Option<i8> {
        let count = i64::from(self.count);
        let half = count / 2;
        let sum = if self.sum.is_negative() {
            self.sum.saturating_sub(half)
        } else {
            self.sum.saturating_add(half)
        };
        i8::try_from(sum.checked_div(count)?).ok()
    }
}

/// Which way altitude was last going, for the ascent filter.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Heading {
    Level,
    Up,
    Down,
}

/// The most records the ascent filter averages.
const SMOOTHING: usize = crate::messages::SMOOTHING as usize;

/// The ascent filter: altitude averaged over the last few records, and a change of that
/// average counted once it passes the source's threshold from the extreme it left, the highest
/// since climbing or the lowest since descending, or before either, the lowest or highest so
/// far; and then counted in full.
#[derive(Clone, Copy, Debug)]
struct Climb {
    threshold: i64,
    /// The records averaged, and the latest of them, newest last.
    window: usize,
    recent: [i64; SMOOTHING],
    heading: Heading,
    low: i64,
    high: i64,
    /// The last altitude, and what is added to each after it, so a jump across a pause counts
    /// nothing; and whether the next comes after a pause.
    last: i64,
    shift: i64,
    paused: bool,
}

/// How many records an altitude's `window` averages over.
fn span(window: u8) -> usize {
    usize::from(window).clamp(1, SMOOTHING)
}

impl Climb {
    fn new(fifths: u32, threshold: u32, window: u8) -> Self {
        let at = i64::from(fifths);
        let (low, high, last) = (at, at, at);
        let threshold = i64::from(threshold);
        let window = span(window);
        let recent = [at; SMOOTHING];
        Self {
            threshold,
            window,
            recent,
            heading: Heading::Level,
            low,
            high,
            last,
            shift: 0,
            paused: false,
        }
    }

    /// The average of the latest records with `at`, which joins them, to the nearest fifth.
    fn average(&mut self, at: i64) -> i64 {
        self.recent.rotate_left(1);
        if let Some(newest) = self.recent.last_mut() {
            *newest = at;
        }
        let latest = self.recent.iter().rev().take(self.window);
        let sum = latest.fold(0i64, |sum, &a| sum.saturating_add(a));
        let n = i64::try_from(self.window).unwrap_or(1);
        sum.saturating_add(n / 2).checked_div_euclid(n).unwrap_or(at)
    }

    /// The fifths of a metre `fifths` climbs and descends from where the filter was.
    fn step(&mut self, fifths: u32) -> (u32, u32) {
        let mut at = i64::from(fifths).saturating_add(self.shift);
        if self.paused {
            self.shift = self.shift.saturating_add(self.last.saturating_sub(at));
            (at, self.paused) = (self.last, false);
        }
        self.last = at;
        let at = self.average(at);
        let (low, high, th) = (self.low, self.high, self.threshold);
        let fifths = |d: i64| u32::try_from(d).unwrap_or(u32::MAX);
        match self.heading {
            Heading::Up if at > high => {
                self.high = at;
                (fifths(at.saturating_sub(high)), 0)
            }
            Heading::Down if at < low => {
                self.low = at;
                (0, fifths(low.saturating_sub(at)))
            }
            Heading::Level | Heading::Down if at >= low.saturating_add(th) => {
                (self.heading, self.high) = (Heading::Up, at);
                (fifths(at.saturating_sub(low)), 0)
            }
            Heading::Level | Heading::Up if at.saturating_add(th) <= high => {
                (self.heading, self.low) = (Heading::Down, at);
                (0, fifths(high.saturating_sub(at)))
            }
            Heading::Level => {
                (self.low, self.high) = (low.min(at), high.max(at));
                (0, 0)
            }
            Heading::Up | Heading::Down => (0, 0),
        }
    }
}

/// Longitudes seen, both as signed semicircles and as unsigned ones, which run from 0° east
/// round to 360°, so a track across ±180° has a narrow box in one of the two.
#[derive(Clone, Copy, Debug)]
struct Longitudes {
    signed: (i32, i32),
    unsigned: (u32, u32),
}

impl Longitudes {
    #[allow(clippy::cast_sign_loss)]
    const fn new(long: i32) -> Self {
        Self { signed: (long, long), unsigned: (long as u32, long as u32) }
    }

    #[allow(clippy::cast_sign_loss)]
    fn add(&mut self, long: i32) {
        self.signed = (self.signed.0.min(long), self.signed.1.max(long));
        let u = long as u32;
        self.unsigned = (self.unsigned.0.min(u), self.unsigned.1.max(u));
    }

    /// West and east: east is less than west when the box crosses ±180°.
    #[allow(clippy::cast_possible_wrap)]
    fn west_east(self) -> (i32, i32) {
        let signed = self.signed.1.abs_diff(self.signed.0);
        let unsigned = self.unsigned.1.abs_diff(self.unsigned.0);
        if unsigned < signed {
            (self.unsigned.0 as i32, self.unsigned.1 as i32)
        } else {
            self.signed
        }
    }
}

/// What a lap or session has seen of its records.
#[derive(Clone, Copy, Debug, Default)]
struct Seen {
    heart_rate: Stat,
    cadence: Stat,
    power: Stat,
    max_speed: Option<u16>,
    temperature: Temperatures,
    /// The activity's distance at the start, and the last a record in it gave.
    distance_base: u32,
    distance: Option<u32>,
    /// Climbed and descended, in fifths of a metre, and whether a record gave an altitude.
    ascent: u32,
    descent: u32,
    climbed: bool,
    /// The session's climb and descent before a lap, which its metres count from.
    climb_base: (u32, u32),
    start: Option<Position>,
    end: Option<Position>,
    latitudes: Option<(i32, i32)>,
    longitudes: Option<Longitudes>,
    /// Pool lengths, idle and active, the first one's index, and the strokes of those swum
    /// with a stroke count, with the distance they covered in centimetres.
    lengths: u16,
    active_lengths: u16,
    first_length: Option<u16>,
    strokes: u32,
    stroked_cm: u32,
    swim_stroke: Option<SwimStroke>,
    /// Repetitions of strength sets, kept for the session alone.
    repetitions: Option<u32>,
}

impl Seen {
    fn new(distance_base: u32) -> Self {
        Self { distance_base, ..Self::default() }
    }

    fn add(&mut self, r: &Record, climb: Option<(u32, u32)>) {
        if let Some(p) = r.position {
            let (lat, long) = p.semicircles();
            self.start.get_or_insert(p);
            self.end = Some(p);
            let (south, north) = self.latitudes.unwrap_or((lat, lat));
            self.latitudes = Some((south.min(lat), north.max(lat)));
            self.longitudes.get_or_insert(Longitudes::new(long)).add(long);
        }
        if r.distance.is_some() {
            self.distance = r.distance;
        }
        if let Some((up, down)) = climb {
            self.ascent = self.ascent.saturating_add(up);
            self.descent = self.descent.saturating_add(down);
            self.climbed = true;
        }
        if let Some(v) = r.heart_rate {
            self.heart_rate.add(u32::from(v));
        }
        if let Some(v) = r.cadence {
            self.cadence.add(u32::from(v));
        }
        if let Some(v) = r.power {
            self.power.add(u32::from(v));
        }
        if let Some(v) = r.speed {
            self.max_speed = Some(self.max_speed.map_or(v, |m| m.max(v)));
        }
        if let Some(v) = r.temperature {
            self.temperature.add(v);
        }
    }

    /// A pool length with its index, the activity's distance after it, and for one swum, the
    /// pool, its speed and cadence.
    fn add_length(
        &mut self,
        index: u16,
        swum: Option<(Length, u16)>,
        distance: u32,
        msg: &LengthMsg,
    ) {
        self.lengths = self.lengths.saturating_add(1);
        self.first_length.get_or_insert(index);
        self.distance = Some(distance);
        let Some((length, pool_cm)) = swum else { return };
        self.active_lengths = self.active_lengths.saturating_add(1);
        let stroke = length.stroke;
        self.swim_stroke = Some(match self.swim_stroke {
            Some(s) if s != stroke => SwimStroke::MIXED,
            _ => stroke,
        });
        if let Some(n) = length.strokes {
            self.strokes = self.strokes.saturating_add(u32::from(n));
            self.stroked_cm = self.stroked_cm.saturating_add(u32::from(pool_cm));
        }
        if let Some(v) = msg.cadence {
            self.cadence.add(u32::from(v));
        }
        if let Some(v) = msg.avg_speed {
            self.max_speed = Some(self.max_speed.map_or(v, |m| m.max(v)));
        }
    }

    fn add_repetitions(&mut self, set: &Set) {
        if let Some(n) = set.repetitions {
            self.repetitions = Some(self.repetitions.unwrap_or(0).saturating_add(u32::from(n)));
        }
    }

    /// The totals over `timer` seconds, with a value its field cannot hold left as none.
    fn totals(&self, timer: u32) -> Totals {
        let distance = self.distance.map(|last| last.saturating_sub(self.distance_base));
        let avg_speed = distance.and_then(|d| {
            let mm_per_s = per(u64::from(d) * 10, timer)?;
            u16::try_from(mm_per_s).ok().filter(|&v| v != u16::MAX)
        });
        // A maximum below the average is a sampling gap, not a speed: leave it out.
        let max_speed = self.max_speed.filter(|&m| avg_speed.is_none_or(|avg| m >= avg));
        let metres =
            |fifths: u32| u16::try_from(per(fifths, 5u32)?).ok().filter(|&v| v != u16::MAX);
        let since = |base: u32, fifths: u32| {
            metres(base.saturating_add(fifths))?.checked_sub(metres(base)?)
        };
        let swam = self.lengths > 0;
        let (avg_cadence, max_cadence) = self.cadence.summary_u8();
        let (avg_power, max_power) = self.power.summary_u16();
        let corners = self.latitudes.zip(self.longitudes).map(|((south, north), longs)| {
            let (west, east) = longs.west_east();
            (Position::from_semicircles(north, east), Position::from_semicircles(south, west))
        });
        Totals {
            start: self.start,
            end: self.end,
            north_east: corners.and_then(|c| c.0),
            south_west: corners.and_then(|c| c.1),
            distance,
            avg_speed,
            max_speed,
            avg_cadence,
            max_cadence,
            avg_power,
            max_power,
            ascent: self.climbed.then(|| since(self.climb_base.0, self.ascent)).flatten(),
            descent: self.climbed.then(|| since(self.climb_base.1, self.descent)).flatten(),
            avg_temperature: self.temperature.average(),
            max_temperature: self.temperature.max,
            cycles: swam.then_some(self.strokes),
            lengths: swam.then_some(self.lengths),
            active_lengths: swam.then_some(self.active_lengths),
            stroke_distance: per(self.stroked_cm, self.strokes)
                .and_then(|cm| u16::try_from(cm).ok())
                .filter(|&cm| cm != u16::MAX),
            swim_stroke: self.swim_stroke,
        }
    }
}

/// A lap or session that has started and not yet ended.
#[derive(Clone, Copy, Debug)]
struct Open {
    start: Timestamp,
    /// The timer's seconds at `start`.
    timer: u32,
    seen: Seen,
}

impl Open {
    fn new(start: Timestamp, timer: u32, distance: u32) -> Self {
        Self { start, timer, seen: Seen::new(distance) }
    }
}

#[derive(Clone, Copy, Debug)]
struct OpenSession {
    span: Open,
    sport: Sport,
    sub_sport: SubSport,
    pool: Option<Pool>,
    first_lap: u16,
    lap: Open,
    /// Where the next length or set starts, with the timer's seconds there, and whether a
    /// rest started there.
    mark: (Timestamp, u32),
    resting: bool,
}

impl OpenSession {
    /// Whether it takes strength sets and rests between them: training, of any sub-sport, and
    /// HIIT.
    fn takes_sets(&self) -> bool {
        self.sport == Sport::TRAINING || self.sport == Sport::HIIT
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Phase {
    NotStarted,
    Started,
    /// Writing the end into the bytes kept for it.
    Ending,
    Ended,
}

/// Where the activity is.
#[derive(Clone, Copy, Debug)]
pub(super) struct Act {
    phase: Phase,
    /// The latest time written.
    now: Timestamp,
    /// The timer's seconds up to `since`, and whether it has run since then.
    timer: u32,
    since: Timestamp,
    running: bool,
    session: Option<OpenSession>,
    devices: u8,
    /// The distance covered, in centimetres, and the ascent filter.
    distance: u32,
    micrometres: u64,
    climb: Option<Climb>,
    lengths: u16,
    sets: u16,
    /// Beat intervals not yet written, in milliseconds.
    beats: [u16; HRV_BEATS],
    beat_count: usize,
}

impl Act {
    pub(super) const fn new() -> Self {
        let zero = Timestamp::from_fit(0);
        Self {
            phase: Phase::NotStarted,
            now: zero,
            timer: 0,
            since: zero,
            running: false,
            session: None,
            devices: 0,
            distance: 0,
            micrometres: 0,
            climb: None,
            lengths: 0,
            sets: 0,
            beats: [0; HRV_BEATS],
            beat_count: 0,
        }
    }

    pub(super) fn ended(&self) -> bool {
        self.phase == Phase::Ended
    }

    /// The bytes every write must leave free so the activity can still end.
    pub(super) fn kept_for_end(&self) -> u32 {
        if self.phase == Phase::Started {
            END
        } else {
            0
        }
    }

    /// Refuses a call outside the activity.
    pub(super) fn open(&self) -> Result<(), Error> {
        self.started(self.now)
    }

    /// Refuses a call outside a session.
    pub(super) fn in_session(&self) -> Result<(), Error> {
        self.open()?;
        self.session.map(|_| ()).ok_or(Error::OutOfOrder)
    }

    /// The timer's seconds at `t`, which is no earlier than `since`.
    fn timer_at(&self, t: Timestamp) -> u32 {
        let running = if self.running { t.fit().saturating_sub(self.since.fit()) } else { 0 };
        self.timer.saturating_add(running)
    }

    /// The activity's distance after `input`, which may not take it back, in centimetres and
    /// the micrometres past them.
    fn distance_after(&self, input: Distance) -> Result<(u32, u64), Error> {
        let next = match input {
            Distance::Advanced(um) => {
                let total = u64::from(self.distance)
                    .saturating_mul(10_000)
                    .saturating_add(self.micrometres);
                total
                    .checked_add(um)
                    .and_then(|t| Some((u32::try_from(t / 10_000).ok()?, t % 10_000)))
            }
            Distance::Total(cm) if cm < self.distance => return Err(Error::DistanceWentBack),
            Distance::Total(cm) => Some((cm, 0)),
        };
        next.filter(|&(d, _)| d <= DISTANCE_CM_MAX).ok_or(Error::OutOfRange)
    }

    /// Moves the ascent filter to `altitude`, returning what it climbed and descended; a
    /// different threshold or smoothing starts the filter afresh.
    fn climb_to(&mut self, altitude: Altitude) -> (u32, u32) {
        let (fifths, threshold) = (u32::from(altitude.fifths), u32::from(altitude.threshold));
        let window = altitude.window;
        match self.climb.as_mut() {
            Some(c) if c.threshold == i64::from(threshold) && c.window == span(window) => {
                c.step(fifths)
            }
            _ => {
                self.climb = Some(Climb::new(fifths, threshold, window));
                (0, 0)
            }
        }
    }

    /// The latest time written.
    pub(super) const fn now(&self) -> Timestamp {
        self.now
    }

    /// Moves the activity on to `t`, no earlier than its time.
    pub(super) fn move_to(&mut self, t: Timestamp) {
        self.now = t;
    }

    pub(super) fn started(&self, t: Timestamp) -> Result<(), Error> {
        if self.phase != Phase::Started {
            return Err(Error::OutOfOrder);
        }
        if t < self.now {
            return Err(Error::TimeWentBack);
        }
        Ok(())
    }
}

impl Leg<'_> {
    /// Refuses a leg that [`Writer::leg`] could never start, whatever the activity: one of
    /// `lap_swimming` without a pool, a pool of no length or too long, a sport or sub-sport of
    /// FIT's "none", or a name too long or holding a NUL. What it refuses, `leg` refuses the
    /// same way whenever it could otherwise start one, so a recorder that writes an activity
    /// later can refuse a leg when it is chosen.
    ///
    /// ```
    /// use fit_encoder::{Error, Leg, Sport, SubSport};
    ///
    /// assert_eq!(Leg::new(Sport::RUNNING, SubSport::TRAIL).check(), Ok(()));
    /// let pool_swim = Leg::new(Sport::SWIMMING, SubSport::LAP_SWIMMING);
    /// assert_eq!(pool_swim.check(), Err(Error::OutOfRange));
    /// ```
    ///
    /// # Errors
    ///
    /// [`Error::OutOfRange`] or [`Error::StringTooLong`].
    pub fn check(&self) -> Result<(), Error> {
        let no_pool = self.pool.is_none() && self.sport.sub_sport == SubSport::LAP_SWIMMING;
        if no_pool || self.pool.is_some_and(|p| p.centimetres == 0 || p.centimetres == u16::MAX) {
            return Err(Error::OutOfRange);
        }
        check(&self.sport)
    }
}

/// `n` over `d`, rounded half up; `None` over nothing.
fn per(n: impl Into<u64>, d: impl Into<u64>) -> Option<u64> {
    let (n, d) = (n.into(), d.into());
    n.saturating_add(d / 2).checked_div(d)
}

/// Seconds as FIT's milliseconds; too many is FIT's "none", which writing refuses.
fn ms(seconds: u32) -> u32 {
    if seconds > DURATION_SECONDS_MAX {
        u32::MAX
    } else {
        seconds.saturating_mul(1000)
    }
}

fn lap_message(lap: &Open, end: Timestamp, timer: u32, session: &OpenSession) -> Lap {
    let elapsed = end.fit().saturating_sub(lap.start.fit());
    let timer = timer.saturating_sub(lap.timer);
    let mut msg = Lap::new(lap.start, end, ms(elapsed), ms(timer))
        .sport(session.sport, session.sub_sport)
        .totals(lap.seen.totals(timer));
    if let Some(i) = lap.seen.first_length {
        msg = msg.first_length(i);
    }
    if let (Some(avg), Some(max)) = lap.seen.heart_rate.summary_u8() {
        msg = msg.heart_rate(avg, max);
    }
    msg
}

impl Writer<'_> {
    /// Starts the activity at `t`, recorded by `creator`. The timer starts with the first
    /// session.
    ///
    /// # Errors
    ///
    /// [`Error::OutOfOrder`] if it has started already; see [`Error`].
    pub fn start(&mut self, t: Timestamp, creator: &Device<'_>) -> Result<(), Error> {
        if self.st.act.phase != Phase::NotStarted {
            return Err(Error::OutOfOrder);
        }
        let mut id = FileId::new(FileType::ACTIVITY, creator.manufacturer, creator.product, t);
        if let Some(serial) = creator.serial_number {
            id = id.serial_number(serial);
        }
        let info = creator.info(t, 0);
        let first = self.cost(&id)?;
        self.endable(t, 0, 0)?;
        self.room(first.size().saturating_add(self.cost(&info)?.after(&first)))?;
        self.raw_file_id(&id)?;
        self.raw_device_info(&info)?;
        let act = &mut self.st.act;
        act.phase = Phase::Started;
        (act.now, act.since, act.running, act.timer) = (t, t, false, 0);
        Ok(())
    }

    /// Writes a sensor the activity used, as the next `device_index` after the creator's.
    ///
    /// # Errors
    ///
    /// [`Error::OutOfOrder`] outside the activity, [`Error::IndexFull`] after
    /// [`SENSORS_MAX`]; see [`Error`].
    pub fn device(&mut self, device: &Device<'_>) -> Result<(), Error> {
        let now = self.st.act.now;
        self.st.act.started(now)?;
        let index = self.st.act.devices.checked_add(1).filter(|&i| i <= SENSORS_MAX);
        let index = index.ok_or(Error::IndexFull)?;
        self.raw_device_info(&device.info(now, index))?;
        self.st.act.devices = index;
        Ok(())
    }

    /// Starts a session of `sport` at `t`, ending the one before it there: the next leg of a
    /// multisport activity, or a transition between legs. [`Writer::leg`] starts one with a
    /// name, or moved to by hand.
    ///
    /// # Errors
    ///
    /// [`Error::OutOfRange`] for `lap_swimming`, as a pool swim starts with
    /// [`Writer::pool_swim`], or for FIT's "none", as [`Leg::check`] refuses them; see
    /// [`Error`].
    pub fn session(
        &mut self,
        t: Timestamp,
        sport: Sport,
        sub_sport: SubSport,
    ) -> Result<(), Error> {
        self.leg(t, &Leg::new(sport, sub_sport))
    }

    /// Starts a pool swim at `t` in `pool`, as [`Writer::session`] starts any other: its
    /// distance is the pool's length for each length swum, from [`Writer::length`].
    ///
    /// # Errors
    ///
    /// [`Error::OutOfRange`] for a pool of no length or too long; see [`Error`].
    pub fn pool_swim(&mut self, t: Timestamp, pool: Pool) -> Result<(), Error> {
        self.leg(t, &Leg::pool_swim(pool))
    }

    /// Starts the session `leg` describes at `t`, ending the one before it there, as
    /// [`Writer::session`] and [`Writer::pool_swim`] do.
    ///
    /// # Errors
    ///
    /// Those of [`Leg::check`], [`Error::OutOfOrder`] for a first leg moved to by hand; see
    /// [`Error`].
    pub fn leg(&mut self, t: Timestamp, leg: &Leg<'_>) -> Result<(), Error> {
        let Leg { sport, pool, by_hand } = *leg;
        self.st.act.started(t)?;
        leg.check()?;
        let first = self.st.act.session.is_none();
        if first && by_hand {
            return Err(Error::OutOfOrder);
        }
        let closed = u16::from(!first);
        let (laps, sessions) = (self.st.laps, self.st.sessions);
        self.endable(t, laps.saturating_add(closed), sessions.saturating_add(closed))?;
        let cost = self.cost(&sport)?;
        if first {
            let start = Event::timer_start(t);
            let event = self.cost(&start)?;
            self.room(event.size().saturating_add(cost.after(&event)))?;
            self.raw_event(start)?;
            let act = &mut self.st.act;
            (act.since, act.running) = (t, true);
        } else {
            self.room(SWITCH)?;
            if let Some(piece) = self.rest_piece(t)? {
                self.put_piece(t, piece)?;
            }
            let trigger = if self.st.options.auto_multisport && !by_hand {
                trigger::AUTO_MULTI_SPORT
            } else {
                trigger::MANUAL
            };
            self.close_session(t, trigger)?;
        }
        self.fixed(&sport, 0)?;
        let SportMsg { sport, sub_sport, .. } = sport;
        let (timer, distance) = (self.st.act.timer_at(t), self.st.act.distance);
        self.st.act.session = Some(OpenSession {
            span: Open::new(t, timer, distance),
            sport,
            sub_sport,
            pool,
            first_lap: self.st.laps,
            lap: Open::new(t, timer, distance),
            mark: (t, timer),
            resting: false,
        });
        // Each leg climbs from where it starts.
        self.st.act.climb = None;
        self.st.act.now = t;
        Ok(())
    }

    /// Writes a record in the current session.
    ///
    /// # Errors
    ///
    /// [`Error::OutOfOrder`] outside a session, [`Error::Paused`] while the timer is paused,
    /// [`Error::DistanceWentBack`] for a total distance below one already written; see
    /// [`Error`].
    pub fn record(&mut self, record: &Record) -> Result<(), Error> {
        self.record_with(record, &[])
    }

    /// Writes a record with fields besides those [`Record`] models: developer fields, from
    /// [`RecordField::value`], and raw fields, from [`RawField`]. A raw field may not be one
    /// the encoder writes: those [`Record`] sets, the `timestamp`, or another form of one,
    /// `compressed_speed_distance` (8), `enhanced_speed` (73) and `enhanced_altitude` (78).
    ///
    /// # Errors
    ///
    /// Those of [`Writer::record`]; [`Error::Undeclared`] for a field this file did not
    /// declare, [`Error::Duplicate`] for one given twice, [`Error::Reserved`] for a raw field
    /// the encoder writes, [`Error::TooMany`] past [`RAW_FIELDS_MAX`] raw fields.
    pub fn record_with(&mut self, record: &Record, extras: &[Extra<'_>]) -> Result<(), Error> {
        let t = record.timestamp;
        self.st.act.started(t)?;
        let Some(session) = self.st.act.session else { return Err(Error::OutOfOrder) };
        if !self.st.act.running {
            return Err(Error::Paused);
        }
        let from_lengths =
            record.distance_input.is_some() || record.speed.is_some() || record.cadence.is_some();
        if session.pool.is_some() && from_lengths {
            return Err(Error::GivenByLengths);
        }
        let mut record = *record;
        let distance = match record.distance_input {
            None => None,
            Some(input) => Some(self.st.act.distance_after(input)?),
        };
        record.distance = distance.map(|(cm, _)| cm);
        self.endable(t, self.st.laps, self.st.sessions)?;
        let size = self.record_cost(&record, extras)?;
        self.room(self.beats_cost()?.saturating_add(size))?;
        // Beats follow the record before them, which readers count their times from.
        self.write_beats()?;
        self.raw_record_with(record, extras)?;
        let act = &mut self.st.act;
        act.now = t;
        if let Some((cm, um)) = distance {
            (act.distance, act.micrometres) = (cm, um);
        }
        let climb = record.altitude.map(|a| act.climb_to(a));
        if let Some(s) = act.session.as_mut() {
            s.span.seen.add(&record, climb);
            s.lap.seen.add(&record, climb);
        }
        Ok(())
    }

    /// Ends the current lap at `t`, by hand, and starts the next.
    ///
    /// # Errors
    ///
    /// [`Error::OutOfOrder`] outside a session or during a rest in a pool swim; see [`Error`].
    pub fn lap(&mut self, t: Timestamp) -> Result<(), Error> {
        self.lap_by(t, LapTrigger::Manual)
    }

    /// [`Writer::lap`], for a lap that `trigger` ended, such as the device's automatic lap
    /// every kilometre.
    ///
    /// # Errors
    ///
    /// As [`Writer::lap`].
    pub fn lap_by(&mut self, t: Timestamp, trigger: LapTrigger) -> Result<(), Error> {
        self.st.act.started(t)?;
        let Some(session) = self.st.act.session else { return Err(Error::OutOfOrder) };
        if session.resting && session.pool.is_some() {
            return Err(Error::OutOfOrder);
        }
        self.end_lap(t, &session, trigger)
    }

    /// Ends the open session's current lap at `t` and starts the next there.
    fn end_lap(
        &mut self,
        t: Timestamp,
        session: &OpenSession,
        trigger: LapTrigger,
    ) -> Result<(), Error> {
        let timer = self.st.act.timer_at(t);
        let lap = lap_message(&session.lap, t, timer, session).trigger(trigger.get());
        check(&lap)?;
        self.endable(t, self.st.laps.saturating_add(1), self.st.sessions)?;
        self.raw_lap(&lap)?;
        let act = &mut self.st.act;
        act.now = t;
        if let Some(s) = act.session.as_mut() {
            s.lap = Open::new(t, timer, act.distance);
            s.lap.seen.climb_base = (s.span.seen.ascent, s.span.seen.descent);
            if !s.resting {
                s.mark = (t, timer);
            }
        }
        Ok(())
    }

    /// Pauses the timer at `t`.
    ///
    /// # Errors
    ///
    /// [`Error::OutOfOrder`] before the first session or if it is paused already; see
    /// [`Error`].
    pub fn pause(&mut self, t: Timestamp) -> Result<(), Error> {
        self.st.act.started(t)?;
        if !self.st.act.running {
            return Err(Error::OutOfOrder);
        }
        self.endable(t, self.st.laps, self.st.sessions)?;
        self.raw_event(Event::timer_stop(t))?;
        let act = &mut self.st.act;
        (act.timer, act.since, act.running, act.now) = (act.timer_at(t), t, false, t);
        if let Some(c) = act.climb.as_mut() {
            c.paused = true;
        }
        Ok(())
    }

    /// Resumes the timer at `t`.
    ///
    /// # Errors
    ///
    /// [`Error::OutOfOrder`] before the first session or if it is running; see [`Error`].
    pub fn resume(&mut self, t: Timestamp) -> Result<(), Error> {
        self.st.act.started(t)?;
        if self.st.act.running || self.st.act.session.is_none() {
            return Err(Error::OutOfOrder);
        }
        self.endable(t, self.st.laps, self.st.sessions)?;
        self.raw_event(Event::timer_start(t))?;
        let act = &mut self.st.act;
        (act.since, act.running, act.now) = (t, true, t);
        Ok(())
    }

    /// Ends a length of the pool at `t`, swum since the last length, rest or lap ended, or the
    /// pool swim started.
    ///
    /// # Errors
    ///
    /// [`Error::OutOfOrder`] outside a pool swim or during a rest, [`Error::Paused`] while the
    /// timer is paused, [`Error::IndexFull`] after [`LENGTHS_MAX`]; see [`Error`].
    pub fn length(&mut self, t: Timestamp, length: &Length) -> Result<(), Error> {
        self.st.act.started(t)?;
        let Some(session) = self.st.act.session else { return Err(Error::OutOfOrder) };
        if session.pool.is_none() || session.resting {
            return Err(Error::OutOfOrder);
        }
        if !self.st.act.running {
            return Err(Error::Paused);
        }
        let piece = self.length_at(t, &session, Some(*length))?;
        self.put_piece(t, piece)
    }

    /// Writes a strength set that ends at `t`, done since the last set, rest or lap ended, or
    /// the session started.
    ///
    /// # Errors
    ///
    /// [`Error::OutOfOrder`] outside a training or HIIT session or during a rest,
    /// [`Error::Paused`] while the timer is paused, [`Error::IndexFull`] after [`SETS_MAX`];
    /// see [`Error`].
    pub fn set(&mut self, t: Timestamp, set: &Set) -> Result<(), Error> {
        self.st.act.started(t)?;
        let Some(session) = self.st.act.session else { return Err(Error::OutOfOrder) };
        if !session.takes_sets() || session.resting {
            return Err(Error::OutOfOrder);
        }
        if !self.st.act.running {
            return Err(Error::Paused);
        }
        let piece = self.set_at(t, &session, Some(*set))?;
        self.put_piece(t, piece)
    }

    /// Starts a rest at `t`, which [`Writer::end_rest`] ends. In a pool swim the lap of lengths
    /// before it ends here, and the rest is an idle length in a lap of its own; in a training
    /// or HIIT session it is a rest between strength sets.
    ///
    /// # Errors
    ///
    /// [`Error::OutOfOrder`] outside a pool swim or a training or HIIT session, or during a
    /// rest; see [`Error`].
    pub fn rest(&mut self, t: Timestamp) -> Result<(), Error> {
        self.st.act.started(t)?;
        let Some(session) = self.st.act.session else { return Err(Error::OutOfOrder) };
        if session.resting || (session.pool.is_none() && !session.takes_sets()) {
            return Err(Error::OutOfOrder);
        }
        // Whatever ends the rest writes a length or set, which must have an index left.
        match session.pool {
            Some(_) => next_index(self.st.act.lengths, LENGTHS_MAX)?,
            None => next_index(self.st.act.sets, SETS_MAX)?,
        };
        if session.pool.is_some() && session.lap.seen.lengths > 0 {
            self.end_lap(t, &session, LapTrigger::Manual)?;
        } else {
            self.endable(t, self.st.laps, self.st.sessions)?;
        }
        let act = &mut self.st.act;
        let timer = act.timer_at(t);
        act.now = t;
        if let Some(s) = act.session.as_mut() {
            (s.mark, s.resting) = ((t, timer), true);
        }
        Ok(())
    }

    /// Ends the rest at `t`.
    ///
    /// # Errors
    ///
    /// [`Error::OutOfOrder`] outside a rest, [`Error::IndexFull`] after [`LENGTHS_MAX`] or
    /// [`SETS_MAX`]; see [`Error`].
    pub fn end_rest(&mut self, t: Timestamp) -> Result<(), Error> {
        self.st.act.started(t)?;
        let Some(session) = self.st.act.session.filter(|s| s.resting) else {
            return Err(Error::OutOfOrder);
        };
        if session.pool.is_none() {
            let piece = self.set_at(t, &session, None)?;
            return self.put_piece(t, piece);
        }
        let piece = self.length_at(t, &session, None)?;
        self.endable(t, self.st.laps.saturating_add(1), self.st.sessions)?;
        let mut after = session;
        piece.add_to(&mut after);
        let lap = lap_message(&after.lap, t, self.st.act.timer_at(t), &after);
        check(&lap)?;
        let lap = self.cost_with(&lap, Extras::Staged(KindId::Lap))?;
        let length = piece.cost(self)?;
        self.room(length.size().saturating_add(lap.after(&length)))?;
        self.put_piece(t, piece)?;
        let session = self.st.act.session.ok_or(Error::OutOfOrder)?;
        self.end_lap(t, &session, LapTrigger::Manual)
    }

    /// Adds the intervals between heartbeats, in milliseconds, as they arrive; a beat's
    /// interval ends it. They are written five to a `hrv` message, and before the next record,
    /// so each follows the record it came after; they are kept while the timer is paused, as
    /// their sum is their only clock.
    ///
    /// # Errors
    ///
    /// [`Error::OutOfOrder`] outside the activity, [`Error::OutOfRange`] for 65,535; see
    /// [`Error`].
    pub fn beat_intervals_ms(&mut self, intervals: &[u16]) -> Result<(), Error> {
        self.beats_fit(intervals, true)?;
        self.beats(intervals.iter().copied())
    }

    /// [`Writer::beat_intervals_ms`], from intervals in 1/1024 s, as a Bluetooth heart rate
    /// sensor gives them; each is rounded to the millisecond.
    ///
    /// # Errors
    ///
    /// [`Error::OutOfOrder`] outside the activity; see [`Error`].
    pub fn beat_intervals_1024ths(&mut self, intervals: &[u16]) -> Result<(), Error> {
        self.beats_fit(intervals, false)?;
        self.beats(intervals.iter().map(|&n| {
            let ms = per(u32::from(n).saturating_mul(1000), 1024u32);
            ms.and_then(|ms| u16::try_from(ms).ok()).unwrap_or(u16::MAX)
        }))
    }

    /// Refuses `intervals`, in milliseconds or else 1/1024 s, unless every message they fill
    /// can be written.
    pub(super) fn beats_fit(&mut self, intervals: &[u16], ms: bool) -> Result<(), Error> {
        self.st.act.started(self.st.act.now)?;
        if ms && intervals.contains(&u16::MAX) {
            return Err(Error::OutOfRange);
        }
        let count = self.st.act.beat_count.saturating_add(intervals.len());
        if let Some(more) = (count / HRV_BEATS).checked_sub(1) {
            let first = self.cost(&Hrv(&[0; HRV_BEATS]))?;
            let more = u32::try_from(more).unwrap_or(u32::MAX).saturating_mul(first.body);
            self.room(first.size().saturating_add(more))?;
        }
        Ok(())
    }

    /// Keeps `intervals`, which [`Writer::beats_fit`] allowed, writing each five as they fill.
    fn beats(&mut self, intervals: impl Iterator<Item = u16>) -> Result<(), Error> {
        for ms in intervals {
            let act = &mut self.st.act;
            if let Some(slot) = act.beats.get_mut(act.beat_count) {
                *slot = ms;
                act.beat_count = act.beat_count.saturating_add(1);
            }
            if act.beat_count == HRV_BEATS {
                self.write_beats()?;
            }
        }
        Ok(())
    }

    /// The bytes the beat intervals not yet written take.
    fn beats_cost(&self) -> Result<u32, Error> {
        let act = &self.st.act;
        match act.beats.get(..act.beat_count).filter(|b| !b.is_empty()) {
            Some(beats) => Ok(self.cost(&Hrv(beats))?.size()),
            None => Ok(0),
        }
    }

    /// Writes the beat intervals not yet written.
    fn write_beats(&mut self) -> Result<(), Error> {
        let act = self.st.act;
        let Some(beats) = act.beats.get(..act.beat_count).filter(|b| !b.is_empty()) else {
            return Ok(());
        };
        self.fixed(&Hrv(beats), 0)?;
        self.st.act.beat_count = 0;
        Ok(())
    }

    /// What ends the open session's rest at `t`, if it has one: an idle length or a rest set.
    fn rest_piece(&self, t: Timestamp) -> Result<Option<Piece>, Error> {
        let Some(session) = self.st.act.session.filter(|s| s.resting) else { return Ok(None) };
        let piece = if session.pool.is_some() {
            self.length_at(t, &session, None)?
        } else {
            self.set_at(t, &session, None)?
        };
        Ok(Some(piece))
    }

    /// A length ending at `t`, swum or, without one, idle.
    fn length_at(
        &self,
        t: Timestamp,
        session: &OpenSession,
        swum: Option<Length>,
    ) -> Result<Piece, Error> {
        let pool = session.pool.ok_or(Error::OutOfOrder)?;
        let index = next_index(self.st.act.lengths, LENGTHS_MAX)?;
        let (start, since) = session.mark;
        let seconds = self.st.act.timer_at(t).saturating_sub(since);
        let cm = u32::from(pool.centimetres);
        let msg = LengthMsg {
            span: Span {
                start_time: start,
                timestamp: t,
                total_elapsed_ms: ms(t.fit().saturating_sub(start.fit())),
                total_timer_ms: ms(seconds),
            },
            swum,
            avg_speed: swum
                .and_then(|_| per(cm.saturating_mul(10), seconds))
                .and_then(|v| u16::try_from(v).ok())
                .filter(|&v| v != u16::MAX),
            cadence: swum
                .and_then(|l| per(u32::from(l.strokes?).saturating_mul(60), seconds))
                .and_then(|v| u8::try_from(v).ok())
                .filter(|&v| v != u8::MAX),
        };
        check(&msg)?;
        let distance = match swum {
            Some(_) => self.st.act.distance.checked_add(cm).filter(|&d| d <= DISTANCE_CM_MAX),
            None => Some(self.st.act.distance),
        };
        let distance = distance.ok_or(Error::OutOfRange)?;
        self.endable(t, self.st.laps, self.st.sessions)?;
        Ok(Piece::Length { msg, index, distance, pool })
    }

    /// A set ending at `t`, or without one, a rest.
    fn set_at(
        &self,
        t: Timestamp,
        session: &OpenSession,
        set: Option<Set>,
    ) -> Result<Piece, Error> {
        let index = next_index(self.st.act.sets, SETS_MAX)?;
        let (start, since) = session.mark;
        let msg = SetMsg {
            start_time: start,
            timestamp: t,
            duration_ms: ms(self.st.act.timer_at(t).saturating_sub(since)),
            set,
        };
        check(&msg)?;
        self.endable(t, self.st.laps, self.st.sessions)?;
        Ok(Piece::Set { msg, index })
    }

    /// Writes a length or set ending at `t`, which ends any rest.
    fn put_piece(&mut self, t: Timestamp, piece: Piece) -> Result<(), Error> {
        let timer = self.st.act.timer_at(t);
        match piece {
            Piece::Length { msg, index, distance, .. } => {
                self.fixed(&msg, index)?;
                let act = &mut self.st.act;
                (act.lengths, act.now, act.distance) = (index.saturating_add(1), t, distance);
                if let Some(s) = act.session.as_mut() {
                    piece.add_to(s);
                }
            }
            Piece::Set { msg, index } => {
                self.fixed(&msg, index)?;
                let act = &mut self.st.act;
                (act.sets, act.now) = (index.saturating_add(1), t);
                if let (Some(s), Some(set)) = (act.session.as_mut(), &msg.set) {
                    s.span.seen.add_repetitions(set);
                }
            }
        }
        if let Some(s) = self.st.act.session.as_mut() {
            (s.mark, s.resting) = ((t, timer), false);
        }
        Ok(())
    }

    /// Ends the activity at `t`: the timer stops, and the last lap, the last session and the
    /// activity are written.
    ///
    /// # Errors
    ///
    /// [`Error::OutOfOrder`] if no session has started; see [`Error`].
    pub fn end(&mut self, t: Timestamp) -> Result<(), Error> {
        self.st.act.started(t)?;
        if self.st.act.session.is_none() {
            return Err(Error::OutOfOrder);
        }
        self.endable(t, self.st.laps, self.st.sessions)?;
        let rest = self.rest_piece(t)?;
        let timer = self.st.act.timer_at(t);
        let activity = self.activity(t);
        self.ahead(END)?;
        self.st.act.phase = Phase::Ending;
        if let Some(piece) = rest {
            self.put_piece(t, piece)?;
        }
        self.write_beats()?;
        self.raw_event(Event::timer_stop_all(t))?;
        self.close_session(t, trigger::ACTIVITY_END)?;
        self.raw_activity(&activity)?;
        let act = &mut self.st.act;
        (act.timer, act.since, act.running, act.now, act.phase) =
            (timer, t, false, t, Phase::Ended);
        Ok(())
    }

    /// The open session's last lap and the session itself as they would end at `t`.
    fn closing(&self, t: Timestamp, trigger: u8) -> Option<(Lap, Session)> {
        let s = self.st.act.session?;
        let timer = self.st.act.timer_at(t);
        let lap = lap_message(&s.lap, t, timer, &s).trigger(lap_trigger::SESSION_END);
        let elapsed = t.fit().saturating_sub(s.span.start.fit());
        let laps = self.st.laps.saturating_add(1).saturating_sub(s.first_lap);
        let running = timer.saturating_sub(s.span.timer);
        let mut totals = s.span.seen.totals(running);
        if s.takes_sets() {
            totals.cycles = s.span.seen.repetitions;
        }
        let mut session = Session::new(s.span.start, t, ms(elapsed), ms(running))
            .sport(s.sport, s.sub_sport)
            .laps(s.first_lap, laps)
            .totals(totals)
            .trigger(trigger);
        if let Some(pool) = s.pool {
            session = session.pool(pool);
        }
        if let (Some(avg), Some(max)) = s.span.seen.heart_rate.summary_u8() {
            session = session.heart_rate(avg, max);
        }
        Some((lap, session))
    }

    /// The activity message as it would end at `t`.
    fn activity(&self, t: Timestamp) -> Activity {
        let timer = ms(self.st.act.timer_at(t));
        let activity = Activity::new(t, timer)
            .sessions(self.st.sessions.saturating_add(1))
            .auto_multisport(self.st.options.auto_multisport);
        match self.st.options.utc_offset {
            Some(offset) => activity.utc_offset(offset),
            None => activity,
        }
    }

    /// Refuses a call after which, with `laps` laps and `sessions` sessions written, the
    /// activity could not end at `t`.
    pub(super) fn endable(&self, t: Timestamp, laps: u16, sessions: u16) -> Result<(), Error> {
        next_index(laps, LAPS_MAX)?;
        next_index(sessions, SESSIONS_MAX)?;
        check(&self.activity(t))?;
        if let Some((lap, session)) = self.closing(t, trigger::ACTIVITY_END) {
            check(&lap)?;
            check(&session)?;
        }
        Ok(())
    }

    /// Ends the open session, if any, at `t`, by `trigger`.
    fn close_session(&mut self, t: Timestamp, trigger: u8) -> Result<(), Error> {
        let Some((lap, session)) = self.closing(t, trigger) else { return Ok(()) };
        check(&lap)?;
        check(&session)?;
        self.raw_lap(&lap)?;
        self.raw_session(&session)?;
        self.st.act.session = None;
        Ok(())
    }
}

#[cfg(test)]
mod tests;