romy_core/
serial.rs

1//! Standard serialization encoding for the project
2
3use byteorder::{LittleEndian, ReadBytesExt};
4
5/// Encodes an object as a series of bytes
6/// 
7/// # Arguments
8/// * `object` - the object to encode
9pub fn encode(object: &impl serde::Serialize) -> Vec<u8> {
10    bincode::serialize(object).unwrap()
11}
12
13/// Encodes an object as a series of bytes, tacking on the size of the data as a u64 at the front
14/// 
15/// # Arguments
16/// * `object` - the object to encode
17pub fn encode_with_size(object: &impl serde::Serialize) -> Vec<u8> {
18    let mut data = Vec::new();
19    let serial = encode(object);
20    data.extend((serial.len() as u64).to_le_bytes().iter());
21    data.extend(serial.iter());
22    data
23}
24
25/// Decodes an object from a series of bytes
26/// 
27/// # Arguments
28/// * `data` - the data to decode 
29pub fn decode<'a, T: serde::Deserialize<'a>>(data: &'a [u8]) -> T {
30    bincode::deserialize(data).unwrap()
31}
32
33/// Decodes an object from a series of bytes that has had a size tacked on the front as a u64
34/// 
35/// # Arguments
36/// * `data` - the data to decode 
37pub fn decode_with_size<'a, T: serde::Deserialize<'a>>(data: &'a [u8]) -> T {
38    decode(&data[8..])
39}
40
41/// Decodes an object from a series of bytes given as a pointer that has had a size tacked on the
42/// front as a u64
43/// 
44/// # Arguments
45/// * `data` - the data to decode 
46pub unsafe fn decode_with_size_ptr<'a, T: serde::Deserialize<'a>>(data: *const u8) -> T {
47    let size = std::slice::from_raw_parts(data, 8)
48        .read_u64::<LittleEndian>()
49        .unwrap();
50    let data = std::slice::from_raw_parts(data.offset(8), size as usize);
51    decode(&data)
52}