trust_graph/
certificate_serde.rs

1/*
2 * Copyright 2020 Fluence Labs Limited
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use crate::Certificate;
18use serde::de::Error;
19use serde::{Deserialize, Deserializer, Serialize, Serializer};
20use std::str::FromStr;
21
22mod single {
23    #![allow(dead_code)]
24    use super::*;
25    pub fn serialize<S>(value: &Certificate, serializer: S) -> Result<S::Ok, S::Error>
26    where
27        S: Serializer,
28    {
29        value.to_string().serialize(serializer)
30    }
31
32    pub fn deserialize<'de, D>(deserializer: D) -> Result<Certificate, D::Error>
33    where
34        D: Deserializer<'de>,
35    {
36        let str = String::deserialize(deserializer)?;
37        Certificate::from_str(&str)
38            .map_err(|e| Error::custom(format!("certificate deserialization failed for {e:?}")))
39    }
40}
41
42pub mod vec {
43    use super::*;
44    use serde::ser::SerializeSeq;
45
46    pub fn serialize<S>(value: &[Certificate], serializer: S) -> Result<S::Ok, S::Error>
47    where
48        S: Serializer,
49    {
50        let mut seq = serializer.serialize_seq(Some(value.len()))?;
51        for e in value {
52            let e = e.to_string();
53            seq.serialize_element(&e)?;
54        }
55        seq.end()
56    }
57
58    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<Certificate>, D::Error>
59    where
60        D: Deserializer<'de>,
61    {
62        let v: Vec<String> = Vec::deserialize(deserializer)?;
63        v.into_iter()
64            .map(|e| {
65                Certificate::from_str(&e).map_err(|e| {
66                    Error::custom(format!("certificate deserialization failed for {e:?}"))
67                })
68            })
69            .collect()
70    }
71}