How to serialize a type to bytes?

If I want to make a type in Rust serializable to a String I use fmt::Display. If I want to serialize it to hex I use serialize::hex::ToHex, but what trait should I use to convert a type to binary? There is io::Read but it is targeted at io, it is not as trivial to implement as the others and it is used mostly for io and not for general purpose in the current std.

There are a few types that implement a to_bytes or into_bytes method, but it is nothing standard: std - Rust

Display is not for serialization. It's for display.

For serializing to strings, you should be using rustc-serialize (https://crates.io/crates/rustc-serialize). I don't know of any libraries offering a binary serialization format but you could probably write a binary encoder/decoder for rustc-serialize.

1 Like

This blog post about serde mentions a few binary serialization libraries in the benchmark table.

1 Like

There's also CBOR for Rust, which is basically binary JSON. It has lots of implementations in other languages too: http://cbor.io/

Thanks. This made things a lot more clear.