зеркало из https://github.com/mozilla/gecko-dev.git
Bug 1447286 - Update Cargo lockfiles and re-vendor rust dependencies. r=jrmuizel
MozReview-Commit-ID: 1gpB9n4dNHG --HG-- extra : rebase_source : ef976a762c8c18b14dc509c31c7bc3d6c46833b3
This commit is contained in:
Родитель
c87aa15000
Коммит
1e20dc719f
|
@ -115,15 +115,6 @@ name = "binary-space-partition"
|
|||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
|
||||
[[package]]
|
||||
name = "bincode"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"serde 1.0.27 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bincode"
|
||||
version = "1.0.0"
|
||||
|
@ -2025,7 +2016,7 @@ name = "webrender"
|
|||
version = "0.57.0"
|
||||
dependencies = [
|
||||
"app_units 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"bincode 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"bincode 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"bitflags 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"core-foundation 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
|
@ -2054,7 +2045,7 @@ name = "webrender_api"
|
|||
version = "0.57.0"
|
||||
dependencies = [
|
||||
"app_units 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"bincode 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"bincode 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"bitflags 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"core-foundation 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
|
@ -2195,7 +2186,6 @@ dependencies = [
|
|||
"checksum atty 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "d912da0db7fa85514874458ca3651fe2cddace8d0b0505571dbdcd41ab490159"
|
||||
"checksum base64 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "96434f987501f0ed4eb336a411e0631ecd1afa11574fe148587adc4ff96143c9"
|
||||
"checksum binary-space-partition 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "88ceb0d16c4fd0e42876e298d7d3ce3780dd9ebdcbe4199816a32c77e08597ff"
|
||||
"checksum bincode 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)" = "9d3fb369af639822830328794eba2501b3479652fcd021b2aeb1ed4984202afd"
|
||||
"checksum bincode 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bda13183df33055cbb84b847becce220d392df502ebe7a4a78d7021771ed94d0"
|
||||
"checksum bindgen 0.33.2 (registry+https://github.com/rust-lang/crates.io-index)" = "603ed8d8392ace9581e834e26bd09799bf1e989a79bd1aedbb893e72962bdc6e"
|
||||
"checksum bitflags 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "aad18937a628ec6abcd26d1489012cc0e18c21798210f491af69ded9b881106d"
|
||||
|
|
|
@ -1 +1 @@
|
|||
{"files":{".travis.yml":"f705a11b487bf71c41ebd8223cc1f3cbde0dfdfeea96a100af55e06e93397a1b","Cargo.toml":"f84aff9184ddcf55e949223d373eb6e25bd50a15d62cda08967c001997658239","LICENSE.md":"90d7e062634054e6866d3c81e6a2b3058a840e6af733e98e80bdfe1a7dec6912","changelist.org":"936b58455e1c221539b73b5250302dcd96baa04a5d8536199d3351142addad57","examples/basic.rs":"6c897fac722343138db14911da8d08c65cfd8d9a8143a5169845914897af8e21","logo.png":"ebc5305aae938c1f834cf35302faa8be0f1b7b8c3c3beef5cf6b2f68b9628c35","readme.dev.md":"43bad3bcc13a5c057344d3ba7f64bd2b313f8c133d6afa068108df73e8e8facd","readme.md":"a0cf9077393f746baa131934b53780d78e7807f8ce3f71d97347c657aebf5a0a","src/de/mod.rs":"be66fad5844a0b89025a089ab114540ab7ca6fa867cd2d72383af06c9ee30345","src/de/read.rs":"7ad8a1ae881ce135c3a56af66a3c83dad3f66722a3d21ad5c7addf0460d0edf3","src/internal.rs":"60e1c3fac7d8e6b01dc362b3171e2b4d2d8809fcbc98dc2431fffa01da6b63ae","src/lib.rs":"5bb0c0be61c8a7d9c1ef6209e05e25d44ae23e0b9b4a2adc0ae4264d35ea849b","src/ser/mod.rs":"0eeb467eeb8189fb935e4996cd45d1f292c401f92b00793907bd428f1bde421d","tests/test.rs":"a0116953ec3a3d6b9a9fc202d1bc886c5bb95110f2a3d4ac52e5945e4f6d182e"},"package":"9d3fb369af639822830328794eba2501b3479652fcd021b2aeb1ed4984202afd"}
|
||||
{"files":{"Cargo.toml":"eda034c33e46b4b2ec6e6af6f1ddbcbf6642eaa88b46a1692ecc8acc7df9bf53","LICENSE.md":"90d7e062634054e6866d3c81e6a2b3058a840e6af733e98e80bdfe1a7dec6912","readme.md":"2ff3f54e6efd24b38f981b539be77438c10b9b8f67cad41ca2188396f95bcde8","src/config.rs":"2a6da0f5f95794add175c0a37e2a293f6d4c5932fc43f41492f646a98bf58aa9","src/de/mod.rs":"1da6149812e2d2c4ae8f9fdf7fc5bf85376d2f82da9a9311b0c45eff4033b71d","src/de/read.rs":"f8c5f2466c632f062e6fe55734d27c8fc7566c0894b610f012d8835af1810628","src/error.rs":"00a7a4de5cf1cc4a28dcf44c5c3ff607887baf41d5410b76468088963257b783","src/internal.rs":"6c827579a325e02bc7df8403965616b970b0f9b9763896ed938e719309a681b4","src/lib.rs":"9af9d73dcc1fc19240b8855ed521d38ae963e6685627e5d3eebf9acf40424aa3","src/ser/mod.rs":"b544c335a39a9b702772d586caa44f0e6febae3a0a109625fcee8ac68fc95645"},"package":"bda13183df33055cbb84b847becce220d392df502ebe7a4a78d7021771ed94d0"}
|
|
@ -1,5 +0,0 @@
|
|||
language: rust
|
||||
rust:
|
||||
- stable
|
||||
- beta
|
||||
- nightly
|
|
@ -12,22 +12,24 @@
|
|||
|
||||
[package]
|
||||
name = "bincode"
|
||||
version = "0.9.1"
|
||||
version = "1.0.0"
|
||||
authors = ["Ty Overby <ty@pre-alpha.com>", "Francesco Mazzoli <f@mazzo.li>", "David Tolnay <dtolnay@gmail.com>", "Daniel Griffen"]
|
||||
exclude = ["./logo.png"]
|
||||
exclude = ["logo.png", "tests/*", "examples/*", ".gitignore", ".travis.yml", "changelist.org"]
|
||||
publish = true
|
||||
description = "A binary serialization / deserialization strategy that uses Serde for transforming structs into bytes and vice versa!"
|
||||
documentation = "https://docs.rs/bincode"
|
||||
readme = "./readme.md"
|
||||
keywords = ["binary", "encode", "decode", "serialize", "deserialize"]
|
||||
categories = ["network-programming"]
|
||||
license = "MIT"
|
||||
repository = "https://github.com/TyOverby/bincode"
|
||||
[dependencies.byteorder]
|
||||
version = "1.0.0"
|
||||
version = "1.2.0"
|
||||
|
||||
[dependencies.serde]
|
||||
version = "1.*.*"
|
||||
version = "^1.0.27"
|
||||
[dev-dependencies.serde_bytes]
|
||||
version = "0.10.*"
|
||||
version = "^0.10.3"
|
||||
|
||||
[dev-dependencies.serde_derive]
|
||||
version = "1.*.*"
|
||||
version = "^1.0.27"
|
||||
|
|
|
@ -1,27 +0,0 @@
|
|||
* 1.0.0
|
||||
** Removed depricated rustc-serialize support
|
||||
Rustc-serialize was a stopgap until projects like Serde were able to catch up.
|
||||
With macros stabilization on its way, we are able to switch to serde without any
|
||||
big user-friendliness issues. Major congratulations to Serde for coming this far!
|
||||
|
||||
** Moved Refbox, Strbox and Slicebox into a "refbox" module
|
||||
Refbox, Strbox and Slicebox are still an integral piece of bincode, but since
|
||||
they are mainly used by power-users, this move will make the crate API more organized
|
||||
and easier for new users to understand.
|
||||
|
||||
** Upgraded to Serde 0.9.*
|
||||
Serde 0.9.* gives us a better API surface area and allows use of procedural macros for
|
||||
deriving serialize and deserialize implemenetations.
|
||||
|
||||
** Moved serde functions into global module
|
||||
Since serde is the only supported serialization mechanism, it makes sense to have these
|
||||
functions available at the top level.
|
||||
|
||||
** Added the ability to chose your own endian encoding.
|
||||
This functionality is located in the endian_choice module.
|
||||
|
||||
** Changed SizeLimit to be a trait instead of an enum
|
||||
Mostly for performance reasons.
|
||||
|
||||
** Removed RefBox / StrBox / SliceBox
|
||||
Since rustc-serialize support was phased out, you can use `Cow<T>` with serde.
|
|
@ -1,27 +0,0 @@
|
|||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
extern crate bincode;
|
||||
|
||||
use bincode::{serialize, deserialize, Infinite};
|
||||
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
struct Entity {
|
||||
x: f32,
|
||||
y: f32,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
struct World(Vec<Entity>);
|
||||
|
||||
fn main() {
|
||||
let world = World(vec![Entity { x: 0.0, y: 4.0 }, Entity { x: 10.0, y: 20.5 }]);
|
||||
|
||||
let encoded: Vec<u8> = serialize(&world, Infinite).unwrap();
|
||||
|
||||
// 8 bytes for the length of the vector (usize), 4 bytes per float.
|
||||
assert_eq!(encoded.len(), 8 + 4 * 4);
|
||||
|
||||
let decoded: World = deserialize(&encoded[..]).unwrap();
|
||||
|
||||
assert_eq!(world, decoded);
|
||||
}
|
Двоичный файл не отображается.
До Ширина: | Высота: | Размер: 252 KiB |
|
@ -1,39 +0,0 @@
|
|||
# Bincode
|
||||
|
||||
<img align="right" src="./logo.png" />
|
||||
|
||||
[![Build Status](https://travis-ci.org/TyOverby/bincode.svg)](https://travis-ci.org/TyOverby/bincode)
|
||||
[![](http://meritbadge.herokuapp.com/bincode)](https://crates.io/crates/bincode)
|
||||
|
||||
A compact encoder / decoder pair that uses an binary zero-fluff encoding scheme.
|
||||
The size of the encoded object will be the same or smaller than the size that
|
||||
the object takes up in memory in a running Rust program.
|
||||
|
||||
In addition to exposing two simple funcitons that encode to Vec<u8> and decode
|
||||
from Vec<u8>, binary-encode exposes a Reader/Writer API that makes it work
|
||||
perfectly with other stream-based apis such as rust files, network streams,
|
||||
and the [flate2-rs](https://github.com/alexcrichton/flate2-rs) compression
|
||||
library.
|
||||
|
||||
[Api Documentation](http://tyoverby.github.io/bincode/bincode/)
|
||||
|
||||
## Example
|
||||
|
||||
^code(./examples/basic.rs)
|
||||
|
||||
|
||||
## Details
|
||||
|
||||
The encoding (and thus decoding) proceeds unsurprisingly -- primitive
|
||||
types are encoded according to the underlying `Writer`, tuples and
|
||||
structs are encoded by encoding their fields one-by-one, and enums are
|
||||
encoded by first writing out the tag representing the variant and
|
||||
then the contents.
|
||||
|
||||
However, there are some implementation details to be aware of:
|
||||
|
||||
* `isize`/`usize` are encoded as `i64`/`u64`, for portability.
|
||||
* enums variants are encoded as a `u32` instead that as a `uint`.
|
||||
`u32` is enough for all practical uses.
|
||||
* `str` is encoded as `(u64, &[u8])`, where the `u64` is the number of
|
||||
bytes contained in the encoded string.
|
|
@ -3,7 +3,7 @@
|
|||
<img align="right" src="./logo.png" />
|
||||
|
||||
[![Build Status](https://travis-ci.org/TyOverby/bincode.svg)](https://travis-ci.org/TyOverby/bincode)
|
||||
[![](http://meritbadge.herokuapp.com/bincode)](https://crates.io/crates/bincode)
|
||||
[![](https://meritbadge.herokuapp.com/bincode)](https://crates.io/crates/bincode)
|
||||
[![](https://img.shields.io/badge/license-MIT-blue.svg)](http://opensource.org/licenses/MIT)
|
||||
|
||||
A compact encoder / decoder pair that uses a binary zero-fluff encoding scheme.
|
||||
|
|
|
@ -0,0 +1,312 @@
|
|||
use super::internal::{Bounded, Infinite, SizeLimit};
|
||||
use ::error::Result;
|
||||
use byteorder::{BigEndian, ByteOrder, LittleEndian, NativeEndian};
|
||||
use {DeserializerAcceptor, SerializerAcceptor};
|
||||
use serde;
|
||||
use std::io::{Write, Read};
|
||||
use std::marker::PhantomData;
|
||||
use de::read::BincodeRead;
|
||||
|
||||
use self::LimitOption::*;
|
||||
use self::EndianOption::*;
|
||||
|
||||
struct DefaultOptions(Infinite);
|
||||
|
||||
pub(crate) trait Options {
|
||||
type Limit: SizeLimit + 'static;
|
||||
type Endian: ByteOrder + 'static;
|
||||
|
||||
fn limit(&mut self) -> &mut Self::Limit;
|
||||
}
|
||||
|
||||
pub(crate) trait OptionsExt: Options + Sized {
|
||||
fn with_no_limit(self) -> WithOtherLimit<Self, Infinite> {
|
||||
WithOtherLimit::new(self, Infinite)
|
||||
}
|
||||
|
||||
fn with_limit(self, limit: u64) -> WithOtherLimit<Self, Bounded> {
|
||||
WithOtherLimit::new(self, Bounded(limit))
|
||||
}
|
||||
|
||||
fn with_little_endian(self) -> WithOtherEndian<Self, LittleEndian> {
|
||||
WithOtherEndian::new(self)
|
||||
}
|
||||
|
||||
fn with_big_endian(self) -> WithOtherEndian<Self, BigEndian> {
|
||||
WithOtherEndian::new(self)
|
||||
}
|
||||
|
||||
fn with_native_endian(self) -> WithOtherEndian<Self, NativeEndian> {
|
||||
WithOtherEndian::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, O: Options> Options for &'a mut O {
|
||||
type Limit = O::Limit;
|
||||
type Endian = O::Endian;
|
||||
|
||||
#[inline(always)]
|
||||
fn limit(&mut self) -> &mut Self::Limit {
|
||||
(*self).limit()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Options> OptionsExt for T {}
|
||||
|
||||
impl DefaultOptions {
|
||||
fn new() -> DefaultOptions {
|
||||
DefaultOptions(Infinite)
|
||||
}
|
||||
}
|
||||
|
||||
impl Options for DefaultOptions {
|
||||
type Limit = Infinite;
|
||||
type Endian = LittleEndian;
|
||||
|
||||
#[inline(always)]
|
||||
fn limit(&mut self) -> &mut Infinite {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum LimitOption {
|
||||
Unlimited,
|
||||
Limited(u64),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum EndianOption {
|
||||
Big,
|
||||
Little,
|
||||
Native,
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub struct Config {
|
||||
limit: LimitOption,
|
||||
endian: EndianOption,
|
||||
}
|
||||
|
||||
pub(crate) struct WithOtherLimit<O: Options, L: SizeLimit> {
|
||||
_options: O,
|
||||
pub(crate) new_limit: L,
|
||||
}
|
||||
|
||||
pub(crate) struct WithOtherEndian<O: Options, E: ByteOrder> {
|
||||
options: O,
|
||||
_endian: PhantomData<E>,
|
||||
}
|
||||
|
||||
|
||||
impl<O: Options, L: SizeLimit> WithOtherLimit<O, L> {
|
||||
#[inline(always)]
|
||||
pub(crate) fn new(options: O, limit: L) -> WithOtherLimit<O, L> {
|
||||
WithOtherLimit {
|
||||
_options: options,
|
||||
new_limit: limit,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<O: Options, E: ByteOrder> WithOtherEndian<O, E> {
|
||||
#[inline(always)]
|
||||
pub(crate) fn new(options: O) -> WithOtherEndian<O, E> {
|
||||
WithOtherEndian {
|
||||
options: options,
|
||||
_endian: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<O: Options, E: ByteOrder + 'static> Options for WithOtherEndian<O, E> {
|
||||
type Limit = O::Limit;
|
||||
type Endian = E;
|
||||
|
||||
#[inline(always)]
|
||||
fn limit(&mut self) -> &mut O::Limit {
|
||||
self.options.limit()
|
||||
}
|
||||
}
|
||||
|
||||
impl<O: Options, L: SizeLimit + 'static> Options for WithOtherLimit<O, L> {
|
||||
type Limit = L;
|
||||
type Endian = O::Endian;
|
||||
|
||||
fn limit(&mut self) -> &mut L {
|
||||
&mut self.new_limit
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! config_map {
|
||||
($self:expr, $opts:ident => $call:expr) => {
|
||||
match ($self.limit, $self.endian) {
|
||||
(Unlimited, Little) => {
|
||||
let $opts = DefaultOptions::new().with_no_limit().with_little_endian();
|
||||
$call
|
||||
}
|
||||
(Unlimited, Big) => {
|
||||
let $opts = DefaultOptions::new().with_no_limit().with_big_endian();
|
||||
$call
|
||||
}
|
||||
(Unlimited, Native) => {
|
||||
let $opts = DefaultOptions::new().with_no_limit().with_native_endian();
|
||||
$call
|
||||
}
|
||||
|
||||
(Limited(l), Little) => {
|
||||
let $opts = DefaultOptions::new().with_limit(l).with_little_endian();
|
||||
$call
|
||||
}
|
||||
(Limited(l), Big) => {
|
||||
let $opts = DefaultOptions::new().with_limit(l).with_big_endian();
|
||||
$call
|
||||
}
|
||||
(Limited(l), Native) => {
|
||||
let $opts = DefaultOptions::new().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 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 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))
|
||||
}
|
||||
|
||||
/// Executes the acceptor with a serde::Deserializer instance.
|
||||
/// NOT A PART OF THE STABLE PUBLIC API
|
||||
#[doc(hidden)]
|
||||
pub fn with_deserializer<'a, A, R>(&self, reader: R, acceptor: A) -> A::Output
|
||||
where A: DeserializerAcceptor<'a>,
|
||||
R: BincodeRead<'a>
|
||||
{
|
||||
config_map!(self, opts => {
|
||||
let mut deserializer = ::de::Deserializer::new(reader, opts);
|
||||
acceptor.accept(&mut deserializer)
|
||||
})
|
||||
}
|
||||
|
||||
/// Executes the acceptor with a serde::Serializer instance.
|
||||
/// NOT A PART OF THE STABLE PUBLIC API
|
||||
#[doc(hidden)]
|
||||
pub fn with_serializer<A, W>(&self, writer: W, acceptor: A) -> A::Output
|
||||
where A: SerializerAcceptor,
|
||||
W: Write
|
||||
{
|
||||
config_map!(self, opts => {
|
||||
let mut serializer = ::ser::Serializer::new(writer, opts);
|
||||
acceptor.accept(&mut serializer)
|
||||
})
|
||||
}
|
||||
}
|
|
@ -1,12 +1,12 @@
|
|||
use std::io::Read;
|
||||
use std::marker::PhantomData;
|
||||
use ::config::Options;
|
||||
|
||||
use byteorder::{ReadBytesExt, ByteOrder};
|
||||
use serde_crate as serde;
|
||||
use serde_crate::de::IntoDeserializer;
|
||||
use serde_crate::de::Error as DeError;
|
||||
use ::SizeLimit;
|
||||
use super::{Result, Error, ErrorKind};
|
||||
use serde;
|
||||
use byteorder::ReadBytesExt;
|
||||
use serde::de::IntoDeserializer;
|
||||
use serde::de::Error as DeError;
|
||||
use ::{Error, ErrorKind, Result};
|
||||
use ::internal::SizeLimit;
|
||||
use self::read::BincodeRead;
|
||||
|
||||
pub mod read;
|
||||
|
@ -14,7 +14,7 @@ pub mod read;
|
|||
/// A Deserializer that reads bytes from a buffer.
|
||||
///
|
||||
/// This struct should rarely be used.
|
||||
/// In most cases, prefer the `decode_from` function.
|
||||
/// In most cases, prefer the `deserialize_from` function.
|
||||
///
|
||||
/// The ByteOrder that is chosen will impact the endianness that
|
||||
/// is used to read integers out of the reader.
|
||||
|
@ -24,24 +24,22 @@ pub mod read;
|
|||
/// serde::Deserialize::deserialize(&mut deserializer);
|
||||
/// let bytes_read = d.bytes_read();
|
||||
/// ```
|
||||
pub struct Deserializer<R, S: SizeLimit, E: ByteOrder> {
|
||||
pub(crate) struct Deserializer<R, O: Options> {
|
||||
reader: R,
|
||||
size_limit: S,
|
||||
_phantom: PhantomData<E>,
|
||||
options: O,
|
||||
}
|
||||
|
||||
impl<'de, R: BincodeRead<'de>, E: ByteOrder, S: SizeLimit> Deserializer<R, S, E> {
|
||||
impl<'de, R: BincodeRead<'de>, O: Options> Deserializer<R, O> {
|
||||
/// Creates a new Deserializer with a given `Read`er and a size_limit.
|
||||
pub fn new(r: R, size_limit: S) -> Deserializer<R, S, E> {
|
||||
pub(crate) fn new(r: R, options: O) -> Deserializer<R, O> {
|
||||
Deserializer {
|
||||
reader: r,
|
||||
size_limit: size_limit,
|
||||
_phantom: PhantomData
|
||||
options: options,
|
||||
}
|
||||
}
|
||||
|
||||
fn read_bytes(&mut self, count: u64) -> Result<()> {
|
||||
self.size_limit.add(count)
|
||||
self.options.limit().add(count)
|
||||
}
|
||||
|
||||
fn read_type<T>(&mut self) -> Result<()> {
|
||||
|
@ -57,8 +55,7 @@ impl<'de, R: BincodeRead<'de>, E: ByteOrder, S: SizeLimit> Deserializer<R, S, E>
|
|||
|
||||
fn read_string(&mut self) -> Result<String> {
|
||||
let vec = self.read_vec()?;
|
||||
String::from_utf8(vec).map_err(|e|
|
||||
ErrorKind::InvalidUtf8Encoding(e.utf8_error()).into())
|
||||
String::from_utf8(vec).map_err(|e| ErrorKind::InvalidUtf8Encoding(e.utf8_error()).into())
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -69,33 +66,36 @@ macro_rules! impl_nums {
|
|||
where V: serde::de::Visitor<'de>,
|
||||
{
|
||||
try!(self.read_type::<$ty>());
|
||||
let value = try!(self.reader.$reader_method::<E>());
|
||||
let value = try!(self.reader.$reader_method::<O::Endian>());
|
||||
visitor.$visitor_method(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, 'a, R, S, E> serde::Deserializer<'de> for &'a mut Deserializer<R, S, E>
|
||||
where R: BincodeRead<'de>, S: SizeLimit, E: ByteOrder {
|
||||
impl<'de, 'a, R, O> serde::Deserializer<'de> for &'a mut Deserializer<R, O>
|
||||
where
|
||||
R: BincodeRead<'de>,
|
||||
O: Options,
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
Err(Box::new(ErrorKind::DeserializeAnyNotSupported))
|
||||
}
|
||||
|
||||
fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
let value: u8 = try!(serde::Deserialize::deserialize(self));
|
||||
match value {
|
||||
1 => visitor.visit_bool(true),
|
||||
0 => visitor.visit_bool(false),
|
||||
value => {
|
||||
Err(ErrorKind::InvalidBoolEncoding(value).into())
|
||||
}
|
||||
value => Err(ErrorKind::InvalidBoolEncoding(value).into()),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -111,7 +111,8 @@ where R: BincodeRead<'de>, S: SizeLimit, E: ByteOrder {
|
|||
|
||||
#[inline]
|
||||
fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
try!(self.read_type::<u8>());
|
||||
visitor.visit_u8(try!(self.reader.read_u8()))
|
||||
|
@ -119,45 +120,56 @@ where R: BincodeRead<'de>, S: SizeLimit, E: ByteOrder {
|
|||
|
||||
#[inline]
|
||||
fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
try!(self.read_type::<i8>());
|
||||
visitor.visit_i8(try!(self.reader.read_i8()))
|
||||
}
|
||||
|
||||
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
visitor.visit_unit()
|
||||
}
|
||||
|
||||
fn deserialize_char<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
use std::str;
|
||||
|
||||
let error = || {
|
||||
ErrorKind::InvalidCharEncoding.into()
|
||||
};
|
||||
let error = || ErrorKind::InvalidCharEncoding.into();
|
||||
|
||||
let mut buf = [0u8; 4];
|
||||
|
||||
// Look at the first byte to see how many bytes must be read
|
||||
let _ = try!(self.reader.read_exact(&mut buf[..1]));
|
||||
let width = utf8_char_width(buf[0]);
|
||||
if width == 1 { return visitor.visit_char(buf[0] as char) }
|
||||
if width == 0 { return Err(error())}
|
||||
if width == 1 {
|
||||
return visitor.visit_char(buf[0] as char);
|
||||
}
|
||||
if width == 0 {
|
||||
return Err(error());
|
||||
}
|
||||
|
||||
if self.reader.read_exact(&mut buf[1..width]).is_err() {
|
||||
return Err(error());
|
||||
}
|
||||
|
||||
let res = try!(str::from_utf8(&buf[..width]).ok().and_then(|s| s.chars().next()).ok_or(error()));
|
||||
let res = try!(
|
||||
str::from_utf8(&buf[..width])
|
||||
.ok()
|
||||
.and_then(|s| s.chars().next())
|
||||
.ok_or(error())
|
||||
);
|
||||
visitor.visit_char(res)
|
||||
}
|
||||
|
||||
fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
let len: usize = try!(serde::Deserialize::deserialize(&mut *self));
|
||||
try!(self.read_bytes(len as u64));
|
||||
|
@ -165,13 +177,15 @@ where R: BincodeRead<'de>, S: SizeLimit, E: ByteOrder {
|
|||
}
|
||||
|
||||
fn deserialize_string<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
visitor.visit_string(try!(self.read_string()))
|
||||
}
|
||||
|
||||
fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
let len: usize = try!(serde::Deserialize::deserialize(&mut *self));
|
||||
try!(self.read_bytes(len as u64));
|
||||
|
@ -179,19 +193,23 @@ where R: BincodeRead<'de>, S: SizeLimit, E: ByteOrder {
|
|||
}
|
||||
|
||||
fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
visitor.visit_byte_buf(try!(self.read_vec()))
|
||||
}
|
||||
|
||||
fn deserialize_enum<V>(self,
|
||||
_enum: &'static str,
|
||||
_variants: &'static [&'static str],
|
||||
visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
fn deserialize_enum<V>(
|
||||
self,
|
||||
_enum: &'static str,
|
||||
_variants: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value>
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
impl<'de, 'a, R: 'a, S, E> serde::de::EnumAccess<'de> for &'a mut Deserializer<R, S, E>
|
||||
where R: BincodeRead<'de>, S: SizeLimit, E: ByteOrder {
|
||||
impl<'de, 'a, R: 'a, O> serde::de::EnumAccess<'de> for &'a mut Deserializer<R, O>
|
||||
where R: BincodeRead<'de>, O: Options {
|
||||
type Error = Error;
|
||||
type Variant = Self;
|
||||
|
||||
|
@ -207,25 +225,34 @@ where R: BincodeRead<'de>, S: SizeLimit, E: ByteOrder {
|
|||
visitor.visit_enum(self)
|
||||
}
|
||||
|
||||
fn deserialize_tuple<V>(self,
|
||||
len: usize,
|
||||
visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value>
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
struct Access<'a, R: Read + 'a, S: SizeLimit + 'a, E: ByteOrder + 'a> {
|
||||
deserializer: &'a mut Deserializer<R, S, E>,
|
||||
struct Access<'a, R: Read + 'a, O: Options + 'a> {
|
||||
deserializer: &'a mut Deserializer<R, O>,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl<'de, 'a, 'b: 'a, R: BincodeRead<'de>+ 'b, S: SizeLimit, E: ByteOrder> serde::de::SeqAccess<'de> for Access<'a, R, S, E> {
|
||||
impl<
|
||||
'de,
|
||||
'a,
|
||||
'b: 'a,
|
||||
R: BincodeRead<'de> + 'b,
|
||||
O: Options,
|
||||
> serde::de::SeqAccess<'de> for Access<'a, R, O> {
|
||||
type Error = Error;
|
||||
|
||||
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
|
||||
where T: serde::de::DeserializeSeed<'de>,
|
||||
where
|
||||
T: serde::de::DeserializeSeed<'de>,
|
||||
{
|
||||
if self.len > 0 {
|
||||
self.len -= 1;
|
||||
let value = try!(serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer));
|
||||
let value = try!(serde::de::DeserializeSeed::deserialize(
|
||||
seed,
|
||||
&mut *self.deserializer,
|
||||
));
|
||||
Ok(Some(value))
|
||||
} else {
|
||||
Ok(None)
|
||||
|
@ -237,22 +264,27 @@ where R: BincodeRead<'de>, S: SizeLimit, E: ByteOrder {
|
|||
}
|
||||
}
|
||||
|
||||
visitor.visit_seq(Access { deserializer: self, len: len })
|
||||
visitor.visit_seq(Access {
|
||||
deserializer: self,
|
||||
len: len,
|
||||
})
|
||||
}
|
||||
|
||||
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
let value: u8 = try!(serde::de::Deserialize::deserialize(&mut *self));
|
||||
match value {
|
||||
0 => visitor.visit_none(),
|
||||
1 => visitor.visit_some(&mut *self),
|
||||
v => Err(ErrorKind::InvalidTagEncoding(v as usize).into())
|
||||
v => Err(ErrorKind::InvalidTagEncoding(v as usize).into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
let len = try!(serde::Deserialize::deserialize(&mut *self));
|
||||
|
||||
|
@ -260,22 +292,33 @@ where R: BincodeRead<'de>, S: SizeLimit, E: ByteOrder {
|
|||
}
|
||||
|
||||
fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
struct Access<'a, R: Read + 'a, S: SizeLimit + 'a, E: ByteOrder + 'a> {
|
||||
deserializer: &'a mut Deserializer<R, S, E>,
|
||||
struct Access<'a, R: Read + 'a, O: Options + 'a> {
|
||||
deserializer: &'a mut Deserializer<R, O>,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl<'de, 'a, 'b: 'a, R: BincodeRead<'de> + 'b, S: SizeLimit, E: ByteOrder> serde::de::MapAccess<'de> for Access<'a, R, S, E> {
|
||||
impl<
|
||||
'de,
|
||||
'a,
|
||||
'b: 'a,
|
||||
R: BincodeRead<'de> + 'b,
|
||||
O: Options,
|
||||
> serde::de::MapAccess<'de> for Access<'a, R, O> {
|
||||
type Error = Error;
|
||||
|
||||
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
|
||||
where K: serde::de::DeserializeSeed<'de>,
|
||||
where
|
||||
K: serde::de::DeserializeSeed<'de>,
|
||||
{
|
||||
if self.len > 0 {
|
||||
self.len -= 1;
|
||||
let key = try!(serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer));
|
||||
let key = try!(serde::de::DeserializeSeed::deserialize(
|
||||
seed,
|
||||
&mut *self.deserializer,
|
||||
));
|
||||
Ok(Some(key))
|
||||
} else {
|
||||
Ok(None)
|
||||
|
@ -283,9 +326,13 @@ where R: BincodeRead<'de>, S: SizeLimit, E: ByteOrder {
|
|||
}
|
||||
|
||||
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
|
||||
where V: serde::de::DeserializeSeed<'de>,
|
||||
where
|
||||
V: serde::de::DeserializeSeed<'de>,
|
||||
{
|
||||
let value = try!(serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer));
|
||||
let value = try!(serde::de::DeserializeSeed::deserialize(
|
||||
seed,
|
||||
&mut *self.deserializer,
|
||||
));
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
|
@ -296,62 +343,73 @@ where R: BincodeRead<'de>, S: SizeLimit, E: ByteOrder {
|
|||
|
||||
let len = try!(serde::Deserialize::deserialize(&mut *self));
|
||||
|
||||
visitor.visit_map(Access { deserializer: self, len: len })
|
||||
visitor.visit_map(Access {
|
||||
deserializer: self,
|
||||
len: len,
|
||||
})
|
||||
}
|
||||
|
||||
fn deserialize_struct<V>(self,
|
||||
_name: &str,
|
||||
fields: &'static [&'static str],
|
||||
visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
fn deserialize_struct<V>(
|
||||
self,
|
||||
_name: &str,
|
||||
fields: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value>
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
self.deserialize_tuple(fields.len(), visitor)
|
||||
}
|
||||
|
||||
fn deserialize_identifier<V>(self,
|
||||
_visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
fn deserialize_identifier<V>(self, _visitor: V) -> Result<V::Value>
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
let message = "bincode does not support Deserializer::deserialize_identifier";
|
||||
let message = "Bincode does not support Deserializer::deserialize_identifier";
|
||||
Err(Error::custom(message))
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct<V>(self,
|
||||
_name: &str,
|
||||
visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value>
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
visitor.visit_newtype_struct(self)
|
||||
}
|
||||
|
||||
fn deserialize_unit_struct<V>(self,
|
||||
_name: &'static str,
|
||||
visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
visitor.visit_unit()
|
||||
}
|
||||
|
||||
fn deserialize_tuple_struct<V>(self,
|
||||
_name: &'static str,
|
||||
len: usize,
|
||||
visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
fn deserialize_tuple_struct<V>(
|
||||
self,
|
||||
_name: &'static str,
|
||||
len: usize,
|
||||
visitor: V,
|
||||
) -> Result<V::Value>
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
self.deserialize_tuple(len, visitor)
|
||||
}
|
||||
|
||||
fn deserialize_ignored_any<V>(self,
|
||||
_visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'de>,
|
||||
fn deserialize_ignored_any<V>(self, _visitor: V) -> Result<V::Value>
|
||||
where
|
||||
V: serde::de::Visitor<'de>,
|
||||
{
|
||||
let message = "bincode does not support Deserializer::deserialize_ignored_any";
|
||||
let message = "Bincode does not support Deserializer::deserialize_ignored_any";
|
||||
Err(Error::custom(message))
|
||||
}
|
||||
|
||||
fn is_human_readable(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, 'a, R, S, E> serde::de::VariantAccess<'de> for &'a mut Deserializer<R, S, E>
|
||||
where R: BincodeRead<'de>, S: SizeLimit, E: ByteOrder {
|
||||
impl<'de, 'a, R, O> serde::de::VariantAccess<'de> for &'a mut Deserializer<R, O>
|
||||
where R: BincodeRead<'de>, O: Options{
|
||||
type Error = Error;
|
||||
|
||||
fn unit_variant(self) -> Result<()> {
|
||||
|
@ -399,6 +457,7 @@ static UTF8_CHAR_WIDTH: [u8; 256] = [
|
|||
4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
|
||||
];
|
||||
|
||||
// This function is a copy of core::str::utf8_char_width
|
||||
fn utf8_char_width(b: u8) -> usize {
|
||||
UTF8_CHAR_WIDTH[b as usize] as usize
|
||||
}
|
||||
|
|
|
@ -1,43 +1,49 @@
|
|||
use std::io;
|
||||
use ::Result;
|
||||
use serde_crate as serde;
|
||||
use error::Result;
|
||||
use serde;
|
||||
|
||||
/// A byte-oriented reading trait that is specialized for
|
||||
/// slices and generic readers.
|
||||
pub trait BincodeRead<'storage>: io::Read + ::private::Sealed {
|
||||
#[doc(hidden)]
|
||||
fn forward_read_str<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'storage>;
|
||||
/// An optional Read trait for advanced Bincode usage.
|
||||
///
|
||||
/// It is highly recommended to use bincode with `io::Read` or `&[u8]` before
|
||||
/// implementing a custom `BincodeRead`.
|
||||
pub trait BincodeRead<'storage>: io::Read {
|
||||
/// Forwards reading `length` bytes of a string on to the serde reader.
|
||||
fn forward_read_str<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
|
||||
where
|
||||
V: serde::de::Visitor<'storage>;
|
||||
|
||||
#[doc(hidden)]
|
||||
/// Return the first `length` bytes of the internal byte buffer.
|
||||
fn get_byte_buffer(&mut self, length: usize) -> Result<Vec<u8>>;
|
||||
|
||||
#[doc(hidden)]
|
||||
fn forward_read_bytes<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'storage>;
|
||||
/// Forwards reading `length` bytes on to the serde reader.
|
||||
fn forward_read_bytes<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
|
||||
where
|
||||
V: serde::de::Visitor<'storage>;
|
||||
}
|
||||
|
||||
/// A BincodeRead implementation for byte slices
|
||||
/// NOT A PART OF THE STABLE PUBLIC API
|
||||
#[doc(hidden)]
|
||||
pub struct SliceReader<'storage> {
|
||||
slice: &'storage [u8]
|
||||
slice: &'storage [u8],
|
||||
}
|
||||
|
||||
/// A BincodeRead implementation for io::Readers
|
||||
/// NOT A PART OF THE STABLE PUBLIC API
|
||||
#[doc(hidden)]
|
||||
pub struct IoReader<R> {
|
||||
reader: R,
|
||||
temp_buffer: Vec<u8>,
|
||||
}
|
||||
|
||||
impl <'storage> SliceReader<'storage> {
|
||||
impl<'storage> SliceReader<'storage> {
|
||||
/// Constructs a slice reader
|
||||
pub fn new(bytes: &'storage [u8]) -> SliceReader<'storage> {
|
||||
SliceReader {
|
||||
slice: bytes,
|
||||
}
|
||||
SliceReader { slice: bytes }
|
||||
}
|
||||
}
|
||||
|
||||
impl <R> IoReader<R> {
|
||||
impl<R> IoReader<R> {
|
||||
/// Constructs an IoReadReader
|
||||
pub fn new(r: R) -> IoReader<R> {
|
||||
IoReader {
|
||||
|
@ -47,34 +53,44 @@ impl <R> IoReader<R> {
|
|||
}
|
||||
}
|
||||
|
||||
impl <'storage> io::Read for SliceReader<'storage> {
|
||||
fn read(&mut self, out: & mut [u8]) -> io::Result<usize> {
|
||||
impl<'storage> io::Read for SliceReader<'storage> {
|
||||
#[inline(always)]
|
||||
fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
|
||||
(&mut self.slice).read(out)
|
||||
}
|
||||
fn read_exact(&mut self, out: & mut [u8]) -> io::Result<()> {
|
||||
#[inline(always)]
|
||||
fn read_exact(&mut self, out: &mut [u8]) -> io::Result<()> {
|
||||
(&mut self.slice).read_exact(out)
|
||||
}
|
||||
}
|
||||
|
||||
impl <R: io::Read> io::Read for IoReader<R> {
|
||||
fn read(&mut self, out: & mut [u8]) -> io::Result<usize> {
|
||||
impl<R: io::Read> io::Read for IoReader<R> {
|
||||
#[inline(always)]
|
||||
fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
|
||||
self.reader.read(out)
|
||||
}
|
||||
fn read_exact(&mut self, out: & mut [u8]) -> io::Result<()> {
|
||||
#[inline(always)]
|
||||
fn read_exact(&mut self, out: &mut [u8]) -> io::Result<()> {
|
||||
self.reader.read_exact(out)
|
||||
}
|
||||
}
|
||||
|
||||
impl <'storage> SliceReader<'storage> {
|
||||
impl<'storage> SliceReader<'storage> {
|
||||
#[inline(always)]
|
||||
fn unexpected_eof() -> Box<::ErrorKind> {
|
||||
return Box::new(::ErrorKind::Io(io::Error::new(io::ErrorKind::UnexpectedEof, "")));
|
||||
return Box::new(::ErrorKind::Io(
|
||||
io::Error::new(io::ErrorKind::UnexpectedEof, ""),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
impl <'storage> BincodeRead<'storage> for SliceReader<'storage> {
|
||||
fn forward_read_str<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'storage> {
|
||||
use ::ErrorKind;
|
||||
impl<'storage> BincodeRead<'storage> for SliceReader<'storage> {
|
||||
#[inline(always)]
|
||||
fn forward_read_str<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
|
||||
where
|
||||
V: serde::de::Visitor<'storage>,
|
||||
{
|
||||
use ErrorKind;
|
||||
if length > self.slice.len() {
|
||||
return Err(SliceReader::unexpected_eof());
|
||||
}
|
||||
|
@ -88,6 +104,7 @@ impl <'storage> BincodeRead<'storage> for SliceReader<'storage> {
|
|||
r
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn get_byte_buffer(&mut self, length: usize) -> Result<Vec<u8>> {
|
||||
if length > self.slice.len() {
|
||||
return Err(SliceReader::unexpected_eof());
|
||||
|
@ -98,8 +115,11 @@ impl <'storage> BincodeRead<'storage> for SliceReader<'storage> {
|
|||
Ok(r.to_vec())
|
||||
}
|
||||
|
||||
fn forward_read_bytes<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'storage> {
|
||||
#[inline(always)]
|
||||
fn forward_read_bytes<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
|
||||
where
|
||||
V: serde::de::Visitor<'storage>,
|
||||
{
|
||||
if length > self.slice.len() {
|
||||
return Err(SliceReader::unexpected_eof());
|
||||
}
|
||||
|
@ -110,25 +130,36 @@ impl <'storage> BincodeRead<'storage> for SliceReader<'storage> {
|
|||
}
|
||||
}
|
||||
|
||||
impl <R> IoReader<R> where R: io::Read {
|
||||
impl<R> IoReader<R>
|
||||
where
|
||||
R: io::Read,
|
||||
{
|
||||
fn fill_buffer(&mut self, length: usize) -> Result<()> {
|
||||
let current_length = self.temp_buffer.len();
|
||||
if length > current_length{
|
||||
if length > current_length {
|
||||
self.temp_buffer.reserve_exact(length - current_length);
|
||||
unsafe { self.temp_buffer.set_len(length); }
|
||||
}
|
||||
|
||||
self.reader.read_exact(&mut self.temp_buffer[..length])?;
|
||||
unsafe {
|
||||
self.temp_buffer.set_len(length);
|
||||
}
|
||||
|
||||
self.reader.read_exact(&mut self.temp_buffer)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl <R> BincodeRead<'static> for IoReader<R> where R: io::Read {
|
||||
fn forward_read_str<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'static> {
|
||||
impl<R> BincodeRead<'static> for IoReader<R>
|
||||
where
|
||||
R: io::Read,
|
||||
{
|
||||
fn forward_read_str<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
|
||||
where
|
||||
V: serde::de::Visitor<'static>,
|
||||
{
|
||||
self.fill_buffer(length)?;
|
||||
|
||||
let string = match ::std::str::from_utf8(&self.temp_buffer[..length]) {
|
||||
let string = match ::std::str::from_utf8(&self.temp_buffer[..]) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return Err(::ErrorKind::InvalidUtf8Encoding(e).into()),
|
||||
};
|
||||
|
@ -139,13 +170,15 @@ impl <R> BincodeRead<'static> for IoReader<R> where R: io::Read {
|
|||
|
||||
fn get_byte_buffer(&mut self, length: usize) -> Result<Vec<u8>> {
|
||||
self.fill_buffer(length)?;
|
||||
Ok(self.temp_buffer[..length].to_vec())
|
||||
Ok(::std::mem::replace(&mut self.temp_buffer, Vec::new()))
|
||||
}
|
||||
|
||||
fn forward_read_bytes<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
|
||||
where V: serde::de::Visitor<'static> {
|
||||
fn forward_read_bytes<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
|
||||
where
|
||||
V: serde::de::Visitor<'static>,
|
||||
{
|
||||
self.fill_buffer(length)?;
|
||||
let r = visitor.visit_bytes(&self.temp_buffer[..length]);
|
||||
let r = visitor.visit_bytes(&self.temp_buffer[..]);
|
||||
r
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,119 @@
|
|||
use std::io;
|
||||
use std::{error, fmt};
|
||||
use std::str::Utf8Error;
|
||||
use std::error::Error as StdError;
|
||||
|
||||
use serde;
|
||||
|
||||
/// The result of a serialization or deserialization operation.
|
||||
pub type Result<T> = ::std::result::Result<T, Error>;
|
||||
|
||||
/// An error that can be produced during (de)serializing.
|
||||
pub type Error = Box<ErrorKind>;
|
||||
|
||||
/// The kind of error that can be produced during a serialization or deserialization.
|
||||
#[derive(Debug)]
|
||||
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.
|
||||
Io(io::Error),
|
||||
/// Returned if the deserializer attempts to deserialize a string that is not valid utf8
|
||||
InvalidUtf8Encoding(Utf8Error),
|
||||
/// Returned if the deserializer attempts to deserialize a bool that was
|
||||
/// not encoded as either a 1 or a 0
|
||||
InvalidBoolEncoding(u8),
|
||||
/// Returned if the deserializer attempts to deserialize a char that is not in the correct format.
|
||||
InvalidCharEncoding,
|
||||
/// Returned if the deserializer attempts to deserialize the tag of an enum that is
|
||||
/// not in the expected ranges
|
||||
InvalidTagEncoding(usize),
|
||||
/// Serde has a deserialize_any method that lets the format hint to the
|
||||
/// object which route to take in deserializing.
|
||||
DeserializeAnyNotSupported,
|
||||
/// If (de)serializing a message takes more than the provided size limit, this
|
||||
/// error is returned.
|
||||
SizeLimit,
|
||||
/// Bincode can not encode sequences of unknown length (like iterators).
|
||||
SequenceMustHaveLength,
|
||||
/// A custom error message from Serde.
|
||||
Custom(String),
|
||||
}
|
||||
|
||||
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> {
|
||||
match *self {
|
||||
ErrorKind::Io(ref err) => Some(err),
|
||||
ErrorKind::InvalidUtf8Encoding(_) => None,
|
||||
ErrorKind::InvalidBoolEncoding(_) => None,
|
||||
ErrorKind::InvalidCharEncoding => None,
|
||||
ErrorKind::InvalidTagEncoding(_) => None,
|
||||
ErrorKind::SequenceMustHaveLength => None,
|
||||
ErrorKind::DeserializeAnyNotSupported => None,
|
||||
ErrorKind::SizeLimit => None,
|
||||
ErrorKind::Custom(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<io::Error> for Error {
|
||||
fn from(err: io::Error) -> Error {
|
||||
ErrorKind::Io(err).into()
|
||||
}
|
||||
}
|
||||
|
||||
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::InvalidBoolEncoding(b) => {
|
||||
write!(fmt, "{}, expected 0 or 1, found {}", self.description(), b)
|
||||
}
|
||||
ErrorKind::InvalidCharEncoding => write!(fmt, "{}", self.description()),
|
||||
ErrorKind::InvalidTagEncoding(tag) => {
|
||||
write!(fmt, "{}, found {}", self.description(), tag)
|
||||
}
|
||||
ErrorKind::SequenceMustHaveLength => {
|
||||
write!(fmt, "{}", self.description())
|
||||
}
|
||||
ErrorKind::SizeLimit => write!(fmt, "{}", self.description()),
|
||||
ErrorKind::DeserializeAnyNotSupported => {
|
||||
write!(
|
||||
fmt,
|
||||
"Bincode does not support the serde::Deserializer::deserialize_any method"
|
||||
)
|
||||
}
|
||||
ErrorKind::Custom(ref s) => s.fmt(fmt),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl serde::de::Error for Error {
|
||||
fn custom<T: fmt::Display>(desc: T) -> Error {
|
||||
ErrorKind::Custom(desc.to_string()).into()
|
||||
}
|
||||
}
|
||||
|
||||
impl serde::ser::Error for Error {
|
||||
fn custom<T: fmt::Display>(msg: T) -> Self {
|
||||
ErrorKind::Custom(msg.to_string()).into()
|
||||
}
|
||||
}
|
|
@ -1,183 +1,50 @@
|
|||
//! A collection of serialization and deserialization functions
|
||||
//! that use the `serde` crate for the serializable and deserializable
|
||||
//! implementation.
|
||||
use std::io::{Read, Write};
|
||||
use serde;
|
||||
|
||||
use std::io::{self, Write, Read};
|
||||
use std::{error, fmt, result};
|
||||
use std::str::Utf8Error;
|
||||
use ::{CountSize, SizeLimit};
|
||||
use byteorder::{ByteOrder};
|
||||
use std::error::Error as StdError;
|
||||
use config::{Options, OptionsExt};
|
||||
use de::read::BincodeRead;
|
||||
use {ErrorKind, Result};
|
||||
|
||||
pub use super::de::{
|
||||
Deserializer,
|
||||
};
|
||||
|
||||
pub use super::ser::{
|
||||
Serializer,
|
||||
};
|
||||
|
||||
use super::ser::SizeChecker;
|
||||
|
||||
use serde_crate as serde;
|
||||
|
||||
/// The result of a serialization or deserialization operation.
|
||||
pub type Result<T> = result::Result<T, Error>;
|
||||
|
||||
/// An error that can be produced during (de)serializing.
|
||||
pub type Error = Box<ErrorKind>;
|
||||
|
||||
/// The kind of error that can be produced during a serialization or deserialization.
|
||||
#[derive(Debug)]
|
||||
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.
|
||||
Io(io::Error),
|
||||
/// Returned if the deserializer attempts to deserialize a string that is not valid utf8
|
||||
InvalidUtf8Encoding(Utf8Error),
|
||||
/// Returned if the deserializer attempts to deserialize a bool that was
|
||||
/// not encoded as either a 1 or a 0
|
||||
InvalidBoolEncoding(u8),
|
||||
/// Returned if the deserializer attempts to deserialize a char that is not in the correct format.
|
||||
InvalidCharEncoding,
|
||||
/// Returned if the deserializer attempts to deserialize the tag of an enum that is
|
||||
/// not in the expected ranges
|
||||
InvalidTagEncoding(usize),
|
||||
/// Serde has a deserialize_any method that lets the format hint to the
|
||||
/// object which route to take in deserializing.
|
||||
DeserializeAnyNotSupported,
|
||||
/// If (de)serializing a message takes more than the provided size limit, this
|
||||
/// error is returned.
|
||||
SizeLimit,
|
||||
/// Bincode can not encode sequences of unknown length (like iterators).
|
||||
SequenceMustHaveLength,
|
||||
/// A custom error message from Serde.
|
||||
Custom(String)
|
||||
#[derive(Clone)]
|
||||
struct CountSize<L: SizeLimit> {
|
||||
total: u64,
|
||||
other_limit: L,
|
||||
}
|
||||
|
||||
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't encode infinite sequences",
|
||||
ErrorKind::DeserializeAnyNotSupported => "bincode doesn't support serde::Deserializer::deserialize_any",
|
||||
ErrorKind::SizeLimit => "the size limit for decoding has been reached",
|
||||
ErrorKind::Custom(ref msg) => msg,
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
fn cause(&self) -> Option<&error::Error> {
|
||||
match *self {
|
||||
ErrorKind::Io(ref err) => Some(err),
|
||||
ErrorKind::InvalidUtf8Encoding(_) => None,
|
||||
ErrorKind::InvalidBoolEncoding(_) => None,
|
||||
ErrorKind::InvalidCharEncoding => None,
|
||||
ErrorKind::InvalidTagEncoding(_) => None,
|
||||
ErrorKind::SequenceMustHaveLength => None,
|
||||
ErrorKind::DeserializeAnyNotSupported => None,
|
||||
ErrorKind::SizeLimit => None,
|
||||
ErrorKind::Custom(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<io::Error> for Error {
|
||||
fn from(err: io::Error) -> Error {
|
||||
ErrorKind::Io(err).into()
|
||||
}
|
||||
}
|
||||
|
||||
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::InvalidBoolEncoding(b) =>
|
||||
write!(fmt, "{}, expected 0 or 1, found {}", self.description(), b),
|
||||
ErrorKind::InvalidCharEncoding =>
|
||||
write!(fmt, "{}", self.description()),
|
||||
ErrorKind::InvalidTagEncoding(tag) =>
|
||||
write!(fmt, "{}, found {}", self.description(), tag),
|
||||
ErrorKind::SequenceMustHaveLength =>
|
||||
write!(fmt, "bincode can only encode sequences and maps that have a knowable size ahead of time."),
|
||||
ErrorKind::SizeLimit =>
|
||||
write!(fmt, "size limit was exceeded"),
|
||||
ErrorKind::DeserializeAnyNotSupported=>
|
||||
write!(fmt, "bincode does not support the serde::Deserializer::deserialize_any method"),
|
||||
ErrorKind::Custom(ref s) =>
|
||||
s.fmt(fmt),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl serde::de::Error for Error {
|
||||
fn custom<T: fmt::Display>(desc: T) -> Error {
|
||||
ErrorKind::Custom(desc.to_string()).into()
|
||||
}
|
||||
}
|
||||
|
||||
impl serde::ser::Error for Error {
|
||||
fn custom<T: fmt::Display>(msg: T) -> Self {
|
||||
ErrorKind::Custom(msg.to_string()).into()
|
||||
}
|
||||
}
|
||||
|
||||
/// Serializes an object directly into a `Writer`.
|
||||
///
|
||||
/// If the serialization would take more bytes than allowed by `size_limit`, an error
|
||||
/// is returned and *no bytes* will be written into the `Writer`.
|
||||
///
|
||||
/// If this returns an `Error` (other than SizeLimit), assume that the
|
||||
/// writer is in an invalid state, as writing could bail out in the middle of
|
||||
/// serializing.
|
||||
pub fn serialize_into<W, T: ?Sized, S, E>(writer: W, value: &T, size_limit: S) -> Result<()>
|
||||
where W: Write, T: serde::Serialize, S: SizeLimit, E: ByteOrder
|
||||
pub(crate) fn serialize_into<W, T: ?Sized, O>(writer: W, value: &T, mut options: O) -> Result<()>
|
||||
where
|
||||
W: Write,
|
||||
T: serde::Serialize,
|
||||
O: Options,
|
||||
{
|
||||
if let Some(limit) = size_limit.limit() {
|
||||
try!(serialized_size_bounded(value, limit).ok_or(ErrorKind::SizeLimit));
|
||||
if options.limit().limit().is_some() {
|
||||
// "compute" the size for the side-effect
|
||||
// of returning Err if the bound was reached.
|
||||
serialized_size(value, &mut options)?;
|
||||
}
|
||||
|
||||
let mut serializer = Serializer::<_, E>::new(writer);
|
||||
let mut serializer = ::ser::Serializer::<_, O>::new(writer, options);
|
||||
serde::Serialize::serialize(value, &mut serializer)
|
||||
}
|
||||
|
||||
/// Serializes a serializable object into a `Vec` of bytes.
|
||||
///
|
||||
/// If the serialization would take more bytes than allowed by `size_limit`,
|
||||
/// an error is returned.
|
||||
pub fn serialize<T: ?Sized, S, E>(value: &T, size_limit: S) -> Result<Vec<u8>>
|
||||
where T: serde::Serialize, S: SizeLimit, E: ByteOrder
|
||||
pub(crate) fn serialize<T: ?Sized, O>(value: &T, mut options: O) -> Result<Vec<u8>>
|
||||
where
|
||||
T: serde::Serialize,
|
||||
O: Options,
|
||||
{
|
||||
let mut writer = match size_limit.limit() {
|
||||
Some(size_limit) => {
|
||||
let actual_size = try!(serialized_size_bounded(value, size_limit).ok_or(ErrorKind::SizeLimit));
|
||||
Vec::with_capacity(actual_size as usize)
|
||||
}
|
||||
None => {
|
||||
let size = serialized_size(value) as usize;
|
||||
Vec::with_capacity(size)
|
||||
}
|
||||
let mut writer = {
|
||||
let actual_size = serialized_size(value, &mut options)?;
|
||||
Vec::with_capacity(actual_size as usize)
|
||||
};
|
||||
|
||||
try!(serialize_into::<_, _, _, E>(&mut writer, value, super::Infinite));
|
||||
serialize_into(&mut writer, value, options.with_no_limit())?;
|
||||
Ok(writer)
|
||||
}
|
||||
|
||||
impl SizeLimit for CountSize {
|
||||
impl<L: SizeLimit> SizeLimit for CountSize<L> {
|
||||
fn add(&mut self, c: u64) -> Result<()> {
|
||||
self.other_limit.add(c)?;
|
||||
self.total += c;
|
||||
if let Some(limit) = self.limit {
|
||||
if self.total > limit {
|
||||
return Err(Box::new(ErrorKind::SizeLimit))
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
@ -186,64 +53,112 @@ impl SizeLimit for CountSize {
|
|||
}
|
||||
}
|
||||
|
||||
/// Returns the size that an object would be if serialized using bincode.
|
||||
///
|
||||
/// This is used internally as part of the check for encode_into, but it can
|
||||
/// be useful for preallocating buffers if thats your style.
|
||||
pub fn serialized_size<T: ?Sized>(value: &T) -> u64
|
||||
where T: serde::Serialize
|
||||
pub(crate) fn serialized_size<T: ?Sized, O: Options>(value: &T, mut options: O) -> Result<u64>
|
||||
where
|
||||
T: serde::Serialize,
|
||||
{
|
||||
let mut size_counter = SizeChecker {
|
||||
size_limit: CountSize { total: 0, limit: None }
|
||||
let old_limiter = options.limit().clone();
|
||||
let mut size_counter = ::ser::SizeChecker {
|
||||
options: ::config::WithOtherLimit::new(
|
||||
options,
|
||||
CountSize {
|
||||
total: 0,
|
||||
other_limit: old_limiter,
|
||||
},
|
||||
),
|
||||
};
|
||||
|
||||
value.serialize(&mut size_counter).ok();
|
||||
size_counter.size_limit.total
|
||||
let result = value.serialize(&mut size_counter);
|
||||
result.map(|_| size_counter.options.new_limit.total)
|
||||
}
|
||||
|
||||
/// Given a maximum size limit, check how large an object would be if it
|
||||
/// were to be serialized.
|
||||
///
|
||||
/// If it can be serialized in `max` or fewer bytes, that number will be returned
|
||||
/// inside `Some`. If it goes over bounds, then None is returned.
|
||||
pub fn serialized_size_bounded<T: ?Sized>(value: &T, max: u64) -> Option<u64>
|
||||
where T: serde::Serialize
|
||||
pub(crate) fn deserialize_from<R, T, O>(reader: R, options: O) -> Result<T>
|
||||
where
|
||||
R: Read,
|
||||
T: serde::de::DeserializeOwned,
|
||||
O: Options,
|
||||
{
|
||||
let mut size_counter = SizeChecker {
|
||||
size_limit: CountSize { total: 0, limit: Some(max) }
|
||||
};
|
||||
let reader = ::de::read::IoReader::new(reader);
|
||||
let mut deserializer = ::de::Deserializer::<_, O>::new(reader, options);
|
||||
serde::Deserialize::deserialize(&mut deserializer)
|
||||
}
|
||||
|
||||
match value.serialize(&mut size_counter) {
|
||||
Ok(_) => Some(size_counter.size_limit.total),
|
||||
Err(_) => None,
|
||||
pub(crate) fn deserialize_from_custom<'a, R, T, O>(reader: R, options: O) -> Result<T>
|
||||
where
|
||||
R: BincodeRead<'a>,
|
||||
T: serde::de::DeserializeOwned,
|
||||
O: Options,
|
||||
{
|
||||
let mut deserializer = ::de::Deserializer::<_, O>::new(reader, options);
|
||||
serde::Deserialize::deserialize(&mut deserializer)
|
||||
}
|
||||
|
||||
pub(crate) fn deserialize_in_place<'a, R, T, O>(reader: R, options: O, place: &mut T) -> Result<()>
|
||||
where
|
||||
R: BincodeRead<'a>,
|
||||
T: serde::de::Deserialize<'a>,
|
||||
O: Options,
|
||||
{
|
||||
let mut deserializer = ::de::Deserializer::<_, _>::new(reader, options);
|
||||
serde::Deserialize::deserialize_in_place(&mut deserializer, place)
|
||||
}
|
||||
|
||||
pub(crate) fn deserialize<'a, T, O>(bytes: &'a [u8], options: O) -> Result<T>
|
||||
where
|
||||
T: serde::de::Deserialize<'a>,
|
||||
O: Options,
|
||||
{
|
||||
let reader = ::de::read::SliceReader::new(bytes);
|
||||
let options = ::config::WithOtherLimit::new(options, Infinite);
|
||||
let mut deserializer = ::de::Deserializer::new(reader, options);
|
||||
serde::Deserialize::deserialize(&mut deserializer)
|
||||
}
|
||||
|
||||
|
||||
pub(crate) trait SizeLimit: Clone {
|
||||
/// Tells the SizeLimit that a certain number of bytes has been
|
||||
/// read or written. Returns Err if the limit has been exceeded.
|
||||
fn add(&mut self, n: u64) -> Result<()>;
|
||||
/// Returns the hard limit (if one exists)
|
||||
fn limit(&self) -> Option<u64>;
|
||||
}
|
||||
|
||||
|
||||
/// A SizeLimit that restricts serialized or deserialized messages from
|
||||
/// exceeding a certain byte length.
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct Bounded(pub u64);
|
||||
|
||||
/// A SizeLimit without a limit!
|
||||
/// Use this if you don't care about the size of encoded or decoded messages.
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct Infinite;
|
||||
|
||||
impl SizeLimit for Bounded {
|
||||
#[inline(always)]
|
||||
fn add(&mut self, n: u64) -> Result<()> {
|
||||
if self.0 >= n {
|
||||
self.0 -= n;
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Box::new(ErrorKind::SizeLimit))
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn limit(&self) -> Option<u64> {
|
||||
Some(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Deserializes an object directly from a `Read`er.
|
||||
///
|
||||
/// If the provided `SizeLimit` is reached, the deserialization will bail immediately.
|
||||
/// A SizeLimit can help prevent an attacker from flooding your server with
|
||||
/// a neverending stream of values that runs your server out of memory.
|
||||
///
|
||||
/// If this returns an `Error`, assume that the buffer that you passed
|
||||
/// in is in an invalid state, as the error could be returned during any point
|
||||
/// in the reading.
|
||||
pub fn deserialize_from<R, T, S, E>(reader: R, size_limit: S) -> Result<T>
|
||||
where R: Read, T: serde::de::DeserializeOwned, S: SizeLimit, E: ByteOrder
|
||||
{
|
||||
let reader = ::de::read::IoReader::new(reader);
|
||||
let mut deserializer = Deserializer::<_, S, E>::new(reader, size_limit);
|
||||
serde::Deserialize::deserialize(&mut deserializer)
|
||||
}
|
||||
impl SizeLimit for Infinite {
|
||||
#[inline(always)]
|
||||
fn add(&mut self, _: u64) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Deserializes a slice of bytes into an object.
|
||||
///
|
||||
/// This method does not have a size-limit because if you already have the bytes
|
||||
/// in memory, then you don't gain anything by having a limiter.
|
||||
pub fn deserialize<'a, T, E: ByteOrder>(bytes: &'a [u8]) -> Result<T>
|
||||
where T: serde::de::Deserialize<'a>,
|
||||
{
|
||||
let reader = ::de::read::SliceReader::new(bytes);
|
||||
let mut deserializer = Deserializer::<_, _, E>::new(reader, super::Infinite);
|
||||
serde::Deserialize::deserialize(&mut deserializer)
|
||||
#[inline(always)]
|
||||
fn limit(&self) -> Option<u64> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,32 +1,20 @@
|
|||
#![deny(missing_docs)]
|
||||
|
||||
//! `bincode` is a crate for encoding and decoding using a tiny binary
|
||||
//! serialization strategy.
|
||||
//!
|
||||
//! There are simple functions for encoding to `Vec<u8>` and decoding from
|
||||
//! `&[u8]`, but the meat of the library is the `serialize_into` and `deserialize_from`
|
||||
//! functions which respectively allow encoding into any `std::io::Write`
|
||||
//! or decode from any `std::io::Read`.
|
||||
//!
|
||||
//! ## Modules
|
||||
//! Until "default type parameters" lands, we have an extra module called `endian_choice`
|
||||
//! that duplicates all of the core bincode functionality but with the option to choose
|
||||
//! which endianness the integers are encoded using.
|
||||
//!
|
||||
//! The default endianness is little.
|
||||
//! Bincode is a crate for encoding and decoding using a tiny binary
|
||||
//! serialization strategy. Using it, you can easily go from having
|
||||
//! an object in memory, quickly serialize it to bytes, and then
|
||||
//! deserialize it back just as fast!
|
||||
//!
|
||||
//! ### Using Basic Functions
|
||||
//!
|
||||
//! ```rust
|
||||
//! extern crate bincode;
|
||||
//! use bincode::{serialize, deserialize, Bounded};
|
||||
//! use bincode::{serialize, deserialize};
|
||||
//! fn main() {
|
||||
//! // The object that we will serialize.
|
||||
//! let target = Some("hello world".to_string());
|
||||
//! // The maximum size of the encoded message.
|
||||
//! let limit = Bounded(20);
|
||||
//! let target: Option<String> = Some("hello world".to_string());
|
||||
//!
|
||||
//! let encoded: Vec<u8> = serialize(&target, limit).unwrap();
|
||||
//! let encoded: Vec<u8> = serialize(&target).unwrap();
|
||||
//! let decoded: Option<String> = deserialize(&encoded[..]).unwrap();
|
||||
//! assert_eq!(target, decoded);
|
||||
//! }
|
||||
|
@ -37,145 +25,141 @@
|
|||
#![crate_type = "dylib"]
|
||||
|
||||
extern crate byteorder;
|
||||
extern crate serde as serde_crate;
|
||||
extern crate serde;
|
||||
|
||||
mod config;
|
||||
mod ser;
|
||||
mod error;
|
||||
mod de;
|
||||
pub mod internal;
|
||||
mod internal;
|
||||
|
||||
pub mod read_types {
|
||||
//! The types that the deserializer uses for optimizations
|
||||
pub use ::de::read::{SliceReader, BincodeRead, IoReader};
|
||||
pub use error::{Error, ErrorKind, Result};
|
||||
pub use config::Config;
|
||||
pub use de::read::{BincodeRead, IoReader, SliceReader};
|
||||
|
||||
/// An object that implements this trait can be passed a
|
||||
/// serde::Deserializer without knowing its concrete type.
|
||||
///
|
||||
/// This trait should be used only for `with_deserializer` functions.
|
||||
#[doc(hidden)]
|
||||
pub trait DeserializerAcceptor<'a> {
|
||||
/// The return type for the accept method
|
||||
type Output;
|
||||
/// Accept a serde::Deserializer and do whatever you want with it.
|
||||
fn accept<T: serde::Deserializer<'a>>(self, T) -> Self::Output;
|
||||
}
|
||||
|
||||
use std::io::{Read, Write};
|
||||
|
||||
pub use internal::{ErrorKind, Error, Result, serialized_size, serialized_size_bounded};
|
||||
|
||||
/// A Deserializer that uses LittleEndian byteorder
|
||||
pub type Deserializer<W, S> = internal::Deserializer<W, S, byteorder::LittleEndian>;
|
||||
/// A Serializer that uses LittleEndian byteorder
|
||||
pub type Serializer<W> = internal::Serializer<W, byteorder::LittleEndian>;
|
||||
|
||||
/// Deserializes a slice of bytes into an object.
|
||||
/// An object that implements this trait can be passed a
|
||||
/// serde::Serializer without knowing its concrete type.
|
||||
///
|
||||
/// This method does not have a size-limit because if you already have the bytes
|
||||
/// in memory, then you don't gain anything by having a limiter.
|
||||
pub fn deserialize<'a, T>(bytes: &'a [u8]) -> internal::Result<T>
|
||||
where T: serde_crate::de::Deserialize<'a>,
|
||||
{
|
||||
internal::deserialize::<_, byteorder::LittleEndian>(bytes)
|
||||
/// This trait should be used only for `with_serializer` functions.
|
||||
#[doc(hidden)]
|
||||
pub trait SerializerAcceptor {
|
||||
/// The return type for the accept method
|
||||
type Output;
|
||||
/// Accept a serde::Serializer and do whatever you want with it.
|
||||
fn accept<T: serde::Serializer>(self, T) -> Self::Output;
|
||||
}
|
||||
|
||||
/// Deserializes an object directly from a `Buffer`ed Reader.
|
||||
/// Get a default configuration object.
|
||||
///
|
||||
/// If the provided `SizeLimit` is reached, the deserialization will bail immediately.
|
||||
/// A SizeLimit can help prevent an attacker from flooding your server with
|
||||
/// a neverending stream of values that runs your server out of memory.
|
||||
/// ### Default Configuration:
|
||||
///
|
||||
/// If this returns an `Error`, assume that the buffer that you passed
|
||||
/// in is in an invalid state, as the error could be returned during any point
|
||||
/// in the reading.
|
||||
pub fn deserialize_from<R: ?Sized, T, S>(reader: &mut R, size_limit: S) -> internal::Result<T>
|
||||
where R: Read, T: serde_crate::de::DeserializeOwned, S: SizeLimit
|
||||
{
|
||||
internal::deserialize_from::<_, _, _, byteorder::LittleEndian>(reader, size_limit)
|
||||
/// | Byte limit | Endianness |
|
||||
/// |------------|------------|
|
||||
/// | Unlimited | Little |
|
||||
pub fn config() -> Config {
|
||||
Config::new()
|
||||
}
|
||||
|
||||
/// Serializes an object directly into a `Writer`.
|
||||
/// Serializes an object directly into a `Writer` using the default configuration.
|
||||
///
|
||||
/// If the serialization would take more bytes than allowed by `size_limit`, an error
|
||||
/// 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`.
|
||||
///
|
||||
/// If this returns an `Error` (other than SizeLimit), assume that the
|
||||
/// writer is in an invalid state, as writing could bail out in the middle of
|
||||
/// serializing.
|
||||
pub fn serialize_into<W: ?Sized, T: ?Sized, S>(writer: &mut W, value: &T, size_limit: S) -> internal::Result<()>
|
||||
where W: Write, T: serde_crate::Serialize, S: SizeLimit
|
||||
pub fn serialize_into<W, T: ?Sized>(writer: W, value: &T) -> Result<()>
|
||||
where
|
||||
W: std::io::Write,
|
||||
T: serde::Serialize,
|
||||
{
|
||||
internal::serialize_into::<_, _, _, byteorder::LittleEndian>(writer, value, size_limit)
|
||||
config().serialize_into(writer, value)
|
||||
}
|
||||
|
||||
/// Serializes a serializable object into a `Vec` of bytes.
|
||||
///
|
||||
/// If the serialization would take more bytes than allowed by `size_limit`,
|
||||
/// an error is returned.
|
||||
pub fn serialize<T: ?Sized, S>(value: &T, size_limit: S) -> internal::Result<Vec<u8>>
|
||||
where T: serde_crate::Serialize, S: SizeLimit
|
||||
/// Serializes a serializable object into a `Vec` of bytes using the default configuration.
|
||||
pub fn serialize<T: ?Sized>(value: &T) -> Result<Vec<u8>>
|
||||
where
|
||||
T: serde::Serialize,
|
||||
{
|
||||
internal::serialize::<_, _, byteorder::LittleEndian>(value, size_limit)
|
||||
config().serialize(value)
|
||||
}
|
||||
|
||||
/// A limit on the amount of bytes that can be read or written.
|
||||
/// Deserializes an object directly from a `Read`er using the default configuration.
|
||||
///
|
||||
/// Size limits are an incredibly important part of both encoding and decoding.
|
||||
/// If this returns an `Error`, `reader` may be in an invalid state.
|
||||
pub fn deserialize_from<R, T>(reader: R) -> Result<T>
|
||||
where
|
||||
R: std::io::Read,
|
||||
T: serde::de::DeserializeOwned,
|
||||
{
|
||||
config().deserialize_from(reader)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
///
|
||||
/// In order to prevent DOS attacks on a decoder, it is important to limit the
|
||||
/// amount of bytes that a single encoded message can be; otherwise, if you
|
||||
/// are decoding bytes right off of a TCP stream for example, it would be
|
||||
/// possible for an attacker to flood your server with a 3TB vec, causing the
|
||||
/// decoder to run out of memory and crash your application!
|
||||
/// Because of this, you can provide a maximum-number-of-bytes that can be read
|
||||
/// during decoding, and the decoder will explicitly fail if it has to read
|
||||
/// any more than that.
|
||||
/// If this returns an `Error`, `reader` may be in an invalid state.
|
||||
pub fn deserialize_from_custom<'a, R, T>(reader: R) -> Result<T>
|
||||
where
|
||||
R: de::read::BincodeRead<'a>,
|
||||
T: serde::de::DeserializeOwned,
|
||||
{
|
||||
config().deserialize_from_custom(reader)
|
||||
}
|
||||
|
||||
/// Only use this if you know what you're doing.
|
||||
///
|
||||
/// On the other side, you want to make sure that you aren't encoding a message
|
||||
/// that is larger than your decoder expects. By supplying a size limit to an
|
||||
/// encoding function, the encoder will verify that the structure can be encoded
|
||||
/// within that limit. This verification occurs before any bytes are written to
|
||||
/// the Writer, so recovering from an error is easy.
|
||||
pub trait SizeLimit: private::Sealed {
|
||||
/// Tells the SizeLimit that a certain number of bytes has been
|
||||
/// read or written. Returns Err if the limit has been exceeded.
|
||||
fn add(&mut self, n: u64) -> Result<()>;
|
||||
/// Returns the hard limit (if one exists)
|
||||
fn limit(&self) -> Option<u64>;
|
||||
/// This is part of the public API.
|
||||
#[doc(hidden)]
|
||||
pub fn deserialize_in_place<'a, R, T>(reader: R, place: &mut T) -> Result<()>
|
||||
where
|
||||
T: serde::de::Deserialize<'a>,
|
||||
R: BincodeRead<'a>
|
||||
{
|
||||
config().deserialize_in_place(reader, place)
|
||||
}
|
||||
|
||||
/// A SizeLimit that restricts serialized or deserialized messages from
|
||||
/// exceeding a certain byte length.
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct Bounded(pub u64);
|
||||
|
||||
/// A SizeLimit without a limit!
|
||||
/// Use this if you don't care about the size of encoded or decoded messages.
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct Infinite;
|
||||
|
||||
struct CountSize {
|
||||
total: u64,
|
||||
limit: Option<u64>,
|
||||
/// Deserializes a slice of bytes into an instance of `T` using the default configuration.
|
||||
pub fn deserialize<'a, T>(bytes: &'a [u8]) -> Result<T>
|
||||
where
|
||||
T: serde::de::Deserialize<'a>,
|
||||
{
|
||||
config().deserialize(bytes)
|
||||
}
|
||||
|
||||
impl SizeLimit for Bounded {
|
||||
#[inline(always)]
|
||||
fn add(&mut self, n: u64) -> Result<()> {
|
||||
if self.0 >= n {
|
||||
self.0 -= n;
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Box::new(ErrorKind::SizeLimit))
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn limit(&self) -> Option<u64> { Some(self.0) }
|
||||
/// Returns the size that an object would be if serialized using Bincode with the default configuration.
|
||||
pub fn serialized_size<T: ?Sized>(value: &T) -> Result<u64>
|
||||
where
|
||||
T: serde::Serialize,
|
||||
{
|
||||
config().serialized_size(value)
|
||||
}
|
||||
|
||||
impl SizeLimit for Infinite {
|
||||
#[inline(always)]
|
||||
fn add(&mut self, _: u64) -> Result<()> { Ok (()) }
|
||||
|
||||
#[inline(always)]
|
||||
fn limit(&self) -> Option<u64> { None }
|
||||
/// Executes the acceptor with a serde::Deserializer instance.
|
||||
/// NOT A PART OF THE STABLE PUBLIC API
|
||||
#[doc(hidden)]
|
||||
pub fn with_deserializer<'a, A, R>(reader: R, acceptor: A) -> A::Output
|
||||
where A: DeserializerAcceptor<'a>,
|
||||
R: BincodeRead<'a>
|
||||
{
|
||||
config().with_deserializer(reader, acceptor)
|
||||
}
|
||||
|
||||
mod private {
|
||||
pub trait Sealed {}
|
||||
|
||||
impl<'a> Sealed for super::de::read::SliceReader<'a> {}
|
||||
impl<R> Sealed for super::de::read::IoReader<R> {}
|
||||
impl Sealed for super::Infinite {}
|
||||
impl Sealed for super::Bounded {}
|
||||
impl Sealed for super::CountSize {}
|
||||
/// Executes the acceptor with a serde::Serializer instance.
|
||||
/// NOT A PART OF THE STABLE PUBLIC API
|
||||
#[doc(hidden)]
|
||||
pub fn with_serializer<A, W>(writer: W, acceptor: A) -> A::Output
|
||||
where A: SerializerAcceptor,
|
||||
W: std::io::Write
|
||||
{
|
||||
config().with_serializer(writer, acceptor)
|
||||
}
|
||||
|
|
|
@ -1,13 +1,13 @@
|
|||
use std::io::Write;
|
||||
use std::u32;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use serde_crate as serde;
|
||||
use serde;
|
||||
|
||||
use byteorder::{WriteBytesExt, ByteOrder};
|
||||
use byteorder::WriteBytesExt;
|
||||
|
||||
use super::{Result, Error, ErrorKind};
|
||||
use super::SizeLimit;
|
||||
use ::config::Options;
|
||||
use super::internal::SizeLimit;
|
||||
|
||||
/// An Serializer that encodes values directly into a Writer.
|
||||
///
|
||||
|
@ -16,38 +16,44 @@ use super::SizeLimit;
|
|||
///
|
||||
/// This struct should not be used often.
|
||||
/// For most cases, prefer the `encode_into` function.
|
||||
pub struct Serializer<W, E: ByteOrder> {
|
||||
pub(crate) struct Serializer<W, O: Options> {
|
||||
writer: W,
|
||||
_phantom: PhantomData<E>,
|
||||
_options: O,
|
||||
}
|
||||
|
||||
impl<W: Write, E: ByteOrder> Serializer<W, E> {
|
||||
impl<W: Write, O: Options> Serializer<W, O> {
|
||||
/// Creates a new Serializer with the given `Write`r.
|
||||
pub fn new(w: W) -> Serializer<W, E> {
|
||||
pub fn new(w: W, options: O) -> Serializer<W, O> {
|
||||
Serializer {
|
||||
writer: w,
|
||||
_phantom: PhantomData,
|
||||
_options: options,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, W: Write, E: ByteOrder> serde::Serializer for &'a mut Serializer<W, E> {
|
||||
impl<'a, W: Write, O: Options> serde::Serializer for &'a mut Serializer<W, O> {
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
type SerializeSeq = Compound<'a, W, E>;
|
||||
type SerializeTuple = Compound<'a, W, E>;
|
||||
type SerializeTupleStruct = Compound<'a, W, E>;
|
||||
type SerializeTupleVariant = Compound<'a, W, E>;
|
||||
type SerializeMap = Compound<'a, W, E>;
|
||||
type SerializeStruct = Compound<'a, W, E>;
|
||||
type SerializeStructVariant = Compound<'a, W, E>;
|
||||
type SerializeSeq = Compound<'a, W, O>;
|
||||
type SerializeTuple = Compound<'a, W, O>;
|
||||
type SerializeTupleStruct = Compound<'a, W, O>;
|
||||
type SerializeTupleVariant = Compound<'a, W, O>;
|
||||
type SerializeMap = Compound<'a, W, O>;
|
||||
type SerializeStruct = Compound<'a, W, O>;
|
||||
type SerializeStructVariant = Compound<'a, W, O>;
|
||||
|
||||
fn serialize_unit(self) -> Result<()> { Ok(()) }
|
||||
fn serialize_unit(self) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_unit_struct(self, _: &'static str) -> Result<()> { Ok(()) }
|
||||
fn serialize_unit_struct(self, _: &'static str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_bool(self, v: bool) -> Result<()> {
|
||||
self.writer.write_u8(if v {1} else {0}).map_err(Into::into)
|
||||
self.writer.write_u8(if v { 1 } else { 0 }).map_err(
|
||||
Into::into,
|
||||
)
|
||||
}
|
||||
|
||||
fn serialize_u8(self, v: u8) -> Result<()> {
|
||||
|
@ -55,15 +61,15 @@ impl<'a, W: Write, E: ByteOrder> serde::Serializer for &'a mut Serializer<W, E>
|
|||
}
|
||||
|
||||
fn serialize_u16(self, v: u16) -> Result<()> {
|
||||
self.writer.write_u16::<E>(v).map_err(Into::into)
|
||||
self.writer.write_u16::<O::Endian>(v).map_err(Into::into)
|
||||
}
|
||||
|
||||
fn serialize_u32(self, v: u32) -> Result<()> {
|
||||
self.writer.write_u32::<E>(v).map_err(Into::into)
|
||||
self.writer.write_u32::<O::Endian>(v).map_err(Into::into)
|
||||
}
|
||||
|
||||
fn serialize_u64(self, v: u64) -> Result<()> {
|
||||
self.writer.write_u64::<E>(v).map_err(Into::into)
|
||||
self.writer.write_u64::<O::Endian>(v).map_err(Into::into)
|
||||
}
|
||||
|
||||
fn serialize_i8(self, v: i8) -> Result<()> {
|
||||
|
@ -71,23 +77,23 @@ impl<'a, W: Write, E: ByteOrder> serde::Serializer for &'a mut Serializer<W, E>
|
|||
}
|
||||
|
||||
fn serialize_i16(self, v: i16) -> Result<()> {
|
||||
self.writer.write_i16::<E>(v).map_err(Into::into)
|
||||
self.writer.write_i16::<O::Endian>(v).map_err(Into::into)
|
||||
}
|
||||
|
||||
fn serialize_i32(self, v: i32) -> Result<()> {
|
||||
self.writer.write_i32::<E>(v).map_err(Into::into)
|
||||
self.writer.write_i32::<O::Endian>(v).map_err(Into::into)
|
||||
}
|
||||
|
||||
fn serialize_i64(self, v: i64) -> Result<()> {
|
||||
self.writer.write_i64::<E>(v).map_err(Into::into)
|
||||
self.writer.write_i64::<O::Endian>(v).map_err(Into::into)
|
||||
}
|
||||
|
||||
fn serialize_f32(self, v: f32) -> Result<()> {
|
||||
self.writer.write_f32::<E>(v).map_err(Into::into)
|
||||
self.writer.write_f32::<O::Endian>(v).map_err(Into::into)
|
||||
}
|
||||
|
||||
fn serialize_f64(self, v: f64) -> Result<()> {
|
||||
self.writer.write_f64::<E>(v).map_err(Into::into)
|
||||
self.writer.write_f64::<O::Endian>(v).map_err(Into::into)
|
||||
}
|
||||
|
||||
fn serialize_str(self, v: &str) -> Result<()> {
|
||||
|
@ -96,7 +102,9 @@ impl<'a, W: Write, E: ByteOrder> serde::Serializer for &'a mut Serializer<W, E>
|
|||
}
|
||||
|
||||
fn serialize_char(self, c: char) -> Result<()> {
|
||||
self.writer.write_all(encode_utf8(c).as_slice()).map_err(Into::into)
|
||||
self.writer.write_all(encode_utf8(c).as_slice()).map_err(
|
||||
Into::into,
|
||||
)
|
||||
}
|
||||
|
||||
fn serialize_bytes(self, v: &[u8]) -> Result<()> {
|
||||
|
@ -109,7 +117,8 @@ impl<'a, W: Write, E: ByteOrder> serde::Serializer for &'a mut Serializer<W, E>
|
|||
}
|
||||
|
||||
fn serialize_some<T: ?Sized>(self, v: &T) -> Result<()>
|
||||
where T: serde::Serialize,
|
||||
where
|
||||
T: serde::Serialize,
|
||||
{
|
||||
try!(self.writer.write_u8(1));
|
||||
v.serialize(self)
|
||||
|
@ -118,87 +127,99 @@ impl<'a, W: Write, E: ByteOrder> serde::Serializer for &'a mut Serializer<W, E>
|
|||
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
|
||||
let len = try!(len.ok_or(ErrorKind::SequenceMustHaveLength));
|
||||
try!(self.serialize_u64(len as u64));
|
||||
Ok(Compound {ser: self})
|
||||
Ok(Compound { ser: self })
|
||||
}
|
||||
|
||||
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
|
||||
Ok(Compound {ser: self})
|
||||
Ok(Compound { ser: self })
|
||||
}
|
||||
|
||||
fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct> {
|
||||
Ok(Compound {ser: self})
|
||||
fn serialize_tuple_struct(
|
||||
self,
|
||||
_name: &'static str,
|
||||
_len: usize,
|
||||
) -> Result<Self::SerializeTupleStruct> {
|
||||
Ok(Compound { ser: self })
|
||||
}
|
||||
|
||||
fn serialize_tuple_variant(self,
|
||||
_name: &'static str,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
_len: usize) -> Result<Self::SerializeTupleVariant>
|
||||
{
|
||||
fn serialize_tuple_variant(
|
||||
self,
|
||||
_name: &'static str,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
_len: usize,
|
||||
) -> Result<Self::SerializeTupleVariant> {
|
||||
try!(self.serialize_u32(variant_index));
|
||||
Ok(Compound {ser: self})
|
||||
Ok(Compound { ser: self })
|
||||
}
|
||||
|
||||
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
|
||||
let len = try!(len.ok_or(ErrorKind::SequenceMustHaveLength));
|
||||
try!(self.serialize_u64(len as u64));
|
||||
Ok(Compound {ser: self})
|
||||
Ok(Compound { ser: self })
|
||||
}
|
||||
|
||||
fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
|
||||
Ok(Compound {ser: self})
|
||||
Ok(Compound { ser: self })
|
||||
}
|
||||
|
||||
fn serialize_struct_variant(self,
|
||||
_name: &'static str,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
_len: usize) -> Result<Self::SerializeStructVariant>
|
||||
{
|
||||
fn serialize_struct_variant(
|
||||
self,
|
||||
_name: &'static str,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
_len: usize,
|
||||
) -> Result<Self::SerializeStructVariant> {
|
||||
try!(self.serialize_u32(variant_index));
|
||||
Ok(Compound {ser: self})
|
||||
Ok(Compound { ser: self })
|
||||
}
|
||||
|
||||
fn serialize_newtype_struct<T: ?Sized>(self,
|
||||
_name: &'static str,
|
||||
value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize,
|
||||
fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) -> Result<()>
|
||||
where
|
||||
T: serde::ser::Serialize,
|
||||
{
|
||||
value.serialize(self)
|
||||
}
|
||||
|
||||
fn serialize_newtype_variant<T: ?Sized>(self,
|
||||
_name: &'static str,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize,
|
||||
fn serialize_newtype_variant<T: ?Sized>(
|
||||
self,
|
||||
_name: &'static str,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
value: &T,
|
||||
) -> Result<()>
|
||||
where
|
||||
T: serde::ser::Serialize,
|
||||
{
|
||||
try!(self.serialize_u32(variant_index));
|
||||
value.serialize(self)
|
||||
}
|
||||
|
||||
fn serialize_unit_variant(self,
|
||||
_name: &'static str,
|
||||
variant_index: u32,
|
||||
_variant: &'static str) -> Result<()> {
|
||||
fn serialize_unit_variant(
|
||||
self,
|
||||
_name: &'static str,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
) -> Result<()> {
|
||||
self.serialize_u32(variant_index)
|
||||
}
|
||||
|
||||
fn is_human_readable(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SizeChecker<S: SizeLimit> {
|
||||
pub size_limit: S,
|
||||
pub(crate) struct SizeChecker<O: Options> {
|
||||
pub options: O,
|
||||
}
|
||||
|
||||
impl <S: SizeLimit> SizeChecker<S> {
|
||||
pub fn new(size_limit: S) -> SizeChecker<S> {
|
||||
SizeChecker {
|
||||
size_limit: size_limit
|
||||
}
|
||||
impl<O: Options> SizeChecker<O> {
|
||||
pub fn new(options: O) -> SizeChecker<O> {
|
||||
SizeChecker { options: options }
|
||||
}
|
||||
|
||||
fn add_raw(&mut self, size: u64) -> Result<()> {
|
||||
self.size_limit.add(size)
|
||||
self.options.limit().add(size)
|
||||
}
|
||||
|
||||
fn add_value<T>(&mut self, t: T) -> Result<()> {
|
||||
|
@ -207,20 +228,24 @@ impl <S: SizeLimit> SizeChecker<S> {
|
|||
}
|
||||
}
|
||||
|
||||
impl<'a, S: SizeLimit> serde::Serializer for &'a mut SizeChecker<S> {
|
||||
impl<'a, O: Options> serde::Serializer for &'a mut SizeChecker<O> {
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
type SerializeSeq = SizeCompound<'a, S>;
|
||||
type SerializeTuple = SizeCompound<'a, S>;
|
||||
type SerializeTupleStruct = SizeCompound<'a, S>;
|
||||
type SerializeTupleVariant = SizeCompound<'a, S>;
|
||||
type SerializeMap = SizeCompound<'a, S>;
|
||||
type SerializeStruct = SizeCompound<'a, S>;
|
||||
type SerializeStructVariant = SizeCompound<'a, S>;
|
||||
type SerializeSeq = SizeCompound<'a, O>;
|
||||
type SerializeTuple = SizeCompound<'a, O>;
|
||||
type SerializeTupleStruct = SizeCompound<'a, O>;
|
||||
type SerializeTupleVariant = SizeCompound<'a, O>;
|
||||
type SerializeMap = SizeCompound<'a, O>;
|
||||
type SerializeStruct = SizeCompound<'a, O>;
|
||||
type SerializeStructVariant = SizeCompound<'a, O>;
|
||||
|
||||
fn serialize_unit(self) -> Result<()> { Ok(()) }
|
||||
fn serialize_unit(self) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_unit_struct(self, _: &'static str) -> Result<()> { Ok(()) }
|
||||
fn serialize_unit_struct(self, _: &'static str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_bool(self, _: bool) -> Result<()> {
|
||||
self.add_value(0 as u8)
|
||||
|
@ -285,7 +310,8 @@ impl<'a, S: SizeLimit> serde::Serializer for &'a mut SizeChecker<S> {
|
|||
}
|
||||
|
||||
fn serialize_some<T: ?Sized>(self, v: &T) -> Result<()>
|
||||
where T: serde::Serialize,
|
||||
where
|
||||
T: serde::Serialize,
|
||||
{
|
||||
try!(self.add_value(1 as u8));
|
||||
v.serialize(self)
|
||||
|
@ -295,85 +321,103 @@ impl<'a, S: SizeLimit> serde::Serializer for &'a mut SizeChecker<S> {
|
|||
let len = try!(len.ok_or(ErrorKind::SequenceMustHaveLength));
|
||||
|
||||
try!(self.serialize_u64(len as u64));
|
||||
Ok(SizeCompound {ser: self})
|
||||
Ok(SizeCompound { ser: self })
|
||||
}
|
||||
|
||||
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
|
||||
Ok(SizeCompound {ser: self})
|
||||
Ok(SizeCompound { ser: self })
|
||||
}
|
||||
|
||||
fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct> {
|
||||
Ok(SizeCompound {ser: self})
|
||||
fn serialize_tuple_struct(
|
||||
self,
|
||||
_name: &'static str,
|
||||
_len: usize,
|
||||
) -> Result<Self::SerializeTupleStruct> {
|
||||
Ok(SizeCompound { ser: self })
|
||||
}
|
||||
|
||||
fn serialize_tuple_variant(self,
|
||||
_name: &'static str,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
_len: usize) -> Result<Self::SerializeTupleVariant>
|
||||
{
|
||||
fn serialize_tuple_variant(
|
||||
self,
|
||||
_name: &'static str,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
_len: usize,
|
||||
) -> Result<Self::SerializeTupleVariant> {
|
||||
try!(self.add_value(variant_index));
|
||||
Ok(SizeCompound {ser: self})
|
||||
Ok(SizeCompound { ser: self })
|
||||
}
|
||||
|
||||
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap>
|
||||
{
|
||||
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
|
||||
let len = try!(len.ok_or(ErrorKind::SequenceMustHaveLength));
|
||||
|
||||
try!(self.serialize_u64(len as u64));
|
||||
Ok(SizeCompound {ser: self})
|
||||
Ok(SizeCompound { ser: self })
|
||||
}
|
||||
|
||||
fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
|
||||
Ok(SizeCompound {ser: self})
|
||||
Ok(SizeCompound { ser: self })
|
||||
}
|
||||
|
||||
fn serialize_struct_variant(self,
|
||||
_name: &'static str,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
_len: usize) -> Result<Self::SerializeStructVariant>
|
||||
{
|
||||
fn serialize_struct_variant(
|
||||
self,
|
||||
_name: &'static str,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
_len: usize,
|
||||
) -> Result<Self::SerializeStructVariant> {
|
||||
try!(self.add_value(variant_index));
|
||||
Ok(SizeCompound {ser: self})
|
||||
Ok(SizeCompound { ser: self })
|
||||
}
|
||||
|
||||
fn serialize_newtype_struct<V: serde::Serialize + ?Sized>(self, _name: &'static str, v: &V) -> Result<()> {
|
||||
fn serialize_newtype_struct<V: serde::Serialize + ?Sized>(
|
||||
self,
|
||||
_name: &'static str,
|
||||
v: &V,
|
||||
) -> Result<()> {
|
||||
v.serialize(self)
|
||||
}
|
||||
|
||||
fn serialize_unit_variant(self,
|
||||
_name: &'static str,
|
||||
variant_index: u32,
|
||||
_variant: &'static str) -> Result<()> {
|
||||
fn serialize_unit_variant(
|
||||
self,
|
||||
_name: &'static str,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
) -> Result<()> {
|
||||
self.add_value(variant_index)
|
||||
}
|
||||
|
||||
fn serialize_newtype_variant<V: serde::Serialize + ?Sized>(self,
|
||||
_name: &'static str,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
value: &V) -> Result<()>
|
||||
{
|
||||
fn serialize_newtype_variant<V: serde::Serialize + ?Sized>(
|
||||
self,
|
||||
_name: &'static str,
|
||||
variant_index: u32,
|
||||
_variant: &'static str,
|
||||
value: &V,
|
||||
) -> Result<()> {
|
||||
try!(self.add_value(variant_index));
|
||||
value.serialize(self)
|
||||
}
|
||||
|
||||
fn is_human_readable(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct Compound<'a, W: 'a, E: ByteOrder + 'a> {
|
||||
ser: &'a mut Serializer<W, E>,
|
||||
pub(crate) struct Compound<'a, W: 'a, O: Options + 'a> {
|
||||
ser: &'a mut Serializer<W, O>,
|
||||
}
|
||||
|
||||
impl<'a, W, E> serde::ser::SerializeSeq for Compound<'a, W, E>
|
||||
where W: Write, E: ByteOrder
|
||||
impl<'a, W, O> serde::ser::SerializeSeq for Compound<'a, W, O>
|
||||
where
|
||||
W: Write,
|
||||
O: Options,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
where
|
||||
T: serde::ser::Serialize,
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -384,15 +428,18 @@ impl<'a, W, E> serde::ser::SerializeSeq for Compound<'a, W, E>
|
|||
}
|
||||
}
|
||||
|
||||
impl<'a, W, E> serde::ser::SerializeTuple for Compound<'a, W, E>
|
||||
where W: Write, E: ByteOrder
|
||||
impl<'a, W, O> serde::ser::SerializeTuple for Compound<'a, W, O>
|
||||
where
|
||||
W: Write,
|
||||
O: Options,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
where
|
||||
T: serde::ser::Serialize,
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -403,15 +450,18 @@ impl<'a, W, E> serde::ser::SerializeTuple for Compound<'a, W, E>
|
|||
}
|
||||
}
|
||||
|
||||
impl<'a, W, E> serde::ser::SerializeTupleStruct for Compound<'a, W, E>
|
||||
where W: Write, E: ByteOrder
|
||||
impl<'a, W, O> serde::ser::SerializeTupleStruct for Compound<'a, W, O>
|
||||
where
|
||||
W: Write,
|
||||
O: Options,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
where
|
||||
T: serde::ser::Serialize,
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -422,15 +472,18 @@ impl<'a, W, E> serde::ser::SerializeTupleStruct for Compound<'a, W, E>
|
|||
}
|
||||
}
|
||||
|
||||
impl<'a, W, E> serde::ser::SerializeTupleVariant for Compound<'a, W, E>
|
||||
where W: Write, E: ByteOrder
|
||||
impl<'a, W, O> serde::ser::SerializeTupleVariant for Compound<'a, W, O>
|
||||
where
|
||||
W: Write,
|
||||
O: Options,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
where
|
||||
T: serde::ser::Serialize,
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -441,22 +494,26 @@ impl<'a, W, E> serde::ser::SerializeTupleVariant for Compound<'a, W, E>
|
|||
}
|
||||
}
|
||||
|
||||
impl<'a, W, E> serde::ser::SerializeMap for Compound<'a, W, E>
|
||||
where W: Write, E: ByteOrder
|
||||
impl<'a, W, O> serde::ser::SerializeMap for Compound<'a, W, O>
|
||||
where
|
||||
W: Write,
|
||||
O: Options,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_key<K: ?Sized>(&mut self, value: &K) -> Result<()>
|
||||
where K: serde::ser::Serialize
|
||||
where
|
||||
K: serde::ser::Serialize,
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[inline]
|
||||
fn serialize_value<V: ?Sized>(&mut self, value: &V) -> Result<()>
|
||||
where V: serde::ser::Serialize
|
||||
where
|
||||
V: serde::ser::Serialize,
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -467,15 +524,18 @@ impl<'a, W, E> serde::ser::SerializeMap for Compound<'a, W, E>
|
|||
}
|
||||
}
|
||||
|
||||
impl<'a, W, E> serde::ser::SerializeStruct for Compound<'a, W, E>
|
||||
where W: Write, E: ByteOrder
|
||||
impl<'a, W, O> serde::ser::SerializeStruct for Compound<'a, W, O>
|
||||
where
|
||||
W: Write,
|
||||
O: Options,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
where
|
||||
T: serde::ser::Serialize,
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -486,15 +546,18 @@ impl<'a, W, E> serde::ser::SerializeStruct for Compound<'a, W, E>
|
|||
}
|
||||
}
|
||||
|
||||
impl<'a, W, E> serde::ser::SerializeStructVariant for Compound<'a, W, E>
|
||||
where W: Write, E: ByteOrder
|
||||
impl<'a, W, O> serde::ser::SerializeStructVariant for Compound<'a, W, O>
|
||||
where
|
||||
W: Write,
|
||||
O: Options,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
where
|
||||
T: serde::ser::Serialize,
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -505,19 +568,18 @@ impl<'a, W, E> serde::ser::SerializeStructVariant for Compound<'a, W, E>
|
|||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct SizeCompound<'a, S: SizeLimit + 'a> {
|
||||
pub(crate) struct SizeCompound<'a, S: Options + 'a> {
|
||||
ser: &'a mut SizeChecker<S>,
|
||||
}
|
||||
|
||||
impl<'a, S: SizeLimit> serde::ser::SerializeSeq for SizeCompound<'a, S>
|
||||
{
|
||||
impl<'a, O: Options> serde::ser::SerializeSeq for SizeCompound<'a, O> {
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
where
|
||||
T: serde::ser::Serialize,
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -528,14 +590,14 @@ impl<'a, S: SizeLimit> serde::ser::SerializeSeq for SizeCompound<'a, S>
|
|||
}
|
||||
}
|
||||
|
||||
impl<'a, S: SizeLimit> serde::ser::SerializeTuple for SizeCompound<'a, S>
|
||||
{
|
||||
impl<'a, O: Options> serde::ser::SerializeTuple for SizeCompound<'a, O> {
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
where
|
||||
T: serde::ser::Serialize,
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -546,14 +608,14 @@ impl<'a, S: SizeLimit> serde::ser::SerializeTuple for SizeCompound<'a, S>
|
|||
}
|
||||
}
|
||||
|
||||
impl<'a, S: SizeLimit> serde::ser::SerializeTupleStruct for SizeCompound<'a, S>
|
||||
{
|
||||
impl<'a, O: Options> serde::ser::SerializeTupleStruct for SizeCompound<'a, O> {
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
where
|
||||
T: serde::ser::Serialize,
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -564,14 +626,14 @@ impl<'a, S: SizeLimit> serde::ser::SerializeTupleStruct for SizeCompound<'a, S>
|
|||
}
|
||||
}
|
||||
|
||||
impl<'a, S: SizeLimit> serde::ser::SerializeTupleVariant for SizeCompound<'a, S>
|
||||
{
|
||||
impl<'a, O: Options> serde::ser::SerializeTupleVariant for SizeCompound<'a, O> {
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
where
|
||||
T: serde::ser::Serialize,
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -582,21 +644,22 @@ impl<'a, S: SizeLimit> serde::ser::SerializeTupleVariant for SizeCompound<'a, S>
|
|||
}
|
||||
}
|
||||
|
||||
impl<'a, S: SizeLimit + 'a> serde::ser::SerializeMap for SizeCompound<'a, S>
|
||||
{
|
||||
impl<'a, O: Options+ 'a> serde::ser::SerializeMap for SizeCompound<'a, O> {
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_key<K: ?Sized>(&mut self, value: &K) -> Result<()>
|
||||
where K: serde::ser::Serialize
|
||||
where
|
||||
K: serde::ser::Serialize,
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[inline]
|
||||
fn serialize_value<V: ?Sized>(&mut self, value: &V) -> Result<()>
|
||||
where V: serde::ser::Serialize
|
||||
where
|
||||
V: serde::ser::Serialize,
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -607,14 +670,14 @@ impl<'a, S: SizeLimit + 'a> serde::ser::SerializeMap for SizeCompound<'a, S>
|
|||
}
|
||||
}
|
||||
|
||||
impl<'a, S: SizeLimit> serde::ser::SerializeStruct for SizeCompound<'a, S>
|
||||
{
|
||||
impl<'a, O: Options> serde::ser::SerializeStruct for SizeCompound<'a, O> {
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
where
|
||||
T: serde::ser::Serialize,
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -625,14 +688,14 @@ impl<'a, S: SizeLimit> serde::ser::SerializeStruct for SizeCompound<'a, S>
|
|||
}
|
||||
}
|
||||
|
||||
impl<'a, S: SizeLimit> serde::ser::SerializeStructVariant for SizeCompound<'a, S>
|
||||
{
|
||||
impl<'a, O: Options> serde::ser::SerializeStructVariant for SizeCompound<'a, O> {
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
|
||||
where T: serde::ser::Serialize
|
||||
where
|
||||
T: serde::ser::Serialize,
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
@ -642,13 +705,13 @@ impl<'a, S: SizeLimit> serde::ser::SerializeStructVariant for SizeCompound<'a, S
|
|||
Ok(())
|
||||
}
|
||||
}
|
||||
const TAG_CONT: u8 = 0b1000_0000;
|
||||
const TAG_TWO_B: u8 = 0b1100_0000;
|
||||
const TAG_CONT: u8 = 0b1000_0000;
|
||||
const TAG_TWO_B: u8 = 0b1100_0000;
|
||||
const TAG_THREE_B: u8 = 0b1110_0000;
|
||||
const TAG_FOUR_B: u8 = 0b1111_0000;
|
||||
const MAX_ONE_B: u32 = 0x80;
|
||||
const MAX_TWO_B: u32 = 0x800;
|
||||
const MAX_THREE_B: u32 = 0x10000;
|
||||
const TAG_FOUR_B: u8 = 0b1111_0000;
|
||||
const MAX_ONE_B: u32 = 0x80;
|
||||
const MAX_TWO_B: u32 = 0x800;
|
||||
const MAX_THREE_B: u32 = 0x10000;
|
||||
|
||||
fn encode_utf8(c: char) -> EncodeUtf8 {
|
||||
let code = c as u32;
|
||||
|
@ -662,13 +725,13 @@ fn encode_utf8(c: char) -> EncodeUtf8 {
|
|||
2
|
||||
} else if code < MAX_THREE_B {
|
||||
buf[1] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
|
||||
buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[3] = (code & 0x3F) as u8 | TAG_CONT;
|
||||
1
|
||||
} else {
|
||||
buf[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
|
||||
buf[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[3] = (code & 0x3F) as u8 | TAG_CONT;
|
||||
0
|
||||
};
|
||||
|
|
|
@ -1,426 +0,0 @@
|
|||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
extern crate bincode;
|
||||
extern crate serde;
|
||||
extern crate serde_bytes;
|
||||
extern crate byteorder;
|
||||
|
||||
use std::fmt::Debug;
|
||||
use std::collections::HashMap;
|
||||
use std::borrow::Cow;
|
||||
|
||||
use bincode::{Infinite, Bounded};
|
||||
use bincode::{serialized_size, ErrorKind, Result};
|
||||
use bincode::internal::{serialize, deserialize, deserialize_from};
|
||||
|
||||
use bincode::serialize as serialize_little;
|
||||
use bincode::deserialize as deserialize_little;
|
||||
use bincode::deserialize_from as deserialize_from_little;
|
||||
|
||||
fn the_same<V>(element: V)
|
||||
where V: serde::Serialize+serde::de::DeserializeOwned+PartialEq+Debug+'static
|
||||
{
|
||||
let size = serialized_size(&element);
|
||||
|
||||
{
|
||||
let encoded = serialize_little(&element, Infinite).unwrap();
|
||||
let decoded = deserialize_little(&encoded[..]).unwrap();
|
||||
|
||||
assert_eq!(element, decoded);
|
||||
assert_eq!(size, encoded.len() as u64);
|
||||
}
|
||||
|
||||
{
|
||||
let encoded = serialize::<_, _, byteorder::BigEndian>(&element, Infinite).unwrap();
|
||||
let decoded = deserialize::<_, byteorder::BigEndian>(&encoded[..]).unwrap();
|
||||
let decoded_reader = deserialize_from::<_, _, _, byteorder::BigEndian>(&mut &encoded[..], Infinite).unwrap();
|
||||
|
||||
assert_eq!(element, decoded);
|
||||
assert_eq!(element, decoded_reader);
|
||||
assert_eq!(size, encoded.len() as u64);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_numbers() {
|
||||
// unsigned positive
|
||||
the_same(5u8);
|
||||
the_same(5u16);
|
||||
the_same(5u32);
|
||||
the_same(5u64);
|
||||
the_same(5usize);
|
||||
// signed positive
|
||||
the_same(5i8);
|
||||
the_same(5i16);
|
||||
the_same(5i32);
|
||||
the_same(5i64);
|
||||
the_same(5isize);
|
||||
// signed negative
|
||||
the_same(-5i8);
|
||||
the_same(-5i16);
|
||||
the_same(-5i32);
|
||||
the_same(-5i64);
|
||||
the_same(-5isize);
|
||||
// floating
|
||||
the_same(-100f32);
|
||||
the_same(0f32);
|
||||
the_same(5f32);
|
||||
the_same(-100f64);
|
||||
the_same(5f64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_string() {
|
||||
the_same("".to_string());
|
||||
the_same("a".to_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple() {
|
||||
the_same((1isize,));
|
||||
the_same((1isize,2isize,3isize));
|
||||
the_same((1isize,"foo".to_string(),()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_basic_struct() {
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
struct Easy {
|
||||
x: isize,
|
||||
s: String,
|
||||
y: usize
|
||||
}
|
||||
the_same(Easy{x: -4, s: "foo".to_string(), y: 10});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_nested_struct() {
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
struct Easy {
|
||||
x: isize,
|
||||
s: String,
|
||||
y: usize
|
||||
}
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
struct Nest {
|
||||
f: Easy,
|
||||
b: usize,
|
||||
s: Easy
|
||||
}
|
||||
|
||||
the_same(Nest {
|
||||
f: Easy {x: -1, s: "foo".to_string(), y: 20},
|
||||
b: 100,
|
||||
s: Easy {x: -100, s: "bar".to_string(), y: 20}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_struct_newtype() {
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
struct NewtypeStr(usize);
|
||||
|
||||
the_same(NewtypeStr(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_struct_tuple() {
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
struct TubStr(usize, String, f32);
|
||||
|
||||
the_same(TubStr(5, "hello".to_string(), 3.2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_option() {
|
||||
the_same(Some(5usize));
|
||||
the_same(Some("foo bar".to_string()));
|
||||
the_same(None::<usize>);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_enum() {
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
enum TestEnum {
|
||||
NoArg,
|
||||
OneArg(usize),
|
||||
Args(usize, usize),
|
||||
AnotherNoArg,
|
||||
StructLike{x: usize, y: f32}
|
||||
}
|
||||
the_same(TestEnum::NoArg);
|
||||
the_same(TestEnum::OneArg(4));
|
||||
//the_same(TestEnum::Args(4, 5));
|
||||
the_same(TestEnum::AnotherNoArg);
|
||||
the_same(TestEnum::StructLike{x: 4, y: 3.14159});
|
||||
the_same(vec![TestEnum::NoArg, TestEnum::OneArg(5), TestEnum::AnotherNoArg,
|
||||
TestEnum::StructLike{x: 4, y:1.4}]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_vec() {
|
||||
let v: Vec<u8> = vec![];
|
||||
the_same(v);
|
||||
the_same(vec![1u64]);
|
||||
the_same(vec![1u64,2,3,4,5,6]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_map() {
|
||||
let mut m = HashMap::new();
|
||||
m.insert(4u64, "foo".to_string());
|
||||
m.insert(0u64, "bar".to_string());
|
||||
the_same(m);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bool() {
|
||||
the_same(true);
|
||||
the_same(false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_unicode() {
|
||||
the_same("å".to_string());
|
||||
the_same("aåååååååa".to_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fixed_size_array() {
|
||||
the_same([24u32; 32]);
|
||||
the_same([1u64, 2, 3, 4, 5, 6, 7, 8]);
|
||||
the_same([0u8; 19]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserializing_errors() {
|
||||
|
||||
match *deserialize_little::<bool>(&vec![0xA][..]).unwrap_err() {
|
||||
ErrorKind::InvalidBoolEncoding(0xA) => {},
|
||||
_ => panic!(),
|
||||
}
|
||||
match *deserialize_little::<String>(&vec![1, 0, 0, 0, 0, 0, 0, 0, 0xFF][..]).unwrap_err() {
|
||||
ErrorKind::InvalidUtf8Encoding(_) => {},
|
||||
_ => panic!(),
|
||||
}
|
||||
|
||||
// Out-of-bounds variant
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
enum Test {
|
||||
One,
|
||||
Two,
|
||||
};
|
||||
|
||||
match *deserialize_little::<Test>(&vec![0, 0, 0, 5][..]).unwrap_err() {
|
||||
// Error message comes from serde
|
||||
ErrorKind::Custom(_) => {},
|
||||
_ => panic!(),
|
||||
}
|
||||
match *deserialize_little::<Option<u8>>(&vec![5, 0][..]).unwrap_err() {
|
||||
ErrorKind::InvalidTagEncoding(_) => {},
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_big_deserialize() {
|
||||
let serialized = vec![0,0,0,3];
|
||||
let deserialized: Result<u32> = deserialize_from_little::<_, _, _>(&mut &serialized[..], Bounded(3));
|
||||
assert!(deserialized.is_err());
|
||||
|
||||
let serialized = vec![0,0,0,3];
|
||||
let deserialized: Result<u32> = deserialize_from_little::<_, _, _>(&mut &serialized[..], Bounded(4));
|
||||
assert!(deserialized.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn char_serialization() {
|
||||
let chars = "Aa\0☺♪";
|
||||
for c in chars.chars() {
|
||||
let encoded = serialize_little(&c, Bounded(4)).expect("serializing char failed");
|
||||
let decoded: char = deserialize_little(&encoded).expect("deserializing failed");
|
||||
assert_eq!(decoded, c);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_big_char_deserialize() {
|
||||
let serialized = vec![0x41];
|
||||
let deserialized: Result<char> = deserialize_from_little::<_, _, _>(&mut &serialized[..], Bounded(1));
|
||||
assert!(deserialized.is_ok());
|
||||
assert_eq!(deserialized.unwrap(), 'A');
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_big_serialize() {
|
||||
assert!(serialize_little(&0u32, Bounded(3)).is_err());
|
||||
assert!(serialize_little(&0u32, Bounded(4)).is_ok());
|
||||
|
||||
assert!(serialize_little(&"abcde", Bounded(8 + 4)).is_err());
|
||||
assert!(serialize_little(&"abcde", Bounded(8 + 5)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_proxy_encoded_size() {
|
||||
assert!(serialized_size(&0u8) == 1);
|
||||
assert!(serialized_size(&0u16) == 2);
|
||||
assert!(serialized_size(&0u32) == 4);
|
||||
assert!(serialized_size(&0u64) == 8);
|
||||
|
||||
// length isize stored as u64
|
||||
assert!(serialized_size(&"") == 8);
|
||||
assert!(serialized_size(&"a") == 8 + 1);
|
||||
|
||||
assert!(serialized_size(&vec![0u32, 1u32, 2u32]) == 8 + 3 * (4))
|
||||
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_serialized_size() {
|
||||
assert!(serialized_size(&0u8) == 1);
|
||||
assert!(serialized_size(&0u16) == 2);
|
||||
assert!(serialized_size(&0u32) == 4);
|
||||
assert!(serialized_size(&0u64) == 8);
|
||||
|
||||
// length isize stored as u64
|
||||
assert!(serialized_size(&"") == 8);
|
||||
assert!(serialized_size(&"a") == 8 + 1);
|
||||
|
||||
assert!(serialized_size(&vec![0u32, 1u32, 2u32]) == 8 + 3 * (4))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_box() {
|
||||
the_same(Box::new(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cow_serialize() {
|
||||
let large_object = vec![1u32,2,3,4,5,6];
|
||||
let mut large_map = HashMap::new();
|
||||
large_map.insert(1, 2);
|
||||
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
enum Message<'a> {
|
||||
M1(Cow<'a, Vec<u32>>),
|
||||
M2(Cow<'a, HashMap<u32, u32>>)
|
||||
}
|
||||
|
||||
// Test 1
|
||||
{
|
||||
let serialized = serialize_little(&Message::M1(Cow::Borrowed(&large_object)), Infinite).unwrap();
|
||||
let deserialized: Message<'static> = deserialize_from_little(&mut &serialized[..], Infinite).unwrap();
|
||||
|
||||
match deserialized {
|
||||
Message::M1(b) => assert!(&b.into_owned() == &large_object),
|
||||
_ => assert!(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Test 2
|
||||
{
|
||||
let serialized = serialize_little(&Message::M2(Cow::Borrowed(&large_map)), Infinite).unwrap();
|
||||
let deserialized: Message<'static> = deserialize_from_little(&mut &serialized[..], Infinite).unwrap();
|
||||
|
||||
match deserialized {
|
||||
Message::M2(b) => assert!(&b.into_owned() == &large_map),
|
||||
_ => assert!(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strbox_serialize() {
|
||||
let strx: &'static str = "hello world";
|
||||
let serialized = serialize_little(&Cow::Borrowed(strx), Infinite).unwrap();
|
||||
let deserialized: Cow<'static, String> = deserialize_from_little(&mut &serialized[..], Infinite).unwrap();
|
||||
let stringx: String = deserialized.into_owned();
|
||||
assert!(strx == &stringx[..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_slicebox_serialize() {
|
||||
let slice = [1u32, 2, 3 ,4, 5];
|
||||
let serialized = serialize_little(&Cow::Borrowed(&slice[..]), Infinite).unwrap();
|
||||
println!("{:?}", serialized);
|
||||
let deserialized: Cow<'static, Vec<u32>> = deserialize_from_little(&mut &serialized[..], Infinite).unwrap();
|
||||
{
|
||||
let sb: &[u32] = &deserialized;
|
||||
assert!(slice == sb);
|
||||
}
|
||||
let vecx: Vec<u32> = deserialized.into_owned();
|
||||
assert!(slice == &vecx[..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multi_strings_serialize() {
|
||||
assert!(serialize_little(&("foo", "bar", "baz"), Infinite).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_oom_protection() {
|
||||
use std::io::Cursor;
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
struct FakeVec {
|
||||
len: u64,
|
||||
byte: u8
|
||||
}
|
||||
let x = serialize_little(&FakeVec { len: 0xffffffffffffffffu64, byte: 1 }, Bounded(10)).unwrap();
|
||||
let y: Result<Vec<u8>> = deserialize_from_little(&mut Cursor::new(&x[..]), Bounded(10));
|
||||
assert!(y.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_buf() {
|
||||
use std::path::{Path, PathBuf};
|
||||
let path = Path::new("foo").to_path_buf();
|
||||
let serde_encoded = serialize_little(&path, Infinite).unwrap();
|
||||
let decoded: PathBuf = deserialize_little(&serde_encoded).unwrap();
|
||||
assert!(path.to_str() == decoded.to_str());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bytes() {
|
||||
use serde_bytes::Bytes;
|
||||
|
||||
let data = b"abc\0123";
|
||||
let s = serialize_little(&data[..], Infinite).unwrap();
|
||||
let s2 = serialize_little(&Bytes::new(data), Infinite).unwrap();
|
||||
assert_eq!(s[..], s2[..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serde_bytes() {
|
||||
use serde_bytes::ByteBuf;
|
||||
the_same(ByteBuf::from(vec![1,2,3,4,5]));
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn endian_difference() {
|
||||
let x = 10u64;
|
||||
let little = serialize_little(&x, Infinite).unwrap();
|
||||
let big = serialize::<_, _, byteorder::BigEndian>(&x, Infinite).unwrap();
|
||||
assert_ne!(little, big);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_zero_copy_parse() {
|
||||
#[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
|
||||
struct Foo<'a> {
|
||||
borrowed_str: &'a str,
|
||||
borrowed_bytes: &'a [u8],
|
||||
}
|
||||
|
||||
let f = Foo {
|
||||
borrowed_str: "hi",
|
||||
borrowed_bytes: &[0, 1, 2, 3],
|
||||
};
|
||||
{
|
||||
let encoded = serialize_little(&f, Infinite).unwrap();
|
||||
let out: Foo = deserialize_little(&encoded[..]).unwrap();
|
||||
assert_eq!(out, f);
|
||||
}
|
||||
}
|
Загрузка…
Ссылка в новой задаче