flpdf 0.10.0

A pure-Rust PDF toolkit modeled on qpdf — read, rewrite, linearize, and inspect PDFs.
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
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
//! Provide shared PDF utilities for integer conversion, file identity, and
//! text encoding. Invalid or unrepresentable input is converted to `?` where
//! the corresponding API is lossy; resource lookup, font selection, and
//! password policy remain owned by their respective modules.
//!
//! qpdf correspondence: `QUtil.cc` integer conversion, filesystem identity, and UTF-8 single-byte encoding primitives, used by form appearance generation per `libqpdf/QPDFFormFieldObjectHelper.cc:811-849`.
//!
//!

use std::fs::{File, OpenOptions};
use std::path::Path;

/// Return whether two existing paths identify the same filesystem object.
///
/// This is qpdf's `QUtil::same_file` (`libqpdf/QUtil.cc:574-610`): missing or
/// otherwise uninspectable paths are not considered equal, while hard-link
/// and symlink aliases compare by the underlying file identity. On Unix,
/// qpdf compares `stat()` device/inode numbers without opening either path
/// (`libqpdf/QUtil.cc:601-604`); opening first (as the `same_file` crate's
/// path-based comparison does) would block indefinitely on a FIFO
/// destination with no writer yet connected. On Windows qpdf's own
/// comparison opens both paths via `CreateFile`
/// (`libqpdf/QUtil.cc:581-591`), so the `same_file` crate's handle-based
/// comparison matches there.
#[must_use]
pub fn same_file(first: &Path, second: &Path) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        let (Ok(first_meta), Ok(second_meta)) = (first.metadata(), second.metadata()) else {
            return false;
        };
        first_meta.dev() == second_meta.dev() && first_meta.ino() == second_meta.ino()
    }
    #[cfg(not(unix))]
    {
        same_file::is_same_file(first, second).unwrap_or(false)
    }
}

/// Open a file with qpdf's `QUtil::safe_fopen` error boundary.
///
/// The mode grammar mirrors the portable `fopen` modes qpdf passes here:
/// `r`, `w`, and `a`, optionally followed by `b` and/or `+`. The returned
/// filesystem failure is promoted to `Error::System`, matching qpdf's
/// `QPDFSystemError` rather than leaking a bare `std::io::Error` through a
/// utility consumer.
pub fn safe_fopen(filename: &str, mode: &str) -> crate::Result<File> {
    let mut mode_bytes = mode.bytes();
    let Some(kind) = mode_bytes.next() else {
        return Err(crate::Error::System(format!(
            "open {filename}: invalid fopen mode"
        )));
    };

    let mut plus = false;
    let mut exclusive = false;
    for modifier in mode_bytes {
        match modifier {
            b'b' => {}
            b'+' => plus = true,
            b'x' => exclusive = true,
            _ => {
                return Err(crate::Error::System(format!(
                    "open {filename}: invalid fopen mode"
                )))
            }
        }
    }

    let mut options = OpenOptions::new();
    match kind {
        b'r' => {
            options.read(true);
            if plus {
                options.write(true);
            }
        }
        b'w' => {
            options.write(true);
            if plus {
                options.read(true);
            }
            if exclusive {
                options.create_new(true);
            } else {
                options.create(true).truncate(true);
            }
        }
        b'a' => {
            options.append(true).create(true);
            if plus {
                options.read(true);
            }
            if exclusive {
                options.create_new(true);
            }
        }
        _ => {
            return Err(crate::Error::System(format!(
                "open {filename}: invalid fopen mode"
            )))
        }
    }

    options.open(filename).map_err(|error| {
        crate::Error::System(format!("open {filename}: {}", strerror_text(&error)))
    })
}

/// Render an [`std::io::Error`] using qpdf's portable `strerror`-based
/// wording instead of Rust's own `Display`.
///
/// `QPDFSystemError::createWhat` (`libqpdf/QPDFSystemError.cc:13-29`) formats
/// every qpdf filesystem failure as `strerror(errno)`, which is the same
/// C-runtime text on every host qpdf builds for, including Windows. Rust's
/// `io::Error` `Display` reproduces that same POSIX text on Unix hosts
/// (modulo an appended `(os error N)` suffix `strerror` does not produce,
/// stripped below), but on Windows it instead renders the native Win32
/// `FormatMessage` wording (e.g. "The system cannot find the file
/// specified." for a missing path) rather than the `strerror` text qpdf
/// itself prints there. Map the common kinds to that fixed portable wording
/// first; every kind below was confirmed against a real syscall failure on
/// Unix to already agree with the suffix-stripped `Display` text there, so
/// this changes only the platforms whose native wording diverges from
/// `strerror`. Any qpdf-compatible caller that reports a raw filesystem
/// failure (not just [`safe_fopen`]) should route it through this instead of
/// `io::Error`'s own `Display`.
pub(crate) fn strerror_text(error: &std::io::Error) -> String {
    // A real syscall failure on a `strerror`-rendering host already carries
    // exactly the text qpdf prints, so use it rather than the table below.
    // The table keys on `ErrorKind`, which is coarser than `errno`: `EPERM`
    // and `EACCES` share `PermissionDenied` but print "Operation not
    // permitted" and "Permission denied" respectively, and only the raw code
    // tells them apart. The table still covers synthetic errors carrying no
    // `errno`, and every host whose `Display` is not `strerror`.
    #[cfg(unix)]
    if error.raw_os_error().is_some() {
        return strerror_from_display(error);
    }
    let message = match error.kind() {
        std::io::ErrorKind::NotFound => Some("No such file or directory"),
        std::io::ErrorKind::PermissionDenied => Some("Permission denied"),
        std::io::ErrorKind::AlreadyExists => Some("File exists"),
        std::io::ErrorKind::InvalidInput => Some("Invalid argument"),
        std::io::ErrorKind::IsADirectory => Some("Is a directory"),
        std::io::ErrorKind::NotADirectory => Some("Not a directory"),
        _ => None,
    };
    if let Some(message) = message {
        return message.to_owned();
    }
    strerror_from_display(error)
}

/// Render `error` through its own `Display`, less the ` (os error N)` suffix
/// Rust appends and `strerror` does not.
fn strerror_from_display(error: &std::io::Error) -> String {
    let rendered = error.to_string();
    error
        .raw_os_error()
        .and_then(|code| rendered.strip_suffix(&format!(" (os error {code})")))
        .map_or(rendered.clone(), str::to_owned)
}

/// Format a signed integer using qpdf's supported bases and width rules.
///
/// This is qpdf's `QUtil::int_to_string_base` (`include/qpdf/QUtil.hh:46-48`,
/// `libqpdf/QUtil.cc:294-300,337-350`). Positive lengths prepend zeroes;
/// negative lengths append spaces. Unsupported bases are the qpdf
/// `std::logic_error` boundary and therefore become `Error::Internal`.
pub fn int_to_string_base(number: i64, base: i32, length: i32) -> crate::Result<String> {
    let mut converted = match base {
        // qpdf formats these through `std::ostringstream << std::setbase(base)
        // << num` (`libqpdf/QUtil.cc:305-310`); C++ streams print a negative
        // integer in octal or hexadecimal as its unsigned two's-complement
        // representation, not as a sign plus magnitude.
        8 => format!("{:o}", number as u64),
        16 => format!("{:x}", number as u64),
        10 => number.to_string(),
        _ => {
            return Err(crate::Error::Internal(
                "int_to_string_base called with unsupported base".to_owned(),
            ))
        }
    };

    // cov:ignore-start: qpdf length is an i32 and the supported target is 64-bit
    let width = usize::try_from(i64::from(length).unsigned_abs()).map_err(|_| {
        crate::Error::Internal("int_to_string_base length does not fit usize".to_owned())
    })?;
    // cov:ignore-end
    if length > 0 && converted.len() < width {
        let mut padded = String::with_capacity(width);
        padded.extend(std::iter::repeat_n('0', width - converted.len()));
        padded.push_str(&converted);
        converted = padded;
    } else if length < 0 && converted.len() < width {
        converted.extend(std::iter::repeat_n(' ', width - converted.len()));
    }
    Ok(converted)
}

