azathoth_transformers 0.1.0

Data transformers for the AzathothC2 project
Documentation
use alloc::boxed::Box;
use alloc::vec::Vec;

/// Generic error wrapper type
pub type TransformerError = Box<dyn core::error::Error + Send + Sync>;

/// Core transformer trait. Implement this for types that transform data
pub trait Transformer: Send + Sync {
    /// Transforms the data with the transformer
    ///
    /// # Errors
    /// Returns a `Vec<u8>` containing the transformed data, and a [`TransformerError`] if any error occurs
    fn apply_bytes(&mut self, data: &[u8]) -> Result<Vec<u8>, TransformerError>;
    /// Reverses the operation done to the data by the application function
    /// # Errors
    /// Returns a `Vec<u8>` containing the reversed data, and a [`TransformerError`] if any error occurs
    fn reverse_bytes(&mut self, data: &[u8]) -> Result<Vec<u8>, TransformerError>;
    /// Returns the name of the transformer. Mostly left for diagnostics in case you actually need it
    fn name(&self) -> Option<&'static str>;
    /// Required for cloning the transformer
    fn box_clone(&self) -> Box<dyn Transformer>;
}

/// Extension to allow transformation for any type that implements `AsRef<[u8]>`
pub trait TransformerExt: Transformer {
    /// Converts to bytes and transforms the data
    ///
    /// # Errors
    /// Returns a `Vec<u8>` containing the transformed data, and a [`TransformerError`] if any error occurs
    fn apply<D: AsRef<[u8]>>(&mut self, data: D) -> Result<Vec<u8>, TransformerError> {
        self.apply_bytes(data.as_ref())
    }

    /// Converts to bytes and reverses the transformation
    /// # Errors
    /// Returns a `Vec<u8>` containing the reversed data, and a [`TransformerError`] if any error occurs
    fn reverse<D: AsRef<[u8]>>(&mut self, data: D) -> Result<Vec<u8>, TransformerError> {
        self.reverse_bytes(data.as_ref())
    }
}
impl<T: Transformer + ?Sized> TransformerExt for T {}