prep branch for 2.0 work (#379)

* prep branch for 2.0 work

* switch to 2018 edition

* fix clippy issues

* fix tests

* fix warnings

* fix formatting
This commit is contained in:
Lena Hellström 2021-04-08 14:54:31 +02:00 committed by GitHub
parent 810086e473
commit e39a047b4b
15 changed files with 176 additions and 494 deletions

View File

@ -25,7 +25,7 @@
"stable",
"beta",
"nightly",
"1.18.0"
"1.41.0"
]
}
},
@ -57,7 +57,7 @@
"args": "--examples"
},
"name": "Check examples",
"if": "matrix.rust != '1.18.0'"
"if": "matrix.rust != '1.41.0'"
}
]
},

View File

@ -1,6 +1,6 @@
[package]
name = "bincode"
version = "1.3.1" # remember to update html_root_url
version = "2.0.0-dev" # remember to update html_root_url
authors = ["Ty Overby <ty@pre-alpha.com>", "Francesco Mazzoli <f@mazzo.li>", "David Tolnay <dtolnay@gmail.com>", "Zoey Riordan <zoey@dos.cafe>"]
exclude = ["logo.png", "examples/*", ".gitignore", ".travis.yml"]
@ -15,20 +15,11 @@ keywords = ["binary", "encode", "decode", "serialize", "deserialize"]
license = "MIT"
description = "A binary serialization / deserialization strategy that uses Serde for transforming structs into bytes and vice versa!"
edition = "2018"
[dependencies]
byteorder = ">=1.3.0, < 1.4.0"
byteorder = "1.3.0"
serde = "1.0.63"
[dev-dependencies]
serde_bytes = "0.11"
serde_derive = "1.0.27"
[features]
# This feature is no longer used and is DEPRECATED. This crate relies on the
# serde `serde_if_integer128` macro to enable i128 support for Rust compilers
# and targets that support it. The feature will be removed if and when a new
# major version is released.
i128 = []
[badges]
travis-ci = { repository = "servo/bincode" }

View File

