diff --git a/.travis.yml b/.travis.yml index 23b588e..b67e3bf 100644 --- a/.travis.yml +++ b/.travis.yml @@ -24,6 +24,4 @@ install: script: - multirust default $CHANNEL - cargo build - - cargo build --no-default-features --features "rustc-serialize" - - cargo build --no-default-features --features "serde" - if [ $CHANNEL = 'nightly' ] ; then cargo test ; fi diff --git a/Cargo.toml b/Cargo.toml index 7897165..f541343 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "bincode" -version = "0.6.1" +version = "1.0.0-alpha1" authors = ["Ty Overby ", "Francesco Mazzoli ", "David Tolnay ", "Daniel Griffen"] repository = "https://github.com/TyOverby/bincode" @@ -14,16 +14,8 @@ description = "A binary serialization / deserialization strategy and implementat byteorder = "1.0.0" num-traits = "0.1.32" -[dependencies.rustc-serialize] -version = "0.3.*" -optional = true - [dependencies.serde] version = "0.9.*" -optional = true [dev-dependencies] serde_derive = "0.9.*" - -[features] -default = ["rustc-serialize", "serde"] diff --git a/changelist.org b/changelist.org new file mode 100644 index 0000000..761068b --- /dev/null +++ b/changelist.org @@ -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. diff --git a/examples/basic.rs b/examples/basic.rs index 670f6bc..c5d9d3e 100644 --- a/examples/basic.rs +++ b/examples/basic.rs @@ -1,5 +1,6 @@ +/* extern crate bincode; -extern crate rustc_serialize; +extern crate use bincode::SizeLimit; use bincode::rustc_serialize::{encode, decode}; @@ -29,3 +30,6 @@ fn main() { assert!(world == decoded); } + */ + +fn main() {} diff --git a/src/lib.rs b/src/lib.rs index 138a9e0..c76e219 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -16,17 +16,16 @@ //! ### Using Basic Functions //! //! ```rust -//! #![allow(unstable)] //! extern crate bincode; -//! use bincode::rustc_serialize::{encode, decode}; +//! use bincode::{serialize, deserialize}; //! fn main() { //! // The object that we will serialize. //! let target = Some("hello world".to_string()); //! // The maximum size of the encoded message. //! let limit = bincode::SizeLimit::Bounded(20); //! -//! let encoded: Vec = encode(&target, limit).unwrap(); -//! let decoded: Option = decode(&encoded[..]).unwrap(); +//! let encoded: Vec = serialize(&target, limit).unwrap(); +//! let decoded: Option = deserialize(&encoded[..]).unwrap(); //! assert_eq!(target, decoded); //! } //! ``` @@ -37,21 +36,14 @@ #![doc(html_logo_url = "./icon.png")] -#[cfg(feature = "rustc-serialize")] -extern crate rustc_serialize as rustc_serialize_crate; extern crate byteorder; extern crate num_traits; -#[cfg(feature = "serde")] extern crate serde as serde_crate; +pub mod refbox; +mod serde; -pub use refbox::{RefBox, StrBox, SliceBox}; - -mod refbox; -#[cfg(feature = "rustc-serialize")] -pub mod rustc_serialize; -#[cfg(feature = "serde")] -pub mod serde; +pub use serde::*; /// A limit on the amount of bytes that can be read or written. /// @@ -76,4 +68,3 @@ pub enum SizeLimit { Infinite, Bounded(u64) } - diff --git a/src/refbox.rs b/src/refbox.rs index addfa48..be663f9 100644 --- a/src/refbox.rs +++ b/src/refbox.rs @@ -1,10 +1,6 @@ use std::boxed::Box; use std::ops::Deref; -#[cfg(feature = "rustc-serialize")] -use rustc_serialize_crate::{Encodable, Encoder, Decodable, Decoder}; - -#[cfg(feature = "serde")] use serde_crate as serde; /// A struct for encoding nested reference types. @@ -141,22 +137,6 @@ impl RefBox<'static, T> { } } -#[cfg(feature = "rustc-serialize")] -impl <'a, T: Encodable> Encodable for RefBox<'a, T> { - fn encode(&self, s: &mut S) -> Result<(), S::Error> { - self.inner.encode(s) - } -} - -#[cfg(feature = "rustc-serialize")] -impl Decodable for RefBox<'static, T> { - fn decode(d: &mut D) -> Result, D::Error> { - let inner = try!(Decodable::decode(d)); - Ok(RefBox{inner: inner}) - } -} - -#[cfg(feature = "serde")] impl<'a, T> serde::Serialize for RefBox<'a, T> 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> { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer @@ -239,22 +218,7 @@ impl StrBox<'static> { } } -#[cfg(feature = "rustc-serialize")] -impl <'a> Encodable for StrBox<'a> { - fn encode(&self, s: &mut S) -> Result<(), S::Error> { - self.inner.encode(s) - } -} -#[cfg(feature = "rustc-serialize")] -impl Decodable for StrBox<'static> { - fn decode(d: &mut D) -> Result, 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> { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer @@ -263,7 +227,6 @@ impl<'a> serde::Serialize for StrBox<'a> { } } -#[cfg(feature = "serde")] impl serde::Deserialize for StrBox<'static> { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer @@ -330,22 +293,7 @@ impl SliceBox<'static, T> { } } -#[cfg(feature = "rustc-serialize")] -impl <'a, T: Encodable> Encodable for SliceBox<'a, T> { - fn encode(&self, s: &mut S) -> Result<(), S::Error> { - self.inner.encode(s) - } -} -#[cfg(feature = "rustc-serialize")] -impl Decodable for SliceBox<'static, T> { - fn decode(d: &mut D) -> Result, D::Error> { - let inner: RefBoxInner<'static, [T], Vec> = try!(Decodable::decode(d)); - Ok(SliceBox{inner: inner}) - } -} - -#[cfg(feature = "serde")] impl<'a, T> serde::Serialize for SliceBox<'a, T> 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> { fn deserialize(deserializer: D) -> Result 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(&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> where A: 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 Decodable for RefBoxInner<'static, A, B> { - fn decode(d: &mut D) -> Result, 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> where B: serde::Deserialize, { diff --git a/src/rustc_serialize/mod.rs b/src/rustc_serialize/mod.rs deleted file mode 100644 index 2b75e80..0000000 --- a/src/rustc_serialize/mod.rs +++ /dev/null @@ -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: &T, size_limit: SizeLimit) -> EncodingResult> { - // 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(b: &[u8]) -> DecodingResult { - 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: &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: &mut R, size_limit: SizeLimit) -> DecodingResult { - 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: &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: &T, max: u64) -> Option { - let mut size_checker = SizeChecker::new(max); - t.encode(&mut size_checker).ok().map(|_| size_checker.written) -} diff --git a/src/rustc_serialize/reader.rs b/src/rustc_serialize/reader.rs deleted file mode 100644 index ba1fd31..0000000 --- a/src/rustc_serialize/reader.rs +++ /dev/null @@ -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, -} - -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 = Result; - -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 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(&mut self) -> Result<(), DecodingError> { - use std::mem::size_of; - self.read_bytes(size_of::() 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 { - Ok(try!(self.read_u64().map(|x| x as usize))) - } - fn read_u64(&mut self) -> DecodingResult { - try!(self.read_type::()); - self.reader.read_u64::().map_err(wrap_io) - } - fn read_u32(&mut self) -> DecodingResult { - try!(self.read_type::()); - self.reader.read_u32::().map_err(wrap_io) - } - fn read_u16(&mut self) -> DecodingResult { - try!(self.read_type::()); - self.reader.read_u16::().map_err(wrap_io) - } - fn read_u8(&mut self) -> DecodingResult { - try!(self.read_type::()); - self.reader.read_u8().map_err(wrap_io) - } - fn read_isize(&mut self) -> DecodingResult { - self.read_i64().map(|x| x as isize) - } - fn read_i64(&mut self) -> DecodingResult { - try!(self.read_type::()); - self.reader.read_i64::().map_err(wrap_io) - } - fn read_i32(&mut self) -> DecodingResult { - try!(self.read_type::()); - self.reader.read_i32::().map_err(wrap_io) - } - fn read_i16(&mut self) -> DecodingResult { - try!(self.read_type::()); - self.reader.read_i16::().map_err(wrap_io) - } - fn read_i8(&mut self) -> DecodingResult { - try!(self.read_type::()); - self.reader.read_i8().map_err(wrap_io) - } - fn read_bool(&mut self) -> DecodingResult { - 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 { - try!(self.read_type::()); - self.reader.read_f64::().map_err(wrap_io) - } - fn read_f32(&mut self) -> DecodingResult { - try!(self.read_type::()); - self.reader.read_f32::().map_err(wrap_io) - } - fn read_char(&mut self) -> DecodingResult { - 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 { - 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(&mut self, _: &str, f: F) -> DecodingResult - where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult - { - f(self) - } - fn read_enum_variant(&mut self, names: &[&str], mut f: F) -> DecodingResult - where F: FnMut(&mut DecoderReader<'a, R>, usize) -> DecodingResult - { - 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(&mut self, _: usize, f: F) -> DecodingResult - where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult - { - f(self) - } - fn read_enum_struct_variant(&mut self, names: &[&str], f: F) -> DecodingResult - where F: FnMut(&mut DecoderReader<'a, R>, usize) -> DecodingResult - { - self.read_enum_variant(names, f) - } - fn read_enum_struct_variant_field(&mut self, - _: &str, - f_idx: usize, - f: F) - -> DecodingResult - where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult - { - self.read_enum_variant_arg(f_idx, f) - } - fn read_struct(&mut self, _: &str, _: usize, f: F) -> DecodingResult - where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult - { - f(self) - } - fn read_struct_field(&mut self, _: &str, _: usize, f: F) -> DecodingResult - where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult - { - f(self) - } - fn read_tuple(&mut self, _: usize, f: F) -> DecodingResult - where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult - { - f(self) - } - fn read_tuple_arg(&mut self, _: usize, f: F) -> DecodingResult - where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult - { - f(self) - } - fn read_tuple_struct(&mut self, _: &str, len: usize, f: F) -> DecodingResult - where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult - { - self.read_tuple(len, f) - } - fn read_tuple_struct_arg(&mut self, a_idx: usize, f: F) -> DecodingResult - where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult - { - self.read_tuple_arg(a_idx, f) - } - fn read_option(&mut self, mut f: F) -> DecodingResult - where F: FnMut(&mut DecoderReader<'a, R>, bool) -> DecodingResult - { - 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(&mut self, f: F) -> DecodingResult - where F: FnOnce(&mut DecoderReader<'a, R>, usize) -> DecodingResult - { - let len = try!(self.read_usize()); - f(self, len) - } - fn read_seq_elt(&mut self, _: usize, f: F) -> DecodingResult - where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult - { - f(self) - } - fn read_map(&mut self, f: F) -> DecodingResult - where F: FnOnce(&mut DecoderReader<'a, R>, usize) -> DecodingResult - { - let len = try!(self.read_usize()); - f(self, len) - } - fn read_map_elt_key(&mut self, _: usize, f: F) -> DecodingResult - where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult - { - f(self) - } - fn read_map_elt_val(&mut self, _: usize, f: F) -> DecodingResult - where F: FnOnce(&mut DecoderReader<'a, R>) -> DecodingResult - { - 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 -} diff --git a/src/rustc_serialize/writer.rs b/src/rustc_serialize/writer.rs deleted file mode 100644 index 2ab8da4..0000000 --- a/src/rustc_serialize/writer.rs +++ /dev/null @@ -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 = Result; - - -/// 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(&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::(v).map_err(wrap_io) - } - fn emit_u32(&mut self, v: u32) -> EncodingResult<()> { - self.writer.write_u32::(v).map_err(wrap_io) - } - fn emit_u16(&mut self, v: u16) -> EncodingResult<()> { - self.writer.write_u16::(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::(v).map_err(wrap_io) - } - fn emit_i32(&mut self, v: i32) -> EncodingResult<()> { - self.writer.write_i32::(v).map_err(wrap_io) - } - fn emit_i16(&mut self, v: i16) -> EncodingResult<()> { - self.writer.write_i16::(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::(v).map_err(wrap_io) - } - fn emit_f32(&mut self, v: f32) -> EncodingResult<()> { - self.writer.write_f32::(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(&mut self, __: &str, f: F) -> EncodingResult<()> - where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()> - { - f(self) - } - fn emit_enum_variant(&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(&mut self, _: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()> - { - f(self) - } - fn emit_enum_struct_variant(&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(&mut self, _: &str, _: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()> - { - f(self) - } - fn emit_struct(&mut self, _: &str, _: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()> - { - f(self) - } - fn emit_struct_field(&mut self, _: &str, _: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()> - { - f(self) - } - fn emit_tuple(&mut self, _: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()> - { - f(self) - } - fn emit_tuple_arg(&mut self, _: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()> - { - f(self) - } - fn emit_tuple_struct(&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(&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(&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(&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(&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(&mut self, _: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()> - { - f(self) - } - fn emit_map(&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(&mut self, _: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut EncoderWriter<'a, W>) -> EncodingResult<()> - { - f(self) - } - fn emit_map_elt_val(&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(&mut self, __: &str, f: F) -> EncodingResult<()> - where F: FnOnce(&mut SizeChecker) -> EncodingResult<()> - { - f(self) - } - fn emit_enum_variant(&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(&mut self, _: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut SizeChecker) -> EncodingResult<()> - { - f(self) - } - fn emit_enum_struct_variant(&mut self, - _: &str, - _: usize, - _: usize, - f: F) - -> EncodingResult<()> - where F: FnOnce(&mut SizeChecker) -> EncodingResult<()> - { - f(self) - } - fn emit_enum_struct_variant_field(&mut self, _: &str, _: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut SizeChecker) -> EncodingResult<()> - { - f(self) - } - fn emit_struct(&mut self, _: &str, _: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut SizeChecker) -> EncodingResult<()> - { - f(self) - } - fn emit_struct_field(&mut self, _: &str, _: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut SizeChecker) -> EncodingResult<()> - { - f(self) - } - fn emit_tuple(&mut self, _: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut SizeChecker) -> EncodingResult<()> - { - f(self) - } - fn emit_tuple_arg(&mut self, _: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut SizeChecker) -> EncodingResult<()> - { - f(self) - } - fn emit_tuple_struct(&mut self, _: &str, len: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut SizeChecker) -> EncodingResult<()> - { - self.emit_tuple(len, f) - } - fn emit_tuple_struct_arg(&mut self, f_idx: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut SizeChecker) -> EncodingResult<()> - { - self.emit_tuple_arg(f_idx, f) - } - fn emit_option(&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(&mut self, f: F) -> EncodingResult<()> - where F: FnOnce(&mut SizeChecker) -> EncodingResult<()> - { - try!(self.add_value(1 as u8)); - f(self) - } - fn emit_seq(&mut self, len: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut SizeChecker) -> EncodingResult<()> - { - try!(self.emit_usize(len)); - f(self) - } - fn emit_seq_elt(&mut self, _: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut SizeChecker) -> EncodingResult<()> - { - f(self) - } - fn emit_map(&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(&mut self, _: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut SizeChecker) -> EncodingResult<()> - { - f(self) - } - fn emit_map_elt_val(&mut self, _: usize, f: F) -> EncodingResult<()> - where F: FnOnce(&mut SizeChecker) -> EncodingResult<()> - { - f(self) - } - -} diff --git a/tests/test.rs b/tests/test.rs index 1474820..a9dd09f 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -4,61 +4,48 @@ extern crate serde_derive; extern crate bincode; -extern crate rustc_serialize; extern crate serde; use std::fmt::Debug; use std::collections::HashMap; use std::ops::Deref; -use rustc_serialize::{Encodable, Encoder, Decodable, Decoder}; - -use bincode::{RefBox, StrBox, SliceBox}; +use bincode::refbox::{RefBox, StrBox, SliceBox}; use bincode::SizeLimit::{self, Infinite, Bounded}; -use bincode::rustc_serialize::{encode, decode, decode_from, DecodingError}; -use bincode::serde::{serialize, deserialize, deserialize_from, DeserializeError, DeserializeResult}; +use bincode::{serialize, serialized_size, deserialize, deserialize_from, DeserializeError, DeserializeResult}; fn proxy_encode(element: &V, size_limit: SizeLimit) -> Vec - 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 = bincode::serde::serialize(element, size_limit).unwrap(); - assert_eq!(v1, v2); - - v1 + let v2 = serialize(element, size_limit).unwrap(); + v2 } fn proxy_decode(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 = bincode::serde::deserialize(slice).unwrap(); - - assert_eq!(e1, e2); - - e1 + let e2 = deserialize(slice).unwrap(); + e2 } fn proxy_encoded_size(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 = bincode::serde::serialized_size(element); - assert_eq!(ser_size, serde_size); - ser_size + let serde_size = serialized_size(element); + serde_size } fn the_same(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. fn ref_box_correct(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 encoded = bincode::rustc_serialize::encode(&rf, Infinite).unwrap(); - let decoded: RefBox<'static, V> = bincode::rustc_serialize::decode(&encoded[..]).unwrap(); + let encoded = serialize(&rf, Infinite).unwrap(); + let decoded: RefBox<'static, V> = deserialize(&encoded[..]).unwrap(); decoded.take().deref() == v } @@ -116,7 +103,7 @@ fn test_tuple() { #[test] fn test_basic_struct() { - #[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, PartialEq, Debug)] + #[derive(Serialize, Deserialize, PartialEq, Debug)] struct Easy { x: isize, s: String, @@ -127,13 +114,13 @@ fn test_basic_struct() { #[test] fn test_nested_struct() { - #[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, PartialEq, Debug)] + #[derive(Serialize, Deserialize, PartialEq, Debug)] struct Easy { x: isize, s: String, y: usize } - #[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, PartialEq, Debug)] + #[derive(Serialize, Deserialize, PartialEq, Debug)] struct Nest { f: Easy, b: usize, @@ -149,7 +136,7 @@ fn test_nested_struct() { #[test] fn test_struct_newtype() { - #[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, PartialEq, Debug)] + #[derive(Serialize, Deserialize, PartialEq, Debug)] struct NewtypeStr(usize); the_same(NewtypeStr(5)); @@ -157,7 +144,7 @@ fn test_struct_newtype() { #[test] fn test_struct_tuple() { - #[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, PartialEq, Debug)] + #[derive(Serialize, Deserialize, PartialEq, Debug)] struct TubStr(usize, String, f32); the_same(TubStr(5, "hello".to_string(), 3.2)); @@ -172,7 +159,7 @@ fn test_option() { #[test] fn test_enum() { - #[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, PartialEq, Debug)] + #[derive(Serialize, Deserialize, PartialEq, Debug)] enum TestEnum { NoArg, OneArg(usize), @@ -224,29 +211,6 @@ fn test_fixed_size_array() { the_same([0u8; 19]); } -#[test] -fn decoding_errors() { - fn isize_invalid_encoding(res: bincode::rustc_serialize::DecodingResult) { - 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::(&vec![0xA][..])); - isize_invalid_encoding(decode::(&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::(&vec![0, 0, 0, 5][..])); - isize_invalid_encoding(decode::>(&vec![5, 0][..])); -} - #[test] fn deserializing_errors() { fn isize_invalid_deserialize(res: DeserializeResult) { @@ -261,7 +225,7 @@ fn deserializing_errors() { isize_invalid_deserialize(deserialize::(&vec![0xA][..])); isize_invalid_deserialize(deserialize::(&vec![0, 0, 0, 0, 0, 0, 0, 1, 0xFF][..])); // Out-of-bounds variant - #[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, Debug)] + #[derive(Serialize, Deserialize, Debug)] enum Test { One, Two, @@ -270,17 +234,6 @@ fn deserializing_errors() { isize_invalid_deserialize(deserialize::>(&vec![5, 0][..])); } -#[test] -fn too_big_decode() { - let encoded = vec![0,0,0,3]; - let decoded: Result = decode_from(&mut &encoded[..], Bounded(3)); - assert!(decoded.is_err()); - - let encoded = vec![0,0,0,3]; - let decoded: Result = decode_from(&mut &encoded[..], Bounded(4)); - assert!(decoded.is_ok()); -} - #[test] fn too_big_deserialize() { 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 = decode_from(&mut &encoded[..], Bounded(1)); - assert!(decoded.is_ok()); - assert_eq!(decoded.unwrap(), 'A'); -} - #[test] fn too_big_char_deserialize() { let serialized = vec![0x41]; @@ -318,15 +263,6 @@ fn too_big_char_deserialize() { 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] fn too_big_serialize() { assert!(serialize(&0u32, Bounded(3)).is_err()); @@ -370,42 +306,6 @@ fn encode_box() { 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>), - M2(RefBox<'a, HashMap>) - } - - // 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] fn test_refbox_serialize() { let large_object = vec![1u32,2,3,4,5,6]; @@ -413,7 +313,7 @@ fn test_refbox_serialize() { large_map.insert(1, 2); - #[derive(RustcEncodable, RustcDecodable, Serialize, Deserialize, Debug)] + #[derive(Serialize, Deserialize, Debug)] enum Message<'a> { M1(RefBox<'a, Vec>), M2(RefBox<'a, HashMap>) @@ -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] fn test_strbox_serialize() { let strx: &'static str = "hello world"; @@ -460,19 +351,6 @@ fn test_strbox_serialize() { 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 = decoded.take(); - assert!(slice == &vecx[..]); -} - #[test] fn test_slicebox_serialize() { let slice = [1u32, 2, 3 ,4, 5]; @@ -486,20 +364,15 @@ fn test_slicebox_serialize() { assert!(slice == &vecx[..]); } -#[test] -fn test_multi_strings_encode() { - assert!(encode(&("foo", "bar", "baz"), Infinite).is_ok()); -} - #[test] fn test_multi_strings_serialize() { assert!(serialize(&("foo", "bar", "baz"), Infinite).is_ok()); } +/* #[test] fn test_oom_protection() { use std::io::Cursor; - #[derive(RustcEncodable, RustcDecodable)] struct FakeVec { len: u64, 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 y : Result, _> = bincode::rustc_serialize::decode_from(&mut Cursor::new(&x[..]), bincode::SizeLimit::Bounded(10)); assert!(y.is_err()); -} +}*/ #[test] fn path_buf() { use std::path::{Path, PathBuf}; let path = Path::new("foo").to_path_buf(); - let serde_encoded = bincode::serde::serialize(&path, Infinite).unwrap(); - let decoded: PathBuf = bincode::serde::deserialize(&serde_encoded).unwrap(); + let serde_encoded = serialize(&path, Infinite).unwrap(); + let decoded: PathBuf = deserialize(&serde_encoded).unwrap(); assert!(path.to_str() == decoded.to_str()); } #[test] 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; - 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); } -#[test] -fn test_manual_enum_encoding() { - #[derive(PartialEq)] - enum Enumeration { - Variant1, - Variant2 { val: u64 } - } - - impl Encodable for Enumeration { - fn encode(&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(s: &mut D) -> Result { - 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 }); -}