classicube_relay/packet/
continue.rs1use std::io::{Read, Write};
2
3use super::{FlagsError, Packet, flags::Flags};
4
5#[derive(Debug, thiserror::Error)]
6pub enum ContinuePacketError {
7 #[error("wrong data_part len")]
8 DataPartLength,
9
10 #[error("couldn't read full data_part")]
11 ReadFullDataPart,
12
13 #[error(transparent)]
14 Flags(#[from] FlagsError),
15
16 #[error(transparent)]
17 Io(#[from] std::io::Error),
18}
19type Result<T> = std::result::Result<T, ContinuePacketError>;
20
21#[derive(Debug, PartialEq, Eq)]
22pub struct ContinuePacket {
23 pub stream_id: u8,
24 pub data_part: Vec<u8>,
25}
26impl ContinuePacket {
27 pub const DATA_PART_LENGTH: usize = 64 - 1;
28
29 pub fn new(stream_id: u8, data_part: Vec<u8>) -> Result<Self> {
30 if data_part.len() != Self::DATA_PART_LENGTH {
31 return Err(ContinuePacketError::DataPartLength);
32 }
33
34 Ok(Self {
35 stream_id,
36 data_part,
37 })
38 }
39
40 pub fn new_reader(stream_id: u8, data_stream: &mut impl Read) -> Result<Self> {
41 let mut data_part = Vec::with_capacity(Packet::DATA_LENGTH);
42
43 let mut buf = [0; Self::DATA_PART_LENGTH];
44 let n = data_stream.read(&mut buf)?;
45
46 data_part.write_all(&buf[..n])?;
47 data_part.resize(Self::DATA_PART_LENGTH, 0);
48
49 Self::new(stream_id, data_part)
50 }
51
52 pub fn encode(&self) -> Result<Vec<u8>> {
53 let mut data = Vec::with_capacity(Packet::DATA_LENGTH);
54
55 data.write_all(
56 &Flags {
57 is_packet_start: false,
58 stream_id: self.stream_id,
59 }
60 .encode()?,
61 )?;
62 data.write_all(&self.data_part)?;
63
64 Ok(data)
65 }
66
67 pub(crate) fn decode(stream_id: u8, data_stream: &mut impl Read) -> Result<Self> {
68 let mut data_part = [0; Self::DATA_PART_LENGTH];
69 let n = data_stream.read(&mut data_part)?;
70
71 if n != Self::DATA_PART_LENGTH {
72 return Err(ContinuePacketError::ReadFullDataPart);
73 }
74
75 Ok(Self {
76 stream_id,
77 data_part: data_part.to_vec(),
78 })
79 }
80}