diff options
author | Aria <me@aria.rip> | 2023-09-02 21:59:29 +0100 |
---|---|---|
committer | Aria <me@aria.rip> | 2023-09-02 21:59:29 +0100 |
commit | 0a0fb30472aa97ae852ad6f23b224861aa46f358 (patch) | |
tree | ce401563cbc552c3a33d36afbd39934c35d08f2b /common/src/lib.rs |
echo chal
Diffstat (limited to 'common/src/lib.rs')
-rw-r--r-- | common/src/lib.rs | 41 |
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(); + } +} |