Cookie Factory Serialization in Rust: Step-by-Step
In this article
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
nomparser combinators (helpful, but not strictly required)
Step-by-Step
- Add dependencies – In your
Cargo.toml, addcookie_factoryandnom(for types likeNomBytes):[dependencies] cookie_factory = "0.3" nom = "7" - 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}; - 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, } - 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:
Note: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() }gen_simplereturns the remaining buffer, so we capture it and return the filled portion. - Handle variable-length data – For a
Vecor string, you often need to write a length prefix. Usebe_u16orbe_u32before the data. Example:let (buf, _) = be_u16(buf, msg.payload.len() as u16)?; let (buf, _) = all(be_u8)(buf, &msg.payload)?; - Use combinators for complex structures – For tuples or nested structs, use
pairortuple. Example:let ser = pair(be_u16, be_u32); let (buf, _) = ser(buf, (msg.id, msg.length))?; - 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]); } } - Run tests – Execute
cargo testto verify everything works.
Common Mistakes
- Forgetting to update the buffer pointer – Each serializer returns a new buffer slice; you must reassign
bufon every step. - Using the wrong endianness – The crate provides both
be_*andle_*functions; mixing them leads to incorrect byte order. - Not handling the remaining buffer correctly –
gen_simplereturns the leftover buffer after writing; you must slice the original to get the actual data. - Assuming strings are null-terminated –
stringwrites the bytes without a terminator; you must write a length prefix separately. - Using
allon a non-slice –allexpects a slice; for a single value, use the direct function.
Tips
- Use
gen_simplefor simplicity – It handles buffer allocation for you, but you need to manage the returned slice. - Prefer
genfor streaming – If you're writing to a file or network, usegenwith 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
moveclosures or pass data by reference. - Panic on unwrap –
gen_simplereturns aResult; 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_*vsle_*) consistently. - String serialization fails – If you get a type error, ensure you pass a
&str, not aString, tostring.
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.