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
//! `ToUnicode` CMaps (9.10.3): character codes to Unicode text.
//!
//! Only what a `ToUnicode` map holds is read: code-space ranges, `bfchar`
//! and `bfrange` (both forms). Predefined CJK CMaps are the renderer's
//! business.

use crate::parser::Parser;
use crate::object::Object;
use std::collections::BTreeMap;

/// Most mappings kept from one CMap. A `bfrange` can claim 2^32 codes; it is
/// expanded lazily, but the explicit tables are bounded.
const MAX_ENTRIES: usize = 1 << 20;

/// A parsed `ToUnicode` map.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ToUnicode {
    /// (code length in bytes, low, high) for each code-space range.
    spaces: Vec<(usize, u32, u32)>,
    /// Single codes, and the text each stands for.
    chars: BTreeMap<(usize, u32), String>,
    /// `bfrange` with a base string: (length, low, high) → the text for
    /// `low`, whose last character is incremented for each code after it.
    ranges: Vec<(usize, u32, u32, Vec<u16>)>,
}

fn utf16_text(units: &[u16]) -> String {
    char::decode_utf16(units.iter().copied()).map(|r| r.unwrap_or('\u{FFFD}')).collect()
}

fn units(bytes: &[u8]) -> Vec<u16> {
    bytes.chunks(2).map(|p| u16::from_be_bytes([p[0], *p.get(1).unwrap_or(&0)])).collect()
}

fn code_of(bytes: &[u8]) -> Option<(usize, u32)> {
    if bytes.is_empty() || bytes.len() > 4 {
        return None;
    }
    Some((bytes.len(), bytes.iter().fold(0u32, |a, b| a << 8 | u32::from(*b))))
}

impl ToUnicode {
    /// Parse a decoded CMap stream. What cannot be read is skipped: a
    /// partly broken map still maps what it can.
    #[must_use]
    pub fn parse(data: &[u8]) -> Self {
        let mut map = Self::default();
        let mut p = Parser::for_content(data, 16);
        let mut operands: Vec<Object> = Vec::new();
        let total = |m: &Self| m.chars.len() + m.ranges.len();
        while !p.at_end() {
            p.skip_ws();
            if p.at_end() {
                break;
            }
            let before = p.pos;
            if let Ok(o) = p.object() {
                if operands.len() < 4096 {
                    operands.push(o);
                }
                continue;
            }
            p.pos = before;
            let token = p.token();
            if token.is_empty() {
                p.pos += 1;
                continue;
            }
            match token {
                b"endcodespacerange" => {
                    for pair in operands.as_chunks::<2>().0.iter() {
                        if let (Ok(lo), Ok(hi)) = (pair[0].as_str(), pair[1].as_str()) {
                            if let (Some((n, lo)), Some((_, hi))) = (code_of(lo), code_of(hi)) {
                                map.spaces.push((n, lo, hi));
                            }
                        }
                    }
                }
                b"endbfchar" => {
                    for pair in operands.as_chunks::<2>().0.iter() {
                        if total(&map) >= MAX_ENTRIES {
                            break;
                        }
                        let (Ok(src), Ok(dst)) = (pair[0].as_str(), pair[1].as_str()) else { continue };
                        if let Some(code) = code_of(src) {
                            map.chars.insert(code, utf16_text(&units(dst)));
                        }
                    }
                }
                b"endbfrange" => {
                    for triple in operands.as_chunks::<3>().0.iter() {
                        if total(&map) >= MAX_ENTRIES {
                            break;
                        }
                        let (Ok(lo), Ok(hi)) = (triple[0].as_str(), triple[1].as_str()) else { continue };
                        let (Some((n, lo)), Some((_, hi))) = (code_of(lo), code_of(hi)) else { continue };
                        if hi < lo {
                            continue;
                        }
                        match &triple[2] {
                            Object::String(base, _) => map.ranges.push((n, lo, hi, units(base))),
                            Object::Array(items) => {
                                for (i, item) in items.iter().enumerate() {
                                    let Ok(code) = u32::try_from(i).map(|i| lo.saturating_add(i)) else { break };
                                    if code > hi || total(&map) >= MAX_ENTRIES {
                                        break;
                                    }
                                    if let Ok(dst) = item.as_str() {
                                        map.chars.insert((n, code), utf16_text(&units(dst)));
                                    }
                                }
                            }
                            _ => {}
                        }
                    }
                }
                _ => {}
            }
            operands.clear();
        }
        map
    }

