wasmrs_codec/
messagepack.rs

1use serde::{Deserialize, Serialize};
2
3use crate::error::Error;
4use core::result::Result;
5extern crate alloc;
6use alloc::vec::Vec;
7
8#[doc(hidden)]
9pub fn mp_serialize<T>(item: &T) -> Result<Vec<u8>, rmp_serde::encode::Error>
10where
11  T: ?Sized + Serialize,
12{
13  let mut buf = Vec::new();
14  let mut serializer = rmp_serde::encode::Serializer::new(&mut buf)
15    .with_human_readable()
16    .with_struct_map();
17  item.serialize(&mut serializer)?;
18  Ok(buf)
19}
20
21/// The standard function for serializing codec structs into a format that can be.
22/// used for message exchange between actor and host. Use of any other function to.
23/// serialize could result in breaking incompatibilities.
24pub fn serialize<T>(item: &T) -> Result<Vec<u8>, crate::error::Error>
25where
26  T: ?Sized + Serialize,
27{
28  mp_serialize(item).map_err(Error::MsgPackEncode)
29}
30
31#[doc(hidden)]
32pub fn mp_deserialize<'de, T: Deserialize<'de>>(buf: &'de [u8]) -> Result<T, rmp_serde::decode::Error> {
33  rmp_serde::decode::from_slice(buf)
34}
35
36/// The standard function for de-serializing codec structs from a format suitable.
37/// for message exchange between actor and host. Use of any other function to.
38/// deserialize could result in breaking incompatibilities.
39pub fn deserialize<'de, T: Deserialize<'de>>(buf: &'de [u8]) -> Result<T, crate::error::Error> {
40  mp_deserialize(buf).map_err(Error::MsgPackDecode)
41}
42
43#[cfg(test)]
44mod test {
45  use super::*;
46  use bytes::Bytes;
47
48  #[test]
49  fn test_bytes() {
50    let bytes = b"\xc4\xf2PK\x03\x04\x14\0\0\0\x08\x000t\nA~\xe7\xffi$\0\0\0$\0\0\0\x06\0\0\0README\x0b\xc9\xc8,V(\xceM\xcc\xc9QH\xcb\xccIU\0\xf22\xf3\x14\xa2<\x03\xccL\x14\xd2\xf2\x8br\x13K\xf4\xb8\0PK\x01\x02-\x03-\0\0\0\x08\x000t\nA~\xe7\xffi\xff\xff\xff\xff\xff\xff\xff\xff\x06\0\x14\0\0\0\0\0\0\0\0\0\xa4\x81\0\0\0\0README\x01\0\x10\0$\0\0\0\0\0\0\0$\0\0\0\0\0\0\0PK\x06\x06,\0\0\0\0\0\0\0-\0-\0\0\0\0\0\0\0\0\0\x01\0\0\0\0\0\0\0\x01\0\0\0\0\0\0\0H\0\0\0\0\0\0\0H\0\0\0\0\0\0\0PK\x06\x07\0\0\0\0\x90\0\0\0\0\0\0\0\x01\0\0\0PK\x05\x06\0\0\0\0\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\0\0";
51    let v: Bytes = deserialize(bytes).unwrap();
52    assert_eq!(v, Bytes::from(&bytes[2..]));
53  }
54
55  #[test]
56  fn test_map() {
57    let bytes = b"\x81\xa6source\xa9zip64.zip";
58    let actual: serde_json::Value = deserialize(bytes).unwrap();
59    let expected = serde_json::json!({
60      "source": "zip64.zip"
61    });
62    assert_eq!(expected, actual);
63  }
64}