plabble_codec/abstractions/
serializable.rs

1use super::KEY_SIZE;
2
3/// Serializable trait
4pub trait Serializable {
5    /// Returns the size of the serialized data in bytes.
6    fn size(&self) -> usize;
7
8    /// Serializes the data into a vector of bytes.
9    fn get_bytes(&self) -> Vec<u8>;
10
11    /// Deserializes the data from a vector of bytes.
12    ///
13    /// # Arguments
14    ///
15    /// * `data` - slice of bytes to deserialize from
16    /// * `info` - optional information about the data to deserialize, i.e. if encryption is used or not
17    fn from_bytes(data: &[u8], info: Option<SerializationInfo>) -> Result<Self, SerializationError>
18    where
19        Self: Sized;
20}
21
22/// Error that can occur when serializing or deserializing data
23///
24/// # Variants
25///
26/// * `MissingInfo` - More information is needed to deserialize the data. Might indicate that SerializationInfo is missing
27/// * `TooFewBytes` - The data is too short to be deserialized (like, the size is 4 but there are just 2 bytes)
28/// * `InvalidFormat` - The data format is incorrect
29/// * `CounterOverflow` - The client or server counter overflowed (which means a connection should be reset)
30/// * `AuthenticationFailed` - The authentication failed (MAC is incorrect, key is wrong or the bucket key is missing)
31/// * `DecryptionFailed` - The decryption failed (key is wrong or the bucket key is missing)
32#[derive(Debug, PartialEq, Eq)]
33pub enum SerializationError {
34    MissingInfo(String),
35    TooFewBytes(usize),
36    InvalidFormat(String),
37    CounterOverflow,
38    AuthenticationFailed,
39    DecryptionFailed,
40}
41
42/// Information about the data to serialize or deserialize
43///
44/// # Variants
45///
46/// * `PacketType` - Indicates which packet type the data is
47/// * `UseEncryption` - Indicates that the data is/must be encrypted and which keys to use (key0, key1, bucket_key)
48/// * `UseAuthentication` - Indicates that the data is/must be authenticated and which keys to use (key0, bucket_key)
49/// * `None` - No info is needed
50#[derive(Debug, Clone, Copy)]
51pub enum SerializationInfo {
52    PacketType(u8),
53    UseEncryption([u8; KEY_SIZE], [u8; KEY_SIZE], Option<[u8; KEY_SIZE]>),
54    UseAuthentication([u8; KEY_SIZE], Option<[u8; KEY_SIZE]>),
55    None,
56}