rusty_pdf_core 0.2.1

Pure-Rust PDF reader core: objects, classic and stream cross-reference tables, object streams, incremental updates, broken-xref repair, RC4 and AES-128/256 decryption, stream filters, page tree, content streams, editing and save. Hostile input errors or stays bounded. No C, no unsafe.
Documentation
//! PDF text strings: PDFDocEncoding and UTF-16BE (7.9.2.2).

/// Code points of PDFDocEncoding bytes that differ from Latin-1, as
/// (byte, char) pairs. Every other byte from 0x20 maps to the Latin-1 code
/// point of the same value; 0x7F, 0x9F and 0xAD are undefined.
const PDFDOC_SPECIALS: [(u8, char); 41] = [
    (0x18, '\u{02D8}'),
    (0x19, '\u{02C7}'),
    (0x1A, '\u{02C6}'),
    (0x1B, '\u{02D9}'),
    (0x1C, '\u{02DD}'),
    (0x1D, '\u{02DB}'),
    (0x1E, '\u{02DA}'),
    (0x1F, '\u{02DC}'),
    (0x80, '\u{2022}'),
    (0x81, '\u{2020}'),
    (0x82, '\u{2021}'),
    (0x83, '\u{2026}'),
    (0x84, '\u{2014}'),
    (0x85, '\u{2013}'),
    (0x86, '\u{0192}'),
    (0x87, '\u{2044}'),
    (0x88, '\u{2039}'),
    (0x89, '\u{203A}'),
    (0x8A, '\u{2212}'),
    (0x8B, '\u{2030}'),
    (0x8C, '\u{201E}'),
    (0x8D, '\u{201C}'),
    (0x8E, '\u{201D}'),
    (0x8F, '\u{2018}'),
    (0x90, '\u{2019}'),
    (0x91, '\u{201A}'),
    (0x92, '\u{2122}'),
    (0x93, '\u{FB01}'),
    (0x94, '\u{FB02}'),
    (0x95, '\u{0141}'),
    (0x96, '\u{0152}'),
    (0x97, '\u{0160}'),
    (0x98, '\u{0178}'),
    (0x99, '\u{017D}'),
    (0x9A, '\u{0131}'),
    (0x9B, '\u{0142}'),
    (0x9C, '\u{0153}'),
    (0x9D, '\u{0161}'),
    (0x9E, '\u{017E}'),
    (0xA0, '\u{20AC}'),
    (0x7F, '\u{FFFD}'),
];

/// The character a PDFDocEncoding byte stands for.
#[must_use]
pub fn pdfdoc_char(b: u8) -> char {
    match PDFDOC_SPECIALS.iter().find(|(byte, _)| *byte == b) {
        Some((_, c)) => *c,
        None => char::from(b),
    }
}

/// `s` in PDFDocEncoding, or `None` when a character has no byte there.
#[must_use]
pub fn to_pdfdoc(s: &str) -> Option<Vec<u8>> {
    s.chars()
        .map(|c| {
            if let Some((b, _)) = PDFDOC_SPECIALS.iter().find(|(_, ch)| *ch == c) {
                return Some(*b);
            }
            let code = u32::from(c);
            let latin1 = u8::try_from(code).ok()?;
            // A byte whose PDFDocEncoding meaning differs is not the Latin-1
            // character of the same value.
            let reassigned = PDFDOC_SPECIALS.iter().any(|(b, _)| *b == latin1);
            (!reassigned).then_some(latin1)
        })
        .collect()
}

/// Decode a text string: UTF-16BE with a byte-order mark, UTF-8 with one
/// (PDF 2.0), or PDFDocEncoding.
#[must_use]
pub fn decode_text(bytes: &[u8]) -> String {
    if let Some(rest) = bytes.strip_prefix(&[0xFE, 0xFF]) {
        let units: Vec<u16> = rest.as_chunks::<2>().0.iter().map(|p| u16::from_be_bytes([p[0], p[1]])).collect();
        return char::decode_utf16(units).map(|r| r.unwrap_or('\u{FFFD}')).collect();
    }
    if let Some(rest) = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]) {
        return String::from_utf8_lossy(rest).into_owned();
    }
    bytes.iter().map(|b| pdfdoc_char(*b)).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pdfdoc_round_trip() {
        assert_eq!(to_pdfdoc("pässwört"), Some(b"p\xE4ssw\xF6rt".to_vec()));
        assert_eq!(to_pdfdoc("\u{2022}\u{20AC}"), Some(vec![0x80, 0xA0]));
        assert_eq!(to_pdfdoc("\u{4E2D}"), None);
        // U+00A0 (no-break space) has no byte: 0xA0 is the euro sign here.
        assert_eq!(to_pdfdoc("\u{00A0}"), None);
        assert_eq!(decode_text(b"p\xE4ssw\xF6rt \x80"), "pässwört \u{2022}");
    }

    #[test]
    fn utf16_and_utf8_text() {
        assert_eq!(decode_text(&[0xFE, 0xFF, 0x00, 0x41, 0xD8, 0x3D, 0xDE, 0x00]), "A\u{1F600}");
        assert_eq!(decode_text(&[0xEF, 0xBB, 0xBF, b'h', 0xC3, 0xA9]), "hé");
    }
}