printpdf 0.12.4

Rust library for reading and writing PDF files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
/// ToUnicode CMap parsing
use std::collections::BTreeMap;

use lopdf::{Dictionary, Document, Object};

use crate::text::CMap;

/// A single bfrange line may cover at most this many CIDs. Real CMaps map 1–4 byte
/// codes, so no legitimate range spans more than 64k entries — but the CMap stream of
/// a parsed PDF is attacker-controlled, and one hostile 3-token line like
/// `<00000000> <FFFFFFFF> <0041>` would otherwise expand to 2^32 map insertions.
const MAX_BFRANGE_ENTRIES: u64 = 65_536;

/// The mapping from a CID to one or more Unicode code points.
#[derive(Debug)]
pub struct ToUnicodeCMap {
    pub mappings: BTreeMap<u32, Vec<u32>>,
}

/// One whitespace-separated CMap token.
#[derive(Debug, Clone, PartialEq)]
enum CMapToken {
    /// `<...>` hex string (raw hex digits, without the delimiters)
    Hex(String),
    /// `[`
    ArrayOpen,
    /// `]`
    ArrayClose,
    /// any other token (keywords, numbers, names, ...)
    Word(String),
}

/// Tokenize a CMap stream. PostScript is whitespace/delimiter separated, so
/// `1 beginbfchar<0003><0020>endbfchar` on a single line is legal — a line-based
/// parser silently loses those mappings. Comments (`%` to end of line) are skipped.
fn tokenize_cmap(input: &str) -> Vec<CMapToken> {
    let mut tokens = Vec::new();
    let mut chars = input.char_indices().peekable();

    while let Some(&(i, c)) = chars.peek() {
        match c {
            '%' => {
                // comment until end of line
                while let Some(&(_, c2)) = chars.peek() {
                    if c2 == '\n' {
                        break;
                    }
                    chars.next();
                }
            }
            '<' => {
                chars.next();
                let start = i + 1;
                let mut end = start;
                while let Some(&(j, c2)) = chars.peek() {
                    if c2 == '>' {
                        chars.next();
                        break;
                    }
                    // `<<` starts a dictionary, not a hex string — treat like a word
                    end = j + c2.len_utf8();
                    chars.next();
                }
                tokens.push(CMapToken::Hex(
                    input[start..end].split_whitespace().collect::<String>(),
                ));
            }
            '[' => {
                chars.next();
                tokens.push(CMapToken::ArrayOpen);
            }
            ']' => {
                chars.next();
                tokens.push(CMapToken::ArrayClose);
            }
            c if c.is_whitespace() => {
                chars.next();
            }
            _ => {
                let start = i;
                let mut end = i;
                while let Some(&(j, c2)) = chars.peek() {
                    if c2.is_whitespace() || c2 == '<' || c2 == '[' || c2 == ']' || c2 == '%' {
                        break;
                    }
                    end = j + c2.len_utf8();
                    chars.next();
                }
                tokens.push(CMapToken::Word(input[start..end].to_string()));
            }
        }
    }

    tokens
}

/// Parse a hex string token used as a *code* (CID): a single big-endian number.
fn hex_to_u32(hex: &str) -> Result<u32, String> {
    if hex.is_empty() {
        return Err("empty hex token".to_string());
    }
    u32::from_str_radix(hex, 16).map_err(|e| format!("Failed to parse hex token <{}>: {}", hex, e))
}

