lopdf 0.48.0

A Rust library for PDF document manipulation.
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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
use log::warn;

use crate::{
    DEFAULT_MAX_DECOMPRESSED_SIZE, Error, Result,
    content::{Content, Operation},
    document::Document,
    encodings::Encoding,
    error::ParseError,
    object::Object::Name,
    xref::{Xref, XrefEntry, XrefType},
};
use crate::{Dictionary, Object, ObjectId, Stream, parser};
use std::{
    collections::BTreeMap,
    io::{Cursor, Read},
};

impl Content<Vec<Operation>> {
    /// Decode content operations.
    pub fn decode(data: &[u8]) -> Result<Self> {
        parser::content(data).ok_or(ParseError::InvalidContentStream.into())
    }

    /// Decode content operations one at a time without collecting them.
    ///
    /// Yields the operations [`Content::decode`] returns, or its error at the point
    /// where the decode fails.
    pub fn decode_iter(data: &[u8]) -> parser::ContentOperations<'_> {
        parser::ContentOperations::new(data)
    }

    /// Strict decode content operations.
    pub fn decode_strict(data: &[u8]) -> Result<Self> {
        parser::content_strict(data).map_err(|e| e.into())
    }
}

impl Stream {
    /// Decode content after decoding all stream filters.
    pub fn decode_content(&self) -> Result<Content<Vec<Operation>>> {
        Content::decode(&self.content)
    }
}

impl Document {
    /// Get decoded page content;
    pub fn get_and_decode_page_content(&self, page_id: ObjectId) -> Result<Content<Vec<Operation>>> {
        let content_data = self.get_page_content(page_id);
        Content::decode(&content_data)
    }

    /// Add content to a page. All existing content will be unchanged.
    pub fn add_to_page_content(&mut self, page_id: ObjectId, content: Content<Vec<Operation>>) -> Result<()> {
        let content_data = Content::encode(&content)?;
        self.add_page_contents(page_id, content_data)?;
        Ok(())
    }

    /// Extract text from the given pages.
    ///
    /// The decompressed content of each page is bounded by
    /// [`DEFAULT_MAX_DECOMPRESSED_SIZE`](crate::DEFAULT_MAX_DECOMPRESSED_SIZE); a page
    /// over it fails with
    /// [`DecompressError::MemoryLimitExceeded`](crate::DecompressError::MemoryLimitExceeded).
    /// Use [`Document::extract_text_with_limit`] to choose a different bound.
    pub fn extract_text(&self, page_numbers: &[u32]) -> Result<String> {
        self.extract_text_inner(page_numbers, Some(DEFAULT_MAX_DECOMPRESSED_SIZE))
    }

    /// Extract text from the given pages, bounding the total decompressed content
    /// of each page to `max_decompressed_size` bytes.
    ///
    /// Page content is decoded via [`Document::get_page_content_with_limit`], so a
    /// small compressed content stream cannot inflate without limit. Returns
    /// [`DecompressError::MemoryLimitExceeded`](crate::DecompressError::MemoryLimitExceeded)
    /// if any requested page's content would exceed the limit.
    pub fn extract_text_with_limit(&self, page_numbers: &[u32], max_decompressed_size: usize) -> Result<String> {
        self.extract_text_inner(page_numbers, Some(max_decompressed_size))
    }

    fn extract_text_inner(&self, page_numbers: &[u32], limit: Option<usize>) -> Result<String> {
        let text_fragments = self.extract_text_chunks_inner(page_numbers, limit);
        let mut text = String::new();
        for maybe_text_fragment in text_fragments.into_iter() {
            let text_fragment = maybe_text_fragment?;
            text.push_str(&text_fragment);
        }

        Ok(text)
    }

    /// Extract text from the given pages as separate chunks.
    ///
    /// The decompressed content of each page is bounded by
    /// [`DEFAULT_MAX_DECOMPRESSED_SIZE`](crate::DEFAULT_MAX_DECOMPRESSED_SIZE); a page
    /// over it yields an `Err` chunk. Use [`Document::extract_text_chunks_with_limit`]
    /// to choose a different bound.
    pub fn extract_text_chunks(&self, page_numbers: &[u32]) -> Vec<Result<String>> {
        self.extract_text_chunks_inner(page_numbers, Some(DEFAULT_MAX_DECOMPRESSED_SIZE))
    }

    /// Counterpart to [`Document::extract_text_chunks`] with a caller-chosen bound on the
    /// total decompressed content of each page to `max_decompressed_size` bytes.
    /// A page whose content exceeds the limit yields an `Err` chunk carrying
    /// [`DecompressError::MemoryLimitExceeded`](crate::DecompressError::MemoryLimitExceeded).
    pub fn extract_text_chunks_with_limit(
        &self, page_numbers: &[u32], max_decompressed_size: usize,
    ) -> Vec<Result<String>> {
        self.extract_text_chunks_inner(page_numbers, Some(max_decompressed_size))
    }

    fn extract_text_chunks_inner(&self, page_numbers: &[u32], limit: Option<usize>) -> Vec<Result<String>> {
        let pages: BTreeMap<u32, (u32, u16)> = self.get_pages();
        page_numbers
            .iter()
            .flat_map(|page_number| {
                let result = self.extract_text_chunks_from_page(&pages, *page_number, limit);
                match result {
                    Ok(text_chunks) => text_chunks,
                    Err(err) => vec![Err(err)],
                }
            })
            .collect()
    }

    fn extract_text_chunks_from_page(
        &self, pages: &BTreeMap<u32, (u32, u16)>, page_number: u32, limit: Option<usize>,
    ) -> Result<Vec<Result<String>>> {
        let mut collected_chunks_and_errs: Vec<std::result::Result<String, Error>> = Vec::new();

        let page_id = *pages.get(&page_number).ok_or(Error::PageNumberNotFound(page_number))?;
        let fonts = self.get_page_fonts(page_id)?;
        let encodings: BTreeMap<Vec<u8>, Encoding> = fonts
            .into_iter()
            .filter_map(|(name, font)| {
                let encoding = match limit {
                    Some(max) => font.get_font_encoding_with_limit(self, max),
                    None => font.get_font_encoding(self),
                };
                match encoding {
                    Ok(it) => Some((name, it)),
                    Err(err) => {
                        collected_chunks_and_errs.push(Err(err));
                        None
                    }
                }
            })
            .collect();
        let content_data = match limit {
            Some(max) => self.get_page_content_with_limit(page_id, max)?,
            None => self.get_page_content(page_id),
        };
        let content = Content::decode(&content_data)?;

        // each text with different encoding is extracted as separate chunk
        let mut current_encoding = None;
        let mut current_text = String::new();
        for operation in &content.operations {
            match operation.operator.as_ref() {
                "Tf" => {
                    let current_font = operation
                        .operands
                        .first()
                        .ok_or_else(|| Error::Syntax("missing font operand".to_string()))?
                        .as_name();
                    current_encoding = match current_font {
                        Ok(font) => encodings.get(font),
                        Err(err) => {
                            collected_chunks_and_errs.push(Err(err));
                            None
                        }
                    };

                    if !current_text.is_empty() {
                        collected_chunks_and_errs.push(Ok(current_text));
                        current_text = String::new();
                    }
                }
                "Tj" | "TJ" => match current_encoding {
                    Some(encoding) => {
                        let res = collect_text(&mut current_text, encoding, &operation.operands);
                        if let Err(err) = res {
                            collected_chunks_and_errs.push(Err(err));
                        }
                    }
                    None => warn!("Could not decode extracted text"),
                },
                // PDF 32000-1 §9.4.3: `'` is `T* Tj` — move to the next line, then show
                // the single string operand.
                "'" => match current_encoding {
                    Some(encoding) => {
                        if !current_text.ends_with('\n') {
                            current_text.push('\n');
                        }
                        let res = collect_text(&mut current_text, encoding, &operation.operands);
                        if let Err(err) = res {
                            collected_chunks_and_errs.push(Err(err));
                        }
                    }
                    None => warn!("Could not decode extracted text"),
                },
                // PDF 32000-1 §9.4.3: `"` is `aw Tw ac Tc T* Tj`. Operands 0/1 only affect
                // rendering spacing; operand 2 is the string to show.
                "\"" => match current_encoding {
                    Some(encoding) => {
                        if !current_text.ends_with('\n') {
                            current_text.push('\n');
                        }
                        if let Some(string_operand) = operation.operands.get(2) {
                            let res = collect_text(&mut current_text, encoding, std::slice::from_ref(string_operand));
                            if let Err(err) = res {
                                collected_chunks_and_errs.push(Err(err));
                            }
                        }
                    }
                    None => warn!("Could not decode extracted text"),
                },
                // PDF 32000-1 §9.4.2: `T*` moves to the next line, approximated as `\n`
                // like the `ET` arm above.
                "T*" if !current_text.ends_with('\n') => current_text.push('\n'),
                "T*" => {}
                "ET" if !current_text.ends_with('\n') => current_text.push('\n'),
                "ET" => {}
                _ => {}
            }
        }
        if !current_text.is_empty() {
            collected_chunks_and_errs.push(Ok(current_text));
        }

        Ok(collected_chunks_and_errs)
    }

    pub fn replace_text(
        &mut self, page_number: u32, text: &str, other_text: &str, default_str: Option<&str>,
    ) -> Result<()> {
        let page = page_number.saturating_sub(1) as usize;
        let page_id = self
            .page_iter()
            .nth(page)
            .ok_or(Error::PageNumberNotFound(page_number))?;
        let encodings: BTreeMap<Vec<u8>, Encoding> = self
            .get_page_fonts(page_id)?
            .into_iter()
            .map(|(name, font)| font.get_font_encoding(self).map(|it| (name, it)))
            .collect::<Result<BTreeMap<Vec<u8>, Encoding>>>()?;
        let content_data = self.get_page_content(page_id);
        let mut content = Content::decode(&content_data)?;
        let mut current_encoding = None;
        for operation in &mut content.operations {
            match operation.operator.as_ref() {
                "Tf" => {
                    let current_font = operation
                        .operands
                        .first()
                        .ok_or_else(|| Error::Syntax("missing font operand".to_string()))?
                        .as_name()?;
                    current_encoding = encodings.get(current_font);
                }
                "Tj" | "TJ" => match current_encoding {
                    Some(encoding) => {
                        try_to_replace_encoded_text(operation, encoding, text, other_text, default_str.unwrap_or(""))?
                    }
                    None => {
                        warn!("Could not decode extracted text, some of the occurances might not be properly replaced")
                    }
                },
                _ => {}
            }
        }
        let modified_content = content.encode()?;
        self.change_page_content(page_id, modified_content)
    }

    pub fn replace_partial_text(
        &mut self, page_number: u32, search_text: &str, replacement_text: &str, default_char: Option<&str>,
    ) -> Result<usize> {
        let page = page_number.saturating_sub(1) as usize;
        let page_id = self
            .page_iter()
            .nth(page)
            .ok_or(Error::PageNumberNotFound(page_number))?;

        let encodings: BTreeMap<Vec<u8>, Encoding> = self
            .get_page_fonts(page_id)?
            .into_iter()
            .map(|(name, font)| font.get_font_encoding(self).map(|it| (name, it)))
            .collect::<Result<BTreeMap<Vec<u8>, Encoding>>>()?;

        let content_data = self.get_page_content(page_id);
        let mut content = Content::decode(&content_data)?;
        let mut current_encoding = None;
        let mut replacement_count = 0;

        for operation in &mut content.operations {
            match operation.operator.as_ref() {
                "Tf" => {
                    let current_font = operation
                        .operands
                        .first()
                        .ok_or_else(|| Error::Syntax("missing font operand".to_string()))?
                        .as_name()?;
                    current_encoding = encodings.get(current_font);
                }
                "Tj" | "TJ" => {
                    if let Some(encoding) = current_encoding {
                        replacement_count += replace_partial_in_operation(
                            operation,
                            encoding,
                            search_text,
                            replacement_text,
                            default_char.unwrap_or("?"),
                        )?;
                    } else {
                        warn!("No encoding found for text operation");
                    }
                }
                _ => {}
            }
        }

        if replacement_count > 0 {
            let modified_content = content.encode()?;
            self.change_page_content(page_id, modified_content)?;
        }

        Ok(replacement_count)
    }

    pub fn insert_image(
        &mut self, page_id: ObjectId, img_object: Stream, position: (f32, f32), size: (f32, f32),
    ) -> Result<()> {
        let img_id = self.add_object(img_object);
        let img_name = format!("X{}", img_id.0);

        self.add_xobject(page_id, img_name.as_bytes(), img_id)?;

        let mut content = self.get_and_decode_page_content(page_id)?;
        content.operations.push(Operation::new("q", vec![]));
        content.operations.push(Operation::new(
            "cm",
            vec![
                size.0.into(),
                0.into(),
                0.into(),
                size.1.into(),
                position.0.into(),
                position.1.into(),
            ],
        ));
        content
            .operations
            .push(Operation::new("Do", vec![Name(img_name.as_bytes().to_vec())]));
        content.operations.push(Operation::new("Q", vec![]));

        self.change_page_content(page_id, content.encode()?)
    }