@ -5,7 +5,7 @@
![CI](https://github.com/servo/bincode/workflows/CI/badge.svg)
[![](https://meritbadge.herokuapp.com/bincode)](https://crates.io/crates/bincode)
[![](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![](https://img.shields.io/badge/bincode-rustc_1.18+-lightgray.svg)](https://blog.rust-lang.org/2017/06/08/Rust-1.18.html)
[![](https://img.shields.io/badge/bincode-rustc_1.41.1+-lightgray.svg)](https://blog.rust-lang.org/2020/06/18/Rust.1.44.1.html)
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
@ -109,4 +109,4 @@ maximum size limit. Malicious inputs will fail upon deserialization.
### What is Bincode's MSRV (minimum supported Rust version)?
Bincode 1.0 maintains support for rust 1.18.0. Any changes to this are considered a breaking change for semver purposes.
Bincode 2.0 maintains support for rust 1.41.1. Any changes to this are considered a breaking change for semver purposes.

View File

@ -2,8 +2,8 @@ use std::io::Write;
use std::mem::size_of;
use super::Options;
use de::read::BincodeRead;
use error::{ErrorKind, Result};
use crate::de::read::BincodeRead;
use crate::error::{ErrorKind, Result};
pub trait IntEncoding {
/// Gets the size (in bytes) that a value would be serialized to.
@ -28,90 +28,90 @@ pub trait IntEncoding {
/// Serializes a sequence length.
#[inline(always)]
fn serialize_len<W: Write, O: Options>(
ser: &mut ::ser::Serializer<W, O>,
ser: &mut crate::ser::Serializer<W, O>,
len: usize,
) -> Result<()> {
Self::serialize_u64(ser, len as u64)
}
fn serialize_u16<W: Write, O: Options>(
ser: &mut ::ser::Serializer<W, O>,
ser: &mut crate::ser::Serializer<W, O>,
val: u16,
) -> Result<()>;
fn serialize_u32<W: Write, O: Options>(
ser: &mut ::ser::Serializer<W, O>,
ser: &mut crate::ser::Serializer<W, O>,
val: u32,
) -> Result<()>;
fn serialize_u64<W: Write, O: Options>(
ser: &mut ::ser::Serializer<W, O>,
ser: &mut crate::ser::Serializer<W, O>,
val: u64,
) -> Result<()>;
fn serialize_i16<W: Write, O: Options>(
ser: &mut ::ser::Serializer<W, O>,
ser: &mut crate::ser::Serializer<W, O>,
val: i16,
) -> Result<()>;
fn serialize_i32<W: Write, O: Options>(
ser: &mut ::ser::Serializer<W, O>,
ser: &mut crate::ser::Serializer<W, O>,
val: i32,
) -> Result<()>;
fn serialize_i64<W: Write, O: Options>(
ser: &mut ::ser::Serializer<W, O>,
ser: &mut crate::ser::Serializer<W, O>,
val: i64,
) -> Result<()>;
/// Deserializes a sequence length.
#[inline(always)]
fn deserialize_len<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::de::Deserializer<R, O>,
de: &mut crate::de::Deserializer<R, O>,
) -> Result<usize> {
Self::deserialize_u64(de).and_then(cast_u64_to_usize)
}
fn deserialize_u16<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::de::Deserializer<R, O>,
de: &mut crate::de::Deserializer<R, O>,
) -> Result<u16>;
fn deserialize_u32<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::de::Deserializer<R, O>,
de: &mut crate::de::Deserializer<R, O>,
) -> Result<u32>;
fn deserialize_u64<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::de::Deserializer<R, O>,
de: &mut crate::de::Deserializer<R, O>,
) -> Result<u64>;
fn deserialize_i16<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::de::Deserializer<R, O>,
de: &mut crate::de::Deserializer<R, O>,
) -> Result<i16>;
fn deserialize_i32<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::de::Deserializer<R, O>,
de: &mut crate::de::Deserializer<R, O>,
) -> Result<i32>;
fn deserialize_i64<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::de::Deserializer<R, O>,
de: &mut crate::de::Deserializer<R, O>,
) -> Result<i64>;
serde_if_integer128! {
fn u128_size(v: u128) -> u64;
fn i128_size(v: i128) -> u64;
fn serialize_u128<W: Write, O: Options>(
ser: &mut ::Serializer<W, O>,
ser: &mut crate::Serializer<W, O>,
val: u128,
) -> Result<()>;
fn deserialize_u128<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::Deserializer<R, O>,
de: &mut crate::Deserializer<R, O>,
) -> Result<u128>;
fn serialize_i128<W: Write, O: Options>(
ser: &mut ::Serializer<W, O>,
ser: &mut crate::Serializer<W, O>,
val: i128,
) -> Result<()>;
fn deserialize_i128<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::Deserializer<R, O>,
de: &mut crate::Deserializer<R, O>,
) -> Result<i128>;
}
}
@ -221,7 +221,7 @@ impl VarintEncoding {
}
fn serialize_varint<W: Write, O: Options>(
ser: &mut ::ser::Serializer<W, O>,
ser: &mut crate::ser::Serializer<W, O>,
n: u64,
) -> Result<()> {
if n <= SINGLE_BYTE_MAX as u64 {
@ -239,7 +239,7 @@ impl VarintEncoding {
}
fn deserialize_varint<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::de::Deserializer<R, O>,
de: &mut crate::de::Deserializer<R, O>,
) -> Result<u64> {
#[allow(ellipsis_inclusive_range_patterns)]
match de.deserialize_byte()? {
@ -291,7 +291,7 @@ impl VarintEncoding {
}
fn serialize_varint128<W: Write, O: Options>(
ser: &mut ::ser::Serializer<W, O>,
ser: &mut crate::ser::Serializer<W, O>,
n: u128,
) -> Result<()> {
if n <= SINGLE_BYTE_MAX as u128 {
@ -312,7 +312,7 @@ impl VarintEncoding {
}
fn deserialize_varint128<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::de::Deserializer<R, O>,
de: &mut crate::de::Deserializer<R, O>,
) -> Result<u128> {
#[allow(ellipsis_inclusive_range_patterns)]
match de.deserialize_byte()? {
@ -355,65 +355,83 @@ impl IntEncoding for FixintEncoding {
}
#[inline(always)]
fn serialize_u16<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: u16) -> Result<()> {
fn serialize_u16<W: Write, O: Options>(
ser: &mut crate::Serializer<W, O>,
val: u16,
) -> Result<()> {
ser.serialize_literal_u16(val)
}
#[inline(always)]
fn serialize_u32<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: u32) -> Result<()> {
fn serialize_u32<W: Write, O: Options>(
ser: &mut crate::Serializer<W, O>,
val: u32,
) -> Result<()> {
ser.serialize_literal_u32(val)
}
#[inline(always)]
fn serialize_u64<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: u64) -> Result<()> {
fn serialize_u64<W: Write, O: Options>(
ser: &mut crate::Serializer<W, O>,
val: u64,
) -> Result<()> {
ser.serialize_literal_u64(val)
}
#[inline(always)]
fn serialize_i16<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: i16) -> Result<()> {
fn serialize_i16<W: Write, O: Options>(
ser: &mut crate::Serializer<W, O>,
val: i16,
) -> Result<()> {
ser.serialize_literal_u16(val as u16)
}
#[inline(always)]
fn serialize_i32<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: i32) -> Result<()> {
fn serialize_i32<W: Write, O: Options>(
ser: &mut crate::Serializer<W, O>,
val: i32,
) -> Result<()> {
ser.serialize_literal_u32(val as u32)
}
#[inline(always)]
fn serialize_i64<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: i64) -> Result<()> {
fn serialize_i64<W: Write, O: Options>(
ser: &mut crate::Serializer<W, O>,
val: i64,
) -> Result<()> {
ser.serialize_literal_u64(val as u64)
}
#[inline(always)]
fn deserialize_u16<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::Deserializer<R, O>,
de: &mut crate::Deserializer<R, O>,
) -> Result<u16> {
de.deserialize_literal_u16()
}
#[inline(always)]
fn deserialize_u32<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::Deserializer<R, O>,
de: &mut crate::Deserializer<R, O>,
) -> Result<u32> {
de.deserialize_literal_u32()
}
#[inline(always)]
fn deserialize_u64<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::Deserializer<R, O>,
de: &mut crate::Deserializer<R, O>,
) -> Result<u64> {
de.deserialize_literal_u64()
}
#[inline(always)]
fn deserialize_i16<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::Deserializer<R, O>,
de: &mut crate::Deserializer<R, O>,
) -> Result<i16> {
Ok(de.deserialize_literal_u16()? as i16)
}
#[inline(always)]
fn deserialize_i32<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::Deserializer<R, O>,
de: &mut crate::Deserializer<R, O>,
) -> Result<i32> {
Ok(de.deserialize_literal_u32()? as i32)
}
#[inline(always)]
fn deserialize_i64<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::Deserializer<R, O>,
de: &mut crate::Deserializer<R, O>,
) -> Result<i64> {
Ok(de.deserialize_literal_u64()? as i64)
}
@ -430,27 +448,27 @@ impl IntEncoding for FixintEncoding {
#[inline(always)]
fn serialize_u128<W: Write, O: Options>(
ser: &mut ::Serializer<W, O>,
ser: &mut crate::Serializer<W, O>,
val: u128,
) -> Result<()> {
ser.serialize_literal_u128(val)
}
#[inline(always)]
fn serialize_i128<W: Write, O: Options>(
ser: &mut ::Serializer<W, O>,
ser: &mut crate::Serializer<W, O>,
val: i128,
) -> Result<()> {
ser.serialize_literal_u128(val as u128)
}
#[inline(always)]
fn deserialize_u128<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::Deserializer<R, O>,
de: &mut crate::Deserializer<R, O>,
) -> Result<u128> {
de.deserialize_literal_u128()
}
#[inline(always)]
fn deserialize_i128<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::Deserializer<R, O>,
de: &mut crate::Deserializer<R, O>,
) -> Result<i128> {
Ok(de.deserialize_literal_u128()? as i128)
}
@ -485,53 +503,71 @@ impl IntEncoding for VarintEncoding {
}
#[inline(always)]
fn serialize_u16<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: u16) -> Result<()> {
fn serialize_u16<W: Write, O: Options>(
ser: &mut crate::Serializer<W, O>,
val: u16,
) -> Result<()> {
Self::serialize_varint(ser, val as u64)
}
#[inline(always)]
fn serialize_u32<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: u32) -> Result<()> {
fn serialize_u32<W: Write, O: Options>(
ser: &mut crate::Serializer<W, O>,
val: u32,
) -> Result<()> {
Self::serialize_varint(ser, val as u64)
}
#[inline(always)]
fn serialize_u64<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: u64) -> Result<()> {
fn serialize_u64<W: Write, O: Options>(
ser: &mut crate::Serializer<W, O>,
val: u64,
) -> Result<()> {
Self::serialize_varint(ser, val)
}
#[inline(always)]
fn serialize_i16<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: i16) -> Result<()> {
fn serialize_i16<W: Write, O: Options>(
ser: &mut crate::Serializer<W, O>,
val: i16,
) -> Result<()> {
Self::serialize_varint(ser, Self::zigzag_encode(val as i64))
}
#[inline(always)]
fn serialize_i32<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: i32) -> Result<()> {
fn serialize_i32<W: Write, O: Options>(
ser: &mut crate::Serializer<W, O>,
val: i32,
) -> Result<()> {
Self::serialize_varint(ser, Self::zigzag_encode(val as i64))
}
#[inline(always)]
fn serialize_i64<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: i64) -> Result<()> {
fn serialize_i64<W: Write, O: Options>(
ser: &mut crate::Serializer<W, O>,
val: i64,
) -> Result<()> {
Self::serialize_varint(ser, Self::zigzag_encode(val))
}
#[inline(always)]
fn deserialize_u16<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::Deserializer<R, O>,
de: &mut crate::Deserializer<R, O>,
) -> Result<u16> {
Self::deserialize_varint(de).and_then(cast_u64_to_u16)
}
#[inline(always)]
fn deserialize_u32<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::Deserializer<R, O>,
de: &mut crate::Deserializer<R, O>,
) -> Result<u32> {
Self::deserialize_varint(de).and_then(cast_u64_to_u32)
}
#[inline(always)]
fn deserialize_u64<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::Deserializer<R, O>,
de: &mut crate::Deserializer<R, O>,
) -> Result<u64> {
Self::deserialize_varint(de)
}
#[inline(always)]
fn deserialize_i16<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::Deserializer<R, O>,
de: &mut crate::Deserializer<R, O>,
) -> Result<i16> {
Self::deserialize_varint(de)
.map(Self::zigzag_decode)
@ -539,7 +575,7 @@ impl IntEncoding for VarintEncoding {
}
#[inline(always)]
fn deserialize_i32<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::Deserializer<R, O>,
de: &mut crate::Deserializer<R, O>,
) -> Result<i32> {
Self::deserialize_varint(de)
.map(Self::zigzag_decode)
@ -547,7 +583,7 @@ impl IntEncoding for VarintEncoding {
}
#[inline(always)]
fn deserialize_i64<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::Deserializer<R, O>,
de: &mut crate::Deserializer<R, O>,
) -> Result<i64> {
Self::deserialize_varint(de).map(Self::zigzag_decode)
}
@ -563,27 +599,27 @@ impl IntEncoding for VarintEncoding {
}
#[inline(always)]
fn serialize_u128<W: Write, O: Options>(
ser: &mut ::Serializer<W, O>,
ser: &mut crate::Serializer<W, O>,
val: u128,
) -> Result<()> {
Self::serialize_varint128(ser, val)
}
#[inline(always)]
fn serialize_i128<W: Write, O: Options>(
ser: &mut ::Serializer<W, O>,
ser: &mut crate::Serializer<W, O>,
val: i128,
) -> Result<()> {
Self::serialize_varint128(ser, Self::zigzag128_encode(val))
}
#[inline(always)]
fn deserialize_u128<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::Deserializer<R, O>,
de: &mut crate::Deserializer<R, O>,
) -> Result<u128> {
Self::deserialize_varint128(de)
}
#[inline(always)]
fn deserialize_i128<'de, R: BincodeRead<'de>, O: Options>(
de: &mut ::Deserializer<R, O>,
de: &mut crate::Deserializer<R, O>,
) -> Result<i128> {
Self::deserialize_varint128(de).map(Self::zigzag128_decode)
}

