tracing_honeycomb/
deterministic_sampler.rs

1use sha1::{Digest, Sha1};
2
3use crate::TraceId;
4
5/// A port of beeline-nodejs's code for the same functionality.
6///
7/// Samples deterministically on a given TraceId via a SHA-1 hash.
8///
9/// https://github.com/honeycombio/beeline-nodejs/blob/main/lib/deterministic_sampler.js
10pub(crate) fn sample(sample_rate: u32, trace_id: &TraceId) -> bool {
11    let sum = Sha1::digest(trace_id.as_ref());
12    // Since we are operating on u32's in rust, there is no need for the original's `>>> 0`.
13    let upper_bound = std::u32::MAX / sample_rate;
14
15    u32::from_be_bytes([sum[0], sum[1], sum[2], sum[3]]) <= upper_bound
16}