diff --git a/Cargo.lock b/Cargo.lock index 4806a07..212cf38 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -229,7 +229,7 @@ dependencies = [ [[package]] name = "raas_types" -version = "0.0.1" +version = "0.0.2" dependencies = [ "bytes", "prost", diff --git a/Cargo.toml b/Cargo.toml index c8eaf8c..d3778d4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,9 @@ [package] name = "raas_types" -version = "0.0.1" +version = "0.0.2" edition = "2021" +description = "Protobuf definitions for RaaS" +authors = ["Joey Hines joey@ahines.net"] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/src/lib.rs b/src/lib.rs index b55e8f4..67baff8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -20,11 +20,49 @@ pub mod raas { pub mod resp { include!(concat!(env!("OUT_DIR"), "/raas.resp.rs")); } + + #[derive(Debug, Clone)] + pub struct RaasMessage { + pub len: u32, + pub msg: Vec, + } + + impl RaasMessage { + pub fn new(msg: Vec) -> Self { + Self { + len: msg.len() as u32, + msg, + } + } + + pub fn from_bytes(bytes: &[u8]) -> Self { + let (len_bytes, msg) = bytes.split_at(std::mem::size_of::()); + let mut arr = [0u8; 4]; + arr.copy_from_slice(len_bytes); + let len = u32::from_be_bytes(arr); + + Self { + len, + msg: msg.to_vec(), + } + } + + pub fn into_bytes(mut self) -> Vec { + let mut bytes = Vec::new(); + + bytes.extend_from_slice(&self.len.to_be_bytes()); + + bytes.append(&mut self.msg); + + bytes + } + } } #[cfg(test)] mod test { use crate::raas; + use crate::raas::RaasMessage; #[test] fn create_cmd() { @@ -41,7 +79,36 @@ mod test { assert_eq!(cmd.id, 0); assert_eq!(cmd.timestamp, 0); assert!(cmd.cmd.is_some()); + } - let sub_cmd = cmd.cmd.unwrap(); + #[test] + fn encode_message() { + let data = vec![0, 1, 2, 3, 4]; + let msg = RaasMessage::new(data.clone()); + + let msg_bytes = msg.into_bytes(); + + assert_eq!(msg_bytes.len(), data.len() + std::mem::size_of::()); + } + + #[test] + fn decode_message() { + let data: Vec = vec![0, 0, 0, 5, 0, 1, 2, 3, 4]; + let msg = RaasMessage::from_bytes(&data); + + assert_eq!(msg.len, 5); + assert_eq!(msg.msg, data[4..]); + } + + #[test] + fn encode_decode_message() { + let original_message = RaasMessage::new(vec![0x55, 0xff]); + + let data = original_message.clone().into_bytes(); + + let decoded_message = RaasMessage::from_bytes(&data); + + assert_eq!(decoded_message.len, decoded_message.len); + assert_eq!(decoded_message.msg, original_message.msg); } }