119 lines
4.5 KiB
Rust
119 lines
4.5 KiB
Rust
//! R4 oracle plumbing shared by the reader suites: the frozen inputs under
|
|
//! `apps/app/tests/fixtures/pdf/r4/<dir>` (stored bytes, or a `<slug>.gen.json` description
|
|
//! expanded and checked against its length and digest) and the sha256 digests the TypeScript
|
|
//! generators recorded.
|
|
#![allow(
|
|
dead_code,
|
|
clippy::disallowed_methods,
|
|
clippy::unwrap_used,
|
|
clippy::expect_used
|
|
)]
|
|
|
|
use std::path::PathBuf;
|
|
|
|
use serde_json::Value;
|
|
use sha2::{Digest, Sha256};
|
|
|
|
/// Repository root (the workspace lives at `crates/core/../..`).
|
|
pub fn repo_root() -> PathBuf {
|
|
PathBuf::from(format!("{}/../..", env!("CARGO_MANIFEST_DIR")))
|
|
}
|
|
|
|
/// A frozen R4 oracle (`crates/core/tests/oracles/r4/<name>`), as plain serde_json.
|
|
pub fn r4_oracle(name: &str) -> Value {
|
|
let path = repo_root().join("crates/core/tests/oracles/r4").join(name);
|
|
let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{path:?}: {e}"));
|
|
serde_json::from_str(&text).unwrap_or_else(|e| panic!("{path:?}: {e}"))
|
|
}
|
|
|
|
/// Lower-case hex sha256 of `data`, the form every oracle stores.
|
|
pub fn sha256_hex(data: &[u8]) -> String {
|
|
let digest = Sha256::digest(data);
|
|
digest.iter().map(|b| format!("{b:02x}")).collect()
|
|
}
|
|
|
|
/// The bytes of input `file` of `dir` (`read`, `inflate`, `tolerance`): stored as is, or
|
|
/// expanded from `<slug>.gen.json` (`concat/1`: `latin1` text one byte per character, `fill`
|
|
/// a byte repeated, `slice` of another file of the directory), then checked against the
|
|
/// recorded `length` and `sha256`.
|
|
pub fn r4_input(dir: &str, file: &str) -> Vec<u8> {
|
|
let base = repo_root().join("apps/app/tests/fixtures/pdf/r4").join(dir);
|
|
let stored = base.join(file);
|
|
if stored.exists() && !file.ends_with(".gen.json") {
|
|
return std::fs::read(&stored).unwrap_or_else(|e| panic!("{stored:?}: {e}"));
|
|
}
|
|
// A generator row names its description (`<slug>.gen.json`); a stored name may also be
|
|
// asked for by its would-be byte name (`<slug>.pdf`).
|
|
let description = match file.strip_suffix(".gen.json") {
|
|
Some(_) => base.join(file),
|
|
None => base.join(format!(
|
|
"{}.gen.json",
|
|
file.rsplit_once('.').map_or(file, |(stem, _)| stem)
|
|
)),
|
|
};
|
|
let text = std::fs::read_to_string(&description)
|
|
.unwrap_or_else(|e| panic!("{description:?}: {e} (no stored bytes for {file})"));
|
|
let spec: Value = serde_json::from_str(&text).unwrap();
|
|
assert_eq!(spec["generator"], "concat/1", "{file}: unknown generator");
|
|
let bytes = expand_parts(spec["parts"].as_array().unwrap(), &base);
|
|
assert_eq!(
|
|
bytes.len() as u64,
|
|
spec["length"].as_u64().unwrap(),
|
|
"{file}: length"
|
|
);
|
|
assert_eq!(
|
|
sha256_hex(&bytes),
|
|
spec["sha256"].as_str().unwrap(),
|
|
"{file}: digest"
|
|
);
|
|
bytes
|
|
}
|
|
|
|
fn expand_parts(parts: &[Value], dir: &std::path::Path) -> Vec<u8> {
|
|
let mut out = Vec::new();
|
|
for part in parts {
|
|
if let Some(text) = part["latin1"].as_str() {
|
|
out.extend(text.chars().map(|c| u32::from(c) as u8));
|
|
} else if let Some(byte) = part["fill"].as_u64() {
|
|
let count = part["count"].as_u64().unwrap() as usize;
|
|
out.resize(out.len() + count, byte as u8);
|
|
} else if let Some(source) = part["slice"].as_str() {
|
|
let bytes = std::fs::read(dir.join(source)).unwrap();
|
|
let (start, end) = (
|
|
part["start"].as_u64().unwrap(),
|
|
part["end"].as_u64().unwrap(),
|
|
);
|
|
out.extend_from_slice(&bytes[start as usize..end as usize]);
|
|
} else {
|
|
panic!("unknown part {part}");
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// A Latin-1 string of the oracles (one character per byte) back to its bytes.
|
|
pub fn latin1_bytes(text: &str) -> Vec<u8> {
|
|
text.chars().map(|c| u32::from(c) as u8).collect()
|
|
}
|
|
|
|
/// An [`ImageSink`] for the layout oracles: keeps every PNG given, sized from its header,
|
|
/// so the O1 `pngSha256` per embed index can be checked without a PDF writer.
|
|
#[cfg(feature = "pdf-write")]
|
|
#[derive(Default)]
|
|
pub struct PngKeeper {
|
|
pub pngs: Vec<Vec<u8>>,
|
|
}
|
|
|
|
#[cfg(feature = "pdf-write")]
|
|
impl faunosteo_core::pdf::write::layout::ImageSink for PngKeeper {
|
|
fn embed(&mut self, png: &[u8]) -> Option<faunosteo_core::pdf::write::layout::Image> {
|
|
let (width, height) = faunosteo_core::pdf::write::layout::png::dimensions(png)?;
|
|
self.pngs.push(png.to_vec());
|
|
Some(faunosteo_core::pdf::write::layout::Image {
|
|
embed: self.pngs.len() - 1,
|
|
width,
|
|
height,
|
|
})
|
|
}
|
|
}
|