rust/lib-hedgewars-engine/src/ipc.rs
changeset 14281 f0c0d2d217c3
parent 14276 a239e4243cf9
child 14282 1b8c889027a3
--- a/rust/lib-hedgewars-engine/src/ipc.rs	Wed Nov 21 17:28:28 2018 +0300
+++ b/rust/lib-hedgewars-engine/src/ipc.rs	Wed Nov 21 15:49:16 2018 +0100
@@ -1,5 +1,6 @@
-use hedgewars_engine_messages::{messages::*, parser};
+use hedgewars_engine_messages::{messages::*, parser::extract_message};
 use netbuf::*;
+use std::io::*;
 
 pub struct IPC {
     in_buffer: Buf,
@@ -8,6 +9,47 @@
 
 impl IPC {
     pub fn new() -> Self {
+        Self {
+            in_buffer: Buf::new(),
+            out_buffer: Buf::new(),
+        }
+    }
 
+    pub fn send_message(&mut self, message: &EngineMessage) {
+        self.out_buffer.write(&message.to_bytes()).unwrap();
+    }
+}
+
+impl Write for IPC {
+    fn write(&mut self, buf: &[u8]) -> Result<usize> {
+        self.in_buffer.write(buf)
+    }
+
+    fn flush(&mut self) -> Result<()> {
+        self.in_buffer.flush()
     }
 }
+
+impl Read for IPC {
+    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
+        let result = self.out_buffer.as_ref().read(buf);
+
+        if let Ok(read_bytes) = result {
+            self.out_buffer.consume(read_bytes);
+        }
+
+        result
+    }
+}
+
+impl Iterator for IPC {
+    type Item = EngineMessage;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        let (consumed, message) = extract_message(&self.in_buffer[..])?;
+
+        self.in_buffer.consume(consumed);
+
+        Some(message)
+    }
+}