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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
//! Sort an array of i32 elements in constant-time
/// If `a > b`, swap `a` and `b` in-place. Otherwise keep values.
/// Implements `(min(a, b), max(a, b))` in constant time.
const fn int32_minmax(mut a: i32, mut b: i32) -> (i32, i32) {
let ab: i32 = b ^ a;
let mut c: i32 = (!b & a) | ((!b | a) & (b.wrapping_sub(a)));
c ^= ab & (c ^ b);
c >>= 31;
c &= ab;
a ^= c;
b ^= c;
(a, b)
}
/// Sort a sequence of integers using a sorting network to achieve constant time.
/// To our understanding, this implements [djbsort](https://sorting.cr.yp.to/).
pub(crate) fn int32_sort(x: &mut [i32]) {
let n = x.len();
let (mut top, mut p, mut q, mut r, mut i): (usize, usize, usize, usize, usize);
if n < 2 {
return;
}
top = 1;
while top < n.wrapping_sub(top) {
top += top;
}
p = top;
while p > 0 {
i = 0;
while i < n - p {
if (i & p) == 0 {
let (tmp_xi, tmp_xip) = int32_minmax(x[i], x[i + p]);
x[i] = tmp_xi;
x[i + p] = tmp_xip;
}
i += 1;
}
i = 0;
q = top;
while q > p {
while i < n - q {
if (i & p) == 0 {
let mut a = x[i + p];
r = q;
while r > p {
let (tmp_a, tmp_xir) = int32_minmax(a, x[i + r]);
x[i + r] = tmp_xir;
a = tmp_a;
r >>= 1;
}
x[i + p] = a;
}
i += 1;
}
q >>= 1;
}
p >>= 1;
}
}
#[cfg(test)]
mod tests {
use super::*;
use rand::Rng;
fn gen_random_i32() -> i32 {
rand::thread_rng().gen::<i32>()
}
#[test]
fn test_int32_minmax() {
// basic test-case
let x: i32 = 45;
let y: i32 = -17;
// first parameter should become min
// second parameter should become max,
let (x, y) = int32_minmax(x, y);
assert_eq!(x, -17);
assert_eq!(y, 45);
//max value testcase
let x: i32 = i32::MAX;
let y: i32 = 2;
let (x, y) = int32_minmax(x, y);
assert_eq!(x, 2);
assert_eq!(y, 2147483647);
//min, max
let x: i32 = i32::MAX;
let y: i32 = i32::MIN;
let (x, y) = int32_minmax(x, y);
assert_eq!(x, -2147483648);
assert_eq!(y, 2147483647);
for _ in 0..=40 {
let x: i32 = gen_random_i32();
let y: i32 = gen_random_i32();
let (x, y) = int32_minmax(x, y);
if x > y {
println!(
"erroneous behaviour with inputs: x: 0x{:016X}i32 y: 0x{:016X}i32",
x, y
);
}
}
}
#[test]
fn test_int32_sort() {
let mut array: [i32; 64] = [0; 64];
for a in array.iter_mut() {
*a = gen_random_i32();
//println!("{}", array[i]);
}
int32_sort(&mut array[0..64]);
for i in 0..array.len() {
//println!("{}", array[i]);
if i >= 1 {
assert!(array[i] > array[i - 1]);
}
}
}
}