use std::fmt;
use std::panic;
use std::path::{Path, PathBuf};
use rust_j2k::{Error, Image};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Expected {
pub geometry: Geometry,
pub tolerance: Tolerance,
pub samples: Vec<i32>,
pub provenance: Provenance,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Geometry {
pub width: u32,
pub height: u32,
pub bit_depth: u8,
pub signed: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(tag = "mode", rename_all = "snake_case")]
pub enum Tolerance {
Exact,
Absolute { max_abs_error: f64 },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Provenance {
pub source: String,
pub oracle_command: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub notes: Option<String>,
}
impl Expected {
pub fn from_json(text: &str) -> serde_json::Result<Self> {
serde_json::from_str(text)
}
}
impl Geometry {
pub fn sample_count(self) -> usize {
self.width as usize * self.height as usize
}
}
#[derive(Debug)]
pub struct Fixture {
pub name: String,
pub codestream: PathBuf,
pub expected: Result<Expected, String>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Outcome {
Passed,
Pending,
Failed(Mismatch),
LoadError(String),
}
#[derive(Debug, Clone, PartialEq)]
pub enum Mismatch {
Geometry {
expected: Geometry,
actual: Geometry,
},
Sample {
index: usize,
x: u32,
y: u32,
expected: i32,
actual: i32,
bound: f64,
},
DecodeError(String),
}
impl fmt::Display for Mismatch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Mismatch::Geometry { expected, actual } => write!(
f,
"geometry mismatch: expected {}x{} (depth {}, signed {}), \
got {}x{} (depth {}, signed {})",
expected.width,
expected.height,
expected.bit_depth,
expected.signed,
actual.width,
actual.height,
actual.bit_depth,
actual.signed,
),
Mismatch::Sample {
index,
x,
y,
expected,
actual,
bound,
} => write!(
f,
"sample #{index} at ({x},{y}): expected {expected}, got {actual} \
(|diff| = {} exceeds bound {bound})",
(*actual as i64 - *expected as i64).abs(),
),
Mismatch::DecodeError(msg) => {
write!(f, "decoder rejected a known-good fixture: {msg}")
}
}
}
}
pub fn discover(dir: &Path) -> Vec<Fixture> {
let mut fixtures: Vec<Fixture> = match std::fs::read_dir(dir) {
Ok(entries) => entries
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.extension().is_some_and(|ext| ext == "j2k"))
.map(|codestream| {
let name = codestream
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("<non-utf8>")
.to_string();
let snapshot = codestream.with_extension("expected.json");
let expected = load_snapshot(&snapshot);
Fixture {
name,
codestream,
expected,
}
})
.collect(),
Err(_) => Vec::new(),
};
fixtures.sort_by(|a, b| a.name.cmp(&b.name));
fixtures
}
fn load_snapshot(path: &Path) -> Result<Expected, String> {
let text = std::fs::read_to_string(path)
.map_err(|e| format!("cannot read {}: {e}", path.display()))?;
let expected =
Expected::from_json(&text).map_err(|e| format!("cannot parse {}: {e}", path.display()))?;
let want = expected.geometry.sample_count();
if expected.samples.len() != want {
return Err(format!(
"malformed {}: geometry is {}x{} = {want} samples but the array has {}",
path.display(),
expected.geometry.width,
expected.geometry.height,
expected.samples.len(),
));
}
Ok(expected)
}
pub fn compare(actual: &Image, expected: &Expected) -> Result<(), Mismatch> {
let actual_geometry = Geometry {
width: actual.width,
height: actual.height,
bit_depth: actual.bit_depth,
signed: actual.signed,
};
if actual_geometry != expected.geometry {
return Err(Mismatch::Geometry {
expected: expected.geometry,
actual: actual_geometry,
});
}
let bound = match expected.tolerance {
Tolerance::Exact => 0.0,
Tolerance::Absolute { max_abs_error } => max_abs_error,
};
let width = expected.geometry.width;
for (index, (&got, &want)) in actual.samples.iter().zip(&expected.samples).enumerate() {
let diff = (got as i64 - want as i64).abs() as f64;
if diff > bound {
return Err(Mismatch::Sample {
index,
x: (index as u32) % width,
y: (index as u32) / width,
expected: want,
actual: got,
bound,
});
}
}
Ok(())
}
pub fn classify(
decoded: std::thread::Result<Result<Image, Error>>,
expected: &Expected,
) -> Outcome {
match decoded {
Err(_) => Outcome::Pending,
Ok(Ok(image)) => match compare(&image, expected) {
Ok(()) => Outcome::Passed,
Err(mismatch) => Outcome::Failed(mismatch),
},
Ok(Err(e)) => Outcome::Failed(Mismatch::DecodeError(e.to_string())),
}
}
pub fn run_fixture(fixture: &Fixture) -> Outcome {
let expected = match &fixture.expected {
Ok(expected) => expected,
Err(reason) => return Outcome::LoadError(reason.clone()),
};
let bytes = match std::fs::read(&fixture.codestream) {
Ok(bytes) => bytes,
Err(e) => {
return Outcome::LoadError(format!(
"cannot read {}: {e}",
fixture.codestream.display()
));
}
};
let decoded = panic::catch_unwind(panic::AssertUnwindSafe(|| rust_j2k::decode(&bytes)));
classify(decoded, expected)
}