    pub fn insert_form_object(&mut self, page_id: ObjectId, form_obj: Stream) -> Result<()> {
        let form_id = self.add_object(form_obj);
        let form_name = format!("X{}", form_id.0);

        let mut content = self.get_and_decode_page_content(page_id)?;
        content.operations.insert(0, Operation::new("q", vec![]));
        content.operations.push(Operation::new("Q", vec![]));
        content
            .operations
            .push(Operation::new("Do", vec![Name(form_name.as_bytes().to_vec())]));
        let modified_content = content.encode()?;
        self.add_xobject(page_id, form_name, form_id)?;

        self.change_page_content(page_id, modified_content)
    }
}
fn collect_text(text: &mut String, encoding: &Encoding, operands: &[Object]) -> Result<()> {
    for operand in operands.iter() {
        match operand {
            Object::String(bytes, _) => {
                encoding.write_to_string(bytes, text)?;
            }
            Object::Array(arr) => {
                collect_text(text, encoding, arr)?;
                text.push(' ');
            }
            Object::Integer(i) if *i < -100 => {
                text.push(' ');
            }
            _ => {}
        }
    }
    Ok(())
}

/// The characters of `s` starting at character index `start`, up to `len` of
/// them. Indices are counted in characters, not bytes, so a multi-byte
/// character is never split. Note that `len == 0` yields one character, not
/// none; this is long-standing behavior relied on by the sole caller.
pub fn substr(s: &str, start: usize, len: usize) -> &str {
    let mut indices = s.char_indices();

    for _ in 0..start {
        if indices.next().is_none() {
            return "";
        }
    }

    let Some((start_idx, _)) = indices.next() else {
        return "";
    };

    let end_idx = indices
        .nth(len.saturating_sub(1))
        .map(|(idx, _)| idx)
        .unwrap_or(s.len());

    &s[start_idx..end_idx]
}

/// Everything from character index `start` to the end of `s`.
pub fn substring(s: &str, start: usize) -> &str {
    s.char_indices().nth(start).map(|(idx, _)| &s[idx..]).unwrap_or("")
}

fn encode(encoding: &Encoding, txt: &str, default_str: &str) -> Vec<u8> {
    let mut chars = txt.chars();
    match (chars.next(), chars.next()) {
        // More than one character: encode each on its own, into one buffer.
        (Some(first), Some(second)) => {
            let mut result = Vec::with_capacity(txt.len());
            result.extend_from_slice(&encode_one(encoding, first, default_str));
            result.extend_from_slice(&encode_one(encoding, second, default_str));
            for c in chars {
                result.extend_from_slice(&encode_one(encoding, c, default_str));
            }
            result
        }
        // Exactly one character: encode it directly.
        (Some(c), None) => encode_one(encoding, c, default_str),
        // Empty: nothing to encode, but keep the caller's fallback contract.
        (None, _) => {
            let encoded = Document::encode_text(encoding, txt);
            if encoded.is_empty() {
                Document::encode_text(encoding, default_str)
            } else {
                encoded
            }
        }
    }
}

/// Encode a single character, falling back to `default_str` when the encoding
/// has no entry for it.
fn encode_one(encoding: &Encoding, c: char, default_str: &str) -> Vec<u8> {
    // A scratch buffer, so the common one-character case does not allocate a
    // `String` per character on the text-extraction path.
    let mut scratch = [0u8; 4];
    let encoded_bytes = Document::encode_text(encoding, c.encode_utf8(&mut scratch));

    if !encoded_bytes.is_empty() {
        encoded_bytes
    } else {
        Document::encode_text(encoding, default_str)
    }
}

fn try_to_replace_encoded_text(
    operation: &mut Operation, encoding: &Encoding, text_to_replace: &str, replacement: &str, default_str: &str,
) -> Result<()> {
    for operand in &mut operation.operands {
        match operand {
            Object::String(bytes, _) => {
                let decoded_text = Document::decode_text(encoding, bytes)?;
                if decoded_text == text_to_replace {
                    let encoded_bytes = encode(encoding, replacement, default_str);
                    *bytes = encoded_bytes;
                }
            }
            Object::Array(arr) => {
                let mut str_collected = String::new();
                collect_text(&mut str_collected, encoding, arr)?;
                if str_collected == text_to_replace {
                    // The `Object::String` count in a `TJ` array need not match the decoded
                    // character count, and kerning entries are interleaved. Least bad option:
                    // fill the first string slot with the whole replacement, empty the rest,
                    // and leave the kerning entries in place.
                    let encoded_replacement = encode(encoding, replacement, default_str);
                    let mut placed = false;
                    for item in arr.iter_mut() {
                        if let Object::String(bytes, _f) = item {
                            if placed {
                                *bytes = Vec::new();
                            } else {
                                bytes.clone_from(&encoded_replacement);
                                placed = true;
                            }
                        }
                    }
                }
            }
            _ => {}
        }
    }

    Ok(())
}

fn replace_partial_in_operation(
    operation: &mut Operation, encoding: &Encoding, search_text: &str, replacement_text: &str, default_char: &str,
) -> Result<usize> {
    let mut replacement_count = 0;

    for operand in &mut operation.operands {
        match operand {
            Object::String(bytes, _) => {
                let decoded_text = Document::decode_text(encoding, bytes)?;
                if decoded_text.contains(search_text) {
                    let new_text = decoded_text.replace(search_text, replacement_text);
                    let encoded_bytes = encode_with_fallback(encoding, &new_text, default_char);
                    *bytes = encoded_bytes;
                    replacement_count += decoded_text.matches(search_text).count();
                }
            }
            Object::Array(arr) => {
                replacement_count +=
                    replace_partial_in_array(arr, encoding, search_text, replacement_text, default_char)?;
            }
            _ => {}
        }
    }

    Ok(replacement_count)
}

