btn-recognizer 0.2.2

Timestamp-driven button debouncing with multi-tap, hold, repeat, and multi-key chord gesture recognition
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//! 哈希表驱动的有限状态机引擎
//!
//! 核心数据结构: `HashMap<(CS, EVT), (NS, MOTION)>`
//!
//! - **CS** (Current State): 当前状态
//! - **EVT** (Event): 触发事件
//! - **NS** (Next State): 迁移后的目标状态
//! - **MOTION** (Motion): 迁移时执行的副作用/动作
//!
//! 这是 Mealy 机模型 —— 输出(motion)绑定在转移弧上,而非状态节点上。

use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::error::Error;
use std::fmt::{self, Debug};
use std::hash::Hash;

// ── Error ──────────────────────────────────────────────────────────

/// FSM 运行时错误
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FsmError<S, E>
where
    S: Debug + Clone,
    E: Debug + Clone,
{
    /// 在当前状态下收到未注册的事件 —— 状态机存在"空洞"
    NoTransition { state: S, event: E },
}

impl<S, E> fmt::Display for FsmError<S, E>
where
    S: Debug + Clone,
    E: Debug + Clone,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NoTransition { state, event } => {
                write!(f, "FSM NoTransition: state={state:?} event={event:?}")
            }
        }
    }
}

impl<S, E> Error for FsmError<S, E>
where
    S: Debug + Clone,
    E: Debug + Clone,
{
}

/// FSM 构建错误。
///
/// 构建器会延迟报告注册阶段发现的错误,从而保留
/// `Fsm::builder().on(...).build()` 的链式调用风格。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BuildError<S, E>
where
    S: Debug + Clone,
    E: Debug + Clone,
{
    /// 构建器没有设置初始状态。
    MissingInitialState,
    /// 同一个 `(state, event)` 被注册了多次。
    DuplicateTransition { state: S, event: E },
}

impl<S, E> fmt::Display for BuildError<S, E>
where
    S: Debug + Clone,
    E: Debug + Clone,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingInitialState => write!(f, "FSM initial state is required"),
            Self::DuplicateTransition { state, event } => {
                write!(
                    f,
                    "FSM duplicate transition: state={state:?} event={event:?}"
                )
            }
        }
    }
}

impl<S, E> Error for BuildError<S, E>
where
    S: Debug + Clone,
    E: Debug + Clone,
{
}

// ── Transition & TransitionKey ─────────────────────────────────────

/// 转移弧:目标状态 + 副作用动作
#[derive(Debug, Clone, PartialEq, Eq)]
struct Transition<S, M> {
    next_state: S,
    motion: M,
}

/// HashMap key: `(current_state, event)`
type TransitionKey<S, E> = (S, E);

// ── Fsm ────────────────────────────────────────────────────────────

/// 哈希表驱动的有限状态机
///
/// # 类型参数
/// - `S`: 状态类型,需实现 `Hash + Eq + Clone + Debug`
/// - `E`: 事件类型,需实现 `Hash + Eq + Clone + Debug`
/// - `M`: 动作类型,需实现 `Clone + Debug`
///
/// # 示例
/// ```
/// use fsm_engine::Fsm;
///
/// #[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// enum State { A, B }
///
/// #[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// enum Event { Go }
///
/// #[derive(Debug, Clone)]
/// enum Motion { Print }
///
/// let fsm = Fsm::builder()
///     .initial_state(State::A)
///     .on(State::A, Event::Go, State::B, Motion::Print)
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct Fsm<S, E, M>
where
    S: Hash + Eq + Clone + Debug,
    E: Hash + Eq + Clone + Debug,
    M: Clone + Debug,
{
    /// 转移表:`HashMap<(cs, evt), (ns, motion)>`
    transitions: HashMap<TransitionKey<S, E>, Transition<S, M>>,
    /// 当前状态
    state: S,
    /// 初始状态(用于 reset)
    initial_state: S,
}

