Created
February 12, 2019 21:27
-
-
Save msmorgan/58c069b5ecd33ed822b68ac182695575 to your computer and use it in GitHub Desktop.
using typetag to do fancy stuff
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::collections::HashSet; | |
use serde::{Deserialize, Serialize}; | |
struct Context { | |
applications: HashSet<String>, | |
} | |
impl Context { | |
pub fn new() -> Self { | |
Context { | |
applications: HashSet::new(), | |
} | |
} | |
pub fn register_application(&mut self, app_name: &str) { | |
self.applications.insert(app_name.to_string()); | |
} | |
pub fn unregister_application(&mut self, app_name: &str) { | |
self.applications.remove(&app_name.to_string()); | |
} | |
pub fn application_count(&self) -> usize { | |
self.applications.len() | |
} | |
} | |
#[typetag::serde(tag = "type", content = "data")] | |
trait Message { | |
fn handle(&self, ctx: &mut Context); | |
} | |
#[derive(Debug, Deserialize, Serialize)] | |
struct RegisterApplication { | |
app_name: String, | |
} | |
#[typetag::serde] | |
impl Message for RegisterApplication { | |
fn handle(&self, ctx: &mut Context) { | |
println!("Registering application: {}", &self.app_name); | |
ctx.register_application(&self.app_name); | |
} | |
} | |
#[derive(Debug, Deserialize, Serialize)] | |
struct UnregisterApplication { | |
app_name: String, | |
} | |
#[typetag::serde] | |
impl Message for UnregisterApplication { | |
fn handle(&self, ctx: &mut Context) { | |
println!("Unregistering application: {}", &self.app_name); | |
ctx.unregister_application(&self.app_name); | |
} | |
} | |
fn main() { | |
const REGISTER: &str = r#"{ "type": "RegisterApplication", "data": { "app_name": "MyApp" } }"#; | |
const UNREGISTER: &str = r#"{ "type": "UnregisterApplication", "data": { "app_name": "MyApp" } }"#; | |
let mut ctx = Context::new(); | |
let register_message: Box<dyn Message> = serde_json::from_str(REGISTER).unwrap(); | |
register_message.handle(&mut ctx); | |
assert_eq!(ctx.application_count(), 1); | |
let unregister_message: Box<dyn Message> = serde_json::from_str(UNREGISTER).unwrap(); | |
unregister_message.handle(&mut ctx); | |
assert_eq!(ctx.application_count(), 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment