ssb_packetstream/
packet.rs

1use byteorder::{BigEndian, ByteOrder};
2
3#[derive(Clone, Debug, PartialEq)]
4pub struct Packet {
5    pub stream: IsStream,
6    pub end: IsEnd,
7    pub body_type: BodyType,
8    pub id: i32,
9    pub body: Vec<u8>,
10}
11impl Packet {
12    pub fn new(
13        stream: IsStream,
14        end: IsEnd,
15        body_type: BodyType,
16        id: i32,
17        body: Vec<u8>,
18    ) -> Packet {
19        Packet {
20            stream,
21            end,
22            body_type,
23            id,
24            body,
25        }
26    }
27
28    pub fn is_stream(&self) -> bool {
29        self.stream == IsStream::Yes
30    }
31
32    pub fn is_end(&self) -> bool {
33        self.end == IsEnd::Yes
34    }
35
36    pub(crate) fn flags(&self) -> u8 {
37        self.stream as u8 | self.end as u8 | self.body_type as u8
38    }
39    pub(crate) fn header(&self) -> [u8; 9] {
40        let mut header = [0; 9];
41        header[0] = self.flags();
42        BigEndian::write_u32(&mut header[1..5], self.body.len() as u32);
43        BigEndian::write_i32(&mut header[5..], self.id);
44        header
45    }
46}
47
48#[repr(u8)]
49#[derive(Copy, Clone, Debug, PartialEq)]
50pub enum IsStream {
51    No = 0,
52    Yes = 0b0000_1000,
53}
54impl From<u8> for IsStream {
55    fn from(u: u8) -> IsStream {
56        match u & IsStream::Yes as u8 {
57            0 => IsStream::No,
58            _ => IsStream::Yes,
59        }
60    }
61}
62
63#[repr(u8)]
64#[derive(Copy, Clone, Debug, PartialEq)]
65pub enum IsEnd {
66    No = 0,
67    Yes = 0b0000_0100,
68}
69impl From<u8> for IsEnd {
70    fn from(u: u8) -> IsEnd {
71        match u & IsEnd::Yes as u8 {
72            0 => IsEnd::No,
73            _ => IsEnd::Yes,
74        }
75    }
76}
77
78#[repr(u8)]
79#[derive(Copy, Clone, Debug, PartialEq)]
80pub enum BodyType {
81    Binary = 0b00,
82    Utf8 = 0b01,
83    Json = 0b10,
84}
85impl From<u8> for BodyType {
86    fn from(u: u8) -> BodyType {
87        match u & 0b11 {
88            0b00 => BodyType::Binary,
89            0b01 => BodyType::Utf8,
90            0b10 => BodyType::Json,
91            _ => panic!(),
92        }
93    }
94}