Skip to main content

classicube_relay/packet/
mod.rs

1mod r#continue;
2mod flags;
3mod scope;
4mod start;
5
6use std::io::Read;
7
8pub use self::{r#continue::*, flags::*, scope::*, start::*};
9
10#[derive(Debug, thiserror::Error)]
11pub enum StreamError {
12    #[error("{0}")]
13    LengthOverflow(String),
14
15    #[error("can't find free outgoing packet id")]
16    PacketIdLimit,
17
18    #[error(transparent)]
19    Flags(#[from] FlagsError),
20
21    #[error(transparent)]
22    StartPacket(#[from] StartPacketError),
23
24    #[error(transparent)]
25    ContinuePacket(#[from] ContinuePacketError),
26}
27type Result<T> = std::result::Result<T, StreamError>;
28
29// [u8; 64]
30#[derive(Debug, PartialEq, Eq)]
31pub enum Packet {
32    Start(StartPacket),
33    Continue(ContinuePacket),
34}
35impl Packet {
36    pub const DATA_LENGTH: usize = 64;
37
38    pub fn encode(&self) -> Result<Vec<u8>> {
39        match self {
40            Self::Start(packet) => Ok(packet.encode()?),
41            Self::Continue(packet) => Ok(packet.encode()?),
42        }
43    }
44
45    pub fn decode(data_stream: &mut impl Read) -> Result<Self> {
46        let flags = Flags::decode(data_stream)?;
47
48        let packet = if flags.is_packet_start {
49            Packet::Start(StartPacket::decode(flags.stream_id, data_stream)?)
50        } else {
51            Packet::Continue(ContinuePacket::decode(flags.stream_id, data_stream)?)
52        };
53
54        Ok(packet)
55    }
56}