const MAX_SAMPLE: usize = 1_048_576;
#[must_use]
pub fn calculate_entropy(data: &[u8]) -> f64 {
let sample = if data.len() > MAX_SAMPLE {
&data[..MAX_SAMPLE]
} else {
data
};
let n = sample.len();
if n == 0 {
return 0.0;
}
let mut counts = [0u64; 256];
for &b in sample {
counts[b as usize] += 1;
}
#[allow(clippy::cast_precision_loss)]
let n_f64 = n as f64;
let mut entropy = 0.0_f64;
for &c in &counts {
if c == 0 {
continue;
}
#[allow(clippy::cast_precision_loss)]
let p = c as f64 / n_f64;
entropy -= p * p.log2();
}
entropy
}
pub const ENTROPY_THRESHOLD: f64 = 7.5;
#[must_use]
pub fn is_compressible(data: &[u8]) -> bool {
calculate_entropy(data) <= ENTROPY_THRESHOLD
}