cleaned up refbox implementation and added tests
This commit is contained in:
parent
3d8f97923d
commit
1d45873f1e
|
|
@ -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))
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
31
src/test.rs
31
src/test.rs
|
|
@ -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());
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
Loading…
Reference in New Issue