ruma_events/secret_storage/key/
secret_encryption_algorithm_serde.rs

1use serde::{de, Deserialize, Serialize};
2
3use super::{
4    CustomSecretEncryptionAlgorithm, SecretStorageEncryptionAlgorithm,
5    SecretStorageV1AesHmacSha2Properties,
6};
7
8#[derive(Deserialize)]
9#[serde(untagged)]
10enum SecretStorageEncryptionAlgorithmDeHelper {
11    Known(KnownSecretStorageEncryptionAlgorithmDeHelper),
12    Unknown(CustomSecretEncryptionAlgorithm),
13}
14
15#[derive(Deserialize)]
16#[serde(tag = "algorithm")]
17enum KnownSecretStorageEncryptionAlgorithmDeHelper {
18    #[serde(rename = "m.secret_storage.v1.aes-hmac-sha2")]
19    V1AesHmacSha2(SecretStorageV1AesHmacSha2Properties),
20}
21
22impl<'de> Deserialize<'de> for SecretStorageEncryptionAlgorithm {
23    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
24    where
25        D: de::Deserializer<'de>,
26    {
27        let helper = SecretStorageEncryptionAlgorithmDeHelper::deserialize(deserializer)?;
28
29        Ok(match helper {
30            SecretStorageEncryptionAlgorithmDeHelper::Known(k) => match k {
31                KnownSecretStorageEncryptionAlgorithmDeHelper::V1AesHmacSha2(p) => {
32                    Self::V1AesHmacSha2(p)
33                }
34            },
35            SecretStorageEncryptionAlgorithmDeHelper::Unknown(c) => Self::_Custom(c),
36        })
37    }
38}
39
40#[derive(Debug, Serialize)]
41struct SecretStorageEncryptionAlgorithmSerHelper<'a, T: Serialize> {
42    algorithm: &'a str,
43    #[serde(flatten)]
44    properties: T,
45}
46
47impl Serialize for SecretStorageEncryptionAlgorithm {
48    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
49    where
50        S: serde::Serializer,
51    {
52        let algorithm = self.algorithm();
53        match self {
54            Self::V1AesHmacSha2(properties) => {
55                SecretStorageEncryptionAlgorithmSerHelper { algorithm, properties }
56                    .serialize(serializer)
57            }
58            Self::_Custom(properties) => {
59                SecretStorageEncryptionAlgorithmSerHelper { algorithm, properties }
60                    .serialize(serializer)
61            }
62        }
63    }
64}