Skip to main content

rustynes_core/
speedrun.rs

1//! v3.5.0 (`T-SPEEDRUN-MEMIF`) — speedrun auto-timing on RAM predicates,
2//! counted in master-clock cycles.
3//!
4//! A speedrun timer has to answer two questions every frame: has the run
5//! started (or reached its next split, or been reset), and how long has it
6//! taken. `RustyNES` answers the first with **RAM predicates written in the
7//! `RetroAchievements` condition grammar** (the `0xH0770=1_d0xH0770=0` strings
8//! achievement sets are written in, so a condition copied from an achievement
9//! set or a splitter's notes works unchanged), and the second with **the
10//! console's own master clock**: the time of a run is the number of master-
11//! clock cycles between the frame its start predicate fired and the frame its
12//! last split fired.
13//!
14//! # Why the master clock, not frames or the wall clock
15//!
16//! - **Wall-clock time** depends on the host (a stutter, fast-forward, a
17//!   paused window). A run timed from a movie must give the same number on
18//!   every machine and every replay, and only emulated time can.
19//! - **Frames** are not all the same length. An NTSC frame is 89,342 or
20//!   89,341 PPU dots depending on the odd-frame skip, the extra-scanline
21//!   option lengthens them, and a lag frame is still a frame. The master clock
22//!   counts what the console actually ran: [`crate::Nes`]'s CPU master clock,
23//!   which advances by the region's divider (12 NTSC, 16 PAL, 15 Dendy) on
24//!   every CPU cycle. A difference of two readings is exact, and seconds follow
25//!   from the region's master-clock frequency ([`master_clock_hz`]).
26//!
27//! The predicates are evaluated once per frame, after the frame (the same
28//! cadence `RetroAchievements` evaluates achievements at), so a split's time
29//! is resolved to the end of the frame its condition first held in. That is
30//! the resolution every RAM-driven splitter has; what this adds is that the
31//! frame boundary itself is exact.
32//!
33//! # The condition grammar (the subset implemented)
34//!
35//! Written from the `RetroAchievements` developer documentation of the
36//! condition syntax (public prose; no implementation was consulted). A
37//! condition set is one or more **groups** separated by `S`; the set is true
38//! when the first (core) group is true and, if there are more groups, at least
39//! one of them is. A group is **conditions** separated by `_`, all of which
40//! must hold. A condition is
41//!
42//! ```text
43//! operand  comparison  operand  [ "." hits "." ]
44//! ```
45//!
46//! | Piece | Accepted |
47//! | --- | --- |
48//! | memory operand | `0x` + size + hex address. Sizes: `M`..`T` bit 0..7, `L` low nibble, `U` high nibble, `H` 8-bit, none (or a space) 16-bit, `W` 24-bit, `X` 32-bit (little-endian), `I` / `J` / `G` 16 / 24 / 32-bit big-endian, `K` bit count of a byte |
49//! | operand prefix | `d` delta (the value at the previous evaluation), `p` prior (the value before the last change), `b` BCD, `~` bitwise invert (within the operand's size) |
50//! | constant | decimal (`12`) or `h` + hex (`h1F`) |
51//! | comparison | `=` `!=` `<` `<=` `>` `>=` |
52//! | hit target | `.N.`: the condition must have been true on `N` evaluations (counted while its trigger is armed) |
53//!
54//! Addresses are `RetroAchievements` NES addresses, the same ones
55//! `rustynes-cheevos` maps (`ra_addr_to_nes`): the CPU bus itself, per the
56//! rcheevos region table (system RAM at `0x0000`, cartridge RAM at `0x6000`,
57//! ROM at `0x8000`), read side-effect-free; anything above `0xFFFF` reads 0.
58//! [`ra_flat_to_cpu`] is the mapping; a frontend test (in a
59//! `retroachievements` build) pins it to the cheevos crate's. (Until v3.5.0's review both mapped `0x0800..=0x27FF` onto
60//! cartridge RAM, which is not RA's layout; `CodeRabbit` on #624.)
61//!
62//! **Not implemented**, and refused with a message rather than misread:
63//! condition flags (`R:` reset-if, `P:` pause-if, `A:` add-source, `B:`,
64//! `C:`, `N:`, `M:`, `Q:`, `I:`, `T:`, `Z:`, `O:`, `D:`, `K:`), float and
65//! negative constants, arithmetic operators (`*`, `/`, `&`, `^`, `%`, `+`,
66//! `-`), and the `f` float sizes. A splits file has its own `reset` predicate,
67//! which covers the common use of `R:`.
68//!
69//! # The splits definition
70//!
71//! A small line-based text format ([`SplitsDefinition::parse`]):
72//!
73//! ```text
74//! # comments and blank lines are ignored
75//! game = Super Mario Bros.
76//! category = Any%
77//! start = 0xH0770=1_d0xH0770=0
78//! split = World 1 | 0xH075f=1_d0xH075f=0
79//! split = Bowser | 0xH0770=2
80//! reset = 0xH0770=0
81//! ```
82//!
83//! `start` and at least one `split` are required; the last split ends the
84//! run. `reset` is optional. Keys are split from values at the FIRST `=`, so a
85//! condition keeps its own `=` signs; a split's name and condition are split
86//! at the first `|`.
87//!
88//! # Determinism
89//!
90//! The timer only reads: a `FnMut(u32) -> u8` peek closure (side-effect-free
91//! on the NES: [`crate::Nes::peek`]) and two counters. It never writes the
92//! console, so attaching it cannot change a frame, a sample or a bus cycle,
93//! and the same movie replayed twice produces the same split times
94//! (`crates/rustynes-test-harness/tests/speedrun_timer.rs` checks both).
95
96use alloc::format;
97use alloc::string::{String, ToString};
98use alloc::vec::Vec;
99use core::fmt::Write as _;
100
101use crate::Region;
102
103/// The master-clock frequency of `region` as an exact fraction
104/// `(numerator, denominator)` in hertz.
105///
106/// NTSC: 236.25 MHz / 11 = 21.477272... MHz (six times the 315/88 MHz colour
107/// subcarrier). PAL and Dendy: 26.6017125 MHz (six times the 4.43361875 MHz
108/// subcarrier). The rounded figures are in `ref-docs/nesdev-wiki-technical-
109/// report.md`'s clock table (21.477272 / 26.601712 MHz, dividers 12 / 16 / 15).
110#[must_use]
111pub const fn master_clock_hz_ratio(region: Region) -> (u64, u64) {
112    match region {
113        Region::Ntsc => (236_250_000, 11),
114        Region::Pal | Region::Dendy => (53_203_425, 2),
115    }
116}
117
118/// The master-clock frequency of `region` in hertz.
119#[must_use]
120#[allow(clippy::cast_precision_loss)] // both terms are far below 2^53.
121pub fn master_clock_hz(region: Region) -> f64 {
122    let (n, d) = master_clock_hz_ratio(region);
123    n as f64 / d as f64
124}
125
126/// `cycles` master-clock cycles of `region`, in seconds.
127#[must_use]
128#[allow(clippy::cast_precision_loss)] // a run of 2^53 cycles is 13 years.
129pub fn cycles_to_seconds(cycles: u64, region: Region) -> f64 {
130    let (n, d) = master_clock_hz_ratio(region);
131    cycles as f64 * d as f64 / n as f64
132}
133
134/// A `RetroAchievements` NES address as a CPU-bus address: the identity over
135/// `0x0000..=0xFFFF`, `None` above it. See the module docs.
136#[must_use]
137#[allow(clippy::cast_possible_truncation)] // the cast is range-checked.
138pub const fn ra_flat_to_cpu(addr: u32) -> Option<u16> {
139    if addr <= 0xFFFF {
140        Some(addr as u16)
141    } else {
142        None
143    }
144}
145
146/// Why a condition or a splits file was refused.
147#[derive(Clone, Debug, PartialEq, Eq)]
148pub struct ParseError {
149    /// What was wrong, in words, naming the offending text.
150    pub message: String,
151    /// The 1-based line of a splits file, or 0 for a bare condition.
152    pub line: usize,
153}
154
155impl core::fmt::Display for ParseError {
156    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
157        if self.line == 0 {
158            f.write_str(&self.message)
159        } else {
160            write!(f, "line {}: {}", self.line, self.message)
161        }
162    }
163}
164
165fn err(message: impl Into<String>) -> ParseError {
166    ParseError {
167        message: message.into(),
168        line: 0,
169    }
170}
171
172/// The width of a memory operand.
173#[derive(Clone, Copy, Debug, PartialEq, Eq)]
174enum Size {
175    Bit(u8),
176    Low4,
177    High4,
178    Byte,
179    BitCount,
180    Le(u8),
181    Be(u8),
182}
183
184impl Size {
185    /// The largest value this size can hold (for `~`).
186    const fn mask(self) -> u32 {
187        match self {
188            Self::Bit(_) => 1,
189            Self::Low4 | Self::High4 => 0xF,
190            Self::Byte | Self::BitCount => 0xFF,
191            Self::Le(n) | Self::Be(n) => {
192                if n >= 4 {
193                    u32::MAX
194                } else {
195                    (1u32 << (8 * n as u32)) - 1
196                }
197            }
198        }
199    }
200}
201
202/// How a memory operand's value is taken.
203#[derive(Clone, Copy, Debug, PartialEq, Eq)]
204enum Modifier {
205    Value,
206    Delta,
207    Prior,
208    Bcd,
209    Invert,
210}
211
212#[derive(Clone, Debug, PartialEq, Eq)]
213enum Operand {
214    Const(u32),
215    Mem {
216        addr: u32,
217        size: Size,
218        modifier: Modifier,
219        /// The value at the previous evaluation (`None` before the first).
220        delta: Option<u32>,
221        /// The value before the last change.
222        prior: u32,
223    },
224}
225
226#[derive(Clone, Copy, Debug, PartialEq, Eq)]
227enum Cmp {
228    Eq,
229    Ne,
230    Lt,
231    Le,
232    Gt,
233    Ge,
234}
235
236#[derive(Clone, Debug, PartialEq, Eq)]
237struct Condition {
238    left: Operand,
239    cmp: Cmp,
240    right: Operand,
241    /// Hit target (`0` = none: true whenever the comparison is).
242    target: u32,
243    hits: u32,
244}
245
246/// A parsed condition set: the core group and any alternative groups.
247#[derive(Clone, Debug, PartialEq, Eq)]
248pub struct Trigger {
249    groups: Vec<Vec<Condition>>,
250    source: String,
251}
252
253fn read_mem(addr: u32, size: Size, read: &mut impl FnMut(u32) -> u8) -> u32 {
254    let byte = |read: &mut dyn FnMut(u32) -> u8, a: u32| u32::from(read(a));
255    match size {
256        Size::Bit(b) => (byte(read, addr) >> b) & 1,
257        Size::Low4 => byte(read, addr) & 0xF,
258        Size::High4 => byte(read, addr) >> 4,
259        Size::Byte => byte(read, addr),
260        Size::BitCount => byte(read, addr).count_ones(),
261        Size::Le(n) => {
262            (0..u32::from(n)).fold(0, |v, i| v | (byte(read, addr.wrapping_add(i)) << (8 * i)))
263        }
264        Size::Be(n) => {
265            (0..u32::from(n)).fold(0, |v, i| (v << 8) | byte(read, addr.wrapping_add(i)))
266        }
267    }
268}
269
270/// Hex digits of `v` read as decimal (`0x1234` -> 1234); a nibble above 9
271/// reads as its value (`0xA` -> 10), the usual BCD-decoder leniency.
272const fn bcd(v: u32) -> u32 {
273    let mut out = 0u32;
274    let mut mul = 1u32;
275    let mut v = v;
276    while v != 0 {
277        out = out.wrapping_add((v & 0xF).wrapping_mul(mul));
278        mul = mul.wrapping_mul(10);
279        v >>= 4;
280    }
281    out
282}
283
284impl Operand {
285    /// This evaluation's value. `read` peeks a RA flat address.
286    fn value(&self, read: &mut impl FnMut(u32) -> u8) -> u32 {
287        match *self {
288            Self::Const(c) => c,
289            Self::Mem {
290                addr,
291                size,
292                modifier,
293                delta,
294                prior,
295            } => {
296                let now = read_mem(addr, size, read);
297                match modifier {
298                    Modifier::Value => now,
299                    // Before the first evaluation there is no previous value;
300                    // the current one stands in, so `d` never reports a change
301                    // that did not happen (no edge on the first frame).
302                    Modifier::Delta => delta.unwrap_or(now),
303                    // The same rule for `p`: with no history (the first frame,
304                    // or the first after a discontinuity cleared it) the
305                    // current value stands in. Until v3.5.0's review this
306                    // returned the stored prior, 0 on the first frame and the
307                    // pre-jump value after a state load, so `p` could report a
308                    // change that never happened in this timeline (Antigravity
309                    // on #624).
310                    Modifier::Prior => {
311                        if delta.is_some() {
312                            prior
313                        } else {
314                            now
315                        }
316                    }
317                    Modifier::Bcd => bcd(now),
318                    Modifier::Invert => !now & size.mask(),
319                }
320            }
321        }
322    }
323
324    /// Record this evaluation's raw value for the next one's `d` / `p`.
325    fn advance(&mut self, read: &mut impl FnMut(u32) -> u8) {
326        if let Self::Mem {
327            addr,
328            size,
329            delta,
330            prior,
331            ..
332        } = self
333        {
334            let now = read_mem(*addr, *size, read);
335            match *delta {
336                None => *prior = now,
337                Some(last) if last != now => *prior = last,
338                Some(_) => {}
339            }
340            *delta = Some(now);
341        }
342    }
343
344    const fn reset_history(&mut self) {
345        if let Self::Mem { delta, .. } = self {
346            *delta = None;
347        }
348    }
349}
350
351impl Cmp {
352    const fn test(self, a: u32, b: u32) -> bool {
353        match self {
354            Self::Eq => a == b,
355            Self::Ne => a != b,
356            Self::Lt => a < b,
357            Self::Le => a <= b,
358            Self::Gt => a > b,
359            Self::Ge => a >= b,
360        }
361    }
362}
363
364/// A byte cursor over a condition string.
365struct Cursor<'a> {
366    s: &'a [u8],
367    i: usize,
368}
369
370impl Cursor<'_> {
371    fn peek(&self) -> Option<u8> {
372        self.s.get(self.i).copied()
373    }
374    fn eat(&mut self, b: u8) -> bool {
375        if self.peek() == Some(b) {
376            self.i += 1;
377            true
378        } else {
379            false
380        }
381    }
382    fn rest(&self) -> &str {
383        core::str::from_utf8(&self.s[self.i..]).unwrap_or("?")
384    }
385    fn hex(&mut self) -> Option<u32> {
386        let start = self.i;
387        while self.peek().is_some_and(|b| b.is_ascii_hexdigit()) {
388            self.i += 1;
389        }
390        let digits = core::str::from_utf8(&self.s[start..self.i]).ok()?;
391        if digits.is_empty() {
392            None
393        } else {
394            u32::from_str_radix(digits, 16).ok()
395        }
396    }
397    fn dec(&mut self) -> Option<u32> {
398        let start = self.i;
399        while self.peek().is_some_and(|b| b.is_ascii_digit()) {
400            self.i += 1;
401        }
402        let digits = core::str::from_utf8(&self.s[start..self.i]).ok()?;
403        if digits.is_empty() {
404            None
405        } else {
406            digits.parse().ok()
407        }
408    }
409}
410
411fn parse_operand(c: &mut Cursor<'_>) -> Result<Operand, ParseError> {
412    let modifier = match c.peek() {
413        Some(b'd' | b'D') => Modifier::Delta,
414        Some(b'p' | b'P') => Modifier::Prior,
415        Some(b'b' | b'B') => Modifier::Bcd,
416        Some(b'~') => Modifier::Invert,
417        _ => Modifier::Value,
418    };
419    if modifier != Modifier::Value {
420        c.i += 1;
421    }
422    if c.s[c.i..].starts_with(b"0x") || c.s[c.i..].starts_with(b"0X") {
423        c.i += 2;
424        let size = match c.peek().map(|b| b.to_ascii_uppercase()) {
425            Some(b @ b'M'..=b'T') => {
426                c.i += 1;
427                Size::Bit(b - b'M')
428            }
429            Some(b'L') => {
430                c.i += 1;
431                Size::Low4
432            }
433            Some(b'U') => {
434                c.i += 1;
435                Size::High4
436            }
437            Some(b'H') => {
438                c.i += 1;
439                Size::Byte
440            }
441            Some(b'K') => {
442                c.i += 1;
443                Size::BitCount
444            }
445            Some(b'W') => {
446                c.i += 1;
447                Size::Le(3)
448            }
449            Some(b'X') => {
450                c.i += 1;
451                Size::Le(4)
452            }
453            Some(b'I') => {
454                c.i += 1;
455                Size::Be(2)
456            }
457            Some(b'J') => {
458                c.i += 1;
459                Size::Be(3)
460            }
461            Some(b'G') => {
462                c.i += 1;
463                Size::Be(4)
464            }
465            Some(b' ') => {
466                c.i += 1;
467                Size::Le(2)
468            }
469            Some(b) if b.is_ascii_hexdigit() => Size::Le(2),
470            _ => {
471                return Err(err(format!(
472                    "unsupported memory size at {:?} (supported: M-T, L, U, H, K, W, X, I, J, G, or none for 16-bit)",
473                    c.rest()
474                )));
475            }
476        };
477        let addr = c
478            .hex()
479            .ok_or_else(|| err(format!("expected a hex address at {:?}", c.rest())))?;
480        return Ok(Operand::Mem {
481            addr,
482            size,
483            modifier,
484            delta: None,
485            prior: 0,
486        });
487    }
488    if modifier != Modifier::Value && modifier != Modifier::Bcd {
489        return Err(err(format!(
490            "a prefix needs a memory operand at {:?}",
491            c.rest()
492        )));
493    }
494    if modifier == Modifier::Bcd {
495        return Err(err("`b` (BCD) applies to a memory operand"));
496    }
497    if c.eat(b'h') || c.eat(b'H') {
498        return c
499            .hex()
500            .map(Operand::Const)
501            .ok_or_else(|| err(format!("expected hex digits after `h` at {:?}", c.rest())));
502    }
503    if matches!(c.peek(), Some(b'f' | b'F' | b'-' | b'+')) {
504        return Err(err(format!(
505            "float and signed constants are not supported ({:?})",
506            c.rest()
507        )));
508    }
509    c.dec()
510        .map(Operand::Const)
511        .ok_or_else(|| err(format!("expected an operand at {:?}", c.rest())))
512}
513
514fn parse_condition(c: &mut Cursor<'_>) -> Result<Condition, ParseError> {
515    // A flag is one letter and a colon.
516    if c.s.get(c.i + 1) == Some(&b':') && c.peek().is_some_and(|b| b.is_ascii_alphabetic()) {
517        return Err(err(format!(
518            "condition flags are not supported by the speedrun timer ({:?}); use the splits file's `reset` for a reset",
519            c.rest()
520        )));
521    }
522    let left = parse_operand(c)?;
523    let cmp = if c.eat(b'=') {
524        Cmp::Eq
525    } else if c.eat(b'!') {
526        if !c.eat(b'=') {
527            return Err(err("`!` must be `!=`"));
528        }
529        Cmp::Ne
530    } else if c.eat(b'<') {
531        if c.eat(b'=') { Cmp::Le } else { Cmp::Lt }
532    } else if c.eat(b'>') {
533        if c.eat(b'=') { Cmp::Ge } else { Cmp::Gt }
534    } else {
535        return Err(err(format!(
536            "expected a comparison (= != < <= > >=) at {:?}",
537            c.rest()
538        )));
539    };
540    let right = parse_operand(c)?;
541    let mut target = 0;
542    if c.eat(b'.') {
543        target = c
544            .dec()
545            .ok_or_else(|| err("a hit target is `.N.` with N a decimal number"))?;
546        if !c.eat(b'.') {
547            return Err(err("a hit target is `.N.`: missing the closing `.`"));
548        }
549    }
550    Ok(Condition {
551        left,
552        cmp,
553        right,
554        target,
555        hits: 0,
556    })
557}
558
559impl Trigger {
560    /// Parse a condition set (see the module docs for the grammar).
561    ///
562    /// # Errors
563    ///
564    /// [`ParseError`] naming the first piece that is malformed or unsupported.
565    pub fn parse(source: &str) -> Result<Self, ParseError> {
566        let trimmed = source.trim();
567        if trimmed.is_empty() {
568            return Err(err("an empty condition"));
569        }
570        let mut c = Cursor {
571            s: trimmed.as_bytes(),
572            i: 0,
573        };
574        let mut groups = alloc::vec![Vec::new()];
575        loop {
576            let cond = parse_condition(&mut c)?;
577            groups.last_mut().expect("never empty").push(cond);
578            match c.peek() {
579                None => break,
580                Some(b'_') => c.i += 1,
581                Some(b'S') => {
582                    c.i += 1;
583                    groups.push(Vec::new());
584                }
585                Some(_) => {
586                    return Err(err(format!(
587                        "expected `_`, `S` or the end at {:?}",
588                        c.rest()
589                    )));
590                }
591            }
592        }
593        Ok(Self {
594            groups,
595            source: trimmed.to_string(),
596        })
597    }
598
599    /// The condition text this trigger was parsed from.
600    #[must_use]
601    pub fn source(&self) -> &str {
602        &self.source
603    }
604
605    /// Evaluate the set against memory. When `armed`, hit counts advance and
606    /// the result is returned; when not, the conditions are only sampled (so
607    /// their `d` / `p` history stays one frame deep) and the result is
608    /// `false`. Either way the operand history then advances.
609    pub fn evaluate(&mut self, armed: bool, read: &mut impl FnMut(u32) -> u8) -> bool {
610        let mut group_true = Vec::with_capacity(self.groups.len());
611        for group in &mut self.groups {
612            let mut all = true;
613            for cond in group.iter_mut() {
614                let ok = cond.cmp.test(cond.left.value(read), cond.right.value(read));
615                let held = if cond.target == 0 {
616                    ok
617                } else {
618                    if armed && ok && cond.hits < cond.target {
619                        cond.hits += 1;
620                    }
621                    cond.hits >= cond.target
622                };
623                all &= held;
624            }
625            group_true.push(all);
626        }
627        for group in &mut self.groups {
628            for cond in group.iter_mut() {
629                cond.left.advance(read);
630                cond.right.advance(read);
631            }
632        }
633        let core = group_true[0];
634        let alt = group_true.len() == 1 || group_true[1..].iter().any(|&g| g);
635        armed && core && alt
636    }
637
638    /// Clear the hit counts (the trigger is re-armed from zero).
639    pub fn reset_hits(&mut self) {
640        for cond in self.groups.iter_mut().flatten() {
641            cond.hits = 0;
642        }
643    }
644
645    /// Forget the `d` / `p` history, as after a discontinuity in time.
646    fn reset_history(&mut self) {
647        for cond in self.groups.iter_mut().flatten() {
648            cond.left.reset_history();
649            cond.right.reset_history();
650        }
651    }
652}
653
654/// A named split: the predicate that ends its segment.
655#[derive(Clone, Debug, PartialEq, Eq)]
656pub struct Split {
657    /// Its name, as the splits file gives it.
658    pub name: String,
659    /// When it fires.
660    pub trigger: Trigger,
661}
662
663/// A parsed splits file (see the module docs for the format).
664#[derive(Clone, Debug, PartialEq, Eq)]
665pub struct SplitsDefinition {
666    /// The `game` line, or empty.
667    pub game: String,
668    /// The `category` line, or empty.
669    pub category: String,
670    /// When the run starts.
671    pub start: Trigger,
672    /// The splits, in order; the last ends the run. Never empty.
673    pub splits: Vec<Split>,
674    /// When a run in progress (or finished) is abandoned, if ever.
675    pub reset: Option<Trigger>,
676}
677
678/// The most splits a definition may have, which is also the size of the
679/// memory-export interface's split table.
680pub const MAX_SPLITS: usize = 64;
681
682impl SplitsDefinition {
683    /// Parse a splits file.
684    ///
685    /// # Errors
686    ///
687    /// [`ParseError`] with the line number, for an unknown key, a malformed
688    /// condition, a missing `start` or split, a second `game`, `category`,
689    /// `start` or `reset`, or more than [`MAX_SPLITS`] splits.
690    pub fn parse(text: &str) -> Result<Self, ParseError> {
691        let mut game = String::new();
692        let mut category = String::new();
693        let (mut seen_game, mut seen_category) = (false, false);
694        let mut start = None;
695        let mut reset = None;
696        let mut splits = Vec::new();
697        for (n, raw) in text.lines().enumerate() {
698            let line_no = n + 1;
699            let at = |e: ParseError| ParseError {
700                message: e.message,
701                line: line_no,
702            };
703            let line = raw.trim();
704            if line.is_empty() || line.starts_with('#') {
705                continue;
706            }
707            let Some((key, value)) = line.split_once('=') else {
708                return Err(at(err(format!("expected `key = value`, got {line:?}"))));
709            };
710            let (key, value) = (key.trim(), value.trim());
711            match key {
712                "game" | "category" => {
713                    // Refused like a second `start` / `reset`: a repeated
714                    // header line is a copy-paste slip, and keeping the last
715                    // one silently labels the run with the wrong name.
716                    let (slot, seen) = if key == "game" {
717                        (&mut game, &mut seen_game)
718                    } else {
719                        (&mut category, &mut seen_category)
720                    };
721                    if *seen {
722                        return Err(at(err(format!("a second `{key}`"))));
723                    }
724                    *seen = true;
725                    *slot = value.to_string();
726                }
727                "start" | "reset" => {
728                    let slot = if key == "start" {
729                        &mut start
730                    } else {
731                        &mut reset
732                    };
733                    if slot.is_some() {
734                        return Err(at(err(format!("a second `{key}`"))));
735                    }
736                    *slot = Some(Trigger::parse(value).map_err(at)?);
737                }
738                "split" => {
739                    let Some((name, cond)) = value.split_once('|') else {
740                        return Err(at(err("a split is `split = <name> | <condition>`")));
741                    };
742                    if splits.len() == MAX_SPLITS {
743                        return Err(at(err(format!("more than {MAX_SPLITS} splits"))));
744                    }
745                    splits.push(Split {
746                        name: name.trim().to_string(),
747                        trigger: Trigger::parse(cond).map_err(at)?,
748                    });
749                }
750                other => {
751                    return Err(at(err(format!(
752                        "unknown key `{other}` (expected game, category, start, split, reset)"
753                    ))));
754                }
755            }
756        }
757        let start = start.ok_or_else(|| err("no `start` line"))?;
758        if splits.is_empty() {
759            return Err(err("no `split` line: the last split ends the run"));
760        }
761        Ok(Self {
762            game,
763            category,
764            start,
765            splits,
766            reset,
767        })
768    }
769}
770
771/// Where a timer is.
772#[derive(Clone, Copy, Debug, PartialEq, Eq)]
773pub enum TimerState {
774    /// Waiting for the start predicate.
775    Idle,
776    /// Started; the next split has not fired.
777    Running,
778    /// The last split fired. Stays until the reset predicate (or a
779    /// discontinuity) returns it to [`Self::Idle`].
780    Finished,
781}
782
783impl TimerState {
784    /// The memory-export interface's code for this state (0 / 1 / 2).
785    #[must_use]
786    pub const fn code(self) -> u8 {
787        match self {
788            Self::Idle => 0,
789            Self::Running => 1,
790            Self::Finished => 2,
791        }
792    }
793}
794
795/// What one observation changed.
796#[derive(Clone, Copy, Debug, PartialEq, Eq)]
797pub enum TimerEvent {
798    /// The start predicate fired.
799    Started,
800    /// Split `n` (0-based) fired and the run continues.
801    Split(usize),
802    /// The last split fired.
803    Finished,
804    /// The reset predicate fired.
805    Reset,
806    /// Time ran backward or leapt (a state load, rewind, power cycle): the run
807    /// is abandoned, because its time no longer measures one run.
808    Discontinuity,
809}
810
811/// One split's time.
812#[derive(Clone, Copy, Debug, PartialEq, Eq)]
813pub struct SplitTime {
814    /// The master clock at the end of the frame the split fired in.
815    pub master_clock: u64,
816    /// Cycles from the start to this split.
817    pub elapsed: u64,
818    /// The frame counter at that point.
819    pub frame: u64,
820}
821
822/// The longest gap between two observations that still counts as one
823/// continuous run.
824///
825/// Sixteen of the longest region's frames (a PAL frame is
826/// 312 lines of 341 dots at 5 master clocks per dot, 531,960 master clocks),
827/// which leaves room for the extra-scanline option and an observer that skips
828/// a few frames. A larger leap, or any step backward, is a
829/// [`TimerEvent::Discontinuity`].
830pub const MAX_OBSERVATION_GAP: u64 = 16 * 531_960;
831
832/// The timer. Feed it [`Self::observe`] once per frame, after the frame.
833#[derive(Clone, Debug)]
834pub struct SpeedrunTimer {
835    def: SplitsDefinition,
836    region: Region,
837    state: TimerState,
838    start_clock: u64,
839    start_frame: u64,
840    splits: Vec<SplitTime>,
841    last_clock: Option<u64>,
842    now: u64,
843}
844
845impl SpeedrunTimer {
846    /// A timer for `def`, timing in `region`'s master clock.
847    #[must_use]
848    pub const fn new(def: SplitsDefinition, region: Region) -> Self {
849        Self {
850            def,
851            region,
852            state: TimerState::Idle,
853            start_clock: 0,
854            start_frame: 0,
855            splits: Vec::new(),
856            last_clock: None,
857            now: 0,
858        }
859    }
860
861    /// The definition being timed.
862    #[must_use]
863    pub const fn definition(&self) -> &SplitsDefinition {
864        &self.def
865    }
866
867    /// The region whose master clock the times are in.
868    #[must_use]
869    pub const fn region(&self) -> Region {
870        self.region
871    }
872
873    /// The current state.
874    #[must_use]
875    pub const fn state(&self) -> TimerState {
876        self.state
877    }
878
879    /// The splits fired so far in this run.
880    #[must_use]
881    pub fn splits(&self) -> &[SplitTime] {
882        &self.splits
883    }
884
885    /// The master clock the run started at (meaningful once started).
886    #[must_use]
887    pub const fn start_clock(&self) -> u64 {
888        self.start_clock
889    }
890
891    /// Cycles since the start: live while running, the final time once
892    /// finished, 0 when idle.
893    #[must_use]
894    pub fn elapsed(&self) -> u64 {
895        match self.state {
896            TimerState::Idle => 0,
897            TimerState::Running => self.now.saturating_sub(self.start_clock),
898            TimerState::Finished => self.splits.last().map_or(0, |s| s.elapsed),
899        }
900    }
901
902    /// Return to idle and clear every hit count, as if just created (the
903    /// operand history is kept: time did not jump).
904    pub fn reset(&mut self) {
905        self.state = TimerState::Idle;
906        self.splits.clear();
907        self.def.start.reset_hits();
908        for s in &mut self.def.splits {
909            s.trigger.reset_hits();
910        }
911        if let Some(r) = self.def.reset.as_mut() {
912            r.reset_hits();
913        }
914    }
915
916    /// Observe the end of a frame: `master_clock` and `frame` are the
917    /// console's counters now (on [`crate::Nes`], `cpu().master_clock()` and
918    /// `frame()`), and `read` peeks a `RetroAchievements` flat address
919    /// (unmapped addresses should read 0; [`Self::observe_nes`] does this).
920    pub fn observe(
921        &mut self,
922        master_clock: u64,
923        frame: u64,
924        mut read: impl FnMut(u32) -> u8,
925    ) -> Option<TimerEvent> {
926        let mut event = None;
927        if let Some(last) = self.last_clock
928            && (master_clock < last || master_clock - last > MAX_OBSERVATION_GAP)
929        {
930            let was_active = self.state != TimerState::Idle;
931            self.reset();
932            self.def.start.reset_history();
933            for s in &mut self.def.splits {
934                s.trigger.reset_history();
935            }
936            if let Some(r) = self.def.reset.as_mut() {
937                r.reset_history();
938            }
939            if was_active {
940                event = Some(TimerEvent::Discontinuity);
941            }
942        }
943        self.last_clock = Some(master_clock);
944        self.now = master_clock;
945
946        // Every trigger is evaluated every frame so its `d` / `p` history is
947        // one frame deep whenever it becomes the one that matters; only the
948        // armed ones count hits or fire.
949        let state = self.state;
950        let next = self.splits.len();
951        let start_fired = self
952            .def
953            .start
954            .evaluate(state == TimerState::Idle, &mut read);
955        let reset_fired = self
956            .def
957            .reset
958            .as_mut()
959            .is_some_and(|r| r.evaluate(state != TimerState::Idle, &mut read));
960        let mut split_fired = false;
961        for (i, s) in self.def.splits.iter_mut().enumerate() {
962            let fired = s
963                .trigger
964                .evaluate(state == TimerState::Running && i == next, &mut read);
965            split_fired |= fired;
966        }
967        if event.is_some() {
968            return event;
969        }
970        match state {
971            TimerState::Idle if start_fired => {
972                self.state = TimerState::Running;
973                self.start_clock = master_clock;
974                self.start_frame = frame;
975                self.splits.clear();
976                Some(TimerEvent::Started)
977            }
978            TimerState::Running | TimerState::Finished if reset_fired => {
979                self.reset();
980                Some(TimerEvent::Reset)
981            }
982            TimerState::Running if split_fired => {
983                self.splits.push(SplitTime {
984                    master_clock,
985                    elapsed: master_clock - self.start_clock,
986                    frame,
987                });
988                if self.splits.len() == self.def.splits.len() {
989                    self.state = TimerState::Finished;
990                    Some(TimerEvent::Finished)
991                } else {
992                    Some(TimerEvent::Split(self.splits.len() - 1))
993                }
994            }
995            _ => None,
996        }
997    }
998
999    /// [`Self::observe`] against a live console, after its frame.
1000    pub fn observe_nes(&mut self, nes: &mut crate::Nes) -> Option<TimerEvent> {
1001        let clock = nes.cpu().master_clock();
1002        let frame = nes.frame();
1003        self.observe(clock, frame, |a| {
1004            ra_flat_to_cpu(a).map_or(0, |cpu| nes.peek(cpu))
1005        })
1006    }
1007
1008    /// The run as a JSON document (format `rustynes-splits-result`, version
1009    /// 1, documented in `docs/memory-export-interface.md`). Times are given
1010    /// both as exact master-clock cycle counts and as seconds.
1011    #[must_use]
1012    pub fn to_json(&self) -> String {
1013        let region = match self.region {
1014            Region::Ntsc => "NTSC",
1015            Region::Pal => "PAL",
1016            Region::Dendy => "Dendy",
1017        };
1018        let (num, den) = master_clock_hz_ratio(self.region);
1019        let mut out = String::new();
1020        // `fmt::Write` for a `String` cannot fail; the results are discarded.
1021        let _ = writeln!(out, "{{");
1022        let _ = writeln!(out, "  \"format\": \"rustynes-splits-result\",");
1023        let _ = writeln!(out, "  \"version\": 1,");
1024        let _ = writeln!(out, "  \"game\": {},", json_str(&self.def.game));
1025        let _ = writeln!(out, "  \"category\": {},", json_str(&self.def.category));
1026        let _ = writeln!(out, "  \"region\": \"{region}\",");
1027        let _ = writeln!(
1028            out,
1029            "  \"master_clock_hz\": {{\"numerator\": {num}, \"denominator\": {den}}},"
1030        );
1031        let state = match self.state {
1032            TimerState::Idle => "idle",
1033            TimerState::Running => "running",
1034            TimerState::Finished => "finished",
1035        };
1036        let _ = writeln!(out, "  \"state\": \"{state}\",");
1037        let _ = writeln!(out, "  \"start_master_clock\": {},", self.start_clock);
1038        let _ = writeln!(out, "  \"start_frame\": {},", self.start_frame);
1039        out.push_str("  \"splits\": [");
1040        let mut prev = 0u64;
1041        for (i, (t, s)) in self.splits.iter().zip(&self.def.splits).enumerate() {
1042            if i > 0 {
1043                out.push(',');
1044            }
1045            let _ = write!(
1046                out,
1047                "\n    {{\"name\": {}, \"master_clock\": {}, \"frame\": {}, \"elapsed_cycles\": {}, \"segment_cycles\": {}, \"elapsed_seconds\": {:.9}}}",
1048                json_str(&s.name),
1049                t.master_clock,
1050                t.frame,
1051                t.elapsed,
1052                t.elapsed - prev,
1053                cycles_to_seconds(t.elapsed, self.region)
1054            );
1055            prev = t.elapsed;
1056        }
1057        out.push_str(if self.splits.is_empty() {
1058            "],\n"
1059        } else {
1060            "\n  ],\n"
1061        });
1062        let total = self.elapsed();
1063        let _ = writeln!(out, "  \"elapsed_cycles\": {total},");
1064        let _ = writeln!(
1065            out,
1066            "  \"elapsed_seconds\": {:.9}",
1067            cycles_to_seconds(total, self.region)
1068        );
1069        let _ = writeln!(out, "}}");
1070        out
1071    }
1072}
1073
1074/// `s` as a JSON string literal.
1075fn json_str(s: &str) -> String {
1076    let mut out = String::with_capacity(s.len() + 2);
1077    out.push('"');
1078    for ch in s.chars() {
1079        match ch {
1080            '"' => out.push_str("\\\""),
1081            '\\' => out.push_str("\\\\"),
1082            '\n' => out.push_str("\\n"),
1083            '\r' => out.push_str("\\r"),
1084            '\t' => out.push_str("\\t"),
1085            c if (c as u32) < 0x20 => {
1086                let _ = write!(out, "\\u{:04x}", c as u32);
1087            }
1088            c => out.push(c),
1089        }
1090    }
1091    out.push('"');
1092    out
1093}
1094
1095#[cfg(test)]
1096mod tests {
1097    use super::*;
1098    use alloc::vec;
1099
1100    /// A 64 KiB flat memory for the evaluator tests (RA addresses index it
1101    /// directly).
1102    struct Mem(Vec<u8>);
1103    impl Mem {
1104        fn new() -> Self {
1105            Self(vec![0; 0x1_0000])
1106        }
1107        fn read(&self) -> impl FnMut(u32) -> u8 + '_ {
1108            |a| self.0.get(a as usize).copied().unwrap_or(0)
1109        }
1110    }
1111
1112    fn fire(t: &mut Trigger, m: &Mem) -> bool {
1113        t.evaluate(true, &mut m.read())
1114    }
1115
1116    #[test]
1117    fn sizes_and_comparisons() {
1118        let mut m = Mem::new();
1119        m.0[0x10] = 0b1010_0101;
1120        m.0[0x11] = 0x34;
1121        m.0[0x12] = 0x12;
1122        m.0[0x13] = 0x56;
1123        m.0[0x14] = 0x78;
1124        for (cond, want) in [
1125            ("0xH0010=165", true),
1126            ("0xH0010=h a5", false), // no spaces inside a constant
1127            ("0xH0010=hA5", true),
1128            ("0xM0010=1", true),
1129            ("0xN0010=0", true),
1130            ("0xO0010=1", true),
1131            ("0xT0010=1", true),
1132            ("0xS0010=0", true),
1133            ("0xL0010=5", true),
1134            ("0xU0010=10", true),
1135            ("0xK0010=4", true),
1136            ("0x0011=h1234", true),
1137            ("0x 0011=h1234", true),
1138            ("0xW0011=h561234", true),
1139            ("0xX0011=h78561234", true),
1140            ("0xI0011=h3412", true),
1141            ("0xJ0011=h341256", true),
1142            ("0xG0011=h34125678", true),
1143            ("b0xH0011=34", true),
1144            ("~0xH0010=h5a", true),
1145            ("0xH0011>0xH0012", true),
1146            ("0xH0011<=h34", true),
1147            ("0xH0011<h34", false),
1148            ("0xH0011>=h35", false),
1149            ("0xH0011!=h34", false),
1150        ] {
1151            if cond.contains("h a5") {
1152                assert!(Trigger::parse(cond).is_err(), "{cond}");
1153                continue;
1154            }
1155            let mut t = Trigger::parse(cond).unwrap_or_else(|e| panic!("{cond}: {e}"));
1156            assert_eq!(fire(&mut t, &m), want, "{cond}");
1157        }
1158    }
1159
1160    /// `S` separates groups, but `0xS` is bit 6: the tokenizer must not split
1161    /// inside a memory operand.
1162    #[test]
1163    fn groups_and_the_bit6_size() {
1164        let mut m = Mem::new();
1165        m.0[0x20] = 0x40;
1166        let mut t = Trigger::parse("0xS0020=1").unwrap();
1167        assert_eq!(t.groups.len(), 1);
1168        assert!(fire(&mut t, &m));
1169        // core AND (alt1 OR alt2)
1170        let mut t = Trigger::parse("0xS0020=1S0xH0021=1S0xH0022=1").unwrap();
1171        assert_eq!(t.groups.len(), 3);
1172        assert!(!fire(&mut t, &m), "neither alternative holds");
1173        m.0[0x22] = 1;
1174        assert!(fire(&mut t, &m));
1175        m.0[0x20] = 0;
1176        assert!(!fire(&mut t, &m), "the core group fails");
1177    }
1178
1179    #[test]
1180    fn delta_prior_and_hits() {
1181        let mut m = Mem::new();
1182        let mut edge = Trigger::parse("0xH0000=1_d0xH0000=0").unwrap();
1183        m.0[0] = 1;
1184        assert!(!fire(&mut edge, &m), "no edge on the first evaluation");
1185        m.0[0] = 0;
1186        assert!(!fire(&mut edge, &m));
1187        m.0[0] = 1;
1188        assert!(fire(&mut edge, &m), "0 -> 1 is an edge");
1189        assert!(!fire(&mut edge, &m), "held is not an edge");
1190
1191        let mut prior = Trigger::parse("p0xH0001=7").unwrap();
1192        m.0[1] = 7;
1193        fire(&mut prior, &m);
1194        m.0[1] = 9;
1195        fire(&mut prior, &m);
1196        assert!(fire(&mut prior, &m), "the value before the last change");
1197        // A discontinuity clears the history: the next evaluation has no
1198        // prior, so the current value (9) stands in, not the stale 7.
1199        prior.reset_history();
1200        assert!(!fire(&mut prior, &m), "no stale prior after a reset");
1201        let mut first = Trigger::parse("p0xH0003=0").unwrap();
1202        m.0[3] = 5;
1203        assert!(!fire(&mut first, &m), "no prior of 0 on the first frame");
1204
1205        let mut held = Trigger::parse("0xH0002=1.3.").unwrap();
1206        m.0[2] = 1;
1207        assert!(!fire(&mut held, &m));
1208        assert!(!fire(&mut held, &m));
1209        assert!(fire(&mut held, &m), "third hit");
1210        m.0[2] = 0;
1211        assert!(fire(&mut held, &m), "hits are kept once reached");
1212        held.reset_hits();
1213        assert!(!fire(&mut held, &m));
1214    }
1215
1216    #[test]
1217    fn unsupported_syntax_is_refused_not_misread() {
1218        for bad in [
1219            "",
1220            "R:0xH0000=1",
1221            "A:0xH0000=1",
1222            "0xH0000",
1223            "0xH0000=f1.5",
1224            "0xH0000=-1",
1225            "0xH0000*2=4",
1226            "0xZ0000=1",
1227            "0xH=1",
1228            "0xH0000==1",
1229            "0xH0000=1.3",
1230            "0xH0000=1|",
1231            "d5=5",
1232        ] {
1233            assert!(Trigger::parse(bad).is_err(), "{bad:?} must be refused");
1234        }
1235    }
1236
1237    #[test]
1238    fn the_flat_map_matches_the_ra_layout() {
1239        assert_eq!(ra_flat_to_cpu(0), Some(0));
1240        assert_eq!(ra_flat_to_cpu(0x07FF), Some(0x07FF));
1241        assert_eq!(ra_flat_to_cpu(0x0800), Some(0x0800));
1242        assert_eq!(ra_flat_to_cpu(0x6000), Some(0x6000));
1243        assert_eq!(ra_flat_to_cpu(0xFFFF), Some(0xFFFF));
1244        assert_eq!(ra_flat_to_cpu(0x1_0000), None);
1245    }
1246
1247    #[test]
1248    fn master_clock_rates() {
1249        // 21.477272... MHz and 26.6017125 MHz.
1250        assert!((master_clock_hz(Region::Ntsc) - 21_477_272.727_272_7).abs() < 1e-3);
1251        assert!((master_clock_hz(Region::Pal) - 26_601_712.5).abs() < 1e-6);
1252        assert_eq!(master_clock_hz(Region::Dendy), master_clock_hz(Region::Pal));
1253        // One NTSC second of CPU cycles (1,789,772.7 at divider 12).
1254        let one_second = 236_250_000 / 11;
1255        assert!((cycles_to_seconds(one_second, Region::Ntsc) - 1.0).abs() < 1e-7);
1256    }
1257
1258    const DEF: &str = "\
1259# a test definition
1260game = Test \"Game\"
1261category = Any%
1262start = 0xH0000=1_d0xH0000=0
1263split = Half way | 0xH0001=1
1264split = The end | 0xH0002=1
1265reset = 0xH0003=1
1266";
1267
1268    #[test]
1269    fn the_splits_file_parses() {
1270        let d = SplitsDefinition::parse(DEF).unwrap();
1271        assert_eq!(d.game, "Test \"Game\"");
1272        assert_eq!(d.category, "Any%");
1273        assert_eq!(d.splits.len(), 2);
1274        assert_eq!(d.splits[1].name, "The end");
1275        assert_eq!(d.start.source(), "0xH0000=1_d0xH0000=0");
1276        assert!(d.reset.is_some());
1277        for (bad, line) in [
1278            ("start = 0xH0000=1\n", 0),
1279            ("split = a | 0xH0000=1\n", 0),
1280            ("start = 0xH0000=1\nsplit = a | 0xH0000=1\nfoo = 1\n", 3),
1281            (
1282                "start = 0xH0000=1\nstart = 0xH0000=1\nsplit = a | 0xH0000=1\n",
1283                2,
1284            ),
1285            ("start = 0xH0000\nsplit = a | 0xH0000=1\n", 1),
1286            ("start = 0xH0000=1\nsplit = no-bar 0xH0000=1\n", 2),
1287            // A second `game` or `category` is refused like a second `start`
1288            // or `reset`, rather than silently replacing the first (PR #624
1289            // review, Antigravity).
1290            (
1291                "game = A\ngame = B\nstart = 0xH0000=1\nsplit = a | 0xH0000=1\n",
1292                2,
1293            ),
1294            (
1295                "category = A\nstart = 0xH0000=1\ncategory = B\nsplit = a | 0xH0000=1\n",
1296                3,
1297            ),
1298        ] {
1299            let e = SplitsDefinition::parse(bad).unwrap_err();
1300            assert_eq!(e.line, line, "{bad:?}: {e}");
1301        }
1302    }
1303
1304    /// Drive a timer through a scripted memory history: start on an edge,
1305    /// two splits, a reset, a discontinuity.
1306    #[test]
1307    fn the_timer_runs_splits_finishes_and_resets() {
1308        let def = SplitsDefinition::parse(DEF).unwrap();
1309        let mut t = SpeedrunTimer::new(def, Region::Ntsc);
1310        let mut m = Mem::new();
1311        let mut clock = 1_000u64;
1312        let mut frame = 0u64;
1313        let mut step = |t: &mut SpeedrunTimer, m: &Mem| {
1314            clock += 357_368; // one NTSC frame: 341 x 262 dots x 4
1315            frame += 1;
1316            t.observe(clock, frame, m.read())
1317        };
1318        assert_eq!(step(&mut t, &m), None);
1319        m.0[0] = 1;
1320        assert_eq!(step(&mut t, &m), Some(TimerEvent::Started));
1321        let started = t.start_clock();
1322        assert_eq!(step(&mut t, &m), None, "the start is an edge");
1323        m.0[2] = 1;
1324        assert_eq!(
1325            step(&mut t, &m),
1326            None,
1327            "split 2 is not armed before split 1"
1328        );
1329        m.0[1] = 1;
1330        assert_eq!(step(&mut t, &m), Some(TimerEvent::Split(0)));
1331        assert_eq!(t.splits()[0].elapsed, 3 * 357_368);
1332        assert_eq!(step(&mut t, &m), Some(TimerEvent::Finished));
1333        assert_eq!(t.state(), TimerState::Finished);
1334        assert_eq!(t.elapsed(), 4 * 357_368);
1335        assert_eq!(t.splits()[1].master_clock - started, 4 * 357_368);
1336        let json = t.to_json();
1337        assert!(json.contains("\"elapsed_cycles\": 1429472"), "{json}");
1338        assert!(json.contains("\"segment_cycles\": 357368"), "{json}");
1339        assert!(json.contains("\"game\": \"Test \\\"Game\\\"\""), "{json}");
1340        assert_eq!(step(&mut t, &m), None, "finished holds");
1341        assert_eq!(t.elapsed(), 4 * 357_368, "the final time does not move");
1342        m.0[3] = 1;
1343        assert_eq!(step(&mut t, &m), Some(TimerEvent::Reset));
1344        assert_eq!(t.state(), TimerState::Idle);
1345        // Restart, then go back in time.
1346        m.0[3] = 0;
1347        m.0[0] = 0;
1348        step(&mut t, &m);
1349        m.0[0] = 1;
1350        assert_eq!(step(&mut t, &m), Some(TimerEvent::Started));
1351        assert_eq!(t.observe(10, 99, m.read()), Some(TimerEvent::Discontinuity));
1352        assert_eq!(t.state(), TimerState::Idle);
1353        // And a leap forward.
1354        assert_eq!(t.observe(20, 100, m.read()), None);
1355        m.0[0] = 0;
1356        t.observe(30, 101, m.read());
1357        m.0[0] = 1;
1358        assert_eq!(t.observe(40, 102, m.read()), Some(TimerEvent::Started));
1359        assert_eq!(
1360            t.observe(40 + MAX_OBSERVATION_GAP + 1, 103, m.read()),
1361            Some(TimerEvent::Discontinuity)
1362        );
1363        // A one-frame step back (a rewind of a single frame) is a
1364        // discontinuity too, however small.
1365        let base = 40 + MAX_OBSERVATION_GAP + 1;
1366        m.0[0] = 0;
1367        t.observe(base + 357_368, 104, m.read());
1368        m.0[0] = 1;
1369        assert_eq!(
1370            t.observe(base + 2 * 357_368, 105, m.read()),
1371            Some(TimerEvent::Started)
1372        );
1373        assert_eq!(
1374            t.observe(base + 357_368, 104, m.read()),
1375            Some(TimerEvent::Discontinuity)
1376        );
1377    }
1378}