fn replace_partial_in_array(
    arr: &mut [Object], encoding: &Encoding, search_text: &str, replacement_text: &str, default_char: &str,
) -> Result<usize> {
    let mut replacement_count = 0;

    for item in arr.iter_mut() {
        if let Object::String(bytes, _) = item {
            let decoded_text = Document::decode_text(encoding, bytes)?;
            if decoded_text.contains(search_text) {
                let new_text = decoded_text.replace(search_text, replacement_text);
                let encoded_bytes = encode_with_fallback(encoding, &new_text, default_char);
                *bytes = encoded_bytes;
                replacement_count += decoded_text.matches(search_text).count();
            }
        }
    }

    Ok(replacement_count)
}

fn encode_with_fallback(encoding: &Encoding, text: &str, default_char: &str) -> Vec<u8> {
    let encoded = Document::encode_text(encoding, text);
    if !encoded.is_empty() {
        return encoded;
    }

    encode(encoding, text, default_char)
}

/// Decode a cross-reference stream, bounding its decompressed content by
/// [`DEFAULT_MAX_DECOMPRESSED_SIZE`](crate::DEFAULT_MAX_DECOMPRESSED_SIZE).
pub fn decode_xref_stream(stream: Stream) -> Result<(Xref, Dictionary)> {
    decode_xref_stream_with_limit(stream, Some(DEFAULT_MAX_DECOMPRESSED_SIZE))
}

/// Decode a cross-reference stream, rejecting it if its decompressed content
/// would exceed `max_decompressed_size` bytes. `None` means no limit. Cross-reference
/// streams are decoded early during loading, so this bounds the memory a `/XRef`
/// stream can use.
pub fn decode_xref_stream_with_limit(
    mut stream: Stream, max_decompressed_size: Option<usize>,
) -> Result<(Xref, Dictionary)> {
    if stream.is_compressed() {
        match max_decompressed_size {
            Some(max) => stream.decompress_with_limit(max)?,
            None => stream.decompress()?,
        }
    }
    let mut dict = stream.dict;
    let mut reader = Cursor::new(stream.content);
    let size = dict
        .get(b"Size")
        .and_then(Object::as_i64)
        .map_err(|_| ParseError::InvalidXref)?;
    let mut xref = Xref::new(size as u32, XrefType::CrossReferenceStream);
    {
        let section_indice = dict
            .get(b"Index")
            .and_then(parse_integer_array)
            .unwrap_or_else(|_| vec![0, size]);
        let field_widths = dict
            .get(b"W")
            .and_then(parse_integer_array)
            .map_err(|_| ParseError::InvalidXref)?;

        // Each width is a byte count for one xref-stream field; 8 covers the full u64/i64 range.
        // Bound them before sizing a Vec, or a crafted stream requests up to 2^64-1 bytes per field.
        const MAX_XREF_FIELD_WIDTH: i64 = 8;
        if field_widths.len() < 3
            || field_widths[0].is_negative()
            || field_widths[1].is_negative()
            || field_widths[2].is_negative()
            || field_widths[0] > MAX_XREF_FIELD_WIDTH
            || field_widths[1] > MAX_XREF_FIELD_WIDTH
            || field_widths[2] > MAX_XREF_FIELD_WIDTH
        {
            return Err(ParseError::InvalidXref.into());
        }

        // Total bytes one entry consumes. With every width zero the loop below would spin on
        // attacker-controlled /Index counts forever, so reject it (also avoids a division by zero).
        let entry_width = (field_widths[0] + field_widths[1] + field_widths[2]) as usize;
        if entry_width == 0 {
            return Err(ParseError::InvalidXref.into());
        }

        let index_entries = section_indice
            .as_chunks::<2>()
            .0
            .iter()
            .try_fold(0_usize, |total, section| {
                let count = usize::try_from(section[1]).map_err(|_| ParseError::InvalidXref)?;
                total.checked_add(count).ok_or(ParseError::InvalidXref)
            })?;
        // Validate the total before inserting anything so multiple plausible /Index sections
        // cannot overrun the body. Records narrower than three bytes are rejected to limit
        // amplification; lopdf's writer emits /W [1 4 2], so its own output is unaffected.
        const MIN_ENTRY_WIDTH: usize = 3;
        if index_entries > reader.get_ref().len() / entry_width.max(MIN_ENTRY_WIDTH) {
            return Err(ParseError::InvalidXref.into());
        }

        let mut bytes1 = vec![0_u8; field_widths[0] as usize];
        let mut bytes2 = vec![0_u8; field_widths[1] as usize];
        let mut bytes3 = vec![0_u8; field_widths[2] as usize];

        for section in section_indice.as_chunks::<2>().0 {
            let start = section[0];
            let count = section[1];
            let mut skipped = 0usize;

            for j in 0..count {
                let entry_type = if !bytes1.is_empty() {
                    read_big_endian_integer(&mut reader, bytes1.as_mut_slice())?
                } else {
                    1
                };
                let entry = match entry_type {
                    0 => {
                        // free object
                        read_big_endian_integer(&mut reader, bytes2.as_mut_slice())?;
                        read_big_endian_integer(&mut reader, bytes3.as_mut_slice())?;
                        Some(XrefEntry::Free)
                    }
                    1 => {
                        // normal object
                        let offset = read_big_endian_integer(&mut reader, bytes2.as_mut_slice())?;
                        let generation = if !bytes3.is_empty() {
                            read_big_endian_integer(&mut reader, bytes3.as_mut_slice())?
                        } else {
                            0
                        } as u16;
                        Some(XrefEntry::Normal { offset, generation })
                    }
                    2 => {
                        // compressed object
                        let container = read_big_endian_integer(&mut reader, bytes2.as_mut_slice())?;
                        let index = read_big_endian_integer(&mut reader, bytes3.as_mut_slice())? as u16;
                        Some(XrefEntry::Compressed { container, index })
                    }
                    _ => {
                        // unknown types are null references, but their fields still take up space
                        read_big_endian_integer(&mut reader, bytes2.as_mut_slice())?;
                        read_big_endian_integer(&mut reader, bytes3.as_mut_slice())?;
                        None
                    }
                };
                // `start` is untrusted, as in a cross-reference table: `start + j` can overflow,
                // and a `start` outside the u32 range would truncate into a valid-looking number.
                if let Some(entry) = entry {
                    match start.checked_add(j).and_then(|id| u32::try_from(id).ok()) {
                        Some(id) => xref.insert(id, entry),
                        None => skipped += 1,
                    }
                }
            }
            if skipped > 0 {
                warn!(
                    "cross-reference stream section starting at {start} has {skipped} entr{} with an object number outside u32; skipping",
                    if skipped == 1 { "y" } else { "ies" }
                );
            }
        }
    }
    dict.remove(b"Length");
    dict.remove(b"W");
    dict.remove(b"Index");
    Ok((xref, dict))
}

