core_crypto_ffi/
ciphersuite.rs

1use core_crypto::prelude::{CiphersuiteName, MlsCiphersuite};
2#[cfg(target_family = "wasm")]
3use wasm_bindgen::prelude::*;
4
5use crate::{CoreCryptoError, CoreCryptoResult};
6
7#[derive(Debug, Clone, Copy, derive_more::From, derive_more::Into)]
8#[cfg_attr(target_family = "wasm", wasm_bindgen, derive(serde::Serialize, serde::Deserialize))]
9pub struct Ciphersuite(CiphersuiteName);
10
11#[cfg(not(target_family = "wasm"))]
12uniffi::custom_type!(Ciphersuite, u16, {
13    lower: |ciphersuite| (&ciphersuite.0).into(),
14    try_lift: |val| Ciphersuite::new(val).map_err(Into::into),
15});
16
17impl From<MlsCiphersuite> for Ciphersuite {
18    fn from(value: MlsCiphersuite) -> Self {
19        Self(value.into())
20    }
21}
22
23impl From<Ciphersuite> for MlsCiphersuite {
24    fn from(cs: Ciphersuite) -> Self {
25        cs.0.into()
26    }
27}
28
29#[cfg(target_family = "wasm")]
30#[wasm_bindgen]
31impl Ciphersuite {
32    pub fn as_u16(&self) -> u16 {
33        self.0.into()
34    }
35}
36
37#[cfg_attr(target_family = "wasm", wasm_bindgen)]
38impl Ciphersuite {
39    #[cfg_attr(target_family = "wasm", wasm_bindgen(constructor))]
40    pub fn new(discriminant: u16) -> CoreCryptoResult<Self> {
41        CiphersuiteName::try_from(discriminant)
42            .map(Into::into)
43            .map_err(CoreCryptoError::generic())
44    }
45}
46
47#[derive(Debug, Default, Clone, derive_more::From, derive_more::Into)]
48#[cfg_attr(target_family = "wasm", wasm_bindgen)]
49pub struct Ciphersuites(Vec<CiphersuiteName>);
50
51impl<'a> From<&'a Ciphersuites> for Vec<MlsCiphersuite> {
52    fn from(cs: &'a Ciphersuites) -> Self {
53        cs.0.iter().copied().map(Into::into).collect()
54    }
55}
56
57#[cfg(not(target_family = "wasm"))]
58uniffi::custom_type!(Ciphersuites, Vec<u16>, {
59    lower: |cs| cs.0.into_iter().map(|c| (&c).into()).collect(),
60    try_lift: |val| {
61        val.iter().try_fold(Ciphersuites(vec![]), |mut acc, c| -> uniffi::Result<Self> {
62            let cs = CiphersuiteName::try_from(*c)?;
63            acc.0.push(cs);
64            Ok(acc)
65        })
66    }
67});
68
69#[cfg(target_family = "wasm")]
70#[wasm_bindgen]
71impl Ciphersuites {
72    #[wasm_bindgen(constructor)]
73    pub fn from_u16s(ids: Vec<u16>) -> CoreCryptoResult<Self> {
74        let names = ids
75            .into_iter()
76            .map(CiphersuiteName::try_from)
77            .collect::<Result<Vec<_>, _>>()
78            .map_err(CoreCryptoError::generic())?;
79        Ok(Self(names))
80    }
81}