/// Encode a qpdf Unicode code point as UTF-8 bytes.
///
/// This is qpdf's `QUtil::toUTF8` (`include/qpdf/QUtil.hh:280`,
/// `libqpdf/QUtil.cc:997-1031`). qpdf accepts values through `0x7fffffff`
/// using its historical 1-to-6-byte encoding and reports larger values as a
/// runtime error, which maps to `Error::System` here.
pub fn to_utf8(mut value: u32) -> crate::Result<Vec<u8>> {
    if value > 0x7fff_ffff {
        return Err(crate::Error::System(
            "bounds error in QUtil::toUTF8".to_owned(),
        ));
    }
    if value < 128 {
        return Ok(vec![value as u8]);
    }

    let mut bytes = [0u8; 6];
    let mut cursor = 5usize;
    let mut max_value = 0x3fu8;
    while value > u32::from(max_value) {
        bytes[cursor] = 0x80 | (value as u8 & 0x3f);
        value >>= 6;
        max_value >>= 1;
        // cov:ignore-start: qpdf accepts at most 31-bit values, which cannot exhaust the six-byte buffer
        if cursor == 0 {
            return Err(crate::Error::Internal(
                "QUtil::toUTF8: overflow error".to_owned(),
            ));
        }
        // cov:ignore-end
        cursor -= 1;
    }
    let first = 0xffu32 - (1 + (u32::from(max_value) << 1)) + value;
    bytes[cursor] = u8::try_from(first)
        .map_err(|_| crate::Error::Internal("QUtil::toUTF8: overflow error".to_owned()))?; // cov:ignore: qpdf's bounded encoding keeps the leading byte within u8
    Ok(bytes[cursor..].to_vec())
}

#[derive(Clone, Copy)]
enum SingleByteEncoding {
    Ascii,
    WinAnsi,
    MacRoman,
    PdfDoc,
}

/// Convert UTF-8 bytes to ASCII, replacing unrepresentable code points with `?`.
pub fn utf8_to_ascii(input: &[u8]) -> Vec<u8> {
    transcode_utf8(input, SingleByteEncoding::Ascii)
}

/// Convert UTF-8 bytes to WinAnsiEncoding bytes, replacing unrepresentable code points with `?`.
pub fn utf8_to_win_ansi(input: &[u8]) -> Vec<u8> {
    transcode_utf8(input, SingleByteEncoding::WinAnsi)
}

/// Convert UTF-8 bytes to MacRomanEncoding bytes, replacing unrepresentable code points with `?`.
pub fn utf8_to_mac_roman(input: &[u8]) -> Vec<u8> {
    transcode_utf8(input, SingleByteEncoding::MacRoman)
}

/// Convert UTF-8 bytes to PDFDocEncoding bytes, replacing unrepresentable code points with `?`.
///
/// This is qpdf's `QUtil::utf8_to_pdf_doc` (`libqpdf/QUtil.cc:1646-1650`).
/// Unlike [`utf8_to_ascii`]/[`utf8_to_win_ansi`]/[`utf8_to_mac_roman`),
/// PDFDocEncoding reassigns four ASCII control codes (`0x18`-`0x1f`) and
/// `0x7f` to accent glyphs, so those code points cannot round-trip and are
/// replaced with `?` rather than passed through; `U+00AD` (soft hyphen) is
/// similarly unrepresentable, since PDFDocEncoding omits it
/// (`libqpdf/QUtil.cc:1541-1546`).
pub fn utf8_to_pdf_doc(input: &[u8]) -> Vec<u8> {
    transcode_utf8(input, SingleByteEncoding::PdfDoc)
}

/// Convert UTF-8 bytes to PDFDocEncoding, reporting whether every code point
/// was representable.
///
/// This is qpdf's second `QUtil::utf8_to_pdf_doc` overload
/// (`include/qpdf/QUtil.hh:332`, `libqpdf/QUtil.cc:1669-1673`), which returns
/// that flag alongside the bytes; [`utf8_to_pdf_doc`] is the form that
/// discards it. The bytes are identical either way, so a `?` in the output
/// alone cannot distinguish an unrepresentable code point from a literal
/// question mark in the input -- only this flag can.
pub fn utf8_to_pdf_doc_checked(input: &[u8]) -> (Vec<u8>, bool) {
    transcode_utf8_with_status(input, SingleByteEncoding::PdfDoc)
}

/// Convert UTF-8 bytes to ASCII, reporting whether every code point was
/// representable.
///
/// qpdf's second `QUtil::utf8_to_ascii` overload
/// (`include/qpdf/QUtil.hh:326`, `libqpdf/QUtil.cc:1651-1655`).
pub fn utf8_to_ascii_checked(input: &[u8]) -> (Vec<u8>, bool) {
    transcode_utf8_with_status(input, SingleByteEncoding::Ascii)
}

fn transcode_utf8(input: &[u8], encoding: SingleByteEncoding) -> Vec<u8> {
    transcode_utf8_with_status(input, encoding).0
}

/// The transcoder qpdf's four `utf8_to_*` families share, returning both the
/// bytes and whether every code point was representable.
///
/// qpdf's overloads differ only in this: the `std::string`-returning form
/// discards the flag (`libqpdf/QUtil.cc:1614-1621`) while the
/// `bool`-returning form hands it back (`:1651-1673`). The flag is cleared
/// in exactly the places qpdf clears `okay` (`:1553,1565,1579,1588` and the
/// unmapped-code-point fallthrough at `:1595-1608`).
fn transcode_utf8_with_status(input: &[u8], encoding: SingleByteEncoding) -> (Vec<u8>, bool) {
    let mut representable = true;
    let mut output = Vec::with_capacity(input.len());
    if matches!(encoding, SingleByteEncoding::PdfDoc) && pdf_doc_prefix_collides_with_a_bom(input) {
        representable = false;
        // qpdf avoids emitting a PDFDocEncoding string that a reader would
        // mistake for a UTF-16 or UTF-8 BOM by checking the *input*
        // codepoints that would produce one, rather than the output bytes
        // (`libqpdf/QUtil.cc:1533-1546`). This check does not consume any
        // input; the flagged codepoints are still transcoded normally below.
        output.push(b'?');
    }
    let mut position = 0;
    while position < input.len() {
        let (codepoint, error) = next_utf8_codepoint(input, &mut position);
        if error {
            representable = false;
            output.push(b'?');
        } else if codepoint < 128 {
            if matches!(encoding, SingleByteEncoding::PdfDoc)
                && (matches!(codepoint, 0x18..=0x1f) || codepoint == 127)
            {
                representable = false;
                output.push(b'?');
            } else {
                output.push(codepoint as u8);
            }
        } else if codepoint == 0xad && matches!(encoding, SingleByteEncoding::PdfDoc) {
            representable = false;
            output.push(b'?');
        } else if matches!(
            encoding,
            SingleByteEncoding::WinAnsi | SingleByteEncoding::PdfDoc
        ) && (161..256).contains(&codepoint)
        {
            output.push(codepoint as u8);
        } else if let Some(byte) = encode_extended(codepoint, encoding) {
            output.push(byte);
        } else {
            representable = false;
            output.push(b'?');
        }
    }
    (output, representable)
}

