classicube_relay/packet/
flags.rs

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