I had planned on implementing some sort of checksum on the file read side, but I hadn't thought of the write process being interrupted, I'm going to have to give that some thought.
And fair enough, I'm not familiar enough with the terminology to give an accurate shorthand description, so trying to keep it as brief as is useful:
I have a serialization module that introduces a trait CustomSer with two required function signatures:
pub trait CustomSer {
fn serialize(&self) -> Vec<u8>;
fn from_serial(serial: &mut Vec<u8>) -> Self;
}
The module also contains the functions for primitive type conversions to Vec<u8> and other common need functions for creating the buffers, like cap_serial which adds a u32 indication of the buffer length of the next item for types without a fixed byte length. Typically I've been using a mutable borrow of an ongoing buffer and adding onto it:
pub fn serialize_string(buffer: &mut Vec<u8>, data: &String) {
let mut data_bytes: Vec<u8> = Vec::<u8>::with_capacity(data.len()+4);
for byte in data.as_bytes() {data_bytes.push(*byte)};
let append_buffer = cap_serial(data_bytes);
for byte in append_buffer {buffer.push(byte)};
}
pub fn cap_serial(mut buffer: Vec<u8>) -> Vec<u8> {
let buffer_length: u32 = buffer.len() as u32;
let mut buffer_total: Vec<u8> = Vec::<u8>::new();
for byte in buffer_length.to_le_bytes() {buffer_total.push(byte)};
buffer_total.append(&mut buffer);
return buffer_total
}
The CustomSer trait is implemented for any struct or sub-struct that will be written to file, and the implementation uses the serialization module definitions for primitive types:
use crate::serial_common as sc;
pub struct TestStruct {
text: String,
number: i32,
}
impl CustomSer for TestStruct {
fn serialize(&self) -> Vec<u8> {
let mut buffer: Vec<u8> = Vec::<u8>::new();
sc::serialize_string(&mut buffer, &self.text);
sc::serialize_i32(&mut buffer, &self.number);
return buffer
}
}
Saving to file is just an fs::write() call, and read is an fs::read() call. Both will eventually have typical path/dir/file error handling. De-serialization is just the same in reverse, de-serialization functions for primitives in the module:
pub fn deserialize_string(mut buffer: &mut Vec<u8>) -> String {
let string_length = deserialize_u32(&mut buffer);
let mut string_vec: Vec<u8> = Vec::<u8>::with_capacity(string_length as usize);
for _ in 0..string_length {string_vec.push(buffer.pop().unwrap())};
return String::from_utf8(string_vec).unwrap()
}
And similarly, all relevant structs implement the from_serial function using calls to the module functions or sub-structures' from_serial functions, using pop() loops to eat through the byte buffer read from the file.
So far nothing has broken it that wouldn't also break the underlying primitive types. I have enough working to encode and decode structures containing any of: primitives (at least the ones covered in the module), other structures that implement CustomSer, or vectors of either.