bincode-1.2.1/Cargo.toml.orig010064400017500001750000000021711357363511500142400ustar0000000000000000[package] name = "bincode" version = "1.2.1" # remember to update html_root_url authors = ["Ty Overby ", "Francesco Mazzoli ", "David Tolnay ", "Daniel Griffen"] exclude = ["logo.png", "tests/*", "examples/*", ".gitignore", ".travis.yml"] publish = true repository = "https://github.com/servo/bincode" documentation = "https://docs.rs/bincode" readme = "./readme.md" categories = ["encoding", "network-programming"] keywords = ["binary", "encode", "decode", "serialize", "deserialize"] license = "MIT" description = "A binary serialization / deserialization strategy that uses Serde for transforming structs into bytes and vice versa!" [dependencies] byteorder = "1.3.0" serde = "1.0.63" [dev-dependencies] serde_bytes = "0.11" serde_derive = "1.0.27" [features] # This feature is no longer used and is DEPRECATED. This crate relies on the # serde `serde_if_integer128` macro to enable i128 support for Rust compilers # and targets that support it. The feature will be removed if and when a new # major version is released. i128 = [] [badges] travis-ci = { repository = "servo/bincode" } bincode-1.2.1/Cargo.toml0000644000000026251357363523300105530ustar00# 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.2.1" authors = ["Ty Overby ", "Francesco Mazzoli ", "David Tolnay ", "Daniel Griffen"] exclude = ["logo.png", "tests/*", "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.byteorder] version = "1.3.0" [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" bincode-1.2.1/LICENSE.md010064400017500001750000000020641346021704700127510ustar0000000000000000The MIT License (MIT) Copyright (c) 2014 Ty Overby Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. bincode-1.2.1/readme.md010064400017500001750000000050671357363510400131350ustar0000000000000000# Bincode [![Build Status](https://travis-ci.com/servo/bincode.svg)](https://travis-ci.com/servo/bincode) [![](https://meritbadge.herokuapp.com/bincode)](https://crates.io/crates/bincode) [![](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT) A compact encoder / decoder pair that uses a binary zero-fluff encoding scheme. The size of the encoded object will be the same or smaller than the size that the object takes up in memory in a running Rust program. In addition to exposing two simple functions (one that encodes to `Vec`, and one that decodes from `&[u8]`), binary-encode exposes a Reader/Writer API that makes it work perfectly with other stream-based APIs such as Rust files, network streams, and the [flate2-rs](https://github.com/alexcrichton/flate2-rs) compression library. ## [API Documentation](https://docs.rs/bincode/) ## Bincode in the wild * [google/tarpc](https://github.com/google/tarpc): Bincode is used to serialize and deserialize networked RPC messages. * [servo/webrender](https://github.com/servo/webrender): Bincode records webrender API calls for record/replay-style graphics debugging. * [servo/ipc-channel](https://github.com/servo/ipc-channel): IPC-Channel uses Bincode to send structs between processes using a channel-like API. ## Example ```rust use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, PartialEq, Debug)] struct Entity { x: f32, y: f32, } #[derive(Serialize, Deserialize, PartialEq, Debug)] struct World(Vec); fn main() { let world = World(vec![Entity { x: 0.0, y: 4.0 }, Entity { x: 10.0, y: 20.5 }]); let encoded: Vec = bincode::serialize(&world).unwrap(); // 8 bytes for the length of the vector, 4 bytes per float. assert_eq!(encoded.len(), 8 + 4 * 4); let decoded: World = bincode::deserialize(&encoded[..]).unwrap(); assert_eq!(world, decoded); } ``` ## Details The encoding (and thus decoding) proceeds unsurprisingly -- primitive types are encoded according to the underlying `Writer`, tuples and structs are encoded by encoding their fields one-by-one, and enums are encoded by first writing out the tag representing the variant and then the contents. However, there are some implementation details to be aware of: * `isize`/`usize` are encoded as `i64`/`u64`, for portability. * enums variants are encoded as a `u32` instead of a `usize`. `u32` is enough for all practical uses. * `str` is encoded as `(u64, &[u8])`, where the `u64` is the number of bytes contained in the encoded string. bincode-1.2.1/src/config.rs010064400017500001750000000255411357363510400137570ustar0000000000000000use super::internal::{Bounded, Infinite, SizeLimit}; use byteorder::{BigEndian, ByteOrder, LittleEndian, NativeEndian}; use de::read::BincodeRead; use error::Result; use serde; use std::io::{Read, Write}; use std::marker::PhantomData; use {DeserializerAcceptor, SerializerAcceptor}; use self::EndianOption::*; use self::LimitOption::*; struct DefaultOptions(Infinite); pub(crate) trait Options { type Limit: SizeLimit + 'static; type Endian: ByteOrder + 'static; fn limit(&mut self) -> &mut Self::Limit; } pub(crate) trait OptionsExt: Options + Sized { fn with_no_limit(self) -> WithOtherLimit { WithOtherLimit::new(self, Infinite) } fn with_limit(self, limit: u64) -> WithOtherLimit { WithOtherLimit::new(self, Bounded(limit)) } fn with_little_endian(self) -> WithOtherEndian { WithOtherEndian::new(self) } fn with_big_endian(self) -> WithOtherEndian { WithOtherEndian::new(self) } fn with_native_endian(self) -> WithOtherEndian { WithOtherEndian::new(self) } } impl<'a, O: Options> Options for &'a mut O { type Limit = O::Limit; type Endian = O::Endian; #[inline(always)] fn limit(&mut self) -> &mut Self::Limit { (*self).limit() } } impl OptionsExt for T {} impl DefaultOptions { fn new() -> DefaultOptions { DefaultOptions(Infinite) } } impl Options for DefaultOptions { type Limit = Infinite; type Endian = LittleEndian; #[inline(always)] fn limit(&mut self) -> &mut Infinite { &mut self.0 } } #[derive(Clone, Copy)] enum LimitOption { Unlimited, Limited(u64), } #[derive(Clone, Copy)] enum EndianOption { Big, Little, Native, } /// A configuration builder whose options Bincode will use /// while serializing and deserializing. /// /// ### Options /// Endianness: The endianness with which multi-byte integers will be read/written. *default: little endian* /// Limit: The maximum number of bytes that will be read/written in a bincode serialize/deserialize. *default: unlimited* /// /// ### Byte Limit Details /// The purpose of byte-limiting is to prevent Denial-Of-Service attacks whereby malicious attackers get bincode /// deserialization to crash your process by allocating too much memory or keeping a connection open for too long. /// /// When a byte limit is set, bincode will return `Err` on any deserialization that goes over the limit, or any /// serialization that goes over the limit. #[derive(Clone)] pub struct Config { limit: LimitOption, endian: EndianOption, } pub(crate) struct WithOtherLimit { _options: O, pub(crate) new_limit: L, } pub(crate) struct WithOtherEndian { options: O, _endian: PhantomData, } impl WithOtherLimit { #[inline(always)] pub(crate) fn new(options: O, limit: L) -> WithOtherLimit { WithOtherLimit { _options: options, new_limit: limit, } } } impl WithOtherEndian { #[inline(always)] pub(crate) fn new(options: O) -> WithOtherEndian { WithOtherEndian { options: options, _endian: PhantomData, } } } impl Options for WithOtherEndian { type Limit = O::Limit; type Endian = E; #[inline(always)] fn limit(&mut self) -> &mut O::Limit { self.options.limit() } } impl Options for WithOtherLimit { type Limit = L; type Endian = O::Endian; fn limit(&mut self) -> &mut L { &mut self.new_limit } } macro_rules! config_map { ($self:expr, $opts:ident => $call:expr) => { match ($self.limit, $self.endian) { (Unlimited, Little) => { let $opts = DefaultOptions::new().with_no_limit().with_little_endian(); $call } (Unlimited, Big) => { let $opts = DefaultOptions::new().with_no_limit().with_big_endian(); $call } (Unlimited, Native) => { let $opts = DefaultOptions::new().with_no_limit().with_native_endian(); $call } (Limited(l), Little) => { let $opts = DefaultOptions::new().with_limit(l).with_little_endian(); $call } (Limited(l), Big) => { let $opts = DefaultOptions::new().with_limit(l).with_big_endian(); $call } (Limited(l), Native) => { let $opts = DefaultOptions::new().with_limit(l).with_native_endian(); $call } } }; } impl Config { #[inline(always)] pub(crate) fn new() -> Config { Config { limit: LimitOption::Unlimited, endian: EndianOption::Little, } } /// Sets the byte limit to be unlimited. /// This is the default. #[inline(always)] pub fn no_limit(&mut self) -> &mut Self { self.limit = LimitOption::Unlimited; self } /// Sets the byte limit to `limit`. #[inline(always)] pub fn limit(&mut self, limit: u64) -> &mut Self { self.limit = LimitOption::Limited(limit); self } /// Sets the endianness to little-endian /// This is the default. #[inline(always)] pub fn little_endian(&mut self) -> &mut Self { self.endian = EndianOption::Little; self } /// Sets the endianness to big-endian #[inline(always)] pub fn big_endian(&mut self) -> &mut Self { self.endian = EndianOption::Big; self } /// Sets the endianness to the the machine-native endianness #[inline(always)] pub fn native_endian(&mut self) -> &mut Self { self.endian = EndianOption::Native; self } /// Serializes a serializable object into a `Vec` of bytes using this configuration #[inline(always)] pub fn serialize(&self, t: &T) -> Result> { config_map!(self, opts => ::internal::serialize(t, opts)) } /// Returns the size that an object would be if serialized using Bincode with this configuration #[inline(always)] pub fn serialized_size(&self, t: &T) -> Result { config_map!(self, opts => ::internal::serialized_size(t, opts)) } /// Serializes an object directly into a `Writer` using this configuration /// /// If the serialization would take more bytes than allowed by the size limit, an error /// is returned and *no bytes* will be written into the `Writer` #[inline(always)] pub fn serialize_into( &self, w: W, t: &T, ) -> Result<()> { config_map!(self, opts => ::internal::serialize_into(w, t, opts)) } /// Deserializes a slice of bytes into an instance of `T` using this configuration #[inline(always)] pub fn deserialize<'a, T: serde::Deserialize<'a>>(&self, bytes: &'a [u8]) -> Result { config_map!(self, opts => ::internal::deserialize(bytes, opts)) } /// TODO: document #[doc(hidden)] #[inline(always)] pub fn deserialize_in_place<'a, R, T>(&self, reader: R, place: &mut T) -> Result<()> where R: BincodeRead<'a>, T: serde::de::Deserialize<'a>, { config_map!(self, opts => ::internal::deserialize_in_place(reader, opts, place)) } /// Deserializes a slice of bytes with state `seed` using this configuration. #[inline(always)] pub fn deserialize_seed<'a, T: serde::de::DeserializeSeed<'a>>( &self, seed: T, bytes: &'a [u8], ) -> Result { config_map!(self, opts => ::internal::deserialize_seed(seed, bytes, opts)) } /// Deserializes an object directly from a `Read`er using this configuration /// /// If this returns an `Error`, `reader` may be in an invalid state. #[inline(always)] pub fn deserialize_from( &self, reader: R, ) -> Result { config_map!(self, opts => ::internal::deserialize_from(reader, opts)) } /// Deserializes an object directly from a `Read`er with state `seed` using this configuration /// /// If this returns an `Error`, `reader` may be in an invalid state. #[inline(always)] pub fn deserialize_from_seed<'a, R: Read, T: serde::de::DeserializeSeed<'a>>( &self, seed: T, reader: R, ) -> Result { config_map!(self, opts => ::internal::deserialize_from_seed(seed, reader, opts)) } /// Deserializes an object from a custom `BincodeRead`er using the default configuration. /// It is highly recommended to use `deserialize_from` unless you need to implement /// `BincodeRead` for performance reasons. /// /// If this returns an `Error`, `reader` may be in an invalid state. #[inline(always)] pub fn deserialize_from_custom<'a, R: BincodeRead<'a>, T: serde::de::DeserializeOwned>( &self, reader: R, ) -> Result { config_map!(self, opts => ::internal::deserialize_from_custom(reader, opts)) } /// Deserializes an object from a custom `BincodeRead`er with state `seed` using the default /// configuration. It is highly recommended to use `deserialize_from` unless you need to /// implement `BincodeRead` for performance reasons. /// /// If this returns an `Error`, `reader` may be in an invalid state. #[inline(always)] pub fn deserialize_from_custom_seed< 'a, R: BincodeRead<'a>, T: serde::de::DeserializeSeed<'a>, >( &self, seed: T, reader: R, ) -> Result { config_map!(self, opts => ::internal::deserialize_from_custom_seed(seed, reader, opts)) } /// Executes the acceptor with a serde::Deserializer instance. /// NOT A PART OF THE STABLE PUBLIC API #[doc(hidden)] pub fn with_deserializer<'a, A, R>(&self, reader: R, acceptor: A) -> A::Output where A: DeserializerAcceptor<'a>, R: BincodeRead<'a>, { config_map!(self, opts => { let mut deserializer = ::de::Deserializer::new(reader, opts); acceptor.accept(&mut deserializer) }) } /// Executes the acceptor with a serde::Serializer instance. /// NOT A PART OF THE STABLE PUBLIC API #[doc(hidden)] pub fn with_serializer(&self, writer: W, acceptor: A) -> A::Output where A: SerializerAcceptor, W: Write, { config_map!(self, opts => { let mut serializer = ::ser::Serializer::new(writer, opts); acceptor.accept(&mut serializer) }) } } bincode-1.2.1/src/de/mod.rs010064400017500001750000000326201357363510400136550ustar0000000000000000use config::Options; use std::io::Read; use self::read::BincodeRead; use byteorder::ReadBytesExt; use internal::SizeLimit; use serde; use serde::de::Error as DeError; use serde::de::IntoDeserializer; use {Error, ErrorKind, Result}; pub mod read; /// A Deserializer that reads bytes from a buffer. /// /// This struct should rarely be used. /// In most cases, prefer the `deserialize_from` function. /// /// The ByteOrder that is chosen will impact the endianness that /// is used to read integers out of the reader. /// /// ```ignore /// let d = Deserializer::new(&mut some_reader, SizeLimit::new()); /// serde::Deserialize::deserialize(&mut deserializer); /// let bytes_read = d.bytes_read(); /// ``` pub(crate) struct Deserializer { reader: R, options: O, } impl<'de, R: BincodeRead<'de>, O: Options> Deserializer { /// Creates a new Deserializer with a given `Read`er and a size_limit. pub(crate) fn new(r: R, options: O) -> Deserializer { Deserializer { reader: r, options: options, } } fn read_bytes(&mut self, count: u64) -> Result<()> { self.options.limit().add(count) } fn read_type(&mut self) -> Result<()> { use std::mem::size_of; self.read_bytes(size_of::() as u64) } fn read_vec(&mut self) -> Result> { let len: usize = try!(serde::Deserialize::deserialize(&mut *self)); self.read_bytes(len as u64)?; self.reader.get_byte_buffer(len) } fn read_string(&mut self) -> Result { let vec = self.read_vec()?; String::from_utf8(vec).map_err(|e| ErrorKind::InvalidUtf8Encoding(e.utf8_error()).into()) } } macro_rules! impl_nums { ($ty:ty, $dser_method:ident, $visitor_method:ident, $reader_method:ident) => { #[inline] fn $dser_method(self, visitor: V) -> Result where V: serde::de::Visitor<'de>, { try!(self.read_type::<$ty>()); let value = try!(self.reader.$reader_method::()); visitor.$visitor_method(value) } } } impl<'de, 'a, R, O> serde::Deserializer<'de> for &'a mut Deserializer where R: BincodeRead<'de>, O: Options, { type Error = Error; #[inline] fn deserialize_any(self, _visitor: V) -> Result where V: serde::de::Visitor<'de>, { Err(Box::new(ErrorKind::DeserializeAnyNotSupported)) } fn deserialize_bool(self, visitor: V) -> Result where V: serde::de::Visitor<'de>, { let value: u8 = try!(serde::Deserialize::deserialize(self)); match value { 1 => visitor.visit_bool(true), 0 => visitor.visit_bool(false), value => Err(ErrorKind::InvalidBoolEncoding(value).into()), } } impl_nums!(u16, deserialize_u16, visit_u16, read_u16); impl_nums!(u32, deserialize_u32, visit_u32, read_u32); impl_nums!(u64, deserialize_u64, visit_u64, read_u64); impl_nums!(i16, deserialize_i16, visit_i16, read_i16); impl_nums!(i32, deserialize_i32, visit_i32, read_i32); impl_nums!(i64, deserialize_i64, visit_i64, read_i64); impl_nums!(f32, deserialize_f32, visit_f32, read_f32); impl_nums!(f64, deserialize_f64, visit_f64, read_f64); serde_if_integer128! { impl_nums!(u128, deserialize_u128, visit_u128, read_u128); impl_nums!(i128, deserialize_i128, visit_i128, read_i128); } #[inline] fn deserialize_u8(self, visitor: V) -> Result where V: serde::de::Visitor<'de>, { try!(self.read_type::()); visitor.visit_u8(try!(self.reader.read_u8())) } #[inline] fn deserialize_i8(self, visitor: V) -> Result where V: serde::de::Visitor<'de>, { try!(self.read_type::()); visitor.visit_i8(try!(self.reader.read_i8())) } fn deserialize_unit(self, visitor: V) -> Result where V: serde::de::Visitor<'de>, { visitor.visit_unit() } fn deserialize_char(self, visitor: V) -> Result where V: serde::de::Visitor<'de>, { use std::str; let error = || ErrorKind::InvalidCharEncoding.into(); let mut buf = [0u8; 4]; // Look at the first byte to see how many bytes must be read let _ = try!(self.reader.read_exact(&mut buf[..1])); let width = utf8_char_width(buf[0]); if width == 1 { return visitor.visit_char(buf[0] as char); } if width == 0 { return Err(error()); } if self.reader.read_exact(&mut buf[1..width]).is_err() { return Err(error()); } let res = try!( str::from_utf8(&buf[..width]) .ok() .and_then(|s| s.chars().next()) .ok_or(error()) ); visitor.visit_char(res) } fn deserialize_str(self, visitor: V) -> Result where V: serde::de::Visitor<'de>, { let len: usize = try!(serde::Deserialize::deserialize(&mut *self)); try!(self.read_bytes(len as u64)); self.reader.forward_read_str(len, visitor) } fn deserialize_string(self, visitor: V) -> Result where V: serde::de::Visitor<'de>, { visitor.visit_string(try!(self.read_string())) } fn deserialize_bytes(self, visitor: V) -> Result where V: serde::de::Visitor<'de>, { let len: usize = try!(serde::Deserialize::deserialize(&mut *self)); try!(self.read_bytes(len as u64)); self.reader.forward_read_bytes(len, visitor) } fn deserialize_byte_buf(self, visitor: V) -> Result where V: serde::de::Visitor<'de>, { visitor.visit_byte_buf(try!(self.read_vec())) } fn deserialize_enum( self, _enum: &'static str, _variants: &'static [&'static str], visitor: V, ) -> Result where V: serde::de::Visitor<'de>, { impl<'de, 'a, R: 'a, O> serde::de::EnumAccess<'de> for &'a mut Deserializer where R: BincodeRead<'de>, O: Options, { type Error = Error; type Variant = Self; fn variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant)> where V: serde::de::DeserializeSeed<'de>, { let idx: u32 = try!(serde::de::Deserialize::deserialize(&mut *self)); let val: Result<_> = seed.deserialize(idx.into_deserializer()); Ok((try!(val), self)) } } visitor.visit_enum(self) } fn deserialize_tuple(self, len: usize, visitor: V) -> Result where V: serde::de::Visitor<'de>, { struct Access<'a, R: Read + 'a, O: Options + 'a> { deserializer: &'a mut Deserializer, len: usize, } impl<'de, 'a, 'b: 'a, R: BincodeRead<'de> + 'b, O: Options> serde::de::SeqAccess<'de> for Access<'a, R, O> { type Error = Error; fn next_element_seed(&mut self, seed: T) -> Result> where T: serde::de::DeserializeSeed<'de>, { if self.len > 0 { self.len -= 1; let value = try!(serde::de::DeserializeSeed::deserialize( seed, &mut *self.deserializer, )); Ok(Some(value)) } else { Ok(None) } } fn size_hint(&self) -> Option { Some(self.len) } } visitor.visit_seq(Access { deserializer: self, len: len, }) } fn deserialize_option(self, visitor: V) -> Result where V: serde::de::Visitor<'de>, { let value: u8 = try!(serde::de::Deserialize::deserialize(&mut *self)); match value { 0 => visitor.visit_none(), 1 => visitor.visit_some(&mut *self), v => Err(ErrorKind::InvalidTagEncoding(v as usize).into()), } } fn deserialize_seq(self, visitor: V) -> Result where V: serde::de::Visitor<'de>, { let len = try!(serde::Deserialize::deserialize(&mut *self)); self.deserialize_tuple(len, visitor) } fn deserialize_map(self, visitor: V) -> Result where V: serde::de::Visitor<'de>, { struct Access<'a, R: Read + 'a, O: Options + 'a> { deserializer: &'a mut Deserializer, len: usize, } impl<'de, 'a, 'b: 'a, R: BincodeRead<'de> + 'b, O: Options> serde::de::MapAccess<'de> for Access<'a, R, O> { type Error = Error; fn next_key_seed(&mut self, seed: K) -> Result> where K: serde::de::DeserializeSeed<'de>, { if self.len > 0 { self.len -= 1; let key = try!(serde::de::DeserializeSeed::deserialize( seed, &mut *self.deserializer, )); Ok(Some(key)) } else { Ok(None) } } fn next_value_seed(&mut self, seed: V) -> Result where V: serde::de::DeserializeSeed<'de>, { let value = try!(serde::de::DeserializeSeed::deserialize( seed, &mut *self.deserializer, )); Ok(value) } fn size_hint(&self) -> Option { Some(self.len) } } let len = try!(serde::Deserialize::deserialize(&mut *self)); visitor.visit_map(Access { deserializer: self, len: len, }) } fn deserialize_struct( self, _name: &str, fields: &'static [&'static str], visitor: V, ) -> Result where V: serde::de::Visitor<'de>, { self.deserialize_tuple(fields.len(), visitor) } fn deserialize_identifier(self, _visitor: V) -> Result where V: serde::de::Visitor<'de>, { let message = "Bincode does not support Deserializer::deserialize_identifier"; Err(Error::custom(message)) } fn deserialize_newtype_struct(self, _name: &str, visitor: V) -> Result where V: serde::de::Visitor<'de>, { visitor.visit_newtype_struct(self) } fn deserialize_unit_struct(self, _name: &'static str, visitor: V) -> Result where V: serde::de::Visitor<'de>, { visitor.visit_unit() } fn deserialize_tuple_struct( self, _name: &'static str, len: usize, visitor: V, ) -> Result where V: serde::de::Visitor<'de>, { self.deserialize_tuple(len, visitor) } fn deserialize_ignored_any(self, _visitor: V) -> Result where V: serde::de::Visitor<'de>, { let message = "Bincode does not support Deserializer::deserialize_ignored_any"; Err(Error::custom(message)) } fn is_human_readable(&self) -> bool { false } } impl<'de, 'a, R, O> serde::de::VariantAccess<'de> for &'a mut Deserializer where R: BincodeRead<'de>, O: Options, { type Error = Error; fn unit_variant(self) -> Result<()> { Ok(()) } fn newtype_variant_seed(self, seed: T) -> Result where T: serde::de::DeserializeSeed<'de>, { serde::de::DeserializeSeed::deserialize(seed, self) } fn tuple_variant(self, len: usize, visitor: V) -> Result where V: serde::de::Visitor<'de>, { serde::de::Deserializer::deserialize_tuple(self, len, visitor) } fn struct_variant(self, fields: &'static [&'static str], visitor: V) -> Result where V: serde::de::Visitor<'de>, { serde::de::Deserializer::deserialize_tuple(self, fields.len(), visitor) } } static UTF8_CHAR_WIDTH: [u8; 256] = [ 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, 1, // 0x1F 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, 1, // 0x3F 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, 1, // 0x5F 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, 1, // 0x7F 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, 0, // 0x9F 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, 0, // 0xBF 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, 2, // 0xDF 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEF 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xFF ]; // This function is a copy of core::str::utf8_char_width fn utf8_char_width(b: u8) -> usize { UTF8_CHAR_WIDTH[b as usize] as usize } bincode-1.2.1/src/de/read.rs010064400017500001750000000135051357363510400140120ustar0000000000000000use error::Result; use serde; use std::{io, slice}; /// An optional Read trait for advanced Bincode usage. /// /// It is highly recommended to use bincode with `io::Read` or `&[u8]` before /// implementing a custom `BincodeRead`. pub trait BincodeRead<'storage>: io::Read { /// Forwards reading `length` bytes of a string on to the serde reader. fn forward_read_str(&mut self, length: usize, visitor: V) -> Result where V: serde::de::Visitor<'storage>; /// Return the first `length` bytes of the internal byte buffer. fn get_byte_buffer(&mut self, length: usize) -> Result>; /// Forwards reading `length` bytes on to the serde reader. fn forward_read_bytes(&mut self, length: usize, visitor: V) -> Result where V: serde::de::Visitor<'storage>; } /// A BincodeRead implementation for byte slices /// NOT A PART OF THE STABLE PUBLIC API #[doc(hidden)] pub struct SliceReader<'storage> { slice: &'storage [u8], } /// A BincodeRead implementation for io::Readers /// NOT A PART OF THE STABLE PUBLIC API #[doc(hidden)] pub struct IoReader { reader: R, temp_buffer: Vec, } impl<'storage> SliceReader<'storage> { /// Constructs a slice reader pub fn new(bytes: &'storage [u8]) -> SliceReader<'storage> { SliceReader { slice: bytes } } } impl IoReader { /// Constructs an IoReadReader pub fn new(r: R) -> IoReader { IoReader { reader: r, temp_buffer: vec![], } } } impl<'storage> io::Read for SliceReader<'storage> { #[inline(always)] fn read(&mut self, out: &mut [u8]) -> io::Result { (&mut self.slice).read(out) } #[inline(always)] fn read_exact(&mut self, out: &mut [u8]) -> io::Result<()> { (&mut self.slice).read_exact(out) } } impl io::Read for IoReader { #[inline(always)] fn read(&mut self, out: &mut [u8]) -> io::Result { self.reader.read(out) } #[inline(always)] fn read_exact(&mut self, out: &mut [u8]) -> io::Result<()> { self.reader.read_exact(out) } } impl<'storage> SliceReader<'storage> { #[inline(always)] fn unexpected_eof() -> Box<::ErrorKind> { return Box::new(::ErrorKind::Io(io::Error::new( io::ErrorKind::UnexpectedEof, "", ))); } } impl<'storage> BincodeRead<'storage> for SliceReader<'storage> { #[inline(always)] fn forward_read_str(&mut self, length: usize, visitor: V) -> Result where V: serde::de::Visitor<'storage>, { use ErrorKind; if length > self.slice.len() { return Err(SliceReader::unexpected_eof()); } let string = match ::std::str::from_utf8(&self.slice[..length]) { Ok(s) => s, Err(e) => return Err(ErrorKind::InvalidUtf8Encoding(e).into()), }; let r = visitor.visit_borrowed_str(string); self.slice = &self.slice[length..]; r } #[inline(always)] fn get_byte_buffer(&mut self, length: usize) -> Result> { if length > self.slice.len() { return Err(SliceReader::unexpected_eof()); } let r = &self.slice[..length]; self.slice = &self.slice[length..]; Ok(r.to_vec()) } #[inline(always)] fn forward_read_bytes(&mut self, length: usize, visitor: V) -> Result where V: serde::de::Visitor<'storage>, { if length > self.slice.len() { return Err(SliceReader::unexpected_eof()); } let r = visitor.visit_borrowed_bytes(&self.slice[..length]); self.slice = &self.slice[length..]; r } } impl IoReader where R: io::Read, { fn fill_buffer(&mut self, length: usize) -> Result<()> { // We first reserve the space needed in our buffer. let current_length = self.temp_buffer.len(); if length > current_length { self.temp_buffer.reserve_exact(length - current_length); } // Then create a slice with the length as our desired length. This is // safe as long as we only write (no reads) to this buffer, because // `reserve_exact` above has allocated this space. let buf = unsafe { slice::from_raw_parts_mut(self.temp_buffer.as_mut_ptr(), length) }; // This method is assumed to properly handle slices which include // uninitialized bytes (as ours does). See discussion at the link below. // https://github.com/servo/bincode/issues/260 self.reader.read_exact(buf)?; // Only after `read_exact` successfully returns do we set the buffer // length. By doing this after the call to `read_exact`, we can avoid // exposing uninitialized memory in the case of `read_exact` returning // an error. unsafe { self.temp_buffer.set_len(length); } Ok(()) } } impl<'a, R> BincodeRead<'a> for IoReader where R: io::Read, { fn forward_read_str(&mut self, length: usize, visitor: V) -> Result where V: serde::de::Visitor<'a>, { self.fill_buffer(length)?; let string = match ::std::str::from_utf8(&self.temp_buffer[..]) { Ok(s) => s, Err(e) => return Err(::ErrorKind::InvalidUtf8Encoding(e).into()), }; let r = visitor.visit_str(string); r } fn get_byte_buffer(&mut self, length: usize) -> Result> { self.fill_buffer(length)?; Ok(::std::mem::replace(&mut self.temp_buffer, Vec::new())) } fn forward_read_bytes(&mut self, length: usize, visitor: V) -> Result where V: serde::de::Visitor<'a>, { self.fill_buffer(length)?; let r = visitor.visit_bytes(&self.temp_buffer[..]); r } } bincode-1.2.1/src/error.rs010064400017500001750000000107351346021704700136370ustar0000000000000000use std::error::Error as StdError; use std::io; use std::str::Utf8Error; use std::{error, fmt}; use serde; /// The result of a serialization or deserialization operation. pub type Result = ::std::result::Result; /// An error that can be produced during (de)serializing. pub type Error = Box; /// The kind of error that can be produced during a serialization or deserialization. #[derive(Debug)] pub enum ErrorKind { /// If the error stems from the reader/writer that is being used /// during (de)serialization, that error will be stored and returned here. Io(io::Error), /// Returned if the deserializer attempts to deserialize a string that is not valid utf8 InvalidUtf8Encoding(Utf8Error), /// Returned if the deserializer attempts to deserialize a bool that was /// not encoded as either a 1 or a 0 InvalidBoolEncoding(u8), /// Returned if the deserializer attempts to deserialize a char that is not in the correct format. InvalidCharEncoding, /// Returned if the deserializer attempts to deserialize the tag of an enum that is /// not in the expected ranges InvalidTagEncoding(usize), /// Serde has a deserialize_any method that lets the format hint to the /// object which route to take in deserializing. DeserializeAnyNotSupported, /// If (de)serializing a message takes more than the provided size limit, this /// error is returned. SizeLimit, /// Bincode can not encode sequences of unknown length (like iterators). SequenceMustHaveLength, /// A custom error message from Serde. Custom(String), } impl StdError for ErrorKind { fn description(&self) -> &str { match *self { ErrorKind::Io(ref err) => error::Error::description(err), ErrorKind::InvalidUtf8Encoding(_) => "string is not valid utf8", ErrorKind::InvalidBoolEncoding(_) => "invalid u8 while decoding bool", ErrorKind::InvalidCharEncoding => "char is not valid", ErrorKind::InvalidTagEncoding(_) => "tag for enum is not valid", ErrorKind::SequenceMustHaveLength => { "Bincode can only encode sequences and maps that have a knowable size ahead of time" } ErrorKind::DeserializeAnyNotSupported => { "Bincode doesn't support serde::Deserializer::deserialize_any" } ErrorKind::SizeLimit => "the size limit has been reached", ErrorKind::Custom(ref msg) => msg, } } fn cause(&self) -> Option<&error::Error> { match *self { ErrorKind::Io(ref err) => Some(err), ErrorKind::InvalidUtf8Encoding(_) => None, ErrorKind::InvalidBoolEncoding(_) => None, ErrorKind::InvalidCharEncoding => None, ErrorKind::InvalidTagEncoding(_) => None, ErrorKind::SequenceMustHaveLength => None, ErrorKind::DeserializeAnyNotSupported => None, ErrorKind::SizeLimit => None, ErrorKind::Custom(_) => None, } } } impl From for Error { fn from(err: io::Error) -> Error { ErrorKind::Io(err).into() } } impl fmt::Display for ErrorKind { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { ErrorKind::Io(ref ioerr) => write!(fmt, "io error: {}", ioerr), ErrorKind::InvalidUtf8Encoding(ref e) => write!(fmt, "{}: {}", self.description(), e), ErrorKind::InvalidBoolEncoding(b) => { write!(fmt, "{}, expected 0 or 1, found {}", self.description(), b) } ErrorKind::InvalidCharEncoding => write!(fmt, "{}", self.description()), ErrorKind::InvalidTagEncoding(tag) => { write!(fmt, "{}, found {}", self.description(), tag) } ErrorKind::SequenceMustHaveLength => write!(fmt, "{}", self.description()), ErrorKind::SizeLimit => write!(fmt, "{}", self.description()), ErrorKind::DeserializeAnyNotSupported => write!( fmt, "Bincode does not support the serde::Deserializer::deserialize_any method" ), ErrorKind::Custom(ref s) => s.fmt(fmt), } } } impl serde::de::Error for Error { fn custom(desc: T) -> Error { ErrorKind::Custom(desc.to_string()).into() } } impl serde::ser::Error for Error { fn custom(msg: T) -> Self { ErrorKind::Custom(msg.to_string()).into() } } bincode-1.2.1/src/internal.rs010064400017500001750000000115521357363510400143230ustar0000000000000000use serde; use std::io::{Read, Write}; use std::marker::PhantomData; use config::{Options, OptionsExt}; use de::read::BincodeRead; use {ErrorKind, Result}; #[derive(Clone)] struct CountSize { total: u64, other_limit: L, } pub(crate) fn serialize_into(writer: W, value: &T, mut options: O) -> Result<()> where W: Write, T: serde::Serialize, O: Options, { if options.limit().limit().is_some() { // "compute" the size for the side-effect // of returning Err if the bound was reached. serialized_size(value, &mut options)?; } let mut serializer = ::ser::Serializer::<_, O>::new(writer, options); serde::Serialize::serialize(value, &mut serializer) } pub(crate) fn serialize(value: &T, mut options: O) -> Result> where T: serde::Serialize, O: Options, { let mut writer = { let actual_size = serialized_size(value, &mut options)?; Vec::with_capacity(actual_size as usize) }; serialize_into(&mut writer, value, options.with_no_limit())?; Ok(writer) } impl SizeLimit for CountSize { fn add(&mut self, c: u64) -> Result<()> { self.other_limit.add(c)?; self.total += c; Ok(()) } fn limit(&self) -> Option { unreachable!(); } } pub(crate) fn serialized_size(value: &T, mut options: O) -> Result where T: serde::Serialize, { let old_limiter = options.limit().clone(); let mut size_counter = ::ser::SizeChecker { options: ::config::WithOtherLimit::new( options, CountSize { total: 0, other_limit: old_limiter, }, ), }; let result = value.serialize(&mut size_counter); result.map(|_| size_counter.options.new_limit.total) } pub(crate) fn deserialize_from(reader: R, options: O) -> Result where R: Read, T: serde::de::DeserializeOwned, O: Options, { deserialize_from_seed(PhantomData, reader, options) } pub(crate) fn deserialize_from_seed<'a, R, T, O>(seed: T, reader: R, options: O) -> Result where R: Read, T: serde::de::DeserializeSeed<'a>, O: Options, { let reader = ::de::read::IoReader::new(reader); deserialize_from_custom_seed(seed, reader, options) } pub(crate) fn deserialize_from_custom<'a, R, T, O>(reader: R, options: O) -> Result where R: BincodeRead<'a>, T: serde::de::DeserializeOwned, O: Options, { deserialize_from_custom_seed(PhantomData, reader, options) } pub(crate) fn deserialize_from_custom_seed<'a, R, T, O>( seed: T, reader: R, options: O, ) -> Result where R: BincodeRead<'a>, T: serde::de::DeserializeSeed<'a>, O: Options, { let mut deserializer = ::de::Deserializer::<_, O>::new(reader, options); seed.deserialize(&mut deserializer) } pub(crate) fn deserialize_in_place<'a, R, T, O>(reader: R, options: O, place: &mut T) -> Result<()> where R: BincodeRead<'a>, T: serde::de::Deserialize<'a>, O: Options, { let mut deserializer = ::de::Deserializer::<_, _>::new(reader, options); serde::Deserialize::deserialize_in_place(&mut deserializer, place) } pub(crate) fn deserialize<'a, T, O>(bytes: &'a [u8], options: O) -> Result where T: serde::de::Deserialize<'a>, O: Options, { deserialize_seed(PhantomData, bytes, options) } pub(crate) fn deserialize_seed<'a, T, O>(seed: T, bytes: &'a [u8], options: O) -> Result where T: serde::de::DeserializeSeed<'a>, O: Options, { let reader = ::de::read::SliceReader::new(bytes); let options = ::config::WithOtherLimit::new(options, Infinite); deserialize_from_custom_seed(seed, reader, options) } pub(crate) trait SizeLimit: Clone { /// Tells the SizeLimit that a certain number of bytes has been /// read or written. Returns Err if the limit has been exceeded. fn add(&mut self, n: u64) -> Result<()>; /// Returns the hard limit (if one exists) fn limit(&self) -> Option; } /// A SizeLimit that restricts serialized or deserialized messages from /// exceeding a certain byte length. #[derive(Copy, Clone)] pub struct Bounded(pub u64); /// A SizeLimit without a limit! /// Use this if you don't care about the size of encoded or decoded messages. #[derive(Copy, Clone)] pub struct Infinite; impl SizeLimit for Bounded { #[inline(always)] fn add(&mut self, n: u64) -> Result<()> { if self.0 >= n { self.0 -= n; Ok(()) } else { Err(Box::new(ErrorKind::SizeLimit)) } } #[inline(always)] fn limit(&self) -> Option { Some(self.0) } } impl SizeLimit for Infinite { #[inline(always)] fn add(&mut self, _: u64) -> Result<()> { Ok(()) } #[inline(always)] fn limit(&self) -> Option { None } } bincode-1.2.1/src/lib.rs010064400017500001750000000120221357363512100132450ustar0000000000000000#![deny(missing_docs)] //! Bincode is a crate for encoding and decoding using a tiny binary //! serialization strategy. Using it, you can easily go from having //! an object in memory, quickly serialize it to bytes, and then //! deserialize it back just as fast! //! //! ### Using Basic Functions //! //! ```edition2018 //! fn main() { //! // The object that we will serialize. //! let target: Option = Some("hello world".to_string()); //! //! let encoded: Vec = bincode::serialize(&target).unwrap(); //! let decoded: Option = bincode::deserialize(&encoded[..]).unwrap(); //! assert_eq!(target, decoded); //! } //! ``` //! //! ### 128bit numbers //! //! Support for `i128` and `u128` is automatically enabled on Rust toolchains //! greater than or equal to `1.26.0` and disabled for targets which do not support it #![doc(html_root_url = "https://docs.rs/bincode/1.2.1")] #![crate_name = "bincode"] #![crate_type = "rlib"] #![crate_type = "dylib"] extern crate byteorder; #[macro_use] extern crate serde; mod config; mod de; mod error; mod internal; mod ser; pub use config::Config; pub use de::read::{BincodeRead, IoReader, SliceReader}; pub use error::{Error, ErrorKind, Result}; /// An object that implements this trait can be passed a /// serde::Deserializer without knowing its concrete type. /// /// This trait should be used only for `with_deserializer` functions. #[doc(hidden)] pub trait DeserializerAcceptor<'a> { /// The return type for the accept method type Output; /// Accept a serde::Deserializer and do whatever you want with it. fn accept>(self, T) -> Self::Output; } /// An object that implements this trait can be passed a /// serde::Serializer without knowing its concrete type. /// /// This trait should be used only for `with_serializer` functions. #[doc(hidden)] pub trait SerializerAcceptor { /// The return type for the accept method type Output; /// Accept a serde::Serializer and do whatever you want with it. fn accept(self, T) -> Self::Output; } /// Get a default configuration object. /// /// ### Default Configuration: /// /// | Byte limit | Endianness | /// |------------|------------| /// | Unlimited | Little | #[inline(always)] pub fn config() -> Config { Config::new() } /// Serializes an object directly into a `Writer` using the default configuration. /// /// If the serialization would take more bytes than allowed by the size limit, an error /// is returned and *no bytes* will be written into the `Writer`. pub fn serialize_into(writer: W, value: &T) -> Result<()> where W: std::io::Write, T: serde::Serialize, { config().serialize_into(writer, value) } /// Serializes a serializable object into a `Vec` of bytes using the default configuration. pub fn serialize(value: &T) -> Result> where T: serde::Serialize, { config().serialize(value) } /// Deserializes an object directly from a `Read`er using the default configuration. /// /// If this returns an `Error`, `reader` may be in an invalid state. pub fn deserialize_from(reader: R) -> Result where R: std::io::Read, T: serde::de::DeserializeOwned, { config().deserialize_from(reader) } /// Deserializes an object from a custom `BincodeRead`er using the default configuration. /// It is highly recommended to use `deserialize_from` unless you need to implement /// `BincodeRead` for performance reasons. /// /// If this returns an `Error`, `reader` may be in an invalid state. pub fn deserialize_from_custom<'a, R, T>(reader: R) -> Result where R: de::read::BincodeRead<'a>, T: serde::de::DeserializeOwned, { config().deserialize_from_custom(reader) } /// Only use this if you know what you're doing. /// /// This is part of the public API. #[doc(hidden)] pub fn deserialize_in_place<'a, R, T>(reader: R, place: &mut T) -> Result<()> where T: serde::de::Deserialize<'a>, R: BincodeRead<'a>, { config().deserialize_in_place(reader, place) } /// Deserializes a slice of bytes into an instance of `T` using the default configuration. pub fn deserialize<'a, T>(bytes: &'a [u8]) -> Result where T: serde::de::Deserialize<'a>, { config().deserialize(bytes) } /// Returns the size that an object would be if serialized using Bincode with the default configuration. pub fn serialized_size(value: &T) -> Result where T: serde::Serialize, { config().serialized_size(value) } /// Executes the acceptor with a serde::Deserializer instance. /// NOT A PART OF THE STABLE PUBLIC API #[doc(hidden)] pub fn with_deserializer<'a, A, R>(reader: R, acceptor: A) -> A::Output where A: DeserializerAcceptor<'a>, R: BincodeRead<'a>, { config().with_deserializer(reader, acceptor) } /// Executes the acceptor with a serde::Serializer instance. /// NOT A PART OF THE STABLE PUBLIC API #[doc(hidden)] pub fn with_serializer(writer: W, acceptor: A) -> A::Output where A: SerializerAcceptor, W: std::io::Write, { config().with_serializer(writer, acceptor) } bincode-1.2.1/src/ser/mod.rs010064400017500001750000000440541357363510400140620ustar0000000000000000use std::io::Write; use std::u32; use serde; use byteorder::WriteBytesExt; use super::internal::SizeLimit; use super::{Error, ErrorKind, Result}; use config::Options; /// An Serializer that encodes values directly into a Writer. /// /// The specified byte-order will impact the endianness that is /// used during the encoding. /// /// This struct should not be used often. /// For most cases, prefer the `encode_into` function. pub(crate) struct Serializer { writer: W, _options: O, } impl Serializer { /// Creates a new Serializer with the given `Write`r. pub fn new(w: W, options: O) -> Serializer { Serializer { writer: w, _options: options, } } } impl<'a, W: Write, O: Options> serde::Serializer for &'a mut Serializer { type Ok = (); type Error = Error; type SerializeSeq = Compound<'a, W, O>; type SerializeTuple = Compound<'a, W, O>; type SerializeTupleStruct = Compound<'a, W, O>; type SerializeTupleVariant = Compound<'a, W, O>; type SerializeMap = Compound<'a, W, O>; type SerializeStruct = Compound<'a, W, O>; type SerializeStructVariant = Compound<'a, W, O>; fn serialize_unit(self) -> Result<()> { Ok(()) } fn serialize_unit_struct(self, _: &'static str) -> Result<()> { Ok(()) } fn serialize_bool(self, v: bool) -> Result<()> { self.writer .write_u8(if v { 1 } else { 0 }) .map_err(Into::into) } fn serialize_u8(self, v: u8) -> Result<()> { self.writer.write_u8(v).map_err(Into::into) } fn serialize_u16(self, v: u16) -> Result<()> { self.writer.write_u16::(v).map_err(Into::into) } fn serialize_u32(self, v: u32) -> Result<()> { self.writer.write_u32::(v).map_err(Into::into) } fn serialize_u64(self, v: u64) -> Result<()> { self.writer.write_u64::(v).map_err(Into::into) } fn serialize_i8(self, v: i8) -> Result<()> { self.writer.write_i8(v).map_err(Into::into) } fn serialize_i16(self, v: i16) -> Result<()> { self.writer.write_i16::(v).map_err(Into::into) } fn serialize_i32(self, v: i32) -> Result<()> { self.writer.write_i32::(v).map_err(Into::into) } fn serialize_i64(self, v: i64) -> Result<()> { self.writer.write_i64::(v).map_err(Into::into) } serde_if_integer128! { fn serialize_u128(self, v: u128) -> Result<()> { self.writer.write_u128::(v).map_err(Into::into) } fn serialize_i128(self, v: i128) -> Result<()> { self.writer.write_i128::(v).map_err(Into::into) } } fn serialize_f32(self, v: f32) -> Result<()> { self.writer.write_f32::(v).map_err(Into::into) } fn serialize_f64(self, v: f64) -> Result<()> { self.writer.write_f64::(v).map_err(Into::into) } fn serialize_str(self, v: &str) -> Result<()> { try!(self.serialize_u64(v.len() as u64)); self.writer.write_all(v.as_bytes()).map_err(Into::into) } fn serialize_char(self, c: char) -> Result<()> { self.writer .write_all(encode_utf8(c).as_slice()) .map_err(Into::into) } fn serialize_bytes(self, v: &[u8]) -> Result<()> { try!(self.serialize_u64(v.len() as u64)); self.writer.write_all(v).map_err(Into::into) } fn serialize_none(self) -> Result<()> { self.writer.write_u8(0).map_err(Into::into) } fn serialize_some(self, v: &T) -> Result<()> where T: serde::Serialize, { try!(self.writer.write_u8(1)); v.serialize(self) } fn serialize_seq(self, len: Option) -> Result { let len = try!(len.ok_or(ErrorKind::SequenceMustHaveLength)); try!(self.serialize_u64(len as u64)); Ok(Compound { ser: self }) } fn serialize_tuple(self, _len: usize) -> Result { Ok(Compound { ser: self }) } fn serialize_tuple_struct( self, _name: &'static str, _len: usize, ) -> Result { Ok(Compound { ser: self }) } fn serialize_tuple_variant( self, _name: &'static str, variant_index: u32, _variant: &'static str, _len: usize, ) -> Result { try!(self.serialize_u32(variant_index)); Ok(Compound { ser: self }) } fn serialize_map(self, len: Option) -> Result { let len = try!(len.ok_or(ErrorKind::SequenceMustHaveLength)); try!(self.serialize_u64(len as u64)); Ok(Compound { ser: self }) } fn serialize_struct(self, _name: &'static str, _len: usize) -> Result { Ok(Compound { ser: self }) } fn serialize_struct_variant( self, _name: &'static str, variant_index: u32, _variant: &'static str, _len: usize, ) -> Result { try!(self.serialize_u32(variant_index)); Ok(Compound { ser: self }) } fn serialize_newtype_struct(self, _name: &'static str, value: &T) -> Result<()> where T: serde::ser::Serialize, { value.serialize(self) } fn serialize_newtype_variant( self, _name: &'static str, variant_index: u32, _variant: &'static str, value: &T, ) -> Result<()> where T: serde::ser::Serialize, { try!(self.serialize_u32(variant_index)); value.serialize(self) } fn serialize_unit_variant( self, _name: &'static str, variant_index: u32, _variant: &'static str, ) -> Result<()> { self.serialize_u32(variant_index) } fn is_human_readable(&self) -> bool { false } } pub(crate) struct SizeChecker { pub options: O, } impl SizeChecker { pub fn new(options: O) -> SizeChecker { SizeChecker { options: options } } fn add_raw(&mut self, size: u64) -> Result<()> { self.options.limit().add(size) } fn add_value(&mut self, t: T) -> Result<()> { use std::mem::size_of_val; self.add_raw(size_of_val(&t) as u64) } } impl<'a, O: Options> serde::Serializer for &'a mut SizeChecker { type Ok = (); type Error = Error; type SerializeSeq = SizeCompound<'a, O>; type SerializeTuple = SizeCompound<'a, O>; type SerializeTupleStruct = SizeCompound<'a, O>; type SerializeTupleVariant = SizeCompound<'a, O>; type SerializeMap = SizeCompound<'a, O>; type SerializeStruct = SizeCompound<'a, O>; type SerializeStructVariant = SizeCompound<'a, O>; fn serialize_unit(self) -> Result<()> { Ok(()) } fn serialize_unit_struct(self, _: &'static str) -> Result<()> { Ok(()) } fn serialize_bool(self, _: bool) -> Result<()> { self.add_value(0 as u8) } fn serialize_u8(self, v: u8) -> Result<()> { self.add_value(v) } fn serialize_u16(self, v: u16) -> Result<()> { self.add_value(v) } fn serialize_u32(self, v: u32) -> Result<()> { self.add_value(v) } fn serialize_u64(self, v: u64) -> Result<()> { self.add_value(v) } fn serialize_i8(self, v: i8) -> Result<()> { self.add_value(v) } fn serialize_i16(self, v: i16) -> Result<()> { self.add_value(v) } fn serialize_i32(self, v: i32) -> Result<()> { self.add_value(v) } fn serialize_i64(self, v: i64) -> Result<()> { self.add_value(v) } serde_if_integer128! { fn serialize_u128(self, v: u128) -> Result<()> { self.add_value(v) } fn serialize_i128(self, v: i128) -> Result<()> { self.add_value(v) } } fn serialize_f32(self, v: f32) -> Result<()> { self.add_value(v) } fn serialize_f64(self, v: f64) -> Result<()> { self.add_value(v) } fn serialize_str(self, v: &str) -> Result<()> { try!(self.add_value(0 as u64)); self.add_raw(v.len() as u64) } fn serialize_char(self, c: char) -> Result<()> { self.add_raw(encode_utf8(c).as_slice().len() as u64) } fn serialize_bytes(self, v: &[u8]) -> Result<()> { try!(self.add_value(0 as u64)); self.add_raw(v.len() as u64) } fn serialize_none(self) -> Result<()> { self.add_value(0 as u8) } fn serialize_some(self, v: &T) -> Result<()> where T: serde::Serialize, { try!(self.add_value(1 as u8)); v.serialize(self) } fn serialize_seq(self, len: Option) -> Result { let len = try!(len.ok_or(ErrorKind::SequenceMustHaveLength)); try!(self.serialize_u64(len as u64)); Ok(SizeCompound { ser: self }) } fn serialize_tuple(self, _len: usize) -> Result { Ok(SizeCompound { ser: self }) } fn serialize_tuple_struct( self, _name: &'static str, _len: usize, ) -> Result { Ok(SizeCompound { ser: self }) } fn serialize_tuple_variant( self, _name: &'static str, variant_index: u32, _variant: &'static str, _len: usize, ) -> Result { try!(self.add_value(variant_index)); Ok(SizeCompound { ser: self }) } fn serialize_map(self, len: Option) -> Result { let len = try!(len.ok_or(ErrorKind::SequenceMustHaveLength)); try!(self.serialize_u64(len as u64)); Ok(SizeCompound { ser: self }) } fn serialize_struct(self, _name: &'static str, _len: usize) -> Result { Ok(SizeCompound { ser: self }) } fn serialize_struct_variant( self, _name: &'static str, variant_index: u32, _variant: &'static str, _len: usize, ) -> Result { try!(self.add_value(variant_index)); Ok(SizeCompound { ser: self }) } fn serialize_newtype_struct( self, _name: &'static str, v: &V, ) -> Result<()> { v.serialize(self) } fn serialize_unit_variant( self, _name: &'static str, variant_index: u32, _variant: &'static str, ) -> Result<()> { self.add_value(variant_index) } fn serialize_newtype_variant( self, _name: &'static str, variant_index: u32, _variant: &'static str, value: &V, ) -> Result<()> { try!(self.add_value(variant_index)); value.serialize(self) } fn is_human_readable(&self) -> bool { false } } pub(crate) struct Compound<'a, W: 'a, O: Options + 'a> { ser: &'a mut Serializer, } impl<'a, W, O> serde::ser::SerializeSeq for Compound<'a, W, O> where W: Write, O: Options, { type Ok = (); type Error = Error; #[inline] fn serialize_element(&mut self, value: &T) -> Result<()> where T: serde::ser::Serialize, { value.serialize(&mut *self.ser) } #[inline] fn end(self) -> Result<()> { Ok(()) } } impl<'a, W, O> serde::ser::SerializeTuple for Compound<'a, W, O> where W: Write, O: Options, { type Ok = (); type Error = Error; #[inline] fn serialize_element(&mut self, value: &T) -> Result<()> where T: serde::ser::Serialize, { value.serialize(&mut *self.ser) } #[inline] fn end(self) -> Result<()> { Ok(()) } } impl<'a, W, O> serde::ser::SerializeTupleStruct for Compound<'a, W, O> where W: Write, O: Options, { type Ok = (); type Error = Error; #[inline] fn serialize_field(&mut self, value: &T) -> Result<()> where T: serde::ser::Serialize, { value.serialize(&mut *self.ser) } #[inline] fn end(self) -> Result<()> { Ok(()) } } impl<'a, W, O> serde::ser::SerializeTupleVariant for Compound<'a, W, O> where W: Write, O: Options, { type Ok = (); type Error = Error; #[inline] fn serialize_field(&mut self, value: &T) -> Result<()> where T: serde::ser::Serialize, { value.serialize(&mut *self.ser) } #[inline] fn end(self) -> Result<()> { Ok(()) } } impl<'a, W, O> serde::ser::SerializeMap for Compound<'a, W, O> where W: Write, O: Options, { type Ok = (); type Error = Error; #[inline] fn serialize_key(&mut self, value: &K) -> Result<()> where K: serde::ser::Serialize, { value.serialize(&mut *self.ser) } #[inline] fn serialize_value(&mut self, value: &V) -> Result<()> where V: serde::ser::Serialize, { value.serialize(&mut *self.ser) } #[inline] fn end(self) -> Result<()> { Ok(()) } } impl<'a, W, O> serde::ser::SerializeStruct for Compound<'a, W, O> where W: Write, O: Options, { type Ok = (); type Error = Error; #[inline] fn serialize_field(&mut self, _key: &'static str, value: &T) -> Result<()> where T: serde::ser::Serialize, { value.serialize(&mut *self.ser) } #[inline] fn end(self) -> Result<()> { Ok(()) } } impl<'a, W, O> serde::ser::SerializeStructVariant for Compound<'a, W, O> where W: Write, O: Options, { type Ok = (); type Error = Error; #[inline] fn serialize_field(&mut self, _key: &'static str, value: &T) -> Result<()> where T: serde::ser::Serialize, { value.serialize(&mut *self.ser) } #[inline] fn end(self) -> Result<()> { Ok(()) } } pub(crate) struct SizeCompound<'a, S: Options + 'a> { ser: &'a mut SizeChecker, } impl<'a, O: Options> serde::ser::SerializeSeq for SizeCompound<'a, O> { type Ok = (); type Error = Error; #[inline] fn serialize_element(&mut self, value: &T) -> Result<()> where T: serde::ser::Serialize, { value.serialize(&mut *self.ser) } #[inline] fn end(self) -> Result<()> { Ok(()) } } impl<'a, O: Options> serde::ser::SerializeTuple for SizeCompound<'a, O> { type Ok = (); type Error = Error; #[inline] fn serialize_element(&mut self, value: &T) -> Result<()> where T: serde::ser::Serialize, { value.serialize(&mut *self.ser) } #[inline] fn end(self) -> Result<()> { Ok(()) } } impl<'a, O: Options> serde::ser::SerializeTupleStruct for SizeCompound<'a, O> { type Ok = (); type Error = Error; #[inline] fn serialize_field(&mut self, value: &T) -> Result<()> where T: serde::ser::Serialize, { value.serialize(&mut *self.ser) } #[inline] fn end(self) -> Result<()> { Ok(()) } } impl<'a, O: Options> serde::ser::SerializeTupleVariant for SizeCompound<'a, O> { type Ok = (); type Error = Error; #[inline] fn serialize_field(&mut self, value: &T) -> Result<()> where T: serde::ser::Serialize, { value.serialize(&mut *self.ser) } #[inline] fn end(self) -> Result<()> { Ok(()) } } impl<'a, O: Options + 'a> serde::ser::SerializeMap for SizeCompound<'a, O> { type Ok = (); type Error = Error; #[inline] fn serialize_key(&mut self, value: &K) -> Result<()> where K: serde::ser::Serialize, { value.serialize(&mut *self.ser) } #[inline] fn serialize_value(&mut self, value: &V) -> Result<()> where V: serde::ser::Serialize, { value.serialize(&mut *self.ser) } #[inline] fn end(self) -> Result<()> { Ok(()) } } impl<'a, O: Options> serde::ser::SerializeStruct for SizeCompound<'a, O> { type Ok = (); type Error = Error; #[inline] fn serialize_field(&mut self, _key: &'static str, value: &T) -> Result<()> where T: serde::ser::Serialize, { value.serialize(&mut *self.ser) } #[inline] fn end(self) -> Result<()> { Ok(()) } } impl<'a, O: Options> serde::ser::SerializeStructVariant for SizeCompound<'a, O> { type Ok = (); type Error = Error; #[inline] fn serialize_field(&mut self, _key: &'static str, value: &T) -> Result<()> where T: serde::ser::Serialize, { value.serialize(&mut *self.ser) } #[inline] fn end(self) -> Result<()> { Ok(()) } } const TAG_CONT: u8 = 0b1000_0000; const TAG_TWO_B: u8 = 0b1100_0000; const TAG_THREE_B: u8 = 0b1110_0000; const TAG_FOUR_B: u8 = 0b1111_0000; const MAX_ONE_B: u32 = 0x80; const MAX_TWO_B: u32 = 0x800; const MAX_THREE_B: u32 = 0x10000; fn encode_utf8(c: char) -> EncodeUtf8 { let code = c as u32; let mut buf = [0; 4]; let pos = if code < MAX_ONE_B { buf[3] = code as u8; 3 } else if code < MAX_TWO_B { buf[2] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B; buf[3] = (code & 0x3F) as u8 | TAG_CONT; 2 } else if code < MAX_THREE_B { buf[1] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B; buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT; buf[3] = (code & 0x3F) as u8 | TAG_CONT; 1 } else { buf[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B; buf[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT; buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT; buf[3] = (code & 0x3F) as u8 | TAG_CONT; 0 }; EncodeUtf8 { buf: buf, pos: pos } } struct EncodeUtf8 { buf: [u8; 4], pos: usize, } impl EncodeUtf8 { fn as_slice(&self) -> &[u8] { &self.buf[self.pos..] } } bincode-1.2.1/.cargo_vcs_info.json0000644000000001121357363523300125420ustar00{ "git": { "sha1": "b676754eeee41d169e96bcaf211ed49a331b0d87" } } bincode-1.2.1/Cargo.lock0000644000000065041357363523300105300ustar00# This file is automatically @generated by Cargo. # It is not intended for manual editing. [[package]] name = "bincode" version = "1.2.1" dependencies = [ "byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.90 (registry+https://github.com/rust-lang/crates.io-index)", "serde_bytes 0.11.1 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.90 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "byteorder" version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "proc-macro2" version = "0.4.29" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "quote" version = "0.6.12" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "proc-macro2 0.4.29 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "serde" version = "1.0.90" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "serde_bytes" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "serde 1.0.90 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "serde_derive" version = "1.0.90" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "proc-macro2 0.4.29 (registry+https://github.com/rust-lang/crates.io-index)", "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)", "syn 0.15.33 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "syn" version = "0.15.33" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "proc-macro2 0.4.29 (registry+https://github.com/rust-lang/crates.io-index)", "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "unicode-xid" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" [metadata] "checksum byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a019b10a2a7cdeb292db131fc8113e57ea2a908f6e7894b0c3c671893b65dbeb" "checksum proc-macro2 0.4.29 (registry+https://github.com/rust-lang/crates.io-index)" = "64c827cea7a7ab30ce4593e5e04d7a11617ad6ece2fa230605a78b00ff965316" "checksum quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)" = "faf4799c5d274f3868a4aae320a0a182cbd2baee377b378f080e16a23e9d80db" "checksum serde 1.0.90 (registry+https://github.com/rust-lang/crates.io-index)" = "aa5f7c20820475babd2c077c3ab5f8c77a31c15e16ea38687b4c02d3e48680f4" "checksum serde_bytes 0.11.1 (registry+https://github.com/rust-lang/crates.io-index)" = "aaff47db6ef8771cca5d88febef2f22f47f645420e51226374049f68c6b08569" "checksum serde_derive 1.0.90 (registry+https://github.com/rust-lang/crates.io-index)" = "58fc82bec244f168b23d1963b45c8bf5726e9a15a9d146a067f9081aeed2de79" "checksum syn 0.15.33 (registry+https://github.com/rust-lang/crates.io-index)" = "ec52cd796e5f01d0067225a5392e70084acc4c0013fa71d55166d38a8b307836" "checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc"