Import bincode 1.3.3 upstream upstream/1.3.3
authorWoohyun Jung <wh0705.jung@samsung.com>
Mon, 13 Mar 2023 07:56:26 +0000 (16:56 +0900)
committerWoohyun Jung <wh0705.jung@samsung.com>
Mon, 13 Mar 2023 07:56:26 +0000 (16:56 +0900)
23 files changed:
.cargo_vcs_info.json [new file with mode: 0644]
.github/workflows/rust.yml [new file with mode: 0644]
.github/workflows/security.yml [new file with mode: 0644]
.mailmap [new file with mode: 0644]
Cargo.lock [new file with mode: 0644]
Cargo.toml [new file with mode: 0644]
Cargo.toml.orig [new file with mode: 0644]
LICENSE.md [new file with mode: 0644]
readme.md [new file with mode: 0644]
src/byteorder.rs [new file with mode: 0644]
src/config/endian.rs [new file with mode: 0644]
src/config/int.rs [new file with mode: 0644]
src/config/legacy.rs [new file with mode: 0644]
src/config/limit.rs [new file with mode: 0644]
src/config/mod.rs [new file with mode: 0644]
src/config/trailing.rs [new file with mode: 0644]
src/de/mod.rs [new file with mode: 0644]
src/de/read.rs [new file with mode: 0644]
src/error.rs [new file with mode: 0644]
src/internal.rs [new file with mode: 0644]
src/lib.rs [new file with mode: 0644]
src/ser/mod.rs [new file with mode: 0644]
tests/test.rs [new file with mode: 0644]

diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json
new file mode 100644 (file)
index 0000000..dc4c924
--- /dev/null
@@ -0,0 +1,5 @@
+{
+  "git": {
+    "sha1": "c44b5e364e7084cdbabf9f94b63a3c7f32b8fb68"
+  }
+}
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml
new file mode 100644 (file)
index 0000000..841f124
--- /dev/null
@@ -0,0 +1,175 @@
+{\r
+  "name": "CI",\r
+  "on": {\r
+    "push": {\r
+      "branches": [\r
+        "trunk",\r
+        "v*.x"\r
+      ]\r
+    },\r
+    "pull_request": {\r
+      "branches": [\r
+        "trunk",\r
+        "v*.x"\r
+      ]\r
+    }\r
+  },\r
+  "jobs": {\r
+    "check": {\r
+      "name": "Check",\r
+      "runs-on": "ubuntu-latest",\r
+      "strategy": {\r
+        "fail-fast": false,\r
+        "matrix": {\r
+          "rust": [\r
+            "stable",\r
+            "beta",\r
+            "nightly",\r
+            "1.18.0"\r
+          ]\r
+        }\r
+      },\r
+      "steps": [\r
+        {\r
+          "uses": "actions/checkout@v2",\r
+          "name": "Checkout"\r
+        },\r
+        {\r
+          "uses": "actions-rs/toolchain@v1",\r
+          "with": {\r
+            "profile": "minimal",\r
+            "toolchain": "${{ matrix.rust }}",\r
+            "override": true\r
+          },\r
+          "name": "Install Rust ${{ matrix.rust }}"\r
+        },\r
+        {\r
+          "uses": "actions-rs/cargo@v1",\r
+          "with": {\r
+            "command": "check"\r
+          },\r
+          "name": "Run `cargo check`"\r
+        },\r
+        {\r
+          "uses": "actions-rs/cargo@v1",\r
+          "with": {\r
+            "command": "check",\r
+            "args": "--examples"\r
+          },\r
+          "name": "Check examples",\r
+          "if": "matrix.rust != '1.18.0'"\r
+        }\r
+      ]\r
+    },\r
+    "test": {\r
+      "name": "Test",\r
+      "runs-on": "ubuntu-latest",\r
+      "strategy": {\r
+        "matrix": {\r
+          "rust": [\r
+            "stable",\r
+            "beta",\r
+            "nightly"\r
+          ]\r
+        }\r
+      },\r
+      "steps": [\r
+        {\r
+          "uses": "actions/checkout@v2",\r
+          "name": "Checkout"\r
+        },\r
+        {\r
+          "uses": "actions-rs/toolchain@v1",\r
+          "with": {\r
+            "profile": "minimal",\r
+            "toolchain": "${{ matrix.rust }}",\r
+            "override": true\r
+          },\r
+          "name": "Install Rust ${{ matrix.rust }}"\r
+        },\r
+        {\r
+          "uses": "actions-rs/cargo@v1",\r
+          "with": {\r
+            "command": "test"\r
+          },\r
+          "name": "Run `cargo test`"\r
+        }\r
+      ]\r
+    },\r
+    "lints": {\r
+      "name": "Lints",\r
+      "runs-on": "ubuntu-latest",\r
+      "steps": [\r
+        {\r
+          "uses": "actions/checkout@v2",\r
+          "name": "Checkout"\r
+        },\r
+        {\r
+          "uses": "actions-rs/toolchain@v1",\r
+          "with": {\r
+            "profile": "minimal",\r
+            "toolchain": "stable",\r
+            "override": true,\r
+            "components": "rustfmt, clippy"\r
+          },\r
+          "name": "Install Rust stable"\r
+        },\r
+        {\r
+          "uses": "actions-rs/cargo@v1",\r
+          "with": {\r
+            "command": "fmt",\r
+            "args": "--all -- --check"\r
+          },\r
+          "name": "Run `cargo fmt`"\r
+        },\r
+        {\r
+          "uses": "actions-rs/cargo@v1",\r
+          "with": {\r
+            "command": "clippy",\r
+            "args": "-- -D warnings"\r
+          },\r
+          "name": "Run `cargo clippy`"\r
+        }\r
+      ]\r
+    },\r
+    "coverage": {\r
+      "name": "Code Coverage",\r
+      "runs-on": "ubuntu-latest",\r
+      "steps": [\r
+        {\r
+          "uses": "actions/checkout@v2",\r
+          "name": "Checkout"\r
+        },\r
+        {\r
+          "uses": "actions-rs/toolchain@v1",\r
+          "with": {\r
+            "profile": "minimal",\r
+            "toolchain": "nightly",\r
+            "override": true\r
+          },\r
+          "name": "Install Rust nightly"\r
+        },\r
+        {\r
+          "name": "Run cargo-tarpaulin",\r
+          "uses": "actions-rs/tarpaulin@v0.1",\r
+          "with": {\r
+            "version": "0.12.3",\r
+            "args": "--ignore-tests -- --test-threads 1"\r
+          }\r
+        },\r
+        {\r
+          "name": "Upload to codecov.io",\r
+          "uses": "codecov/codecov-action@v1"\r
+        },\r
+        {\r
+          "name": "Archive code coverage results",\r
+          "uses": "actions/upload-artifact@v1",\r
+          "with": {\r
+            "name": "code-coverage-report",\r
+            "path": "cobertura.xml"\r
+          }\r
+        }\r
+      ]\r
+    }\r
+  }\r
+}\r
diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml
new file mode 100644 (file)
index 0000000..704c5f0
--- /dev/null
@@ -0,0 +1,26 @@
+{\r
+  "name": "Security audit",\r
+  "on": {\r
+    "schedule": [\r
+      {\r
+        "cron": "0 0 * * *"\r
+      }\r
+    ]\r
+  },\r
+  "jobs": {\r
+    "audit": {\r
+      "runs-on": "ubuntu-latest",\r
+      "steps": [\r
+        {\r
+          "uses": "actions/checkout@v1"\r
+        },\r
+        {\r
+          "uses": "actions-rs/audit-check@v1",\r
+          "with": {\r
+            "token": "${{ secrets.GITHUB_TOKEN }}"\r
+          }\r
+        }\r
+      ]\r
+    }\r
+  }\r
+}\r
diff --git a/.mailmap b/.mailmap
new file mode 100644 (file)
index 0000000..85e4fe3
--- /dev/null
+++ b/.mailmap
@@ -0,0 +1,3 @@
+Ty Overby <ty@pre-alpha.com>\r
+Ty Overby <ty@pre-alpha.com> <tyoverby@abelay.cs.washington.edu>\r
+Zoey Riordan <zoey@dos.cafe> <daniel@griffen.io>\r
diff --git a/Cargo.lock b/Cargo.lock
new file mode 100644 (file)
index 0000000..86e0ba6
--- /dev/null
@@ -0,0 +1,71 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+[[package]]
+name = "bincode"
+version = "1.3.3"
+dependencies = [
+ "serde",
+ "serde_bytes",
+ "serde_derive",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71"
+dependencies = [
+ "unicode-xid",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3d0b9745dc2debf507c8422de05d7226cc1f0644216dfdfead988f9b1ab32a7"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "serde"
+version = "1.0.123"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92d5161132722baa40d802cc70b15262b98258453e85e5d1d365c757c73869ae"
+
+[[package]]
+name = "serde_bytes"
+version = "0.11.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "16ae07dd2f88a366f15bd0632ba725227018c69a1c8550a927324f8eb8368bb9"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.123"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9391c295d64fc0abb2c556bad848f33cb8296276b1ad2677d1ae1ace4f258f31"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "syn"
+version = "1.0.60"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c700597eca8a5a762beb35753ef6b94df201c81cca676604f547495a0d7f0081"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-xid",
+]
+
+[[package]]
+name = "unicode-xid"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564"
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644 (file)
index 0000000..4c81bfc
--- /dev/null
@@ -0,0 +1,37 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies
+#
+# If you believe there's an error in this file please file an
+# issue against the rust-lang/cargo repository. If you're
+# editing this file be aware that the upstream Cargo.toml
+# will likely look very different (and much more reasonable)
+
+[package]
+name = "bincode"
+version = "1.3.3"
+authors = ["Ty Overby <ty@pre-alpha.com>", "Francesco Mazzoli <f@mazzo.li>", "David Tolnay <dtolnay@gmail.com>", "Zoey Riordan <zoey@dos.cafe>"]
+exclude = ["logo.png", "examples/*", ".gitignore", ".travis.yml"]
+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 = ["encoding", "network-programming"]
+license = "MIT"
+repository = "https://github.com/servo/bincode"
+[dependencies.serde]
+version = "1.0.63"
+[dev-dependencies.serde_bytes]
+version = "0.11"
+
+[dev-dependencies.serde_derive]
+version = "1.0.27"
+
+[features]
+i128 = []
+[badges.travis-ci]
+repository = "servo/bincode"
diff --git a/Cargo.toml.orig b/Cargo.toml.orig
new file mode 100644 (file)
index 0000000..ae106be
--- /dev/null
@@ -0,0 +1,33 @@
+[package]\r
+name = "bincode"\r
+version = "1.3.3" # remember to update html_root_url\r
+authors = ["Ty Overby <ty@pre-alpha.com>", "Francesco Mazzoli <f@mazzo.li>", "David Tolnay <dtolnay@gmail.com>", "Zoey Riordan <zoey@dos.cafe>"]\r
+exclude = ["logo.png", "examples/*", ".gitignore", ".travis.yml"]\r
+\r
+publish =  true\r
+\r
+repository = "https://github.com/servo/bincode"\r
+documentation = "https://docs.rs/bincode"\r
+readme = "./readme.md"\r
+categories = ["encoding", "network-programming"]\r
+keywords = ["binary", "encode", "decode", "serialize", "deserialize"]\r
+\r
+license = "MIT"\r
+description = "A binary serialization / deserialization strategy that uses Serde for transforming structs into bytes and vice versa!"\r
+\r
+[dependencies]\r
+serde = "1.0.63"\r
+\r
+[dev-dependencies]\r
+serde_bytes = "0.11"\r
+serde_derive = "1.0.27"\r
+\r
+[features]\r
+# This feature is no longer used and is DEPRECATED. This crate relies on the\r
+# serde `serde_if_integer128` macro to enable i128 support for Rust compilers\r
+# and targets that support it. The feature will be removed if and when a new\r
+# major version is released.\r
+i128 = []\r
+\r
+[badges]\r
+travis-ci = { repository = "servo/bincode" }\r
diff --git a/LICENSE.md b/LICENSE.md
new file mode 100644 (file)
index 0000000..3db1f01
--- /dev/null
@@ -0,0 +1,21 @@
+The MIT License (MIT)\r
+\r
+Copyright (c) 2014 Ty Overby\r
+\r
+Permission is hereby granted, free of charge, to any person obtaining a copy\r
+of this software and associated documentation files (the "Software"), to deal\r
+in the Software without restriction, including without limitation the rights\r
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r
+copies of the Software, and to permit persons to whom the Software is\r
+furnished to do so, subject to the following conditions:\r
+\r
+The above copyright notice and this permission notice shall be included in all\r
+copies or substantial portions of the Software.\r
+\r
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r
+SOFTWARE.\r
diff --git a/readme.md b/readme.md
new file mode 100644 (file)
index 0000000..e916512
--- /dev/null
+++ b/readme.md
@@ -0,0 +1,112 @@
+# Bincode\r
+\r
+<img align="right" src="./logo.png" />\r
+\r
+![CI](https://github.com/servo/bincode/workflows/CI/badge.svg)\r
+[![](https://meritbadge.herokuapp.com/bincode)](https://crates.io/crates/bincode)\r
+[![](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT)\r
+[![](https://img.shields.io/badge/bincode-rustc_1.18+-lightgray.svg)](https://blog.rust-lang.org/2017/06/08/Rust-1.18.html)\r
+\r
+A compact encoder / decoder pair that uses a binary zero-fluff encoding scheme.\r
+The size of the encoded object will be the same or smaller than the size that\r
+the object takes up in memory in a running Rust program.\r
+\r
+In addition to exposing two simple functions\r
+(one that encodes to `Vec<u8>`, and one that decodes from `&[u8]`),\r
+binary-encode exposes a Reader/Writer API that makes it work\r
+perfectly with other stream-based APIs such as Rust files, network streams,\r
+and the [flate2-rs](https://github.com/alexcrichton/flate2-rs) compression\r
+library.\r
+\r
+## [API Documentation](https://docs.rs/bincode/)\r
+\r
+## Bincode in the wild\r
+\r
+* [google/tarpc](https://github.com/google/tarpc): Bincode is used to serialize and deserialize networked RPC messages.\r
+* [servo/webrender](https://github.com/servo/webrender): Bincode records webrender API calls for record/replay-style graphics debugging.\r
+* [servo/ipc-channel](https://github.com/servo/ipc-channel): IPC-Channel uses Bincode to send structs between processes using a channel-like API.\r
+\r
+## Example\r
+\r
+```rust\r
+use serde::{Serialize, Deserialize};\r
+\r
+#[derive(Serialize, Deserialize, PartialEq, Debug)]\r
+struct Entity {\r
+    x: f32,\r
+    y: f32,\r
+}\r
+\r
+#[derive(Serialize, Deserialize, PartialEq, Debug)]\r
+struct World(Vec<Entity>);\r
+\r
+fn main() {\r
+    let world = World(vec![Entity { x: 0.0, y: 4.0 }, Entity { x: 10.0, y: 20.5 }]);\r
+\r
+    let encoded: Vec<u8> = bincode::serialize(&world).unwrap();\r
+\r
+    // 8 bytes for the length of the vector, 4 bytes per float.\r
+    assert_eq!(encoded.len(), 8 + 4 * 4);\r
+\r
+    let decoded: World = bincode::deserialize(&encoded[..]).unwrap();\r
+\r
+    assert_eq!(world, decoded);\r
+}\r
+```\r
+\r
+## Details\r
+\r
+The encoding (and thus decoding) proceeds unsurprisingly -- primitive\r
+types are encoded according to the underlying `Writer`, tuples and\r
+structs are encoded by encoding their fields one-by-one, and enums are\r
+encoded by first writing out the tag representing the variant and\r
+then the contents.\r
+\r
+However, there are some implementation details to be aware of:\r
+\r
+* `isize`/`usize` are encoded as `i64`/`u64`, for portability.\r
+* enums variants are encoded as a `u32` instead of a `usize`.\r
+  `u32` is enough for all practical uses.\r
+* `str` is encoded as `(u64, &[u8])`, where the `u64` is the number of\r
+  bytes contained in the encoded string.\r
+\r
+## Specification\r
+\r
+Bincode's format will eventually be codified into a specification, along with\r
+its configuration options and default configuration. In the meantime, here are\r
+some frequently asked questions regarding use of the crate:\r
+\r
+### Is Bincode suitable for storage?\r
+\r
+The encoding format is stable across minor revisions, provided the same\r
+configuration is used. This should ensure that later versions can still read\r
+data produced by a previous versions of the library if no major version change\r
+has occured.\r
+\r
+Bincode is invariant over byte-order in the default configuration\r
+(`bincode::options::DefaultOptions`), making an exchange between different\r
+architectures possible. It is also rather space efficient, as it stores no\r
+metadata like struct field names in the output format and writes long streams of\r
+binary data without needing any potentially size-increasing encoding.\r
+\r
+As a result, Bincode is suitable for storing data. Be aware that it does not\r
+implement any sort of data versioning scheme or file headers, as these\r
+features are outside the scope of this crate.\r
+\r
+### Is Bincode suitable for untrusted inputs?\r
+\r
+Bincode attempts to protect against hostile data. There is a maximum size\r
+configuration available (`bincode::config::Bounded`), but not enabled in the\r
+default configuration. Enabling it causes pre-allocation size to be limited to\r
+prevent against memory exhaustion attacks.\r
+\r
+Deserializing any incoming data will not cause undefined behavior or memory\r
+issues, assuming that the deserialization code for the struct is safe itself.\r
+\r
+Bincode can be used for untrusted inputs in the sense that it will not create a\r
+security issues in your application, provided the configuration is changed to enable a\r
+maximum size limit. Malicious inputs will fail upon deserialization.\r
+\r
+### What is Bincode's MSRV (minimum supported Rust version)?\r
+\r
+Bincode 1.0 maintains support for rust 1.18.0. Any changes to this are considered a breaking change for semver purposes.
\ No newline at end of file
diff --git a/src/byteorder.rs b/src/byteorder.rs
new file mode 100644 (file)
index 0000000..298503d
--- /dev/null
@@ -0,0 +1,385 @@
+// Copyright (c) 2015 Andrew Gallant\r
+\r
+use std::io;\r
+use std::io::Result;\r
+use std::ptr::copy_nonoverlapping;\r
+\r
+#[derive(Copy, Clone)]\r
+pub struct LittleEndian;\r
+\r
+#[derive(Copy, Clone)]\r
+pub struct BigEndian;\r
+\r
+#[cfg(target_endian = "little")]\r
+pub type NativeEndian = LittleEndian;\r
+\r
+#[cfg(target_endian = "big")]\r
+pub type NativeEndian = BigEndian;\r
+\r
+macro_rules! read_num_bytes {\r
+    ($ty:ty, $size:expr, $src:expr, $which:ident) => {{\r
+        assert!($size == ::std::mem::size_of::<$ty>());\r
+        assert!($size <= $src.len());\r
+        let mut data: $ty = 0;\r
+        unsafe {\r
+            copy_nonoverlapping($src.as_ptr(), &mut data as *mut $ty as *mut u8, $size);\r
+        }\r
+        data.$which()\r
+    }};\r
+}\r
+\r
+macro_rules! write_num_bytes {\r
+    ($ty:ty, $size:expr, $n:expr, $dst:expr, $which:ident) => {{\r
+        assert!($size <= $dst.len());\r
+        unsafe {\r
+            // N.B. https://github.com/rust-lang/rust/issues/22776\r
+            let bytes = *(&$n.$which() as *const _ as *const [u8; $size]);\r
+            copy_nonoverlapping((&bytes).as_ptr(), $dst.as_mut_ptr(), $size);\r
+        }\r
+    }};\r
+}\r
+\r
+impl ByteOrder for LittleEndian {\r
+    #[inline]\r
+    fn read_u16(buf: &[u8]) -> u16 {\r
+        read_num_bytes!(u16, 2, buf, to_le)\r
+    }\r
+\r
+    #[inline]\r
+    fn read_u32(buf: &[u8]) -> u32 {\r
+        read_num_bytes!(u32, 4, buf, to_le)\r
+    }\r
+\r
+    #[inline]\r
+    fn read_u64(buf: &[u8]) -> u64 {\r
+        read_num_bytes!(u64, 8, buf, to_le)\r
+    }\r
+\r
+    #[inline]\r
+    fn write_u16(buf: &mut [u8], n: u16) {\r
+        write_num_bytes!(u16, 2, n, buf, to_le);\r
+    }\r
+\r
+    #[inline]\r
+    fn write_u32(buf: &mut [u8], n: u32) {\r
+        write_num_bytes!(u32, 4, n, buf, to_le);\r
+    }\r
+\r
+    #[inline]\r
+    fn write_u64(buf: &mut [u8], n: u64) {\r
+        write_num_bytes!(u64, 8, n, buf, to_le);\r
+    }\r
+\r
+    serde_if_integer128! {\r
+        #[inline]\r
+        fn write_u128(buf: &mut [u8], n: u128) {\r
+            write_num_bytes!(u128, 16, n, buf, to_le);\r
+        }\r
+\r
+        #[inline]\r
+        fn read_u128(buf: &[u8]) -> u128 {\r
+            read_num_bytes!(u128, 16, buf, to_le)\r
+        }\r
+    }\r
+}\r
+\r
+impl ByteOrder for BigEndian {\r
+    #[inline]\r
+    fn read_u16(buf: &[u8]) -> u16 {\r
+        read_num_bytes!(u16, 2, buf, to_be)\r
+    }\r
+\r
+    #[inline]\r
+    fn read_u32(buf: &[u8]) -> u32 {\r
+        read_num_bytes!(u32, 4, buf, to_be)\r
+    }\r
+\r
+    #[inline]\r
+    fn read_u64(buf: &[u8]) -> u64 {\r
+        read_num_bytes!(u64, 8, buf, to_be)\r
+    }\r
+\r
+    #[inline]\r
+    fn write_u16(buf: &mut [u8], n: u16) {\r
+        write_num_bytes!(u16, 2, n, buf, to_be);\r
+    }\r
+\r
+    #[inline]\r
+    fn write_u32(buf: &mut [u8], n: u32) {\r
+        write_num_bytes!(u32, 4, n, buf, to_be);\r
+    }\r
+\r
+    #[inline]\r
+    fn write_u64(buf: &mut [u8], n: u64) {\r
+        write_num_bytes!(u64, 8, n, buf, to_be);\r
+    }\r
+\r
+    serde_if_integer128! {\r
+        #[inline]\r
+        fn write_u128(buf: &mut [u8], n: u128) {\r
+            write_num_bytes!(u128, 16, n, buf, to_be);\r
+        }\r
+\r
+        #[inline]\r
+        fn read_u128(buf: &[u8]) -> u128 {\r
+            read_num_bytes!(u128, 16, buf, to_be)\r
+        }\r
+    }\r
+}\r
+\r
+pub trait ByteOrder: Clone + Copy {\r
+    fn read_u16(buf: &[u8]) -> u16;\r
+\r
+    fn read_u32(buf: &[u8]) -> u32;\r
+\r
+    fn read_u64(buf: &[u8]) -> u64;\r
+\r
+    fn write_u16(buf: &mut [u8], n: u16);\r
+\r
+    fn write_u32(buf: &mut [u8], n: u32);\r
+\r
+    fn write_u64(buf: &mut [u8], n: u64);\r
+\r
+    #[inline]\r
+    fn read_i16(buf: &[u8]) -> i16 {\r
+        Self::read_u16(buf) as i16\r
+    }\r
+\r
+    #[inline]\r
+    fn read_i32(buf: &[u8]) -> i32 {\r
+        Self::read_u32(buf) as i32\r
+    }\r
+\r
+    #[inline]\r
+    fn read_i64(buf: &[u8]) -> i64 {\r
+        Self::read_u64(buf) as i64\r
+    }\r
+\r
+    #[inline]\r
+    fn read_f32(buf: &[u8]) -> f32 {\r
+        unsafe { *(&Self::read_u32(buf) as *const u32 as *const f32) }\r
+    }\r
+\r
+    #[inline]\r
+    fn read_f64(buf: &[u8]) -> f64 {\r
+        unsafe { *(&Self::read_u64(buf) as *const u64 as *const f64) }\r
+    }\r
+\r
+    #[inline]\r
+    fn write_i16(buf: &mut [u8], n: i16) {\r
+        Self::write_u16(buf, n as u16)\r
+    }\r
+\r
+    #[inline]\r
+    fn write_i32(buf: &mut [u8], n: i32) {\r
+        Self::write_u32(buf, n as u32)\r
+    }\r
+\r
+    #[inline]\r
+    fn write_i64(buf: &mut [u8], n: i64) {\r
+        Self::write_u64(buf, n as u64)\r
+    }\r
+\r
+    #[inline]\r
+    fn write_f32(buf: &mut [u8], n: f32) {\r
+        let n = unsafe { *(&n as *const f32 as *const u32) };\r
+        Self::write_u32(buf, n)\r
+    }\r
+\r
+    #[inline]\r
+    fn write_f64(buf: &mut [u8], n: f64) {\r
+        let n = unsafe { *(&n as *const f64 as *const u64) };\r
+        Self::write_u64(buf, n)\r
+    }\r
+\r
+    serde_if_integer128! {\r
+        fn read_u128(buf: &[u8]) -> u128;\r
+        fn write_u128(buf: &mut [u8], n: u128);\r
+\r
+        #[inline]\r
+        fn read_i128(buf: &[u8]) -> i128 {\r
+            Self::read_u128(buf) as i128\r
+        }\r
+\r
+        #[inline]\r
+        fn write_i128(buf: &mut [u8], n: i128) {\r
+            Self::write_u128(buf, n as u128)\r
+        }\r
+    }\r
+}\r
+\r
+pub trait ReadBytesExt: io::Read {\r
+    #[inline]\r
+    fn read_u8(&mut self) -> Result<u8> {\r
+        let mut buf = [0; 1];\r
+        try!(self.read_exact(&mut buf));\r
+        Ok(buf[0])\r
+    }\r
+\r
+    #[inline]\r
+    fn read_i8(&mut self) -> Result<i8> {\r
+        let mut buf = [0; 1];\r
+        try!(self.read_exact(&mut buf));\r
+        Ok(buf[0] as i8)\r
+    }\r
+\r
+    #[inline]\r
+    fn read_u16<T: ByteOrder>(&mut self) -> Result<u16> {\r
+        let mut buf = [0; 2];\r
+        try!(self.read_exact(&mut buf));\r
+        Ok(T::read_u16(&buf))\r
+    }\r
+\r
+    #[inline]\r
+    fn read_i16<T: ByteOrder>(&mut self) -> Result<i16> {\r
+        let mut buf = [0; 2];\r
+        try!(self.read_exact(&mut buf));\r
+        Ok(T::read_i16(&buf))\r
+    }\r
+\r
+    #[inline]\r
+    fn read_u32<T: ByteOrder>(&mut self) -> Result<u32> {\r
+        let mut buf = [0; 4];\r
+        try!(self.read_exact(&mut buf));\r
+        Ok(T::read_u32(&buf))\r
+    }\r
+\r
+    #[inline]\r
+    fn read_i32<T: ByteOrder>(&mut self) -> Result<i32> {\r
+        let mut buf = [0; 4];\r
+        try!(self.read_exact(&mut buf));\r
+        Ok(T::read_i32(&buf))\r
+    }\r
+\r
+    #[inline]\r
+    fn read_u64<T: ByteOrder>(&mut self) -> Result<u64> {\r
+        let mut buf = [0; 8];\r
+        try!(self.read_exact(&mut buf));\r
+        Ok(T::read_u64(&buf))\r
+    }\r
+\r
+    #[inline]\r
+    fn read_i64<T: ByteOrder>(&mut self) -> Result<i64> {\r
+        let mut buf = [0; 8];\r
+        try!(self.read_exact(&mut buf));\r
+        Ok(T::read_i64(&buf))\r
+    }\r
+\r
+    #[inline]\r
+    fn read_f32<T: ByteOrder>(&mut self) -> Result<f32> {\r
+        let mut buf = [0; 4];\r
+        try!(self.read_exact(&mut buf));\r
+        Ok(T::read_f32(&buf))\r
+    }\r
+\r
+    #[inline]\r
+    fn read_f64<T: ByteOrder>(&mut self) -> Result<f64> {\r
+        let mut buf = [0; 8];\r
+        try!(self.read_exact(&mut buf));\r
+        Ok(T::read_f64(&buf))\r
+    }\r
+\r
+    serde_if_integer128! {\r
+        #[inline]\r
+        fn read_u128<T: ByteOrder>(&mut self) -> Result<u128> {\r
+            let mut buf = [0; 16];\r
+            try!(self.read_exact(&mut buf));\r
+            Ok(T::read_u128(&buf))\r
+        }\r
+\r
+        #[inline]\r
+        fn read_i128<T: ByteOrder>(&mut self) -> Result<i128> {\r
+            let mut buf = [0; 16];\r
+            try!(self.read_exact(&mut buf));\r
+            Ok(T::read_i128(&buf))\r
+        }\r
+    }\r
+}\r
+\r
+impl<R: io::Read + ?Sized> ReadBytesExt for R {}\r
+\r
+pub trait WriteBytesExt: io::Write {\r
+    #[inline]\r
+    fn write_u8(&mut self, n: u8) -> Result<()> {\r
+        self.write_all(&[n])\r
+    }\r
+\r
+    #[inline]\r
+    fn write_i8(&mut self, n: i8) -> Result<()> {\r
+        self.write_all(&[n as u8])\r
+    }\r
+\r
+    #[inline]\r
+    fn write_u16<T: ByteOrder>(&mut self, n: u16) -> Result<()> {\r
+        let mut buf = [0; 2];\r
+        T::write_u16(&mut buf, n);\r
+        self.write_all(&buf)\r
+    }\r
+\r
+    #[inline]\r
+    fn write_i16<T: ByteOrder>(&mut self, n: i16) -> Result<()> {\r
+        let mut buf = [0; 2];\r
+        T::write_i16(&mut buf, n);\r
+        self.write_all(&buf)\r
+    }\r
+\r
+    #[inline]\r
+    fn write_u32<T: ByteOrder>(&mut self, n: u32) -> Result<()> {\r
+        let mut buf = [0; 4];\r
+        T::write_u32(&mut buf, n);\r
+        self.write_all(&buf)\r
+    }\r
+\r
+    #[inline]\r
+    fn write_i32<T: ByteOrder>(&mut self, n: i32) -> Result<()> {\r
+        let mut buf = [0; 4];\r
+        T::write_i32(&mut buf, n);\r
+        self.write_all(&buf)\r
+    }\r
+\r
+    #[inline]\r
+    fn write_u64<T: ByteOrder>(&mut self, n: u64) -> Result<()> {\r
+        let mut buf = [0; 8];\r
+        T::write_u64(&mut buf, n);\r
+        self.write_all(&buf)\r
+    }\r
+\r
+    #[inline]\r
+    fn write_i64<T: ByteOrder>(&mut self, n: i64) -> Result<()> {\r
+        let mut buf = [0; 8];\r
+        T::write_i64(&mut buf, n);\r
+        self.write_all(&buf)\r
+    }\r
+\r
+    #[inline]\r
+    fn write_f32<T: ByteOrder>(&mut self, n: f32) -> Result<()> {\r
+        let mut buf = [0; 4];\r
+        T::write_f32(&mut buf, n);\r
+        self.write_all(&buf)\r
+    }\r
+\r
+    #[inline]\r
+    fn write_f64<T: ByteOrder>(&mut self, n: f64) -> Result<()> {\r
+        let mut buf = [0; 8];\r
+        T::write_f64(&mut buf, n);\r
+        self.write_all(&buf)\r
+    }\r
+\r
+    serde_if_integer128! {\r
+        #[inline]\r
+        fn write_u128<T: ByteOrder>(&mut self, n: u128) -> Result<()> {\r
+            let mut buf = [0; 16];\r
+            T::write_u128(&mut buf, n);\r
+            self.write_all(&buf)\r
+        }\r
+\r
+        #[inline]\r
+        fn write_i128<T: ByteOrder>(&mut self, n: i128) -> Result<()> {\r
+            let mut buf = [0; 16];\r
+            T::write_i128(&mut buf, n);\r
+            self.write_all(&buf)\r
+        }\r
+    }\r
+}\r
+\r
+impl<W: io::Write + ?Sized> WriteBytesExt for W {}\r
diff --git a/src/config/endian.rs b/src/config/endian.rs
new file mode 100644 (file)
index 0000000..2561620
--- /dev/null
@@ -0,0 +1,27 @@
+pub trait BincodeByteOrder {\r
+    type Endian: ::byteorder::ByteOrder + 'static;\r
+}\r
+\r
+/// Little-endian byte ordering.\r
+#[derive(Copy, Clone)]\r
+pub struct LittleEndian;\r
+\r
+/// Big-endian byte ordering.\r
+#[derive(Copy, Clone)]\r
+pub struct BigEndian;\r
+\r
+/// The native byte ordering of the current system.\r
+#[derive(Copy, Clone)]\r
+pub struct NativeEndian;\r
+\r
+impl BincodeByteOrder for LittleEndian {\r
+    type Endian = ::byteorder::LittleEndian;\r
+}\r
+\r
+impl BincodeByteOrder for BigEndian {\r
+    type Endian = ::byteorder::BigEndian;\r
+}\r
+\r
+impl BincodeByteOrder for NativeEndian {\r
+    type Endian = ::byteorder::NativeEndian;\r
+}\r
diff --git a/src/config/int.rs b/src/config/int.rs
new file mode 100644 (file)
index 0000000..f716d1a
--- /dev/null
@@ -0,0 +1,682 @@
+use std::io::Write;\r
+use std::mem::size_of;\r
+\r
+use super::Options;\r
+use de::read::BincodeRead;\r
+use error::{ErrorKind, Result};\r
+\r
+pub trait IntEncoding {\r
+    /// Gets the size (in bytes) that a value would be serialized to.\r
+    fn u16_size(n: u16) -> u64;\r
+    /// Gets the size (in bytes) that a value would be serialized to.\r
+    fn u32_size(n: u32) -> u64;\r
+    /// Gets the size (in bytes) that a value would be serialized to.\r
+    fn u64_size(n: u64) -> u64;\r
+\r
+    /// Gets the size (in bytes) that a value would be serialized to.\r
+    fn i16_size(n: i16) -> u64;\r
+    /// Gets the size (in bytes) that a value would be serialized to.\r
+    fn i32_size(n: i32) -> u64;\r
+    /// Gets the size (in bytes) that a value would be serialized to.\r
+    fn i64_size(n: i64) -> u64;\r
+\r
+    #[inline(always)]\r
+    fn len_size(len: usize) -> u64 {\r
+        Self::u64_size(len as u64)\r
+    }\r
+\r
+    /// Serializes a sequence length.\r
+    #[inline(always)]\r
+    fn serialize_len<W: Write, O: Options>(\r
+        ser: &mut ::ser::Serializer<W, O>,\r
+        len: usize,\r
+    ) -> Result<()> {\r
+        Self::serialize_u64(ser, len as u64)\r
+    }\r
+\r
+    fn serialize_u16<W: Write, O: Options>(\r
+        ser: &mut ::ser::Serializer<W, O>,\r
+        val: u16,\r
+    ) -> Result<()>;\r
+\r
+    fn serialize_u32<W: Write, O: Options>(\r
+        ser: &mut ::ser::Serializer<W, O>,\r
+        val: u32,\r
+    ) -> Result<()>;\r
+\r
+    fn serialize_u64<W: Write, O: Options>(\r
+        ser: &mut ::ser::Serializer<W, O>,\r
+        val: u64,\r
+    ) -> Result<()>;\r
+\r
+    fn serialize_i16<W: Write, O: Options>(\r
+        ser: &mut ::ser::Serializer<W, O>,\r
+        val: i16,\r
+    ) -> Result<()>;\r
+\r
+    fn serialize_i32<W: Write, O: Options>(\r
+        ser: &mut ::ser::Serializer<W, O>,\r
+        val: i32,\r
+    ) -> Result<()>;\r
+\r
+    fn serialize_i64<W: Write, O: Options>(\r
+        ser: &mut ::ser::Serializer<W, O>,\r
+        val: i64,\r
+    ) -> Result<()>;\r
+\r
+    /// Deserializes a sequence length.\r
+    #[inline(always)]\r
+    fn deserialize_len<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::de::Deserializer<R, O>,\r
+    ) -> Result<usize> {\r
+        Self::deserialize_u64(de).and_then(cast_u64_to_usize)\r
+    }\r
+\r
+    fn deserialize_u16<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::de::Deserializer<R, O>,\r
+    ) -> Result<u16>;\r
+\r
+    fn deserialize_u32<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::de::Deserializer<R, O>,\r
+    ) -> Result<u32>;\r
+\r
+    fn deserialize_u64<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::de::Deserializer<R, O>,\r
+    ) -> Result<u64>;\r
+\r
+    fn deserialize_i16<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::de::Deserializer<R, O>,\r
+    ) -> Result<i16>;\r
+\r
+    fn deserialize_i32<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::de::Deserializer<R, O>,\r
+    ) -> Result<i32>;\r
+\r
+    fn deserialize_i64<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::de::Deserializer<R, O>,\r
+    ) -> Result<i64>;\r
+\r
+    serde_if_integer128! {\r
+        fn u128_size(v: u128) -> u64;\r
+        fn i128_size(v: i128) -> u64;\r
+        fn serialize_u128<W: Write, O: Options>(\r
+            ser: &mut ::Serializer<W, O>,\r
+            val: u128,\r
+        ) -> Result<()>;\r
+        fn deserialize_u128<'de, R: BincodeRead<'de>, O: Options>(\r
+            de: &mut ::Deserializer<R, O>,\r
+        ) -> Result<u128>;\r
+        fn serialize_i128<W: Write, O: Options>(\r
+            ser: &mut ::Serializer<W, O>,\r
+            val: i128,\r
+        ) -> Result<()>;\r
+        fn deserialize_i128<'de, R: BincodeRead<'de>, O: Options>(\r
+            de: &mut ::Deserializer<R, O>,\r
+        ) -> Result<i128>;\r
+    }\r
+}\r
+\r
+/// Fixed-size integer encoding.\r
+///\r
+/// * Fixed size integers are encoded directly\r
+/// * Enum discriminants are encoded as u32\r
+/// * Lengths and usize are encoded as u64\r
+#[derive(Copy, Clone)]\r
+pub struct FixintEncoding;\r
+\r
+/// Variable-size integer encoding (excepting [ui]8).\r
+///\r
+/// Encoding an unsigned integer v (of any type excepting u8) works as follows:\r
+///\r
+/// 1. If `u < 251`, encode it as a single byte with that value.\r
+/// 2. If `251 <= u < 2**16`, encode it as a literal byte 251, followed by a u16 with value `u`.\r
+/// 3. If `2**16 <= u < 2**32`, encode it as a literal byte 252, followed by a u32 with value `u`.\r
+/// 4. If `2**32 <= u < 2**64`, encode it as a literal byte 253, followed by a u64 with value `u`.\r
+/// 5. If `2**64 <= u < 2**128`, encode it as a literal byte 254, followed by a\r
+///   u128 with value `u`.\r
+///\r
+/// Then, for signed integers, we first convert to unsigned using the zigzag algorithm,\r
+/// and then encode them as we do for unsigned integers generally. The reason we use this\r
+/// algorithm is that it encodes those values which are close to zero in less bytes; the\r
+/// obvious algorithm, where we encode the cast values, gives a very large encoding for all\r
+/// negative values.\r
+///\r
+/// The zigzag algorithm is defined as follows:\r
+///\r
+/// ```ignore\r
+/// fn zigzag(v: Signed) -> Unsigned {\r
+///     match v {\r
+///         0 => 0,\r
+///         v if v < 0 => |v| * 2 - 1\r
+///         v if v > 0 => v * 2\r
+///     }\r
+/// }\r
+/// ```\r
+///\r
+/// And works such that:\r
+///\r
+/// ```ignore\r
+/// assert_eq!(zigzag(0), 0);\r
+/// assert_eq!(zigzag(-1), 1);\r
+/// assert_eq!(zigzag(1), 2);\r
+/// assert_eq!(zigzag(-2), 3);\r
+/// assert_eq!(zigzag(2), 4);\r
+/// assert_eq!(zigzag(i64::min_value()), u64::max_value());\r
+/// ```\r
+///\r
+/// Note that u256 and the like are unsupported by this format; if and when they are added to the\r
+/// language, they may be supported via the extension point given by the 255 byte.\r
+#[derive(Copy, Clone)]\r
+pub struct VarintEncoding;\r
+\r
+const SINGLE_BYTE_MAX: u8 = 250;\r
+const U16_BYTE: u8 = 251;\r
+const U32_BYTE: u8 = 252;\r
+const U64_BYTE: u8 = 253;\r
+const U128_BYTE: u8 = 254;\r
+const DESERIALIZE_EXTENSION_POINT_ERR: &str = r#"\r
+Byte 255 is treated as an extension point; it should not be encoding anything.\r
+Do you have a mismatched bincode version or configuration?\r
+"#;\r
+\r
+impl VarintEncoding {\r
+    fn varint_size(n: u64) -> u64 {\r
+        if n <= SINGLE_BYTE_MAX as u64 {\r
+            1\r
+        } else if n <= u16::max_value() as u64 {\r
+            (1 + size_of::<u16>()) as u64\r
+        } else if n <= u32::max_value() as u64 {\r
+            (1 + size_of::<u32>()) as u64\r
+        } else {\r
+            (1 + size_of::<u64>()) as u64\r
+        }\r
+    }\r
+\r
+    #[inline(always)]\r
+    fn zigzag_encode(n: i64) -> u64 {\r
+        if n < 0 {\r
+            // let's avoid the edge case of i64::min_value()\r
+            // !n is equal to `-n - 1`, so this is:\r
+            // !n * 2 + 1 = 2(-n - 1) + 1 = -2n - 2 + 1 = -2n - 1\r
+            !(n as u64) * 2 + 1\r
+        } else {\r
+            (n as u64) * 2\r
+        }\r
+    }\r
+\r
+    #[inline(always)]\r
+    fn zigzag_decode(n: u64) -> i64 {\r
+        if n % 2 == 0 {\r
+            // positive number\r
+            (n / 2) as i64\r
+        } else {\r
+            // negative number\r
+            // !m * 2 + 1 = n\r
+            // !m * 2 = n - 1\r
+            // !m = (n - 1) / 2\r
+            // m = !((n - 1) / 2)\r
+            // since we have n is odd, we have floor(n / 2) = floor((n - 1) / 2)\r
+            !(n / 2) as i64\r
+        }\r
+    }\r
+\r
+    fn serialize_varint<W: Write, O: Options>(\r
+        ser: &mut ::ser::Serializer<W, O>,\r
+        n: u64,\r
+    ) -> Result<()> {\r
+        if n <= SINGLE_BYTE_MAX as u64 {\r
+            ser.serialize_byte(n as u8)\r
+        } else if n <= u16::max_value() as u64 {\r
+            ser.serialize_byte(U16_BYTE)?;\r
+            ser.serialize_literal_u16(n as u16)\r
+        } else if n <= u32::max_value() as u64 {\r
+            ser.serialize_byte(U32_BYTE)?;\r
+            ser.serialize_literal_u32(n as u32)\r
+        } else {\r
+            ser.serialize_byte(U64_BYTE)?;\r
+            ser.serialize_literal_u64(n as u64)\r
+        }\r
+    }\r
+\r
+    fn deserialize_varint<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::de::Deserializer<R, O>,\r
+    ) -> Result<u64> {\r
+        #[allow(ellipsis_inclusive_range_patterns)]\r
+        match de.deserialize_byte()? {\r
+            byte @ 0...SINGLE_BYTE_MAX => Ok(byte as u64),\r
+            U16_BYTE => Ok(de.deserialize_literal_u16()? as u64),\r
+            U32_BYTE => Ok(de.deserialize_literal_u32()? as u64),\r
+            U64_BYTE => de.deserialize_literal_u64(),\r
+            U128_BYTE => Err(Box::new(ErrorKind::Custom(\r
+                "Invalid value (u128 range): you may have a version or configuration disagreement?"\r
+                    .to_string(),\r
+            ))),\r
+            _ => Err(Box::new(ErrorKind::Custom(\r
+                DESERIALIZE_EXTENSION_POINT_ERR.to_string(),\r
+            ))),\r
+        }\r
+    }\r
+\r
+    serde_if_integer128! {\r
+        // see zigzag_encode and zigzag_decode for implementation comments\r
+        #[inline(always)]\r
+        fn zigzag128_encode(n: i128) -> u128 {\r
+            if n < 0 {\r
+                !(n as u128) * 2 + 1\r
+            } else {\r
+                (n as u128) * 2\r
+            }\r
+        }\r
+        #[inline(always)]\r
+        fn zigzag128_decode(n: u128) -> i128 {\r
+            if n % 2 == 0 {\r
+                (n / 2) as i128\r
+            } else {\r
+                !(n / 2) as i128\r
+            }\r
+        }\r
+\r
+        fn varint128_size(n: u128) -> u64 {\r
+            if n <= SINGLE_BYTE_MAX as u128 {\r
+                1\r
+            } else if n <= u16::max_value() as u128 {\r
+                (1 + size_of::<u16>()) as u64\r
+            } else if n <= u32::max_value() as u128 {\r
+                (1 + size_of::<u32>()) as u64\r
+            } else if n <= u64::max_value() as u128 {\r
+                (1 + size_of::<u64>()) as u64\r
+            } else {\r
+                (1 + size_of::<u128>()) as u64\r
+            }\r
+        }\r
+\r
+        fn serialize_varint128<W: Write, O: Options>(\r
+            ser: &mut ::ser::Serializer<W, O>,\r
+            n: u128,\r
+        ) -> Result<()> {\r
+            if n <= SINGLE_BYTE_MAX as u128 {\r
+                ser.serialize_byte(n as u8)\r
+            } else if n <= u16::max_value() as u128 {\r
+                ser.serialize_byte(U16_BYTE)?;\r
+                ser.serialize_literal_u16(n as u16)\r
+            } else if n <= u32::max_value() as u128 {\r
+                ser.serialize_byte(U32_BYTE)?;\r
+                ser.serialize_literal_u32(n as u32)\r
+            } else if n <= u64::max_value() as u128 {\r
+                ser.serialize_byte(U64_BYTE)?;\r
+                ser.serialize_literal_u64(n as u64)\r
+            } else {\r
+                ser.serialize_byte(U128_BYTE)?;\r
+                ser.serialize_literal_u128(n)\r
+            }\r
+        }\r
+\r
+        fn deserialize_varint128<'de, R: BincodeRead<'de>, O: Options>(\r
+            de: &mut ::de::Deserializer<R, O>,\r
+        ) -> Result<u128> {\r
+            #[allow(ellipsis_inclusive_range_patterns)]\r
+            match de.deserialize_byte()? {\r
+                byte @ 0...SINGLE_BYTE_MAX => Ok(byte as u128),\r
+                U16_BYTE => Ok(de.deserialize_literal_u16()? as u128),\r
+                U32_BYTE => Ok(de.deserialize_literal_u32()? as u128),\r
+                U64_BYTE => Ok(de.deserialize_literal_u64()? as u128),\r
+                U128_BYTE => de.deserialize_literal_u128(),\r
+                _ => Err(Box::new(ErrorKind::Custom(DESERIALIZE_EXTENSION_POINT_ERR.to_string()))),\r
+            }\r
+        }\r
+    }\r
+}\r
+\r
+impl IntEncoding for FixintEncoding {\r
+    #[inline(always)]\r
+    fn u16_size(_: u16) -> u64 {\r
+        size_of::<u16>() as u64\r
+    }\r
+    #[inline(always)]\r
+    fn u32_size(_: u32) -> u64 {\r
+        size_of::<u32>() as u64\r
+    }\r
+    #[inline(always)]\r
+    fn u64_size(_: u64) -> u64 {\r
+        size_of::<u64>() as u64\r
+    }\r
+\r
+    #[inline(always)]\r
+    fn i16_size(_: i16) -> u64 {\r
+        size_of::<i16>() as u64\r
+    }\r
+    #[inline(always)]\r
+    fn i32_size(_: i32) -> u64 {\r
+        size_of::<i32>() as u64\r
+    }\r
+    #[inline(always)]\r
+    fn i64_size(_: i64) -> u64 {\r
+        size_of::<i64>() as u64\r
+    }\r
+\r
+    #[inline(always)]\r
+    fn serialize_u16<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: u16) -> Result<()> {\r
+        ser.serialize_literal_u16(val)\r
+    }\r
+    #[inline(always)]\r
+    fn serialize_u32<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: u32) -> Result<()> {\r
+        ser.serialize_literal_u32(val)\r
+    }\r
+    #[inline(always)]\r
+    fn serialize_u64<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: u64) -> Result<()> {\r
+        ser.serialize_literal_u64(val)\r
+    }\r
+\r
+    #[inline(always)]\r
+    fn serialize_i16<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: i16) -> Result<()> {\r
+        ser.serialize_literal_u16(val as u16)\r
+    }\r
+    #[inline(always)]\r
+    fn serialize_i32<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: i32) -> Result<()> {\r
+        ser.serialize_literal_u32(val as u32)\r
+    }\r
+    #[inline(always)]\r
+    fn serialize_i64<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: i64) -> Result<()> {\r
+        ser.serialize_literal_u64(val as u64)\r
+    }\r
+\r
+    #[inline(always)]\r
+    fn deserialize_u16<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::Deserializer<R, O>,\r
+    ) -> Result<u16> {\r
+        de.deserialize_literal_u16()\r
+    }\r
+    #[inline(always)]\r
+    fn deserialize_u32<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::Deserializer<R, O>,\r
+    ) -> Result<u32> {\r
+        de.deserialize_literal_u32()\r
+    }\r
+    #[inline(always)]\r
+    fn deserialize_u64<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::Deserializer<R, O>,\r
+    ) -> Result<u64> {\r
+        de.deserialize_literal_u64()\r
+    }\r
+\r
+    #[inline(always)]\r
+    fn deserialize_i16<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::Deserializer<R, O>,\r
+    ) -> Result<i16> {\r
+        Ok(de.deserialize_literal_u16()? as i16)\r
+    }\r
+    #[inline(always)]\r
+    fn deserialize_i32<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::Deserializer<R, O>,\r
+    ) -> Result<i32> {\r
+        Ok(de.deserialize_literal_u32()? as i32)\r
+    }\r
+    #[inline(always)]\r
+    fn deserialize_i64<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::Deserializer<R, O>,\r
+    ) -> Result<i64> {\r
+        Ok(de.deserialize_literal_u64()? as i64)\r
+    }\r
+\r
+    serde_if_integer128! {\r
+        #[inline(always)]\r
+        fn u128_size(_: u128) -> u64{\r
+            size_of::<u128>() as u64\r
+        }\r
+        #[inline(always)]\r
+        fn i128_size(_: i128) -> u64{\r
+            size_of::<i128>() as u64\r
+        }\r
+\r
+        #[inline(always)]\r
+        fn serialize_u128<W: Write, O: Options>(\r
+            ser: &mut ::Serializer<W, O>,\r
+            val: u128,\r
+        ) -> Result<()> {\r
+            ser.serialize_literal_u128(val)\r
+        }\r
+        #[inline(always)]\r
+        fn serialize_i128<W: Write, O: Options>(\r
+            ser: &mut ::Serializer<W, O>,\r
+            val: i128,\r
+        ) -> Result<()> {\r
+            ser.serialize_literal_u128(val as u128)\r
+        }\r
+        #[inline(always)]\r
+        fn deserialize_u128<'de, R: BincodeRead<'de>, O: Options>(\r
+            de: &mut ::Deserializer<R, O>,\r
+        ) -> Result<u128> {\r
+            de.deserialize_literal_u128()\r
+        }\r
+        #[inline(always)]\r
+        fn deserialize_i128<'de, R: BincodeRead<'de>, O: Options>(\r
+            de: &mut ::Deserializer<R, O>,\r
+        ) -> Result<i128> {\r
+            Ok(de.deserialize_literal_u128()? as i128)\r
+        }\r
+    }\r
+}\r
+\r
+impl IntEncoding for VarintEncoding {\r
+    #[inline(always)]\r
+    fn u16_size(n: u16) -> u64 {\r
+        Self::varint_size(n as u64)\r
+    }\r
+    #[inline(always)]\r
+    fn u32_size(n: u32) -> u64 {\r
+        Self::varint_size(n as u64)\r
+    }\r
+    #[inline(always)]\r
+    fn u64_size(n: u64) -> u64 {\r
+        Self::varint_size(n)\r
+    }\r
+\r
+    #[inline(always)]\r
+    fn i16_size(n: i16) -> u64 {\r
+        Self::varint_size(Self::zigzag_encode(n as i64))\r
+    }\r
+    #[inline(always)]\r
+    fn i32_size(n: i32) -> u64 {\r
+        Self::varint_size(Self::zigzag_encode(n as i64))\r
+    }\r
+    #[inline(always)]\r
+    fn i64_size(n: i64) -> u64 {\r
+        Self::varint_size(Self::zigzag_encode(n))\r
+    }\r
+\r
+    #[inline(always)]\r
+    fn serialize_u16<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: u16) -> Result<()> {\r
+        Self::serialize_varint(ser, val as u64)\r
+    }\r
+    #[inline(always)]\r
+    fn serialize_u32<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: u32) -> Result<()> {\r
+        Self::serialize_varint(ser, val as u64)\r
+    }\r
+    #[inline(always)]\r
+    fn serialize_u64<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: u64) -> Result<()> {\r
+        Self::serialize_varint(ser, val)\r
+    }\r
+\r
+    #[inline(always)]\r
+    fn serialize_i16<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: i16) -> Result<()> {\r
+        Self::serialize_varint(ser, Self::zigzag_encode(val as i64))\r
+    }\r
+    #[inline(always)]\r
+    fn serialize_i32<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: i32) -> Result<()> {\r
+        Self::serialize_varint(ser, Self::zigzag_encode(val as i64))\r
+    }\r
+    #[inline(always)]\r
+    fn serialize_i64<W: Write, O: Options>(ser: &mut ::Serializer<W, O>, val: i64) -> Result<()> {\r
+        Self::serialize_varint(ser, Self::zigzag_encode(val))\r
+    }\r
+\r
+    #[inline(always)]\r
+    fn deserialize_u16<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::Deserializer<R, O>,\r
+    ) -> Result<u16> {\r
+        Self::deserialize_varint(de).and_then(cast_u64_to_u16)\r
+    }\r
+    #[inline(always)]\r
+    fn deserialize_u32<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::Deserializer<R, O>,\r
+    ) -> Result<u32> {\r
+        Self::deserialize_varint(de).and_then(cast_u64_to_u32)\r
+    }\r
+    #[inline(always)]\r
+    fn deserialize_u64<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::Deserializer<R, O>,\r
+    ) -> Result<u64> {\r
+        Self::deserialize_varint(de)\r
+    }\r
+\r
+    #[inline(always)]\r
+    fn deserialize_i16<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::Deserializer<R, O>,\r
+    ) -> Result<i16> {\r
+        Self::deserialize_varint(de)\r
+            .map(Self::zigzag_decode)\r
+            .and_then(cast_i64_to_i16)\r
+    }\r
+    #[inline(always)]\r
+    fn deserialize_i32<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::Deserializer<R, O>,\r
+    ) -> Result<i32> {\r
+        Self::deserialize_varint(de)\r
+            .map(Self::zigzag_decode)\r
+            .and_then(cast_i64_to_i32)\r
+    }\r
+    #[inline(always)]\r
+    fn deserialize_i64<'de, R: BincodeRead<'de>, O: Options>(\r
+        de: &mut ::Deserializer<R, O>,\r
+    ) -> Result<i64> {\r
+        Self::deserialize_varint(de).map(Self::zigzag_decode)\r
+    }\r
+\r
+    serde_if_integer128! {\r
+        #[inline(always)]\r
+        fn u128_size(n: u128) -> u64 {\r
+            Self::varint128_size(n)\r
+        }\r
+        #[inline(always)]\r
+        fn i128_size(n: i128) -> u64 {\r
+            Self::varint128_size(Self::zigzag128_encode(n))\r
+        }\r
+        #[inline(always)]\r
+        fn serialize_u128<W: Write, O: Options>(\r
+            ser: &mut ::Serializer<W, O>,\r
+            val: u128,\r
+        ) -> Result<()> {\r
+            Self::serialize_varint128(ser, val)\r
+        }\r
+        #[inline(always)]\r
+        fn serialize_i128<W: Write, O: Options>(\r
+            ser: &mut ::Serializer<W, O>,\r
+            val: i128,\r
+        ) -> Result<()> {\r
+            Self::serialize_varint128(ser, Self::zigzag128_encode(val))\r
+        }\r
+        #[inline(always)]\r
+        fn deserialize_u128<'de, R: BincodeRead<'de>, O: Options>(\r
+            de: &mut ::Deserializer<R, O>,\r
+        ) -> Result<u128> {\r
+            Self::deserialize_varint128(de)\r
+        }\r
+        #[inline(always)]\r
+        fn deserialize_i128<'de, R: BincodeRead<'de>, O: Options>(\r
+            de: &mut ::Deserializer<R, O>,\r
+        ) -> Result<i128> {\r
+            Self::deserialize_varint128(de).map(Self::zigzag128_decode)\r
+        }\r
+    }\r
+}\r
+\r
+fn cast_u64_to_usize(n: u64) -> Result<usize> {\r
+    if n <= usize::max_value() as u64 {\r
+        Ok(n as usize)\r
+    } else {\r
+        Err(Box::new(ErrorKind::Custom(format!(\r
+            "Invalid size {}: sizes must fit in a usize (0 to {})",\r
+            n,\r
+            usize::max_value()\r
+        ))))\r
+    }\r
+}\r
+fn cast_u64_to_u32(n: u64) -> Result<u32> {\r
+    if n <= u32::max_value() as u64 {\r
+        Ok(n as u32)\r
+    } else {\r
+        Err(Box::new(ErrorKind::Custom(format!(\r
+            "Invalid u32 {}: you may have a version disagreement?",\r
+            n,\r
+        ))))\r
+    }\r
+}\r
+fn cast_u64_to_u16(n: u64) -> Result<u16> {\r
+    if n <= u16::max_value() as u64 {\r
+        Ok(n as u16)\r
+    } else {\r
+        Err(Box::new(ErrorKind::Custom(format!(\r
+            "Invalid u16 {}: you may have a version disagreement?",\r
+            n,\r
+        ))))\r
+    }\r
+}\r
+\r
+fn cast_i64_to_i32(n: i64) -> Result<i32> {\r
+    if n <= i32::max_value() as i64 && n >= i32::min_value() as i64 {\r
+        Ok(n as i32)\r
+    } else {\r
+        Err(Box::new(ErrorKind::Custom(format!(\r
+            "Invalid i32 {}: you may have a version disagreement?",\r
+            n,\r
+        ))))\r
+    }\r
+}\r
+\r
+fn cast_i64_to_i16(n: i64) -> Result<i16> {\r
+    if n <= i16::max_value() as i64 && n >= i16::min_value() as i64 {\r
+        Ok(n as i16)\r
+    } else {\r
+        Err(Box::new(ErrorKind::Custom(format!(\r
+            "Invalid i16 {}: you may have a version disagreement?",\r
+            n,\r
+        ))))\r
+    }\r
+}\r
+\r
+#[cfg(test)]\r
+mod test {\r
+    use super::VarintEncoding;\r
+\r
+    #[test]\r
+    fn test_zigzag_encode() {\r
+        let zigzag = VarintEncoding::zigzag_encode;\r
+\r
+        assert_eq!(zigzag(0), 0);\r
+        for x in 1..512 {\r
+            assert_eq!(zigzag(x), (x as u64) * 2);\r
+            assert_eq!(zigzag(-x), (x as u64) * 2 - 1);\r
+        }\r
+    }\r
+\r
+    #[test]\r
+    fn test_zigzag_decode() {\r
+        // zigzag'\r
+        let zigzagp = VarintEncoding::zigzag_decode;\r
+        for x in (0..512).map(|x| x * 2) {\r
+            assert_eq!(zigzagp(x), x as i64 / 2);\r
+            assert_eq!(zigzagp(x + 1), -(x as i64) / 2 - 1);\r
+        }\r
+    }\r
+\r
+    #[test]\r
+    fn test_zigzag_edge_cases() {\r
+        let (zigzag, zigzagp) = (VarintEncoding::zigzag_encode, VarintEncoding::zigzag_decode);\r
+\r
+        assert_eq!(zigzag(i64::max_value()), u64::max_value() - 1);\r
+        assert_eq!(zigzag(i64::min_value()), u64::max_value());\r
+\r
+        assert_eq!(zigzagp(u64::max_value() - 1), i64::max_value());\r
+        assert_eq!(zigzagp(u64::max_value()), i64::min_value());\r
+    }\r
+}\r
diff --git a/src/config/legacy.rs b/src/config/legacy.rs
new file mode 100644 (file)
index 0000000..ec5c7f0
--- /dev/null
@@ -0,0 +1,253 @@
+use std::io::{Read, Write};\r
+\r
+use self::EndianOption::*;\r
+use self::LimitOption::*;\r
+use super::{DefaultOptions, Options};\r
+use de::read::BincodeRead;\r
+use error::Result;\r
+use serde;\r
+\r
+/// A configuration builder whose options Bincode will use\r
+/// while serializing and deserializing.\r
+///\r
+/// ### Options\r
+/// Endianness: The endianness with which multi-byte integers will be read/written.  *default: little endian*\r
+/// Limit: The maximum number of bytes that will be read/written in a bincode serialize/deserialize. *default: unlimited*\r
+///\r
+/// ### Byte Limit Details\r
+/// The purpose of byte-limiting is to prevent Denial-Of-Service attacks whereby malicious attackers get bincode\r
+/// deserialization to crash your process by allocating too much memory or keeping a connection open for too long.\r
+///\r
+/// When a byte limit is set, bincode will return `Err` on any deserialization that goes over the limit, or any\r
+/// serialization that goes over the limit.\r
+#[derive(Clone, Debug)]\r
+#[deprecated(\r
+    since = "1.3.0",\r
+    note = "please use the `DefaultOptions`/`Options` system instead"\r
+)]\r
+pub struct Config {\r
+    limit: LimitOption,\r
+    endian: EndianOption,\r
+}\r
+\r
+#[derive(Clone, Copy, Debug)]\r
+enum LimitOption {\r
+    Unlimited,\r
+    Limited(u64),\r
+}\r
+\r
+#[derive(Clone, Copy, Debug)]\r
+enum EndianOption {\r
+    Big,\r
+    Little,\r
+    Native,\r
+}\r
+\r
+macro_rules! config_map {\r
+    ($self:expr, $opts:ident => $call:expr) => {\r
+        match ($self.limit, $self.endian) {\r
+            (Unlimited, Little) => {\r
+                let $opts = DefaultOptions::new()\r
+                    .with_fixint_encoding()\r
+                    .allow_trailing_bytes()\r
+                    .with_no_limit()\r
+                    .with_little_endian();\r
+                $call\r
+            }\r
+            (Unlimited, Big) => {\r
+                let $opts = DefaultOptions::new()\r
+                    .with_fixint_encoding()\r
+                    .allow_trailing_bytes()\r
+                    .with_no_limit()\r
+                    .with_big_endian();\r
+                $call\r
+            }\r
+            (Unlimited, Native) => {\r
+                let $opts = DefaultOptions::new()\r
+                    .with_fixint_encoding()\r
+                    .allow_trailing_bytes()\r
+                    .with_no_limit()\r
+                    .with_native_endian();\r
+                $call\r
+            }\r
+\r
+            (Limited(l), Little) => {\r
+                let $opts = DefaultOptions::new()\r
+                    .with_fixint_encoding()\r
+                    .allow_trailing_bytes()\r
+                    .with_limit(l)\r
+                    .with_little_endian();\r
+                $call\r
+            }\r
+            (Limited(l), Big) => {\r
+                let $opts = DefaultOptions::new()\r
+                    .with_fixint_encoding()\r
+                    .allow_trailing_bytes()\r
+                    .with_limit(l)\r
+                    .with_big_endian();\r
+                $call\r
+            }\r
+            (Limited(l), Native) => {\r
+                let $opts = DefaultOptions::new()\r
+                    .with_fixint_encoding()\r
+                    .allow_trailing_bytes()\r
+                    .with_limit(l)\r
+                    .with_native_endian();\r
+                $call\r
+            }\r
+        }\r
+    };\r
+}\r
+\r
+impl Config {\r
+    #[inline(always)]\r
+    pub(crate) fn new() -> Config {\r
+        Config {\r
+            limit: LimitOption::Unlimited,\r
+            endian: EndianOption::Little,\r
+        }\r
+    }\r
+\r
+    /// Sets the byte limit to be unlimited.\r
+    /// This is the default.\r
+    #[inline(always)]\r
+    pub fn no_limit(&mut self) -> &mut Self {\r
+        self.limit = LimitOption::Unlimited;\r
+        self\r
+    }\r
+\r
+    /// Sets the byte limit to `limit`.\r
+    #[inline(always)]\r
+    pub fn limit(&mut self, limit: u64) -> &mut Self {\r
+        self.limit = LimitOption::Limited(limit);\r
+        self\r
+    }\r
+\r
+    /// Sets the endianness to little-endian\r
+    /// This is the default.\r
+    #[inline(always)]\r
+    pub fn little_endian(&mut self) -> &mut Self {\r
+        self.endian = EndianOption::Little;\r
+        self\r
+    }\r
+\r
+    /// Sets the endianness to big-endian\r
+    #[inline(always)]\r
+    pub fn big_endian(&mut self) -> &mut Self {\r
+        self.endian = EndianOption::Big;\r
+        self\r
+    }\r
+\r
+    /// Sets the endianness to the the machine-native endianness\r
+    #[inline(always)]\r
+    pub fn native_endian(&mut self) -> &mut Self {\r
+        self.endian = EndianOption::Native;\r
+        self\r
+    }\r
+\r
+    /// Serializes a serializable object into a `Vec` of bytes using this configuration\r
+    #[inline(always)]\r
+    pub fn serialize<T: ?Sized + serde::Serialize>(&self, t: &T) -> Result<Vec<u8>> {\r
+        config_map!(self, opts => ::internal::serialize(t, opts))\r
+    }\r
+\r
+    /// Returns the size that an object would be if serialized using Bincode with this configuration\r
+    #[inline(always)]\r
+    pub fn serialized_size<T: ?Sized + serde::Serialize>(&self, t: &T) -> Result<u64> {\r
+        config_map!(self, opts => ::internal::serialized_size(t, opts))\r
+    }\r
+\r
+    /// Serializes an object directly into a `Writer` using this configuration\r
+    ///\r
+    /// If the serialization would take more bytes than allowed by the size limit, an error\r
+    /// is returned and *no bytes* will be written into the `Writer`\r
+    #[inline(always)]\r
+    pub fn serialize_into<W: Write, T: ?Sized + serde::Serialize>(\r
+        &self,\r
+        w: W,\r
+        t: &T,\r
+    ) -> Result<()> {\r
+        config_map!(self, opts => ::internal::serialize_into(w, t, opts))\r
+    }\r
+\r
+    /// Deserializes a slice of bytes into an instance of `T` using this configuration\r
+    #[inline(always)]\r
+    pub fn deserialize<'a, T: serde::Deserialize<'a>>(&self, bytes: &'a [u8]) -> Result<T> {\r
+        config_map!(self, opts => ::internal::deserialize(bytes, opts))\r
+    }\r
+\r
+    /// TODO: document\r
+    #[doc(hidden)]\r
+    #[inline(always)]\r
+    pub fn deserialize_in_place<'a, R, T>(&self, reader: R, place: &mut T) -> Result<()>\r
+    where\r
+        R: BincodeRead<'a>,\r
+        T: serde::de::Deserialize<'a>,\r
+    {\r
+        config_map!(self, opts => ::internal::deserialize_in_place(reader, opts, place))\r
+    }\r
+\r
+    /// Deserializes a slice of bytes with state `seed` using this configuration.\r
+    #[inline(always)]\r
+    pub fn deserialize_seed<'a, T: serde::de::DeserializeSeed<'a>>(\r
+        &self,\r
+        seed: T,\r
+        bytes: &'a [u8],\r
+    ) -> Result<T::Value> {\r
+        config_map!(self, opts => ::internal::deserialize_seed(seed, bytes, opts))\r
+    }\r
+\r
+    /// Deserializes an object directly from a `Read`er using this configuration\r
+    ///\r
+    /// If this returns an `Error`, `reader` may be in an invalid state.\r
+    #[inline(always)]\r
+    pub fn deserialize_from<R: Read, T: serde::de::DeserializeOwned>(\r
+        &self,\r
+        reader: R,\r
+    ) -> Result<T> {\r
+        config_map!(self, opts => ::internal::deserialize_from(reader, opts))\r
+    }\r
+\r
+    /// Deserializes an object directly from a `Read`er with state `seed` using this configuration\r
+    ///\r
+    /// If this returns an `Error`, `reader` may be in an invalid state.\r
+    #[inline(always)]\r
+    pub fn deserialize_from_seed<'a, R: Read, T: serde::de::DeserializeSeed<'a>>(\r
+        &self,\r
+        seed: T,\r
+        reader: R,\r
+    ) -> Result<T::Value> {\r
+        config_map!(self, opts => ::internal::deserialize_from_seed(seed, reader, opts))\r
+    }\r
+\r
+    /// Deserializes an object from a custom `BincodeRead`er using the default configuration.\r
+    /// It is highly recommended to use `deserialize_from` unless you need to implement\r
+    /// `BincodeRead` for performance reasons.\r
+    ///\r
+    /// If this returns an `Error`, `reader` may be in an invalid state.\r
+    #[inline(always)]\r
+    pub fn deserialize_from_custom<'a, R: BincodeRead<'a>, T: serde::de::DeserializeOwned>(\r
+        &self,\r
+        reader: R,\r
+    ) -> Result<T> {\r
+        config_map!(self, opts => ::internal::deserialize_from_custom(reader, opts))\r
+    }\r
+\r
+    /// Deserializes an object from a custom `BincodeRead`er with state `seed` using the default\r
+    /// configuration. It is highly recommended to use `deserialize_from` unless you need to\r
+    /// implement `BincodeRead` for performance reasons.\r
+    ///\r
+    /// If this returns an `Error`, `reader` may be in an invalid state.\r
+    #[inline(always)]\r
+    pub fn deserialize_from_custom_seed<\r
+        'a,\r
+        R: BincodeRead<'a>,\r
+        T: serde::de::DeserializeSeed<'a>,\r
+    >(\r
+        &self,\r
+        seed: T,\r
+        reader: R,\r
+    ) -> Result<T::Value> {\r
+        config_map!(self, opts => ::internal::deserialize_from_custom_seed(seed, reader, opts))\r
+    }\r
+}\r
diff --git a/src/config/limit.rs b/src/config/limit.rs
new file mode 100644 (file)
index 0000000..4772298
--- /dev/null
@@ -0,0 +1,49 @@
+use error::{ErrorKind, Result};\r
+\r
+/// A trait for stopping serialization and deserialization when a certain limit has been reached.\r
+pub trait SizeLimit {\r
+    /// Tells the SizeLimit that a certain number of bytes has been\r
+    /// read or written.  Returns Err if the limit has been exceeded.\r
+    fn add(&mut self, n: u64) -> Result<()>;\r
+    /// Returns the hard limit (if one exists)\r
+    fn limit(&self) -> Option<u64>;\r
+}\r
+\r
+/// A SizeLimit that restricts serialized or deserialized messages from\r
+/// exceeding a certain byte length.\r
+#[derive(Copy, Clone)]\r
+pub struct Bounded(pub u64);\r
+\r
+/// A SizeLimit without a limit!\r
+/// Use this if you don't care about the size of encoded or decoded messages.\r
+#[derive(Copy, Clone)]\r
+pub struct Infinite;\r
+\r
+impl SizeLimit for Bounded {\r
+    #[inline(always)]\r
+    fn add(&mut self, n: u64) -> Result<()> {\r
+        if self.0 >= n {\r
+            self.0 -= n;\r
+            Ok(())\r
+        } else {\r
+            Err(Box::new(ErrorKind::SizeLimit))\r
+        }\r
+    }\r
+\r
+    #[inline(always)]\r
+    fn limit(&self) -> Option<u64> {\r
+        Some(self.0)\r
+    }\r
+}\r
+\r
+impl SizeLimit for Infinite {\r
+    #[inline(always)]\r
+    fn add(&mut self, _: u64) -> Result<()> {\r
+        Ok(())\r
+    }\r
+\r
+    #[inline(always)]\r
+    fn limit(&self) -> Option<u64> {\r
+        None\r
+    }\r
+}\r
diff --git a/src/config/mod.rs b/src/config/mod.rs
new file mode 100644 (file)
index 0000000..33fa920
--- /dev/null
@@ -0,0 +1,408 @@
+//! `bincode` uses a Builder-pattern to configure the Serializers and Deserializers in this\r
+//! crate. This means that if you need to customize the behavior of `bincode`, you should create an\r
+//! instance of the `DefaultOptions` struct:\r
+//!\r
+//! ```rust\r
+//! use bincode::Options;\r
+//! let my_options = bincode::DefaultOptions::new();\r
+//! ```\r
+//!\r
+//! # Options Struct vs bincode functions\r
+//!\r
+//! Due to historical reasons, the default options used by the `serialize()` and `deserialize()`\r
+//! family of functions are different than the default options created by the `DefaultOptions` struct:\r
+//!\r
+//! |          | Byte limit | Endianness | Int Encoding | Trailing Behavior |\r
+//! |----------|------------|------------|--------------|-------------------|\r
+//! | struct   | Unlimited  | Little     | Varint       | Reject            |\r
+//! | function | Unlimited  | Little     | Fixint       | Allow             |\r
+//!\r
+//! This means that if you want to use the `Serialize` / `Deserialize` structs with the same\r
+//! settings as the functions, you should adjust the `DefaultOptions` struct like so:\r
+//!\r
+//! ```rust\r
+//! use bincode::Options;\r
+//! let my_options = bincode::DefaultOptions::new()\r
+//!     .with_fixint_encoding()\r
+//!     .allow_trailing_bytes();\r
+//! ```\r
+\r
+use de::read::BincodeRead;\r
+use error::Result;\r
+use serde;\r
+use std::io::{Read, Write};\r
+use std::marker::PhantomData;\r
+\r
+pub(crate) use self::endian::BincodeByteOrder;\r
+pub(crate) use self::int::IntEncoding;\r
+pub(crate) use self::internal::*;\r
+pub(crate) use self::limit::SizeLimit;\r
+pub(crate) use self::trailing::TrailingBytes;\r
+\r
+pub use self::endian::{BigEndian, LittleEndian, NativeEndian};\r
+pub use self::int::{FixintEncoding, VarintEncoding};\r
+pub use self::legacy::*;\r
+pub use self::limit::{Bounded, Infinite};\r
+pub use self::trailing::{AllowTrailing, RejectTrailing};\r
+\r
+mod endian;\r
+mod int;\r
+mod legacy;\r
+mod limit;\r
+mod trailing;\r
+\r
+/// The default options for bincode serialization/deserialization.\r
+///\r
+/// ### Defaults\r
+/// By default bincode will use little-endian encoding for multi-byte integers, and will not\r
+/// limit the number of serialized/deserialized bytes.\r
+///\r
+/// ### Configuring `DefaultOptions`\r
+///\r
+/// `DefaultOptions` implements the [Options] trait, which means it exposes functions to change the behavior of bincode.\r
+///\r
+/// For example, if you wanted to limit the bincode deserializer to 1 kilobyte of user input:\r
+///\r
+/// ```rust\r
+/// use bincode::Options;\r
+/// let my_options = bincode::DefaultOptions::new().with_limit(1024);\r
+/// ```\r
+///\r
+/// ### DefaultOptions struct vs. functions\r
+///\r
+/// The default configuration used by this struct is not the same as that used by the bincode\r
+/// helper functions in the root of this crate. See the\r
+/// [config](index.html#options-struct-vs-bincode-functions) module for more details\r
+#[derive(Copy, Clone)]\r
+pub struct DefaultOptions(Infinite);\r
+\r
+impl DefaultOptions {\r
+    /// Get a default configuration object.\r
+    ///\r
+    /// ### Default Configuration:\r
+    ///\r
+    /// | Byte limit | Endianness | Int Encoding | Trailing Behavior |\r
+    /// |------------|------------|--------------|-------------------|\r
+    /// | Unlimited  | Little     | Varint       | Reject            |\r
+    pub fn new() -> DefaultOptions {\r
+        DefaultOptions(Infinite)\r
+    }\r
+}\r
+\r
+impl Default for DefaultOptions {\r
+    fn default() -> Self {\r
+        Self::new()\r
+    }\r
+}\r
+\r
+impl InternalOptions for DefaultOptions {\r
+    type Limit = Infinite;\r
+    type Endian = LittleEndian;\r
+    type IntEncoding = VarintEncoding;\r
+    type Trailing = RejectTrailing;\r
+\r
+    #[inline(always)]\r
+    fn limit(&mut self) -> &mut Infinite {\r
+        &mut self.0\r
+    }\r
+}\r
+\r
+/// A configuration builder trait whose options Bincode will use\r
+/// while serializing and deserializing.\r
+///\r
+/// ### Options\r
+/// Endianness: The endianness with which multi-byte integers will be read/written.  *default: little endian*\r
+///\r
+/// Limit: The maximum number of bytes that will be read/written in a bincode serialize/deserialize. *default: unlimited*\r
+///\r
+/// Int Encoding: The encoding used for numbers, enum discriminants, and lengths. *default: varint*\r
+///\r
+/// Trailing Behavior: The behavior when there are trailing bytes left over in a slice after deserialization. *default: reject*\r
+///\r
+/// ### Byte Limit Details\r
+/// The purpose of byte-limiting is to prevent Denial-Of-Service attacks whereby malicious attackers get bincode\r
+/// deserialization to crash your process by allocating too much memory or keeping a connection open for too long.\r
+///\r
+/// When a byte limit is set, bincode will return `Err` on any deserialization that goes over the limit, or any\r
+/// serialization that goes over the limit.\r
+pub trait Options: InternalOptions + Sized {\r
+    /// Sets the byte limit to be unlimited.\r
+    /// This is the default.\r
+    fn with_no_limit(self) -> WithOtherLimit<Self, Infinite> {\r
+        WithOtherLimit::new(self, Infinite)\r
+    }\r
+\r
+    /// Sets the byte limit to `limit`.\r
+    fn with_limit(self, limit: u64) -> WithOtherLimit<Self, Bounded> {\r
+        WithOtherLimit::new(self, Bounded(limit))\r
+    }\r
+\r
+    /// Sets the endianness to little-endian\r
+    /// This is the default.\r
+    fn with_little_endian(self) -> WithOtherEndian<Self, LittleEndian> {\r
+        WithOtherEndian::new(self)\r
+    }\r
+\r
+    /// Sets the endianness to big-endian\r
+    fn with_big_endian(self) -> WithOtherEndian<Self, BigEndian> {\r
+        WithOtherEndian::new(self)\r
+    }\r
+\r
+    /// Sets the endianness to the the machine-native endianness\r
+    fn with_native_endian(self) -> WithOtherEndian<Self, NativeEndian> {\r
+        WithOtherEndian::new(self)\r
+    }\r
+\r
+    /// Sets the length encoding to varint\r
+    fn with_varint_encoding(self) -> WithOtherIntEncoding<Self, VarintEncoding> {\r
+        WithOtherIntEncoding::new(self)\r
+    }\r
+\r
+    /// Sets the length encoding to be fixed\r
+    fn with_fixint_encoding(self) -> WithOtherIntEncoding<Self, FixintEncoding> {\r
+        WithOtherIntEncoding::new(self)\r
+    }\r
+\r
+    /// Sets the deserializer to reject trailing bytes\r
+    fn reject_trailing_bytes(self) -> WithOtherTrailing<Self, RejectTrailing> {\r
+        WithOtherTrailing::new(self)\r
+    }\r
+\r
+    /// Sets the deserializer to allow trailing bytes\r
+    fn allow_trailing_bytes(self) -> WithOtherTrailing<Self, AllowTrailing> {\r
+        WithOtherTrailing::new(self)\r
+    }\r
+\r
+    /// Serializes a serializable object into a `Vec` of bytes using this configuration\r
+    #[inline(always)]\r
+    fn serialize<S: ?Sized + serde::Serialize>(self, t: &S) -> Result<Vec<u8>> {\r
+        ::internal::serialize(t, self)\r
+    }\r
+\r
+    /// Returns the size that an object would be if serialized using Bincode with this configuration\r
+    #[inline(always)]\r
+    fn serialized_size<T: ?Sized + serde::Serialize>(self, t: &T) -> Result<u64> {\r
+        ::internal::serialized_size(t, self)\r
+    }\r
+\r
+    /// Serializes an object directly into a `Writer` using this configuration\r
+    ///\r
+    /// If the serialization would take more bytes than allowed by the size limit, an error\r
+    /// is returned and *no bytes* will be written into the `Writer`\r
+    #[inline(always)]\r
+    fn serialize_into<W: Write, T: ?Sized + serde::Serialize>(self, w: W, t: &T) -> Result<()> {\r
+        ::internal::serialize_into(w, t, self)\r
+    }\r
+\r
+    /// Deserializes a slice of bytes into an instance of `T` using this configuration\r
+    #[inline(always)]\r
+    fn deserialize<'a, T: serde::Deserialize<'a>>(self, bytes: &'a [u8]) -> Result<T> {\r
+        ::internal::deserialize(bytes, self)\r
+    }\r
+\r
+    /// TODO: document\r
+    #[doc(hidden)]\r
+    #[inline(always)]\r
+    fn deserialize_in_place<'a, R, T>(self, reader: R, place: &mut T) -> Result<()>\r
+    where\r
+        R: BincodeRead<'a>,\r
+        T: serde::de::Deserialize<'a>,\r
+    {\r
+        ::internal::deserialize_in_place(reader, self, place)\r
+    }\r
+\r
+    /// Deserializes a slice of bytes with state `seed` using this configuration.\r
+    #[inline(always)]\r
+    fn deserialize_seed<'a, T: serde::de::DeserializeSeed<'a>>(\r
+        self,\r
+        seed: T,\r
+        bytes: &'a [u8],\r
+    ) -> Result<T::Value> {\r
+        ::internal::deserialize_seed(seed, bytes, self)\r
+    }\r
+\r
+    /// Deserializes an object directly from a `Read`er using this configuration\r
+    ///\r
+    /// If this returns an `Error`, `reader` may be in an invalid state.\r
+    #[inline(always)]\r
+    fn deserialize_from<R: Read, T: serde::de::DeserializeOwned>(self, reader: R) -> Result<T> {\r
+        ::internal::deserialize_from(reader, self)\r
+    }\r
+\r
+    /// Deserializes an object directly from a `Read`er with state `seed` using this configuration\r
+    ///\r
+    /// If this returns an `Error`, `reader` may be in an invalid state.\r
+    #[inline(always)]\r
+    fn deserialize_from_seed<'a, R: Read, T: serde::de::DeserializeSeed<'a>>(\r
+        self,\r
+        seed: T,\r
+        reader: R,\r
+    ) -> Result<T::Value> {\r
+        ::internal::deserialize_from_seed(seed, reader, self)\r
+    }\r
+\r
+    /// Deserializes an object from a custom `BincodeRead`er using the default configuration.\r
+    /// It is highly recommended to use `deserialize_from` unless you need to implement\r
+    /// `BincodeRead` for performance reasons.\r
+    ///\r
+    /// If this returns an `Error`, `reader` may be in an invalid state.\r
+    #[inline(always)]\r
+    fn deserialize_from_custom<'a, R: BincodeRead<'a>, T: serde::de::DeserializeOwned>(\r
+        self,\r
+        reader: R,\r
+    ) -> Result<T> {\r
+        ::internal::deserialize_from_custom(reader, self)\r
+    }\r
+\r
+    /// Deserializes an object from a custom `BincodeRead`er with state `seed` using the default\r
+    /// configuration. It is highly recommended to use `deserialize_from` unless you need to\r
+    /// implement `BincodeRead` for performance reasons.\r
+    ///\r
+    /// If this returns an `Error`, `reader` may be in an invalid state.\r
+    #[inline(always)]\r
+    fn deserialize_from_custom_seed<'a, R: BincodeRead<'a>, T: serde::de::DeserializeSeed<'a>>(\r
+        self,\r
+        seed: T,\r
+        reader: R,\r
+    ) -> Result<T::Value> {\r
+        ::internal::deserialize_from_custom_seed(seed, reader, self)\r
+    }\r
+}\r
+\r
+impl<T: InternalOptions> Options for T {}\r
+\r
+/// A configuration struct with a user-specified byte limit\r
+#[derive(Clone, Copy)]\r
+pub struct WithOtherLimit<O: Options, L: SizeLimit> {\r
+    _options: O,\r
+    pub(crate) new_limit: L,\r
+}\r
+\r
+/// A configuration struct with a user-specified endian order\r
+#[derive(Clone, Copy)]\r
+pub struct WithOtherEndian<O: Options, E: BincodeByteOrder> {\r
+    options: O,\r
+    _endian: PhantomData<E>,\r
+}\r
+\r
+/// A configuration struct with a user-specified length encoding\r
+#[derive(Clone, Copy)]\r
+pub struct WithOtherIntEncoding<O: Options, I: IntEncoding> {\r
+    options: O,\r
+    _length: PhantomData<I>,\r
+}\r
+\r
+/// A configuration struct with a user-specified trailing bytes behavior.\r
+#[derive(Clone, Copy)]\r
+pub struct WithOtherTrailing<O: Options, T: TrailingBytes> {\r
+    options: O,\r
+    _trailing: PhantomData<T>,\r
+}\r
+\r
+impl<O: Options, L: SizeLimit> WithOtherLimit<O, L> {\r
+    #[inline(always)]\r
+    pub(crate) fn new(options: O, limit: L) -> WithOtherLimit<O, L> {\r
+        WithOtherLimit {\r
+            _options: options,\r
+            new_limit: limit,\r
+        }\r
+    }\r
+}\r
+\r
+impl<O: Options, E: BincodeByteOrder> WithOtherEndian<O, E> {\r
+    #[inline(always)]\r
+    pub(crate) fn new(options: O) -> WithOtherEndian<O, E> {\r
+        WithOtherEndian {\r
+            options,\r
+            _endian: PhantomData,\r
+        }\r
+    }\r
+}\r
+\r
+impl<O: Options, I: IntEncoding> WithOtherIntEncoding<O, I> {\r
+    #[inline(always)]\r
+    pub(crate) fn new(options: O) -> WithOtherIntEncoding<O, I> {\r
+        WithOtherIntEncoding {\r
+            options,\r
+            _length: PhantomData,\r
+        }\r
+    }\r
+}\r
+\r
+impl<O: Options, T: TrailingBytes> WithOtherTrailing<O, T> {\r
+    #[inline(always)]\r
+    pub(crate) fn new(options: O) -> WithOtherTrailing<O, T> {\r
+        WithOtherTrailing {\r
+            options,\r
+            _trailing: PhantomData,\r
+        }\r
+    }\r
+}\r
+\r
+impl<O: Options, E: BincodeByteOrder + 'static> InternalOptions for WithOtherEndian<O, E> {\r
+    type Limit = O::Limit;\r
+    type Endian = E;\r
+    type IntEncoding = O::IntEncoding;\r
+    type Trailing = O::Trailing;\r
+    #[inline(always)]\r
+    fn limit(&mut self) -> &mut O::Limit {\r
+        self.options.limit()\r
+    }\r
+}\r
+\r
+impl<O: Options, L: SizeLimit + 'static> InternalOptions for WithOtherLimit<O, L> {\r
+    type Limit = L;\r
+    type Endian = O::Endian;\r
+    type IntEncoding = O::IntEncoding;\r
+    type Trailing = O::Trailing;\r
+    fn limit(&mut self) -> &mut L {\r
+        &mut self.new_limit\r
+    }\r
+}\r
+\r
+impl<O: Options, I: IntEncoding + 'static> InternalOptions for WithOtherIntEncoding<O, I> {\r
+    type Limit = O::Limit;\r
+    type Endian = O::Endian;\r
+    type IntEncoding = I;\r
+    type Trailing = O::Trailing;\r
+\r
+    fn limit(&mut self) -> &mut O::Limit {\r
+        self.options.limit()\r
+    }\r
+}\r
+\r
+impl<O: Options, T: TrailingBytes + 'static> InternalOptions for WithOtherTrailing<O, T> {\r
+    type Limit = O::Limit;\r
+    type Endian = O::Endian;\r
+    type IntEncoding = O::IntEncoding;\r
+    type Trailing = T;\r
+\r
+    fn limit(&mut self) -> &mut O::Limit {\r
+        self.options.limit()\r
+    }\r
+}\r
+\r
+mod internal {\r
+    use super::*;\r
+\r
+    pub trait InternalOptions {\r
+        type Limit: SizeLimit + 'static;\r
+        type Endian: BincodeByteOrder + 'static;\r
+        type IntEncoding: IntEncoding + 'static;\r
+        type Trailing: TrailingBytes + 'static;\r
+\r
+        fn limit(&mut self) -> &mut Self::Limit;\r
+    }\r
+\r
+    impl<'a, O: InternalOptions> InternalOptions for &'a mut O {\r
+        type Limit = O::Limit;\r
+        type Endian = O::Endian;\r
+        type IntEncoding = O::IntEncoding;\r
+        type Trailing = O::Trailing;\r
+\r
+        #[inline(always)]\r
+        fn limit(&mut self) -> &mut Self::Limit {\r
+            (*self).limit()\r
+        }\r
+    }\r
+}\r
diff --git a/src/config/trailing.rs b/src/config/trailing.rs
new file mode 100644 (file)
index 0000000..6052fc7
--- /dev/null
@@ -0,0 +1,37 @@
+use de::read::SliceReader;\r
+use {ErrorKind, Result};\r
+\r
+/// A trait for erroring deserialization if not all bytes were read.\r
+pub trait TrailingBytes {\r
+    /// Checks a given slice reader to determine if deserialization used all bytes in the slice.\r
+    fn check_end(reader: &SliceReader) -> Result<()>;\r
+}\r
+\r
+/// A TrailingBytes config that will allow trailing bytes in slices after deserialization.\r
+#[derive(Copy, Clone)]\r
+pub struct AllowTrailing;\r
+\r
+/// A TrailingBytes config that will cause bincode to produce an error if bytes are left over in the slice when deserialization is complete.\r
+\r
+#[derive(Copy, Clone)]\r
+pub struct RejectTrailing;\r
+\r
+impl TrailingBytes for AllowTrailing {\r
+    #[inline(always)]\r
+    fn check_end(_reader: &SliceReader) -> Result<()> {\r
+        Ok(())\r
+    }\r
+}\r
+\r
+impl TrailingBytes for RejectTrailing {\r
+    #[inline(always)]\r
+    fn check_end(reader: &SliceReader) -> Result<()> {\r
+        if reader.is_finished() {\r
+            Ok(())\r
+        } else {\r
+            Err(Box::new(ErrorKind::Custom(\r
+                "Slice had bytes remaining after deserialization".to_string(),\r
+            )))\r
+        }\r
+    }\r
+}\r
diff --git a/src/de/mod.rs b/src/de/mod.rs
new file mode 100644 (file)
index 0000000..7b2bdf5
--- /dev/null
@@ -0,0 +1,515 @@
+use config::{BincodeByteOrder, Options};\r
+use std::io::Read;\r
+\r
+use self::read::{BincodeRead, IoReader, SliceReader};\r
+use byteorder::ReadBytesExt;\r
+use config::{IntEncoding, SizeLimit};\r
+use serde;\r
+use serde::de::Error as DeError;\r
+use serde::de::IntoDeserializer;\r
+use {Error, ErrorKind, Result};\r
+\r
+/// Specialized ways to read data into bincode.\r
+pub mod read;\r
+\r
+/// A Deserializer that reads bytes from a buffer.\r
+///\r
+/// This struct should rarely be used.\r
+/// In most cases, prefer the `deserialize_from` function.\r
+///\r
+/// The ByteOrder that is chosen will impact the endianness that\r
+/// is used to read integers out of the reader.\r
+///\r
+/// ```ignore\r
+/// let d = Deserializer::new(&mut some_reader, SizeLimit::new());\r
+/// serde::Deserialize::deserialize(&mut deserializer);\r
+/// let bytes_read = d.bytes_read();\r
+/// ```\r
+pub struct Deserializer<R, O: Options> {\r
+    pub(crate) reader: R,\r
+    options: O,\r
+}\r
+\r
+macro_rules! impl_deserialize_literal {\r
+    ($name:ident : $ty:ty = $read:ident()) => {\r
+        #[inline]\r
+        pub(crate) fn $name(&mut self) -> Result<$ty> {\r
+            self.read_literal_type::<$ty>()?;\r
+            self.reader\r
+                .$read::<<O::Endian as BincodeByteOrder>::Endian>()\r
+                .map_err(Into::into)\r
+        }\r
+    };\r
+}\r
+\r
+impl<'de, IR: Read, O: Options> Deserializer<IoReader<IR>, O> {\r
+    /// Creates a new Deserializer with a given `Read`er and options.\r
+    pub fn with_reader(r: IR, options: O) -> Self {\r
+        Deserializer {\r
+            reader: IoReader::new(r),\r
+            options,\r
+        }\r
+    }\r
+}\r
+\r
+impl<'de, O: Options> Deserializer<SliceReader<'de>, O> {\r
+    /// Creates a new Deserializer that will read from the given slice.\r
+    pub fn from_slice(slice: &'de [u8], options: O) -> Self {\r
+        Deserializer {\r
+            reader: SliceReader::new(slice),\r
+            options,\r
+        }\r
+    }\r
+}\r
+\r
+impl<'de, R: BincodeRead<'de>, O: Options> Deserializer<R, O> {\r
+    /// Creates a new Deserializer with the given `BincodeRead`er\r
+    pub fn with_bincode_read(r: R, options: O) -> Deserializer<R, O> {\r
+        Deserializer { reader: r, options }\r
+    }\r
+\r
+    pub(crate) fn deserialize_byte(&mut self) -> Result<u8> {\r
+        self.read_literal_type::<u8>()?;\r
+        self.reader.read_u8().map_err(Into::into)\r
+    }\r
+\r
+    impl_deserialize_literal! { deserialize_literal_u16 : u16 = read_u16() }\r
+    impl_deserialize_literal! { deserialize_literal_u32 : u32 = read_u32() }\r
+    impl_deserialize_literal! { deserialize_literal_u64 : u64 = read_u64() }\r
+\r
+    serde_if_integer128! {\r
+        impl_deserialize_literal! { deserialize_literal_u128 : u128 = read_u128() }\r
+    }\r
+\r
+    fn read_bytes(&mut self, count: u64) -> Result<()> {\r
+        self.options.limit().add(count)\r
+    }\r
+\r
+    fn read_literal_type<T>(&mut self) -> Result<()> {\r
+        use std::mem::size_of;\r
+        self.read_bytes(size_of::<T>() as u64)\r
+    }\r
+\r
+    fn read_vec(&mut self) -> Result<Vec<u8>> {\r
+        let len = O::IntEncoding::deserialize_len(self)?;\r
+        self.read_bytes(len as u64)?;\r
+        self.reader.get_byte_buffer(len)\r
+    }\r
+\r
+    fn read_string(&mut self) -> Result<String> {\r
+        let vec = self.read_vec()?;\r
+        String::from_utf8(vec).map_err(|e| ErrorKind::InvalidUtf8Encoding(e.utf8_error()).into())\r
+    }\r
+}\r
+\r
+macro_rules! impl_deserialize_int {\r
+    ($name:ident = $visitor_method:ident ($dser_method:ident)) => {\r
+        #[inline]\r
+        fn $name<V>(self, visitor: V) -> Result<V::Value>\r
+        where\r
+            V: serde::de::Visitor<'de>,\r
+        {\r
+            visitor.$visitor_method(O::IntEncoding::$dser_method(self)?)\r
+        }\r
+    };\r
+}\r
+\r
+impl<'de, 'a, R, O> serde::Deserializer<'de> for &'a mut Deserializer<R, O>\r
+where\r
+    R: BincodeRead<'de>,\r
+    O: Options,\r
+{\r
+    type Error = Error;\r
+\r
+    #[inline]\r
+    fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        Err(Box::new(ErrorKind::DeserializeAnyNotSupported))\r
+    }\r
+\r
+    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        match self.deserialize_byte()? {\r
+            1 => visitor.visit_bool(true),\r
+            0 => visitor.visit_bool(false),\r
+            value => Err(ErrorKind::InvalidBoolEncoding(value).into()),\r
+        }\r
+    }\r
+\r
+    impl_deserialize_int!(deserialize_u16 = visit_u16(deserialize_u16));\r
+    impl_deserialize_int!(deserialize_u32 = visit_u32(deserialize_u32));\r
+    impl_deserialize_int!(deserialize_u64 = visit_u64(deserialize_u64));\r
+    impl_deserialize_int!(deserialize_i16 = visit_i16(deserialize_i16));\r
+    impl_deserialize_int!(deserialize_i32 = visit_i32(deserialize_i32));\r
+    impl_deserialize_int!(deserialize_i64 = visit_i64(deserialize_i64));\r
+\r
+    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        self.read_literal_type::<f32>()?;\r
+        let value = self\r
+            .reader\r
+            .read_f32::<<O::Endian as BincodeByteOrder>::Endian>()?;\r
+        visitor.visit_f32(value)\r
+    }\r
+\r
+    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        self.read_literal_type::<f64>()?;\r
+        let value = self\r
+            .reader\r
+            .read_f64::<<O::Endian as BincodeByteOrder>::Endian>()?;\r
+        visitor.visit_f64(value)\r
+    }\r
+\r
+    serde_if_integer128! {\r
+        impl_deserialize_int!(deserialize_u128 = visit_u128(deserialize_u128));\r
+        impl_deserialize_int!(deserialize_i128 = visit_i128(deserialize_i128));\r
+    }\r
+\r
+    #[inline]\r
+    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        visitor.visit_u8(self.deserialize_byte()? as u8)\r
+    }\r
+\r
+    #[inline]\r
+    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        visitor.visit_i8(self.deserialize_byte()? as i8)\r
+    }\r
+\r
+    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        visitor.visit_unit()\r
+    }\r
+\r
+    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        use std::str;\r
+\r
+        let error = || ErrorKind::InvalidCharEncoding.into();\r
+\r
+        let mut buf = [0u8; 4];\r
+\r
+        // Look at the first byte to see how many bytes must be read\r
+        self.reader.read_exact(&mut buf[..1])?;\r
+        let width = utf8_char_width(buf[0]);\r
+        if width == 1 {\r
+            return visitor.visit_char(buf[0] as char);\r
+        }\r
+        if width == 0 {\r
+            return Err(error());\r
+        }\r
+\r
+        if self.reader.read_exact(&mut buf[1..width]).is_err() {\r
+            return Err(error());\r
+        }\r
+\r
+        let res = str::from_utf8(&buf[..width])\r
+            .ok()\r
+            .and_then(|s| s.chars().next())\r
+            .ok_or_else(error)?;\r
+        visitor.visit_char(res)\r
+    }\r
+\r
+    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        let len = O::IntEncoding::deserialize_len(self)?;\r
+        self.read_bytes(len as u64)?;\r
+        self.reader.forward_read_str(len, visitor)\r
+    }\r
+\r
+    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        visitor.visit_string(self.read_string()?)\r
+    }\r
+\r
+    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        let len = O::IntEncoding::deserialize_len(self)?;\r
+        self.read_bytes(len as u64)?;\r
+        self.reader.forward_read_bytes(len, visitor)\r
+    }\r
+\r
+    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        visitor.visit_byte_buf(self.read_vec()?)\r
+    }\r
+\r
+    fn deserialize_enum<V>(\r
+        self,\r
+        _enum: &'static str,\r
+        _variants: &'static [&'static str],\r
+        visitor: V,\r
+    ) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        impl<'de, 'a, R: 'a, O> serde::de::EnumAccess<'de> for &'a mut Deserializer<R, O>\r
+        where\r
+            R: BincodeRead<'de>,\r
+            O: Options,\r
+        {\r
+            type Error = Error;\r
+            type Variant = Self;\r
+\r
+            fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)>\r
+            where\r
+                V: serde::de::DeserializeSeed<'de>,\r
+            {\r
+                let idx: u32 = O::IntEncoding::deserialize_u32(self)?;\r
+                let val: Result<_> = seed.deserialize(idx.into_deserializer());\r
+                Ok((val?, self))\r
+            }\r
+        }\r
+\r
+        visitor.visit_enum(self)\r
+    }\r
+\r
+    fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        struct Access<'a, R: Read + 'a, O: Options + 'a> {\r
+            deserializer: &'a mut Deserializer<R, O>,\r
+            len: usize,\r
+        }\r
+\r
+        impl<'de, 'a, 'b: 'a, R: BincodeRead<'de> + 'b, O: Options> serde::de::SeqAccess<'de>\r
+            for Access<'a, R, O>\r
+        {\r
+            type Error = Error;\r
+\r
+            fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>\r
+            where\r
+                T: serde::de::DeserializeSeed<'de>,\r
+            {\r
+                if self.len > 0 {\r
+                    self.len -= 1;\r
+                    let value =\r
+                        serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer)?;\r
+                    Ok(Some(value))\r
+                } else {\r
+                    Ok(None)\r
+                }\r
+            }\r
+\r
+            fn size_hint(&self) -> Option<usize> {\r
+                Some(self.len)\r
+            }\r
+        }\r
+\r
+        visitor.visit_seq(Access {\r
+            deserializer: self,\r
+            len,\r
+        })\r
+    }\r
+\r
+    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        let value: u8 = serde::de::Deserialize::deserialize(&mut *self)?;\r
+        match value {\r
+            0 => visitor.visit_none(),\r
+            1 => visitor.visit_some(&mut *self),\r
+            v => Err(ErrorKind::InvalidTagEncoding(v as usize).into()),\r
+        }\r
+    }\r
+\r
+    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        let len = O::IntEncoding::deserialize_len(self)?;\r
+\r
+        self.deserialize_tuple(len, visitor)\r
+    }\r
+\r
+    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        struct Access<'a, R: Read + 'a, O: Options + 'a> {\r
+            deserializer: &'a mut Deserializer<R, O>,\r
+            len: usize,\r
+        }\r
+\r
+        impl<'de, 'a, 'b: 'a, R: BincodeRead<'de> + 'b, O: Options> serde::de::MapAccess<'de>\r
+            for Access<'a, R, O>\r
+        {\r
+            type Error = Error;\r
+\r
+            fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>\r
+            where\r
+                K: serde::de::DeserializeSeed<'de>,\r
+            {\r
+                if self.len > 0 {\r
+                    self.len -= 1;\r
+                    let key =\r
+                        serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer)?;\r
+                    Ok(Some(key))\r
+                } else {\r
+                    Ok(None)\r
+                }\r
+            }\r
+\r
+            fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>\r
+            where\r
+                V: serde::de::DeserializeSeed<'de>,\r
+            {\r
+                let value = serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer)?;\r
+                Ok(value)\r
+            }\r
+\r
+            fn size_hint(&self) -> Option<usize> {\r
+                Some(self.len)\r
+            }\r
+        }\r
+\r
+        let len = O::IntEncoding::deserialize_len(self)?;\r
+\r
+        visitor.visit_map(Access {\r
+            deserializer: self,\r
+            len,\r
+        })\r
+    }\r
+\r
+    fn deserialize_struct<V>(\r
+        self,\r
+        _name: &str,\r
+        fields: &'static [&'static str],\r
+        visitor: V,\r
+    ) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        self.deserialize_tuple(fields.len(), visitor)\r
+    }\r
+\r
+    fn deserialize_identifier<V>(self, _visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        let message = "Bincode does not support Deserializer::deserialize_identifier";\r
+        Err(Error::custom(message))\r
+    }\r
+\r
+    fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        visitor.visit_newtype_struct(self)\r
+    }\r
+\r
+    fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        visitor.visit_unit()\r
+    }\r
+\r
+    fn deserialize_tuple_struct<V>(\r
+        self,\r
+        _name: &'static str,\r
+        len: usize,\r
+        visitor: V,\r
+    ) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        self.deserialize_tuple(len, visitor)\r
+    }\r
+\r
+    fn deserialize_ignored_any<V>(self, _visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        let message = "Bincode does not support Deserializer::deserialize_ignored_any";\r
+        Err(Error::custom(message))\r
+    }\r
+\r
+    fn is_human_readable(&self) -> bool {\r
+        false\r
+    }\r
+}\r
+\r
+impl<'de, 'a, R, O> serde::de::VariantAccess<'de> for &'a mut Deserializer<R, O>\r
+where\r
+    R: BincodeRead<'de>,\r
+    O: Options,\r
+{\r
+    type Error = Error;\r
+\r
+    fn unit_variant(self) -> Result<()> {\r
+        Ok(())\r
+    }\r
+\r
+    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value>\r
+    where\r
+        T: serde::de::DeserializeSeed<'de>,\r
+    {\r
+        serde::de::DeserializeSeed::deserialize(seed, self)\r
+    }\r
+\r
+    fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        serde::de::Deserializer::deserialize_tuple(self, len, visitor)\r
+    }\r
+\r
+    fn struct_variant<V>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'de>,\r
+    {\r
+        serde::de::Deserializer::deserialize_tuple(self, fields.len(), visitor)\r
+    }\r
+}\r
+static UTF8_CHAR_WIDTH: [u8; 256] = [\r
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\r
+    1, // 0x1F\r
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\r
+    1, // 0x3F\r
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\r
+    1, // 0x5F\r
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\r
+    1, // 0x7F\r
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\r
+    0, // 0x9F\r
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\r
+    0, // 0xBF\r
+    0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\r
+    2, // 0xDF\r
+    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEF\r
+    4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xFF\r
+];\r
+\r
+// This function is a copy of core::str::utf8_char_width\r
+fn utf8_char_width(b: u8) -> usize {\r
+    UTF8_CHAR_WIDTH[b as usize] as usize\r
+}\r
diff --git a/src/de/read.rs b/src/de/read.rs
new file mode 100644 (file)
index 0000000..08b76ad
--- /dev/null
@@ -0,0 +1,202 @@
+use error::Result;\r
+use serde;\r
+use std::io;\r
+\r
+/// An optional Read trait for advanced Bincode usage.\r
+///\r
+/// It is highly recommended to use bincode with `io::Read` or `&[u8]` before\r
+/// implementing a custom `BincodeRead`.\r
+///\r
+/// The forward_read_* methods are necessary because some byte sources want\r
+/// to pass a long-lived borrow to the visitor and others want to pass a\r
+/// transient slice.\r
+pub trait BincodeRead<'storage>: io::Read {\r
+    /// Check that the next `length` bytes are a valid string and pass\r
+    /// it on to the serde reader.\r
+    fn forward_read_str<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'storage>;\r
+\r
+    /// Transfer ownership of the next `length` bytes to the caller.\r
+    fn get_byte_buffer(&mut self, length: usize) -> Result<Vec<u8>>;\r
+\r
+    /// Pass a slice of the next `length` bytes on to the serde reader.\r
+    fn forward_read_bytes<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'storage>;\r
+}\r
+\r
+/// A BincodeRead implementation for byte slices\r
+pub struct SliceReader<'storage> {\r
+    slice: &'storage [u8],\r
+}\r
+\r
+/// A BincodeRead implementation for `io::Read`ers\r
+pub struct IoReader<R> {\r
+    reader: R,\r
+    temp_buffer: Vec<u8>,\r
+}\r
+\r
+impl<'storage> SliceReader<'storage> {\r
+    /// Constructs a slice reader\r
+    pub(crate) fn new(bytes: &'storage [u8]) -> SliceReader<'storage> {\r
+        SliceReader { slice: bytes }\r
+    }\r
+\r
+    #[inline(always)]\r
+    fn get_byte_slice(&mut self, length: usize) -> Result<&'storage [u8]> {\r
+        if length > self.slice.len() {\r
+            return Err(SliceReader::unexpected_eof());\r
+        }\r
+        let (read_slice, remaining) = self.slice.split_at(length);\r
+        self.slice = remaining;\r
+        Ok(read_slice)\r
+    }\r
+\r
+    pub(crate) fn is_finished(&self) -> bool {\r
+        self.slice.is_empty()\r
+    }\r
+}\r
+\r
+impl<R> IoReader<R> {\r
+    /// Constructs an IoReadReader\r
+    pub(crate) fn new(r: R) -> IoReader<R> {\r
+        IoReader {\r
+            reader: r,\r
+            temp_buffer: vec![],\r
+        }\r
+    }\r
+}\r
+\r
+impl<'storage> io::Read for SliceReader<'storage> {\r
+    #[inline(always)]\r
+    fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {\r
+        if out.len() > self.slice.len() {\r
+            return Err(io::ErrorKind::UnexpectedEof.into());\r
+        }\r
+        let (read_slice, remaining) = self.slice.split_at(out.len());\r
+        out.copy_from_slice(read_slice);\r
+        self.slice = remaining;\r
+\r
+        Ok(out.len())\r
+    }\r
+\r
+    #[inline(always)]\r
+    fn read_exact(&mut self, out: &mut [u8]) -> io::Result<()> {\r
+        self.read(out).map(|_| ())\r
+    }\r
+}\r
+\r
+impl<R: io::Read> io::Read for IoReader<R> {\r
+    #[inline(always)]\r
+    fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {\r
+        self.reader.read(out)\r
+    }\r
+    #[inline(always)]\r
+    fn read_exact(&mut self, out: &mut [u8]) -> io::Result<()> {\r
+        self.reader.read_exact(out)\r
+    }\r
+}\r
+\r
+impl<'storage> SliceReader<'storage> {\r
+    #[inline(always)]\r
+    fn unexpected_eof() -> Box<::ErrorKind> {\r
+        Box::new(::ErrorKind::Io(io::Error::new(\r
+            io::ErrorKind::UnexpectedEof,\r
+            "",\r
+        )))\r
+    }\r
+}\r
+\r
+impl<'storage> BincodeRead<'storage> for SliceReader<'storage> {\r
+    #[inline(always)]\r
+    fn forward_read_str<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'storage>,\r
+    {\r
+        use ErrorKind;\r
+        let string = match ::std::str::from_utf8(self.get_byte_slice(length)?) {\r
+            Ok(s) => s,\r
+            Err(e) => return Err(ErrorKind::InvalidUtf8Encoding(e).into()),\r
+        };\r
+        visitor.visit_borrowed_str(string)\r
+    }\r
+\r
+    #[inline(always)]\r
+    fn get_byte_buffer(&mut self, length: usize) -> Result<Vec<u8>> {\r
+        self.get_byte_slice(length).map(|x| x.to_vec())\r
+    }\r
+\r
+    #[inline(always)]\r
+    fn forward_read_bytes<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'storage>,\r
+    {\r
+        visitor.visit_borrowed_bytes(self.get_byte_slice(length)?)\r
+    }\r
+}\r
+\r
+impl<R> IoReader<R>\r
+where\r
+    R: io::Read,\r
+{\r
+    fn fill_buffer(&mut self, length: usize) -> Result<()> {\r
+        self.temp_buffer.resize(length, 0);\r
+\r
+        self.reader.read_exact(&mut self.temp_buffer)?;\r
+\r
+        Ok(())\r
+    }\r
+}\r
+\r
+impl<'a, R> BincodeRead<'a> for IoReader<R>\r
+where\r
+    R: io::Read,\r
+{\r
+    fn forward_read_str<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'a>,\r
+    {\r
+        self.fill_buffer(length)?;\r
+\r
+        let string = match ::std::str::from_utf8(&self.temp_buffer[..]) {\r
+            Ok(s) => s,\r
+            Err(e) => return Err(::ErrorKind::InvalidUtf8Encoding(e).into()),\r
+        };\r
+\r
+        visitor.visit_str(string)\r
+    }\r
+\r
+    fn get_byte_buffer(&mut self, length: usize) -> Result<Vec<u8>> {\r
+        self.fill_buffer(length)?;\r
+        Ok(::std::mem::replace(&mut self.temp_buffer, Vec::new()))\r
+    }\r
+\r
+    fn forward_read_bytes<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>\r
+    where\r
+        V: serde::de::Visitor<'a>,\r
+    {\r
+        self.fill_buffer(length)?;\r
+        visitor.visit_bytes(&self.temp_buffer[..])\r
+    }\r
+}\r
+\r
+#[cfg(test)]\r
+mod test {\r
+    use super::IoReader;\r
+\r
+    #[test]\r
+    fn test_fill_buffer() {\r
+        let buffer = vec![0u8; 64];\r
+        let mut reader = IoReader::new(buffer.as_slice());\r
+\r
+        reader.fill_buffer(20).unwrap();\r
+        assert_eq!(20, reader.temp_buffer.len());\r
+\r
+        reader.fill_buffer(30).unwrap();\r
+        assert_eq!(30, reader.temp_buffer.len());\r
+\r
+        reader.fill_buffer(5).unwrap();\r
+        assert_eq!(5, reader.temp_buffer.len());\r
+    }\r
+}\r
diff --git a/src/error.rs b/src/error.rs
new file mode 100644 (file)
index 0000000..420fa7a
--- /dev/null
@@ -0,0 +1,115 @@
+use std::error::Error as StdError;\r
+use std::io;\r
+use std::str::Utf8Error;\r
+use std::{error, fmt};\r
+\r
+use serde;\r
+\r
+/// The result of a serialization or deserialization operation.\r
+pub type Result<T> = ::std::result::Result<T, Error>;\r
+\r
+/// An error that can be produced during (de)serializing.\r
+pub type Error = Box<ErrorKind>;\r
+\r
+/// The kind of error that can be produced during a serialization or deserialization.\r
+#[derive(Debug)]\r
+pub enum ErrorKind {\r
+    /// If the error stems from the reader/writer that is being used\r
+    /// during (de)serialization, that error will be stored and returned here.\r
+    Io(io::Error),\r
+    /// Returned if the deserializer attempts to deserialize a string that is not valid utf8\r
+    InvalidUtf8Encoding(Utf8Error),\r
+    /// Returned if the deserializer attempts to deserialize a bool that was\r
+    /// not encoded as either a 1 or a 0\r
+    InvalidBoolEncoding(u8),\r
+    /// Returned if the deserializer attempts to deserialize a char that is not in the correct format.\r
+    InvalidCharEncoding,\r
+    /// Returned if the deserializer attempts to deserialize the tag of an enum that is\r
+    /// not in the expected ranges\r
+    InvalidTagEncoding(usize),\r
+    /// Serde has a deserialize_any method that lets the format hint to the\r
+    /// object which route to take in deserializing.\r
+    DeserializeAnyNotSupported,\r
+    /// If (de)serializing a message takes more than the provided size limit, this\r
+    /// error is returned.\r
+    SizeLimit,\r
+    /// Bincode can not encode sequences of unknown length (like iterators).\r
+    SequenceMustHaveLength,\r
+    /// A custom error message from Serde.\r
+    Custom(String),\r
+}\r
+\r
+impl StdError for ErrorKind {\r
+    fn description(&self) -> &str {\r
+        match *self {\r
+            ErrorKind::Io(ref err) => error::Error::description(err),\r
+            ErrorKind::InvalidUtf8Encoding(_) => "string is not valid utf8",\r
+            ErrorKind::InvalidBoolEncoding(_) => "invalid u8 while decoding bool",\r
+            ErrorKind::InvalidCharEncoding => "char is not valid",\r
+            ErrorKind::InvalidTagEncoding(_) => "tag for enum is not valid",\r
+            ErrorKind::SequenceMustHaveLength => {\r
+                "Bincode can only encode sequences and maps that have a knowable size ahead of time"\r
+            }\r
+            ErrorKind::DeserializeAnyNotSupported => {\r
+                "Bincode doesn't support serde::Deserializer::deserialize_any"\r
+            }\r
+            ErrorKind::SizeLimit => "the size limit has been reached",\r
+            ErrorKind::Custom(ref msg) => msg,\r
+        }\r
+    }\r
+\r
+    fn cause(&self) -> Option<&error::Error> {\r
+        match *self {\r
+            ErrorKind::Io(ref err) => Some(err),\r
+            ErrorKind::InvalidUtf8Encoding(_) => None,\r
+            ErrorKind::InvalidBoolEncoding(_) => None,\r
+            ErrorKind::InvalidCharEncoding => None,\r
+            ErrorKind::InvalidTagEncoding(_) => None,\r
+            ErrorKind::SequenceMustHaveLength => None,\r
+            ErrorKind::DeserializeAnyNotSupported => None,\r
+            ErrorKind::SizeLimit => None,\r
+            ErrorKind::Custom(_) => None,\r
+        }\r
+    }\r
+}\r
+\r
+impl From<io::Error> for Error {\r
+    fn from(err: io::Error) -> Error {\r
+        ErrorKind::Io(err).into()\r
+    }\r
+}\r
+\r
+impl fmt::Display for ErrorKind {\r
+    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {\r
+        match *self {\r
+            ErrorKind::Io(ref ioerr) => write!(fmt, "io error: {}", ioerr),\r
+            ErrorKind::InvalidUtf8Encoding(ref e) => write!(fmt, "{}: {}", self.description(), e),\r
+            ErrorKind::InvalidBoolEncoding(b) => {\r
+                write!(fmt, "{}, expected 0 or 1, found {}", self.description(), b)\r
+            }\r
+            ErrorKind::InvalidCharEncoding => write!(fmt, "{}", self.description()),\r
+            ErrorKind::InvalidTagEncoding(tag) => {\r
+                write!(fmt, "{}, found {}", self.description(), tag)\r
+            }\r
+            ErrorKind::SequenceMustHaveLength => write!(fmt, "{}", self.description()),\r
+            ErrorKind::SizeLimit => write!(fmt, "{}", self.description()),\r
+            ErrorKind::DeserializeAnyNotSupported => write!(\r
+                fmt,\r
+                "Bincode does not support the serde::Deserializer::deserialize_any method"\r
+            ),\r
+            ErrorKind::Custom(ref s) => s.fmt(fmt),\r
+        }\r
+    }\r
+}\r
+\r
+impl serde::de::Error for Error {\r
+    fn custom<T: fmt::Display>(desc: T) -> Error {\r
+        ErrorKind::Custom(desc.to_string()).into()\r
+    }\r
+}\r
+\r
+impl serde::ser::Error for Error {\r
+    fn custom<T: fmt::Display>(msg: T) -> Self {\r
+        ErrorKind::Custom(msg.to_string()).into()\r
+    }\r
+}\r
diff --git a/src/internal.rs b/src/internal.rs
new file mode 100644 (file)
index 0000000..1d2a9a1
--- /dev/null
@@ -0,0 +1,124 @@
+use serde;\r
+use std::io::{Read, Write};\r
+use std::marker::PhantomData;\r
+\r
+use config::{Infinite, InternalOptions, Options, SizeLimit, TrailingBytes};\r
+use de::read::BincodeRead;\r
+use Result;\r
+\r
+pub(crate) fn serialize_into<W, T: ?Sized, O>(writer: W, value: &T, mut options: O) -> Result<()>\r
+where\r
+    W: Write,\r
+    T: serde::Serialize,\r
+    O: InternalOptions,\r
+{\r
+    if options.limit().limit().is_some() {\r
+        // "compute" the size for the side-effect\r
+        // of returning Err if the bound was reached.\r
+        serialized_size(value, &mut options)?;\r
+    }\r
+\r
+    let mut serializer = ::ser::Serializer::<_, O>::new(writer, options);\r
+    serde::Serialize::serialize(value, &mut serializer)\r
+}\r
+\r
+pub(crate) fn serialize<T: ?Sized, O>(value: &T, mut options: O) -> Result<Vec<u8>>\r
+where\r
+    T: serde::Serialize,\r
+    O: InternalOptions,\r
+{\r
+    let mut writer = {\r
+        let actual_size = serialized_size(value, &mut options)?;\r
+        Vec::with_capacity(actual_size as usize)\r
+    };\r
+\r
+    serialize_into(&mut writer, value, options.with_no_limit())?;\r
+    Ok(writer)\r
+}\r
+\r
+pub(crate) fn serialized_size<T: ?Sized, O: InternalOptions>(value: &T, options: O) -> Result<u64>\r
+where\r
+    T: serde::Serialize,\r
+{\r
+    let mut size_counter = ::ser::SizeChecker { options, total: 0 };\r
+\r
+    let result = value.serialize(&mut size_counter);\r
+    result.map(|_| size_counter.total)\r
+}\r
+\r
+pub(crate) fn deserialize_from<R, T, O>(reader: R, options: O) -> Result<T>\r
+where\r
+    R: Read,\r
+    T: serde::de::DeserializeOwned,\r
+    O: InternalOptions,\r
+{\r
+    deserialize_from_seed(PhantomData, reader, options)\r
+}\r
+\r
+pub(crate) fn deserialize_from_seed<'a, R, T, O>(seed: T, reader: R, options: O) -> Result<T::Value>\r
+where\r
+    R: Read,\r
+    T: serde::de::DeserializeSeed<'a>,\r
+    O: InternalOptions,\r
+{\r
+    let reader = ::de::read::IoReader::new(reader);\r
+    deserialize_from_custom_seed(seed, reader, options)\r
+}\r
+\r
+pub(crate) fn deserialize_from_custom<'a, R, T, O>(reader: R, options: O) -> Result<T>\r
+where\r
+    R: BincodeRead<'a>,\r
+    T: serde::de::DeserializeOwned,\r
+    O: InternalOptions,\r
+{\r
+    deserialize_from_custom_seed(PhantomData, reader, options)\r
+}\r
+\r
+pub(crate) fn deserialize_from_custom_seed<'a, R, T, O>(\r
+    seed: T,\r
+    reader: R,\r
+    options: O,\r
+) -> Result<T::Value>\r
+where\r
+    R: BincodeRead<'a>,\r
+    T: serde::de::DeserializeSeed<'a>,\r
+    O: InternalOptions,\r
+{\r
+    let mut deserializer = ::de::Deserializer::<_, O>::with_bincode_read(reader, options);\r
+    seed.deserialize(&mut deserializer)\r
+}\r
+\r
+pub(crate) fn deserialize_in_place<'a, R, T, O>(reader: R, options: O, place: &mut T) -> Result<()>\r
+where\r
+    R: BincodeRead<'a>,\r
+    T: serde::de::Deserialize<'a>,\r
+    O: InternalOptions,\r
+{\r
+    let mut deserializer = ::de::Deserializer::<_, _>::with_bincode_read(reader, options);\r
+    serde::Deserialize::deserialize_in_place(&mut deserializer, place)\r
+}\r
+\r
+pub(crate) fn deserialize<'a, T, O>(bytes: &'a [u8], options: O) -> Result<T>\r
+where\r
+    T: serde::de::Deserialize<'a>,\r
+    O: InternalOptions,\r
+{\r
+    deserialize_seed(PhantomData, bytes, options)\r
+}\r
+\r
+pub(crate) fn deserialize_seed<'a, T, O>(seed: T, bytes: &'a [u8], options: O) -> Result<T::Value>\r
+where\r
+    T: serde::de::DeserializeSeed<'a>,\r
+    O: InternalOptions,\r
+{\r
+    let options = ::config::WithOtherLimit::new(options, Infinite);\r
+\r
+    let reader = ::de::read::SliceReader::new(bytes);\r
+    let mut deserializer = ::de::Deserializer::with_bincode_read(reader, options);\r
+    let val = seed.deserialize(&mut deserializer)?;\r
+\r
+    match O::Trailing::check_end(&deserializer.reader) {\r
+        Ok(_) => Ok(val),\r
+        Err(err) => Err(err),\r
+    }\r
+}\r
diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644 (file)
index 0000000..3969ab7
--- /dev/null
@@ -0,0 +1,201 @@
+#![deny(missing_docs)]\r
+#![allow(unknown_lints, bare_trait_objects, deprecated)]\r
+\r
+//! Bincode is a crate for encoding and decoding using a tiny binary\r
+//! serialization strategy.  Using it, you can easily go from having\r
+//! an object in memory, quickly serialize it to bytes, and then\r
+//! deserialize it back just as fast!\r
+//!\r
+//! ### Using Basic Functions\r
+//!\r
+//! ```edition2018\r
+//! fn main() {\r
+//!     // The object that we will serialize.\r
+//!     let target: Option<String>  = Some("hello world".to_string());\r
+//!\r
+//!     let encoded: Vec<u8> = bincode::serialize(&target).unwrap();\r
+//!     let decoded: Option<String> = bincode::deserialize(&encoded[..]).unwrap();\r
+//!     assert_eq!(target, decoded);\r
+//! }\r
+//! ```\r
+//!\r
+//! ### 128bit numbers\r
+//!\r
+//! Support for `i128` and `u128` is automatically enabled on Rust toolchains\r
+//! greater than or equal to `1.26.0` and disabled for targets which do not support it\r
+\r
+#![doc(html_root_url = "https://docs.rs/bincode/1.3.3")]\r
+#![crate_name = "bincode"]\r
+#![crate_type = "rlib"]\r
+#![crate_type = "dylib"]\r
+\r
+#[macro_use]\r
+extern crate serde;\r
+\r
+pub mod config;\r
+/// Deserialize bincode data to a Rust data structure.\r
+pub mod de;\r
+\r
+mod byteorder;\r
+mod error;\r
+mod internal;\r
+mod ser;\r
+\r
+pub use config::{Config, DefaultOptions, Options};\r
+pub use de::read::BincodeRead;\r
+pub use de::Deserializer;\r
+pub use error::{Error, ErrorKind, Result};\r
+pub use ser::Serializer;\r
+\r
+/// Get a default configuration object.\r
+///\r
+/// ### Default Configuration:\r
+///\r
+/// | Byte limit | Endianness |\r
+/// |------------|------------|\r
+/// | Unlimited  | Little     |\r
+#[inline(always)]\r
+#[deprecated(since = "1.3.0", note = "please use `options()` instead")]\r
+pub fn config() -> Config {\r
+    Config::new()\r
+}\r
+\r
+/// Get a default configuration object.\r
+///\r
+/// **Warning:** the default configuration returned by this function\r
+/// is not the same as that used by the other functions in this\r
+/// module. See the\r
+/// [config](config/index.html#options-struct-vs-bincode-functions)\r
+/// module for more details\r
+///\r
+/// ### Default Configuration:\r
+///\r
+/// | Byte limit | Endianness | Int Encoding | Trailing Behavior |\r
+/// |------------|------------|--------------|-------------------|\r
+/// | Unlimited  | Little     | Varint       | Reject            |\r
+#[inline(always)]\r
+pub fn options() -> DefaultOptions {\r
+    DefaultOptions::new()\r
+}\r
+\r
+/// Serializes an object directly into a `Writer` using the default configuration.\r
+///\r
+/// If the serialization would take more bytes than allowed by the size limit, an error\r
+/// is returned and *no bytes* will be written into the `Writer`.\r
+///\r
+/// **Warning:** the default configuration used by this function is not\r
+/// the same as that used by the `DefaultOptions` struct. See the\r
+/// [config](config/index.html#options-struct-vs-bincode-functions)\r
+/// module for more details\r
+pub fn serialize_into<W, T: ?Sized>(writer: W, value: &T) -> Result<()>\r
+where\r
+    W: std::io::Write,\r
+    T: serde::Serialize,\r
+{\r
+    DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .serialize_into(writer, value)\r
+}\r
+\r
+/// Serializes a serializable object into a `Vec` of bytes using the default configuration.\r
+///\r
+/// **Warning:** the default configuration used by this function is not\r
+/// the same as that used by the `DefaultOptions` struct. See the\r
+/// [config](config/index.html#options-struct-vs-bincode-functions)\r
+/// module for more details\r
+pub fn serialize<T: ?Sized>(value: &T) -> Result<Vec<u8>>\r
+where\r
+    T: serde::Serialize,\r
+{\r
+    DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .allow_trailing_bytes()\r
+        .serialize(value)\r
+}\r
+\r
+/// Deserializes an object directly from a `Read`er using the default configuration.\r
+///\r
+/// If this returns an `Error`, `reader` may be in an invalid state.\r
+///\r
+/// **Warning:** the default configuration used by this function is not\r
+/// the same as that used by the `DefaultOptions` struct. See the\r
+/// [config](config/index.html#options-struct-vs-bincode-functions)\r
+/// module for more details\r
+pub fn deserialize_from<R, T>(reader: R) -> Result<T>\r
+where\r
+    R: std::io::Read,\r
+    T: serde::de::DeserializeOwned,\r
+{\r
+    DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .allow_trailing_bytes()\r
+        .deserialize_from(reader)\r
+}\r
+\r
+/// Deserializes an object from a custom `BincodeRead`er using the default configuration.\r
+/// It is highly recommended to use `deserialize_from` unless you need to implement\r
+/// `BincodeRead` for performance reasons.\r
+///\r
+/// If this returns an `Error`, `reader` may be in an invalid state.\r
+///\r
+/// **Warning:** the default configuration used by this function is not\r
+/// the same as that used by the `DefaultOptions` struct. See the\r
+/// [config](config/index.html#options-struct-vs-bincode-functions)\r
+/// module for more details\r
+pub fn deserialize_from_custom<'a, R, T>(reader: R) -> Result<T>\r
+where\r
+    R: de::read::BincodeRead<'a>,\r
+    T: serde::de::DeserializeOwned,\r
+{\r
+    DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .allow_trailing_bytes()\r
+        .deserialize_from_custom(reader)\r
+}\r
+\r
+/// Only use this if you know what you're doing.\r
+///\r
+/// This is part of the public API.\r
+#[doc(hidden)]\r
+pub fn deserialize_in_place<'a, R, T>(reader: R, place: &mut T) -> Result<()>\r
+where\r
+    T: serde::de::Deserialize<'a>,\r
+    R: BincodeRead<'a>,\r
+{\r
+    DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .allow_trailing_bytes()\r
+        .deserialize_in_place(reader, place)\r
+}\r
+\r
+/// Deserializes a slice of bytes into an instance of `T` using the default configuration.\r
+///\r
+/// **Warning:** the default configuration used by this function is not\r
+/// the same as that used by the `DefaultOptions` struct. See the\r
+/// [config](config/index.html#options-struct-vs-bincode-functions)\r
+/// module for more details\r
+pub fn deserialize<'a, T>(bytes: &'a [u8]) -> Result<T>\r
+where\r
+    T: serde::de::Deserialize<'a>,\r
+{\r
+    DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .allow_trailing_bytes()\r
+        .deserialize(bytes)\r
+}\r
+\r
+/// Returns the size that an object would be if serialized using Bincode with the default configuration.\r
+///\r
+/// **Warning:** the default configuration used by this function is not\r
+/// the same as that used by the `DefaultOptions` struct. See the\r
+/// [config](config/index.html#options-struct-vs-bincode-functions)\r
+/// module for more details\r
+pub fn serialized_size<T: ?Sized>(value: &T) -> Result<u64>\r
+where\r
+    T: serde::Serialize,\r
+{\r
+    DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .allow_trailing_bytes()\r
+        .serialized_size(value)\r
+}\r
diff --git a/src/ser/mod.rs b/src/ser/mod.rs
new file mode 100644 (file)
index 0000000..be4f3f2
--- /dev/null
@@ -0,0 +1,772 @@
+use std::io::Write;\r
+use std::u32;\r
+\r
+use serde;\r
+\r
+use byteorder::WriteBytesExt;\r
+\r
+use super::config::{IntEncoding, SizeLimit};\r
+use super::{Error, ErrorKind, Result};\r
+use config::{BincodeByteOrder, Options};\r
+use std::mem::size_of;\r
+\r
+/// An Serializer that encodes values directly into a Writer.\r
+///\r
+/// The specified byte-order will impact the endianness that is\r
+/// used during the encoding.\r
+///\r
+/// This struct should not be used often.\r
+/// For most cases, prefer the `encode_into` function.\r
+pub struct Serializer<W, O: Options> {\r
+    writer: W,\r
+    _options: O,\r
+}\r
+\r
+macro_rules! impl_serialize_literal {\r
+    ($ser_method:ident($ty:ty) = $write:ident()) => {\r
+        pub(crate) fn $ser_method(&mut self, v: $ty) -> Result<()> {\r
+            self.writer\r
+                .$write::<<O::Endian as BincodeByteOrder>::Endian>(v)\r
+                .map_err(Into::into)\r
+        }\r
+    };\r
+}\r
+\r
+impl<W: Write, O: Options> Serializer<W, O> {\r
+    /// Creates a new Serializer with the given `Write`r.\r
+    pub fn new(w: W, options: O) -> Serializer<W, O> {\r
+        Serializer {\r
+            writer: w,\r
+            _options: options,\r
+        }\r
+    }\r
+\r
+    pub(crate) fn serialize_byte(&mut self, v: u8) -> Result<()> {\r
+        self.writer.write_u8(v).map_err(Into::into)\r
+    }\r
+\r
+    impl_serialize_literal! {serialize_literal_u16(u16) = write_u16()}\r
+    impl_serialize_literal! {serialize_literal_u32(u32) = write_u32()}\r
+    impl_serialize_literal! {serialize_literal_u64(u64) = write_u64()}\r
+\r
+    serde_if_integer128! {\r
+        impl_serialize_literal!{serialize_literal_u128(u128) = write_u128()}\r
+    }\r
+}\r
+\r
+macro_rules! impl_serialize_int {\r
+    ($ser_method:ident($ty:ty) = $ser_int:ident()) => {\r
+        fn $ser_method(self, v: $ty) -> Result<()> {\r
+            O::IntEncoding::$ser_int(self, v)\r
+        }\r
+    };\r
+}\r
+\r
+impl<'a, W: Write, O: Options> serde::Serializer for &'a mut Serializer<W, O> {\r
+    type Ok = ();\r
+    type Error = Error;\r
+    type SerializeSeq = Compound<'a, W, O>;\r
+    type SerializeTuple = Compound<'a, W, O>;\r
+    type SerializeTupleStruct = Compound<'a, W, O>;\r
+    type SerializeTupleVariant = Compound<'a, W, O>;\r
+    type SerializeMap = Compound<'a, W, O>;\r
+    type SerializeStruct = Compound<'a, W, O>;\r
+    type SerializeStructVariant = Compound<'a, W, O>;\r
+\r
+    fn serialize_unit(self) -> Result<()> {\r
+        Ok(())\r
+    }\r
+\r
+    fn serialize_unit_struct(self, _: &'static str) -> Result<()> {\r
+        Ok(())\r
+    }\r
+\r
+    fn serialize_bool(self, v: bool) -> Result<()> {\r
+        self.serialize_byte(v as u8)\r
+    }\r
+\r
+    fn serialize_u8(self, v: u8) -> Result<()> {\r
+        self.serialize_byte(v)\r
+    }\r
+\r
+    impl_serialize_int! {serialize_u16(u16) = serialize_u16()}\r
+    impl_serialize_int! {serialize_u32(u32) = serialize_u32()}\r
+    impl_serialize_int! {serialize_u64(u64) = serialize_u64()}\r
+\r
+    fn serialize_i8(self, v: i8) -> Result<()> {\r
+        self.serialize_byte(v as u8)\r
+    }\r
+\r
+    impl_serialize_int! {serialize_i16(i16) = serialize_i16()}\r
+    impl_serialize_int! {serialize_i32(i32) = serialize_i32()}\r
+    impl_serialize_int! {serialize_i64(i64) = serialize_i64()}\r
+\r
+    serde_if_integer128! {\r
+        impl_serialize_int!{serialize_u128(u128) = serialize_u128()}\r
+        impl_serialize_int!{serialize_i128(i128) = serialize_i128()}\r
+    }\r
+\r
+    fn serialize_f32(self, v: f32) -> Result<()> {\r
+        self.writer\r
+            .write_f32::<<O::Endian as BincodeByteOrder>::Endian>(v)\r
+            .map_err(Into::into)\r
+    }\r
+\r
+    fn serialize_f64(self, v: f64) -> Result<()> {\r
+        self.writer\r
+            .write_f64::<<O::Endian as BincodeByteOrder>::Endian>(v)\r
+            .map_err(Into::into)\r
+    }\r
+\r
+    fn serialize_str(self, v: &str) -> Result<()> {\r
+        O::IntEncoding::serialize_len(self, v.len())?;\r
+        self.writer.write_all(v.as_bytes()).map_err(Into::into)\r
+    }\r
+\r
+    fn serialize_char(self, c: char) -> Result<()> {\r
+        self.writer\r
+            .write_all(encode_utf8(c).as_slice())\r
+            .map_err(Into::into)\r
+    }\r
+\r
+    fn serialize_bytes(self, v: &[u8]) -> Result<()> {\r
+        O::IntEncoding::serialize_len(self, v.len())?;\r
+        self.writer.write_all(v).map_err(Into::into)\r
+    }\r
+\r
+    fn serialize_none(self) -> Result<()> {\r
+        self.writer.write_u8(0).map_err(Into::into)\r
+    }\r
+\r
+    fn serialize_some<T: ?Sized>(self, v: &T) -> Result<()>\r
+    where\r
+        T: serde::Serialize,\r
+    {\r
+        self.writer.write_u8(1)?;\r
+        v.serialize(self)\r
+    }\r
+\r
+    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {\r
+        let len = len.ok_or(ErrorKind::SequenceMustHaveLength)?;\r
+        O::IntEncoding::serialize_len(self, len)?;\r
+        Ok(Compound { ser: self })\r
+    }\r
+\r
+    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {\r
+        Ok(Compound { ser: self })\r
+    }\r
+\r
+    fn serialize_tuple_struct(\r
+        self,\r
+        _name: &'static str,\r
+        _len: usize,\r
+    ) -> Result<Self::SerializeTupleStruct> {\r
+        Ok(Compound { ser: self })\r
+    }\r
+\r
+    fn serialize_tuple_variant(\r
+        self,\r
+        _name: &'static str,\r
+        variant_index: u32,\r
+        _variant: &'static str,\r
+        _len: usize,\r
+    ) -> Result<Self::SerializeTupleVariant> {\r
+        O::IntEncoding::serialize_u32(self, variant_index)?;\r
+        Ok(Compound { ser: self })\r
+    }\r
+\r
+    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {\r
+        let len = len.ok_or(ErrorKind::SequenceMustHaveLength)?;\r
+        O::IntEncoding::serialize_len(self, len)?;\r
+        Ok(Compound { ser: self })\r
+    }\r
+\r
+    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {\r
+        Ok(Compound { ser: self })\r
+    }\r
+\r
+    fn serialize_struct_variant(\r
+        self,\r
+        _name: &'static str,\r
+        variant_index: u32,\r
+        _variant: &'static str,\r
+        _len: usize,\r
+    ) -> Result<Self::SerializeStructVariant> {\r
+        O::IntEncoding::serialize_u32(self, variant_index)?;\r
+        Ok(Compound { ser: self })\r
+    }\r
+\r
+    fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) -> Result<()>\r
+    where\r
+        T: serde::ser::Serialize,\r
+    {\r
+        value.serialize(self)\r
+    }\r
+\r
+    fn serialize_newtype_variant<T: ?Sized>(\r
+        self,\r
+        _name: &'static str,\r
+        variant_index: u32,\r
+        _variant: &'static str,\r
+        value: &T,\r
+    ) -> Result<()>\r
+    where\r
+        T: serde::ser::Serialize,\r
+    {\r
+        O::IntEncoding::serialize_u32(self, variant_index)?;\r
+        value.serialize(self)\r
+    }\r
+\r
+    fn serialize_unit_variant(\r
+        self,\r
+        _name: &'static str,\r
+        variant_index: u32,\r
+        _variant: &'static str,\r
+    ) -> Result<()> {\r
+        O::IntEncoding::serialize_u32(self, variant_index)\r
+    }\r
+\r
+    fn is_human_readable(&self) -> bool {\r
+        false\r
+    }\r
+}\r
+\r
+pub(crate) struct SizeChecker<O: Options> {\r
+    pub options: O,\r
+    pub total: u64,\r
+}\r
+\r
+impl<O: Options> SizeChecker<O> {\r
+    fn add_raw(&mut self, size: u64) -> Result<()> {\r
+        self.options.limit().add(size)?;\r
+        self.total += size;\r
+\r
+        Ok(())\r
+    }\r
+\r
+    fn add_discriminant(&mut self, idx: u32) -> Result<()> {\r
+        let bytes = O::IntEncoding::u32_size(idx);\r
+        self.add_raw(bytes)\r
+    }\r
+\r
+    fn add_len(&mut self, len: usize) -> Result<()> {\r
+        let bytes = O::IntEncoding::len_size(len);\r
+        self.add_raw(bytes)\r
+    }\r
+}\r
+\r
+macro_rules! impl_size_int {\r
+    ($ser_method:ident($ty:ty) = $size_method:ident()) => {\r
+        fn $ser_method(self, v: $ty) -> Result<()> {\r
+            self.add_raw(O::IntEncoding::$size_method(v))\r
+        }\r
+    };\r
+}\r
+\r
+impl<'a, O: Options> serde::Serializer for &'a mut SizeChecker<O> {\r
+    type Ok = ();\r
+    type Error = Error;\r
+    type SerializeSeq = SizeCompound<'a, O>;\r
+    type SerializeTuple = SizeCompound<'a, O>;\r
+    type SerializeTupleStruct = SizeCompound<'a, O>;\r
+    type SerializeTupleVariant = SizeCompound<'a, O>;\r
+    type SerializeMap = SizeCompound<'a, O>;\r
+    type SerializeStruct = SizeCompound<'a, O>;\r
+    type SerializeStructVariant = SizeCompound<'a, O>;\r
+\r
+    fn serialize_unit(self) -> Result<()> {\r
+        Ok(())\r
+    }\r
+\r
+    fn serialize_unit_struct(self, _: &'static str) -> Result<()> {\r
+        Ok(())\r
+    }\r
+\r
+    fn serialize_bool(self, _: bool) -> Result<()> {\r
+        self.add_raw(1)\r
+    }\r
+\r
+    fn serialize_u8(self, _: u8) -> Result<()> {\r
+        self.add_raw(1)\r
+    }\r
+    fn serialize_i8(self, _: i8) -> Result<()> {\r
+        self.add_raw(1)\r
+    }\r
+\r
+    impl_size_int! {serialize_u16(u16) = u16_size()}\r
+    impl_size_int! {serialize_u32(u32) = u32_size()}\r
+    impl_size_int! {serialize_u64(u64) = u64_size()}\r
+    impl_size_int! {serialize_i16(i16) = i16_size()}\r
+    impl_size_int! {serialize_i32(i32) = i32_size()}\r
+    impl_size_int! {serialize_i64(i64) = i64_size()}\r
+\r
+    serde_if_integer128! {\r
+        impl_size_int!{serialize_u128(u128) = u128_size()}\r
+        impl_size_int!{serialize_i128(i128) = i128_size()}\r
+    }\r
+\r
+    fn serialize_f32(self, _: f32) -> Result<()> {\r
+        self.add_raw(size_of::<f32>() as u64)\r
+    }\r
+\r
+    fn serialize_f64(self, _: f64) -> Result<()> {\r
+        self.add_raw(size_of::<f64>() as u64)\r
+    }\r
+\r
+    fn serialize_str(self, v: &str) -> Result<()> {\r
+        self.add_len(v.len())?;\r
+        self.add_raw(v.len() as u64)\r
+    }\r
+\r
+    fn serialize_char(self, c: char) -> Result<()> {\r
+        self.add_raw(encode_utf8(c).as_slice().len() as u64)\r
+    }\r
+\r
+    fn serialize_bytes(self, v: &[u8]) -> Result<()> {\r
+        self.add_len(v.len())?;\r
+        self.add_raw(v.len() as u64)\r
+    }\r
+\r
+    fn serialize_none(self) -> Result<()> {\r
+        self.add_raw(1)\r
+    }\r
+\r
+    fn serialize_some<T: ?Sized>(self, v: &T) -> Result<()>\r
+    where\r
+        T: serde::Serialize,\r
+    {\r
+        self.add_raw(1)?;\r
+        v.serialize(self)\r
+    }\r
+\r
+    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {\r
+        let len = len.ok_or(ErrorKind::SequenceMustHaveLength)?;\r
+\r
+        self.add_len(len)?;\r
+        Ok(SizeCompound { ser: self })\r
+    }\r
+\r
+    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {\r
+        Ok(SizeCompound { ser: self })\r
+    }\r
+\r
+    fn serialize_tuple_struct(\r
+        self,\r
+        _name: &'static str,\r
+        _len: usize,\r
+    ) -> Result<Self::SerializeTupleStruct> {\r
+        Ok(SizeCompound { ser: self })\r
+    }\r
+\r
+    fn serialize_tuple_variant(\r
+        self,\r
+        _name: &'static str,\r
+        variant_index: u32,\r
+        _variant: &'static str,\r
+        _len: usize,\r
+    ) -> Result<Self::SerializeTupleVariant> {\r
+        self.add_raw(O::IntEncoding::u32_size(variant_index))?;\r
+        Ok(SizeCompound { ser: self })\r
+    }\r
+\r
+    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {\r
+        let len = len.ok_or(ErrorKind::SequenceMustHaveLength)?;\r
+\r
+        self.add_len(len)?;\r
+        Ok(SizeCompound { ser: self })\r
+    }\r
+\r
+    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {\r
+        Ok(SizeCompound { ser: self })\r
+    }\r
+\r
+    fn serialize_struct_variant(\r
+        self,\r
+        _name: &'static str,\r
+        variant_index: u32,\r
+        _variant: &'static str,\r
+        _len: usize,\r
+    ) -> Result<Self::SerializeStructVariant> {\r
+        self.add_discriminant(variant_index)?;\r
+        Ok(SizeCompound { ser: self })\r
+    }\r
+\r
+    fn serialize_newtype_struct<V: serde::Serialize + ?Sized>(\r
+        self,\r
+        _name: &'static str,\r
+        v: &V,\r
+    ) -> Result<()> {\r
+        v.serialize(self)\r
+    }\r
+\r
+    fn serialize_unit_variant(\r
+        self,\r
+        _name: &'static str,\r
+        variant_index: u32,\r
+        _variant: &'static str,\r
+    ) -> Result<()> {\r
+        self.add_discriminant(variant_index)\r
+    }\r
+\r
+    fn serialize_newtype_variant<V: serde::Serialize + ?Sized>(\r
+        self,\r
+        _name: &'static str,\r
+        variant_index: u32,\r
+        _variant: &'static str,\r
+        value: &V,\r
+    ) -> Result<()> {\r
+        self.add_discriminant(variant_index)?;\r
+        value.serialize(self)\r
+    }\r
+\r
+    fn is_human_readable(&self) -> bool {\r
+        false\r
+    }\r
+}\r
+\r
+pub struct Compound<'a, W: 'a, O: Options + 'a> {\r
+    ser: &'a mut Serializer<W, O>,\r
+}\r
+\r
+impl<'a, W, O> serde::ser::SerializeSeq for Compound<'a, W, O>\r
+where\r
+    W: Write,\r
+    O: Options,\r
+{\r
+    type Ok = ();\r
+    type Error = Error;\r
+\r
+    #[inline]\r
+    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>\r
+    where\r
+        T: serde::ser::Serialize,\r
+    {\r
+        value.serialize(&mut *self.ser)\r
+    }\r
+\r
+    #[inline]\r
+    fn end(self) -> Result<()> {\r
+        Ok(())\r
+    }\r
+}\r
+\r
+impl<'a, W, O> serde::ser::SerializeTuple for Compound<'a, W, O>\r
+where\r
+    W: Write,\r
+    O: Options,\r
+{\r
+    type Ok = ();\r
+    type Error = Error;\r
+\r
+    #[inline]\r
+    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>\r
+    where\r
+        T: serde::ser::Serialize,\r
+    {\r
+        value.serialize(&mut *self.ser)\r
+    }\r
+\r
+    #[inline]\r
+    fn end(self) -> Result<()> {\r
+        Ok(())\r
+    }\r
+}\r
+\r
+impl<'a, W, O> serde::ser::SerializeTupleStruct for Compound<'a, W, O>\r
+where\r
+    W: Write,\r
+    O: Options,\r
+{\r
+    type Ok = ();\r
+    type Error = Error;\r
+\r
+    #[inline]\r
+    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>\r
+    where\r
+        T: serde::ser::Serialize,\r
+    {\r
+        value.serialize(&mut *self.ser)\r
+    }\r
+\r
+    #[inline]\r
+    fn end(self) -> Result<()> {\r
+        Ok(())\r
+    }\r
+}\r
+\r
+impl<'a, W, O> serde::ser::SerializeTupleVariant for Compound<'a, W, O>\r
+where\r
+    W: Write,\r
+    O: Options,\r
+{\r
+    type Ok = ();\r
+    type Error = Error;\r
+\r
+    #[inline]\r
+    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>\r
+    where\r
+        T: serde::ser::Serialize,\r
+    {\r
+        value.serialize(&mut *self.ser)\r
+    }\r
+\r
+    #[inline]\r
+    fn end(self) -> Result<()> {\r
+        Ok(())\r
+    }\r
+}\r
+\r
+impl<'a, W, O> serde::ser::SerializeMap for Compound<'a, W, O>\r
+where\r
+    W: Write,\r
+    O: Options,\r
+{\r
+    type Ok = ();\r
+    type Error = Error;\r
+\r
+    #[inline]\r
+    fn serialize_key<K: ?Sized>(&mut self, value: &K) -> Result<()>\r
+    where\r
+        K: serde::ser::Serialize,\r
+    {\r
+        value.serialize(&mut *self.ser)\r
+    }\r
+\r
+    #[inline]\r
+    fn serialize_value<V: ?Sized>(&mut self, value: &V) -> Result<()>\r
+    where\r
+        V: serde::ser::Serialize,\r
+    {\r
+        value.serialize(&mut *self.ser)\r
+    }\r
+\r
+    #[inline]\r
+    fn end(self) -> Result<()> {\r
+        Ok(())\r
+    }\r
+}\r
+\r
+impl<'a, W, O> serde::ser::SerializeStruct for Compound<'a, W, O>\r
+where\r
+    W: Write,\r
+    O: Options,\r
+{\r
+    type Ok = ();\r
+    type Error = Error;\r
+\r
+    #[inline]\r
+    fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>\r
+    where\r
+        T: serde::ser::Serialize,\r
+    {\r
+        value.serialize(&mut *self.ser)\r
+    }\r
+\r
+    #[inline]\r
+    fn end(self) -> Result<()> {\r
+        Ok(())\r
+    }\r
+}\r
+\r
+impl<'a, W, O> serde::ser::SerializeStructVariant for Compound<'a, W, O>\r
+where\r
+    W: Write,\r
+    O: Options,\r
+{\r
+    type Ok = ();\r
+    type Error = Error;\r
+\r
+    #[inline]\r
+    fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>\r
+    where\r
+        T: serde::ser::Serialize,\r
+    {\r
+        value.serialize(&mut *self.ser)\r
+    }\r
+\r
+    #[inline]\r
+    fn end(self) -> Result<()> {\r
+        Ok(())\r
+    }\r
+}\r
+\r
+pub(crate) struct SizeCompound<'a, S: Options + 'a> {\r
+    ser: &'a mut SizeChecker<S>,\r
+}\r
+\r
+impl<'a, O: Options> serde::ser::SerializeSeq for SizeCompound<'a, O> {\r
+    type Ok = ();\r
+    type Error = Error;\r
+\r
+    #[inline]\r
+    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>\r
+    where\r
+        T: serde::ser::Serialize,\r
+    {\r
+        value.serialize(&mut *self.ser)\r
+    }\r
+\r
+    #[inline]\r
+    fn end(self) -> Result<()> {\r
+        Ok(())\r
+    }\r
+}\r
+\r
+impl<'a, O: Options> serde::ser::SerializeTuple for SizeCompound<'a, O> {\r
+    type Ok = ();\r
+    type Error = Error;\r
+\r
+    #[inline]\r
+    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>\r
+    where\r
+        T: serde::ser::Serialize,\r
+    {\r
+        value.serialize(&mut *self.ser)\r
+    }\r
+\r
+    #[inline]\r
+    fn end(self) -> Result<()> {\r
+        Ok(())\r
+    }\r
+}\r
+\r
+impl<'a, O: Options> serde::ser::SerializeTupleStruct for SizeCompound<'a, O> {\r
+    type Ok = ();\r
+    type Error = Error;\r
+\r
+    #[inline]\r
+    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>\r
+    where\r
+        T: serde::ser::Serialize,\r
+    {\r
+        value.serialize(&mut *self.ser)\r
+    }\r
+\r
+    #[inline]\r
+    fn end(self) -> Result<()> {\r
+        Ok(())\r
+    }\r
+}\r
+\r
+impl<'a, O: Options> serde::ser::SerializeTupleVariant for SizeCompound<'a, O> {\r
+    type Ok = ();\r
+    type Error = Error;\r
+\r
+    #[inline]\r
+    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>\r
+    where\r
+        T: serde::ser::Serialize,\r
+    {\r
+        value.serialize(&mut *self.ser)\r
+    }\r
+\r
+    #[inline]\r
+    fn end(self) -> Result<()> {\r
+        Ok(())\r
+    }\r
+}\r
+\r
+impl<'a, O: Options + 'a> serde::ser::SerializeMap for SizeCompound<'a, O> {\r
+    type Ok = ();\r
+    type Error = Error;\r
+\r
+    #[inline]\r
+    fn serialize_key<K: ?Sized>(&mut self, value: &K) -> Result<()>\r
+    where\r
+        K: serde::ser::Serialize,\r
+    {\r
+        value.serialize(&mut *self.ser)\r
+    }\r
+\r
+    #[inline]\r
+    fn serialize_value<V: ?Sized>(&mut self, value: &V) -> Result<()>\r
+    where\r
+        V: serde::ser::Serialize,\r
+    {\r
+        value.serialize(&mut *self.ser)\r
+    }\r
+\r
+    #[inline]\r
+    fn end(self) -> Result<()> {\r
+        Ok(())\r
+    }\r
+}\r
+\r
+impl<'a, O: Options> serde::ser::SerializeStruct for SizeCompound<'a, O> {\r
+    type Ok = ();\r
+    type Error = Error;\r
+\r
+    #[inline]\r
+    fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>\r
+    where\r
+        T: serde::ser::Serialize,\r
+    {\r
+        value.serialize(&mut *self.ser)\r
+    }\r
+\r
+    #[inline]\r
+    fn end(self) -> Result<()> {\r
+        Ok(())\r
+    }\r
+}\r
+\r
+impl<'a, O: Options> serde::ser::SerializeStructVariant for SizeCompound<'a, O> {\r
+    type Ok = ();\r
+    type Error = Error;\r
+\r
+    #[inline]\r
+    fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>\r
+    where\r
+        T: serde::ser::Serialize,\r
+    {\r
+        value.serialize(&mut *self.ser)\r
+    }\r
+\r
+    #[inline]\r
+    fn end(self) -> Result<()> {\r
+        Ok(())\r
+    }\r
+}\r
+const TAG_CONT: u8 = 0b1000_0000;\r
+const TAG_TWO_B: u8 = 0b1100_0000;\r
+const TAG_THREE_B: u8 = 0b1110_0000;\r
+const TAG_FOUR_B: u8 = 0b1111_0000;\r
+const MAX_ONE_B: u32 = 0x80;\r
+const MAX_TWO_B: u32 = 0x800;\r
+const MAX_THREE_B: u32 = 0x10000;\r
+\r
+fn encode_utf8(c: char) -> EncodeUtf8 {\r
+    let code = c as u32;\r
+    let mut buf = [0; 4];\r
+    let pos = if code < MAX_ONE_B {\r
+        buf[3] = code as u8;\r
+        3\r
+    } else if code < MAX_TWO_B {\r
+        buf[2] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;\r
+        buf[3] = (code & 0x3F) as u8 | TAG_CONT;\r
+        2\r
+    } else if code < MAX_THREE_B {\r
+        buf[1] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;\r
+        buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;\r
+        buf[3] = (code & 0x3F) as u8 | TAG_CONT;\r
+        1\r
+    } else {\r
+        buf[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;\r
+        buf[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT;\r
+        buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;\r
+        buf[3] = (code & 0x3F) as u8 | TAG_CONT;\r
+        0\r
+    };\r
+    EncodeUtf8 { buf, pos }\r
+}\r
+\r
+struct EncodeUtf8 {\r
+    buf: [u8; 4],\r
+    pos: usize,\r
+}\r
+\r
+impl EncodeUtf8 {\r
+    fn as_slice(&self) -> &[u8] {\r
+        &self.buf[self.pos..]\r
+    }\r
+}\r
diff --git a/tests/test.rs b/tests/test.rs
new file mode 100644 (file)
index 0000000..23d65f4
--- /dev/null
@@ -0,0 +1,899 @@
+#[macro_use]\r
+extern crate serde_derive;\r
+\r
+extern crate bincode;\r
+#[macro_use]\r
+extern crate serde;\r
+extern crate serde_bytes;\r
+\r
+use std::borrow::Cow;\r
+use std::collections::HashMap;\r
+use std::fmt::{self, Debug};\r
+use std::result::Result as StdResult;\r
+\r
+use bincode::{\r
+    deserialize, deserialize_from, deserialize_in_place, serialize, serialized_size,\r
+    DefaultOptions, ErrorKind, Options, Result,\r
+};\r
+use serde::de::{Deserialize, DeserializeSeed, Deserializer, SeqAccess, Visitor};\r
+\r
+const LEN_SIZE: u64 = 8;\r
+\r
+fn the_same_impl<V, O>(element: V, options: &mut O)\r
+where\r
+    V: serde::Serialize + serde::de::DeserializeOwned + PartialEq + Debug + 'static,\r
+    O: Options,\r
+{\r
+    let size = options.serialized_size(&element).unwrap();\r
+\r
+    {\r
+        let encoded = options.serialize(&element).unwrap();\r
+        let decoded: V = options.deserialize(&encoded[..]).unwrap();\r
+        let decoded_reader = options.deserialize_from(&mut &encoded[..]).unwrap();\r
+\r
+        assert_eq!(element, decoded);\r
+        assert_eq!(element, decoded_reader);\r
+        assert_eq!(size, encoded.len() as u64);\r
+    }\r
+}\r
+\r
+fn the_same<V>(element: V)\r
+where\r
+    V: serde::Serialize + serde::de::DeserializeOwned + PartialEq + Debug + Clone + 'static,\r
+{\r
+    // add a new macro which calls the previous when you add a new option set\r
+    macro_rules! all_endians {\r
+        ($element:expr, $options:expr) => {\r
+            the_same_impl($element.clone(), &mut $options.with_native_endian());\r
+            the_same_impl($element.clone(), &mut $options.with_big_endian());\r
+            the_same_impl($element.clone(), &mut $options.with_little_endian());\r
+        };\r
+    }\r
+\r
+    macro_rules! all_integer_encodings {\r
+        ($element:expr, $options:expr) => {\r
+            all_endians!($element, $options.with_fixint_encoding());\r
+            all_endians!($element, $options.with_varint_encoding());\r
+        };\r
+    }\r
+\r
+    all_integer_encodings!(element, DefaultOptions::new());\r
+}\r
+\r
+#[test]\r
+fn test_numbers() {\r
+    // unsigned positive\r
+    the_same(5u8);\r
+    the_same(5u16);\r
+    the_same(5u32);\r
+    the_same(5u64);\r
+    the_same(5usize);\r
+    // signed positive\r
+    the_same(5i8);\r
+    the_same(5i16);\r
+    the_same(5i32);\r
+    the_same(5i64);\r
+    the_same(5isize);\r
+    // signed negative\r
+    the_same(-5i8);\r
+    the_same(-5i16);\r
+    the_same(-5i32);\r
+    the_same(-5i64);\r
+    the_same(-5isize);\r
+    // floating\r
+    the_same(-100f32);\r
+    the_same(0f32);\r
+    the_same(5f32);\r
+    the_same(-100f64);\r
+    the_same(5f64);\r
+}\r
+\r
+serde_if_integer128! {\r
+    #[test]\r
+    fn test_numbers_128bit() {\r
+        // unsigned positive\r
+        the_same(5u128);\r
+        the_same(u128::max_value());\r
+        // signed positive\r
+        the_same(5i128);\r
+        the_same(i128::max_value());\r
+        // signed negative\r
+        the_same(-5i128);\r
+        the_same(i128::min_value());\r
+    }\r
+}\r
+\r
+#[test]\r
+fn test_string() {\r
+    the_same("".to_string());\r
+    the_same("a".to_string());\r
+}\r
+\r
+#[test]\r
+fn test_tuple() {\r
+    the_same((1isize,));\r
+    the_same((1isize, 2isize, 3isize));\r
+    the_same((1isize, "foo".to_string(), ()));\r
+}\r
+\r
+#[test]\r
+fn test_basic_struct() {\r
+    #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]\r
+    struct Easy {\r
+        x: isize,\r
+        s: String,\r
+        y: usize,\r
+    }\r
+    the_same(Easy {\r
+        x: -4,\r
+        s: "foo".to_string(),\r
+        y: 10,\r
+    });\r
+}\r
+\r
+#[test]\r
+fn test_nested_struct() {\r
+    #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]\r
+    struct Easy {\r
+        x: isize,\r
+        s: String,\r
+        y: usize,\r
+    }\r
+    #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]\r
+    struct Nest {\r
+        f: Easy,\r
+        b: usize,\r
+        s: Easy,\r
+    }\r
+\r
+    the_same(Nest {\r
+        f: Easy {\r
+            x: -1,\r
+            s: "foo".to_string(),\r
+            y: 20,\r
+        },\r
+        b: 100,\r
+        s: Easy {\r
+            x: -100,\r
+            s: "bar".to_string(),\r
+            y: 20,\r
+        },\r
+    });\r
+}\r
+\r
+#[test]\r
+fn test_struct_newtype() {\r
+    #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]\r
+    struct NewtypeStr(usize);\r
+\r
+    the_same(NewtypeStr(5));\r
+}\r
+\r
+#[test]\r
+fn test_struct_tuple() {\r
+    #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]\r
+    struct TubStr(usize, String, f32);\r
+\r
+    the_same(TubStr(5, "hello".to_string(), 3.2));\r
+}\r
+\r
+#[test]\r
+fn test_option() {\r
+    the_same(Some(5usize));\r
+    the_same(Some("foo bar".to_string()));\r
+    the_same(None::<usize>);\r
+}\r
+\r
+#[test]\r
+fn test_enum() {\r
+    #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]\r
+    enum TestEnum {\r
+        NoArg,\r
+        OneArg(usize),\r
+        Args(usize, usize),\r
+        AnotherNoArg,\r
+        StructLike { x: usize, y: f32 },\r
+    }\r
+    the_same(TestEnum::NoArg);\r
+    the_same(TestEnum::OneArg(4));\r
+    //the_same(TestEnum::Args(4, 5));\r
+    the_same(TestEnum::AnotherNoArg);\r
+    the_same(TestEnum::StructLike { x: 4, y: 3.14159 });\r
+    the_same(vec![\r
+        TestEnum::NoArg,\r
+        TestEnum::OneArg(5),\r
+        TestEnum::AnotherNoArg,\r
+        TestEnum::StructLike { x: 4, y: 1.4 },\r
+    ]);\r
+}\r
+\r
+#[test]\r
+fn test_vec() {\r
+    let v: Vec<u8> = vec![];\r
+    the_same(v);\r
+    the_same(vec![1u64]);\r
+    the_same(vec![1u64, 2, 3, 4, 5, 6]);\r
+}\r
+\r
+#[test]\r
+fn test_map() {\r
+    let mut m = HashMap::new();\r
+    m.insert(4u64, "foo".to_string());\r
+    m.insert(0u64, "bar".to_string());\r
+    the_same(m);\r
+}\r
+\r
+#[test]\r
+fn test_bool() {\r
+    the_same(true);\r
+    the_same(false);\r
+}\r
+\r
+#[test]\r
+fn test_unicode() {\r
+    the_same("Ã¥".to_string());\r
+    the_same("aåååååååa".to_string());\r
+}\r
+\r
+#[test]\r
+fn test_fixed_size_array() {\r
+    the_same([24u32; 32]);\r
+    the_same([1u64, 2, 3, 4, 5, 6, 7, 8]);\r
+    the_same([0u8; 19]);\r
+}\r
+\r
+#[test]\r
+fn deserializing_errors() {\r
+    match *deserialize::<bool>(&vec![0xA][..]).unwrap_err() {\r
+        ErrorKind::InvalidBoolEncoding(0xA) => {}\r
+        _ => panic!(),\r
+    }\r
+\r
+    let invalid_str = vec![1, 0, 0, 0, 0, 0, 0, 0, 0xFF];\r
+\r
+    match *deserialize::<String>(&invalid_str[..]).unwrap_err() {\r
+        ErrorKind::InvalidUtf8Encoding(_) => {}\r
+        _ => panic!(),\r
+    }\r
+\r
+    // Out-of-bounds variant\r
+    #[derive(Serialize, Deserialize, Debug)]\r
+    enum Test {\r
+        One,\r
+        Two,\r
+    };\r
+\r
+    let invalid_enum = vec![0, 0, 0, 5];\r
+\r
+    match *deserialize::<Test>(&invalid_enum[..]).unwrap_err() {\r
+        // Error message comes from serde\r
+        ErrorKind::Custom(_) => {}\r
+        _ => panic!(),\r
+    }\r
+    match *deserialize::<Option<u8>>(&vec![5, 0][..]).unwrap_err() {\r
+        ErrorKind::InvalidTagEncoding(_) => {}\r
+        _ => panic!(),\r
+    }\r
+}\r
+\r
+#[test]\r
+fn trailing_bytes() {\r
+    match DefaultOptions::new()\r
+        .deserialize::<char>(b"1x")\r
+        .map_err(|e| *e)\r
+    {\r
+        Err(ErrorKind::Custom(_)) => {}\r
+        other => panic!("Expecting TrailingBytes, got {:?}", other),\r
+    }\r
+}\r
+\r
+#[test]\r
+fn too_big_deserialize() {\r
+    let serialized = vec![0, 0, 0, 3];\r
+    let deserialized: Result<u32> = DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .with_limit(3)\r
+        .deserialize_from(&mut &serialized[..]);\r
+    assert!(deserialized.is_err());\r
+\r
+    let serialized = vec![0, 0, 0, 3];\r
+    let deserialized: Result<u32> = DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .with_limit(4)\r
+        .deserialize_from(&mut &serialized[..]);\r
+    assert!(deserialized.is_ok());\r
+}\r
+\r
+#[test]\r
+fn char_serialization() {\r
+    let chars = "Aa\0☺♪";\r
+    for c in chars.chars() {\r
+        let encoded = DefaultOptions::new()\r
+            .with_limit(4)\r
+            .serialize(&c)\r
+            .expect("serializing char failed");\r
+        let decoded: char = deserialize(&encoded).expect("deserializing failed");\r
+        assert_eq!(decoded, c);\r
+    }\r
+}\r
+\r
+#[test]\r
+fn too_big_char_deserialize() {\r
+    let serialized = vec![0x41];\r
+    let deserialized: Result<char> = DefaultOptions::new()\r
+        .with_limit(1)\r
+        .deserialize_from(&mut &serialized[..]);\r
+    assert!(deserialized.is_ok());\r
+    assert_eq!(deserialized.unwrap(), 'A');\r
+}\r
+\r
+#[test]\r
+fn too_big_serialize() {\r
+    assert!(DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .with_limit(3)\r
+        .serialize(&0u32)\r
+        .is_err());\r
+    assert!(DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .with_limit(4)\r
+        .serialize(&0u32)\r
+        .is_ok());\r
+\r
+    assert!(DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .with_limit(LEN_SIZE + 4)\r
+        .serialize(&"abcde")\r
+        .is_err());\r
+    assert!(DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .with_limit(LEN_SIZE + 5)\r
+        .serialize(&"abcde")\r
+        .is_ok());\r
+}\r
+\r
+#[test]\r
+fn test_serialized_size() {\r
+    assert!(serialized_size(&0u8).unwrap() == 1);\r
+    assert!(serialized_size(&0u16).unwrap() == 2);\r
+    assert!(serialized_size(&0u32).unwrap() == 4);\r
+    assert!(serialized_size(&0u64).unwrap() == 8);\r
+\r
+    // length isize stored as u64\r
+    assert!(serialized_size(&"").unwrap() == LEN_SIZE);\r
+    assert!(serialized_size(&"a").unwrap() == LEN_SIZE + 1);\r
+\r
+    assert!(serialized_size(&vec![0u32, 1u32, 2u32]).unwrap() == LEN_SIZE + 3 * (4));\r
+}\r
+\r
+#[test]\r
+fn test_serialized_size_bounded() {\r
+    // JUST RIGHT\r
+    assert!(\r
+        DefaultOptions::new()\r
+            .with_fixint_encoding()\r
+            .with_limit(1)\r
+            .serialized_size(&0u8)\r
+            .unwrap()\r
+            == 1\r
+    );\r
+    assert!(\r
+        DefaultOptions::new()\r
+            .with_fixint_encoding()\r
+            .with_limit(2)\r
+            .serialized_size(&0u16)\r
+            .unwrap()\r
+            == 2\r
+    );\r
+    assert!(\r
+        DefaultOptions::new()\r
+            .with_fixint_encoding()\r
+            .with_limit(4)\r
+            .serialized_size(&0u32)\r
+            .unwrap()\r
+            == 4\r
+    );\r
+    assert!(\r
+        DefaultOptions::new()\r
+            .with_fixint_encoding()\r
+            .with_limit(8)\r
+            .serialized_size(&0u64)\r
+            .unwrap()\r
+            == 8\r
+    );\r
+    assert!(\r
+        DefaultOptions::new()\r
+            .with_fixint_encoding()\r
+            .with_limit(8)\r
+            .serialized_size(&"")\r
+            .unwrap()\r
+            == LEN_SIZE\r
+    );\r
+    assert!(\r
+        DefaultOptions::new()\r
+            .with_fixint_encoding()\r
+            .with_limit(8 + 1)\r
+            .serialized_size(&"a")\r
+            .unwrap()\r
+            == LEN_SIZE + 1\r
+    );\r
+    assert!(\r
+        DefaultOptions::new()\r
+            .with_fixint_encoding()\r
+            .with_limit(LEN_SIZE + 3 * 4)\r
+            .serialized_size(&vec![0u32, 1u32, 2u32])\r
+            .unwrap()\r
+            == LEN_SIZE + 3 * 4\r
+    );\r
+    // Below\r
+    assert!(DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .with_limit(0)\r
+        .serialized_size(&0u8)\r
+        .is_err());\r
+    assert!(DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .with_limit(1)\r
+        .serialized_size(&0u16)\r
+        .is_err());\r
+    assert!(DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .with_limit(3)\r
+        .serialized_size(&0u32)\r
+        .is_err());\r
+    assert!(DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .with_limit(7)\r
+        .serialized_size(&0u64)\r
+        .is_err());\r
+    assert!(DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .with_limit(7)\r
+        .serialized_size(&"")\r
+        .is_err());\r
+    assert!(DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .with_limit(8 + 0)\r
+        .serialized_size(&"a")\r
+        .is_err());\r
+    assert!(DefaultOptions::new()\r
+        .with_fixint_encoding()\r
+        .with_limit(8 + 3 * 4 - 1)\r
+        .serialized_size(&vec![0u32, 1u32, 2u32])\r
+        .is_err());\r
+}\r
+\r
+#[test]\r
+fn encode_box() {\r
+    the_same(Box::new(5));\r
+}\r
+\r
+#[test]\r
+fn test_cow_serialize() {\r
+    let large_object = vec![1u32, 2, 3, 4, 5, 6];\r
+    let mut large_map = HashMap::new();\r
+    large_map.insert(1, 2);\r
+\r
+    #[derive(Serialize, Deserialize, Debug)]\r
+    enum Message<'a> {\r
+        M1(Cow<'a, Vec<u32>>),\r
+        M2(Cow<'a, HashMap<u32, u32>>),\r
+    }\r
+\r
+    // Test 1\r
+    {\r
+        let serialized = serialize(&Message::M1(Cow::Borrowed(&large_object))).unwrap();\r
+        let deserialized: Message<'static> = deserialize_from(&mut &serialized[..]).unwrap();\r
+\r
+        match deserialized {\r
+            Message::M1(b) => assert!(&b.into_owned() == &large_object),\r
+            _ => assert!(false),\r
+        }\r
+    }\r
+\r
+    // Test 2\r
+    {\r
+        let serialized = serialize(&Message::M2(Cow::Borrowed(&large_map))).unwrap();\r
+        let deserialized: Message<'static> = deserialize_from(&mut &serialized[..]).unwrap();\r
+\r
+        match deserialized {\r
+            Message::M2(b) => assert!(&b.into_owned() == &large_map),\r
+            _ => assert!(false),\r
+        }\r
+    }\r
+}\r
+\r
+#[test]\r
+fn test_strbox_serialize() {\r
+    let strx: &'static str = "hello world";\r
+    let serialized = serialize(&Cow::Borrowed(strx)).unwrap();\r
+    let deserialized: Cow<'static, String> = deserialize_from(&mut &serialized[..]).unwrap();\r
+    let stringx: String = deserialized.into_owned();\r
+    assert!(strx == &stringx[..]);\r
+}\r
+\r
+#[test]\r
+fn test_slicebox_serialize() {\r
+    let slice = [1u32, 2, 3, 4, 5];\r
+    let serialized = serialize(&Cow::Borrowed(&slice[..])).unwrap();\r
+    println!("{:?}", serialized);\r
+    let deserialized: Cow<'static, Vec<u32>> = deserialize_from(&mut &serialized[..]).unwrap();\r
+    {\r
+        let sb: &[u32] = &deserialized;\r
+        assert!(slice == sb);\r
+    }\r
+    let vecx: Vec<u32> = deserialized.into_owned();\r
+    assert!(slice == &vecx[..]);\r
+}\r
+\r
+#[test]\r
+fn test_multi_strings_serialize() {\r
+    assert!(serialize(&("foo", "bar", "baz")).is_ok());\r
+}\r
+\r
+#[test]\r
+fn test_oom_protection() {\r
+    use std::io::Cursor;\r
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]\r
+    struct FakeVec {\r
+        len: u64,\r
+        byte: u8,\r
+    }\r
+    let x = DefaultOptions::new()\r
+        .with_limit(10)\r
+        .serialize(&FakeVec {\r
+            len: 0xffffffffffffffffu64,\r
+            byte: 1,\r
+        })\r
+        .unwrap();\r
+    let y: Result<Vec<u8>> = DefaultOptions::new()\r
+        .with_limit(10)\r
+        .deserialize_from(&mut Cursor::new(&x[..]));\r
+    assert!(y.is_err());\r
+}\r
+\r
+#[test]\r
+fn path_buf() {\r
+    use std::path::{Path, PathBuf};\r
+    let path = Path::new("foo").to_path_buf();\r
+    let serde_encoded = serialize(&path).unwrap();\r
+    let decoded: PathBuf = deserialize(&serde_encoded).unwrap();\r
+    assert!(path.to_str() == decoded.to_str());\r
+}\r
+\r
+#[test]\r
+fn bytes() {\r
+    use serde_bytes::Bytes;\r
+\r
+    let data = b"abc\0123";\r
+    let s = serialize(&data[..]).unwrap();\r
+    let s2 = serialize(&Bytes::new(data)).unwrap();\r
+    assert_eq!(s[..], s2[..]);\r
+}\r
+\r
+#[test]\r
+fn serde_bytes() {\r
+    use serde_bytes::ByteBuf;\r
+    the_same(ByteBuf::from(vec![1, 2, 3, 4, 5]));\r
+}\r
+\r
+#[test]\r
+fn endian_difference() {\r
+    let x = 10u64;\r
+    let little = serialize(&x).unwrap();\r
+    let big = DefaultOptions::new()\r
+        .with_big_endian()\r
+        .serialize(&x)\r
+        .unwrap();\r
+    assert_ne!(little, big);\r
+}\r
+\r
+#[test]\r
+fn test_zero_copy_parse() {\r
+    #[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]\r
+    struct Foo<'a> {\r
+        borrowed_str: &'a str,\r
+        borrowed_bytes: &'a [u8],\r
+    }\r
+\r
+    let f = Foo {\r
+        borrowed_str: "hi",\r
+        borrowed_bytes: &[0, 1, 2, 3],\r
+    };\r
+    {\r
+        let encoded = serialize(&f).unwrap();\r
+        let out: Foo = deserialize(&encoded[..]).unwrap();\r
+        assert_eq!(out, f);\r
+    }\r
+}\r
+\r
+#[test]\r
+fn test_zero_copy_parse_deserialize_into() {\r
+    use bincode::BincodeRead;\r
+    use std::io;\r
+\r
+    /// A BincodeRead implementation for byte slices\r
+    pub struct SliceReader<'storage> {\r
+        slice: &'storage [u8],\r
+    }\r
+\r
+    impl<'storage> SliceReader<'storage> {\r
+        #[inline(always)]\r
+        fn unexpected_eof() -> Box<::ErrorKind> {\r
+            return Box::new(::ErrorKind::Io(io::Error::new(\r
+                io::ErrorKind::UnexpectedEof,\r
+                "",\r
+            )));\r
+        }\r
+    }\r
+\r
+    impl<'storage> io::Read for SliceReader<'storage> {\r
+        #[inline(always)]\r
+        fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {\r
+            (&mut self.slice).read(out)\r
+        }\r
+        #[inline(always)]\r
+        fn read_exact(&mut self, out: &mut [u8]) -> io::Result<()> {\r
+            (&mut self.slice).read_exact(out)\r
+        }\r
+    }\r
+\r
+    impl<'storage> BincodeRead<'storage> for SliceReader<'storage> {\r
+        #[inline(always)]\r
+        fn forward_read_str<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>\r
+        where\r
+            V: serde::de::Visitor<'storage>,\r
+        {\r
+            use ErrorKind;\r
+            if length > self.slice.len() {\r
+                return Err(SliceReader::unexpected_eof());\r
+            }\r
+\r
+            let string = match ::std::str::from_utf8(&self.slice[..length]) {\r
+                Ok(s) => s,\r
+                Err(e) => return Err(ErrorKind::InvalidUtf8Encoding(e).into()),\r
+            };\r
+            let r = visitor.visit_borrowed_str(string);\r
+            self.slice = &self.slice[length..];\r
+            r\r
+        }\r
+\r
+        #[inline(always)]\r
+        fn get_byte_buffer(&mut self, length: usize) -> Result<Vec<u8>> {\r
+            if length > self.slice.len() {\r
+                return Err(SliceReader::unexpected_eof());\r
+            }\r
+\r
+            let r = &self.slice[..length];\r
+            self.slice = &self.slice[length..];\r
+            Ok(r.to_vec())\r
+        }\r
+\r
+        #[inline(always)]\r
+        fn forward_read_bytes<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>\r
+        where\r
+            V: serde::de::Visitor<'storage>,\r
+        {\r
+            if length > self.slice.len() {\r
+                return Err(SliceReader::unexpected_eof());\r
+            }\r
+\r
+            let r = visitor.visit_borrowed_bytes(&self.slice[..length]);\r
+            self.slice = &self.slice[length..];\r
+            r\r
+        }\r
+    }\r
+\r
+    #[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]\r
+    struct Foo<'a> {\r
+        borrowed_str: &'a str,\r
+        borrowed_bytes: &'a [u8],\r
+    }\r
+\r
+    let f = Foo {\r
+        borrowed_str: "hi",\r
+        borrowed_bytes: &[0, 1, 2, 3],\r
+    };\r
+\r
+    {\r
+        let encoded = serialize(&f).unwrap();\r
+        let mut target = Foo {\r
+            borrowed_str: "hello",\r
+            borrowed_bytes: &[10, 11, 12, 13],\r
+        };\r
+        deserialize_in_place(\r
+            SliceReader {\r
+                slice: &encoded[..],\r
+            },\r
+            &mut target,\r
+        )\r
+        .unwrap();\r
+        assert_eq!(target, f);\r
+    }\r
+}\r
+\r
+#[test]\r
+fn not_human_readable() {\r
+    use std::net::Ipv4Addr;\r
+    let ip = Ipv4Addr::new(1, 2, 3, 4);\r
+    the_same(ip);\r
+    assert_eq!(&ip.octets()[..], &serialize(&ip).unwrap()[..]);\r
+    assert_eq!(\r
+        ::std::mem::size_of::<Ipv4Addr>() as u64,\r
+        serialized_size(&ip).unwrap()\r
+    );\r
+}\r
+\r
+// The example is taken from serde::de::DeserializeSeed.\r
+struct ExtendVec<'a, T: 'a>(&'a mut Vec<T>);\r
+\r
+impl<'de, 'a, T> DeserializeSeed<'de> for ExtendVec<'a, T>\r
+where\r
+    T: Deserialize<'de>,\r
+{\r
+    // The return type of the `deserialize` method. This implementation\r
+    // appends onto an existing vector but does not create any new data\r
+    // structure, so the return type is ().\r
+    type Value = ();\r
+\r
+    fn deserialize<D>(self, deserializer: D) -> StdResult<Self::Value, D::Error>\r
+    where\r
+        D: Deserializer<'de>,\r
+    {\r
+        // Visitor implementation that will walk an inner array of the JSON\r
+        // input.\r
+        struct ExtendVecVisitor<'a, T: 'a>(&'a mut Vec<T>);\r
+\r
+        impl<'de, 'a, T> Visitor<'de> for ExtendVecVisitor<'a, T>\r
+        where\r
+            T: Deserialize<'de>,\r
+        {\r
+            type Value = ();\r
+\r
+            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\r
+                write!(formatter, "an array of integers")\r
+            }\r
+\r
+            fn visit_seq<A>(self, mut seq: A) -> StdResult<(), A::Error>\r
+            where\r
+                A: SeqAccess<'de>,\r
+            {\r
+                // Visit each element in the inner array and push it onto\r
+                // the existing vector.\r
+                while let Some(elem) = seq.next_element()? {\r
+                    self.0.push(elem);\r
+                }\r
+                Ok(())\r
+            }\r
+        }\r
+\r
+        deserializer.deserialize_seq(ExtendVecVisitor(self.0))\r
+    }\r
+}\r
+\r
+#[test]\r
+fn test_default_deserialize_seed() {\r
+    let config = DefaultOptions::new();\r
+\r
+    let data: Vec<_> = (10..100).collect();\r
+    let bytes = config.serialize(&data).expect("Config::serialize failed");\r
+\r
+    let mut seed_data: Vec<_> = (0..10).collect();\r
+    {\r
+        let seed = ExtendVec(&mut seed_data);\r
+        config\r
+            .deserialize_seed(seed, &bytes)\r
+            .expect("Config::deserialize_seed failed");\r
+    }\r
+\r
+    assert_eq!(seed_data, (0..100).collect::<Vec<_>>());\r
+}\r
+\r
+#[test]\r
+fn test_big_endian_deserialize_seed() {\r
+    let config = DefaultOptions::new().with_big_endian();\r
+\r
+    let data: Vec<_> = (10..100).collect();\r
+    let bytes = config.serialize(&data).expect("Config::serialize failed");\r
+\r
+    let mut seed_data: Vec<_> = (0..10).collect();\r
+    {\r
+        let seed = ExtendVec(&mut seed_data);\r
+        config\r
+            .deserialize_seed(seed, &bytes)\r
+            .expect("Config::deserialize_seed failed");\r
+    }\r
+\r
+    assert_eq!(seed_data, (0..100).collect::<Vec<_>>());\r
+}\r
+\r
+#[test]\r
+fn test_default_deserialize_from_seed() {\r
+    let config = DefaultOptions::new();\r
+\r
+    let data: Vec<_> = (10..100).collect();\r
+    let bytes = config.serialize(&data).expect("Config::serialize failed");\r
+\r
+    let mut seed_data: Vec<_> = (0..10).collect();\r
+    {\r
+        let seed = ExtendVec(&mut seed_data);\r
+        config\r
+            .deserialize_from_seed(seed, &mut &*bytes)\r
+            .expect("Config::deserialize_from_seed failed");\r
+    }\r
+\r
+    assert_eq!(seed_data, (0..100).collect::<Vec<_>>());\r
+}\r
+\r
+#[test]\r
+fn test_big_endian_deserialize_from_seed() {\r
+    let config = DefaultOptions::new().with_big_endian();\r
+\r
+    let data: Vec<_> = (10..100).collect();\r
+    let bytes = config.serialize(&data).expect("Config::serialize failed");\r
+\r
+    let mut seed_data: Vec<_> = (0..10).collect();\r
+    {\r
+        let seed = ExtendVec(&mut seed_data);\r
+        config\r
+            .deserialize_from_seed(seed, &mut &*bytes)\r
+            .expect("Config::deserialize_from_seed failed");\r
+    }\r
+\r
+    assert_eq!(seed_data, (0..100).collect::<Vec<_>>());\r
+}\r
+\r
+#[test]\r
+fn test_varint_length_prefixes() {\r
+    let a = vec![(); 127]; // should be a single byte\r
+    let b = vec![(); 250]; // also should be a single byte\r
+    let c = vec![(); 251];\r
+    let d = vec![(); u16::max_value() as usize + 1];\r
+\r
+    assert_eq!(\r
+        DefaultOptions::new()\r
+            .with_varint_encoding()\r
+            .serialized_size(&a[..])\r
+            .unwrap(),\r
+        1\r
+    ); // 2 ** 7 - 1\r
+    assert_eq!(\r
+        DefaultOptions::new()\r
+            .with_varint_encoding()\r
+            .serialized_size(&b[..])\r
+            .unwrap(),\r
+        1\r
+    ); // 250\r
+    assert_eq!(\r
+        DefaultOptions::new()\r
+            .with_varint_encoding()\r
+            .serialized_size(&c[..])\r
+            .unwrap(),\r
+        (1 + std::mem::size_of::<u16>()) as u64\r
+    ); // 251\r
+    assert_eq!(\r
+        DefaultOptions::new()\r
+            .with_varint_encoding()\r
+            .serialized_size(&d[..])\r
+            .unwrap(),\r
+        (1 + std::mem::size_of::<u32>()) as u64\r
+    ); // 2 ** 16 + 1\r
+}\r
+\r
+#[test]\r
+fn test_byte_vec_struct() {\r
+    #[derive(PartialEq, Eq, Clone, Serialize, Deserialize, Debug)]\r
+    struct ByteVecs {\r
+        a: Vec<u8>,\r
+        b: Vec<u8>,\r
+        c: Vec<u8>,\r
+    };\r
+\r
+    let byte_struct = ByteVecs {\r
+        a: vec![2; 20],\r
+        b: vec![3; 30],\r
+        c: vec![1; 10],\r
+    };\r
+\r
+    the_same(byte_struct);\r
+}\r