fit-encoder 0.1.2

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
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
use super::super::{
    plan, write, Counter, Locals, OnePass, Options, State, WriteError, DISTANCE_METERS_MAX, LIMIT,
};
use super::*;
use crate::developer::{InLap, InRecord, InSession, LapField};
use crate::messages::{Altitude, Exercise};
use crate::types::ExerciseCategory;
use crate::types::Manufacturer;
use crate::SliceSink;
use std::vec::Vec;

const T: Timestamp = Timestamp::from_fit(0x1122_3344);

fn at(s: u32) -> Timestamp {
    Timestamp::from_fit(0x1122_3344 + s)
}

fn watch() -> Device<'static> {
    Device::new(Manufacturer::DEVELOPMENT, 1)
}

/// A first pass over `f`, returning its writer's state.
fn run(f: impl FnOnce(&mut Writer<'_>)) -> State {
    let mut st = State::new(Options::new(), None);
    f(&mut Writer { out: &mut Counter, st: &mut st });
    st
}

#[test]
fn nothing_before_the_start() {
    run(|w| {
        let r = Record::new(T);
        assert_eq!(w.session(T, Sport::RUNNING, SubSport::GENERIC), Err(Error::OutOfOrder));
        assert_eq!(w.record(&r), Err(Error::OutOfOrder));
        assert_eq!(w.lap(T), Err(Error::OutOfOrder));
        assert_eq!(w.pause(T), Err(Error::OutOfOrder));
        assert_eq!(w.resume(T), Err(Error::OutOfOrder));
        assert_eq!(w.device(&watch()), Err(Error::OutOfOrder));
        assert_eq!(w.end(T), Err(Error::OutOfOrder));
        assert_eq!(w.st.written, 0);
    });
}

#[test]
fn records_and_laps_need_a_session_and_the_end_needs_one() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        let written = w.st.written;
        assert_eq!(w.start(T, &watch()), Err(Error::OutOfOrder));
        assert_eq!(w.record(&Record::new(T)), Err(Error::OutOfOrder));
        assert_eq!(w.lap(T), Err(Error::OutOfOrder));
        assert_eq!(w.end(T), Err(Error::OutOfOrder));
        assert_eq!(w.st.written, written, "nothing written");
        w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
        w.record(&Record::new(T)).unwrap();
        w.lap(T).unwrap();
        w.end(T).unwrap();
        assert!(w.st.act.ended());
    });
}

#[test]
fn nothing_after_the_end() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
        w.end(at(1)).unwrap();
        let written = w.st.written;
        assert_eq!(w.record(&Record::new(at(1))), Err(Error::OutOfOrder));
        assert_eq!(w.session(at(1), Sport::RUNNING, SubSport::GENERIC), Err(Error::OutOfOrder));
        assert_eq!(w.end(at(1)), Err(Error::OutOfOrder));
        assert_eq!(w.start(at(1), &watch()), Err(Error::OutOfOrder));
        assert_eq!(w.st.written, written);
    });
}

#[test]
fn the_timer_pauses_and_resumes_in_turn() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        assert_eq!(w.pause(T), Err(Error::OutOfOrder));
        assert_eq!(w.resume(T), Err(Error::OutOfOrder));
        assert_eq!(w.st.act.timer_at(at(9)), 0, "not before the first session");
        w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
        assert_eq!(w.resume(T), Err(Error::OutOfOrder));
        w.pause(at(1)).unwrap();
        assert_eq!(w.pause(at(1)), Err(Error::OutOfOrder));
        w.resume(at(5)).unwrap();
        assert_eq!(w.st.act.timer_at(at(7)), 3);
        w.pause(at(8)).unwrap();
        assert_eq!(w.st.act.timer_at(at(20)), 4);
    });
}

#[test]
fn time_never_goes_back() {
    run(|w| {
        w.start(at(10), &watch()).unwrap();
        w.session(at(10), Sport::RUNNING, SubSport::GENERIC).unwrap();
        w.record(&Record::new(at(12))).unwrap();
        let written = w.st.written;
        assert_eq!(w.record(&Record::new(at(11))), Err(Error::TimeWentBack));
        assert_eq!(w.lap(at(11)), Err(Error::TimeWentBack));
        assert_eq!(w.pause(at(11)), Err(Error::TimeWentBack));
        assert_eq!(w.session(at(11), Sport::RUNNING, SubSport::GENERIC), Err(Error::TimeWentBack));
        assert_eq!(w.end(at(11)), Err(Error::TimeWentBack));
        assert_eq!(w.st.written, written);
        w.record(&Record::new(at(12))).unwrap();
        w.end(at(12)).unwrap();
    });
}

#[test]
fn a_refused_value_changes_nothing() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
        let before = w.st.act;
        let _ = before.phase;
        assert_eq!(w.record(&Record::new(at(1)).heart_rate(255)), Err(Error::OutOfRange));
        assert_eq!(w.st.act.now, before.now);
        let written = w.st.written;
        assert_eq!(w.session(at(2), Sport::new(255), SubSport::GENERIC), Err(Error::OutOfRange));
        assert_eq!(w.session(at(2), Sport::RUNNING, SubSport::new(255)), Err(Error::OutOfRange));
        assert_eq!(w.st.written, written, "the open session is not closed");
        assert_eq!(w.st.act.session.map(|s| s.sport), Some(Sport::RUNNING));
    });
}

#[test]
fn sensors_take_the_next_device_index() {
    let st = run(|w| {
        w.start(T, &watch()).unwrap();
        for _ in 0..SENSORS_MAX {
            w.device(&watch()).unwrap();
        }
        assert_eq!(w.device(&watch()), Err(Error::IndexFull));
    });
    assert_eq!(st.act.devices, 254);
    assert_eq!(SENSORS_MAX, 254);
}

#[test]
fn summaries() {
    let mut stat = Stat::default();
    assert_eq!(stat.summary(), None);
    assert_eq!(stat.summary_u8(), (None, None));
    for v in [100, 101] {
        stat.add(v);
    }
    assert_eq!(stat.summary(), Some((101, 101)), "100.5 rounds up");
    stat.add(90);
    assert_eq!(stat.summary_u8(), (Some(97), Some(101)));
    stat.add(300);
    assert_eq!(stat.summary_u8(), (Some(148), None), "a maximum too large for its field");
    assert_eq!(stat.summary_u16(), (Some(148), Some(300)));

    let mut t = Temperatures::default();
    assert_eq!((t.average(), t.max), (None, None));
    for v in [-3, -4] {
        t.add(v);
    }
    assert_eq!((t.average(), t.max), (Some(-4), Some(-3)), "-3.5 rounds away from zero");
    t.add(10);
    assert_eq!((t.average(), t.max), (Some(1), Some(10)));
}

#[test]
fn milliseconds_out_of_range_are_none_which_is_refused() {
    assert_eq!(DURATION_SECONDS_MAX, 4_294_967);
    assert_eq!(ms(DURATION_SECONDS_MAX), 4_294_967_000);
    assert_eq!(ms(DURATION_SECONDS_MAX + 1), u32::MAX);
    assert_eq!(ms(u32::MAX), u32::MAX);
}

#[test]
fn an_unended_activity_is_refused() {
    let unended = |w: &mut Writer<'_>| {
        w.start(T, &watch())?;
        w.session(T, Sport::RUNNING, SubSport::GENERIC)
    };
    assert_eq!(
        plan(Options::new(), &mut |w: &mut Writer<'_>| unended(w), true),
        Err(Error::Unfinished)
    );
    assert_eq!(super::super::size(Options::new(), unended), Err(Error::Unfinished));
    let mut buf = [0u8; 256];
    let r = write(SliceSink::new(&mut buf), Options::new(), unended);
    assert_eq!(r.map(|_| ()), Err(WriteError::Source(Error::Unfinished)));
    assert_eq!(buf, [0; 256], "nothing written");
    let mut one = OnePass::new(SliceSink::new(&mut buf), Options::new()).unwrap();
    unended(&mut one.writer()).unwrap();
    let error = one.finish().map(|_| ()).map_err(|e| e.into_parts().0);
    assert_eq!(error, Err(WriteError::Source(Error::Unfinished)));
}

#[test]
fn a_start_refused_writes_nothing() {
    run(|w| {
        let long = watch().product_name("0123456789abcdefghij");
        assert_eq!(w.start(T, &long), Err(Error::StringTooLong));
        assert_eq!(w.start(T, &watch().serial_number(0)), Err(Error::OutOfRange));
        assert_eq!(w.start(T, &watch().product_name("Open\0Water")), Err(Error::OutOfRange));
        assert_eq!(w.st.written, 0, "not even the file_id");
        w.start(T, &watch()).unwrap();
    });
}

#[test]
fn a_span_too_long_for_milliseconds_is_refused_whole() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
        // Paused, so only the elapsed times are too long, not the timer's.
        w.pause(at(1)).unwrap();
        let written = w.st.written;
        let too_long = at(DURATION_SECONDS_MAX + 1);
        assert_eq!(w.lap(too_long), Err(Error::OutOfRange));
        assert_eq!(w.end(too_long), Err(Error::OutOfRange));
        assert_eq!(w.session(too_long, Sport::CYCLING, SubSport::GENERIC), Err(Error::OutOfRange));
        assert_eq!(w.st.written, written, "not even the timer's stop");
        w.lap(at(DURATION_SECONDS_MAX)).unwrap();
        w.end(at(DURATION_SECONDS_MAX)).unwrap();
    });
}

#[test]
fn a_call_after_which_the_activity_could_not_end_is_refused() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
        w.session(at(3_000_000), Sport::CYCLING, SubSport::GENERIC).unwrap();
        let too_long = at(4_294_968);
        let written = w.st.written;
        assert_eq!(w.record(&Record::new(too_long).heart_rate(90)), Err(Error::OutOfRange));
        assert_eq!(w.pause(too_long), Err(Error::OutOfRange));
        assert_eq!(w.session(too_long, Sport::RUNNING, SubSport::GENERIC), Err(Error::OutOfRange));
        assert_eq!(w.st.written, written);
        w.pause(at(4_000_000)).unwrap();
        assert_eq!(w.resume(at(7_400_000)), Err(Error::OutOfRange));
        w.end(at(4_294_967)).unwrap();
    });
    let mut st = State::new(Options::new().utc_offset(-0x1122_3345), None);
    let mut w = Writer { out: &mut Counter, st: &mut st };
    assert_eq!(w.start(T, &watch()), Err(Error::OutOfRange));
    assert_eq!(w.st.written, 0);
}

#[test]
fn laps_and_sessions_leave_an_index_for_the_end() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
        w.st.laps = 0x0FFD;
        w.lap(at(1)).unwrap();
        let written = w.st.written;
        assert_eq!(w.lap(at(2)), Err(Error::IndexFull));
        assert_eq!(w.session(at(2), Sport::CYCLING, SubSport::GENERIC), Err(Error::IndexFull));
        assert_eq!(w.st.written, written);
        w.end(at(2)).unwrap();
    });
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
        w.st.sessions = 0x0FFE;
        assert_eq!(w.session(at(1), Sport::CYCLING, SubSport::GENERIC), Err(Error::IndexFull));
        w.end(at(1)).unwrap();
    });
}

/// A record with every field.
fn full(t: Timestamp, metres: f64) -> Record {
    Record::new(t)
        .position(crate::Position::from_degrees(45.0 + metres / 1e4, -75.0).unwrap())
        .altitude(Altitude::barometric_meters(100.0 + metres))
        .heart_rate(140)
        .cadence_rpm(80)
        .distance_advanced_meters(3.0)
        .speed_meters_per_second(3.0 + metres)
        .power_watts(200)
        .temperature_celsius(20)
}

#[test]
fn an_activity_filled_to_the_size_limit_still_ends() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
        w.st.written = LIMIT - 2_000;
        let mut refused = None;
        for s in 0..1_000 {
            if let Err(e) = w.record(&full(at(s), 0.0)) {
                refused = Some(e);
                break;
            }
        }
        assert_eq!(refused, Some(Error::TooLarge));
        let written = w.st.written;
        assert_eq!(w.session(at(1_000), Sport::CYCLING, SubSport::GENERIC), Err(Error::TooLarge));
        assert_eq!(w.st.written, written, "not even the lap");
        w.end(at(1_000)).unwrap();
        assert!(w.st.written <= LIMIT);
    });
}

#[test]
fn every_call_leaves_room_for_the_end() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
        w.record(&full(T, 0.0)).unwrap();
        let size = w.st.written;
        w.record(&full(at(1), 0.0)).unwrap();
        let size = w.st.written - size;

        w.st.written = LIMIT - END - size + 1;
        assert_eq!(w.record(&full(at(2), 0.0)), Err(Error::TooLarge), "one byte short");
        assert_eq!(w.st.written, LIMIT - END - size + 1);
        w.st.written = LIMIT - END - size;
        w.record(&full(at(2), 0.0)).unwrap();
        assert_eq!(w.st.written, LIMIT - END, "only the end's bytes left");

        assert_eq!(w.record(&Record::new(at(2))), Err(Error::TooLarge));
        assert_eq!(w.lap(at(2)), Err(Error::TooLarge));
        assert_eq!(w.pause(at(2)), Err(Error::TooLarge));
        assert_eq!(w.device(&watch()), Err(Error::TooLarge));
        assert_eq!(w.session(at(2), Sport::CYCLING, SubSport::GENERIC), Err(Error::TooLarge));
        assert_eq!(w.st.written, LIMIT - END, "nothing written");
        w.end(at(2)).unwrap();
    });
}

/// Runs `call` with one byte too few left before the end's, then with just enough, and checks
/// it wrote nothing the first time, and `size` bytes the second.
fn at_the_limit(
    w: &mut Writer<'_>,
    size: u32,
    mut call: impl FnMut(&mut Writer<'_>) -> Result<(), Error>,
) {
    let act = w.st.act;
    let dev = std::format!("{:?}", w.st.dev);
    w.st.written = LIMIT - END - size + 1;
    assert_eq!(call(w), Err(Error::TooLarge), "one byte short");
    assert_eq!(w.st.written, LIMIT - END - size + 1, "nothing written");
    assert_eq!(std::format!("{:?}", w.st.act), std::format!("{act:?}"), "nothing changed");
    assert_eq!(std::format!("{:?}", w.st.dev), dev, "nothing declared");
    w.st.written = LIMIT - END - size;
    call(w).unwrap();
    assert_eq!(w.st.written, LIMIT - END);
}

#[test]
fn lengths_rests_and_sets_leave_room_for_the_end() {
    let free = Length::swum(SwimStroke::FREESTYLE, 15);
    run(|w| {
        pool_swim(w);
        w.length(at(30), &free).unwrap();
        // Its layout defined already.
        at_the_limit(w, 28, |w| w.length(at(60), &free));
        // The lap of lengths before it, with its definition.
        at_the_limit(w, 116, |w| w.rest(at(60)));
        // An idle length with its definition, and its lap.
        at_the_limit(w, 52 + 94, |w| w.end_rest(at(90)));
        w.end(at(90)).unwrap();
    });
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::TRAINING, SubSport::STRENGTH_TRAINING).unwrap();
        at_the_limit(w, 42, |w| w.set(at(30), &Set::new().repetitions(8)));
        w.rest(at(30)).unwrap();
        at_the_limit(w, 37, |w| w.end_rest(at(60)));
        w.end(at(60)).unwrap();
    });
}

#[test]
fn beat_intervals_leave_room_for_the_end() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
        w.beat_intervals_ms(&[800; 4]).unwrap();
        // Two messages: the first with its definition.
        at_the_limit(w, 9 + 11 + 11, |w| w.beat_intervals_ms(&[800; 7]));
        assert_eq!(w.st.act.beat_count, 1);
        w.beat_intervals_ms(&[800; 3]).unwrap();
        // The beats waiting, then the record after them.
        let record = Record::new(at(1)).heart_rate(75);
        at_the_limit(w, 11 + 6 + 2 * 3 + 1 + 5, |w| w.record(&record));
        assert_eq!(w.st.act.beat_count, 0);
        w.end(at(2)).unwrap();
    });
}

#[test]
fn developer_fields_leave_room_for_the_end() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        let mut dev = None;
        let app = crate::Developer::new([7; 16]);
        // Its definition, then its ID and index.
        at_the_limit(w, 12 + 18, |w| w.developer(&app).map(|d| dev = Some(d)));
        let dev = dev.unwrap();
        let mut field = None;
        let description = dev.field::<u16, InRecord>(0, "f").units("u");
        at_the_limit(w, 110, |w| w.declare(&description).map(|f| field = Some(f)));
        let field = field.unwrap();
        w.st.written = 0;
        w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
        w.beat_intervals_ms(&[800; 2]).unwrap();
        let record = Record::new(at(1)).heart_rate(75);
        // The beats waiting, then the record, both with their definitions.
        at_the_limit(w, 20 + 16 + 8, |w| w.record_with(&record, &[field.value(3)]));
        assert_eq!(w.st.act.beat_count, 0);
        w.end(at(2)).unwrap();
    });
}

#[test]
fn raw_fields_and_messages_leave_room_for_the_end() {
    use crate::RawField;
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::CYCLING, SubSport::ROAD).unwrap();
        w.beat_intervals_ms(&[800; 2]).unwrap();
        let breaths = [RawField::number(108, 1850u16).into()];
        // The beats waiting, then the record, both with their definitions.
        at_the_limit(w, 20 + 12 + 7, |w| w.record_with(&Record::new(at(1)), &breaths));
        let gear = [
            RawField::number(253, at(2).fit()),
            RawField::enumeration(0, 43),
            RawField::enumeration(1, 3),
        ];
        at_the_limit(w, 15 + 7, |w| w.raw_message(21, &gear));
        w.end(at(2)).unwrap();
    });
}

#[test]
fn a_new_session_leaves_room_for_the_end() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
        w.st.written = LIMIT - END - SWITCH + 1;
        let written = w.st.written;
        assert_eq!(w.session(at(1), Sport::CYCLING, SubSport::GENERIC), Err(Error::TooLarge));
        assert_eq!(w.st.written, written);
        w.st.written = LIMIT - END - SWITCH;
        w.session(at(1), Sport::CYCLING, SubSport::GENERIC).unwrap();
        w.end(at(2)).unwrap();
    });
    run(|w| {
        pool_swim(w);
        w.rest(T).unwrap();
        w.st.written = LIMIT - END - SWITCH + 1;
        let written = w.st.written;
        assert_eq!(w.session(at(1), Sport::RUNNING, SubSport::GENERIC), Err(Error::TooLarge));
        assert_eq!((w.st.written, w.st.act.lengths), (written, 0), "not even the idle length");
        w.st.written = LIMIT - END - SWITCH;
        w.session(at(1), Sport::RUNNING, SubSport::GENERIC).unwrap();
        w.end(at(2)).unwrap();
    });
}

/// A record with every field a pool swim's records take.
fn swim(t: Timestamp, metres: f64) -> Record {
    Record::new(t)
        .position(crate::Position::from_degrees(45.0 + metres / 1e4, -75.0).unwrap())
        .altitude(Altitude::barometric_meters(100.0 + metres))
        .heart_rate(140)
        .power_watts(200)
        .temperature_celsius(20)
}

/// The largest end: a pool swim whose last lap and session have every field, every developer
/// field the file may hold among them, ended during a rest with beat intervals waiting, every
/// layout to be defined again.
fn the_largest_end(w: &mut Writer<'_>) {
    w.start(T, &watch()).unwrap();
    let dev = w.developer(&crate::Developer::new([7; 16])).unwrap();
    let long = SUMMARY_BYTES_MAX - (DEVELOPER_FIELDS_MAX - 1);
    let long: LapField<str> =
        w.declare(&dev.string(0, "notes", u8::try_from(long - 1).unwrap())).unwrap();
    let mut laps = std::vec::Vec::new();
    let mut sessions = std::vec::Vec::new();
    for n in 1..u8::try_from(DEVELOPER_FIELDS_MAX).unwrap() {
        if n % 2 == 0 {
            laps.push(w.declare::<u8, InLap>(&dev.field(n, "l")).unwrap());
        } else {
            sessions.push(w.declare::<u8, InSession>(&dev.field(n, "s")).unwrap());
        }
    }
    w.pool_swim(T, Pool::meters(25.0)).unwrap();
    for s in 0..4 {
        w.record(&swim(at(s * 30), f64::from(s) * 3.0)).unwrap();
        let stroke = if s == 0 { SwimStroke::BACKSTROKE } else { SwimStroke::FREESTYLE };
        w.length(at(s * 30 + 20 + s), &Length::swum(stroke, 15)).unwrap();
    }
    w.rest(at(120)).unwrap();
    w.record(&swim(at(121), 0.0)).unwrap();
    w.beat_intervals_ms(&[800, 810, 790]).unwrap();
    w.developer_value(&long, "the longest note a file can hold, the rest of its bytes").unwrap();
    for f in &laps {
        w.developer_value(f, 1).unwrap();
    }
    for f in &sessions {
        w.developer_value(f, 2).unwrap();
    }
    // A rest's lap has no strokes; the reserve counts a lap with every field.
    if let Some(s) = w.st.act.session.as_mut() {
        s.lap = s.span;
    }
    w.st.locals = Locals::new();
}

#[test]
fn the_largest_end_takes_exactly_the_bytes_kept_for_it() {
    assert_eq!(END, 795);
    assert_eq!(SWITCH, 750);
    let mut st = State::new(Options::new().utc_offset(3600), None);
    let mut w = Writer { out: &mut Counter, st: &mut st };
    the_largest_end(&mut w);
    assert_eq!(w.st.act.kept_for_end(), END);
    w.st.written = LIMIT - END;
    w.end(at(130)).unwrap();
    assert_eq!(w.st.written, LIMIT);
    assert_eq!(w.st.act.kept_for_end(), 0);
}

/// Where each data message in a file's messages starts, and its global number.
fn data_messages(data: &[u8]) -> Vec<(u32, u16)> {
    let mut layouts = [(0, 0); 16];
    let mut found = Vec::new();
    let mut i = 0;
    while let Some(&h) = data.get(i) {
        if h & 0xC0 == 0x40 {
            let global = u16::from_le_bytes([data[i + 3], data[i + 4]]);
            let n = usize::from(data[i + 5]);
            let mut fields = data[i + 6..i + 6 + 3 * n].to_vec();
            i += 6 + 3 * n;
            // Developer fields follow, with their count.
            if h & 0x20 != 0 {
                let n = usize::from(data[i]);
                fields.extend_from_slice(&data[i + 1..i + 1 + 3 * n]);
                i += 1 + 3 * n;
            }
            let size = fields.chunks(3).map(|f| usize::from(f[1])).sum();
            layouts[usize::from(h & 0x0F)] = (global, size);
        } else {
            let local = if h & 0x80 == 0 { h & 0x0F } else { (h >> 5) & 0x03 };
            let (global, size) = layouts[usize::from(local)];
            found.push((u32::try_from(i).unwrap(), global));
            i += 1 + size;
        }
    }
    found
}

/// What the end and a session ending another write, as [`END`] and [`SWITCH`] count it: a
/// message written here that they do not list fails this.
#[test]
fn the_end_and_a_switch_write_only_what_is_kept_for_them() {
    let mut buf = [0u8; 4096];
    let mut one = OnePass::new(SliceSink::new(&mut buf), Options::new()).unwrap();
    let mut w = one.writer();
    // Each ends a rest with developer values staged, and the end has beat intervals waiting.
    w.start(T, &watch()).unwrap();
    let dev = w.developer(&crate::Developer::new([7; 16])).unwrap();
    let lap = w.declare::<u8, InLap>(&dev.field(0, "l")).unwrap();
    let session = w.declare::<u8, InSession>(&dev.field(1, "s")).unwrap();
    w.pool_swim(T, Pool::meters(25.0)).unwrap();
    w.length(at(1), &Length::swum(SwimStroke::FREESTYLE, 15)).unwrap();
    w.rest(at(1)).unwrap();
    w.developer_value(&lap, 1).unwrap();
    w.developer_value(&session, 2).unwrap();
    let switch = w.st.written;
    w.session(at(2), Sport::TRAINING, SubSport::STRENGTH_TRAINING).unwrap();
    let set = w.st.written;
    w.set(at(3), &Set::new().repetitions(5)).unwrap();
    w.rest(at(3)).unwrap();
    w.beat_intervals_ms(&[800; 3]).unwrap();
    w.developer_value(&lap, 3).unwrap();
    w.developer_value(&session, 4).unwrap();
    let end = w.st.written;
    w.end(at(4)).unwrap();
    let len = w.st.written;
    one.finish().unwrap();
    let messages = data_messages(&buf[14..14 + len as usize]);
    let written = |from, to| {
        let range = from..to;
        messages.iter().filter(|(at, _)| range.contains(at)).map(|&(_, g)| g).collect::<Vec<_>>()
    };
    let switched = [LengthMsg::GLOBAL, Lap::GLOBAL, Session::GLOBAL, SportMsg::GLOBAL];
    assert_eq!(written(switch, set), switched);
    assert_eq!(written(set, end), [SetMsg::GLOBAL]);
    let ended = [SetMsg::GLOBAL, Hrv::GLOBAL, Event::GLOBAL, Lap::GLOBAL, Session::GLOBAL];
    assert_eq!(written(end, len), [&ended[..], &[Activity::GLOBAL]].concat());
}

#[test]
fn an_end_that_failed_leaves_the_activity_unfinished() {
    let mut pass = 0;
    let source = |w: &mut Writer<'_>| {
        pass += 1;
        w.start(T, &watch())?;
        w.session(T, Sport::RUNNING, SubSport::GENERIC)?;
        w.record(&Record::new(at(1)).heart_rate(100))?;
        if pass == 2 {
            w.record(&Record::new(at(2)).heart_rate(100))?;
        }
        assert_eq!(w.end(at(3)).is_err(), pass == 2);
        Ok(())
    };
    let mut buf = [0u8; 1024];
    let r = write(SliceSink::new(&mut buf), Options::new(), source);
    assert_eq!(r.map(|_| ()), Err(WriteError::Source(Error::Unfinished)));
}

#[test]
fn the_largest_switch_takes_exactly_the_bytes_kept_for_it() {
    let name = "Twenty-three bytes long";
    assert_eq!(name.len(), crate::SPORT_NAME_MAX);
    for (kept, written) in
        [(SWITCH, Ok(())), (SWITCH - most(SportMsg::FIELDS), Err(Error::TooLarge))]
    {
        let mut st = State::new(Options::new().utc_offset(3600), None);
        let mut w = Writer { out: &mut Counter, st: &mut st };
        the_largest_end(&mut w);
        w.st.written = LIMIT - END - kept;
        let switched = w.leg(at(130), &Leg::new(Sport::CYCLING, SubSport::ROAD).named(name));
        assert_eq!(switched, written, "kept {kept}");
        if switched.is_ok() {
            assert_eq!(w.st.written, LIMIT - END, "its sport, defined, the last of it");
        }
    }
}

#[test]
fn the_first_session_leaves_room_for_the_end() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        // A timer start and a sport, each with its definition.
        at_the_limit(w, 15 + 7 + 12 + 3, |w| w.session(T, Sport::RUNNING, SubSport::GENERIC));
        w.end(at(1)).unwrap();
    });
}

#[test]
fn the_end_needs_room_for_each_part_of_its_largest() {
    let parts = [
        ("an idle length", REST),
        ("beat intervals", most(Hrv::FIELDS)),
        ("developer fields", DEV),
    ];
    for (part, size) in parts {
        let mut st = State::new(Options::new().utc_offset(3600), None);
        let mut w = Writer { out: &mut Counter, st: &mut st };
        the_largest_end(&mut w);
        w.st.written = LIMIT - (END - size);
        assert_eq!(w.end(at(130)), Err(Error::TooLarge), "kept without {part}");
    }
}

#[test]
fn record_values_out_of_range_are_refused() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
        let r = Record::new(at(1));
        for bad in [
            r.distance_meters(-0.01),
            r.distance_meters(f64::NAN),
            r.distance_meters(42_949_672.96),
            r.speed_meters_per_second(65.535),
            r.speed_meters_per_second(-1.0),
            r.altitude(Altitude::smoothed_meters(-500.2)),
            r.altitude(Altitude::smoothed_meters(12_606.9)),
            r.altitude(Altitude::smoothed_meters(f64::INFINITY)),
            r.power_watts(u16::MAX),
            r.cadence_rpm(u8::MAX),
            r.temperature_celsius(i8::MAX),
        ] {
            assert_eq!(w.record(&bad), Err(Error::OutOfRange), "{bad:?}");
        }
        for good in [
            r.distance_meters(0.0),
            r.distance_meters(42_949_672.94),
            r.speed_meters_per_second(65.534),
            r.altitude(Altitude::smoothed_meters(-500.0)),
            r.altitude(Altitude::smoothed_meters(12_606.8)),
            r.power_watts(u16::MAX - 1),
            r.cadence_rpm(u8::MAX - 1),
            r.temperature_celsius(i8::MIN),
        ] {
            assert_eq!(w.record(&good), Ok(()), "{good:?}");
        }
    });
}

#[test]
fn nothing_is_recorded_while_paused() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
        w.pause(at(1)).unwrap();
        let written = w.st.written;
        assert_eq!(w.record(&Record::new(at(2)).heart_rate(90)), Err(Error::Paused));
        assert_eq!(w.st.written, written);
        w.resume(at(3)).unwrap();
        w.record(&Record::new(at(3)).heart_rate(90)).unwrap();
    });
}

#[test]
fn the_encoder_keeps_the_distance() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::ROWING, SubSport::GENERIC).unwrap();
        let r = |s| Record::new(at(s));
        w.record(&r(1).distance_advanced_meters(1000.0)).unwrap();
        assert_eq!(w.st.act.distance, 100_000);
        // A counter that resets gives increments; a total may not go back.
        w.record(&r(2).distance_advanced_meters(400.0)).unwrap();
        assert_eq!(w.st.act.distance, 140_000);
        assert_eq!(w.record(&r(3).distance_meters(1399.99)), Err(Error::DistanceWentBack));
        w.record(&r(3).distance_meters(1400.0)).unwrap();
        w.record(&r(4).distance_meters(1500.0)).unwrap();
        assert_eq!(w.st.act.distance, 150_000);
        assert_eq!(w.record(&r(5).distance_advanced_meters(-1.0)), Err(Error::OutOfRange));
        let huge = r(5).distance_advanced_meters(42_949_672.0);
        assert_eq!(w.record(&huge), Err(Error::OutOfRange), "past the field");
        assert_eq!(w.st.act.distance, 150_000);
        let s = w.st.act.session.unwrap();
        assert_eq!(s.span.seen.totals(5).distance, Some(150_000), "from zero");
    });
}

#[test]
fn increments_keep_their_fractions() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::CYCLING, SubSport::GENERIC).unwrap();
        for s in 0..1000 {
            w.record(&Record::new(at(s)).distance_advanced_meters(1.004)).unwrap();
        }
        assert_eq!(w.st.act.distance, 100_400);
        for s in 1000..1999 {
            w.record(&Record::new(at(s)).distance_advanced_meters(0.004)).unwrap();
        }
        assert_eq!(w.st.act.distance, 100_799, "a total is never rounded up");
    });
}

/// `altitude`, taken as it is but for its threshold.
fn unaveraged(altitude: Altitude) -> Altitude {
    Altitude { window: 1, ..altitude }
}

#[test]
fn ascent_counts_sustained_climbs() {
    let climb = |threshold: f64, metres: &[f64]| {
        let mut act = Act::new();
        let mut total = (0, 0);
        for &m in metres {
            let (up, down) =
                act.climb_to(unaveraged(Altitude::meters_with_threshold(m, threshold)));
            total = (total.0 + up, total.1 + down);
        }
        total
    };
    let dither: std::vec::Vec<f64> = (0..3600).map(|i| 100.0 + f64::from(i % 2) * 0.2).collect();
    assert_eq!(climb(2.0, &dither), (0, 0), "noise is not a climb");
    assert_eq!(climb(0.0, &dither), (1800, 1799), "unless every change counts");
    // A steady climb counts in full once it passes the threshold, and so does the descent.
    assert_eq!(climb(2.0, &[100.0, 101.0, 102.0, 103.0, 101.4, 100.6]), (15, 12));
    // A dip smaller than the threshold does not end the climb.
    assert_eq!(climb(2.0, &[100.0, 103.0, 101.4, 104.0]), (20, 0));
    // Below the threshold, nothing; past it from the extreme it left, all of it.
    assert_eq!(climb(10.0, &[100.0, 109.0, 101.0, 100.0]), (0, 0));
    assert_eq!(climb(10.0, &[100.0, 109.0, 92.0, 100.0]), (0, 85));
    assert_eq!(climb(10.0, &[100.0, 91.0, 108.0, 100.0]), (85, 0));
    assert_eq!(climb(10.0, &[100.0, 109.0, 89.0, 100.0]), (55, 100));
    assert_eq!(climb(10.0, &[100.0, 110.0]), (50, 0), "the threshold itself counts");
    assert_eq!(climb(10.0, &[100.0, 90.0]), (0, 50));
    // A new source starts the filter afresh.
    let mut act = Act::new();
    assert_eq!(act.climb_to(Altitude::barometric_meters(100.0)), (0, 0));
    assert_eq!(act.climb_to(Altitude::smoothed_meters(150.0)), (0, 0));
    assert_eq!(act.climb_to(Altitude::gnss_meters(150.0)), (0, 0));
    assert_eq!(act.climb_to(Altitude::smoothed_meters(161.0)), (0, 0));
    assert_eq!(act.climb_to(Altitude::smoothed_meters(161.2)), (1, 0));
    // So does a different window at the same threshold.
    assert_eq!(act.climb_to(Altitude::meters_with_threshold(200.0, 0.0)), (0, 0));
}

