Skip to main content

junobuild_utils/with/
principal.rs

1use crate::serializers::types::JsonDataPrincipal;
2use candid::Principal;
3use serde::{Deserialize, Deserializer, Serialize, Serializer};
4
5pub fn serialize<S>(principal: &Principal, s: S) -> Result<S::Ok, S::Error>
6where
7    S: Serializer,
8{
9    JsonDataPrincipal { value: *principal }.serialize(s)
10}
11
12pub fn deserialize<'de, D>(deserializer: D) -> Result<Principal, D::Error>
13where
14    D: Deserializer<'de>,
15{
16    JsonDataPrincipal::deserialize(deserializer).map(|d| d.value)
17}
18
19#[cfg(test)]
20mod tests {
21    use candid::Principal;
22    use serde::{Deserialize, Serialize};
23    use serde_json;
24
25    #[derive(Serialize, Deserialize, PartialEq, Debug)]
26    struct TestStruct {
27        #[serde(with = "super")]
28        value: Principal,
29    }
30
31    fn p(txt: &str) -> Principal {
32        Principal::from_text(txt).expect("principal text should parse")
33    }
34
35    #[test]
36    fn serialize_principal() {
37        let s = TestStruct {
38            value: p("aaaaa-aa"),
39        };
40        let json = serde_json::to_string(&s).expect("serialize");
41        assert_eq!(json, r#"{"value":{"__principal__":"aaaaa-aa"}}"#);
42    }
43
44    #[test]
45    fn deserialize_principal() {
46        let json = r#"{"value":{"__principal__":"aaaaa-aa"}}"#;
47        let s: TestStruct = serde_json::from_str(json).expect("deserialize");
48        assert_eq!(s.value, p("aaaaa-aa"));
49    }
50
51    #[test]
52    fn round_trip() {
53        let original = TestStruct {
54            value: p("ryjl3-tyaaa-aaaaa-aaaba-cai"),
55        };
56        let json = serde_json::to_string(&original).unwrap();
57        let decoded: TestStruct = serde_json::from_str(&json).unwrap();
58        assert_eq!(decoded.value, original.value);
59    }
60}