timed-fsm 0.2.0

A timed finite state machine framework where timer commands are declarative transition outputs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use std::time::Duration;

/// The result of a state machine transition.
///
/// A `Response` is a **declarative description** of what should happen:
/// which actions to emit, which timers to set or kill, and whether the
/// original event was consumed.
///
/// The state machine never executes side effects directly. The runtime
/// reads the `Response` and performs the actual timer operations and
/// action execution via [`dispatch`](crate::dispatch::dispatch).
///
/// # Three-field contract
///
/// | Field | Type | Meaning |
/// |-------|------|---------|
/// | `consumed` | `bool` | `true` → caller must **not** forward the event further; `false` → caller should pass it to the next handler |
/// | `actions` | `Vec<A>` | Ordered list of output actions to execute; may be empty |
/// | `timers` | `Vec<TimerCommand<T>>` | Ordered timer instructions (set/kill); processed before `actions` by [`dispatch`](crate::dispatch::dispatch) |
///
/// Build responses with the constructor methods ([`emit_one`](Self::emit_one),
/// [`consume`](Self::consume), [`pass_through`](Self::pass_through)) and the
/// chaining methods ([`with_timer`](Self::with_timer),
/// [`with_kill_timer`](Self::with_kill_timer)).
#[derive(Debug)]
pub struct Response<A, T> {
    /// Whether the original event was consumed by the state machine.
    ///
    /// - `true`: the event was handled; the caller should **not** propagate it.
    /// - `false`: the event was not handled; the caller should propagate it
    ///   (e.g., pass through to the next hook in a chain).
    pub consumed: bool,

    /// Actions to emit, in order.
    ///
    /// May be empty if the transition only affects internal state or timers.
    pub actions: Vec<A>,

    /// Timer commands to execute, in order.
    ///
    /// The runtime must process these commands after the actions.
    /// A [`Set`](TimerCommand::Set) with an ID that already has an active
    /// timer should reset (overwrite) that timer.
    pub timers: Vec<TimerCommand<T>>,
}

/// A command to set or kill a timer.
///
/// Timer commands are part of the [`Response`] returned by state machine
/// transitions. The runtime is responsible for translating these into
/// actual platform timer operations.
///
/// # `Set` vs `Kill`
///
/// | Variant | When to use |
/// |---------|-------------|
/// | [`Set`](Self::Set) | Start a new timer **or** reset an existing one (e.g., restart the debounce window on every incoming event) |
/// | [`Kill`](Self::Kill) | Cancel a pending timer that is no longer needed (e.g., a key was released before the chord window closed) |
///
/// `Set` with an ID that already has an active timer **resets** that
/// timer — it does not create a second concurrent timer for the same ID.
/// `Kill` for an ID with no active timer is a silent no-op.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TimerCommand<T> {
    /// Start (or restart) a timer with the given ID and duration.
    ///
    /// If a timer with the same ID is already active, it is reset
    /// to the new duration. Use this to implement "restart the window
    /// on every new event" patterns such as debounce or inactivity
    /// timeouts.
    Set {
        /// Timer identifier.
        id: T,
        /// Duration after which [`TimedStateMachine::on_timeout`](crate::TimedStateMachine::on_timeout) should be called.
        duration: Duration,
    },

    /// Stop an active timer.
    ///
    /// If no timer with this ID is active, this is a no-op. Use this
    /// when a subsequent event makes the pending timeout irrelevant
    /// (e.g., the other chord key was released, so the window is moot).
    Kill {
        /// Timer identifier to stop.
        id: T,
    },
}

// ── Builder methods ──────────────────────────────────────────

impl<A, T> Response<A, T> {
    /// Create a response that consumes the event and emits multiple actions.
    ///
    /// Use this when a single transition produces two or more output actions
    /// that need to be dispatched together (e.g., a chord that generates a
    /// modifier keydown followed by a character keydown).
    #[must_use]
    pub const fn emit(actions: Vec<A>) -> Self {
        Self {
            consumed: true,
            actions,
            timers: Vec::new(),
        }
    }

    /// Create a response that consumes the event and emits a single action.
    ///
    /// Use this for the common case where exactly one output action is
    /// produced (e.g., a confirmed debounce level, a recognized key stroke).
    #[must_use]
    pub fn emit_one(action: A) -> Self {
        Self {
            consumed: true,
            actions: vec![action],
            timers: Vec::new(),
        }
    }