/// Parse a hex string token used as a *target*: UTF-16BE code units, possibly
/// several characters (ligatures like `<004600660069>` = "ffi") and possibly
/// surrogate pairs (`<D835DC56>` = U+1D456). Returns Unicode scalar values.
///
/// Tokens of up to 4 hex digits (the overwhelmingly common case) decode exactly
/// like the old single-number path.
fn hex_to_unicode_scalars(hex: &str) -> Result<Vec<u32>, String> {
    if hex.is_empty() {
        return Err("empty hex token".to_string());
    }
    if hex.len() <= 4 {
        // single UTF-16 code unit (or fewer digits, e.g. `<20>`)
        return Ok(vec![hex_to_u32(hex)?]);
    }
    if hex.len() % 4 != 0 {
        // Not a whole number of UTF-16BE units; historic behavior parsed the
        // token as one number, keep that as a fallback for short odd tokens.
        return hex_to_u32(hex).map(|v| vec![v]);
    }
    let mut units = Vec::with_capacity(hex.len() / 4);
    for i in (0..hex.len()).step_by(4) {
        units.push(
            u16::from_str_radix(&hex[i..i + 4], 16)
                .map_err(|e| format!("Failed to parse hex token <{}>: {}", hex, e))?,
        );
    }
    let scalars: Vec<u32> = char::decode_utf16(units.iter().copied())
        .map(|r| r.map(|c| c as u32).unwrap_or(0xFFFD))
        .collect();
    Ok(scalars)
}

impl ToUnicodeCMap {
    /// Parses a ToUnicode CMap from the given input string.
    pub fn parse(input: &str) -> Result<ToUnicodeCMap, String> {
        let mut mappings = BTreeMap::new();
        let tokens = tokenize_cmap(input);
        let mut i = 0;

        while i < tokens.len() {
            match &tokens[i] {
                CMapToken::Word(w) if w == "beginbfchar" => {
                    i += 1;
                    // Each mapping is: <code> <target>
                    while i < tokens.len() {
                        match (&tokens[i], tokens.get(i + 1)) {
                            (CMapToken::Word(w), _) if w == "endbfchar" => break,
                            (CMapToken::Hex(code), Some(CMapToken::Hex(target))) => {
                                let cid = hex_to_u32(code)?;
                                let uni = hex_to_unicode_scalars(target)?;
                                mappings.insert(cid, uni);
                                i += 2;
                            }
                            _ => {
                                // skip malformed token
                                i += 1;
                            }
                        }
                    }
                }
                CMapToken::Word(w) if w == "beginbfrange" => {
                    i += 1;
                    while i < tokens.len() {
                        // Two forms:
                        //   form1: <start> <end> <startUnicode>
                        //   form2: <start> <end> [ <unicode1> <unicode2> ... ]
                        match &tokens[i] {
                            CMapToken::Word(w) if w == "endbfrange" => break,
                            CMapToken::Hex(start_tok) => {
                                let Some(CMapToken::Hex(end_tok)) = tokens.get(i + 1) else {
                                    i += 1;
                                    continue;
                                };
                                let start = hex_to_u32(start_tok)?;
                                let end = hex_to_u32(end_tok)?;
                                // Reject reversed and oversized ranges instead of expanding
                                // them: `end - start + 1` underflows (panics with overflow
                                // checks on) when end < start, and an unbounded span is a
                                // decompression-bomb-style DoS. The caller
                                // (extract_to_unicode_cmap) downgrades the Err to a warning,
                                // so a hostile CMap costs the font its ToUnicode map but
                                // never the whole document.
                                if end < start {
                                    return Err(format!(
                                        "bfrange: end {:04X} < start {:04X}",
                                        end, start
                                    ));
                                }
                                let span = end - start;
                                if span as u64 + 1 > MAX_BFRANGE_ENTRIES {
                                    return Err(format!(
                                        "bfrange spans {} CIDs (max {})",
                                        span as u64 + 1,
                                        MAX_BFRANGE_ENTRIES
                                    ));
                                }
                                match tokens.get(i + 2) {
                                    Some(CMapToken::ArrayOpen) => {
                                        // form2: one target per CID.
                                        i += 3;
                                        let mut offset = 0u32;
                                        while i < tokens.len() {
                                            match &tokens[i] {
                                                CMapToken::ArrayClose => {
                                                    i += 1;
                                                    break;
                                                }
                                                CMapToken::Hex(target) => {
                                                    // Ignore surplus entries beyond the
                                                    // declared range instead of erroring:
                                                    // partial data beats no data.
                                                    if offset <= span {
                                                        let uni = hex_to_unicode_scalars(target)?;
                                                        mappings.insert(start + offset, uni);
                                                    }
                                                    offset += 1;
                                                    i += 1;
                                                }
                                                _ => {
                                                    i += 1;
                                                }
                                            }
                                        }
                                    }
                                    Some(CMapToken::Hex(target)) => {
                                        // form1: single starting value, incremented over
                                        // the range. Increment applies to the *last*
                                        // character of the target string (ISO 32000-1,
                                        // 9.10.3).
                                        let unis = hex_to_unicode_scalars(target)?;
                                        let last = unis.last().copied().unwrap_or(0);
                                        if last.checked_add(span).is_none() {
                                            return Err(
                                                "bfrange: target unicode values overflow u32"
                                                    .to_string(),
                                            );
                                        }
                                        for off in 0..=span {
                                            let mut target = unis.clone();
                                            if let Some(l) = target.last_mut() {
                                                *l = last + off;
                                            }
                                            mappings.insert(start + off, target);
                                        }
                                        i += 3;
                                    }
                                    _ => {
                                        // malformed entry, skip the start token
                                        i += 1;
                                    }
                                }
                                continue;
                            }
                            _ => {
                                i += 1;
                            }
                        }
                    }
                }
                _ => {}
            }
            i += 1;
        }

        Ok(ToUnicodeCMap { mappings })
    }

    /// Look up a single code/CID, returning its Unicode scalar values.
    pub fn lookup(&self, cid: u32) -> Option<&Vec<u32>> {
        self.mappings.get(&cid)
    }

    /// Map a single code/CID to a String (empty when unmapped).
    pub fn lookup_string(&self, cid: u32) -> Option<String> {
        let unis = self.mappings.get(&cid)?;
        let s: String = unis
            .iter()
            .filter_map(|&u| std::char::from_u32(u))
            .collect();
        if s.is_empty() {
            None
        } else {
            Some(s)
        }
    }

    /// Generates a CMap string representation suitable for embedding in a PDF.
    pub fn to_cmap_string(&self, font_name: &str) -> String {
        // Header section
        let mut result = format!(
            "/CIDInit /ProcSet findresource begin\n\n12 dict begin\n\nbegincmap\n\n%!PS-Adobe-3.0 \
             Resource-CMap\n%%DocumentNeededResources: procset CIDInit\n%%IncludeResource: \
             procset CIDInit\n\n/CIDSystemInfo 3 dict dup begin\n/Registry (FontSpecific) \
             def\n/Ordering ({}) def\n/Supplement 0 def\nend def\n\n/CMapName /FontSpecific-{} \
             def\n/CMapVersion 1 def\n/CMapType 2 def\n/WMode 0 def\n\n1 \
             begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n",
            font_name, font_name
        );

        // Group mappings by high byte for better organization
        let mut grouped_by_high_byte: BTreeMap<u8, Vec<(u32, &Vec<u32>)>> = BTreeMap::new();

        for (&cid, unicode_values) in &self.mappings {
            if unicode_values.is_empty() {
                continue;
            }
            let high_byte = ((cid >> 8) & 0xFF) as u8;
            grouped_by_high_byte
                .entry(high_byte)
                .or_insert_with(Vec::new)
                .push((cid, unicode_values));
        }

        // Generate bfchar blocks with at most 100 entries each
        for (_high_byte, mut entries) in grouped_by_high_byte {
            // Sort by CID for deterministic output
            entries.sort_by_key(|&(cid, _)| cid);

            // Process in chunks of 100
            for chunk in entries.chunks(100) {
                result.push_str(&format!("{} beginbfchar\n", chunk.len()));
                for &(cid, unicode_values) in chunk {
                    // Encode the full target as UTF-16BE so multi-char mappings
                    // (ligatures) and non-BMP chars survive the round trip.
                    let mut target_hex = String::new();
                    for &u in unicode_values {
                        match std::char::from_u32(u) {
                            Some(c) => {
                                let mut buf = [0u16; 2];
                                for unit in c.encode_utf16(&mut buf) {
                                    target_hex.push_str(&format!("{:04X}", unit));
                                }
                            }
                            None => target_hex.push_str(&format!("{:04X}", u)),
                        }
                    }
                    result.push_str(&format!("<{:04X}> <{}>\n", cid, target_hex));
                }
                result.push_str("endbfchar\n");
            }
        }

        // Footer section
        result.push_str(
            "\
            endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n",
        );

        result
    }
}

