use crate::ToBytes;
#[repr(u8)]
#[derive(Copy, Clone)]
pub enum BussSettings {
BodyLength = 0,
Host,
Custom = 0xff,
}
pub trait BaseSettings {
fn get_type(&self) -> BussSettings;
fn get_body(&self) -> Vec<u8>;
}
pub struct CustomSettings {
custom_tag: u8,
bytes: Vec<u8>,
}
impl CustomSettings {
pub fn new(custom_tag: u8, bytes: Vec<u8>) -> Self {
CustomSettings { custom_tag, bytes }
}
}
impl BaseSettings for CustomSettings {
fn get_type(&self) -> BussSettings {
BussSettings::Custom
}
fn get_body(&self) -> Vec<u8> {
let mut bytes: Vec<u8> = Vec::new();
bytes.push(self.get_type() as u8);
bytes.push(self.custom_tag);
bytes.extend(self.bytes.iter());
bytes
}
}
pub struct Settings {
entries: Vec<Box<dyn BaseSettings>>,
}
impl Settings {
pub fn new() -> Self {
Self {
entries: Vec::new(),
}
}
pub fn add(&mut self, entry: Box<dyn BaseSettings>) {
self.entries.push(entry);
}
pub fn iter(&self) -> std::slice::Iter<'_, Box<dyn BaseSettings>> {
self.entries.iter()
}
}
impl ToBytes for Settings {
fn to_bytes(self) -> Vec<u8> {
let mut bytes = Vec::new();
let length = self.entries.len() as u16;
bytes.extend(length.to_be_bytes());
for s in self.entries {
bytes.push(s.get_type() as u8);
bytes.append(&mut s.get_body());
}
bytes
}
}
impl Default for Settings {
fn default() -> Self {
Self::new()
}
}
pub struct BodyLength {
length: usize,
}
impl BodyLength {
pub fn new(size: usize) -> Self {
BodyLength { length: size }
}
pub fn get_length(&self) -> usize {
self.length
}
}
impl BaseSettings for BodyLength {
fn get_type(&self) -> BussSettings {
BussSettings::BodyLength
}
fn get_body(&self) -> Vec<u8> {
self.length.to_be_bytes().to_vec()
}
}
pub struct Host {
host: String,
}
impl Host {
pub fn new(host: &str) -> Self {
Host {
host: String::from(host),
}
}
}
impl BaseSettings for Host {
fn get_type(&self) -> BussSettings {
BussSettings::Host
}
fn get_body(&self) -> Vec<u8> {
let mut bytes = Vec::new();
bytes.extend(self.host.len().to_be_bytes());
bytes.append(&mut self.host.clone().into_bytes());
bytes
}
}