11 unstable releases (5 breaking)

0.6.0 Mar 24, 2024
0.6.0-alpha.2 Feb 29, 2024
0.5.0 Oct 17, 2023
0.4.0 May 14, 2023

#107 in Encoding

Download history 326/week @ 2024-01-05 358/week @ 2024-01-12 427/week @ 2024-01-19 653/week @ 2024-01-26 865/week @ 2024-02-02 849/week @ 2024-02-09 1253/week @ 2024-02-16 1864/week @ 2024-02-23 1806/week @ 2024-03-01 2606/week @ 2024-03-08 1678/week @ 2024-03-15 2184/week @ 2024-03-22 2236/week @ 2024-03-29 2309/week @ 2024-04-05 2595/week @ 2024-04-12 2527/week @ 2024-04-19

10,021 downloads per month
Used in 9 crates (8 directly)

MIT/Apache

260KB
6.5K SLoC

Bitcode

Documentation crates.io Build

A binary encoder/decoder with the following goals:

  • 🔥 Blazingly fast
  • 🐁 Tiny serialized size
  • 💎 Highly compressible by Deflate/LZ4/Zstd

In contrast, these are non-goals:

  • Stable format across major versions
  • Self describing format
  • Compatibility with languages other than Rust

See rust_serialization_benchmark for benchmarks.

Example

use bitcode::{Encode, Decode};

#[derive(Encode, Decode, PartialEq, Debug)]
struct Foo<'a> {
    x: u32,
    y: &'a str,
}

let original = Foo {
    x: 10,
    y: "abc",
};

let encoded: Vec<u8> = bitcode::encode(&original); // No error
let decoded: Foo<'_> = bitcode::decode(&encoded).unwrap();
assert_eq!(original, decoded);

Library Example

Add bitcode to libraries without specifying the major version so binary crates can pick the version. This is a minimal stable subset of the bitcode API so avoid using any other functionality.

bitcode = { version = "0", features = ["derive"], default-features = false, optional = true }
#[cfg_attr(feature = "bitcode", derive(bitcode::Encode, bitcode::Decode))]
pub struct Vec2 {
    x: f32,
    y: f32,
}

Tuple vs Array

If you have multiple values of the same type:

  • Use a tuple or struct when the values are semantically different: x: u32, y: u32
  • Use an array when all values are semantically similar: pixels: [u8; 16]

Implementation Details

  • Heavily inspired by https://github.com/That3Percent/tree-buf
  • All instances of each field are grouped together making compression easier
  • Uses smaller integers where possible all the way down to 1 bit
  • Validation is performed up front on typed vectors before deserialization
  • Code is designed to be auto-vectorized by LLVM

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~0.1–1MB
~28K SLoC