1pub const REPLACEMENT: char = '\u{FFFD}';
21
22const HIGH: [Option<char>; 33] = [
24 Some('\u{2022}'), Some('\u{2020}'), Some('\u{2021}'), Some('\u{2026}'), Some('\u{2014}'), Some('\u{2013}'), Some('\u{0192}'), Some('\u{2044}'), Some('\u{2039}'), Some('\u{203A}'), Some('\u{2212}'), Some('\u{2030}'), Some('\u{201E}'), Some('\u{201C}'), Some('\u{201D}'), Some('\u{2018}'), Some('\u{2019}'), Some('\u{201A}'), Some('\u{2122}'), Some('\u{FB01}'), Some('\u{FB02}'), Some('\u{0141}'), Some('\u{0152}'), Some('\u{0160}'), Some('\u{0178}'), Some('\u{017D}'), Some('\u{0131}'), Some('\u{0142}'), Some('\u{0153}'), Some('\u{0161}'), Some('\u{017E}'), None, Some('\u{20AC}'), ];
58
59const ACCENTS: [char; 8] = [
61 '\u{02D8}', '\u{02C7}', '\u{02C6}', '\u{02D9}', '\u{02DD}', '\u{02DB}', '\u{02DA}', '\u{02DC}', ];
70
71#[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#[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 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#[must_use]
140pub fn decode_text_string(bytes: &[u8]) -> String {
141 if let Some(utf16) = bytes.strip_prefix(b"\xFE\xFF") {
142 decode_utf16be(utf16)
143 } else if let Some(utf8) = bytes.strip_prefix(b"\xEF\xBB\xBF") {
144 String::from_utf8_lossy(utf8).into_owned()
145 } else {
146 bytes
147 .iter()
148 .map(|&b| pdf_doc_decode(b).unwrap_or(REPLACEMENT))
149 .collect()
150 }
151}
152
153#[must_use]
170pub fn encode_text_string(text: &str) -> Vec<u8> {
171 if text.contains(ESCAPE) {
172 return encode_text_string(&text.replace(ESCAPE, "\u{FFFD}"));
173 }
174 let pdf_doc: Option<Vec<u8>> = text.chars().map(pdf_doc_encode).collect();
175 match pdf_doc {
176 Some(bytes) if !bytes.starts_with(b"\xFE\xFF") && !bytes.starts_with(b"\xEF\xBB\xBF") => bytes,
177 _ => {
178 let mut out = Vec::with_capacity(2 + text.len() * 2);
179 out.extend_from_slice(b"\xFE\xFF");
180 for unit in text.encode_utf16() {
181 out.extend_from_slice(&unit.to_be_bytes());
182 }
183 out
184 }
185 }
186}
187
188fn decode_utf16be(bytes: &[u8]) -> String {
189 let (pairs, rest) = bytes.as_chunks::<2>();
190 let odd = !rest.is_empty();
191 let units = pairs.iter().map(|&pair| u16::from_be_bytes(pair));
192 let chars: Vec<char> = char::decode_utf16(units).map(|c| c.unwrap_or(REPLACEMENT)).collect();
193 let mut out = String::with_capacity(chars.len());
194 let mut i = 0;
195 while let Some(&c) = chars.get(i) {
196 if c == ESCAPE {
197 if let Some(len) = language_escape(chars.get(i..).unwrap_or_default()) {
198 i += len;
199 continue;
200 }
201 out.push(REPLACEMENT);
203 } else {
204 out.push(c);
205 }
206 i += 1;
207 }
208 if odd {
209 out.push(REPLACEMENT);
210 }
211 out
212}
213
214const ESCAPE: char = '\u{1B}';
216
217fn language_escape(chars: &[char]) -> Option<usize> {
221 let rest = chars.strip_prefix(&[ESCAPE])?;
222 [2, 4].into_iter().find_map(|code_len| {
223 let code = rest.get(..code_len)?;
224 let closed = rest.get(code_len) == Some(&ESCAPE);
225 (closed && code.iter().all(char::is_ascii_alphabetic)).then_some(code_len + 2)
226 })
227}
228
229#[cfg(test)]
230mod tests {
231 use super::*;
232
233 const NON_IDENTITY: [(u8, u32); 41] = [
235 (0x18, 0x02D8),
236 (0x19, 0x02C7),
237 (0x1A, 0x02C6),
238 (0x1B, 0x02D9),
239 (0x1C, 0x02DD),
240 (0x1D, 0x02DB),
241 (0x1E, 0x02DA),
242 (0x1F, 0x02DC),
243 (0x80, 0x2022),
244 (0x81, 0x2020),
245 (0x82, 0x2021),
246 (0x83, 0x2026),
247 (0x84, 0x2014),
248 (0x85, 0x2013),
249 (0x86, 0x0192),
250 (0x87, 0x2044),
251 (0x88, 0x2039),
252 (0x89, 0x203A),
253 (0x8A, 0x2212),
254 (0x8B, 0x2030),
255 (0x8C, 0x201E),
256 (0x8D, 0x201C),
257 (0x8E, 0x201D),
258 (0x8F, 0x2018),
259 (0x90, 0x2019),
260 (0x91, 0x201A),
261 (0x92, 0x2122),
262 (0x93, 0xFB01),
263 (0x94, 0xFB02),
264 (0x95, 0x0141),
265 (0x96, 0x0152),
266 (0x97, 0x0160),
267 (0x98, 0x0178),
268 (0x99, 0x017D),
269 (0x9A, 0x0131),
270 (0x9B, 0x0142),
271 (0x9C, 0x0153),
272 (0x9D, 0x0161),
273 (0x9E, 0x017E),
274 (0xA0, 0x20AC),
275 (0x09, 0x0009),
276 ];
277
278 const UNDEFINED: [u8; 4] = [0x7F, 0x9F, 0xAD, 0x00];
279
280 #[test]
281 fn decode_maps_every_non_identity_code_as_table_d2() {
282 for (code, scalar) in NON_IDENTITY {
283 assert_eq!(pdf_doc_decode(code).map(u32::from), Some(scalar), "code {code:#04x}");
284 }
285 }
286
287 #[test]
288 fn decode_is_identity_for_ascii_and_latin1() {
289 for code in (0x20..=0x7E).chain(0xA1..=0xAC).chain(0xAE..=0xFF) {
290 assert_eq!(pdf_doc_decode(code), Some(char::from(code)), "code {code:#04x}");
291 }
292 }
293
294 #[test]
295 fn decode_leaves_undefined_codes_undefined() {
296 let undefined: Vec<u8> = (0..=0xFF).filter(|&c| pdf_doc_decode(c).is_none()).collect();
297 let mut expected: Vec<u8> = (0x00..0x09).chain([0x0B, 0x0C]).chain(0x0E..0x18).collect();
298 expected.extend([0x7F, 0x9F, 0xAD]);
299 assert_eq!(undefined, expected);
300 }
301
302 #[test]
303 fn encode_reverses_decode_for_every_defined_code() {
304 for code in 0..=0xFF_u8 {
305 if let Some(c) = pdf_doc_decode(code) {
306 assert_eq!(pdf_doc_encode(c), Some(code), "code {code:#04x}");
307 }
308 }
309 }
310
311 #[test]
312 fn encode_rejects_scalars_without_a_code() {
313 for c in ['\u{AD}', '\u{7F}', '\u{0}', '中', '\u{2023}'] {
314 assert_eq!(pdf_doc_encode(c), None, "{c:?}");
315 }
316 }
317
318 #[test]
319 fn decode_text_string_replaces_undefined_pdfdoc_codes() {
320 for code in UNDEFINED {
321 assert_eq!(decode_text_string(&[b'a', code]), "a\u{FFFD}");
322 }
323 }
324
325 #[test]
326 fn decode_text_string_reads_utf16be_surrogate_pairs() {
327 assert_eq!(decode_text_string(b"\xFE\xFF\xD8\x34\xDD\x1E"), "\u{1D11E}");
328 }
329
330 #[test]
331 fn decode_text_string_replaces_an_unpaired_high_surrogate() {
332 assert_eq!(decode_text_string(b"\xFE\xFF\xD8\x34\x00A"), "\u{FFFD}A");
333 }
334
335 #[test]
336 fn decode_text_string_replaces_an_unpaired_low_surrogate() {
337 assert_eq!(decode_text_string(b"\xFE\xFF\xDD\x1E"), "\u{FFFD}");
338 }
339
340 #[test]
341 fn decode_text_string_replaces_a_trailing_odd_byte() {
342 assert_eq!(decode_text_string(b"\xFE\xFF\x00A\x00"), "A\u{FFFD}");
343 }
344
345 #[test]
346 fn decode_text_string_drops_utf16_language_escapes() {
347 assert_eq!(
348 decode_text_string(b"\xFE\xFF\x00\x1B\x00e\x00n\x00\x1B\x00H\x00i"),
349 "Hi"
350 );
351 }
352
353 #[test]
354 fn decode_text_string_drops_language_and_country_escapes() {
355 assert_eq!(
356 decode_text_string(b"\xFE\xFF\x00\x1B\x00e\x00n\x00U\x00S\x00\x1B\x00H\x00i"),
357 "Hi"
358 );
359 }
360
361 #[test]
362 fn decode_text_string_keeps_text_after_a_stray_escape() {
363 assert_eq!(decode_text_string(b"\xFE\xFF\x00\x1B\x00H\x00i"), "\u{FFFD}Hi");
364 }
365
366 #[test]
367 fn decode_text_string_keeps_text_after_an_overlong_escape() {
368 assert_eq!(
369 decode_text_string(b"\xFE\xFF\x00\x1B\x00a\x00b\x00c\x00d\x00e\x00\x1B\x00!"),
370 "\u{FFFD}abcde\u{FFFD}!"
371 );
372 }
373
374 #[test]
375 fn decode_text_string_reads_utf8_with_bom() {
376 assert_eq!(decode_text_string(b"\xEF\xBB\xBF\xE2\x82\xAC"), "€");
377 }
378
379 #[test]
380 fn decode_text_string_replaces_invalid_utf8() {
381 assert_eq!(decode_text_string(b"\xEF\xBB\xBFa\xFFb"), "a\u{FFFD}b");
382 }
383
384 #[test]
385 fn decode_text_string_of_an_empty_string_is_empty() {
386 assert_eq!(decode_text_string(b""), "");
387 }
388
389 #[test]
390 fn encode_text_string_round_trips_through_decode() {
391 for text in [
392 "",
393 "Title",
394 "Café €",
395 "• – —",
396 "中文",
397 "emoji 😀",
398 "þÿ",
399 "x",
400 "\u{7F}",
401 ] {
402 assert_eq!(decode_text_string(&encode_text_string(text)), text, "{text:?}");
403 }
404 }
405
406 #[test]
407 fn encode_text_string_never_writes_a_language_escape() {
408 let text = "a\u{1B}en\u{1B}b";
409 assert_eq!(decode_text_string(&encode_text_string(text)), "a\u{FFFD}en\u{FFFD}b");
410 }
411
412 #[test]
413 fn encode_text_string_prefers_pdfdoc() {
414 assert_eq!(encode_text_string("A€"), b"A\xA0");
415 }
416
417 #[test]
418 fn decode_text_string_without_a_bom_is_pdfdoc() {
419 assert_eq!(decode_text_string(b"\xFE"), "\u{FE}");
420 }
421}