Expand description
Bincode is a crate for encoding and decoding using a tiny binary serialization strategy. Using it, you can easily go from having an object in memory, quickly serialize it to bytes, and then deserialize it back just as fast!
If you’re coming from bincode 1, check out our migration guide
§Serde
Starting from bincode 2, serde is now an optional dependency. If you want to use serde, please enable the serde feature. See Features for more information.
§Features
| Name | Default? | Affects MSRV? | Supported types for Encode/Decode | Enabled methods | Other |
|---|---|---|---|---|---|
| std | Yes | No | HashMap and HashSet | decode_from_std_read and encode_into_std_write | |
| alloc | Yes | No | All common containers in alloc, like Vec, String, Box | encode_to_vec | |
| atomic | Yes | No | All Atomic* integer types, e.g. AtomicUsize, and AtomicBool | ||
| derive | Yes | No | Enables the BorrowDecode, Decode and Encode derive macros | ||
| serde | No | Yes (MSRV reliant on serde) | Compat and BorrowCompat, which will work for all types that implement serde’s traits | serde-specific encode/decode functions in the serde module | Note: There are several known issues when using serde and bincode |
§Which functions to use
Bincode has a couple of pairs of functions that are used in different situations.
| Situation | Encode | Decode |
|---|---|---|
You’re working with fs::File or net::TcpStream | encode_into_std_write | decode_from_std_read |
| you’re working with in-memory buffers | encode_to_vec | decode_from_slice |
| You want to use a custom Reader and Writer | encode_into_writer | decode_from_reader |
| You’re working with pre-allocated buffers or on embedded targets | encode_into_slice | decode_from_slice |
Note: If you’re using serde, use bincode::serde::... instead of bincode::...
§Untrusted input
The *_untrusted decoding functions opt into collection allocation safeguards.
Ordinary decoding functions retain upstream 2.0.1 behavior. Untrusted functions
require the independent DecodeUntrusted/BorrowDecodeUntrusted traits.
Derive only DecodeUntrusted for client types that should not support ordinary
decoding, or derive both traits when both APIs are intended. Nested values
dispatch through the corresponding untrusted trait. These implementations own
guarded allocation; ordinary Decode is independent of the decoder capability.
Manual implementations must also call the untrusted traits for nested values.
Both paths retain the same configuration and wire format.
#[derive(bincode::DecodeUntrusted)]
struct Message { value: u8 }
let (message, consumed): (Message, _) = bincode::decode_from_slice_untrusted(
&[42], bincode::config::standard(),
).unwrap();
assert_eq!(message.value, 42);
assert_eq!(consumed, 1);With Serde, custom implementations explicitly implement
serde::DeserializeUntrusted for their entire deserialization graph. Serde
constructors expose constrained decode/decode_seed methods in this mode.
Untrusted native vector and hash collection implementations allocate storage after
entries decode. Byte vectors first verify the available payload, or read bounded
chunks when the reader cannot expose it. Failed reservations in these containers
return error::DecodeError::LimitExceeded. Serde adapters omit collection size
hints that could otherwise cause visitors to allocate from an unchecked length.
These safeguards are not a general memory, recursion, or CPU budget. Custom
decoders and Serde visitors remain responsible for their own resource use;
types that consume no bytes can still decode from arbitrarily large counts.
Existing configured limits retain their meaning, including with_no_limit().
Failed untrusted byte-vector reads may consume earlier chunks and report a
missing-byte estimate for the failing chunk. Successful values and consumed
lengths are unchanged; hash collection iteration order is unspecified.
§Example
let mut slice = [0u8; 100];
// You can encode any type that implements `Encode`.
// You can automatically implement this trait on custom types with the `derive` feature.
let input = (
0u8,
10u32,
10000i128,
'a',
[0u8, 1u8, 2u8, 3u8]
);
let length = bincode::encode_into_slice(
input,
&mut slice,
bincode::config::standard()
).unwrap();
let slice = &slice[..length];
println!("Bytes written: {:?}", slice);
// Decoding works the same as encoding.
// The trait used is `Decode`, and can also be automatically implemented with the `derive` feature.
let decoded: (u8, u32, i128, char, [u8; 4]) = bincode::decode_from_slice(slice, bincode::config::standard()).unwrap().0;
assert_eq!(decoded, input);Re-exports§
pub use de::BorrowDecode;pub use de::BorrowDecodeUntrusted;pub use de::Decode;pub use de::DecodeUntrusted;pub use enc::Encode;
Modules§
- config
- The config module is used to change the behavior of bincode’s encoding and decoding logic.
- de
- Decoder-based structs and traits.
- enc
- Encoder-based structs and traits.
- error
- Errors that can be encounting by Encoding and Decoding.
- migration_
guide - Migrating from bincode 1 to 2
- serde
serde - Support for serde integration. Enable this with the
serdefeature. - spec
allocandderive - Serialization Specification
Macros§
- impl_
borrow_ decode - Helper macro to implement
BorrowDecodefor any type that implementsDecode. - impl_
borrow_ decode_ untrusted - Implement borrowed untrusted decoding by delegating to an explicit owned implementation.
- impl_
borrow_ decode_ with_ context - Helper macro to implement
BorrowDecodefor any type that implementsDecode.
Structs§
- IoReader
stdand (allocorderiveorserdeorstd) - Adapts a standard reader for bincode’s
Readertrait.
Functions§
- borrow_
decode_ from_ slice - Attempt to decode a given type
Dfrom the given slice. Returns the decoded output and the amount of bytes read. - borrow_
decode_ from_ slice_ untrusted - Borrow-decode from a slice with the untrusted collection safeguards. Returns the decoded value and the number of bytes consumed.
- borrow_
decode_ from_ slice_ untrusted_ with_ context - Borrow-decode with a context and the untrusted collection safeguards. Returns the decoded value and the number of bytes consumed.
- borrow_
decode_ from_ slice_ with_ context - Attempt to decode a given type
Dfrom the given slice withContext. Returns the decoded output and the amount of bytes read. - decode_
from_ reader - Attempt to decode a given type
Dfrom the given Reader. - decode_
from_ reader_ untrusted - Decode from a custom reader with the untrusted collection safeguards.
- decode_
from_ slice - Attempt to decode a given type
Dfrom the given slice. Returns the decoded output and the amount of bytes read. - decode_
from_ slice_ untrusted - Decode from a slice with the untrusted collection safeguards. Returns the decoded value and the number of bytes consumed.
- decode_
from_ slice_ untrusted_ with_ context - Decode from a slice with a context and the untrusted collection safeguards. Returns the decoded value and the number of bytes consumed.
- decode_
from_ slice_ with_ context - Attempt to decode a given type
Dfrom the given slice withContext. Returns the decoded output and the amount of bytes read. - decode_
from_ std_ read std - Decode type
Dfrom the given reader with the givenConfig. The reader can be any type that implementsstd::io::Read, e.g.std::fs::File. - decode_
from_ std_ read_ untrusted std - Decode from a standard reader with the untrusted collection safeguards.
- decode_
from_ std_ read_ untrusted_ with_ context std - Decode from a standard reader with a context and the untrusted collection safeguards.
- decode_
from_ std_ read_ with_ context std - Decode type
Dfrom the given reader with the givenConfigandContext. The reader can be any type that implementsstd::io::Read, e.g.std::fs::File. - encode_
into_ slice - Encode the given value into the given slice. Returns the amount of bytes that have been written.
- encode_
into_ std_ write std - Encode the given value into any type that implements
std::io::Write, e.g.std::fs::File, with the givenConfig. See the config module for more information. Returns the amount of bytes written. - encode_
into_ writer - Encode the given value into a custom Writer.
- encode_
to_ vec alloc - Encode the given value into a
Vec<u8>with the givenConfig. See the config module for more information.
Derive Macros§
- Borrow
Decode derive - Borrow
Decode Untrusted derive - Decode
derive - Decode
Untrusted derive - Encode
derive