/// Whether `input`'s leading UTF-8 bytes decode to `U+00FE U+00FF`,
/// `U+00FF U+00FE`, or `U+00EF U+00BB U+00BF` -- the three codepoint
/// sequences whose PDFDocEncoding bytes (`0xFE 0xFF`, `0xFF 0xFE`,
/// `0xEF 0xBB 0xBF`) collide with the UTF-16BE BOM, the (non-standard but
/// widely recognized) UTF-16LE BOM, and the UTF-8 BOM respectively. All
/// three codepoints are in PDFDocEncoding's `0xA1`-`0xFF` direct range, so
/// their UTF-8 encoding always starts with `0xC3` (`libqpdf/QUtil.cc:
/// 1533-1546`).
fn pdf_doc_prefix_collides_with_a_bom(input: &[u8]) -> bool {
    const FE_FF: &[u8] = &[0xc3, 0xbe, 0xc3, 0xbf];
    const FF_FE: &[u8] = &[0xc3, 0xbf, 0xc3, 0xbe];
    const EF_BB_BF: &[u8] = &[0xc3, 0xaf, 0xc2, 0xbb, 0xc2, 0xbf];
    input.starts_with(FE_FF) || input.starts_with(FF_FE) || input.starts_with(EF_BB_BF)
}

fn next_utf8_codepoint(input: &[u8], position: &mut usize) -> (u32, bool) {
    let original_position = *position;
    let first = input[*position];
    *position += 1;
    if first < 128 {
        return (u32::from(first), false);
    }

    let mut bytes_needed = 0;
    let mut bit_check = 0x40;
    let mut to_clear = 0x80;
    while first & bit_check != 0 {
        bytes_needed += 1;
        to_clear |= bit_check;
        bit_check >>= 1;
    }
    if !(1..=5).contains(&bytes_needed) || *position + bytes_needed > input.len() {
        return (0xfffd, true);
    }

    let mut codepoint = u32::from(first & !to_clear);
    for _ in 0..bytes_needed {
        *position += 1;
        let byte = input[*position - 1];
        if byte & 0xc0 != 0x80 {
            *position -= 1;
            return (0xfffd, true);
        }
        codepoint = (codepoint << 6) | u32::from(byte & 0x3f);
    }

    let lower_bound = match *position - original_position {
        2 => 1 << 7,
        3 => 1 << 11,
        4 => 1 << 16,
        5 => 1 << 12,
        6 => 1 << 26,
        _ => 0, // cov:ignore: non-ASCII decoder paths have only 2-6-byte total lengths
    };
    (codepoint, lower_bound > 0 && codepoint < lower_bound)
}

fn encode_extended(codepoint: u32, encoding: SingleByteEncoding) -> Option<u8> {
    match encoding {
        SingleByteEncoding::Ascii => None,
        SingleByteEncoding::WinAnsi => match codepoint {
            0x00a0 => Some(0xa0),
            0x0192 => Some(0x83),
            0x0152 => Some(0x8c),
            0x0153 => Some(0x9c),
            0x0160 => Some(0x8a),
            0x0161 => Some(0x9a),
            0x0178 => Some(0x9f),
            0x017d => Some(0x8e),
            0x017e => Some(0x9e),
            0x02c6 => Some(0x88),
            0x0303 => Some(0x98),
            0x2013 => Some(0x96),
            0x2014 => Some(0x97),
            0x2018 => Some(0x91),
            0x2019 => Some(0x92),
            0x201a => Some(0x82),
            0x201c => Some(0x93),
            0x201d => Some(0x94),
            0x201e => Some(0x84),
            0x2020 => Some(0x86),
            0x2021 => Some(0x87),
            0x2022 => Some(0x95),
            0x2026 => Some(0x85),
            0x2030 => Some(0x89),
            0x2039 => Some(0x8b),
            0x203a => Some(0x9b),
            0x20ac => Some(0x80),
            0x2122 => Some(0x99),
            _ => None,
        },
        SingleByteEncoding::MacRoman => MAC_ROMAN_TO_UNICODE
            .iter()
            .position(|&value| value == codepoint && value != 0xfffd)
            .map(|index| index as u8 + 0x80),
        SingleByteEncoding::PdfDoc => UNICODE_TO_PDF_DOC
            .iter()
            .find(|&&(unicode, _)| unicode == codepoint)
            .map(|&(_, byte)| byte),
    }
}

/// qpdf's `unicode_to_pdf_doc` (`libqpdf/QUtil.cc:282-289`): the reverse of
/// PDFDocEncoding's `0x18`-`0x1f`/`0x80`-`0x9e`/`0xa0` special-character
/// range (this crate's own decode-direction `PDFDOC_ENCODING` table in
/// `pdf_string.rs`), plus `U+FFFD` (the Unicode replacement character)
/// mapping to `0x9f`, which the decode table omits.
const UNICODE_TO_PDF_DOC: [(u32, u8); 41] = [
    (0x02d8, 0x18),
    (0x02c7, 0x19),
    (0x02c6, 0x1a),
    (0x02d9, 0x1b),
    (0x02dd, 0x1c),
    (0x02db, 0x1d),
    (0x02da, 0x1e),
    (0x02dc, 0x1f),
    (0x2022, 0x80),
    (0x2020, 0x81),
    (0x2021, 0x82),
    (0x2026, 0x83),
    (0x2014, 0x84),
    (0x2013, 0x85),
    (0x0192, 0x86),
    (0x2044, 0x87),
    (0x2039, 0x88),
    (0x203a, 0x89),
    (0x2212, 0x8a),
    (0x2030, 0x8b),
    (0x201e, 0x8c),
    (0x201c, 0x8d),
    (0x201d, 0x8e),
    (0x2018, 0x8f),
    (0x2019, 0x90),
    (0x201a, 0x91),
    (0x2122, 0x92),
    (0xfb01, 0x93),
    (0xfb02, 0x94),
    (0x0141, 0x95),
    (0x0152, 0x96),
    (0x0160, 0x97),
    (0x0178, 0x98),
    (0x017d, 0x99),
    (0x0131, 0x9a),
    (0x0142, 0x9b),
    (0x0153, 0x9c),
    (0x0161, 0x9d),
    (0x017e, 0x9e),
    (0xfffd, 0x9f),
    (0x20ac, 0xa0),
];

/// Result of qpdf's two-stage decimal-integer conversion
/// (`QUtil::string_to_int`, `libqpdf/QUtil.cc:373-393`): `strtoll` parses a
/// leading digit run into an i64 (`string_to_ll`), then `QIntC::to_int`
/// narrows that i64 to i32. Both stages throw an uncaught `std::range_error`
/// on overflow in qpdf (`include/qpdf/QIntC.hh:87-109`); callers must
/// surface [`Overflow`](QpdfIntParse::Overflow) as a fatal error rather than
/// silently treating the value as absent or mismatched.
///
/// [`NoDigits`](QpdfIntParse::NoDigits) represents qpdf's `strtoll` result of
/// zero when the input has no leading digit run. Callers with a shape
/// precondition may treat that as impossible; unchecked qpdf callers use it as
/// the numeric zero.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum QpdfIntParse {
    /// No leading digit was found; qpdf's `strtoll` result is zero.
    NoDigits,
    /// qpdf's 64-bit parse or i32 narrowing would overflow.
    Overflow(String),
    /// The parsed value after qpdf's i32 narrowing stage.
    Value(i32),
}

