1#![cfg_attr(not(test), no_std)]
2extern crate alloc;
3
4use alloc::vec::Vec;
5use purewasm_core::{Codec, PureError};
6use serde::{Serialize, de::DeserializeOwned};
7
8pub struct CborCodec;
9
10impl Codec for CborCodec {
11 fn get_code(&self) -> i64 {
12 0x51
13 }
14
15 fn to_bytes<T: Serialize>(&self, t: &T) -> Result<Vec<u8>, PureError> {
16 let mut bytes: Vec<u8> = Vec::new();
17 if let Err(_) = ciborium::into_writer(&t, &mut bytes) {
18 return Err("CBOR_SERIALIZE_ERROR".into());
19 }
20 Ok(bytes)
21 }
22
23 fn from_bytes<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, PureError> {
24 match ciborium::from_reader(bytes) {
25 Ok(t) => Ok(t),
26 Err(_) => Err("CBOR_DESERIALIZE_ERROR".into())
27 }
28 }
29}
30
31
32#[cfg(test)]
33mod tests {
34
35 use serde::Deserialize;
36
37 use super::*;
38 #[derive(Debug, Serialize, Deserialize)]
39 struct Input{ code: i32 }
40
41 #[derive(Debug, Serialize, Deserialize)]
42 struct ExampleResult{ msg: String }
43
44 #[test]
45 fn cbor_test(){
46 let codec = CborCodec;
47 let bytes = codec.to_bytes(&Input{code: 5}).unwrap();
48 let rbytes = codec.to_bytes(&ExampleResult{msg: "The input code is 5".to_owned()}).unwrap();
49 eprintln!("{:?}", bytes);
51 eprintln!("{:?}", rbytes);
52
53 }
54}
55