Expose message method and data field

Signed-off-by: trivernis <trivernis@protonmail.com>
pull/1/head
trivernis 4 years ago
parent 90c68cce99
commit c84d69c164
Signed by: Trivernis
GPG Key ID: DFFFCC2C7A02DB45

@ -16,8 +16,7 @@ mod tests {
fn it_deserializes_messages() { fn it_deserializes_messages() {
let bytes = vec![0x00, 0x00, 0x00, 0x10, 0x01, 0x00, 0x10, 0x00, 0x00, 0x11, 0xFF, 0x00, 0x96, 0xA9, 0xB2, 0x2E]; let bytes = vec![0x00, 0x00, 0x00, 0x10, 0x01, 0x00, 0x10, 0x00, 0x00, 0x11, 0xFF, 0x00, 0x96, 0xA9, 0xB2, 0x2E];
let message = Message::from_bytes(&bytes); let message = Message::from_bytes(&bytes);
let mut other_message = Message::new([0x01, 0x00, 0x10, 0x00], vec![0x00, 0x11, 0xFF, 0x00]); let other_message = Message::new([0x01, 0x00, 0x10, 0x00], vec![0x00, 0x11, 0xFF, 0x00]);
other_message.crc = Some( 0x96A9B22E );
assert_eq!(message, Ok(other_message)) assert_eq!(message, Ok(other_message))
} }

@ -12,20 +12,16 @@ pub enum DeserializeError {
#[derive(Clone, Debug, PartialOrd, PartialEq)] #[derive(Clone, Debug, PartialOrd, PartialEq)]
pub struct Message { pub struct Message {
length: u32, pub method: [u8; 4],
method: [u8; 4], pub data: Vec<u8>,
data: Vec<u8>,
pub crc: Option<u32>,
} }
impl Message { impl Message {
/// Creates a new message /// Creates a new message
pub fn new(method: [u8; 4], data: Vec<u8>) -> Self { pub fn new(method: [u8; 4], data: Vec<u8>) -> Self {
Self { Self {
length: (12 + data.len()) as u32,
method, method,
data, data,
crc: None,
} }
} }
@ -35,9 +31,7 @@ impl Message {
data.serialize(&mut Serializer::new(&mut buf)).unwrap(); data.serialize(&mut Serializer::new(&mut buf)).unwrap();
Self { Self {
method, method,
length: (12 + buf.len()) as u32,
data: buf, data: buf,
crc: None,
} }
} }
@ -65,10 +59,8 @@ impl Message {
let data = bytes[8..(length as usize - 4)].to_vec(); let data = bytes[8..(length as usize - 4)].to_vec();
Ok(Self { Ok(Self {
length,
method, method,
data, data,
crc: Some(crc)
}) })
} }
@ -76,7 +68,7 @@ impl Message {
pub fn to_bytes(&self) -> Vec<u8> { pub fn to_bytes(&self) -> Vec<u8> {
let mut data = Vec::new(); let mut data = Vec::new();
let mut length_raw = [0u8; 4]; let mut length_raw = [0u8; 4];
BigEndian::write_u32(&mut length_raw, self.length); BigEndian::write_u32(&mut length_raw, self.data.len() as u32 + 12);
data.append(&mut length_raw.to_vec()); data.append(&mut length_raw.to_vec());
data.append(&mut self.method.clone().to_vec()); data.append(&mut self.method.clone().to_vec());
data.append(&mut self.data.clone()); data.append(&mut self.data.clone());

Loading…
Cancel
Save