Entropy Visualizer — Rust source
Visualize the randomness quality of any data. See Shannon entropy, byte frequency distribution, chi-squared score, and a visual entropy heatmap.
This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! entropy-visualizer — pure byte-level randomness analysis. std only.
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `entropy-visualizer` tool, ported from
//! src/lib/entropy-visualizer.ts (the canonical TypeScript implementation).
//!
//! Everything is deterministic: the same bytes always produce the same numbers.
//! std has no ln Γ, so the Lanczos approximation is ported verbatim to keep the
//! χ² p-value bit-comparable with the TypeScript original.
/// Bytes per heatmap block.
pub const BLOCK_SIZE: usize = 16;
/// Degrees of freedom for the byte-frequency χ² test (256 bins − 1 constraint).
pub const CHI_SQUARED_DF: f64 = 255.0;
/// Result bundle for [`analyze_entropy`] (mirrors the TS interface).
pub struct EntropyAnalysis {
/// Shannon entropy in bits per byte (0 = one repeating byte, 8 = perfectly uniform).
pub shannon_entropy: f64,
/// χ² statistic against the uniform 256-bin expectation.
pub chi_squared: f64,
/// Upper-tail p-value for χ² with 255 degrees of freedom.
pub chi_squared_p_value: f64,
/// Circular serial correlation between consecutive bytes (−1 … +1).
pub serial_correlation: f64,
/// Monte Carlo π estimate from consecutive byte pairs (≈3.14159 for random data).
pub monte_carlo_pi: f64,
/// Occurrence count per byte value 0-255 (always 256 entries).
pub byte_frequencies: [u64; 256],
/// Shannon entropy (bits/byte) of each BLOCK_SIZE-byte block, for the heatmap.
pub block_entropies: Vec<f64>,
/// Verdict label derived from the Shannon entropy.
pub verdict: &'static str,
}
/// Count occurrences of each byte value 0-255.
pub fn count_bytes(data: &[u8]) -> [u64; 256] {
let mut freq = [0u64; 256];
for &byte in data {
freq[byte as usize] += 1;
}
freq
}
/// Shannon entropy H = −Σ p·log₂p in bits/byte; zero-count bins contribute nothing.
pub fn shannon_bits_per_byte(frequencies: &[u64], total: u64) -> f64 {
if total == 0 {
return 0.0;
}
let mut h = 0.0;
for &count in frequencies {
if count == 0 {
continue;
}
let p = count as f64 / total as f64;
h -= p * p.log2();
}
h
}
/// Pearson χ² against the uniform expectation E = total/256 per bin.
///
/// Panics when `total` is 0, mirroring the TS lib's throw.
pub fn chi_squared_statistic(frequencies: &[u64], total: u64) -> f64 {
assert!(total > 0, "chi-squared needs a positive sample size");
let expected = total as f64 / 256.0;
let mut chi2 = 0.0;
for &observed in frequencies {
let diff = observed as f64 - expected;
chi2 += diff * diff / expected;
}
chi2
}
/// Lanczos approximation (g=7, 9 coefficients) of ln Γ(x); reflection below x<0.5.
fn ln_gamma(x: f64) -> f64 {
const G: [f64; 9] = [
0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7,
];
if x < 0.5 {
return (std::f64::consts::PI / (std::f64::consts::PI * x).sin()).ln() - ln_gamma(1.0 - x);
}
let x = x - 1.0;
let mut a = G[0];
let t = x + 7.5;
for i in 1..9 {
a += G[i] / (x + i as f64);
}
0.5 * (2.0 * std::f64::consts::PI).ln() + (x + 0.5) * t.ln() - t + a.ln()
}
/// Regularized upper incomplete gamma Q(a,x): power series below a+1, Lentz fraction above.
pub fn gamma_q(a: f64, x: f64) -> f64 {
if a <= 0.0 || x < 0.0 {
return f64::NAN;
}
if x == 0.0 {
return 1.0;
}
let prefix = (-x + a * x.ln() - ln_gamma(a)).exp();
if x < a + 1.0 {
// Series for P(a,x); Q = 1 − P.
let mut ap = a;
let mut sum = 1.0 / a;
let mut del = sum;
for _ in 0..1000 {
ap += 1.0;
del *= x / ap;
sum += del;
if del.abs() < sum.abs() * 1e-15 {
break;
}
}
(1.0 - sum * prefix).clamp(0.0, 1.0)
} else {
// Continued fraction (modified Lentz) for Q(a,x).
const FPMIN: f64 = 1e-300;
let mut b = x + 1.0 - a;
let mut c = 1.0 / FPMIN;
let mut d = 1.0 / b;
let mut h = d;
for i in 1..=1000 {
let an = -(i as f64) * (i as f64 - a);
b += 2.0;
d = an * d + b;
if d.abs() < FPMIN {
d = FPMIN;
}
c = b + an / c;
if c.abs() < FPMIN {
c = FPMIN;
}
d = 1.0 / d;
let del = d * c;
h *= del;
if (del - 1.0).abs() < 1e-15 {
break;
}
}
(prefix * h).clamp(0.0, 1.0)
}
}
/// Upper-tail p-value for a χ² statistic with `df` degrees of freedom.
pub fn chi_squared_p(chi2: f64, df: f64) -> f64 {
if chi2 < 0.0 || df <= 0.0 {
return f64::NAN;
}
gamma_q(df / 2.0, chi2 / 2.0)
}
/// Circular serial correlation of consecutive bytes (`ent` metric); 0 for n<2 or constant input.
pub fn serial_correlation_coefficient(data: &[u8]) -> f64 {
let n = data.len();
if n < 2 {
return 0.0;
}
let mut sum = 0f64;
let mut sum_sq = 0f64;
let mut sum_xy = 0f64;
for (i, &x) in data.iter().enumerate() {
let y = data[(i + 1) % n] as f64;
let x = x as f64;
sum += x;
sum_sq += x * x;
sum_xy += x * y;
}
let mean_sq = sum * sum / n as f64;
let denom = sum_sq - mean_sq;
if denom == 0.0 {
return 0.0;
}
(sum_xy - mean_sq) / denom
}
/// Monte Carlo π estimate: byte pairs as points in a 256×256 square, circle radius 128.
pub fn monte_carlo_pi_estimate(data: &[u8]) -> f64 {
let pairs = data.len() / 2;
if pairs == 0 {
return 0.0;
}
let mut inside = 0u64;
for i in 0..pairs {
let dx = data[2 * i] as f64 - 127.5;
let dy = data[2 * i + 1] as f64 - 127.5;
if dx * dx + dy * dy <= 128.0 * 128.0 {
inside += 1;
}
}
4.0 * inside as f64 / pairs as f64
}
/// Shannon entropy (bits/byte) of each consecutive `block_size`-byte block (heatmap data).
///
/// Panics when `block_size` is 0, mirroring the TS lib's throw.
pub fn block_entropies(data: &[u8], block_size: usize) -> Vec<f64> {
assert!(block_size >= 1, "blockSize must be at least 1");
data.chunks(block_size)
.map(|chunk| {
let counts = count_bytes(chunk);
shannon_bits_per_byte(&counts, chunk.len() as u64)
})
.collect()
}
/// Map a Shannon entropy (bits/byte) to the verdict scale.
pub fn verdict_from_shannon(bits_per_byte: f64) -> &'static str {
if bits_per_byte > 7.5 {
"excellent"
} else if bits_per_byte > 6.0 {
"good"
} else if bits_per_byte > 4.0 {
"suspicious"
} else {
"low"
}
}
/// Full analysis of a byte sequence; `Err` on empty input (the TS lib throws).
pub fn analyze_entropy(data: &[u8]) -> Result<EntropyAnalysis, String> {
if data.is_empty() {
return Err("Nothing to analyze - provide at least 1 byte of data.".to_string());
}
let total = data.len() as u64;
let freq = count_bytes(data);
let shannon = shannon_bits_per_byte(&freq, total);
let chi2 = chi_squared_statistic(&freq, total);
Ok(EntropyAnalysis {
shannon_entropy: shannon,
chi_squared: chi2,
chi_squared_p_value: chi_squared_p(chi2, CHI_SQUARED_DF),
serial_correlation: serial_correlation_coefficient(data),
monte_carlo_pi: monte_carlo_pi_estimate(data),
byte_frequencies: freq,
block_entropies: block_entropies(data, BLOCK_SIZE),
verdict: verdict_from_shannon(shannon),
})
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →