aboutsummaryrefslogtreecommitdiff
path: root/utils/src/protocol.rs
blob: fce168d241c4062232408274fbbe11ef2f0fee79 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
use std::convert::TryInto;
use std::io::{self, BufReader, ErrorKind, Read};
use std::net::TcpStream;

pub enum MessageBody {
    Version(u32),
    NewCore(String, Vec<u8>),
    Job(u64, Vec<u8>),
}

pub enum Reply {
    Version(bool),
    NewCore,
    Job(i32, Vec<u8>),
}

pub struct RawMessage {
    pub typ: u8,
    pub id: u64,
    pub payload: Vec<u8>,
}

impl RawMessage {
    pub fn receive(reader: &mut BufReader<TcpStream>) -> io::Result<Option<Self>> {
        let mut header = [0u8; 17];
        if let Err(e) = reader.read_exact(&mut header) {
            if e.kind() == ErrorKind::UnexpectedEof { return Ok(None); }
            else { return Err(e); }
        }

        let typ = header[0];
        let id = u64::from_le_bytes(header[1..9].try_into().unwrap());
        let length = usize::from_le_bytes(header[9..17].try_into().unwrap());

        let mut payload = Vec::new();
        payload.resize(length, 0u8);
        if let Err(e) = reader.read_exact(&mut payload) {
            if e.kind() == ErrorKind::UnexpectedEof { return Ok(None); }
            else { return Err(e); }
        }

        Ok(Some(Self { typ, id, payload }))
    }
}