    /// Whether the map holds no mappings.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.chars.is_empty() && self.ranges.is_empty()
    }

    /// The text for the code of `len` bytes with value `code`.
    #[must_use]
    pub fn lookup(&self, len: usize, code: u32) -> Option<String> {
        let mut out = String::new();
        self.lookup_into(len, code, &mut out).then_some(out)
    }

    /// Append the text for a code to `out`; `false` when the map has none.
    /// Allocates nothing beyond `out`'s own growth.
    pub fn lookup_into(&self, len: usize, code: u32, out: &mut String) -> bool {
        if let Some(s) = self.chars.get(&(len, code)) {
            out.push_str(s);
            return true;
        }
        let Some((_, lo, _, base)) = self.ranges.iter().find(|(n, lo, hi, _)| *n == len && (*lo..=*hi).contains(&code)) else {
            return false;
        };
        // The offset is at most the range width; wrapping keeps a malformed
        // range from panicking.
        let offset = u16::try_from(code - lo).unwrap_or(0);
        let last = base.len().saturating_sub(1);
        let units = base.iter().enumerate().map(|(i, u)| if i == last { u.wrapping_add(offset) } else { *u });
        out.extend(char::decode_utf16(units).map(|r| r.unwrap_or('\u{FFFD}')));
        true
    }

    /// How many bytes the code starting `bytes` takes. With no code-space
    /// ranges, codes are as long as the mappings' codes (two bytes for a
    /// typical CID font, else one).
    #[must_use]
    pub fn code_length(&self, bytes: &[u8]) -> usize {
        for n in 1..=4.min(bytes.len()) {
            let Some((_, value)) = code_of(&bytes[..n]) else { break };
            if self.spaces.iter().any(|(len, lo, hi)| *len == n && (*lo..=*hi).contains(&value)) {
                return n;
            }
        }
        if !self.spaces.is_empty() {
            // Not in any range: the shortest code length in use (9.7.6.3).
            return self.spaces.iter().map(|(n, _, _)| *n).min().unwrap_or(1).min(bytes.len()).max(1);
        }
        let n = self.chars.keys().map(|(n, _)| *n).chain(self.ranges.iter().map(|r| r.0)).max().unwrap_or(1);
        n.clamp(1, bytes.len().max(1))
    }
}

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

    #[test]
    fn bfchar_and_bfrange() {
        let cmap = ToUnicode::parse(
            b"/CIDInit /ProcSet findresource begin 12 dict begin begincmap
              1 begincodespacerange <0000> <FFFF> endcodespacerange
              2 beginbfchar <0003> <0020> <0011> <D83DDE00> endbfchar
              2 beginbfrange <0024> <0026> <0041> <0030> <0031> [<0066006C> <0078>] endbfrange
              endcmap",
        );
        assert_eq!(cmap.lookup(2, 3).as_deref(), Some(" "));
        assert_eq!(cmap.lookup(2, 0x11).as_deref(), Some("\u{1F600}"));
        assert_eq!(cmap.lookup(2, 0x25).as_deref(), Some("B"));
        assert_eq!(cmap.lookup(2, 0x30).as_deref(), Some("fl"));
        assert_eq!(cmap.lookup(2, 0x31).as_deref(), Some("x"));
        assert_eq!(cmap.lookup(2, 0x99), None);
        assert_eq!(cmap.code_length(&[0, 3]), 2);
    }

    #[test]
    fn a_hostile_range_is_not_expanded() {
        let cmap = ToUnicode::parse(b"1 beginbfrange <00000000> <FFFFFFFF> <0041> endbfrange");
        assert_eq!(cmap.lookup(4, 1).as_deref(), Some("B"));
        let cmap = ToUnicode::parse(b"garbage ) ] >> 1 beginbfchar <01> endbfchar");
        assert!(cmap.is_empty());
    }
}