#[cfg(feature = "encryption")]
mod encryption;
#[cfg(feature = "compression")]
mod compression;
#[derive(Default)]
pub struct Packs {
items: Vec<Pack>,
}
impl Packs {
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
#[cfg(feature = "compression")]
pub fn compress(mut self) -> Self {
self.items
.push(Pack::Compression(compression::Compression::Lz4));
self
}
#[cfg(feature = "encryption")]
pub fn encrypt(mut self, key: &[u8]) -> Self {
use chacha20poly1305::{ChaCha20Poly1305, KeyInit};
let c = ChaCha20Poly1305::new(key.into());
self.items
.push(Pack::Encryption(encryption::Encryption::Ccp(c)));
self
}
}
#[allow(unused)]
pub(crate) trait PackUnpack {
fn pack(&self, data: &[u8]) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
Ok(data.to_vec())
}
fn unpack(&self, data: &[u8]) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
Ok(data.to_vec())
}
}
impl PackUnpack for Packs {
fn pack(&self, data: &[u8]) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
if data.is_empty() {
return Ok(Vec::new());
}
let mut res = data.to_vec();
for p in self.items.iter() {
res = p.pack(&res)?
}
Ok(res)
}
fn unpack(&self, data: &[u8]) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
if data.is_empty() {
return Ok(Vec::new());
}
let mut res = data.to_vec();
for p in self.items.iter().rev() {
res = p.unpack(&res)?
}
Ok(res)
}
}
enum Pack {
#[cfg(feature = "compression")]
Compression(compression::Compression),
#[cfg(feature = "encryption")]
#[allow(unused)]
Encryption(encryption::Encryption),
}
impl PackUnpack for Pack {
#[cfg(any(feature = "encryption", feature = "compression"))]
fn pack(&self, data: &[u8]) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
match self {
#[cfg(feature = "compression")]
Pack::Compression(c) => c.pack(data),
#[cfg(feature = "encryption")]
Pack::Encryption(e) => e.pack(data),
}
}
#[cfg(any(feature = "encryption", feature = "compression"))]
fn unpack(&self, data: &[u8]) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
match self {
#[cfg(feature = "compression")]
Pack::Compression(c) => c.unpack(data),
#[cfg(feature = "encryption")]
Pack::Encryption(e) => e.unpack(data),
}
}
}