Added macro to generate cast traits and impls automatically

This commit is contained in:
Dreaded_X 2022-12-14 05:49:51 +01:00
parent fd1540b63d
commit 4de0b31ec8
Signed by: Dreaded_X
GPG Key ID: 76BDEC4E165D8AD9
3 changed files with 34 additions and 31 deletions

7
Cargo.lock generated
View File

@ -29,6 +29,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"dotenv", "dotenv",
"google-home", "google-home",
"paste",
"rumqttc", "rumqttc",
"serde", "serde",
"serde_json", "serde_json",
@ -492,6 +493,12 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"
[[package]]
name = "paste"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf1c2c742266c2f1041c914ba65355a83ae8747b05f208319784083583494b4b"
[[package]] [[package]]
name = "pin-project" name = "pin-project"
version = "1.0.12" version = "1.0.12"

View File

@ -11,3 +11,7 @@ serde = { version ="1.0.149", features = ["derive"] }
serde_json = "1.0.89" serde_json = "1.0.89"
dotenv = "0.15.0" dotenv = "0.15.0"
google-home = {path = "./google-home"} google-home = {path = "./google-home"}
paste = "1.0.10"
[profile.release]
lto=true

View File

@ -6,39 +6,31 @@ use crate::{mqtt::Listener, state::StateOnOff};
pub use self::ikea_outlet::IkeaOutlet; pub use self::ikea_outlet::IkeaOutlet;
pub trait AsListener { macro_rules! add_cast_for {
fn cast(&self) -> Option<&dyn Listener> { ($i:ident) => {
None paste::paste! {
} pub trait [< As $i>] {
fn cast_mut(&mut self) -> Option<&mut dyn Listener> { fn cast(&self) -> Option<&dyn $i> {
None None
} }
} fn cast_mut(&mut self) -> Option<&mut dyn $i> {
impl<T: Device + Listener> AsListener for T { None
fn cast(&self) -> Option<&dyn Listener> { }
Some(self) }
} impl<T: $i> [< As $i>] for T {
fn cast_mut(&mut self) -> Option<&mut dyn Listener> { fn cast(&self) -> Option<&dyn $i> {
Some(self) Some(self)
} }
fn cast_mut(&mut self) -> Option<&mut dyn $i> {
Some(self)
}
}
}
};
} }
pub trait AsStateOnOff { add_cast_for!(Listener);
fn cast(&self) -> Option<&dyn StateOnOff> { add_cast_for!(StateOnOff);
None
}
fn cast_mut(&mut self) -> Option<&mut dyn StateOnOff> {
None
}
}
impl<T: Device + StateOnOff> AsStateOnOff for T {
fn cast(&self) -> Option<&dyn StateOnOff> {
Some(self)
}
fn cast_mut(&mut self) -> Option<&mut dyn StateOnOff> {
Some(self)
}
}
pub trait Device: AsListener + AsStateOnOff { pub trait Device: AsListener + AsStateOnOff {
fn get_identifier(&self) -> &str; fn get_identifier(&self) -> &str;