handler macro

This commit is contained in:
Robin Appelman 2021-08-08 01:06:19 +02:00
commit e846fcceae
5 changed files with 91 additions and 56 deletions

View file

@ -4,12 +4,13 @@ use crate::module::EventHandler;
use crate::raw_event::RawEventType;
use crate::SubjectMap;
use chrono::{DateTime, FixedOffset, NaiveDateTime, TimeZone, Utc};
use serde::{Serialize, Serializer};
use std::num::ParseIntError;
use std::str::{FromStr, ParseBoolError};
use steamid_ng::SteamID;
use thiserror::Error;
#[derive(Debug)]
#[derive(Debug, Serialize)]
pub enum GameType {
Sixes,
Highlander,
@ -27,7 +28,7 @@ impl FromStr for GameType {
}
}
#[derive(Debug)]
#[derive(Debug, Serialize)]
pub enum Location {
Europe,
NorthAmerica,
@ -45,7 +46,7 @@ impl FromStr for Location {
}
}
#[derive(Debug, Default)]
#[derive(Debug, Default, Serialize)]
pub struct LobbyLeader {
name: String,
steam_id: SteamID,
@ -70,7 +71,7 @@ impl FromStr for LobbyLeader {
}
}
#[derive(Debug)]
#[derive(Debug, Serialize)]
pub struct Settings {
id: u32,
leader: LobbyLeader,
@ -127,6 +128,15 @@ pub enum LobbySettingsError {
InvalidDate(#[from] chrono::ParseError),
}
impl Serialize for LobbySettingsError {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
format!("{}", self).serialize(serializer)
}
}
pub enum LobbySettingsHandler {
NotAvailable,
Active(Settings),

View file

@ -46,3 +46,59 @@ impl<Head: EventHandler, Tail: EventHandler> EventHandler for HandlerStack<Head,
(self.head.finish(subjects), self.tail.finish(subjects))
}
}
#[macro_export]
macro_rules! handler {
($name:ident {$($child:ident: $ty:path),*}) => {
handler!($name { $($child: $ty,)* } );
};
($name:ident {$($child:ident: $ty:path,)*}) => {
paste::paste! {
#[derive(Default)]
pub struct $name {
$($child: $ty),*
}
pub struct [<$name Output>] {
$($child: <$ty as $crate::EventHandler>::Output),*
}
impl serde::Serialize for [<$name Output>] {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeStruct;
let mut state = serializer.serialize_struct(concat!("$name", "output"), 3)?;
$(state.serialize_field("$child", &self.$child)?;)*
state.end()
}
}
impl $crate::EventHandler for $name {
type Output = [<$name Output>];
fn does_handle(&self, ty: $crate::RawEventType) -> bool {
#[allow(unused_imports)]
use $crate::EventHandler;
$(self.$child.does_handle(ty))||*
}
fn handle(&mut self, time: u32, subject: $crate::SubjectId, event: &$crate::GameEvent) {
#[allow(unused_imports)]
use $crate::EventHandler;
$(self.$child.handle(time, subject, event);)*
}
fn finish(self, subjects: &$crate::SubjectMap) -> Self::Output {
#[allow(unused_imports)]
use $crate::EventHandler;
Self::Output {
$($child: self.$child.finish(subjects),)*
}
}
}
}
};
}