Hi I just started out with Rust which I am really enjoying.
However, I am not sure how best to accomplish a serialisation task.
Basically I have a structure like
#[derive(Debug, Clone, Copy)] struct SensorValueArray { id: i32, len: i32, values: Vec<SensorValue> }
Where SensorValue is
#[derive(Debug)] struct SensorValue { dt: NaiveDateTime, // byte format i64 + u32 = 8 + 4 = 12 bytes value: i64 // 8 bytes }
NaiveDateTime is part of the chronos crate. I only need millisecond accuracy so could store the NaiveDateTime as a 13 digit integer.
I would like to convert SensorValueArray to and from a byte array for sending over a tcp socket.
So I guess the byte array format should be something like
<sensor_id_bytes><length of entries_in_bytes><val1_datetime_bytes><val1_value_bytes>val2_datetime_bytes><val2_value_bytes> ...
So for reading I have something like below but not sure how to efficiently read the bytes into a SensorValue vector.
impl SensorValueByteReader { pub fn from_byte_array(raw: &[u8]) -> Option<BmosSensorValueArray> { if raw.len() < 28 { None }
self.id = read_u32(raw); self.len = read_u32(raw[4..]); self.values = Vec<BmosSensorValue>::with_capacity(self.len); let mut rdr = Cursor::new(raw[8..]); // Not sure ho to read
} }
fn read_u32(data: &[u8]) -> u32 { (data[0] as u32 << 24) + (data[1] as u32 << 16) + (data[2] as u32 << 8) + (data[3] as u32 << 0) }
Thanks for any advice on completing the serialisation to an from a byte array.