mirror of https://git.sr.ht/~stygianentity/bincode
Remove rustc serialize support (#95)
* Remove rustc_serialize support * Add changelist and bump version number for alpha * Move refbox and friends into own module * update changelog * update travis config * move serde functions out into global namespace
This commit is contained in:
parent
8998ecaef6
commit
e7a74aa6c2
|
|
@ -24,6 +24,4 @@ install:
|
||||||
script:
|
script:
|
||||||
- multirust default $CHANNEL
|
- multirust default $CHANNEL
|
||||||
- cargo build
|
- cargo build
|
||||||
- cargo build --no-default-features --features "rustc-serialize"
|
|
||||||
- cargo build --no-default-features --features "serde"
|
|
||||||
- if [ $CHANNEL = 'nightly' ] ; then cargo test ; fi
|
- if [ $CHANNEL = 'nightly' ] ; then cargo test ; fi
|
||||||
|
|
|
||||||
10
Cargo.toml
10
Cargo.toml
|
|
@ -1,6 +1,6 @@
|
||||||
[package]
|
[package]
|
||||||
name = "bincode"
|
name = "bincode"
|
||||||
version = "0.6.1"
|
version = "1.0.0-alpha1"
|
||||||
authors = ["Ty Overby <ty@pre-alpha.com>", "Francesco Mazzoli <f@mazzo.li>", "David Tolnay <dtolnay@gmail.com>", "Daniel Griffen"]
|
authors = ["Ty Overby <ty@pre-alpha.com>", "Francesco Mazzoli <f@mazzo.li>", "David Tolnay <dtolnay@gmail.com>", "Daniel Griffen"]
|
||||||
|
|
||||||
repository = "https://github.com/TyOverby/bincode"
|
repository = "https://github.com/TyOverby/bincode"
|
||||||
|
|
@ -14,16 +14,8 @@ description = "A binary serialization / deserialization strategy and implementat
|
||||||
byteorder = "1.0.0"
|
byteorder = "1.0.0"
|
||||||
num-traits = "0.1.32"
|
num-traits = "0.1.32"
|
||||||
|
|
||||||
[dependencies.rustc-serialize]
|
|
||||||
version = "0.3.*"
|
|
||||||
optional = true
|
|
||||||
|
|
||||||
[dependencies.serde]
|
[dependencies.serde]
|
||||||
version = "0.9.*"
|
version = "0.9.*"
|
||||||
optional = true
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
serde_derive = "0.9.*"
|
serde_derive = "0.9.*"
|
||||||
|
|
||||||
[features]
|
|
||||||
default = ["rustc-serialize", "serde"]
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,18 @@
|
||||||
|
* 1.0.0
|
||||||
|
** Removed depricated rustc-serialize support
|
||||||
|
Rustc-serialize was a stopgap until projects like Serde were able to catch up.
|
||||||
|
With macros stabilization on its way, we are able to switch to serde without any
|
||||||
|
big user-friendliness issues. Major congratulations to Serde for coming this far!
|
||||||
|
|
||||||
|
** Moved Refbox, Strbox and Slicebox into a "refbox" module
|
||||||
|
Refbox, Strbox and Slicebox are still an integral piece of bincode, but since
|
||||||
|
they are mainly used by power-users, this move will make the crate API more organized
|
||||||
|
and easier for new users to understand.
|
||||||
|
|
||||||
|
** Upgraded to Serde 0.9.*
|
||||||
|
Serde 0.9.* gives us a better API surface area and allows use of procedural macros for
|
||||||
|
deriving serialize and deserialize implemenetations.
|
||||||
|
|
||||||
|
** Moved serde functions into global module
|
||||||
|
Since serde is the only supported serialization mechanism, it makes sense to have these
|
||||||
|
functions available at the top level.
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
|
/*
|
||||||
extern crate bincode;
|
extern crate bincode;
|
||||||
extern crate rustc_serialize;
|
extern crate
|
||||||
|
|
||||||
use bincode::SizeLimit;
|
use bincode::SizeLimit;
|
||||||
use bincode::rustc_serialize::{encode, decode};
|
use bincode::rustc_serialize::{encode, decode};
|
||||||
|
|
@ -29,3 +30,6 @@ fn main() {
|
||||||
|
|
||||||
assert!(world == decoded);
|
assert!(world == decoded);
|
||||||
}
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
fn main() {}
|
||||||
|
|
|
||||||
21
src/lib.rs
21
src/lib.rs
|
|
@ -16,17 +16,16 @@
|
||||||
//! ### Using Basic Functions
|
//! ### Using Basic Functions
|
||||||
//!
|
//!
|
||||||
//! ```rust
|
//! ```rust
|
||||||
//! #![allow(unstable)]
|
|
||||||
//! extern crate bincode;
|
//! extern crate bincode;
|
||||||
//! use bincode::rustc_serialize::{encode, decode};
|
//! use bincode::{serialize, deserialize};
|
||||||
//! fn main() {
|
//! fn main() {
|
||||||
//! // The object that we will serialize.
|
//! // The object that we will serialize.
|
||||||
//! let target = Some("hello world".to_string());
|
//! let target = Some("hello world".to_string());
|
||||||
//! // The maximum size of the encoded message.
|
//! // The maximum size of the encoded message.
|
||||||
//! let limit = bincode::SizeLimit::Bounded(20);
|
//! let limit = bincode::SizeLimit::Bounded(20);
|
||||||
//!
|
//!
|
||||||
//! let encoded: Vec<u8> = encode(&target, limit).unwrap();
|
//! let encoded: Vec<u8> = serialize(&target, limit).unwrap();
|
||||||
//! let decoded: Option<String> = decode(&encoded[..]).unwrap();
|
//! let decoded: Option<String> = deserialize(&encoded[..]).unwrap();
|
||||||
//! assert_eq!(target, decoded);
|
//! assert_eq!(target, decoded);
|
||||||
//! }
|
//! }
|
||||||
//! ```
|
//! ```
|
||||||
|
|
@ -37,21 +36,14 @@
|
||||||
|
|
||||||
#![doc(html_logo_url = "./icon.png")]
|
#![doc(html_logo_url = "./icon.png")]
|
||||||
|
|
||||||
#[cfg(feature = "rustc-serialize")]
|
|
||||||
extern crate rustc_serialize as rustc_serialize_crate;
|
|
||||||
extern crate byteorder;
|
extern crate byteorder;
|
||||||
extern crate num_traits;
|
extern crate num_traits;
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
extern crate serde as serde_crate;
|
extern crate serde as serde_crate;
|
||||||
|
|
||||||
|
pub mod refbox;
|
||||||
|
mod serde;
|
||||||
|
|
||||||
pub use refbox::{RefBox, StrBox, SliceBox};
|
pub use serde::*;
|
||||||
|
|
||||||
mod refbox;
|
|
||||||
#[cfg(feature = "rustc-serialize")]
|
|
||||||
pub mod rustc_serialize;
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
pub mod serde;
|
|
||||||
|
|
||||||
/// A limit on the amount of bytes that can be read or written.
|
/// A limit on the amount of bytes that can be read or written.
|
||||||
///
|
///
|
||||||
|
|
@ -76,4 +68,3 @@ pub enum SizeLimit {
|
||||||
Infinite,
|
Infinite,
|
||||||
Bounded(u64)
|
Bounded(u64)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,6 @@
|
||||||
use std::boxed::Box;
|
use std::boxed::Box;
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
|
|
||||||
#[cfg(feature = "rustc-serialize")]
|
|
||||||
use rustc_serialize_crate::{Encodable, Encoder, Decodable, Decoder};
|
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
use serde_crate as serde;
|
use serde_crate as serde;
|
||||||
|
|
||||||
/// A struct for encoding nested reference types.
|
/// A struct for encoding nested reference types.
|
||||||
|
|
@ -141,22 +137,6 @@ impl <T> RefBox<'static, T> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "rustc-serialize")]
|
|
||||||
impl <'a, T: Encodable> Encodable for RefBox<'a, T> {
|
|
||||||
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
|
|
||||||
self.inner.encode(s)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "rustc-serialize")]
|
|
||||||
impl <T: Decodable> Decodable for RefBox<'static, T> {
|
|
||||||
fn decode<D: Decoder>(d: &mut D) -> Result<RefBox<'static, T>, D::Error> {
|
|
||||||
let inner = try!(Decodable::decode(d));
|
|
||||||
Ok(RefBox{inner: inner})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
impl<'a, T> serde::Serialize for RefBox<'a, T>
|
impl<'a, T> serde::Serialize for RefBox<'a, T>
|
||||||
where T: serde::Serialize,
|
where T: serde::Serialize,
|
||||||
{
|
{
|
||||||
|
|
@ -167,7 +147,6 @@ impl<'a, T> serde::Serialize for RefBox<'a, T>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
impl<'a, T: serde::Deserialize> serde::Deserialize for RefBox<'a, T> {
|
impl<'a, T: serde::Deserialize> serde::Deserialize for RefBox<'a, T> {
|
||||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||||
where D: serde::Deserializer
|
where D: serde::Deserializer
|
||||||
|
|
@ -239,22 +218,7 @@ impl StrBox<'static> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "rustc-serialize")]
|
|
||||||
impl <'a> Encodable for StrBox<'a> {
|
|
||||||
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
|
|
||||||
self.inner.encode(s)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "rustc-serialize")]
|
|
||||||
impl Decodable for StrBox<'static> {
|
|
||||||
fn decode<D: Decoder>(d: &mut D) -> Result<StrBox<'static>, D::Error> {
|
|
||||||
let inner: RefBoxInner<'static, str, String> = try!(Decodable::decode(d));
|
|
||||||
Ok(StrBox{inner: inner})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
impl<'a> serde::Serialize for StrBox<'a> {
|
impl<'a> serde::Serialize for StrBox<'a> {
|
||||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
where S: serde::Serializer
|
where S: serde::Serializer
|
||||||
|
|
@ -263,7 +227,6 @@ impl<'a> serde::Serialize for StrBox<'a> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
impl serde::Deserialize for StrBox<'static> {
|
impl serde::Deserialize for StrBox<'static> {
|
||||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||||
where D: serde::Deserializer
|
where D: serde::Deserializer
|
||||||
|
|
@ -330,22 +293,7 @@ impl <T> SliceBox<'static, T> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "rustc-serialize")]
|
|
||||||
impl <'a, T: Encodable> Encodable for SliceBox<'a, T> {
|
|
||||||
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
|
|
||||||
self.inner.encode(s)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "rustc-serialize")]
|
|
||||||
impl <T: Decodable> Decodable for SliceBox<'static, T> {
|
|
||||||
fn decode<D: Decoder>(d: &mut D) -> Result<SliceBox<'static, T>, D::Error> {
|
|
||||||
let inner: RefBoxInner<'static, [T], Vec<T>> = try!(Decodable::decode(d));
|
|
||||||
Ok(SliceBox{inner: inner})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
impl<'a, T> serde::Serialize for SliceBox<'a, T>
|
impl<'a, T> serde::Serialize for SliceBox<'a, T>
|
||||||
where T: serde::Serialize,
|
where T: serde::Serialize,
|
||||||
{
|
{
|
||||||
|
|
@ -356,7 +304,6 @@ impl<'a, T> serde::Serialize for SliceBox<'a, T>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
impl<'a, T: serde::Deserialize> serde::Deserialize for SliceBox<'a, T> {
|
impl<'a, T: serde::Deserialize> serde::Deserialize for SliceBox<'a, T> {
|
||||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||||
where D: serde::Deserializer
|
where D: serde::Deserializer
|
||||||
|
|
@ -366,17 +313,7 @@ impl<'a, T: serde::Deserialize> serde::Deserialize for SliceBox<'a, T> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "rustc-serialize")]
|
|
||||||
impl <'a, A: Encodable + ?Sized, B: Encodable> Encodable for RefBoxInner<'a, A, B> {
|
|
||||||
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
|
|
||||||
match self {
|
|
||||||
&RefBoxInner::Ref(ref r) => r.encode(s),
|
|
||||||
&RefBoxInner::Box(ref b) => b.encode(s)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
impl<'a, A: ?Sized, B> serde::Serialize for RefBoxInner<'a, A, B>
|
impl<'a, A: ?Sized, B> serde::Serialize for RefBoxInner<'a, A, B>
|
||||||
where A: serde::Serialize,
|
where A: serde::Serialize,
|
||||||
B: serde::Serialize,
|
B: serde::Serialize,
|
||||||
|
|
@ -391,15 +328,7 @@ impl<'a, A: ?Sized, B> serde::Serialize for RefBoxInner<'a, A, B>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "rustc-serialize")]
|
|
||||||
impl <A: ?Sized, B: Decodable> Decodable for RefBoxInner<'static, A, B> {
|
|
||||||
fn decode<D: Decoder>(d: &mut D) -> Result<RefBoxInner<'static, A, B>, D::Error> {
|
|
||||||
let decoded = try!(Decodable::decode(d));
|
|
||||||
Ok(RefBoxInner::Box(decoded))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
impl<'a, A: ?Sized, B> serde::Deserialize for RefBoxInner<'a, A, B>
|
impl<'a, A: ?Sized, B> serde::Deserialize for RefBoxInner<'a, A, B>
|
||||||
where B: serde::Deserialize,
|
where B: serde::Deserialize,
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -1,102 +0,0 @@
|
||||||
//! A collection of serialization and deserialization functions
|
|
||||||
//! that use the `rustc_serialize` crate for the encodable and decodable
|
|
||||||
//! implementation.
|
|
||||||
|
|
||||||
use rustc_serialize_crate::{Encodable, Decodable};
|
|
||||||
use std::io::{Write, Read};
|
|
||||||
use ::SizeLimit;
|
|
||||||
|
|
||||||
pub use self::writer::{SizeChecker, EncoderWriter, EncodingResult, EncodingError};
|
|
||||||
pub use self::reader::{DecoderReader, DecodingResult, DecodingError, InvalidEncoding};
|
|
||||||
|
|
||||||
mod reader;
|
|
||||||
mod writer;
|
|
||||||
|
|
||||||
/// Encodes an encodable object into a `Vec` of bytes.
|
|
||||||
///
|
|
||||||
/// If the encoding would take more bytes than allowed by `size_limit`,
|
|
||||||
/// an error is returned.
|
|
||||||
pub fn encode<T: Encodable>(t: &T, size_limit: SizeLimit) -> EncodingResult<Vec<u8>> {
|
|
||||||
// Since we are putting values directly into a vector, we can do size
|
|
||||||
// computation out here and pre-allocate a buffer of *exactly*
|
|
||||||
// the right size.
|
|
||||||
let mut w = if let SizeLimit::Bounded(l) = size_limit {
|
|
||||||
let actual_size = encoded_size_bounded(t, l);
|
|
||||||
let actual_size = try!(actual_size.ok_or(EncodingError::SizeLimit));
|
|
||||||
Vec::with_capacity(actual_size as usize)
|
|
||||||
} else {
|
|
||||||
vec![]
|
|
||||||
};
|
|
||||||
|
|
||||||
match encode_into(t, &mut w, SizeLimit::Infinite) {
|
|
||||||
Ok(()) => Ok(w),
|
|
||||||
Err(e) => Err(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Decodes a slice of bytes into an object.
|
|
||||||
///
|
|
||||||
/// This method does not have a size-limit because if you already have the bytes
|
|
||||||
/// in memory, then you don't gain anything by having a limiter.
|
|
||||||
pub fn decode<T: Decodable>(b: &[u8]) -> DecodingResult<T> {
|
|
||||||
let mut b = b;
|
|
||||||
decode_from(&mut b, SizeLimit::Infinite)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Encodes an object directly into a `Writer`.
|
|
||||||
///
|
|
||||||
/// If the encoding would take more bytes than allowed by `size_limit`, an error
|
|
||||||
/// is returned and *no bytes* will be written into the `Writer`.
|
|
||||||
///
|
|
||||||
/// If this returns an `EncodingError` (other than SizeLimit), assume that the
|
|
||||||
/// writer is in an invalid state, as writing could bail out in the middle of
|
|
||||||
/// encoding.
|
|
||||||
pub fn encode_into<T: Encodable, W: Write>(t: &T,
|
|
||||||
w: &mut W,
|
|
||||||
size_limit: SizeLimit)
|
|
||||||
-> EncodingResult<()> {
|
|
||||||
try!(match size_limit {
|
|
||||||
SizeLimit::Infinite => Ok(()),
|
|
||||||
SizeLimit::Bounded(x) => {
|
|
||||||
let mut size_checker = SizeChecker::new(x);
|
|
||||||
t.encode(&mut size_checker)
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
t.encode(&mut writer::EncoderWriter::new(w))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Decoes an object directly from a `Buffer`ed Reader.
|
|
||||||
///
|
|
||||||
/// If the provided `SizeLimit` is reached, the decode will bail immediately.
|
|
||||||
/// A SizeLimit can help prevent an attacker from flooding your server with
|
|
||||||
/// a neverending stream of values that runs your server out of memory.
|
|
||||||
///
|
|
||||||
/// If this returns an `DecodingError`, assume that the buffer that you passed
|
|
||||||
/// in is in an invalid state, as the error could be returned during any point
|
|
||||||
/// in the reading.
|
|
||||||
pub fn decode_from<R: Read, T: Decodable>(r: &mut R, size_limit: SizeLimit) -> DecodingResult<T> {
|
|
||||||
Decodable::decode(&mut reader::DecoderReader::new(r, size_limit))
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// Returns the size that an object would be if encoded using bincode.
|
|
||||||
///
|
|
||||||
/// This is used internally as part of the check for encode_into, but it can
|
|
||||||
/// be useful for preallocating buffers if thats your style.
|
|
||||||
pub fn encoded_size<T: Encodable>(t: &T) -> u64 {
|
|
||||||
use std::u64::MAX;
|
|
||||||
let mut size_checker = SizeChecker::new(MAX);
|
|
||||||
t.encode(&mut size_checker).ok();
|
|
||||||
size_checker.written
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Given a maximum size limit, check how large an object would be if it
|
|
||||||
/// were to be encoded.
|
|
||||||
///
|
|
||||||
/// If it can be encoded in `max` or fewer bytes, that number will be returned
|
|
||||||
/// inside `Some`. If it goes over bounds, then None is returned.
|
|
||||||
pub fn encoded_size_bounded<T: Encodable>(t: &T, max: u64) -> Option<u64> {
|
|
||||||
let mut size_checker = SizeChecker::new(max);
|
|
||||||
t.encode(&mut size_checker).ok().map(|_| size_checker.written)
|
|
||||||
}
|
|
||||||
|
|
@ -1,392 +0,0 @@
|
||||||
use std::io::Read;
|
|
||||||
use std::io::Error as IoError;
|
|
||||||
use std::error::Error;
|
|
||||||
use std::fmt;
|
|
||||||
use std::convert::From;
|
|
||||||
|
|
||||||
use rustc_serialize_crate::Decoder;
|
|
||||||
|
|
||||||
use byteorder::{BigEndian, ReadBytesExt};
|
|
||||||
use ::SizeLimit;
|
|
||||||
|
|
||||||
#[derive(Eq, PartialEq, Clone, Debug)]
|
|
||||||
pub struct InvalidEncoding {
|
|
||||||
pub desc: &'static str,
|
|
||||||
pub detail: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for InvalidEncoding {
|
|
||||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
|
||||||
match *self {
|
|
||||||
InvalidEncoding { detail: None, desc } =>
|
|
||||||
write!(fmt, "{}", desc),
|
|
||||||
InvalidEncoding { detail: Some(ref detail), desc } =>
|
|
||||||
write!(fmt, "{} ({})", desc, detail)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An error that can be produced during decoding.
|
|
||||||
///
|
|
||||||
/// If decoding from a Buffer, assume that the buffer has been left
|
|
||||||
/// in an invalid state.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum DecodingError {
|
|
||||||
/// If the error stems from the reader that is being used
|
|
||||||
/// during decoding, that error will be stored and returned here.
|
|
||||||
IoError(IoError),
|
|
||||||
/// If the bytes in the reader are not decodable because of an invalid
|
|
||||||
/// encoding, this error will be returned. This error is only possible
|
|
||||||
/// if a stream is corrupted. A stream produced from `encode` or `encode_into`
|
|
||||||
/// should **never** produce an InvalidEncoding error.
|
|
||||||
InvalidEncoding(InvalidEncoding),
|
|
||||||
/// If decoding a message takes more than the provided size limit, this
|
|
||||||
/// error is returned.
|
|
||||||
SizeLimit
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for DecodingError {
|
|
||||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
|
||||||
match *self {
|
|
||||||
DecodingError::IoError(ref ioerr) =>
|
|
||||||
write!(fmt, "IoError: {}", ioerr),
|
|
||||||
DecodingError::InvalidEncoding(ref ib) =>
|
|
||||||
write!(fmt, "InvalidEncoding: {}", ib),
|
|
||||||
DecodingError::SizeLimit =>
|
|
||||||
write!(fmt, "SizeLimit")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub type DecodingResult<T> = Result<T, DecodingError>;
|
|
||||||
|
|
||||||
fn wrap_io(err: IoError) -> DecodingError {
|
|
||||||
DecodingError::IoError(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Error for DecodingError {
|
|
||||||
fn description(&self) -> &str {
|
|
||||||
match *self {
|
|
||||||
DecodingError::IoError(ref err) => Error::description(err),
|
|
||||||
DecodingError::InvalidEncoding(ref ib) => ib.desc,
|
|
||||||
DecodingError::SizeLimit => "the size limit for decoding has been reached"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn cause(&self) -> Option<&Error> {
|
|
||||||
match *self {
|
|
||||||
DecodingError::IoError(ref err) => err.cause(),
|
|
||||||
DecodingError::InvalidEncoding(_) => None,
|
|
||||||
DecodingError::SizeLimit => None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<IoError> for DecodingError {
|
|
||||||
fn from(err: IoError) -> DecodingError {
|
|
||||||
DecodingError::IoError(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A Decoder that reads bytes from a buffer.
|
|
||||||
///
|
|
||||||
/// This struct should rarely be used.
|
|
||||||
/// In most cases, prefer the `decode_from` function.
|
|
||||||
///
|
|
||||||
/// ```rust,ignore
|
|
||||||
/// let dr = bincode::rustc_serialize::DecoderReader::new(&mut some_reader, SizeLimit::Infinite);
|
|
||||||
/// let result: T = Decodable::decode(&mut dr);
|
|
||||||
/// let bytes_read = dr.bytes_read();
|
|
||||||
/// ```
|
|
||||||
pub struct DecoderReader<'a, R: 'a> {
|
|
||||||
reader: &'a mut R,
|
|
||||||
size_limit: SizeLimit,
|
|
||||||
read: u64
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, R: Read> DecoderReader<'a, R> {
|
|
||||||
pub fn new(r: &'a mut R, size_limit: SizeLimit) -> DecoderReader<'a, R> {
|
|
||||||
DecoderReader {
|
|
||||||
reader: r,
|
|
||||||
size_limit: size_limit,
|
|
||||||
read: 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the number of bytes read from the contained Reader.
|
|
||||||
pub fn bytes_read(&self) -> u64 {
|
|
||||||
self.read
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl <'a, A> DecoderReader<'a, A> {
|
|
||||||
fn read_bytes(&mut self, count: u64) -> Result<(), DecodingError> {
|
|
||||||
self.read = match self.read.checked_add(count) {
|
|
||||||
Some(read) => read,
|
|
||||||
None => return Err(DecodingError::SizeLimit),
|
|
||||||
};
|
|
||||||
match self.size_limit {
|
|
||||||
SizeLimit::Infinite => Ok(()),
|
|
||||||
SizeLimit::Bounded(x) if self.read <= x => Ok(()),
|
|
||||||
SizeLimit::Bounded(_) => Err(DecodingError::SizeLimit)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_type<T>(&mut self) -> Result<(), DecodingError> {
|
|
||||||
use std::mem::size_of;
|
|
||||||
self.read_bytes(size_of::<T>() as u64)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, R: Read> Decoder for DecoderReader<'a, R> {
|
|
||||||
type Error = DecodingError;
|
|
||||||
|
|
||||||
fn read_nil(&mut self) -> DecodingResult<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
fn read_usize(&mut self) -> DecodingResult<usize> {
|
|
||||||
Ok(try!(self.read_u64().map(|x| x as usize)))
|
|
||||||
}
|
|
||||||
fn read_u64(&mut self) -> DecodingResult<u64> {
|
|
||||||
try!(self.read_type::<u64>());
|
|
||||||
self.reader.read_u64::<BigEndian>().map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn read_u32(&mut self) -> DecodingResult<u32> {
|
|
||||||
try!(self.read_type::<u32>());
|
|
||||||
self.reader.read_u32::<BigEndian>().map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn read_u16(&mut self) -> DecodingResult<u16> {
|
|
||||||
try!(self.read_type::<u16>());
|
|
||||||
self.reader.read_u16::<BigEndian>().map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn read_u8(&mut self) -> DecodingResult<u8> {
|
|
||||||
try!(self.read_type::<u8>());
|
|
||||||
self.reader.read_u8().map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn read_isize(&mut self) -> DecodingResult<isize> {
|
|
||||||
self.read_i64().map(|x| x as isize)
|
|
||||||
}
|
|
||||||
fn read_i64(&mut self) -> DecodingResult<i64> {
|
|
||||||
try!(self.read_type::<i64>());
|
|
||||||
self.reader.read_i64::<BigEndian>().map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn read_i32(&mut self) -> DecodingResult<i32> {
|
|
||||||
try!(self.read_type::<i32>());
|
|
||||||
self.reader.read_i32::<BigEndian>().map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn read_i16(&mut self) -> DecodingResult<i16> {
|
|
||||||
try!(self.read_type::<i16>());
|
|
||||||
self.reader.read_i16::<BigEndian>().map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn read_i8(&mut self) -> DecodingResult<i8> {
|
|
||||||
try!(self.read_type::<i8>());
|
|
||||||
self.reader.read_i8().map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn read_bool(&mut self) -> DecodingResult<bool> {
|
|
||||||
let x = try!(self.read_i8());
|
|
||||||
match x {
|
|
||||||
1 => Ok(true),
|
|
||||||
0 => Ok(false),
|
|
||||||
_ => Err(DecodingError::InvalidEncoding(InvalidEncoding{
|
|
||||||
desc: "invalid u8 when decoding bool",
|
|
||||||
detail: Some(format!("Expected 0 or 1, got {}", x))
|
|
||||||
})),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn read_f64(&mut self) -> DecodingResult<f64> {
|
|
||||||
try!(self.read_type::<f64>());
|
|
||||||
self.reader.read_f64::<BigEndian>().map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn read_f32(&mut self) -> DecodingResult<f32> {
|
|
||||||
try!(self.read_type::<f32>());
|
|
||||||
self.reader.read_f32::<BigEndian>().map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn read_char(&mut self) -> DecodingResult<char> {
|
|
||||||
use std::str;
|
|
||||||
|
|
||||||
let error = DecodingError::InvalidEncoding(InvalidEncoding {
|
|
||||||
desc: "Invalid char encoding",
|
|
||||||
detail: None
|
|
||||||
});
|
|
||||||
|
|
||||||
let mut buf = [0];
|
|
||||||
|
|
||||||
let _ = try!(self.reader.read(&mut buf[..]));
|
|
||||||
let first_byte = buf[0];
|
|
||||||
let width = utf8_char_width(first_byte);
|
|
||||||
if width == 1 { return Ok(first_byte as char) }
|
|
||||||
if width == 0 { return Err(error)}
|
|
||||||
|
|
||||||
let mut buf = [first_byte, 0, 0, 0];
|
|
||||||
{
|
|
||||||
let mut start = 1;
|
|
||||||
while start < width {
|
|
||||||
match try!(self.reader.read(&mut buf[start .. width])) {
|
|
||||||
n if n == width - start => break,
|
|
||||||
n if n < width - start => { start += n; }
|
|
||||||
_ => return Err(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let res = try!(match str::from_utf8(&buf[..width]).ok() {
|
|
||||||
Some(s) => Ok(s.chars().next().unwrap()),
|
|
||||||
None => Err(error)
|
|
||||||
});
|
|
||||||
|
|
||||||
try!(self.read_bytes(res.len_utf8() as u64));
|
|
||||||
Ok(res)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_str(&mut self) -> DecodingResult<String> {
|
|
||||||
let len = try!(self.read_usize());
|
|
||||||
try!(self.read_bytes(len as u64));
|
|
||||||
|
|
||||||
let mut buff = Vec::new();
|
|
||||||
try!(self.reader.by_ref().take(len as u64).read_to_end(&mut buff));
|
|
||||||
match String::from_utf8(buff) {
|
|
||||||
Ok(s) => Ok(s),
|
|
||||||
Err(err) => Err(DecodingError::InvalidEncoding(InvalidEncoding {
|
|
||||||
desc: "error while decoding utf8 string",
|
|
||||||
detail: Some(format!("Decoding error: {}", err))
|
|
||||||
})),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn read_enum<T, F>(&mut self, _: &str, f: F) -> DecodingResult<T>
|
|
||||||
where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn read_enum_variant<T, F>(&mut self, names: &[&str], mut f: F) -> DecodingResult<T>
|
|
||||||
where F: FnMut(&mut DecoderReader<'a, R>, usize) -> DecodingResult<T>
|
|
||||||
{
|
|
||||||
let id = try!(self.read_u32());
|
|
||||||
let id = id as usize;
|
|
||||||
if id >= names.len() {
|
|
||||||
Err(DecodingError::InvalidEncoding(InvalidEncoding {
|
|
||||||
desc: "out of bounds tag when reading enum variant",
|
|
||||||
detail: Some(format!("Expected tag < {}, got {}", names.len(), id))
|
|
||||||
}))
|
|
||||||
} else {
|
|
||||||
f(self, id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn read_enum_variant_arg<T, F>(&mut self, _: usize, f: F) -> DecodingResult<T>
|
|
||||||
where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> DecodingResult<T>
|
|
||||||
where F: FnMut(&mut DecoderReader<'a, R>, usize) -> DecodingResult<T>
|
|
||||||
{
|
|
||||||
self.read_enum_variant(names, f)
|
|
||||||
}
|
|
||||||
fn read_enum_struct_variant_field<T, F>(&mut self,
|
|
||||||
_: &str,
|
|
||||||
f_idx: usize,
|
|
||||||
f: F)
|
|
||||||
-> DecodingResult<T>
|
|
||||||
where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
|
|
||||||
{
|
|
||||||
self.read_enum_variant_arg(f_idx, f)
|
|
||||||
}
|
|
||||||
fn read_struct<T, F>(&mut self, _: &str, _: usize, f: F) -> DecodingResult<T>
|
|
||||||
where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn read_struct_field<T, F>(&mut self, _: &str, _: usize, f: F) -> DecodingResult<T>
|
|
||||||
where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn read_tuple<T, F>(&mut self, _: usize, f: F) -> DecodingResult<T>
|
|
||||||
where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn read_tuple_arg<T, F>(&mut self, _: usize, f: F) -> DecodingResult<T>
|
|
||||||
where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn read_tuple_struct<T, F>(&mut self, _: &str, len: usize, f: F) -> DecodingResult<T>
|
|
||||||
where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
|
|
||||||
{
|
|
||||||
self.read_tuple(len, f)
|
|
||||||
}
|
|
||||||
fn read_tuple_struct_arg<T, F>(&mut self, a_idx: usize, f: F) -> DecodingResult<T>
|
|
||||||
where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
|
|
||||||
{
|
|
||||||
self.read_tuple_arg(a_idx, f)
|
|
||||||
}
|
|
||||||
fn read_option<T, F>(&mut self, mut f: F) -> DecodingResult<T>
|
|
||||||
where F: FnMut(&mut DecoderReader<'a, R>, bool) -> DecodingResult<T>
|
|
||||||
{
|
|
||||||
let x = try!(self.read_u8());
|
|
||||||
match x {
|
|
||||||
1 => f(self, true),
|
|
||||||
0 => f(self, false),
|
|
||||||
_ => Err(DecodingError::InvalidEncoding(InvalidEncoding {
|
|
||||||
desc: "invalid tag when decoding Option",
|
|
||||||
detail: Some(format!("Expected 0 or 1, got {}", x))
|
|
||||||
})),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn read_seq<T, F>(&mut self, f: F) -> DecodingResult<T>
|
|
||||||
where F: FnOnce(&mut DecoderReader<'a, R>, usize) -> DecodingResult<T>
|
|
||||||
{
|
|
||||||
let len = try!(self.read_usize());
|
|
||||||
f(self, len)
|
|
||||||
}
|
|
||||||
fn read_seq_elt<T, F>(&mut self, _: usize, f: F) -> DecodingResult<T>
|
|
||||||
where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn read_map<T, F>(&mut self, f: F) -> DecodingResult<T>
|
|
||||||
where F: FnOnce(&mut DecoderReader<'a, R>, usize) -> DecodingResult<T>
|
|
||||||
{
|
|
||||||
let len = try!(self.read_usize());
|
|
||||||
f(self, len)
|
|
||||||
}
|
|
||||||
fn read_map_elt_key<T, F>(&mut self, _: usize, f: F) -> DecodingResult<T>
|
|
||||||
where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn read_map_elt_val<T, F>(&mut self, _: usize, f: F) -> DecodingResult<T>
|
|
||||||
where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult<T>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn error(&mut self, err: &str) -> DecodingError {
|
|
||||||
DecodingError::InvalidEncoding(InvalidEncoding {
|
|
||||||
desc: "user-induced error",
|
|
||||||
detail: Some(err.to_string()),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
];
|
|
||||||
|
|
||||||
fn utf8_char_width(b: u8) -> usize {
|
|
||||||
UTF8_CHAR_WIDTH[b as usize] as usize
|
|
||||||
}
|
|
||||||
|
|
@ -1,422 +0,0 @@
|
||||||
use std::io::Write;
|
|
||||||
use std::io::Error as IoError;
|
|
||||||
use std::error::Error;
|
|
||||||
use std::fmt;
|
|
||||||
|
|
||||||
use rustc_serialize_crate::Encoder;
|
|
||||||
|
|
||||||
use byteorder::{BigEndian, WriteBytesExt};
|
|
||||||
|
|
||||||
pub type EncodingResult<T> = Result<T, EncodingError>;
|
|
||||||
|
|
||||||
|
|
||||||
/// An error that can be produced during encoding.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum EncodingError {
|
|
||||||
/// An error originating from the underlying `Writer`.
|
|
||||||
IoError(IoError),
|
|
||||||
/// An object could not be encoded with the given size limit.
|
|
||||||
///
|
|
||||||
/// This error is returned before any bytes are written to the
|
|
||||||
/// output `Writer`.
|
|
||||||
SizeLimit,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An Encoder that encodes values directly into a Writer.
|
|
||||||
///
|
|
||||||
/// This struct should not be used often.
|
|
||||||
/// For most cases, prefer the `encode_into` function.
|
|
||||||
pub struct EncoderWriter<'a, W: 'a> {
|
|
||||||
writer: &'a mut W,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct SizeChecker {
|
|
||||||
pub size_limit: u64,
|
|
||||||
pub written: u64
|
|
||||||
}
|
|
||||||
|
|
||||||
fn wrap_io(err: IoError) -> EncodingError {
|
|
||||||
EncodingError::IoError(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for EncodingError {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
|
||||||
match *self {
|
|
||||||
EncodingError::IoError(ref err) => write!(f, "IoError: {}", err),
|
|
||||||
EncodingError::SizeLimit => write!(f, "SizeLimit")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Error for EncodingError {
|
|
||||||
fn description(&self) -> &str {
|
|
||||||
match *self {
|
|
||||||
EncodingError::IoError(ref err) => Error::description(err),
|
|
||||||
EncodingError::SizeLimit => "the size limit for decoding has been reached"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn cause(&self) -> Option<&Error> {
|
|
||||||
match *self {
|
|
||||||
EncodingError::IoError(ref err) => err.cause(),
|
|
||||||
EncodingError::SizeLimit => None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl <'a, W: Write> EncoderWriter<'a, W> {
|
|
||||||
pub fn new(w: &'a mut W) -> EncoderWriter<'a, W> {
|
|
||||||
EncoderWriter {
|
|
||||||
writer: w,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SizeChecker {
|
|
||||||
pub fn new(limit: u64) -> SizeChecker {
|
|
||||||
SizeChecker {
|
|
||||||
size_limit: limit,
|
|
||||||
written: 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn add_raw(&mut self, size: usize) -> EncodingResult<()> {
|
|
||||||
self.written += size as u64;
|
|
||||||
if self.written <= self.size_limit {
|
|
||||||
Ok(())
|
|
||||||
} else {
|
|
||||||
Err(EncodingError::SizeLimit)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn add_value<T>(&mut self, t: T) -> EncodingResult<()> {
|
|
||||||
use std::mem::size_of_val;
|
|
||||||
self.add_raw(size_of_val(&t))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, W: Write> Encoder for EncoderWriter<'a, W> {
|
|
||||||
type Error = EncodingError;
|
|
||||||
|
|
||||||
fn emit_nil(&mut self) -> EncodingResult<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
fn emit_usize(&mut self, v: usize) -> EncodingResult<()> {
|
|
||||||
self.emit_u64(v as u64)
|
|
||||||
}
|
|
||||||
fn emit_u64(&mut self, v: u64) -> EncodingResult<()> {
|
|
||||||
self.writer.write_u64::<BigEndian>(v).map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn emit_u32(&mut self, v: u32) -> EncodingResult<()> {
|
|
||||||
self.writer.write_u32::<BigEndian>(v).map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn emit_u16(&mut self, v: u16) -> EncodingResult<()> {
|
|
||||||
self.writer.write_u16::<BigEndian>(v).map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn emit_u8(&mut self, v: u8) -> EncodingResult<()> {
|
|
||||||
self.writer.write_u8(v).map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn emit_isize(&mut self, v: isize) -> EncodingResult<()> {
|
|
||||||
self.emit_i64(v as i64)
|
|
||||||
}
|
|
||||||
fn emit_i64(&mut self, v: i64) -> EncodingResult<()> {
|
|
||||||
self.writer.write_i64::<BigEndian>(v).map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn emit_i32(&mut self, v: i32) -> EncodingResult<()> {
|
|
||||||
self.writer.write_i32::<BigEndian>(v).map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn emit_i16(&mut self, v: i16) -> EncodingResult<()> {
|
|
||||||
self.writer.write_i16::<BigEndian>(v).map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn emit_i8(&mut self, v: i8) -> EncodingResult<()> {
|
|
||||||
self.writer.write_i8(v).map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn emit_bool(&mut self, v: bool) -> EncodingResult<()> {
|
|
||||||
self.writer.write_u8(if v {1} else {0}).map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn emit_f64(&mut self, v: f64) -> EncodingResult<()> {
|
|
||||||
self.writer.write_f64::<BigEndian>(v).map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn emit_f32(&mut self, v: f32) -> EncodingResult<()> {
|
|
||||||
self.writer.write_f32::<BigEndian>(v).map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn emit_char(&mut self, v: char) -> EncodingResult<()> {
|
|
||||||
// TODO: change this back once unicode works
|
|
||||||
//let mut cbuf = [0; 4];
|
|
||||||
//let sz = v.encode_utf8(&mut cbuf[..]).unwrap_or(0);
|
|
||||||
//let ptr = &cbuf[..sz];
|
|
||||||
//self.writer.write_all(ptr).map_err(EncodingError::IoError)
|
|
||||||
|
|
||||||
let mut inter = String::with_capacity(1);
|
|
||||||
inter.push(v);
|
|
||||||
self.writer.write_all(inter.as_bytes()).map_err(EncodingError::IoError)
|
|
||||||
}
|
|
||||||
fn emit_str(&mut self, v: &str) -> EncodingResult<()> {
|
|
||||||
try!(self.emit_usize(v.len()));
|
|
||||||
self.writer.write_all(v.as_bytes()).map_err(EncodingError::IoError)
|
|
||||||
}
|
|
||||||
fn emit_enum<F>(&mut self, __: &str, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_enum_variant<F>(&mut self, _: &str, v_id: usize, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
let max_u32: u32 = ::std::u32::MAX;
|
|
||||||
if v_id > (max_u32 as usize) {
|
|
||||||
panic!("Variant tag doesn't fit in a u32")
|
|
||||||
}
|
|
||||||
try!(self.emit_u32(v_id as u32));
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_enum_variant_arg<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_enum_struct_variant<F>(&mut self,
|
|
||||||
v_name: &str,
|
|
||||||
v_id: usize,
|
|
||||||
len: usize,
|
|
||||||
f: F)
|
|
||||||
-> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
self.emit_enum_variant(v_name, v_id, len, f)
|
|
||||||
}
|
|
||||||
fn emit_enum_struct_variant_field<F>(&mut self, _: &str, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_struct<F>(&mut self, _: &str, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_struct_field<F>(&mut self, _: &str, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_tuple<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_tuple_arg<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_tuple_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
self.emit_tuple(len, f)
|
|
||||||
}
|
|
||||||
fn emit_tuple_struct_arg<F>(&mut self, f_idx: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
self.emit_tuple_arg(f_idx, f)
|
|
||||||
}
|
|
||||||
fn emit_option<F>(&mut self, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_option_none(&mut self) -> EncodingResult<()> {
|
|
||||||
self.writer.write_u8(0).map_err(wrap_io)
|
|
||||||
}
|
|
||||||
fn emit_option_some<F>(&mut self, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
try!(self.writer.write_u8(1).map_err(wrap_io));
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
try!(self.emit_usize(len));
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_seq_elt<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_map<F>(&mut self, len: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
try!(self.emit_usize(len));
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_map_elt_key<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_map_elt_val<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Encoder for SizeChecker {
|
|
||||||
type Error = EncodingError;
|
|
||||||
|
|
||||||
fn emit_nil(&mut self) -> EncodingResult<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
fn emit_usize(&mut self, v: usize) -> EncodingResult<()> {
|
|
||||||
self.add_value(v as u64)
|
|
||||||
}
|
|
||||||
fn emit_u64(&mut self, v: u64) -> EncodingResult<()> {
|
|
||||||
self.add_value(v)
|
|
||||||
}
|
|
||||||
fn emit_u32(&mut self, v: u32) -> EncodingResult<()> {
|
|
||||||
self.add_value(v)
|
|
||||||
}
|
|
||||||
fn emit_u16(&mut self, v: u16) -> EncodingResult<()> {
|
|
||||||
self.add_value(v)
|
|
||||||
}
|
|
||||||
fn emit_u8(&mut self, v: u8) -> EncodingResult<()> {
|
|
||||||
self.add_value(v)
|
|
||||||
}
|
|
||||||
fn emit_isize(&mut self, v: isize) -> EncodingResult<()> {
|
|
||||||
self.add_value(v as i64)
|
|
||||||
}
|
|
||||||
fn emit_i64(&mut self, v: i64) -> EncodingResult<()> {
|
|
||||||
self.add_value(v)
|
|
||||||
}
|
|
||||||
fn emit_i32(&mut self, v: i32) -> EncodingResult<()> {
|
|
||||||
self.add_value(v)
|
|
||||||
}
|
|
||||||
fn emit_i16(&mut self, v: i16) -> EncodingResult<()> {
|
|
||||||
self.add_value(v)
|
|
||||||
}
|
|
||||||
fn emit_i8(&mut self, v: i8) -> EncodingResult<()> {
|
|
||||||
self.add_value(v)
|
|
||||||
}
|
|
||||||
fn emit_bool(&mut self, _: bool) -> EncodingResult<()> {
|
|
||||||
self.add_value(0 as u8)
|
|
||||||
}
|
|
||||||
fn emit_f64(&mut self, v: f64) -> EncodingResult<()> {
|
|
||||||
self.add_value(v)
|
|
||||||
}
|
|
||||||
fn emit_f32(&mut self, v: f32) -> EncodingResult<()> {
|
|
||||||
self.add_value(v)
|
|
||||||
}
|
|
||||||
fn emit_char(&mut self, v: char) -> EncodingResult<()> {
|
|
||||||
self.add_raw(v.len_utf8())
|
|
||||||
}
|
|
||||||
fn emit_str(&mut self, v: &str) -> EncodingResult<()> {
|
|
||||||
try!(self.add_value(0 as u64));
|
|
||||||
self.add_raw(v.len())
|
|
||||||
}
|
|
||||||
fn emit_enum<F>(&mut self, __: &str, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_enum_variant<F>(&mut self, _: &str, v_id: usize, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
try!(self.add_value(v_id as u32));
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_enum_variant_arg<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_enum_struct_variant<F>(&mut self,
|
|
||||||
_: &str,
|
|
||||||
_: usize,
|
|
||||||
_: usize,
|
|
||||||
f: F)
|
|
||||||
-> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_enum_struct_variant_field<F>(&mut self, _: &str, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_struct<F>(&mut self, _: &str, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_struct_field<F>(&mut self, _: &str, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_tuple<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_tuple_arg<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_tuple_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
self.emit_tuple(len, f)
|
|
||||||
}
|
|
||||||
fn emit_tuple_struct_arg<F>(&mut self, f_idx: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
self.emit_tuple_arg(f_idx, f)
|
|
||||||
}
|
|
||||||
fn emit_option<F>(&mut self, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_option_none(&mut self) -> EncodingResult<()> {
|
|
||||||
self.add_value(0 as u8)
|
|
||||||
}
|
|
||||||
fn emit_option_some<F>(&mut self, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
try!(self.add_value(1 as u8));
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
try!(self.emit_usize(len));
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_seq_elt<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_map<F>(&mut self, len: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
try!(self.emit_usize(len));
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_map_elt_key<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
fn emit_map_elt_val<F>(&mut self, _: usize, f: F) -> EncodingResult<()>
|
|
||||||
where F: FnOnce(&mut SizeChecker) -> EncodingResult<()>
|
|
||||||
{
|
|
||||||
f(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
238
tests/test.rs
238
tests/test.rs
|
|
@ -4,61 +4,48 @@
|
||||||
extern crate serde_derive;
|
extern crate serde_derive;
|
||||||
|
|
||||||
extern crate bincode;
|
extern crate bincode;
|
||||||
extern crate rustc_serialize;
|
|
||||||
extern crate serde;
|
extern crate serde;
|
||||||
|
|
||||||
use std::fmt::Debug;
|
use std::fmt::Debug;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
|
|
||||||
use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
|
use bincode::refbox::{RefBox, StrBox, SliceBox};
|
||||||
|
|
||||||
use bincode::{RefBox, StrBox, SliceBox};
|
|
||||||
|
|
||||||
use bincode::SizeLimit::{self, Infinite, Bounded};
|
use bincode::SizeLimit::{self, Infinite, Bounded};
|
||||||
use bincode::rustc_serialize::{encode, decode, decode_from, DecodingError};
|
use bincode::{serialize, serialized_size, deserialize, deserialize_from, DeserializeError, DeserializeResult};
|
||||||
use bincode::serde::{serialize, deserialize, deserialize_from, DeserializeError, DeserializeResult};
|
|
||||||
|
|
||||||
fn proxy_encode<V>(element: &V, size_limit: SizeLimit) -> Vec<u8>
|
fn proxy_encode<V>(element: &V, size_limit: SizeLimit) -> Vec<u8>
|
||||||
where V: Encodable + Decodable + serde::Serialize + serde::Deserialize + PartialEq + Debug + 'static
|
where V: serde::Serialize + serde::Deserialize + PartialEq + Debug + 'static
|
||||||
{
|
{
|
||||||
let v1 = bincode::rustc_serialize::encode(element, size_limit).unwrap();
|
let v2 = serialize(element, size_limit).unwrap();
|
||||||
let v2 = bincode::serde::serialize(element, size_limit).unwrap();
|
v2
|
||||||
assert_eq!(v1, v2);
|
|
||||||
|
|
||||||
v1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn proxy_decode<V>(slice: &[u8]) -> V
|
fn proxy_decode<V>(slice: &[u8]) -> V
|
||||||
where V: Encodable + Decodable + serde::Serialize + serde::Deserialize + PartialEq + Debug + 'static
|
where V: serde::Serialize + serde::Deserialize + PartialEq + Debug + 'static
|
||||||
{
|
{
|
||||||
let e1 = bincode::rustc_serialize::decode(slice).unwrap();
|
let e2 = deserialize(slice).unwrap();
|
||||||
let e2 = bincode::serde::deserialize(slice).unwrap();
|
e2
|
||||||
|
|
||||||
assert_eq!(e1, e2);
|
|
||||||
|
|
||||||
e1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn proxy_encoded_size<V>(element: &V) -> u64
|
fn proxy_encoded_size<V>(element: &V) -> u64
|
||||||
where V: Encodable + serde::Serialize + PartialEq + Debug + 'static
|
where V: serde::Serialize + PartialEq + Debug + 'static
|
||||||
{
|
{
|
||||||
let ser_size = bincode::rustc_serialize::encoded_size(element);
|
let serde_size = serialized_size(element);
|
||||||
let serde_size = bincode::serde::serialized_size(element);
|
serde_size
|
||||||
assert_eq!(ser_size, serde_size);
|
|
||||||
ser_size
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn the_same<V>(element: V)
|
fn the_same<V>(element: V)
|
||||||
where V: Encodable+Decodable+serde::Serialize+serde::Deserialize+PartialEq+Debug+'static
|
where V: serde::Serialize+serde::Deserialize+PartialEq+Debug+'static
|
||||||
{
|
{
|
||||||
// Make sure that the bahavior isize correct when wrapping with a RefBox.
|
// Make sure that the bahavior isize correct when wrapping with a RefBox.
|
||||||
fn ref_box_correct<V>(v: &V) -> bool
|
fn ref_box_correct<V>(v: &V) -> bool
|
||||||
where V: Encodable + Decodable + PartialEq + Debug + 'static
|
where V: serde::Serialize + serde::Deserialize + PartialEq + Debug + 'static
|
||||||
{
|
{
|
||||||
let rf = RefBox::new(v);
|
let rf = RefBox::new(v);
|
||||||
let encoded = bincode::rustc_serialize::encode(&rf, Infinite).unwrap();
|
let encoded = serialize(&rf, Infinite).unwrap();
|
||||||
let decoded: RefBox<'static, V> = bincode::rustc_serialize::decode(&encoded[..]).unwrap();
|
let decoded: RefBox<'static, V> = deserialize(&encoded[..]).unwrap();
|
||||||
|
|
||||||
decoded.take().deref() == v
|
decoded.take().deref() == v
|
||||||
}
|
}
|
||||||
|
|
@ -116,7 +103,7 @@ fn test_tuple() {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_basic_struct() {
|
fn test_basic_struct() {
|
||||||
#[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, PartialEq, Debug)]
|
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||||
struct Easy {
|
struct Easy {
|
||||||
x: isize,
|
x: isize,
|
||||||
s: String,
|
s: String,
|
||||||
|
|
@ -127,13 +114,13 @@ fn test_basic_struct() {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_nested_struct() {
|
fn test_nested_struct() {
|
||||||
#[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, PartialEq, Debug)]
|
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||||
struct Easy {
|
struct Easy {
|
||||||
x: isize,
|
x: isize,
|
||||||
s: String,
|
s: String,
|
||||||
y: usize
|
y: usize
|
||||||
}
|
}
|
||||||
#[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, PartialEq, Debug)]
|
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||||
struct Nest {
|
struct Nest {
|
||||||
f: Easy,
|
f: Easy,
|
||||||
b: usize,
|
b: usize,
|
||||||
|
|
@ -149,7 +136,7 @@ fn test_nested_struct() {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_struct_newtype() {
|
fn test_struct_newtype() {
|
||||||
#[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, PartialEq, Debug)]
|
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||||
struct NewtypeStr(usize);
|
struct NewtypeStr(usize);
|
||||||
|
|
||||||
the_same(NewtypeStr(5));
|
the_same(NewtypeStr(5));
|
||||||
|
|
@ -157,7 +144,7 @@ fn test_struct_newtype() {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_struct_tuple() {
|
fn test_struct_tuple() {
|
||||||
#[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, PartialEq, Debug)]
|
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||||
struct TubStr(usize, String, f32);
|
struct TubStr(usize, String, f32);
|
||||||
|
|
||||||
the_same(TubStr(5, "hello".to_string(), 3.2));
|
the_same(TubStr(5, "hello".to_string(), 3.2));
|
||||||
|
|
@ -172,7 +159,7 @@ fn test_option() {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_enum() {
|
fn test_enum() {
|
||||||
#[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, PartialEq, Debug)]
|
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||||
enum TestEnum {
|
enum TestEnum {
|
||||||
NoArg,
|
NoArg,
|
||||||
OneArg(usize),
|
OneArg(usize),
|
||||||
|
|
@ -224,29 +211,6 @@ fn test_fixed_size_array() {
|
||||||
the_same([0u8; 19]);
|
the_same([0u8; 19]);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn decoding_errors() {
|
|
||||||
fn isize_invalid_encoding<T>(res: bincode::rustc_serialize::DecodingResult<T>) {
|
|
||||||
match res {
|
|
||||||
Ok(_) => panic!("Expecting error"),
|
|
||||||
Err(DecodingError::IoError(_)) => panic!("Expecting InvalidEncoding"),
|
|
||||||
Err(DecodingError::SizeLimit) => panic!("Expecting InvalidEncoding"),
|
|
||||||
Err(DecodingError::InvalidEncoding(_)) => {},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
isize_invalid_encoding(decode::<bool>(&vec![0xA][..]));
|
|
||||||
isize_invalid_encoding(decode::<String>(&vec![0, 0, 0, 0, 0, 0, 0, 1, 0xFF][..]));
|
|
||||||
// Out-of-bounds variant
|
|
||||||
#[derive(RustcEncodable, RustcDecodable, Serialize)]
|
|
||||||
enum Test {
|
|
||||||
One,
|
|
||||||
Two,
|
|
||||||
};
|
|
||||||
isize_invalid_encoding(decode::<Test>(&vec![0, 0, 0, 5][..]));
|
|
||||||
isize_invalid_encoding(decode::<Option<u8>>(&vec![5, 0][..]));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn deserializing_errors() {
|
fn deserializing_errors() {
|
||||||
fn isize_invalid_deserialize<T: Debug>(res: DeserializeResult<T>) {
|
fn isize_invalid_deserialize<T: Debug>(res: DeserializeResult<T>) {
|
||||||
|
|
@ -261,7 +225,7 @@ fn deserializing_errors() {
|
||||||
isize_invalid_deserialize(deserialize::<bool>(&vec![0xA][..]));
|
isize_invalid_deserialize(deserialize::<bool>(&vec![0xA][..]));
|
||||||
isize_invalid_deserialize(deserialize::<String>(&vec![0, 0, 0, 0, 0, 0, 0, 1, 0xFF][..]));
|
isize_invalid_deserialize(deserialize::<String>(&vec![0, 0, 0, 0, 0, 0, 0, 1, 0xFF][..]));
|
||||||
// Out-of-bounds variant
|
// Out-of-bounds variant
|
||||||
#[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
enum Test {
|
enum Test {
|
||||||
One,
|
One,
|
||||||
Two,
|
Two,
|
||||||
|
|
@ -270,17 +234,6 @@ fn deserializing_errors() {
|
||||||
isize_invalid_deserialize(deserialize::<Option<u8>>(&vec![5, 0][..]));
|
isize_invalid_deserialize(deserialize::<Option<u8>>(&vec![5, 0][..]));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn too_big_decode() {
|
|
||||||
let encoded = vec![0,0,0,3];
|
|
||||||
let decoded: Result<u32, _> = decode_from(&mut &encoded[..], Bounded(3));
|
|
||||||
assert!(decoded.is_err());
|
|
||||||
|
|
||||||
let encoded = vec![0,0,0,3];
|
|
||||||
let decoded: Result<u32, _> = decode_from(&mut &encoded[..], Bounded(4));
|
|
||||||
assert!(decoded.is_ok());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn too_big_deserialize() {
|
fn too_big_deserialize() {
|
||||||
let serialized = vec![0,0,0,3];
|
let serialized = vec![0,0,0,3];
|
||||||
|
|
@ -302,14 +255,6 @@ fn char_serialization() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn too_big_char_decode() {
|
|
||||||
let encoded = vec![0x41];
|
|
||||||
let decoded: Result<char, _> = decode_from(&mut &encoded[..], Bounded(1));
|
|
||||||
assert!(decoded.is_ok());
|
|
||||||
assert_eq!(decoded.unwrap(), 'A');
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn too_big_char_deserialize() {
|
fn too_big_char_deserialize() {
|
||||||
let serialized = vec![0x41];
|
let serialized = vec![0x41];
|
||||||
|
|
@ -318,15 +263,6 @@ fn too_big_char_deserialize() {
|
||||||
assert_eq!(deserialized.unwrap(), 'A');
|
assert_eq!(deserialized.unwrap(), 'A');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn too_big_encode() {
|
|
||||||
assert!(encode(&0u32, Bounded(3)).is_err());
|
|
||||||
assert!(encode(&0u32, Bounded(4)).is_ok());
|
|
||||||
|
|
||||||
assert!(encode(&"abcde", Bounded(8 + 4)).is_err());
|
|
||||||
assert!(encode(&"abcde", Bounded(8 + 5)).is_ok());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn too_big_serialize() {
|
fn too_big_serialize() {
|
||||||
assert!(serialize(&0u32, Bounded(3)).is_err());
|
assert!(serialize(&0u32, Bounded(3)).is_err());
|
||||||
|
|
@ -370,42 +306,6 @@ fn encode_box() {
|
||||||
the_same(Box::new(5));
|
the_same(Box::new(5));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_refbox_encode() {
|
|
||||||
let large_object = vec![1u32,2,3,4,5,6];
|
|
||||||
let mut large_map = HashMap::new();
|
|
||||||
large_map.insert(1, 2);
|
|
||||||
|
|
||||||
|
|
||||||
#[derive(RustcEncodable, RustcDecodable, Debug)]
|
|
||||||
enum Message<'a> {
|
|
||||||
M1(RefBox<'a, Vec<u32>>),
|
|
||||||
M2(RefBox<'a, HashMap<u32, u32>>)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test 1
|
|
||||||
{
|
|
||||||
let encoded = encode(&Message::M1(RefBox::new(&large_object)), Infinite).unwrap();
|
|
||||||
let decoded: Message<'static> = decode(&encoded[..]).unwrap();
|
|
||||||
|
|
||||||
match decoded {
|
|
||||||
Message::M1(b) => assert!(b.take().deref() == &large_object),
|
|
||||||
_ => assert!(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test 2
|
|
||||||
{
|
|
||||||
let encoded = encode(&Message::M2(RefBox::new(&large_map)), Infinite).unwrap();
|
|
||||||
let decoded: Message<'static> = decode(&encoded[..]).unwrap();
|
|
||||||
|
|
||||||
match decoded {
|
|
||||||
Message::M2(b) => assert!(b.take().deref() == &large_map),
|
|
||||||
_ => assert!(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_refbox_serialize() {
|
fn test_refbox_serialize() {
|
||||||
let large_object = vec![1u32,2,3,4,5,6];
|
let large_object = vec![1u32,2,3,4,5,6];
|
||||||
|
|
@ -413,7 +313,7 @@ fn test_refbox_serialize() {
|
||||||
large_map.insert(1, 2);
|
large_map.insert(1, 2);
|
||||||
|
|
||||||
|
|
||||||
#[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
enum Message<'a> {
|
enum Message<'a> {
|
||||||
M1(RefBox<'a, Vec<u32>>),
|
M1(RefBox<'a, Vec<u32>>),
|
||||||
M2(RefBox<'a, HashMap<u32, u32>>)
|
M2(RefBox<'a, HashMap<u32, u32>>)
|
||||||
|
|
@ -442,15 +342,6 @@ fn test_refbox_serialize() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_strbox_encode() {
|
|
||||||
let strx: &'static str = "hello world";
|
|
||||||
let encoded = encode(&StrBox::new(strx), Infinite).unwrap();
|
|
||||||
let decoded: StrBox<'static> = decode(&encoded[..]).unwrap();
|
|
||||||
let stringx: String = decoded.take();
|
|
||||||
assert!(strx == &stringx[..]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_strbox_serialize() {
|
fn test_strbox_serialize() {
|
||||||
let strx: &'static str = "hello world";
|
let strx: &'static str = "hello world";
|
||||||
|
|
@ -460,19 +351,6 @@ fn test_strbox_serialize() {
|
||||||
assert!(strx == &stringx[..]);
|
assert!(strx == &stringx[..]);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_slicebox_encode() {
|
|
||||||
let slice = [1u32, 2, 3 ,4, 5];
|
|
||||||
let encoded = encode(&SliceBox::new(&slice), Infinite).unwrap();
|
|
||||||
let decoded: SliceBox<'static, u32> = decode(&encoded[..]).unwrap();
|
|
||||||
{
|
|
||||||
let sb: &[u32] = &decoded;
|
|
||||||
assert!(slice == sb);
|
|
||||||
}
|
|
||||||
let vecx: Vec<u32> = decoded.take();
|
|
||||||
assert!(slice == &vecx[..]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_slicebox_serialize() {
|
fn test_slicebox_serialize() {
|
||||||
let slice = [1u32, 2, 3 ,4, 5];
|
let slice = [1u32, 2, 3 ,4, 5];
|
||||||
|
|
@ -486,20 +364,15 @@ fn test_slicebox_serialize() {
|
||||||
assert!(slice == &vecx[..]);
|
assert!(slice == &vecx[..]);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_multi_strings_encode() {
|
|
||||||
assert!(encode(&("foo", "bar", "baz"), Infinite).is_ok());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_multi_strings_serialize() {
|
fn test_multi_strings_serialize() {
|
||||||
assert!(serialize(&("foo", "bar", "baz"), Infinite).is_ok());
|
assert!(serialize(&("foo", "bar", "baz"), Infinite).is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
#[test]
|
#[test]
|
||||||
fn test_oom_protection() {
|
fn test_oom_protection() {
|
||||||
use std::io::Cursor;
|
use std::io::Cursor;
|
||||||
#[derive(RustcEncodable, RustcDecodable)]
|
|
||||||
struct FakeVec {
|
struct FakeVec {
|
||||||
len: u64,
|
len: u64,
|
||||||
byte: u8
|
byte: u8
|
||||||
|
|
@ -507,73 +380,24 @@ fn test_oom_protection() {
|
||||||
let x = bincode::rustc_serialize::encode(&FakeVec { len: 0xffffffffffffffffu64, byte: 1 }, bincode::SizeLimit::Bounded(10)).unwrap();
|
let x = bincode::rustc_serialize::encode(&FakeVec { len: 0xffffffffffffffffu64, byte: 1 }, bincode::SizeLimit::Bounded(10)).unwrap();
|
||||||
let y : Result<Vec<u8>, _> = bincode::rustc_serialize::decode_from(&mut Cursor::new(&x[..]), bincode::SizeLimit::Bounded(10));
|
let y : Result<Vec<u8>, _> = bincode::rustc_serialize::decode_from(&mut Cursor::new(&x[..]), bincode::SizeLimit::Bounded(10));
|
||||||
assert!(y.is_err());
|
assert!(y.is_err());
|
||||||
}
|
}*/
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn path_buf() {
|
fn path_buf() {
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
let path = Path::new("foo").to_path_buf();
|
let path = Path::new("foo").to_path_buf();
|
||||||
let serde_encoded = bincode::serde::serialize(&path, Infinite).unwrap();
|
let serde_encoded = serialize(&path, Infinite).unwrap();
|
||||||
let decoded: PathBuf = bincode::serde::deserialize(&serde_encoded).unwrap();
|
let decoded: PathBuf = deserialize(&serde_encoded).unwrap();
|
||||||
assert!(path.to_str() == decoded.to_str());
|
assert!(path.to_str() == decoded.to_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn bytes() {
|
fn bytes() {
|
||||||
let data = b"abc\0123";
|
|
||||||
let b = bincode::rustc_serialize::encode(&data, Infinite).unwrap();
|
|
||||||
let s = bincode::serde::serialize(&data, Infinite).unwrap();
|
|
||||||
assert_eq!(b, s);
|
|
||||||
|
|
||||||
use serde::bytes::Bytes;
|
use serde::bytes::Bytes;
|
||||||
let s2 = bincode::serde::serialize(&Bytes::new(data), Infinite).unwrap();
|
|
||||||
|
let data = b"abc\0123";
|
||||||
|
let s = serialize(&data, Infinite).unwrap();
|
||||||
|
let s2 = serialize(&Bytes::new(data), Infinite).unwrap();
|
||||||
assert_eq!(s, s2);
|
assert_eq!(s, s2);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_manual_enum_encoding() {
|
|
||||||
#[derive(PartialEq)]
|
|
||||||
enum Enumeration {
|
|
||||||
Variant1,
|
|
||||||
Variant2 { val: u64 }
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Encodable for Enumeration {
|
|
||||||
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
|
|
||||||
s.emit_enum("Enumeration", |s| {
|
|
||||||
match *self {
|
|
||||||
Enumeration::Variant1 => {
|
|
||||||
s.emit_enum_variant("Variant1", 0, 0, |_| Ok(()))
|
|
||||||
},
|
|
||||||
Enumeration::Variant2 { val } => {
|
|
||||||
s.emit_enum_struct_variant("Variant2", 1, 1, |s| {
|
|
||||||
s.emit_enum_struct_variant_field("val", 0, |s| s.emit_u64(val))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Decodable for Enumeration {
|
|
||||||
fn decode<D: Decoder>(s: &mut D) -> Result<Self, D::Error> {
|
|
||||||
s.read_enum("Enumeration", |s| {
|
|
||||||
s.read_enum_struct_variant(&["Variant1", "Variant2"], |s, num| {
|
|
||||||
match num {
|
|
||||||
0 => Ok(Enumeration::Variant1),
|
|
||||||
1 => Ok(Enumeration::Variant2 { val: try!(s.read_u64()) }),
|
|
||||||
_ => Err(s.error("Unknown enum variant"))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let encoded = bincode::rustc_serialize::encode(&Enumeration::Variant1, Infinite).unwrap();
|
|
||||||
let decoded: Enumeration = decode(&encoded[..]).unwrap();
|
|
||||||
assert!(decoded == Enumeration::Variant1);
|
|
||||||
|
|
||||||
let encoded = bincode::rustc_serialize::encode(&Enumeration::Variant2 { val: 42 }, Infinite).unwrap();
|
|
||||||
let decoded: Enumeration = decode(&encoded[..]).unwrap();
|
|
||||||
assert!(decoded == Enumeration::Variant2 { val: 42 });
|
|
||||||
}
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue