Skip to content

Commit 8f32ba3

Browse files
committed
refactor: compute the BIT_PAIRS_DIFF arrays at compile time.
Instead of using a mutable global array that is computed the first time it is used, compute the array at compile time.
1 parent 221dcf4 commit 8f32ba3

1 file changed

Lines changed: 26 additions & 34 deletions

File tree

lib/src/modules/elf/tlsh/helper.rs

Lines changed: 26 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,31 @@ pub(crate) const TOPVAL: [usize; 170] = [
5151

5252
const _MAX_DATA_LEN: usize = TOPVAL[TOPVAL.len() - 1];
5353

54-
static mut BIT_PAIRS_FLAG: bool = false;
55-
static mut BIT_PAIRS_DIFF: [[usize; 256]; 256] = [[0; 256]; 256];
54+
const fn compute_bit_pairs_diff() -> [[usize; 256]; 256] {
55+
let mut a = [[0; 256]; 256];
56+
57+
let mut i: i16 = 0;
58+
while i < 256 {
59+
let mut j: i16 = 0;
60+
while j < 256 {
61+
let (mut x, mut y, mut diff) = (i, j, 0);
62+
let mut k = 0;
63+
while k < 4 {
64+
let d = (x % 4 - y % 4).abs();
65+
diff += if d == 3 { 6 } else { d };
66+
x /= 4;
67+
y /= 4;
68+
k += 1;
69+
}
70+
a[i as usize][j as usize] = diff as usize;
71+
j += 1;
72+
}
73+
i += 1;
74+
}
75+
a
76+
}
77+
78+
const BIT_PAIRS_DIFF: [[usize; 256]; 256] = compute_bit_pairs_diff();
5679

5780
pub(crate) fn pearson_hash(salt: u8, ii: u8, jj: u8, kk: u8) -> u8 {
5881
let mut h = 0;
@@ -209,43 +232,12 @@ where
209232

210233
pub(crate) fn bit_distance(x: &[u8], y: &[u8]) -> usize {
211234
let mut result = 0;
212-
213235
for ii in 0..x.len() {
214-
unsafe {
215-
result += bit_pairs_diff(x[ii] as usize, y[ii] as usize);
216-
}
236+
result += BIT_PAIRS_DIFF[x[ii] as usize][y[ii] as usize];
217237
}
218-
219238
result
220239
}
221240

222-
#[inline]
223-
unsafe fn bit_pairs_diff(row: usize, col: usize) -> usize {
224-
let f = |x: &mut i16, y: &mut i16, diff: &mut i16| {
225-
let d = (*x % 4 - *y % 4).abs();
226-
*diff += if d == 3 { 6 } else { d };
227-
228-
*x /= 4;
229-
*y /= 4;
230-
};
231-
232-
if !BIT_PAIRS_FLAG {
233-
for ii in 0..256i16 {
234-
for jj in 0..256 {
235-
let (mut x, mut y, mut diff) = (ii, jj, 0);
236-
for _ in 0..4 {
237-
f(&mut x, &mut y, &mut diff);
238-
}
239-
240-
BIT_PAIRS_DIFF[ii as usize][jj as usize] = diff as usize;
241-
}
242-
}
243-
BIT_PAIRS_FLAG = true;
244-
}
245-
246-
BIT_PAIRS_DIFF[row][col]
247-
}
248-
249241
pub(crate) fn l_capturing(len: usize) -> Result<usize, TlshError> {
250242
let (mut top, mut bottom) = (TOPVAL.len(), 0);
251243
let mut idx = top >> 1;

0 commit comments

Comments
 (0)