From b7728d43c5acb91fa5df92dfd7b7b2b428ffa4d1 Mon Sep 17 00:00:00 2001 From: Ishan Jain Date: Thu, 4 Jan 2024 00:44:15 +0530 Subject: [PATCH] fixed bugs in parsing inputs and responding to them --- src/lib.rs | 69 +++++++++++++++++++++++++++++------------------------- 1 file changed, 37 insertions(+), 32 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index de5c1ef..4dbd814 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -43,6 +43,7 @@ impl MalestormIo { fn write(&self, buf: &[u8]) -> Result<(), IoError> { let mut writer = self.stdout.lock(); writer.write_all(buf)?; + writer.write_all(&[b'\n'])?; writer.flush() } @@ -59,40 +60,44 @@ impl<'a> Malestorm<'a> { let mut buf = Vec::new(); - let read = match program.io.read_line(&mut buf) { - Ok(v) => v, - Err(e) => panic!("{:?}", e), - }; + loop { + let read = match program.io.read_line(&mut buf) { + Ok(v) => v, + Err(e) => panic!("{:?}", e), + }; - if read == 0 { - return; + if read == 0 { + continue; + } + + let message: Message = match serde_json::from_slice(&buf) { + Ok(v) => v, + Err(e) => { + eprintln!( + "error in parsing input: {:?} msg = {:?}", + e, + String::from_utf8_lossy(&buf) + ); + continue; + } + }; + + buf.clear(); + + let mtype = message.body.message_type.clone(); + + let pc = program.clone(); + + let handler = match program.handlers.get(&mtype.as_str()) { + Some(v) => v, + None => { + eprintln!("no handler found for {}", message.body.message_type); + continue; + } + }; + + handler(message, pc); } - - let message: Message = match serde_json::from_slice(&buf) { - Ok(v) => v, - Err(e) => { - eprintln!( - "error in parsing input: {:?} msg = {}", - e, - String::from_utf8_lossy(&buf) - ); - return; - } - }; - - let mtype = message.body.message_type.clone(); - - let pc = program.clone(); - - let handler = match program.handlers.get(&mtype.as_str()) { - Some(v) => v, - None => { - eprintln!("no handler found for {}", message.body.message_type); - return; - } - }; - - handler(message, pc); } pub fn set_node_id(&self, node_id: String) {