#[test]
fn ascent_averages_five_records() {
    let mut act = Act::new();
    let mut climbed = |m| act.climb_to(Altitude::barometric_meters(m));
    assert_eq!(climbed(100.0), (0, 0));
    // A spike of 4 m moves the average 0.8 m, short of a climb.
    assert_eq!(climbed(104.0), (0, 0));
    assert_eq!(climbed(100.0), (0, 0));
    // A step of 3 m counts once the average is 2 m above the lowest, and the rest as it
    // catches up, a little late while the spike leaves it.
    assert_eq!(climbed(103.0), (0, 0));
    assert_eq!(climbed(103.0), (10, 0));
    assert_eq!(climbed(103.0), (3, 0));
    assert_eq!(climbed(103.0), (0, 0));
    assert_eq!(climbed(103.0), (2, 0));
    assert_eq!(climbed(103.0), (0, 0), "the average has caught up");
}

/// Altitudes along `profile` every second for an hour, with the noise `noise` gives, and the
/// metres a filter of `altitude` counts up, beside those the profile truly climbs.
fn climbed_along(
    profile: impl Fn(f64) -> f64,
    mut noise: impl FnMut() -> f64,
    altitude: fn(f64) -> Altitude,
) -> (f64, f64) {
    let mut act = Act::new();
    let (mut counted, mut truly, mut last) = (0, 0.0, profile(0.0));
    for s in 0..3600 {
        let m = profile(f64::from(s));
        truly += (m - last).max(0.0);
        last = m;
        counted += act.climb_to(altitude(m + noise())).0;
    }
    (f64::from(counted) / 5.0, truly)
}

/// Noise of standard deviation `sd`, roughly normal, the same each run.
fn noise(seed: u64, sd: f64) -> impl FnMut() -> f64 {
    let mut x = seed;
    move || {
        let mut uniform = || {
            x ^= x << 13;
            x ^= x >> 7;
            x ^= x << 17;
            f64::from(u32::try_from(x >> 32).unwrap()) / 4_294_967_296.0
        };
        // Twelve uniforms less six have a standard deviation of one.
        ((0..12).map(|_| uniform()).sum::<f64>() - 6.0) * sd
    }
}

#[test]
fn ascent_follows_realistic_profiles() {
    use std::f64::consts::TAU;
    let close = |(counted, truly): (f64, f64), within: f64, what: &str| {
        assert!((counted - truly).abs() <= truly * within, "{what}: {counted} m for {truly} m");
    };
    let baro = Altitude::barometric_meters;
    // A barometer's half a metre of noise on the flat.
    let (counted, _) = climbed_along(|_| 100.0, noise(1, 0.5), baro);
    assert!(counted <= 1.0, "{counted} m on the flat");
    // Rolling hills 4 m and 10 m high, every five minutes, and one of 80 m every half hour.
    for (seed, height, period) in [(2, 4.0, 300.0), (3, 10.0, 300.0), (4, 80.0, 1800.0)] {
        let hills = move |s: f64| 100.0 + height / 2.0 * (TAU * s / period).sin();
        close(climbed_along(hills, noise(seed, 0.25), baro), 0.08, "hills");
    }
    // A 200 m climb and back, from satellites wandering a few metres.
    let mut wander = (noise(5, 3.0), 0.0);
    let gnss = move || {
        wander.1 = 0.97 * wander.1 + 0.24 * wander.0();
        wander.1
    };
    let pass = |s: f64| 100.0 + s.min(1800.0) / 9.0 - (s - 1800.0).max(0.0) / 9.0;
    close(climbed_along(pass, gnss, Altitude::gnss_meters), 0.05, "pass");
}

#[test]
fn a_pause_mid_climb_keeps_the_climb() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::CYCLING, SubSport::ROAD).unwrap();
        let mut noise = noise(6, 0.25);
        let mut ride = |w: &mut Writer<'_>, start: u32, from: f64| {
            for s in start..start + 300 {
                let m = from + f64::from(s - start) / 12.0 + noise();
                w.record(&Record::new(at(s)).altitude(Altitude::barometric_meters(m))).unwrap();
            }
        };
        // 25 m up, a pause, and 25 m on from 30 m higher than it stopped.
        ride(w, 0, 100.0);
        w.pause(at(300)).unwrap();
        w.resume(at(400)).unwrap();
        ride(w, 400, 155.0);
        let ascent = w.st.act.session.unwrap().span.seen.totals(1).ascent.unwrap();
        assert!((48..=50).contains(&ascent), "{ascent} m");
    });
}

#[test]
fn lap_ascents_add_up_to_the_session() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::HIKING, SubSport::GENERIC).unwrap();
        let mut laps = 0;
        for s in 0..100 {
            let m = 100.0 + 0.2 * f64::from(s);
            w.record(&Record::new(at(s)).altitude(Altitude::barometric_meters(m))).unwrap();
            if s % 7 == 6 {
                laps += w.st.act.session.unwrap().lap.seen.totals(1).ascent.unwrap();
                w.lap(at(s)).unwrap();
            }
        }
        let s = w.st.act.session.unwrap();
        laps += s.lap.seen.totals(1).ascent.unwrap();
        assert_eq!(laps, s.span.seen.totals(1).ascent.unwrap());
    });
}

#[test]
fn each_leg_climbs_from_where_it_starts() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        let alt = |s, m| Record::new(at(s)).altitude(unaveraged(Altitude::barometric_meters(m)));
        let ascent = |w: &Writer<'_>| w.st.act.session.unwrap().span.seen.totals(1).ascent;
        w.session(T, Sport::TRANSITION, SubSport::SWIM_TO_BIKE_TRANSITION).unwrap();
        for (s, m) in [(0, 100.0), (1, 101.0), (2, 101.6)] {
            w.record(&alt(s, m)).unwrap();
        }
        assert_eq!(ascent(w), Some(0), "1.6 m is short of a climb");
        w.session(at(3), Sport::CYCLING, SubSport::ROAD).unwrap();
        for (s, m) in [(3, 102.4), (4, 103.4)] {
            w.record(&alt(s, m)).unwrap();
        }
        assert_eq!(ascent(w), Some(0), "the transition's rise is not the ride's");
        w.record(&alt(5, 104.4)).unwrap();
        assert_eq!(ascent(w), Some(2), "the ride's own 2 m");
        w.session(at(6), Sport::TRANSITION, SubSport::BIKE_TO_RUN_TRANSITION).unwrap();
        w.record(&alt(6, 104.4)).unwrap();
        w.record(&alt(7, 102.8)).unwrap();
        w.session(at(8), Sport::RUNNING, SubSport::STREET).unwrap();
        w.record(&alt(8, 102.4)).unwrap();
        let t = w.st.act.session.unwrap().span.seen.totals(1);
        assert_eq!((t.ascent, t.descent), (Some(0), Some(0)), "nor its fall the run's");
    });
}

/// A run's satellite altitude rising 8.6 m and falling 18 m from there, then on after a pause.
#[test]
fn a_fall_from_the_peak_counts_across_a_pause() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::RUNNING, SubSport::STREET).unwrap();
        let alt = |s, m| Record::new(at(s)).altitude(unaveraged(Altitude::gnss_meters(m)));
        for (s, m) in [(1, 33.0), (2, 41.6), (3, 23.6)] {
            w.record(&alt(s, m)).unwrap();
        }
        w.pause(at(4)).unwrap();
        w.resume(at(5)).unwrap();
        w.record(&alt(5, 23.6)).unwrap();
        w.record(&alt(6, 18.6)).unwrap();
        let t = w.st.act.session.unwrap().span.seen.totals(4);
        assert_eq!((t.ascent, t.descent), (Some(0), Some(23)), "41.6 m down to 18.6 m");
    });
}

#[test]
fn a_pause_keeps_the_ascent_filter_but_not_its_jump() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::HIKING, SubSport::GENERIC).unwrap();
        let alt = |s, m| Record::new(at(s)).altitude(unaveraged(Altitude::barometric_meters(m)));
        w.record(&alt(1, 100.0)).unwrap();
        w.record(&alt(2, 101.4)).unwrap();
        w.pause(at(2)).unwrap();
        w.resume(at(3)).unwrap();
        w.record(&alt(3, 150.0)).unwrap();
        let s = w.st.act.session.unwrap();
        assert_eq!(s.span.seen.totals(3).ascent, Some(0), "not the 48.6 m across the pause");
        w.record(&alt(4, 150.6)).unwrap();
        let s = w.st.act.session.unwrap();
        assert_eq!(s.span.seen.totals(3).ascent, Some(2), "the 1.4 m before it and 0.6 m after");
    });
}

#[test]
fn a_maximum_speed_below_the_average_is_left_out() {
    let mut seen = Seen::new(0);
    let fast = Record::new(T).speed_meters_per_second(5.0);
    let mut moved = Record::new(T);
    moved.distance = Some(10_000);
    seen.add(&fast, None);
    seen.add(&moved, None);
    // 100 m in 10 s is 10 m/s on average, above the 5 m/s sampled.
    assert_eq!((seen.totals(10).avg_speed, seen.totals(10).max_speed), (Some(10_000), None));
    // 100 m in 20 s is 5 m/s: the maximum stands.
    assert_eq!(seen.totals(20).max_speed, Some(5000));
    assert_eq!(Seen::new(0).totals(10).max_speed, None);
}

#[test]
fn a_box_across_the_antimeridian_wraps() {
    let deg = |d: f64| Position::from_degrees(0.0, d).unwrap().semicircles().1;
    let mut longs = Longitudes::new(deg(179.0));
    longs.add(deg(-179.0));
    assert_eq!(longs.west_east(), (deg(179.0), deg(-179.0)), "east of west, across 180");
    let mut longs = Longitudes::new(deg(-10.0));
    longs.add(deg(10.0));
    assert_eq!(longs.west_east(), (deg(-10.0), deg(10.0)));
    let mut longs = Longitudes::new(deg(-170.0));
    longs.add(deg(10.0));
    assert_eq!(longs.west_east(), (deg(-170.0), deg(10.0)), "the narrower is 180 wide");
}

#[test]
fn an_unfinished_file_can_be_ended_and_finished_again() {
    let mut buf = [0u8; 512];
    let mut one = OnePass::new(SliceSink::new(&mut buf), Options::new()).unwrap();
    let mut w = one.writer();
    w.start(T, &watch()).unwrap();
    w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
    let e = one.finish().map(|_| ()).unwrap_err();
    assert_eq!(e.error(), &WriteError::Source(Error::Unfinished));
    assert_eq!(std::format!("{e}"), "the activity was not ended");
    assert_eq!(std::format!("{e:?}"), "FinishError { error: Source(Unfinished), .. }");
    let mut one = e.into_inner();
    one.writer().end(at(1)).unwrap();
    let sink = one.finish().unwrap();
    let mut crc = crate::Crc::new();
    crc.update(sink.written());
    assert_eq!(crc.value(), 0, "a whole file");

    let mut buf = [0u8; 512];
    let one = OnePass::new(SliceSink::new(&mut buf), Options::new()).unwrap();
    assert_eq!(one.into_sink().written().len(), 14);
}

fn pool_swim(w: &mut Writer<'_>) {
    w.start(T, &watch()).unwrap();
    w.pool_swim(T, Pool::meters(25.0)).unwrap();
}

#[test]
fn lengths_belong_to_pool_swims() {
    run(|w| {
        let free = Length::swum(SwimStroke::FREESTYLE, 15);
        w.start(T, &watch()).unwrap();
        assert_eq!(w.length(at(1), &free), Err(Error::OutOfOrder));
        assert_eq!(w.pool_swim(T, Pool::meters(0.0)), Err(Error::OutOfRange));
        assert_eq!(w.pool_swim(T, Pool::meters(655.35)), Err(Error::OutOfRange));
        w.session(T, Sport::SWIMMING, SubSport::OPEN_WATER).unwrap();
        assert_eq!(w.length(at(1), &free), Err(Error::OutOfOrder), "no pool");
        let written = w.st.written;
        let lap_swimming = w.session(at(1), Sport::SWIMMING, SubSport::LAP_SWIMMING);
        assert_eq!(lap_swimming, Err(Error::OutOfRange), "a pool swim needs its pool");
        let lap_swimming = w.session(at(1), Sport::GENERIC, SubSport::LAP_SWIMMING);
        assert_eq!(lap_swimming, Err(Error::OutOfRange));
        let lap_swimming =
            w.leg(at(1), &Leg::new(Sport::SWIMMING, SubSport::LAP_SWIMMING).named("Pool"));
        assert_eq!(lap_swimming, Err(Error::OutOfRange));
        let named =
            w.leg(at(1), &Leg::new(Sport::SWIMMING, SubSport::OPEN_WATER).named("Open\0Water"));
        assert_eq!(named, Err(Error::OutOfRange), "a name holding a NUL");
        let named = w.leg(at(1), &Leg::pool_swim(Pool::meters(25.0)).named("Pool\0Swim"));
        assert_eq!(named, Err(Error::OutOfRange));
        assert_eq!(w.st.written, written);
        w.pool_swim(at(1), Pool::meters(655.34)).unwrap();
        let written = w.st.written;
        let r = Record::new(at(2)).heart_rate(120);
        assert_eq!(w.record(&r.distance_meters(1.0)), Err(Error::GivenByLengths));
        assert_eq!(w.record(&r.distance_advanced_meters(1.0)), Err(Error::GivenByLengths));
        assert_eq!(w.record(&r.speed_meters_per_second(1.0)), Err(Error::GivenByLengths));
        assert_eq!(w.record(&r.cadence_rpm(30)), Err(Error::GivenByLengths));
        assert_eq!(w.set(at(2), &Set::new()), Err(Error::OutOfOrder));
        w.pause(at(2)).unwrap();
        assert_eq!(w.length(at(3), &free), Err(Error::Paused));
        w.resume(at(3)).unwrap();
        w.rest(at(4)).unwrap();
        assert_eq!(w.length(at(5), &free), Err(Error::OutOfOrder), "resting");
        assert_eq!(w.lap(at(5)), Err(Error::OutOfOrder), "a rest is a lap of its own");
        assert_eq!(w.rest(at(5)), Err(Error::OutOfOrder));
        w.record(&Record::new(at(5)).heart_rate(120)).unwrap();
        w.end_rest(at(6)).unwrap();
        assert_eq!(w.end_rest(at(6)), Err(Error::OutOfOrder));
        assert!(w.st.written > written);
        w.record(&Record::new(at(7)).heart_rate(121)).unwrap();
        w.length(at(9), &free).unwrap();
        assert_eq!(w.st.act.distance, 65_534);
        w.lap(at(10)).unwrap();
        assert_eq!(w.st.act.session.unwrap().mark.0, at(10), "the next length starts here");
    });
}

#[test]
fn a_pool_swims_lengths_give_its_laps_and_session() {
    run(|w| {
        pool_swim(w);
        w.length(at(30), &Length::swum(SwimStroke::FREESTYLE, 15)).unwrap();
        w.length(at(58), &Length::swum(SwimStroke::FREESTYLE, 13)).unwrap();
        let lap = w.st.act.session.unwrap().lap.seen.totals(58);
        assert_eq!(lap.distance, Some(5000));
        assert_eq!((lap.lengths, lap.active_lengths, lap.cycles), (Some(2), Some(2), Some(28)));
        assert_eq!(lap.stroke_distance, Some(179), "5000 cm over 28 strokes");
        assert_eq!(lap.swim_stroke, Some(SwimStroke::FREESTYLE));
        // 30 and 27.86 strokes a minute; 0.833 and 0.893 m/s.
        assert_eq!((lap.avg_cadence, lap.max_cadence), (Some(29), Some(30)));
        assert_eq!((lap.avg_speed, lap.max_speed), (Some(862), Some(893)));
        assert_eq!(w.st.act.session.unwrap().lap.seen.first_length, Some(0));

        w.rest(at(60)).unwrap();
        assert_eq!(w.st.laps, 1, "the lap of lengths ends where the rest starts");
        w.end_rest(at(90)).unwrap();
        assert_eq!((w.st.laps, w.st.act.lengths), (2, 3));
        w.rest(at(90)).unwrap();
        assert_eq!(w.st.laps, 2, "a lap with no lengths stays open");
        w.end_rest(at(95)).unwrap();
        w.length(at(125), &Length::swum(SwimStroke::BACKSTROKE, 20)).unwrap();
        w.length(at(155), &Length::swum(SwimStroke::DRILL, 0)).unwrap();
        let s = w.st.act.session.unwrap();
        let lap = s.lap.seen.totals(60);
        assert_eq!(s.lap.seen.first_length, Some(4));
        assert_eq!((lap.lengths, lap.active_lengths, lap.cycles), (Some(2), Some(2), Some(20)));
        assert_eq!(lap.stroke_distance, Some(125), "a drill's distance has no strokes");
        assert_eq!(lap.swim_stroke, Some(SwimStroke::MIXED));
        assert_eq!((lap.avg_cadence, lap.max_cadence), (Some(40), Some(40)));
        let session = s.span.seen.totals(155);
        assert_eq!(session.distance, Some(10_000));
        assert_eq!((session.lengths, session.active_lengths), (Some(6), Some(4)));
        assert_eq!((session.cycles, session.stroke_distance), (Some(48), Some(156)));
        assert_eq!(session.swim_stroke, Some(SwimStroke::MIXED));
    });
}

