openmls/
utils.rs

1// === The folowing functions aren't necessarily cryptographically secure!
2
3#[cfg(any(feature = "test-utils", test))]
4use rand::{rngs::OsRng, RngCore};
5
6#[cfg(any(feature = "test-utils", test))]
7pub fn random_u32() -> u32 {
8    OsRng.next_u32()
9}
10
11#[cfg(any(feature = "test-utils", test))]
12pub fn random_u64() -> u64 {
13    OsRng.next_u64()
14}
15
16#[cfg(any(feature = "test-utils", test))]
17pub fn random_u8() -> u8 {
18    let mut b = [0u8; 1];
19    OsRng.fill_bytes(&mut b);
20    b[0]
21}
22
23// With the crypto-debug feature enabled sensitive crypto parts can be logged.
24#[cfg(feature = "crypto-debug")]
25macro_rules! log_crypto {
26    (debug, $($arg:tt)*) => ({
27        log::debug!($($arg)*);
28    });
29    (trace, $($arg:tt)*) => ({
30        log::trace!($($arg)*);
31    })
32}
33
34// With the content-debug feature enabled sensitive message content parts can be logged.
35#[cfg(feature = "content-debug")]
36macro_rules! log_content {
37    (debug, $($arg:tt)*) => ({
38        log::debug!($($arg)*);
39    });
40    (trace, $($arg:tt)*) => ({
41        log::trace!($($arg)*);
42    })
43}
44
45#[cfg(not(feature = "crypto-debug"))]
46macro_rules! log_crypto {
47    (debug, $($arg:tt)*) => {{}};
48    (trace, $($arg:tt)*) => {{}};
49}
50
51#[cfg(not(feature = "content-debug"))]
52macro_rules! log_content {
53    (debug, $($arg:tt)*) => {{}};
54    (trace, $($arg:tt)*) => {{}};
55}
56
57/// Helper mod that converts a objects that implement FromIterator<_,_> (like a
58/// HashMap or a BTreeMap) into a vector of tuples and vice versa.
59pub mod vector_converter {
60    use serde::{Deserialize, Deserializer, Serialize, Serializer};
61
62    pub fn serialize<'a, T, K, V, S>(target: T, ser: S) -> Result<S::Ok, S::Error>
63    where
64        S: Serializer,
65        T: IntoIterator<Item = (&'a K, &'a V)>,
66        K: Serialize + 'a,
67        V: Serialize + 'a,
68    {
69        let container: Vec<_> = target.into_iter().collect();
70        serde::Serialize::serialize(&container, ser)
71    }
72
73    pub fn deserialize<'de, T, K, V, D>(des: D) -> Result<T, D::Error>
74    where
75        D: Deserializer<'de>,
76        T: FromIterator<(K, V)>,
77        K: Deserialize<'de>,
78        V: Deserialize<'de>,
79    {
80        let container: Vec<_> = serde::Deserialize::deserialize(des)?;
81        Ok(T::from_iter(container))
82    }
83}