junobuild_utils/serializers/
principal.rs1use crate::serializers::types::DocDataPrincipal;
2use candid::Principal as CandidPrincipal;
3use serde::de::{self, MapAccess, Visitor};
4use serde::ser::SerializeStruct;
5use serde::{Deserialize, Deserializer, Serialize, Serializer};
6use std::fmt;
7
8impl Serialize for DocDataPrincipal {
9 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
10 where
11 S: Serializer,
12 {
13 let mut state = serializer.serialize_struct("DocDataPrincipal", 1)?;
14 state.serialize_field("__principal__", &self.value.to_string())?;
15 state.end()
16 }
17}
18
19impl<'de> Deserialize<'de> for DocDataPrincipal {
20 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
21 where
22 D: Deserializer<'de>,
23 {
24 deserializer.deserialize_struct(
25 "DocDataPrincipal",
26 &["__principal__"],
27 DocDataPrincipalVisitor,
28 )
29 }
30}
31
32struct DocDataPrincipalVisitor;
33
34impl<'de> Visitor<'de> for DocDataPrincipalVisitor {
35 type Value = DocDataPrincipal;
36
37 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
38 formatter.write_str("an object with a key __principal__")
39 }
40
41 fn visit_map<V>(self, mut map: V) -> Result<DocDataPrincipal, V::Error>
42 where
43 V: MapAccess<'de>,
44 {
45 let mut value = None;
46 while let Some(key) = map.next_key::<String>()? {
47 if key == "__principal__" {
48 if value.is_some() {
49 return Err(de::Error::duplicate_field("__principal__"));
50 }
51 value = Some(map.next_value::<String>()?);
52 }
53 }
54 let value_str = value.ok_or_else(|| de::Error::missing_field("__principal__"))?;
55 let principal = CandidPrincipal::from_text(value_str)
56 .map_err(|_| de::Error::custom("Invalid format for __principal__"))?;
57 Ok(DocDataPrincipal { value: principal })
58 }
59}