fn read_big_endian_integer(reader: &mut Cursor<Vec<u8>>, buffer: &mut [u8]) -> Result<u32> {
    reader.read_exact(buffer)?;
    let mut value = 0;
    for &mut byte in buffer {
        value = (value << 8) + u32::from(byte);
    }
    Ok(value)
}

fn parse_integer_array(array: &Object) -> Result<Vec<i64>> {
    let array = array.as_array()?;
    let mut out = Vec::with_capacity(array.len());

    for n in array {
        out.push(n.as_i64()?);
    }

    Ok(out)
}

#[cfg(test)]
mod tests {
    #[cfg(not(feature = "async"))]
    #[test]
    fn load_and_save() {
        use crate::Document;
        use crate::creator::tests::{create_document, save_document};

        // test load_from() and save_to()
        use std::fs::File;
        use std::io::Cursor;
        // Create temporary folder to store file.
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("test_1_load_and_save.pdf");

        let mut doc = create_document();

        save_document(&file_path, &mut doc);

        let in_file = File::open(file_path).unwrap();
        let mut in_doc = Document::load_from(in_file).unwrap();

        let out_buf = Vec::new();
        let mut memory_cursor = Cursor::new(out_buf);
        in_doc.save_to(&mut memory_cursor).unwrap();
        // Check if saved file is not an empty bytes vector.
        assert!(!memory_cursor.get_ref().is_empty());
    }

    #[test]
    fn extract_text_chunks() {
        use crate::creator::tests::create_document_with_texts;

        let text1 = "Hello world!";
        let text2 = "Ferris is the best!";
        let doc = create_document_with_texts(&[text1, text2]);
        let extracted_texts = doc.extract_text_chunks(&[1, 2]);
        assert_eq!(extracted_texts.len(), 2);
        assert_eq!(
            [
                extracted_texts[0].as_ref().unwrap().trim(),
                extracted_texts[1].as_ref().unwrap().trim()
            ],
            [text1, text2]
        );
    }

    #[test]
    fn extract_text_concatenates_text_from_multiple_pages() {
        use crate::creator::tests::create_document_with_texts;

        let text1 = "Hello world!";
        let text2 = "Ferris is the best!";
        let doc = create_document_with_texts(&[text1, text2]);
        let extracted_text = doc.extract_text(&[1, 2]);
        assert_eq!(extracted_text.unwrap(), format!("{text1}\n{text2}\n"));
    }

    /// ISO 32000-1 §9.7.5.2 — the codes of a Type 0 font whose `/Encoding` is a
    /// predefined Unicode CMap (here `UniJIS-UCS2-H`) are UCS-2 values, so
    /// the text can be extracted without a `/ToUnicode` CMap.
    #[test]
    fn extract_text_decodes_type0_font_with_predefined_unicode_cmap() {
        use crate::content::Operation;
        use crate::creator::tests::create_document_with_operations;
        use crate::{Object, StringFormat};

        let mut doc = create_document_with_operations(vec![
            Operation::new("BT", vec![]),
            Operation::new("Tf", vec!["F1".into(), 12.into()]),
            Operation::new("Td", vec![100.into(), 700.into()]),
            Operation::new(
                "Tj",
                vec![Object::String(vec![0x65, 0xE5, 0x67, 0x2C], StringFormat::Hexadecimal)],
            ),
            Operation::new("ET", vec![]),
        ]);
        let font_id = doc
            .objects
            .iter()
            .find(|(_, obj)| obj.as_dict().map(|d| d.has_type(b"Font")).unwrap_or(false))
            .map(|(id, _)| *id)
            .expect("font object exists");
        let font = doc.get_object_mut(font_id).and_then(Object::as_dict_mut).unwrap();
        font.set("Subtype", "Type0");
        font.set("BaseFont", "KozMinPr6N-Regular");
        font.set("Encoding", "UniJIS-UCS2-H");

        let text = doc.extract_text(&[1]).unwrap();
        assert_eq!(text.trim(), "日本");
    }

    const BOMB_MIB: usize = 1024 * 1024;

