Skip to content

Commit e6acdfc

Browse files
authored
Merge pull request #2291 from CosmWasm/msgpack-examples
Add examples to from_msgpack, to_msgpack_vec and to_msgpack_binary
2 parents c5eb22d + 130f5a0 commit e6acdfc

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

packages/std/src/msgpack.rs

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,51 @@ use crate::{StdError, StdResult};
1212
/// Deserializes the given MessagePack bytes to a data structure.
1313
///
1414
/// Errors if the input is not valid MessagePack or cannot be deserialized to the given type.
15+
///
16+
/// ## Examples
17+
///
18+
/// Encoding and decoding an enum using MessagePack.
19+
///
20+
/// ```
21+
/// use cosmwasm_schema::cw_serde;
22+
/// use cosmwasm_std::{to_msgpack_binary, from_msgpack};
23+
///
24+
/// #[cw_serde]
25+
/// enum MyPacket {
26+
/// Cowsay {
27+
/// text: String,
28+
/// },
29+
/// }
30+
///
31+
/// let packet = MyPacket::Cowsay { text: "hi".to_string() };
32+
/// let encoded = to_msgpack_binary(&packet).unwrap();
33+
/// let decoded: MyPacket = from_msgpack(&encoded).unwrap();
34+
/// assert_eq!(decoded, packet);
1535
pub fn from_msgpack<T: DeserializeOwned>(value: impl AsRef<[u8]>) -> StdResult<T> {
1636
rmp_serde::from_read(value.as_ref()).map_err(|e| StdError::parse_err(type_name::<T>(), e))
1737
}
1838

1939
/// Serializes the given data structure as a MessagePack byte vector.
40+
///
41+
/// ## Examples
42+
///
43+
/// Encoding and decoding an enum using MessagePack.
44+
///
45+
/// ```
46+
/// use cosmwasm_schema::cw_serde;
47+
/// use cosmwasm_std::{to_msgpack_vec, from_msgpack};
48+
///
49+
/// #[cw_serde]
50+
/// enum MyPacket {
51+
/// Cowsay {
52+
/// text: String,
53+
/// },
54+
/// }
55+
///
56+
/// let packet = MyPacket::Cowsay { text: "hi".to_string() };
57+
/// let encoded = to_msgpack_vec(&packet).unwrap();
58+
/// let decoded: MyPacket = from_msgpack(&encoded).unwrap();
59+
/// assert_eq!(decoded, packet);
2060
pub fn to_msgpack_vec<T>(data: &T) -> StdResult<Vec<u8>>
2161
where
2262
T: Serialize + ?Sized,
@@ -25,6 +65,27 @@ where
2565
}
2666

2767
/// Serializes the given data structure as MessagePack bytes.
68+
///
69+
/// ## Examples
70+
///
71+
/// Encoding and decoding an enum using MessagePack.
72+
///
73+
/// ```
74+
/// use cosmwasm_schema::cw_serde;
75+
/// use cosmwasm_std::{to_msgpack_binary, from_msgpack};
76+
///
77+
/// #[cw_serde]
78+
/// enum MyPacket {
79+
/// Cowsay {
80+
/// text: String,
81+
/// },
82+
/// }
83+
///
84+
/// let packet = MyPacket::Cowsay { text: "hi".to_string() };
85+
/// let encoded = to_msgpack_binary(&packet).unwrap();
86+
/// let decoded: MyPacket = from_msgpack(&encoded).unwrap();
87+
/// assert_eq!(decoded, packet);
88+
/// ```
2889
pub fn to_msgpack_binary<T>(data: &T) -> StdResult<Binary>
2990
where
3091
T: Serialize + ?Sized,

0 commit comments

Comments
 (0)