/// Parse a decimal prefix with qpdf's `QUtil::string_to_int` semantics.
pub(crate) fn qpdf_string_to_int_checked(text: &str) -> QpdfIntParse {
    // `QUtil::string_to_ll` delegates to `strtoll`, which consumes leading C
    // whitespace and exactly one optional sign before the digit prefix.
    let text = text.split('\0').next().unwrap_or(text);
    let stripped = text.trim_start_matches(|character| {
        matches!(
            character,
            ' ' | '\n' | '\r' | '\t' | '\u{000c}' | '\u{000b}'
        )
    });
    let (negative, digits) = match stripped.as_bytes().first() {
        Some(b'-') => (true, &stripped[1..]),
        Some(b'+') => (false, &stripped[1..]),
        _ => (false, stripped),
    };
    let digits_end = digits
        .bytes()
        .position(|byte| !byte.is_ascii_digit())
        .unwrap_or(digits.len());
    if digits_end == 0 {
        return QpdfIntParse::NoDigits;
    }
    let Ok(magnitude) = digits[..digits_end].parse::<u128>() else {
        return QpdfIntParse::Overflow(format!(
            "overflow/underflow converting {text} to 64-bit integer"
        ));
    };
    let signed = if negative {
        -(i128::try_from(magnitude).unwrap_or(i128::MAX))
    } else {
        i128::try_from(magnitude).unwrap_or(i128::MAX)
    };
    if signed < i128::from(i64::MIN) || signed > i128::from(i64::MAX) {
        return QpdfIntParse::Overflow(format!(
            "overflow/underflow converting {text} to 64-bit integer"
        ));
    }
    let value = signed as i64;
    match i32::try_from(value) {
        Ok(value) => QpdfIntParse::Value(value),
        Err(_) => QpdfIntParse::Overflow(format!(
            "integer out of range converting {value} from a 8-byte signed type to a 4-byte signed type"
        )),
    }
}

/// Narrow qpdf's `size_t` page count through `QIntC::to_int` semantics.
///
/// qpdf uses this conversion in `QPDFJob::handleRotations`
/// (`libqpdf/QPDFJob.cc:2638`) before calling `QUtil::parse_numrange`; the
/// checked failure is a runtime error, not a saturating or placeholder value.
pub fn qpdf_size_to_int(value: usize) -> crate::Result<i32> {
    i32::try_from(value).map_err(|_| {
        crate::Error::System(format!(
            "integer out of range converting {value} from a {}-byte unsigned type to a {}-byte signed type",
            std::mem::size_of::<usize>(),
            std::mem::size_of::<i32>()
        ))
    })
}

/// Parse qpdf's numeric page-range language.
///
/// This is the byte-oriented counterpart of `QUtil::parse_numrange`
/// (`libqpdf/QUtil.cc:1304-1429`, `include/qpdf/QUtil.hh:464`). qpdf receives a
/// NUL-terminated `char const*`, so the input is truncated at the first NUL;
/// retaining bytes here also keeps qpdf's runtime diagnostic payload intact at
/// the job/CLI boundary. `max == 0` performs syntax-only validation, while a
/// positive max performs qpdf's 1-based range checks. Non-positive maxima are
/// intentionally not rejected because qpdf gates those checks on `max > 0`.
pub fn parse_numrange(range: &[u8], max: i32) -> crate::Result<Vec<i32>> {
    let range = &range[..range
        .iter()
        .position(|&byte| byte == 0)
        .unwrap_or(range.len())];
    let mut range_end = range.len();
    let mut skip = 1usize;
    let mut start_idx = 0usize;
    if let Some(colon) = range.iter().position(|&byte| byte == b':') {
        if &range[colon..] == b":odd" {
            skip = 2;
        } else if &range[colon..] == b":even" {
            skip = 2;
            start_idx = 1;
        } else {
            return Err(numrange_error(range, colon, b"expected :even or :odd"));
        }
        range_end = colon;
    }

    let mut result = Vec::new();
    let mut last_group = Vec::new();
    let mut cursor = 0usize;
    let mut first = true;
    while cursor != range_end {
        let group_end = range[cursor..range_end]
            .iter()
            .position(|&byte| byte == b',')
            .map_or(range_end, |offset| cursor + offset);
        let group = &range[cursor..group_end];
        let Some(group_match) = capture_numrange_group(group) else {
            return Err(numrange_error(range, cursor, b"invalid range syntax"));
        };
        if first && group_match.is_exclude {
            return Err(numrange_error(
                range,
                cursor,
                b"first range group may not be an exclusion",
            ));
        }
        first = false;

        let first_num = parse_numrange_integer(range, cursor, group_match.first, max)?;
        let last_num = group_match
            .last
            .map(|last| parse_numrange_integer(range, cursor, last, max))
            .transpose()?;
        let is_span = last_num.is_some();
        let last_num = last_num.unwrap_or_default();

        if group_match.is_exclude {
            let work = populate_numrange_group(first_num, is_span, last_num)?;
            let mut exclusions = std::collections::BTreeSet::new();
            exclusions.extend(work.iter().copied());
            let previous = std::mem::take(&mut last_group);
            last_group.extend(previous.into_iter().filter(|n| !exclusions.contains(n)));
        } else {
            result.append(&mut last_group);
            last_group = populate_numrange_group(first_num, is_span, last_num)?;
        }

        cursor = group_end;
        if cursor < range_end && range[cursor] == b',' {
            cursor += 1;
            if cursor == range_end {
                return Err(numrange_error(range, cursor, b"trailing comma"));
            }
        }
    }
    result.append(&mut last_group);
    if skip == 1 {
        return Ok(result);
    }
    Ok(result.into_iter().skip(start_idx).step_by(skip).collect())
}

struct NumrangeGroup<'a> {
    is_exclude: bool,
    first: &'a [u8],
    last: Option<&'a [u8]>,
}

fn capture_numrange_group(group: &[u8]) -> Option<NumrangeGroup<'_>> {
    let is_exclude = group.first() == Some(&b'x');
    let mut position = usize::from(is_exclude);
    let first_start = position;
    position = capture_numrange_endpoint(group, position)?;
    let first = &group[first_start..position];
    let last = if group.get(position) == Some(&b'-') {
        position += 1;
        let last_start = position;
        position = capture_numrange_endpoint(group, position)?;
        Some(&group[last_start..position])
    } else {
        None
    };
    (position == group.len()).then_some(NumrangeGroup {
        is_exclude,
        first,
        last,
    })
}

fn capture_numrange_endpoint(group: &[u8], mut position: usize) -> Option<usize> {
    if group.get(position) == Some(&b'z') {
        return Some(position + 1);
    }
    if group.get(position) == Some(&b'r') {
        position += 1;
    }
    let start = position;
    while group
        .get(position)
        .is_some_and(|byte| byte.is_ascii_digit())
    {
        position += 1;
    }
    (position != start).then_some(position)
}