    /// A FlateDecode-compressed stream that inflates to `target` zero-bytes, built
    /// by streaming zeros through the compressor so the test process never holds
    /// `target` bytes at once.
    fn flate_bomb(target: usize) -> Vec<u8> {
        use flate2::Compression;
        use flate2::write::ZlibEncoder;
        use std::io::Write;

        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::best());
        let zeros = [0u8; 64 * 1024];
        let mut remaining = target;
        while remaining > 0 {
            let n = remaining.min(zeros.len());
            encoder.write_all(&zeros[..n]).unwrap();
            remaining -= n;
        }
        encoder.finish().unwrap()
    }

    /// A `create_document_with_texts` document whose first page's content stream
    /// has been swapped for a FlateDecode bomb that inflates to `target` bytes.
    fn doc_with_page_content_bomb(target: usize) -> crate::Document {
        use crate::{Dictionary, Object, Stream};

        let mut doc = create_document_with_texts(&["Hello"]);
        let page_id = *doc.get_pages().get(&1).expect("page 1 exists");
        let content_id = doc.get_page_contents(page_id)[0];
        let mut dict = Dictionary::new();
        dict.set("Filter", "FlateDecode");
        doc.objects
            .insert(content_id, Object::Stream(Stream::new(dict, flate_bomb(target))));
        doc
    }

    /// A `create_document_with_texts` document whose font carries a `/ToUnicode`
    /// CMap that is a FlateDecode bomb. Font encodings are resolved (and thus this
    /// stream is decoded) during text extraction, *before* the page content — so
    /// this exercises a decompression vector distinct from page content.
    fn doc_with_tounicode_font_bomb(target: usize) -> crate::Document {
        use crate::{Dictionary, Object, Stream};

        let mut doc = create_document_with_texts(&["Hello"]);
        let font_id = doc
            .objects
            .iter()
            .find(|(_, obj)| obj.as_dict().map(|d| d.has_type(b"Font")).unwrap_or(false))
            .map(|(id, _)| *id)
            .expect("font object exists");

        let mut tounicode_dict = Dictionary::new();
        tounicode_dict.set("Filter", "FlateDecode");
        let tounicode_id = doc.add_object(Object::Stream(Stream::new(tounicode_dict, flate_bomb(target))));

        let font = doc.get_object_mut(font_id).and_then(Object::as_dict_mut).unwrap();
        font.set("ToUnicode", Object::Reference(tounicode_id));
        doc
    }

    use crate::creator::tests::create_document_with_texts;

    /// Under a generous limit, `extract_text_with_limit` returns exactly the same
    /// text as `extract_text`.
    #[test]
    fn extract_text_with_limit_matches_unbounded_under_limit() {
        use crate::creator::tests::create_document_with_texts;

        let text1 = "Hello world!";
        let text2 = "Ferris is the best!";
        let doc = create_document_with_texts(&[text1, text2]);

        let bounded = doc.extract_text_with_limit(&[1, 2], BOMB_MIB).unwrap();
        let unbounded = doc.extract_text(&[1, 2]).unwrap();
        assert_eq!(bounded, unbounded);
    }

    /// A page-content decompression bomb is rejected end-to-end by
    /// `extract_text_with_limit` instead of inflating without bound.
    #[test]
    fn extract_text_with_limit_rejects_page_content_bomb() {
        use crate::{DecompressError, Error};

        let doc = doc_with_page_content_bomb(32 * BOMB_MIB);

        match doc.extract_text_with_limit(&[1], 4 * BOMB_MIB).map(|s| s.len()) {
            Err(Error::Decompress(DecompressError::MemoryLimitExceeded { limit })) => {
                assert_eq!(limit, 4 * BOMB_MIB);
            }
            other => panic!("expected MemoryLimitExceeded, got {other:?}"),
        }
    }

    /// The chunked variant surfaces the same bomb as an `Err` chunk rather than
    /// panicking or silently truncating.
    #[test]
    fn extract_text_chunks_with_limit_surfaces_limit_error() {
        use crate::{DecompressError, Error};

        let doc = doc_with_page_content_bomb(32 * BOMB_MIB);
        let chunks = doc.extract_text_chunks_with_limit(&[1], 4 * BOMB_MIB);

        assert!(
            chunks.iter().any(|chunk| matches!(
                chunk,
                Err(Error::Decompress(DecompressError::MemoryLimitExceeded { .. }))
            )),
            "expected a MemoryLimitExceeded error chunk"
        );
    }

    /// A bomb reached through a font's `/ToUnicode` CMap (decoded during encoding
    /// resolution, before page content) is also bounded by `extract_text_with_limit`
    /// — otherwise the "safe for untrusted input" guarantee has a hole.
    #[test]
    fn extract_text_with_limit_rejects_tounicode_font_bomb() {
        use crate::{DecompressError, Error};

        let doc = doc_with_tounicode_font_bomb(32 * BOMB_MIB);

        match doc.extract_text_with_limit(&[1], 4 * BOMB_MIB).map(|s| s.len()) {
            Err(Error::Decompress(DecompressError::MemoryLimitExceeded { limit })) => {
                assert_eq!(limit, 4 * BOMB_MIB);
            }
            other => panic!("expected MemoryLimitExceeded from ToUnicode font bomb, got {other:?}"),
        }
    }

    /// `extract_text` bounds page content by `DEFAULT_MAX_DECOMPRESSED_SIZE` without
    /// the caller opting in, so a bomb just over the default is rejected.
    #[test]
    fn extract_text_rejects_page_content_bomb_by_default() {
        use crate::{DEFAULT_MAX_DECOMPRESSED_SIZE, DecompressError, Error};

        let doc = doc_with_page_content_bomb(DEFAULT_MAX_DECOMPRESSED_SIZE + BOMB_MIB);

        match doc.extract_text(&[1]).map(|s| s.len()) {
            Err(Error::Decompress(DecompressError::MemoryLimitExceeded { limit })) => {
                assert_eq!(limit, DEFAULT_MAX_DECOMPRESSED_SIZE);
            }
            other => panic!("expected MemoryLimitExceeded at the default limit, got {other:?}"),
        }
    }

    /// `extract_text_chunks` applies the same default bound and reports it as an
    /// `Err` chunk.
    #[test]
    fn extract_text_chunks_rejects_page_content_bomb_by_default() {
        use crate::{DEFAULT_MAX_DECOMPRESSED_SIZE, DecompressError, Error};

        let doc = doc_with_page_content_bomb(DEFAULT_MAX_DECOMPRESSED_SIZE + BOMB_MIB);
        let chunks = doc.extract_text_chunks(&[1]);

        assert!(
            chunks.iter().any(|chunk| matches!(
                chunk,
                Err(Error::Decompress(DecompressError::MemoryLimitExceeded { limit }))
                    if *limit == DEFAULT_MAX_DECOMPRESSED_SIZE
            )),
            "expected a MemoryLimitExceeded error chunk at the default limit"
        );
    }

    #[test]
    fn test_replace_partial_text() {
        use crate::creator::tests::create_document_with_texts;

        let mut doc = create_document_with_texts(&["Hello World! Hello Universe!"]);
        let replacements = doc.replace_partial_text(1, "Hello", "Hi", None).unwrap();
        assert_eq!(replacements, 2); // Should replace both occurrences

        let extracted_text = doc.extract_text(&[1]).unwrap();
        assert!(extracted_text.contains("Hi World! Hi Universe!"));
    }

    /// PDF 1.7 / ISO 32000-1 §9.4.3 — `'` is equivalent to `T* Tj`:
    /// move to the next line and show a string. extract_text should
    /// recover the string operand and emit a line break before it.
    #[test]
    fn extract_text_handles_apostrophe_show_text_op() {
        use crate::Object;
        use crate::content::Operation;
        use crate::creator::tests::create_document_with_operations;

        let doc = create_document_with_operations(vec![
            Operation::new("BT", vec![]),
            Operation::new("Tf", vec!["F1".into(), 12.into()]),
            Operation::new("Td", vec![100.into(), 700.into()]),
            Operation::new("Tj", vec![Object::string_literal("first")]),
            Operation::new("'", vec![Object::string_literal("second")]),
            Operation::new("'", vec![Object::string_literal("third")]),
            Operation::new("ET", vec![]),
        ]);

        let text = doc.extract_text(&[1]).unwrap();
        assert!(text.contains("first"), "Tj string lost: {text:?}");
        assert!(text.contains("second"), "first ' string lost: {text:?}");
        assert!(text.contains("third"), "second ' string lost: {text:?}");
    }

    /// PDF 1.7 / ISO 32000-1 §9.4.3 — `"` is equivalent to
    /// `aw Tw ac Tc T* Tj` with operands `[aw, ac, string]`. extract_text
    /// should recover operand index 2 (the string); operands 0 and 1 set
    /// rendering spacing and don't affect the extracted character sequence.
    #[test]
    fn extract_text_handles_quote_show_text_op() {
        use crate::Object;
        use crate::content::Operation;
        use crate::creator::tests::create_document_with_operations;

        let doc = create_document_with_operations(vec![
            Operation::new("BT", vec![]),
            Operation::new("Tf", vec!["F1".into(), 12.into()]),
            Operation::new("Td", vec![100.into(), 700.into()]),
            Operation::new("\"", vec![0.into(), 0.into(), Object::string_literal("from-quote-op")]),
            Operation::new("ET", vec![]),
        ]);

        let text = doc.extract_text(&[1]).unwrap();
        assert!(text.contains("from-quote-op"), "\" string operand lost: {text:?}");
    }

    /// PDF 1.7 / ISO 32000-1 §9.4.2 — `T*` moves to the start of the
    /// next line. For text extraction we approximate as `\n`, so a
    /// `Tj T* Tj` sequence should produce two strings separated by a
    /// newline rather than running together.
    #[test]
    fn extract_text_preserves_line_breaks_for_t_star() {
        use crate::Object;
        use crate::content::Operation;
        use crate::creator::tests::create_document_with_operations;

        let doc = create_document_with_operations(vec![
            Operation::new("BT", vec![]),
            Operation::new("Tf", vec!["F1".into(), 12.into()]),
            Operation::new("Td", vec![100.into(), 700.into()]),
            Operation::new("Tj", vec![Object::string_literal("line-one")]),
            Operation::new("T*", vec![]),
            Operation::new("Tj", vec![Object::string_literal("line-two")]),
            Operation::new("ET", vec![]),
        ]);

        let text = doc.extract_text(&[1]).unwrap();
        let one = text.find("line-one").expect("line-one missing");
        let two = text.find("line-two").expect("line-two missing");
        assert!(one < two, "order wrong: {text:?}");
        let between = &text[one + "line-one".len()..two];
        assert!(
            between.contains('\n'),
            "T* did not insert a line break between Tj strings: between={between:?}"
        );
    }

    /// A ToUnicode CMap with one codespace range and the given `bfchar` lines.
    fn to_unicode_cmap(codespace: &str, bfchar: &[&str]) -> Vec<u8> {
        format!(
            "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n\
             /CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n\
             1 begincodespacerange\n{codespace}\nendcodespacerange\n\
             {} beginbfchar\n{}\nendbfchar\n\
             endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n",
            bfchar.len(),
            bfchar.join("\n")
        )
        .into_bytes()
    }

    /// A one-page document that shows `shown` with a TrueType font whose `/Encoding` is
    /// `/WinAnsiEncoding` and whose `/ToUnicode` stream (if any) has the given content.
    fn doc_with_simple_font(shown: &[u8], to_unicode: Option<Vec<u8>>) -> crate::Document {
        use crate::content::Operation;
        use crate::creator::tests::create_document_with_operations;
        use crate::{Dictionary, Object, Stream};

        let mut doc = create_document_with_operations(vec![
            Operation::new("BT", vec![]),
            Operation::new("Tf", vec!["F1".into(), 12.into()]),
            Operation::new("Td", vec![100.into(), 700.into()]),
            Operation::new("Tj", vec![Object::string_literal(shown)]),
            Operation::new("ET", vec![]),
        ]);
        let font_id = doc
            .objects
            .iter()
            .find(|(_, obj)| obj.as_dict().map(|d| d.has_type(b"Font")).unwrap_or(false))
            .map(|(id, _)| *id)
            .expect("font object exists");
        let to_unicode_id = to_unicode.map(|content| doc.add_object(Stream::new(Dictionary::new(), content)));
        let font = doc.get_object_mut(font_id).and_then(Object::as_dict_mut).unwrap();
        font.set("Subtype", "TrueType");
        font.set("BaseFont", "Arial");
        font.set("Encoding", "WinAnsiEncoding");
        if let Some(id) = to_unicode_id {
            font.set("ToUnicode", id);
        }
        doc
    }

    /// ISO 32000-1 §9.10.2 — `/ToUnicode` is the first method for mapping a code to
    /// Unicode, so it wins over `/Encoding`. A code the CMap leaves out still comes
    /// from `/Encoding`.
    #[test]
    fn extract_text_prefers_tounicode_over_encoding() {
        let cmap = to_unicode_cmap("<00> <FF>", &["<41> <3042>"]);
        let doc = doc_with_simple_font(b"AB", Some(cmap));

        assert_eq!(doc.extract_text(&[1]).unwrap().trim(), "\u{3042}B");
    }

    /// A simple font's codes are one byte each, even when its ToUnicode CMap is written
    /// with a two-byte codespace and two-byte keys, as many producers do.
    #[test]
    fn extract_text_reads_simple_font_tounicode_with_two_byte_codespace() {
        let cmap = to_unicode_cmap("<0000> <FFFF>", &["<0041> <0391>", "<42> <0392>"]);
        let doc = doc_with_simple_font(b"AB", Some(cmap));

        assert_eq!(doc.extract_text(&[1]).unwrap().trim(), "\u{0391}\u{0392}");
    }

    /// A ToUnicode CMap that cannot be parsed falls back to `/Encoding`, not to
    /// StandardEncoding (where 0xE9 would be "Ø").
    #[test]
    fn extract_text_falls_back_to_encoding_when_tounicode_is_unparsable() {
        let broken = b"1 beginbfrange\n<05> <01> <0041>\nendbfrange\n".to_vec();
        assert!(crate::encodings::cmap::ToUnicodeCMap::parse(broken.clone()).is_err());
        let doc = doc_with_simple_font(b"caf\xE9", Some(broken));

        assert_eq!(doc.extract_text(&[1]).unwrap().trim(), "caf\u{e9}");
    }

    /// Text replaced in a simple font that has a ToUnicode CMap is written back as
    /// one-byte codes, including for characters that only `/Encoding` maps.
    #[test]
    fn replace_text_writes_one_byte_codes_for_simple_font_with_tounicode() {
        let cmap = to_unicode_cmap("<0000> <FFFF>", &["<0041> <3042>"]);
        let mut doc = doc_with_simple_font(b"AB", Some(cmap));

        doc.replace_text(1, "\u{3042}B", "B\u{3042}", None).unwrap();

        assert_eq!(doc.extract_text(&[1]).unwrap().trim(), "B\u{3042}");
        let page_id = doc.page_iter().next().unwrap();
        let content = doc.get_and_decode_page_content(page_id).unwrap();
        let shown = content.operations.iter().find(|op| op.operator == "Tj").unwrap();
        assert_eq!(shown.operands[0].as_str().unwrap(), b"BA");
    }

    /// A decompression bomb in `/ToUnicode` still surfaces when the font also has
    /// `/Encoding`, now that `/ToUnicode` is read first.
    #[test]
    fn extract_text_with_limit_rejects_tounicode_bomb_in_font_with_encoding() {
        use crate::{DecompressError, Error, Object};

        let mut doc = doc_with_tounicode_font_bomb(32 * BOMB_MIB);
        let font_id = doc
            .objects
            .iter()
            .find(|(_, obj)| obj.as_dict().map(|d| d.has_type(b"Font")).unwrap_or(false))
            .map(|(id, _)| *id)
            .expect("font object exists");
        let font = doc.get_object_mut(font_id).and_then(Object::as_dict_mut).unwrap();
        font.set("Encoding", "WinAnsiEncoding");

        match doc.extract_text_with_limit(&[1], 4 * BOMB_MIB).map(|s| s.len()) {
            Err(Error::Decompress(DecompressError::MemoryLimitExceeded { limit })) => {
                assert_eq!(limit, 4 * BOMB_MIB);
            }
            other => panic!("expected MemoryLimitExceeded from ToUnicode font bomb, got {other:?}"),
        }
    }

    /// A one-page document that shows the two-byte codes `<0001><0002>` with a Type 0
    /// font whose `/Encoding` is made by `encoding` and whose ToUnicode CMap maps codes
    /// 1, 2 and 3 to "한", "글" and "A".
    fn doc_with_type0_font(encoding: &dyn Fn(&mut crate::Document) -> crate::Object) -> crate::Document {
        use crate::content::Operation;
        use crate::creator::tests::create_document_with_operations;
        use crate::{Dictionary, Object, Stream, StringFormat};

        let mut doc = create_document_with_operations(vec![
            Operation::new("BT", vec![]),
            Operation::new("Tf", vec!["F1".into(), 12.into()]),
            Operation::new("Td", vec![100.into(), 700.into()]),
            Operation::new(
                "Tj",
                vec![Object::String(vec![0x00, 0x01, 0x00, 0x02], StringFormat::Hexadecimal)],
            ),
            Operation::new("ET", vec![]),
        ]);
        let font_id = doc
            .objects
            .iter()
            .find(|(_, obj)| obj.as_dict().map(|d| d.has_type(b"Font")).unwrap_or(false))
            .map(|(id, _)| *id)
            .expect("font object exists");
        let cmap = to_unicode_cmap("<0000> <FFFF>", &["<0001> <D55C>", "<0002> <AE00>", "<0003> <0041>"]);
        let to_unicode_id = doc.add_object(Stream::new(Dictionary::new(), cmap));
        let encoding = encoding(&mut doc);
        let font = doc.get_object_mut(font_id).and_then(Object::as_dict_mut).unwrap();
        font.set("Subtype", "Type0");
        font.set("BaseFont", "NotoSansCJK-Regular");
        font.set("Encoding", encoding);
        font.set("ToUnicode", to_unicode_id);
        doc
    }

    /// The bytes of the first `Tj` string on page 1.
    fn shown_bytes(doc: &crate::Document) -> Vec<u8> {
        let page_id = doc.page_iter().next().unwrap();
        let content = doc.get_and_decode_page_content(page_id).unwrap();
        let shown = content.operations.iter().find(|op| op.operator == "Tj").unwrap();
        shown.operands[0].as_str().unwrap().to_vec()
    }

    /// Text replaced in a Type 0 font is written as the two-byte codes of its ToUnicode
    /// CMap, without a byte order mark, and reads back as the replacement.
    fn assert_type0_replacement_uses_tounicode_codes(encoding: &dyn Fn(&mut crate::Document) -> crate::Object) {
        let mut doc = doc_with_type0_font(encoding);
        assert_eq!(doc.extract_text(&[1]).unwrap().trim(), "한글");

        doc.replace_text(1, "한글", "글A한", None).unwrap();
        assert_eq!(shown_bytes(&doc), [0x00, 0x02, 0x00, 0x03, 0x00, 0x01]);
        assert_eq!(doc.extract_text(&[1]).unwrap().trim(), "글A한");

        let mut doc = doc_with_type0_font(encoding);
        assert_eq!(doc.replace_partial_text(1, "한", "A글", None).unwrap(), 1);
        assert_eq!(shown_bytes(&doc), [0x00, 0x03, 0x00, 0x02, 0x00, 0x02]);
        assert_eq!(doc.extract_text(&[1]).unwrap().trim(), "A글글");
    }

    #[test]
    fn replace_text_writes_tounicode_codes_for_type0_font_with_predefined_cmap() {
        for name in ["UniKS-UCS2-H", "UniGB-UCS2-H"] {
            assert_type0_replacement_uses_tounicode_codes(&|_| crate::Object::Name(name.into()));
        }
    }

    #[test]
    fn replace_text_writes_tounicode_codes_for_type0_font_with_embedded_cmap() {
        use crate::{Object, Stream};

        let cmap = b"/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n\
            /CMapName /Custom-H def\n/CMapType 1 def\n\
            1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n\
            1 begincidrange\n<0000> <FFFF> 0\nendcidrange\n\
            endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n";
        assert_type0_replacement_uses_tounicode_codes(&|doc| {
            let stream = Stream::new(
                dictionary! { "Type" => "CMap", "CMapName" => "Custom-H" },
                cmap.to_vec(),
            );
            Object::Reference(doc.add_object(stream))
        });
    }
}

#[cfg(test)]
mod encode_equivalence_tests {
    use super::encode;
    use crate::encodings::Encoding;

    /// The single-character path must encode one character exactly as the
    /// whole-string path did, and the empty string must keep its fallback.
    #[test]
    fn encode_handles_empty_single_and_multi_character() {
        let encoding = Encoding::SimpleEncoding(b"WinAnsiEncoding");

        assert_eq!(encode(&encoding, "A", "?"), vec![b'A']);
        assert_eq!(encode(&encoding, "AB", "?"), vec![b'A', b'B']);
        // An unmappable character falls back per character.
        assert_eq!(encode(&encoding, "A\u{1F600}B", "?"), vec![b'A', b'?', b'B']);
        // The empty string yields no bytes of its own.
        assert_eq!(encode(&encoding, "", "?"), vec![b'?']);
    }
}