Skip to main content

laminapdf_syntax/
text.rs

1//! Text strings (ISO 32000-2 §7.9.2.2): `PDFDocEncoding`, UTF-16BE with a byte-order mark,
2//! and (PDF 2.0) UTF-8 with a byte-order mark.
3//!
4//! This module holds the workspace's one `PDFDocEncoding` table (Annex D, Table D.2), in both
5//! directions: [`pdf_doc_decode`] maps a code to its Unicode scalar and [`pdf_doc_encode`]
6//! maps a scalar back to its code. Layers above (the string encoder for ops, simple fonts)
7//! reuse it instead of writing their own.
8//!
9//! ```
10//! use laminapdf_syntax::text::decode_text_string;
11//!
12//! assert_eq!(decode_text_string(b"Caf\xe9 \x84 menu"), "Café — menu");
13//! assert_eq!(decode_text_string(b"\xfe\xff\x00H\x00i\xd8\x3d\xde\x00"), "Hi😀");
14//! assert_eq!(decode_text_string(b"\xef\xbb\xbfna\xc3\xafve"), "naïve");
15//! ```
16
17/// The Unicode replacement character, produced for invalid UTF-16 and UTF-8 sequences.
18///
19/// Added in 0.2.0.
20pub const REPLACEMENT: char = '\u{FFFD}';
21
22/// Codes 0x80–0xA0 of `PDFDocEncoding` (Table D.2); `None` marks an undefined code (0x9F).
23const HIGH: [Option<char>; 33] = [
24    Some('\u{2022}'), // 0x80 bullet
25    Some('\u{2020}'), // 0x81 dagger
26    Some('\u{2021}'), // 0x82 daggerdbl
27    Some('\u{2026}'), // 0x83 ellipsis
28    Some('\u{2014}'), // 0x84 emdash
29    Some('\u{2013}'), // 0x85 endash
30    Some('\u{0192}'), // 0x86 florin
31    Some('\u{2044}'), // 0x87 fraction
32    Some('\u{2039}'), // 0x88 guilsinglleft
33    Some('\u{203A}'), // 0x89 guilsinglright
34    Some('\u{2212}'), // 0x8A minus
35    Some('\u{2030}'), // 0x8B perthousand
36    Some('\u{201E}'), // 0x8C quotedblbase
37    Some('\u{201C}'), // 0x8D quotedblleft
38    Some('\u{201D}'), // 0x8E quotedblright
39    Some('\u{2018}'), // 0x8F quoteleft
40    Some('\u{2019}'), // 0x90 quoteright
41    Some('\u{201A}'), // 0x91 quotesinglbase
42    Some('\u{2122}'), // 0x92 trademark
43    Some('\u{FB01}'), // 0x93 fi
44    Some('\u{FB02}'), // 0x94 fl
45    Some('\u{0141}'), // 0x95 Lslash
46    Some('\u{0152}'), // 0x96 OE
47    Some('\u{0160}'), // 0x97 Scaron
48    Some('\u{0178}'), // 0x98 Ydieresis
49    Some('\u{017D}'), // 0x99 Zcaron
50    Some('\u{0131}'), // 0x9A dotlessi
51    Some('\u{0142}'), // 0x9B lslash
52    Some('\u{0153}'), // 0x9C oe
53    Some('\u{0161}'), // 0x9D scaron
54    Some('\u{017E}'), // 0x9E zcaron
55    None,             // 0x9F undefined
56    Some('\u{20AC}'), // 0xA0 Euro
57];
58
59/// Codes 0x18–0x1F of `PDFDocEncoding`: spacing accents.
60const ACCENTS: [char; 8] = [
61    '\u{02D8}', // 0x18 breve
62    '\u{02C7}', // 0x19 caron
63    '\u{02C6}', // 0x1A circumflex
64    '\u{02D9}', // 0x1B dotaccent
65    '\u{02DD}', // 0x1C hungarumlaut
66    '\u{02DB}', // 0x1D ogonek
67    '\u{02DA}', // 0x1E ring
68    '\u{02DC}', // 0x1F tilde
69];
70
71/// The Unicode scalar of `PDFDocEncoding` code `code`, or `None` for an undefined code.
72///
73/// Defined (Annex D, Table D.2): tab, line feed and carriage return; the spacing accents at
74/// 0x18–0x1F; printable ASCII 0x20–0x7E; the punctuation and letters at 0x80–0x9E; the Euro
75/// sign at 0xA0; and ISO Latin-1 at 0xA1–0xFF except 0xAD. Undefined: the other C0 controls,
76/// 0x7F, 0x9F and 0xAD.
77///
78/// ```
79/// use laminapdf_syntax::text::pdf_doc_decode;
80///
81/// assert_eq!(pdf_doc_decode(0x92), Some('™'));
82/// assert_eq!(pdf_doc_decode(0x9F), None);
83/// ```
84///
85/// Added in 0.2.0.
86#[must_use]
87pub fn pdf_doc_decode(code: u8) -> Option<char> {
88    match code {
89        0x09 | 0x0A | 0x0D | 0x20..=0x7E | 0xA1..=0xAC | 0xAE..=0xFF => Some(char::from(code)),
90        0x18..=0x1F => ACCENTS.get(usize::from(code - 0x18)).copied(),
91        0x80..=0xA0 => HIGH.get(usize::from(code - 0x80)).copied().flatten(),
92        _ => None,
93    }
94}
95
96/// The `PDFDocEncoding` code of `c`, or `None` when `c` has no code (the reverse of
97/// [`pdf_doc_decode`]).
98///
99/// ```
100/// use laminapdf_syntax::text::pdf_doc_encode;
101///
102/// assert_eq!(pdf_doc_encode('€'), Some(0xA0));
103/// assert_eq!(pdf_doc_encode('é'), Some(0xE9));
104/// assert_eq!(pdf_doc_encode('中'), None);
105/// ```
106///
107/// Added in 0.2.0.
108#[must_use]
109pub fn pdf_doc_encode(c: char) -> Option<u8> {
110    let scalar = u32::from(c);
111    if let Ok(code) = u8::try_from(scalar)
112        && pdf_doc_decode(code) == Some(c)
113    {
114        return Some(code);
115    }
116    // Every other defined code maps outside Latin-1: search the two small tables.
117    let in_table = |table: &[Option<char>], base: u8| {
118        table
119            .iter()
120            .position(|&t| t == Some(c))
121            .and_then(|i| u8::try_from(i).ok())
122            .map(|i| base + i)
123    };
124    let accents: [Option<char>; 8] = ACCENTS.map(Some);
125    in_table(&accents, 0x18).or_else(|| in_table(&HIGH, 0x80))
126}
127
128/// Decodes a PDF text string (§7.9.2.2) to Unicode.
129///
130/// * Bytes starting with `FE FF` are UTF-16BE. Unpaired surrogates and a trailing odd byte
131///   become U+FFFD; language escape sequences (`U+001B`, a language code, `U+001B`,
132///   §7.9.2.2.1) are removed.
133/// * Bytes starting with `EF BB BF` are UTF-8 (PDF 2.0); invalid sequences become U+FFFD.
134/// * Anything else is `PDFDocEncoding`. An undefined code (a C0 control other than tab, line
135///   feed and carriage return, 0x7F, 0x9F, 0xAD) keeps its own scalar, U+0000–U+00FF, as
136///   pdf.js, qpdf and pypdf read it: nothing is lost, and a caller that shows the text can
137///   drop control characters (ADR 0003 §1).
138///
139/// Never fails: text strings are display data, and a damaged one is still worth showing.
140///
141/// Added in 0.2.0.
142#[must_use]
143pub fn decode_text_string(bytes: &[u8]) -> String {
144    if let Some(utf16) = bytes.strip_prefix(b"\xFE\xFF") {
145        decode_utf16be(utf16)
146    } else if let Some(utf8) = bytes.strip_prefix(b"\xEF\xBB\xBF") {
147        String::from_utf8_lossy(utf8).into_owned()
148    } else {
149        bytes
150            .iter()
151            .map(|&b| pdf_doc_decode(b).unwrap_or_else(|| char::from(b)))
152            .collect()
153    }
154}
155
156/// Encodes `text` as a PDF text string (§7.9.2.2), the inverse of [`decode_text_string`]:
157/// `PDFDocEncoding` when every character has a code, else UTF-16BE with a `FE FF` byte
158/// order mark. PDFDocEncoding output that would start with a byte order mark (`þÿ`, ``)
159/// is written as UTF-16BE too, so it never decodes as something else. U+001B (ESC) is
160/// written as U+FFFD: in UTF-16BE it brackets a language code (§7.9.2.2.1), so a literal
161/// ESC could make a reader drop the text after it.
162///
163/// ```
164/// use laminapdf_syntax::text::{decode_text_string, encode_text_string};
165///
166/// assert_eq!(encode_text_string("Café €"), b"Caf\xE9 \xA0");
167/// assert_eq!(encode_text_string("中"), b"\xFE\xFF\x4E\x2D");
168/// assert_eq!(decode_text_string(&encode_text_string("Grüße, 世界")), "Grüße, 世界");
169/// ```
170///
171/// Added in 0.2.0.
172#[must_use]
173pub fn encode_text_string(text: &str) -> Vec<u8> {
174    if text.contains(ESCAPE) {
175        return encode_text_string(&text.replace(ESCAPE, "\u{FFFD}"));
176    }
177    let pdf_doc: Option<Vec<u8>> = text.chars().map(pdf_doc_encode).collect();
178    match pdf_doc {
179        Some(bytes) if !bytes.starts_with(b"\xFE\xFF") && !bytes.starts_with(b"\xEF\xBB\xBF") => bytes,
180        _ => {
181            let mut out = Vec::with_capacity(2 + text.len() * 2);
182            out.extend_from_slice(b"\xFE\xFF");
183            for unit in text.encode_utf16() {
184                out.extend_from_slice(&unit.to_be_bytes());
185            }
186            out
187        }
188    }
189}
190
191fn decode_utf16be(bytes: &[u8]) -> String {
192    let (pairs, rest) = bytes.as_chunks::<2>();
193    let odd = !rest.is_empty();
194    let units = pairs.iter().map(|&pair| u16::from_be_bytes(pair));
195    let chars: Vec<char> = char::decode_utf16(units).map(|c| c.unwrap_or(REPLACEMENT)).collect();
196    let mut out = String::with_capacity(chars.len());
197    let mut i = 0;
198    while let Some(&c) = chars.get(i) {
199        if c == ESCAPE {
200            if let Some(len) = language_escape(chars.get(i..).unwrap_or_default()) {
201                i += len;
202                continue;
203            }
204            // A stray or unterminated escape is not a language marker: keep the text.
205            out.push(REPLACEMENT);
206        } else {
207            out.push(c);
208        }
209        i += 1;
210    }
211    if odd {
212        out.push(REPLACEMENT);
213    }
214    out
215}
216
217/// The escape character that brackets a language code in a UTF-16 text string.
218const ESCAPE: char = '\u{1B}';
219
220/// The length of the language escape sequence `chars` starts with (§7.9.2.2.1): ESC, a
221/// two-letter ISO 639 language code, an optional two-letter ISO 3166 country code, ESC.
222/// `None` when `chars` does not start with one.
223fn language_escape(chars: &[char]) -> Option<usize> {
224    let rest = chars.strip_prefix(&[ESCAPE])?;
225    [2, 4].into_iter().find_map(|code_len| {
226        let code = rest.get(..code_len)?;
227        let closed = rest.get(code_len) == Some(&ESCAPE);
228        (closed && code.iter().all(char::is_ascii_alphabetic)).then_some(code_len + 2)
229    })
230}
231
232#[cfg(test)]
233mod tests {
234    use super::*;
235
236    /// Table D.2 as (code, scalar) pairs for every code outside ASCII and Latin-1 identity.
237    const NON_IDENTITY: [(u8, u32); 41] = [
238        (0x18, 0x02D8),
239        (0x19, 0x02C7),
240        (0x1A, 0x02C6),
241        (0x1B, 0x02D9),
242        (0x1C, 0x02DD),
243        (0x1D, 0x02DB),
244        (0x1E, 0x02DA),
245        (0x1F, 0x02DC),
246        (0x80, 0x2022),
247        (0x81, 0x2020),
248        (0x82, 0x2021),
249        (0x83, 0x2026),
250        (0x84, 0x2014),
251        (0x85, 0x2013),
252        (0x86, 0x0192),
253        (0x87, 0x2044),
254        (0x88, 0x2039),
255        (0x89, 0x203A),
256        (0x8A, 0x2212),
257        (0x8B, 0x2030),
258        (0x8C, 0x201E),
259        (0x8D, 0x201C),
260        (0x8E, 0x201D),
261        (0x8F, 0x2018),
262        (0x90, 0x2019),
263        (0x91, 0x201A),
264        (0x92, 0x2122),
265        (0x93, 0xFB01),
266        (0x94, 0xFB02),
267        (0x95, 0x0141),
268        (0x96, 0x0152),
269        (0x97, 0x0160),
270        (0x98, 0x0178),
271        (0x99, 0x017D),
272        (0x9A, 0x0131),
273        (0x9B, 0x0142),
274        (0x9C, 0x0153),
275        (0x9D, 0x0161),
276        (0x9E, 0x017E),
277        (0xA0, 0x20AC),
278        (0x09, 0x0009),
279    ];
280
281    const UNDEFINED: [u8; 4] = [0x7F, 0x9F, 0xAD, 0x00];
282
283    #[test]
284    fn decode_maps_every_non_identity_code_as_table_d2() {
285        for (code, scalar) in NON_IDENTITY {
286            assert_eq!(pdf_doc_decode(code).map(u32::from), Some(scalar), "code {code:#04x}");
287        }
288    }
289
290    #[test]
291    fn decode_is_identity_for_ascii_and_latin1() {
292        for code in (0x20..=0x7E).chain(0xA1..=0xAC).chain(0xAE..=0xFF) {
293            assert_eq!(pdf_doc_decode(code), Some(char::from(code)), "code {code:#04x}");
294        }
295    }
296
297    #[test]
298    fn decode_leaves_undefined_codes_undefined() {
299        let undefined: Vec<u8> = (0..=0xFF).filter(|&c| pdf_doc_decode(c).is_none()).collect();
300        let mut expected: Vec<u8> = (0x00..0x09).chain([0x0B, 0x0C]).chain(0x0E..0x18).collect();
301        expected.extend([0x7F, 0x9F, 0xAD]);
302        assert_eq!(undefined, expected);
303    }
304
305    #[test]
306    fn encode_reverses_decode_for_every_defined_code() {
307        for code in 0..=0xFF_u8 {
308            if let Some(c) = pdf_doc_decode(code) {
309                assert_eq!(pdf_doc_encode(c), Some(code), "code {code:#04x}");
310            }
311        }
312    }
313
314    #[test]
315    fn encode_rejects_scalars_without_a_code() {
316        for c in ['\u{AD}', '\u{7F}', '\u{0}', '中', '\u{2023}'] {
317            assert_eq!(pdf_doc_encode(c), None, "{c:?}");
318        }
319    }
320
321    #[test]
322    fn decode_text_string_keeps_an_undefined_pdfdoc_code_as_its_own_scalar() {
323        for code in UNDEFINED.into_iter().chain([0x11]) {
324            assert_eq!(decode_text_string(&[b'a', code]), format!("a{}", char::from(code)));
325        }
326    }
327
328    #[test]
329    fn decode_text_string_reads_utf16be_surrogate_pairs() {
330        assert_eq!(decode_text_string(b"\xFE\xFF\xD8\x34\xDD\x1E"), "\u{1D11E}");
331    }
332
333    #[test]
334    fn decode_text_string_replaces_an_unpaired_high_surrogate() {
335        assert_eq!(decode_text_string(b"\xFE\xFF\xD8\x34\x00A"), "\u{FFFD}A");
336    }
337
338    #[test]
339    fn decode_text_string_replaces_an_unpaired_low_surrogate() {
340        assert_eq!(decode_text_string(b"\xFE\xFF\xDD\x1E"), "\u{FFFD}");
341    }
342
343    #[test]
344    fn decode_text_string_replaces_a_trailing_odd_byte() {
345        assert_eq!(decode_text_string(b"\xFE\xFF\x00A\x00"), "A\u{FFFD}");
346    }
347
348    #[test]
349    fn decode_text_string_drops_utf16_language_escapes() {
350        assert_eq!(
351            decode_text_string(b"\xFE\xFF\x00\x1B\x00e\x00n\x00\x1B\x00H\x00i"),
352            "Hi"
353        );
354    }
355
356    #[test]
357    fn decode_text_string_drops_language_and_country_escapes() {
358        assert_eq!(
359            decode_text_string(b"\xFE\xFF\x00\x1B\x00e\x00n\x00U\x00S\x00\x1B\x00H\x00i"),
360            "Hi"
361        );
362    }
363
364    #[test]
365    fn decode_text_string_keeps_text_after_a_stray_escape() {
366        assert_eq!(decode_text_string(b"\xFE\xFF\x00\x1B\x00H\x00i"), "\u{FFFD}Hi");
367    }
368
369    #[test]
370    fn decode_text_string_keeps_text_after_an_overlong_escape() {
371        assert_eq!(
372            decode_text_string(b"\xFE\xFF\x00\x1B\x00a\x00b\x00c\x00d\x00e\x00\x1B\x00!"),
373            "\u{FFFD}abcde\u{FFFD}!"
374        );
375    }
376
377    #[test]
378    fn decode_text_string_reads_utf8_with_bom() {
379        assert_eq!(decode_text_string(b"\xEF\xBB\xBF\xE2\x82\xAC"), "€");
380    }
381
382    #[test]
383    fn decode_text_string_replaces_invalid_utf8() {
384        assert_eq!(decode_text_string(b"\xEF\xBB\xBFa\xFFb"), "a\u{FFFD}b");
385    }
386
387    #[test]
388    fn decode_text_string_of_an_empty_string_is_empty() {
389        assert_eq!(decode_text_string(b""), "");
390    }
391
392    #[test]
393    fn encode_text_string_round_trips_through_decode() {
394        for text in [
395            "",
396            "Title",
397            "Café €",
398            "• – —",
399            "中文",
400            "emoji 😀",
401            "þÿ",
402            "x",
403            "\u{7F}",
404        ] {
405            assert_eq!(decode_text_string(&encode_text_string(text)), text, "{text:?}");
406        }
407    }
408
409    #[test]
410    fn encode_text_string_never_writes_a_language_escape() {
411        let text = "a\u{1B}en\u{1B}b";
412        assert_eq!(decode_text_string(&encode_text_string(text)), "a\u{FFFD}en\u{FFFD}b");
413    }
414
415    #[test]
416    fn encode_text_string_prefers_pdfdoc() {
417        assert_eq!(encode_text_string("A€"), b"A\xA0");
418    }
419
420    #[test]
421    fn decode_text_string_without_a_bom_is_pdfdoc() {
422        assert_eq!(decode_text_string(b"\xFE"), "\u{FE}");
423    }
424}