7 releases (4 stable)

1.3.0 Apr 30, 2024
1.1.2 Jul 21, 2023
1.1.1 Sep 27, 2022
1.1.0 Apr 19, 2022
0.8.2 Nov 10, 2015

#9 in Encoding

Download history 218161/week @ 2024-01-26 230216/week @ 2024-02-02 250401/week @ 2024-02-09 227777/week @ 2024-02-16 270027/week @ 2024-02-23 278596/week @ 2024-03-01 241994/week @ 2024-03-08 252166/week @ 2024-03-15 247522/week @ 2024-03-22 270071/week @ 2024-03-29 237940/week @ 2024-04-05 261030/week @ 2024-04-12 266497/week @ 2024-04-19 253257/week @ 2024-04-26 229402/week @ 2024-05-03 208580/week @ 2024-05-10

1,004,015 downloads per month
Used in 1,341 crates (561 directly)

MIT license

195KB
4K SLoC

MessagePack + Serde

This crate connects Rust MessagePack library with serde providing an ability to easily serialize and deserialize both Rust built-in types, the standard library and custom data structures.

Motivating example

let buf = rmp_serde::to_vec(&(42, "the Answer")).unwrap();

assert_eq!(
    vec![0x92, 0x2a, 0xaa, 0x74, 0x68, 0x65, 0x20, 0x41, 0x6e, 0x73, 0x77, 0x65, 0x72],
    buf
);

assert_eq!((42, "the Answer"), rmp_serde::from_slice(&buf).unwrap());

Type-based Serialization and Deserialization

Serde provides a mechanism for low boilerplate serialization & deserialization of values to and from MessagePack via the serialization API.

To be able to serialize a piece of data, it must implement the serde::Serialize trait. To be able to deserialize a piece of data, it must implement the serde::Deserialize trait. Serde provides an annotation to automatically generate the code for these traits: #[derive(Serialize, Deserialize)].

Examples

use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use rmp_serde::{Deserializer, Serializer};

#[derive(Debug, PartialEq, Deserialize, Serialize)]
struct Human {
    age: u32,
    name: String,
}

fn main() {
    let mut buf = Vec::new();
    let val = Human {
        age: 42,
        name: "John".into(),
    };

    val.serialize(&mut Serializer::new(&mut buf)).unwrap();
}

Efficient storage of &[u8] types

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.

Wrap your data in serde_bytes to store blobs quickly and efficiently. Alternatively, configure an override in rmp_serde to force use of byte slices.

Dependencies

~295–620KB
~12K SLoC