fn parse_numrange_integer(
    input: &[u8],
    offset: usize,
    endpoint: &[u8],
    max: i32,
) -> crate::Result<i32> {
    if endpoint == b"z" {
        return check_numrange_value(input, offset, max, max);
    }
    let from_end = endpoint.first() == Some(&b'r');
    let digits = if from_end { &endpoint[1..] } else { endpoint };
    let text = std::str::from_utf8(digits)
        .map_err(|_| numrange_error(input, offset, b"invalid range syntax"))?;
    let number = match qpdf_string_to_int_checked(text) {
        QpdfIntParse::Value(value) if value != 0 => value,
        QpdfIntParse::Overflow(message) => {
            return Err(numrange_error(input, offset, message.as_bytes()));
        }
        QpdfIntParse::Value(_) | QpdfIntParse::NoDigits => 0,
    };
    let value = if from_end {
        max.wrapping_add(1).wrapping_sub(number)
    } else {
        number
    };
    check_numrange_value(input, offset, value, max)
}

fn check_numrange_value(input: &[u8], offset: usize, value: i32, max: i32) -> crate::Result<i32> {
    if max > 0 && (value < 1 || value > max) {
        return Err(numrange_error(
            input,
            offset,
            format!("number {value} out of range").as_bytes(),
        ));
    }
    Ok(value)
}

fn populate_numrange_group(first: i32, is_span: bool, last: i32) -> crate::Result<Vec<i32>> {
    let mut group = Vec::new();
    try_push_numrange_value(&mut group, first)?;
    if is_span {
        if first > last {
            for value in (last..first).rev() {
                try_push_numrange_value(&mut group, value)?;
            }
        } else if first < last {
            for value in (first + 1)..=last {
                try_push_numrange_value(&mut group, value)?;
            }
        }
    }
    Ok(group)
}

/// Push one eagerly materialized range value without allowing Rust's global
/// allocator to abort the process. qpdf's vector growth throws `std::bad_alloc`,
/// which its CLI catches as an ordinary exit-2 error (`QUtil.cc:1328-1340`,
/// `qpdf/qpdf.cc:32-43`).
fn try_push_numrange_value(group: &mut Vec<i32>, value: i32) -> crate::Result<()> {
    group
        .try_reserve(1)
        .map_err(|_| crate::Error::System("std::bad_alloc".to_owned()))?;
    group.push(value);
    Ok(())
}

fn numrange_error(input: &[u8], offset: usize, detail: &[u8]) -> crate::Error {
    let offset = offset.min(input.len());
    let mut message = b"error at * in numeric range ".to_vec();
    message.extend_from_slice(&input[..offset]);
    message.push(b'*');
    message.extend_from_slice(&input[offset..]);
    message.extend_from_slice(b": ");
    message.extend_from_slice(detail);
    crate::Error::SystemBytes(message)
}

const MAC_ROMAN_TO_UNICODE: [u32; 128] = [
    0x00c4, 0x00c5, 0x00c7, 0x00c9, 0x00d1, 0x00d6, 0x00dc, 0x00e1, 0x00e0, 0x00e2, 0x00e4, 0x00e3,
    0x00e5, 0x00e7, 0x00e9, 0x00e8, 0x00ea, 0x00eb, 0x00ed, 0x00ec, 0x00ee, 0x00ef, 0x00f1, 0x00f3,
    0x00f2, 0x00f4, 0x00f6, 0x00f5, 0x00fa, 0x00f9, 0x00fb, 0x00fc, 0x2020, 0x00b0, 0x00a2, 0x00a3,
    0x00a7, 0x2022, 0x00b6, 0x00df, 0x00ae, 0x00a9, 0x2122, 0x0301, 0x0308, 0xfffd, 0x00c6, 0x00d8,
    0xfffd, 0x00b1, 0xfffd, 0xfffd, 0x00a5, 0x03bc, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0x1d43,
    0x1d52, 0xfffd, 0x00e6, 0x00f8, 0x00bf, 0x00a1, 0x00ac, 0xfffd, 0x0192, 0xfffd, 0xfffd, 0x00ab,
    0x00bb, 0x2026, 0xfffd, 0x00c0, 0x00c3, 0x00d5, 0x0152, 0x0153, 0x2013, 0x2014, 0x201c, 0x201d,
    0x2018, 0x2019, 0x00f7, 0xfffd, 0x00ff, 0x0178, 0x2044, 0x00a4, 0x2039, 0x203a, 0xfb01, 0xfb02,
    0x2021, 0x00b7, 0x201a, 0x201e, 0x2030, 0x00c2, 0x00ca, 0x00c1, 0x00cb, 0x00c8, 0x00cd, 0x00ce,
    0x00cf, 0x00cc, 0x00d3, 0x00d4, 0xfffd, 0x00d2, 0x00da, 0x00db, 0x00d9, 0x0131, 0x02c6, 0x0303,
    0x0304, 0x0306, 0x0307, 0x030a, 0x0327, 0x030b, 0x0328, 0x02c7,
];

#[cfg(test)]
mod tests {
    use super::{
        int_to_string_base, parse_numrange, qpdf_size_to_int, qpdf_string_to_int_checked,
        safe_fopen, same_file, strerror_text, to_utf8, utf8_to_ascii, utf8_to_ascii_checked,
        utf8_to_mac_roman, utf8_to_pdf_doc, utf8_to_pdf_doc_checked, utf8_to_win_ansi,
        QpdfIntParse,
    };
    use std::io::{Read, Write};

    #[test]
    fn to_utf8_matches_qpdf_for_ascii_and_multibyte_values() {
        assert_eq!(to_utf8(0x41).unwrap(), b"A");
        assert_eq!(to_utf8(0x20ac).unwrap(), vec![0xe2, 0x82, 0xac]);
        assert_eq!(
            to_utf8(0x7fff_ffff).unwrap(),
            vec![0xfd, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf]
        );
    }

    #[test]
    fn to_utf8_rejects_values_above_qpdfs_31_bit_limit() {
        let error = to_utf8(0xffff_ffff).expect_err("qpdf rejects values above 0x7fffffff");

        assert!(
            matches!(error, crate::Error::System(message) if message == "bounds error in QUtil::toUTF8")
        );
    }

    #[test]
    fn int_to_string_base_matches_qpdf_bases_and_widths() {
        assert_eq!(int_to_string_base(42, 8, 0).unwrap(), "52");
        assert_eq!(int_to_string_base(42, 10, 4).unwrap(), "0042");
        // `std::ostringstream << std::hex << -42LL` prints the unsigned
        // two's-complement representation.
        assert_eq!(int_to_string_base(-42, 16, 0).unwrap(), "ffffffffffffffd6");
        assert_eq!(
            int_to_string_base(-8, 8, 0).unwrap(),
            "1777777777777777777770"
        );
        assert_eq!(int_to_string_base(-42, 10, 0).unwrap(), "-42");
        assert_eq!(int_to_string_base(42, 10, -4).unwrap(), "42  ");
    }

    #[test]
    fn int_to_string_base_rejects_an_unsupported_base_as_a_logic_error() {
        let error = int_to_string_base(0, 12, 0).expect_err("base 12 is not supported by qpdf");

        assert!(
            matches!(error, crate::Error::Internal(message) if message == "int_to_string_base called with unsupported base")
        );
    }

    #[test]
    fn safe_fopen_missing_path_is_a_qpdf_system_error() {
        let error = safe_fopen("/definitely/not/a/flpdf/file", "rb")
            .expect_err("opening a missing path must fail");

        assert!(
            matches!(&error, crate::Error::System(message) if message.starts_with("open /definitely/not/a/flpdf/file: "))
        );
        #[cfg(unix)]
        assert!(
            matches!(&error, crate::Error::System(message) if message == "open /definitely/not/a/flpdf/file: No such file or directory"),
            "qpdf renders strerror without Rust's os-error suffix: {error:?}"
        );
    }

    /// `strerror_text` only strips Rust's `(os error N)` suffix when the
    /// failure carries a raw OS error code (`raw_os_error()`); a
    /// constructed [`std::io::Error`] without one (e.g. `Error::other`) has
    /// no such suffix to strip, and the text must pass through unchanged.
    #[test]
    fn strerror_text_passes_through_an_error_without_a_raw_os_code() {
        let error = std::io::Error::other("custom failure");
        assert_eq!(strerror_text(&error), "custom failure");
    }

    /// `strerror_text` maps qpdf's common `strerror(errno)` kinds to fixed
    /// portable wording rather than `std::io::Error`'s platform-native
    /// `Display` (`QPDFSystemError::createWhat`, `QPDFSystemError.cc:13-29`).
    /// A synthetic [`std::io::Error::from`] carries no `raw_os_error()`, so
    /// this specifically exercises the `ErrorKind` match arms rather than
    /// the suffix-stripped `Display` fallback -- the fallback path a real
    /// syscall failure exercises is covered separately by
    /// `safe_fopen_missing_path_is_a_qpdf_system_error` on Unix.
    /// `ErrorKind` is coarser than `errno`: `EPERM` and `EACCES` both map to
    /// `PermissionDenied`, but `strerror` prints "Operation not permitted"
    /// for the first and "Permission denied" for the second, and qpdf prints
    /// whichever `strerror(errno)` returns. A real syscall failure carries
    /// the raw code, so it must not be flattened through the `ErrorKind`
    /// table.
    #[cfg(unix)]
    #[test]
    fn strerror_text_keeps_errno_wording_that_error_kind_cannot_distinguish() {
        for (code, expected) in [
            (libc_eperm(), "Operation not permitted"),
            (libc_eacces(), "Permission denied"),
        ] {
            let error = std::io::Error::from_raw_os_error(code);
            assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
            assert_eq!(strerror_text(&error), expected, "errno {code}");
        }
    }

    #[cfg(unix)]
    fn libc_eperm() -> i32 {
        1
    }

    #[cfg(unix)]
    fn libc_eacces() -> i32 {
        13
    }

    #[test]
    fn strerror_text_maps_common_error_kinds_to_qpdf_wording() {
        for (kind, expected) in [
            (std::io::ErrorKind::NotFound, "No such file or directory"),
            (std::io::ErrorKind::PermissionDenied, "Permission denied"),
            (std::io::ErrorKind::AlreadyExists, "File exists"),
            (std::io::ErrorKind::InvalidInput, "Invalid argument"),
            (std::io::ErrorKind::IsADirectory, "Is a directory"),
            (std::io::ErrorKind::NotADirectory, "Not a directory"),
        ] {
            assert_eq!(strerror_text(&std::io::Error::from(kind)), expected);
        }
    }

    #[test]
    fn safe_fopen_supports_qpdf_read_write_modes() {
        let directory = tempfile::tempdir().expect("create temporary directory");
        let path = directory.path().join("safe-fopen.pdf");
        let path = path.to_str().expect("temporary path is UTF-8");

        let mut writer = safe_fopen(path, "wb").expect("open file for writing");
        writer.write_all(b"first").expect("write first chunk");
        drop(writer);

        let mut appender = safe_fopen(path, "ab").expect("open file for appending");
        appender
            .write_all(b" second")
            .expect("write appended chunk");
        drop(appender);

        let mut append_plus = safe_fopen(path, "a+").expect("open plus append mode");
        append_plus
            .write_all(b" third")
            .expect("write plus append chunk");
        drop(append_plus);

        let mut reader = safe_fopen(path, "rb").expect("open file for reading");
        let mut bytes = Vec::new();
        reader.read_to_end(&mut bytes).expect("read file");
        assert_eq!(bytes, b"first second third");
    }

    #[test]
    fn safe_fopen_covers_plus_exclusive_and_invalid_modes() {
        let directory = tempfile::tempdir().expect("create temporary directory");
        let plus_path = directory.path().join("plus");
        let plus_path = plus_path.to_str().expect("temporary path is UTF-8");
        let mut writer = safe_fopen(plus_path, "w+").expect("open plus write mode");
        writer.write_all(b"plus").expect("write plus-mode data");
        drop(writer);
        let _reader = safe_fopen(plus_path, "r+").expect("open plus read mode");

        let exclusive_path = directory.path().join("exclusive");
        let exclusive_path = exclusive_path.to_str().expect("temporary path is UTF-8");
        let _exclusive = safe_fopen(exclusive_path, "wx").expect("create exclusive file");
        assert!(safe_fopen(exclusive_path, "wx").is_err());

        let append_exclusive_path = directory.path().join("append-exclusive");
        let append_exclusive_path = append_exclusive_path
            .to_str()
            .expect("temporary path is UTF-8");
        let _append_exclusive =
            safe_fopen(append_exclusive_path, "ax").expect("create append-exclusive file");

        assert!(safe_fopen(plus_path, "").is_err());
        assert!(safe_fopen(plus_path, "r?").is_err());
        assert!(safe_fopen(plus_path, "z").is_err());
    }

    #[test]
    fn qpdf_string_to_int_checked_handles_empty_and_negative_values() {
        assert_eq!(qpdf_string_to_int_checked("-"), QpdfIntParse::NoDigits);
        assert_eq!(qpdf_string_to_int_checked("-42"), QpdfIntParse::Value(-42));
    }

    #[test]
    fn qpdf_string_to_int_checked_matches_strtoll_prefix_rules() {
        assert_eq!(
            qpdf_string_to_int_checked("  +42trailing"),
            QpdfIntParse::Value(42)
        );
        assert_eq!(qpdf_string_to_int_checked("+-42"), QpdfIntParse::NoDigits);
    }

    #[test]
    fn qpdf_string_to_int_checked_overflows_at_i64_stage() {
        assert_eq!(
            qpdf_string_to_int_checked("9999999999999999999999999999999999999999"),
            QpdfIntParse::Overflow(
                "overflow/underflow converting 9999999999999999999999999999999999999999 to 64-bit integer".into()
            )
        );
    }

    #[test]
    fn qpdf_string_to_int_checked_overflows_at_i32_narrowing_stage() {
        assert_eq!(
            qpdf_string_to_int_checked("4294967296"),
            QpdfIntParse::Overflow(
                "integer out of range converting 4294967296 from a 8-byte signed type to a 4-byte signed type".into()
            )
        );
    }

    #[test]
    fn parse_numrange_matches_qpdf_groups_exclusions_and_position_filters() {
        assert_eq!(parse_numrange(b"1-5,x3", 5).unwrap(), vec![1, 2, 4, 5]);
        assert_eq!(parse_numrange(b"5-1", 5).unwrap(), vec![5, 4, 3, 2, 1]);
        assert_eq!(parse_numrange(b"1-5:odd", 5).unwrap(), vec![1, 3, 5]);
        assert_eq!(parse_numrange(b"1-5:even", 5).unwrap(), vec![2, 4]);
        assert_eq!(parse_numrange(b":odd", 5).unwrap(), Vec::<i32>::new());
        assert_eq!(parse_numrange(b":even", 5).unwrap(), Vec::<i32>::new());
        assert_eq!(parse_numrange(b"1,1-3:odd", 5).unwrap(), vec![1, 2]);
        assert_eq!(parse_numrange(b"1,1-3:even", 5).unwrap(), vec![1, 3]);
        assert_eq!(parse_numrange(b"01-03", 5).unwrap(), vec![1, 2, 3]);
        assert_eq!(parse_numrange(b"1-3,x2,4", 5).unwrap(), vec![1, 3, 4]);
    }

