serde_rmpv/lib.rs
1//! Serde integration for the rmpv MessagePack Value type.
2//!
3//! This crate handles all Serde data model types and includes special support for MessagePack's
4//! Ext type through the [`MSGPACK_EXT_STRUCT_NAME`] type annotation.
5
6mod de;
7mod error;
8mod ser;
9
10pub use error::Error;
11
12/// Name of the Serde newtype struct to represent MessagePack's Ext type
13///
14/// MessagePack Ext format: Ext(tag, binary)
15/// Serde data model: _ExtStruct((tag, binary))
16///
17/// # Example
18/// ```rust,ignore
19/// #[derive(Debug, PartialEq, Serialize, Deserialize)]
20/// #[serde(rename = "_ExtStruct")]
21/// struct ExtStruct((i8, Vec<u8>));
22/// ```
23pub const MSGPACK_EXT_STRUCT_NAME: &str = "_ExtStruct";
24
25/// Deserializes rmpv::Value into a target type.
26///
27/// # Errors
28/// Returns an error if:
29/// - Value cannot be deserialized into target type
30/// - Value contains unsupported or invalid data for target type
31pub fn from_value<'a, T>(s: &'a rmpv::Value) -> Result<T, Error>
32where
33 T: serde::de::Deserialize<'a>,
34{
35 de::from_value(s)
36}
37
38/// Serializes a type into rmpv::Value.
39///
40/// # Errors
41/// Returns an error if:
42/// - Value cannot be serialized
43/// - Value contains unsupported types
44pub fn to_value<T>(value: &T) -> Result<rmpv::Value, Error>
45where
46 T: serde::ser::Serialize,
47{
48 ser::to_value(value)
49}
50
51#[cfg(test)]
52mod tests {
53 use super::*;
54
55 use serde_derive::{Deserialize, Serialize};
56 use serde_with::{serde_as, Bytes};
57
58 #[test]
59 fn test_exttype_idemp() {
60 #[serde_as]
61 #[derive(Serialize, Deserialize, Debug, PartialEq)]
62 #[serde(rename = "_ExtStruct")]
63 struct Foo(#[serde_as(as = "(_, Bytes)")] (i8, Vec<u8>));
64
65 let f = Foo((42, vec![1, 2, 3]));
66 let val = to_value(&f).unwrap();
67 let f2 = from_value(&val).unwrap();
68 assert_eq!(f, f2);
69 }
70}