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
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
use std::fmt;

use derive_more::{Display, Error};
use rand::{thread_rng, RngCore};

use crate::utils::Base64DebugFmtHelper;

/// A compact representation of contact numbers.
#[derive(Default, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct TracingKey {
    bytes: [u8; 32],
}

impl fmt::Debug for TracingKey {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("TracingKey")
            .field(&Base64DebugFmtHelper(self))
            .finish()
    }
}

impl TracingKey {
    /// Returns a new unique tracing key.
    pub fn unique() -> TracingKey {
        let mut bytes = [0u8; 32];
        let mut rng = thread_rng();
        rng.fill_bytes(&mut bytes[..]);
        TracingKey::from_bytes(&bytes[..]).unwrap()
    }

    /// loads a tracing key from raw bytes.
    pub fn from_bytes(b: &[u8]) -> Result<TracingKey, InvalidTracingKey> {
        if b.len() != 32 {
            return Err(InvalidTracingKey);
        }
        let mut bytes = [0u8; 32];
        bytes.copy_from_slice(b);
        Ok(TracingKey { bytes })
    }

    /// Returns the bytes behind the tracing key.
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes
    }
}

/// Raised if a tracing key is invalid.
#[derive(Error, Display, Debug)]
#[display(fmt = "invalid tracing key")]
pub struct InvalidTracingKey;

#[cfg(feature = "base64")]
mod base64_impl {
    use super::*;
    use std::{fmt, str};

    impl str::FromStr for TracingKey {
        type Err = InvalidTracingKey;

        fn from_str(value: &str) -> Result<TracingKey, InvalidTracingKey> {
            let mut bytes = [0u8; 32];
            if value.len() != 43 {
                return Err(InvalidTracingKey);
            }
            base64_::decode_config_slice(value, base64_::URL_SAFE_NO_PAD, &mut bytes[..])
                .map_err(|_| InvalidTracingKey)?;
            Ok(TracingKey { bytes })
        }
    }

    impl fmt::Display for TracingKey {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            let mut buf = [0u8; 50];
            let len = base64_::encode_config_slice(self.bytes, base64_::URL_SAFE_NO_PAD, &mut buf);
            f.write_str(unsafe { std::str::from_utf8_unchecked(&buf[..len]) })
        }
    }
}

#[cfg(feature = "serde")]
mod serde_impl {
    use super::*;

    use serde_::de::Deserializer;
    use serde_::ser::Serializer;
    use serde_::{Deserialize, Serialize};

    impl Serialize for TracingKey {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            if serializer.is_human_readable() {
                serializer.serialize_str(&self.to_string())
            } else {
                serializer.serialize_bytes(self.as_bytes())
            }
        }
    }

    impl<'de> Deserialize<'de> for TracingKey {
        fn deserialize<D>(deserializer: D) -> Result<TracingKey, D::Error>
        where
            D: Deserializer<'de>,
        {
            use serde_::de::Error;
            if deserializer.is_human_readable() {
                let s = String::deserialize(deserializer).map_err(D::Error::custom)?;
                s.parse().map_err(D::Error::custom)
            } else {
                let buf = Vec::<u8>::deserialize(deserializer).map_err(D::Error::custom)?;
                TracingKey::from_bytes(&buf).map_err(D::Error::custom)
            }
        }
    }
}