buss_protocol/settings/
mod.rs1use crate::ToBytes;
2
3#[repr(u8)]
11#[derive(Copy, Clone)]
12pub enum BussSettings {
13 BodyLength = 0,
15 Host,
17 Custom = 0xff,
19}
20
21pub trait BaseSettings {
23 fn get_type(&self) -> BussSettings;
25 fn get_body(&self) -> Vec<u8>;
27}
28
29pub struct CustomSettings {
31 custom_tag: u8,
33 bytes: Vec<u8>,
35}
36
37impl CustomSettings {
38 pub fn new(custom_tag: u8, bytes: Vec<u8>) -> Self {
40 CustomSettings { custom_tag, bytes }
41 }
42}
43
44impl BaseSettings for CustomSettings {
45 fn get_type(&self) -> BussSettings {
46 BussSettings::Custom
47 }
48 fn get_body(&self) -> Vec<u8> {
49 let mut bytes: Vec<u8> = Vec::new();
50 bytes.push(self.get_type() as u8);
51 bytes.push(self.custom_tag);
52 bytes.extend(self.bytes.iter());
53 bytes
54 }
55}
56
57pub struct Settings {
59 entries: Vec<Box<dyn BaseSettings>>,
61}
62
63impl Settings {
64 pub fn new() -> Self {
66 Self {
67 entries: Vec::new(),
68 }
69 }
70 pub fn add(&mut self, entry: Box<dyn BaseSettings>) {
72 self.entries.push(entry);
73 }
74
75 pub fn iter(&self) -> std::slice::Iter<'_, Box<dyn BaseSettings>> {
76 self.entries.iter()
77 }
78}
79
80impl ToBytes for Settings {
81 fn to_bytes(self) -> Vec<u8> {
82 let mut bytes = Vec::new();
83 let length = self.entries.len() as u16;
85 bytes.extend(length.to_be_bytes());
86 for s in self.entries {
87 bytes.push(s.get_type() as u8);
88 bytes.append(&mut s.get_body());
89 }
90
91 bytes
92 }
93}
94
95impl Default for Settings {
96 fn default() -> Self {
97 Self::new()
98 }
99}
100
101pub struct BodyLength {
104 length: usize,
106}
107
108impl BodyLength {
109 pub fn new(size: usize) -> Self {
111 BodyLength { length: size }
112 }
113 pub fn get_length(&self) -> usize {
115 self.length
116 }
117}
118
119impl BaseSettings for BodyLength {
120 fn get_type(&self) -> BussSettings {
121 BussSettings::BodyLength
122 }
123 fn get_body(&self) -> Vec<u8> {
124 self.length.to_be_bytes().to_vec()
125 }
126}
127
128pub struct Host {
130 host: String,
132}
133
134impl Host {
135 pub fn new(host: &str) -> Self {
136 Host {
137 host: String::from(host),
138 }
139 }
140}
141impl BaseSettings for Host {
142 fn get_type(&self) -> BussSettings {
143 BussSettings::Host
144 }
145 fn get_body(&self) -> Vec<u8> {
147 let mut bytes = Vec::new();
148 bytes.extend(self.host.len().to_be_bytes());
149 bytes.append(&mut self.host.clone().into_bytes());
150 bytes
151 }
152}