    #[test]
    fn parse_numrange_max_zero_and_nonpositive_values_follow_qpdf() {
        assert_eq!(parse_numrange(b"", 0).unwrap(), Vec::<i32>::new());
        assert_eq!(parse_numrange(b"0,r0,z", 0).unwrap(), vec![0, 1, 0]);
        assert_eq!(parse_numrange(b"z,r1", -1).unwrap(), vec![-1, -1]);
    }

    #[test]
    fn parse_numrange_truncates_at_nul_and_preserves_raw_error_bytes() {
        assert_eq!(parse_numrange(b"1-2\0not-a-range", 2).unwrap(), vec![1, 2]);
        let error = parse_numrange(b"1-\xff", 2).unwrap_err();
        assert_eq!(
            error.raw_message(),
            Some(b"error at * in numeric range *1-\xff: invalid range syntax".as_slice())
        );
    }

    #[test]
    fn parse_numrange_reports_qpdf_integer_overflow() {
        let error = parse_numrange(b"999999999999999999999999", 0).unwrap_err();
        assert_eq!(
            error.to_string(),
            "error at * in numeric range *999999999999999999999999: overflow/underflow converting 999999999999999999999999 to 64-bit integer"
        );
    }

    #[test]
    fn parse_numrange_reports_qpdf_trailing_comma_position() {
        let error = parse_numrange(b"1-5,:odd", 5).unwrap_err();
        assert_eq!(
            error.to_string(),
            "error at * in numeric range 1-5,*:odd: trailing comma"
        );
    }

    #[test]
    fn qpdf_size_to_int_matches_qintc_unsigned_narrowing() {
        assert_eq!(qpdf_size_to_int(17).unwrap(), 17);
        let error = qpdf_size_to_int(i32::MAX as usize + 1).unwrap_err();
        assert_eq!(
            error.to_string(),
            format!(
                "integer out of range converting 2147483648 from a {}-byte unsigned type to a {}-byte signed type",
                std::mem::size_of::<usize>(),
                std::mem::size_of::<i32>()
            )
        );
    }

    #[test]
    fn parse_numrange_validates_group_syntax_before_exclusion_or_narrowing() {
        for input in [b"x".as_slice(), b"xfoo", b"x1-", b"2147483648x", b"0x"] {
            let error = parse_numrange(input, 5).unwrap_err();
            assert!(
                error.to_string().ends_with(": invalid range syntax"),
                "{input:?}: {error}"
            );
        }
    }

    #[test]
    fn parse_numrange_reports_invalid_suffix_and_first_exclusion() {
        let suffix = parse_numrange(b"1:unexpected", 5).unwrap_err();
        assert!(suffix.to_string().ends_with(": expected :even or :odd"));
        let exclusion = parse_numrange(b"x3", 5).unwrap_err();
        assert!(exclusion
            .to_string()
            .ends_with(": first range group may not be an exclusion"));
    }

    #[test]
    fn parse_numrange_matches_qpdf_narrowing_and_wrapping_boundaries() {
        let leading_zero = parse_numrange(b"02147483648", 0).unwrap_err();
        assert!(leading_zero
            .to_string()
            .contains("integer out of range converting 2147483648 from"));
        let leading_zero_short = parse_numrange(b"0004294967296", 0).unwrap_err();
        assert!(leading_zero_short
            .to_string()
            .contains("integer out of range converting 4294967296 from"));
        let wrapped = parse_numrange(b"r0", i32::MAX).unwrap_err();
        assert_eq!(
            wrapped.to_string(),
            "error at * in numeric range *r0: number -2147483648 out of range"
        );
    }

    #[test]
    fn same_file_identifies_hard_link_and_symlink_aliases() {
        let dir = tempfile::tempdir().unwrap();
        let original = dir.path().join("original");
        let hard_link = dir.path().join("hard-link");
        let symlink = dir.path().join("symlink");
        let unrelated = dir.path().join("unrelated");
        std::fs::write(&original, b"content").unwrap();
        std::fs::write(&unrelated, b"content").unwrap();
        std::fs::hard_link(&original, &hard_link).unwrap();
        #[cfg(unix)]
        std::os::unix::fs::symlink(&original, &symlink).unwrap();
        #[cfg(windows)]
        std::os::windows::fs::symlink_file(&original, &symlink).unwrap();

        assert!(same_file(&original, &original));
        assert!(same_file(&original, &hard_link));
        assert!(same_file(&original, &symlink));
        assert!(!same_file(&original, &unrelated));
    }

    #[test]
    fn same_file_returns_false_for_a_missing_path() {
        let dir = tempfile::tempdir().unwrap();
        let existing = dir.path().join("existing");
        let missing = dir.path().join("missing");
        std::fs::write(&existing, b"content").unwrap();

        assert!(!same_file(&existing, &missing));
        assert!(!same_file(&missing, &missing));
    }

    #[cfg(unix)]
    #[test]
    fn same_file_does_not_open_a_fifo_and_completes_without_a_reader() {
        // qpdf's own `QUtil::same_file` compares `stat()` device/inode
        // numbers without opening either path (`libqpdf/QUtil.cc:601-604`).
        // A same_file implementation that opens its arguments (e.g. the
        // `same_file` crate's path-based `is_same_file`) would block
        // indefinitely here: opening a FIFO for reading waits for a writer,
        // and nothing in this test ever opens the write end. Bound the call
        // in a thread so a regression fails this test instead of hanging
        // the process.
        let dir = tempfile::tempdir().unwrap();
        let fifo_path = dir.path().join("fifo");
        let status = std::process::Command::new("mkfifo")
            .arg(&fifo_path)
            .status()
            .expect("mkfifo command should be available on Unix test runners");
        assert!(status.success(), "mkfifo failed: {status}");

        let (sender, receiver) = std::sync::mpsc::channel();
        let probe_path = fifo_path.clone();
        std::thread::spawn(move || {
            let _ = sender.send(same_file(&probe_path, &probe_path));
        });
        let result = receiver
            .recv_timeout(std::time::Duration::from_secs(5))
            .expect("same_file must not open a FIFO path; it deadlocks with no writer connected");
        assert!(result, "a FIFO path must compare equal to itself");
    }

    #[test]
    fn utf8_to_ascii_preserves_ascii_and_replaces_unrepresentable_text() {
        assert_eq!(utf8_to_ascii(b"A\xc3\xa9\xe2\x98\x83"), b"A??".to_vec());
    }

    #[test]
    fn utf8_to_ascii_replaces_invalid_sequences_one_byte_at_a_time() {
        assert_eq!(utf8_to_ascii(b"A\xc3(\xff"), b"A?(?".to_vec());
    }

    #[test]
    fn utf8_to_win_ansi_maps_extended_codepoints_and_nbsp() {
        assert_eq!(
            utf8_to_win_ansi("€—é\u{a0}☃".as_bytes()),
            vec![0x80, 0x97, 0xe9, 0xa0, b'?']
        );
    }

    #[test]
    fn utf8_to_mac_roman_maps_qpdf_extended_table() {
        assert_eq!(
            utf8_to_mac_roman("Äé†μ☃".as_bytes()),
            vec![0x80, 0x8e, 0xa0, 0xb5, b'?']
        );
    }

    #[test]
    fn empty_input_stays_empty_in_every_qpdf_single_byte_encoding() {
        assert!(utf8_to_ascii(b"").is_empty());
        assert!(utf8_to_win_ansi(b"").is_empty());
        assert!(utf8_to_mac_roman(b"").is_empty());
    }

