Considerations or quirks for direct Vec<u8> file writing/reading

I'm working on a program that will involve storing struct instances in data files, and so far have a working process of serialization, writing, reading, and de-serialization directly manipulating the Vec<u8> buffers (I understand serde is a fantastic crate, but I'm avoiding external dependencies until it's unreasonable to do so). It works in a clean, local environment (Linux), however I intend to compile to both Linux and Windows x64 targets.

My question is if there are any issues I'm not seeing now that will likely come up if this is compiled and released into the wild. Things such as ease of corruption, modification of the data by the file system, compatibility, etc., that I'm blindly walking into by using a simple struct -> buffer -> file (and then reverse) process. I don't necessarily need to know how to solve all potential issues right now, I'm just unfamiliar enough with low-level file handling that I thought it was worth a check to see if I need to dig into it or adjust course now rather than later.

Things such as ease of corruption, modification of the data by the file system

Some file formats include checksums or other redundant elements so that the decoder can check if there was corruption. Many (e.g. almost all text and text-based files) do not. In general, the file system’s job is to give you back exactly the bytes you wrote, and you can choose to be concerned with failures of that (or accidental or malicious modifications using programs other than yours), or not.

One case worth noting is the event that the program crashes (or the computer loses power) halfway through writing a file. Many programs take no specific care about this, with the result that the file on disk may then be incomplete; ways to take more care include “atomic renaming” (writing a separate new file, then using a rename call to replace the old file with it), refusing to overwrite existing files at all, or designing a file format so that parts of it can be rewritten without invalidating the rest (databases do this).

by using a simple struct -> buffer -> file (and then reverse) process

The important part here is what your “simple” process actually is — what is hiding under your “->”? Without knowing that, we can’t tell you more about how good it is.

If you are transmuting / pointer-casting to convert your own types to [u8], then there are many ways for this to go wrong unless the types involved have been carefully designed to be usable for this purpose. But I only mention this because of a guess about what you consider “simple”. So, tell us more.

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.

You can use a slice for from_serial:

pub trait CustomSer {
    fn serialize(&self) -> Vec<u8>;
    fn from_serial(serial: &[u8]) -> Self; // Only a slice, not mut
}

And the whole serialize_string can be simplified:

// `data`: Only string slice, not String
pub fn serialize_string(buffer: &mut Vec<u8>,  data: &str) {
    // panics, if string is to large
    let strlen = u32::try_from(data.len()).unwrap(); 

    // append strlen to `buffer`
    buffer.extend(strlen.to_le_bytes().as_slice());
    
    // append string bytes
    buffer.extend(data.as_bytes());
}

There’s a crate to help with that…
https://crates.io/crates/phazer

A random collection of advice.

Given the presence of functions like serialize_string, perhaps your trait could be

pub trait CustomSer {
    // Typical implementors will not override this
    fn serialize(&self) -> Vec<u8> {
        let mut buffer = Vec::new();
        self.serialize_into(&mut buffer);
        buffer
    }

    // Implementor must provide this one.  The intention is that
    // you append to the buffer ala `serialize_string`.
    fn serialize_into(&self, buffer: &mut Vec<u8>);
    // ...
}

Speaking of serialize_string, you're creating a lot of temporary Vecs and then moving data around (to e.g. prepend a length after writing the contents). I suggest

// This could be `CustomSer::serialize_into` for `String` (or a newtype)
pub fn serialize_string(buffer: &mut Vec<u8>, data: &String) {
    // Instead of `with_capacity`
    buffer.reserve(data.len() + 4);
    // Aim to always append to avoid prepending
    append_length(buffer, data.len());
    // Replaces your `push` loops
    buffer.extend_from_slice(data.as_bytes());
}

pub fn append_length(buffer: &mut Vec<u8>, length: usize) {
    // Panic instead of writing an invalid length due to `as` casting
    let length = u32::try_from(length).expect("length {length} exceeds 32 bits");
    buffer.extend_from_slice(&length.to_le_bytes());
}

For from_serial (and the deserialize_* functions), I'm not sure why you're taking &mut Vec<u8>. Are you moving all the data around once you consume a prefix? deserialize_string doesn't seem to, but I'm not sure why else you'd take a &mut Vec<_>. Perhaps you want something more like

// Pass in `&mut Serialized` and update `offset` to reflect how many bytes
// you have consumed.  When deserializing, due so from `data[offset..]`.
pub struct Serialized {
    offset: usize,
    data: Vec<u8>,
}

(Alternatively you could pass around a &mut &[u8] but I think the above would be more approachable/less confusing while learning.)

On top of this, you're probably going to eventually want proper error handling instead of just panicking. The sooner you build that into your APIs, the less painful it is to do so. Perhaps something like

