#binary #encode #decode #serialize #deserialize

bincode

A binary serialization / deserialization strategy that uses Serde for transforming structs into bytes and vice versa!

49 releases (9 stable)

1.3.1 Jun 24, 2020
1.2.1 Dec 10, 2019
1.2.0 Sep 24, 2019
1.1.4 May 15, 2019
0.0.2 Nov 24, 2014

#8 in Encoding

Download history 45491/week @ 2020-03-16 44881/week @ 2020-03-23 44288/week @ 2020-03-30 41461/week @ 2020-04-06 43065/week @ 2020-04-13 50073/week @ 2020-04-20 47882/week @ 2020-04-27 45667/week @ 2020-05-04 50765/week @ 2020-05-11 45840/week @ 2020-05-18 48128/week @ 2020-05-25 46632/week @ 2020-06-01 47875/week @ 2020-06-08 47817/week @ 2020-06-15 58668/week @ 2020-06-22 55862/week @ 2020-06-29

197,997 downloads per month
Used in 1,075 crates (629 directly)

MIT license

105KB
2.5K SLoC

Bincode

CI

A compact encoder / decoder pair that uses a binary zero-fluff encoding scheme. The size of the encoded object will be the same or smaller than the size that the object takes up in memory in a running Rust program.

In addition to exposing two simple functions (one that encodes to Vec<u8>, and one that decodes from &[u8]), binary-encode exposes a Reader/Writer API that makes it work perfectly with other stream-based APIs such as Rust files, network streams, and the flate2-rs compression library.

API Documentation

Bincode in the wild

  • google/tarpc: Bincode is used to serialize and deserialize networked RPC messages.
  • servo/webrender: Bincode records webrender API calls for record/replay-style graphics debugging.
  • servo/ipc-channel: IPC-Channel uses Bincode to send structs between processes using a channel-like API.

Example

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Entity {
    x: f32,
    y: f32,
}

#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct World(Vec<Entity>);

fn main() {
    let world = World(vec![Entity { x: 0.0, y: 4.0 }, Entity { x: 10.0, y: 20.5 }]);

    let encoded: Vec<u8> = bincode::serialize(&world).unwrap();

    // 8 bytes for the length of the vector, 4 bytes per float.
    assert_eq!(encoded.len(), 8 + 4 * 4);

    let decoded: World = bincode::deserialize(&encoded[..]).unwrap();

    assert_eq!(world, decoded);
}

Details

The encoding (and thus decoding) proceeds unsurprisingly -- primitive types are encoded according to the underlying Writer, tuples and structs are encoded by encoding their fields one-by-one, and enums are encoded by first writing out the tag representing the variant and then the contents.

However, there are some implementation details to be aware of:

  • isize/usize are encoded as i64/u64, for portability.
  • enums variants are encoded as a u32 instead of a usize. u32 is enough for all practical uses.
  • str is encoded as (u64, &[u8]), where the u64 is the number of bytes contained in the encoded string.

Dependencies

~240–390KB