use std::io::Read;
use std::fs::File;
pub struct Entropy {
pub byte_count: [u64; 256],
pub length: u64,
}
impl Entropy {
pub fn new(file: &File) -> Entropy {
let mut byte_count = [0u64; 256];
for byte in file.bytes() {
byte_count[byte.unwrap() as usize] += 1
}
Entropy {
byte_count: byte_count,
length: file.metadata().unwrap().len(),
}
}
pub fn shannon_entropy(&self) -> f32 {
let mut entropy = 0f32;
for &count in self.byte_count.iter() {
if count != 0 {
let symbol_probability = count as f32 / self.length as f32;
entropy += symbol_probability * symbol_probability.log2();
}
}
-entropy
}
pub fn metric_entropy(&self) -> f32 {
self.shannon_entropy() / 8f32
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::{Seek, SeekFrom, Write};
use tempfile::tempfile;
#[test]
fn test_new() {
let mut test_file = tempfile().unwrap();
test_file.write(&[0x00, 0x00, 0x01, 0x01, 0x02]).unwrap();
test_file.seek(SeekFrom::Start(0)).unwrap();
let test_entropy = Entropy::new(&test_file);
assert_eq!(test_entropy.byte_count[0], 2);
assert_eq!(test_entropy.byte_count[1], 2);
assert_eq!(test_entropy.byte_count[2], 1);
assert_eq!(test_entropy.length, 5);
}
#[test]
fn test_shannon_entropy() {
let mut test_file = tempfile().unwrap();
test_file.write(&[0x00, 0x00, 0x01, 0x01, 0x02]).unwrap();
test_file.seek(SeekFrom::Start(0)).unwrap();
let test_entropy = Entropy::new(&test_file);
let shannon_entropy = test_entropy.shannon_entropy();
assert_eq!(shannon_entropy, 1.5219281);
}
#[test]
fn test_metric_entropy() {
let mut test_file = tempfile().unwrap();
test_file.write(&[0x00, 0x00, 0x01, 0x01, 0x02]).unwrap();
test_file.seek(SeekFrom::Start(0)).unwrap();
let test_entropy = Entropy::new(&test_file);
let metric_entropy = test_entropy.metric_entropy();
assert_eq!(metric_entropy, 0.19024101);
}
}