Skip to main content

paas_client/
sessions.rs

1use base64::Engine;
2use base64::engine::general_purpose;
3use libpep::factors::EncryptionContext;
4use paas_api::status::SystemId;
5use serde::de::Error;
6use serde::{Deserialize, Deserializer, Serialize, Serializer};
7use std::collections::HashMap;
8
9#[derive(Debug, Clone)]
10pub struct EncryptionContexts(pub HashMap<SystemId, EncryptionContext>);
11impl EncryptionContexts {
12    pub fn get(&self, system_id: &SystemId) -> Option<&EncryptionContext> {
13        self.0.get(system_id)
14    }
15    pub fn encode(&self) -> String {
16        let json_string = serde_json::to_string(&self.0).unwrap();
17        general_purpose::URL_SAFE.encode(json_string)
18    }
19    pub fn decode(s: &str) -> Option<Self> {
20        let bytes = general_purpose::URL_SAFE.decode(s.as_bytes()).ok()?;
21        let json_string = String::from_utf8(bytes).ok()?;
22        let map: HashMap<String, EncryptionContext> = serde_json::from_str(&json_string).ok()?;
23        Some(Self(map))
24    }
25}
26
27impl Serialize for EncryptionContexts {
28    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
29        self.encode().serialize(serializer)
30    }
31}
32impl<'de> Deserialize<'de> for EncryptionContexts {
33    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
34    where
35        D: Deserializer<'de>,
36    {
37        let s = String::deserialize(deserializer)?;
38        Self::decode(&s).ok_or(Error::custom("Failed to decode EncryptionContexts"))
39    }
40}
41
42impl PartialEq for EncryptionContexts {
43    fn eq(&self, other: &Self) -> bool {
44        if self.0.len() != other.0.len() {
45            return false;
46        }
47
48        for (system_id, context) in &self.0 {
49            match other.0.get(system_id) {
50                Some(other_context) => {
51                    if context != other_context {
52                        return false;
53                    }
54                }
55                None => return false,
56            }
57        }
58
59        true
60    }
61}
62
63impl Eq for EncryptionContexts {}