ctbench_foo/
ctbench-foo.rs

1use dudect_bencher::{ctbench_main_with_seeds, BenchRng, Class, CtRunner};
2use rand::Rng;
3
4// Return a random vector of length len
5fn rand_vec(len: usize, rng: &mut BenchRng) -> Vec<u8> {
6    let mut arr = vec![0u8; len];
7    rng.fill(arr.as_mut_slice());
8    arr
9}
10
11// Benchmark for some random arithmetic operations. This should produce small t-values
12fn arith(runner: &mut CtRunner, rng: &mut BenchRng) {
13    let mut inputs = Vec::new();
14    let mut classes = Vec::new();
15
16    // Make 100,000 inputs on each run
17    for _ in 0..100_000 {
18        inputs.push(rng.gen::<usize>());
19        // Randomly pick which distribution this example belongs to
20        if rng.gen::<bool>() {
21            classes.push(Class::Left);
22        } else {
23            classes.push(Class::Right);
24        }
25    }
26
27    for (u, class) in inputs.into_iter().zip(classes.into_iter()) {
28        // Time some random arithmetic operations
29        runner.run_one(class, || ((u + 10) / 6) << 5);
30    }
31}
32
33// Benchmark for equality of vectors. This does an early return when it finds an inequality, so it
34// should be very much not constant-time
35fn vec_eq(runner: &mut CtRunner, rng: &mut BenchRng) {
36    // Make vectors of size 100
37    let vlen = 100;
38    let mut inputs: Vec<(Vec<u8>, Vec<u8>)> = Vec::new();
39    let mut classes = Vec::new();
40
41    // Make 100,000 random pairs of vectors
42    for _ in 0..100_000 {
43        // Flip a coin. If true, make a pair of vectors that are equal to each other and put it
44        // in the Left distribution
45        if rng.gen::<bool>() {
46            let v1 = rand_vec(vlen, rng);
47            let v2 = v1.clone();
48            inputs.push((v1, v2));
49            classes.push(Class::Left);
50        }
51        // Otherwise, make a pair of vectors that differ at the 6th element and put it in the
52        // right distribution
53        else {
54            let v1 = rand_vec(vlen, rng);
55            let mut v2 = v1.clone();
56            v2[5] = 7;
57            inputs.push((v1, v2));
58            classes.push(Class::Right);
59        }
60    }
61
62    for (class, (u, v)) in classes.into_iter().zip(inputs.into_iter()) {
63        // Now time how long it takes to do a vector comparison
64        runner.run_one(class, || u == v);
65    }
66}
67
68// Expand the main function to include benches for arith and vec_eq
69ctbench_main_with_seeds!((arith, Some(0x6b6c816d)), (vec_eq, None));
70// Alternatively, for no explicit seeds, you can use
71// ctbench_main!(arith, vec_eq);