1#![cfg_attr(not(test), no_std)]
2extern crate alloc;
3use alloc::vec::Vec;
4use serde::{de::DeserializeOwned, Serialize};
5use purewasm_core::{Codec, PureError};
6
7pub struct JsonCodec;
8
9impl Codec for JsonCodec {
10 fn get_code(&self) -> i64 {
11 0x0200
12 }
13
14 fn to_bytes<T: Serialize>(&self, t: &T) -> Result<Vec<u8>, PureError> {
15 let r = serde_json::to_vec(t);
16 match r {
17 Ok(t) => Ok(t),
18 Err(_) => Err("JSON_SERIALIZE_ERROR".into()),
19 }
20 }
21
22 fn from_bytes<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, PureError> {
23 match serde_json::from_slice(bytes) {
24 Ok(t) => Ok(t),
25 Err(_) => Err("JSON_DESERIALIZE_ERROR".into()),
26 }
27 }
28}
29