summaryrefslogtreecommitdiff
path: root/common/src/lib.rs
diff options
context:
space:
mode:
Diffstat (limited to 'common/src/lib.rs')
-rw-r--r--common/src/lib.rs41
1 files changed, 41 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();
+ }
+}