Debian Codegraph @

third_party/rust/neqo-common/benches/decoder.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 #![expect(clippy::unwrap_used, reason = "OK in a bench.")]
8
9 use std::{hint::black_box, time::Duration};
10
11 use criterion::{criterion_group, criterion_main, Criterion};
12 use neqo_common::Decoder;
13 use neqo_crypto::{init, randomize};
14
15 fn randomize_buffer(n: usize, mask: u8) -> Vec<u8> {
16 let mut buf = vec![0; n];
17 // NSS doesn't like randomizing larger buffers, so chunk them up.
18 // https://searchfox.org/nss/rev/968939484921b0ceecca189cd1b66e97950c39da/lib/freebl/drbg.c#29
19 for chunk in buf.chunks_mut(0x10000) {
20 randomize(chunk);
21 }
22 // Masking the top bits off causes the resulting values to be interpreted as
23 // smaller varints, which stresses the decoder differently.
24 // This is worth testing because most varints contain small values.
25 for x in &mut buf[..] {
26 *x &= mask;
27 }
28 buf
29 }
30
31 fn decoder(c: &mut Criterion, count: usize, mask: u8) {
32 c.bench_function(&format!("decode {count} bytes, mask {mask:x}"), |b| {
33 b.iter_batched_ref(
34 || randomize_buffer(count, mask),
35 |buf| {
36 let mut dec = Decoder::new(&buf[..]);
37 while black_box(dec.decode_varint()).is_some() {
38 // Do nothing;
39 }
40 },
41 criterion::BatchSize::SmallInput,
42 );
43 });
44 }
45
46 fn benchmark_decoder(c: &mut Criterion) {
47 init().unwrap();
48 for mask in [0xff, 0x7f, 0x3f] {
49 for exponent in [12, 20] {
50 decoder(c, 1 << exponent, mask);
51 }
52 }
53 }
54
55 criterion_group! {
56 name = benches;
57 config = Criterion::default().warm_up_time(Duration::from_secs(5)).measurement_time(Duration::from_secs(60));
58 targets = benchmark_decoder
59 }
60 criterion_main!(benches);