View File

@ -1,253 +0,0 @@
use std::io::{Read, Write};
use self::EndianOption::*;
use self::LimitOption::*;
use super::{DefaultOptions, Options};
use de::read::BincodeRead;
use error::Result;
use serde;
/// A configuration builder whose options Bincode will use
/// while serializing and deserializing.
///
/// ### Options
/// Endianness: The endianness with which multi-byte integers will be read/written. *default: little endian*
/// Limit: The maximum number of bytes that will be read/written in a bincode serialize/deserialize. *default: unlimited*
///
/// ### Byte Limit Details
/// The purpose of byte-limiting is to prevent Denial-Of-Service attacks whereby malicious attackers get bincode
/// deserialization to crash your process by allocating too much memory or keeping a connection open for too long.
///
/// When a byte limit is set, bincode will return `Err` on any deserialization that goes over the limit, or any
/// serialization that goes over the limit.
#[derive(Clone, Debug)]
#[deprecated(
since = "1.3.0",
note = "please use the `DefaultOptions`/`Options` system instead"
)]
pub struct Config {
limit: LimitOption,
endian: EndianOption,
}
#[derive(Clone, Copy, Debug)]
enum LimitOption {
Unlimited,
Limited(u64),
}
#[derive(Clone, Copy, Debug)]
enum EndianOption {
Big,
Little,
Native,
}
macro_rules! config_map {
($self:expr, $opts:ident => $call:expr) => {
match ($self.limit, $self.endian) {
(Unlimited, Little) => {
let $opts = DefaultOptions::new()
.with_fixint_encoding()
.allow_trailing_bytes()
.with_no_limit()
.with_little_endian();
$call
}
(Unlimited, Big) => {
let $opts = DefaultOptions::new()
.with_fixint_encoding()
.allow_trailing_bytes()
.with_no_limit()
.with_big_endian();
$call
}
(Unlimited, Native) => {
let $opts = DefaultOptions::new()
.with_fixint_encoding()
.allow_trailing_bytes()
.with_no_limit()
.with_native_endian();
$call
}
(Limited(l), Little) => {
let $opts = DefaultOptions::new()
.with_fixint_encoding()
.allow_trailing_bytes()
.with_limit(l)
.with_little_endian();
$call
}
(Limited(l), Big) => {
let $opts = DefaultOptions::new()
.with_fixint_encoding()
.allow_trailing_bytes()
.with_limit(l)
.with_big_endian();
$call
}
(Limited(l), Native) => {
let $opts = DefaultOptions::new()
.with_fixint_encoding()
.allow_trailing_bytes()
.with_limit(l)
.with_native_endian();
$call
}
}
};
}
impl Config {
#[inline(always)]
pub(crate) fn new() -> Config {
Config {
limit: LimitOption::Unlimited,
endian: EndianOption::Little,
}
}
/// Sets the byte limit to be unlimited.
/// This is the default.
#[inline(always)]
pub fn no_limit(&mut self) -> &mut Self {
self.limit = LimitOption::Unlimited;
self
}
/// Sets the byte limit to `limit`.
#[inline(always)]
pub fn limit(&mut self, limit: u64) -> &mut Self {
self.limit = LimitOption::Limited(limit);
self
}
/// Sets the endianness to little-endian
/// This is the default.
#[inline(always)]
pub fn little_endian(&mut self) -> &mut Self {
self.endian = EndianOption::Little;
self
}
/// Sets the endianness to big-endian
#[inline(always)]
pub fn big_endian(&mut self) -> &mut Self {
self.endian = EndianOption::Big;
self
}
/// Sets the endianness to the the machine-native endianness
#[inline(always)]
pub fn native_endian(&mut self) -> &mut Self {
self.endian = EndianOption::Native;
self
}
/// Serializes a serializable object into a `Vec` of bytes using this configuration
#[inline(always)]
pub fn serialize<T: ?Sized + serde::Serialize>(&self, t: &T) -> Result<Vec<u8>> {
config_map!(self, opts => ::internal::serialize(t, opts))
}
/// Returns the size that an object would be if serialized using Bincode with this configuration
#[inline(always)]
pub fn serialized_size<T: ?Sized + serde::Serialize>(&self, t: &T) -> Result<u64> {
config_map!(self, opts => ::internal::serialized_size(t, opts))
}
/// Serializes an object directly into a `Writer` using this configuration
///
/// If the serialization would take more bytes than allowed by the size limit, an error
/// is returned and *no bytes* will be written into the `Writer`
#[inline(always)]
pub fn serialize_into<W: Write, T: ?Sized + serde::Serialize>(
&self,
w: W,
t: &T,
) -> Result<()> {
config_map!(self, opts => ::internal::serialize_into(w, t, opts))
}
/// Deserializes a slice of bytes into an instance of `T` using this configuration
#[inline(always)]
pub fn deserialize<'a, T: serde::Deserialize<'a>>(&self, bytes: &'a [u8]) -> Result<T> {
config_map!(self, opts => ::internal::deserialize(bytes, opts))
}
/// TODO: document
#[doc(hidden)]
#[inline(always)]
pub fn deserialize_in_place<'a, R, T>(&self, reader: R, place: &mut T) -> Result<()>
where
R: BincodeRead<'a>,
T: serde::de::Deserialize<'a>,
{
config_map!(self, opts => ::internal::deserialize_in_place(reader, opts, place))
}
/// Deserializes a slice of bytes with state `seed` using this configuration.
#[inline(always)]
pub fn deserialize_seed<'a, T: serde::de::DeserializeSeed<'a>>(
&self,
seed: T,
bytes: &'a [u8],
) -> Result<T::Value> {
config_map!(self, opts => ::internal::deserialize_seed(seed, bytes, opts))
}
/// Deserializes an object directly from a `Read`er using this configuration
///
/// If this returns an `Error`, `reader` may be in an invalid state.
#[inline(always)]
pub fn deserialize_from<R: Read, T: serde::de::DeserializeOwned>(
&self,
reader: R,
) -> Result<T> {
config_map!(self, opts => ::internal::deserialize_from(reader, opts))
}
/// Deserializes an object directly from a `Read`er with state `seed` using this configuration
///
/// If this returns an `Error`, `reader` may be in an invalid state.
#[inline(always)]
pub fn deserialize_from_seed<'a, R: Read, T: serde::de::DeserializeSeed<'a>>(
&self,
seed: T,
reader: R,
) -> Result<T::Value> {
config_map!(self, opts => ::internal::deserialize_from_seed(seed, reader, opts))
}
/// Deserializes an object from a custom `BincodeRead`er using the default configuration.
/// It is highly recommended to use `deserialize_from` unless you need to implement
/// `BincodeRead` for performance reasons.
///
/// If this returns an `Error`, `reader` may be in an invalid state.
#[inline(always)]
pub fn deserialize_from_custom<'a, R: BincodeRead<'a>, T: serde::de::DeserializeOwned>(
&self,
reader: R,
) -> Result<T> {
config_map!(self, opts => ::internal::deserialize_from_custom(reader, opts))
}
/// Deserializes an object from a custom `BincodeRead`er with state `seed` using the default
/// configuration. It is highly recommended to use `deserialize_from` unless you need to
/// implement `BincodeRead` for performance reasons.
///
/// If this returns an `Error`, `reader` may be in an invalid state.
#[inline(always)]
pub fn deserialize_from_custom_seed<
'a,
R: BincodeRead<'a>,
T: serde::de::DeserializeSeed<'a>,
>(
&self,
seed: T,
reader: R,
) -> Result<T::Value> {
config_map!(self, opts => ::internal::deserialize_from_custom_seed(seed, reader, opts))
}
}

View File

@ -1,4 +1,4 @@
use error::{ErrorKind, Result};
use crate::error::{ErrorKind, Result};
/// A trait for stopping serialization and deserialization when a certain limit has been reached.
pub trait SizeLimit {

View File

@ -27,9 +27,8 @@
//! .allow_trailing_bytes();
//! ```
use de::read::BincodeRead;
use error::Result;
use serde;
use crate::de::read::BincodeRead;
use crate::error::Result;
use std::io::{Read, Write};
use std::marker::PhantomData;
@ -41,13 +40,11 @@ pub(crate) use self::trailing::TrailingBytes;
pub use self::endian::{BigEndian, LittleEndian, NativeEndian};
pub use self::int::{FixintEncoding, VarintEncoding};
pub use self::legacy::*;
pub use self::limit::{Bounded, Infinite};
pub use self::trailing::{AllowTrailing, RejectTrailing};
mod endian;
mod int;
mod legacy;
mod limit;
mod trailing;
@ -176,13 +173,13 @@ pub trait Options: InternalOptions + Sized {
/// Serializes a serializable object into a `Vec` of bytes using this configuration
#[inline(always)]
fn serialize<S: ?Sized + serde::Serialize>(self, t: &S) -> Result<Vec<u8>> {
::internal::serialize(t, self)
crate::internal::serialize(t, self)
}
/// Returns the size that an object would be if serialized using Bincode with this configuration
#[inline(always)]
fn serialized_size<T: ?Sized + serde::Serialize>(self, t: &T) -> Result<u64> {
::internal::serialized_size(t, self)
crate::internal::serialized_size(t, self)
}
/// Serializes an object directly into a `Writer` using this configuration
@ -191,13 +188,13 @@ pub trait Options: InternalOptions + Sized {
/// is returned and *no bytes* will be written into the `Writer`
#[inline(always)]
fn serialize_into<W: Write, T: ?Sized + serde::Serialize>(self, w: W, t: &T) -> Result<()> {
::internal::serialize_into(w, t, self)
crate::internal::serialize_into(w, t, self)
}
/// Deserializes a slice of bytes into an instance of `T` using this configuration
#[inline(always)]
fn deserialize<'a, T: serde::Deserialize<'a>>(self, bytes: &'a [u8]) -> Result<T> {
::internal::deserialize(bytes, self)
crate::internal::deserialize(bytes, self)
}
/// TODO: document
@ -208,7 +205,7 @@ pub trait Options: InternalOptions + Sized {
R: BincodeRead<'a>,
T: serde::de::Deserialize<'a>,
{
::internal::deserialize_in_place(reader, self, place)
crate::internal::deserialize_in_place(reader, self, place)
}
/// Deserializes a slice of bytes with state `seed` using this configuration.
@ -218,7 +215,7 @@ pub trait Options: InternalOptions + Sized {
seed: T,
bytes: &'a [u8],
) -> Result<T::Value> {
::internal::deserialize_seed(seed, bytes, self)
crate::internal::deserialize_seed(seed, bytes, self)
}
/// Deserializes an object directly from a `Read`er using this configuration
@ -226,7 +223,7 @@ pub trait Options: InternalOptions + Sized {
/// If this returns an `Error`, `reader` may be in an invalid state.
#[inline(always)]
fn deserialize_from<R: Read, T: serde::de::DeserializeOwned>(self, reader: R) -> Result<T> {
::internal::deserialize_from(reader, self)
crate::internal::deserialize_from(reader, self)
}
/// Deserializes an object directly from a `Read`er with state `seed` using this configuration
@ -238,7 +235,7 @@ pub trait Options: InternalOptions + Sized {
seed: T,
reader: R,
) -> Result<T::Value> {
::internal::deserialize_from_seed(seed, reader, self)
crate::internal::deserialize_from_seed(seed, reader, self)
}
/// Deserializes an object from a custom `BincodeRead`er using the default configuration.
@ -251,7 +248,7 @@ pub trait Options: InternalOptions + Sized {
self,
reader: R,
) -> Result<T> {
::internal::deserialize_from_custom(reader, self)
crate::internal::deserialize_from_custom(reader, self)
}
/// Deserializes an object from a custom `BincodeRead`er with state `seed` using the default
@ -265,7 +262,7 @@ pub trait Options: InternalOptions + Sized {
seed: T,
reader: R,
) -> Result<T::Value> {
::internal::deserialize_from_custom_seed(seed, reader, self)
crate::internal::deserialize_from_custom_seed(seed, reader, self)
}
}

View File

@ -1,5 +1,5 @@
use de::read::SliceReader;
use {ErrorKind, Result};
use crate::de::read::SliceReader;
use crate::{ErrorKind, Result};
/// A trait for erroring deserialization if not all bytes were read.
pub trait TrailingBytes {

View File

@ -1,13 +1,12 @@
use config::{BincodeByteOrder, Options};
use crate::config::{BincodeByteOrder, Options};
use std::io::Read;
use self::read::{BincodeRead, IoReader, SliceReader};
use crate::config::{IntEncoding, SizeLimit};
use crate::{Error, ErrorKind, Result};
use byteorder::ReadBytesExt;
use config::{IntEncoding, SizeLimit};
use serde;
use serde::de::Error as DeError;
use serde::de::IntoDeserializer;
use {Error, ErrorKind, Result};
/// Specialized ways to read data into bincode.
pub mod read;

View File

@ -1,5 +1,4 @@
use error::Result;
use serde;
use crate::error::Result;
use std::io;
/// An optional Read trait for advanced Bincode usage.
@ -100,8 +99,8 @@ impl<R: io::Read> io::Read for IoReader<R> {
impl<'storage> SliceReader<'storage> {
#[inline(always)]
fn unexpected_eof() -> Box<::ErrorKind> {
Box::new(::ErrorKind::Io(io::Error::new(
fn unexpected_eof() -> Box<crate::ErrorKind> {
Box::new(crate::ErrorKind::Io(io::Error::new(
io::ErrorKind::UnexpectedEof,
"",
)))
@ -114,7 +113,7 @@ impl<'storage> BincodeRead<'storage> for SliceReader<'storage> {
where
V: serde::de::Visitor<'storage>,
{
use ErrorKind;
use crate::ErrorKind;
let string = match ::std::str::from_utf8(self.get_byte_slice(length)?) {
Ok(s) => s,
Err(e) => return Err(ErrorKind::InvalidUtf8Encoding(e).into()),
@ -161,7 +160,7 @@ where
let string = match ::std::str::from_utf8(&self.temp_buffer[..]) {
Ok(s) => s,
Err(e) => return Err(::ErrorKind::InvalidUtf8Encoding(e).into()),
Err(e) => return Err(crate::ErrorKind::InvalidUtf8Encoding(e).into()),
};
visitor.visit_str(string)

View File

@ -1,9 +1,7 @@
use std::error::Error as StdError;
use std::fmt;
use std::io;
use std::str::Utf8Error;
use std::{error, fmt};
use serde;
/// The result of a serialization or deserialization operation.
pub type Result<T> = ::std::result::Result<T, Error>;
@ -13,6 +11,7 @@ pub type Error = Box<ErrorKind>;
/// The kind of error that can be produced during a serialization or deserialization.
#[derive(Debug)]
#[non_exhaustive]
pub enum ErrorKind {
/// If the error stems from the reader/writer that is being used
/// during (de)serialization, that error will be stored and returned here.
@ -40,25 +39,7 @@ pub enum ErrorKind {
}
impl StdError for ErrorKind {
fn description(&self) -> &str {
match *self {
ErrorKind::Io(ref err) => error::Error::description(err),
ErrorKind::InvalidUtf8Encoding(_) => "string is not valid utf8",
ErrorKind::InvalidBoolEncoding(_) => "invalid u8 while decoding bool",
ErrorKind::InvalidCharEncoding => "char is not valid",
ErrorKind::InvalidTagEncoding(_) => "tag for enum is not valid",
ErrorKind::SequenceMustHaveLength => {
"Bincode can only encode sequences and maps that have a knowable size ahead of time"
}
ErrorKind::DeserializeAnyNotSupported => {
"Bincode doesn't support serde::Deserializer::deserialize_any"
}
ErrorKind::SizeLimit => "the size limit has been reached",
ErrorKind::Custom(ref msg) => msg,
}
}
fn cause(&self) -> Option<&error::Error> {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match *self {
ErrorKind::Io(ref err) => Some(err),
ErrorKind::InvalidUtf8Encoding(_) => None,
@ -83,16 +64,16 @@ impl fmt::Display for ErrorKind {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
ErrorKind::Io(ref ioerr) => write!(fmt, "io error: {}", ioerr),
ErrorKind::InvalidUtf8Encoding(ref e) => write!(fmt, "{}: {}", self.description(), e),
ErrorKind::InvalidUtf8Encoding(ref e) => write!(fmt, "string is not valid utf8: {}", e),
ErrorKind::InvalidBoolEncoding(b) => {
write!(fmt, "{}, expected 0 or 1, found {}", self.description(), b)
write!(fmt, "invalid u8 while decoding bool, expected 0 or 1, found {}", b)
}
ErrorKind::InvalidCharEncoding => write!(fmt, "{}", self.description()),
ErrorKind::InvalidCharEncoding => write!(fmt, "char is not valid"),
ErrorKind::InvalidTagEncoding(tag) => {
write!(fmt, "{}, found {}", self.description(), tag)
write!(fmt, "tag for enum is not valid, found {}", tag)
}
ErrorKind::SequenceMustHaveLength => write!(fmt, "{}", self.description()),
ErrorKind::SizeLimit => write!(fmt, "{}", self.description()),
ErrorKind::SequenceMustHaveLength => write!(fmt, "Bincode can only encode sequences and maps that have a knowable size ahead of time"),
ErrorKind::SizeLimit => write!(fmt, "the size limit has been reached"),
ErrorKind::DeserializeAnyNotSupported => write!(
fmt,
"Bincode does not support the serde::Deserializer::deserialize_any method"

View File

@ -1,10 +1,9 @@
use serde;
use std::io::{Read, Write};
use std::marker::PhantomData;
use config::{Infinite, InternalOptions, Options, SizeLimit, TrailingBytes};
use de::read::BincodeRead;
use Result;
use crate::config::{Infinite, InternalOptions, Options, SizeLimit, TrailingBytes};
use crate::de::read::BincodeRead;
use crate::Result;
pub(crate) fn serialize_into<W, T: ?Sized, O>(writer: W, value: &T, mut options: O) -> Result<()>
where
@ -18,7 +17,7 @@ where
serialized_size(value, &mut options)?;
}
let mut serializer = ::ser::Serializer::<_, O>::new(writer, options);
let mut serializer = crate::ser::Serializer::<_, O>::new(writer, options);
serde::Serialize::serialize(value, &mut serializer)
}
@ -40,7 +39,7 @@ pub(crate) fn serialized_size<T: ?Sized, O: InternalOptions>(value: &T, options:
where
T: serde::Serialize,
{
let mut size_counter = ::ser::SizeChecker { options, total: 0 };
let mut size_counter = crate::ser::SizeChecker { options, total: 0 };
let result = value.serialize(&mut size_counter);
result.map(|_| size_counter.total)
@ -61,7 +60,7 @@ where
T: serde::de::DeserializeSeed<'a>,
O: InternalOptions,
{
let reader = ::de::read::IoReader::new(reader);
let reader = crate::de::read::IoReader::new(reader);
deserialize_from_custom_seed(seed, reader, options)
}
@ -84,7 +83,7 @@ where
T: serde::de::DeserializeSeed<'a>,
O: InternalOptions,
{
let mut deserializer = ::de::Deserializer::<_, O>::with_bincode_read(reader, options);
let mut deserializer = crate::de::Deserializer::<_, O>::with_bincode_read(reader, options);
seed.deserialize(&mut deserializer)
}
@ -94,7 +93,7 @@ where
T: serde::de::Deserialize<'a>,
O: InternalOptions,
{
let mut deserializer = ::de::Deserializer::<_, _>::with_bincode_read(reader, options);
let mut deserializer = crate::de::Deserializer::<_, _>::with_bincode_read(reader, options);
serde::Deserialize::deserialize_in_place(&mut deserializer, place)
}
@ -111,10 +110,10 @@ where
T: serde::de::DeserializeSeed<'a>,
O: InternalOptions,
{
let options = ::config::WithOtherLimit::new(options, Infinite);
let options = crate::config::WithOtherLimit::new(options, Infinite);
let reader = ::de::read::SliceReader::new(bytes);
let mut deserializer = ::de::Deserializer::with_bincode_read(reader, options);
let reader = crate::de::read::SliceReader::new(bytes);
let mut deserializer = crate::de::Deserializer::with_bincode_read(reader, options);
let val = seed.deserialize(&mut deserializer)?;
match O::Trailing::check_end(&deserializer.reader) {

View File

@ -1,5 +1,4 @@
#![deny(missing_docs)]
#![allow(unknown_lints, bare_trait_objects, deprecated)]
//! Bincode is a crate for encoding and decoding using a tiny binary
//! serialization strategy. Using it, you can easily go from having
@ -24,7 +23,7 @@
//! Support for `i128` and `u128` is automatically enabled on Rust toolchains
//! greater than or equal to `1.26.0` and disabled for targets which do not support it
#![doc(html_root_url = "https://docs.rs/bincode/1.3.1")]
#![doc(html_root_url = "https://docs.rs/bincode/2.0.0-dev")]
#![crate_name = "bincode"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
@ -41,35 +40,16 @@ mod error;
mod internal;
mod ser;
pub use config::{Config, DefaultOptions, Options};
pub use de::read::BincodeRead;
pub use de::Deserializer;
pub use error::{Error, ErrorKind, Result};
pub use ser::Serializer;
pub use crate::config::{DefaultOptions, Options};
pub use crate::de::read::BincodeRead;
pub use crate::de::Deserializer;
pub use crate::error::{Error, ErrorKind, Result};
pub use crate::ser::Serializer;
/// Get a default configuration object.
///
/// ### Default Configuration:
///
/// | Byte limit | Endianness |
/// |------------|------------|
/// | Unlimited | Little |
#[inline(always)]
#[deprecated(since = "1.3.0", note = "please use `options()` instead")]
pub fn config() -> Config {
Config::new()
}
/// Get a default configuration object.
///
/// **Warning:** the default configuration returned by this function
/// is not the same as that used by the other functions in this
/// module. See the
/// [config](config/index.html#options-struct-vs-bincode-functions)
/// module for more details
///
/// ### Default Configuration:
///
/// | Byte limit | Endianness | Int Encoding | Trailing Behavior |
/// |------------|------------|--------------|-------------------|
/// | Unlimited | Little | Varint | Reject |
@ -82,54 +62,31 @@ pub fn options() -> DefaultOptions {
///
/// If the serialization would take more bytes than allowed by the size limit, an error
/// is returned and *no bytes* will be written into the `Writer`.
///
/// **Warning:** the default configuration used by this function is not
/// the same as that used by the `DefaultOptions` struct. See the
/// [config](config/index.html#options-struct-vs-bincode-functions)
/// module for more details
pub fn serialize_into<W, T: ?Sized>(writer: W, value: &T) -> Result<()>
where
W: std::io::Write,
T: serde::Serialize,
{
DefaultOptions::new()
.with_fixint_encoding()
.serialize_into(writer, value)
DefaultOptions::new().serialize_into(writer, value)
}
/// Serializes a serializable object into a `Vec` of bytes using the default configuration.
///
/// **Warning:** the default configuration used by this function is not
/// the same as that used by the `DefaultOptions` struct. See the
/// [config](config/index.html#options-struct-vs-bincode-functions)
/// module for more details
pub fn serialize<T: ?Sized>(value: &T) -> Result<Vec<u8>>
where
T: serde::Serialize,
{
DefaultOptions::new()
.with_fixint_encoding()
.allow_trailing_bytes()
.serialize(value)
DefaultOptions::new().serialize(value)
}
/// Deserializes an object directly from a `Read`er using the default configuration.
///
/// If this returns an `Error`, `reader` may be in an invalid state.
///
/// **Warning:** the default configuration used by this function is not
/// the same as that used by the `DefaultOptions` struct. See the
/// [config](config/index.html#options-struct-vs-bincode-functions)
/// module for more details
pub fn deserialize_from<R, T>(reader: R) -> Result<T>
where
R: std::io::Read,
T: serde::de::DeserializeOwned,
{
DefaultOptions::new()
.with_fixint_encoding()
.allow_trailing_bytes()
.deserialize_from(reader)
DefaultOptions::new().deserialize_from(reader)
}
/// Deserializes an object from a custom `BincodeRead`er using the default configuration.
@ -137,20 +94,12 @@ where
/// `BincodeRead` for performance reasons.
///
/// If this returns an `Error`, `reader` may be in an invalid state.
///
/// **Warning:** the default configuration used by this function is not
/// the same as that used by the `DefaultOptions` struct. See the
/// [config](config/index.html#options-struct-vs-bincode-functions)
/// module for more details
pub fn deserialize_from_custom<'a, R, T>(reader: R) -> Result<T>
where
R: de::read::BincodeRead<'a>,
T: serde::de::DeserializeOwned,
{
DefaultOptions::new()
.with_fixint_encoding()
.allow_trailing_bytes()
.deserialize_from_custom(reader)
DefaultOptions::new().deserialize_from_custom(reader)
}
/// Only use this if you know what you're doing.
@ -162,40 +111,21 @@ where
T: serde::de::Deserialize<'a>,
R: BincodeRead<'a>,
{
DefaultOptions::new()
.with_fixint_encoding()
.allow_trailing_bytes()
.deserialize_in_place(reader, place)
DefaultOptions::new().deserialize_in_place(reader, place)
}
/// Deserializes a slice of bytes into an instance of `T` using the default configuration.
///
/// **Warning:** the default configuration used by this function is not
/// the same as that used by the `DefaultOptions` struct. See the
/// [config](config/index.html#options-struct-vs-bincode-functions)
/// module for more details
pub fn deserialize<'a, T>(bytes: &'a [u8]) -> Result<T>
where
T: serde::de::Deserialize<'a>,
{
DefaultOptions::new()
.with_fixint_encoding()
.allow_trailing_bytes()
.deserialize(bytes)
DefaultOptions::new().deserialize(bytes)
}
/// Returns the size that an object would be if serialized using Bincode with the default configuration.
///
/// **Warning:** the default configuration used by this function is not
/// the same as that used by the `DefaultOptions` struct. See the
/// [config](config/index.html#options-struct-vs-bincode-functions)
/// module for more details
pub fn serialized_size<T: ?Sized>(value: &T) -> Result<u64>
where
T: serde::Serialize,
{
DefaultOptions::new()
.with_fixint_encoding()
.allow_trailing_bytes()
.serialized_size(value)
DefaultOptions::new().serialized_size(value)
}

View File

@ -1,13 +1,11 @@
use std::io::Write;
use std::u32;
use serde;
use byteorder::WriteBytesExt;
use super::config::{IntEncoding, SizeLimit};
use super::{Error, ErrorKind, Result};
use config::{BincodeByteOrder, Options};
use crate::config::{BincodeByteOrder, Options};
use std::mem::size_of;
/// An Serializer that encodes values directly into a Writer.

View File

@ -250,11 +250,11 @@ fn deserializing_errors() {
_ => panic!(),
}
let invalid_str = vec![1, 0, 0, 0, 0, 0, 0, 0, 0xFF];
let invalid_str = vec![1, 0xFF];
match *deserialize::<String>(&invalid_str[..]).unwrap_err() {
ErrorKind::InvalidUtf8Encoding(_) => {}
_ => panic!(),
e => panic!("{:?}", e),
}
// Out-of-bounds variant
@ -262,7 +262,7 @@ fn deserializing_errors() {
enum Test {
One,
Two,
};
}
let invalid_enum = vec![0, 0, 0, 5];
@ -355,16 +355,17 @@ fn too_big_serialize() {
#[test]
fn test_serialized_size() {
assert!(serialized_size(&0u8).unwrap() == 1);
assert!(serialized_size(&0u16).unwrap() == 2);
assert!(serialized_size(&0u32).unwrap() == 4);
assert!(serialized_size(&0u64).unwrap() == 8);
let opt = DefaultOptions::new().with_fixint_encoding();
assert!(opt.serialized_size(&0u8).unwrap() == 1);
assert!(opt.serialized_size(&0u16).unwrap() == 2);
assert!(opt.serialized_size(&0u32).unwrap() == 4);
assert!(opt.serialized_size(&0u64).unwrap() == 8);
// length isize stored as u64
assert!(serialized_size(&"").unwrap() == LEN_SIZE);
assert!(serialized_size(&"a").unwrap() == LEN_SIZE + 1);
assert!(opt.serialized_size(&"").unwrap() == LEN_SIZE);
assert!(opt.serialized_size(&"a").unwrap() == LEN_SIZE + 1);
assert!(serialized_size(&vec![0u32, 1u32, 2u32]).unwrap() == LEN_SIZE + 3 * (4));
assert!(opt.serialized_size(&vec![0u32, 1u32, 2u32]).unwrap() == LEN_SIZE + 3 * (4));
}
#[test]
@ -581,9 +582,13 @@ fn serde_bytes() {
#[test]
fn endian_difference() {
let x = 10u64;
let little = serialize(&x).unwrap();
let little = DefaultOptions::new()
.with_fixint_encoding()
.serialize(&x)
.unwrap();
let big = DefaultOptions::new()
.with_big_endian()
.with_fixint_encoding()
.serialize(&x)
.unwrap();
assert_ne!(little, big);
@ -620,8 +625,8 @@ fn test_zero_copy_parse_deserialize_into() {
impl<'storage> SliceReader<'storage> {
#[inline(always)]
fn unexpected_eof() -> Box<::ErrorKind> {
return Box::new(::ErrorKind::Io(io::Error::new(
fn unexpected_eof() -> Box<crate::ErrorKind> {
return Box::new(crate::ErrorKind::Io(io::Error::new(
io::ErrorKind::UnexpectedEof,
"",
)));
@ -645,7 +650,7 @@ fn test_zero_copy_parse_deserialize_into() {
where
V: serde::de::Visitor<'storage>,
{
use ErrorKind;
use crate::ErrorKind;
if length > self.slice.len() {
return Err(SliceReader::unexpected_eof());
}
@ -888,7 +893,7 @@ fn test_byte_vec_struct() {
a: Vec<u8>,
b: Vec<u8>,
c: Vec<u8>,
};
}
let byte_struct = ByteVecs {
a: vec![2; 20],