// ---------------------------------------------------------------------------
// CID CMaps (the Type0 /Encoding side — NOT ToUnicode)
// ---------------------------------------------------------------------------

/// A code→CID CMap: the `/Encoding` of a composite (Type0) font (ISO 32000-1,
/// 9.7.5). Where [`ToUnicodeCMap`] maps *codes to text* for extraction, this maps
/// the raw content-stream bytes to *codes* (via the codespace ranges — codes may
/// be 1–4 bytes, variable width!) and codes to *CIDs* (via cidrange/cidchar).
///
/// Built either from an embedded CMap stream or from the two predefined CMaps
/// printpdf fully supports without external data (`Identity-H`/`Identity-V`).
/// The other predefined CMaps (90ms-RKSJ-H, GBK-EUC-H, UniJIS-UCS2-H, …) require
/// Adobe's CMap data files, which printpdf does not ship — the caller keeps its
/// warning for those.
#[derive(Debug, Clone, PartialEq)]
pub struct CidCMap {
    /// 0 = horizontal, 1 = vertical (`/WMode`).
    pub wmode: u8,
    /// `(byte_len, lo_bytes, hi_bytes)` — a code of `byte_len` bytes belongs to
    /// this range when every byte lies within the corresponding lo/hi bytes
    /// (bytewise comparison per spec, not numeric).
    codespace: Vec<(u8, [u8; 4], [u8; 4])>,
    /// `(byte_len, lo, hi, dst_cid)` from cidrange: code → dst + (code - lo).
    ranges: Vec<(u8, u32, u32, u32)>,
    /// `(byte_len, code, cid)` from cidchar.
    singles: BTreeMap<(u8, u32), u32>,
    /// True for the identity CMaps: code == CID, no table lookups needed.
    identity: bool,
}

/// One entry from a CMap-supported hex range line may cover at most this many
/// codes; mirrors [`MAX_BFRANGE_ENTRIES`] (the stream is attacker-controlled).
const MAX_CIDRANGE_SPAN: u64 = 65_536;

impl CidCMap {
    /// The `Identity-H` (wmode 0) / `Identity-V` (wmode 1) predefined CMap:
    /// 2-byte codes, code == CID.
    pub fn identity(wmode: u8) -> Self {
        CidCMap {
            wmode,
            codespace: vec![(2, [0, 0, 0, 0], [0xFF, 0xFF, 0, 0])],
            ranges: Vec::new(),
            singles: BTreeMap::new(),
            identity: true,
        }
    }

    /// Whether this is one of the identity CMaps (the fast path everywhere).
    pub fn is_identity(&self) -> bool {
        self.identity
    }