impl<S, E, M> Fsm<S, E, M>
where
    S: Hash + Eq + Clone + Debug,
    E: Hash + Eq + Clone + Debug,
    M: Clone + Debug,
{
    // ── 构造器入口 ────────────────────────────────────────────────

    /// 获取 Builder,用于声明式地构建转移表
    pub fn builder() -> FsmBuilder<S, E, M> {
        FsmBuilder::new()
    }

    // ── 运行时 API ────────────────────────────────────────────────

    /// 摄入一个事件,触发状态迁移并返回 `(下一状态, 动作)`
    ///
    /// # Errors
    /// 若当前状态下没有为该事件注册的转移,返回 `FsmError::NoTransition`
    pub fn step(&mut self, event: &E) -> Result<(&S, &M), FsmError<S, E>> {
        let key = (self.state.clone(), event.clone());
        let transition = self
            .transitions
            .get(&key)
            .ok_or_else(|| FsmError::NoTransition {
                state: self.state.clone(),
                event: event.clone(),
            })?;

        self.state = transition.next_state.clone();
        Ok((&self.state, &transition.motion))
    }

    /// 只做状态迁移,忽略 motion(语法糖)
    pub fn step_state(&mut self, event: &E) -> Result<&S, FsmError<S, E>> {
        self.step(event).map(|(s, _)| s)
    }

    /// 查询当前状态
    pub fn current_state(&self) -> &S {
        &self.state
    }

    /// 查询初始状态
    pub fn initial_state(&self) -> &S {
        &self.initial_state
    }

    /// 重置到初始状态
    pub fn reset(&mut self) {
        self.state = self.initial_state.clone();
    }

    /// 转移表的大小(注册的转移弧数量)
    pub fn transition_count(&self) -> usize {
        self.transitions.len()
    }

    /// 检查某个转移是否存在
    pub fn has_transition(&self, state: &S, event: &E) -> bool {
        self.transitions
            .contains_key(&(state.clone(), event.clone()))
    }

    /// 遍历所有已注册的转移弧,返回 `Vec<(cs, evt, ns, motion)>`
    pub fn transitions(&self) -> Vec<(&S, &E, &S, &M)> {
        self.transitions
            .iter()
            .map(|((cs, evt), t)| (cs, evt, &t.next_state, &t.motion))
            .collect()
    }
}

// ── Builder ────────────────────────────────────────────────────────

/// FSM 构建器 —— 声明式地构造转移表
///
/// # 示例
/// ```
/// # use fsm_engine::{Fsm, FsmBuilder};
/// let fsm = Fsm::<i32, &str, ()>::builder()
///     .initial_state(0)
///     .on(0, "inc", 1, ())
///     .on(1, "inc", 2, ())
///     .on(1, "dec", 0, ())
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct FsmBuilder<S, E, M>
where
    S: Hash + Eq + Clone + Debug,
    E: Hash + Eq + Clone + Debug,
    M: Clone + Debug,
{
    transitions: HashMap<TransitionKey<S, E>, Transition<S, M>>,
    initial_state: Option<S>,
    error: Option<BuildError<S, E>>,
}

impl<S, E, M> FsmBuilder<S, E, M>
where
    S: Hash + Eq + Clone + Debug,
    E: Hash + Eq + Clone + Debug,
    M: Clone + Debug,
{
    pub fn new() -> Self {
        Self {
            transitions: HashMap::new(),
            initial_state: None,
            error: None,
        }
    }

    /// 设置初始状态
    pub fn initial_state(mut self, state: S) -> Self {
        self.initial_state = Some(state);
        self
    }

    /// 注册一条转移弧: `(cs, evt) → (ns, motion)`
    ///
    /// 重复注册同一个 `(cs, evt)` 时保留第一条转移,并由 [`Self::build`]
    /// 返回 [`BuildError::DuplicateTransition`]。若存在多个重复定义,报告
    /// 第一个被检测到的重复键。
    pub fn on(mut self, cs: S, evt: E, ns: S, motion: M) -> Self {
        match self.transitions.entry((cs, evt)) {
            Entry::Vacant(entry) => {
                entry.insert(Transition {
                    next_state: ns,
                    motion,
                });
            }
            Entry::Occupied(entry) => {
                if self.error.is_none() {
                    let (state, event) = entry.key();
                    self.error = Some(BuildError::DuplicateTransition {
                        state: state.clone(),
                        event: event.clone(),
                    });
                }
            }
        }
        self
    }

    /// 从任意迭代器批量注册转移弧。
    ///
    /// 重复键的处理与 [`Self::on`] 一致,在 [`Self::build`] 时报告错误。
    pub fn on_many<I>(mut self, transitions: I) -> Self
    where
        I: IntoIterator<Item = (S, E, S, M)>,
    {
        for (cs, evt, ns, motion) in transitions {
            self = self.on(cs, evt, ns, motion);
        }
        self
    }

    /// 消费 builder,产出 Fsm 实例
    ///
    /// # Errors
    ///
    /// - 未设置初始状态时返回 [`BuildError::MissingInitialState`]。
    /// - 注册了重复转移时返回 [`BuildError::DuplicateTransition`]。
    ///
    /// 若两类错误同时存在,优先报告缺少初始状态。
    pub fn build(self) -> Result<Fsm<S, E, M>, BuildError<S, E>> {
        let initial_state = self.initial_state.ok_or(BuildError::MissingInitialState)?;

        if let Some(error) = self.error {
            return Err(error);
        }

        Ok(Fsm {
            transitions: self.transitions,
            state: initial_state.clone(),
            initial_state,
        })
    }
}

// ── 默认实现 ───────────────────────────────────────────────────────

impl<S, E, M> Default for FsmBuilder<S, E, M>
where
    S: Hash + Eq + Clone + Debug,
    E: Hash + Eq + Clone + Debug,
    M: Clone + Debug,
{
    fn default() -> Self {
        Self::new()
    }
}

