fire_crypto/cipher/
nonce.rs1use crate::error::TryFromError;
2use crate::fill_random;
3
4use std::convert::{TryFrom, TryInto};
5
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct Nonce {
8 bytes: [u8; 24],
9}
10
11impl Nonce {
12 pub const LEN: usize = 24;
13
14 pub fn new() -> Self {
16 let mut this = Self { bytes: [0u8; 24] };
17 this.fill_random();
18 this
19 }
20
21 pub fn fill_random(&mut self) {
23 fill_random(&mut self.bytes);
24 }
25
26 #[cfg(test)]
27 pub fn ones() -> Self {
28 Self { bytes: [1u8; 24] }
29 }
30
31 pub fn from_slice(slice: &[u8]) -> Self {
34 slice.try_into().unwrap()
35 }
36
37 pub fn to_bytes(&self) -> [u8; 24] {
38 self.bytes
39 }
40
41 pub fn into_bytes(self) -> [u8; 24] {
43 self.bytes
44 }
45
46 pub fn take(&mut self) -> Self {
49 let n = Nonce::new();
50 std::mem::replace(self, n)
51 }
52}
53
54impl From<[u8; 24]> for Nonce {
55 fn from(bytes: [u8; 24]) -> Self {
57 Self { bytes }
58 }
59}
60
61impl TryFrom<&[u8]> for Nonce {
62 type Error = TryFromError;
63
64 fn try_from(s: &[u8]) -> Result<Self, Self::Error> {
65 <[u8; 24]>::try_from(s)
66 .map_err(TryFromError::from_any)
67 .map(Nonce::from)
68 }
69}
70
71impl AsRef<[u8]> for Nonce {
72 fn as_ref(&self) -> &[u8] {
73 &self.bytes
74 }
75}