summaryrefslogtreecommitdiff
path: root/common
diff options
context:
space:
mode:
Diffstat (limited to 'common')
-rw-r--r--common/Cargo.toml10
-rw-r--r--common/src/lib.rs41
-rw-r--r--common/src/msg.rs50
3 files changed, 101 insertions, 0 deletions
diff --git a/common/Cargo.toml b/common/Cargo.toml
new file mode 100644
index 0000000..3abc652
--- /dev/null
+++ b/common/Cargo.toml
@@ -0,0 +1,10 @@
+[package]
+name = "common"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+serde = { version = "1.0.185", features = ["derive"] }
+serde_json = "1.0.105" \ No newline at end of file
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 },
+}