exprim 0.4.1

A concurrent, memory-bounded PDF reader and renderer: parse, extract text, and rasterize pages on an immutable document snapshot
Documentation
#![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)]
// Build-time authenticated-source generator: malformed or changed vendored
// inputs must stop compilation rather than silently emit incorrect tables.

use std::fmt::Write as _;
use std::fs;
use std::path::{Path, PathBuf};

const UCD_PATH: &str = "upstream/pdfium/core/fxcrt/fx_ucddata.inc";
const UNICODE_PATH: &str = "upstream/pdfium/core/fxcrt/fx_unicode.cpp";
const NORMALIZATION_PATH: &str = "upstream/pdfium/core/fpdftext/unicodenormalizationdata.cpp";

const UCD_SHA256: &str = "e05118aa0537401ffdee74fa2db6143e021edd8be6ee8a1fc104a77ace07d9a6";
const UNICODE_SHA256: &str = "c317970bdc08c915191fc29ee1688ef45b5fed0b6cdd583bb4b049b64405a27d";
const NORMALIZATION_SHA256: &str =
    "aa0c725f898274e48f7d2d9c026d3ea990ac1251cf7b4ef4d943c313b6540828";

fn main() {
    println!("cargo:rerun-if-changed={UCD_PATH}");
    println!("cargo:rerun-if-changed={UNICODE_PATH}");
    println!("cargo:rerun-if-changed={NORMALIZATION_PATH}");
    println!("cargo:rerun-if-changed=build.rs");

    let ucd = verified_source(UCD_PATH, UCD_SHA256);
    let unicode = verified_source(UNICODE_PATH, UNICODE_SHA256);
    let normalization = verified_source(NORMALIZATION_PATH, NORMALIZATION_SHA256);

    let (bidi_classes, mirror_indices) = parse_ucd(&ucd);
    let mirrors = parse_named_hex_array(&unicode, "kFXTextLayoutBidiMirror", 366);
    assert!(
        mirror_indices
            .iter()
            .all(|&index| index == 0x1ff || usize::from(index) < mirrors.len()),
        "PDFium mirror index is outside the copied mirror table"
    );

    let normalization_table =
        parse_named_hex_array(&normalization, "kUnicodeDataNormalization", 65_536);
    let normalization_map1 =
        parse_named_hex_array(&normalization, "kUnicodeDataNormalizationMap1", 5_376);
    let normalization_map2 =
        parse_named_hex_array(&normalization, "kUnicodeDataNormalizationMap2", 1_724);
    let normalization_map3 =
        parse_named_hex_array(&normalization, "kUnicodeDataNormalizationMap3", 1_164);
    let normalization_map4 =
        parse_named_hex_array(&normalization, "kUnicodeDataNormalizationMap4", 488);

    let mut generated = String::with_capacity(900_000);
    generated.push_str(
        "// @generated by crates/pdf-text/build.rs from byte-exact PDFium sources.\n\
         // Do not edit or transcribe these tables by hand.\n",
    );
    write_array(&mut generated, "BIDI_CLASS", "u8", &bidi_classes);
    write_array(&mut generated, "MIRROR_INDEX", "u16", &mirror_indices);
    write_array(&mut generated, "BIDI_MIRRORS", "u16", &mirrors);
    write_array(
        &mut generated,
        "UNICODE_NORMALIZATION",
        "u16",
        &normalization_table,
    );
    write_array(
        &mut generated,
        "UNICODE_NORMALIZATION_MAP1",
        "u16",
        &normalization_map1,
    );
    write_array(
        &mut generated,
        "UNICODE_NORMALIZATION_MAP2",
        "u16",
        &normalization_map2,
    );
    write_array(
        &mut generated,
        "UNICODE_NORMALIZATION_MAP3",
        "u16",
        &normalization_map3,
    );
    write_array(
        &mut generated,
        "UNICODE_NORMALIZATION_MAP4",
        "u16",
        &normalization_map4,
    );

    let out = PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR is set by Cargo"));
    fs::write(out.join("pdfium_unicode_tables.rs"), generated)
        .expect("write generated PDFium Unicode tables");
}

