Created
March 17, 2015 22:55
-
-
Save anonymous/dde703d5b9c5a856a39c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate cbor; | |
extern crate "rustc-serialize" as rustc_serialize; | |
use std::borrow::ToOwned; | |
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; | |
#[derive(Debug, Eq, PartialEq, RustcEncodable, RustcDecodable)] | |
struct NameType(Vec<u8>); | |
#[derive(Debug, PartialEq, Eq)] | |
struct CustomData { | |
name: NameType, | |
value: Vec<u8>, | |
} | |
impl Encodable for CustomData { | |
fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> { | |
cbor::CborTagEncode::new(5483_001, &(&self.name, &self.value)).encode(e) | |
} | |
} | |
impl Decodable for CustomData { | |
fn decode<D: Decoder>(d: &mut D) -> Result<CustomData, D::Error> { | |
try!(d.read_u64()); | |
let (name, value) = try!(Decodable::decode(d)); | |
Ok(CustomData { name: name, value: value }) | |
} | |
} | |
fn main() { | |
let obj_sent = CustomData { | |
name: NameType(b"hi".to_owned()), | |
value: vec![1, 2, 3, 4, 5], | |
}; | |
let mut e = cbor::Encoder::from_memory(); | |
e.encode(&[&obj_sent]).unwrap(); | |
let mut d = cbor::Decoder::from_bytes(e.as_bytes()); | |
let obj_got: CustomData = d.decode().next().unwrap().unwrap(); | |
assert_eq!(obj_sent, obj_got); | |
println!("{:?}", obj_got); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment