feat(domain): R4.5a content stream emitter: pdf-lib operator sequences and numberToString byte for byte

drawText/drawImage/drawLine/drawRectangle as pdf-lib 1.17.1 emits them (cleanText, 24 TL,
upper-case hex, the doubled m of drawLine, the h f of a filled rectangle); numberToString
with the e-N / e+N branches and V8's Math.pow(10, k) one-ULP quirk at k = 23 and 210;
WinAnsi text encoding. The 12 R3 PDFs' 60 content streams (224,534 bytes) equal the
emitter's output from the O1 logs with only the resource names renamed; 703 O4 cases.
This commit is contained in:
bchanot committed 2026-10-18 22:54:04 +02:00
1 parent 5dd4c26f18
commit d420f67352
2 files changed
+682 -2

No files matched your search

+316 -1
View File
@@ -1 +1,316 @@
//! R4.5a: the content stream emitter (pdf-lib operator sequences, `numberToString`). Written by the R4.5a track.
//! R4.5a: one page of the draw log as the bytes of its PDF content stream, operator for
//! operator what pdf-lib 1.17.1 wrote for the same calls (`api/PDFPage.js` → `api/operations.js`
//! → `api/operators.js`), number spelling included (`utils/numbers.js` `numberToString`).
//! Pinned against the content streams of the twelve R3 PDFs, whose calls the O1 logs carry.
//!
//! The resource names are ours, the serialiser declares them: fonts `/F1` Helvetica, `/F2`
//! Helvetica-Bold, `/F3` Times-Roman ([`font_resource_name`]), images `/Im<embed index>`
//! ([`image_resource_name`]). pdf-lib named a fresh `/Helvetica-<random>` or
//! `/Image-<random>` per call; the bytes are otherwise the same.
use super::afm_data;
use super::draw_log::{DrawOp, ImageOp, LineOp, PageLog, RectangleOp, Rgb, TextOp};
use super::text::Font;
use crate::json::js_number;
/// `PDFPage`'s default `lineHeight` (constructor, `api/PDFPage.js`): the `TL` of every text,
/// since the engine never passes one.
const DEFAULT_LINE_HEIGHT: f64 = 24.0;
/// `PDFPage`'s default `fontSize`: `drawText` uses `options.size || this.fontSize`.
const DEFAULT_FONT_SIZE: f64 = 24.0;
/// `drawRectangle`'s `options.borderWidth ?? 0` (`api/PDFPage.js`).
const DEFAULT_BORDER_WIDTH: f64 = 0.0;
/// The upright text matrix of `rotateAndSkewTextRadiansAndTranslate` (`api/operators.js`) for
/// pdf-lib's `degrees(0)` defaults: `cos 0`, `sin 0 + tan 0`, `-sin 0 + tan 0` (= +0), `cos 0`.
const UPRIGHT_TEXT: [f64; 4] = [1.0, 0.0, 0.0, 1.0];
/// `rotateRadians(0)` (`api/operators.js`): `cos 0, sin 0, -sin 0, cos 0, 0, 0`; the `-0`
/// prints `0`.
const ROTATE_ZERO: [f64; 6] = [1.0, 0.0, -0.0, 1.0, 0.0, 0.0];
/// `skewRadians(0, 0)` (`api/operators.js`): `1, tan 0, tan 0, 1, 0, 0`.
const SKEW_ZERO: [f64; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
/// The WinAnsi byte of `?`, what a code point outside the encoding prints.
const QUESTION_BYTE: u8 = b'?';
/// The powers of ten where V8's `Math.pow(10, k)` (its fdlibm `ieee754::pow`, Node 24 /
/// V8 13.6) is one ULP above the correctly rounded `1e<k>`: checked for every `k` in -330..=330.
const POW10_ONE_ULP_UP: [i32; 2] = [23, 210];
/// The `/Font` resource key of `font` on every page (without the `/` of the name syntax).
pub fn font_resource_name(font: Font) -> &'static str {
match font {
Font::Helvetica => "F1",
Font::HelveticaBold => "F2",
Font::TimesRoman => "F3",
}
}
/// The `/XObject` resource key of the image of embed index `embed` (without the `/`).
pub fn image_resource_name(embed: usize) -> String {
format!("Im{embed}")
}
/// The content stream of `page`, uncompressed: every call of the log in order, each as the
/// operators pdf-lib's `PDFPage.drawText` / `drawImage` / `drawLine` / `drawRectangle` pushed
/// with the options the engine passed and the defaults pdf-lib filled in.
pub fn page_content(page: &PageLog) -> Vec<u8> {
let mut content = Content::default();
for op in &page.ops {
match op {
DrawOp::Text(text) => draw_text(&mut content, text),
DrawOp::Image(image) => draw_image(&mut content, image),
DrawOp::Line(line) => draw_line(&mut content, line),
DrawOp::Rectangle(rectangle) => draw_rectangle(&mut content, rectangle),
}
}
content.bytes
}
/// `numberToString` (`utils/numbers.js`), the printer of every `PDFNumber` operand: the
/// JavaScript `String(num)`, except that an exponent form is spelt out in full, through the
/// same float arithmetic (`num * 10^(e-1)` below 1, `num / 10^(e-20)` above `1e21`).
pub fn number_to_string(value: f64) -> String {
let text = js_to_string(value);
if value.abs() < 1.0 {
spell_small(value, text)
} else {
spell_large(value, text)
}
}
/// The WinAnsi bytes of `text` (`StandardFontEmbedder.encodeTextAsGlyphs`,
/// `core/embedders/StandardFontEmbedder.js`, one glyph per code point); a code point the
/// encoding lacks, where pdf-lib would throw and `safeText` leaves none, prints `?`.
pub fn encode_text(text: &str) -> Vec<u8> {
text.chars()
.map(|c| winansi_byte(c).unwrap_or(QUESTION_BYTE))
.collect()
}
/// `Encodings.WinAnsi.encodeUnicodeCodePoint(c).code` from `afm_data::WINANSI`.
fn winansi_byte(c: char) -> Option<u8> {
let table = afm_data::WINANSI;
let index = table
.binary_search_by_key(&u32::from(c), |&(cp, _)| cp)
.ok()?;
table.get(index).map(|&(_, byte)| byte)
}
/// One content stream being written: `PDFContentStream.getUnencodedContents`
/// (`core/structures/PDFContentStream.js`) writes every operator followed by `\n`.
#[derive(Default)]
struct Content {
bytes: Vec<u8>,
}
impl Content {
/// `PDFOperator.copyBytesInto` (`core/operators/PDFOperator.js`): every operand followed by
/// one space, then the operator name.
fn op(&mut self, operands: &[&str], name: &str) {
for operand in operands {
self.bytes.extend_from_slice(operand.as_bytes());
self.bytes.push(b' ');
}
self.bytes.extend_from_slice(name.as_bytes());
self.bytes.push(b'\n');
}
/// An operator whose operands are all `PDFNumber`s (`asPDFNumber`, `api/objects.js`).
fn numbers(&mut self, values: &[f64], name: &str) {
let printed: Vec<String> = values.iter().map(|&v| number_to_string(v)).collect();
let operands: Vec<&str> = printed.iter().map(String::as_str).collect();
self.op(&operands, name);
}
}
/// `setFillingColor` → `setFillingRgbColor` (`api/colors.js`, `api/operators.js`): `r g b rg`.
fn set_filling_rgb(content: &mut Content, color: Rgb) {
content.numbers(&[color.red, color.green, color.blue], "rg");
}
/// `setStrokingColor` → `setStrokingRgbColor`: `r g b RG`.
fn set_stroking_rgb(content: &mut Content, color: Rgb) {
content.numbers(&[color.red, color.green, color.blue], "RG");
}
/// `setDashPattern([], 0)` (`api/operators.js`): the array is a pre-printed `"[]"` operand.
fn set_no_dash(content: &mut Content) {
content.op(&["[]", &number_to_string(0.0)], "d");
}
/// `translate(x, y)` = `concatTransformationMatrix(1, 0, 0, 1, x, y)`.
fn translate(content: &mut Content, x: f64, y: f64) {
content.numbers(&[1.0, 0.0, 0.0, 1.0, x, y], "cm");
}
/// `drawText` of `api/PDFPage.js`: `lineSplit(cleanText(text))`, each line `encodeText`-ed,
/// then `drawLinesOfText` (`api/operations.js`): `q BT rg Tf TL Tm`, `Tj T*` per line, `ET Q`.
fn draw_text(content: &mut Content, op: &TextOp) {
let font = format!("/{}", font_resource_name(op.font));
let [a, b, c, d] = UPRIGHT_TEXT;
content.op(&[], "q");
content.op(&[], "BT");
set_filling_rgb(content, op.color);
content.op(&[&font, &number_to_string(font_size(op.size))], "Tf");
content.numbers(&[DEFAULT_LINE_HEIGHT], "TL");
content.numbers(&[a, b, c, d, op.x, op.y], "Tm");
for line in line_split(&clean_text(&op.text)) {
content.op(&[&hex_string(&encode_text(line))], "Tj");
content.op(&[], "T*");
}
content.op(&[], "ET");
content.op(&[], "Q");
}
/// `options.size || this.fontSize`: a falsy size (`0`, `-0`, `NaN`) falls back to 24.
fn font_size(size: f64) -> f64 {
if size == 0.0 || size.is_nan() {
DEFAULT_FONT_SIZE
} else {
size
}
}
/// `cleanText` (`utils/strings.js`): tab, U+0085, U+2028 and U+2029 become four spaces, then
/// backspace and vertical tab are removed.
fn clean_text(text: &str) -> String {
let mut clean = String::with_capacity(text.len());
for c in text.chars() {
match c {
'\t' | '\u{85}' | '\u{2028}' | '\u{2029}' => clean.push_str(" "),
'\u{8}' | '\u{B}' => {}
other => clean.push(other),
}
}
clean
}
/// `lineSplit` (`utils/strings.js`): `text.split(/[\n\f\r\u000B]/)`, empty pieces kept.
fn line_split(text: &str) -> impl Iterator<Item = &str> {
text.split(['\n', '\u{C}', '\r', '\u{B}'])
}
/// `PDFHexString.copyBytesInto` (`core/objects/PDFHexString.js`) of the value `encodeText`
/// builds: `<`, two upper-case hex digits per glyph code (`toHexString`), `>`.
fn hex_string(bytes: &[u8]) -> String {
let mut hex = String::with_capacity(bytes.len() * 2 + 2);
hex.push('<');
for byte in bytes {
hex.push_str(&format!("{byte:02X}"));
}
hex.push('>');
hex
}
/// `drawImage` (`api/PDFPage.js` → `api/operations.js`): `q`, translate, `rotateRadians(0)`,
/// `scale(width, height)`, `skewRadians(0, 0)`, `/Im<k> Do`, `Q`.
fn draw_image(content: &mut Content, op: &ImageOp) {
let name = format!("/{}", image_resource_name(op.embed));
content.op(&[], "q");
translate(content, op.x, op.y);
content.numbers(&ROTATE_ZERO, "cm");
content.numbers(&[op.width, 0.0, 0.0, op.height, 0.0, 0.0], "cm");
content.numbers(&SKEW_ZERO, "cm");
content.op(&[&name], "Do");
content.op(&[], "Q");
}
/// `drawLine` (`api/PDFPage.js` → `api/operations.js`): `q RG w`, no dash, the start point
/// moved to twice (pdf-lib's `moveTo` stands on both sides of the absent `lineCap`), `l S Q`.
fn draw_line(content: &mut Content, op: &LineOp) {
content.op(&[], "q");
set_stroking_rgb(content, op.color);
content.numbers(&[op.thickness], "w");
set_no_dash(content);
content.numbers(&[op.start.x, op.start.y], "m");
content.numbers(&[op.start.x, op.start.y], "m");
content.numbers(&[op.end.x, op.end.y], "l");
content.op(&[], "S");
content.op(&[], "Q");
}
/// `drawRectangle` (`api/PDFPage.js` → `api/operations.js`): `q rg`, border width 0, no dash,
/// translate, `rotateRadians(0)`, `skewRadians(0, 0)`, the path from the origin, `h`, then `f`
/// (a colour with a falsy border width fills only), `Q`.
fn draw_rectangle(content: &mut Content, op: &RectangleOp) {
content.op(&[], "q");
set_filling_rgb(content, op.color);
content.numbers(&[DEFAULT_BORDER_WIDTH], "w");
set_no_dash(content);
translate(content, op.x, op.y);
content.numbers(&ROTATE_ZERO, "cm");
content.numbers(&SKEW_ZERO, "cm");
content.numbers(&[0.0, 0.0], "m");
content.numbers(&[0.0, op.height], "l");
content.numbers(&[op.width, op.height], "l");
content.numbers(&[op.width, 0.0], "l");
content.op(&[], "h");
content.op(&[], "f");
content.op(&[], "Q");
}
/// JavaScript `String(num)`: [`js_number`] for a finite value, `NaN` / `Infinity` otherwise.
fn js_to_string(value: f64) -> String {
if value.is_nan() {
"NaN".to_owned()
} else if value.is_infinite() {
let sign = if value < 0.0 { "-" } else { "" };
format!("{sign}Infinity")
} else {
js_number(value)
}
}
/// `parseInt(text.split(separator)[1])` on a JavaScript number's spelling: the digits after
/// the exponent separator, `None` (NaN) when there is none.
fn exponent_after(text: &str, separator: &str) -> Option<i32> {
let (_, rest) = text.split_once(separator)?;
let end = rest
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(rest.len());
rest.get(..end)?.parse().ok()
}
/// The `Math.abs(num) < 1` branch: `e` from `e-`, then `'0.' + (e - 1) zeros +
/// String(|num| * 10^(e-1)).substring(2)`, signed back.
fn spell_small(value: f64, text: String) -> String {
let Some(e) = exponent_after(&text, "e-").filter(|&e| e != 0) else {
return text;
};
let negative = value < 0.0;
let magnitude = if negative { -value } else { value };
let scaled = js_to_string(magnitude * js_pow10(e - 1));
let zeros = "0".repeat(usize::try_from(e - 1).unwrap_or(0));
let sign = if negative { "-" } else { "" };
format!("{sign}0.{zeros}{}", scaled.get(2..).unwrap_or(""))
}
/// The other branch: an exponent `e` above 20 (from `e+`) divides by `10^(e-20)` and appends
/// `e - 20` zeros to the quotient's `String`.
fn spell_large(value: f64, text: String) -> String {
match exponent_after(&text, "+") {
Some(e) if e > 20 => {
let shift = e - 20;
let quotient = js_to_string(value / js_pow10(shift));
let zeros = "0".repeat(usize::try_from(shift).unwrap_or(0));
format!("{quotient}{zeros}")
}
_ => text,
}
}
/// V8's `Math.pow(10, k)`: the correctly rounded `1e<k>` (`Infinity` past the range), one ULP
/// up at the two exponents where V8's pow is ([`POW10_ONE_ULP_UP`]).
fn js_pow10(k: i32) -> f64 {
let rounded: f64 = format!("1e{k}").parse().unwrap_or(f64::INFINITY);
if POW10_ONE_ULP_UP.contains(&k) {
f64::from_bits(rounded.to_bits() + 1)
} else {
rounded
}
}