How does serde/bincode serialize byte arrays?

Viewed 1384

This code serializes an array of 32 bytes exactly as I want:

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
struct Hash([u8; 32]);

let hash = Hash([1u8; 32]);
let hash_bin = bincode::serialize(&hash).unwrap();
assert_eq!(hash_bin, [1u8; 32]);

How does it work?

According to https://serde.rs/impl-serializer.html there is a serialize_bytes() function, but the bincode version it prepends a length to the data.

fn serialize_bytes(self, v: &[u8]) -> Result<()> {
    O::IntEncoding::serialize_len(self, v.len())?;
    self.writer.write_all(v).map_err(Into::into)
}

What function in Serialize does the code (further above) call, to serialize the 32 bytes as themselves with no length prefix?


Context: I'm implementing a customer serialize for a type and I want it (under some circumstances) to serialize arrays of bytes so that bincode encodes them as bytes with no length prefix. This is a problem because calling serialize_bytes() adds a length prefix.

I want to understand how arrays of bytes are serialized by default, as I do not know which method to call in place of serialize_bytes() to get bytes without a length prefix.

0 Answers
Related