pub trait CustomSer {
    // (Some shared error type could be an alternative approach)
    type Error;
    fn from_serial(serial: &mut Serialized) -> Result<Self, Self::Error>;
    // ...
    // Maybe make serialization fallible too (to avoid e.g. panic on
    // lengths which are too large).
}

Even if you use type Error = () and effectively keep unwrapping things at the start, this makes adding proper errors easier down the road in my experience.

@mroth Not using a slice for from_serial was intentional, and I'm going to do my best to explain my reasoning in responding to quinedot, who raised a similar point. On the other hand, I didn't realize that the extend() method existed! I had read through many of the Vec methods, but that one looks to be stuck down in the trait implementation section, which I had not learned to make sense of when this was written. Thanks!


@quinedot On the error handling, I very much agree. I was holding off until I knew the code actually worked, but it's going to be a pain to implement later. If I remember, declaring the "type Error;" in the trait definition means that I would need to make the struct implementations associated type implementations, where they each have their own specific handling for the Error type?

The improvement to serialize_string makes sense, I think I have enough to make that improvement across the board.

I was in the middle of typing up a question on the change to the CustomSer definition to use self.serialize_into when it sunk in, I think I understand that one now. It's shifting the instructions that would be common to all serialize implementations to the trait definition, instead of repeating them in every implementation.

The use of &mut Vec<u8> was intentional, though perhaps my reasoning doesn't hold. It's more or less twofold:

  1. The data buffer exists only to reconstruct the structure data that represents. I've been trying to keep to a mentality of only passing data ownership to a function scope if that function is the end goal of the data. While passing &mut isn't technically ownership, passing &mut into a pop() loop consumes the data relevant to the function. That particular chunk of the data vector is useless after the struct data is reconstructed from it, so there's no reason for it to live past the function scope.

  2. It simplified some positional complexity, though your point of a counter would also work. If I have a struct with 3 string fields (a, b, c) and I serialize them in order, then with the &mut consumption, I never have to worry about keeping position. Once the 'a' field is converted from the serial, its bytes have been consumed from the vec, so the next byte will always be the start of the serialization of field 'b'. The care has to be in the order of serialization and de-serialization as defined in the struct implementations, but if those are correct, it seemed to be reliable.

A minor thought on my first point was that 'consume as you go' method might prevent unnecessary memory reservation by removing the need to copy information during the process, but pop() may not affect vector capacity, and it's probably not enough data volume to worry about in the first place.

You don't need to worry about position keeping. The idea is, to modify the reference to some data, not the data themself. You can "consume", aka, split_off bytes from a slice at both ends.

Because I'm somewhat lazy, and like writing code more than ordinary text, here an extended example to study:

// `data`: Only string slice, not String
pub fn serialize_string(buffer: &mut Vec<u8>,  data: &str) {
    // panics, if string to large
    let strlen = u32::try_from(data.len()).unwrap(); 

    // append strlen as to `buffer`
    buffer.extend(&strlen.to_le_bytes());
    
    // append string bytes
    buffer.extend(data.as_bytes());
}


pub fn deserialize_string(bytes: &mut &[u8]) -> String {
    // "consume" the 4 LE encoded bytes
    let len_bytes = bytes.split_off(..4).unwrap();
    
    // convert the 4 LE encoded bytes into u32
    let strlen = u32::from_le_bytes(len_bytes.try_into().unwrap());
    
    // convert u32 into usize
    let strlen = usize::try_from(strlen).unwrap();
    
    // "consume" the bytes for the string slice
    let str_bytes = bytes.split_off(..strlen).unwrap();
    
    // convert the byte slice into a string slice, aka all bytes are checked to be valid UTF8
    let s = str::from_utf8(str_bytes).unwrap();
    
    // Allocates a new String and return
    s.into()
}


fn main() {
    let original = "Hello, world!".to_string();

    let mut buffer = Vec::new();
    serialize_string(&mut buffer, &original);
    
    // Serialized size
    assert_eq!(buffer.len(), 17);
    
    // This is a reference to the serialized bytes
    let mut data = buffer.as_slice();
    assert_eq!(data.len(), 17);

    // "consume" the referenced bytes
    let reconstructed = deserialize_string(&mut data);
    
    // deserialized should equal to the original
    assert_eq!(original, reconstructed);
    
    // check that we "consumed" all bytes
    assert!(data.is_empty());
    
    // but our original encoded bytes are still there
    // because we only modified the reference to the serialized bytes.
    assert_eq!(buffer.len(), 17);
}

Oh, yeah, I missed exactly what was happening -- popping the Vec. So do you reverse it first? (pop takes off the end.) You miss out on some optimizations that way, probably, like copying a whole string out in one go. Using a VecDeque would re-enable them (another alternative to my suggestion).

Anyway, it seems this is a question of optimization, so it's something you could punt on for now if your current approach is working.

Every implementation declares it's own error type if you make it an associated type, yeah. Though an implementation can choose to use the same error type as some other implementation.

