mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-07 12:13:20 +00:00
pdf: keep a CID font's /W2 table past an out-of-range first CID; vendor hayro-cmap from PdfCraft (#254)
* pdf: keep a CID font's /W2 table past an out-of-range first CID; vendor hayro-cmap from PdfCraft - hayro-interpret: a /W2 run whose first CID is past 65535 is skipped, as in /W. A run starting at 4294967295 overflowed the CID counter and discarded the whole table. Unit test in font::cid. - hayro-cmap 0.1.0 is vendored from PdfCraft a2ec27b47 with its malformed-CMap patch (PdfCraft #3177): bad bfchar/bfrange entries, an unresolvable usecmap and an unparseable tail are skipped instead of failing the whole CMap. The crate's tests come with it. Wired up like the other vendored Hayro crates (workspace exclude, patch entry, SOURCE.json, backend test script); NOTICE, ATTRIBUTION.md and vendor/README.craft-reader.md record the source. * hayro-syntax: refuse an xref-stream subsection that runs past object number u32::MAX The object number was start + i in unchecked u32: a subsection starting near u32::MAX overflowed (a panic in debug builds, a wrong object number in release). Covered in xref::tests::xref_stream_entries_need_backing_bytes. * hayro-cmap: a binary usecmap counts against the nesting limit; /W2 checks the CID first - hayro-cmap: a binary CMap's usecmap passed its own depth to the nested parse, so a self-referencing binary CMap recursed until the stack overflowed. It now counts like a text usecmap. Test: self_referencing_binary_usecmap_stops_at_the_nesting_limit. - hayro-interpret: the /W2 first-CID check runs before the run's metrics are read, so an incomplete run past CID 65535 no longer discards the rest of the table. * hayro-syntax: refuse xref-stream object numbers past i32::MAX ObjectIdentifier stores an i32; a number between i32::MAX and u32::MAX was cast to a negative object number.
This commit is contained in:
+4
-4
@@ -32,10 +32,10 @@ The vendored source patch and per-file hashes are recorded in `vendor/krilla/REA
|
||||
|
||||
## Assets retained with the optional PDF reader
|
||||
|
||||
The shared reader centralizes the four existing patched Hayro source trees from PdfCraft.
|
||||
The shared reader centralizes the five patched Hayro source trees from PdfCraft.
|
||||
The standard-14 fonts, CMYK profile and generated metrics listed below remain byte-identical
|
||||
in `vendor/hayro-interpret`; no application document fonts are added. CMaps remain a pinned
|
||||
registry dependency. The removed upstream LAB.icc profile is not restored. Source hashes
|
||||
in `vendor/hayro-interpret`, and the CMaps in `vendor/hayro-cmap/assets`; no application
|
||||
document fonts are added. The removed upstream LAB.icc profile is not restored. Source hashes
|
||||
and the exact transfer revision are recorded in each vendored crate's SOURCE.json.
|
||||
|
||||
| Crate / file | Author | Source | Licence | SHA-256 | Use |
|
||||
@@ -55,5 +55,5 @@ and the exact transfer revision are recorded in each vendored crate's SOURCE.jso
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb | BSD-3-Clause | `610ae0687198045c4db5d1a6650fd5e92536631706382eb8b72e38df578d0ae9` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSymbol.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSymbol.pfb | BSD-3-Clause | `47967d055530e7357088a08403115425643ec2cdfd6201ba8af0fbd7116c1539` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc | CC0-1.0 | `73e1ba37d2bad5bab2a964f40a9eed96209666efc067c3322626214bbef234a0` | Default CMYK colour conversion (pinned hayro-interpret) |
|
||||
| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://crates.io/crates/hayro-cmap/0.1.0 | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged |
|
||||
| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://github.com/storytold/pdfcraft/blob/a2ec27b4775f53c40cad3456936d9406611e3a8d/vendor/hayro-cmap/assets/cmaps.brotli | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged |
|
||||
| `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged |
|
||||
|
||||
Generated
-2
@@ -1850,8 +1850,6 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "24d285dc30731c8485de5fa732fbdf2b3affdf01e4da7c2135022ca6fa664bf6"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"hayro-postscript",
|
||||
|
||||
+2
-1
@@ -1,7 +1,7 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/*"]
|
||||
exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2"]
|
||||
exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
@@ -54,3 +54,4 @@ hayro = { path = "vendor/hayro" }
|
||||
hayro-interpret = { path = "vendor/hayro-interpret" }
|
||||
hayro-syntax = { path = "vendor/hayro-syntax" }
|
||||
hayro-jbig2 = { path = "vendor/hayro-jbig2" }
|
||||
hayro-cmap = { path = "vendor/hayro-cmap" }
|
||||
|
||||
@@ -96,15 +96,16 @@ and vendor/krilla/SOURCE.json. Its upstream MIT/Apache-2.0 licences and CC0 prof
|
||||
|
||||
Optional PDF reader
|
||||
|
||||
Hayro 0.7.1, hayro-interpret 0.7.0, hayro-syntax 0.7.2 and hayro-jbig2 0.3.0
|
||||
Hayro 0.7.1, hayro-interpret 0.7.0, hayro-syntax 0.7.2, hayro-jbig2 0.3.0 and hayro-cmap 0.1.0
|
||||
(https://github.com/LaurenzV/hayro), MIT OR Apache-2.0, retain their upstream licence files.
|
||||
These patched sources are transferred from PdfCraft revision
|
||||
7437bde378f43856eada40af25b983812e615e8a (https://github.com/storytold/pdfcraft).
|
||||
These patched sources are transferred from PdfCraft (https://github.com/storytold/pdfcraft):
|
||||
hayro-cmap from revision a2ec27b4775f53c40cad3456936d9406611e3a8d, the others from revision
|
||||
7437bde378f43856eada40af25b983812e615e8a.
|
||||
See vendor/README.craft-reader.md and each crate's SOURCE.json for provenance and local changes.
|
||||
The reader retains the existing Foxit/PDFium standard-14 font assets (BSD-3-Clause),
|
||||
Compact ICC Profiles by Clinton Ingram (CC0-1.0), and dependency CMaps (BSD-3-Clause).
|
||||
Their licences and per-file hashes are retained in vendor/hayro-interpret/assets,
|
||||
licenses/pdf-backend and ATTRIBUTION.md. These are existing reader dependency assets;
|
||||
vendor/hayro-cmap/assets, licenses/pdf-backend and ATTRIBUTION.md. These are existing reader dependency assets;
|
||||
applications retain their own document-font selection and licensing policy.
|
||||
|
||||
Platform lifecycle source provenance
|
||||
|
||||
@@ -7,11 +7,11 @@ test_root=$(mktemp -d "${TMPDIR:-/tmp}/craft-pdf-backends.XXXXXX")
|
||||
trap 'rm -rf "$test_root"' EXIT
|
||||
export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$root/target}"
|
||||
patches=()
|
||||
for backend in hayro hayro-interpret hayro-syntax hayro-jbig2; do
|
||||
for backend in hayro hayro-interpret hayro-syntax hayro-jbig2 hayro-cmap; do
|
||||
cp -R "$root/vendor/$backend" "$test_root/$backend"
|
||||
patches+=(--config "patch.crates-io.$backend.path=\"$test_root/$backend\"")
|
||||
done
|
||||
for backend in hayro-syntax hayro-interpret hayro hayro-jbig2; do
|
||||
for backend in hayro-syntax hayro-interpret hayro hayro-jbig2 hayro-cmap; do
|
||||
cargo test --manifest-path "$test_root/$backend/Cargo.toml" --lib "${patches[@]}"
|
||||
done
|
||||
cargo test --manifest-path "$test_root/hayro-syntax/Cargo.toml" --doc "${patches[@]}"
|
||||
|
||||
Vendored
+12
@@ -6,6 +6,14 @@ The upstream [patch ledger](https://github.com/storytold/pdfcraft/blob/7437bde37
|
||||
describes the inherited patches. Source manifests record every transferred Git blob and
|
||||
SHA-256 alongside the local hash. The source manifests themselves are not self-hashed.
|
||||
|
||||
`hayro-cmap` 0.1.0 is transferred from [PdfCraft revision a2ec27b4775f53c40cad3456936d9406611e3a8d](https://github.com/storytold/pdfcraft/tree/a2ec27b4775f53c40cad3456936d9406611e3a8d/vendor/hayro-cmap)
|
||||
with its malformed-CMap patch (PdfCraft #3177): bad `bfchar` or `bfrange` entries, an
|
||||
unresolvable `usecmap` and an unparseable tail are skipped instead of discarding the whole
|
||||
CMap. Its tests `tests::bad_bfchar_entry_is_skipped` and `tests::unresolvable_usecmap_is_skipped`
|
||||
come with it. One local patch: a binary `usecmap` counts against the 16-level nesting limit
|
||||
as a text one does, so a self-referencing binary CMap stops instead of overflowing the stack.
|
||||
Consuming workspaces need a `hayro-cmap` patch entry beside the other Hayro entries.
|
||||
|
||||
The shared snapshot adds immutable per-document ordinary decode limits, threaded through
|
||||
initial xrefs, object streams, fallback and repair. Existing constructors retain their
|
||||
previous default. Known-size image budgets and streaming content budgets remain distinct.
|
||||
@@ -58,6 +66,10 @@ Hostile-input bounds (CodeRabbit findings):
|
||||
- An xref-stream `/W` type field wider than one byte is read at its full width (big-endian)
|
||||
instead of only its first byte, and `/W[0]` over 8 bytes is refused like `/W[1]`.
|
||||
A dash array over 256 entries strokes solid.
|
||||
- An xref-stream subsection running past object number `i32::MAX` is refused instead of
|
||||
overflowing or turning negative.
|
||||
- A CID font's `/W2` run that starts past CID 65535 is skipped as in `/W`, instead of
|
||||
overflowing and discarding the whole table.
|
||||
|
||||
This remains the patched 0.7 backend. It retains the existing Bradford Lab conversion,
|
||||
floating component precision and codec versions, rather than claiming full 0.8
|
||||
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "alloc-no-stdlib"
|
||||
version = "2.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
|
||||
|
||||
[[package]]
|
||||
name = "alloc-stdlib"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "brotli"
|
||||
version = "8.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4bd8b9603c7aa97359dbd97ecf258968c95f3adddd6db2f7e7a5bef101c84560"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
"brotli-decompressor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "brotli-decompressor"
|
||||
version = "5.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "874bb8112abecc98cbd6d81ea4fa7e94fb9449648c93cc89aa40c81c24d7de03"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"hayro-postscript",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "885c5ef0654933139a9b9546fc2c69e18d37f38aa2520f079092b1be18f1fcaa"
|
||||
Vendored
+87
@@ -0,0 +1,87 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2024"
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
authors = ["Laurenz Stampfl <laurenz.stampfl@gmail.com>"]
|
||||
build = false
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "A parser for CMap files."
|
||||
readme = "README.md"
|
||||
license = "Apache-2.0 OR MIT"
|
||||
repository = "https://github.com/LaurenzV/hayro"
|
||||
resolver = "2"
|
||||
|
||||
[features]
|
||||
default = ["embed-cmaps"]
|
||||
embed-cmaps = [
|
||||
"std",
|
||||
"dep:brotli",
|
||||
]
|
||||
std = []
|
||||
|
||||
[lib]
|
||||
name = "hayro_cmap"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies.brotli]
|
||||
version = "8"
|
||||
features = [
|
||||
"std",
|
||||
"std",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.hayro-postscript]
|
||||
version = "0.1.0"
|
||||
default-features = false
|
||||
|
||||
[lints.clippy]
|
||||
collection_is_never_read = "warn"
|
||||
dbg_macro = "warn"
|
||||
debug_assert_with_mut_call = "warn"
|
||||
default_trait_access = "warn"
|
||||
doc_markdown = "warn"
|
||||
fn_to_numeric_cast_any = "warn"
|
||||
infinite_loop = "warn"
|
||||
large_stack_arrays = "warn"
|
||||
mismatching_type_param_order = "warn"
|
||||
negative_feature_names = "warn"
|
||||
redundant_feature_names = "warn"
|
||||
same_functions_in_if_condition = "warn"
|
||||
semicolon_if_nothing_returned = "warn"
|
||||
todo = "warn"
|
||||
too_many_arguments = "allow"
|
||||
unseparated_literal_suffix = "warn"
|
||||
use_self = "warn"
|
||||
wildcard_dependencies = "warn"
|
||||
|
||||
[lints.rust]
|
||||
elided_lifetimes_in_paths = "warn"
|
||||
keyword_idents_2024 = "forbid"
|
||||
missing_docs = "warn"
|
||||
non_ascii_idents = "forbid"
|
||||
non_local_definitions = "forbid"
|
||||
trivial_numeric_casts = "warn"
|
||||
unnameable_types = "warn"
|
||||
unreachable_pub = "warn"
|
||||
unsafe_op_in_unsafe_fn = "forbid"
|
||||
unused_import_braces = "warn"
|
||||
unused_lifetimes = "warn"
|
||||
unused_macro_rules = "warn"
|
||||
unused_qualifications = "warn"
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
description = "A parser for CMap files."
|
||||
authors = { workspace = true }
|
||||
edition = { workspace = true }
|
||||
repository = { workspace = true }
|
||||
license = { workspace = true }
|
||||
|
||||
[features]
|
||||
default = ["embed-cmaps"]
|
||||
std = []
|
||||
# Embed the 61 predefined cmaps into the binary. Adds about ~250KB of brotli-encoded data.
|
||||
embed-cmaps = ["std", "dep:brotli"]
|
||||
|
||||
[dependencies]
|
||||
hayro-postscript = { workspace = true }
|
||||
brotli = { workspace = true, optional = true, features = ["std"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
Vendored
+177
@@ -0,0 +1,177 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
Copyright (c) The Hayro Authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
Vendored
+25
@@ -0,0 +1,25 @@
|
||||
# hayro-cmap
|
||||
|
||||
[](https://crates.io/crates/hayro-cmap)
|
||||
[](https://docs.rs/hayro-cmap)
|
||||
|
||||
<!-- cargo-rdme start -->
|
||||
|
||||
A parser for cmap files, as they are found in PDFs.
|
||||
|
||||
This crate provides a parser for CMap files and allows you to
|
||||
- Map character codes from text-showing operators to CID identifiers.
|
||||
- Map CIDs to Unicode characters or strings.
|
||||
|
||||
### Safety
|
||||
This crate forbids unsafe code via a crate-level attribute.
|
||||
|
||||
<!-- cargo-rdme end -->
|
||||
|
||||
## License
|
||||
Licensed under either of
|
||||
|
||||
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
|
||||
- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
|
||||
|
||||
at your option.
|
||||
Vendored
+98
@@ -0,0 +1,98 @@
|
||||
{
|
||||
"crate": "hayro-cmap",
|
||||
"source_repository": "https://github.com/storytold/pdfcraft",
|
||||
"source_revision": "a2ec27b4775f53c40cad3456936d9406611e3a8d",
|
||||
"source_directory": "vendor/hayro-cmap",
|
||||
"files": [
|
||||
{
|
||||
"path": "Cargo.lock",
|
||||
"source_sha256": "b0ffb94a754c7254ecbead6649fa7877b6875531f9af8c62f7c28e1b11c5a391",
|
||||
"source_git_blob": "b19a6c70fe633320e822a370fa242f32b7e0f914",
|
||||
"sha256": "b0ffb94a754c7254ecbead6649fa7877b6875531f9af8c62f7c28e1b11c5a391"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.toml",
|
||||
"source_sha256": "7066550c610db3cb13df3c955f5737dccc3d9d24b6b680e9f633ecfadb82bf86",
|
||||
"source_git_blob": "3818d177b6dcc5c0d754bc3ecf1a3422476c7e2f",
|
||||
"sha256": "7066550c610db3cb13df3c955f5737dccc3d9d24b6b680e9f633ecfadb82bf86"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.toml.orig",
|
||||
"source_sha256": "9bcaf09fca4f5880318ba762cf07d5d269c458bb06f0b6409ae0879b2e564be3",
|
||||
"source_git_blob": "59f5c99d3f5082e9f5064055da016aed0d4fcf35",
|
||||
"sha256": "9bcaf09fca4f5880318ba762cf07d5d269c458bb06f0b6409ae0879b2e564be3"
|
||||
},
|
||||
{
|
||||
"path": "LICENSE-APACHE",
|
||||
"source_sha256": "0cec06e0e55fbc3dc5cee4fca9b607f66cb8f4e4dbcf3b3c013594dd156732e9",
|
||||
"source_git_blob": "4947287f7b5ccb5d1e8b7b2d3aa5d89f322c160d",
|
||||
"sha256": "0cec06e0e55fbc3dc5cee4fca9b607f66cb8f4e4dbcf3b3c013594dd156732e9"
|
||||
},
|
||||
{
|
||||
"path": "LICENSE-MIT",
|
||||
"source_sha256": "51b50e6120c344dcc146bbd6375ca1c78e079d97c8bea76e67a53d6ff0efebac",
|
||||
"source_git_blob": "ae3742de4e9ccb463cb46f05fe3ca0ec23fbb0d2",
|
||||
"sha256": "51b50e6120c344dcc146bbd6375ca1c78e079d97c8bea76e67a53d6ff0efebac"
|
||||
},
|
||||
{
|
||||
"path": "README.md",
|
||||
"source_sha256": "167f3ef1e830520bcc45359a21e513069e75a42393722accca9f56822f1dcc82",
|
||||
"source_git_blob": "bc93f93daa6b750afd709e2bcdfa2b2518b6e6a5",
|
||||
"sha256": "167f3ef1e830520bcc45359a21e513069e75a42393722accca9f56822f1dcc82"
|
||||
},
|
||||
{
|
||||
"path": "assets/LICENSE.txt",
|
||||
"source_sha256": "742665db9c8e1bc72603c6d319ca3e90b83bd6d95202f0cd4ef11068a07a9c29",
|
||||
"source_git_blob": "2552cc990c12f85cdc50ef3c5185061a8c64e326",
|
||||
"sha256": "742665db9c8e1bc72603c6d319ca3e90b83bd6d95202f0cd4ef11068a07a9c29"
|
||||
},
|
||||
{
|
||||
"path": "assets/README.md",
|
||||
"source_sha256": "61a2206d48aa4bac7dfc39416b0526fd994d0173897666f231f5c370cc06f646",
|
||||
"source_git_blob": "4cedb1ff6d3c6d0b44e5cf20f749fb470bc8de01",
|
||||
"sha256": "61a2206d48aa4bac7dfc39416b0526fd994d0173897666f231f5c370cc06f646"
|
||||
},
|
||||
{
|
||||
"path": "assets/cmaps.brotli",
|
||||
"source_sha256": "ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46",
|
||||
"source_git_blob": "ba74bd32fc71bb274e3e7e5c36bafaf89b9d6815",
|
||||
"sha256": "ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46"
|
||||
},
|
||||
{
|
||||
"path": "src/bcmap/embedded.rs",
|
||||
"source_sha256": "c1e18cf9fa5c413fe87bbc69394f2b8f0a7f6b5cda30b926665d0596ea79691b",
|
||||
"source_git_blob": "0f5c241a0e278da6e3eefe72fe3925ce7e177f57",
|
||||
"sha256": "c1e18cf9fa5c413fe87bbc69394f2b8f0a7f6b5cda30b926665d0596ea79691b"
|
||||
},
|
||||
{
|
||||
"path": "src/bcmap/huffman.rs",
|
||||
"source_sha256": "9b1f4ba036f8b6e9011b2fb9c1d80f6b34ba4c1be3c101b9678a8b49a8d352ea",
|
||||
"source_git_blob": "b6e8e9ab5d9fcdf831ceedaa7f620bd9d5e7ac8c",
|
||||
"sha256": "9b1f4ba036f8b6e9011b2fb9c1d80f6b34ba4c1be3c101b9678a8b49a8d352ea"
|
||||
},
|
||||
{
|
||||
"path": "src/bcmap/mod.rs",
|
||||
"source_sha256": "38dafbd8fcb5ca6f647d70d02cdb5af532ea7f2a3ac3f7ac8d1dea23abc93058",
|
||||
"source_git_blob": "997bc00d85db1504c63cf56e3cb157410ebdb0bb",
|
||||
"sha256": "3d0ea5e34bc92c40a250923ecb71b48571100bba5cc4664ea2c46d51086fe6be"
|
||||
},
|
||||
{
|
||||
"path": "src/bcmap/reader.rs",
|
||||
"source_sha256": "343b20170f8445258fb564f4f5387f66df804920d73886981f0db8829562d1cf",
|
||||
"source_git_blob": "25d6639104148a9123044c2c092a9bee5c889fd3",
|
||||
"sha256": "343b20170f8445258fb564f4f5387f66df804920d73886981f0db8829562d1cf"
|
||||
},
|
||||
{
|
||||
"path": "src/lib.rs",
|
||||
"source_sha256": "d666b3d8e4d37fc06c299a60ab9748ae17badcea271ff2cf864dcee76e27648c",
|
||||
"source_git_blob": "fb42ff37ec9ccece66d33d1888bd25963cbf1171",
|
||||
"sha256": "d6b9c6fa8de00942dd4cdfbd43578d3e53f8a3a6cf1e3563b345a9f6f35bc5e8"
|
||||
},
|
||||
{
|
||||
"path": "src/parse.rs",
|
||||
"source_sha256": "1999127f05b59bdd55e2a7349dafc0b2213238201da37f7c35cd698996f2dc6b",
|
||||
"source_git_blob": "a936209275ffca797912dec052dc03ddb0d2dce4",
|
||||
"sha256": "1999127f05b59bdd55e2a7349dafc0b2213238201da37f7c35cd698996f2dc6b"
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+28
@@ -0,0 +1,28 @@
|
||||
Copyright 1990-2023 Adobe. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
|
||||
Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
Neither the name of Adobe nor the names of its contributors may be
|
||||
used to endorse or promote products derived from this software without
|
||||
specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
See https://github.com/LaurenzV/cmap-resources/tree/hayro for information on how this blob was generated and how
|
||||
it can be parsed.
|
||||
BIN
Binary file not shown.
+129
@@ -0,0 +1,129 @@
|
||||
use std::ops::Range;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use super::huffman::{self, HuffmanTable};
|
||||
use super::reader::Reader;
|
||||
use crate::CMapName;
|
||||
|
||||
pub(super) static BUNDLE: LazyLock<Bundle> = LazyLock::new(|| {
|
||||
// We already know the bundle is valid, so we can skip validation and just
|
||||
// unwrap everywhere.
|
||||
|
||||
let compressed = include_bytes!("../../assets/cmaps.brotli");
|
||||
let mut decompressed = Vec::new();
|
||||
let mut reader = compressed.as_slice();
|
||||
|
||||
brotli::BrotliDecompress(&mut reader, &mut decompressed)
|
||||
.ok()
|
||||
.unwrap();
|
||||
|
||||
let mut reader = Reader::new(&decompressed);
|
||||
let huff_size = reader.read_u32().unwrap() as usize;
|
||||
let huff_data = reader.read_bytes(huff_size).unwrap();
|
||||
let (delta_table, count_table) = huffman::decode_tables(huff_data).unwrap();
|
||||
|
||||
let mut entries = Vec::new();
|
||||
|
||||
while !reader.at_end() {
|
||||
let start = reader.position();
|
||||
|
||||
// Skip file magic and version.
|
||||
reader.read_bytes(6).unwrap();
|
||||
let file_len = reader.read_u32().unwrap() as usize;
|
||||
|
||||
reader.read_bytes(file_len - 10).unwrap();
|
||||
entries.push(start..start + file_len);
|
||||
}
|
||||
|
||||
Bundle {
|
||||
data: decompressed,
|
||||
delta_table,
|
||||
count_table,
|
||||
entries,
|
||||
}
|
||||
});
|
||||
|
||||
pub(super) struct Bundle {
|
||||
data: Vec<u8>,
|
||||
pub(super) delta_table: HuffmanTable,
|
||||
pub(super) count_table: HuffmanTable,
|
||||
entries: Vec<Range<usize>>,
|
||||
}
|
||||
|
||||
/// Load the data for a cmap file, by name.
|
||||
pub fn load_embedded(name: CMapName<'_>) -> Option<&'static [u8]> {
|
||||
// Get the index of the font of the cmap in the bundle. They are sorted
|
||||
// alphabetically.
|
||||
let idx = match name {
|
||||
CMapName::N83pvRksjH => 0,
|
||||
CMapName::N90msRksjH => 1,
|
||||
CMapName::N90msRksjV => 2,
|
||||
CMapName::N90mspRksjH => 3,
|
||||
CMapName::N90mspRksjV => 4,
|
||||
CMapName::N90pvRksjH => 5,
|
||||
CMapName::AddRksjH => 6,
|
||||
CMapName::AddRksjV => 7,
|
||||
CMapName::AdobeCns1Ucs2 => 8,
|
||||
CMapName::AdobeGb1Ucs2 => 9,
|
||||
CMapName::AdobeJapan1Ucs2 => 10,
|
||||
CMapName::AdobeKorea1Ucs2 => 11,
|
||||
CMapName::B5pcH => 12,
|
||||
CMapName::B5pcV => 13,
|
||||
CMapName::CnsEucH => 14,
|
||||
CMapName::CnsEucV => 15,
|
||||
CMapName::ETenB5H => 16,
|
||||
CMapName::ETenB5V => 17,
|
||||
CMapName::ETenmsB5H => 18,
|
||||
CMapName::ETenmsB5V => 19,
|
||||
CMapName::EucH => 20,
|
||||
CMapName::EucV => 21,
|
||||
CMapName::ExtRksjH => 22,
|
||||
CMapName::ExtRksjV => 23,
|
||||
CMapName::GbEucH => 24,
|
||||
CMapName::GbEucV => 25,
|
||||
CMapName::GbkEucH => 26,
|
||||
CMapName::GbkEucV => 27,
|
||||
CMapName::Gbk2kH => 28,
|
||||
CMapName::Gbk2kV => 29,
|
||||
CMapName::GbkpEucH => 30,
|
||||
CMapName::GbkpEucV => 31,
|
||||
CMapName::GbpcEucH => 32,
|
||||
CMapName::GbpcEucV => 33,
|
||||
CMapName::H => 34,
|
||||
CMapName::HKscsB5H => 35,
|
||||
CMapName::HKscsB5V => 36,
|
||||
CMapName::IdentityH => 37,
|
||||
CMapName::IdentityV => 38,
|
||||
CMapName::KscEucH => 39,
|
||||
CMapName::KscEucV => 40,
|
||||
CMapName::KscmsUhcH => 41,
|
||||
CMapName::KscmsUhcHwH => 42,
|
||||
CMapName::KscmsUhcHwV => 43,
|
||||
CMapName::KscmsUhcV => 44,
|
||||
CMapName::KscpcEucH => 45,
|
||||
CMapName::UniCnsUcs2H => 46,
|
||||
CMapName::UniCnsUcs2V => 47,
|
||||
CMapName::UniCnsUtf16H => 48,
|
||||
CMapName::UniCnsUtf16V => 49,
|
||||
CMapName::UniGbUcs2H => 50,
|
||||
CMapName::UniGbUcs2V => 51,
|
||||
CMapName::UniGbUtf16H => 52,
|
||||
CMapName::UniGbUtf16V => 53,
|
||||
CMapName::UniJisUcs2H => 54,
|
||||
CMapName::UniJisUcs2HwH => 55,
|
||||
CMapName::UniJisUcs2HwV => 56,
|
||||
CMapName::UniJisUcs2V => 57,
|
||||
CMapName::UniJisUtf16H => 58,
|
||||
CMapName::UniJisUtf16V => 59,
|
||||
CMapName::UniKsUcs2H => 60,
|
||||
CMapName::UniKsUcs2V => 61,
|
||||
CMapName::UniKsUtf16H => 62,
|
||||
CMapName::UniKsUtf16V => 63,
|
||||
CMapName::V => 64,
|
||||
CMapName::Custom(_) => return None,
|
||||
};
|
||||
|
||||
let range = BUNDLE.entries.get(idx)?;
|
||||
|
||||
Some(&BUNDLE.data[range.clone()])
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
use alloc::vec;
|
||||
use alloc::vec::Vec;
|
||||
use core::num::NonZeroU32;
|
||||
|
||||
use super::reader::Reader;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(super) enum HuffmanNode {
|
||||
/// Intermediate node with optional children.
|
||||
Intermediate {
|
||||
/// Index of the zero-child.
|
||||
zero: Option<NonZeroU32>,
|
||||
/// Index of the one-child.
|
||||
one: Option<NonZeroU32>,
|
||||
},
|
||||
/// Leaf node holding a decoded symbol value.
|
||||
Leaf(u32),
|
||||
}
|
||||
|
||||
/// A Huffman table built from canonical codes.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct HuffmanTable {
|
||||
nodes: Vec<HuffmanNode>,
|
||||
}
|
||||
|
||||
impl HuffmanTable {
|
||||
/// Decode a single symbol from the bit reader.
|
||||
pub(super) fn decode(&self, reader: &mut Reader<'_>) -> Option<u32> {
|
||||
let mut idx = 0_u32;
|
||||
|
||||
loop {
|
||||
match self.nodes[idx as usize] {
|
||||
HuffmanNode::Intermediate { zero, one } => {
|
||||
let bit = reader.read_bit()?;
|
||||
let child = if bit == 0 { zero } else { one };
|
||||
idx = child?.get();
|
||||
}
|
||||
HuffmanNode::Leaf(symbol) => return Some(symbol),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_code(
|
||||
nodes: &mut Vec<HuffmanNode>,
|
||||
node_index: u32,
|
||||
code: u32,
|
||||
length: u8,
|
||||
symbol: u32,
|
||||
) {
|
||||
if length == 0 {
|
||||
nodes[node_index as usize] = HuffmanNode::Leaf(symbol);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
let bit = (code >> (length - 1)) & 1;
|
||||
let remaining = code & ((1 << (length - 1)) - 1);
|
||||
|
||||
let child_index = match &nodes[node_index as usize] {
|
||||
HuffmanNode::Intermediate { zero, one } => {
|
||||
let existing = if bit == 0 { *zero } else { *one };
|
||||
match existing {
|
||||
Some(idx) => idx,
|
||||
None => {
|
||||
let new_idx = NonZeroU32::new(nodes.len() as u32).unwrap();
|
||||
nodes.push(HuffmanNode::Intermediate {
|
||||
zero: None,
|
||||
one: None,
|
||||
});
|
||||
|
||||
match &mut nodes[node_index as usize] {
|
||||
HuffmanNode::Intermediate { zero, one } => {
|
||||
if bit == 0 {
|
||||
*zero = Some(new_idx);
|
||||
} else {
|
||||
*one = Some(new_idx);
|
||||
}
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
new_idx
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => return,
|
||||
};
|
||||
|
||||
Self::insert_code(nodes, child_index.get(), remaining, length - 1, symbol);
|
||||
}
|
||||
|
||||
fn build(code_lengths: &[u8], symbols: &[u32]) -> Self {
|
||||
debug_assert_eq!(code_lengths.len(), symbols.len());
|
||||
|
||||
if symbols.is_empty() {
|
||||
return Self {
|
||||
nodes: vec![HuffmanNode::Intermediate {
|
||||
zero: None,
|
||||
one: None,
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
let max_length = *code_lengths.iter().max().unwrap_or(&0) as usize;
|
||||
|
||||
let mut codes = vec![0_u32; symbols.len()];
|
||||
let mut code = 0_u32;
|
||||
|
||||
for length in 1..=max_length {
|
||||
for (i, &cl) in code_lengths.iter().enumerate() {
|
||||
if cl as usize == length {
|
||||
codes[i] = code;
|
||||
code += 1;
|
||||
}
|
||||
}
|
||||
code <<= 1;
|
||||
}
|
||||
|
||||
let mut nodes = vec![HuffmanNode::Intermediate {
|
||||
zero: None,
|
||||
one: None,
|
||||
}];
|
||||
|
||||
for (i, &symbol) in symbols.iter().enumerate() {
|
||||
if code_lengths[i] == 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
Self::insert_code(&mut nodes, 0, codes[i], code_lengths[i], symbol);
|
||||
}
|
||||
|
||||
Self { nodes }
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn decode_tables(data: &[u8]) -> Option<(HuffmanTable, HuffmanTable)> {
|
||||
let mut reader = Reader::new(data);
|
||||
let delta = decode_single_table(&mut reader, |r| r.read_u32())?;
|
||||
let count = decode_single_table(&mut reader, |r| r.read_u8().map(u32::from))?;
|
||||
|
||||
Some((delta, count))
|
||||
}
|
||||
|
||||
fn decode_single_table(
|
||||
reader: &mut Reader<'_>,
|
||||
read_sym: fn(&mut Reader<'_>) -> Option<u32>,
|
||||
) -> Option<HuffmanTable> {
|
||||
let n_symbols = reader.read_u16()? as usize;
|
||||
|
||||
if n_symbols == 0 {
|
||||
let _max_len = reader.read_u8()?;
|
||||
|
||||
return Some(HuffmanTable {
|
||||
nodes: vec![HuffmanNode::Intermediate {
|
||||
zero: None,
|
||||
one: None,
|
||||
}],
|
||||
});
|
||||
}
|
||||
|
||||
let max_code_length = reader.read_u8()? as usize;
|
||||
|
||||
let mut counts = Vec::with_capacity(max_code_length);
|
||||
for _ in 0..max_code_length {
|
||||
counts.push(reader.read_u16()?);
|
||||
}
|
||||
|
||||
let mut code_lengths = Vec::with_capacity(n_symbols);
|
||||
let mut symbols = Vec::with_capacity(n_symbols);
|
||||
|
||||
for (length_idx, &count) in counts.iter().enumerate() {
|
||||
let code_len = (length_idx + 1) as u8;
|
||||
|
||||
for _ in 0..count {
|
||||
symbols.push(read_sym(reader)?);
|
||||
code_lengths.push(code_len);
|
||||
}
|
||||
}
|
||||
|
||||
Some(HuffmanTable::build(&code_lengths, &symbols))
|
||||
}
|
||||
Vendored
+419
@@ -0,0 +1,419 @@
|
||||
//! Inspired by pdf.js, we use a custom binary format to optionally embed
|
||||
//! the required cmaps in a space-efficient manner. However, we don't use
|
||||
//! their format description but have a custom one. For more information,
|
||||
//! see <https://github.com/LaurenzV/cmap-resources/tree/hayro>.
|
||||
|
||||
pub(crate) mod embedded;
|
||||
pub(crate) mod huffman;
|
||||
pub(crate) mod reader;
|
||||
|
||||
use alloc::boxed::Box;
|
||||
use alloc::vec::Vec;
|
||||
|
||||
pub use embedded::load_embedded;
|
||||
|
||||
use crate::bcmap::embedded::BUNDLE;
|
||||
use crate::{
|
||||
BfRange, CMap, CMapName, CharacterCollection, CidFamily, CidRange, CodespaceRange, Metadata,
|
||||
PartitionedRanges, Range, WritingMode, parse,
|
||||
};
|
||||
use huffman::HuffmanTable;
|
||||
use reader::Reader;
|
||||
|
||||
const BCMAP_MAGIC: &[u8] = b"bcmap";
|
||||
const BCMAP_VERSION: u8 = 0x01;
|
||||
const BCMAP_FILE_HEADER_SIZE: usize = 10;
|
||||
const SEG_HEADER_SIZE: usize = 5;
|
||||
|
||||
const SEGMENT_RANGE_1B: u8 = 0x01;
|
||||
const SEGMENT_SINGLE_1B: u8 = 0x02;
|
||||
const SEGMENT_RANGE_2B: u8 = 0x03;
|
||||
const SEGMENT_SINGLE_2B: u8 = 0x04;
|
||||
const SEGMENT_RANGE_3B: u8 = 0x05;
|
||||
const SEGMENT_SINGLE_3B: u8 = 0x06;
|
||||
const SEGMENT_RANGE_4B: u8 = 0x07;
|
||||
const SEGMENT_SINGLE_4B: u8 = 0x08;
|
||||
const SEGMENT_USECMAP: u8 = 0x09;
|
||||
const SEGMENT_NOTDEF: u8 = 0x0A;
|
||||
const SEGMENT_WMODE: u8 = 0x0B;
|
||||
const SEGMENT_CODESPACE: u8 = 0x0C;
|
||||
const SEGMENT_NAME: u8 = 0x0D;
|
||||
const SEGMENT_CID_SYSTEM_INFO: u8 = 0x0E;
|
||||
const SEGMENT_BF_RANGE_VARIABLE: u8 = 0x0F;
|
||||
const SEGMENT_BF_SINGLE_VARIABLE: u8 = 0x10;
|
||||
const SEGMENT_BF_SINGLE_1U: u8 = 0x11;
|
||||
const SEGMENT_BF_SINGLE_2U: u8 = 0x12;
|
||||
const SEGMENT_BF_SINGLE_3U: u8 = 0x13;
|
||||
const SEGMENT_BF_SINGLE_4U: u8 = 0x14;
|
||||
const SEGMENT_BF_RANGE_1U: u8 = 0x15;
|
||||
const SEGMENT_BF_RANGE_2U: u8 = 0x16;
|
||||
|
||||
pub(crate) fn parse<'a>(
|
||||
data: &[u8],
|
||||
get_cmap: impl Fn(CMapName<'_>) -> Option<&'a [u8]> + Clone + 'a,
|
||||
depth: u32,
|
||||
) -> Option<CMap> {
|
||||
// While in theory we can assume that all binary cmaps are valid, it can
|
||||
// of course happen that an invalid one has been passed from outside, so
|
||||
// we still need to do proper validation.
|
||||
|
||||
if data.get(..5)? != BCMAP_MAGIC || *data.get(5)? != BCMAP_VERSION {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut reader = Reader::new(data);
|
||||
reader.read_bytes(6)?; // Skip magic + version.
|
||||
|
||||
let file_len = reader.read_u32()? as usize;
|
||||
|
||||
let delta_table = &BUNDLE.delta_table;
|
||||
let count_table = &BUNDLE.count_table;
|
||||
|
||||
let mut cmap_name = None;
|
||||
let mut character_collection = None;
|
||||
let mut writing_mode = None;
|
||||
let mut base: Option<Box<CMap>> = None;
|
||||
let mut _codespace_ranges = Vec::new();
|
||||
let mut cid_ranges = PartitionedRanges::new();
|
||||
let mut notdef_ranges = PartitionedRanges::new();
|
||||
let mut bf_entries = Vec::new();
|
||||
|
||||
// Start parsing all segments of the file.
|
||||
let mut reader = Reader::new(data.get(BCMAP_FILE_HEADER_SIZE..file_len)?);
|
||||
|
||||
while !reader.at_end() {
|
||||
let seg_type = reader.read_u8()?;
|
||||
let seg_len = reader.read_u32()? as usize;
|
||||
|
||||
let payload = reader.read_bytes(seg_len.checked_sub(SEG_HEADER_SIZE)?)?;
|
||||
|
||||
match seg_type {
|
||||
SEGMENT_NAME => {
|
||||
cmap_name = Some(Vec::from(payload));
|
||||
}
|
||||
SEGMENT_CID_SYSTEM_INFO => {
|
||||
// Format: Each string is 0-terminated.
|
||||
let mut r = Reader::new(payload);
|
||||
let registry = Vec::from(r.eat_until(|b| b == 0));
|
||||
r.read_u8()?;
|
||||
|
||||
let ordering = Vec::from(r.eat_until(|b| b == 0));
|
||||
r.read_u8()?;
|
||||
let supplement = r.read_u16()? as i32;
|
||||
|
||||
character_collection = Some(CharacterCollection {
|
||||
family: CidFamily::from_registry_ordering(®istry, &ordering),
|
||||
supplement,
|
||||
});
|
||||
}
|
||||
SEGMENT_USECMAP => {
|
||||
let base_data = get_cmap(CMapName::from_bytes(payload))?;
|
||||
|
||||
// PdfCraft patch: a binary `usecmap` counts against the nesting limit as a text
|
||||
// one does; passing the same depth let a self-referencing CMap recurse until the
|
||||
// stack overflowed.
|
||||
base = Some(Box::new(parse::parse_inner(
|
||||
base_data,
|
||||
get_cmap.clone(),
|
||||
depth + 1,
|
||||
)?));
|
||||
}
|
||||
SEGMENT_WMODE => {
|
||||
writing_mode = match payload.first()? {
|
||||
0 => Some(WritingMode::Horizontal),
|
||||
1 => Some(WritingMode::Vertical),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
SEGMENT_CODESPACE => {
|
||||
parse_codespace(payload, &mut _codespace_ranges)?;
|
||||
}
|
||||
SEGMENT_NOTDEF => {
|
||||
parse_notdef(payload, &mut notdef_ranges)?;
|
||||
}
|
||||
SEGMENT_RANGE_1B | SEGMENT_RANGE_2B | SEGMENT_RANGE_3B | SEGMENT_RANGE_4B => {
|
||||
let bw = seg_type.div_ceil(2) as usize;
|
||||
parse_cid_segment(payload, &mut cid_ranges, bw, delta_table, Some(count_table))?;
|
||||
}
|
||||
SEGMENT_SINGLE_1B | SEGMENT_SINGLE_2B | SEGMENT_SINGLE_3B | SEGMENT_SINGLE_4B => {
|
||||
let bw = seg_type.div_ceil(2) as usize;
|
||||
parse_cid_segment(payload, &mut cid_ranges, bw, delta_table, None)?;
|
||||
}
|
||||
SEGMENT_BF_RANGE_VARIABLE => {
|
||||
parse_bf_segment(
|
||||
payload,
|
||||
&mut bf_entries,
|
||||
delta_table,
|
||||
Some(count_table),
|
||||
None,
|
||||
)?;
|
||||
}
|
||||
SEGMENT_BF_SINGLE_VARIABLE => {
|
||||
parse_bf_segment(payload, &mut bf_entries, delta_table, None, None)?;
|
||||
}
|
||||
SEGMENT_BF_RANGE_1U => {
|
||||
parse_bf_segment(
|
||||
payload,
|
||||
&mut bf_entries,
|
||||
delta_table,
|
||||
Some(count_table),
|
||||
Some(1),
|
||||
)?;
|
||||
}
|
||||
SEGMENT_BF_RANGE_2U => {
|
||||
parse_bf_segment(
|
||||
payload,
|
||||
&mut bf_entries,
|
||||
delta_table,
|
||||
Some(count_table),
|
||||
Some(2),
|
||||
)?;
|
||||
}
|
||||
SEGMENT_BF_SINGLE_1U => {
|
||||
parse_bf_segment(payload, &mut bf_entries, delta_table, None, Some(1))?;
|
||||
}
|
||||
SEGMENT_BF_SINGLE_2U => {
|
||||
parse_bf_segment(payload, &mut bf_entries, delta_table, None, Some(2))?;
|
||||
}
|
||||
SEGMENT_BF_SINGLE_3U => {
|
||||
parse_bf_segment(payload, &mut bf_entries, delta_table, None, Some(3))?;
|
||||
}
|
||||
SEGMENT_BF_SINGLE_4U => {
|
||||
parse_bf_segment(payload, &mut bf_entries, delta_table, None, Some(4))?;
|
||||
}
|
||||
_ => {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cid_ranges.sort();
|
||||
notdef_ranges.sort();
|
||||
bf_entries.sort_by(|a, b| a.range.start.cmp(&b.range.start));
|
||||
|
||||
Some(CMap {
|
||||
metadata: Metadata {
|
||||
character_collection,
|
||||
name: cmap_name,
|
||||
writing_mode,
|
||||
},
|
||||
_codespace_ranges,
|
||||
cid_ranges,
|
||||
notdef_ranges,
|
||||
bf_entries,
|
||||
base,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_codespace(payload: &[u8], ranges: &mut Vec<CodespaceRange>) -> Option<()> {
|
||||
let mut r = Reader::new(payload);
|
||||
let n_ranges = r.read_u8()? as usize;
|
||||
|
||||
for _ in 0..n_ranges {
|
||||
let bw = r.read_u8()? as usize;
|
||||
let low = r.read_n_bytes(bw)?;
|
||||
let high = r.read_n_bytes(bw)?;
|
||||
|
||||
ranges.push(CodespaceRange {
|
||||
number_bytes: bw as u8,
|
||||
low,
|
||||
high,
|
||||
});
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn parse_notdef(payload: &[u8], ranges: &mut PartitionedRanges) -> Option<()> {
|
||||
let mut r = Reader::new(payload);
|
||||
let bw = r.read_u8()? as usize;
|
||||
let n_entries = r.read_u16()? as usize;
|
||||
|
||||
for _ in 0..n_entries {
|
||||
let start = r.read_n_bytes(bw)?;
|
||||
let end = r.read_n_bytes(bw)?;
|
||||
let cid = r.read_u16()? as u32;
|
||||
|
||||
ranges.push(
|
||||
bw,
|
||||
CidRange {
|
||||
range: Range { start, end },
|
||||
cid_start: cid,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn parse_cid_segment(
|
||||
payload: &[u8],
|
||||
ranges: &mut PartitionedRanges,
|
||||
byte_width: usize,
|
||||
delta_table: &HuffmanTable,
|
||||
count_table: Option<&HuffmanTable>,
|
||||
) -> Option<()> {
|
||||
let mut r = Reader::new(payload);
|
||||
let n_entries = r.read_u16()? as usize;
|
||||
|
||||
if n_entries == 0 {
|
||||
return Some(());
|
||||
}
|
||||
|
||||
// There are two types of CID segments, all of which are stored in a columnar
|
||||
// fastion in the file:
|
||||
// For the first type, we have a simple mapping from a single code to a single
|
||||
// CID. In this case, the data stream first contains all codes using delta-coding,
|
||||
// encoded using huffman coding. This is followed by all CIDs, stored as
|
||||
// u16 (either as a raw CID, or as `0` in case the CID is +1 the previous CID).
|
||||
//
|
||||
// For the second type, we have a range of consecutive codes, which map
|
||||
// to a range of consecutive CIDs. In this case, we have an additional "count"
|
||||
// column that stores how many codes are mapped consecutively. These are also
|
||||
// encoded using huffman coding.
|
||||
|
||||
// Read deltas for the start code points.
|
||||
let delta_len = r.read_u32()? as usize;
|
||||
let delta_data = r.read_bytes(delta_len)?;
|
||||
|
||||
let mut delta_reader = Reader::new(delta_data);
|
||||
let mut deltas = Vec::with_capacity(n_entries);
|
||||
|
||||
for _ in 0..n_entries {
|
||||
deltas.push(delta_table.decode(&mut delta_reader)?);
|
||||
}
|
||||
|
||||
// Read the counts for each consecutive code range.
|
||||
let mut counts = Vec::new();
|
||||
if let Some(ct) = count_table {
|
||||
let count_len = r.read_u32()? as usize;
|
||||
let count_data = r.read_bytes(count_len)?;
|
||||
|
||||
let mut count_reader = Reader::new(count_data);
|
||||
counts.reserve(n_entries);
|
||||
for _ in 0..n_entries {
|
||||
counts.push(ct.decode(&mut count_reader)?);
|
||||
}
|
||||
}
|
||||
|
||||
// Read the CIDs and reconstruct the character codes that map to them.
|
||||
let is_range = count_table.is_some();
|
||||
let mut prev_end: Option<u32> = None;
|
||||
let mut prev_cid: Option<u32> = None;
|
||||
let mut prev_range_len: u32 = 0;
|
||||
|
||||
for i in 0..n_entries {
|
||||
let raw_cid = r.read_u16()?;
|
||||
|
||||
// Note that start deltas and counts are encoded minus one, so we
|
||||
// need to add one when reconstructing them.
|
||||
|
||||
// Reconstruct start code.
|
||||
let start = if let Some(pe) = prev_end {
|
||||
pe + 1 + deltas[i]
|
||||
} else {
|
||||
deltas[i]
|
||||
};
|
||||
|
||||
// Reconstruct end code.
|
||||
let end = if is_range {
|
||||
start + counts[i] + 1
|
||||
} else {
|
||||
start
|
||||
};
|
||||
|
||||
// CID 0 means it's consecutive to the last seen CID, plus 1.
|
||||
let cid = if raw_cid == 0 {
|
||||
if let Some(pc) = prev_cid {
|
||||
pc + prev_range_len + 1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
} else {
|
||||
raw_cid as u32
|
||||
};
|
||||
|
||||
ranges.push(
|
||||
byte_width,
|
||||
CidRange {
|
||||
range: Range { start, end },
|
||||
cid_start: cid,
|
||||
},
|
||||
);
|
||||
|
||||
prev_end = Some(end);
|
||||
prev_cid = Some(cid);
|
||||
prev_range_len = end - start;
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn parse_bf_segment(
|
||||
payload: &[u8],
|
||||
entries: &mut Vec<BfRange>,
|
||||
delta_table: &HuffmanTable,
|
||||
count_table: Option<&HuffmanTable>,
|
||||
fixed_units: Option<usize>,
|
||||
) -> Option<()> {
|
||||
let mut r = Reader::new(payload);
|
||||
let n_entries = r.read_u16()? as usize;
|
||||
|
||||
let delta_len = r.read_u32()? as usize;
|
||||
let delta_data = r.read_bytes(delta_len)?;
|
||||
|
||||
let mut delta_reader = Reader::new(delta_data);
|
||||
let mut deltas = Vec::with_capacity(n_entries);
|
||||
for _ in 0..n_entries {
|
||||
deltas.push(delta_table.decode(&mut delta_reader)?);
|
||||
}
|
||||
|
||||
// Read counts for range segments.
|
||||
let mut counts = Vec::new();
|
||||
if let Some(ct) = count_table {
|
||||
let count_len = r.read_u32()? as usize;
|
||||
let count_data = r.read_bytes(count_len)?;
|
||||
|
||||
let mut count_reader = Reader::new(count_data);
|
||||
counts.reserve(n_entries);
|
||||
for _ in 0..n_entries {
|
||||
counts.push(ct.decode(&mut count_reader)?);
|
||||
}
|
||||
}
|
||||
|
||||
let is_range = count_table.is_some();
|
||||
let mut prev_end: Option<u32> = None;
|
||||
|
||||
for i in 0..n_entries {
|
||||
// Fixed-width segments encode destinations without a length prefix.
|
||||
let n_units = match fixed_units {
|
||||
Some(nu) => nu,
|
||||
None => r.read_u8()? as usize,
|
||||
};
|
||||
let mut dst_base = Vec::with_capacity(n_units);
|
||||
for _ in 0..n_units {
|
||||
dst_base.push(r.read_u16()?);
|
||||
}
|
||||
|
||||
let start = if let Some(pe) = prev_end {
|
||||
pe + 1 + deltas[i]
|
||||
} else {
|
||||
deltas[i]
|
||||
};
|
||||
|
||||
let end = if is_range {
|
||||
start + counts[i] + 1
|
||||
} else {
|
||||
start
|
||||
};
|
||||
|
||||
entries.push(BfRange {
|
||||
range: Range { start, end },
|
||||
dst_base,
|
||||
});
|
||||
|
||||
prev_end = Some(end);
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
pub(super) struct Reader<'a> {
|
||||
data: &'a [u8],
|
||||
byte_pos: usize,
|
||||
bit_pos: u8,
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
#[inline]
|
||||
pub(super) fn new(data: &'a [u8]) -> Self {
|
||||
Self {
|
||||
data,
|
||||
byte_pos: 0,
|
||||
bit_pos: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn read_bit(&mut self) -> Option<u8> {
|
||||
let byte = *self.data.get(self.byte_pos)?;
|
||||
let bit = (byte >> (7 - self.bit_pos)) & 1;
|
||||
|
||||
self.bit_pos += 1;
|
||||
|
||||
if self.bit_pos == 8 {
|
||||
self.bit_pos = 0;
|
||||
self.byte_pos += 1;
|
||||
}
|
||||
|
||||
Some(bit)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn read_u16(&mut self) -> Option<u16> {
|
||||
debug_assert_eq!(self.bit_pos, 0, "read_u16 called at non-byte boundary");
|
||||
|
||||
let bytes: [u8; 2] = self
|
||||
.data
|
||||
.get(self.byte_pos..self.byte_pos + 2)?
|
||||
.try_into()
|
||||
.ok()?;
|
||||
self.byte_pos += 2;
|
||||
|
||||
Some(u16::from_be_bytes(bytes))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn read_u32(&mut self) -> Option<u32> {
|
||||
debug_assert_eq!(self.bit_pos, 0, "read_u32 called at non-byte boundary");
|
||||
|
||||
let bytes: [u8; 4] = self
|
||||
.data
|
||||
.get(self.byte_pos..self.byte_pos + 4)?
|
||||
.try_into()
|
||||
.ok()?;
|
||||
self.byte_pos += 4;
|
||||
|
||||
Some(u32::from_be_bytes(bytes))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn read_u8(&mut self) -> Option<u8> {
|
||||
debug_assert_eq!(self.bit_pos, 0, "read_u8 called at non-byte boundary");
|
||||
|
||||
let val = *self.data.get(self.byte_pos)?;
|
||||
self.byte_pos += 1;
|
||||
|
||||
Some(val)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn read_n_bytes(&mut self, n: usize) -> Option<u32> {
|
||||
debug_assert_eq!(
|
||||
self.bit_pos, 0,
|
||||
"read_n_bytes_be called at non-byte boundary"
|
||||
);
|
||||
|
||||
match n {
|
||||
1 => Some(self.read_u8()? as u32),
|
||||
2 => Some(self.read_u16()? as u32),
|
||||
3 => {
|
||||
let bytes = self.read_bytes(3)?;
|
||||
Some((bytes[0] as u32) << 16 | (bytes[1] as u32) << 8 | bytes[2] as u32)
|
||||
}
|
||||
4 => self.read_u32(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn read_bytes(&mut self, n: usize) -> Option<&'a [u8]> {
|
||||
debug_assert_eq!(self.bit_pos, 0, "read_bytes called at non-byte boundary");
|
||||
|
||||
let bytes = self.data.get(self.byte_pos..self.byte_pos + n)?;
|
||||
self.byte_pos += n;
|
||||
|
||||
Some(bytes)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn position(&self) -> usize {
|
||||
self.byte_pos
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn at_end(&self) -> bool {
|
||||
self.byte_pos >= self.data.len()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn eat_until(&mut self, f: impl Fn(u8) -> bool) -> &'a [u8] {
|
||||
debug_assert_eq!(self.bit_pos, 0, "eat_until called at non-byte boundary");
|
||||
|
||||
let start = self.byte_pos;
|
||||
while let Some(&b) = self.data.get(self.byte_pos) {
|
||||
if f(b) {
|
||||
break;
|
||||
}
|
||||
self.byte_pos += 1;
|
||||
}
|
||||
|
||||
&self.data[start..self.byte_pos]
|
||||
}
|
||||
}
|
||||
Vendored
+1710
File diff suppressed because it is too large
Load Diff
Vendored
+469
@@ -0,0 +1,469 @@
|
||||
use alloc::boxed::Box;
|
||||
use alloc::vec::Vec;
|
||||
|
||||
use hayro_postscript::{Object, Scanner};
|
||||
|
||||
#[cfg(feature = "embed-cmaps")]
|
||||
use crate::bcmap;
|
||||
use crate::{
|
||||
BfRange, CMap, CMapName, CharacterCollection, CidFamily, CidRange, CodespaceRange,
|
||||
MAX_NESTING_DEPTH, Metadata, PartitionedRanges, Range, WritingMode,
|
||||
};
|
||||
|
||||
struct Context<F> {
|
||||
buf: Vec<u8>,
|
||||
get_cmap: F,
|
||||
}
|
||||
|
||||
pub(crate) fn parse_inner<'a>(
|
||||
data: &[u8],
|
||||
get_cmap: impl Fn(CMapName<'_>) -> Option<&'a [u8]> + Clone + 'a,
|
||||
depth: u32,
|
||||
) -> Option<CMap> {
|
||||
// Prevent stack overflow for malicious cmap files or circular references.
|
||||
if depth >= MAX_NESTING_DEPTH {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Check if it's in our custom embedded cmap format.
|
||||
#[cfg(feature = "embed-cmaps")]
|
||||
if data.starts_with(b"bcmap") {
|
||||
return bcmap::parse(data, get_cmap, depth);
|
||||
}
|
||||
|
||||
let mut scanner = Scanner::new(data);
|
||||
let mut ctx = Context {
|
||||
buf: Vec::new(),
|
||||
get_cmap,
|
||||
};
|
||||
let mut _codespace_ranges = Vec::new();
|
||||
let mut ranges = PartitionedRanges::new();
|
||||
let mut notdef_ranges = PartitionedRanges::new();
|
||||
let mut bf_entries = Vec::new();
|
||||
let mut base = None;
|
||||
|
||||
let mut registry = None;
|
||||
let mut ordering = None;
|
||||
let mut supplement = None;
|
||||
let mut cmap_name = None;
|
||||
let mut writing_mode = None;
|
||||
let mut last_name: Option<Vec<u8>> = None;
|
||||
|
||||
// PdfCraft patch: track whether the scan was cut short. A CMap with an
|
||||
// unparseable tail, including one that ends inside a `begin…` block,
|
||||
// keeps the entries read so far (the block parsers push into the shared
|
||||
// lists as they go) instead of being discarded wholesale; one that
|
||||
// yielded nothing still reports failure.
|
||||
let mut truncated = false;
|
||||
|
||||
// PdfCraft patch: track a `usecmap` reference that could not be resolved
|
||||
// or parsed. When the stream yields no mappings of its own, the caller
|
||||
// must see failure rather than an empty map, so its encoding fallback
|
||||
// paths run exactly as they did before the tolerant-usecmap change.
|
||||
let mut usecmap_failed = false;
|
||||
while !scanner.at_end() {
|
||||
let Ok(obj) = scanner.parse_object() else {
|
||||
truncated = true;
|
||||
break;
|
||||
};
|
||||
|
||||
let Object::Name(name) = &obj else { continue };
|
||||
|
||||
if name.is_literal() {
|
||||
match name.as_str() {
|
||||
// Strictly speaking, Registry and Ordering should be strings,
|
||||
// but some PDF generators emit names instead, so be lenient
|
||||
// and try both.
|
||||
Some("Registry") => {
|
||||
registry = parse_string_or_name(&mut scanner);
|
||||
}
|
||||
Some("Ordering") => {
|
||||
ordering = parse_string_or_name(&mut scanner);
|
||||
}
|
||||
Some("Supplement") => {
|
||||
supplement = scanner.parse_number().ok().map(|n| n.as_i32());
|
||||
}
|
||||
Some("CMapName") => {
|
||||
cmap_name = scanner.parse_name().ok().and_then(|n| n.decode().ok());
|
||||
}
|
||||
Some("WMode") => {
|
||||
writing_mode = parse_writing_mode(&mut scanner);
|
||||
}
|
||||
_ => {
|
||||
last_name = name.decode().ok();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match name.as_str() {
|
||||
Some("begincodespacerange") => {
|
||||
if parse_codespace_range(&mut scanner, &mut _codespace_ranges, &mut ctx).is_none() {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some("begincidrange") => {
|
||||
if parse_range(&mut scanner, &mut ranges, &mut ctx, "endcidrange").is_none() {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some("begincidchar") => {
|
||||
if parse_char(&mut scanner, &mut ranges, &mut ctx, "endcidchar").is_none() {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some("beginnotdefrange") => {
|
||||
if parse_range(&mut scanner, &mut notdef_ranges, &mut ctx, "endnotdefrange").is_none() {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some("beginnotdefchar") => {
|
||||
if parse_char(&mut scanner, &mut notdef_ranges, &mut ctx, "endnotdefchar").is_none() {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some("beginbfchar") => {
|
||||
if parse_bf_char(&mut scanner, &mut bf_entries, &mut ctx).is_none() {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some("beginbfrange") => {
|
||||
if parse_bf_range(&mut scanner, &mut bf_entries, &mut ctx).is_none() {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some("usecmap") => {
|
||||
// PdfCraft patch: an unresolvable or unparseable `usecmap`
|
||||
// reference drops only the base, not the whole CMap, but
|
||||
// is remembered so a stream that then yields no mappings
|
||||
// at all still reports failure.
|
||||
let resolved = last_name.as_deref().and_then(|name| {
|
||||
(ctx.get_cmap)(CMapName::from_bytes(name))
|
||||
});
|
||||
match resolved {
|
||||
Some(nested_data) => {
|
||||
match parse_inner(nested_data, ctx.get_cmap.clone(), depth + 1) {
|
||||
Some(nested) => base = Some(Box::new(nested)),
|
||||
None => usecmap_failed = true,
|
||||
}
|
||||
}
|
||||
None => usecmap_failed = true,
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Since we will use binary search for finding the correct entry, sort now.
|
||||
ranges.sort();
|
||||
notdef_ranges.sort();
|
||||
bf_entries.sort_by(|a, b| a.range.start.cmp(&b.range.start));
|
||||
|
||||
// See PDFJS-3323, which has an invalid CIDSystemInfo entry.
|
||||
// We ignore it if it's invalid.
|
||||
let character_collection = if let (Some(registry), Some(ordering), Some(supplement)) =
|
||||
(registry, ordering, supplement)
|
||||
{
|
||||
Some(CharacterCollection {
|
||||
family: CidFamily::from_registry_ordering(®istry, &ordering),
|
||||
supplement,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let metadata = Metadata {
|
||||
character_collection,
|
||||
name: cmap_name,
|
||||
writing_mode,
|
||||
};
|
||||
|
||||
// PdfCraft patch: a CMap that was cut short or whose `usecmap` base could
|
||||
// not be resolved, and that yielded no mappings of its own, still reports
|
||||
// failure, so callers fall back to the font's own encoding exactly as
|
||||
// before.
|
||||
if (truncated || usecmap_failed)
|
||||
&& ranges.is_empty()
|
||||
&& notdef_ranges.is_empty()
|
||||
&& bf_entries.is_empty()
|
||||
&& base.is_none()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(CMap {
|
||||
metadata,
|
||||
_codespace_ranges,
|
||||
cid_ranges: ranges,
|
||||
notdef_ranges,
|
||||
bf_entries,
|
||||
base,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_writing_mode(scanner: &mut Scanner<'_>) -> Option<WritingMode> {
|
||||
match scanner.parse_number().ok()?.as_i32() {
|
||||
0 => Some(WritingMode::Horizontal),
|
||||
1 => Some(WritingMode::Vertical),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_string_or_name(scanner: &mut Scanner<'_>) -> Option<Vec<u8>> {
|
||||
match scanner.parse_object().ok()? {
|
||||
Object::String(s) => s.decode().ok(),
|
||||
Object::Name(n) => n.decode().ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_codespace_range<F>(
|
||||
scanner: &mut Scanner<'_>,
|
||||
ranges: &mut Vec<CodespaceRange>,
|
||||
ctx: &mut Context<F>,
|
||||
) -> Option<()> {
|
||||
loop {
|
||||
let obj = scanner.parse_object().ok()?;
|
||||
|
||||
if name_matches(&obj, "endcodespacerange") {
|
||||
return Some(());
|
||||
}
|
||||
|
||||
// PdfCraft patch: a malformed codespace entry is skipped, not fatal.
|
||||
let Some(low) = extract_u32_code(&obj, &mut ctx.buf) else { continue };
|
||||
let Ok(n_bytes) = u8::try_from(ctx.buf.len()) else { continue };
|
||||
let Some(high) = read_u32_code(scanner, &mut ctx.buf) else { continue };
|
||||
|
||||
if ctx.buf.len() != usize::from(n_bytes) {
|
||||
continue;
|
||||
}
|
||||
|
||||
ranges.push(CodespaceRange {
|
||||
number_bytes: n_bytes,
|
||||
low,
|
||||
high,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_range<F>(
|
||||
scanner: &mut Scanner<'_>,
|
||||
ranges: &mut PartitionedRanges,
|
||||
ctx: &mut Context<F>,
|
||||
end_marker: &str,
|
||||
) -> Option<()> {
|
||||
loop {
|
||||
let obj = scanner.parse_object().ok()?;
|
||||
|
||||
if name_matches(&obj, end_marker) {
|
||||
return Some(());
|
||||
}
|
||||
|
||||
// PdfCraft patch: a malformed range entry is skipped, not fatal.
|
||||
let Some(start) = extract_u32_code(&obj, &mut ctx.buf) else { continue };
|
||||
let byte_len = ctx.buf.len();
|
||||
let Some(end) = read_u32_code(scanner, &mut ctx.buf) else { continue };
|
||||
let Some(cid_start) = scanner.parse_number().ok().and_then(|n| u32::try_from(n.as_i32()).ok()) else { continue };
|
||||
|
||||
ranges.push(
|
||||
byte_len,
|
||||
CidRange {
|
||||
range: Range { start, end },
|
||||
cid_start,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_char<F>(
|
||||
scanner: &mut Scanner<'_>,
|
||||
ranges: &mut PartitionedRanges,
|
||||
ctx: &mut Context<F>,
|
||||
end_marker: &str,
|
||||
) -> Option<()> {
|
||||
loop {
|
||||
let obj = scanner.parse_object().ok()?;
|
||||
|
||||
if name_matches(&obj, end_marker) {
|
||||
return Some(());
|
||||
}
|
||||
|
||||
// PdfCraft patch: a malformed char entry is skipped, not fatal.
|
||||
let Some(code) = extract_u32_code(&obj, &mut ctx.buf) else { continue };
|
||||
let byte_len = ctx.buf.len();
|
||||
let Some(cid_start) = scanner.parse_number().ok().and_then(|n| u32::try_from(n.as_i32()).ok()) else { continue };
|
||||
|
||||
ranges.push(
|
||||
byte_len,
|
||||
CidRange {
|
||||
range: Range {
|
||||
start: code,
|
||||
end: code,
|
||||
},
|
||||
cid_start,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_bf_char<F>(
|
||||
scanner: &mut Scanner<'_>,
|
||||
entries: &mut Vec<BfRange>,
|
||||
ctx: &mut Context<F>,
|
||||
) -> Option<()> {
|
||||
loop {
|
||||
let obj = scanner.parse_object().ok()?;
|
||||
|
||||
if name_matches(&obj, "endbfchar") {
|
||||
return Some(());
|
||||
}
|
||||
|
||||
// PdfCraft patch: a malformed bfchar entry (e.g. a non-hex destination)
|
||||
// is skipped, not fatal - the entries after it still apply.
|
||||
let Some(code) = extract_u32_code(&obj, &mut ctx.buf) else {
|
||||
// The malformed code is still followed by its destination
|
||||
// object; skip it so later entries stay aligned.
|
||||
let _ = scanner.parse_object();
|
||||
continue;
|
||||
};
|
||||
let Ok(dst) = scanner.parse_string() else { continue };
|
||||
if dst.decode_into(&mut ctx.buf).is_err() { continue }
|
||||
let Some(dst_base) = decode_be(&ctx.buf) else { continue };
|
||||
|
||||
entries.push(BfRange {
|
||||
range: Range {
|
||||
start: code,
|
||||
end: code,
|
||||
},
|
||||
dst_base,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_bf_range<F>(
|
||||
scanner: &mut Scanner<'_>,
|
||||
entries: &mut Vec<BfRange>,
|
||||
ctx: &mut Context<F>,
|
||||
) -> Option<()> {
|
||||
loop {
|
||||
let obj = scanner.parse_object().ok()?;
|
||||
|
||||
if name_matches(&obj, "endbfrange") {
|
||||
return Some(());
|
||||
}
|
||||
|
||||
// PdfCraft patch: a malformed bfrange entry is skipped, not fatal.
|
||||
let Some(start) = extract_u32_code(&obj, &mut ctx.buf) else {
|
||||
// Skip the range's end and destination objects too, so later
|
||||
// entries stay aligned.
|
||||
let _ = scanner.parse_object();
|
||||
let _ = scanner.parse_object();
|
||||
continue;
|
||||
};
|
||||
let Some(end) = read_u32_code(scanner, &mut ctx.buf) else {
|
||||
// Skip the destination object as well to stay aligned.
|
||||
let _ = scanner.parse_object();
|
||||
continue;
|
||||
};
|
||||
|
||||
let Ok(next) = scanner.parse_object() else { continue };
|
||||
|
||||
match &next {
|
||||
Object::String(s) => {
|
||||
if s.decode_into(&mut ctx.buf).is_err() { continue }
|
||||
let Some(dst_base) = decode_be(&ctx.buf) else { continue };
|
||||
|
||||
entries.push(BfRange {
|
||||
range: Range { start, end },
|
||||
dst_base,
|
||||
});
|
||||
}
|
||||
Object::Array(array) => {
|
||||
let mut array_scanner = array.objects();
|
||||
|
||||
for code in start..=end {
|
||||
// An exhausted or broken array cannot be resynced to a
|
||||
// member boundary; stop instead of spinning over the
|
||||
// remaining codes. A decodable-but-bad member still
|
||||
// drops only itself.
|
||||
let Ok(s) = array_scanner.parse_string() else { break };
|
||||
if s.decode_into(&mut ctx.buf).is_err() { continue }
|
||||
let Some(dst_base) = decode_be(&ctx.buf) else { continue };
|
||||
|
||||
entries.push(BfRange {
|
||||
range: Range {
|
||||
start: code,
|
||||
end: code,
|
||||
},
|
||||
dst_base,
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert the buffer into native-endian u16, so that we can use `String::from_utf16`.
|
||||
fn decode_be(bytes: &[u8]) -> Option<Vec<u16>> {
|
||||
if bytes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut out = Vec::with_capacity(bytes.len().div_ceil(2));
|
||||
let mut i = 0;
|
||||
|
||||
// My understanding is that the bf strings should always be UTF16-BE encoded,
|
||||
// but it seems like some PDFs only have a single byte there? I guess we just
|
||||
// pad them? Wasn't able to find anything specific in the specifications.
|
||||
if !bytes.len().is_multiple_of(2) {
|
||||
out.push(u16::from(bytes[0]));
|
||||
i = 1;
|
||||
}
|
||||
|
||||
while i < bytes.len() {
|
||||
out.push(u16::from_be_bytes([bytes[i], bytes[i + 1]]));
|
||||
i += 2;
|
||||
}
|
||||
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_u32_code(scanner: &mut Scanner<'_>, buf: &mut Vec<u8>) -> Option<u32> {
|
||||
let s = scanner.parse_string().ok()?;
|
||||
s.decode_into(buf).ok()?;
|
||||
bytes_to_u32(buf)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn extract_u32_code(obj: &Object<'_>, buf: &mut Vec<u8>) -> Option<u32> {
|
||||
let Object::String(s) = obj else { return None };
|
||||
s.decode_into(buf).ok()?;
|
||||
bytes_to_u32(buf)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn bytes_to_u32(bytes: &[u8]) -> Option<u32> {
|
||||
if bytes.is_empty() || bytes.len() > 4 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut val = 0_u32;
|
||||
for &b in bytes {
|
||||
val = (val << 8) | b as u32;
|
||||
}
|
||||
|
||||
Some(val)
|
||||
}
|
||||
|
||||
fn name_matches(obj: &Object<'_>, expected: &str) -> bool {
|
||||
matches!(obj, Object::Name(name) if !name.is_literal() && name.as_str() == Some(expected))
|
||||
}
|
||||
Vendored
+1
-1
@@ -218,7 +218,7 @@
|
||||
"path": "src/font/cid.rs",
|
||||
"source_sha256": "c1dbe7fe5b7f7092d97b84063008df54aebf87db4ba1fdb3a179fab9fe6674b8",
|
||||
"source_git_blob": "b99dcbc116ca1169df3a229eafd05ee5b9204626",
|
||||
"sha256": "c1dbe7fe5b7f7092d97b84063008df54aebf87db4ba1fdb3a179fab9fe6674b8"
|
||||
"sha256": "df194fbcaf7811ad1833038b97bcfed51bd11593d1a4ed96125cb2035630c000"
|
||||
},
|
||||
{
|
||||
"path": "src/font/generated/glyph_names.rs",
|
||||
|
||||
+25
@@ -592,6 +592,12 @@ fn read_widths2(arr: &Array<'_>) -> Option<HashMap<u32, [f32; 3]>> {
|
||||
let mut iter = range.iter::<f32>();
|
||||
|
||||
while let Some(w) = iter.next() {
|
||||
// PdfCraft patch: as in `read_widths`, checked before the run's metrics are
|
||||
// read. Without it, a run starting at 4294967295 overflowed `first` and
|
||||
// discarded the whole /W2 table.
|
||||
if first > MAX_CID {
|
||||
break;
|
||||
}
|
||||
let v1 = iter.next()?;
|
||||
let v2 = iter.next()?;
|
||||
map.insert(first, [w, v1, v2]);
|
||||
@@ -643,3 +649,22 @@ fn read_encoding(object: &Object<'_>, cmap_resolver: &CMapResolverFn) -> Option<
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::read_widths2;
|
||||
use hayro_syntax::object::{Array, FromBytes};
|
||||
|
||||
#[test]
|
||||
fn w2_run_past_the_largest_cid_keeps_the_rest_of_the_table() {
|
||||
let arr =
|
||||
Array::from_bytes(b"[4294967295 [1000 500] 10 [900 450 860] 20 30 800 400 870]")
|
||||
.unwrap();
|
||||
let map = read_widths2(&arr).unwrap();
|
||||
|
||||
assert_eq!(map.get(&4_294_967_295), None);
|
||||
assert_eq!(map.get(&10), Some(&[900.0, 450.0, 860.0]));
|
||||
assert_eq!(map.get(&25), Some(&[800.0, 400.0, 870.0]));
|
||||
assert_eq!(map.len(), 12);
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+1
-1
@@ -338,7 +338,7 @@
|
||||
"path": "src/xref.rs",
|
||||
"source_sha256": "51ffeeb7d4ac035bae2cd5ba9288c180088ae06cdcefe2b29dfeda560a793aa0",
|
||||
"source_git_blob": "20e33a410489d42e438a3f2b87d70c7bb8d66eae",
|
||||
"sha256": "411ce7e3c0d385b1735f945b92dba164825456ef3b70ef464279ba0bac0879d4"
|
||||
"sha256": "fa8d24280df15ffe5628057fdcfa2a3d2a9f42539b6f9096b2feb836ac54ac30"
|
||||
},
|
||||
{
|
||||
"path": "src/decode_limits_tests.rs",
|
||||
|
||||
Vendored
+12
-3
@@ -984,7 +984,9 @@ fn xref_stream_subsection<'a>(
|
||||
bytes.iter().fold(0u64, |acc, b| (acc << 8) | *b as u64)
|
||||
};
|
||||
|
||||
let obj_number = start + i;
|
||||
// PdfCraft patch: object numbers are stored as `i32`; a subsection running past
|
||||
// `i32::MAX` is refused instead of overflowing or turning negative.
|
||||
let obj_number = i32::try_from(start.checked_add(i)?).ok()?;
|
||||
|
||||
match f_type {
|
||||
// We don't care about free objects.
|
||||
@@ -1007,7 +1009,7 @@ fn xref_stream_subsection<'a>(
|
||||
};
|
||||
|
||||
insert_map.insert(
|
||||
ObjectIdentifier::new(obj_number as i32, gen_number as i32),
|
||||
ObjectIdentifier::new(obj_number, gen_number as i32),
|
||||
EntryType::Normal(offset as usize),
|
||||
);
|
||||
}
|
||||
@@ -1025,7 +1027,7 @@ fn xref_stream_subsection<'a>(
|
||||
};
|
||||
|
||||
insert_map.insert(
|
||||
ObjectIdentifier::new(obj_number as i32, gen_number),
|
||||
ObjectIdentifier::new(obj_number, gen_number),
|
||||
EntryType::ObjStream(obj_stream_number, index),
|
||||
);
|
||||
}
|
||||
@@ -1177,6 +1179,13 @@ mod tests {
|
||||
let mut whole = Reader::new(&data[..6]);
|
||||
assert!(xref_stream_subsection(&mut whole, 0, 2, 1, 1, 1, &mut map).is_some());
|
||||
assert_eq!(map.len(), 2);
|
||||
// A subsection running past object number i32::MAX is refused.
|
||||
for start in [i32::MAX as u32, u32::MAX] {
|
||||
let mut past_end = XrefMap::default();
|
||||
let mut wrap = Reader::new(&data[..6]);
|
||||
assert!(xref_stream_subsection(&mut wrap, start, 2, 1, 1, 1, &mut past_end).is_none());
|
||||
assert!(past_end.keys().all(|id| id.obj_number >= 0));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user