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
use std::rc::Rc;

use dcbor::{CBOREncodable, CBOR, CBORDecodable};

/// The HMAC authentication tag produced by the encryption process.
#[derive(Clone, Eq, PartialEq)]
pub struct AuthenticationTag([u8; Self::AUTHENTICATION_TAG_SIZE]);

impl AuthenticationTag {
    pub const AUTHENTICATION_TAG_SIZE: usize = 16;

    /// Restore an `AuthenticationTag` from a fixed-size array of bytes.
    pub const fn from_data(data: [u8; Self::AUTHENTICATION_TAG_SIZE]) -> Self {
        Self(data)
    }

    /// Restore an `AuthenticationTag` from a reference to an array of bytes.
    pub fn from_data_ref<T>(data: &T) -> Option<Self> where T: AsRef<[u8]> {
        let data = data.as_ref();
        if data.len() != Self::AUTHENTICATION_TAG_SIZE {
            return None;
        }
        let mut arr = [0u8; Self::AUTHENTICATION_TAG_SIZE];
        arr.copy_from_slice(data.as_ref());
        Some(Self::from_data(arr))
    }

    /// Get a reference to the fixed-size array of bytes.
    pub fn data(&self) -> &[u8; Self::AUTHENTICATION_TAG_SIZE] {
        self.into()
    }
}

impl std::fmt::Debug for AuthenticationTag {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("AuthenticationTag")
            .field(&hex::encode(self.data()))
            .finish()
    }
}

impl From<Rc<AuthenticationTag>> for AuthenticationTag {
    fn from(value: Rc<AuthenticationTag>) -> Self {
        (*value).clone()
    }
}

impl<'a> From<&'a AuthenticationTag> for &'a [u8; AuthenticationTag::AUTHENTICATION_TAG_SIZE] {
    fn from(value: &'a AuthenticationTag) -> Self {
        &value.0
    }
}

impl From<&[u8]> for AuthenticationTag {
    fn from(data: &[u8]) -> Self {
        Self::from_data_ref(&data).unwrap()
    }
}

impl From<[u8; Self::AUTHENTICATION_TAG_SIZE]> for AuthenticationTag {
    fn from(data: [u8; Self::AUTHENTICATION_TAG_SIZE]) -> Self {
        Self::from_data(data)
    }
}

impl From<Vec<u8>> for AuthenticationTag {
    fn from(data: Vec<u8>) -> Self {
        Self::from_data_ref(&data).unwrap()
    }
}

impl CBOREncodable for AuthenticationTag {
    fn cbor(&self) -> CBOR {
        CBOR::byte_string(self.data())
    }
}

impl CBORDecodable for AuthenticationTag {
    fn from_cbor(cbor: &CBOR) -> Result<Self, dcbor::Error> {
        let data = CBOR::expect_byte_string(cbor)?;
        let instance = Self::from_data_ref(&data).ok_or(dcbor::Error::InvalidFormat)?;
        Ok(instance)
    }
}