ruma_events/secret_storage/key/
secret_encryption_algorithm_serde.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use serde::{de, Deserialize, Serialize};

use super::{
    CustomSecretEncryptionAlgorithm, SecretStorageEncryptionAlgorithm,
    SecretStorageV1AesHmacSha2Properties,
};

#[derive(Deserialize)]
#[serde(untagged)]
enum SecretStorageEncryptionAlgorithmDeHelper {
    Known(KnownSecretStorageEncryptionAlgorithmDeHelper),
    Unknown(CustomSecretEncryptionAlgorithm),
}

#[derive(Deserialize)]
#[serde(tag = "algorithm")]
enum KnownSecretStorageEncryptionAlgorithmDeHelper {
    #[serde(rename = "m.secret_storage.v1.aes-hmac-sha2")]
    V1AesHmacSha2(SecretStorageV1AesHmacSha2Properties),
}

impl<'de> Deserialize<'de> for SecretStorageEncryptionAlgorithm {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        let helper = SecretStorageEncryptionAlgorithmDeHelper::deserialize(deserializer)?;

        Ok(match helper {
            SecretStorageEncryptionAlgorithmDeHelper::Known(k) => match k {
                KnownSecretStorageEncryptionAlgorithmDeHelper::V1AesHmacSha2(p) => {
                    Self::V1AesHmacSha2(p)
                }
            },
            SecretStorageEncryptionAlgorithmDeHelper::Unknown(c) => Self::_Custom(c),
        })
    }
}

#[derive(Debug, Serialize)]
struct SecretStorageEncryptionAlgorithmSerHelper<'a, T: Serialize> {
    algorithm: &'a str,
    #[serde(flatten)]
    properties: T,
}

impl Serialize for SecretStorageEncryptionAlgorithm {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let algorithm = self.algorithm();
        match self {
            Self::V1AesHmacSha2(properties) => {
                SecretStorageEncryptionAlgorithmSerHelper { algorithm, properties }
                    .serialize(serializer)
            }
            Self::_Custom(properties) => {
                SecretStorageEncryptionAlgorithmSerHelper { algorithm, properties }
                    .serialize(serializer)
            }
        }
    }
}