    #[test]
    fn undefined_extended_slots_use_qpdfs_replacement_byte() {
        assert_eq!(utf8_to_win_ansi("\u{81}\u{8d}\u{9d}".as_bytes()), b"???");
        assert_eq!(
            utf8_to_mac_roman("\u{ad}\u{b0}\u{bd}".as_bytes()),
            vec![b'?', 0xa1, b'?']
        );
    }

    #[test]
    fn qpdf_utf8_decoder_covers_four_five_and_six_byte_forms() {
        let input = [
            0xf0, 0x9f, 0x98, 0x80, // U+1F600
            0xf8, 0x88, 0x80, 0x80, 0x80, // qpdf's five-byte form
            0xfc, 0x84, 0x80, 0x80, 0x80, 0x80, // qpdf's six-byte form
        ];
        assert_eq!(utf8_to_ascii(&input), b"???");
    }

    #[test]
    fn utf8_to_win_ansi_covers_qpdfs_extended_mapping() {
        let codepoints = [
            0x00a0, 0x0192, 0x0152, 0x0153, 0x0160, 0x0161, 0x0178, 0x017d, 0x017e, 0x02c6, 0x0303,
            0x2013, 0x2014, 0x2018, 0x2019, 0x201a, 0x201c, 0x201d, 0x201e, 0x2020, 0x2021, 0x2022,
            0x2026, 0x2030, 0x2039, 0x203a, 0x20ac, 0x2122,
        ];
        let input: String = codepoints
            .into_iter()
            .map(|codepoint| char::from_u32(codepoint).unwrap())
            .collect();
        assert_eq!(
            utf8_to_win_ansi(input.as_bytes()),
            vec![
                0xa0, 0x83, 0x8c, 0x9c, 0x8a, 0x9a, 0x9f, 0x8e, 0x9e, 0x88, 0x98, 0x96, 0x97, 0x91,
                0x92, 0x82, 0x93, 0x94, 0x84, 0x86, 0x87, 0x95, 0x85, 0x89, 0x8b, 0x9b, 0x80, 0x99,
            ]
        );
    }

    #[test]
    fn utf8_to_pdf_doc_preserves_ascii_and_the_direct_high_range() {
        assert_eq!(utf8_to_pdf_doc("Aé".as_bytes()), vec![b'A', 0xe9]);
    }

    #[test]
    fn checked_transcoders_separate_substitution_from_a_literal_question_mark() {
        // The whole point of qpdf's second overload: the bytes alone cannot
        // tell these apart, only the flag can (`libqpdf/QUtil.cc:1669-1673`).
        assert_eq!(utf8_to_pdf_doc_checked(b"\x1f"), (b"?".to_vec(), false));
        assert_eq!(utf8_to_pdf_doc_checked(b"?"), (b"?".to_vec(), true));
        // U+00AD is the other PDFDoc-specific omission (`:1586-1589`).
        assert_eq!(
            utf8_to_pdf_doc_checked("\u{ad}".as_bytes()),
            (b"?".to_vec(), false)
        );
        assert_eq!(utf8_to_pdf_doc_checked("€".as_bytes()), (vec![0xa0], true));

        // ASCII keeps 0x1f, so the same input is representable there
        // (`:1651-1655`); a high code point is not.
        assert_eq!(utf8_to_ascii_checked(b"\x1f"), (b"\x1f".to_vec(), true));
        assert_eq!(
            utf8_to_ascii_checked("é".as_bytes()),
            (b"?".to_vec(), false)
        );
    }

    #[test]
    fn utf8_to_pdf_doc_maps_the_euro_sign_to_its_pdfdoc_byte() {
        // PDFDocEncoding assigns U+20AC to 0xA0, which is outside the
        // 0xA1-0xFF direct range, so it has to come from the table:
        // qpdf's `unicode_to_pdf_doc` carries `{0x20ac, 0xa0}`
        // (`libqpdf/QUtil.cc:289`). The WinAnsi table maps the same
        // codepoint to 0x80 (`:255`), which is a different encoding.
        assert_eq!(utf8_to_pdf_doc("€".as_bytes()), vec![0xa0]);
    }

    #[test]
    fn utf8_to_pdf_doc_rejects_ascii_control_codes_pdfdoc_reassigns() {
        // qpdf test_driver.cc's own test_86: `utf8_to_pdf_doc` on a bare
        // U+001F fails and yields the replacement character alone, unlike
        // `utf8_to_ascii`, which passes every ASCII byte through unchanged.
        assert_eq!(utf8_to_pdf_doc(b"\x1f"), b"?");
        assert_eq!(utf8_to_ascii(b"\x1f"), b"\x1f");
        for byte in 0x18u8..=0x1f {
            assert_eq!(utf8_to_pdf_doc(&[byte]), b"?", "byte {byte:#x}");
        }
        assert_eq!(utf8_to_pdf_doc(b"\x7f"), b"?");
    }

    #[test]
    fn utf8_to_pdf_doc_rejects_soft_hyphen() {
        assert_eq!(utf8_to_pdf_doc("\u{ad}".as_bytes()), b"?");
    }

    #[test]
    fn utf8_to_pdf_doc_covers_qpdfs_extended_mapping() {
        let codepoints = [
            0x02d8, 0x02c7, 0x02c6, 0x02d9, 0x02dd, 0x02db, 0x02da, 0x02dc, 0x2022, 0x2020, 0x2021,
            0x2026, 0x2014, 0x2013, 0x0192, 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c,
            0x201d, 0x2018, 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x0141, 0x0152, 0x0160, 0x0178,
            0x017d, 0x0131, 0x0142, 0x0153, 0x0161, 0x017e, 0xfffd,
        ];
        let input: String = codepoints
            .into_iter()
            .map(|codepoint| char::from_u32(codepoint).unwrap())
            .collect();
        let expected: Vec<u8> = (0x18u8..=0x1f).chain(0x80u8..=0x9f).collect();
        assert_eq!(utf8_to_pdf_doc(input.as_bytes()), expected);
    }

    #[test]
    fn utf8_to_pdf_doc_flags_input_that_would_collide_with_a_bom() {
        // qpdf avoids emitting PDFDocEncoding bytes that a reader would
        // mistake for a UTF-16BE/LE or UTF-8 byte-order mark by checking the
        // *input* Unicode codepoints, not the output bytes: the check does
        // not consume input, so the flagged codepoints are still transcoded
        // (here, through the direct 0xA1-0xFF range) after the leading `?`.
        assert_eq!(
            utf8_to_pdf_doc("\u{fe}\u{ff}".as_bytes()),
            vec![b'?', 0xfe, 0xff]
        );
        assert_eq!(
            utf8_to_pdf_doc("\u{ff}\u{fe}".as_bytes()),
            vec![b'?', 0xff, 0xfe]
        );
        assert_eq!(
            utf8_to_pdf_doc("\u{ef}\u{bb}\u{bf}".as_bytes()),
            vec![b'?', 0xef, 0xbb, 0xbf]
        );
        // A prefix that only partially matches (or an unrelated string) does
        // not trigger the leading `?`.
        assert_eq!(utf8_to_pdf_doc("\u{fe}".as_bytes()), vec![0xfe]);
        assert_eq!(utf8_to_pdf_doc("A".as_bytes()), vec![b'A']);
    }

    #[test]
    fn empty_input_stays_empty_for_pdf_doc_too() {
        assert!(utf8_to_pdf_doc(b"").is_empty());
    }
}