Debian Codegraph @

third_party/rust/rmp-serde/README.md

raw
1 # MessagePack + Serde
2
3 This crate connects Rust MessagePack library with [`serde`][serde] providing an ability to
4 easily serialize and deserialize both Rust built-in types, the standard library and custom data
5 structures.
6
7 ## Motivating example
8
9 ```rust
10 let buf = rmp_serde::to_vec(&(42, "the Answer")).unwrap();
11
12 assert_eq!(
13 vec![0x92, 0x2a, 0xaa, 0x74, 0x68, 0x65, 0x20, 0x41, 0x6e, 0x73, 0x77, 0x65, 0x72],
14 buf
15 );
16
17 assert_eq!((42, "the Answer"), rmp_serde::from_slice(&buf).unwrap());
18 ```
19
20 ## Type-based Serialization and Deserialization
21
22 Serde provides a mechanism for low boilerplate serialization & deserialization of values to and
23 from MessagePack via the serialization API.
24
25 To be able to serialize a piece of data, it must implement the `serde::Serialize` trait. To be
26 able to deserialize a piece of data, it must implement the `serde::Deserialize` trait. Serde
27 provides an annotation to automatically generate the code for these
28 traits: `#[derive(Serialize, Deserialize)]`.
29
30 ## Examples
31
32 ```rust
33 use std::collections::HashMap;
34 use serde::{Deserialize, Serialize};
35 use rmp_serde::{Deserializer, Serializer};
36
37 #[derive(Debug, PartialEq, Deserialize, Serialize)]
38 struct Human {
39 age: u32,
40 name: String,
41 }
42
43 fn main() {
44 let mut buf = Vec::new();
45 let val = Human {
46 age: 42,
47 name: "John".into(),
48 };
49
50 val.serialize(&mut Serializer::new(&mut buf)).unwrap();
51 }
52 ```
53
54 ## Efficient storage of `&[u8]` types
55
56 MessagePack can efficiently store binary data. However, Serde's standard derived implementations *do not* use binary representations by default. Serde prefers to represent types like `&[u8; N]` or `Vec<u8>` as arrays of objects of arbitrary/unknown type, and not as slices of bytes. This creates about a 50% overhead in storage size.
57
58 Wrap your data in [`serde_bytes`](https://lib.rs/crates/serde_bytes) to store blobs quickly and efficiently. Alternatively, [configure an override in `rmp_serde` to force use of byte slices](https://docs.rs/rmp-serde/latest/rmp_serde/encode/struct.Serializer.html#method.with_bytes).
59
60 [serde]: https://serde.rs/