    /// Parse an embedded CMap stream. Returns the CMap plus the name of a
    /// `usecmap` base it could NOT resolve (only the identity CMaps can be
    /// resolved without Adobe's data files) — the caller should warn about it.
    pub fn parse(input: &str) -> Result<(CidCMap, Option<String>), String> {
        let tokens = tokenize_cmap(input);
        let mut cmap = CidCMap {
            wmode: 0,
            codespace: Vec::new(),
            ranges: Vec::new(),
            singles: BTreeMap::new(),
            identity: false,
        };
        let mut unresolved_usecmap = None;

        let hex_bytes = |hex: &str| -> Result<(u8, [u8; 4], u32), String> {
            let digits = hex.len();
            if digits == 0 || digits > 8 || digits % 2 != 0 {
                return Err(format!("codespace hex <{hex}> is not 1–4 bytes"));
            }
            let len = (digits / 2) as u8;
            let mut bytes = [0u8; 4];
            for (idx, i) in (0..digits).step_by(2).enumerate() {
                bytes[idx] = u8::from_str_radix(&hex[i..i + 2], 16)
                    .map_err(|e| format!("bad hex <{hex}>: {e}"))?;
            }
            Ok((len, bytes, hex_to_u32(hex)?))
        };

        let mut i = 0;
        while i < tokens.len() {
            match &tokens[i] {
                CMapToken::Word(w) if w == "begincodespacerange" => {
                    i += 1;
                    while i < tokens.len() {
                        match (&tokens[i], tokens.get(i + 1)) {
                            (CMapToken::Word(w), _) if w == "endcodespacerange" => break,
                            (CMapToken::Hex(lo), Some(CMapToken::Hex(hi))) => {
                                let (llen, lb, _) = hex_bytes(lo)?;
                                let (hlen, hb, _) = hex_bytes(hi)?;
                                if llen == hlen {
                                    cmap.codespace.push((llen, lb, hb));
                                }
                                i += 2;
                            }
                            _ => i += 1,
                        }
                    }
                }
                CMapToken::Word(w) if w == "begincidrange" || w == "beginnotdefrange" => {
                    let end_kw = if w == "begincidrange" {
                        "endcidrange"
                    } else {
                        "endnotdefrange"
                    };
                    i += 1;
                    while i < tokens.len() {
                        match (&tokens[i], tokens.get(i + 1), tokens.get(i + 2)) {
                            (CMapToken::Word(w), _, _) if w == end_kw => break,
                            (
                                CMapToken::Hex(lo),
                                Some(CMapToken::Hex(hi)),
                                Some(CMapToken::Word(dst)),
                            ) => {
                                let (llen, _, lov) = hex_bytes(lo)?;
                                let (hlen, _, hiv) = hex_bytes(hi)?;
                                let dst: u32 = dst
                                    .parse()
                                    .map_err(|e| format!("cidrange dst {dst:?}: {e}"))?;
                                if llen == hlen && lov <= hiv {
                                    if (hiv - lov) as u64 + 1 > MAX_CIDRANGE_SPAN {
                                        return Err(format!(
                                            "cidrange spans {} codes (max {})",
                                            (hiv - lov) as u64 + 1,
                                            MAX_CIDRANGE_SPAN
                                        ));
                                    }
                                    cmap.ranges.push((llen, lov, hiv, dst));
                                }
                                i += 3;
                            }
                            _ => i += 1,
                        }
                    }
                }
                CMapToken::Word(w) if w == "begincidchar" => {
                    i += 1;
                    while i < tokens.len() {
                        match (&tokens[i], tokens.get(i + 1)) {
                            (CMapToken::Word(w), _) if w == "endcidchar" => break,
                            (CMapToken::Hex(code), Some(CMapToken::Word(cid))) => {
                                let (len, _, code_v) = hex_bytes(code)?;
                                if let Ok(cid) = cid.parse::<u32>() {
                                    cmap.singles.insert((len, code_v), cid);
                                }
                                i += 2;
                            }
                            _ => i += 1,
                        }
                    }
                }
                CMapToken::Word(w) if w == "usecmap" => {
                    // The base CMap name is the last /Name token before `usecmap`.
                    let base = tokens[..i].iter().rev().find_map(|t| match t {
                        CMapToken::Word(w) if w.starts_with('/') => Some(w[1..].to_string()),
                        _ => None,
                    });
                    match base.as_deref() {
                        Some("Identity-H") => cmap.identity = cmap.tables_are_empty(),
                        Some("Identity-V") => {
                            cmap.identity = cmap.tables_are_empty();
                            cmap.wmode = 1;
                        }
                        Some(other) => unresolved_usecmap = Some(other.to_string()),
                        None => {}
                    }
                }
                CMapToken::Word(w) if w == "/WMode" => {
                    if let Some(CMapToken::Word(v)) = tokens.get(i + 1) {
                        if v == "1" {
                            cmap.wmode = 1;
                        }
                    }
                }
                _ => {}
            }
            i += 1;
        }

        // A CMap with no codespace at all cannot split codes; assume the
        // ubiquitous 2-byte space rather than failing the whole font.
        if cmap.codespace.is_empty() {
            cmap.codespace.push((2, [0, 0, 0, 0], [0xFF, 0xFF, 0, 0]));
        }
        Ok((cmap, unresolved_usecmap))
    }

    fn tables_are_empty(&self) -> bool {
        self.ranges.is_empty() && self.singles.is_empty()
    }

    /// Split a content-stream string into `(code, byte_len)` per the codespace
    /// ranges (ISO 32000-1, 9.7.6.2): a code matches a range of length L when its
    /// L bytes each lie within the range's corresponding lo/hi bytes. On no
    /// match, the shortest range length starting at a matching first byte is
    /// consumed (mapping to notdef later); failing that, one byte.
    pub fn split_codes(&self, bytes: &[u8]) -> Vec<(u32, u8)> {
        let mut out = Vec::with_capacity(bytes.len() / 2);
        let mut pos = 0;
        while pos < bytes.len() {
            let rest = &bytes[pos..];
            let mut matched: Option<u8> = None;
            // Prefer the shortest matching range (ranges are tried by length).
            let mut lens: Vec<u8> = self.codespace.iter().map(|(l, ..)| *l).collect();
            lens.sort_unstable();
            lens.dedup();
            'outer: for len in lens {
                let len_usize = len as usize;
                if rest.len() < len_usize {
                    continue;
                }
                for (l, lo, hi) in &self.codespace {
                    if *l != len {
                        continue;
                    }
                    if (0..len_usize)
                        .all(|k| rest[k] >= lo[k] && rest[k] <= hi[k])
                    {
                        matched = Some(len);
                        break 'outer;
                    }
                }
            }
            let len = matched.unwrap_or_else(|| {
                // No full match: shortest range whose FIRST byte matches, else 1.
                self.codespace
                    .iter()
                    .filter(|(l, lo, hi)| {
                        *l >= 1 && rest[0] >= lo[0] && rest[0] <= hi[0]
                    })
                    .map(|(l, ..)| *l)
                    .min()
                    .unwrap_or(1)
            });
            let len_usize = (len as usize).min(rest.len());
            let mut code = 0u32;
            for &b in &rest[..len_usize] {
                code = (code << 8) | b as u32;
            }
            out.push((code, len_usize as u8));
            pos += len_usize;
        }
        out
    }

    /// The CID for a code of the given byte length. Unmapped codes are CID 0
    /// (notdef) — except for the identity CMaps, where code == CID by
    /// definition.
    pub fn cid_for_code(&self, code: u32, byte_len: u8) -> u32 {
        if self.identity {
            return code;
        }
        if let Some(cid) = self.singles.get(&(byte_len, code)) {
            return *cid;
        }
        for (len, lo, hi, dst) in &self.ranges {
            if *len == byte_len && code >= *lo && code <= *hi {
                return dst + (code - lo);
            }
        }
        0
    }
}

/// Implement the CMap trait on our ToUnicodeCMap.
impl CMap for ToUnicodeCMap {
    fn map_bytes(&self, bytes: &[u8]) -> String {
        // For simplicity, assume that the byte sequence represents CIDs in big-endian,
        // and that each CID is 2 bytes long.
        let mut result = String::new();
        let mut i = 0;
        while i + 1 < bytes.len() {
            let cid = u16::from_be_bytes([bytes[i], bytes[i + 1]]) as u32;
            if let Some(unis) = self.mappings.get(&cid) {
                for &u in unis {
                    if let Some(ch) = std::char::from_u32(u) {
                        result.push(ch);
                    }
                }
            }
            i += 2;
        }
        result
    }
}

/// Looks for a `ToUnicode` CMap entry on the dictionary, resolves it to a dictionary
/// and parses the `ToUnicodeCMap`.
pub fn get_to_unicode_cmap_from_font(
    font_dict: &Dictionary,
    doc: &Document,
) -> Result<ToUnicodeCMap, String> {
    let to_unicode_obj = font_dict
        .get(b"ToUnicode")
        .ok()
        .ok_or("No ToUnicode entry found")?;

    let stream = match to_unicode_obj {
        Object::Reference(r) => doc
            .get_object(*r)
            .and_then(|obj| obj.as_stream().map(|s| s.clone()))
            .map_err(|e| format!("Error getting ToUnicode stream: {}", e))?,
        Object::Stream(s) => s.clone(),
        _ => return Err("Unexpected type for ToUnicode entry".into()),
    };

    let content = stream
        .decompressed_content()
        .map_err(|e| format!("Decompress error: {}", e))?;

    let cmap_str =
        String::from_utf8(content).map_err(|e| format!("UTF-8 conversion error: {}", e))?;

    ToUnicodeCMap::parse(&cmap_str)
}

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

    #[test]
    fn single_line_bfchar_is_parsed() {
        // PostScript does not require newlines; a line-based parser lost these.
        let cmap = "begincmap 1 beginbfchar <0003> <0020> endbfchar endcmap";
        let parsed = ToUnicodeCMap::parse(cmap).unwrap();
        assert_eq!(parsed.mappings.get(&3), Some(&vec![0x20]));
    }

    #[test]
    fn multi_codepoint_bfchar_target() {
        // <00660066> is the two-character target "ff". The old parser tried to
        // read it as one u32 (0x00660066) and produced garbage, and 12-digit
        // targets made the whole CMap fail to parse.
        let cmap = "beginbfchar\n<0001> <00660066>\n<0002> <004600660069>\nendbfchar";
        let parsed = ToUnicodeCMap::parse(cmap).unwrap();
        assert_eq!(parsed.mappings.get(&1), Some(&vec![0x66, 0x66]));
        assert_eq!(parsed.mappings.get(&2), Some(&vec![0x46, 0x66, 0x69]));
    }

    #[test]
    fn surrogate_pair_bfchar_target() {
        // <D835DC56> is U+1D456 (mathematical italic small i) as UTF-16BE.
        let cmap = "beginbfchar\n<0001> <D835DC56>\nendbfchar";
        let parsed = ToUnicodeCMap::parse(cmap).unwrap();
        assert_eq!(parsed.mappings.get(&1), Some(&vec![0x1D456]));
    }

    #[test]
    fn bfrange_form1_still_works() {
        let cmap = "beginbfrange\n<0041> <0043> <0061>\nendbfrange";
        let parsed = ToUnicodeCMap::parse(cmap).unwrap();
        assert_eq!(parsed.mappings.get(&0x41), Some(&vec![0x61]));
        assert_eq!(parsed.mappings.get(&0x42), Some(&vec![0x62]));
        assert_eq!(parsed.mappings.get(&0x43), Some(&vec![0x63]));
    }

    #[test]
    fn bfrange_form2_array_still_works() {
        let cmap = "beginbfrange\n<0001> <0002> [<0041> <0042>]\nendbfrange";
        let parsed = ToUnicodeCMap::parse(cmap).unwrap();
        assert_eq!(parsed.mappings.get(&1), Some(&vec![0x41]));
        assert_eq!(parsed.mappings.get(&2), Some(&vec![0x42]));
    }

    #[test]
    fn bfrange_reversed_is_error() {
        // Guard: keep rejecting reversed ranges (underflow / DoS protection).
        let cmap = "beginbfrange\n<0002> <0001> [<0041>]\nendbfrange";
        assert!(ToUnicodeCMap::parse(cmap).is_err());
    }

    #[test]
    fn bfrange_huge_range_is_bounded() {
        // Guard: a hostile few-byte bfrange must not allocate 2^21 entries.
        let cmap = "beginbfrange\n<000000> <1FFFFF> <0041>\nendbfrange";
        match ToUnicodeCMap::parse(cmap) {
            Ok(m) => assert!(m.mappings.len() <= 65_536),
            Err(_) => {}
        }
    }

    #[test]
    fn roundtrip_through_cmap_string() {
        let mut mappings = BTreeMap::new();
        mappings.insert(1, vec![0x66, 0x66]); // "ff" ligature
        mappings.insert(2, vec![0x1D456]); // non-BMP char
        mappings.insert(3, vec![0x41]);
        let cmap = ToUnicodeCMap { mappings };
        let s = cmap.to_cmap_string("TESTFONT");
        let reparsed = ToUnicodeCMap::parse(&s).unwrap();
        assert_eq!(reparsed.mappings.get(&1), Some(&vec![0x66, 0x66]));
        assert_eq!(reparsed.mappings.get(&2), Some(&vec![0x1D456]));
        assert_eq!(reparsed.mappings.get(&3), Some(&vec![0x41]));
    }
}