rekt_common/datagrams/
data_request.rs

1use crate::enums::datagram_type::DatagramType;
2use crate::libs::types::{Size, TopicId};
3use crate::libs::utils::{get_u16_at_pos, get_u32_at_pos, get_u64_at_pos};
4
5// The datagram data is used to embed a payload to send information through a specific topic
6#[no_mangle]
7pub struct DtgData {
8    pub datagram_type: DatagramType,
9    // 1 byte
10    pub size: Size,
11    // 2 bytes (u16)
12    pub sequence_number: u32,
13    // 4 bytes (u32)
14    pub topic_id: TopicId,
15    // 8 bytes (u64)
16    pub payload: Vec<u8>, // size bytes
17}
18
19impl DtgData {
20    pub fn new(sequence_number: u32, topic_id: TopicId, payload: Vec<u8>) -> DtgData {
21        DtgData {
22            datagram_type: DatagramType::Data,
23            size: payload.len() as Size,
24            sequence_number,
25            topic_id,
26            payload,
27        }
28    }
29
30    pub fn as_bytes(&self) -> Vec<u8>
31    {
32        let mut bytes: Vec<u8> = Vec::with_capacity(15 + self.size as usize);
33        bytes.push(u8::from(self.datagram_type));
34        bytes.extend(self.size.to_le_bytes());
35        bytes.extend(self.sequence_number.to_le_bytes());
36        bytes.extend(self.topic_id.to_le_bytes());
37        bytes.extend(self.payload.iter());
38        return bytes;
39    }
40}
41
42impl<'a> TryFrom<&'a [u8]> for DtgData {
43    type Error = &'a str;
44
45    fn try_from(buffer: &'a [u8]) -> Result<Self, Self::Error> {
46        if buffer.len() < 15 {
47            return Err("Payload len is to short for a DtgData.");
48        }
49        let size = get_u16_at_pos(buffer, 1)?;
50        let sequence_number = get_u32_at_pos(buffer, 3)?;
51        let topic_id = get_u64_at_pos(buffer, 7)?;
52
53        Ok(DtgData {
54            datagram_type: DatagramType::Data,
55            size,
56            sequence_number,
57            topic_id,
58            payload: buffer[15..15 + size as usize].into(),
59        })
60    }
61}