events: implement a first attempt at an eventing system

This commit is contained in:
Torrie Fischer
2024-12-13 00:56:50 +01:00
parent 9a749c40a1
commit d7f312ffe4
8 changed files with 236 additions and 30 deletions

163
src/events.rs Normal file
View File

@@ -0,0 +1,163 @@
use core::fmt::Debug;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputEvent {
PowerOn,
PowerOff,
NetworkActivity,
NetworkOnline,
NetworkOffline
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Variant {
Byte(u8),
UInt(u32),
Int(i32),
BigUInt(u64),
BigInt(i64),
Boolean(bool)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Event {
ReadyToRock,
Tick,
StartThing(&'static str),
StopThing(&'static str),
Input(InputEvent),
PropertyChange(&'static str, Variant)
}
pub struct SystemState {
key: &'static str,
value: Variant,
values: Vec::<Box<SystemState>>
}
impl SystemState {
pub fn new() -> Self {
SystemState {
key: "",
value: Variant::Byte(0),
values: Vec::new()
}
}
fn get_key(&self, key: &'static str) -> Option<&Self> {
if key == self.key {
Some(self)
} else {
for next in self.values.iter() {
match next.get_key(key) {
None => (),
Some(next_val) => return Some(next_val)
}
}
return None
}
}
fn get_key_mut(&mut self, key: &'static str) -> Option<&mut Self> {
if key == self.key {
Some(self)
} else {
for next in self.values.iter_mut() {
match next.get_key_mut(key) {
None => (),
Some(next_val) => return Some(next_val)
}
}
return None
}
}
pub fn get(&self, key: &'static str) -> Option<Variant> {
match self.get_key(key) {
None => None,
Some(v) => Some(v.value)
}
}
pub fn set<V>(&mut self, key: &'static str, value: V) where Variant: From<V> {
match self.get_key_mut(key) {
None => self.values.push(Box::new(SystemState {
value: value.into(),
key: key,
values: Vec::new()
})),
Some(found_key) => {
found_key.value = value.into()
}
}
}
}
impl Event {
pub fn new_tick() -> Self {
Event::Tick
}
pub fn new_property_change<T>(key: &'static str, data: T) -> Self where Variant: From<T> {
Event::PropertyChange(key, Variant::from(data))
}
pub fn new_ready_to_rock() -> Self {
Event::ReadyToRock
}
pub fn new_input_event(event: InputEvent) -> Self {
Event::Input(event)
}
}
impl Into<u8> for Variant {
fn into(self) -> u8 {
match self {
Variant::Byte(b) => b,
_ => 0
}
}
}
impl From<bool> for Variant {
fn from(value: bool) -> Self {
Variant::Boolean(value)
}
}
impl From<i64> for Variant {
fn from(value: i64) -> Self {
Variant::BigInt(value)
}
}
impl From<u8> for Variant {
fn from(value: u8) -> Self {
Variant::Byte(value)
}
}
pub struct EventBus {
pending: Vec<Event>
}
impl EventBus {
pub fn new() -> Self {
EventBus {
pending: Vec::new()
}
}
pub fn next(&mut self) -> Event {
if self.pending.len() == 0 {
Event::new_tick()
} else {
self.pending.pop().unwrap()
}
}
pub fn push(&mut self, event: Event) {
self.pending.push(event);
}
}