fn verified_source(path: &str, expected_sha256: &str) -> String {
    let bytes = fs::read(Path::new(path)).unwrap_or_else(|error| panic!("read {path}: {error}"));
    let actual = hex_digest(sha256(&bytes));
    assert_eq!(
        actual, expected_sha256,
        "{path} differs from the reviewed upstream PDFium source; copy the new file byte-for-byte \
         and update the parser and digest intentionally"
    );
    String::from_utf8(bytes).unwrap_or_else(|error| panic!("{path} is not UTF-8: {error}"))
}

fn parse_ucd(source: &str) -> (Vec<u8>, Vec<u16>) {
    let mut bidi = Vec::with_capacity(65_536);
    let mut mirrors = Vec::with_capacity(65_536);
    for line in source.lines() {
        let Some(arguments) = line
            .trim_start()
            .strip_prefix("CHARPROP____(")
            .and_then(|rest| rest.split_once(')').map(|pair| pair.0))
        else {
            continue;
        };
        let fields: Vec<_> = arguments.split(',').map(str::trim).collect();
        assert_eq!(fields.len(), 4, "unexpected fx_ucddata.inc row: {line}");
        mirrors.push(parse_u16(fields[0]));
        bidi.push(match fields[2] {
            "kON" | "kN" => 0,
            "kL" => 1,
            "kR" => 2,
            "kAN" => 3,
            "kEN" => 4,
            "kAL" => 5,
            "kNSM" => 6,
            "kCS" => 7,
            "kES" => 8,
            "kET" => 9,
            "kBN" => 10,
            "kS" => 11,
            "kWS" => 12,
            "kB" => 13,
            "kRLO" => 14,
            "kRLE" => 15,
            "kLRO" => 16,
            "kLRE" => 17,
            "kPDF" => 18,
            value => panic!("unknown PDFium bidi class {value}"),
        });
    }
    assert_eq!(bidi.len(), 65_536, "fx_ucddata.inc must cover the BMP");
    (bidi, mirrors)
}

fn parse_named_hex_array(source: &str, name: &str, expected_len: usize) -> Vec<u16> {
    let name_start = source
        .find(name)
        .unwrap_or_else(|| panic!("missing array {name}"));
    let array_start = source[name_start..]
        .find('{')
        .map(|offset| name_start + offset)
        .unwrap_or_else(|| panic!("missing initializer for {name}"));
    let mut depth = 0usize;
    let mut array_end = None;
    for (offset, byte) in source.as_bytes()[array_start..].iter().copied().enumerate() {
        match byte {
            b'{' => depth += 1,
            b'}' => {
                depth -= 1;
                if depth == 0 {
                    array_end = Some(array_start + offset + 1);
                    break;
                }
            }
            _ => {}
        }
    }
    let initializer = &source[array_start..array_end.expect("unterminated array initializer")];
    let bytes = initializer.as_bytes();
    let mut values = Vec::with_capacity(expected_len);
    let mut index = 0;
    while index + 2 <= bytes.len() {
        if bytes[index] == b'0'
            && index + 2 < bytes.len()
            && matches!(bytes[index + 1], b'x' | b'X')
        {
            let start = index + 2;
            let mut end = start;
            while end < bytes.len() && bytes[end].is_ascii_hexdigit() {
                end += 1;
            }
            values.push(
                u16::from_str_radix(&initializer[start..end], 16)
                    .unwrap_or_else(|error| panic!("invalid value in {name}: {error}")),
            );
            index = end;
        } else {
            index += 1;
        }
    }
    assert_eq!(
        values.len(),
        expected_len,
        "unexpected number of entries in {name}"
    );
    values
}

