Debian Codegraph @

debian/rust-vendor/chacha20/src/variants.rs

raw
1 //! ChaCha variant-specific configurations.
2
3 mod sealed {
4 pub trait Sealed {}
5 }
6
7 /// A trait that distinguishes some ChaCha variants. Contains configurations
8 /// for "Legacy" DJB variant and the IETF variant.
9 pub trait Variant: sealed::Sealed {
10 /// The counter's type.
11 #[cfg(not(feature = "cipher"))]
12 type Counter: Copy;
13
14 /// The counter's type.
15 #[cfg(feature = "cipher")]
16 type Counter: cipher::StreamCipherCounter;
17
18 /// Takes a slice of `state[12..NONCE_INDEX]` to convert it into
19 /// `Self::Counter`.
20 fn get_block_pos(row: &[u32]) -> Self::Counter;
21
22 /// Breaks down the `Self::Counter` type into a u32 array for setting the
23 /// block pos.
24 fn set_block_pos(row: &mut [u32], pos: Self::Counter);
25
26 /// A helper method for calculating the remaining blocks using these types
27 fn remaining_blocks(block_pos: Self::Counter) -> Option<usize>;
28 }
29
30 /// IETF ChaCha configuration to use a 32-bit counter and 96-bit nonce.
31 #[derive(Clone, Copy, Debug)]
32 pub enum Ietf {}
33
34 impl sealed::Sealed for Ietf {}
35
36 impl Variant for Ietf {
37 type Counter = u32;
38
39 #[inline(always)]
40 fn get_block_pos(row: &[u32]) -> u32 {
41 row[0]
42 }
43
44 #[inline(always)]
45 fn set_block_pos(row: &mut [u32], pos: u32) {
46 row[0] = pos;
47 }
48
49 #[inline(always)]
50 fn remaining_blocks(block_pos: u32) -> Option<usize> {
51 let remaining = u32::MAX - block_pos;
52 remaining.try_into().ok()
53 }
54 }
55
56 /// DJB variant specific features: 64-bit counter and 64-bit nonce.
57 #[cfg(any(feature = "legacy", feature = "rng"))]
58 #[derive(Clone, Copy, Debug)]
59 pub enum Legacy {}
60
61 #[cfg(any(feature = "legacy", feature = "rng"))]
62 impl sealed::Sealed for Legacy {}
63
64 #[cfg(any(feature = "legacy", feature = "rng"))]
65 impl Variant for Legacy {
66 type Counter = u64;
67
68 #[inline(always)]
69 fn get_block_pos(row: &[u32]) -> u64 {
70 (u64::from(row[1]) << 32) | u64::from(row[0])
71 }
72
73 #[inline(always)]
74 fn set_block_pos(row: &mut [u32], pos: u64) {
75 row[0] = (pos & 0xFFFF_FFFF) as u32;
76 row[1] = (pos >> 32) as u32;
77 }
78
79 #[inline(always)]
80 fn remaining_blocks(block_pos: u64) -> Option<usize> {
81 let remaining = u64::MAX - block_pos;
82 remaining.try_into().ok()
83 }
84 }