use specs::{System, WriteExpect};
use std::sync::mpsc::Receiver;
#[non_exhaustive]
#[derive(Debug, PartialEq)]
pub enum AppEvent {
ExitRequested,
}
pub(crate) struct AppEventReceivingSystem {
receiver: Receiver<AppEvent>,
}
impl AppEventReceivingSystem {
pub fn new(receiver: Receiver<AppEvent>) -> Self {
Self { receiver }
}
}
impl<'a> System<'a> for AppEventReceivingSystem {
type SystemData = WriteExpect<'a, Events<AppEvent>>;
fn run(&mut self, mut events: Self::SystemData) {
#[allow(clippy::single_match)] match self.receiver.try_recv() {
Ok(AppEvent::ExitRequested) => {
events.send(AppEvent::ExitRequested);
}
_ => {}
}
}
}
#[derive(Debug)]
pub struct Events<T> {
current: Vec<T>,
next: Vec<T>,
}
impl<T> Default for Events<T> {
fn default() -> Self {
Self {
current: Vec::new(),
next: Vec::new(),
}
}
}
impl<T> Events<T> {
pub fn send(&mut self, event: T) {
self.next.push(event);
}
pub fn iter(&self) -> impl Iterator<Item = &T> {
self.current.iter()
}
pub(crate) fn update(&mut self) {
self.current.clear();
std::mem::swap(&mut self.current, &mut self.next);
}
#[allow(unused)]
pub(crate) fn clear(&mut self) {
self.current.clear();
self.next.clear();
}
pub fn is_empty(&self) -> bool {
self.current.is_empty()
}
}