Skip to main content

junobuild_utils/with/
uint8array.rs

1use crate::serializers::types::JsonDataUint8Array;
2use serde::{Deserialize, Deserializer, Serialize, Serializer};
3
4pub fn serialize<S>(value: &[u8], s: S) -> Result<S::Ok, S::Error>
5where
6    S: Serializer,
7{
8    JsonDataUint8Array {
9        value: value.to_owned(),
10    }
11    .serialize(s)
12}
13
14pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
15where
16    D: Deserializer<'de>,
17{
18    JsonDataUint8Array::deserialize(deserializer).map(|d| d.value)
19}
20
21#[cfg(test)]
22mod tests {
23    use serde::{Deserialize, Serialize};
24    use serde_json;
25
26    #[derive(Serialize, Deserialize, PartialEq, Debug)]
27    struct TestStruct {
28        #[serde(with = "super")]
29        value: Vec<u8>,
30    }
31
32    #[test]
33    fn serialize_uint8array() {
34        let s = TestStruct {
35            value: vec![1, 2, 3],
36        };
37        let json = serde_json::to_string(&s).expect("serialize");
38        assert_eq!(json, r#"{"value":{"__uint8array__":[1,2,3]}}"#);
39    }
40
41    #[test]
42    fn deserialize_uint8array() {
43        let json = r#"{"value":{"__uint8array__":[1,2,3]}}"#;
44        let s: TestStruct = serde_json::from_str(json).expect("deserialize");
45        assert_eq!(s.value, vec![1, 2, 3]);
46    }
47
48    #[test]
49    fn round_trip() {
50        let original = TestStruct {
51            value: vec![0, 1, 2, 3, 255],
52        };
53        let json = serde_json::to_string(&original).unwrap();
54        let decoded: TestStruct = serde_json::from_str(&json).unwrap();
55        assert_eq!(decoded.value, original.value);
56    }
57}