Skip to main content

fit_encoder/encoder/
activity.rs

1//! An activity as timed calls: the encoder writes the summaries, numbers and counts.
2
3use super::{check, definition_len, next_index, Error, Extras, Planned, Writer};
4#[allow(unused_imports, reason = "for the docs")]
5use crate::developer::RecordField;
6use crate::developer::{Extra, KindId, DEVELOPER_FIELDS_MAX, SUMMARY_BYTES_MAX};
7use crate::messages::{
8    lap_trigger, trigger, Activity, Altitude, Device, Distance, Event, FieldDef, FileId, Hrv, Lap,
9    LapTrigger, Leg, Length, LengthMsg, Message, Pool, Record, Session, Set, SetMsg, Span,
10    SportMsg, Totals, HRV_BEATS,
11};
12use crate::types::{FileType, Position, Sport, SubSport, SwimStroke, Timestamp};
13#[allow(unused_imports, reason = "for the docs")]
14use crate::{raw::RawField, raw::RAW_FIELDS_MAX};
15
16/// The most bytes the end writes: what ending a session writes, any beat intervals waiting, a
17/// stop event and the activity.
18const END: u32 = CLOSE
19    .saturating_add(most(Hrv::FIELDS))
20    .saturating_add(most(Event::FIELDS))
21    .saturating_add(most(Activity::FIELDS));
22
23/// The most bytes a session ending another writes: what ends that one, and its own sport.
24const SWITCH: u32 = CLOSE.saturating_add(most(SportMsg::FIELDS));
25
26/// The most bytes ending a session writes: what ends its rest, its last lap and itself, and
27/// their developer fields.
28const CLOSE: u32 = REST
29    .saturating_add(most(Lap::FIELDS))
30    .saturating_add(most(Session::FIELDS))
31    .saturating_add(DEV);
32
33/// The most bytes developer fields add to a lap and a session: the file's fields split between
34/// their definitions, each with its count of them, and every byte their values may take.
35#[allow(clippy::cast_possible_truncation, reason = "both are small")]
36const DEV: u32 = {
37    let none = definition_len(0, 0);
38    let split = definition_len(0, (DEVELOPER_FIELDS_MAX as u32).saturating_sub(1))
39        .saturating_add(definition_len(0, 1))
40        .saturating_sub(none)
41        .saturating_sub(none);
42    split.saturating_add(SUMMARY_BYTES_MAX as u32)
43};
44
45/// The most bytes ending a rest writes: an idle length or a rest set.
46const REST: u32 = {
47    let length = most_without(LengthMsg::FIELDS, LengthMsg::SWUM);
48    let set = most_without(SetMsg::FIELDS, SetMsg::ACTIVE);
49    // The larger of the two; `Ord::max` is not const.
50    length.saturating_add(set.saturating_sub(length))
51};
52
53/// The most bytes a message of `fields` takes: its definition, its header and every field.
54const fn most(fields: &[FieldDef]) -> u32 {
55    most_without(fields, &[])
56}
57
58/// [`most`], leaving out the fields numbered in `without`.
59const fn most_without(fields: &[FieldDef], without: &[u8]) -> u32 {
60    let (count, data) = kept_sizes(fields, without);
61    definition_len(count, 0).saturating_add(1).saturating_add(data)
62}
63
64/// How many of `fields` are not numbered in `without`, and their bytes.
65#[allow(clippy::cast_lossless, reason = "u32::from is not const")]
66const fn kept_sizes(fields: &[FieldDef], without: &[u8]) -> (u32, u32) {
67    match fields {
68        [] => (0, 0),
69        [f, rest @ ..] => {
70            let (count, data) = kept_sizes(rest, without);
71            if listed(f.num, without) {
72                (count, data)
73            } else {
74                (count.saturating_add(1), data.saturating_add(f.size as u32))
75            }
76        }
77    }
78}
79
80const fn listed(num: u8, list: &[u8]) -> bool {
81    match list {
82        [] => false,
83        [n, rest @ ..] => *n == num || listed(num, rest),
84    }
85}
86
87/// A length or set, ready to write.
88#[derive(Clone, Copy, Debug)]
89enum Piece {
90    Length { msg: LengthMsg, index: u16, distance: u32, pool: Pool },
91    Set { msg: SetMsg, index: u16 },
92}
93
94impl Piece {
95    fn cost(&self, w: &Writer<'_>) -> Result<Planned, Error> {
96        match self {
97            Self::Length { msg, .. } => w.cost(msg),
98            Self::Set { msg, .. } => w.cost(msg),
99        }
100    }
101
102    /// Adds a length to what `session` and its lap have seen.
103    fn add_to(&self, session: &mut OpenSession) {
104        if let Self::Length { msg, index, distance, pool } = *self {
105            let swum = msg.swum.map(|l| (l, pool.centimetres));
106            session.span.seen.add_length(index, swum, distance, &msg);
107            session.lap.seen.add_length(index, swum, distance, &msg);
108        }
109    }
110}
111
112/// Samples of one unsigned field.
113#[derive(Clone, Copy, Debug, Default)]
114struct Stat {
115    sum: u64,
116    count: u32,
117    max: u32,
118}
119
120impl Stat {
121    fn add(&mut self, v: u32) {
122        self.sum = self.sum.saturating_add(u64::from(v));
123        self.count = self.count.saturating_add(1);
124        self.max = self.max.max(v);
125    }
126
127    /// The average, rounded half up, and the maximum; `None` without a sample.
128    fn summary(self) -> Option<(u32, u32)> {
129        let avg = per(self.sum, self.count)?;
130        Some((u32::try_from(avg).unwrap_or(u32::MAX), self.max))
131    }
132
133    fn summary_u8(self) -> (Option<u8>, Option<u8>) {
134        let s = self.summary();
135        (s.and_then(|(a, _)| u8::try_from(a).ok()), s.and_then(|(_, m)| u8::try_from(m).ok()))
136    }
137
138    fn summary_u16(self) -> (Option<u16>, Option<u16>) {
139        let s = self.summary();
140        (s.and_then(|(a, _)| u16::try_from(a).ok()), s.and_then(|(_, m)| u16::try_from(m).ok()))
141    }
142}
143
144/// Temperatures: their average, rounded half away from zero, and maximum.
145#[derive(Clone, Copy, Debug, Default)]
146struct Temperatures {
147    sum: i64,
148    count: u32,
149    max: Option<i8>,
150}
151
152impl Temperatures {
153    fn add(&mut self, v: i8) {
154        self.sum = self.sum.saturating_add(i64::from(v));
155        self.count = self.count.saturating_add(1);
156        self.max = Some(self.max.map_or(v, |m| m.max(v)));
157    }
158
159    fn average(self) -> Option<i8> {
160        let count = i64::from(self.count);
161        let half = count / 2;
162        let sum = if self.sum.is_negative() {
163            self.sum.saturating_sub(half)
164        } else {
165            self.sum.saturating_add(half)
166        };
167        i8::try_from(sum.checked_div(count)?).ok()
168    }
169}
170
171/// Which way altitude was last going, for the ascent filter.
172#[derive(Clone, Copy, Debug, PartialEq, Eq)]
173enum Heading {
174    Level,
175    Up,
176    Down,
177}
178
179/// The most records the ascent filter averages.
180const SMOOTHING: usize = crate::messages::SMOOTHING as usize;
181
182/// The ascent filter: altitude averaged over the last few records, and a change of that
183/// average counted once it passes the source's threshold from the extreme it left, the highest
184/// since climbing or the lowest since descending, or before either, the lowest or highest so
185/// far; and then counted in full.
186#[derive(Clone, Copy, Debug)]
187struct Climb {
188    threshold: i64,
189    /// The records averaged, and the latest of them, newest last.
190    window: usize,
191    recent: [i64; SMOOTHING],
192    heading: Heading,
193    low: i64,
194    high: i64,
195    /// The last altitude, and what is added to each after it, so a jump across a pause counts
196    /// nothing; and whether the next comes after a pause.
197    last: i64,
198    shift: i64,
199    paused: bool,
200}
201
202/// How many records an altitude's `window` averages over.
203fn span(window: u8) -> usize {
204    usize::from(window).clamp(1, SMOOTHING)
205}
206
207impl Climb {
208    fn new(fifths: u32, threshold: u32, window: u8) -> Self {
209        let at = i64::from(fifths);
210        let (low, high, last) = (at, at, at);
211        let threshold = i64::from(threshold);
212        let window = span(window);
213        let recent = [at; SMOOTHING];
214        Self {
215            threshold,
216            window,
217            recent,
218            heading: Heading::Level,
219            low,
220            high,
221            last,
222            shift: 0,
223            paused: false,
224        }
225    }
226
227    /// The average of the latest records with `at`, which joins them, to the nearest fifth.
228    fn average(&mut self, at: i64) -> i64 {
229        self.recent.rotate_left(1);
230        if let Some(newest) = self.recent.last_mut() {
231            *newest = at;
232        }
233        let latest = self.recent.iter().rev().take(self.window);
234        let sum = latest.fold(0i64, |sum, &a| sum.saturating_add(a));
235        let n = i64::try_from(self.window).unwrap_or(1);
236        sum.saturating_add(n / 2).checked_div_euclid(n).unwrap_or(at)
237    }
238
239    /// The fifths of a metre `fifths` climbs and descends from where the filter was.
240    fn step(&mut self, fifths: u32) -> (u32, u32) {
241        let mut at = i64::from(fifths).saturating_add(self.shift);
242        if self.paused {
243            self.shift = self.shift.saturating_add(self.last.saturating_sub(at));
244            (at, self.paused) = (self.last, false);
245        }
246        self.last = at;
247        let at = self.average(at);
248        let (low, high, th) = (self.low, self.high, self.threshold);
249        let fifths = |d: i64| u32::try_from(d).unwrap_or(u32::MAX);
250        match self.heading {
251            Heading::Up if at > high => {
252                self.high = at;
253                (fifths(at.saturating_sub(high)), 0)
254            }
255            Heading::Down if at < low => {
256                self.low = at;
257                (0, fifths(low.saturating_sub(at)))
258            }
259            Heading::Level | Heading::Down if at >= low.saturating_add(th) => {
260                (self.heading, self.high) = (Heading::Up, at);
261                (fifths(at.saturating_sub(low)), 0)
262            }
263            Heading::Level | Heading::Up if at.saturating_add(th) <= high => {
264                (self.heading, self.low) = (Heading::Down, at);
265                (0, fifths(high.saturating_sub(at)))
266            }
267            Heading::Level => {
268                (self.low, self.high) = (low.min(at), high.max(at));
269                (0, 0)
270            }
271            Heading::Up | Heading::Down => (0, 0),
272        }
273    }
274}
275
276/// Longitudes seen, both as signed semicircles and as unsigned ones, which run from 0° east
277/// round to 360°, so a track across ±180° has a narrow box in one of the two.
278#[derive(Clone, Copy, Debug)]
279struct Longitudes {
280    signed: (i32, i32),
281    unsigned: (u32, u32),
282}
283
284impl Longitudes {
285    #[allow(clippy::cast_sign_loss)]
286    const fn new(long: i32) -> Self {
287        Self { signed: (long, long), unsigned: (long as u32, long as u32) }
288    }
289
290    #[allow(clippy::cast_sign_loss)]
291    fn add(&mut self, long: i32) {
292        self.signed = (self.signed.0.min(long), self.signed.1.max(long));
293        let u = long as u32;
294        self.unsigned = (self.unsigned.0.min(u), self.unsigned.1.max(u));
295    }
296
297    /// West and east: east is less than west when the box crosses ±180°.
298    #[allow(clippy::cast_possible_wrap)]
299    fn west_east(self) -> (i32, i32) {
300        let signed = self.signed.1.abs_diff(self.signed.0);
301        let unsigned = self.unsigned.1.abs_diff(self.unsigned.0);
302        if unsigned < signed {
303            (self.unsigned.0 as i32, self.unsigned.1 as i32)
304        } else {
305            self.signed
306        }
307    }
308}
309
310/// What a lap or session has seen of its records.
311#[derive(Clone, Copy, Debug, Default)]
312struct Seen {
313    heart_rate: Stat,
314    cadence: Stat,
315    power: Stat,
316    max_speed: Option<u16>,
317    temperature: Temperatures,
318    /// The activity's distance at the start, and the last a record in it gave.
319    distance_base: u32,
320    distance: Option<u32>,
321    /// Climbed and descended, in fifths of a metre, and whether a record gave an altitude.
322    ascent: u32,
323    descent: u32,
324    climbed: bool,
325    /// The session's climb and descent before a lap, which its metres count from.
326    climb_base: (u32, u32),
327    start: Option<Position>,
328    end: Option<Position>,
329    latitudes: Option<(i32, i32)>,
330    longitudes: Option<Longitudes>,
331    /// Pool lengths, idle and active, the first one's index, and the strokes of those swum
332    /// with a stroke count, with the distance they covered in centimetres.
333    lengths: u16,
334    active_lengths: u16,
335    first_length: Option<u16>,
336    strokes: u32,
337    stroked_cm: u32,
338    swim_stroke: Option<SwimStroke>,
339    /// Repetitions of strength sets, kept for the session alone.
340    repetitions: Option<u32>,
341}
342
343impl Seen {
344    fn new(distance_base: u32) -> Self {
345        Self { distance_base, ..Self::default() }
346    }
347
348    fn add(&mut self, r: &Record, climb: Option<(u32, u32)>) {
349        if let Some(p) = r.position {
350            let (lat, long) = p.semicircles();
351            self.start.get_or_insert(p);
352            self.end = Some(p);
353            let (south, north) = self.latitudes.unwrap_or((lat, lat));
354            self.latitudes = Some((south.min(lat), north.max(lat)));
355            self.longitudes.get_or_insert(Longitudes::new(long)).add(long);
356        }
357        if r.distance.is_some() {
358            self.distance = r.distance;
359        }
360        if let Some((up, down)) = climb {
361            self.ascent = self.ascent.saturating_add(up);
362            self.descent = self.descent.saturating_add(down);
363            self.climbed = true;
364        }
365        if let Some(v) = r.heart_rate {
366            self.heart_rate.add(u32::from(v));
367        }
368        if let Some(v) = r.cadence {
369            self.cadence.add(u32::from(v));
370        }
371        if let Some(v) = r.power {
372            self.power.add(u32::from(v));
373        }
374        if let Some(v) = r.speed {
375            self.max_speed = Some(self.max_speed.map_or(v, |m| m.max(v)));
376        }
377        if let Some(v) = r.temperature {
378            self.temperature.add(v);
379        }
380    }
381
382    /// A pool length with its index, the activity's distance after it, and for one swum, the
383    /// pool, its speed and cadence.
384    fn add_length(
385        &mut self,
386        index: u16,
387        swum: Option<(Length, u16)>,
388        distance: u32,
389        msg: &LengthMsg,
390    ) {
391        self.lengths = self.lengths.saturating_add(1);
392        self.first_length.get_or_insert(index);
393        self.distance = Some(distance);
394        let Some((length, pool_cm)) = swum else { return };
395        self.active_lengths = self.active_lengths.saturating_add(1);
396        let stroke = length.stroke;
397        self.swim_stroke = Some(match self.swim_stroke {
398            Some(s) if s != stroke => SwimStroke::MIXED,
399            _ => stroke,
400        });
401        if let Some(n) = length.strokes {
402            self.strokes = self.strokes.saturating_add(u32::from(n));
403            self.stroked_cm = self.stroked_cm.saturating_add(u32::from(pool_cm));
404        }
405        if let Some(v) = msg.cadence {
406            self.cadence.add(u32::from(v));
407        }
408        if let Some(v) = msg.avg_speed {
409            self.max_speed = Some(self.max_speed.map_or(v, |m| m.max(v)));
410        }
411    }
412
413    fn add_repetitions(&mut self, set: &Set) {
414        if let Some(n) = set.repetitions {
415            self.repetitions = Some(self.repetitions.unwrap_or(0).saturating_add(u32::from(n)));
416        }
417    }
418
419    /// The totals over `timer` seconds, with a value its field cannot hold left as none.
420    fn totals(&self, timer: u32) -> Totals {
421        let distance = self.distance.map(|last| last.saturating_sub(self.distance_base));
422        let avg_speed = distance.and_then(|d| {
423            let mm_per_s = per(u64::from(d) * 10, timer)?;
424            u16::try_from(mm_per_s).ok().filter(|&v| v != u16::MAX)
425        });
426        // A maximum below the average is a sampling gap, not a speed: leave it out.
427        let max_speed = self.max_speed.filter(|&m| avg_speed.is_none_or(|avg| m >= avg));
428        let metres =
429            |fifths: u32| u16::try_from(per(fifths, 5u32)?).ok().filter(|&v| v != u16::MAX);
430        let since = |base: u32, fifths: u32| {
431            metres(base.saturating_add(fifths))?.checked_sub(metres(base)?)
432        };
433        let swam = self.lengths > 0;
434        let (avg_cadence, max_cadence) = self.cadence.summary_u8();
435        let (avg_power, max_power) = self.power.summary_u16();
436        let corners = self.latitudes.zip(self.longitudes).map(|((south, north), longs)| {
437            let (west, east) = longs.west_east();
438            (Position::from_semicircles(north, east), Position::from_semicircles(south, west))
439        });
440        Totals {
441            start: self.start,
442            end: self.end,
443            north_east: corners.and_then(|c| c.0),
444            south_west: corners.and_then(|c| c.1),
445            distance,
446            avg_speed,
447            max_speed,
448            avg_cadence,
449            max_cadence,
450            avg_power,
451            max_power,
452            ascent: self.climbed.then(|| since(self.climb_base.0, self.ascent)).flatten(),
453            descent: self.climbed.then(|| since(self.climb_base.1, self.descent)).flatten(),
454            avg_temperature: self.temperature.average(),
455            max_temperature: self.temperature.max,
456            cycles: swam.then_some(self.strokes),
457            lengths: swam.then_some(self.lengths),
458            active_lengths: swam.then_some(self.active_lengths),
459            stroke_distance: per(self.stroked_cm, self.strokes)
460                .and_then(|cm| u16::try_from(cm).ok())
461                .filter(|&cm| cm != u16::MAX),
462            swim_stroke: self.swim_stroke,
463        }
464    }
465}
466
467/// A lap or session that has started and not yet ended.
468#[derive(Clone, Copy, Debug)]
469struct Open {
470    start: Timestamp,
471    /// The timer's seconds at `start`.
472    timer: u32,
473    seen: Seen,
474}
475
476impl Open {
477    fn new(start: Timestamp, timer: u32, distance: u32) -> Self {
478        Self { start, timer, seen: Seen::new(distance) }
479    }
480}
481
482#[derive(Clone, Copy, Debug)]
483struct OpenSession {
484    span: Open,
485    sport: Sport,
486    sub_sport: SubSport,
487    pool: Option<Pool>,
488    first_lap: u16,
489    lap: Open,
490    /// Where the next length or set starts, with the timer's seconds there, and whether a
491    /// rest started there.
492    mark: (Timestamp, u32),
493    resting: bool,
494}
495
496impl OpenSession {
497    /// Whether it takes strength sets and rests between them: training, of any sub-sport, and
498    /// HIIT.
499    fn takes_sets(&self) -> bool {
500        self.sport == Sport::TRAINING || self.sport == Sport::HIIT
501    }
502}
503
504#[derive(Clone, Copy, Debug, PartialEq, Eq)]
505enum Phase {
506    NotStarted,
507    Started,
508    /// Writing the end into the bytes kept for it.
509    Ending,
510    Ended,
511}
512
513/// Where the activity is.
514#[derive(Clone, Copy, Debug)]
515pub(super) struct Act {
516    phase: Phase,
517    /// The latest time written.
518    now: Timestamp,
519    /// The timer's seconds up to `since`, and whether it has run since then.
520    timer: u32,
521    since: Timestamp,
522    running: bool,
523    session: Option<OpenSession>,
524    devices: u8,
525    /// The distance covered, in centimetres, and the ascent filter.
526    distance: u32,
527    micrometres: u64,
528    climb: Option<Climb>,
529    lengths: u16,
530    sets: u16,
531    /// Beat intervals not yet written, in milliseconds.
532    beats: [u16; HRV_BEATS],
533    beat_count: usize,
534}
535
536impl Act {
537    pub(super) const fn new() -> Self {
538        let zero = Timestamp::from_fit(0);
539        Self {
540            phase: Phase::NotStarted,
541            now: zero,
542            timer: 0,
543            since: zero,
544            running: false,
545            session: None,
546            devices: 0,
547            distance: 0,
548            micrometres: 0,
549            climb: None,
550            lengths: 0,
551            sets: 0,
552            beats: [0; HRV_BEATS],
553            beat_count: 0,
554        }
555    }
556
557    pub(super) fn ended(&self) -> bool {
558        self.phase == Phase::Ended
559    }
560
561    /// The bytes every write must leave free so the activity can still end.
562    pub(super) fn kept_for_end(&self) -> u32 {
563        if self.phase == Phase::Started {
564            END
565        } else {
566            0
567        }
568    }
569
570    /// Refuses a call outside the activity.
571    pub(super) fn open(&self) -> Result<(), Error> {
572        self.started(self.now)
573    }
574
575    /// Refuses a call outside a session.
576    pub(super) fn in_session(&self) -> Result<(), Error> {
577        self.open()?;
578        self.session.map(|_| ()).ok_or(Error::OutOfOrder)
579    }
580
581    /// The timer's seconds at `t`, which is no earlier than `since`.
582    fn timer_at(&self, t: Timestamp) -> u32 {
583        let running = if self.running { t.fit().saturating_sub(self.since.fit()) } else { 0 };
584        self.timer.saturating_add(running)
585    }
586
587    /// The activity's distance after `input`, which may not take it back, in centimetres and
588    /// the micrometres past them.
589    fn distance_after(&self, input: Distance) -> Result<(u32, u64), Error> {
590        let next = match input {
591            Distance::Advanced(um) => {
592                let total = u64::from(self.distance)
593                    .saturating_mul(10_000)
594                    .saturating_add(self.micrometres);
595                total
596                    .checked_add(um)
597                    .and_then(|t| Some((u32::try_from(t / 10_000).ok()?, t % 10_000)))
598            }
599            Distance::Total(cm) if cm < self.distance => return Err(Error::DistanceWentBack),
600            Distance::Total(cm) => Some((cm, 0)),
601        };
602        next.filter(|&(d, _)| d != u32::MAX).ok_or(Error::OutOfRange)
603    }
604
605    /// Moves the ascent filter to `altitude`, returning what it climbed and descended; a
606    /// different threshold or smoothing starts the filter afresh.
607    fn climb_to(&mut self, altitude: Altitude) -> (u32, u32) {
608        let (fifths, threshold) = (u32::from(altitude.fifths), u32::from(altitude.threshold));
609        let window = altitude.window;
610        match self.climb.as_mut() {
611            Some(c) if c.threshold == i64::from(threshold) && c.window == span(window) => {
612                c.step(fifths)
613            }
614            _ => {
615                self.climb = Some(Climb::new(fifths, threshold, window));
616                (0, 0)
617            }
618        }
619    }
620
621    /// The latest time written.
622    pub(super) const fn now(&self) -> Timestamp {
623        self.now
624    }
625
626    /// Moves the activity on to `t`, no earlier than its time.
627    pub(super) fn move_to(&mut self, t: Timestamp) {
628        self.now = t;
629    }
630
631    pub(super) fn started(&self, t: Timestamp) -> Result<(), Error> {
632        if self.phase != Phase::Started {
633            return Err(Error::OutOfOrder);
634        }
635        if t < self.now {
636            return Err(Error::TimeWentBack);
637        }
638        Ok(())
639    }
640}
641
642/// `n` over `d`, rounded half up; `None` over nothing.
643fn per(n: impl Into<u64>, d: impl Into<u64>) -> Option<u64> {
644    let (n, d) = (n.into(), d.into());
645    n.saturating_add(d / 2).checked_div(d)
646}
647
648/// Seconds as FIT's milliseconds; too many is out of range.
649fn ms(seconds: u32) -> u32 {
650    seconds.saturating_mul(1000)
651}
652
653fn lap_message(lap: &Open, end: Timestamp, timer: u32, session: &OpenSession) -> Lap {
654    let elapsed = end.fit().saturating_sub(lap.start.fit());
655    let timer = timer.saturating_sub(lap.timer);
656    let mut msg = Lap::new(lap.start, end, ms(elapsed), ms(timer))
657        .sport(session.sport, session.sub_sport)
658        .totals(lap.seen.totals(timer));
659    if let Some(i) = lap.seen.first_length {
660        msg = msg.first_length(i);
661    }
662    if let (Some(avg), Some(max)) = lap.seen.heart_rate.summary_u8() {
663        msg = msg.heart_rate(avg, max);
664    }
665    msg
666}
667
668impl Writer<'_> {
669    /// Starts the activity at `t`, recorded by `creator`. The timer starts with the first
670    /// session.
671    ///
672    /// # Errors
673    ///
674    /// [`Error::OutOfOrder`] if it has started already; see [`Error`].
675    pub fn start(&mut self, t: Timestamp, creator: &Device<'_>) -> Result<(), Error> {
676        if self.st.act.phase != Phase::NotStarted {
677            return Err(Error::OutOfOrder);
678        }
679        let mut id = FileId::new(FileType::ACTIVITY, creator.manufacturer, creator.product, t);
680        if let Some(serial) = creator.serial_number {
681            id = id.serial_number(serial);
682        }
683        let info = creator.info(t, 0);
684        let first = self.cost(&id)?;
685        self.endable(t, 0, 0)?;
686        self.room(first.size().saturating_add(self.cost(&info)?.after(&first)))?;
687        self.raw_file_id(&id)?;
688        self.raw_device_info(&info)?;
689        let act = &mut self.st.act;
690        act.phase = Phase::Started;
691        (act.now, act.since, act.running, act.timer) = (t, t, false, 0);
692        Ok(())
693    }
694
695    /// Writes a sensor the activity used, as the next `device_index` after the creator's.
696    ///
697    /// # Errors
698    ///
699    /// [`Error::OutOfOrder`] outside the activity, [`Error::IndexFull`] after 254 sensors; see
700    /// [`Error`].
701    pub fn device(&mut self, device: &Device<'_>) -> Result<(), Error> {
702        let now = self.st.act.now;
703        self.st.act.started(now)?;
704        let index = self.st.act.devices.checked_add(1).filter(|&i| i != u8::MAX);
705        let index = index.ok_or(Error::IndexFull)?;
706        self.raw_device_info(&device.info(now, index))?;
707        self.st.act.devices = index;
708        Ok(())
709    }
710
711    /// Starts a session of `sport` at `t`, ending the one before it there: the next leg of a
712    /// multisport activity, or a transition between legs. [`Writer::leg`] starts one with a
713    /// name, or moved to by hand.
714    ///
715    /// # Errors
716    ///
717    /// [`Error::OutOfRange`] for `lap_swimming`, as a pool swim starts with
718    /// [`Writer::pool_swim`]; see [`Error`].
719    pub fn session(
720        &mut self,
721        t: Timestamp,
722        sport: Sport,
723        sub_sport: SubSport,
724    ) -> Result<(), Error> {
725        self.leg(t, &Leg::new(sport, sub_sport))
726    }
727
728    /// Starts a pool swim at `t` in `pool`, as [`Writer::session`] starts any other: its
729    /// distance is the pool's length for each length swum, from [`Writer::length`].
730    ///
731    /// # Errors
732    ///
733    /// [`Error::OutOfRange`] for a pool of no length; see [`Error`].
734    pub fn pool_swim(&mut self, t: Timestamp, pool: Pool) -> Result<(), Error> {
735        self.leg(t, &Leg::pool_swim(pool))
736    }
737
738    /// Starts the session `leg` describes at `t`, ending the one before it there, as
739    /// [`Writer::session`] and [`Writer::pool_swim`] do.
740    ///
741    /// # Errors
742    ///
743    /// [`Error::OutOfRange`] for `lap_swimming` without a pool, a pool of no length or a name
744    /// holding a NUL, [`Error::StringTooLong`] for a name too long, [`Error::OutOfOrder`] for
745    /// a first leg moved to by hand; see [`Error`].
746    pub fn leg(&mut self, t: Timestamp, leg: &Leg<'_>) -> Result<(), Error> {
747        let Leg { sport, pool, by_hand } = *leg;
748        self.st.act.started(t)?;
749        let no_pool = pool.is_none() && sport.sub_sport == SubSport::LAP_SWIMMING;
750        if no_pool || pool.is_some_and(|p| p.centimetres == 0 || p.centimetres == u16::MAX) {
751            return Err(Error::OutOfRange);
752        }
753        let first = self.st.act.session.is_none();
754        if first && by_hand {
755            return Err(Error::OutOfOrder);
756        }
757        let closed = u16::from(!first);
758        let (laps, sessions) = (self.st.laps, self.st.sessions);
759        self.endable(t, laps.saturating_add(closed), sessions.saturating_add(closed))?;
760        let cost = self.cost(&sport)?;
761        if first {
762            let start = Event::timer_start(t);
763            let event = self.cost(&start)?;
764            self.room(event.size().saturating_add(cost.after(&event)))?;
765            self.raw_event(start)?;
766            let act = &mut self.st.act;
767            (act.since, act.running) = (t, true);
768        } else {
769            self.room(SWITCH)?;
770            if let Some(piece) = self.rest_piece(t)? {
771                self.put_piece(t, piece)?;
772            }
773            let trigger = if self.st.options.auto_multisport && !by_hand {
774                trigger::AUTO_MULTI_SPORT
775            } else {
776                trigger::MANUAL
777            };
778            self.close_session(t, trigger)?;
779        }
780        self.fixed(&sport, 0)?;
781        let SportMsg { sport, sub_sport, .. } = sport;
782        let (timer, distance) = (self.st.act.timer_at(t), self.st.act.distance);
783        self.st.act.session = Some(OpenSession {
784            span: Open::new(t, timer, distance),
785            sport,
786            sub_sport,
787            pool,
788            first_lap: self.st.laps,
789            lap: Open::new(t, timer, distance),
790            mark: (t, timer),
791            resting: false,
792        });
793        // Each leg climbs from where it starts.
794        self.st.act.climb = None;
795        self.st.act.now = t;
796        Ok(())
797    }
798
799    /// Writes a record in the current session.
800    ///
801    /// # Errors
802    ///
803    /// [`Error::OutOfOrder`] outside a session, [`Error::Paused`] while the timer is paused,
804    /// [`Error::DistanceWentBack`] for a total distance below one already written; see
805    /// [`Error`].
806    pub fn record(&mut self, record: &Record) -> Result<(), Error> {
807        self.record_with(record, &[])
808    }
809
810    /// Writes a record with fields besides those [`Record`] models: developer fields, from
811    /// [`RecordField::value`], and raw fields, from [`RawField`]. A raw field may not be one
812    /// the encoder writes: those [`Record`] sets, the `timestamp`, or another form of one,
813    /// `compressed_speed_distance` (8), `enhanced_speed` (73) and `enhanced_altitude` (78).
814    ///
815    /// # Errors
816    ///
817    /// Those of [`Writer::record`]; [`Error::Undeclared`] for a field this file did not
818    /// declare, [`Error::Duplicate`] for one given twice, [`Error::Reserved`] for a raw field
819    /// the encoder writes, [`Error::TooMany`] past [`RAW_FIELDS_MAX`] raw fields.
820    pub fn record_with(&mut self, record: &Record, extras: &[Extra<'_>]) -> Result<(), Error> {
821        let t = record.timestamp;
822        self.st.act.started(t)?;
823        let Some(session) = self.st.act.session else { return Err(Error::OutOfOrder) };
824        if !self.st.act.running {
825            return Err(Error::Paused);
826        }
827        let from_lengths =
828            record.distance_input.is_some() || record.speed.is_some() || record.cadence.is_some();
829        if session.pool.is_some() && from_lengths {
830            return Err(Error::GivenByLengths);
831        }
832        let mut record = *record;
833        let distance = match record.distance_input {
834            None => None,
835            Some(input) => Some(self.st.act.distance_after(input)?),
836        };
837        record.distance = distance.map(|(cm, _)| cm);
838        self.endable(t, self.st.laps, self.st.sessions)?;
839        let size = self.record_cost(&record, extras)?;
840        self.room(self.beats_cost()?.saturating_add(size))?;
841        // Beats follow the record before them, which readers count their times from.
842        self.write_beats()?;
843        self.raw_record_with(record, extras)?;
844        let act = &mut self.st.act;
845        act.now = t;
846        if let Some((cm, um)) = distance {
847            (act.distance, act.micrometres) = (cm, um);
848        }
849        let climb = record.altitude.map(|a| act.climb_to(a));
850        if let Some(s) = act.session.as_mut() {
851            s.span.seen.add(&record, climb);
852            s.lap.seen.add(&record, climb);
853        }
854        Ok(())
855    }
856
857    /// Ends the current lap at `t`, by hand, and starts the next.
858    ///
859    /// # Errors
860    ///
861    /// [`Error::OutOfOrder`] outside a session or during a rest in a pool swim; see [`Error`].
862    pub fn lap(&mut self, t: Timestamp) -> Result<(), Error> {
863        self.lap_by(t, LapTrigger::Manual)
864    }
865
866    /// [`Writer::lap`], for a lap that `trigger` ended, such as the device's automatic lap
867    /// every kilometre.
868    ///
869    /// # Errors
870    ///
871    /// As [`Writer::lap`].
872    pub fn lap_by(&mut self, t: Timestamp, trigger: LapTrigger) -> Result<(), Error> {
873        self.st.act.started(t)?;
874        let Some(session) = self.st.act.session else { return Err(Error::OutOfOrder) };
875        if session.resting && session.pool.is_some() {
876            return Err(Error::OutOfOrder);
877        }
878        self.end_lap(t, &session, trigger)
879    }
880
881    /// Ends the open session's current lap at `t` and starts the next there.
882    fn end_lap(
883        &mut self,
884        t: Timestamp,
885        session: &OpenSession,
886        trigger: LapTrigger,
887    ) -> Result<(), Error> {
888        let timer = self.st.act.timer_at(t);
889        let lap = lap_message(&session.lap, t, timer, session).trigger(trigger.get());
890        check(&lap)?;
891        self.endable(t, self.st.laps.saturating_add(1), self.st.sessions)?;
892        self.raw_lap(&lap)?;
893        let act = &mut self.st.act;
894        act.now = t;
895        if let Some(s) = act.session.as_mut() {
896            s.lap = Open::new(t, timer, act.distance);
897            s.lap.seen.climb_base = (s.span.seen.ascent, s.span.seen.descent);
898            if !s.resting {
899                s.mark = (t, timer);
900            }
901        }
902        Ok(())
903    }
904
905    /// Pauses the timer at `t`.
906    ///
907    /// # Errors
908    ///
909    /// [`Error::OutOfOrder`] before the first session or if it is paused already; see
910    /// [`Error`].
911    pub fn pause(&mut self, t: Timestamp) -> Result<(), Error> {
912        self.st.act.started(t)?;
913        if !self.st.act.running {
914            return Err(Error::OutOfOrder);
915        }
916        self.endable(t, self.st.laps, self.st.sessions)?;
917        self.raw_event(Event::timer_stop(t))?;
918        let act = &mut self.st.act;
919        (act.timer, act.since, act.running, act.now) = (act.timer_at(t), t, false, t);
920        if let Some(c) = act.climb.as_mut() {
921            c.paused = true;
922        }
923        Ok(())
924    }
925
926    /// Resumes the timer at `t`.
927    ///
928    /// # Errors
929    ///
930    /// [`Error::OutOfOrder`] before the first session or if it is running; see [`Error`].
931    pub fn resume(&mut self, t: Timestamp) -> Result<(), Error> {
932        self.st.act.started(t)?;
933        if self.st.act.running || self.st.act.session.is_none() {
934            return Err(Error::OutOfOrder);
935        }
936        self.endable(t, self.st.laps, self.st.sessions)?;
937        self.raw_event(Event::timer_start(t))?;
938        let act = &mut self.st.act;
939        (act.since, act.running, act.now) = (t, true, t);
940        Ok(())
941    }
942
943    /// Ends a length of the pool at `t`, swum since the last length, rest or lap ended, or the
944    /// pool swim started.
945    ///
946    /// # Errors
947    ///
948    /// [`Error::OutOfOrder`] outside a pool swim or during a rest, [`Error::Paused`] while the
949    /// timer is paused, [`Error::IndexFull`] after 4,095 lengths; see [`Error`].
950    pub fn length(&mut self, t: Timestamp, length: &Length) -> Result<(), Error> {
951        self.st.act.started(t)?;
952        let Some(session) = self.st.act.session else { return Err(Error::OutOfOrder) };
953        if session.pool.is_none() || session.resting {
954            return Err(Error::OutOfOrder);
955        }
956        if !self.st.act.running {
957            return Err(Error::Paused);
958        }
959        let piece = self.length_at(t, &session, Some(*length))?;
960        self.put_piece(t, piece)
961    }
962
963    /// Writes a strength set that ends at `t`, done since the last set, rest or lap ended, or
964    /// the session started.
965    ///
966    /// # Errors
967    ///
968    /// [`Error::OutOfOrder`] outside a training or HIIT session or during a rest,
969    /// [`Error::Paused`] while the timer is paused, [`Error::IndexFull`] after 4,095 sets; see
970    /// [`Error`].
971    pub fn set(&mut self, t: Timestamp, set: &Set) -> Result<(), Error> {
972        self.st.act.started(t)?;
973        let Some(session) = self.st.act.session else { return Err(Error::OutOfOrder) };
974        if !session.takes_sets() || session.resting {
975            return Err(Error::OutOfOrder);
976        }
977        if !self.st.act.running {
978            return Err(Error::Paused);
979        }
980        let piece = self.set_at(t, &session, Some(*set))?;
981        self.put_piece(t, piece)
982    }
983
984    /// Starts a rest at `t`, which [`Writer::end_rest`] ends. In a pool swim the lap of lengths
985    /// before it ends here, and the rest is an idle length in a lap of its own; in a training
986    /// or HIIT session it is a rest between strength sets.
987    ///
988    /// # Errors
989    ///
990    /// [`Error::OutOfOrder`] outside a pool swim or a training or HIIT session, or during a
991    /// rest; see [`Error`].
992    pub fn rest(&mut self, t: Timestamp) -> Result<(), Error> {
993        self.st.act.started(t)?;
994        let Some(session) = self.st.act.session else { return Err(Error::OutOfOrder) };
995        if session.resting || (session.pool.is_none() && !session.takes_sets()) {
996            return Err(Error::OutOfOrder);
997        }
998        // Whatever ends the rest writes a length or set, which must have an index left.
999        next_index(if session.pool.is_some() { self.st.act.lengths } else { self.st.act.sets })?;
1000        if session.pool.is_some() && session.lap.seen.lengths > 0 {
1001            self.end_lap(t, &session, LapTrigger::Manual)?;
1002        } else {
1003            self.endable(t, self.st.laps, self.st.sessions)?;
1004        }
1005        let act = &mut self.st.act;
1006        let timer = act.timer_at(t);
1007        act.now = t;
1008        if let Some(s) = act.session.as_mut() {
1009            (s.mark, s.resting) = ((t, timer), true);
1010        }
1011        Ok(())
1012    }
1013
1014    /// Ends the rest at `t`.
1015    ///
1016    /// # Errors
1017    ///
1018    /// [`Error::OutOfOrder`] outside a rest, [`Error::IndexFull`] after 4,095 lengths or sets;
1019    /// see [`Error`].
1020    pub fn end_rest(&mut self, t: Timestamp) -> Result<(), Error> {
1021        self.st.act.started(t)?;
1022        let Some(session) = self.st.act.session.filter(|s| s.resting) else {
1023            return Err(Error::OutOfOrder);
1024        };
1025        if session.pool.is_none() {
1026            let piece = self.set_at(t, &session, None)?;
1027            return self.put_piece(t, piece);
1028        }
1029        let piece = self.length_at(t, &session, None)?;
1030        self.endable(t, self.st.laps.saturating_add(1), self.st.sessions)?;
1031        let mut after = session;
1032        piece.add_to(&mut after);
1033        let lap = lap_message(&after.lap, t, self.st.act.timer_at(t), &after);
1034        check(&lap)?;
1035        let lap = self.cost_with(&lap, Extras::Staged(KindId::Lap))?;
1036        let length = piece.cost(self)?;
1037        self.room(length.size().saturating_add(lap.after(&length)))?;
1038        self.put_piece(t, piece)?;
1039        let session = self.st.act.session.ok_or(Error::OutOfOrder)?;
1040        self.end_lap(t, &session, LapTrigger::Manual)
1041    }
1042
1043    /// Adds the intervals between heartbeats, in milliseconds, as they arrive; a beat's
1044    /// interval ends it. They are written five to a `hrv` message, and before the next record,
1045    /// so each follows the record it came after; they are kept while the timer is paused, as
1046    /// their sum is their only clock.
1047    ///
1048    /// # Errors
1049    ///
1050    /// [`Error::OutOfOrder`] outside the activity, [`Error::OutOfRange`] for 65,535; see
1051    /// [`Error`].
1052    pub fn beat_intervals_ms(&mut self, intervals: &[u16]) -> Result<(), Error> {
1053        self.beats_fit(intervals, true)?;
1054        self.beats(intervals.iter().copied())
1055    }
1056
1057    /// [`Writer::beat_intervals_ms`], from intervals in 1/1024 s, as a Bluetooth heart rate
1058    /// sensor gives them; each is rounded to the millisecond.
1059    ///
1060    /// # Errors
1061    ///
1062    /// [`Error::OutOfOrder`] outside the activity; see [`Error`].
1063    pub fn beat_intervals_1024ths(&mut self, intervals: &[u16]) -> Result<(), Error> {
1064        self.beats_fit(intervals, false)?;
1065        self.beats(intervals.iter().map(|&n| {
1066            let ms = per(u32::from(n).saturating_mul(1000), 1024u32);
1067            ms.and_then(|ms| u16::try_from(ms).ok()).unwrap_or(u16::MAX)
1068        }))
1069    }
1070
1071    /// Refuses `intervals`, in milliseconds or else 1/1024 s, unless every message they fill
1072    /// can be written.
1073    pub(super) fn beats_fit(&mut self, intervals: &[u16], ms: bool) -> Result<(), Error> {
1074        self.st.act.started(self.st.act.now)?;
1075        if ms && intervals.contains(&u16::MAX) {
1076            return Err(Error::OutOfRange);
1077        }
1078        let count = self.st.act.beat_count.saturating_add(intervals.len());
1079        if let Some(more) = (count / HRV_BEATS).checked_sub(1) {
1080            let first = self.cost(&Hrv(&[0; HRV_BEATS]))?;
1081            let more = u32::try_from(more).unwrap_or(u32::MAX).saturating_mul(first.body);
1082            self.room(first.size().saturating_add(more))?;
1083        }
1084        Ok(())
1085    }
1086
1087    /// Keeps `intervals`, which [`Writer::beats_fit`] allowed, writing each five as they fill.
1088    fn beats(&mut self, intervals: impl Iterator<Item = u16>) -> Result<(), Error> {
1089        for ms in intervals {
1090            let act = &mut self.st.act;
1091            if let Some(slot) = act.beats.get_mut(act.beat_count) {
1092                *slot = ms;
1093                act.beat_count = act.beat_count.saturating_add(1);
1094            }
1095            if act.beat_count == HRV_BEATS {
1096                self.write_beats()?;
1097            }
1098        }
1099        Ok(())
1100    }
1101
1102    /// The bytes the beat intervals not yet written take.
1103    fn beats_cost(&self) -> Result<u32, Error> {
1104        let act = &self.st.act;
1105        match act.beats.get(..act.beat_count).filter(|b| !b.is_empty()) {
1106            Some(beats) => Ok(self.cost(&Hrv(beats))?.size()),
1107            None => Ok(0),
1108        }
1109    }
1110
1111    /// Writes the beat intervals not yet written.
1112    fn write_beats(&mut self) -> Result<(), Error> {
1113        let act = self.st.act;
1114        let Some(beats) = act.beats.get(..act.beat_count).filter(|b| !b.is_empty()) else {
1115            return Ok(());
1116        };
1117        self.fixed(&Hrv(beats), 0)?;
1118        self.st.act.beat_count = 0;
1119        Ok(())
1120    }
1121
1122    /// What ends the open session's rest at `t`, if it has one: an idle length or a rest set.
1123    fn rest_piece(&self, t: Timestamp) -> Result<Option<Piece>, Error> {
1124        let Some(session) = self.st.act.session.filter(|s| s.resting) else { return Ok(None) };
1125        let piece = if session.pool.is_some() {
1126            self.length_at(t, &session, None)?
1127        } else {
1128            self.set_at(t, &session, None)?
1129        };
1130        Ok(Some(piece))
1131    }
1132
1133    /// A length ending at `t`, swum or, without one, idle.
1134    fn length_at(
1135        &self,
1136        t: Timestamp,
1137        session: &OpenSession,
1138        swum: Option<Length>,
1139    ) -> Result<Piece, Error> {
1140        let pool = session.pool.ok_or(Error::OutOfOrder)?;
1141        let index = next_index(self.st.act.lengths)?;
1142        let (start, since) = session.mark;
1143        let seconds = self.st.act.timer_at(t).saturating_sub(since);
1144        let cm = u32::from(pool.centimetres);
1145        let msg = LengthMsg {
1146            span: Span {
1147                start_time: start,
1148                timestamp: t,
1149                total_elapsed_ms: ms(t.fit().saturating_sub(start.fit())),
1150                total_timer_ms: ms(seconds),
1151            },
1152            swum,
1153            avg_speed: swum
1154                .and_then(|_| per(cm.saturating_mul(10), seconds))
1155                .and_then(|v| u16::try_from(v).ok())
1156                .filter(|&v| v != u16::MAX),
1157            cadence: swum
1158                .and_then(|l| per(u32::from(l.strokes?).saturating_mul(60), seconds))
1159                .and_then(|v| u8::try_from(v).ok())
1160                .filter(|&v| v != u8::MAX),
1161        };
1162        check(&msg)?;
1163        let distance = match swum {
1164            Some(_) => self.st.act.distance.checked_add(cm).filter(|&d| d != u32::MAX),
1165            None => Some(self.st.act.distance),
1166        };
1167        let distance = distance.ok_or(Error::OutOfRange)?;
1168        self.endable(t, self.st.laps, self.st.sessions)?;
1169        Ok(Piece::Length { msg, index, distance, pool })
1170    }
1171
1172    /// A set ending at `t`, or without one, a rest.
1173    fn set_at(
1174        &self,
1175        t: Timestamp,
1176        session: &OpenSession,
1177        set: Option<Set>,
1178    ) -> Result<Piece, Error> {
1179        let index = next_index(self.st.act.sets)?;
1180        let (start, since) = session.mark;
1181        let msg = SetMsg {
1182            start_time: start,
1183            timestamp: t,
1184            duration_ms: ms(self.st.act.timer_at(t).saturating_sub(since)),
1185            set,
1186        };
1187        check(&msg)?;
1188        self.endable(t, self.st.laps, self.st.sessions)?;
1189        Ok(Piece::Set { msg, index })
1190    }
1191
1192    /// Writes a length or set ending at `t`, which ends any rest.
1193    fn put_piece(&mut self, t: Timestamp, piece: Piece) -> Result<(), Error> {
1194        let timer = self.st.act.timer_at(t);
1195        match piece {
1196            Piece::Length { msg, index, distance, .. } => {
1197                self.fixed(&msg, index)?;
1198                let act = &mut self.st.act;
1199                (act.lengths, act.now, act.distance) = (index.saturating_add(1), t, distance);
1200                if let Some(s) = act.session.as_mut() {
1201                    piece.add_to(s);
1202                }
1203            }
1204            Piece::Set { msg, index } => {
1205                self.fixed(&msg, index)?;
1206                let act = &mut self.st.act;
1207                (act.sets, act.now) = (index.saturating_add(1), t);
1208                if let (Some(s), Some(set)) = (act.session.as_mut(), &msg.set) {
1209                    s.span.seen.add_repetitions(set);
1210                }
1211            }
1212        }
1213        if let Some(s) = self.st.act.session.as_mut() {
1214            (s.mark, s.resting) = ((t, timer), false);
1215        }
1216        Ok(())
1217    }
1218
1219    /// Ends the activity at `t`: the timer stops, and the last lap, the last session and the
1220    /// activity are written.
1221    ///
1222    /// # Errors
1223    ///
1224    /// [`Error::OutOfOrder`] if no session has started; see [`Error`].
1225    pub fn end(&mut self, t: Timestamp) -> Result<(), Error> {
1226        self.st.act.started(t)?;
1227        if self.st.act.session.is_none() {
1228            return Err(Error::OutOfOrder);
1229        }
1230        self.endable(t, self.st.laps, self.st.sessions)?;
1231        let rest = self.rest_piece(t)?;
1232        let timer = self.st.act.timer_at(t);
1233        let activity = self.activity(t);
1234        self.ahead(END)?;
1235        self.st.act.phase = Phase::Ending;
1236        if let Some(piece) = rest {
1237            self.put_piece(t, piece)?;
1238        }
1239        self.write_beats()?;
1240        self.raw_event(Event::timer_stop_all(t))?;
1241        self.close_session(t, trigger::ACTIVITY_END)?;
1242        self.raw_activity(&activity)?;
1243        let act = &mut self.st.act;
1244        (act.timer, act.since, act.running, act.now, act.phase) =
1245            (timer, t, false, t, Phase::Ended);
1246        Ok(())
1247    }
1248
1249    /// The open session's last lap and the session itself as they would end at `t`.
1250    fn closing(&self, t: Timestamp, trigger: u8) -> Option<(Lap, Session)> {
1251        let s = self.st.act.session?;
1252        let timer = self.st.act.timer_at(t);
1253        let lap = lap_message(&s.lap, t, timer, &s).trigger(lap_trigger::SESSION_END);
1254        let elapsed = t.fit().saturating_sub(s.span.start.fit());
1255        let laps = self.st.laps.saturating_add(1).saturating_sub(s.first_lap);
1256        let running = timer.saturating_sub(s.span.timer);
1257        let mut totals = s.span.seen.totals(running);
1258        if s.takes_sets() {
1259            totals.cycles = s.span.seen.repetitions;
1260        }
1261        let mut session = Session::new(s.span.start, t, ms(elapsed), ms(running))
1262            .sport(s.sport, s.sub_sport)
1263            .laps(s.first_lap, laps)
1264            .totals(totals)
1265            .trigger(trigger);
1266        if let Some(pool) = s.pool {
1267            session = session.pool(pool);
1268        }
1269        if let (Some(avg), Some(max)) = s.span.seen.heart_rate.summary_u8() {
1270            session = session.heart_rate(avg, max);
1271        }
1272        Some((lap, session))
1273    }
1274
1275    /// The activity message as it would end at `t`.
1276    fn activity(&self, t: Timestamp) -> Activity {
1277        let timer = ms(self.st.act.timer_at(t));
1278        let activity = Activity::new(t, timer)
1279            .sessions(self.st.sessions.saturating_add(1))
1280            .auto_multisport(self.st.options.auto_multisport);
1281        match self.st.options.utc_offset {
1282            Some(offset) => activity.utc_offset(offset),
1283            None => activity,
1284        }
1285    }
1286
1287    /// Refuses a call after which, with `laps` laps and `sessions` sessions written, the
1288    /// activity could not end at `t`.
1289    pub(super) fn endable(&self, t: Timestamp, laps: u16, sessions: u16) -> Result<(), Error> {
1290        next_index(laps)?;
1291        next_index(sessions)?;
1292        check(&self.activity(t))?;
1293        if let Some((lap, session)) = self.closing(t, trigger::ACTIVITY_END) {
1294            check(&lap)?;
1295            check(&session)?;
1296        }
1297        Ok(())
1298    }
1299
1300    /// Ends the open session, if any, at `t`, by `trigger`.
1301    fn close_session(&mut self, t: Timestamp, trigger: u8) -> Result<(), Error> {
1302        let Some((lap, session)) = self.closing(t, trigger) else { return Ok(()) };
1303        check(&lap)?;
1304        check(&session)?;
1305        self.raw_lap(&lap)?;
1306        self.raw_session(&session)?;
1307        self.st.act.session = None;
1308        Ok(())
1309    }
1310}
1311
1312#[cfg(test)]
1313mod tests;