Skip to main content

classicube_relay/packet/
flags.rs

1use std::io::Read;
2
3use byteorder::{ReadBytesExt, WriteBytesExt};
4
5#[derive(Debug, thiserror::Error)]
6pub enum FlagsError {
7    #[error(transparent)]
8    Io(#[from] std::io::Error),
9}
10type Result<T> = std::result::Result<T, FlagsError>;
11
12// u8
13// is_packet_start: mask 1000_0000
14// stream_id: mask 0111_1111
15#[derive(Debug, PartialEq, Eq)]
16pub struct Flags {
17    /// is a start packet, or is a continuation
18    pub is_packet_start: bool,
19
20    // TODO what am i
21    pub stream_id: u8,
22}
23impl Flags {
24    pub fn encode(&self) -> Result<Vec<u8>> {
25        let mut data = Vec::with_capacity(1);
26
27        let mut b = 0;
28        b |= if self.is_packet_start { 0b1000_0000 } else { 0 };
29        b |= self.stream_id & 0b0111_1111;
30
31        data.write_u8(b)?;
32
33        Ok(data)
34    }
35
36    pub fn decode(data_stream: &mut impl Read) -> Result<Self> {
37        let byte = data_stream.read_u8()?;
38        let is_packet_start = (byte & 0b1000_0000) != 0;
39        let stream_id = byte & 0b0111_1111;
40        Ok(Self {
41            is_packet_start,
42            stream_id,
43        })
44    }
45}