hashx/register.rs
1//! Define HashX's register file, and how it's created and digested.
2
3use crate::siphash::{SipState, siphash24_ctr};
4use arrayvec::ArrayVec;
5use std::fmt;
6
7/// Number of virtual registers in the HashX machine
8pub(crate) const NUM_REGISTERS: usize = 8;
9
10/// Register `R5`
11///
12/// Most HashX registers have no special properties, so we don't even
13/// bother naming them. Register R5 is the exception, HashX defines a
14/// specific constraint there for the benefit of x86_64 code generation.
15pub(crate) const R5: RegisterId = RegisterId(5);
16
17/// Identify one register (R0 - R7) in HashX's virtual machine
18#[derive(Clone, Copy, Eq, PartialEq)]
19pub(crate) struct RegisterId(u8);
20
21impl fmt::Debug for RegisterId {
22 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23 write!(f, "R{}", self.0)
24 }
25}
26
27impl RegisterId {
28 /// Cast this RegisterId into a plain usize
29 #[inline(always)]
30 pub(crate) fn as_usize(&self) -> usize {
31 self.0 as usize
32 }
33
34 /// Return the underlying u8 for this RegisterId.
35 ///
36 /// (Recall that hashx has 8 virtual registers,
37 /// so the output of this method is always in range 0..=7.)
38 #[inline(always)]
39 pub(crate) fn as_u8(&self) -> u8 {
40 self.0
41 }
42
43 /// Create an iterator over all RegisterId
44 #[inline(always)]
45 pub(crate) fn all() -> impl Iterator<Item = RegisterId> {
46 (0_u8..(NUM_REGISTERS as u8)).map(RegisterId)
47 }
48}
49
50/// Identify a set of RegisterIds
51///
52/// This could be done compactly as a u8 bitfield for storage purposes, but
53/// in our program generator this is never stored long-term. Instead, we want
54/// something the optimizer can reason about as effectively as possible, and
55/// we want to optimize for an index() implementation that doesn't branch.
56/// This uses a fixed-capacity array of registers in-set, always sorted.
57#[derive(Default, Clone, Eq, PartialEq)]
58pub(crate) struct RegisterSet(ArrayVec<RegisterId, NUM_REGISTERS>);
59
60impl fmt::Debug for RegisterSet {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 write!(f, "[")?;
63 for n in 0..self.len() {
64 if n != 0 {
65 write!(f, ",")?;
66 }
67 self.index(n).fmt(f)?;
68 }
69 write!(f, "]")
70 }
71}
72
73impl RegisterSet {
74 /// Number of registers still contained in this set
75 #[inline(always)]
76 pub(crate) fn len(&self) -> usize {
77 self.0.len()
78 }
79
80 /// Test if a register is contained in the set.
81 #[inline(always)]
82 pub(crate) fn contains(&self, id: RegisterId) -> bool {
83 self.0.contains(&id)
84 }
85
86 /// Build a new RegisterSet from each register for which a predicate
87 /// function returns `true`.
88 #[inline(always)]
89 pub(crate) fn from_filter<P: FnMut(RegisterId) -> bool>(mut predicate: P) -> Self {
90 let mut result: Self = Default::default();
91 for r in RegisterId::all() {
92 if predicate(r) {
93 result.0.push(r);
94 }
95 }
96 result
97 }
98
99 /// Return a particular register within this set, counting from R0 to R7.
100 ///
101 /// The supplied index must be less than the [`Self::len()`] of this set.
102 /// Panics if the index is out of range.
103 #[inline(always)]
104 pub(crate) fn index(&self, index: usize) -> RegisterId {
105 self.0[index]
106 }
107}
108
109/// Values for all registers in the HashX machine
110///
111/// Guaranteed to have a `repr(C)` layout that includes each register in order
112/// with no padding and no extra fields. The compiled runtime will produce
113/// functions that read or write a `RegisterFile` directly.
114
115#[derive(Debug, Clone, Eq, PartialEq)]
116#[repr(C)]
117pub(crate) struct RegisterFile([u64; NUM_REGISTERS]);
118
119impl RegisterFile {
120 /// Load a word from the register file.
121 #[inline(always)]
122 pub(crate) fn load(&self, id: RegisterId) -> u64 {
123 self.0[id.as_usize()]
124 }
125
126 /// Store a word into the register file.
127 #[inline(always)]
128 pub(crate) fn store(&mut self, id: RegisterId, value: u64) {
129 self.0[id.as_usize()] = value;
130 }
131
132 /// Initialize a new HashX register file, given a key (derived from
133 /// the seed) and the user-specified hash input word.
134 #[inline(always)]
135 pub(crate) fn new(key: SipState, input: u64) -> Self {
136 RegisterFile(siphash24_ctr(key, input))
137 }
138
139 /// Finalize the state of the register file and generate up to 4 words of
140 /// output in HashX's final result format.
141 ///
142 /// This splits the register file into two halves, mixes in the siphash
143 /// keys again to "remove bias toward 0 caused by multiplications", and
144 /// runs one siphash round on each half before recombining them.
145 #[inline(always)]
146 pub(crate) fn digest(&self, key: SipState) -> [u64; 4] {
147 let mut x = SipState {
148 v0: self.0[0].wrapping_add(key.v0),
149 v1: self.0[1].wrapping_add(key.v1),
150 v2: self.0[2],
151 v3: self.0[3],
152 };
153 let mut y = SipState {
154 v0: self.0[4],
155 v1: self.0[5],
156 v2: self.0[6].wrapping_add(key.v2),
157 v3: self.0[7].wrapping_add(key.v3),
158 };
159 x.sip_round();
160 y.sip_round();
161 [x.v0 ^ y.v0, x.v1 ^ y.v1, x.v2 ^ y.v2, x.v3 ^ y.v3]
162 }
163}