#[test]
fn a_rest_lap_covers_no_distance() {
    let mut seen = Seen::new(700);
    let msg = |swum| LengthMsg {
        span: Span { start_time: T, timestamp: T, total_elapsed_ms: 0, total_timer_ms: 0 },
        swum,
        avg_speed: None,
        cadence: None,
    };
    seen.add_length(3, None, 700, &msg(None));
    let t = seen.totals(10);
    assert_eq!((t.distance, t.avg_speed, t.cycles), (Some(0), Some(0), Some(0)));
    assert_eq!((t.lengths, t.active_lengths, t.stroke_distance), (Some(1), Some(0), None));
    assert_eq!((t.swim_stroke, seen.first_length), (None, Some(3)));
    let none = Seen::new(0).totals(10);
    assert_eq!((none.cycles, none.lengths, none.active_lengths), (None, None, None));
    let drill = Some(Length::drill());
    seen.add_length(4, drill.map(|l| (l, 2500)), 3200, &msg(drill));
    let t = seen.totals(10);
    assert_eq!(
        (t.cycles, t.stroke_distance, t.swim_stroke),
        (Some(0), None, Some(SwimStroke::DRILL))
    );
}

#[test]
fn a_length_too_quick_to_time_has_no_speed_or_cadence() {
    run(|w| {
        pool_swim(w);
        w.length(T, &Length::swum(SwimStroke::FREESTYLE, 4)).unwrap();
        let lap = w.st.act.session.unwrap().lap.seen.totals(0);
        assert_eq!((lap.max_speed, lap.avg_cadence, lap.cycles), (None, None, Some(4)));
        // 2.5 m/s and 254 strokes a minute are the most their fields hold.
        w.length(at(10), &Length::swum(SwimStroke::FREESTYLE, 42)).unwrap();
        w.length(at(20), &Length::swum(SwimStroke::FREESTYLE, 43)).unwrap();
        let lap = w.st.act.session.unwrap().lap.seen.totals(30);
        assert_eq!((lap.max_speed, lap.avg_cadence), (Some(2500), Some(252)));
        assert_eq!(lap.max_cadence, Some(252), "258 is past the field");
        assert_eq!(
            w.length(at(20), &Length::swum(SwimStroke::FREESTYLE, u16::MAX)),
            Err(Error::OutOfRange)
        );
    });
}

#[test]
fn a_rest_ends_with_the_session_or_the_activity() {
    run(|w| {
        pool_swim(w);
        w.length(at(30), &Length::swum(SwimStroke::FREESTYLE, 15)).unwrap();
        w.rest(at(30)).unwrap();
        w.session(at(40), Sport::TRAINING, SubSport::GENERIC).unwrap();
        assert_eq!((w.st.laps, w.st.act.lengths), (2, 2), "an idle length and its lap");
        w.set(at(50), &Set::new()).unwrap();
        w.rest(at(50)).unwrap();
        w.end(at(60)).unwrap();
        assert_eq!(w.st.act.sets, 2, "a set and a rest");
    });
}

#[test]
fn a_rest_needs_an_index_for_what_ends_it() {
    run(|w| {
        pool_swim(w);
        w.st.act.lengths = 0x0FFE;
        w.length(at(1), &Length::drill()).unwrap();
        let written = w.st.written;
        assert_eq!(w.rest(at(1)), Err(Error::IndexFull), "its idle length would have none");
        assert_eq!(w.st.written, written);
        w.end(at(2)).unwrap();
    });
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::TRAINING, SubSport::STRENGTH_TRAINING).unwrap();
        w.st.act.sets = 0x0FFF;
        let written = w.st.written;
        assert_eq!(w.set(at(1), &Set::new()), Err(Error::IndexFull));
        assert_eq!(w.rest(at(1)), Err(Error::IndexFull));
        assert_eq!(w.st.written, written);
        w.end(at(2)).unwrap();
    });
}

#[test]
fn sets_count_their_repetitions() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        assert_eq!(w.set(T, &Set::new()), Err(Error::OutOfOrder));
        w.session(T, Sport::TRAINING, SubSport::STRENGTH_TRAINING).unwrap();
        let squat = Set::new().exercise(Exercise::new(ExerciseCategory::SQUAT).name(37));
        w.set(at(40), &squat.repetitions(10).weight_kilograms(60.0)).unwrap();
        w.rest(at(40)).unwrap();
        assert_eq!(w.set(at(50), &squat), Err(Error::OutOfOrder), "resting");
        w.lap(at(50)).unwrap();
        assert_eq!(w.st.act.session.unwrap().mark.0, at(40), "the rest goes on");
        w.end_rest(at(100)).unwrap();
        assert_eq!(w.st.act.session.unwrap().mark.0, at(100));
        w.set(at(140), &squat.repetitions(8)).unwrap();
        w.set(at(150), &Set::new()).unwrap();
        let written = w.st.written;
        assert_eq!(w.set(at(150), &squat.repetitions(u16::MAX)), Err(Error::OutOfRange));
        assert_eq!(w.set(at(150), &squat.weight_kilograms(4096.0)), Err(Error::OutOfRange));
        let unnamed = Set::new().exercise(Exercise::new(ExerciseCategory::SQUAT).name(u16::MAX));
        assert_eq!(w.set(at(150), &unnamed), Err(Error::OutOfRange));
        assert_eq!(w.st.written, written);
        w.pause(at(150)).unwrap();
        assert_eq!(w.set(at(160), &squat), Err(Error::Paused));
        let s = w.st.act.session.unwrap();
        assert_eq!((s.span.seen.repetitions, s.lap.seen.repetitions), (Some(18), None));
        let last = lap_message(&s.lap, at(150), 150, &s).trigger(lap_trigger::SESSION_END);
        assert_eq!(w.closing(at(150), 0).unwrap().0, last);
        assert_eq!(s.span.seen.totals(150).cycles, None, "not on a lap");
        assert_eq!(w.st.act.sets, 4);
    });
}

#[test]
fn sets_and_rests_belong_to_sessions_that_take_them() {
    let sessions = [
        (Sport::RUNNING, SubSport::GENERIC),
        (Sport::CYCLING, SubSport::ROAD),
        (Sport::SWIMMING, SubSport::OPEN_WATER),
        (Sport::GENERIC, SubSport::STRENGTH_TRAINING),
    ];
    for (sport, sub_sport) in sessions {
        run(|w| {
            w.start(T, &watch()).unwrap();
            w.session(T, sport, sub_sport).unwrap();
            let written = w.st.written;
            assert_eq!(w.set(at(1), &Set::new().repetitions(5)), Err(Error::OutOfOrder));
            assert_eq!(w.rest(at(1)), Err(Error::OutOfOrder), "{sport} {sub_sport}");
            assert_eq!(w.end_rest(at(2)), Err(Error::OutOfOrder));
            assert_eq!(w.st.written, written);
            assert_eq!(w.st.act.sets, 0);
            w.end(at(2)).unwrap();
        });
    }
}

#[test]
fn repetitions_are_the_cycles_of_sessions_that_take_sets() {
    let sessions = [
        (Sport::TRAINING, SubSport::STRENGTH_TRAINING),
        (Sport::TRAINING, SubSport::CARDIO_TRAINING),
        (Sport::HIIT, SubSport::GENERIC),
    ];
    for (sport, sub_sport) in sessions {
        let mut st = run(|w| {
            w.start(T, &watch()).unwrap();
            w.session(T, sport, sub_sport).unwrap();
            w.set(at(1), &Set::new().repetitions(5)).unwrap();
            w.rest(at(1)).unwrap();
            w.end_rest(at(2)).unwrap();
            w.set(at(3), &Set::new().repetitions(4)).unwrap();
        });
        let session = Writer { out: &mut Counter, st: &mut st }.closing(at(4), 0).map(|(_, s)| s);
        let mut want = Totals::NONE;
        want.cycles = Some(9);
        let want = crate::messages::Session::new(T, at(4), 4000, 4000)
            .sport(sport, sub_sport)
            .laps(0, 1)
            .totals(want);
        assert_eq!(session, Some(want));
    }
}

/// Bytes of a `hrv` definition and of its message.
const HRV_DEFINITION: u32 = 9;
const HRV_MESSAGE: u32 = 11;

