nebkor-maelstrom/examples/broadcast.rs

57 lines
1.8 KiB
Rust
Raw Normal View History

use nebkor_maelstrom::{mk_payload, Body, Message, Node, Runner};
use std::{collections::HashSet, thread, time::Duration};
fn main() {
let node = SingleNodeBroadcast::default();
let on_init = |runner: &Runner| {
let backdoor = runner.get_backdoor();
let msg = Message::from_body(Body::from_type("tony_danza"));
thread::spawn(move || {
// send a `tony_danza` message to the broadcast node every 100ms
thread::sleep(Duration::from_millis(100));
backdoor.send(msg.clone()).unwrap();
});
};
let on_init = Box::new(on_init);
let runner = Runner::new(node);
runner.run(Some(on_init));
}
#[derive(Clone, Default)]
struct SingleNodeBroadcast {
pub store: HashSet<i64>,
}
impl Node for SingleNodeBroadcast {
fn handle(&mut self, runner: &Runner, req: Message) {
let typ = req.typ();
match typ {
"broadcast" => {
let val = req.body.payload.get("message").unwrap().as_i64().unwrap();
self.store.insert(val);
// maybe before replying with "broadcast_ok" maybe consider telling your neighbors
// about what you heard? maybe?
runner.reply(&req, Body::from_type("broadcast_ok"));
}
"read" => {
let vals = self.store.iter().cloned().collect::<Vec<_>>();
let payload = mk_payload(&[("messages", vals.into())]);
let body = Body::from_type("read_ok").with_payload(payload);
runner.reply(&req, body);
}
"topology" => {
let body = Body::from_type("topology_ok");
runner.reply(&req, body);
}
"tony_danza" => {
eprintln!("Eh, oh, oh, eh!");
}
_ => {}
}
}
}