1use crate::endian::{ArrayEncoding, BigEndian, Encoding, FromArray, LittleEndian};
7use crate::error;
8use crate::iv::FixedLength;
9
10pub struct Nonce(pub(crate) FixedLength<NONCE_LEN>);
17
18impl Nonce {
19 #[inline]
26 pub fn try_assume_unique_for_key(value: &[u8]) -> Result<Self, error::Unspecified> {
27 Ok(Self(FixedLength::<NONCE_LEN>::try_from(value)?))
28 }
29
30 #[inline]
33 #[must_use]
34 pub fn assume_unique_for_key(value: [u8; NONCE_LEN]) -> Self {
35 Self(FixedLength::<NONCE_LEN>::from(value))
36 }
37}
38
39impl AsRef<[u8; NONCE_LEN]> for Nonce {
40 #[inline]
41 fn as_ref(&self) -> &[u8; NONCE_LEN] {
42 self.0.as_ref()
43 }
44}
45
46impl From<&[u8; NONCE_LEN]> for Nonce {
47 #[inline]
48 fn from(bytes: &[u8; NONCE_LEN]) -> Self {
49 Self(FixedLength::from(bytes))
50 }
51}
52
53#[allow(useless_deprecated)] #[deprecated]
55impl From<&[u32; NONCE_LEN / 4]> for Nonce {
56 #[inline]
57 fn from(values: &[u32; NONCE_LEN / 4]) -> Self {
58 Nonce::from(&LittleEndian::<u32>::from_array(values))
59 }
60}
61
62impl From<&[BigEndian<u32>; NONCE_LEN / 4]> for Nonce {
63 #[inline]
64 fn from(values: &[BigEndian<u32>; NONCE_LEN / 4]) -> Self {
65 Nonce(FixedLength::from(values.as_byte_array()))
66 }
67}
68
69impl From<&[LittleEndian<u32>; NONCE_LEN / 4]> for Nonce {
70 #[inline]
71 fn from(nonce: &[LittleEndian<u32>; NONCE_LEN / 4]) -> Self {
72 Nonce(FixedLength::from(nonce.as_byte_array()))
73 }
74}
75
76impl From<BigEndian<u32>> for Nonce {
77 #[inline]
78 fn from(number: BigEndian<u32>) -> Self {
79 Nonce::from([BigEndian::ZERO, BigEndian::ZERO, number].as_byte_array())
80 }
81}
82
83pub const IV_LEN: usize = 16;
84impl From<&[u8; IV_LEN]> for Nonce {
85 #[inline]
86 fn from(bytes: &[u8; IV_LEN]) -> Self {
87 let mut nonce_bytes = [0u8; NONCE_LEN];
88 nonce_bytes.copy_from_slice(&bytes[0..NONCE_LEN]);
89 Nonce(FixedLength::from(nonce_bytes))
90 }
91}
92
93pub const NONCE_LEN: usize = 96 / 8;
95
96#[cfg(test)]
97mod tests {
98
99 #[test]
100 fn test_nonce_from_byte_array() {
101 use crate::aead::nonce::IV_LEN;
102 use crate::aead::Nonce;
103 let iv: [u8; IV_LEN] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
104 let nonce = Nonce::from(&iv);
105
106 assert_eq!(&[1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], nonce.as_ref());
107 }
108}