mgui_app_lifecycle/
lib.rs1#![forbid(unsafe_code)]
12
13use std::cell::RefCell;
14use std::collections::VecDeque;
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
18pub struct FeatureKey(usize);
19
20impl FeatureKey {
21 pub const fn new(value: usize) -> Self {
22 Self(value)
23 }
24
25 pub const fn get(self) -> usize {
26 self.0
27 }
28}
29
30impl From<usize> for FeatureKey {
31 fn from(value: usize) -> Self {
32 Self(value)
33 }
34}
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
38pub enum FeatureEvent {
39 Activated(FeatureKey),
41 Deactivated(FeatureKey),
43 Closed(FeatureKey),
45}
46
47#[derive(Default)]
52pub struct FeatureLifecycle {
53 pending: RefCell<VecDeque<FeatureEvent>>,
54}
55
56impl FeatureLifecycle {
57 pub fn new() -> Self {
58 Self::default()
59 }
60
61 pub fn post(&self, event: FeatureEvent) {
62 self.pending.borrow_mut().push_back(event);
63 }
64
65 pub fn drain(&self) -> Vec<FeatureEvent> {
66 self.pending.borrow_mut().drain(..).collect()
67 }
68
69 pub fn len(&self) -> usize {
70 self.pending.borrow().len()
71 }
72
73 pub fn is_empty(&self) -> bool {
74 self.pending.borrow().is_empty()
75 }
76}
77
78#[cfg(test)]
79mod tests {
80 use super::*;
81
82 #[test]
83 fn events_are_drained_once_in_order() {
84 let bus = FeatureLifecycle::new();
85 let a = FeatureKey::new(28);
86 let b = FeatureKey::new(29);
87 assert!(bus.is_empty());
88
89 bus.post(FeatureEvent::Deactivated(a));
90 bus.post(FeatureEvent::Activated(b));
91 bus.post(FeatureEvent::Closed(a));
92 assert_eq!(bus.len(), 3);
93
94 assert_eq!(
95 bus.drain(),
96 vec![FeatureEvent::Deactivated(a), FeatureEvent::Activated(b), FeatureEvent::Closed(a),]
97 );
98 assert!(bus.is_empty());
99 assert!(bus.drain().is_empty(), "事件只能被消费一次");
100 }
101}