// ── 测试 ───────────────────────────────────────────────────────────

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

    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
    enum State {
        Idle,
        Running,
        Stopped,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
    enum Event {
        Start,
        Stop,
        Reset,
    }

    #[derive(Debug, Clone, PartialEq)]
    enum Motion {
        Log(String),
        Alert,
        None,
    }

    fn build_test_fsm() -> Fsm<State, Event, Motion> {
        Fsm::builder()
            .initial_state(State::Idle)
            .on(
                State::Idle,
                Event::Start,
                State::Running,
                Motion::Log("started".into()),
            )
            .on(State::Running, Event::Stop, State::Stopped, Motion::Alert)
            .on(State::Stopped, Event::Reset, State::Idle, Motion::None)
            .build()
            .unwrap()
    }

    #[test]
    fn test_basic_transition() {
        let mut fsm = build_test_fsm();
        assert_eq!(*fsm.current_state(), State::Idle);

        let (ns, motion) = fsm.step(&Event::Start).unwrap();
        assert_eq!(*ns, State::Running);
        assert_eq!(*motion, Motion::Log("started".into()));
    }

    #[test]
    fn test_no_transition_error() {
        let mut fsm = build_test_fsm();
        let error = fsm.step(&Event::Stop).unwrap_err();
        assert_eq!(
            error,
            FsmError::NoTransition {
                state: State::Idle,
                event: Event::Stop,
            }
        );
        assert_eq!(*fsm.current_state(), State::Idle);
    }

    #[test]
    fn test_reset() {
        let mut fsm = build_test_fsm();
        fsm.step(&Event::Start).unwrap();
        fsm.step(&Event::Stop).unwrap();
        assert_eq!(*fsm.current_state(), State::Stopped);

        fsm.reset();
        assert_eq!(*fsm.current_state(), State::Idle);
    }

    #[test]
    fn test_full_cycle() {
        let mut fsm = build_test_fsm();
        fsm.step(&Event::Start).unwrap();
        fsm.step(&Event::Stop).unwrap();
        fsm.step(&Event::Reset).unwrap();
        assert_eq!(*fsm.current_state(), State::Idle);
    }

    #[test]
    fn test_builder_requires_initial_state() {
        let error = Fsm::<State, Event, Motion>::builder().build().unwrap_err();
        assert_eq!(error, BuildError::MissingInitialState);
    }

    #[test]
    fn test_duplicate_transition_is_a_build_error() {
        let error = Fsm::builder()
            .initial_state(State::Idle)
            .on(State::Idle, Event::Start, State::Running, Motion::Alert)
            .on(State::Idle, Event::Start, State::Stopped, Motion::None)
            .build()
            .unwrap_err();

        assert_eq!(
            error,
            BuildError::DuplicateTransition {
                state: State::Idle,
                event: Event::Start,
            }
        );
    }

    #[test]
    fn test_first_duplicate_transition_is_reported() {
        let error = Fsm::builder()
            .initial_state(State::Idle)
            .on(State::Idle, Event::Start, State::Running, Motion::Alert)
            .on(State::Idle, Event::Start, State::Stopped, Motion::None)
            .on(State::Running, Event::Stop, State::Idle, Motion::Alert)
            .on(State::Running, Event::Stop, State::Stopped, Motion::None)
            .build()
            .unwrap_err();

        assert_eq!(
            error,
            BuildError::DuplicateTransition {
                state: State::Idle,
                event: Event::Start,
            }
        );
    }

    #[test]
    fn test_missing_initial_state_takes_precedence() {
        let error = Fsm::builder()
            .on(State::Idle, Event::Start, State::Running, Motion::Alert)
            .on(State::Idle, Event::Start, State::Stopped, Motion::None)
            .build()
            .unwrap_err();

        assert_eq!(error, BuildError::MissingInitialState);
    }

    #[test]
    fn test_on_many_accepts_into_iterator() {
        let transitions = [
            (State::Idle, Event::Start, State::Running, Motion::Alert),
            (State::Running, Event::Stop, State::Stopped, Motion::None),
        ];

        let fsm = Fsm::builder()
            .initial_state(State::Idle)
            .on_many(transitions)
            .on_many(std::iter::once((
                State::Stopped,
                Event::Reset,
                State::Idle,
                Motion::Alert,
            )))
            .build()
            .unwrap();

        assert_eq!(fsm.transition_count(), 3);
    }

    #[test]
    fn test_error_types_implement_std_error() {
        fn assert_error<T: std::error::Error>() {}

        assert_error::<FsmError<State, Event>>();
        assert_error::<BuildError<State, Event>>();
    }

    #[test]
    fn test_transition_count() {
        let fsm = build_test_fsm();
        assert_eq!(fsm.transition_count(), 3);
    }
}