#![forbid(unsafe_code)]
use std::cell::RefCell;
use std::collections::VecDeque;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FeatureKey(usize);
impl FeatureKey {
pub const fn new(value: usize) -> Self {
Self(value)
}
pub const fn get(self) -> usize {
self.0
}
}
impl From<usize> for FeatureKey {
fn from(value: usize) -> Self {
Self(value)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FeatureEvent {
Activated(FeatureKey),
Deactivated(FeatureKey),
Closed(FeatureKey),
}
#[derive(Default)]
pub struct FeatureLifecycle {
pending: RefCell<VecDeque<FeatureEvent>>,
}
impl FeatureLifecycle {
pub fn new() -> Self {
Self::default()
}
pub fn post(&self, event: FeatureEvent) {
self.pending.borrow_mut().push_back(event);
}
pub fn drain(&self) -> Vec<FeatureEvent> {
self.pending.borrow_mut().drain(..).collect()
}
pub fn len(&self) -> usize {
self.pending.borrow().len()
}
pub fn is_empty(&self) -> bool {
self.pending.borrow().is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn events_are_drained_once_in_order() {
let bus = FeatureLifecycle::new();
let a = FeatureKey::new(28);
let b = FeatureKey::new(29);
assert!(bus.is_empty());
bus.post(FeatureEvent::Deactivated(a));
bus.post(FeatureEvent::Activated(b));
bus.post(FeatureEvent::Closed(a));
assert_eq!(bus.len(), 3);
assert_eq!(
bus.drain(),
vec![FeatureEvent::Deactivated(a), FeatureEvent::Activated(b), FeatureEvent::Closed(a),]
);
assert!(bus.is_empty());
assert!(bus.drain().is_empty(), "事件只能被消费一次");
}
}