If that's a pain for whatever reason you could slap on

-> Result<Self, ()>
// or
-> Result<Self, Box<dyn Error>>
// or
-> Result<Self, SomeLocalErrorType>

instead, and revisit/generalize later, if you need to.

... slices can be mutable?

Puppet Awkward GIF - Puppet Awkward Looking - Discover & Share GIFs

I uh... I need to go rethink some code.

@kpreid @mroth @quinedot Appreciate the help!

Mutating a slice is one option, but I also like this pattern:

fn parse_foo<'input>(input: &'input [u8]) -> Result<(Foo, &'input [u8]), Error> {
  let (bar, input) = parse_bar(input)?;
  ...
  Ok((Foo { bar, ... }, input))
}

Roughly, you always return the remaining input, and shadow the previous input on a successful parse.

This is a bit noisier and a bit more bookkeeping in eg loops, than &mut &[u8], but makes it really easy to think about, especially recovery, and I suspect might be a little easier to optimize?

Generally if you're doing this you're doing a combinator based approach to handle common patterns in your parse, which lightens up the bookkeeping a lot.

Sounds weird, but is dead simple.

Warning: The following examples are simplified, they omit lifetimes, so they are not ready for usage but only demonstrate the principle!

Consider, what a String is, it's only a pointer to some bytes in memory, a length, and a capacity:

struct MyString {
    data: *mut u8,
    len: usize,
    capacity: usize,
}

A slice is mostly the same, it points to some bytes in memory and has a length, but no capacity:

struct MySlice {
    data: *mut u8,
    len: usize,
}

When a slice is created from a string, both point to the same bytes in memory:

impl MyString {
    pub fn as_my_slice(&self) -> MySlice {
        MySlice {
            data: self.data,
            len: self.len,
        }
    }
}

To split a part off from a slice, the code looks something like this:

impl MySlice {
    pub fn split_off(&mut self, len: usize) -> MySlice {
        // make sure, `len` does not exceed our length
        assert!(len <= self.len);
        
        // split off some of the data
        let result = MySlice {
            data: self.data,
            len
        };
        
        // Move our pointer to new start position
        self.data = unsafe { self.data.add(len) };
        
        // adjust our length
        self.len -= len;
        
        // voila
        result
    }
}

Please note, self for MySlice::split_off is a mutable reference to a MySlice. This allows modifying the content of self.

So you can create both values, and the slice itself can be mutable, and split_off works:

    let my_string = MyString::new(...);

    // Create a mutable slice, that means, the slice can be modified
    let mut my_slice_1 = my_string.as_my_slice();

    // Modify our original slice and create a new one:
    let my_slice_2 = my_slice_1.split_off(5);

The result is:

  • my_string points to the start of the string bytes, and its len matches the complete string.
  • my_slice_2 points to the start too, but its len is only 5.
  • my_slice_1: The pointer is incremented by 5 bytes, and its len is 5 less then my_string.

Instead of inventing your own serialization format (and dealing with file corruption, compatibility, etc.), it might be a good idea to use SQLite As An Application File Format. In some cases, sqlite might actually be faster than directly manipulating files.

If I were smart, I would probably use something like that. As it is, this program is as much as much for my own benefit learning as it is to reach an end product, so I'm doing possibly inadvisable things like making my own serialization format, and the other side of my patchwork file handling, saved file obfuscation (not encryption). Hopefully that way, when I do move to using something like SQLite, I have enough of an understanding of low-level file IO, encoding, etc. that I can determine the best tool and the best way to use it.

However, I will definitely give that a read. I know a tiny bit about SQLite from a user's perspective, but I've never dealt with it in detail, and definitely never from the programming side. Thanks!

Even if you don't reach proficiency in working with serialisation and files, the proverbial rakes don't hurt as much as real ones when you step on them, and you get at least a rough idea of what you'll need to deal with if you get serious about it. Experiment, have fun, learn — it will pay off one way or another. If you ever feel too out of depth with a particular task and don't have much free time, there are always plenty of crates to choose from.

As for checksums, I suggest to write the file header with a dummy one first (i.e. a definitely invalid one), write the data, then seek to the checksum offset and write the real checksum. That way you end up with a file that's either entirely valid or corrupted and safe to discard.

What is the advantage of this approach compared to simply appending the checksum (CRC or hash) at the end?

After thinking about it carefully, I couldn't find a decisive advantage. I learned this approach a long time ago and cannot recall the reasoning behind it. You're right to question it.

Same for me. It is more difficult to store it at the end if the length of the checksum is variable, or it is stored alongside other fields that are variable length, but that's probably not true in this case at least.

With no real experience, EOF shenanigans would be the only thing I could think of, but I would also think that would just result in an invalid checksum, not any sort of undefined behavior.

If the content can be changed, what prevent you to change checksum as well?