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(
61 since = "1.6.0",
62 note = "Use `Nonce::assume_unique_for_key` with explicitly encoded bytes."
63)]
64impl From<&[u32; NONCE_LEN / 4]> for Nonce {
65 #[inline]
66 fn from(values: &[u32; NONCE_LEN / 4]) -> Self {
67 Nonce::from(&LittleEndian::<u32>::from_array(values))
68 }
69}
70
71impl From<&[BigEndian<u32>; NONCE_LEN / 4]> for Nonce {
72 #[inline]
73 fn from(values: &[BigEndian<u32>; NONCE_LEN / 4]) -> Self {
74 Nonce(FixedLength::from(values.as_byte_array()))
75 }
76}
77
78impl From<&[LittleEndian<u32>; NONCE_LEN / 4]> for Nonce {
79 #[inline]
80 fn from(nonce: &[LittleEndian<u32>; NONCE_LEN / 4]) -> Self {
81 Nonce(FixedLength::from(nonce.as_byte_array()))
82 }
83}
84
85impl From<BigEndian<u32>> for Nonce {
86 #[inline]
87 fn from(number: BigEndian<u32>) -> Self {
88 Nonce::from([BigEndian::ZERO, BigEndian::ZERO, number].as_byte_array())
89 }
90}
91
92pub const IV_LEN: usize = 16;
93impl From<&[u8; IV_LEN]> for Nonce {
94 #[inline]
95 fn from(bytes: &[u8; IV_LEN]) -> Self {
96 let mut nonce_bytes = [0u8; NONCE_LEN];
97 nonce_bytes.copy_from_slice(&bytes[0..NONCE_LEN]);
98 Nonce(FixedLength::from(nonce_bytes))
99 }
100}
101
102pub const NONCE_LEN: usize = 96 / 8;
104
105#[cfg(test)]
106mod tests {
107
108 #[test]
109 fn test_nonce_from_byte_array() {
110 use crate::aead::nonce::IV_LEN;
111 use crate::aead::Nonce;
112 let iv: [u8; IV_LEN] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
113 let nonce = Nonce::from(&iv);
114
115 assert_eq!(&[1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], nonce.as_ref());
116 }
117}