    /// Create a response that consumes the event but emits no actions yet.
    ///
    /// Use this when the state machine enters a pending (buffering) state
    /// and will emit actions only on a later event or timeout — the
    /// **timer-pending pattern**. Typically followed by
    /// [`.with_timer(…)`](Self::with_timer) to start the decision window.
    ///
    /// ```
    /// # use std::time::Duration;
    /// # use timed_fsm::Response;
    /// // Absorb the event and start a 50 ms window.
    /// let r: Response<u8, ()> = Response::consume()
    ///     .with_timer((), Duration::from_millis(50));
    /// r.assert_consumed();
    /// r.assert_timer_set(());
    /// ```
    #[must_use]
    pub const fn consume() -> Self {
        Self {
            consumed: true,
            actions: Vec::new(),
            timers: Vec::new(),
        }
    }

    /// Create a response that does **not** consume the event.
    ///
    /// Use this when this state machine does not handle the current event
    /// and the caller should pass it to the next handler in the chain
    /// (e.g., a key combination that is not part of this machine's grammar).
    #[must_use]
    pub const fn pass_through() -> Self {
        Self {
            consumed: false,
            actions: Vec::new(),
            timers: Vec::new(),
        }
    }

    /// Add a timer set command to this response.
    ///
    /// This is a chainable builder method. It appends a
    /// [`TimerCommand::Set`] with the given `id` and `duration`.
    /// If a timer with the same ID is already running, the runtime
    /// must reset it to the new duration.
    #[must_use]
    pub fn with_timer(mut self, id: T, duration: Duration) -> Self {
        self.timers.push(TimerCommand::Set { id, duration });
        self
    }

    /// Add a timer kill command to this response.
    ///
    /// This is a chainable builder method. It appends a
    /// [`TimerCommand::Kill`] for the given `id`. If no timer with
    /// that ID is active, the runtime treats this as a no-op.
    #[must_use]
    pub fn with_kill_timer(mut self, id: T) -> Self {
        self.timers.push(TimerCommand::Kill { id });
        self
    }
}

// ── Trait implementations ────────────────────────────────────

impl<A, T> Default for Response<A, T> {
    fn default() -> Self {
        Self::pass_through()
    }
}

impl<A: Clone, T: Clone> Clone for Response<A, T> {
    fn clone(&self) -> Self {
        Self {
            consumed: self.consumed,
            actions: self.actions.clone(),
            timers: self.timers.clone(),
        }
    }
}

impl<A: PartialEq, T: PartialEq> PartialEq for Response<A, T> {
    fn eq(&self, other: &Self) -> bool {
        self.consumed == other.consumed
            && self.actions == other.actions
            && self.timers == other.timers
    }
}

impl<A: Eq, T: Eq> Eq for Response<A, T> {}

// ── Assertion helpers ────────────────────────────────────────

impl<A: core::fmt::Debug, T: Copy + Eq + core::fmt::Debug> Response<A, T> {
    /// Assert that the event was consumed.
    ///
    /// # Panics
    ///
    /// Panics if `consumed` is `false`.
    #[track_caller]
    pub fn assert_consumed(&self) {
        assert!(self.consumed, "expected consumed, got pass-through");
    }

    /// Assert that the event was not consumed (pass-through).
    ///
    /// # Panics
    ///
    /// Panics if `consumed` is `true`.
    #[track_caller]
    pub fn assert_pass_through(&self) {
        assert!(!self.consumed, "expected pass-through, got consumed");
    }

    /// Assert that a timer set command exists for the given ID.
    ///
    /// # Panics
    ///
    /// Panics if no `Set` command with the given ID is found.
    #[track_caller]
    pub fn assert_timer_set(&self, id: T) {
        assert!(
            self.timers
                .iter()
                .any(|t| matches!(t, TimerCommand::Set { id: i, .. } if *i == id)),
            "expected TimerCommand::Set with id {id:?}, found {:?}",
            self.timers
        );
    }