#[test]
fn beats_go_five_to_a_message() {
    run(|w| {
        assert_eq!(w.beat_intervals_ms(&[800]), Err(Error::OutOfOrder));
        w.start(T, &watch()).unwrap();
        let written = w.st.written;
        w.beat_intervals_ms(&[800, 810, 820]).unwrap();
        assert_eq!((w.st.written, w.st.act.beat_count), (written, 3), "kept");
        w.beat_intervals_ms(&[830, 840, 850, 860]).unwrap();
        assert_eq!(w.st.written, written + HRV_DEFINITION + HRV_MESSAGE);
        assert_eq!((w.st.act.beat_count, &w.st.act.beats[..2]), (2, &[850, 860][..]));
        assert_eq!(w.beat_intervals_ms(&[700, u16::MAX]), Err(Error::OutOfRange));
        assert_eq!(w.st.act.beat_count, 2, "none of them");
        w.beat_intervals_ms(&[]).unwrap();
        assert_eq!(w.st.act.beat_count, 2);
    });
}

#[test]
fn beats_are_written_before_the_next_record_and_at_the_end() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
        w.beat_intervals_ms(&[800]).unwrap();
        let written = w.st.written;
        assert_eq!(w.record(&Record::new(at(1)).heart_rate(255)), Err(Error::OutOfRange));
        assert_eq!((w.st.written, w.st.act.beat_count), (written, 1), "a refused record");
        w.record(&Record::new(at(1)).heart_rate(75)).unwrap();
        assert_eq!(w.st.act.beat_count, 0);
        w.pause(at(2)).unwrap();
        w.beat_intervals_ms(&[790]).unwrap();
        assert_eq!(w.st.act.beat_count, 1, "kept while paused");
        let written = w.st.written;
        w.end(at(3)).unwrap();
        assert_eq!(w.st.act.beat_count, 0);
        assert!(w.st.written >= written + HRV_MESSAGE);
        assert_eq!(w.beat_intervals_ms(&[800]), Err(Error::OutOfOrder));
    });
}

#[test]
fn beats_in_1024ths_of_a_second() {
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.beat_intervals_1024ths(&[1024, 512, 1, u16::MAX]).unwrap();
        assert_eq!(&w.st.act.beats[..4], [1000, 500, 1, 63_999]);
    });
    let mut st = State::new(Options::new(), None);
    let mut w = Writer { out: &mut Counter, st: &mut st };
    assert_eq!(w.beat_intervals_1024ths(&[1024]), Err(Error::OutOfOrder));
}

#[test]
fn quotients_round_half_up() {
    assert_eq!((per(5u32, 2u32), per(4u32, 3u32), per(7u32, 0u32)), (Some(3), Some(1), None));
    assert_eq!(per(u64::MAX, 1u32), Some(u64::MAX));
}

#[test]
fn a_leg_by_hand_changes_only_an_automatic_change() {
    let bytes = |auto: bool, second: Leg<'_>| {
        let mut st = State::new(Options::new().auto_multisport(auto), None);
        let w = &mut Writer { out: &mut Counter, st: &mut st };
        w.start(T, &watch()).unwrap();
        let swim = Leg::new(Sport::SWIMMING, SubSport::OPEN_WATER);
        let written = w.st.written;
        assert_eq!(w.leg(T, &swim.by_hand()), Err(Error::OutOfOrder), "nothing before the first");
        assert_eq!(w.st.written, written);
        w.leg(T, &swim).unwrap();
        w.leg(at(1), &second).unwrap();
        w.end(at(2)).unwrap();
        (st.written, st.data_crc.value())
    };
    let run = Leg::new(Sport::RUNNING, SubSport::TRAIL);
    for auto in [true, false] {
        assert_eq!(bytes(auto, run.by_hand()) == bytes(auto, run), !auto);
    }
}

#[test]
fn a_leg_is_refused_as_its_check_refuses_it() {
    for sport in 0..=u8::MAX {
        for sub_sport in 0..=u8::MAX {
            let (sport, sub_sport) = (Sport::new(sport), SubSport::new(sub_sport));
            let check = Leg::new(sport, sub_sport).check();
            run(|w| {
                w.start(T, &watch()).unwrap();
                assert_eq!(w.session(T, sport, sub_sport), check, "{sport} {sub_sport}");
            });
        }
    }
    let pool = |centimetres| Pool { centimetres, unit: 0 };
    let name = "Open Water 0123456789ab";
    assert_eq!(name.len(), crate::SPORT_NAME_MAX);
    let legs = [
        Leg::pool_swim(pool(0)),
        Leg::pool_swim(pool(1)),
        Leg::pool_swim(pool(u16::MAX - 1)),
        Leg::pool_swim(pool(u16::MAX)),
        Leg::pool_swim(pool(2500)).named("Pool\0Swim"),
        Leg::new(Sport::SWIMMING, SubSport::LAP_SWIMMING).named("Pool"),
        Leg::new(Sport::SWIMMING, SubSport::OPEN_WATER).named(name),
        Leg::new(Sport::SWIMMING, SubSport::OPEN_WATER).named("Open Water 0123456789abc"),
        Leg::new(Sport::SWIMMING, SubSport::OPEN_WATER).named("Open\0Water"),
        Leg::new(Sport::new(u8::MAX), SubSport::GENERIC).named("Open Water"),
    ];
    for leg in legs {
        run(|w| {
            w.start(T, &watch()).unwrap();
            assert_eq!(w.leg(T, &leg), leg.check(), "first: {leg:?}");
            w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
            assert_eq!(w.leg(at(1), &leg), leg.check(), "after another: {leg:?}");
        });
    }
    let (e, long) = (Some(Error::OutOfRange), Some(Error::StringTooLong));
    let refused = legs.map(|l| l.check().err());
    assert_eq!(refused, [e, None, None, e, e, e, None, long, e, e]);
}

#[test]
fn laps_stop_at_their_limit() {
    let st = run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
        for _ in 1..LAPS_MAX {
            w.lap(at(1)).unwrap();
        }
        assert_eq!(w.lap(at(1)), Err(Error::IndexFull), "the session's last lap needs one");
        w.end(at(1)).unwrap();
    });
    assert_eq!((st.laps, LAPS_MAX), (0x0FFF, 0x0FFF));
}

#[test]
fn sessions_stop_at_their_limit() {
    let st = run(|w| {
        w.start(T, &watch()).unwrap();
        for _ in 0..SESSIONS_MAX {
            w.session(T, Sport::RUNNING, SubSport::GENERIC).unwrap();
        }
        assert_eq!(w.session(T, Sport::RUNNING, SubSport::GENERIC), Err(Error::IndexFull));
        w.end(T).unwrap();
    });
    assert_eq!((st.sessions, SESSIONS_MAX), (0x0FFF, 0x0FFF));
}

#[test]
fn lengths_and_sets_stop_at_their_limits() {
    let free = Length::swum(SwimStroke::FREESTYLE, 15);
    let st = run(|w| {
        pool_swim(w);
        for _ in 0..LENGTHS_MAX {
            w.length(at(1), &free).unwrap();
        }
        assert_eq!(w.length(at(1), &free), Err(Error::IndexFull));
        w.end(at(1)).unwrap();
    });
    assert_eq!((st.act.lengths, LENGTHS_MAX), (0x0FFF, 0x0FFF));
    let st = run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::TRAINING, SubSport::STRENGTH_TRAINING).unwrap();
        for _ in 0..SETS_MAX {
            w.set(at(1), &Set::new()).unwrap();
        }
        assert_eq!(w.set(at(1), &Set::new()), Err(Error::IndexFull));
        w.end(at(1)).unwrap();
    });
    assert_eq!((st.act.sets, SETS_MAX), (0x0FFF, 0x0FFF));
}

#[test]
fn distance_stops_at_its_limit() {
    let r = |s| Record::new(at(s));
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::CYCLING, SubSport::GENERIC).unwrap();
        w.record(&r(1).distance_advanced_meters(DISTANCE_METERS_MAX)).unwrap();
        assert_eq!(w.st.act.distance, u32::MAX - 1);
        assert_eq!(w.record(&r(2).distance_advanced_meters(0.01)), Err(Error::OutOfRange));
        w.record(&r(2).distance_advanced_meters(0.0)).unwrap();
    });
    run(|w| {
        w.start(T, &watch()).unwrap();
        w.session(T, Sport::CYCLING, SubSport::GENERIC).unwrap();
        let over = r(1).distance_meters(DISTANCE_METERS_MAX + 0.01);
        assert_eq!(w.record(&over), Err(Error::OutOfRange));
        w.record(&r(1).distance_meters(DISTANCE_METERS_MAX - 25.0)).unwrap();
        w.pool_swim(at(1), Pool::meters(25.0)).unwrap();
        let free = Length::swum(SwimStroke::FREESTYLE, 15);
        w.length(at(2), &free).unwrap();
        assert_eq!(w.st.act.distance, u32::MAX - 1);
        assert_eq!(w.length(at(3), &free), Err(Error::OutOfRange));
        assert_eq!(w.length(at(3), &Length::drill()), Err(Error::OutOfRange));
        w.end(at(3)).unwrap();
    });
}