plabble-codec 0.1.0

Plabble Transport Protocol codec
Documentation
use super::KEY_SIZE;

/// Serializable trait
pub trait Serializable {
    /// Returns the size of the serialized data in bytes.
    fn size(&self) -> usize;

    /// Serializes the data into a vector of bytes.
    fn get_bytes(&self) -> Vec<u8>;

    /// Deserializes the data from a vector of bytes.
    ///
    /// # Arguments
    ///
    /// * `data` - slice of bytes to deserialize from
    /// * `info` - optional information about the data to deserialize, i.e. if encryption is used or not
    fn from_bytes(data: &[u8], info: Option<SerializationInfo>) -> Result<Self, SerializationError>
    where
        Self: Sized;
}

/// Error that can occur when serializing or deserializing data
///
/// # Variants
///
/// * `MissingInfo` - More information is needed to deserialize the data. Might indicate that SerializationInfo is missing
/// * `TooFewBytes` - The data is too short to be deserialized (like, the size is 4 but there are just 2 bytes)
/// * `InvalidFormat` - The data format is incorrect
/// * `CounterOverflow` - The client or server counter overflowed (which means a connection should be reset)
/// * `AuthenticationFailed` - The authentication failed (MAC is incorrect, key is wrong or the bucket key is missing)
/// * `DecryptionFailed` - The decryption failed (key is wrong or the bucket key is missing)
#[derive(Debug, PartialEq, Eq)]
pub enum SerializationError {
    MissingInfo(String),
    TooFewBytes(usize),
    InvalidFormat(String),
    CounterOverflow,
    AuthenticationFailed,
    DecryptionFailed,
}

/// Information about the data to serialize or deserialize
///
/// # Variants
///
/// * `PacketType` - Indicates which packet type the data is
/// * `UseEncryption` - Indicates that the data is/must be encrypted and which keys to use (key0, key1, bucket_key)
/// * `UseAuthentication` - Indicates that the data is/must be authenticated and which keys to use (key0, bucket_key)
/// * `None` - No info is needed
#[derive(Debug, Clone, Copy)]
pub enum SerializationInfo {
    PacketType(u8),
    UseEncryption([u8; KEY_SIZE], [u8; KEY_SIZE], Option<[u8; KEY_SIZE]>),
    UseAuthentication([u8; KEY_SIZE], Option<[u8; KEY_SIZE]>),
    None,
}