Various macros I made and liked to use occasionally!
Attach functionality to type variants
Basically write this:
enum Object {RedSphere, GreenCube}
match_fns!{
[Object]
shape() -> &'static str;
color(brightness:f32) -> &'static str;
[::RedSphere]
shape: "sphere";
color: if brightness > 0.5 {"bright-red"} else {"red"};
[::GreenCube]
shape: "cube";
color: "just-green";
}
Instead of:
impl Object {
pub fn shape(&self) -> &'static str {
match self {
Color::RedSphere => "sphere",
Color::GreenCube => "cube",
}
}
pub fn color(&self, brightness: f32) -> &'static str {
match self {
Color::RedSphere => {
if brightness > 0.5 {"bright-red"} else {"red"}
}
Color::GreenCube => "just-green",
}
}
}
Quick Implementations
Alternative syntax for implementing trait with ONE required method.
quimp!{StructName
fn clone(&self) -> Self {Self::new(self.0)};
fn default() -> Self {Self::new(100)};
}
Or using this:
#[imp(Struct)]: for a owned Type
#[imp(Struct|Trait)]: to impl a singe-method trait
#[imp(Struct|*)]: for a foreign Type (generates a new trait)
#[imp(Struct)]
fn function(){}
Bool Aliases
Simple macro that replaces X -> true and O -> false:
xoxo!{match [true,false,true] {
[O,O,O] => "nope",
[O,O,X] => "nope",
[X,O,X] => "YEP!",
[_,_,_] => "nope"
}}