    /// Assert that a timer kill command exists for the given ID.
    ///
    /// # Panics
    ///
    /// Panics if no `Kill` command with the given ID is found.
    #[track_caller]
    pub fn assert_timer_kill(&self, id: T) {
        assert!(
            self.timers
                .iter()
                .any(|t| matches!(t, TimerCommand::Kill { id: i } if *i == id)),
            "expected TimerCommand::Kill with id {id:?}, found {:?}",
            self.timers
        );
    }

    /// Assert the number of actions in the response.
    ///
    /// # Panics
    ///
    /// Panics if the action count does not match.
    #[track_caller]
    pub fn assert_action_count(&self, expected: usize) {
        assert_eq!(
            self.actions.len(),
            expected,
            "expected {expected} actions, got {}: {:?}",
            self.actions.len(),
            self.actions
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn emit_one_is_consumed_with_one_action() {
        let r: Response<&str, ()> = Response::emit_one("hello");
        assert!(r.consumed);
        assert_eq!(r.actions, vec!["hello"]);
        assert!(r.timers.is_empty());
    }

    #[test]
    fn pass_through_is_not_consumed() {
        let r: Response<&str, ()> = Response::pass_through();
        assert!(!r.consumed);
        assert!(r.actions.is_empty());
        assert!(r.timers.is_empty());
    }

    #[test]
    fn consume_is_consumed_with_no_actions() {
        let r: Response<&str, ()> = Response::consume();
        assert!(r.consumed);
        assert!(r.actions.is_empty());
    }

    #[test]
    fn builder_chain() {
        let r: Response<i32, u8> = Response::emit_one(42)
            .with_timer(1, Duration::from_millis(100))
            .with_kill_timer(2);

        assert!(r.consumed);
        assert_eq!(r.actions, vec![42]);
        assert_eq!(r.timers.len(), 2);
        assert_eq!(
            r.timers[0],
            TimerCommand::Set {
                id: 1,
                duration: Duration::from_millis(100)
            }
        );
        assert_eq!(r.timers[1], TimerCommand::Kill { id: 2 });
    }

    #[test]
    fn default_is_pass_through() {
        let r: Response<(), ()> = Response::default();
        assert!(!r.consumed);
    }

    #[test]
    fn assert_helpers_pass() {
        let r: Response<i32, u8> = Response::emit_one(1)
            .with_timer(0, Duration::from_millis(50))
            .with_kill_timer(1);

        r.assert_consumed();
        r.assert_action_count(1);
        r.assert_timer_set(0);
        r.assert_timer_kill(1);
    }

    #[test]
    #[should_panic(expected = "expected consumed")]
    fn assert_consumed_panics_on_pass_through() {
        Response::<(), ()>::pass_through().assert_consumed();
    }

    #[test]
    #[should_panic(expected = "expected pass-through")]
    fn assert_pass_through_panics_on_consumed() {
        Response::<(), ()>::consume().assert_pass_through();
    }

    #[test]
    fn clone_preserves_all_fields() {
        let r = Response::emit(vec![1, 2])
            .with_timer(0u8, Duration::from_millis(50))
            .with_kill_timer(1);
        let c = r.clone();
        assert_eq!(r, c);
    }

    #[test]
    fn partial_eq_detects_differences() {
        let a: Response<i32, u8> = Response::emit_one(1);
        let b: Response<i32, u8> = Response::emit_one(2);
        assert_ne!(a, b);

        let c: Response<i32, u8> = Response::consume();
        let d: Response<i32, u8> = Response::pass_through();
        assert_ne!(c, d);
    }

    #[test]
    #[should_panic(expected = "expected TimerCommand::Set")]
    fn assert_timer_set_panics_when_missing() {
        Response::<(), u8>::consume().assert_timer_set(0);
    }

    #[test]
    #[should_panic(expected = "expected TimerCommand::Kill")]
    fn assert_timer_kill_panics_when_missing() {
        Response::<(), u8>::consume().assert_timer_kill(0);
    }

    #[test]
    #[should_panic(expected = "expected 3 actions")]
    fn assert_action_count_panics_on_mismatch() {
        Response::<i32, u8>::emit_one(1).assert_action_count(3);
    }

    #[test]
    fn emit_with_multiple_actions() {
        let r: Response<&str, ()> = Response::emit(vec!["a", "b", "c"]);
        assert!(r.consumed);
        assert_eq!(r.actions.len(), 3);
        r.assert_action_count(3);
    }
}