cleaned up refbox implementation and added tests

This commit is contained in:
Ty Overby 2015-05-02 12:23:27 -07:00
parent 3d8f97923d
commit 1d45873f1e
3 changed files with 36 additions and 22 deletions

View File

@ -218,30 +218,17 @@ impl <T: Decodable> Decodable for SliceBox<'static, T> {
impl <'a, A: Encodable + ?Sized, B: Encodable> Encodable for RefBoxInner<'a, A, B> {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_enum("RefBox", |s| {
s.emit_enum_variant("Box", 1, 1, |s| {
s.emit_enum_variant_arg(0, |s| {
match self {
&RefBoxInner::Ref(ref r) => r.encode(s),
&RefBoxInner::Box(ref b) => b.encode(s)
}
})
})
})
}
}
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> {
d.read_enum("RefBox", |d| {
d.read_enum_variant(&["Ref", "Box"], |d, i| {
assert!(i == 1);
d.read_enum_variant_arg(0, |d| {
let decoded = try!(Decodable::decode(d));
Ok(RefBoxInner::Box(decoded))
})
})
})
}
}

View File

@ -4,8 +4,17 @@ use std::ops::Deref;
use rustc_serialize::{Encoder, Decoder, Encodable, Decodable};
use super::{encode, decode, decode_from, encoded_size, DecodingError,
DecodingResult, RefBox};
use super::{
encode,
decode,
decode_from,
encoded_size,
DecodingError,
DecodingResult,
RefBox,
StrBox,
SliceBox,
};
use super::SizeLimit::{Infinite, Bounded};
@ -288,6 +297,24 @@ fn test_refbox() {
}
}
#[test]
fn test_strbox() {
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.0.take();
assert!(strx == &stringx[..]);
}
#[test]
fn test_slicebox() {
let slice = [1u32, 2, 3 ,4, 5];
let encoded = encode(&SliceBox::new(&slice), Infinite).unwrap();
let decoded: (SliceBox<'static, u32>, _) = decode(&encoded[..]).unwrap();
let vecx: Vec<u32> = decoded.0.take();
assert!(slice == &vecx[..]);
}
#[test]
fn test_multi_strings() {
assert!(encode(&("foo", "bar", "baz"), Infinite).is_ok());

View File

@ -21,7 +21,7 @@ pub enum EncodingError {
///
/// This error is returned before any bytes are written to the
/// output `Writer`.
SizeLimit
SizeLimit,
}
/// An Encoder that encodes values directly into a Writer.