From 0a0fb30472aa97ae852ad6f23b224861aa46f358 Mon Sep 17 00:00:00 2001 From: Aria Date: Sat, 2 Sep 2023 21:59:29 +0100 Subject: echo chal --- common/src/lib.rs | 41 +++++++++++++++++++++++++++++++++++++++++ common/src/msg.rs | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 common/src/lib.rs create mode 100644 common/src/msg.rs (limited to 'common/src') diff --git a/common/src/lib.rs b/common/src/lib.rs new file mode 100644 index 0000000..d0db5d1 --- /dev/null +++ b/common/src/lib.rs @@ -0,0 +1,41 @@ +use std::io::{Stdout, Write}; + +use msg::{MaelstromBodyOr, Message, MessageHeader}; +use serde::{Deserialize, Serialize}; + +pub mod msg; + +pub trait Handler { + type Body: Serialize + for<'a> Deserialize<'a>; + + fn init(node_id: String, node_ids: Vec, msg_id: usize) -> Self; + fn handle( + &mut self, + header: MessageHeader, + body: Self::Body, + writer: &mut MsgWriter, + ) -> (); +} + +pub struct MsgWriter { + node_id: String, + writer: W, +} + +impl MsgWriter { + pub fn new(node_id: String, writer: W) -> Self { + Self { node_id, writer } + } + + pub fn write(&mut self, dst: String, msg: &T) { + let msg = Message { + header: MessageHeader { + src: self.node_id.clone(), + dst, + }, + body: MaelstromBodyOr::Other { inner: msg }, + }; + serde_json::to_writer(&mut self.writer, &msg).unwrap(); + self.writer.write(&[b'\n']).unwrap(); + } +} diff --git a/common/src/msg.rs b/common/src/msg.rs new file mode 100644 index 0000000..23db171 --- /dev/null +++ b/common/src/msg.rs @@ -0,0 +1,50 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Serialize, Deserialize)] +pub struct Message { + #[serde(flatten)] + pub header: MessageHeader, + pub body: MaelstromBodyOr, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct MessageHeader { + pub src: String, + #[serde(rename = "dest")] + pub dst: String, +} + +impl MessageHeader { + pub fn flip(self) -> Self { + Self { + src: self.dst, + dst: self.src, + } + } +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(untagged)] +pub enum MaelstromBodyOr { + MaelstromBody { + #[serde(flatten)] + inner: MaelstromBody, + }, + Other { + #[serde(flatten)] + inner: B, + }, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(tag = "type")] +pub enum MaelstromBody { + #[serde(rename = "init")] + Init { + node_id: String, + node_ids: Vec, + msg_id: usize, + }, + #[serde(rename = "init_ok")] + InitOk { msg_id: usize, in_reply_to: usize }, +} -- cgit v1.2.3