Added wrapper RaaS Message type

main
Joey Hines 2024-05-26 20:44:21 -06:00
parent 64ced3ddc8
commit 76cced03cb
Signed by: joeyahines
GPG Key ID: 995E531F7A569DDB
3 changed files with 72 additions and 3 deletions

2
Cargo.lock generated
View File

@ -229,7 +229,7 @@ dependencies = [
[[package]]
name = "raas_types"
version = "0.0.1"
version = "0.0.2"
dependencies = [
"bytes",
"prost",

View File

@ -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

View File

@ -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<u8>,
}
impl RaasMessage {
pub fn new(msg: Vec<u8>) -> 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::<u32>());
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<u8> {
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::<u32>());
}
#[test]
fn decode_message() {
let data: Vec<u8> = 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);
}
}