Moved Configuration::standard() and ::legacy() to the config module (#481)

* Moved Configuration::standard() and ::legacy() to the config module

* Fixed issue with config that would overwrite the limit, added a checklist on adding config variables
This commit is contained in:
Trangar 2022-01-19 16:46:25 +01:00 committed by GitHub
parent a5e57d51d8
commit 59b787cbf8
19 changed files with 162 additions and 177 deletions

View File

@ -30,7 +30,7 @@ library.
## Example ## Example
```rust ```rust
use bincode::{config::Configuration, Decode, Encode}; use bincode::{config, Decode, Encode};
#[derive(Encode, Decode, PartialEq, Debug)] #[derive(Encode, Decode, PartialEq, Debug)]
struct Entity { struct Entity {
@ -42,7 +42,7 @@ struct Entity {
struct World(Vec<Entity>); struct World(Vec<Entity>);
fn main() { fn main() {
let config = Configuration::standard(); let config = config::standard();
let world = World(vec![Entity { x: 0.0, y: 4.0 }, Entity { x: 10.0, y: 20.5 }]); let world = World(vec![Entity { x: 0.0, y: 4.0 }, Entity { x: 10.0, y: 20.5 }]);
@ -103,7 +103,7 @@ Bincode 2.0 is still in development and does not yet have a targetted MSRV. Once
### Why does bincode not respect `#[repr(u8)]`? ### Why does bincode not respect `#[repr(u8)]`?
Bincode will encode enum variants as a `u32`. If you're worried about storage size, we can recommend enabling `Configuration::with_varint_encoding()`. This option is enabled by default with the `standard` configuration. In this case enum variants will almost always be encoded as a `u8`. Bincode will encode enum variants as a `u32`. If you're worried about storage size, we can recommend enabling `Configuration::with_variable_int_encoding()`. This option is enabled by default with the `standard` configuration. In this case enum variants will almost always be encoded as a `u8`.
Currently we have not found a compelling case to respect `#[repr(...)]`. You're most likely trying to interop with a format that is similar-but-not-quite-bincode. We only support our own protocol ([spec](https://github.com/bincode-org/bincode/blob/trunk/docs/spec.md)). Currently we have not found a compelling case to respect `#[repr(...)]`. You're most likely trying to interop with a format that is similar-but-not-quite-bincode. We only support our own protocol ([spec](https://github.com/bincode-org/bincode/blob/trunk/docs/spec.md)).

View File

@ -1,9 +1,8 @@
use bincode::config;
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use criterion::{black_box, criterion_group, criterion_main, Criterion};
use bincode::config::Configuration;
fn inline_decoder_claim_bytes_read(c: &mut Criterion) { fn inline_decoder_claim_bytes_read(c: &mut Criterion) {
let config = Configuration::standard().with_limit::<100000>(); let config = config::standard().with_limit::<100000>();
let slice = bincode::encode_to_vec(vec![String::from("Hello world"); 1000], config).unwrap(); let slice = bincode::encode_to_vec(vec![String::from("Hello world"); 1000], config).unwrap();
c.bench_function("inline_decoder_claim_bytes_read", |b| { c.bench_function("inline_decoder_claim_bytes_read", |b| {

View File

@ -1,6 +1,5 @@
use bincode::config;
use criterion::{criterion_group, criterion_main, Criterion}; use criterion::{criterion_group, criterion_main, Criterion};
use bincode::config::Configuration;
use rand::distributions::Distribution; use rand::distributions::Distribution;
fn slice_varint_u8(c: &mut Criterion) { fn slice_varint_u8(c: &mut Criterion) {
@ -9,7 +8,7 @@ fn slice_varint_u8(c: &mut Criterion) {
let input: Vec<u8> = std::iter::from_fn(|| Some(dist.sample(&mut rng))) let input: Vec<u8> = std::iter::from_fn(|| Some(dist.sample(&mut rng)))
.take(10_000) .take(10_000)
.collect(); .collect();
let config = Configuration::standard(); let config = config::standard();
let bytes = bincode::encode_to_vec(&input, config).unwrap(); let bytes = bincode::encode_to_vec(&input, config).unwrap();
c.bench_function("slice_varint_u8", |b| { c.bench_function("slice_varint_u8", |b| {
@ -25,7 +24,7 @@ fn slice_varint_u16(c: &mut Criterion) {
let input: Vec<u16> = std::iter::from_fn(|| Some(dist.sample(&mut rng))) let input: Vec<u16> = std::iter::from_fn(|| Some(dist.sample(&mut rng)))
.take(10_000) .take(10_000)
.collect(); .collect();
let config = Configuration::standard(); let config = config::standard();
let bytes = bincode::encode_to_vec(&input, config).unwrap(); let bytes = bincode::encode_to_vec(&input, config).unwrap();
c.bench_function("slice_varint_u16", |b| { c.bench_function("slice_varint_u16", |b| {
@ -41,7 +40,7 @@ fn slice_varint_u32(c: &mut Criterion) {
let input: Vec<u32> = std::iter::from_fn(|| Some(dist.sample(&mut rng))) let input: Vec<u32> = std::iter::from_fn(|| Some(dist.sample(&mut rng)))
.take(10_000) .take(10_000)
.collect(); .collect();
let config = Configuration::standard(); let config = config::standard();
let bytes = bincode::encode_to_vec(&input, config).unwrap(); let bytes = bincode::encode_to_vec(&input, config).unwrap();
c.bench_function("slice_varint_u32", |b| { c.bench_function("slice_varint_u32", |b| {
@ -57,7 +56,7 @@ fn slice_varint_u64(c: &mut Criterion) {
let input: Vec<u64> = std::iter::from_fn(|| Some(dist.sample(&mut rng))) let input: Vec<u64> = std::iter::from_fn(|| Some(dist.sample(&mut rng)))
.take(10_000) .take(10_000)
.collect(); .collect();
let config = Configuration::standard(); let config = config::standard();
let bytes = bincode::encode_to_vec(&input, config).unwrap(); let bytes = bincode::encode_to_vec(&input, config).unwrap();
c.bench_function("slice_varint_u64", |b| { c.bench_function("slice_varint_u64", |b| {
@ -73,7 +72,7 @@ fn bufreader_varint_u8(c: &mut Criterion) {
let input: Vec<u8> = std::iter::from_fn(|| Some(dist.sample(&mut rng))) let input: Vec<u8> = std::iter::from_fn(|| Some(dist.sample(&mut rng)))
.take(10_000) .take(10_000)
.collect(); .collect();
let config = Configuration::standard(); let config = config::standard();
let bytes = bincode::encode_to_vec(&input, config).unwrap(); let bytes = bincode::encode_to_vec(&input, config).unwrap();
c.bench_function("bufreader_varint_u8", |b| { c.bench_function("bufreader_varint_u8", |b| {
@ -91,7 +90,7 @@ fn bufreader_varint_u16(c: &mut Criterion) {
let input: Vec<u16> = std::iter::from_fn(|| Some(dist.sample(&mut rng))) let input: Vec<u16> = std::iter::from_fn(|| Some(dist.sample(&mut rng)))
.take(10_000) .take(10_000)
.collect(); .collect();
let config = Configuration::standard(); let config = config::standard();
let bytes = bincode::encode_to_vec(&input, config).unwrap(); let bytes = bincode::encode_to_vec(&input, config).unwrap();
c.bench_function("bufreader_varint_u16", |b| { c.bench_function("bufreader_varint_u16", |b| {
@ -109,7 +108,7 @@ fn bufreader_varint_u32(c: &mut Criterion) {
let input: Vec<u32> = std::iter::from_fn(|| Some(dist.sample(&mut rng))) let input: Vec<u32> = std::iter::from_fn(|| Some(dist.sample(&mut rng)))
.take(10_000) .take(10_000)
.collect(); .collect();
let config = Configuration::standard(); let config = config::standard();
let bytes = bincode::encode_to_vec(&input, config).unwrap(); let bytes = bincode::encode_to_vec(&input, config).unwrap();
c.bench_function("bufreader_varint_u32", |b| { c.bench_function("bufreader_varint_u32", |b| {
@ -127,7 +126,7 @@ fn bufreader_varint_u64(c: &mut Criterion) {
let input: Vec<u64> = std::iter::from_fn(|| Some(dist.sample(&mut rng))) let input: Vec<u64> = std::iter::from_fn(|| Some(dist.sample(&mut rng)))
.take(10_000) .take(10_000)
.collect(); .collect();
let config = Configuration::standard(); let config = config::standard();
let bytes = bincode::encode_to_vec(&input, config).unwrap(); let bytes = bincode::encode_to_vec(&input, config).unwrap();
c.bench_function("bufreader_varint_u64", |b| { c.bench_function("bufreader_varint_u64", |b| {

View File

@ -18,10 +18,8 @@ All floating point types will take up exactly 4 (for `f32`) or 8 (for `f64`) byt
All tuples have no additional bytes, and are encoded in their specified order, e.g. All tuples have no additional bytes, and are encoded in their specified order, e.g.
```rust ```rust
use bincode::config::Configuration;
let tuple = (u32::min_value(), i32::max_value()); // 8 bytes let tuple = (u32::min_value(), i32::max_value()); // 8 bytes
let encoded = bincode::encode_to_vec(tuple, Configuration::legacy()).unwrap(); let encoded = bincode::encode_to_vec(tuple, bincode::config::legacy()).unwrap();
assert_eq!(encoded.as_slice(), &[ assert_eq!(encoded.as_slice(), &[
0, 0, 0, 0, // 4 bytes for first type: u32 0, 0, 0, 0, // 4 bytes for first type: u32
255, 255, 255, 127 // 4 bytes for second type: i32 255, 255, 255, 127 // 4 bytes for second type: i32
@ -59,8 +57,6 @@ Enums are encoded with their variant first, followed by optionally the variant f
Both named and unnamed fields are serialized with their values only, and therefor encode to the same value. Both named and unnamed fields are serialized with their values only, and therefor encode to the same value.
```rust ```rust
use bincode::config::Configuration;
#[derive(bincode::Encode)] #[derive(bincode::Encode)]
pub enum SomeEnum { pub enum SomeEnum {
A, A,
@ -69,21 +65,21 @@ pub enum SomeEnum {
} }
// SomeEnum::A // SomeEnum::A
let encoded = bincode::encode_to_vec(SomeEnum::A, Configuration::legacy()).unwrap(); let encoded = bincode::encode_to_vec(SomeEnum::A, bincode::config::legacy()).unwrap();
assert_eq!(encoded.as_slice(), &[ assert_eq!(encoded.as_slice(), &[
0, 0, 0, 0, // first variant, A 0, 0, 0, 0, // first variant, A
// no extra bytes because A has no fields // no extra bytes because A has no fields
]); ]);
// SomeEnum::B(0) // SomeEnum::B(0)
let encoded = bincode::encode_to_vec(SomeEnum::B(0), Configuration::legacy()).unwrap(); let encoded = bincode::encode_to_vec(SomeEnum::B(0), bincode::config::legacy()).unwrap();
assert_eq!(encoded.as_slice(), &[ assert_eq!(encoded.as_slice(), &[
1, 0, 0, 0, // first variant, B 1, 0, 0, 0, // first variant, B
0, 0, 0, 0 // B has 1 unnamed field, which is an u32, so 4 bytes 0, 0, 0, 0 // B has 1 unnamed field, which is an u32, so 4 bytes
]); ]);
// SomeEnum::C { value: 0u32 } // SomeEnum::C { value: 0u32 }
let encoded = bincode::encode_to_vec(SomeEnum::C { value: 0u32 }, Configuration::legacy()).unwrap(); let encoded = bincode::encode_to_vec(SomeEnum::C { value: 0u32 }, bincode::config::legacy()).unwrap();
assert_eq!(encoded.as_slice(), &[ assert_eq!(encoded.as_slice(), &[
2, 0, 0, 0, // first variant, C 2, 0, 0, 0, // first variant, C
0, 0, 0, 0 // C has 1 named field which is a u32, so 4 bytes 0, 0, 0, 0 // C has 1 named field which is a u32, so 4 bytes
@ -97,14 +93,13 @@ Collections are encoded with their length value first, following by each entry o
**note**: fixed array length may not have their `len` encoded. See [Arrays](#arrays) **note**: fixed array length may not have their `len` encoded. See [Arrays](#arrays)
```rust ```rust
use bincode::config::Configuration;
let list = vec![ let list = vec![
0u8, 0u8,
1u8, 1u8,
2u8 2u8
]; ];
let encoded = bincode::encode_to_vec(list, Configuration::legacy()).unwrap(); let encoded = bincode::encode_to_vec(list, bincode::config::legacy()).unwrap();
assert_eq!(encoded.as_slice(), &[ assert_eq!(encoded.as_slice(), &[
3, 0, 0, 0, 0, 0, 0, 0, // length of 3u64 3, 0, 0, 0, 0, 0, 0, 0, // length of 3u64
0, // entry 0 0, // entry 0
@ -120,11 +115,9 @@ This also applies to e.g. `HashMap`, where each entry is a [tuple](#basic-types)
Both `String` and `&str` are treated as a `Vec<u8>`. See [Collections](#collections) for more information. Both `String` and `&str` are treated as a `Vec<u8>`. See [Collections](#collections) for more information.
```rust ```rust
use bincode::config::Configuration;
let str = "Hello"; // Could also be `String::new(...)` let str = "Hello"; // Could also be `String::new(...)`
let encoded = bincode::encode_to_vec(str, Configuration::legacy()).unwrap(); let encoded = bincode::encode_to_vec(str, bincode::config::legacy()).unwrap();
assert_eq!(encoded.as_slice(), &[ assert_eq!(encoded.as_slice(), &[
5, 0, 0, 0, 0, 0, 0, 0, // length of the string, 5 bytes 5, 0, 0, 0, 0, 0, 0, 0, // length of the string, 5 bytes
b'H', b'e', b'l', b'l', b'o' b'H', b'e', b'l', b'l', b'o'
@ -139,16 +132,14 @@ Note that `&[T]` is encoded as a [Collection](#collections).
```rust ```rust
use bincode::config::Configuration;
let arr: [u8; 5] = [10, 20, 30, 40, 50]; let arr: [u8; 5] = [10, 20, 30, 40, 50];
let encoded = bincode::encode_to_vec(arr, Configuration::legacy()).unwrap(); let encoded = bincode::encode_to_vec(arr, bincode::config::legacy()).unwrap();
assert_eq!(encoded.as_slice(), &[ assert_eq!(encoded.as_slice(), &[
5, 0, 0, 0, 0, 0, 0, 0, // The length, as a u64 5, 0, 0, 0, 0, 0, 0, 0, // The length, as a u64
10, 20, 30, 40, 50, // the bytes 10, 20, 30, 40, 50, // the bytes
]); ]);
let encoded = bincode::encode_to_vec(arr, Configuration::legacy().skip_fixed_array_length()).unwrap(); let encoded = bincode::encode_to_vec(arr, bincode::config::legacy().skip_fixed_array_length()).unwrap();
assert_eq!(encoded.as_slice(), &[ assert_eq!(encoded.as_slice(), &[
// no length // no length
10, 20, 30, 40, 50, // the bytes 10, 20, 30, 40, 50, // the bytes
@ -158,8 +149,6 @@ assert_eq!(encoded.as_slice(), &[
This applies to any type `T` that implements `Encode`/`Decode` This applies to any type `T` that implements `Encode`/`Decode`
```rust ```rust
use bincode::config::Configuration;
#[derive(bincode::Encode)] #[derive(bincode::Encode)]
struct Foo { struct Foo {
first: u8, first: u8,
@ -177,14 +166,14 @@ let arr: [Foo; 2] = [
}, },
]; ];
let encoded = bincode::encode_to_vec(&arr, Configuration::legacy()).unwrap(); let encoded = bincode::encode_to_vec(&arr, bincode::config::legacy()).unwrap();
assert_eq!(encoded.as_slice(), &[ assert_eq!(encoded.as_slice(), &[
2, 0, 0, 0, 0, 0, 0, 0, // Length of the array 2, 0, 0, 0, 0, 0, 0, 0, // Length of the array
10, 20, // First Foo 10, 20, // First Foo
30, 40, // Second Foo 30, 40, // Second Foo
]); ]);
let encoded = bincode::encode_to_vec(&arr, Configuration::legacy().skip_fixed_array_length()).unwrap(); let encoded = bincode::encode_to_vec(&arr, bincode::config::legacy().skip_fixed_array_length()).unwrap();
assert_eq!(encoded.as_slice(), &[ assert_eq!(encoded.as_slice(), &[
// no length // no length
10, 20, // First Foo 10, 20, // First Foo

View File

@ -40,7 +40,7 @@ enum AllTypes {
} }
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
let config = bincode::config::Configuration::standard().with_limit::<1024>(); let config = bincode::config::standard().with_limit::<1024>();
let result: Result<(AllTypes, _), _> = bincode::decode_from_slice(data, config); let result: Result<(AllTypes, _), _> = bincode::decode_from_slice(data, config);
if let Ok((before, _)) = result { if let Ok((before, _)) = result {

View File

@ -5,8 +5,7 @@
//! To use a config, first create a type of [Configuration]. This type will implement trait [Config] for use with bincode. //! To use a config, first create a type of [Configuration]. This type will implement trait [Config] for use with bincode.
//! //!
//! ``` //! ```
//! use bincode::config::{Config, Configuration}; //! let config = bincode::config::standard()
//! let config = Configuration::standard()
//! // pick one of: //! // pick one of:
//! .with_big_endian() //! .with_big_endian()
//! .with_little_endian() //! .with_little_endian()
@ -47,42 +46,49 @@ pub struct Configuration<E = LittleEndian, I = Varint, A = SkipFixedArrayLength,
_l: PhantomData<L>, _l: PhantomData<L>,
} }
impl Configuration { /// The default config for bincode 2.0. By default this will be:
/// The default config for bincode 2.0. By default this will be: /// - Little endian
/// - Little endian /// - Variable int encoding
/// - Variable int encoding /// - Skip fixed array length
/// - Skip fixed array length pub const fn standard() -> Configuration {
pub const fn standard() -> Self { generate()
Self::generate()
}
/// Creates the "legacy" default config. This is the default config that was present in bincode 1.0
/// - Little endian
/// - Fixed int length encoding
/// - Write array lengths
pub const fn legacy() -> Configuration<LittleEndian, Fixint, WriteFixedArrayLength, NoLimit> {
Self::generate()
}
} }
impl<E, I, A, L> Configuration<E, I, A, L> { /// Creates the "legacy" default config. This is the default config that was present in bincode 1.0
const fn generate<_E, _I, _A, _L>() -> Configuration<_E, _I, _A, _L> { /// - Little endian
/// - Fixed int length encoding
/// - Write array lengths
pub const fn legacy() -> Configuration<LittleEndian, Fixint, WriteFixedArrayLength, NoLimit> {
generate()
}
const fn generate<_E, _I, _A, _L>() -> Configuration<_E, _I, _A, _L> {
Configuration { Configuration {
_e: PhantomData, _e: PhantomData,
_i: PhantomData, _i: PhantomData,
_a: PhantomData, _a: PhantomData,
_l: PhantomData, _l: PhantomData,
} }
} }
// When adding more features to configuration, follow these steps:
// - Create 2 or more structs that can be used as a type (e.g. Limit and NoLimit)
// - Add an `Internal...Config` to the `internal` module
// - Make sure `Config` and `impl<T> Config for T` extend from this new trait
// - Add a generic to `Configuration`
// - Add this generic to `const fn generate<...>()`
// - Add this generic to _every_ function in `Configuration`
// - Add your new methods
impl<E, I, A, L> Configuration<E, I, A, L> {
/// Makes bincode encode all integer types in big endian. /// Makes bincode encode all integer types in big endian.
pub const fn with_big_endian(self) -> Configuration<BigEndian, I, A> { pub const fn with_big_endian(self) -> Configuration<BigEndian, I, A, L> {
Self::generate() generate()
} }
/// Makes bincode encode all integer types in little endian. /// Makes bincode encode all integer types in little endian.
pub const fn with_little_endian(self) -> Configuration<LittleEndian, I, A> { pub const fn with_little_endian(self) -> Configuration<LittleEndian, I, A, L> {
Self::generate() generate()
} }
/// Makes bincode encode all integer types with a variable integer encoding. /// Makes bincode encode all integer types with a variable integer encoding.
@ -142,8 +148,8 @@ impl<E, I, A, L> Configuration<E, I, A, L> {
/// ///
/// Note that u256 and the like are unsupported by this format; if and when they are added to the /// Note that u256 and the like are unsupported by this format; if and when they are added to the
/// language, they may be supported via the extension point given by the 255 byte. /// language, they may be supported via the extension point given by the 255 byte.
pub const fn with_variable_int_encoding(self) -> Configuration<E, Varint, A> { pub const fn with_variable_int_encoding(self) -> Configuration<E, Varint, A, L> {
Self::generate() generate()
} }
/// Fixed-size integer encoding. /// Fixed-size integer encoding.
@ -151,28 +157,28 @@ impl<E, I, A, L> Configuration<E, I, A, L> {
/// * Fixed size integers are encoded directly /// * Fixed size integers are encoded directly
/// * Enum discriminants are encoded as u32 /// * Enum discriminants are encoded as u32
/// * Lengths and usize are encoded as u64 /// * Lengths and usize are encoded as u64
pub const fn with_fixed_int_encoding(self) -> Configuration<E, Fixint, A> { pub const fn with_fixed_int_encoding(self) -> Configuration<E, Fixint, A, L> {
Self::generate() generate()
} }
/// Skip writing the length of fixed size arrays (`[u8; N]`) before writing the array /// Skip writing the length of fixed size arrays (`[u8; N]`) before writing the array
pub const fn skip_fixed_array_length(self) -> Configuration<E, I, SkipFixedArrayLength> { pub const fn skip_fixed_array_length(self) -> Configuration<E, I, SkipFixedArrayLength, L> {
Self::generate() generate()
} }
/// Write the length of fixed size arrays (`[u8; N]`) before writing the array /// Write the length of fixed size arrays (`[u8; N]`) before writing the array
pub const fn write_fixed_array_length(self) -> Configuration<E, I, WriteFixedArrayLength> { pub const fn write_fixed_array_length(self) -> Configuration<E, I, WriteFixedArrayLength, L> {
Self::generate() generate()
} }
/// Sets the byte limit to `limit`. /// Sets the byte limit to `limit`.
pub const fn with_limit<const N: usize>(self) -> Configuration<E, I, A, Limit<N>> { pub const fn with_limit<const N: usize>(self) -> Configuration<E, I, A, Limit<N>> {
Self::generate() generate()
} }
/// Clear the byte limit. /// Clear the byte limit.
pub const fn with_no_limit(self) -> Configuration<E, I, A, NoLimit> { pub const fn with_no_limit(self) -> Configuration<E, I, A, NoLimit> {
Self::generate() generate()
} }
} }

View File

@ -16,8 +16,7 @@ use crate::{config::Config, error::DecodeError, utils::Sealed};
/// # let slice: &[u8] = &[0, 0, 0, 0]; /// # let slice: &[u8] = &[0, 0, 0, 0];
/// # let some_reader = bincode::de::read::SliceReader::new(slice); /// # let some_reader = bincode::de::read::SliceReader::new(slice);
/// use bincode::de::{DecoderImpl, Decode}; /// use bincode::de::{DecoderImpl, Decode};
/// use bincode::config; /// let mut decoder = DecoderImpl::new(some_reader, bincode::config::standard());
/// let mut decoder = DecoderImpl::new(some_reader, config::Configuration::standard());
/// // this u32 can be any Decode /// // this u32 can be any Decode
/// let value = u32::decode(&mut decoder).unwrap(); /// let value = u32::decode(&mut decoder).unwrap();
/// ``` /// ```

View File

@ -11,9 +11,9 @@ use crate::{config::Config, utils::Sealed};
/// ///
/// ``` /// ```
/// # use bincode::enc::{write::SliceWriter, EncoderImpl, Encode}; /// # use bincode::enc::{write::SliceWriter, EncoderImpl, Encode};
/// # use bincode::config::{self, Config};
/// # let config = config::Configuration::standard().with_fixed_int_encoding().with_big_endian();
/// let slice: &mut [u8] = &mut [0, 0, 0, 0]; /// let slice: &mut [u8] = &mut [0, 0, 0, 0];
/// let config = bincode::config::legacy().with_big_endian();
///
/// let mut encoder = EncoderImpl::new(SliceWriter::new(slice), config); /// let mut encoder = EncoderImpl::new(SliceWriter::new(slice), config);
/// // this u32 can be any Encodable /// // this u32 can be any Encodable
/// 5u32.encode(&mut encoder).unwrap(); /// 5u32.encode(&mut encoder).unwrap();

View File

@ -24,8 +24,6 @@
//! # Example //! # Example
//! //!
//! ```rust //! ```rust
//! use bincode::config::Configuration;
//!
//! let mut slice = [0u8; 100]; //! let mut slice = [0u8; 100];
//! //!
//! // You can encode any type that implements `enc::Encode`. //! // You can encode any type that implements `enc::Encode`.
@ -41,7 +39,7 @@
//! let length = bincode::encode_into_slice( //! let length = bincode::encode_into_slice(
//! input, //! input,
//! &mut slice, //! &mut slice,
//! Configuration::standard() //! bincode::config::standard()
//! ).unwrap(); //! ).unwrap();
//! //!
//! let slice = &slice[..length]; //! let slice = &slice[..length];
@ -49,7 +47,7 @@
//! //!
//! // Decoding works the same as encoding. //! // Decoding works the same as encoding.
//! // The trait used is `de::Decode`, and can also be automatically implemented with the `derive` feature. //! // The trait used is `de::Decode`, and can also be automatically implemented with the `derive` feature.
//! let decoded: (u8, u32, i128, char, [u8; 4]) = bincode::decode_from_slice(slice, Configuration::standard()).unwrap().0; //! let decoded: (u8, u32, i128, char, [u8; 4]) = bincode::decode_from_slice(slice, bincode::config::standard()).unwrap().0;
//! //!
//! assert_eq!(decoded, input); //! assert_eq!(decoded, input);
//! ``` //! ```

View File

@ -9,7 +9,6 @@ use alloc::collections::*;
use alloc::rc::Rc; use alloc::rc::Rc;
#[cfg(feature = "atomic")] #[cfg(feature = "atomic")]
use alloc::sync::Arc; use alloc::sync::Arc;
use bincode::config::Configuration;
use utils::{the_same, the_same_with_comparer}; use utils::{the_same, the_same_with_comparer};
struct Foo { struct Foo {
@ -41,11 +40,11 @@ impl bincode::Decode for Foo {
#[test] #[test]
fn test_vec() { fn test_vec() {
let vec = bincode::encode_to_vec(Foo { a: 5, b: 10 }, Configuration::standard()).unwrap(); let vec = bincode::encode_to_vec(Foo { a: 5, b: 10 }, bincode::config::standard()).unwrap();
assert_eq!(vec, &[5, 10]); assert_eq!(vec, &[5, 10]);
let (foo, len): (Foo, usize) = let (foo, len): (Foo, usize) =
bincode::decode_from_slice(&vec, Configuration::standard()).unwrap(); bincode::decode_from_slice(&vec, bincode::config::standard()).unwrap();
assert_eq!(foo.a, 5); assert_eq!(foo.a, 5);
assert_eq!(foo.b, 10); assert_eq!(foo.b, 10);
assert_eq!(len, 2); assert_eq!(len, 2);
@ -101,15 +100,15 @@ fn test_container_limits() {
// for this test we'll create a malformed package of a lot of bytes // for this test we'll create a malformed package of a lot of bytes
let test_cases = &[ let test_cases = &[
// u64::max_value(), should overflow // u64::max_value(), should overflow
bincode::encode_to_vec(u64::max_value(), Configuration::standard()).unwrap(), bincode::encode_to_vec(u64::max_value(), bincode::config::standard()).unwrap(),
// A high value which doesn't overflow, but exceeds the decode limit // A high value which doesn't overflow, but exceeds the decode limit
bincode::encode_to_vec(DECODE_LIMIT as u64, Configuration::standard()).unwrap(), bincode::encode_to_vec(DECODE_LIMIT as u64, bincode::config::standard()).unwrap(),
]; ];
fn validate_fail<T: Decode + core::fmt::Debug>(slice: &[u8]) { fn validate_fail<T: Decode + core::fmt::Debug>(slice: &[u8]) {
let result = bincode::decode_from_slice::<T, _>( let result = bincode::decode_from_slice::<T, _>(
slice, slice,
Configuration::standard().with_limit::<DECODE_LIMIT>(), bincode::config::standard().with_limit::<DECODE_LIMIT>(),
); );
assert_eq!(result.unwrap_err(), DecodeError::LimitExceeded); assert_eq!(result.unwrap_err(), DecodeError::LimitExceeded);

View File

@ -1,6 +1,5 @@
mod utils; mod utils;
use bincode::config::Configuration;
use core::cell::{Cell, RefCell}; use core::cell::{Cell, RefCell};
use core::ops::Bound; use core::ops::Bound;
use core::time::Duration; use core::time::Duration;
@ -120,7 +119,7 @@ fn test_refcell_already_borrowed() {
let _mutable_guard = cell.borrow_mut(); let _mutable_guard = cell.borrow_mut();
// now try to encode it // now try to encode it
let mut slice = [0u8; 10]; let mut slice = [0u8; 10];
let result = bincode::encode_into_slice(&cell, &mut slice, Configuration::standard()) let result = bincode::encode_into_slice(&cell, &mut slice, bincode::config::standard())
.expect_err("Encoding a borrowed refcell should fail"); .expect_err("Encoding a borrowed refcell should fail");
match result { match result {
@ -133,11 +132,11 @@ fn test_refcell_already_borrowed() {
fn test_slice() { fn test_slice() {
let mut buffer = [0u8; 32]; let mut buffer = [0u8; 32];
let input: &[u8] = &[1, 2, 3, 4, 5, 6, 7]; let input: &[u8] = &[1, 2, 3, 4, 5, 6, 7];
bincode::encode_into_slice(input, &mut buffer, Configuration::standard()).unwrap(); bincode::encode_into_slice(input, &mut buffer, bincode::config::standard()).unwrap();
assert_eq!(&buffer[..8], &[7, 1, 2, 3, 4, 5, 6, 7]); assert_eq!(&buffer[..8], &[7, 1, 2, 3, 4, 5, 6, 7]);
let (output, len): (&[u8], usize) = let (output, len): (&[u8], usize) =
bincode::decode_from_slice(&mut buffer[..8], Configuration::standard()).unwrap(); bincode::decode_from_slice(&mut buffer[..8], bincode::config::standard()).unwrap();
assert_eq!(input, output); assert_eq!(input, output);
assert_eq!(len, 8); assert_eq!(len, 8);
} }
@ -146,21 +145,21 @@ fn test_slice() {
fn test_option_slice() { fn test_option_slice() {
let mut buffer = [0u8; 32]; let mut buffer = [0u8; 32];
let input: Option<&[u8]> = Some(&[1, 2, 3, 4, 5, 6, 7]); let input: Option<&[u8]> = Some(&[1, 2, 3, 4, 5, 6, 7]);
let n = bincode::encode_into_slice(input, &mut buffer, Configuration::standard()).unwrap(); let n = bincode::encode_into_slice(input, &mut buffer, bincode::config::standard()).unwrap();
assert_eq!(&buffer[..n], &[1, 7, 1, 2, 3, 4, 5, 6, 7]); assert_eq!(&buffer[..n], &[1, 7, 1, 2, 3, 4, 5, 6, 7]);
let (output, len): (Option<&[u8]>, usize) = let (output, len): (Option<&[u8]>, usize) =
bincode::decode_from_slice(&buffer[..n], Configuration::standard()).unwrap(); bincode::decode_from_slice(&buffer[..n], bincode::config::standard()).unwrap();
assert_eq!(input, output); assert_eq!(input, output);
assert_eq!(len, n); assert_eq!(len, n);
let mut buffer = [0u8; 32]; let mut buffer = [0u8; 32];
let input: Option<&[u8]> = None; let input: Option<&[u8]> = None;
let n = bincode::encode_into_slice(input, &mut buffer, Configuration::standard()).unwrap(); let n = bincode::encode_into_slice(input, &mut buffer, bincode::config::standard()).unwrap();
assert_eq!(&buffer[..n], &[0]); assert_eq!(&buffer[..n], &[0]);
let (output, len): (Option<&[u8]>, usize) = let (output, len): (Option<&[u8]>, usize) =
bincode::decode_from_slice(&buffer[..n], Configuration::standard()).unwrap(); bincode::decode_from_slice(&buffer[..n], bincode::config::standard()).unwrap();
assert_eq!(input, output); assert_eq!(input, output);
assert_eq!(len, n); assert_eq!(len, n);
} }
@ -169,14 +168,14 @@ fn test_option_slice() {
fn test_str() { fn test_str() {
let mut buffer = [0u8; 32]; let mut buffer = [0u8; 32];
let input: &str = "Hello world"; let input: &str = "Hello world";
bincode::encode_into_slice(input, &mut buffer, Configuration::standard()).unwrap(); bincode::encode_into_slice(input, &mut buffer, bincode::config::standard()).unwrap();
assert_eq!( assert_eq!(
&buffer[..12], &buffer[..12],
&[11, 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] &[11, 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
); );
let (output, len): (&str, usize) = let (output, len): (&str, usize) =
bincode::decode_from_slice(&mut buffer[..12], Configuration::standard()).unwrap(); bincode::decode_from_slice(&mut buffer[..12], bincode::config::standard()).unwrap();
assert_eq!(input, output); assert_eq!(input, output);
assert_eq!(len, 12); assert_eq!(len, 12);
} }
@ -185,24 +184,24 @@ fn test_str() {
fn test_option_str() { fn test_option_str() {
let mut buffer = [0u8; 32]; let mut buffer = [0u8; 32];
let input: Option<&str> = Some("Hello world"); let input: Option<&str> = Some("Hello world");
let n = bincode::encode_into_slice(input, &mut buffer, Configuration::standard()).unwrap(); let n = bincode::encode_into_slice(input, &mut buffer, bincode::config::standard()).unwrap();
assert_eq!( assert_eq!(
&buffer[..n], &buffer[..n],
&[1, 11, 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] &[1, 11, 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
); );
let (output, len): (Option<&str>, usize) = let (output, len): (Option<&str>, usize) =
bincode::decode_from_slice(&buffer[..n], Configuration::standard()).unwrap(); bincode::decode_from_slice(&buffer[..n], bincode::config::standard()).unwrap();
assert_eq!(input, output); assert_eq!(input, output);
assert_eq!(len, n); assert_eq!(len, n);
let mut buffer = [0u8; 32]; let mut buffer = [0u8; 32];
let input: Option<&str> = None; let input: Option<&str> = None;
let n = bincode::encode_into_slice(input, &mut buffer, Configuration::standard()).unwrap(); let n = bincode::encode_into_slice(input, &mut buffer, bincode::config::standard()).unwrap();
assert_eq!(&buffer[..n], &[0]); assert_eq!(&buffer[..n], &[0]);
let (output, len): (Option<&str>, usize) = let (output, len): (Option<&str>, usize) =
bincode::decode_from_slice(&buffer[..n], Configuration::standard()).unwrap(); bincode::decode_from_slice(&buffer[..n], bincode::config::standard()).unwrap();
assert_eq!(input, output); assert_eq!(input, output);
assert_eq!(len, n); assert_eq!(len, n);
} }
@ -211,11 +210,11 @@ fn test_option_str() {
fn test_array() { fn test_array() {
let mut buffer = [0u8; 32]; let mut buffer = [0u8; 32];
let input: [u8; 10] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]; let input: [u8; 10] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
bincode::encode_into_slice(input, &mut buffer, Configuration::standard()).unwrap(); bincode::encode_into_slice(input, &mut buffer, bincode::config::standard()).unwrap();
assert_eq!(&buffer[..10], &[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]); assert_eq!(&buffer[..10], &[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]);
let (output, len): ([u8; 10], usize) = let (output, len): ([u8; 10], usize) =
bincode::decode_from_slice(&mut buffer[..10], Configuration::standard()).unwrap(); bincode::decode_from_slice(&mut buffer[..10], bincode::config::standard()).unwrap();
assert_eq!(input, output); assert_eq!(input, output);
assert_eq!(len, 10); assert_eq!(len, 10);
} }
@ -224,11 +223,15 @@ fn test_array() {
fn test_duration_out_of_range() { fn test_duration_out_of_range() {
let mut input = [0u8; 14]; let mut input = [0u8; 14];
bincode::encode_into_slice(&(u64::MAX, u32::MAX), &mut input, Configuration::standard()) bincode::encode_into_slice(
&(u64::MAX, u32::MAX),
&mut input,
bincode::config::standard(),
)
.unwrap(); .unwrap();
let result: Result<(std::time::Duration, usize), _> = let result: Result<(std::time::Duration, usize), _> =
bincode::decode_from_slice(&mut input, Configuration::standard()); bincode::decode_from_slice(&mut input, bincode::config::standard());
assert_eq!( assert_eq!(
result.unwrap_err(), result.unwrap_err(),
@ -246,12 +249,12 @@ fn test_duration_wrapping() {
bincode::encode_into_slice( bincode::encode_into_slice(
&(u64::MAX - 4, u32::MAX), &(u64::MAX - 4, u32::MAX),
&mut input, &mut input,
Configuration::standard(), bincode::config::standard(),
) )
.unwrap(); .unwrap();
let (result, _): (std::time::Duration, _) = let (result, _): (std::time::Duration, _) =
bincode::decode_from_slice(&mut input, Configuration::standard()).unwrap(); bincode::decode_from_slice(&mut input, bincode::config::standard()).unwrap();
assert_eq!(result.as_secs(), u64::MAX); assert_eq!(result.as_secs(), u64::MAX);

View File

@ -1,7 +1,5 @@
#![cfg(feature = "derive")] #![cfg(feature = "derive")]
use bincode::config::Configuration;
#[derive(bincode::Encode, PartialEq, Debug)] #[derive(bincode::Encode, PartialEq, Debug)]
pub(crate) struct Test<T> { pub(crate) struct Test<T> {
a: T, a: T,
@ -50,7 +48,7 @@ fn test_encode() {
}; };
let mut slice = [0u8; 1024]; let mut slice = [0u8; 1024];
let bytes_written = let bytes_written =
bincode::encode_into_slice(start, &mut slice, Configuration::standard()).unwrap(); bincode::encode_into_slice(start, &mut slice, bincode::config::standard()).unwrap();
assert_eq!(bytes_written, 3); assert_eq!(bytes_written, 3);
assert_eq!(&slice[..bytes_written], &[10, 10, 20]); assert_eq!(&slice[..bytes_written], &[10, 10, 20]);
} }
@ -64,7 +62,7 @@ fn test_decode() {
}; };
let slice = [5, 10, 251, 0, 4]; let slice = [5, 10, 251, 0, 4];
let (result, len): (Test2<u32>, usize) = let (result, len): (Test2<u32>, usize) =
bincode::decode_from_slice(&slice, Configuration::standard()).unwrap(); bincode::decode_from_slice(&slice, bincode::config::standard()).unwrap();
assert_eq!(result, start); assert_eq!(result, start);
assert_eq!(len, 5); assert_eq!(len, 5);
} }
@ -79,10 +77,10 @@ fn test_encode_decode_str() {
}; };
let mut slice = [0u8; 100]; let mut slice = [0u8; 100];
let len = bincode::encode_into_slice(&start, &mut slice, Configuration::standard()).unwrap(); let len = bincode::encode_into_slice(&start, &mut slice, bincode::config::standard()).unwrap();
assert_eq!(len, 21); assert_eq!(len, 21);
let (end, len): (Test3, usize) = let (end, len): (Test3, usize) =
bincode::decode_from_slice(&slice[..len], Configuration::standard()).unwrap(); bincode::decode_from_slice(&slice[..len], bincode::config::standard()).unwrap();
assert_eq!(end, start); assert_eq!(end, start);
assert_eq!(len, 21); assert_eq!(len, 21);
} }
@ -92,7 +90,7 @@ fn test_encode_tuple() {
let start = TestTupleStruct(5, 10, 1024); let start = TestTupleStruct(5, 10, 1024);
let mut slice = [0u8; 1024]; let mut slice = [0u8; 1024];
let bytes_written = let bytes_written =
bincode::encode_into_slice(start, &mut slice, Configuration::standard()).unwrap(); bincode::encode_into_slice(start, &mut slice, bincode::config::standard()).unwrap();
assert_eq!(bytes_written, 5); assert_eq!(bytes_written, 5);
assert_eq!(&slice[..bytes_written], &[5, 10, 251, 0, 4]); assert_eq!(&slice[..bytes_written], &[5, 10, 251, 0, 4]);
} }
@ -102,7 +100,7 @@ fn test_decode_tuple() {
let start = TestTupleStruct(5, 10, 1024); let start = TestTupleStruct(5, 10, 1024);
let mut slice = [5, 10, 251, 0, 4]; let mut slice = [5, 10, 251, 0, 4];
let (result, len): (TestTupleStruct, usize) = let (result, len): (TestTupleStruct, usize) =
bincode::decode_from_slice(&mut slice, Configuration::standard()).unwrap(); bincode::decode_from_slice(&mut slice, bincode::config::standard()).unwrap();
assert_eq!(result, start); assert_eq!(result, start);
assert_eq!(len, 5); assert_eq!(len, 5);
} }
@ -112,7 +110,7 @@ fn test_encode_enum_struct_variant() {
let start = TestEnum::Bar { name: 5u32 }; let start = TestEnum::Bar { name: 5u32 };
let mut slice = [0u8; 1024]; let mut slice = [0u8; 1024];
let bytes_written = let bytes_written =
bincode::encode_into_slice(start, &mut slice, Configuration::standard()).unwrap(); bincode::encode_into_slice(start, &mut slice, bincode::config::standard()).unwrap();
assert_eq!(bytes_written, 2); assert_eq!(bytes_written, 2);
assert_eq!(&slice[..bytes_written], &[1, 5]); assert_eq!(&slice[..bytes_written], &[1, 5]);
} }
@ -122,7 +120,7 @@ fn test_decode_enum_struct_variant() {
let start = TestEnum::Bar { name: 5u32 }; let start = TestEnum::Bar { name: 5u32 };
let mut slice = [1, 5]; let mut slice = [1, 5];
let (result, len): (TestEnum, usize) = let (result, len): (TestEnum, usize) =
bincode::decode_from_slice(&mut slice, Configuration::standard()).unwrap(); bincode::decode_from_slice(&mut slice, bincode::config::standard()).unwrap();
assert_eq!(result, start); assert_eq!(result, start);
assert_eq!(len, 2); assert_eq!(len, 2);
} }
@ -132,7 +130,7 @@ fn test_encode_enum_tuple_variant() {
let start = TestEnum::Baz(5, 10, 1024); let start = TestEnum::Baz(5, 10, 1024);
let mut slice = [0u8; 1024]; let mut slice = [0u8; 1024];
let bytes_written = let bytes_written =
bincode::encode_into_slice(start, &mut slice, Configuration::standard()).unwrap(); bincode::encode_into_slice(start, &mut slice, bincode::config::standard()).unwrap();
assert_eq!(bytes_written, 6); assert_eq!(bytes_written, 6);
assert_eq!(&slice[..bytes_written], &[2, 5, 10, 251, 0, 4]); assert_eq!(&slice[..bytes_written], &[2, 5, 10, 251, 0, 4]);
} }
@ -142,7 +140,7 @@ fn test_decode_enum_unit_variant() {
let start = TestEnum::Foo; let start = TestEnum::Foo;
let mut slice = [0]; let mut slice = [0];
let (result, len): (TestEnum, usize) = let (result, len): (TestEnum, usize) =
bincode::decode_from_slice(&mut slice, Configuration::standard()).unwrap(); bincode::decode_from_slice(&mut slice, bincode::config::standard()).unwrap();
assert_eq!(result, start); assert_eq!(result, start);
assert_eq!(len, 1); assert_eq!(len, 1);
} }
@ -152,7 +150,7 @@ fn test_encode_enum_unit_variant() {
let start = TestEnum::Foo; let start = TestEnum::Foo;
let mut slice = [0u8; 1024]; let mut slice = [0u8; 1024];
let bytes_written = let bytes_written =
bincode::encode_into_slice(start, &mut slice, Configuration::standard()).unwrap(); bincode::encode_into_slice(start, &mut slice, bincode::config::standard()).unwrap();
assert_eq!(bytes_written, 1); assert_eq!(bytes_written, 1);
assert_eq!(&slice[..bytes_written], &[0]); assert_eq!(&slice[..bytes_written], &[0]);
} }
@ -162,7 +160,7 @@ fn test_decode_enum_tuple_variant() {
let start = TestEnum::Baz(5, 10, 1024); let start = TestEnum::Baz(5, 10, 1024);
let mut slice = [2, 5, 10, 251, 0, 4]; let mut slice = [2, 5, 10, 251, 0, 4];
let (result, len): (TestEnum, usize) = let (result, len): (TestEnum, usize) =
bincode::decode_from_slice(&mut slice, Configuration::standard()).unwrap(); bincode::decode_from_slice(&mut slice, bincode::config::standard()).unwrap();
assert_eq!(result, start); assert_eq!(result, start);
assert_eq!(len, 6); assert_eq!(len, 6);
} }
@ -181,7 +179,7 @@ fn test_c_style_enum() {
fn ser(e: CStyleEnum) -> u8 { fn ser(e: CStyleEnum) -> u8 {
let mut slice = [0u8; 10]; let mut slice = [0u8; 10];
let bytes_written = let bytes_written =
bincode::encode_into_slice(e, &mut slice, Configuration::standard()).unwrap(); bincode::encode_into_slice(e, &mut slice, bincode::config::standard()).unwrap();
assert_eq!(bytes_written, 1); assert_eq!(bytes_written, 1);
slice[0] slice[0]
} }
@ -193,7 +191,7 @@ fn test_c_style_enum() {
assert_eq!(ser(CStyleEnum::E), 6); assert_eq!(ser(CStyleEnum::E), 6);
fn de(num: u8) -> Result<CStyleEnum, bincode::error::DecodeError> { fn de(num: u8) -> Result<CStyleEnum, bincode::error::DecodeError> {
let (result, len) = bincode::decode_from_slice(&[num], Configuration::standard())?; let (result, len) = bincode::decode_from_slice(&[num], bincode::config::standard())?;
assert_eq!(len, 1); assert_eq!(len, 1);
Ok(result) Ok(result)
} }
@ -229,13 +227,13 @@ fn test_macro_newtype() {
for val in [0, 100, usize::MAX] { for val in [0, 100, usize::MAX] {
let mut usize_slice = [0u8; 10]; let mut usize_slice = [0u8; 10];
let usize_len = let usize_len =
bincode::encode_into_slice(val, &mut usize_slice, Configuration::standard()).unwrap(); bincode::encode_into_slice(val, &mut usize_slice, bincode::config::standard()).unwrap();
let mut newtype_slice = [0u8; 10]; let mut newtype_slice = [0u8; 10];
let newtype_len = bincode::encode_into_slice( let newtype_len = bincode::encode_into_slice(
MacroNewType(val), MacroNewType(val),
&mut newtype_slice, &mut newtype_slice,
Configuration::standard(), bincode::config::standard(),
) )
.unwrap(); .unwrap();
@ -244,7 +242,7 @@ fn test_macro_newtype() {
let (newtype, len) = bincode::decode_from_slice::<MacroNewType, _>( let (newtype, len) = bincode::decode_from_slice::<MacroNewType, _>(
&newtype_slice, &newtype_slice,
Configuration::standard(), bincode::config::standard(),
) )
.unwrap(); .unwrap();
assert_eq!(newtype, MacroNewType(val)); assert_eq!(newtype, MacroNewType(val));
@ -261,7 +259,7 @@ pub enum BorrowedEmptyEnum {}
#[test] #[test]
fn test_empty_enum_decode() { fn test_empty_enum_decode() {
let err = let err =
bincode::decode_from_slice::<EmptyEnum, _>(&[], Configuration::standard()).unwrap_err(); bincode::decode_from_slice::<EmptyEnum, _>(&[], bincode::config::standard()).unwrap_err();
assert_eq!( assert_eq!(
err, err,
bincode::error::DecodeError::EmptyEnum { bincode::error::DecodeError::EmptyEnum {

View File

@ -2,7 +2,7 @@
extern crate std; extern crate std;
use bincode::{config::Configuration, Decode, Encode}; use bincode::{Decode, Encode};
use std::borrow::Cow; use std::borrow::Cow;
use std::string::String; use std::string::String;
@ -24,10 +24,10 @@ fn test() {
let t = T { let t = T {
t: Cow::Borrowed(&u), t: Cow::Borrowed(&u),
}; };
let vec = bincode::encode_to_vec(&t, Configuration::standard()).unwrap(); let vec = bincode::encode_to_vec(&t, bincode::config::standard()).unwrap();
let (decoded, len): (T<String>, usize) = let (decoded, len): (T<String>, usize) =
bincode::decode_from_slice(&vec, Configuration::standard()).unwrap(); bincode::decode_from_slice(&vec, bincode::config::standard()).unwrap();
assert_eq!(t, decoded); assert_eq!(t, decoded);
assert_eq!(len, 12); assert_eq!(len, 12);

View File

@ -9,8 +9,5 @@ struct AllTypes(BTreeMap<u8, AllTypes>);
#[test] #[test]
fn test_issue_459() { fn test_issue_459() {
let _result = bincode::encode_to_vec( let _result = bincode::encode_to_vec(AllTypes(BTreeMap::new()), bincode::config::standard());
AllTypes(BTreeMap::new()),
bincode::config::Configuration::standard(),
);
} }

View File

@ -9,8 +9,6 @@ struct AllTypes(BTreeMap<u8, AllTypes>);
#[test] #[test]
fn test_issue_467() { fn test_issue_467() {
let _result: Result<(AllTypes, _), _> = bincode::decode_from_slice( let _result: Result<(AllTypes, _), _> =
&[], bincode::decode_from_slice(&[], bincode::config::standard().with_limit::<1024>());
bincode::config::Configuration::standard().with_limit::<1024>(),
);
} }

View File

@ -2,7 +2,6 @@
extern crate std; extern crate std;
use bincode::config::Configuration;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use serde_incl::de::DeserializeOwned; use serde_incl::de::DeserializeOwned;
use std::collections::HashMap; use std::collections::HashMap;
@ -63,7 +62,7 @@ impl MemCache {
where where
T: Send + Sync + serde_incl::Serialize, T: Send + Sync + serde_incl::Serialize,
{ {
let config = Configuration::standard(); let config = bincode::config::standard();
let mut guard = self.cache.write().unwrap(); let mut guard = self.cache.write().unwrap();
let encoded = bincode::serde::encode_to_vec(&cache_data, config)?; let encoded = bincode::serde::encode_to_vec(&cache_data, config)?;
@ -77,7 +76,7 @@ impl MemCache {
where where
T: Send + Sync + DeserializeOwned, T: Send + Sync + DeserializeOwned,
{ {
let config = Configuration::standard(); let config = bincode::config::standard();
let guard = self.cache.read().unwrap(); let guard = self.cache.read().unwrap();
let cache_item = guard.get(key).unwrap(); let cache_item = guard.get(key).unwrap();
let (decoded, _len): (T, usize) = let (decoded, _len): (T, usize) =

View File

@ -3,7 +3,6 @@
extern crate alloc; extern crate alloc;
use alloc::string::String; use alloc::string::String;
use bincode::config::Configuration;
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, bincode::Encode, bincode::Decode)] #[derive(Serialize, Deserialize, bincode::Encode, bincode::Decode)]
@ -26,10 +25,11 @@ fn test_serde_round_trip() {
// validate bincode working // validate bincode working
let bytes = let bytes =
bincode::encode_to_vec(SerdeRoundtrip { a: 15, b: 15 }, Configuration::standard()).unwrap(); bincode::encode_to_vec(SerdeRoundtrip { a: 15, b: 15 }, bincode::config::standard())
.unwrap();
assert_eq!(bytes, &[15, 15]); assert_eq!(bytes, &[15, 15]);
let (result, len): (SerdeRoundtrip, usize) = let (result, len): (SerdeRoundtrip, usize) =
bincode::decode_from_slice(&bytes, Configuration::standard()).unwrap(); bincode::decode_from_slice(&bytes, bincode::config::standard()).unwrap();
assert_eq!(result.a, 15); assert_eq!(result.a, 15);
assert_eq!(result.b, 15); assert_eq!(result.b, 15);
assert_eq!(len, 2); assert_eq!(len, 2);
@ -62,16 +62,16 @@ fn test_serialize_deserialize_borrowed_data() {
let mut result = [0u8; 20]; let mut result = [0u8; 20];
let len = let len =
bincode::serde::encode_to_slice(&input, &mut result, Configuration::standard()).unwrap(); bincode::serde::encode_to_slice(&input, &mut result, bincode::config::standard()).unwrap();
let result = &result[..len]; let result = &result[..len];
assert_eq!(result, expected); assert_eq!(result, expected);
let result = bincode::serde::encode_to_vec(&input, Configuration::standard()).unwrap(); let result = bincode::serde::encode_to_vec(&input, bincode::config::standard()).unwrap();
assert_eq!(result, expected); assert_eq!(result, expected);
let output: SerdeWithBorrowedData = let output: SerdeWithBorrowedData =
bincode::serde::decode_borrowed_from_slice(&result, Configuration::standard()).unwrap(); bincode::serde::decode_borrowed_from_slice(&result, bincode::config::standard()).unwrap();
assert_eq!( assert_eq!(
SerdeWithBorrowedData { SerdeWithBorrowedData {
b: 0, // remember: b is skipped b: 0, // remember: b is skipped
@ -108,16 +108,16 @@ fn test_serialize_deserialize_owned_data() {
let mut result = [0u8; 20]; let mut result = [0u8; 20];
let len = let len =
bincode::serde::encode_to_slice(&input, &mut result, Configuration::standard()).unwrap(); bincode::serde::encode_to_slice(&input, &mut result, bincode::config::standard()).unwrap();
let result = &result[..len]; let result = &result[..len];
assert_eq!(result, expected); assert_eq!(result, expected);
let result = bincode::serde::encode_to_vec(&input, Configuration::standard()).unwrap(); let result = bincode::serde::encode_to_vec(&input, bincode::config::standard()).unwrap();
assert_eq!(result, expected); assert_eq!(result, expected);
let (output, len): (SerdeWithOwnedData, usize) = let (output, len): (SerdeWithOwnedData, usize) =
bincode::serde::decode_from_slice(&result, Configuration::standard()).unwrap(); bincode::serde::decode_from_slice(&result, bincode::config::standard()).unwrap();
assert_eq!( assert_eq!(
SerdeWithOwnedData { SerdeWithOwnedData {
b: 0, // remember: b is skipped b: 0, // remember: b is skipped
@ -130,7 +130,7 @@ fn test_serialize_deserialize_owned_data() {
#[cfg(feature = "derive")] #[cfg(feature = "derive")]
mod derive { mod derive {
use bincode::{config::Configuration, Decode, Encode}; use bincode::{Decode, Encode};
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, PartialEq, Debug)] #[derive(Serialize, Deserialize, PartialEq, Debug)]
@ -161,12 +161,12 @@ mod derive {
T: bincode::Encode + bincode::Decode + PartialEq + core::fmt::Debug, T: bincode::Encode + bincode::Decode + PartialEq + core::fmt::Debug,
{ {
let mut slice = [0u8; 100]; let mut slice = [0u8; 100];
let len = let len = bincode::encode_into_slice(&start, &mut slice, bincode::config::standard())
bincode::encode_into_slice(&start, &mut slice, Configuration::standard()).unwrap(); .unwrap();
assert_eq!(len, expected_len); assert_eq!(len, expected_len);
let slice = &slice[..len]; let slice = &slice[..len];
let (result, len): (T, usize) = let (result, len): (T, usize) =
bincode::decode_from_slice(&slice, Configuration::standard()).unwrap(); bincode::decode_from_slice(&slice, bincode::config::standard()).unwrap();
assert_eq!(start, result); assert_eq!(start, result);
assert_eq!(len, expected_len); assert_eq!(len, expected_len);

View File

@ -2,7 +2,6 @@
mod utils; mod utils;
use bincode::config::Configuration;
use std::{ use std::{
ffi::{CStr, CString}, ffi::{CStr, CString},
io::{Cursor, Seek, SeekFrom}, io::{Cursor, Seek, SeekFrom},
@ -44,7 +43,7 @@ impl bincode::Decode for Foo {
#[test] #[test]
fn test_std_cursor() { fn test_std_cursor() {
let mut cursor = Cursor::<&[u8]>::new(&[5, 10]); let mut cursor = Cursor::<&[u8]>::new(&[5, 10]);
let foo: Foo = bincode::decode_from_std_read(&mut cursor, Configuration::standard()).unwrap(); let foo: Foo = bincode::decode_from_std_read(&mut cursor, bincode::config::standard()).unwrap();
assert_eq!(foo.a, 5); assert_eq!(foo.a, 5);
assert_eq!(foo.b, 10); assert_eq!(foo.b, 10);
@ -54,13 +53,16 @@ fn test_std_cursor() {
fn test_std_file() { fn test_std_file() {
let mut file = tempfile::tempfile().expect("Could not create temp file"); let mut file = tempfile::tempfile().expect("Could not create temp file");
let bytes_written = let bytes_written = bincode::encode_into_std_write(
bincode::encode_into_std_write(Foo { a: 30, b: 50 }, &mut file, Configuration::standard()) Foo { a: 30, b: 50 },
&mut file,
bincode::config::standard(),
)
.unwrap(); .unwrap();
assert_eq!(bytes_written, 2); assert_eq!(bytes_written, 2);
file.seek(SeekFrom::Start(0)).unwrap(); file.seek(SeekFrom::Start(0)).unwrap();
let foo: Foo = bincode::decode_from_std_read(&mut file, Configuration::standard()).unwrap(); let foo: Foo = bincode::decode_from_std_read(&mut file, bincode::config::standard()).unwrap();
assert_eq!(foo.a, 30); assert_eq!(foo.a, 30);
assert_eq!(foo.b, 50); assert_eq!(foo.b, 50);
@ -100,7 +102,7 @@ fn test_std_commons() {
the_same(map); the_same(map);
// Borrowed values // Borrowed values
let config = bincode::config::Configuration::standard(); let config = bincode::config::standard();
let mut buffer = [0u8; 1024]; let mut buffer = [0u8; 1024];
// &CStr // &CStr
@ -125,7 +127,7 @@ fn test_system_time_out_of_range() {
let mut input = [0xfd, 0x90, 0x0c, 0xfd, 0xfd, 0x90, 0x0c, 0xfd, 0x90, 0x90]; let mut input = [0xfd, 0x90, 0x0c, 0xfd, 0xfd, 0x90, 0x0c, 0xfd, 0x90, 0x90];
let result: Result<(std::time::SystemTime, usize), _> = let result: Result<(std::time::SystemTime, usize), _> =
bincode::decode_from_slice(&mut input, Configuration::standard()); bincode::decode_from_slice(&mut input, bincode::config::standard());
assert_eq!( assert_eq!(
result.unwrap_err(), result.unwrap_err(),

View File

@ -1,10 +1,9 @@
use bincode::config::{self, Config};
use core::fmt::Debug; use core::fmt::Debug;
fn the_same_with_config<V, C, CMP>(element: &V, config: C, cmp: CMP) fn the_same_with_config<V, C, CMP>(element: &V, config: C, cmp: CMP)
where where
V: bincode::enc::Encode + bincode::Decode + Debug + 'static, V: bincode::enc::Encode + bincode::Decode + Debug + 'static,
C: Config, C: bincode::config::Config,
CMP: Fn(&V, &V) -> bool, CMP: Fn(&V, &V) -> bool,
{ {
let mut buffer = [0u8; 2048]; let mut buffer = [0u8; 2048];
@ -36,7 +35,7 @@ where
// A matrix of each different config option possible // A matrix of each different config option possible
the_same_with_config( the_same_with_config(
&element, &element,
config::Configuration::standard() bincode::config::standard()
.with_little_endian() .with_little_endian()
.with_fixed_int_encoding() .with_fixed_int_encoding()
.skip_fixed_array_length(), .skip_fixed_array_length(),
@ -44,7 +43,7 @@ where
); );
the_same_with_config( the_same_with_config(
&element, &element,
config::Configuration::standard() bincode::config::standard()
.with_big_endian() .with_big_endian()
.with_fixed_int_encoding() .with_fixed_int_encoding()
.skip_fixed_array_length(), .skip_fixed_array_length(),
@ -52,7 +51,7 @@ where
); );
the_same_with_config( the_same_with_config(
&element, &element,
config::Configuration::standard() bincode::config::standard()
.with_little_endian() .with_little_endian()
.with_variable_int_encoding() .with_variable_int_encoding()
.skip_fixed_array_length(), .skip_fixed_array_length(),
@ -60,7 +59,7 @@ where
); );
the_same_with_config( the_same_with_config(
&element, &element,
config::Configuration::standard() bincode::config::standard()
.with_big_endian() .with_big_endian()
.with_variable_int_encoding() .with_variable_int_encoding()
.skip_fixed_array_length(), .skip_fixed_array_length(),
@ -68,7 +67,7 @@ where
); );
the_same_with_config( the_same_with_config(
&element, &element,
config::Configuration::standard() bincode::config::standard()
.with_little_endian() .with_little_endian()
.with_fixed_int_encoding() .with_fixed_int_encoding()
.write_fixed_array_length(), .write_fixed_array_length(),
@ -76,7 +75,7 @@ where
); );
the_same_with_config( the_same_with_config(
&element, &element,
config::Configuration::standard() bincode::config::standard()
.with_big_endian() .with_big_endian()
.with_fixed_int_encoding() .with_fixed_int_encoding()
.write_fixed_array_length(), .write_fixed_array_length(),
@ -84,7 +83,7 @@ where
); );
the_same_with_config( the_same_with_config(
&element, &element,
config::Configuration::standard() bincode::config::standard()
.with_little_endian() .with_little_endian()
.with_variable_int_encoding() .with_variable_int_encoding()
.write_fixed_array_length(), .write_fixed_array_length(),
@ -92,7 +91,7 @@ where
); );
the_same_with_config( the_same_with_config(
&element, &element,
config::Configuration::standard() bincode::config::standard()
.with_big_endian() .with_big_endian()
.with_variable_int_encoding() .with_variable_int_encoding()
.write_fixed_array_length(), .write_fixed_array_length(),