diff options
Diffstat (limited to 'common/src')
-rw-r--r-- | common/src/lib.rs | 41 | ||||
-rw-r--r-- | common/src/msg.rs | 50 |
2 files changed, 91 insertions, 0 deletions
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<String>, msg_id: usize) -> Self; + fn handle( + &mut self, + header: MessageHeader, + body: Self::Body, + writer: &mut MsgWriter<Self::Body>, + ) -> (); +} + +pub struct MsgWriter<W> { + node_id: String, + writer: W, +} + +impl<W: Write> MsgWriter<W> { + pub fn new(node_id: String, writer: W) -> Self { + Self { node_id, writer } + } + + pub fn write<T: Serialize>(&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<B> { + #[serde(flatten)] + pub header: MessageHeader, + pub body: MaelstromBodyOr<B>, +} + +#[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<B> { + 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<String>, + msg_id: usize, + }, + #[serde(rename = "init_ok")] + InitOk { msg_id: usize, in_reply_to: usize }, +} |