use std::time::Duration;
use bcrypt_rust::{Version, bcrypt, bcrypt_many, hash_with_salt, verify};
use codspeed_criterion_compat::{Criterion, black_box, criterion_group, criterion_main};
const PASSWORD: &[u8] = b"correct horse battery staple";
const SALT: [u8; 16] = *b"codspeed-salt-16";
fn bench_single_hash(c: &mut Criterion) {
let mut group = c.benchmark_group("public/single_hash");
hash_with_salt(PASSWORD, 4, SALT).expect("warm-up hash");
group.bench_function("hash_with_salt_cost4", |b| {
b.iter(|| {
black_box(hash_with_salt(black_box(PASSWORD), 4, black_box(SALT)).expect("hash"));
});
});
group.finish();
}
fn bench_batch(c: &mut Criterion) {
let store: [&[u8]; 8] = [
b"alpha",
b"bravo",
b"charlie",
b"delta",
b"echo foxtrot",
b"golf hotel india",
b"juliett kilo lima mike",
b"november oscar papa quebec",
];
let salts: [[u8; 16]; 8] = core::array::from_fn(|i| {
let mut salt = SALT;
salt[0] = i as u8;
salt
});
let mut group = c.benchmark_group("public/batch");
bcrypt_many(4, &store, &salts).expect("warm-up batch");
group.bench_function("bcrypt_many_n8_cost4", |b| {
b.iter(|| {
black_box(bcrypt_many(4, black_box(&store), black_box(&salts)).expect("batch"));
});
});
group.finish();
}
fn bench_verify(c: &mut Criterion) {
let stored = hash_with_salt(PASSWORD, 4, SALT)
.expect("fixture hash")
.format_for_version(Version::TwoB);
verify(PASSWORD, &stored).expect("warm-up verify");
let mut group = c.benchmark_group("public/verify");
group.bench_function("verify_cost4", |b| {
b.iter(|| {
black_box(verify(black_box(PASSWORD), black_box(&stored)).expect("verify"));
});
});
group.finish();
}
fn bench_raw_core(c: &mut Criterion) {
let mut group = c.benchmark_group("core");
group.bench_function("bcrypt_cost4", |b| {
b.iter(|| {
black_box(bcrypt(4, black_box(SALT), black_box(PASSWORD)));
});
});
group.finish();
}
fn bench_base64(c: &mut Criterion) {
use bcrypt_rust::__internal::{decode_16, decode_23, encode_16, encode_23};
let hash_bytes = [0xA5u8; 23];
let enc16 = encode_16(&SALT);
let enc23 = encode_23(&hash_bytes);
let mut group = c.benchmark_group("base64");
group.bench_function("encode_16", |b| {
b.iter(|| black_box(encode_16(black_box(&SALT))));
});
group.bench_function("decode_16", |b| {
b.iter(|| black_box(decode_16(black_box(&enc16)).expect("decodes")));
});
group.bench_function("encode_23", |b| {
b.iter(|| black_box(encode_23(black_box(&hash_bytes))));
});
group.bench_function("decode_23", |b| {
b.iter(|| black_box(decode_23(black_box(&enc23)).expect("decodes")));
});
group.finish();
}
criterion_group! {
name = benches;
config = Criterion::default()
.sample_size(10)
.warm_up_time(Duration::from_secs(1))
.measurement_time(Duration::from_secs(2));
targets = bench_single_hash, bench_verify, bench_batch, bench_raw_core, bench_base64
}
criterion_main!(benches);