aboutsummaryrefslogtreecommitdiff
path: root/src/proto2.rs
diff options
context:
space:
mode:
authorAlex Auvolat <alex@adnab.me>2022-02-21 12:01:04 +0100
committerAlex Auvolat <alex@adnab.me>2022-02-21 12:01:04 +0100
commit3b8bff634198c5ae17ab16d5c85c30b3201ae593 (patch)
tree8f3545c230c08c3a3100faf1293345e88a43d3dd /src/proto2.rs
parent109d6c143d01b2d59027d45738692fa8ef6253ee (diff)
downloadnetapp-3b8bff634198c5ae17ab16d5c85c30b3201ae593.tar.gz
netapp-3b8bff634198c5ae17ab16d5c85c30b3201ae593.zip
Refactoring
Diffstat (limited to 'src/proto2.rs')
-rw-r--r--src/proto2.rs75
1 files changed, 75 insertions, 0 deletions
diff --git a/src/proto2.rs b/src/proto2.rs
new file mode 100644
index 0000000..4e126d3
--- /dev/null
+++ b/src/proto2.rs
@@ -0,0 +1,75 @@
+use crate::proto::*;
+use crate::error::*;
+
+pub(crate) struct QueryMessage<'a> {
+ pub(crate) prio: RequestPriority,
+ pub(crate) path: &'a [u8],
+ pub(crate) telemetry_id: Option<Vec<u8>>,
+ pub(crate) body: &'a [u8],
+}
+
+/// QueryMessage encoding:
+/// - priority: u8
+/// - path length: u8
+/// - path: [u8; path length]
+/// - telemetry id length: u8
+/// - telemetry id: [u8; telemetry id length]
+/// - body [u8; ..]
+impl<'a> QueryMessage<'a> {
+ pub(crate) fn encode(self) -> Vec<u8> {
+ let tel_len = match &self.telemetry_id {
+ Some(t) => t.len(),
+ None => 0,
+ };
+
+ let mut ret = Vec::with_capacity(10 + self.path.len() + tel_len + self.body.len());
+
+ ret.push(self.prio);
+
+ ret.push(self.path.len() as u8);
+ ret.extend_from_slice(self.path);
+
+ if let Some(t) = self.telemetry_id {
+ ret.push(t.len() as u8);
+ ret.extend(t);
+ } else {
+ ret.push(0u8);
+ }
+
+ ret.extend_from_slice(self.body);
+
+ ret
+ }
+
+ pub(crate) fn decode(bytes: &'a [u8]) -> Result<Self, Error> {
+ if bytes.len() < 3 {
+ return Err(Error::Message("Invalid protocol message".into()));
+ }
+
+ let path_length = bytes[1] as usize;
+ if bytes.len() < 3 + path_length {
+ return Err(Error::Message("Invalid protocol message".into()));
+ }
+
+ let telemetry_id_len = bytes[2 + path_length] as usize;
+ if bytes.len() < 3 + path_length + telemetry_id_len {
+ return Err(Error::Message("Invalid protocol message".into()));
+ }
+
+ let path = &bytes[2..2 + path_length];
+ let telemetry_id = if telemetry_id_len > 0 {
+ Some(bytes[3 + path_length .. 3 + path_length + telemetry_id_len].to_vec())
+ } else {
+ None
+ };
+
+ let body = &bytes[3 + path_length + telemetry_id_len..];
+
+ Ok(Self {
+ prio: bytes[0],
+ path,
+ telemetry_id,
+ body,
+ })
+ }
+}