fn parse_u16(value: &str) -> u16 {
    let value = value.trim_end_matches(['u', 'U']);
    if let Some(hex) = value
        .strip_prefix("0x")
        .or_else(|| value.strip_prefix("0X"))
    {
        u16::from_str_radix(hex, 16).expect("valid u16 hex literal")
    } else {
        value.parse().expect("valid u16 literal")
    }
}

fn write_array<T: std::fmt::Display>(output: &mut String, name: &str, ty: &str, values: &[T]) {
    writeln!(
        output,
        "pub(crate) static {name}: [{ty}; {}] = [",
        values.len()
    )
    .expect("write to string");
    for chunk in values.chunks(24) {
        output.push_str("    ");
        for value in chunk {
            write!(output, "{value},").expect("write to string");
        }
        output.push('\n');
    }
    output.push_str("];\n");
}

fn hex_digest(bytes: [u8; 32]) -> String {
    let mut output = String::with_capacity(64);
    for byte in bytes {
        write!(output, "{byte:02x}").expect("write to string");
    }
    output
}

// Small build-only SHA-256 implementation avoids adding a dependency merely
// to authenticate the preserved upstream source inputs.
fn sha256(input: &[u8]) -> [u8; 32] {
    const K: [u32; 64] = [
        0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
        0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
        0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
        0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
        0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
        0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
        0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
        0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
        0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
        0xc67178f2,
    ];
    let bit_len = (input.len() as u64).wrapping_mul(8);
    let mut padded = input.to_vec();
    padded.push(0x80);
    while padded.len() % 64 != 56 {
        padded.push(0);
    }
    padded.extend_from_slice(&bit_len.to_be_bytes());

    let mut state = [
        0x6a09e667u32,
        0xbb67ae85,
        0x3c6ef372,
        0xa54ff53a,
        0x510e527f,
        0x9b05688c,
        0x1f83d9ab,
        0x5be0cd19,
    ];
    for block in padded.chunks_exact(64) {
        let mut words = [0u32; 64];
        for (index, word) in words[..16].iter_mut().enumerate() {
            let offset = index * 4;
            *word = u32::from_be_bytes(block[offset..offset + 4].try_into().expect("four bytes"));
        }
        for index in 16..64 {
            let s0 = words[index - 15].rotate_right(7)
                ^ words[index - 15].rotate_right(18)
                ^ (words[index - 15] >> 3);
            let s1 = words[index - 2].rotate_right(17)
                ^ words[index - 2].rotate_right(19)
                ^ (words[index - 2] >> 10);
            words[index] = words[index - 16]
                .wrapping_add(s0)
                .wrapping_add(words[index - 7])
                .wrapping_add(s1);
        }
        let mut work = state;
        for index in 0..64 {
            let s1 = work[4].rotate_right(6) ^ work[4].rotate_right(11) ^ work[4].rotate_right(25);
            let choice = (work[4] & work[5]) ^ (!work[4] & work[6]);
            let temp1 = work[7]
                .wrapping_add(s1)
                .wrapping_add(choice)
                .wrapping_add(K[index])
                .wrapping_add(words[index]);
            let s0 = work[0].rotate_right(2) ^ work[0].rotate_right(13) ^ work[0].rotate_right(22);
            let majority = (work[0] & work[1]) ^ (work[0] & work[2]) ^ (work[1] & work[2]);
            let temp2 = s0.wrapping_add(majority);
            work = [
                temp1.wrapping_add(temp2),
                work[0],
                work[1],
                work[2],
                work[3].wrapping_add(temp1),
                work[4],
                work[5],
                work[6],
            ];
        }
        for (value, addition) in state.iter_mut().zip(work) {
            *value = value.wrapping_add(addition);
        }
    }

    let mut output = [0u8; 32];
    for (chunk, word) in output.chunks_exact_mut(4).zip(state) {
        chunk.copy_from_slice(&word.to_be_bytes());
    }
    output
}