Zimt

Cookie Factory Serialization in Rust: Step-by-Step

· 4 min read · Cookies and Bars

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Serializing with the cookie_factory crate in Rust lets you build binary data from a structured description, which is the inverse of nom's parsing. Instead of manually writing bytes, you define a serializer that writes fields into a buffer. This guide walks you through the process, from adding the dependency to writing and testing a complete serializer.

What You'll Need

  • A Rust project (e.g., created with cargo new)
  • Basic familiarity with Rust syntax and ownership
  • Understanding of nom parser combinators (helpful, but not strictly required)

Step-by-Step

  1. Add dependencies – In your Cargo.toml, add cookie_factory and nom (for types like NomBytes):
    [dependencies]
    cookie_factory = "0.3"
    nom = "7"
  2. Import the essentials – At the top of your Rust file, bring in the serialization traits and functions:
    use cookie_factory::{SerializeFn, GenError};
    use cookie_factory::gen_simple;
    use cookie_factory::combinators::{all, pair, tuple};
    use cookie_factory::bytes::{be_u16, be_u32, be_i32, be_f32, string};
  3. Define your data structure – Create a struct that holds the data you want to serialize. For example:
    struct Message {
        id: u16,
        length: u32,
        payload: Vec<u8>,
        name: String,
    }
  4. Write a serializer function – The serializer is a function that takes a GenError-returning closure. It writes each field sequentially. Here's a basic example:
    fn serialize_message(msg: &Message) -> Vec<u8> {
        let ser = |buf: &mut [u8]| {
            let (buf, _) = be_u16(buf, msg.id)?;
            let (buf, _) = be_u32(buf, msg.length)?;
            let (buf, _) = all(be_u8)(buf, &msg.payload)?;
            let (buf, _) = string(buf, msg.name.as_str())?;
            Ok((buf, ()))
        };
        let mut buf = Vec::with_capacity(1024);
        let (buf, _) = gen_simple(ser, &mut buf).unwrap();
        buf.to_vec()
    }
    Note: gen_simple returns the remaining buffer, so we capture it and return the filled portion.
  5. Handle variable-length data – For a Vec or string, you often need to write a length prefix. Use be_u16 or be_u32 before the data. Example:
    let (buf, _) = be_u16(buf, msg.payload.len() as u16)?;
    let (buf, _) = all(be_u8)(buf, &msg.payload)?;
  6. Use combinators for complex structures – For tuples or nested structs, use pair or tuple. Example:
    let ser = pair(be_u16, be_u32);
    let (buf, _) = ser(buf, (msg.id, msg.length))?;
  7. Test your serializer – Write a unit test that serializes a sample and checks the bytes:
    #[cfg(test)]
    mod tests {
        use super::*;
        #[test]
        fn test_serialize() {
            let msg = Message { id: 1, length: 3, payload: vec![10, 20, 30], name: "abc".to_string() };
            let bytes = serialize_message(&msg);
            assert_eq!(bytes, vec![0, 1, 0, 0, 0, 3, 10, 20, 30, 97, 98, 99]);
        }
    }
  8. Run tests – Execute cargo test to verify everything works.

Common Mistakes

  • Forgetting to update the buffer pointer – Each serializer returns a new buffer slice; you must reassign buf on every step.
  • Using the wrong endianness – The crate provides both be_* and le_* functions; mixing them leads to incorrect byte order.
  • Not handling the remaining buffer correctly – gen_simple returns the leftover buffer after writing; you must slice the original to get the actual data.
  • Assuming strings are null-terminated – string writes the bytes without a terminator; you must write a length prefix separately.
  • Using all on a non-slice – all expects a slice; for a single value, use the direct function.

Tips

  • Use gen_simple for simplicity – It handles buffer allocation for you, but you need to manage the returned slice.
  • Prefer gen for streaming – If you're writing to a file or network, use gen with a writer instead of building a full Vec.
  • Reuse serializers – Define small serializer functions and combine them with combinators to avoid repetition.
  • Check the crate documentation – The API is similar to nom; reading the docs helps understand the exact signatures.

Troubleshooting

  • Compile errors about lifetimes – Ensure your serializer closure captures references with appropriate lifetimes. If needed, use move closures or pass data by reference.
  • Panic on unwrap – gen_simple returns a Result; handle errors gracefully instead of unwrapping, especially if the buffer is too small.
  • Output is empty – Check that you're returning the correct slice. After gen_simple, the returned buffer is the remaining space; the actual data is in the original buffer up to that point.
  • Bytes are in wrong order – Verify you're using the correct endianness functions (be_* vs le_*) consistently.
  • String serialization fails – If you get a type error, ensure you pass a &str, not a String, to string.

Frequently Asked Questions

What is the difference between cookie_factory and serde?

cookie_factory is for binary formats where you control every byte, while serde handles common formats like JSON and YAML with less control.

Can I serialize to a file directly?

Yes, use gen with a writer that implements Write, e.g., a File.

Does it support bit-level fields?

No, cookie_factory works at byte granularity. For bitfields, you'd need to pack bytes manually.

Is it compatible with no_std?

Yes, but you'll need to use gen with a custom buffer type and avoid Vec unless you have an allocator.

How do I serialize a nested struct?

Define a serializer function for the inner struct and call it from the outer one, passing the buffer along.

What if I need to compute a checksum after writing?

Write the data first, then compute the checksum over the written bytes and write it at the end using a separate serializer.