pub fn calculate_entropy(data: &[u8]) -> f64 {
if data.is_empty() {
return 0.0;
}
let mut byte_counts = [0usize; 256];
for &byte in data {
byte_counts[byte as usize] += 1;
}
let mut entropy: f64 = 0.0;
let total_bytes = data.len() as f64;
for &count in &byte_counts {
if count > 0 {
let probability = count as f64 / total_bytes;
entropy -= probability * probability.log2();
}
}
entropy
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_zero_entropy() {
let data = vec![0u8; 100];
assert_eq!(calculate_entropy(&data), 0.0);
}
#[test]
fn test_high_entropy() {
let mut data = Vec::with_capacity(256);
for i in 0..256 {
data.push(i as u8);
}
assert_eq!(calculate_entropy(&data), 8.0);
}
#[test]
fn test_empty_data() {
let data = vec![];
assert_eq!(calculate_entropy(&data), 0.0);
}
#[test]
fn test_partial_entropy() {
let data = vec![0u8, 1u8];
assert_eq!(calculate_entropy(&data), 1.0);
}
}