rmp_serialize/
lib.rs

1//! ## Examples
2//!
3//! Let's try to encode a tuple of int and string.
4//!
5//! ```rust
6//! extern crate rmp_serialize;
7//! extern crate rustc_serialize;
8//!
9//! use rustc_serialize::Encodable;
10//! use rmp_serialize::Encoder;
11//!
12//! fn main() {
13//!     let val = (42u8, "the Answer");
14//!
15//!     // The encoder borrows the bytearray buffer.
16//!     let mut buf = [0u8; 13];
17//!
18//!     val.encode(&mut Encoder::new(&mut &mut buf[..]));
19//!
20//!     assert_eq!([0x92, 0x2a, 0xaa, 0x74, 0x68, 0x65, 0x20, 0x41, 0x6e, 0x73, 0x77, 0x65, 0x72], buf);
21//! }
22//! ```
23//!
24//! Now we have an encoded buffer, which we can decode the same way:
25//!
26//! ```rust
27//! extern crate rmp_serialize;
28//! extern crate rustc_serialize;
29//!
30//! use rustc_serialize::Decodable;
31//! use rmp_serialize::Decoder;
32//!
33//! fn main() {
34//!     let buf = [0x92, 0x2a, 0xaa, 0x74, 0x68, 0x65, 0x20, 0x41, 0x6e, 0x73, 0x77, 0x65, 0x72];
35//!
36//!     let mut decoder = Decoder::new(&buf[..]);
37//!
38//!     let res: (u8, String) = Decodable::decode(&mut decoder).unwrap();
39//!
40//!     assert_eq!((42u8, "the Answer".to_string()), res);
41//! }
42//! ```
43//!
44//! RMP also allows to automatically serialize/deserialize custom structures using rustc_serialize
45//! reflection. To enable this feature, derive RustcEncodable and RustcDecodable attributes as
46//! shown in the following example:
47//!
48//! ```rust
49//! extern crate rmp_serialize;
50//! extern crate rustc_serialize;
51//!
52//! use rustc_serialize::{Encodable, Decodable};
53//! use rmp_serialize::{Encoder, Decoder};
54//!
55//! #[derive(RustcEncodable, RustcDecodable, PartialEq, Debug)]
56//! struct Custom {
57//!     id: u32,
58//!     key: String,
59//! }
60//!
61//! fn main() {
62//!     let val = Custom { id: 42u32, key: "the Answer".to_string() };
63//!
64//!     let mut buf = [0u8; 13];
65//!
66//!     val.encode(&mut Encoder::new(&mut &mut buf[..]));
67//!
68//!     assert_eq!([0x92, 0x2a, 0xaa, 0x74, 0x68, 0x65, 0x20, 0x41, 0x6e, 0x73, 0x77, 0x65, 0x72], buf);
69//!
70//!     // Now try to unpack the buffer into the initial struct.
71//!     let mut decoder = Decoder::new(&buf[..]);
72//!     let res: Custom = Decodable::decode(&mut decoder).ok().unwrap();
73//!
74//!     assert_eq!(val, res);
75//! }
76//! ```
77
78extern crate rmp;
79extern crate rustc_serialize;
80
81pub mod decode;
82pub mod encode;
83
84pub use decode::Decoder;
85pub use encode::Encoder;