feat(domain): R4.5b/c serialiser, export driver, self-check, from_envelope; O2 parity suite
objects.rs (own minimal writer: numbered objects, streams, classic xref, pdf-lib's string forms; pdf-writer not used: every number spelt through numberToString, no f32), serialize.rs (catalog with names tree and AF, pages, 3 Type1 WinAnsi fonts, image XObjects with the DeviceGray SMask, Link annotations with hex ASCII URIs, Info with Producer/Creator Faunosteo, the Flate attachment with Params and Filespec), export.rs (checks → envelope as JSON.stringify(_, null, 2) → layout → file → self-check through the R4 reader; export_from_envelope). cargo pdf_serialize against the 14 R3 PDFs: content streams equal after resource-name resolution, image planes and SMasks equal, links equal, Info equal but Producer/Creator, attachment bytes equal (store path: values equal, D-R11 order); qpdf --check clean, pdfdetach lists the attachment, poppler 150 dpi 0 pixel differs on 14 runs; R4 PDF → Rust import = R3 PDF import, re-export from the envelope byte-identical; R4 output digests frozen in goldens/r4/pdf.*.sha256.
This commit is contained in:
1 parent
d7984449ed
commit
4d45de5745
21 files changed
+1381
-2
No files matched your search
@@ -0,0 +1,190 @@
|
||||
//! A minimal PDF object writer (R4.5): numbered objects, streams, a classic xref table and
|
||||
//! the trailer, with the string forms pdf-lib used (UTF-16BE hex with a BOM for text,
|
||||
//! literal dates `D:YYYYMMDDHHmmSSZ`, hex ASCII for URIs). pdf-writer was planned here; a
|
||||
//! writer of this size (the document holds a dozen object kinds) spells every number through
|
||||
//! `numberToString` and keeps the dictionaries under our control, so the B5 precision
|
||||
//! difference the plan allowed never arises and no dependency enters the module.
|
||||
|
||||
use super::content::number_to_string;
|
||||
|
||||
/// The bytes of one indirect object's body (a dictionary, or a stream with its dictionary).
|
||||
pub struct Objects {
|
||||
bodies: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// `n 0 R`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Ref(pub usize);
|
||||
|
||||
impl Ref {
|
||||
pub fn text(self) -> String {
|
||||
format!("{} 0 R", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Objects {
|
||||
pub fn new() -> Self {
|
||||
Self { bodies: Vec::new() }
|
||||
}
|
||||
|
||||
/// Reserves the next object number; its body comes later with [`Objects::set`].
|
||||
pub fn reserve(&mut self) -> Ref {
|
||||
self.bodies.push(Vec::new());
|
||||
Ref(self.bodies.len())
|
||||
}
|
||||
|
||||
pub fn set(&mut self, at: Ref, body: Vec<u8>) {
|
||||
if let Some(slot) = self.bodies.get_mut(at.0 - 1) {
|
||||
*slot = body;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add(&mut self, body: Vec<u8>) -> Ref {
|
||||
self.bodies.push(body);
|
||||
Ref(self.bodies.len())
|
||||
}
|
||||
|
||||
/// A stream object: the dictionary entries (without `/Length`) and the data.
|
||||
pub fn add_stream(&mut self, entries: &[(&str, String)], data: &[u8]) -> Ref {
|
||||
self.bodies.push(stream_body(entries, data));
|
||||
Ref(self.bodies.len())
|
||||
}
|
||||
|
||||
/// The whole file: header, objects in number order, xref, trailer.
|
||||
pub fn finish(self, root: Ref, info: Ref) -> Vec<u8> {
|
||||
let mut out =
|
||||
Vec::with_capacity(self.bodies.iter().map(|b| b.len() + 24).sum::<usize>() + 256);
|
||||
out.extend_from_slice(b"%PDF-1.7\n%\xE2\xE3\xCF\xD3\n\n");
|
||||
let mut offsets = Vec::with_capacity(self.bodies.len());
|
||||
for (i, body) in self.bodies.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
|
||||
out.extend_from_slice(body);
|
||||
out.extend_from_slice(b"\nendobj\n\n");
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(
|
||||
format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes(),
|
||||
);
|
||||
for offset in offsets {
|
||||
out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
let trailer = format!(
|
||||
"trailer\n<< /Size {} /Root {} /Info {} >>\nstartxref\n{xref}\n%%EOF\n",
|
||||
self.bodies.len() + 1,
|
||||
root.text(),
|
||||
info.text()
|
||||
);
|
||||
out.extend_from_slice(trailer.as_bytes());
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Objects {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn stream_body(entries: &[(&str, String)], data: &[u8]) -> Vec<u8> {
|
||||
let mut body = Vec::with_capacity(data.len() + 128);
|
||||
let mut head = String::from("<<");
|
||||
for (key, value) in entries {
|
||||
head.push_str(&format!(" /{key} {value}"));
|
||||
}
|
||||
head.push_str(&format!(" /Length {} >>\nstream\n", data.len()));
|
||||
body.extend_from_slice(head.as_bytes());
|
||||
body.extend_from_slice(data);
|
||||
body.extend_from_slice(b"\nendstream");
|
||||
body
|
||||
}
|
||||
|
||||
/// `<< /K v … >>` from entries already spelt as PDF syntax.
|
||||
pub fn dict(entries: &[(&str, String)]) -> String {
|
||||
let mut out = String::from("<<");
|
||||
for (key, value) in entries {
|
||||
out.push_str(&format!(" /{key} {value}"));
|
||||
}
|
||||
out.push_str(" >>");
|
||||
out
|
||||
}
|
||||
|
||||
/// A name object: `#xx` for the bytes a name cannot carry bare (`/application#2fjson`).
|
||||
pub fn name(text: &str) -> String {
|
||||
let mut out = String::from("/");
|
||||
for byte in text.bytes() {
|
||||
let bare = byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'+');
|
||||
if bare {
|
||||
out.push(char::from(byte));
|
||||
} else {
|
||||
out.push_str(&format!("#{byte:02x}"));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `PDFHexString.fromText`: UTF-16BE with a BOM, lowercase hex.
|
||||
pub fn hex_text(text: &str) -> String {
|
||||
let mut out = String::from("<feff");
|
||||
for unit in text.encode_utf16() {
|
||||
out.push_str(&format!("{unit:04x}"));
|
||||
}
|
||||
out.push('>');
|
||||
out
|
||||
}
|
||||
|
||||
/// The hex form of ASCII bytes, one byte per character (`linkAnnotation.ts` `asciiHexOf`).
|
||||
pub fn hex_ascii(text: &str) -> String {
|
||||
let mut out = String::from("<");
|
||||
for byte in text.bytes() {
|
||||
out.push_str(&format!("{byte:02x}"));
|
||||
}
|
||||
out.push('>');
|
||||
out
|
||||
}
|
||||
|
||||
/// A literal string, the three delimiters escaped (pdf-lib did not escape; a fixed ASCII
|
||||
/// name never needs it, the escape only guards the form).
|
||||
pub fn literal(text: &str) -> String {
|
||||
let mut out = String::from("(");
|
||||
for c in text.chars() {
|
||||
if matches!(c, '(' | ')' | '\\') {
|
||||
out.push('\\');
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
out.push(')');
|
||||
out
|
||||
}
|
||||
|
||||
/// An array of numbers in pdf-lib's spelling.
|
||||
pub fn numbers(values: &[f64]) -> String {
|
||||
let items: Vec<String> = values.iter().map(|v| number_to_string(*v)).collect();
|
||||
format!("[{}]", items.join(" "))
|
||||
}
|
||||
|
||||
/// `PDFString.fromDate`: `(D:YYYYMMDDHHmmSSZ)` from the UTC fields of an ISO timestamp
|
||||
/// (`YYYY-MM-DDTHH:MM:SS[.sss]Z`, what `Date.prototype.toISOString` writes); `None` when
|
||||
/// the text is not one.
|
||||
pub fn pdf_date(iso: &str) -> Option<String> {
|
||||
let bytes = iso.as_bytes();
|
||||
let digits = |range: std::ops::Range<usize>| {
|
||||
bytes
|
||||
.get(range.clone())
|
||||
.filter(|part| part.iter().all(u8::is_ascii_digit))
|
||||
.map(|_| &iso[range])
|
||||
};
|
||||
let (year, month, day) = (digits(0..4)?, digits(5..7)?, digits(8..10)?);
|
||||
let (hours, minutes, seconds) = (digits(11..13)?, digits(14..16)?, digits(17..19)?);
|
||||
let separators = bytes.get(4) == Some(&b'-')
|
||||
&& bytes.get(7) == Some(&b'-')
|
||||
&& bytes.get(10) == Some(&b'T')
|
||||
&& bytes.get(13) == Some(&b':')
|
||||
&& bytes.get(16) == Some(&b':');
|
||||
let tail = &iso[19..];
|
||||
let tail_ok = tail == "Z"
|
||||
|| (tail.starts_with('.')
|
||||
&& tail.ends_with('Z')
|
||||
&& tail[1..tail.len() - 1].bytes().all(|b| b.is_ascii_digit()));
|
||||
(separators && tail_ok).then(|| format!("(D:{year}{month}{day}{hours}{minutes}{seconds}Z)"))
|
||||
}
|
||||
Reference in new issue
Block a user