-
Notifications
You must be signed in to change notification settings - Fork 130
/
primitives.rs
85 lines (64 loc) · 2.2 KB
/
primitives.rs
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
85
use core::ops::{Add, BitXor};
use cipher::{
generic_array::{ArrayLength, GenericArray},
typenum::{Diff, Prod, Quot, Sum, U1, U2, U4},
zeroize::DefaultIsZeroes,
};
pub type BlockSize<W> = Prod<<W as Word>::Bytes, U2>;
pub type Block<W> = GenericArray<u8, BlockSize<W>>;
pub type Key<B> = GenericArray<u8, B>;
pub type ExpandedKeyTable<W, R> = GenericArray<W, ExpandedKeyTableSize<R>>;
pub type ExpandedKeyTableSize<R> = Prod<Sum<R, U1>, U2>;
pub type KeyAsWords<W, B> = GenericArray<W, KeyAsWordsSize<W, B>>;
pub type KeyAsWordsSize<W, B> = Quot<Diff<Sum<B, <W as Word>::Bytes>, U1>, <W as Word>::Bytes>;
pub trait Word: Default + Copy + From<u8> + Add<Output = Self> + DefaultIsZeroes + Default {
type Bytes: ArrayLength<u8>;
const ZERO: Self;
const THREE: Self;
const EIGHT: Self;
const P: Self;
const Q: Self;
fn wrapping_add(self, rhs: Self) -> Self;
fn wrapping_sub(self, rhs: Self) -> Self;
fn rotate_left(self, n: Self) -> Self;
fn rotate_right(self, n: Self) -> Self;
fn from_le_bytes(bytes: &GenericArray<u8, Self::Bytes>) -> Self;
fn to_le_bytes(self) -> GenericArray<u8, Self::Bytes>;
fn bitxor(self, other: Self) -> Self;
}
impl Word for u32 {
type Bytes = U4;
const ZERO: Self = 0;
const THREE: Self = 3;
const EIGHT: Self = 8;
const P: Self = 0xb7e15163;
const Q: Self = 0x9e3779b9;
#[inline(always)]
fn wrapping_add(self, rhs: Self) -> Self {
u32::wrapping_add(self, rhs)
}
#[inline(always)]
fn wrapping_sub(self, rhs: Self) -> Self {
u32::wrapping_sub(self, rhs)
}
#[inline(always)]
fn rotate_left(self, n: Self) -> Self {
u32::rotate_left(self, n)
}
#[inline(always)]
fn rotate_right(self, n: Self) -> Self {
u32::rotate_right(self, n)
}
#[inline(always)]
fn from_le_bytes(bytes: &GenericArray<u8, Self::Bytes>) -> Self {
u32::from_le_bytes(bytes.as_slice().try_into().unwrap())
}
#[inline(always)]
fn to_le_bytes(self) -> GenericArray<u8, Self::Bytes> {
u32::to_le_bytes(self).into()
}
#[inline(always)]
fn bitxor(self, other: Self) -> Self {
<u32 as BitXor>::bitxor(self, other)
}
}