Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

M2.6: vendor hayro-syntax 0.7.2 with a page-tree cycle guard (stack overflow on /Kids loops in object streams)

Brandon Thomas2849ad8922db
diff --git a/Cargo.lock b/Cargo.lock
index 402374765..48cc65844 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1756,8 +1756,6 @@ checksum = "885c5ef0654933139a9b9546fc2c69e18d37f38aa2520f079092b1be18f1fcaa"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0edeafd70aa2db743de8ede8637d07ec87db05efe69cde371d03f1b185fcef27"
dependencies = [
"flate2",
"hayro-ccitt",
diff --git a/Cargo.toml b/Cargo.toml
index 147a11903..6d041d806 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -68,3 +68,4 @@ codegen-units = 1
[patch.crates-io]
hayro-interpret = { path = "vendor/hayro-interpret" }
hayro = { path = "vendor/hayro" }
+hayro-syntax = { path = "vendor/hayro-syntax" }
diff --git a/vendor/README.md b/vendor/README.md
index 6362e5351..b3fc2461d 100644
--- a/vendor/README.md
+++ b/vendor/README.md
@@ -10,5 +10,6 @@ the fix. Vendoring copyleft code is never allowed (plan/adr/0001).
| hayro-interpret | 0.7.0 | Apache-2.0 OR MIT | (1) select `/AP /N` appearance states via `/AS` (checkboxes, radios, stateful icons) and honour the NoView flag; (2) Type3 Unicode fallback to `/Encoding` glyph names, then printable ASCII; (3) `Type3Glyph::advance_width`; (4) `InterpreterSettings::ocg_overrides` for viewer layer toggles; (5) soft masks whose group lacks `/CS` were dropped (Chrome gradient text) | (1) `raster::tests::widget_appearance_states`; (2, 3) `xtask text-oracle` on corpus/pdfjs issue918; (4) `raster::tests::layer_override_hides_content`; (5) `raster::tests::soft_mask_without_group_colour_space_is_applied` |
| hayro | 0.7.1 | Apache-2.0 OR MIT | `RenderSettings::{x_offset, y_offset}` to render one tile of a large page | `raster::tests::tiles_match_full_render` |
+| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process | `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers` |
Temporary: hayro is the bootstrap renderer (ADR-0004); M2.6 replaces it with our own devices.
diff --git a/vendor/hayro-syntax/Cargo.lock b/vendor/hayro-syntax/Cargo.lock
new file mode 100644
index 000000000..ebc07dfff
--- /dev/null
+++ b/vendor/hayro-syntax/Cargo.lock
@@ -0,0 +1,272 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "adler2"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+
+[[package]]
+name = "aes"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
+dependencies = [
+ "cfg-if",
+ "cipher",
+ "cpufeatures",
+]
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "block-padding"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "cbc"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"
+dependencies = [
+ "cipher",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "cipher"
+version = "0.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
+dependencies = [
+ "crypto-common",
+ "inout",
+]
+
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crc32fast"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+]
+
+[[package]]
+name = "fearless_simd"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76258897e51fd156ee03b6246ea53f3e0eb395d0b327e9961c4fc4c8b2fa151a"
+
+[[package]]
+name = "flate2"
+version = "1.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
+dependencies = [
+ "crc32fast",
+ "miniz_oxide",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
+name = "hayro-ccitt"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
+
+[[package]]
+name = "hayro-jbig2"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69374b3668dd45aeb3d3145cda68f2c7b4f223aaa2511e67d076f1c7d741388d"
+dependencies = [
+ "fearless_simd",
+ "hayro-ccitt",
+]
+
+[[package]]
+name = "hayro-jpeg2000"
+version = "0.3.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1"
+dependencies = [
+ "fearless_simd",
+ "log",
+]
+
+[[package]]
+name = "hayro-syntax"
+version = "0.7.2"
+dependencies = [
+ "aes",
+ "cbc",
+ "flate2",
+ "hayro-ccitt",
+ "hayro-jbig2",
+ "hayro-jpeg2000",
+ "log",
+ "md5",
+ "memchr",
+ "rustc-hash",
+ "sha2",
+ "smallvec",
+ "zune-jpeg",
+]
+
+[[package]]
+name = "inout"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
+dependencies = [
+ "block-padding",
+ "generic-array",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.184"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "48f5d2a454e16a5ea0f4ced81bd44e4cfc7bd3a507b61887c99fd3538b28e4af"
+
+[[package]]
+name = "log"
+version = "0.4.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
+
+[[package]]
+name = "md5"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae960838283323069879657ca3de837e9f7bbb4c7bf6ea7f1b290d5e9476d2e0"
+
+[[package]]
+name = "memchr"
+version = "2.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
+
+[[package]]
+name = "miniz_oxide"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "rustc-hash"
+version = "2.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe"
+
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
+name = "simd-adler32"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"
+
+[[package]]
+name = "smallvec"
+version = "1.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
+
+[[package]]
+name = "typenum"
+version = "1.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "zune-core"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb8a0807f7c01457d0379ba880ba6322660448ddebc890ce29bb64da71fb40f9"
+
+[[package]]
+name = "zune-jpeg"
+version = "0.5.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
+dependencies = [
+ "zune-core",
+]
diff --git a/vendor/hayro-syntax/Cargo.toml b/vendor/hayro-syntax/Cargo.toml
new file mode 100644
index 000000000..38b683f51
--- /dev/null
+++ b/vendor/hayro-syntax/Cargo.toml
@@ -0,0 +1,155 @@
+# 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"
+rust-version = "1.92"
+name = "hayro-syntax"
+version = "0.7.2"
+authors = ["Laurenz Stampfl <[email protected]>"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
+description = "A low-level crate for reading PDF files."
+readme = "README.md"
+license = "Apache-2.0 OR MIT"
+repository = "https://github.com/LaurenzV/hayro"
+resolver = "2"
+
+[features]
+default = [
+ "std",
+ "images",
+]
+images = [
+ "dep:zune-jpeg",
+ "dep:hayro-ccitt",
+ "dep:hayro-jbig2",
+ "dep:hayro-jpeg2000",
+]
+logging = [
+ "dep:log",
+ "hayro-jpeg2000?/logging",
+]
+std = [
+ "hayro-jbig2?/std",
+ "hayro-jpeg2000?/std",
+ "dep:rustc-hash",
+ "zune-jpeg?/std",
+]
+unsafe = [
+ "std",
+ "dep:flate2",
+ "dep:memchr",
+ "hayro-jbig2?/simd",
+ "hayro-jpeg2000?/simd",
+ "zune-jpeg?/x86",
+ "zune-jpeg?/neon",
+]
+
+[lib]
+name = "hayro_syntax"
+path = "src/lib.rs"
+
+[[example]]
+name = "iterate"
+path = "examples/iterate.rs"
+
+[dependencies.flate2]
+version = "1"
+optional = true
+
+[dependencies.hayro-ccitt]
+version = "0.3.0"
+optional = true
+default-features = false
+
+[dependencies.hayro-jbig2]
+version = "0.3.0"
+optional = true
+default-features = false
+
+[dependencies.hayro-jpeg2000]
+version = "0.3.5"
+optional = true
+default-features = false
+
+[dependencies.log]
+version = "0.4"
+optional = true
+
+[dependencies.memchr]
+version = "2.8.0"
+features = ["alloc"]
+optional = true
+default-features = false
+
+[dependencies.rustc-hash]
+version = "2"
+optional = true
+
+[dependencies.smallvec]
+version = "1"
+
+[dependencies.zune-jpeg]
+version = "0.5"
+optional = true
+default-features = false
+
+[dev-dependencies.aes]
+version = "0.8.4"
+
+[dev-dependencies.cbc]
+version = "0.1.2"
+
+[dev-dependencies.md5]
+version = "0.8"
+
+[dev-dependencies.sha2]
+version = "0.10"
+
+[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"
diff --git a/vendor/hayro-syntax/Cargo.toml.orig b/vendor/hayro-syntax/Cargo.toml.orig
new file mode 100644
index 000000000..bbc9dcf3e
--- /dev/null
+++ b/vendor/hayro-syntax/Cargo.toml.orig
@@ -0,0 +1,46 @@
+[package]
+name = "hayro-syntax"
+version = "0.7.2"
+description = "A low-level crate for reading PDF files."
+authors = { workspace = true }
+edition = { workspace = true }
+rust-version = { workspace = true }
+repository = { workspace = true }
+license = { workspace = true }
+readme = "README.md"
+
+[features]
+default = ["std", "images"]
+std = ["hayro-jbig2?/std", "hayro-jpeg2000?/std", "dep:rustc-hash", "zune-jpeg?/std"]
+images = ["dep:zune-jpeg", "dep:hayro-ccitt", "dep:hayro-jbig2", "dep:hayro-jpeg2000"]
+unsafe = [
+ "std",
+ "dep:flate2",
+ "dep:memchr",
+ "hayro-jbig2?/simd",
+ "hayro-jpeg2000?/simd",
+ "zune-jpeg?/x86",
+ "zune-jpeg?/neon",
+]
+logging = ["dep:log", "hayro-jpeg2000?/logging"]
+
+[dependencies]
+log = { workspace = true, optional = true }
+rustc-hash = { workspace = true, optional = true }
+smallvec = { workspace = true }
+flate2 = { workspace = true, optional = true }
+memchr = { workspace = true, optional = true }
+
+zune-jpeg = { workspace = true, optional = true }
+hayro-ccitt = { workspace = true, optional = true }
+hayro-jbig2 = { workspace = true, optional = true }
+hayro-jpeg2000 = { workspace = true, optional = true }
+
+[lints]
+workspace = true
+
+[dev-dependencies]
+sha2 = "0.10"
+md5 = "0.8"
+aes = "0.8.4"
+cbc = "0.1.2"
diff --git a/vendor/hayro-syntax/LICENSE-APACHE b/vendor/hayro-syntax/LICENSE-APACHE
new file mode 100644
index 000000000..4947287f7
--- /dev/null
+++ b/vendor/hayro-syntax/LICENSE-APACHE
@@ -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
\ No newline at end of file
diff --git a/vendor/hayro-syntax/LICENSE-MIT b/vendor/hayro-syntax/LICENSE-MIT
new file mode 100644
index 000000000..ae3742de4
--- /dev/null
+++ b/vendor/hayro-syntax/LICENSE-MIT
@@ -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.
\ No newline at end of file
diff --git a/vendor/hayro-syntax/README.md b/vendor/hayro-syntax/README.md
new file mode 100644
index 000000000..941a40ea8
--- /dev/null
+++ b/vendor/hayro-syntax/README.md
@@ -0,0 +1,90 @@
+# hayro-syntax
+
+[![Crates.io](https://img.shields.io/crates/v/hayro-syntax.svg)](https://crates.io/crates/hayro-syntax)
+[![Documentation](https://docs.rs/hayro-syntax/badge.svg)](https://docs.rs/hayro-syntax)
+
+<!-- cargo-rdme start -->
+
+A low-level library for reading PDF files.
+
+This crate implements the `Syntax` chapter of the PDF reference, and therefore
+serves as a very good basis for building various abstractions on top of it, without having to reimplement
+the PDF parsing logic.
+
+This crate does not provide more high-level functionality, such as parsing fonts or color spaces.
+Such functionality is out-of-scope for `hayro-syntax`, since this crate is supposed to be
+as *light-weight* and *application-agnostic* as possible.
+
+Functionality-wise, this crate is therefore close to feature-complete. The main missing feature
+is support for password-protected documents. In addition to that, more low-level APIs might be
+added in the future.
+
+The crate is `no_std` compatible but requires an allocator to be available.
+
+## Example
+This short example shows you how to load a PDF file and iterate over the content streams of all
+pages.
+```rust
+use hayro_syntax::Pdf;
+use std::path::PathBuf;
+
+// First load the data that constitutes the PDF file.
+let data = std::fs::read(
+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../hayro-tests/pdfs/custom/text_with_rise.pdf"),
+)
+.unwrap();
+
+// Then create a new PDF file from it.
+//
+// Here we are just unwrapping in case reading the file failed, but you
+// might instead want to apply proper error handling.
+let pdf = Pdf::new(data).unwrap();
+
+// First access all pages, and then iterate over the operators of each page's
+// content stream and print them.
+let pages = pdf.pages();
+for page in pages.iter() {
+ let mut ops = page.typed_operations();
+
+ while let Some(op) = ops.next() {
+ println!("{op:?}");
+ }
+}
+```
+
+## Safety
+When the `unsafe` feature is disabled, there is only use of `unsafe` in `hayro-syntax`.
+We also unconditionally use the `smallvec` crate which uses unsafe internally, but that's
+it.
+
+For better performance, it is strongly recommended to enable the `unsafe` feature,
+which does result in slightly more unsafe code being, but does give better performance:
+- We will use the `flate2` crate for decoding flate streams.
+- SIMD will be enabled to accelerate decoding of images.
+- `memchr` will be used to accelerate some of the fallback parsing code.
+
+## Features
+The supported features include:
+- Parsing xref tables in all its possible formats, including xref streams.
+- Best-effort attempt at repairing PDF files with broken xref tables.
+- Parsing of all objects types (also in object streams).
+- Parsing and decoding PDF streams.
+- Iterating over pages as well as their content streams in a typed or untyped fashion.
+- The crate is very lightweight, especially in comparison to other PDF crates.
+
+## Limitations
+- There are still a few features missing, for example, support for
+ password-protected PDFs. In addition to that, many properties (like page annotations) are
+ currently not exposed.
+- This crate is for read-only processing, you cannot directly use it to manipulate PDF files.
+ If you need to do that, there are other crates in the Rust ecosystem that are suitable for this.
+
+<!-- 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.
diff --git a/vendor/hayro-syntax/examples/iterate.rs b/vendor/hayro-syntax/examples/iterate.rs
new file mode 100644
index 000000000..a30a63c99
--- /dev/null
+++ b/vendor/hayro-syntax/examples/iterate.rs
@@ -0,0 +1,26 @@
+//! This example shows how you can iterate over the content stream of all pages in a PDF.
+
+use hayro_syntax::Pdf;
+use std::path::PathBuf;
+
+fn main() {
+ // First load the data that constitutes the PDF file.
+ let data = std::fs::read(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../in.pdf")).unwrap();
+
+ // Then create a new PDF file from it.
+ //
+ // Here we are just unwrapping in case reading the file failed, but you
+ // might instead want to apply proper error handling.
+ let pdf = Pdf::new(data).unwrap();
+
+ // First access all pages, and then iterate over the operators of each page's
+ // content stream and print them.
+ let pages = pdf.pages();
+ for page in pages.iter() {
+ let mut ops = page.typed_operations();
+
+ while let Some(op) = ops.next() {
+ println!("{op:?}");
+ }
+ }
+}
diff --git a/vendor/hayro-syntax/src/bit_reader.rs b/vendor/hayro-syntax/src/bit_reader.rs
new file mode 100644
index 000000000..361f00b11
--- /dev/null
+++ b/vendor/hayro-syntax/src/bit_reader.rs
@@ -0,0 +1,623 @@
+//! A simple bit reader and writer.
+
+use core::fmt::Debug;
+use smallvec::{SmallVec, smallvec};
+
+/// A bit reader.
+#[derive(Debug, Clone)]
+pub struct BitReader<'a> {
+ /// The underlying bytes of the bit reader.
+ pub data: &'a [u8],
+ cur_pos: usize,
+}
+
+impl<'a> BitReader<'a> {
+ /// Create a new bit reader.
+ #[inline]
+ pub fn new(data: &'a [u8]) -> Self {
+ Self::new_with(data, 0)
+ }
+
+ /// Create a new bit reader, and start at a specific bit offset.
+ #[inline]
+ pub fn new_with(data: &'a [u8], cur_pos: usize) -> Self {
+ Self { data, cur_pos }
+ }
+
+ /// Align the reader to the next byte boundary.
+ #[inline]
+ pub fn align(&mut self) {
+ let bit_pos = self.bit_pos();
+
+ if !bit_pos.is_multiple_of(8) {
+ self.cur_pos += 8 - bit_pos;
+ }
+ }
+
+ /// Read the given number of bits from the byte stream.
+ ///
+ /// Returns `None` if `bit_size` > 32.
+ #[inline(always)]
+ pub fn read(&mut self, bit_size: u8) -> Option<u32> {
+ if !(1..=32).contains(&bit_size) {
+ return None;
+ }
+
+ let byte_pos = self.byte_pos();
+
+ if byte_pos >= self.data.len() {
+ return None;
+ }
+
+ let item = match bit_size {
+ 8 => {
+ let item = self.data[byte_pos] as u32;
+ self.cur_pos += 8;
+
+ Some(item)
+ }
+ 1..=32 => {
+ let bit_pos = self.bit_pos();
+ let end_byte_pos = (bit_pos + bit_size as usize - 1) / 8;
+ let mut read = [0_u8; 8];
+
+ for (i, r) in read.iter_mut().enumerate().take(end_byte_pos + 1) {
+ *r = *self.data.get(byte_pos + i)?;
+ }
+
+ let item = (u64::from_be_bytes(read) >> (64 - bit_pos - bit_size as usize)) as u32
+ & bit_mask(bit_size);
+ self.cur_pos += bit_size as usize;
+
+ Some(item)
+ }
+ _ => None,
+ }?;
+
+ Some(item)
+ }
+
+ /// Peak the given number of bits.
+ pub fn peak(&mut self, bit_size: u8) -> Option<u32> {
+ self.clone().read(bit_size)
+ }
+
+ /// Whether the bit reader has read all bytes.
+ pub fn at_end(&self) -> bool {
+ self.byte_pos() >= self.data.len()
+ }
+
+ /// Get the current byte position.
+ #[inline]
+ pub fn byte_pos(&self) -> usize {
+ self.cur_pos / 8
+ }
+
+ /// Get the current position within the byte.
+ #[inline]
+ pub fn bit_pos(&self) -> usize {
+ self.cur_pos % 8
+ }
+
+ /// Get the current position in bits.
+ #[inline]
+ pub fn cur_pos(&self) -> usize {
+ self.cur_pos
+ }
+
+ /// Get the tail (aligned to the current byte position) of the data.
+ #[inline]
+ pub fn tail(&self) -> &'a [u8] {
+ &self.data[self.byte_pos()..]
+ }
+
+ /// Get the full byte (aligned to the byte boundary) of the current position.
+ #[inline]
+ pub fn cur_byte(&self) -> Option<u8> {
+ self.data.get(self.byte_pos()).copied()
+ }
+}
+
+/// Get the mask for the given bit size.
+pub fn bit_mask(bit_size: u8) -> u32 {
+ match bit_size {
+ 0 => 0,
+ 1..=31 => (1_u32 << bit_size) - 1,
+ _ => u32::MAX,
+ }
+}
+/// A bit writer.
+#[derive(Debug)]
+pub struct BitWriter<'a> {
+ data: &'a mut [u8],
+ cur_pos: usize,
+ bit_size: u8,
+}
+
+impl<'a> BitWriter<'a> {
+ /// Create a new bit writer for a fixed bit size between 1 and 32 (inclusive).
+ #[inline]
+ pub fn new(data: &'a mut [u8], bit_size: u8) -> Option<Self> {
+ if !(1..=32).contains(&bit_size) {
+ return None;
+ }
+
+ Some(Self {
+ data,
+ bit_size,
+ cur_pos: 0,
+ })
+ }
+
+ /// Split off the already-written parts and return a new bit writer for the tail.
+ #[inline]
+ pub fn split_off(self) -> (&'a [u8], Self) {
+ // Assumes that we are currently aligned to a byte boundary!
+ let (left, right) = self.data.split_at_mut(self.cur_pos / 8);
+ (
+ left,
+ BitWriter {
+ data: right,
+ cur_pos: 0,
+ bit_size: self.bit_size,
+ },
+ )
+ }
+
+ /// Align the writer to the next byte boundary.
+ #[inline]
+ pub fn align(&mut self) {
+ let bit_pos = self.bit_pos();
+
+ if !bit_pos.is_multiple_of(8) {
+ self.cur_pos += 8 - bit_pos;
+ }
+ }
+
+ /// Return the number of written bits.
+ #[inline]
+ pub fn cur_pos(&self) -> usize {
+ self.cur_pos
+ }
+
+ /// Return the whole underlying buffer.
+ #[inline]
+ pub fn get_data(&self) -> &[u8] {
+ self.data
+ }
+
+ fn bit_pos(&self) -> usize {
+ self.cur_pos % 8
+ }
+
+ /// Write the given number into the buffer.
+ #[inline]
+ pub fn write(&mut self, val: u32) -> Option<()> {
+ let bit_size = self.bit_size as usize;
+ let mut bits_left = bit_size;
+ let value = val & bit_mask(self.bit_size);
+
+ while bits_left > 0 {
+ let already_advanced = bit_size - bits_left;
+ let absolute_pos = self.cur_pos + already_advanced;
+ let byte_pos = absolute_pos / 8;
+ let bit_pos = absolute_pos % 8;
+ let bits_in_byte = (8 - bit_pos).min(bits_left);
+ let shift = bits_left - bits_in_byte;
+ let chunk_mask = bit_mask(bits_in_byte as u8);
+ let chunk = ((value >> shift) & chunk_mask) as u8;
+
+ let shift_in_byte = 8 - bits_in_byte - bit_pos;
+ let byte = self.data.get_mut(byte_pos)?;
+ let byte_mask = (chunk_mask as u8) << shift_in_byte;
+
+ *byte = (*byte & !byte_mask) | ((chunk << shift_in_byte) & byte_mask);
+
+ bits_left -= bits_in_byte;
+ }
+
+ self.cur_pos += bit_size;
+
+ Some(())
+ }
+
+ /// Fill bytes with a repeated value when at a byte boundary.
+ #[inline]
+ pub fn fill_bytes(&mut self, byte: u8, count: usize) -> Option<()> {
+ debug_assert_eq!(self.cur_pos % 8, 0);
+
+ let start = self.cur_pos / 8;
+ let end = start + count;
+ self.data.get_mut(start..end)?.fill(byte);
+ self.cur_pos += count * 8;
+ Some(())
+ }
+
+ /// Write multiple numbers at once.
+ #[inline]
+ pub fn write_bits(&mut self, bits: impl IntoIterator<Item = u32>) -> Option<()> {
+ for bit in bits {
+ let value: u32 = bit;
+ self.write(value)?;
+ }
+
+ Some(())
+ }
+}
+
+/// An iterator over bit chunks.
+pub struct BitChunks<'a> {
+ reader: BitReader<'a>,
+ bit_size: u8,
+ chunk_len: usize,
+}
+
+impl<'a> BitChunks<'a> {
+ /// Create a new iterator over bit chunks.
+ pub fn new(data: &'a [u8], bit_size: u8, chunk_len: usize) -> Option<Self> {
+ if !(1..=16).contains(&bit_size) || chunk_len == 0 {
+ return None;
+ }
+
+ let reader = BitReader::new(data);
+
+ Some(Self {
+ reader,
+ bit_size,
+ chunk_len,
+ })
+ }
+}
+
+impl Iterator for BitChunks<'_> {
+ type Item = BitChunk;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ let mut bits = SmallVec::new();
+
+ for _ in 0..self.chunk_len {
+ bits.push(self.reader.read(self.bit_size)? as u16);
+ }
+
+ Some(BitChunk { bits })
+ }
+}
+
+/// A chunk of bits.
+#[derive(Debug, Clone)]
+pub struct BitChunk {
+ bits: SmallVec<[u16; 4]>,
+}
+
+impl BitChunk {
+ /// Return an iterator over the numbers in the chunk.
+ pub fn iter(&self) -> impl Iterator<Item = u16> + '_ {
+ self.bits.iter().copied()
+ }
+
+ /// Create a new bit chunk with the given value being repeated `count` times.
+ pub fn new(val: u8, count: usize) -> Self {
+ Self {
+ bits: smallvec![val as u16; count],
+ }
+ }
+
+ /// Create a new bit chunk from the given reader.
+ pub fn from_reader(
+ bit_reader: &mut BitReader<'_>,
+ bit_size: u8,
+ chunk_len: usize,
+ ) -> Option<Self> {
+ if !(1..=16).contains(&bit_size) || chunk_len == 0 {
+ return None;
+ }
+
+ let mut bits = SmallVec::new();
+
+ for _ in 0..chunk_len {
+ bits.push(bit_reader.read(bit_size)? as u16);
+ }
+
+ Some(Self { bits })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn bit_reader_16() {
+ let data = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06];
+ let mut reader = BitReader::new(&data);
+ assert_eq!(
+ reader.read(16).unwrap() as u16,
+ u16::from_be_bytes([0x01, 0x02])
+ );
+ assert_eq!(
+ reader.read(16).unwrap() as u16,
+ u16::from_be_bytes([0x03, 0x04])
+ );
+ assert_eq!(
+ reader.read(16).unwrap() as u16,
+ u16::from_be_bytes([0x05, 0x06])
+ );
+ }
+
+ #[test]
+ fn bit_writer_16() {
+ let mut buf = vec![0_u8; 6];
+ let mut writer = BitWriter::new(&mut buf, 16).unwrap();
+ writer
+ .write(u16::from_be_bytes([0x01, 0x02]) as u32)
+ .unwrap();
+ writer
+ .write(u16::from_be_bytes([0x03, 0x04]) as u32)
+ .unwrap();
+ writer
+ .write(u16::from_be_bytes([0x05, 0x06]) as u32)
+ .unwrap();
+
+ assert_eq!(buf, [0x01, 0x02, 0x03, 0x04, 0x05, 0x06]);
+ }
+
+ #[test]
+ fn bit_reader_12() {
+ let data = [0b10011000, 0b00011111, 0b10101001, 0b11101001, 0b00011010];
+ let mut reader = BitReader::new(&data);
+ assert_eq!(reader.read(12).unwrap(), 0b100110000001);
+ assert_eq!(reader.read(12).unwrap(), 0b111110101001);
+ assert_eq!(reader.read(12).unwrap(), 0b111010010001);
+ }
+
+ #[test]
+ fn bit_reader_9() {
+ let data = [0b10011000, 0b00011111, 0b10101001, 0b11101001, 0b00011010];
+ let mut reader = BitReader::new(&data);
+ assert_eq!(reader.read(9).unwrap(), 0b100110000);
+ assert_eq!(reader.read(9).unwrap(), 0b001111110);
+ assert_eq!(reader.read(9).unwrap(), 0b101001111);
+ assert_eq!(reader.read(9).unwrap(), 0b010010001);
+ }
+
+ #[test]
+ fn bit_writer_8() {
+ let mut buf = vec![0_u8; 3];
+ let mut writer = BitWriter::new(&mut buf, 8).unwrap();
+ writer.write(0x01).unwrap();
+ writer.write(0x02).unwrap();
+ writer.write(0x03).unwrap();
+
+ assert_eq!(buf, [0x01, 0x02, 0x03]);
+ }
+
+ #[test]
+ fn bit_reader_8() {
+ let data = [0x01, 0x02, 0x03];
+ let mut reader = BitReader::new(&data);
+ assert_eq!(reader.read(8).unwrap(), 0x01);
+ assert_eq!(reader.read(8).unwrap(), 0x02);
+ assert_eq!(reader.read(8).unwrap(), 0x03);
+ }
+
+ #[test]
+ fn bit_writer_4() {
+ let mut buf = vec![0_u8; 3];
+ let mut writer = BitWriter::new(&mut buf, 4).unwrap();
+ writer.write(0b1001).unwrap();
+ writer.write(0b1000).unwrap();
+ writer.write(0b0001).unwrap();
+ writer.write(0b1111).unwrap();
+ writer.write(0b1010).unwrap();
+ writer.write(0b1001).unwrap();
+
+ assert_eq!(buf, [0b10011000, 0b00011111, 0b10101001]);
+ }
+
+ #[test]
+ fn bit_reader_4() {
+ let data = [0b10011000, 0b00011111, 0b10101001];
+ let mut reader = BitReader::new(&data);
+ assert_eq!(reader.read(4).unwrap(), 0b1001);
+ assert_eq!(reader.read(4).unwrap(), 0b1000);
+ assert_eq!(reader.read(4).unwrap(), 0b0001);
+ assert_eq!(reader.read(4).unwrap(), 0b1111);
+ assert_eq!(reader.read(4).unwrap(), 0b1010);
+ assert_eq!(reader.read(4).unwrap(), 0b1001);
+ }
+
+ #[test]
+ fn bit_writer_2() {
+ let mut buf = vec![0_u8; 2];
+ let mut writer = BitWriter::new(&mut buf, 2).unwrap();
+ writer.write(0b10).unwrap();
+ writer.write(0b01).unwrap();
+ writer.write(0b10).unwrap();
+ writer.write(0b00).unwrap();
+ writer.write(0b00).unwrap();
+ writer.write(0b01).unwrap();
+ writer.write(0b00).unwrap();
+ writer.write(0b00).unwrap();
+
+ assert_eq!(buf, [0b10011000, 0b00010000]);
+ }
+
+ #[test]
+ fn bit_reader_2() {
+ let data = [0b10011000, 0b00010000];
+ let mut reader = BitReader::new(&data);
+ assert_eq!(reader.read(2).unwrap(), 0b10);
+ assert_eq!(reader.read(2).unwrap(), 0b01);
+ assert_eq!(reader.read(2).unwrap(), 0b10);
+ assert_eq!(reader.read(2).unwrap(), 0b00);
+ assert_eq!(reader.read(2).unwrap(), 0b00);
+ assert_eq!(reader.read(2).unwrap(), 0b01);
+ assert_eq!(reader.read(2).unwrap(), 0b00);
+ assert_eq!(reader.read(2).unwrap(), 0b00);
+ }
+
+ #[test]
+ fn bit_writer_1() {
+ let mut buf = vec![0_u8; 2];
+ let mut writer = BitWriter::new(&mut buf, 1).unwrap();
+ writer.write(0b1).unwrap();
+ writer.write(0b0).unwrap();
+ writer.write(0b0).unwrap();
+ writer.write(0b1).unwrap();
+ writer.write(0b1).unwrap();
+ writer.write(0b0).unwrap();
+ writer.write(0b0).unwrap();
+ writer.write(0b0).unwrap();
+
+ writer.write(0b0).unwrap();
+ writer.write(0b0).unwrap();
+ writer.write(0b0).unwrap();
+ writer.write(0b1).unwrap();
+ writer.write(0b0).unwrap();
+ writer.write(0b0).unwrap();
+ writer.write(0b0).unwrap();
+ writer.write(0b0).unwrap();
+
+ assert_eq!(buf, [0b10011000, 0b00010000]);
+ }
+
+ #[test]
+ fn bit_reader_1() {
+ let data = [0b10011000, 0b00010000];
+ let mut reader = BitReader::new(&data);
+ assert_eq!(reader.read(1).unwrap(), 0b1);
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ assert_eq!(reader.read(1).unwrap(), 0b1);
+ assert_eq!(reader.read(1).unwrap(), 0b1);
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ assert_eq!(reader.read(1).unwrap(), 0b1);
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ }
+
+ #[test]
+ fn bit_reader_align() {
+ let data = [0b10011000, 0b00010000];
+ let mut reader = BitReader::new(&data);
+ assert_eq!(reader.read(1).unwrap(), 0b1);
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ assert_eq!(reader.read(1).unwrap(), 0b1);
+ reader.align();
+
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ assert_eq!(reader.read(1).unwrap(), 0b1);
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ assert_eq!(reader.read(1).unwrap(), 0b0);
+ }
+
+ #[test]
+ fn bit_reader_chunks() {
+ let data = [0b10011000, 0b00010000];
+ let mut reader = BitChunks::new(&data, 1, 3).unwrap();
+ assert_eq!(reader.next().unwrap().bits.as_ref(), &[0b1, 0b0, 0b0]);
+ assert_eq!(reader.next().unwrap().bits.as_ref(), &[0b1, 0b1, 0b0]);
+ assert_eq!(reader.next().unwrap().bits.as_ref(), &[0b0, 0b0, 0b0]);
+ assert_eq!(reader.next().unwrap().bits.as_ref(), &[0b0, 0b0, 0b1]);
+ assert_eq!(reader.next().unwrap().bits.as_ref(), &[0b0, 0b0, 0b0]);
+ }
+
+ #[test]
+ fn bit_reader_varying_bit_sizes() {
+ let data = [0b10011000, 0b00011111, 0b10101001];
+ let mut reader = BitReader::new(&data);
+ assert_eq!(reader.read(4).unwrap(), 0b1001);
+ assert_eq!(reader.read(1).unwrap(), 0b1);
+ assert_eq!(reader.read(4).unwrap(), 0b0000);
+ assert_eq!(reader.read(5).unwrap(), 0b00111);
+ assert_eq!(reader.read(1).unwrap(), 0b1);
+ assert_eq!(reader.read(2).unwrap(), 0b11);
+ assert_eq!(reader.read(7).unwrap(), 0b0101001);
+ }
+
+ #[test]
+ fn bit_writer_rejects_invalid_sizes() {
+ let mut buf = [0_u8; 4];
+ assert!(BitWriter::new(&mut buf, 0).is_none());
+ assert!(BitWriter::new(&mut buf, 33).is_none());
+ }
+
+ #[test]
+ fn bit_reader_rejects_invalid_sizes() {
+ let data = [0xff];
+ let mut reader = BitReader::new(&data);
+ assert!(reader.read(0).is_none());
+ assert!(reader.read(33).is_none());
+ }
+
+ #[test]
+ fn bit_writer_round_trip_all_bit_sizes() {
+ for bit_size in 1_u8..=32 {
+ let mask = bit_mask(bit_size);
+ let sample_count = if bit_size > 16 { 4 } else { 6 };
+ let values: Vec<u32> = (0..sample_count)
+ .map(|i| {
+ let seed = 0x9E37_u32.wrapping_mul(i as u32 + 1) ^ (bit_size as u32 * 0x45);
+ seed & mask
+ })
+ .collect();
+
+ let total_bits = bit_size as usize * values.len();
+ let mut buf = vec![0_u8; total_bits.div_ceil(8)];
+ let mut writer = BitWriter::new(&mut buf, bit_size).unwrap();
+
+ for value in &values {
+ writer.write(*value).unwrap();
+ }
+
+ let mut reader = BitReader::new(&buf);
+ for expected in &values {
+ assert_eq!(
+ reader.read(bit_size).unwrap(),
+ *expected,
+ "round-trip failed for bit size {bit_size}"
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn bit_writer_round_trip_12_and_25_bits() {
+ for &bit_size in &[12_u8, 25_u8] {
+ let mask = bit_mask(bit_size);
+ let values: Vec<u32> = (0..5)
+ .map(|i| ((0xABCDE_u32.wrapping_mul(i + 1)) ^ (bit_size as u32)) & mask)
+ .collect();
+
+ let total_bits = bit_size as usize * values.len();
+ let mut buf = vec![0_u8; total_bits.div_ceil(8)];
+ let mut writer = BitWriter::new(&mut buf, bit_size).unwrap();
+
+ for value in &values {
+ writer.write(*value).unwrap();
+ }
+
+ let mut reader = BitReader::new(&buf);
+ for expected in &values {
+ assert_eq!(
+ reader.read(bit_size).unwrap(),
+ *expected,
+ "round-trip failed for bit size {bit_size}"
+ );
+ }
+ }
+ }
+}
diff --git a/vendor/hayro-syntax/src/byte_reader.rs b/vendor/hayro-syntax/src/byte_reader.rs
new file mode 100644
index 000000000..9ea295728
--- /dev/null
+++ b/vendor/hayro-syntax/src/byte_reader.rs
@@ -0,0 +1,224 @@
+//! A byte reader.
+
+use core::ops::Range;
+
+/// A reader for reading bytes and PDF objects.
+#[derive(Clone, Debug)]
+pub struct Reader<'a> {
+ /// The underlying data of the reader.
+ pub data: &'a [u8],
+ /// The current byte-offset.
+ pub offset: usize,
+}
+
+impl<'a> Reader<'a> {
+ /// Create a new reader.
+ #[inline]
+ pub fn new(data: &'a [u8]) -> Self {
+ Self { data, offset: 0 }
+ }
+
+ /// Create a new reader at the given offset.
+ #[inline]
+ pub fn new_with(data: &'a [u8], offset: usize) -> Self {
+ Self { data, offset }
+ }
+
+ /// Returns `true` if the reader has reached the end of the data.
+ #[inline]
+ pub fn at_end(&self) -> bool {
+ self.offset >= self.data.len()
+ }
+
+ /// Moves the reader offset to the end of the data.
+ #[inline]
+ pub fn jump_to_end(&mut self) {
+ self.offset = self.data.len();
+ }
+
+ /// Moves the reader to the specified offset.
+ #[inline]
+ pub fn jump(&mut self, offset: usize) {
+ self.offset = offset;
+ }
+
+ /// Returns the remaining data from the current offset to the end.
+ #[inline]
+ pub fn tail(&mut self) -> Option<&'a [u8]> {
+ self.data.get(self.offset..)
+ }
+
+ /// Returns the total length of the underlying data.
+ #[inline]
+ pub fn len(&self) -> usize {
+ self.data.len()
+ }
+
+ /// Returns `true` if the underlying data is empty.
+ #[inline]
+ pub fn is_empty(&self) -> bool {
+ self.data.is_empty()
+ }
+
+ /// Returns a slice of the data for the specified range.
+ #[inline]
+ pub fn range(&self, range: Range<usize>) -> Option<&'a [u8]> {
+ self.data.get(range)
+ }
+
+ /// Returns the current offset of the reader.
+ #[inline]
+ pub fn offset(&self) -> usize {
+ self.offset
+ }
+
+ /// Reads the specified number of bytes and advances the offset.
+ #[inline]
+ pub fn read_bytes(&mut self, len: usize) -> Option<&'a [u8]> {
+ let v = self.peek_bytes(len)?;
+ self.offset += len;
+
+ Some(v)
+ }
+
+ /// Reads a single byte and advances the offset.
+ #[inline]
+ pub fn read_byte(&mut self) -> Option<u8> {
+ let v = self.peek_byte()?;
+ self.offset += 1;
+
+ Some(v)
+ }
+
+ /// Skips the specified number of bytes by advancing the offset.
+ #[inline]
+ pub fn skip_bytes(&mut self, len: usize) -> Option<()> {
+ self.read_bytes(len).map(|_| {})
+ }
+
+ /// Peeks the specified number of bytes.
+ #[inline]
+ pub fn peek_bytes(&self, len: usize) -> Option<&'a [u8]> {
+ self.offset
+ .checked_add(len)
+ .and_then(|end| self.data.get(self.offset..end))
+ }
+
+ /// Peeks a single byte.
+ #[inline]
+ pub fn peek_byte(&self) -> Option<u8> {
+ self.data.get(self.offset).copied()
+ }
+
+ /// Eat the next byte if it satisfies the condition.
+ #[inline]
+ pub fn eat(&mut self, f: impl Fn(u8) -> bool) -> Option<u8> {
+ let val = self.peek_byte()?;
+ if f(val) {
+ self.forward();
+ Some(val)
+ } else {
+ None
+ }
+ }
+
+ /// Advances the offset by one byte.
+ #[inline]
+ pub fn forward(&mut self) {
+ self.offset += 1;
+ }
+
+ /// Advances the offset by one byte if the current byte satisfies the predicate.
+ #[inline]
+ pub fn forward_if(&mut self, f: impl Fn(u8) -> bool) -> Option<()> {
+ if f(self.peek_byte()?) {
+ self.forward();
+
+ Some(())
+ } else {
+ None
+ }
+ }
+
+ /// Advances the offset while bytes satisfy the predicate, at least one time.
+ #[inline]
+ pub fn forward_while_1(&mut self, f: impl Fn(u8) -> bool) -> Option<()> {
+ self.eat(&f)?;
+ self.forward_while(f);
+ Some(())
+ }
+
+ /// Advances the offset if the next bytes match the specified tag.
+ #[inline]
+ pub fn forward_tag(&mut self, tag: &[u8]) -> Option<()> {
+ self.peek_tag(tag)?;
+ self.offset += tag.len();
+
+ Some(())
+ }
+
+ /// Advances the offset while the given byte satisfies the predicate.
+ #[inline]
+ pub fn forward_while(&mut self, f: impl Fn(u8) -> bool) {
+ while let Some(b) = self.peek_byte() {
+ if f(b) {
+ self.forward();
+ } else {
+ break;
+ }
+ }
+ }
+
+ /// Checks if the next bytes match the specified tag.
+ #[inline]
+ pub fn peek_tag(&self, tag: &[u8]) -> Option<()> {
+ let mut cloned = self.clone();
+
+ for b in tag.iter().copied() {
+ if cloned.peek_byte() == Some(b) {
+ cloned.forward();
+ } else {
+ return None;
+ }
+ }
+
+ Some(())
+ }
+
+ /// Read a u16 integer (in big endian order).
+ #[inline]
+ pub fn read_u16(&mut self) -> Option<u16> {
+ let bytes = self.read_bytes(2)?;
+
+ Some(u16::from_be_bytes([bytes[0], bytes[1]]))
+ }
+
+ /// Read a u32 integer (in big endian order).
+ #[inline]
+ pub fn read_u32(&mut self) -> Option<u32> {
+ let bytes = self.read_bytes(4)?;
+
+ Some(u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
+ }
+
+ /// Read a u64 integer (in big endian order).
+ #[inline]
+ pub fn read_u64(&mut self) -> Option<u64> {
+ let bytes = self.read_bytes(8)?;
+
+ Some(u64::from_be_bytes([
+ bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
+ ]))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::Reader;
+
+ #[test]
+ fn peek_bytes_rejects_overflowing_len() {
+ let reader = Reader::new(b"abc");
+ assert!(reader.peek_bytes(usize::MAX).is_none());
+ }
+}
diff --git a/vendor/hayro-syntax/src/content/gen_ops.py b/vendor/hayro-syntax/src/content/gen_ops.py
new file mode 100644
index 000000000..2d286a506
--- /dev/null
+++ b/vendor/hayro-syntax/src/content/gen_ops.py
@@ -0,0 +1,222 @@
+from enum import Enum
+
+
+class Type(Enum):
+ Number = "Number"
+ String = "String"
+ Array = "Array"
+ Dict = "Dict"
+ Object = "Object"
+ Stream = "Stream"
+ VecNum = "SmallVec<[Number; OPERANDS_THRESHOLD]>"
+ Name = "Name"
+
+
+ops = {
+ "Compatibility operators": [
+ ("BX", "BeginCompatibility", []),
+ ("EX", "EndCompatibility", []),
+ ],
+ "Graphic state operators": [
+ ("q", "SaveState", []),
+ ("Q", "RestoreState", []),
+ ("cm", "Transform", [Type.Number] * 6),
+ ("w", "LineWidth", [Type.Number]),
+ ("J", "LineCap", [Type.Number]),
+ ("j", "LineJoin", [Type.Number]),
+ ("M", "MiterLimit", [Type.Number]),
+ ("d", "DashPattern", [Type.Array, Type.Number]),
+ ("ri", "RenderingIntent", [Type.Name]),
+ ("i", "FlatnessTolerance", [Type.Number]),
+ ("gs", "SetGraphicsState", [Type.Name]),
+ ],
+ "Path-construction operators": [
+ ("m", "MoveTo", [Type.Number, Type.Number]),
+ ("l", "LineTo", [Type.Number, Type.Number]),
+ ("c", "CubicTo", [Type.Number] * 6),
+ ("v", "CubicStartTo", [Type.Number] * 4),
+ ("y", "CubicEndTo", [Type.Number] * 4),
+ ("h", "ClosePath", []),
+ ("re", "RectPath", [Type.Number] * 4),
+ ],
+ "Path-painting operators": [
+ ("S", "StrokePath", []),
+ ("s", "CloseAndStrokePath", []),
+ ("f", "FillPathNonZero", []),
+ ("F", "FillPathNonZeroCompatibility", []),
+ ("f*", "FillPathEvenOdd", []),
+ ("B", "FillAndStrokeNonZero", []),
+ ("B*", "FillAndStrokeEvenOdd", []),
+ ("b", "CloseFillAndStrokeNonZero", []),
+ ("b*", "CloseFillAndStrokeEvenOdd", []),
+ ("n", "EndPath", []),
+ ],
+ "Clipping path operators": [
+ ("W", "ClipNonZero", []),
+ ("W*", "ClipEvenOdd", []),
+ ],
+ "Colour operators": [
+ ("CS", "ColorSpaceStroke", [Type.Name]),
+ ("cs", "ColorSpaceNonStroke", [Type.Name]),
+ ("SC", "StrokeColor", [Type.VecNum]),
+ ("SCN", "StrokeColorNamed", True),
+ ("sc", "NonStrokeColor", [Type.VecNum]),
+ ("scn", "NonStrokeColorNamed", True),
+ ("G", "StrokeColorDeviceGray", [Type.Number]),
+ ("g", "NonStrokeColorDeviceGray", [Type.Number]),
+ ("RG", "StrokeColorDeviceRgb", [Type.Number] * 3),
+ ("rg", "NonStrokeColorDeviceRgb", [Type.Number] * 3),
+ ("K", "StrokeColorCmyk", [Type.Number] * 4),
+ ("k", "NonStrokeColorCmyk", [Type.Number] * 4),
+ ],
+ "Shading operator": [("sh", "Shading", [Type.Name])],
+ "XObject operator": [("Do", "XObject", [Type.Name])],
+ "Inline-image operators": [
+ ("BI", "InlineImage", [Type.Stream]),
+ # We do not emit ID and EI in the parser.
+ # ("ID", "BeginInlineImageData", []),
+ # ("EI", "EndInlineImage", []),
+ ],
+ "Text-state operators": [
+ ("Tc", "CharacterSpacing", [Type.Number]),
+ ("Tw", "WordSpacing", [Type.Number]),
+ ("Tz", "HorizontalScaling", [Type.Number]),
+ ("TL", "TextLeading", [Type.Number]),
+ ("Tf", "TextFont", [Type.Name, Type.Number]),
+ ("Tr", "TextRenderingMode", [Type.Number]),
+ ("Ts", "TextRise", [Type.Number]),
+ ],
+ "Text-object operators": [
+ ("BT", "BeginText", []),
+ ("ET", "EndText", []),
+ ],
+ "Text-positioning operators": [
+ ("Td", "NextLine", [Type.Number] * 2),
+ ("TD", "NextLineAndSetLeading", [Type.Number] * 2),
+ ("Tm", "SetTextMatrix", [Type.Number] * 6),
+ ("T*", "NextLineUsingLeading", []),
+ ],
+ "Text-showing operators": [
+ ("Tj", "ShowText", [Type.String]),
+ ("'", "NextLineAndShowText", [Type.String]),
+ ('"', "ShowTextWithParameters", [Type.Number, Type.Number, Type.String]),
+ ("TJ", "ShowTexts", [Type.Array]),
+ ],
+ "Type 3 font operators": [
+ ("d0", "ColorGlyph", [Type.Number] * 2),
+ ("d1", "ShapeGlyph", [Type.Number] * 6),
+ ],
+ "Marked content operators": [
+ ("MP", "MarkedContentPoint", [Type.Name]),
+ # Second argument can be name or dict
+ ("DP", "MarkedContentPointWithProperties", [Type.Name, Type.Object]),
+ ("BMC", "BeginMarkedContent", [Type.Name]),
+ # Second argument can be name or dict
+ ("BDC", "BeginMarkedContentWithProperties", [Type.Name, Type.Object]),
+ ("EMC", "EndMarkedContent", []),
+ ],
+}
+
+
+def rust_type(t: Type) -> str:
+ return {
+ Type.Number: "Number",
+ Type.String: "&'b object::String<'a>",
+ Type.Array: "&'b Array<'a>",
+ Type.Object: "&'b Object<'a>",
+ Type.Stream: "&'b Stream<'a>",
+ Type.Name: "&'b Name<'a>",
+ Type.Dict: "&'b Dict<'a>",
+ Type.VecNum: "SmallVec<[Number; OPERANDS_THRESHOLD]>",
+ }[t]
+
+
+def lifetime_if_needed(types):
+ return (
+ "<'b, 'a>"
+ if any(
+ t in [Type.Array, Type.Object, Type.Stream, Type.Dict, Type.Name, Type.String]
+ for t in types
+ )
+ else ""
+ )
+
+
+def gen_struct(name, code, types):
+ lifetime = lifetime_if_needed(types)
+ count = len(types)
+ macro_suffix = count
+ struct = [f"#[derive(Debug, PartialEq, Clone)]"]
+ if count == 0:
+ struct.append(f"pub struct {name};")
+ elif count == 1:
+ struct.append(f"pub struct {name}{lifetime}(pub {rust_type(types[0])});")
+ if types[0] == Type.VecNum:
+ macro_suffix = "_all"
+ else:
+ struct.append(f"pub struct {name}{lifetime}(")
+ struct += [f" pub {rust_type(t)}," for t in types]
+ struct.append(");")
+ # Escape the Rust string literal properly
+ escaped_code = code.replace('"', '\\"')
+ struct.append(f'op{macro_suffix}!({name}{lifetime}, "{escaped_code}");')
+ return "\n".join(struct)
+
+
+def gen_enum_variant(name, types):
+ has_lifetime = name in ["StrokeColorNamed", "NonStrokeColorNamed"] or (
+ (type(types) is list)
+ and any(t in [Type.Array, Type.Object, Type.Stream, Type.Name, Type.String] for t in types)
+ )
+ inner_type = f"{name}<'b, 'a>" if has_lifetime else name
+ return f"{name}({inner_type})"
+
+
+def gen_dispatch_match(code, name, types):
+ escaped_code = code.replace('"', '\\"')
+ return f'b"{escaped_code}" => {name}::from_stack(instruction.operands)?.into(),'
+
+
+# Generate all code pieces
+structs = []
+enum_variants = []
+dispatch_arms = []
+
+for category in ops.values():
+ for code, name, types in category:
+ if type(types) is list:
+ structs.append(gen_struct(name, code, types))
+ enum_variants.append(gen_enum_variant(name, types))
+ dispatch_arms.append(gen_dispatch_match(code, name, types))
+
+# Build the final Rust code blocks
+struct_block = "\n\n".join(structs)
+
+enum_block = (
+ "#[derive(Debug, PartialEq, Clone)]\n"
+ "pub enum TypedInstruction<'b, 'a> {\n" + " " + ",\n ".join(enum_variants) + ",\n"
+ " Fallback(&'b Operator<'a>),\n}"
+)
+
+dispatch_block = (
+ "impl<'b, 'a> TypedInstruction<'b, 'a> {\n"
+ " #[inline(always)]\n"
+ " pub(crate) fn dispatch(instruction: &Instruction<'b, 'a>) -> Option<Self> {\n"
+ " let op_name = instruction.operator.as_ref();\n"
+ " Some(match op_name {\n"
+ + " "
+ + "\n ".join(dispatch_arms)
+ + "\n"
+ " _ => return Some(Self::Fallback(instruction.operator)),\n"
+ " })\n"
+ " }\n"
+ "}"
+)
+
+gen_notice = "// THIS FILE IS AUTO-GENERATED, DO NOT EDIT MANUALLY"
+imports = "use crate::content::Operator;"
+
+joined = "\n\n".join([gen_notice, imports, struct_block, enum_block, dispatch_block])
+
+with open("ops_generated.rs", "w") as f:
+ f.write(joined)
diff --git a/vendor/hayro-syntax/src/content/mod.rs b/vendor/hayro-syntax/src/content/mod.rs
new file mode 100644
index 000000000..794504713
--- /dev/null
+++ b/vendor/hayro-syntax/src/content/mod.rs
@@ -0,0 +1,669 @@
+/*!
+PDF content operators.
+
+This module provides facilities to read and interpret PDF content streams using
+high-level types.
+
+```
+use hayro_syntax::object::Number;
+use hayro_syntax::content::*;
+use hayro_syntax::content::ops::*;
+
+let content_stream = b"1 0 0 -1 0 200 cm
+0 1.0 0 rg
+0 0 m
+200 0 l
+200 200 l
+0 200 l
+h
+f";
+
+let mut iter = TypedIter::new(content_stream);
+assert!(matches!(iter.next(), Some(TypedInstruction::Transform(_))));
+assert!(matches!(iter.next(), Some(TypedInstruction::NonStrokeColorDeviceRgb(_))));
+assert!(matches!(iter.next(), Some(TypedInstruction::MoveTo(_))));
+assert!(matches!(iter.next(), Some(TypedInstruction::LineTo(_))));
+assert!(matches!(iter.next(), Some(TypedInstruction::LineTo(_))));
+assert!(matches!(iter.next(), Some(TypedInstruction::LineTo(_))));
+assert!(matches!(iter.next(), Some(TypedInstruction::ClosePath(_))));
+assert!(matches!(iter.next(), Some(TypedInstruction::FillPathNonZero(_))));
+```
+*/
+
+#[allow(missing_docs)]
+pub mod ops;
+
+use crate::content::ops::TypedInstruction;
+use crate::object;
+use crate::object::dict::InlineImageDict;
+use crate::object::name::{Name, skip_name_like};
+use crate::object::{Array, Null, Number, Object, Stream};
+use crate::reader::Reader;
+use crate::reader::{Readable, ReaderContext, ReaderExt, Skippable};
+use crate::trivia::is_white_space_character;
+use crate::util::find_needle;
+use core::array;
+use core::fmt::{Debug, Formatter};
+use core::ops::Deref;
+use smallvec::SmallVec;
+
+// 6 operands are used for example for ctm or cubic curves,
+// but anything above should be pretty rare (only for example for
+// DeviceN color spaces, or invalid PDF files). So we settle on 10.
+const OPERANDS_THRESHOLD: usize = 10;
+
+impl Debug for Operator<'_> {
+ fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
+ write!(f, "{}", self.0.as_str())
+ }
+}
+
+/// A content stream operator.
+#[derive(Clone, PartialEq)]
+pub struct Operator<'a>(Name<'a>);
+
+impl Deref for Operator<'_> {
+ type Target = [u8];
+
+ fn deref(&self) -> &Self::Target {
+ self.0.as_ref()
+ }
+}
+
+impl Skippable for Operator<'_> {
+ fn skip(r: &mut Reader<'_>, _: bool) -> Option<()> {
+ skip_name_like(r, false).map(|_| ())
+ }
+}
+
+impl<'a> Readable<'a> for Operator<'a> {
+ fn read(r: &mut Reader<'a>, _: &ReaderContext<'a>) -> Option<Self> {
+ let start = r.offset();
+ skip_name_like(r, false)?;
+ let end = r.offset();
+ let data = r.range(start..end)?;
+
+ if data.is_empty() {
+ return None;
+ }
+
+ Some(Self(Name::new(data)?))
+ }
+}
+
+/// An iterator over operators in the PDF content streams, providing raw access to the instructions.
+#[derive(Clone)]
+pub struct UntypedIter<'a> {
+ reader: Reader<'a>,
+ stack: Stack<'a>,
+ operator: Option<Operator<'a>>,
+}
+
+impl<'a> UntypedIter<'a> {
+ /// Create a new untyped iterator.
+ pub fn new(data: &'a [u8]) -> Self {
+ Self {
+ reader: Reader::new(data),
+ stack: Stack::new(),
+ operator: None,
+ }
+ }
+
+ /// Create a new empty untyped iterator.
+ pub fn empty() -> Self {
+ Self {
+ reader: Reader::new(&[]),
+ stack: Stack::new(),
+ operator: None,
+ }
+ }
+
+ /// Return the next instruction.
+ #[allow(clippy::should_implement_trait)]
+ pub fn next(&mut self) -> Option<Instruction<'_, 'a>> {
+ self.stack.clear();
+ self.operator = None;
+
+ self.reader.skip_white_spaces_and_comments();
+
+ while !self.reader.at_end() {
+ // I believe booleans/null never appear as an operator?
+ if matches!(
+ self.reader.peek_byte()?,
+ b'/' | b'.' | b'+' | b'-' | b'0'..=b'9' | b'[' | b'<' | b'('
+ ) {
+ // See issue 994. In all sane scenarios, if the next byte is a number
+ // it has to be an operand (a number). However, it's possible that
+ // the number is followed by a regular character, in which case it
+ // should behave more like an operator (even though there exists
+ // no operator that starts with a number). In order to preserve
+ // similar behavior to Acrobat and Chromium, we try to consume
+ // such an operator and then simply skip it.
+ if let Some(object) = self.reader.read_without_context::<Object<'_>>() {
+ self.stack.push(object)?;
+ } else if self.reader.read_without_context::<Operator<'_>>().is_some() {
+ self.stack.clear();
+ } else {
+ return None;
+ }
+ } else {
+ let operator = match self.reader.read_without_context::<Operator<'_>>() {
+ Some(o) => o,
+ None => {
+ warn!("failed to read operator in content stream");
+
+ self.reader.jump_to_end();
+ return None;
+ }
+ };
+
+ // Inline images need special casing...
+ if operator.as_ref() == b"BI" {
+ // The ID operator will already be consumed by this.
+ let inline_dict = self.reader.read_without_context::<InlineImageDict<'_>>()?;
+ let dict = inline_dict.get_dict().clone();
+
+ // One whitespace after "ID".
+ self.reader.read_white_space()?;
+
+ let stream_data = self.reader.tail()?;
+ let start_offset = self.reader.offset();
+
+ 'outer: while let Some(pos) = find_needle(self.reader.tail()?, b"EI") {
+ self.reader.read_bytes(pos)?;
+
+ if self.reader.peek_bytes(2) == Some(b"EI") {
+ // If the following character is not a whitespace character, then we are in a ASCII-85 stream.
+ if self
+ .reader
+ .peek_bytes(3)
+ .is_some_and(|b| !is_white_space_character(b[2]))
+ {
+ self.reader.read_bytes(3)?;
+
+ continue;
+ }
+
+ let end_offset = self.reader.offset() - start_offset;
+ let image_data = &stream_data[..end_offset];
+
+ let stream = Stream::new(image_data, dict.clone());
+
+ // Note that there is a possibility that the encoded stream data
+ // contains the "EI" operator as part of the data, in which case we
+ // cannot confidently know whether we have hit the actual end of the
+ // stream. See also <https://github.com/pdf-association/pdf-issues/issues/543>
+ // PDF 2.0 does have a `/Length` attribute we can read, but since it's relatively
+ // new we don't bother trying to read it.
+ let tail = &self.reader.tail()?[2..];
+ let mut find_reader = Reader::new(tail);
+
+ while !find_reader.at_end() {
+ let remaining = find_reader.tail()?;
+ let next_ei = find_needle(remaining, b"EI");
+ let next_bi = find_needle(remaining, b"BI");
+
+ let (next_pos, is_ei) = match (next_ei, next_bi) {
+ (Some(ei), Some(bi)) if ei <= bi => (ei, true),
+ (Some(_), Some(bi)) => (bi, false),
+ (Some(ei), None) => (ei, true),
+ (None, Some(bi)) => (bi, false),
+ (None, None) => break,
+ };
+
+ find_reader.read_bytes(next_pos)?;
+
+ if is_ei {
+ let analyze_data = &tail[..find_reader.offset()];
+
+ // If there is any binary data in-between, we for sure
+ // have not reached the end.
+ if analyze_data.iter().any(|c| !c.is_ascii()) {
+ self.reader.read_bytes(2)?;
+ continue 'outer;
+ }
+
+ // Otherwise, the only possibility that we reached an
+ // "EI", even though the previous one was valid, is
+ // that it's part of a string in the content
+ // stream that follows the inline image. Therefore,
+ // it should be valid to interpret `tail` as a content
+ // stream and there should be at least one text-related
+ // operator that can be parsed correctly.
+
+ let mut iter = TypedIter::new(tail);
+ let mut found = false;
+ let mut counter = 0;
+
+ while let Some(op) = iter.next() {
+ // If we have read more than 20 valid operators, it should be
+ // safe to assume that we are in a content stream, so abort
+ // early. The only situation where this could reasonably
+ // be violated is if we have 20 subsequent instances of
+ // q/Q in the image data, which seems very unlikely.
+ if counter >= 20 {
+ found = true;
+ break;
+ }
+
+ if matches!(
+ op,
+ TypedInstruction::NextLineAndShowText(_)
+ | TypedInstruction::ShowText(_)
+ | TypedInstruction::ShowTexts(_)
+ | TypedInstruction::ShowTextWithParameters(_)
+ ) {
+ // Now it should be safe to assume that the
+ // previous `EI` was the correct one.
+ found = true;
+ break;
+ }
+
+ counter += 1;
+ }
+
+ if !found {
+ // Seems like the data in-between is not a valid content
+ // stream, so we are likely still within the image data.
+ self.reader.read_bytes(2)?;
+ continue 'outer;
+ }
+ } else {
+ // Possibly another inline image, if so, the previously found "EI"
+ // is indeed the end of data.
+ let mut cloned = find_reader.clone();
+ cloned.read_bytes(2)?;
+ if cloned
+ .read_without_context::<InlineImageDict<'_>>()
+ .is_some()
+ {
+ break;
+ }
+ }
+
+ find_reader.read_byte()?;
+ }
+
+ self.stack.push(Object::Stream(stream))?;
+
+ self.reader.read_bytes(2)?;
+ self.reader.skip_white_spaces();
+
+ break;
+ }
+ }
+ }
+
+ self.operator = Some(operator);
+ return Some(Instruction {
+ operands: &self.stack,
+ operator: self.operator.as_ref().unwrap(),
+ });
+ }
+
+ self.reader.skip_white_spaces_and_comments();
+ }
+
+ None
+ }
+}
+
+/// An iterator over PDF content streams that provide access to the instructions
+/// in a typed fashion.
+#[derive(Clone)]
+pub struct TypedIter<'a> {
+ untyped: UntypedIter<'a>,
+}
+
+impl<'a> TypedIter<'a> {
+ /// Create a new typed iterator.
+ pub fn new(data: &'a [u8]) -> Self {
+ Self {
+ untyped: UntypedIter::new(data),
+ }
+ }
+
+ pub(crate) fn from_untyped(untyped: UntypedIter<'a>) -> Self {
+ Self { untyped }
+ }
+
+ /// Return the next typed instruction.
+ #[allow(clippy::should_implement_trait)]
+ pub fn next(&mut self) -> Option<TypedInstruction<'_, 'a>> {
+ let op = self.untyped.next()?;
+ // TODO: Explore whether dispatching can be made more efficient.
+ match TypedInstruction::dispatch(&op) {
+ Some(op) => Some(op),
+ // In case this returns `None`, the content stream is invalid. In case a path-drawing
+ // operator was used, let's abort completely, otherwise we might end up drawing random stuff.
+ // However, for other operators it could be worth it to just skip it but keep attempting
+ // to read other content operators.
+ None => {
+ if [
+ &b"m"[..],
+ &b"l"[..],
+ &b"c"[..],
+ &b"v"[..],
+ &b"y"[..],
+ &b"h"[..],
+ &b"re"[..],
+ ]
+ .contains(&op.operator.0.deref())
+ {
+ None
+ } else {
+ Some(TypedInstruction::Fallback(op.operator))
+ }
+ }
+ }
+ }
+}
+
+/// An instruction (= operator and its operands) in a content stream.
+pub struct Instruction<'b, 'a> {
+ /// The stack containing the operands.
+ pub operands: &'b Stack<'a>,
+ /// The actual operator.
+ pub operator: &'b Operator<'a>,
+}
+
+impl<'b, 'a> Instruction<'b, 'a> {
+ /// An iterator over the operands of the instruction.
+ pub fn operands(&self) -> OperandIterator<'b, 'a> {
+ OperandIterator::new(self.operands)
+ }
+}
+
+/// A stack holding the arguments of an operator.
+pub struct Stack<'a> {
+ // TODO: Explore using an object pool to avoid repeatedly
+ // allocating/deallocating objects.
+ data: [Object<'a>; OPERANDS_THRESHOLD],
+ len: usize,
+}
+
+impl<'a> Default for Stack<'a> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl<'a> Stack<'a> {
+ /// Create a new, empty stack.
+ pub fn new() -> Self {
+ Self {
+ data: array::from_fn(|_| Object::Null(Null)),
+ len: 0,
+ }
+ }
+
+ fn push(&mut self, operand: Object<'a>) -> Option<()> {
+ if self.len >= OPERANDS_THRESHOLD {
+ return None;
+ }
+
+ self.data[self.len] = operand;
+ self.len += 1;
+ Some(())
+ }
+
+ fn clear(&mut self) {
+ self.len = 0;
+ }
+
+ fn len(&self) -> usize {
+ self.len
+ }
+
+ fn as_slice(&self) -> &[Object<'a>] {
+ &self.data[..self.len]
+ }
+
+ fn get<'b, T>(&'b self, index: usize) -> Option<T>
+ where
+ T: Operand<'b, 'a>,
+ {
+ self.as_slice().get(index).and_then(T::from_object)
+ }
+
+ fn get_all<'b, T>(&'b self) -> Option<SmallVec<[T; OPERANDS_THRESHOLD]>>
+ where
+ T: Operand<'b, 'a>,
+ {
+ let mut operands = SmallVec::new();
+
+ for op in self.as_slice() {
+ let converted = T::from_object(op)?;
+ operands.push(converted);
+ }
+
+ Some(operands)
+ }
+}
+
+impl Debug for Stack<'_> {
+ fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
+ f.debug_list().entries(self.as_slice()).finish()
+ }
+}
+
+impl Clone for Stack<'_> {
+ fn clone(&self) -> Self {
+ let mut stack = Self::new();
+ for item in self.as_slice() {
+ stack.push(item.clone()).unwrap();
+ }
+ stack
+ }
+}
+
+impl PartialEq for Stack<'_> {
+ fn eq(&self, other: &Self) -> bool {
+ self.as_slice() == other.as_slice()
+ }
+}
+
+trait Operand<'b, 'a>: Sized {
+ fn from_object(object: &'b Object<'a>) -> Option<Self>;
+}
+
+impl<'b, 'a> Operand<'b, 'a> for Number {
+ fn from_object(object: &'b Object<'a>) -> Option<Self> {
+ match object {
+ Object::Number(n) => Some(*n),
+ _ => None,
+ }
+ }
+}
+
+impl<'b, 'a> Operand<'b, 'a> for &'b object::String<'a> {
+ fn from_object(object: &'b Object<'a>) -> Option<Self> {
+ match object {
+ Object::String(s) => Some(s),
+ _ => None,
+ }
+ }
+}
+
+impl<'b, 'a> Operand<'b, 'a> for &'b Name<'a> {
+ fn from_object(object: &'b Object<'a>) -> Option<Self> {
+ match object {
+ Object::Name(n) => Some(n),
+ _ => None,
+ }
+ }
+}
+
+impl<'b, 'a> Operand<'b, 'a> for &'b Array<'a> {
+ fn from_object(object: &'b Object<'a>) -> Option<Self> {
+ match object {
+ Object::Array(a) => Some(a),
+ _ => None,
+ }
+ }
+}
+
+impl<'b, 'a> Operand<'b, 'a> for &'b Stream<'a> {
+ fn from_object(object: &'b Object<'a>) -> Option<Self> {
+ match object {
+ Object::Stream(s) => Some(s),
+ _ => None,
+ }
+ }
+}
+
+impl<'b, 'a> Operand<'b, 'a> for &'b Object<'a> {
+ fn from_object(object: &'b Object<'a>) -> Option<Self> {
+ Some(object)
+ }
+}
+
+/// An iterator over the operands of an operator.
+pub struct OperandIterator<'b, 'a> {
+ stack: &'b Stack<'a>,
+ cur_index: usize,
+}
+
+impl<'b, 'a> OperandIterator<'b, 'a> {
+ fn new(stack: &'b Stack<'a>) -> Self {
+ Self {
+ stack,
+ cur_index: 0,
+ }
+ }
+}
+
+impl<'b, 'a> Iterator for OperandIterator<'b, 'a> {
+ type Item = &'b Object<'a>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if let Some(item) = self.stack.as_slice().get(self.cur_index) {
+ self.cur_index += 1;
+
+ Some(item)
+ } else {
+ None
+ }
+ }
+}
+
+pub(crate) trait OperatorTrait<'b, 'a>: Sized {
+ const OPERATOR: &'static str;
+
+ fn from_stack(stack: &'b Stack<'a>) -> Option<Self>;
+}
+
+mod macros {
+ macro_rules! op_impl {
+ ($t:ident $(<$($l:lifetime),+>)?, $e:expr, $n:expr, |$stack:ident : $stack_ty:ty| $body:block) => {
+ impl<'b, 'a> OperatorTrait<'b, 'a> for $t$(<$($l),+>)? {
+ const OPERATOR: &'static str = $e;
+
+ #[inline(always)]
+ fn from_stack($stack: $stack_ty) -> Option<Self> {
+ $body.or_else(|| {
+ warn!("failed to convert operands for operator {}", Self::OPERATOR);
+
+ None
+ })
+ }
+ }
+
+ impl<'b, 'a> From<$t$(<$($l),+>)?> for TypedInstruction<'b, 'a> {
+ fn from(value: $t$(<$($l),+>)?) -> Self {
+ TypedInstruction::$t(value)
+ }
+ }
+
+ impl<'b, 'a> TryFrom<TypedInstruction<'b, 'a>> for $t$(<$($l),+>)? {
+ type Error = ();
+
+ fn try_from(value: TypedInstruction<'b, 'a>) -> core::result::Result<Self, Self::Error> {
+ match value {
+ TypedInstruction::$t(e) => Ok(e),
+ _ => Err(())
+ }
+ }
+ }
+ };
+ }
+
+ // The `shift` parameter will always be 0 in valid PDFs. The purpose of the parameter is
+ // so that in case there are garbage operands in the content stream, we prefer to use
+ // the operands that are closer to the operator instead of the values at the bottom
+ // of the stack.
+
+ macro_rules! op0 {
+ ($t:ident $(<$($l:lifetime),+>)?, $e:expr) => {
+ crate::content::macros::op_impl!($t$(<$($l),+>)?, $e, 0, |_stack: &'b Stack<'a>| {
+ Some(Self)
+ });
+ }
+ }
+
+ macro_rules! op1 {
+ ($t:ident $(<$($l:lifetime),+>)?, $e:expr) => {
+ crate::content::macros::op_impl!($t$(<$($l),+>)?, $e, 1, |stack: &'b Stack<'a>| {
+ let shift = stack.len().saturating_sub(1);
+ Some(Self(stack.get(0 + shift)?))
+ });
+ }
+ }
+
+ macro_rules! op_all {
+ ($t:ident $(<$($l:lifetime),+>)?, $e:expr) => {
+ crate::content::macros::op_impl!($t$(<$($l),+>)?, $e, u8::MAX as usize, |stack: &'b Stack<'a>| {
+ Some(Self(stack.get_all()?))
+ });
+ }
+ }
+
+ macro_rules! op2 {
+ ($t:ident $(<$($l:lifetime),+>)?, $e:expr) => {
+ crate::content::macros::op_impl!($t$(<$($l),+>)?, $e, 2, |stack: &'b Stack<'a>| {
+ let shift = stack.len().saturating_sub(2);
+ Some(Self(stack.get(0 + shift)?, stack.get(1 + shift)?))
+ });
+ }
+ }
+
+ macro_rules! op3 {
+ ($t:ident $(<$($l:lifetime),+>)?, $e:expr) => {
+ crate::content::macros::op_impl!($t$(<$($l),+>)?, $e, 3, |stack: &'b Stack<'a>| {
+ let shift = stack.len().saturating_sub(3);
+ Some(Self(stack.get(0 + shift)?, stack.get(1 + shift)?,
+ stack.get(2 + shift)?))
+ });
+ }
+ }
+
+ macro_rules! op4 {
+ ($t:ident $(<$($l:lifetime),+>)?, $e:expr) => {
+ crate::content::macros::op_impl!($t$(<$($l),+>)?, $e, 4, |stack: &'b Stack<'a>| {
+ let shift = stack.len().saturating_sub(4);
+ Some(Self(stack.get(0 + shift)?, stack.get(1 + shift)?,
+ stack.get(2 + shift)?, stack.get(3 + shift)?))
+ });
+ }
+ }
+
+ macro_rules! op6 {
+ ($t:ident $(<$($l:lifetime),+>)?, $e:expr) => {
+ crate::content::macros::op_impl!($t$(<$($l),+>)?, $e, 6, |stack: &'b Stack<'a>| {
+ let shift = stack.len().saturating_sub(6);
+ Some(Self(stack.get(0 + shift)?, stack.get(1 + shift)?,
+ stack.get(2 + shift)?, stack.get(3 + shift)?,
+ stack.get(4 + shift)?, stack.get(5 + shift)?))
+ });
+ }
+ }
+
+ pub(crate) use op_all;
+ pub(crate) use op_impl;
+ pub(crate) use op0;
+ pub(crate) use op1;
+ pub(crate) use op2;
+ pub(crate) use op3;
+ pub(crate) use op4;
+ pub(crate) use op6;
+}
diff --git a/vendor/hayro-syntax/src/content/ops.rs b/vendor/hayro-syntax/src/content/ops.rs
new file mode 100644
index 000000000..b06616584
--- /dev/null
+++ b/vendor/hayro-syntax/src/content/ops.rs
@@ -0,0 +1,259 @@
+//! Content stream operators.
+
+use crate::content::{Instruction, OPERANDS_THRESHOLD, OperatorTrait, Stack};
+use crate::object;
+use crate::object::Array;
+use crate::object::Name;
+use crate::object::Number;
+use crate::object::Object;
+use crate::object::Stream;
+use smallvec::{SmallVec, smallvec};
+
+use crate::content::macros::{op_all, op_impl, op0, op1, op2, op3, op4, op6};
+
+include!("ops_generated.rs");
+
+// Need to special-case those because they have variable arguments.
+
+fn parse_named_color<'b, 'a>(
+ objects: &'b [Object<'a>],
+) -> Option<(SmallVec<[Number; OPERANDS_THRESHOLD]>, Option<&'b Name<'a>>)> {
+ let mut nums = smallvec![];
+ let mut name = None;
+
+ for o in objects {
+ match o {
+ Object::Number(n) => nums.push(*n),
+ Object::Name(n) => name = Some(n),
+ _ => {
+ warn!("encountered unknown object {o:?} when parsing scn/SCN");
+
+ return None;
+ }
+ }
+ }
+
+ Some((nums, name))
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct StrokeColorNamed<'b, 'a>(
+ pub SmallVec<[Number; OPERANDS_THRESHOLD]>,
+ pub Option<&'b Name<'a>>,
+);
+
+op_impl!(
+ StrokeColorNamed<'b, 'a>,
+ "SCN",
+ u8::MAX as usize,
+ |stack: &'b Stack<'a>| {
+ let (nums, name) = parse_named_color(stack.as_slice())?;
+ Some(StrokeColorNamed(nums, name))
+ }
+);
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct NonStrokeColorNamed<'b, 'a>(
+ pub SmallVec<[Number; OPERANDS_THRESHOLD]>,
+ pub Option<&'b Name<'a>>,
+);
+
+op_impl!(
+ NonStrokeColorNamed<'b, 'a>,
+ "scn",
+ u8::MAX as usize,
+ |stack: &'b Stack<'a>| {
+ let (nums, name) = parse_named_color(stack.as_slice())?;
+ Some(NonStrokeColorNamed(nums, name))
+ }
+);
+
+#[cfg(test)]
+mod tests {
+ use crate::content::TypedIter;
+ use crate::content::ops::{
+ BeginMarkedContentWithProperties, ClosePath, EndMarkedContent, FillPathNonZero, LineTo,
+ MarkedContentPointWithProperties, MoveTo, NonStrokeColorDeviceRgb, NonStrokeColorNamed,
+ SetGraphicsState, StrokeColorNamed, Transform, TypedInstruction,
+ };
+ use crate::object::Name;
+ use crate::object::Number;
+ use crate::object::Object;
+ use crate::object::{Dict, FromBytes};
+ fn n(num: i32) -> Number {
+ Number::from_i32(num)
+ }
+
+ #[test]
+ fn basic_ops_1() {
+ let input = b"
+1 0 0 -1 0 200 cm
+/g0 gs
+1 0 0 rg
+";
+
+ let mut iter = TypedIter::new(input);
+
+ assert!(matches!(
+ iter.next(),
+ Some(TypedInstruction::Transform(Transform(a, b, c, d, e, f)))
+ if [a, b, c, d, e, f] == [n(1), n(0), n(0), n(-1), n(0), n(200)]
+ ));
+ assert!(matches!(
+ iter.next(),
+ Some(TypedInstruction::SetGraphicsState(SetGraphicsState(name)))
+ if name.as_ref() == b"g0"
+ ));
+ assert!(matches!(
+ iter.next(),
+ Some(TypedInstruction::NonStrokeColorDeviceRgb(NonStrokeColorDeviceRgb(r, g, b)))
+ if [r, g, b] == [n(1), n(0), n(0)]
+ ));
+ assert!(iter.next().is_none());
+ }
+
+ #[test]
+ fn basic_ops_2() {
+ let input = b"
+20 20 m
+180 20 l
+180 180 l
+20 180 l
+h
+f
+";
+
+ let mut iter = TypedIter::new(input);
+
+ assert!(matches!(
+ iter.next(),
+ Some(TypedInstruction::MoveTo(MoveTo(x, y))) if [x, y] == [n(20), n(20)]
+ ));
+ assert!(matches!(
+ iter.next(),
+ Some(TypedInstruction::LineTo(LineTo(x, y))) if [x, y] == [n(180), n(20)]
+ ));
+ assert!(matches!(
+ iter.next(),
+ Some(TypedInstruction::LineTo(LineTo(x, y))) if [x, y] == [n(180), n(180)]
+ ));
+ assert!(matches!(
+ iter.next(),
+ Some(TypedInstruction::LineTo(LineTo(x, y))) if [x, y] == [n(20), n(180)]
+ ));
+ assert!(matches!(
+ iter.next(),
+ Some(TypedInstruction::ClosePath(ClosePath))
+ ));
+ assert!(matches!(
+ iter.next(),
+ Some(TypedInstruction::FillPathNonZero(FillPathNonZero))
+ ));
+ assert!(iter.next().is_none());
+ }
+
+ #[test]
+ fn scn() {
+ let input = b"
+0.0 scn
+1.0 1.0 1.0 /DeviceRgb SCN
+";
+
+ let mut iter = TypedIter::new(input);
+
+ match iter.next() {
+ Some(TypedInstruction::NonStrokeColorNamed(NonStrokeColorNamed(nums, None))) => {
+ assert_eq!(nums.as_slice(), &[Number::from_f32(0.0)]);
+ }
+ other => panic!("unexpected instruction: {other:?}"),
+ }
+
+ match iter.next() {
+ Some(TypedInstruction::StrokeColorNamed(StrokeColorNamed(nums, Some(name)))) => {
+ assert_eq!(
+ nums.as_slice(),
+ &[
+ Number::from_f32(1.0),
+ Number::from_f32(1.0),
+ Number::from_f32(1.0)
+ ]
+ );
+ assert_eq!(name.as_ref(), b"DeviceRgb");
+ }
+ other => panic!("unexpected instruction: {other:?}"),
+ }
+
+ assert!(iter.next().is_none());
+ }
+
+ #[test]
+ fn dp() {
+ let input = b"/Attribute<</ShowCenterPoint false >> DP";
+
+ let mut iter = TypedIter::new(input);
+
+ match iter.next() {
+ Some(TypedInstruction::MarkedContentPointWithProperties(
+ MarkedContentPointWithProperties(name, object),
+ )) => {
+ assert_eq!(name.as_ref(), b"Attribute");
+ assert_eq!(
+ object,
+ &Object::Dict(Dict::from_bytes(b"<</ShowCenterPoint false >>").unwrap())
+ );
+ }
+ other => panic!("unexpected instruction: {other:?}"),
+ }
+
+ assert!(iter.next().is_none());
+ }
+
+ #[test]
+ fn bdc_with_dict() {
+ let input = b"/Span << /MCID 0 /Alt (Alt)>> BDC EMC";
+
+ let mut iter = TypedIter::new(input);
+
+ match iter.next() {
+ Some(TypedInstruction::BeginMarkedContentWithProperties(
+ BeginMarkedContentWithProperties(name, object),
+ )) => {
+ assert_eq!(name.as_ref(), b"Span");
+ assert_eq!(
+ object,
+ &Object::Dict(Dict::from_bytes(b"<< /MCID 0 /Alt (Alt)>>").unwrap())
+ );
+ }
+ other => panic!("unexpected instruction: {other:?}"),
+ }
+
+ assert!(matches!(
+ iter.next(),
+ Some(TypedInstruction::EndMarkedContent(EndMarkedContent))
+ ));
+ assert!(iter.next().is_none());
+ }
+
+ #[test]
+ fn bdc_with_name() {
+ let input = b"/Span /Name BDC EMC";
+
+ let mut iter = TypedIter::new(input);
+
+ match iter.next() {
+ Some(TypedInstruction::BeginMarkedContentWithProperties(
+ BeginMarkedContentWithProperties(name, object),
+ )) => {
+ assert_eq!(name.as_ref(), b"Span");
+ assert_eq!(object, &Object::Name(Name::new_unescaped(b"Name")));
+ }
+ other => panic!("unexpected instruction: {other:?}"),
+ }
+
+ assert!(matches!(
+ iter.next(),
+ Some(TypedInstruction::EndMarkedContent(EndMarkedContent))
+ ));
+ assert!(iter.next().is_none());
+ }
+}
diff --git a/vendor/hayro-syntax/src/content/ops_generated.rs b/vendor/hayro-syntax/src/content/ops_generated.rs
new file mode 100644
index 000000000..1028193c9
--- /dev/null
+++ b/vendor/hayro-syntax/src/content/ops_generated.rs
@@ -0,0 +1,528 @@
+// THIS FILE IS AUTO-GENERATED, DO NOT EDIT MANUALLY
+
+use crate::content::Operator;
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct BeginCompatibility;
+op0!(BeginCompatibility, "BX");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct EndCompatibility;
+op0!(EndCompatibility, "EX");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct SaveState;
+op0!(SaveState, "q");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct RestoreState;
+op0!(RestoreState, "Q");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct Transform(
+ pub Number,
+ pub Number,
+ pub Number,
+ pub Number,
+ pub Number,
+ pub Number,
+);
+op6!(Transform, "cm");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct LineWidth(pub Number);
+op1!(LineWidth, "w");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct LineCap(pub Number);
+op1!(LineCap, "J");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct LineJoin(pub Number);
+op1!(LineJoin, "j");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct MiterLimit(pub Number);
+op1!(MiterLimit, "M");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct DashPattern<'b, 'a>(
+ pub &'b Array<'a>,
+ pub Number,
+);
+op2!(DashPattern<'b, 'a>, "d");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct RenderingIntent<'b, 'a>(pub &'b Name<'a>);
+op1!(RenderingIntent<'b, 'a>, "ri");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct FlatnessTolerance(pub Number);
+op1!(FlatnessTolerance, "i");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct SetGraphicsState<'b, 'a>(pub &'b Name<'a>);
+op1!(SetGraphicsState<'b, 'a>, "gs");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct MoveTo(
+ pub Number,
+ pub Number,
+);
+op2!(MoveTo, "m");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct LineTo(
+ pub Number,
+ pub Number,
+);
+op2!(LineTo, "l");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct CubicTo(
+ pub Number,
+ pub Number,
+ pub Number,
+ pub Number,
+ pub Number,
+ pub Number,
+);
+op6!(CubicTo, "c");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct CubicStartTo(
+ pub Number,
+ pub Number,
+ pub Number,
+ pub Number,
+);
+op4!(CubicStartTo, "v");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct CubicEndTo(
+ pub Number,
+ pub Number,
+ pub Number,
+ pub Number,
+);
+op4!(CubicEndTo, "y");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct ClosePath;
+op0!(ClosePath, "h");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct RectPath(
+ pub Number,
+ pub Number,
+ pub Number,
+ pub Number,
+);
+op4!(RectPath, "re");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct StrokePath;
+op0!(StrokePath, "S");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct CloseAndStrokePath;
+op0!(CloseAndStrokePath, "s");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct FillPathNonZero;
+op0!(FillPathNonZero, "f");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct FillPathNonZeroCompatibility;
+op0!(FillPathNonZeroCompatibility, "F");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct FillPathEvenOdd;
+op0!(FillPathEvenOdd, "f*");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct FillAndStrokeNonZero;
+op0!(FillAndStrokeNonZero, "B");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct FillAndStrokeEvenOdd;
+op0!(FillAndStrokeEvenOdd, "B*");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct CloseFillAndStrokeNonZero;
+op0!(CloseFillAndStrokeNonZero, "b");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct CloseFillAndStrokeEvenOdd;
+op0!(CloseFillAndStrokeEvenOdd, "b*");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct EndPath;
+op0!(EndPath, "n");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct ClipNonZero;
+op0!(ClipNonZero, "W");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct ClipEvenOdd;
+op0!(ClipEvenOdd, "W*");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct ColorSpaceStroke<'b, 'a>(pub &'b Name<'a>);
+op1!(ColorSpaceStroke<'b, 'a>, "CS");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct ColorSpaceNonStroke<'b, 'a>(pub &'b Name<'a>);
+op1!(ColorSpaceNonStroke<'b, 'a>, "cs");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct StrokeColor(pub SmallVec<[Number; OPERANDS_THRESHOLD]>);
+op_all!(StrokeColor, "SC");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct NonStrokeColor(pub SmallVec<[Number; OPERANDS_THRESHOLD]>);
+op_all!(NonStrokeColor, "sc");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct StrokeColorDeviceGray(pub Number);
+op1!(StrokeColorDeviceGray, "G");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct NonStrokeColorDeviceGray(pub Number);
+op1!(NonStrokeColorDeviceGray, "g");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct StrokeColorDeviceRgb(
+ pub Number,
+ pub Number,
+ pub Number,
+);
+op3!(StrokeColorDeviceRgb, "RG");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct NonStrokeColorDeviceRgb(
+ pub Number,
+ pub Number,
+ pub Number,
+);
+op3!(NonStrokeColorDeviceRgb, "rg");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct StrokeColorCmyk(
+ pub Number,
+ pub Number,
+ pub Number,
+ pub Number,
+);
+op4!(StrokeColorCmyk, "K");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct NonStrokeColorCmyk(
+ pub Number,
+ pub Number,
+ pub Number,
+ pub Number,
+);
+op4!(NonStrokeColorCmyk, "k");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct Shading<'b, 'a>(pub &'b Name<'a>);
+op1!(Shading<'b, 'a>, "sh");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct XObject<'b, 'a>(pub &'b Name<'a>);
+op1!(XObject<'b, 'a>, "Do");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct InlineImage<'b, 'a>(pub &'b Stream<'a>);
+op1!(InlineImage<'b, 'a>, "BI");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct CharacterSpacing(pub Number);
+op1!(CharacterSpacing, "Tc");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct WordSpacing(pub Number);
+op1!(WordSpacing, "Tw");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct HorizontalScaling(pub Number);
+op1!(HorizontalScaling, "Tz");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct TextLeading(pub Number);
+op1!(TextLeading, "TL");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct TextFont<'b, 'a>(
+ pub &'b Name<'a>,
+ pub Number,
+);
+op2!(TextFont<'b, 'a>, "Tf");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct TextRenderingMode(pub Number);
+op1!(TextRenderingMode, "Tr");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct TextRise(pub Number);
+op1!(TextRise, "Ts");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct BeginText;
+op0!(BeginText, "BT");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct EndText;
+op0!(EndText, "ET");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct NextLine(
+ pub Number,
+ pub Number,
+);
+op2!(NextLine, "Td");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct NextLineAndSetLeading(
+ pub Number,
+ pub Number,
+);
+op2!(NextLineAndSetLeading, "TD");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct SetTextMatrix(
+ pub Number,
+ pub Number,
+ pub Number,
+ pub Number,
+ pub Number,
+ pub Number,
+);
+op6!(SetTextMatrix, "Tm");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct NextLineUsingLeading;
+op0!(NextLineUsingLeading, "T*");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct ShowText<'b, 'a>(pub &'b object::String<'a>);
+op1!(ShowText<'b, 'a>, "Tj");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct NextLineAndShowText<'b, 'a>(pub &'b object::String<'a>);
+op1!(NextLineAndShowText<'b, 'a>, "'");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct ShowTextWithParameters<'b, 'a>(
+ pub Number,
+ pub Number,
+ pub &'b object::String<'a>,
+);
+op3!(ShowTextWithParameters<'b, 'a>, "\"");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct ShowTexts<'b, 'a>(pub &'b Array<'a>);
+op1!(ShowTexts<'b, 'a>, "TJ");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct ColorGlyph(
+ pub Number,
+ pub Number,
+);
+op2!(ColorGlyph, "d0");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct ShapeGlyph(
+ pub Number,
+ pub Number,
+ pub Number,
+ pub Number,
+ pub Number,
+ pub Number,
+);
+op6!(ShapeGlyph, "d1");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct MarkedContentPoint<'b, 'a>(pub &'b Name<'a>);
+op1!(MarkedContentPoint<'b, 'a>, "MP");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct MarkedContentPointWithProperties<'b, 'a>(
+ pub &'b Name<'a>,
+ pub &'b Object<'a>,
+);
+op2!(MarkedContentPointWithProperties<'b, 'a>, "DP");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct BeginMarkedContent<'b, 'a>(pub &'b Name<'a>);
+op1!(BeginMarkedContent<'b, 'a>, "BMC");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct BeginMarkedContentWithProperties<'b, 'a>(
+ pub &'b Name<'a>,
+ pub &'b Object<'a>,
+);
+op2!(BeginMarkedContentWithProperties<'b, 'a>, "BDC");
+
+#[derive(Debug, PartialEq, Clone)]
+pub struct EndMarkedContent;
+op0!(EndMarkedContent, "EMC");
+
+#[derive(Debug, PartialEq, Clone)]
+pub enum TypedInstruction<'b, 'a> {
+ BeginCompatibility(BeginCompatibility),
+ EndCompatibility(EndCompatibility),
+ SaveState(SaveState),
+ RestoreState(RestoreState),
+ Transform(Transform),
+ LineWidth(LineWidth),
+ LineCap(LineCap),
+ LineJoin(LineJoin),
+ MiterLimit(MiterLimit),
+ DashPattern(DashPattern<'b, 'a>),
+ RenderingIntent(RenderingIntent<'b, 'a>),
+ FlatnessTolerance(FlatnessTolerance),
+ SetGraphicsState(SetGraphicsState<'b, 'a>),
+ MoveTo(MoveTo),
+ LineTo(LineTo),
+ CubicTo(CubicTo),
+ CubicStartTo(CubicStartTo),
+ CubicEndTo(CubicEndTo),
+ ClosePath(ClosePath),
+ RectPath(RectPath),
+ StrokePath(StrokePath),
+ CloseAndStrokePath(CloseAndStrokePath),
+ FillPathNonZero(FillPathNonZero),
+ FillPathNonZeroCompatibility(FillPathNonZeroCompatibility),
+ FillPathEvenOdd(FillPathEvenOdd),
+ FillAndStrokeNonZero(FillAndStrokeNonZero),
+ FillAndStrokeEvenOdd(FillAndStrokeEvenOdd),
+ CloseFillAndStrokeNonZero(CloseFillAndStrokeNonZero),
+ CloseFillAndStrokeEvenOdd(CloseFillAndStrokeEvenOdd),
+ EndPath(EndPath),
+ ClipNonZero(ClipNonZero),
+ ClipEvenOdd(ClipEvenOdd),
+ ColorSpaceStroke(ColorSpaceStroke<'b, 'a>),
+ ColorSpaceNonStroke(ColorSpaceNonStroke<'b, 'a>),
+ StrokeColor(StrokeColor),
+ StrokeColorNamed(StrokeColorNamed<'b, 'a>),
+ NonStrokeColor(NonStrokeColor),
+ NonStrokeColorNamed(NonStrokeColorNamed<'b, 'a>),
+ StrokeColorDeviceGray(StrokeColorDeviceGray),
+ NonStrokeColorDeviceGray(NonStrokeColorDeviceGray),
+ StrokeColorDeviceRgb(StrokeColorDeviceRgb),
+ NonStrokeColorDeviceRgb(NonStrokeColorDeviceRgb),
+ StrokeColorCmyk(StrokeColorCmyk),
+ NonStrokeColorCmyk(NonStrokeColorCmyk),
+ Shading(Shading<'b, 'a>),
+ XObject(XObject<'b, 'a>),
+ InlineImage(InlineImage<'b, 'a>),
+ CharacterSpacing(CharacterSpacing),
+ WordSpacing(WordSpacing),
+ HorizontalScaling(HorizontalScaling),
+ TextLeading(TextLeading),
+ TextFont(TextFont<'b, 'a>),
+ TextRenderingMode(TextRenderingMode),
+ TextRise(TextRise),
+ BeginText(BeginText),
+ EndText(EndText),
+ NextLine(NextLine),
+ NextLineAndSetLeading(NextLineAndSetLeading),
+ SetTextMatrix(SetTextMatrix),
+ NextLineUsingLeading(NextLineUsingLeading),
+ ShowText(ShowText<'b, 'a>),
+ NextLineAndShowText(NextLineAndShowText<'b, 'a>),
+ ShowTextWithParameters(ShowTextWithParameters<'b, 'a>),
+ ShowTexts(ShowTexts<'b, 'a>),
+ ColorGlyph(ColorGlyph),
+ ShapeGlyph(ShapeGlyph),
+ MarkedContentPoint(MarkedContentPoint<'b, 'a>),
+ MarkedContentPointWithProperties(MarkedContentPointWithProperties<'b, 'a>),
+ BeginMarkedContent(BeginMarkedContent<'b, 'a>),
+ BeginMarkedContentWithProperties(BeginMarkedContentWithProperties<'b, 'a>),
+ EndMarkedContent(EndMarkedContent),
+ Fallback(&'b Operator<'a>),
+}
+
+impl<'b, 'a> TypedInstruction<'b, 'a> {
+ #[inline(always)]
+ pub(crate) fn dispatch(instruction: &Instruction<'b, 'a>) -> Option<Self> {
+ let op_name = instruction.operator.as_ref();
+ Some(match op_name {
+ b"BX" => BeginCompatibility::from_stack(instruction.operands)?.into(),
+ b"EX" => EndCompatibility::from_stack(instruction.operands)?.into(),
+ b"q" => SaveState::from_stack(instruction.operands)?.into(),
+ b"Q" => RestoreState::from_stack(instruction.operands)?.into(),
+ b"cm" => Transform::from_stack(instruction.operands)?.into(),
+ b"w" => LineWidth::from_stack(instruction.operands)?.into(),
+ b"J" => LineCap::from_stack(instruction.operands)?.into(),
+ b"j" => LineJoin::from_stack(instruction.operands)?.into(),
+ b"M" => MiterLimit::from_stack(instruction.operands)?.into(),
+ b"d" => DashPattern::from_stack(instruction.operands)?.into(),
+ b"ri" => RenderingIntent::from_stack(instruction.operands)?.into(),
+ b"i" => FlatnessTolerance::from_stack(instruction.operands)?.into(),
+ b"gs" => SetGraphicsState::from_stack(instruction.operands)?.into(),
+ b"m" => MoveTo::from_stack(instruction.operands)?.into(),
+ b"l" => LineTo::from_stack(instruction.operands)?.into(),
+ b"c" => CubicTo::from_stack(instruction.operands)?.into(),
+ b"v" => CubicStartTo::from_stack(instruction.operands)?.into(),
+ b"y" => CubicEndTo::from_stack(instruction.operands)?.into(),
+ b"h" => ClosePath::from_stack(instruction.operands)?.into(),
+ b"re" => RectPath::from_stack(instruction.operands)?.into(),
+ b"S" => StrokePath::from_stack(instruction.operands)?.into(),
+ b"s" => CloseAndStrokePath::from_stack(instruction.operands)?.into(),
+ b"f" => FillPathNonZero::from_stack(instruction.operands)?.into(),
+ b"F" => FillPathNonZeroCompatibility::from_stack(instruction.operands)?.into(),
+ b"f*" => FillPathEvenOdd::from_stack(instruction.operands)?.into(),
+ b"B" => FillAndStrokeNonZero::from_stack(instruction.operands)?.into(),
+ b"B*" => FillAndStrokeEvenOdd::from_stack(instruction.operands)?.into(),
+ b"b" => CloseFillAndStrokeNonZero::from_stack(instruction.operands)?.into(),
+ b"b*" => CloseFillAndStrokeEvenOdd::from_stack(instruction.operands)?.into(),
+ b"n" => EndPath::from_stack(instruction.operands)?.into(),
+ b"W" => ClipNonZero::from_stack(instruction.operands)?.into(),
+ b"W*" => ClipEvenOdd::from_stack(instruction.operands)?.into(),
+ b"CS" => ColorSpaceStroke::from_stack(instruction.operands)?.into(),
+ b"cs" => ColorSpaceNonStroke::from_stack(instruction.operands)?.into(),
+ b"SC" => StrokeColor::from_stack(instruction.operands)?.into(),
+ b"SCN" => StrokeColorNamed::from_stack(instruction.operands)?.into(),
+ b"sc" => NonStrokeColor::from_stack(instruction.operands)?.into(),
+ b"scn" => NonStrokeColorNamed::from_stack(instruction.operands)?.into(),
+ b"G" => StrokeColorDeviceGray::from_stack(instruction.operands)?.into(),
+ b"g" => NonStrokeColorDeviceGray::from_stack(instruction.operands)?.into(),
+ b"RG" => StrokeColorDeviceRgb::from_stack(instruction.operands)?.into(),
+ b"rg" => NonStrokeColorDeviceRgb::from_stack(instruction.operands)?.into(),
+ b"K" => StrokeColorCmyk::from_stack(instruction.operands)?.into(),
+ b"k" => NonStrokeColorCmyk::from_stack(instruction.operands)?.into(),
+ b"sh" => Shading::from_stack(instruction.operands)?.into(),
+ b"Do" => XObject::from_stack(instruction.operands)?.into(),
+ b"BI" => InlineImage::from_stack(instruction.operands)?.into(),
+ b"Tc" => CharacterSpacing::from_stack(instruction.operands)?.into(),
+ b"Tw" => WordSpacing::from_stack(instruction.operands)?.into(),
+ b"Tz" => HorizontalScaling::from_stack(instruction.operands)?.into(),
+ b"TL" => TextLeading::from_stack(instruction.operands)?.into(),
+ b"Tf" => TextFont::from_stack(instruction.operands)?.into(),
+ b"Tr" => TextRenderingMode::from_stack(instruction.operands)?.into(),
+ b"Ts" => TextRise::from_stack(instruction.operands)?.into(),
+ b"BT" => BeginText::from_stack(instruction.operands)?.into(),
+ b"ET" => EndText::from_stack(instruction.operands)?.into(),
+ b"Td" => NextLine::from_stack(instruction.operands)?.into(),
+ b"TD" => NextLineAndSetLeading::from_stack(instruction.operands)?.into(),
+ b"Tm" => SetTextMatrix::from_stack(instruction.operands)?.into(),
+ b"T*" => NextLineUsingLeading::from_stack(instruction.operands)?.into(),
+ b"Tj" => ShowText::from_stack(instruction.operands)?.into(),
+ b"'" => NextLineAndShowText::from_stack(instruction.operands)?.into(),
+ b"\"" => ShowTextWithParameters::from_stack(instruction.operands)?.into(),
+ b"TJ" => ShowTexts::from_stack(instruction.operands)?.into(),
+ b"d0" => ColorGlyph::from_stack(instruction.operands)?.into(),
+ b"d1" => ShapeGlyph::from_stack(instruction.operands)?.into(),
+ b"MP" => MarkedContentPoint::from_stack(instruction.operands)?.into(),
+ b"DP" => MarkedContentPointWithProperties::from_stack(instruction.operands)?.into(),
+ b"BMC" => BeginMarkedContent::from_stack(instruction.operands)?.into(),
+ b"BDC" => BeginMarkedContentWithProperties::from_stack(instruction.operands)?.into(),
+ b"EMC" => EndMarkedContent::from_stack(instruction.operands)?.into(),
+ _ => return Some(Self::Fallback(instruction.operator)),
+ })
+ }
+}
\ No newline at end of file
diff --git a/vendor/hayro-syntax/src/crypto/aes.rs b/vendor/hayro-syntax/src/crypto/aes.rs
new file mode 100644
index 000000000..9d4abad3d
--- /dev/null
+++ b/vendor/hayro-syntax/src/crypto/aes.rs
@@ -0,0 +1,819 @@
+//! Ported from <https://github.com/mozilla/pdf.js/blob/master/src/core/crypto.js>.
+
+// TODO: Explore performance improvements.
+
+use alloc::vec;
+use alloc::vec::Vec;
+
+const S_BOX: [u8; 256] = [
+ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
+ 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
+ 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
+ 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
+ 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
+ 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
+ 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
+ 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
+ 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
+ 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
+ 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
+ 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
+ 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
+ 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
+ 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
+ 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,
+];
+
+const INV_S_BOX: [u8; 256] = [
+ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
+ 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
+ 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
+ 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
+ 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
+ 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
+ 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
+ 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
+ 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
+ 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
+ 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
+ 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
+ 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
+ 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
+ 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
+ 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d,
+];
+
+const RCON: [u8; 10] = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
+
+const MUL2: [u8; 256] = [
+ 0x00, 0x02, 0x04, 0x06, 0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1a, 0x1c, 0x1e,
+ 0x20, 0x22, 0x24, 0x26, 0x28, 0x2a, 0x2c, 0x2e, 0x30, 0x32, 0x34, 0x36, 0x38, 0x3a, 0x3c, 0x3e,
+ 0x40, 0x42, 0x44, 0x46, 0x48, 0x4a, 0x4c, 0x4e, 0x50, 0x52, 0x54, 0x56, 0x58, 0x5a, 0x5c, 0x5e,
+ 0x60, 0x62, 0x64, 0x66, 0x68, 0x6a, 0x6c, 0x6e, 0x70, 0x72, 0x74, 0x76, 0x78, 0x7a, 0x7c, 0x7e,
+ 0x80, 0x82, 0x84, 0x86, 0x88, 0x8a, 0x8c, 0x8e, 0x90, 0x92, 0x94, 0x96, 0x98, 0x9a, 0x9c, 0x9e,
+ 0xa0, 0xa2, 0xa4, 0xa6, 0xa8, 0xaa, 0xac, 0xae, 0xb0, 0xb2, 0xb4, 0xb6, 0xb8, 0xba, 0xbc, 0xbe,
+ 0xc0, 0xc2, 0xc4, 0xc6, 0xc8, 0xca, 0xcc, 0xce, 0xd0, 0xd2, 0xd4, 0xd6, 0xd8, 0xda, 0xdc, 0xde,
+ 0xe0, 0xe2, 0xe4, 0xe6, 0xe8, 0xea, 0xec, 0xee, 0xf0, 0xf2, 0xf4, 0xf6, 0xf8, 0xfa, 0xfc, 0xfe,
+ 0x1b, 0x19, 0x1f, 0x1d, 0x13, 0x11, 0x17, 0x15, 0x0b, 0x09, 0x0f, 0x0d, 0x03, 0x01, 0x07, 0x05,
+ 0x3b, 0x39, 0x3f, 0x3d, 0x33, 0x31, 0x37, 0x35, 0x2b, 0x29, 0x2f, 0x2d, 0x23, 0x21, 0x27, 0x25,
+ 0x5b, 0x59, 0x5f, 0x5d, 0x53, 0x51, 0x57, 0x55, 0x4b, 0x49, 0x4f, 0x4d, 0x43, 0x41, 0x47, 0x45,
+ 0x7b, 0x79, 0x7f, 0x7d, 0x73, 0x71, 0x77, 0x75, 0x6b, 0x69, 0x6f, 0x6d, 0x63, 0x61, 0x67, 0x65,
+ 0x9b, 0x99, 0x9f, 0x9d, 0x93, 0x91, 0x97, 0x95, 0x8b, 0x89, 0x8f, 0x8d, 0x83, 0x81, 0x87, 0x85,
+ 0xbb, 0xb9, 0xbf, 0xbd, 0xb3, 0xb1, 0xb7, 0xb5, 0xab, 0xa9, 0xaf, 0xad, 0xa3, 0xa1, 0xa7, 0xa5,
+ 0xdb, 0xd9, 0xdf, 0xdd, 0xd3, 0xd1, 0xd7, 0xd5, 0xcb, 0xc9, 0xcf, 0xcd, 0xc3, 0xc1, 0xc7, 0xc5,
+ 0xfb, 0xf9, 0xff, 0xfd, 0xf3, 0xf1, 0xf7, 0xf5, 0xeb, 0xe9, 0xef, 0xed, 0xe3, 0xe1, 0xe7, 0xe5,
+];
+
+const MUL3: [u8; 256] = [
+ 0x00, 0x03, 0x06, 0x05, 0x0c, 0x0f, 0x0a, 0x09, 0x18, 0x1b, 0x1e, 0x1d, 0x14, 0x17, 0x12, 0x11,
+ 0x30, 0x33, 0x36, 0x35, 0x3c, 0x3f, 0x3a, 0x39, 0x28, 0x2b, 0x2e, 0x2d, 0x24, 0x27, 0x22, 0x21,
+ 0x60, 0x63, 0x66, 0x65, 0x6c, 0x6f, 0x6a, 0x69, 0x78, 0x7b, 0x7e, 0x7d, 0x74, 0x77, 0x72, 0x71,
+ 0x50, 0x53, 0x56, 0x55, 0x5c, 0x5f, 0x5a, 0x59, 0x48, 0x4b, 0x4e, 0x4d, 0x44, 0x47, 0x42, 0x41,
+ 0xc0, 0xc3, 0xc6, 0xc5, 0xcc, 0xcf, 0xca, 0xc9, 0xd8, 0xdb, 0xde, 0xdd, 0xd4, 0xd7, 0xd2, 0xd1,
+ 0xf0, 0xf3, 0xf6, 0xf5, 0xfc, 0xff, 0xfa, 0xf9, 0xe8, 0xeb, 0xee, 0xed, 0xe4, 0xe7, 0xe2, 0xe1,
+ 0xa0, 0xa3, 0xa6, 0xa5, 0xac, 0xaf, 0xaa, 0xa9, 0xb8, 0xbb, 0xbe, 0xbd, 0xb4, 0xb7, 0xb2, 0xb1,
+ 0x90, 0x93, 0x96, 0x95, 0x9c, 0x9f, 0x9a, 0x99, 0x88, 0x8b, 0x8e, 0x8d, 0x84, 0x87, 0x82, 0x81,
+ 0x9b, 0x98, 0x9d, 0x9e, 0x97, 0x94, 0x91, 0x92, 0x83, 0x80, 0x85, 0x86, 0x8f, 0x8c, 0x89, 0x8a,
+ 0xab, 0xa8, 0xad, 0xae, 0xa7, 0xa4, 0xa1, 0xa2, 0xb3, 0xb0, 0xb5, 0xb6, 0xbf, 0xbc, 0xb9, 0xba,
+ 0xfb, 0xf8, 0xfd, 0xfe, 0xf7, 0xf4, 0xf1, 0xf2, 0xe3, 0xe0, 0xe5, 0xe6, 0xef, 0xec, 0xe9, 0xea,
+ 0xcb, 0xc8, 0xcd, 0xce, 0xc7, 0xc4, 0xc1, 0xc2, 0xd3, 0xd0, 0xd5, 0xd6, 0xdf, 0xdc, 0xd9, 0xda,
+ 0x5b, 0x58, 0x5d, 0x5e, 0x57, 0x54, 0x51, 0x52, 0x43, 0x40, 0x45, 0x46, 0x4f, 0x4c, 0x49, 0x4a,
+ 0x6b, 0x68, 0x6d, 0x6e, 0x67, 0x64, 0x61, 0x62, 0x73, 0x70, 0x75, 0x76, 0x7f, 0x7c, 0x79, 0x7a,
+ 0x3b, 0x38, 0x3d, 0x3e, 0x37, 0x34, 0x31, 0x32, 0x23, 0x20, 0x25, 0x26, 0x2f, 0x2c, 0x29, 0x2a,
+ 0x0b, 0x08, 0x0d, 0x0e, 0x07, 0x04, 0x01, 0x02, 0x13, 0x10, 0x15, 0x16, 0x1f, 0x1c, 0x19, 0x1a,
+];
+
+const MUL9: [u8; 256] = [
+ 0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f, 0x48, 0x41, 0x5a, 0x53, 0x6c, 0x65, 0x7e, 0x77,
+ 0x90, 0x99, 0x82, 0x8b, 0xb4, 0xbd, 0xa6, 0xaf, 0xd8, 0xd1, 0xca, 0xc3, 0xfc, 0xf5, 0xee, 0xe7,
+ 0x3b, 0x32, 0x29, 0x20, 0x1f, 0x16, 0x0d, 0x04, 0x73, 0x7a, 0x61, 0x68, 0x57, 0x5e, 0x45, 0x4c,
+ 0xab, 0xa2, 0xb9, 0xb0, 0x8f, 0x86, 0x9d, 0x94, 0xe3, 0xea, 0xf1, 0xf8, 0xc7, 0xce, 0xd5, 0xdc,
+ 0x76, 0x7f, 0x64, 0x6d, 0x52, 0x5b, 0x40, 0x49, 0x3e, 0x37, 0x2c, 0x25, 0x1a, 0x13, 0x08, 0x01,
+ 0xe6, 0xef, 0xf4, 0xfd, 0xc2, 0xcb, 0xd0, 0xd9, 0xae, 0xa7, 0xbc, 0xb5, 0x8a, 0x83, 0x98, 0x91,
+ 0x4d, 0x44, 0x5f, 0x56, 0x69, 0x60, 0x7b, 0x72, 0x05, 0x0c, 0x17, 0x1e, 0x21, 0x28, 0x33, 0x3a,
+ 0xdd, 0xd4, 0xcf, 0xc6, 0xf9, 0xf0, 0xeb, 0xe2, 0x95, 0x9c, 0x87, 0x8e, 0xb1, 0xb8, 0xa3, 0xaa,
+ 0xec, 0xe5, 0xfe, 0xf7, 0xc8, 0xc1, 0xda, 0xd3, 0xa4, 0xad, 0xb6, 0xbf, 0x80, 0x89, 0x92, 0x9b,
+ 0x7c, 0x75, 0x6e, 0x67, 0x58, 0x51, 0x4a, 0x43, 0x34, 0x3d, 0x26, 0x2f, 0x10, 0x19, 0x02, 0x0b,
+ 0xd7, 0xde, 0xc5, 0xcc, 0xf3, 0xfa, 0xe1, 0xe8, 0x9f, 0x96, 0x8d, 0x84, 0xbb, 0xb2, 0xa9, 0xa0,
+ 0x47, 0x4e, 0x55, 0x5c, 0x63, 0x6a, 0x71, 0x78, 0x0f, 0x06, 0x1d, 0x14, 0x2b, 0x22, 0x39, 0x30,
+ 0x9a, 0x93, 0x88, 0x81, 0xbe, 0xb7, 0xac, 0xa5, 0xd2, 0xdb, 0xc0, 0xc9, 0xf6, 0xff, 0xe4, 0xed,
+ 0x0a, 0x03, 0x18, 0x11, 0x2e, 0x27, 0x3c, 0x35, 0x42, 0x4b, 0x50, 0x59, 0x66, 0x6f, 0x74, 0x7d,
+ 0xa1, 0xa8, 0xb3, 0xba, 0x85, 0x8c, 0x97, 0x9e, 0xe9, 0xe0, 0xfb, 0xf2, 0xcd, 0xc4, 0xdf, 0xd6,
+ 0x31, 0x38, 0x23, 0x2a, 0x15, 0x1c, 0x07, 0x0e, 0x79, 0x70, 0x6b, 0x62, 0x5d, 0x54, 0x4f, 0x46,
+];
+
+const MUL11: [u8; 256] = [
+ 0x00, 0x0b, 0x16, 0x1d, 0x2c, 0x27, 0x3a, 0x31, 0x58, 0x53, 0x4e, 0x45, 0x74, 0x7f, 0x62, 0x69,
+ 0xb0, 0xbb, 0xa6, 0xad, 0x9c, 0x97, 0x8a, 0x81, 0xe8, 0xe3, 0xfe, 0xf5, 0xc4, 0xcf, 0xd2, 0xd9,
+ 0x7b, 0x70, 0x6d, 0x66, 0x57, 0x5c, 0x41, 0x4a, 0x23, 0x28, 0x35, 0x3e, 0x0f, 0x04, 0x19, 0x12,
+ 0xcb, 0xc0, 0xdd, 0xd6, 0xe7, 0xec, 0xf1, 0xfa, 0x93, 0x98, 0x85, 0x8e, 0xbf, 0xb4, 0xa9, 0xa2,
+ 0xf6, 0xfd, 0xe0, 0xeb, 0xda, 0xd1, 0xcc, 0xc7, 0xae, 0xa5, 0xb8, 0xb3, 0x82, 0x89, 0x94, 0x9f,
+ 0x46, 0x4d, 0x50, 0x5b, 0x6a, 0x61, 0x7c, 0x77, 0x1e, 0x15, 0x08, 0x03, 0x32, 0x39, 0x24, 0x2f,
+ 0x8d, 0x86, 0x9b, 0x90, 0xa1, 0xaa, 0xb7, 0xbc, 0xd5, 0xde, 0xc3, 0xc8, 0xf9, 0xf2, 0xef, 0xe4,
+ 0x3d, 0x36, 0x2b, 0x20, 0x11, 0x1a, 0x07, 0x0c, 0x65, 0x6e, 0x73, 0x78, 0x49, 0x42, 0x5f, 0x54,
+ 0xf7, 0xfc, 0xe1, 0xea, 0xdb, 0xd0, 0xcd, 0xc6, 0xaf, 0xa4, 0xb9, 0xb2, 0x83, 0x88, 0x95, 0x9e,
+ 0x47, 0x4c, 0x51, 0x5a, 0x6b, 0x60, 0x7d, 0x76, 0x1f, 0x14, 0x09, 0x02, 0x33, 0x38, 0x25, 0x2e,
+ 0x8c, 0x87, 0x9a, 0x91, 0xa0, 0xab, 0xb6, 0xbd, 0xd4, 0xdf, 0xc2, 0xc9, 0xf8, 0xf3, 0xee, 0xe5,
+ 0x3c, 0x37, 0x2a, 0x21, 0x10, 0x1b, 0x06, 0x0d, 0x64, 0x6f, 0x72, 0x79, 0x48, 0x43, 0x5e, 0x55,
+ 0x01, 0x0a, 0x17, 0x1c, 0x2d, 0x26, 0x3b, 0x30, 0x59, 0x52, 0x4f, 0x44, 0x75, 0x7e, 0x63, 0x68,
+ 0xb1, 0xba, 0xa7, 0xac, 0x9d, 0x96, 0x8b, 0x80, 0xe9, 0xe2, 0xff, 0xf4, 0xc5, 0xce, 0xd3, 0xd8,
+ 0x7a, 0x71, 0x6c, 0x67, 0x56, 0x5d, 0x40, 0x4b, 0x22, 0x29, 0x34, 0x3f, 0x0e, 0x05, 0x18, 0x13,
+ 0xca, 0xc1, 0xdc, 0xd7, 0xe6, 0xed, 0xf0, 0xfb, 0x92, 0x99, 0x84, 0x8f, 0xbe, 0xb5, 0xa8, 0xa3,
+];
+
+const MUL13: [u8; 256] = [
+ 0x00, 0x0d, 0x1a, 0x17, 0x34, 0x39, 0x2e, 0x23, 0x68, 0x65, 0x72, 0x7f, 0x5c, 0x51, 0x46, 0x4b,
+ 0xd0, 0xdd, 0xca, 0xc7, 0xe4, 0xe9, 0xfe, 0xf3, 0xb8, 0xb5, 0xa2, 0xaf, 0x8c, 0x81, 0x96, 0x9b,
+ 0xbb, 0xb6, 0xa1, 0xac, 0x8f, 0x82, 0x95, 0x98, 0xd3, 0xde, 0xc9, 0xc4, 0xe7, 0xea, 0xfd, 0xf0,
+ 0x6b, 0x66, 0x71, 0x7c, 0x5f, 0x52, 0x45, 0x48, 0x03, 0x0e, 0x19, 0x14, 0x37, 0x3a, 0x2d, 0x20,
+ 0x6d, 0x60, 0x77, 0x7a, 0x59, 0x54, 0x43, 0x4e, 0x05, 0x08, 0x1f, 0x12, 0x31, 0x3c, 0x2b, 0x26,
+ 0xbd, 0xb0, 0xa7, 0xaa, 0x89, 0x84, 0x93, 0x9e, 0xd5, 0xd8, 0xcf, 0xc2, 0xe1, 0xec, 0xfb, 0xf6,
+ 0xd6, 0xdb, 0xcc, 0xc1, 0xe2, 0xef, 0xf8, 0xf5, 0xbe, 0xb3, 0xa4, 0xa9, 0x8a, 0x87, 0x90, 0x9d,
+ 0x06, 0x0b, 0x1c, 0x11, 0x32, 0x3f, 0x28, 0x25, 0x6e, 0x63, 0x74, 0x79, 0x5a, 0x57, 0x40, 0x4d,
+ 0xda, 0xd7, 0xc0, 0xcd, 0xee, 0xe3, 0xf4, 0xf9, 0xb2, 0xbf, 0xa8, 0xa5, 0x86, 0x8b, 0x9c, 0x91,
+ 0x0a, 0x07, 0x10, 0x1d, 0x3e, 0x33, 0x24, 0x29, 0x62, 0x6f, 0x78, 0x75, 0x56, 0x5b, 0x4c, 0x41,
+ 0x61, 0x6c, 0x7b, 0x76, 0x55, 0x58, 0x4f, 0x42, 0x09, 0x04, 0x13, 0x1e, 0x3d, 0x30, 0x27, 0x2a,
+ 0xb1, 0xbc, 0xab, 0xa6, 0x85, 0x88, 0x9f, 0x92, 0xd9, 0xd4, 0xc3, 0xce, 0xed, 0xe0, 0xf7, 0xfa,
+ 0xb7, 0xba, 0xad, 0xa0, 0x83, 0x8e, 0x99, 0x94, 0xdf, 0xd2, 0xc5, 0xc8, 0xeb, 0xe6, 0xf1, 0xfc,
+ 0x67, 0x6a, 0x7d, 0x70, 0x53, 0x5e, 0x49, 0x44, 0x0f, 0x02, 0x15, 0x18, 0x3b, 0x36, 0x21, 0x2c,
+ 0x0c, 0x01, 0x16, 0x1b, 0x38, 0x35, 0x22, 0x2f, 0x64, 0x69, 0x7e, 0x73, 0x50, 0x5d, 0x4a, 0x47,
+ 0xdc, 0xd1, 0xc6, 0xcb, 0xe8, 0xe5, 0xf2, 0xff, 0xb4, 0xb9, 0xae, 0xa3, 0x80, 0x8d, 0x9a, 0x97,
+];
+
+const MUL14: [u8; 256] = [
+ 0x00, 0x0e, 0x1c, 0x12, 0x38, 0x36, 0x24, 0x2a, 0x70, 0x7e, 0x6c, 0x62, 0x48, 0x46, 0x54, 0x5a,
+ 0xe0, 0xee, 0xfc, 0xf2, 0xd8, 0xd6, 0xc4, 0xca, 0x90, 0x9e, 0x8c, 0x82, 0xa8, 0xa6, 0xb4, 0xba,
+ 0xdb, 0xd5, 0xc7, 0xc9, 0xe3, 0xed, 0xff, 0xf1, 0xab, 0xa5, 0xb7, 0xb9, 0x93, 0x9d, 0x8f, 0x81,
+ 0x3b, 0x35, 0x27, 0x29, 0x03, 0x0d, 0x1f, 0x11, 0x4b, 0x45, 0x57, 0x59, 0x73, 0x7d, 0x6f, 0x61,
+ 0xad, 0xa3, 0xb1, 0xbf, 0x95, 0x9b, 0x89, 0x87, 0xdd, 0xd3, 0xc1, 0xcf, 0xe5, 0xeb, 0xf9, 0xf7,
+ 0x4d, 0x43, 0x51, 0x5f, 0x75, 0x7b, 0x69, 0x67, 0x3d, 0x33, 0x21, 0x2f, 0x05, 0x0b, 0x19, 0x17,
+ 0x76, 0x78, 0x6a, 0x64, 0x4e, 0x40, 0x52, 0x5c, 0x06, 0x08, 0x1a, 0x14, 0x3e, 0x30, 0x22, 0x2c,
+ 0x96, 0x98, 0x8a, 0x84, 0xae, 0xa0, 0xb2, 0xbc, 0xe6, 0xe8, 0xfa, 0xf4, 0xde, 0xd0, 0xc2, 0xcc,
+ 0x41, 0x4f, 0x5d, 0x53, 0x79, 0x77, 0x65, 0x6b, 0x31, 0x3f, 0x2d, 0x23, 0x09, 0x07, 0x15, 0x1b,
+ 0xa1, 0xaf, 0xbd, 0xb3, 0x99, 0x97, 0x85, 0x8b, 0xd1, 0xdf, 0xcd, 0xc3, 0xe9, 0xe7, 0xf5, 0xfb,
+ 0x9a, 0x94, 0x86, 0x88, 0xa2, 0xac, 0xbe, 0xb0, 0xea, 0xe4, 0xf6, 0xf8, 0xd2, 0xdc, 0xce, 0xc0,
+ 0x7a, 0x74, 0x66, 0x68, 0x42, 0x4c, 0x5e, 0x50, 0x0a, 0x04, 0x16, 0x18, 0x32, 0x3c, 0x2e, 0x20,
+ 0xec, 0xe2, 0xf0, 0xfe, 0xd4, 0xda, 0xc8, 0xc6, 0x9c, 0x92, 0x80, 0x8e, 0xa4, 0xaa, 0xb8, 0xb6,
+ 0x0c, 0x02, 0x10, 0x1e, 0x34, 0x3a, 0x28, 0x26, 0x7c, 0x72, 0x60, 0x6e, 0x44, 0x4a, 0x58, 0x56,
+ 0x37, 0x39, 0x2b, 0x25, 0x0f, 0x01, 0x13, 0x1d, 0x47, 0x49, 0x5b, 0x55, 0x7f, 0x71, 0x63, 0x6d,
+ 0xd7, 0xd9, 0xcb, 0xc5, 0xef, 0xe1, 0xf3, 0xfd, 0xa7, 0xa9, 0xbb, 0xb5, 0x9f, 0x91, 0x83, 0x8d,
+];
+
+struct AESCore;
+
+impl AESCore {
+ fn sub_bytes(state: &mut [u8; 16]) {
+ for byte in state.iter_mut() {
+ *byte = S_BOX[*byte as usize];
+ }
+ }
+
+ fn inv_sub_bytes(state: &mut [u8; 16]) {
+ for byte in state.iter_mut() {
+ *byte = INV_S_BOX[*byte as usize];
+ }
+ }
+
+ fn shift_rows(state: &mut [u8; 16]) {
+ let temp = state[1];
+ state[1] = state[5];
+ state[5] = state[9];
+ state[9] = state[13];
+ state[13] = temp;
+
+ let temp1 = state[2];
+ let temp2 = state[6];
+ state[2] = state[10];
+ state[6] = state[14];
+ state[10] = temp1;
+ state[14] = temp2;
+
+ let temp = state[15];
+ state[15] = state[11];
+ state[11] = state[7];
+ state[7] = state[3];
+ state[3] = temp;
+ }
+
+ fn inv_shift_rows(state: &mut [u8; 16]) {
+ let temp = state[13];
+ state[13] = state[9];
+ state[9] = state[5];
+ state[5] = state[1];
+ state[1] = temp;
+
+ let temp1 = state[2];
+ let temp2 = state[6];
+ state[2] = state[10];
+ state[6] = state[14];
+ state[10] = temp1;
+ state[14] = temp2;
+
+ let temp = state[3];
+ state[3] = state[7];
+ state[7] = state[11];
+ state[11] = state[15];
+ state[15] = temp;
+ }
+
+ #[inline]
+ fn mix_columns(state: &mut [u8; 16]) {
+ for i in 0..4 {
+ let col = i * 4;
+ let [s0, s1, s2, s3] = [state[col], state[col + 1], state[col + 2], state[col + 3]];
+
+ state[col] = MUL2[s0 as usize] ^ MUL3[s1 as usize] ^ s2 ^ s3;
+ state[col + 1] = s0 ^ MUL2[s1 as usize] ^ MUL3[s2 as usize] ^ s3;
+ state[col + 2] = s0 ^ s1 ^ MUL2[s2 as usize] ^ MUL3[s3 as usize];
+ state[col + 3] = MUL3[s0 as usize] ^ s1 ^ s2 ^ MUL2[s3 as usize];
+ }
+ }
+
+ #[inline]
+ fn inv_mix_columns(state: &mut [u8; 16]) {
+ for i in 0..4 {
+ let col = i * 4;
+ let [s0, s1, s2, s3] = [state[col], state[col + 1], state[col + 2], state[col + 3]];
+
+ state[col] =
+ MUL14[s0 as usize] ^ MUL11[s1 as usize] ^ MUL13[s2 as usize] ^ MUL9[s3 as usize];
+ state[col + 1] =
+ MUL9[s0 as usize] ^ MUL14[s1 as usize] ^ MUL11[s2 as usize] ^ MUL13[s3 as usize];
+ state[col + 2] =
+ MUL13[s0 as usize] ^ MUL9[s1 as usize] ^ MUL14[s2 as usize] ^ MUL11[s3 as usize];
+ state[col + 3] =
+ MUL11[s0 as usize] ^ MUL13[s1 as usize] ^ MUL9[s2 as usize] ^ MUL14[s3 as usize];
+ }
+ }
+
+ fn add_round_key(state: &mut [u8; 16], round_key: &[u8; 16]) {
+ for i in 0..16 {
+ state[i] ^= round_key[i];
+ }
+ }
+}
+
+#[derive(Clone)]
+pub(crate) struct AESCipher<const KEY_SIZE: usize, const ROUNDS: usize> {
+ round_keys: [[u8; 16]; ROUNDS],
+}
+
+pub(crate) type AES128Cipher = AESCipher<16, 11>;
+pub(crate) type AES256Cipher = AESCipher<32, 15>;
+
+impl<const KEY_SIZE: usize, const ROUNDS: usize> AESCipher<KEY_SIZE, ROUNDS> {
+ pub(crate) fn new(key: &[u8]) -> Option<Self> {
+ if key.len() != KEY_SIZE {
+ return None;
+ }
+
+ let mut round_keys = [[0_u8; 16]; ROUNDS];
+
+ match KEY_SIZE {
+ 16 => Self::expand_key_128(&mut round_keys, key),
+ 32 => Self::expand_key_256(&mut round_keys, key),
+ _ => return None,
+ }
+
+ Some(Self { round_keys })
+ }
+
+ fn expand_key_128(round_keys: &mut [[u8; 16]; ROUNDS], key: &[u8]) {
+ round_keys[0].copy_from_slice(&key[..16]);
+
+ for i in 1..ROUNDS {
+ let mut temp = [0_u8; 4];
+ temp.copy_from_slice(&round_keys[i - 1][12..16]);
+
+ temp.rotate_left(1);
+ for b in &mut temp {
+ *b = S_BOX[*b as usize];
+ }
+
+ temp[0] ^= RCON[i - 1];
+
+ for j in 0..4 {
+ for k in 0..4 {
+ round_keys[i][j * 4 + k] = round_keys[i - 1][j * 4 + k] ^ temp[k];
+ }
+ if j < 3 {
+ temp.copy_from_slice(&round_keys[i][j * 4..(j + 1) * 4]);
+ }
+ }
+ }
+ }
+
+ fn expand_key_256(round_keys: &mut [[u8; 16]; ROUNDS], key: &[u8]) {
+ round_keys[0].copy_from_slice(&key[0..16]);
+ round_keys[1].copy_from_slice(&key[16..32]);
+
+ for i in 2..ROUNDS {
+ let mut temp = [0_u8; 4];
+
+ if i % 2 == 0 {
+ temp.copy_from_slice(&round_keys[i - 1][12..16]);
+ temp.rotate_left(1);
+ for b in &mut temp {
+ *b = S_BOX[*b as usize];
+ }
+ temp[0] ^= RCON[(i / 2) - 1];
+ } else {
+ temp.copy_from_slice(&round_keys[i - 1][12..16]);
+ for b in &mut temp {
+ *b = S_BOX[*b as usize];
+ }
+ }
+
+ for j in 0..4 {
+ for k in 0..4 {
+ round_keys[i][j * 4 + k] = round_keys[i - 2][j * 4 + k] ^ temp[k];
+ }
+ if j < 3 {
+ temp.copy_from_slice(&round_keys[i][j * 4..(j + 1) * 4]);
+ }
+ }
+ }
+ }
+
+ pub(crate) fn encrypt_block(&self, input: &[u8; 16]) -> [u8; 16] {
+ let mut state = *input;
+
+ AESCore::add_round_key(&mut state, &self.round_keys[0]);
+
+ let main_rounds = ROUNDS - 1;
+ for round in 1..main_rounds {
+ AESCore::sub_bytes(&mut state);
+ AESCore::shift_rows(&mut state);
+ AESCore::mix_columns(&mut state);
+ AESCore::add_round_key(&mut state, &self.round_keys[round]);
+ }
+
+ AESCore::sub_bytes(&mut state);
+ AESCore::shift_rows(&mut state);
+ AESCore::add_round_key(&mut state, &self.round_keys[main_rounds]);
+
+ state
+ }
+
+ pub(crate) fn decrypt_block(&self, input: &[u8; 16]) -> [u8; 16] {
+ let mut state = *input;
+
+ let main_rounds = ROUNDS - 1;
+
+ AESCore::add_round_key(&mut state, &self.round_keys[main_rounds]);
+ AESCore::inv_shift_rows(&mut state);
+ AESCore::inv_sub_bytes(&mut state);
+
+ for round in (1..main_rounds).rev() {
+ AESCore::add_round_key(&mut state, &self.round_keys[round]);
+ AESCore::inv_mix_columns(&mut state);
+ AESCore::inv_shift_rows(&mut state);
+ AESCore::inv_sub_bytes(&mut state);
+ }
+
+ AESCore::add_round_key(&mut state, &self.round_keys[0]);
+
+ state
+ }
+
+ pub(crate) fn encrypt_cbc(&self, data: &[u8], iv: &[u8; 16]) -> Vec<u8> {
+ let mut result = Vec::new();
+ let mut current_iv = *iv;
+
+ let mut padded_data = data.to_vec();
+ let pad_len = 16 - (data.len() % 16);
+ if pad_len == 0 {
+ padded_data.extend(vec![16_u8; 16]);
+ } else {
+ padded_data.extend(vec![pad_len as u8; pad_len]);
+ }
+
+ for chunk in padded_data.chunks(16) {
+ let mut block = [0_u8; 16];
+ block.copy_from_slice(chunk);
+
+ for i in 0..16 {
+ block[i] ^= current_iv[i];
+ }
+
+ let encrypted = self.encrypt_block(&block);
+ result.extend_from_slice(&encrypted);
+ current_iv = encrypted;
+ }
+
+ result
+ }
+
+ pub(crate) fn decrypt_cbc(&self, data: &[u8], iv: &[u8; 16], unpad: bool) -> Vec<u8> {
+ let mut result = Vec::new();
+ let mut prev_block = *iv;
+
+ for chunk in data.chunks_exact(16) {
+ let mut block = [0_u8; 16];
+ block.copy_from_slice(chunk);
+
+ let decrypted = self.decrypt_block(&block);
+
+ let mut plain_block = [0_u8; 16];
+ for i in 0..16 {
+ plain_block[i] = decrypted[i] ^ prev_block[i];
+ }
+
+ result.extend_from_slice(&plain_block);
+ prev_block = block;
+ }
+
+ if unpad
+ && let Some(&pad_len) = result.last()
+ && pad_len > 0
+ && pad_len <= 16
+ && result.len() >= pad_len as usize
+ {
+ let start = result.len() - pad_len as usize;
+ if result[start..].iter().all(|&b| b == pad_len) {
+ result.truncate(start);
+ }
+ }
+
+ result
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use aes::cipher::{
+ BlockDecryptMut, BlockEncrypt, BlockEncryptMut, KeyInit, generic_array::GenericArray,
+ };
+ use aes::{Aes128, Aes256};
+ use cbc::{
+ Decryptor, Encryptor,
+ cipher::{KeyIvInit, block_padding::Pkcs7},
+ };
+
+ type Aes128Cbc = Encryptor<Aes128>;
+ type Aes128CbcDec = Decryptor<Aes128>;
+ type Aes256Cbc = Encryptor<Aes256>;
+ type Aes256CbcDec = Decryptor<Aes256>;
+
+ fn aes_128_block_test(key: &[u8; 16], plaintext: &[u8; 16]) {
+ let our_cipher = AES128Cipher::new(key).unwrap();
+
+ let external_cipher = Aes128::new_from_slice(key).unwrap();
+ let mut external_block = GenericArray::clone_from_slice(plaintext);
+ external_cipher.encrypt_block(&mut external_block);
+
+ let our_ciphertext = our_cipher.encrypt_block(plaintext);
+ assert_eq!(
+ our_ciphertext,
+ external_block.as_slice(),
+ "encryption should match"
+ );
+
+ let our_decrypted = our_cipher.decrypt_block(&our_ciphertext);
+ assert_eq!(
+ our_decrypted, *plaintext,
+ "roundtrip should recover original plaintext"
+ );
+ }
+
+ fn aes_256_block_test(key: &[u8; 32], plaintext: &[u8; 16]) {
+ let our_cipher = AES256Cipher::new(key).unwrap();
+
+ let external_cipher = Aes256::new_from_slice(key).unwrap();
+ let mut external_block = GenericArray::clone_from_slice(plaintext);
+ external_cipher.encrypt_block(&mut external_block);
+
+ let our_ciphertext = our_cipher.encrypt_block(plaintext);
+ assert_eq!(
+ our_ciphertext,
+ external_block.as_slice(),
+ "encryption should match"
+ );
+
+ let our_decrypted = our_cipher.decrypt_block(&our_ciphertext);
+ assert_eq!(
+ our_decrypted, *plaintext,
+ "roundtrip should recover original plaintext"
+ );
+ }
+
+ fn aes_128_cbc_test(key: &[u8; 16], iv: &[u8; 16], plaintext: &[u8]) {
+ let our_cipher = AES128Cipher::new(key).unwrap();
+
+ let our_ciphertext = our_cipher.encrypt_cbc(plaintext, iv);
+
+ let external_decryptor = Aes128CbcDec::new_from_slices(key, iv).unwrap();
+ let mut external_buffer = our_ciphertext.clone();
+ let external_decrypted = external_decryptor
+ .decrypt_padded_mut::<Pkcs7>(&mut external_buffer)
+ .unwrap();
+
+ assert_eq!(
+ external_decrypted, plaintext,
+ "AES-128 CBC: our encryption should be decryptable by external crate"
+ );
+
+ let external_encryptor = Aes128Cbc::new_from_slices(key, iv).unwrap();
+ let mut buffer = plaintext.to_vec();
+ buffer.resize(plaintext.len() + 16, 0);
+ let external_ciphertext = external_encryptor
+ .encrypt_padded_mut::<Pkcs7>(&mut buffer, plaintext.len())
+ .unwrap();
+
+ let our_decrypted = our_cipher.decrypt_cbc(external_ciphertext, iv, true);
+ assert_eq!(
+ our_decrypted, plaintext,
+ "AES-128 CBC: external encryption should be decryptable by our implementation"
+ );
+
+ let our_roundtrip = our_cipher.decrypt_cbc(&our_ciphertext, iv, true);
+ assert_eq!(
+ our_roundtrip, plaintext,
+ "AES-128 CBC: our roundtrip should work"
+ );
+ }
+
+ fn aes_256_cbc_test(key: &[u8; 32], iv: &[u8; 16], plaintext: &[u8]) {
+ let our_cipher = AES256Cipher::new(key).unwrap();
+
+ let our_ciphertext = our_cipher.encrypt_cbc(plaintext, iv);
+
+ let external_decryptor = Aes256CbcDec::new_from_slices(key, iv).unwrap();
+ let mut external_buffer = our_ciphertext.clone();
+ let external_decrypted = external_decryptor
+ .decrypt_padded_mut::<Pkcs7>(&mut external_buffer)
+ .unwrap();
+
+ assert_eq!(
+ external_decrypted, plaintext,
+ "AES-256 CBC: our encryption should be decryptable by external crate"
+ );
+
+ let external_encryptor = Aes256Cbc::new_from_slices(key, iv).unwrap();
+ let mut buffer = plaintext.to_vec();
+ buffer.resize(plaintext.len() + 16, 0);
+ let external_ciphertext = external_encryptor
+ .encrypt_padded_mut::<Pkcs7>(&mut buffer, plaintext.len())
+ .unwrap();
+
+ let our_decrypted = our_cipher.decrypt_cbc(external_ciphertext, iv, true);
+ assert_eq!(
+ our_decrypted, plaintext,
+ "AES-256 CBC: external encryption should be decryptable by our implementation"
+ );
+
+ let our_roundtrip = our_cipher.decrypt_cbc(&our_ciphertext, iv, true);
+ assert_eq!(
+ our_roundtrip, plaintext,
+ "AES-256 CBC: our roundtrip should work"
+ );
+ }
+
+ #[test]
+ fn test_aes128_block_operations() {
+ let test_cases = [
+ (
+ [
+ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09,
+ 0xcf, 0x4f, 0x3c,
+ ],
+ [
+ 0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0,
+ 0x37, 0x07, 0x34,
+ ],
+ ),
+ (
+ [
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
+ 0x0d, 0x0e, 0x0f,
+ ],
+ [
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc,
+ 0xdd, 0xee, 0xff,
+ ],
+ ),
+ ([0xff; 16], [0x00; 16]),
+ ([0x00; 16], [0xff; 16]),
+ ];
+
+ for (key, plaintext) in test_cases {
+ aes_128_block_test(&key, &plaintext);
+ }
+ }
+
+ #[test]
+ fn test_aes256_block_operations() {
+ let test_cases = [
+ (
+ [
+ 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85,
+ 0x7d, 0x77, 0x81, 0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98,
+ 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4,
+ ],
+ [
+ 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73,
+ 0x93, 0x17, 0x2a,
+ ],
+ ),
+ (
+ [
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
+ 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
+ 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
+ ],
+ [
+ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc,
+ 0xdd, 0xee, 0xff,
+ ],
+ ),
+ ([0xff; 32], [0x00; 16]),
+ ([0x00; 32], [0xff; 16]),
+ ];
+
+ for (key, plaintext) in test_cases {
+ aes_256_block_test(&key, &plaintext);
+ }
+ }
+
+ #[test]
+ fn test_aes128_encryption_decryption() {
+ let test_cases = [
+ (
+ [
+ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09,
+ 0xcf, 0x4f, 0x3c,
+ ],
+ [
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
+ 0x0d, 0x0e, 0x0f,
+ ],
+ b"Hello, World!" as &[u8],
+ ),
+ (
+ [
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
+ 0x0d, 0x0e, 0x0f,
+ ],
+ [0xff; 16],
+ b"The quick brown fox jumps over the lazy dog",
+ ),
+ (
+ [0xff; 16],
+ [0x00; 16],
+ b"AES-128 encryption test vector for CBC mode with PKCS7 padding",
+ ),
+ ([0xaa; 16], [0x55; 16], &[0x42_u8; 100]),
+ ];
+
+ for (key, iv, plaintext) in test_cases {
+ aes_128_cbc_test(&key, &iv, plaintext);
+ }
+ }
+
+ #[test]
+ fn test_aes256_encryption_decryption() {
+ let test_cases = [
+ (
+ [
+ 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85,
+ 0x7d, 0x77, 0x81, 0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98,
+ 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4,
+ ],
+ [
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
+ 0x0d, 0x0e, 0x0f,
+ ],
+ b"Hello, World!" as &[u8],
+ ),
+ (
+ [
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
+ 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
+ 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
+ ],
+ [0xff; 16],
+ b"The quick brown fox jumps over the lazy dog",
+ ),
+ (
+ [0xff; 32],
+ [0x00; 16],
+ b"AES-256 encryption test vector for CBC mode with PKCS7 padding",
+ ),
+ ([0xaa; 32], [0x55; 16], &[0x42_u8; 100]),
+ ];
+
+ for (key, iv, plaintext) in test_cases {
+ aes_256_cbc_test(&key, &iv, plaintext);
+ }
+ }
+
+ #[test]
+ fn test_aes128_cbc_decryption() {
+ let test_cases = [
+ (
+ [
+ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09,
+ 0xcf, 0x4f, 0x3c,
+ ],
+ [
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
+ 0x0d, 0x0e, 0x0f,
+ ],
+ b"Hello, World!" as &[u8],
+ ),
+ (
+ [
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
+ 0x0d, 0x0e, 0x0f,
+ ],
+ [0xff; 16],
+ b"The quick brown fox jumps over the lazy dog",
+ ),
+ (
+ [0xff; 16],
+ [0x00; 16],
+ b"AES-128 test vector for CBC mode with PKCS7 padding",
+ ),
+ ([0xaa; 16], [0x55; 16], &[0x42_u8; 100]),
+ ];
+
+ for (key, iv, plaintext) in test_cases {
+ aes_128_cbc_test(&key, &iv, plaintext);
+ }
+ }
+
+ #[test]
+ fn test_aes256_cbc_decryption() {
+ let test_cases = [
+ (
+ [
+ 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85,
+ 0x7d, 0x77, 0x81, 0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98,
+ 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4,
+ ],
+ [
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
+ 0x0d, 0x0e, 0x0f,
+ ],
+ b"Hello, World!" as &[u8],
+ ),
+ (
+ [
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
+ 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
+ 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
+ ],
+ [0xff; 16],
+ b"The quick brown fox jumps over the lazy dog",
+ ),
+ (
+ [0xff; 32],
+ [0x00; 16],
+ b"AES-256 test vector for CBC mode with PKCS7 padding",
+ ),
+ ([0xaa; 32], [0x55; 16], &[0x42_u8; 100]),
+ ];
+
+ for (key, iv, plaintext) in test_cases {
+ aes_256_cbc_test(&key, &iv, plaintext);
+ }
+ }
+
+ #[test]
+ fn test_edge_cases() {
+ let key128 = [
+ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf,
+ 0x4f, 0x3c,
+ ];
+ let key256 = [
+ 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d,
+ 0x77, 0x81, 0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3,
+ 0x09, 0x14, 0xdf, 0xf4,
+ ];
+ let iv = [0x00; 16];
+
+ aes_128_cbc_test(&key128, &iv, b"");
+ aes_256_cbc_test(&key256, &iv, b"");
+
+ aes_128_cbc_test(&key128, &iv, b"a");
+ aes_256_cbc_test(&key256, &iv, b"a");
+
+ aes_128_cbc_test(&key128, &iv, &[0xff_u8; 15]);
+ aes_256_cbc_test(&key256, &iv, &[0xff_u8; 15]);
+
+ aes_128_cbc_test(&key128, &iv, &[0xff_u8; 16]);
+ aes_256_cbc_test(&key256, &iv, &[0xff_u8; 16]);
+
+ aes_128_cbc_test(&key128, &iv, &[0xff_u8; 17]);
+ aes_256_cbc_test(&key256, &iv, &[0xff_u8; 17]);
+ }
+
+ #[test]
+ fn test_invalid_key_lengths() {
+ assert!(AES128Cipher::new(&[0_u8; 15]).is_none());
+ assert!(AES128Cipher::new(&[0_u8; 17]).is_none());
+ assert!(AES256Cipher::new(&[0_u8; 31]).is_none());
+ assert!(AES256Cipher::new(&[0_u8; 33]).is_none());
+ }
+}
diff --git a/vendor/hayro-syntax/src/crypto/md5.rs b/vendor/hayro-syntax/src/crypto/md5.rs
new file mode 100644
index 000000000..30e8453bd
--- /dev/null
+++ b/vendor/hayro-syntax/src/crypto/md5.rs
@@ -0,0 +1,116 @@
+//! Ported from <https://github.com/mozilla/pdf.js/blob/master/src/core/calculate_md5.js>.
+
+use alloc::vec::Vec;
+
+const SHIFT_AMOUNTS: [u32; 64] = [
+ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9,
+ 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15,
+ 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
+];
+
+const CONSTANTS: [u32; 64] = [
+ 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
+ 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
+ 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
+ 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
+ 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
+ 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
+ 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
+ 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,
+];
+
+pub(crate) fn calculate(data: &[u8]) -> [u8; 16] {
+ let mut state = [
+ 0x67452301_u32,
+ 0xefcdab89_u32,
+ 0x98badcfe_u32,
+ 0x10325476_u32,
+ ];
+
+ let original_len = data.len();
+ let mut message = data.to_vec();
+ message.push(0x80);
+
+ while (message.len() % 64) != 56 {
+ message.push(0);
+ }
+
+ message.extend_from_slice(&(original_len as u64 * 8).to_le_bytes());
+
+ for chunk in message.chunks_exact(64) {
+ let words: Vec<u32> = chunk
+ .chunks_exact(4)
+ .map(|bytes| u32::from_le_bytes(bytes.try_into().unwrap()))
+ .collect();
+
+ let mut working_vars = state;
+
+ for i in 0..64 {
+ let (f, g) = match i {
+ 0..=15 => (
+ (working_vars[1] & working_vars[2]) | (!working_vars[1] & working_vars[3]),
+ i,
+ ),
+ 16..=31 => (
+ (working_vars[3] & working_vars[1]) | (!working_vars[3] & working_vars[2]),
+ (5 * i + 1) % 16,
+ ),
+ 32..=47 => (
+ working_vars[1] ^ working_vars[2] ^ working_vars[3],
+ (3 * i + 5) % 16,
+ ),
+ 48..=63 => (
+ working_vars[2] ^ (working_vars[1] | !working_vars[3]),
+ (7 * i) % 16,
+ ),
+ _ => unreachable!(),
+ };
+
+ let temp = working_vars[3];
+ working_vars[3] = working_vars[2];
+ working_vars[2] = working_vars[1];
+ working_vars[1] = working_vars[1].wrapping_add(
+ (working_vars[0]
+ .wrapping_add(f)
+ .wrapping_add(CONSTANTS[i])
+ .wrapping_add(words[g]))
+ .rotate_left(SHIFT_AMOUNTS[i]),
+ );
+ working_vars[0] = temp;
+ }
+
+ for (state_val, working_val) in state.iter_mut().zip(working_vars.iter()) {
+ *state_val = state_val.wrapping_add(*working_val);
+ }
+ }
+
+ let mut result = [0_u8; 16];
+ for (i, &word) in state.iter().enumerate() {
+ result[i * 4..(i + 1) * 4].copy_from_slice(&word.to_le_bytes());
+ }
+ result
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn md5_test(data: &[u8]) {
+ let our_result = calculate(data);
+
+ let external_result = md5::compute(data);
+
+ assert_eq!(
+ our_result,
+ external_result.as_slice(),
+ "MD5 calculation should match external md5 crate for input: {data:?}"
+ );
+ }
+
+ #[test]
+ fn correctness() {
+ md5_test(b"Hello, World!");
+ md5_test(b"The quick brown fox jumps over the lazy dog");
+ md5_test(b"abcdefghijklmnopqrstuvwxyz");
+ }
+}
diff --git a/vendor/hayro-syntax/src/crypto/mod.rs b/vendor/hayro-syntax/src/crypto/mod.rs
new file mode 100644
index 000000000..2d407ad09
--- /dev/null
+++ b/vendor/hayro-syntax/src/crypto/mod.rs
@@ -0,0 +1,674 @@
+//! Cryptographic implementations for hayro, ported from pdf.js.
+//!
+//! **Important note**: Please keep in mind that these haven't been
+//! audited and should not be used for security-critical purposes, like creating new
+//! encrypted PDFs. They solely serve the purpose of being able to decrypt and read
+//! _already_ encrypted documents, where security isn't really relevant.
+
+use crate::crypto::DecryptionError::InvalidEncryption;
+use crate::crypto::aes::{AES128Cipher, AES256Cipher};
+use crate::crypto::rc4::Rc4;
+use crate::object;
+use crate::object::dict::keys::{
+ CF, CFM, ENCRYPT_META_DATA, FILTER, LENGTH, O, OE, P, R, STM_F, STR_F, U, UE, V,
+};
+use crate::object::{Dict, Name, ObjectIdentifier};
+use crate::sync::HashMap;
+use alloc::string::ToString;
+use alloc::vec;
+use alloc::vec::Vec;
+use core::cmp;
+use core::ops::Deref;
+
+mod aes;
+mod md5;
+mod rc4;
+mod sha256;
+mod sha384;
+mod sha512;
+
+const PASSWORD_PADDING: [u8; 32] = [
+ 0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41, 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08,
+ 0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80, 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A,
+];
+
+/// An error that occurred during decryption.
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
+pub enum DecryptionError {
+ /// The ID entry is missing in the PDF.
+ MissingIDEntry,
+ /// The PDF is password-protected and no password (or a wrong one) was
+ /// provided.
+ PasswordProtected,
+ /// The PDF has invalid encryption.
+ InvalidEncryption,
+ /// The PDF uses an unsupported encryption algorithm.
+ UnsupportedAlgorithm,
+}
+
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
+enum DecryptorTag {
+ None,
+ Rc4,
+ Aes128,
+ Aes256,
+}
+
+impl DecryptorTag {
+ fn from_name(name: &Name<'_>) -> Option<Self> {
+ match name.as_str() {
+ "None" | "Identity" => Some(Self::None),
+ "V2" => Some(Self::Rc4),
+ "AESV2" => Some(Self::Aes128),
+ "AESV3" => Some(Self::Aes256),
+ _ => None,
+ }
+ }
+}
+#[derive(Debug, Clone)]
+pub(crate) enum Decryptor {
+ None,
+ Rc4 { key: Vec<u8> },
+ Aes128 { key: Vec<u8>, dict: DecryptorData },
+ Aes256 { key: Vec<u8>, dict: DecryptorData },
+}
+
+#[derive(Debug, Copy, Clone)]
+pub(crate) enum DecryptionTarget {
+ String,
+ Stream,
+}
+
+impl Decryptor {
+ pub(crate) fn decrypt(
+ &self,
+ id: ObjectIdentifier,
+ data: &[u8],
+ target: DecryptionTarget,
+ ) -> Option<Vec<u8>> {
+ match self {
+ Self::None => Some(data.to_vec()),
+ Self::Rc4 { key } => decrypt_rc4(key, data, id),
+ Self::Aes128 { key, dict } | Self::Aes256 { key, dict } => {
+ let crypt_dict = match target {
+ DecryptionTarget::String => dict.string_filter,
+ DecryptionTarget::Stream => dict.stream_filter,
+ };
+
+ match crypt_dict.cfm {
+ DecryptorTag::None => Some(data.to_vec()),
+ DecryptorTag::Rc4 => decrypt_rc4(key, data, id),
+ DecryptorTag::Aes128 => decrypt_aes128(key, data, id),
+ DecryptorTag::Aes256 => decrypt_aes256(key, data),
+ }
+ }
+ }
+ }
+}
+
+pub(crate) fn get(
+ dict: &Dict<'_>,
+ id: &[u8],
+ password: &[u8],
+) -> Result<Decryptor, DecryptionError> {
+ let filter = dict.get::<Name<'_>>(FILTER).ok_or(InvalidEncryption)?;
+
+ if filter.deref() != b"Standard" {
+ return Err(DecryptionError::UnsupportedAlgorithm);
+ }
+
+ let encryption_v = dict.get::<u8>(V).ok_or(InvalidEncryption)?;
+ let encrypt_metadata = dict.get::<bool>(ENCRYPT_META_DATA).unwrap_or(true);
+ let revision = dict.get::<u8>(R).ok_or(InvalidEncryption)?;
+ let length = match encryption_v {
+ 1 => 40,
+ 2 => dict.get::<u16>(LENGTH).unwrap_or(40),
+ 4 => dict.get::<u16>(LENGTH).unwrap_or(128),
+ 5 => 256,
+ _ => return Err(DecryptionError::UnsupportedAlgorithm),
+ };
+
+ let (algorithm, data) = match encryption_v {
+ 1 => (DecryptorTag::Rc4, None),
+ 2 => (DecryptorTag::Rc4, None),
+ 4 => (
+ DecryptorTag::Aes128,
+ Some(DecryptorData::from_dict(dict, length).ok_or(InvalidEncryption)?),
+ ),
+ 5 | 6 => (
+ DecryptorTag::Aes256,
+ Some(DecryptorData::from_dict(dict, length).ok_or(InvalidEncryption)?),
+ ),
+ _ => {
+ return Err(DecryptionError::UnsupportedAlgorithm);
+ }
+ };
+
+ let byte_length = length / 8;
+ if byte_length == 0 {
+ return Err(InvalidEncryption);
+ }
+
+ let owner_string = dict.get::<object::String<'_>>(O).ok_or(InvalidEncryption)?;
+ let user_string = dict.get::<object::String<'_>>(U).ok_or(InvalidEncryption)?;
+ let permissions = {
+ let raw = dict.get::<i64>(P).ok_or(InvalidEncryption)?;
+
+ if raw < 0 {
+ u32::from_be_bytes((raw as i32).to_be_bytes())
+ } else {
+ raw as u32
+ }
+ };
+
+ let mut decryption_key = if revision <= 4 {
+ let key = decryption_key_rev1234(
+ password,
+ encrypt_metadata,
+ revision,
+ byte_length,
+ &owner_string,
+ permissions,
+ id,
+ )?;
+ authenticate_user_password_rev234(revision, &key, id, &user_string)?;
+
+ key
+ } else {
+ decryption_key_rev56(dict, revision, password, &owner_string, &user_string)?
+ };
+
+ // See pdf.js issue 19484.
+ if encryption_v == 4 && decryption_key.len() < 16 {
+ decryption_key.resize(16, 0);
+ }
+
+ match algorithm {
+ DecryptorTag::None => Ok(Decryptor::None),
+ DecryptorTag::Rc4 => Ok(Decryptor::Rc4 {
+ key: decryption_key,
+ }),
+ DecryptorTag::Aes128 => Ok(Decryptor::Aes128 {
+ key: decryption_key,
+ dict: data.unwrap(),
+ }),
+ DecryptorTag::Aes256 => Ok(Decryptor::Aes256 {
+ key: decryption_key,
+ dict: data.unwrap(),
+ }),
+ }
+}
+
+/// Algorithm 1.A: Encryption of data using the AES algorithms
+fn decrypt_aes256(key: &[u8], data: &[u8]) -> Option<Vec<u8>> {
+ // a) Use the 32-byte file encryption key for the AES-256 symmetric key algorithm,
+ // along with the string or stream data to be encrypted.
+ // Use the AES algorithm in Cipher Block Chaining (CBC) mode, which requires an initialization
+ // vector. The block size parameter is set to 16 bytes, and the initialization
+ // vector is a 16-byte random number that is stored as the first 16 bytes of the
+ // encrypted stream or string.
+ let (iv, data) = data.split_at_checked(16)?;
+ let iv: [u8; 16] = iv.try_into().ok()?;
+ let cipher = AES256Cipher::new(key)?;
+ Some(cipher.decrypt_cbc(data, &iv, true))
+}
+
+fn decrypt_aes128(key: &[u8], data: &[u8], id: ObjectIdentifier) -> Option<Vec<u8>> {
+ decrypt_rc_aes(key, id, true, |key| {
+ // If using the AES algorithm, the Cipher Block Chaining (CBC) mode, which requires an initialization
+ // vector, is used. The block size parameter is set to 16 bytes, and the initialization vector is a 16-byte
+ // random number that is stored as the first 16 bytes of the encrypted stream or string.
+ let cipher = AES128Cipher::new(key)?;
+ let (iv, data) = data.split_at_checked(16)?;
+ let iv: [u8; 16] = iv.try_into().ok()?;
+
+ Some(cipher.decrypt_cbc(data, &iv, true))
+ })
+}
+
+fn decrypt_rc4(key: &[u8], data: &[u8], id: ObjectIdentifier) -> Option<Vec<u8>> {
+ decrypt_rc_aes(key, id, false, |key| {
+ let mut rc = Rc4::new(key);
+ Some(rc.decrypt(data))
+ })
+}
+
+/// Algorithm 1: Encryption of data using the RC4 or AES algorithms
+fn decrypt_rc_aes(
+ key: &[u8],
+ id: ObjectIdentifier,
+ aes: bool,
+ with_key: impl FnOnce(&[u8]) -> Option<Vec<u8>>,
+) -> Option<Vec<u8>> {
+ let n = key.len();
+ // a) Obtain the object number and generation number from the object identifier of
+ // the string or stream to be encrypted (see 7.3.10, "Indirect objects"). If the
+ // string is a direct object, use the identifier of the indirect object containing
+ // it.
+ let mut key = key.to_vec();
+
+ // b) For all strings and streams without crypt filter specifier; treating the
+ // object number and generation number as binary integers, extend the original
+ // n-byte file encryption key to n + 5 bytes by appending the low-order 3 bytes of
+ // the object number and the low-order 2 bytes of the generation number in that
+ // order, low-order byte first.
+ key.extend(&id.obj_number.to_le_bytes()[..3]);
+ key.extend(&id.gen_number.to_le_bytes()[..2]);
+
+ // If using the AES algorithm, extend the file encryption key an additional 4 bytes by adding the value
+ // "sAlT", which corresponds to the hexadecimal values 0x73, 0x41, 0x6C, 0x54. (This addition is done
+ // for backward compatibility and is not intended to provide additional security.)
+ if aes {
+ key.extend(b"sAlT");
+ }
+
+ // c) Initialise the MD5 hash function and pass the result of step (b) as input
+ // to this function.
+ let hash = md5::calculate(&key);
+
+ // d) Use the first (n + 5) bytes, up to a maximum of 16, of the output
+ // from the MD5 hash as the key for the RC4 or AES symmetric key algorithms,
+ // along with the string or stream data to be encrypted.
+ let final_key = &hash[..cmp::min(16, n + 5)];
+
+ with_key(final_key)
+}
+
+#[derive(Debug, Copy, Clone)]
+pub(crate) struct DecryptorData {
+ stream_filter: CryptDictionary,
+ string_filter: CryptDictionary,
+}
+
+impl DecryptorData {
+ fn from_dict(dict: &Dict<'_>, default_length: u16) -> Option<Self> {
+ let mut mappings = HashMap::new();
+
+ if let Some(dict) = dict.get::<Dict<'_>>(CF) {
+ for key in dict.keys() {
+ if let Some(dict) = dict.get::<Dict<'_>>(key.as_ref())
+ && let Some(crypt_dict) = CryptDictionary::from_dict(&dict, default_length)
+ {
+ mappings.insert(key.as_str().to_string(), crypt_dict);
+ }
+ }
+ }
+
+ let stm_f = *mappings
+ .get(dict.get::<Name<'_>>(STM_F)?.as_str())
+ .unwrap_or(&CryptDictionary::identity(default_length));
+ let str_f = *mappings
+ .get(dict.get::<Name<'_>>(STR_F)?.as_str())
+ .unwrap_or(&CryptDictionary::identity(default_length));
+
+ Some(Self {
+ stream_filter: stm_f,
+ string_filter: str_f,
+ })
+ }
+}
+
+#[derive(Debug, Copy, Clone)]
+struct CryptDictionary {
+ cfm: DecryptorTag,
+ _length: u16,
+}
+
+impl CryptDictionary {
+ fn from_dict(dict: &Dict<'_>, default_length: u16) -> Option<Self> {
+ let cfm = DecryptorTag::from_name(&dict.get::<Name<'_>>(CFM)?)?;
+ // The standard security handler expresses the Length entry in bytes (e.g., 32 means a
+ // length of 256 bits) and public-key security handlers express it as is (e.g., 256 means a
+ // length of 256 bits).
+ // Note: We only support the standard security handler.
+ let mut length = dict.get::<u16>(LENGTH).unwrap_or(default_length / 8);
+
+ // When CFM is AESV2, the Length key shall have the value of 128. When
+ // CFM is AESV3, the Length key shall have a value of 256.
+ if cfm == DecryptorTag::Aes128 {
+ length = 16;
+ } else if cfm == DecryptorTag::Aes256 {
+ length = 32;
+ }
+
+ Some(Self {
+ cfm,
+ _length: length,
+ })
+ }
+
+ fn identity(default_length: u16) -> Self {
+ Self {
+ cfm: DecryptorTag::None,
+ _length: default_length,
+ }
+ }
+}
+
+/// Algorithm 2.B: Computing a hash (revision 6 and later)
+fn compute_hash_rev56(
+ password: &[u8],
+ validation_salt: &[u8],
+ user_string: Option<&[u8]>,
+ revision: u8,
+) -> Result<[u8; 32], DecryptionError> {
+ // Take the SHA-256 hash of the original input to the algorithm and name the resulting
+ // 32 bytes, K.
+ let mut k = {
+ let mut input = Vec::new();
+ input.extend_from_slice(password);
+ input.extend_from_slice(validation_salt);
+
+ if let Some(user_string) = user_string {
+ input.extend_from_slice(user_string);
+ }
+
+ let hash = sha256::calculate(&input);
+
+ // Apparently revision 5 only uses this hash.
+ if revision == 5 {
+ return Ok(hash);
+ }
+
+ hash.to_vec()
+ };
+
+ let mut round: u16 = 0;
+
+ // Perform the following steps (a)-(d) 64 times:
+ loop {
+ // a) Make a new string, K1, consisting of 64 repetitions of the sequence:
+ // input password, K, the 48-byte user key. The 48 byte user key is only used when
+ // checking the owner password or creating the owner key. If checking the user
+ // password or creating the user key, K1 is the concatenation of the input
+ // password and K.
+ let k1 = {
+ let mut single: Vec<u8> = vec![];
+ single.extend(password);
+ single.extend(&k);
+
+ if let Some(user_string) = user_string {
+ single.extend(user_string);
+ }
+
+ single.repeat(64)
+ };
+
+ // b) Encrypt K1 with the AES-128 (CBC, no padding) algorithm,
+ // using the first 16 bytes of K as the key and the second 16 bytes of K as the
+ // initialization vector. The result of this encryption is E.
+ let e = {
+ let aes = AES128Cipher::new(&k[..16]).ok_or(InvalidEncryption)?;
+ let mut res = aes.encrypt_cbc(&k1, &k[16..32].try_into().unwrap());
+
+ // Remove padding that was added by `encrypt_cbc`.
+ res.truncate(k1.len());
+
+ res
+ };
+
+ // c) Taking the first 16 bytes of E as an unsigned big-endian integer,
+ // compute the remainder, modulo 3. If the result is 0, the next hash used is
+ // SHA-256, if the result is 1, the next hash used is SHA-384, if the result is
+ // 2, the next hash used is SHA-512.
+ let num = u128::from_be_bytes(e[..16].try_into().unwrap()) % 3;
+
+ // d) Using the hash algorithm determined in step c, take the hash of E.
+ // The result is a new value of K, which will be 32, 48, or 64 bytes in length.
+ k = match num {
+ 0 => sha256::calculate(&e).to_vec(),
+ 1 => sha384::calculate(&e).to_vec(),
+ 2 => sha512::calculate(&e).to_vec(),
+ _ => unreachable!(),
+ };
+
+ round += 1;
+
+ // Repeat the process (a-d) with this new value for K. Following 64 rounds
+ // (round number 0 to round number 63), do the following, starting with round
+ // number 64:
+ if round > 63 {
+ // e) Look at the very last byte of E. If the value of that byte
+ // (taken as an unsigned integer) is greater than the round number - 32,
+ // repeat steps (a-d) again.
+ let last_byte = *e.last().unwrap();
+
+ // f) Repeat from steps (a-e) until the value of the last byte
+ // is < (round number) - 32.
+ // For some reason we need to use <= here?
+ if (last_byte as u16) <= round - 32 {
+ break;
+ }
+ }
+ }
+
+ // The first 32 bytes of the final K are the output of the algorithm.
+ let mut result = [0_u8; 32];
+ result.copy_from_slice(&k[..32]);
+ Ok(result)
+}
+
+/// Algorithm 2: Computing a file encryption key in order to encrypt a document (revision 4 and earlier)
+fn decryption_key_rev1234(
+ password: &[u8],
+ encrypt_metadata: bool,
+ revision: u8,
+ byte_length: u16,
+ owner_string: &object::String<'_>,
+ permissions: u32,
+ id: &[u8],
+) -> Result<Vec<u8>, DecryptionError> {
+ let mut md5_input = vec![];
+
+ // TODO: Convert to PDFDocEncoding.
+ // a) Pad or truncate password to 32 bytes using PASSWORD_PADDING.
+ let mut padded_password = [0_u8; 32];
+ let copy_len = password.len().min(32);
+ padded_password[..copy_len].copy_from_slice(&password[..copy_len]);
+ if copy_len < 32 {
+ padded_password[copy_len..].copy_from_slice(&PASSWORD_PADDING[..(32 - copy_len)]);
+ }
+
+ // b) Initialise the MD5 hash function and pass the
+ // result of step a) as input to this function.
+ md5_input.extend(&padded_password);
+
+ // c) Pass the value of the encryption dictionary's O entry
+ // to the MD5 hash function.
+ md5_input.extend(owner_string.as_ref());
+
+ // d) Convert the integer value of the P entry to a 32-bit unsigned
+ // binary number and pass these bytes to the MD5 hash function, low-order byte first.
+ md5_input.extend(permissions.to_le_bytes());
+
+ // e) Pass the first element of the file's file identifier array to the MD5 hash function.
+ md5_input.extend(id);
+
+ // f) (Security handlers of revision 4 or greater) If document metadata
+ // is not being encrypted, pass 4 bytes with the value 0xFFFFFFFF to the MD5 hash function.
+ if !encrypt_metadata && revision >= 4 {
+ md5_input.extend(&[0xff, 0xff, 0xff, 0xff]);
+ }
+
+ // g) Finish the hash.
+ let mut hash = md5::calculate(&md5_input);
+
+ // h) For revisions >= 3, do the following 50 times: Take the output from the previous
+ // MD5 hash and pass the first n bytes of the output as input into a new MD5 hash,
+ // where n is the number of bytes of the file encryption key as defined by the value
+ // of the encryption dictionary's `Length` entry.
+ if revision >= 3 {
+ for _ in 0..50 {
+ hash = md5::calculate(&hash[..byte_length as usize]);
+ }
+ }
+
+ let decryption_key = hash[..byte_length as usize].to_vec();
+ Ok(decryption_key)
+}
+
+/// Algorithm 6: Authenticating the user password
+fn authenticate_user_password_rev234(
+ revision: u8,
+ decryption_key: &[u8],
+ id: &[u8],
+ user_string: &object::String<'_>,
+) -> Result<(), DecryptionError> {
+ // a) Perform all but the last step of Algorithm 4 (revision 2) or Algorithm 5 (revision 3 + 4).
+ let result = match revision {
+ 2 => user_password_rev2(decryption_key),
+ 3 | 4 => user_password_rev34(decryption_key, id),
+ _ => return Err(InvalidEncryption),
+ };
+
+ // b) If the result of step (a) is equal to the value of the encryption dictionary's
+ // U entry (comparing on the first 16 bytes in the case of security handlers of
+ // revision 3 or greater), the password supplied is the correct user password.
+ match revision {
+ 2 => {
+ if result.as_slice() != user_string.as_ref() {
+ return Err(DecryptionError::PasswordProtected);
+ }
+ }
+ 3 | 4 => {
+ if Some(&result[..16]) != user_string.as_ref().get(0..16) {
+ return Err(DecryptionError::PasswordProtected);
+ }
+ }
+ _ => unreachable!(),
+ }
+
+ Ok(())
+}
+
+/// Algorithm 4: Computing the encryption dictionary’s U-entry value
+/// (Security handlers of revision 2).
+fn user_password_rev2(decryption_key: &[u8]) -> Vec<u8> {
+ // a) Create a file encryption key based on the user password string.
+ // b) Encrypt the 32-byte padding string using an RC4 encryption
+ // function with the file encryption key from the preceding step.
+ let mut rc = Rc4::new(decryption_key);
+ rc.decrypt(&PASSWORD_PADDING)
+}
+
+/// Algorithm 5: Computing the encryption dictionary’s U (user password)
+/// value (Security handlers of revision 3 or 4).
+fn user_password_rev34(decryption_key: &[u8], id: &[u8]) -> Vec<u8> {
+ // a) Create a file encryption key based on the user password string.
+ let mut rc = Rc4::new(decryption_key);
+
+ let mut input = vec![];
+ // b) Initialise the MD5 hash function and pass the 32-byte padding string.
+ input.extend(PASSWORD_PADDING);
+
+ // c) Pass the first element of the file's file identifier array to the hash function
+ // and finish the hash.
+ input.extend(id);
+ let hash = md5::calculate(&input);
+
+ // d) Encrypt the 16-byte result of the hash, using an RC4 encryption function with
+ // the encryption key from step (a).
+ let mut encrypted = rc.encrypt(&hash);
+
+ // e) Do the following 19 times: Take the output from the previous invocation of the
+ // RC4 function and pass it as input to a new invocation of the function; use a file
+ // encryption key generated by taking each byte of the original file encryption key
+ // obtained in step (a) and performing an XOR (exclusive or) operation between that
+ // byte and the single-byte value of the iteration counter (from 1 to 19).
+ for i in 1..=19 {
+ let mut key = decryption_key.to_vec();
+ for byte in &mut key {
+ *byte ^= i;
+ }
+
+ let mut rc = Rc4::new(&key);
+ encrypted = rc.encrypt(&encrypted);
+ }
+
+ encrypted.resize(32, 0);
+ encrypted
+}
+
+/// Algorithm 2.A: Retrieving the file encryption key from an encrypted document in order to decrypt it (revision 6 and later)
+fn decryption_key_rev56(
+ dict: &Dict<'_>,
+ revision: u8,
+ password: &[u8],
+ owner_string: &object::String<'_>,
+ user_string: &object::String<'_>,
+) -> Result<Vec<u8>, DecryptionError> {
+ // a) The UTF-8 password string shall be generated from Unicode input by processing the input string with
+ // the SASLprep (Internet RFC 4013) profile of stringprep (Internet RFC 3454) using the Normalize and BiDi
+ // options, and then converting to a UTF-8 representation.
+ // TODO: Do the above.
+ // b) Truncate the UTF-8 representation to 127 bytes if it is longer than 127 bytes.
+ let password = &password[..password.len().min(127)];
+
+ let string_len = if revision <= 4 { 32 } else { 48 };
+
+ let trimmed_os = owner_string.get(..string_len).ok_or(InvalidEncryption)?;
+
+ let (owner_hash, owner_tail) = trimmed_os.split_at_checked(32).ok_or(InvalidEncryption)?;
+ let (owner_validation_salt, owner_key_salt) =
+ owner_tail.split_at_checked(8).ok_or(InvalidEncryption)?;
+
+ let trimmed_us = user_string.get(..string_len).ok_or(InvalidEncryption)?;
+ let (user_hash, user_tail) = trimmed_us.split_at_checked(32).ok_or(InvalidEncryption)?;
+ let (user_validation_salt, user_key_salt) =
+ user_tail.split_at_checked(8).ok_or(InvalidEncryption)?;
+
+ // c) Test the password against the owner key by computing a hash using algorithm 2.B
+ // with an input string consisting of the UTF-8 password concatenated with the 8 bytes of
+ // owner Validation Salt, concatenated with the 48-byte U string. If the 32-byte result
+ // matches the first 32 bytes of the O string, this is the owner password.
+ if compute_hash_rev56(password, owner_validation_salt, Some(trimmed_us), revision)?
+ == owner_hash
+ {
+ // d) Compute an intermediate owner key by computing a hash using algorithm 2.B with an input string
+ // consisting of the UTF-8 owner password concatenated with the 8 bytes of owner Key Salt,
+ // concatenated with the 48-byte U string. The 32-byte result is the key used to decrypt the 32-byte OE string
+ // using AES-256 in CBC mode with no padding and an initialization vector of zero. The 32-byte result is the file encryption key.
+ let intermediate_owner_key =
+ compute_hash_rev56(password, owner_key_salt, Some(trimmed_us), revision)?;
+
+ let oe_string = dict
+ .get::<object::String<'_>>(OE)
+ .ok_or(InvalidEncryption)?;
+
+ if oe_string.len() != 32 {
+ return Err(InvalidEncryption);
+ }
+
+ let cipher = AES256Cipher::new(&intermediate_owner_key).ok_or(InvalidEncryption)?;
+ let zero_iv = [0_u8; 16];
+
+ Ok(cipher.decrypt_cbc(&oe_string, &zero_iv, false))
+ } else if compute_hash_rev56(password, user_validation_salt, None, revision)? == user_hash {
+ // e) Compute an intermediate user key by computing a hash using algorithm 2.B with an input string
+ // consisting of the UTF-8 user password concatenated with the 8 bytes of user Key Salt. The 32-byte result
+ // is the key used to decrypt the 32-byte UE string using AES-256 in CBC mode with no padding and an
+ // initialization vector of zero. The 32-byte result is the file encryption key.
+ let intermediate_key = compute_hash_rev56(password, user_key_salt, None, revision)?;
+
+ let ue_string = dict
+ .get::<object::String<'_>>(UE)
+ .ok_or(InvalidEncryption)?;
+
+ if ue_string.len() != 32 {
+ return Err(InvalidEncryption);
+ }
+
+ let cipher = AES256Cipher::new(&intermediate_key).ok_or(InvalidEncryption)?;
+ let zero_iv = [0_u8; 16];
+
+ Ok(cipher.decrypt_cbc(&ue_string, &zero_iv, false))
+ } else {
+ Err(DecryptionError::PasswordProtected)
+ }
+
+ // TODO:
+ // f) Decrypt the 16-byte Perms string using AES-256 in ECB mode with an initialization vector of zero and
+ // the file encryption key as the key. Verify that bytes 9-11 of the result are the characters "a", "d",
+ // "b". Bytes 0-3 of the decrypted Perms entry, treated as a little-endian integer, are the user
+ // permissions. They shall match the value in the P key.
+}
diff --git a/vendor/hayro-syntax/src/crypto/rc4.rs b/vendor/hayro-syntax/src/crypto/rc4.rs
new file mode 100644
index 000000000..46dd1b6e4
--- /dev/null
+++ b/vendor/hayro-syntax/src/crypto/rc4.rs
@@ -0,0 +1,125 @@
+//! Ported from <https://github.com/mozilla/pdf.js/blob/master/src/core/crypto.js>.
+
+use alloc::vec;
+use alloc::vec::Vec;
+
+#[derive(Clone)]
+pub(crate) struct Rc4 {
+ a: u8,
+ b: u8,
+ s: [u8; 256],
+}
+
+impl Rc4 {
+ pub(crate) fn new(key: &[u8]) -> Self {
+ let mut s = [0_u8; 256];
+ let key_length = key.len();
+
+ for (i, s) in s.iter_mut().enumerate() {
+ *s = i as u8;
+ }
+
+ let mut j = 0_u8;
+ for i in 0..256 {
+ let tmp = s[i];
+ j = j.wrapping_add(tmp).wrapping_add(key[i % key_length]);
+ s[i] = s[j as usize];
+ s[j as usize] = tmp;
+ }
+
+ Self { a: 0, b: 0, s }
+ }
+
+ pub(crate) fn decrypt(&mut self, data: &[u8]) -> Vec<u8> {
+ let n = data.len();
+ let mut output = vec![0_u8; n];
+
+ for i in 0..n {
+ self.a = self.a.wrapping_add(1);
+ let tmp = self.s[self.a as usize];
+ self.b = self.b.wrapping_add(tmp);
+ let tmp2 = self.s[self.b as usize];
+ self.s[self.a as usize] = tmp2;
+ self.s[self.b as usize] = tmp;
+ output[i] = data[i] ^ self.s[tmp.wrapping_add(tmp2) as usize];
+ }
+
+ output
+ }
+
+ pub(crate) fn encrypt(&mut self, data: &[u8]) -> Vec<u8> {
+ self.decrypt(data)
+ }
+}
+
+#[cfg(test)]
+mod rc4_tests {
+ use crate::crypto::rc4::Rc4;
+
+ fn rc4_decrypt(key: &[u8], input: &[u8]) -> Vec<u8> {
+ let mut cipher = Rc4::new(key);
+ cipher.decrypt(input)
+ }
+
+ #[test]
+ fn correctness() {
+ assert_eq!(rc4_decrypt(b"a", &[0x68]), b"x");
+ assert_eq!(rc4_decrypt(b"key", &[0x7F, 0x09, 0x47, 0x99]), b"test");
+ assert_eq!(
+ rc4_decrypt(b"hello", &[0x78, 0x3E, 0xCD, 0x96, 0xCF]),
+ b"world"
+ );
+ assert_eq!(rc4_decrypt(b"\x01\x02", &[0x0C, 0x74, 0xB9]), b"Hi!");
+ assert_eq!(rc4_decrypt(b"secret", &[0x80, 0x45, 0xB5]), b"msg");
+
+ assert_eq!(
+ rc4_decrypt(
+ b"encryption",
+ &[
+ 0x8A, 0x36, 0x3F, 0x85, 0xDB, 0x9A, 0x62, 0x7C, 0x6C, 0x56, 0x81, 0x89
+ ]
+ ),
+ b"Hello World!"
+ );
+ assert_eq!(
+ rc4_decrypt(
+ b"my_secret_key",
+ &[
+ 0x1D, 0xE2, 0xCE, 0x64, 0x4C, 0x88, 0x1C, 0x42, 0x7D, 0x94, 0x7B, 0x1C, 0x49,
+ 0xCD, 0x62, 0x3F, 0xCA, 0x90, 0x99
+ ]
+ ),
+ b"The quick brown fox"
+ );
+ assert_eq!(
+ rc4_decrypt(
+ b"abcdefghijklmnop",
+ &[
+ 0xF8, 0xA8, 0x2A, 0xAE, 0x92, 0x2F, 0x8C, 0x3B, 0x13, 0xC7, 0x4B, 0x99, 0xDB,
+ 0x41, 0x2C, 0x9F, 0x92, 0x59, 0xC2, 0xE5, 0x62, 0x2C
+ ]
+ ),
+ b"This is a test message"
+ );
+ assert_eq!(
+ rc4_decrypt(
+ b"password123",
+ &[
+ 0xDB, 0xC3, 0xA3, 0x21, 0x7E, 0x55, 0x0B, 0x65, 0xA2, 0x3F, 0x0E, 0xB7, 0x58,
+ 0x7C, 0x28, 0xEE, 0xD6, 0x92, 0x05, 0xBC, 0x6C
+ ]
+ ),
+ b"Decryption successful"
+ );
+ assert_eq!(
+ rc4_decrypt(
+ b"very_long_key",
+ &[
+ 0xC6, 0xD2, 0x00, 0x3B, 0x8C, 0x18, 0x49, 0x2C, 0xD0, 0x5C, 0x8A, 0x34, 0xEC,
+ 0xFE, 0xED, 0x62, 0xC0, 0x3C, 0x80, 0x81, 0x7E, 0x4E, 0xE1, 0x7D, 0xBD
+ ]
+ ),
+ b"PDF uses RC4 for security"
+ );
+ }
+}
diff --git a/vendor/hayro-syntax/src/crypto/sha256.rs b/vendor/hayro-syntax/src/crypto/sha256.rs
new file mode 100644
index 000000000..968a024ba
--- /dev/null
+++ b/vendor/hayro-syntax/src/crypto/sha256.rs
@@ -0,0 +1,151 @@
+//! Ported from <https://github.com/mozilla/pdf.js/blob/master/src/core/calculate_sha256.js>.
+
+use alloc::vec;
+
+const K: [u32; 64] = [
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
+];
+
+#[inline]
+const fn rotr(x: u32, n: u32) -> u32 {
+ x.rotate_right(n)
+}
+
+#[inline]
+const fn ch(x: u32, y: u32, z: u32) -> u32 {
+ (x & y) ^ (!x & z)
+}
+
+#[inline]
+const fn maj(x: u32, y: u32, z: u32) -> u32 {
+ (x & y) ^ (x & z) ^ (y & z)
+}
+
+#[inline]
+const fn sigma_0(x: u32) -> u32 {
+ rotr(x, 2) ^ rotr(x, 13) ^ rotr(x, 22)
+}
+
+#[inline]
+const fn sigma_1(x: u32) -> u32 {
+ rotr(x, 6) ^ rotr(x, 11) ^ rotr(x, 25)
+}
+
+#[inline]
+const fn little_sigma_0(x: u32) -> u32 {
+ rotr(x, 7) ^ rotr(x, 18) ^ (x >> 3)
+}
+
+#[inline]
+const fn little_sigma_1(x: u32) -> u32 {
+ rotr(x, 17) ^ rotr(x, 19) ^ (x >> 10)
+}
+
+pub(crate) fn calculate(data: &[u8]) -> [u8; 32] {
+ let mut h = [
+ 0x6a09e667_u32,
+ 0xbb67ae85,
+ 0x3c6ef372,
+ 0xa54ff53a,
+ 0x510e527f,
+ 0x9b05688c,
+ 0x1f83d9ab,
+ 0x5be0cd19,
+ ];
+
+ let bit_len = data.len() as u64 * 8;
+ let padded_len = (data.len() + 9).div_ceil(64) * 64;
+ let mut padded = vec![0_u8; padded_len];
+
+ padded[..data.len()].copy_from_slice(data);
+ padded[data.len()] = 0x80;
+
+ let len_bytes = bit_len.to_be_bytes();
+ padded[padded_len - 8..].copy_from_slice(&len_bytes);
+
+ for chunk in padded.chunks_exact(64) {
+ let mut w = [0_u32; 64];
+
+ for (i, word_bytes) in chunk.chunks_exact(4).enumerate() {
+ w[i] = u32::from_be_bytes([word_bytes[0], word_bytes[1], word_bytes[2], word_bytes[3]]);
+ }
+
+ for i in 16..64 {
+ w[i] = little_sigma_1(w[i - 2])
+ .wrapping_add(w[i - 7])
+ .wrapping_add(little_sigma_0(w[i - 15]))
+ .wrapping_add(w[i - 16]);
+ }
+
+ let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h_var] = h;
+
+ for i in 0..64 {
+ let temp1 = h_var
+ .wrapping_add(sigma_1(e))
+ .wrapping_add(ch(e, f, g))
+ .wrapping_add(K[i])
+ .wrapping_add(w[i]);
+ let temp2 = sigma_0(a).wrapping_add(maj(a, b, c));
+
+ h_var = g;
+ g = f;
+ f = e;
+ e = d.wrapping_add(temp1);
+ d = c;
+ c = b;
+ b = a;
+ a = temp1.wrapping_add(temp2);
+ }
+
+ h[0] = h[0].wrapping_add(a);
+ h[1] = h[1].wrapping_add(b);
+ h[2] = h[2].wrapping_add(c);
+ h[3] = h[3].wrapping_add(d);
+ h[4] = h[4].wrapping_add(e);
+ h[5] = h[5].wrapping_add(f);
+ h[6] = h[6].wrapping_add(g);
+ h[7] = h[7].wrapping_add(h_var);
+ }
+
+ let mut result = [0_u8; 32];
+ for (i, &hash_word) in h.iter().enumerate() {
+ let bytes = hash_word.to_be_bytes();
+ result[i * 4..(i + 1) * 4].copy_from_slice(&bytes);
+ }
+
+ result
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use sha2::{Digest, Sha256};
+
+ #[test]
+ fn correctness() {
+ let test_cases = [
+ b"" as &[u8],
+ b"a",
+ b"abc",
+ b"Hello, World!",
+ &[0xde, 0xad, 0xbe, 0xef],
+ ];
+
+ for test_case in test_cases {
+ let our_result = calculate(test_case);
+ let expected = Sha256::digest(test_case);
+ assert_eq!(
+ our_result,
+ expected.as_slice(),
+ "Failed for input: {test_case:?}"
+ );
+ }
+ }
+}
diff --git a/vendor/hayro-syntax/src/crypto/sha384.rs b/vendor/hayro-syntax/src/crypto/sha384.rs
new file mode 100644
index 000000000..d046f4609
--- /dev/null
+++ b/vendor/hayro-syntax/src/crypto/sha384.rs
@@ -0,0 +1,51 @@
+//! Ported from <https://github.com/mozilla/pdf.js/blob/master/src/core/calculate_sha_other.js>.
+
+pub(crate) fn calculate(data: &[u8]) -> [u8; 48] {
+ let mut h = [
+ 0xcbbb9d5dc1059ed8_u64,
+ 0x629a292a367cd507,
+ 0x9159015a3070dd17,
+ 0x152fecd8f70e5939,
+ 0x67332667ffc00b31,
+ 0x8eb44a8768581511,
+ 0xdb0c2e0d64f98fa7,
+ 0x47b5481dbefa4fa4,
+ ];
+
+ super::sha512::calculate_with_initial_values(data, &mut h);
+
+ let mut result = [0_u8; 48];
+ for (i, &hash_word) in h.iter().take(6).enumerate() {
+ let bytes = hash_word.to_be_bytes();
+ result[i * 8..(i + 1) * 8].copy_from_slice(&bytes);
+ }
+
+ result
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use sha2::{Digest, Sha384};
+
+ #[test]
+ fn correctness() {
+ let test_cases = [
+ b"" as &[u8],
+ b"a",
+ b"abc",
+ b"Hello, World!",
+ &[0xde, 0xad, 0xbe, 0xef],
+ ];
+
+ for test_case in test_cases {
+ let our_result = calculate(test_case);
+ let expected = Sha384::digest(test_case);
+ assert_eq!(
+ our_result,
+ expected.as_slice(),
+ "Failed for input: {test_case:?}"
+ );
+ }
+ }
+}
diff --git a/vendor/hayro-syntax/src/crypto/sha512.rs b/vendor/hayro-syntax/src/crypto/sha512.rs
new file mode 100644
index 000000000..b1d3e9ed3
--- /dev/null
+++ b/vendor/hayro-syntax/src/crypto/sha512.rs
@@ -0,0 +1,237 @@
+//! Ported from <https://github.com/mozilla/pdf.js/blob/master/src/core/calculate_sha_other.js>.
+
+use alloc::vec;
+
+pub(super) const K: [u64; 80] = [
+ 0x428a2f98d728ae22,
+ 0x7137449123ef65cd,
+ 0xb5c0fbcfec4d3b2f,
+ 0xe9b5dba58189dbbc,
+ 0x3956c25bf348b538,
+ 0x59f111f1b605d019,
+ 0x923f82a4af194f9b,
+ 0xab1c5ed5da6d8118,
+ 0xd807aa98a3030242,
+ 0x12835b0145706fbe,
+ 0x243185be4ee4b28c,
+ 0x550c7dc3d5ffb4e2,
+ 0x72be5d74f27b896f,
+ 0x80deb1fe3b1696b1,
+ 0x9bdc06a725c71235,
+ 0xc19bf174cf692694,
+ 0xe49b69c19ef14ad2,
+ 0xefbe4786384f25e3,
+ 0x0fc19dc68b8cd5b5,
+ 0x240ca1cc77ac9c65,
+ 0x2de92c6f592b0275,
+ 0x4a7484aa6ea6e483,
+ 0x5cb0a9dcbd41fbd4,
+ 0x76f988da831153b5,
+ 0x983e5152ee66dfab,
+ 0xa831c66d2db43210,
+ 0xb00327c898fb213f,
+ 0xbf597fc7beef0ee4,
+ 0xc6e00bf33da88fc2,
+ 0xd5a79147930aa725,
+ 0x06ca6351e003826f,
+ 0x142929670a0e6e70,
+ 0x27b70a8546d22ffc,
+ 0x2e1b21385c26c926,
+ 0x4d2c6dfc5ac42aed,
+ 0x53380d139d95b3df,
+ 0x650a73548baf63de,
+ 0x766a0abb3c77b2a8,
+ 0x81c2c92e47edaee6,
+ 0x92722c851482353b,
+ 0xa2bfe8a14cf10364,
+ 0xa81a664bbc423001,
+ 0xc24b8b70d0f89791,
+ 0xc76c51a30654be30,
+ 0xd192e819d6ef5218,
+ 0xd69906245565a910,
+ 0xf40e35855771202a,
+ 0x106aa07032bbd1b8,
+ 0x19a4c116b8d2d0c8,
+ 0x1e376c085141ab53,
+ 0x2748774cdf8eeb99,
+ 0x34b0bcb5e19b48a8,
+ 0x391c0cb3c5c95a63,
+ 0x4ed8aa4ae3418acb,
+ 0x5b9cca4f7763e373,
+ 0x682e6ff3d6b2b8a3,
+ 0x748f82ee5defb2fc,
+ 0x78a5636f43172f60,
+ 0x84c87814a1f0ab72,
+ 0x8cc702081a6439ec,
+ 0x90befffa23631e28,
+ 0xa4506cebde82bde9,
+ 0xbef9a3f7b2c67915,
+ 0xc67178f2e372532b,
+ 0xca273eceea26619c,
+ 0xd186b8c721c0c207,
+ 0xeada7dd6cde0eb1e,
+ 0xf57d4f7fee6ed178,
+ 0x06f067aa72176fba,
+ 0x0a637dc5a2c898a6,
+ 0x113f9804bef90dae,
+ 0x1b710b35131c471b,
+ 0x28db77f523047d84,
+ 0x32caab7b40c72493,
+ 0x3c9ebe0a15c9bebc,
+ 0x431d67c49c100d4c,
+ 0x4cc5d4becb3e42b6,
+ 0x597f299cfc657e2a,
+ 0x5fcb6fab3ad6faec,
+ 0x6c44198c4a475817,
+];
+
+#[inline]
+const fn rotr(x: u64, n: u32) -> u64 {
+ x.rotate_right(n)
+}
+
+#[inline]
+pub(super) const fn ch(x: u64, y: u64, z: u64) -> u64 {
+ (x & y) ^ (!x & z)
+}
+
+#[inline]
+pub(super) const fn maj(x: u64, y: u64, z: u64) -> u64 {
+ (x & y) ^ (x & z) ^ (y & z)
+}
+
+#[inline]
+pub(super) const fn sigma_0(x: u64) -> u64 {
+ rotr(x, 28) ^ rotr(x, 34) ^ rotr(x, 39)
+}
+
+#[inline]
+pub(super) const fn sigma_1(x: u64) -> u64 {
+ rotr(x, 14) ^ rotr(x, 18) ^ rotr(x, 41)
+}
+
+#[inline]
+pub(super) const fn little_sigma_0(x: u64) -> u64 {
+ rotr(x, 1) ^ rotr(x, 8) ^ (x >> 7)
+}
+
+#[inline]
+pub(super) const fn little_sigma_1(x: u64) -> u64 {
+ rotr(x, 19) ^ rotr(x, 61) ^ (x >> 6)
+}
+
+pub(super) fn calculate_with_initial_values(data: &[u8], h: &mut [u64; 8]) {
+ let bit_len = data.len() as u128 * 8;
+ let padded_len = (data.len() + 17).div_ceil(128) * 128; // Round up to nearest multiple of 128
+ let mut padded = vec![0_u8; padded_len];
+
+ padded[..data.len()].copy_from_slice(data);
+
+ padded[data.len()] = 0x80;
+
+ let len_bytes = bit_len.to_be_bytes();
+ padded[padded_len - 16..].copy_from_slice(&len_bytes);
+
+ for chunk in padded.chunks_exact(128) {
+ let mut w = [0_u64; 80];
+
+ for (i, word_bytes) in chunk.chunks_exact(8).enumerate() {
+ w[i] = u64::from_be_bytes([
+ word_bytes[0],
+ word_bytes[1],
+ word_bytes[2],
+ word_bytes[3],
+ word_bytes[4],
+ word_bytes[5],
+ word_bytes[6],
+ word_bytes[7],
+ ]);
+ }
+
+ for i in 16..80 {
+ w[i] = little_sigma_1(w[i - 2])
+ .wrapping_add(w[i - 7])
+ .wrapping_add(little_sigma_0(w[i - 15]))
+ .wrapping_add(w[i - 16]);
+ }
+
+ let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h_var] = *h;
+
+ for i in 0..80 {
+ let temp1 = h_var
+ .wrapping_add(sigma_1(e))
+ .wrapping_add(ch(e, f, g))
+ .wrapping_add(K[i])
+ .wrapping_add(w[i]);
+ let temp2 = sigma_0(a).wrapping_add(maj(a, b, c));
+
+ h_var = g;
+ g = f;
+ f = e;
+ e = d.wrapping_add(temp1);
+ d = c;
+ c = b;
+ b = a;
+ a = temp1.wrapping_add(temp2);
+ }
+
+ h[0] = h[0].wrapping_add(a);
+ h[1] = h[1].wrapping_add(b);
+ h[2] = h[2].wrapping_add(c);
+ h[3] = h[3].wrapping_add(d);
+ h[4] = h[4].wrapping_add(e);
+ h[5] = h[5].wrapping_add(f);
+ h[6] = h[6].wrapping_add(g);
+ h[7] = h[7].wrapping_add(h_var);
+ }
+}
+
+pub(crate) fn calculate(data: &[u8]) -> [u8; 64] {
+ let mut h = [
+ 0x6a09e667f3bcc908_u64,
+ 0xbb67ae8584caa73b,
+ 0x3c6ef372fe94f82b,
+ 0xa54ff53a5f1d36f1,
+ 0x510e527fade682d1,
+ 0x9b05688c2b3e6c1f,
+ 0x1f83d9abfb41bd6b,
+ 0x5be0cd19137e2179,
+ ];
+
+ calculate_with_initial_values(data, &mut h);
+
+ let mut result = [0_u8; 64];
+ for (i, &hash_word) in h.iter().enumerate() {
+ let bytes = hash_word.to_be_bytes();
+ result[i * 8..(i + 1) * 8].copy_from_slice(&bytes);
+ }
+
+ result
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use sha2::{Digest, Sha512};
+
+ #[test]
+ fn correctness() {
+ let test_cases = [
+ b"" as &[u8],
+ b"a",
+ b"abc",
+ b"Hello, World!",
+ &[0xde, 0xad, 0xbe, 0xef],
+ ];
+
+ for test_case in test_cases {
+ let our_result = calculate(test_case);
+ let expected = Sha512::digest(test_case);
+ assert_eq!(
+ our_result,
+ expected.as_slice(),
+ "Failed for input: {test_case:?}"
+ );
+ }
+ }
+}
diff --git a/vendor/hayro-syntax/src/data.rs b/vendor/hayro-syntax/src/data.rs
new file mode 100644
index 000000000..5c5a6b446
--- /dev/null
+++ b/vendor/hayro-syntax/src/data.rs
@@ -0,0 +1,113 @@
+use crate::object::ObjectIdentifier;
+use crate::object::Stream;
+use crate::reader::ReaderContext;
+use crate::sync::HashMap;
+use crate::sync::{Arc, Mutex, MutexExt};
+use crate::util::SegmentList;
+use alloc::borrow::Cow;
+use alloc::vec::Vec;
+use core::fmt::{Debug, Formatter};
+
+/// A container for the bytes of a PDF file.
+#[derive(Clone)]
+pub struct PdfData {
+ #[cfg(feature = "std")]
+ inner: Arc<dyn AsRef<[u8]> + Send + Sync>,
+ #[cfg(not(feature = "std"))]
+ inner: Arc<dyn AsRef<[u8]>>,
+}
+
+impl Debug for PdfData {
+ fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
+ write!(f, "PdfData {{ ... }}")
+ }
+}
+
+impl AsRef<[u8]> for PdfData {
+ fn as_ref(&self) -> &[u8] {
+ (*self.inner).as_ref()
+ }
+}
+
+#[cfg(feature = "std")]
+impl<T: AsRef<[u8]> + Send + Sync + 'static> From<Arc<T>> for PdfData {
+ fn from(data: Arc<T>) -> Self {
+ Self { inner: data }
+ }
+}
+
+#[cfg(not(feature = "std"))]
+impl<T: AsRef<[u8]> + 'static> From<Arc<T>> for PdfData {
+ fn from(data: Arc<T>) -> Self {
+ Self { inner: data }
+ }
+}
+
+impl From<Vec<u8>> for PdfData {
+ fn from(data: Vec<u8>) -> Self {
+ Self {
+ inner: Arc::new(data),
+ }
+ }
+}
+
+/// A structure for storing the data of the PDF.
+// To explain further: This crate uses a zero-parse approach, meaning that objects like
+// dictionaries or arrays always store the underlying data and parse objects lazily as needed,
+// instead of allocating the data and storing it in an owned way. However, the problem is that
+// not all data is readily available in the original data of the PDF: Objects can also be
+// stored in an object streams, in which case we first need to decode the stream before we can
+// access the data.
+//
+// The purpose of `Data` is to allow us to access the original data as well as maybe decoded data
+// by faking the same lifetime, so that we don't run into lifetime issues when dealing with
+// PDF objects that actually stem from different data sources.
+pub(crate) struct Data {
+ data: PdfData,
+ // 32 segments are more than enough as we can't have more objects than this.
+ decoded: SegmentList<Option<Vec<u8>>, 32>,
+ map: Mutex<HashMap<ObjectIdentifier, usize>>,
+}
+
+impl Debug for Data {
+ fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
+ write!(f, "Data {{ ... }}")
+ }
+}
+
+impl Data {
+ /// Create a new `Data` structure.
+ pub(crate) fn new(data: PdfData) -> Self {
+ Self {
+ data,
+ decoded: SegmentList::new(),
+ map: Mutex::new(HashMap::new()),
+ }
+ }
+
+ /// Get access to the original data of the PDF.
+ pub(crate) fn get(&self) -> &PdfData {
+ &self.data
+ }
+
+ /// Get access to the data of a decoded object stream.
+ pub(crate) fn get_with(&self, id: ObjectIdentifier, ctx: &ReaderContext<'_>) -> Option<&[u8]> {
+ if let Some(&idx) = self.map.get().get(&id) {
+ self.decoded.get(idx)?.as_deref()
+ } else {
+ // Block scope to keep the lock short-lived.
+ let idx = {
+ let mut locked = self.map.get();
+ let idx = locked.len();
+ locked.insert(id, idx);
+ idx
+ };
+ self.decoded
+ .get_or_init(idx, || {
+ let stream = ctx.xref().get_with::<Stream<'_>>(id, ctx)?;
+ stream.decoded().ok().map(Cow::into_owned)
+ })
+ .as_deref()
+ }
+ }
+}
diff --git a/vendor/hayro-syntax/src/filter/ascii_85.rs b/vendor/hayro-syntax/src/filter/ascii_85.rs
new file mode 100644
index 000000000..5a18cf835
--- /dev/null
+++ b/vendor/hayro-syntax/src/filter/ascii_85.rs
@@ -0,0 +1,91 @@
+// Keep in sync with `hayro-postscript/src/string/ascii_85.rs`.
+
+use crate::reader::Reader;
+use crate::trivia::is_white_space_character;
+use alloc::vec::Vec;
+
+pub(crate) fn decode(data: &[u8]) -> Option<Vec<u8>> {
+ const POW_85: [u32; 5] = [52200625, 614125, 7225, 85, 1];
+
+ let mut reader = Reader::new(data);
+
+ let mut read_byte = || -> Option<u8> {
+ loop {
+ let b = reader.read_byte()?;
+
+ // White space characters should be ignored.
+ if !is_white_space_character(b) {
+ return Some(b);
+ }
+ }
+ };
+
+ let flush_group = |group: &mut Vec<u8>, decoded: &mut Vec<u8>| -> Option<()> {
+ let (digits, output_len): ([u32; 5], usize) = match group.len() {
+ 0 => return Some(()),
+ 1 => return None, // A single character is not valid.
+ 2 => (
+ [group[0], group[1], b'u', b'u', b'u'].map(|b| (b - b'!') as u32),
+ 1,
+ ),
+ 3 => (
+ [group[0], group[1], group[2], b'u', b'u'].map(|b| (b - b'!') as u32),
+ 2,
+ ),
+ 4 => (
+ [group[0], group[1], group[2], group[3], b'u'].map(|b| (b - b'!') as u32),
+ 3,
+ ),
+ 5 => (
+ [group[0], group[1], group[2], group[3], group[4]].map(|b| (b - b'!') as u32),
+ 4,
+ ),
+ _ => unreachable!(),
+ };
+
+ let value = digits[0]
+ .checked_mul(POW_85[0])?
+ .checked_add(digits[1].checked_mul(POW_85[1])?)?
+ .checked_add(digits[2].checked_mul(POW_85[2])?)?
+ .checked_add(digits[3].checked_mul(POW_85[3])?)?
+ .checked_add(digits[4])?;
+
+ decoded.extend_from_slice(&value.to_be_bytes()[..output_len]);
+ group.clear();
+ Some(())
+ };
+
+ let mut decoded = Vec::with_capacity(data.len() * 4 / 5);
+ let mut group = Vec::with_capacity(5);
+
+ loop {
+ let Some(b) = read_byte() else {
+ // Be lenient and accept what we have (see PDFBOX-5910).
+ flush_group(&mut group, &mut decoded)?;
+
+ return Some(decoded);
+ };
+
+ match b {
+ b'!'..=b'u' => {
+ group.push(b);
+
+ if group.len() == 5 {
+ flush_group(&mut group, &mut decoded)?;
+ }
+ }
+ b'z' => {
+ flush_group(&mut group, &mut decoded)?;
+ decoded.extend_from_slice(&[0, 0, 0, 0]);
+ }
+ b'~' => {
+ // Technically requires a '>', but there is a PDF where it isn't
+ // appended and decodes fine in other viewers.
+ flush_group(&mut group, &mut decoded)?;
+
+ return Some(decoded);
+ }
+ _ => return None, // Invalid character.
+ }
+ }
+}
diff --git a/vendor/hayro-syntax/src/filter/ascii_hex.rs b/vendor/hayro-syntax/src/filter/ascii_hex.rs
new file mode 100644
index 000000000..edcd82d5b
--- /dev/null
+++ b/vendor/hayro-syntax/src/filter/ascii_hex.rs
@@ -0,0 +1,108 @@
+// Keep in sync with `hayro-postscript/src/string/ascii_hex.rs`.
+
+use crate::trivia::is_white_space_character;
+use crate::util::ByteBuf;
+use alloc::vec::Vec;
+
+pub(crate) fn decode(data: &[u8]) -> Option<Vec<u8>> {
+ decode_into(data)
+}
+
+pub(crate) fn decode_into<B: ByteBuf>(data: &[u8]) -> Option<B> {
+ // Find end (at `>` or end of data) and check for whitespace.
+ let mut has_whitespace = false;
+ let mut end = data.len();
+
+ for (idx, byte) in data.iter().enumerate() {
+ has_whitespace |= is_white_space_character(*byte);
+
+ if *byte == b'>' {
+ end = idx;
+ break;
+ }
+ }
+
+ let data = &data[..end];
+ let mut decoded = B::with_capacity(data.len().div_ceil(2));
+
+ if !has_whitespace {
+ // Fast path, don't need to worry about white spaces.
+ let (chunks, remainder) = data.as_chunks::<2>();
+
+ for &[hi, lo] in chunks {
+ decoded.push(decode_hex_digit(hi)? << 4 | decode_hex_digit(lo)?);
+ }
+
+ if let [hi] = remainder {
+ decoded.push(decode_hex_digit(*hi)? << 4);
+ }
+ } else {
+ // Slow path, need to strip white spaces.
+ let mut iter = data.iter().copied();
+ let mut read_byte = || -> Option<u8> {
+ loop {
+ let b = iter.next()?;
+ if !is_white_space_character(b) {
+ return Some(b);
+ }
+ }
+ };
+
+ loop {
+ match (read_byte(), read_byte()) {
+ (Some(hi), Some(lo)) => {
+ decoded.push(decode_hex_digit(hi)? << 4 | decode_hex_digit(lo)?);
+ }
+ (Some(hi), None) => {
+ decoded.push(decode_hex_digit(hi)? << 4);
+
+ break;
+ }
+ (None, _) => break,
+ }
+ }
+ }
+
+ Some(decoded)
+}
+
+#[inline(always)]
+pub(crate) fn decode_hex_digit(c: u8) -> Option<u8> {
+ match c {
+ b'0'..=b'9' => Some(c - b'0'),
+ b'A'..=b'F' => Some(c - b'A' + 10),
+ b'a'..=b'f' => Some(c - b'a' + 10),
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::filter::ascii_hex::decode;
+
+ #[test]
+ fn decode_simple() {
+ let input = b"AF3E2901>";
+ assert_eq!(decode(input).unwrap(), vec![0xaf, 0x3e, 0x29, 0x01]);
+ }
+
+ #[test]
+ fn decode_whitespaces() {
+ let input = b"AF3 E2 901>";
+ assert_eq!(decode(input).unwrap(), vec![0xaf, 0x3e, 0x29, 0x01]);
+ }
+
+ #[test]
+ // Not valid for ASCII hex streams since they require a trailing >,
+ // but used by PDF hex strings as well.
+ fn decode_without_gt() {
+ let input = b"AF3E2901";
+ assert_eq!(decode(input).unwrap(), vec![0xaf, 0x3e, 0x29, 0x01]);
+ }
+
+ #[test]
+ fn decode_with_padding() {
+ let input = b"AF3E291>";
+ assert_eq!(decode(input).unwrap(), vec![0xaf, 0x3e, 0x29, 0x10]);
+ }
+}
diff --git a/vendor/hayro-syntax/src/filter/ccitt.rs b/vendor/hayro-syntax/src/filter/ccitt.rs
new file mode 100644
index 000000000..b96fc4950
--- /dev/null
+++ b/vendor/hayro-syntax/src/filter/ccitt.rs
@@ -0,0 +1,151 @@
+use crate::object::Dict;
+use crate::object::dict::keys::{
+ BLACK_IS_1, COLUMNS, ENCODED_BYTE_ALIGN, END_OF_BLOCK, END_OF_LINE, K, ROWS,
+};
+use crate::object::stream::{FilterResult, ImageColorSpace, ImageData, ImageDecodeParams};
+use alloc::borrow::Cow;
+use alloc::vec::Vec;
+use core::iter;
+use hayro_ccitt::{DecodeSettings, Decoder, DecoderContext, EncodingMode};
+
+pub(crate) fn decode(
+ data: &[u8],
+ params: &Dict<'_>,
+ image_params: &ImageDecodeParams,
+) -> Option<FilterResult<'static>> {
+ let k = params.get::<i32>(K).unwrap_or(0);
+
+ let rows = params.get::<u32>(ROWS).unwrap_or(image_params.height);
+ let end_of_block = params.get::<bool>(END_OF_BLOCK).unwrap_or(true);
+
+ let settings = DecodeSettings {
+ columns: params.get::<usize>(COLUMNS).unwrap_or(1728) as u32,
+ rows,
+ end_of_block,
+ end_of_line: params.get::<bool>(END_OF_LINE).unwrap_or(false),
+ rows_are_byte_aligned: params.get::<bool>(ENCODED_BYTE_ALIGN).unwrap_or(false),
+ encoding: if k < 0 {
+ EncodingMode::Group4
+ } else if k == 0 {
+ EncodingMode::Group3_1D
+ } else {
+ EncodingMode::Group3_2D { k: k as u32 }
+ },
+ invert_black: params.get::<bool>(BLACK_IS_1).unwrap_or(false),
+ };
+
+ // Whenever possible (if we don't have an indexed color space), we convert
+ // the data as 8-bit instead of 1-bit, so that it can be easier converted
+ // into an RGBA8 image.
+
+ let (decoded, bpc) = if image_params.is_indexed {
+ struct BitPackDecoder {
+ output: Vec<u8>,
+ decoded_rows: u32,
+ buffer: u8,
+ bit_count: u8,
+ }
+
+ impl BitPackDecoder {
+ fn push_bit(&mut self, white: bool) {
+ let bit = if white { 1 } else { 0 };
+ self.buffer = (self.buffer << 1) | bit;
+ self.bit_count += 1;
+
+ if self.bit_count == 8 {
+ self.output.push(self.buffer);
+ self.buffer = 0;
+ self.bit_count = 0;
+ }
+ }
+
+ fn flush(&mut self) {
+ if self.bit_count > 0 {
+ let padded = self.buffer << (8 - self.bit_count);
+ self.output.push(padded);
+ self.buffer = 0;
+ self.bit_count = 0;
+ }
+ }
+ }
+
+ impl Decoder for BitPackDecoder {
+ fn push_pixel(&mut self, white: bool) {
+ self.push_bit(white);
+ }
+
+ fn push_pixel_chunk(&mut self, white: bool, chunk_count: u32) {
+ let byte = if white { 0xFF } else { 0x00 };
+ self.output
+ .extend(iter::repeat_n(byte, chunk_count as usize));
+ }
+
+ fn next_line(&mut self) {
+ self.decoded_rows += 1;
+ self.flush();
+ }
+ }
+
+ let mut decoder = BitPackDecoder {
+ output: Vec::new(),
+ decoded_rows: 0,
+ buffer: 0,
+ bit_count: 0,
+ };
+ let mut context = DecoderContext::new(settings);
+ let result = hayro_ccitt::decode(data, &mut decoder, &mut context);
+
+ // If we decoded at least one row, let's be lenient and return what we got.
+ // See also 0001763.pdf.
+ if result.is_err() && decoder.decoded_rows == 0 {
+ return None;
+ }
+
+ (decoder.output, 1)
+ } else {
+ struct Luma8Decoder {
+ output: Vec<u8>,
+ decoded_rows: u32,
+ }
+
+ impl Decoder for Luma8Decoder {
+ fn push_pixel(&mut self, white: bool) {
+ self.output.push(if white { 0xFF } else { 0x00 });
+ }
+
+ fn push_pixel_chunk(&mut self, white: bool, chunk_count: u32) {
+ let byte = if white { 0xFF } else { 0x00 };
+ self.output
+ .extend(iter::repeat_n(byte, chunk_count as usize * 8));
+ }
+
+ fn next_line(&mut self) {
+ self.decoded_rows += 1;
+ }
+ }
+
+ let mut decoder = Luma8Decoder {
+ output: Vec::new(),
+ decoded_rows: 0,
+ };
+ let mut context = DecoderContext::new(settings);
+ let result = hayro_ccitt::decode(data, &mut decoder, &mut context);
+
+ if result.is_err() && decoder.decoded_rows == 0 {
+ return None;
+ }
+
+ (decoder.output, 8)
+ };
+
+ Some(FilterResult {
+ data: Cow::Owned(decoded),
+ image_data: Some(ImageData {
+ alpha: None,
+ color_space: Some(ImageColorSpace::Gray),
+ bits_per_component: bpc,
+ width: settings.columns,
+ height: image_params.height,
+ }),
+ })
+}
diff --git a/vendor/hayro-syntax/src/filter/dct.rs b/vendor/hayro-syntax/src/filter/dct.rs
new file mode 100644
index 000000000..a4fbd1761
--- /dev/null
+++ b/vendor/hayro-syntax/src/filter/dct.rs
@@ -0,0 +1,181 @@
+use crate::object::Dict;
+use crate::object::dict::keys::COLOR_TRANSFORM;
+use crate::object::stream::{FilterResult, ImageColorSpace, ImageData, ImageDecodeParams};
+use alloc::borrow::Cow;
+use core::num::NonZeroU32;
+use zune_jpeg::zune_core::bytestream::ZCursor;
+use zune_jpeg::zune_core::colorspace::ColorSpace;
+use zune_jpeg::zune_core::colorspace::ColorSpace::CMYK;
+use zune_jpeg::zune_core::options::DecoderOptions;
+
+pub(crate) fn decode(
+ data: &[u8],
+ params: &Dict<'_>,
+ image_params: &ImageDecodeParams,
+) -> Option<FilterResult<'static>> {
+ if image_params.width > u16::MAX as u32 || image_params.height > u16::MAX as u32 {
+ return None;
+ }
+
+ // Some PDFs have weird JPEGs where the JPEG metadata is completely wrong
+ // (for example indicating that one of the dimensions is u16::MAX), but the
+ // metadata in the PDF image dictionary is correct. Therefore, we first
+ // validate the JPEG metadata and patch the data if any of the dimensions
+ // are too large (if they are too small, they will just be padded later on).
+ let data = maybe_patch_jpeg_dimensions(data, image_params)?;
+
+ let options = DecoderOptions::default()
+ .set_max_width(u16::MAX as usize)
+ .set_max_height(u16::MAX as usize);
+ let mut decoder = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(&*data), options);
+ decoder.decode_headers().ok()?;
+
+ let color_transform = params.get::<u8>(COLOR_TRANSFORM);
+ let input_color_space = decoder.input_colorspace().unwrap();
+
+ let mut out_colorspace = if let Some(num_components) = image_params.num_components
+ && !matches!(num_components, 1 | 3 | 4)
+ {
+ ColorSpace::MultiBand(NonZeroU32::new(num_components as u32)?)
+ } else {
+ match input_color_space {
+ ColorSpace::YCbCr => {
+ if color_transform.is_none_or(|c| c == 1) {
+ ColorSpace::RGB
+ } else {
+ ColorSpace::YCbCr
+ }
+ }
+ ColorSpace::RGB | ColorSpace::RGBA => ColorSpace::RGB,
+ ColorSpace::Luma | ColorSpace::LumaA => ColorSpace::Luma,
+ // TODO: Find test case with color transform on cmyk
+ CMYK => CMYK,
+ ColorSpace::YCCK => ColorSpace::YCCK,
+ _ => ColorSpace::RGB,
+ }
+ };
+
+ // In case image had APP14 marker, we might have to override the colorspace.
+ if input_color_space == CMYK && decoder.info().unwrap().components == 3 {
+ out_colorspace = ColorSpace::RGB;
+ }
+
+ decoder.set_options(DecoderOptions::default().jpeg_set_out_colorspace(out_colorspace));
+ let mut decoded = decoder.decode().ok()?;
+
+ if out_colorspace == ColorSpace::YCCK {
+ // See <https://github.com/mozilla/pdf.js/blob/69595a29192b7704733404a42a2ebb537601117b/src/core/jpg.js#L1331>
+ for c in decoded.chunks_mut(4) {
+ let y = c[0] as f32;
+ let cb = c[1] as f32;
+ let cr = c[2] as f32;
+ c[0] = (434.456 - y - 1.402 * cr) as u8;
+ c[1] = (119.541 - y + 0.344 * cb + 0.714 * cr) as u8;
+ c[2] = (481.816 - y - 1.772 * cb) as u8;
+ }
+ }
+
+ let width = decoder.dimensions().unwrap().0 as u32;
+ let height = decoder.dimensions().unwrap().1 as u32;
+
+ let image_data = ImageData {
+ alpha: None,
+ color_space: match out_colorspace {
+ ColorSpace::RGB | ColorSpace::YCbCr => Some(ImageColorSpace::Rgb),
+ ColorSpace::Luma => Some(ImageColorSpace::Gray),
+ ColorSpace::YCCK | CMYK => Some(ImageColorSpace::Cmyk),
+ ColorSpace::MultiBand(_) => None,
+ _ => None,
+ },
+ bits_per_component: 8,
+ width,
+ height,
+ };
+
+ Some(FilterResult {
+ data: Cow::Owned(decoded),
+ image_data: Some(image_data),
+ })
+}
+
+fn maybe_patch_jpeg_dimensions<'a>(
+ data: &'a [u8],
+ image_params: &ImageDecodeParams,
+) -> Option<Cow<'a, [u8]>> {
+ let sof_offset = find_sof_marker(data)?;
+
+ let height_offset = sof_offset.checked_add(5)?;
+ let width_offset = sof_offset.checked_add(7)?;
+
+ let jpeg_height = u16::from_be_bytes([
+ *data.get(height_offset)?,
+ *data.get(height_offset.checked_add(1)?)?,
+ ]);
+ let jpeg_width = u16::from_be_bytes([
+ *data.get(width_offset)?,
+ *data.get(width_offset.checked_add(1)?)?,
+ ]);
+
+ let jpeg_area = (jpeg_width as usize).checked_mul(jpeg_height as usize)?;
+ let image_area = (image_params.width as usize).checked_mul(image_params.height as usize)?;
+ let need_patch = jpeg_area > image_area;
+
+ if !need_patch {
+ return Some(Cow::Borrowed(data));
+ }
+
+ let target_w = (image_params.width as u16).to_be_bytes();
+ let target_h = (image_params.height as u16).to_be_bytes();
+
+ let mut patched = data.to_vec();
+ patched[height_offset..height_offset.checked_add(2)?].copy_from_slice(&target_h);
+ patched[width_offset..width_offset.checked_add(2)?].copy_from_slice(&target_w);
+
+ Some(Cow::Owned(patched))
+}
+
+fn find_sof_marker(data: &[u8]) -> Option<usize> {
+ let mut i = 0_usize;
+
+ while i.checked_add(1).is_some_and(|next| next < data.len()) {
+ if data[i] != 0xFF {
+ i += 1;
+ continue;
+ }
+
+ let marker = data[i + 1];
+
+ // Note: Not sure if 100% correct/robust, is AI-generated.
+ match marker {
+ // All SOF markers carry dimensions: SOF0–SOF15, excluding
+ // 0xC4 (DHT), 0xC8 (JPG), 0xCC (DAC) which are not frame markers.
+ 0xC0..=0xCF if marker != 0xC4 && marker != 0xC8 && marker != 0xCC => {
+ return Some(i);
+ }
+ // Skip padding bytes (0xFF followed by 0xFF).
+ 0xFF => {
+ i += 1;
+
+ continue;
+ }
+ // SOI (0xD8), EOI (0xD9), TEM (0x01) and stuffed byte (0x00)
+ // are standalone markers with no payload.
+ 0xD8 | 0xD9 | 0x01 | 0x00 => {
+ i += 2;
+
+ continue;
+ }
+ // All other markers have a 2-byte length field — skip over them.
+ _ => {
+ let len_start = i.checked_add(2)?;
+ let len_end = i.checked_add(3)?;
+ let seg_len =
+ u16::from_be_bytes([*data.get(len_start)?, *data.get(len_end)?]) as usize;
+
+ i = i.checked_add(2)?.checked_add(seg_len)?;
+ }
+ }
+ }
+
+ None
+}
diff --git a/vendor/hayro-syntax/src/filter/jbig2.rs b/vendor/hayro-syntax/src/filter/jbig2.rs
new file mode 100644
index 000000000..d87253f53
--- /dev/null
+++ b/vendor/hayro-syntax/src/filter/jbig2.rs
@@ -0,0 +1,96 @@
+use crate::bit_reader::BitWriter;
+use crate::object::Dict;
+use crate::object::Stream;
+use crate::object::dict::keys::JBIG2_GLOBALS;
+use crate::object::stream::{FilterResult, ImageColorSpace, ImageData, ImageDecodeParams};
+use alloc::borrow::Cow;
+use alloc::vec;
+use alloc::vec::Vec;
+use core::iter;
+
+/// Decode JBIG2 data from a PDF stream.
+///
+/// The `params` dictionary may contain a `JBIG2Globals` entry pointing to
+/// a stream with shared symbol dictionaries.
+pub(crate) fn decode(
+ data: &[u8],
+ params: &Dict<'_>,
+ image_params: &ImageDecodeParams,
+) -> Option<FilterResult<'static>> {
+ let globals = params
+ .get::<Stream<'_>>(JBIG2_GLOBALS)
+ .and_then(|g| g.decoded().ok());
+
+ let image = hayro_jbig2::Image::new_embedded(data, globals.as_deref()).ok()?;
+
+ // Whenever possible (if we don't have an indexed color space), we convert
+ // the data as 8-bit instead of 1-bit, so that it can be easier converted
+ // into an RGBA8 image.
+
+ // We need to invert the color because JBIG2 uses black = 1 and
+ // white = 0, but PDF uses the opposite.
+ let (decoded, bpc) = if image_params.is_indexed {
+ let row_bytes = (image.width() as usize).div_ceil(8);
+ let mut packed = vec![0_u8; row_bytes * image.height() as usize];
+
+ struct BitWriterDecoder<'a> {
+ writer: BitWriter<'a>,
+ }
+
+ impl hayro_jbig2::Decoder for BitWriterDecoder<'_> {
+ fn push_pixel(&mut self, black: bool) {
+ let _ = self.writer.write(u32::from(!black));
+ }
+
+ fn push_pixel_chunk(&mut self, black: bool, chunk_count: u32) {
+ let byte_value = if black { 0x00 } else { 0xFF };
+ let _ = self.writer.fill_bytes(byte_value, chunk_count as usize);
+ }
+
+ fn next_line(&mut self) {
+ // Images need to be padded to the byte boundary after each row.
+ self.writer.align();
+ }
+ }
+
+ let writer = BitWriter::new(&mut packed, 1)?;
+ let mut decoder = BitWriterDecoder { writer };
+ image.decode(&mut decoder).ok()?;
+
+ (packed, 1)
+ } else {
+ struct Luma8Decoder {
+ output: Vec<u8>,
+ }
+
+ impl hayro_jbig2::Decoder for Luma8Decoder {
+ fn push_pixel(&mut self, black: bool) {
+ self.output.push(if black { 0x00 } else { 0xFF });
+ }
+
+ fn push_pixel_chunk(&mut self, black: bool, chunk_count: u32) {
+ let byte = if black { 0x00 } else { 0xFF };
+ self.output
+ .extend(iter::repeat_n(byte, chunk_count as usize * 8));
+ }
+
+ fn next_line(&mut self) {}
+ }
+
+ let mut decoder = Luma8Decoder { output: Vec::new() };
+ image.decode(&mut decoder).ok()?;
+
+ (decoder.output, 8)
+ };
+
+ Some(FilterResult {
+ data: Cow::Owned(decoded),
+ image_data: Some(ImageData {
+ alpha: None,
+ color_space: Some(ImageColorSpace::Gray),
+ bits_per_component: bpc,
+ width: image.width(),
+ height: image.height(),
+ }),
+ })
+}
diff --git a/vendor/hayro-syntax/src/filter/jpx.rs b/vendor/hayro-syntax/src/filter/jpx.rs
new file mode 100644
index 000000000..4acc343b5
--- /dev/null
+++ b/vendor/hayro-syntax/src/filter/jpx.rs
@@ -0,0 +1,126 @@
+use crate::bit_reader::BitWriter;
+use crate::filter::FilterResult;
+use crate::math::round_f32;
+use crate::object::stream::{ImageColorSpace, ImageData, ImageDecodeParams};
+use alloc::borrow::Cow;
+use alloc::vec;
+use alloc::vec::Vec;
+use hayro_jpeg2000::{ColorSpace, DecodeSettings};
+
+impl ImageColorSpace {
+ fn num_components(&self) -> u8 {
+ match self {
+ Self::Gray => 1,
+ Self::Rgb => 3,
+ Self::Cmyk => 4,
+ Self::Unknown(num) => *num,
+ }
+ }
+}
+
+pub(crate) fn decode(data: &[u8], params: &ImageDecodeParams) -> Option<FilterResult<'static>> {
+ use crate::object::stream::ImageColorSpace;
+
+ let settings = DecodeSettings {
+ resolve_palette_indices: false,
+ strict: false,
+ target_resolution: params.target_dimension,
+ };
+
+ let image = hayro_jpeg2000::Image::new(data, &settings).ok()?;
+
+ let width = image.width();
+ let height = image.height();
+ let bpc = params.bpc.unwrap_or(image.original_bit_depth());
+ let cs = match image.color_space() {
+ ColorSpace::Gray => ImageColorSpace::Gray,
+ ColorSpace::RGB => ImageColorSpace::Rgb,
+ ColorSpace::CMYK => ImageColorSpace::Cmyk,
+ ColorSpace::Unknown { num_channels } => ImageColorSpace::Unknown(*num_channels),
+ ColorSpace::Icc {
+ num_channels: num_components,
+ ..
+ } => match num_components {
+ 1 => ImageColorSpace::Gray,
+ 3 => ImageColorSpace::Rgb,
+ 4 => ImageColorSpace::Cmyk,
+ _ => return None,
+ },
+ };
+ let has_alpha = image.has_alpha();
+ let bitmap = image.decode().ok()?;
+
+ let (mut data, mut alpha) = if !has_alpha {
+ (bitmap, None)
+ } else {
+ // Extract the alpha channel.
+ let total_channels = cs.num_components() + 1;
+ let mut color_channels = Vec::with_capacity(
+ (bitmap.len() / total_channels as usize) * cs.num_components() as usize,
+ );
+ let mut alpha_channel = Vec::with_capacity(bitmap.len() / total_channels as usize);
+
+ for sample in bitmap.chunks_exact(total_channels as usize) {
+ let (alpha, color) = sample.split_last()?;
+ alpha_channel.push(*alpha);
+ color_channels.extend_from_slice(color);
+ }
+
+ (color_channels, Some(alpha_channel))
+ };
+
+ // The decoded image is always 8-bit, so if necessary we have to rescale
+ // ourselves.
+ if bpc != 8 {
+ data = scale(&data, bpc, cs.num_components(), width, height)?;
+ alpha = alpha.and_then(|alpha| scale(&alpha, bpc, cs.num_components(), width, height));
+ }
+
+ Some(FilterResult {
+ data: Cow::Owned(data),
+ image_data: Some(ImageData {
+ alpha,
+ color_space: Some(cs),
+ bits_per_component: bpc,
+ width,
+ height,
+ }),
+ })
+}
+
+fn scale(
+ data: &[u8],
+ bit_per_component: u8,
+ num_components: u8,
+ width: u32,
+ height: u32,
+) -> Option<Vec<u8>> {
+ if bit_per_component == 0 || bit_per_component > 32 {
+ return None;
+ }
+
+ let div_factor = ((1 << 8) - 1) as f32;
+ let mul_factor = ((1_u32 << bit_per_component) - 1) as f32;
+
+ let bits_per_row = (width as usize)
+ .checked_mul(num_components as usize)?
+ .checked_mul(bit_per_component as usize)?;
+ let input_len = bits_per_row.div_ceil(8).checked_mul(height as usize)?;
+ let mut input = vec![0; input_len];
+ let mut writer = BitWriter::new(&mut input, bit_per_component)?;
+ let components_per_row = (num_components as usize).checked_mul(width as usize)?;
+
+ for bytes in data.chunks_exact(components_per_row) {
+ for byte in bytes {
+ let scaled = round_f32((*byte as f32 / div_factor) * mul_factor) as u32;
+ writer.write(scaled)?;
+ }
+
+ writer.align();
+ }
+
+ let final_pos = writer.cur_pos();
+ input.truncate(final_pos);
+
+ Some(input)
+}
diff --git a/vendor/hayro-syntax/src/filter/lzw_flate.rs b/vendor/hayro-syntax/src/filter/lzw_flate.rs
new file mode 100644
index 000000000..76d8c7d5d
--- /dev/null
+++ b/vendor/hayro-syntax/src/filter/lzw_flate.rs
@@ -0,0 +1,1073 @@
+use crate::bit_reader::{BitChunk, BitChunks, BitReader, BitWriter, bit_mask};
+use crate::object::Dict;
+use crate::object::dict::keys::{BITS_PER_COMPONENT, COLORS, COLUMNS, EARLY_CHANGE, PREDICTOR};
+use alloc::vec;
+use alloc::vec::Vec;
+
+pub(crate) mod flate {
+ use super::*;
+ use crate::filter::lzw_flate::{PredictorParams, apply_predictor};
+ use crate::object::Dict;
+
+ #[cfg(feature = "unsafe")]
+ pub(crate) fn decode(data: &[u8], params: &Dict<'_>) -> Option<Vec<u8>> {
+ use flate2::read::{DeflateDecoder, ZlibDecoder};
+ use std::io::Read;
+
+ fn zlib_stream(data: &[u8]) -> Option<Vec<u8>> {
+ let mut decoder = ZlibDecoder::new(data);
+ let mut result = Vec::new();
+ decoder.read_to_end(&mut result).ok().map(|_| result)
+ }
+
+ fn deflate_stream(data: &[u8]) -> Option<Vec<u8>> {
+ let mut decoder = DeflateDecoder::new(data);
+ let mut result = Vec::new();
+ decoder.read_to_end(&mut result).ok().map(|_| result)
+ }
+
+ let decoded = zlib_stream(data)
+ .or_else(|| deflate_stream(data))
+ .or_else(|| {
+ warn!("flate stream is broken, decoding with fallback");
+
+ fallback::decode(data)
+ })?;
+ let params = PredictorParams::from_params(params);
+ apply_predictor(decoded, &params)
+ }
+
+ #[cfg(not(feature = "unsafe"))]
+ pub(crate) fn decode(data: &[u8], params: &Dict<'_>) -> Option<Vec<u8>> {
+ let decoded = fallback::decode(data)?;
+ let params = PredictorParams::from_params(params);
+ apply_predictor(decoded, &params)
+ }
+
+ /// Ported from <https://github.com/mozilla/pdf.js/blob/master/src/core/flate_stream.js>
+ /// TODO: Rewrite this in idiomatic Rust.
+ mod fallback {
+ use alloc::vec;
+ use alloc::vec::Vec;
+
+ pub(crate) fn decode(data: &[u8]) -> Option<Vec<u8>> {
+ flate_decode(data)
+ }
+
+ fn flate_decode(data: &[u8]) -> Option<Vec<u8>> {
+ if data.len() >= 2 {
+ let cmf = data[0];
+ let flg = data[1];
+
+ if (cmf & 0x0f) == 0x08
+ && ((cmf as u16) << 8 | flg as u16).is_multiple_of(31)
+ && (flg & 0x20) == 0
+ {
+ let mut stream = FlateStream::new(&data[2..]);
+ return stream.decode();
+ }
+ }
+
+ let mut stream = FlateStream::new(data);
+ stream.decode()
+ }
+
+ struct FlateStream<'a> {
+ data: &'a [u8],
+ pos: usize,
+ code_buf: u32,
+ code_size: u8,
+ output: Vec<u8>,
+ eof: bool,
+ }
+
+ impl<'a> FlateStream<'a> {
+ fn new(data: &'a [u8]) -> Self {
+ FlateStream {
+ data,
+ pos: 0,
+ code_buf: 0,
+ code_size: 0,
+ output: Vec::new(),
+ eof: false,
+ }
+ }
+
+ fn decode(&mut self) -> Option<Vec<u8>> {
+ while !self.eof && self.pos < self.data.len() {
+ self.read_block();
+ }
+
+ Some(core::mem::take(&mut self.output))
+ }
+
+ fn get_byte(&mut self) -> Option<u8> {
+ if self.pos >= self.data.len() {
+ None
+ } else {
+ let byte = self.data[self.pos];
+ self.pos += 1;
+ Some(byte)
+ }
+ }
+
+ fn peek_byte(&self) -> Option<u8> {
+ if self.pos >= self.data.len() {
+ None
+ } else {
+ Some(self.data[self.pos])
+ }
+ }
+
+ fn get_bytes(&mut self, n: usize) -> Vec<u8> {
+ let end = (self.pos + n).min(self.data.len());
+ let bytes = self.data[self.pos..end].to_vec();
+ self.pos = end;
+ bytes
+ }
+
+ fn get_bits(&mut self, bits: u8) -> Option<u32> {
+ while self.code_size < bits {
+ let b = self.get_byte()?;
+ self.code_buf |= (b as u32) << self.code_size;
+ self.code_size += 8;
+ }
+
+ let result = self.code_buf & ((1 << bits) - 1);
+ self.code_buf >>= bits;
+ self.code_size -= bits;
+
+ Some(result)
+ }
+
+ fn get_code(&mut self, table: &HuffmanTable) -> Option<u16> {
+ let codes = &table.codes;
+ let max_len = table.max_len;
+
+ while self.code_size < max_len {
+ if let Some(b) = self.get_byte() {
+ self.code_buf |= (b as u32) << self.code_size;
+ self.code_size += 8;
+ } else {
+ // Premature end of stream
+ break;
+ }
+ }
+
+ let code = codes.get((self.code_buf & ((1 << max_len) - 1)) as usize)?;
+ let code_len = (code >> 16) as u8;
+ let code_val = code & 0xffff;
+
+ if code_len < 1 || self.code_size < code_len {
+ return None;
+ }
+
+ self.code_buf >>= code_len;
+ self.code_size -= code_len;
+
+ Some(code_val as u16)
+ }
+
+ fn read_block(&mut self) {
+ // Read block header
+ let hdr = match self.get_bits(3) {
+ Some(h) => h,
+ None => {
+ warn!("bad block header in flate stream");
+ self.eof = true;
+ return;
+ }
+ };
+
+ if (hdr & 1) != 0 {
+ self.eof = true;
+ }
+
+ let hdr = hdr >> 1;
+
+ match hdr {
+ 0 => self.read_uncompressed_block(),
+ 1 => self.read_compressed_block(true),
+ 2 => self.read_compressed_block(false),
+ _ => {
+ warn!("unknown block type in flate stream");
+ self.eof = true;
+ }
+ }
+ }
+
+ fn read_uncompressed_block(&mut self) {
+ // Skip any remaining bits in current byte
+ self.code_buf = 0;
+ self.code_size = 0;
+
+ let len_low = match self.get_byte() {
+ Some(b) => b as u16,
+ None => {
+ warn!("bad block header in flate stream");
+ self.eof = true;
+ return;
+ }
+ };
+
+ let len_high = match self.get_byte() {
+ Some(b) => b as u16,
+ None => {
+ warn!("bad block header in flate stream");
+ self.eof = true;
+ return;
+ }
+ };
+
+ let block_len = len_low | (len_high << 8);
+
+ let nlen_low = match self.get_byte() {
+ Some(b) => b as u16,
+ None => {
+ warn!("bad block header in flate stream");
+ self.eof = true;
+ return;
+ }
+ };
+
+ let nlen_high = match self.get_byte() {
+ Some(b) => b as u16,
+ None => {
+ warn!("bad block header in flate stream");
+ self.eof = true;
+ return;
+ }
+ };
+
+ let check = nlen_low | (nlen_high << 8);
+
+ if check != !block_len && (block_len != 0 || check != 0) {
+ // Ignoring error for bad "empty" block
+ warn!("bad uncompressed block length in flate stream");
+ }
+
+ if block_len == 0 {
+ if self.peek_byte().is_none() {
+ self.eof = true;
+ }
+ } else {
+ let block = self.get_bytes(block_len as usize);
+ self.output.extend_from_slice(&block);
+ if block.len() < block_len as usize {
+ self.eof = true;
+ }
+ }
+ }
+
+ fn read_compressed_block(&mut self, fixed: bool) {
+ let (lit_code_table, dist_code_table) = if fixed {
+ (get_fixed_lit_table(), get_fixed_dist_table())
+ } else {
+ match self.read_dynamic_tables() {
+ Some(tables) => tables,
+ None => {
+ self.eof = true;
+ return;
+ }
+ }
+ };
+
+ loop {
+ let code1 = match self.get_code(&lit_code_table) {
+ Some(c) => c,
+ None => {
+ self.eof = true;
+ return;
+ }
+ };
+
+ if code1 < 256 {
+ self.output.push(code1 as u8);
+ } else if code1 == 256 {
+ return;
+ } else {
+ let code1 = code1 - 257;
+ let length_info = LENGTH_DECODE.get(code1 as usize).copied().unwrap_or(0);
+ let extra_bits = (length_info >> 16) as u8;
+ let mut length = (length_info & 0xffff) as usize;
+
+ if extra_bits > 0 {
+ if let Some(extra) = self.get_bits(extra_bits) {
+ length += extra as usize;
+ } else {
+ self.eof = true;
+ return;
+ }
+ }
+
+ let dist_code = match self.get_code(&dist_code_table) {
+ Some(c) => c,
+ None => {
+ self.eof = true;
+ return;
+ }
+ };
+
+ let dist_info = match DIST_DECODE.get(dist_code as usize) {
+ Some(&info) => info,
+ None => {
+ warn!("invalid distance code {} in flate stream", dist_code);
+
+ self.eof = true;
+ return;
+ }
+ };
+
+ let extra_bits = (dist_info >> 16) as u8;
+ let mut distance = (dist_info & 0xffff) as usize;
+
+ if extra_bits > 0 {
+ if let Some(extra) = self.get_bits(extra_bits) {
+ distance += extra as usize;
+ } else {
+ self.eof = true;
+ return;
+ }
+ }
+
+ // Copy from previous output
+ let start = self.output.len().wrapping_sub(distance);
+ for _ in 0..length {
+ if start < self.output.len() {
+ let byte = self.output[self.output.len() - distance];
+ self.output.push(byte);
+ }
+ }
+ }
+ }
+ }
+
+ fn read_dynamic_tables(&mut self) -> Option<(HuffmanTable, HuffmanTable)> {
+ let num_lit_codes = self.get_bits(5)? as usize + 257;
+ let num_dist_codes = self.get_bits(5)? as usize + 1;
+ let num_code_len_codes = self.get_bits(4)? as usize + 4;
+
+ // Build code length code table
+ let mut code_len_code_lengths = vec![0_u8; 19];
+ for i in 0..num_code_len_codes {
+ code_len_code_lengths[CODE_LEN_CODE_MAP[i] as usize] = self.get_bits(3)? as u8;
+ }
+
+ let code_len_table = generate_huffman_table(&code_len_code_lengths);
+
+ // Read code lengths
+ let total_codes = num_lit_codes + num_dist_codes;
+ let mut code_lengths = vec![0_u8; total_codes];
+ let mut i = 0;
+
+ while i < total_codes {
+ let code = self.get_code(&code_len_table)?;
+
+ match code {
+ 0..=15 => {
+ code_lengths[i] = code as u8;
+ i += 1;
+ }
+ 16 => {
+ // Repeat previous
+ let repeat_count = self.get_bits(2)? as usize + 3;
+ let prev = if i > 0 { code_lengths[i - 1] } else { 0 };
+ for _ in 0..repeat_count {
+ if i < total_codes {
+ code_lengths[i] = prev;
+ i += 1;
+ }
+ }
+ }
+ 17 => {
+ // Repeat zero 3-10 times
+ let repeat_count = self.get_bits(3)? as usize + 3;
+ for _ in 0..repeat_count {
+ if i < total_codes {
+ code_lengths[i] = 0;
+ i += 1;
+ }
+ }
+ }
+ 18 => {
+ // Repeat zero 11-138 times
+ let repeat_count = self.get_bits(7)? as usize + 11;
+ for _ in 0..repeat_count {
+ if i < total_codes {
+ code_lengths[i] = 0;
+ i += 1;
+ }
+ }
+ }
+ _ => return None,
+ }
+ }
+
+ let lit_table = generate_huffman_table(&code_lengths[..num_lit_codes]);
+ let dist_table = generate_huffman_table(&code_lengths[num_lit_codes..]);
+
+ Some((lit_table, dist_table))
+ }
+ }
+
+ struct HuffmanTable {
+ codes: Vec<u32>,
+ max_len: u8,
+ }
+
+ fn generate_huffman_table(lengths: &[u8]) -> HuffmanTable {
+ let _n = lengths.len();
+
+ // Find max code length
+ let max_len = lengths.iter().cloned().max().unwrap_or(0);
+
+ if max_len == 0 {
+ return HuffmanTable {
+ codes: vec![0; 1],
+ max_len: 1,
+ };
+ }
+
+ // Build the table
+ let size = 1 << max_len;
+ let mut codes = vec![0_u32; size];
+
+ let mut code = 0_u32;
+ for len in 1..=max_len {
+ for (val, &length) in lengths.iter().enumerate() {
+ if length == len {
+ // Bit-reverse the code
+ let mut code2 = 0_u32;
+ let mut t = code;
+ for _ in 0..len {
+ code2 = (code2 << 1) | (t & 1);
+ t >>= 1;
+ }
+
+ // Fill the table entries
+ let skip = 1 << len;
+ let mut i = code2 as usize;
+ while i < size {
+ codes[i] = ((len as u32) << 16) | (val as u32);
+ i += skip;
+ }
+ code += 1;
+ }
+ }
+ code <<= 1;
+ }
+
+ HuffmanTable { codes, max_len }
+ }
+
+ fn get_fixed_lit_table() -> HuffmanTable {
+ HuffmanTable {
+ codes: FIXED_LIT_CODE_TAB.to_vec(),
+ max_len: 9,
+ }
+ }
+
+ fn get_fixed_dist_table() -> HuffmanTable {
+ HuffmanTable {
+ codes: FIXED_DIST_CODE_TAB.to_vec(),
+ max_len: 5,
+ }
+ }
+
+ const CODE_LEN_CODE_MAP: [u8; 19] = [
+ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15,
+ ];
+
+ const LENGTH_DECODE: [u32; 29] = [
+ 0x00003, 0x00004, 0x00005, 0x00006, 0x00007, 0x00008, 0x00009, 0x0000a, 0x1000b,
+ 0x1000d, 0x1000f, 0x10011, 0x20013, 0x20017, 0x2001b, 0x2001f, 0x30023, 0x3002b,
+ 0x30033, 0x3003b, 0x40043, 0x40053, 0x40063, 0x40073, 0x50083, 0x500a3, 0x500c3,
+ 0x500e3, 0x00102,
+ ];
+
+ const DIST_DECODE: [u32; 30] = [
+ 0x00001, 0x00002, 0x00003, 0x00004, 0x10005, 0x10007, 0x20009, 0x2000d, 0x30011,
+ 0x30019, 0x40021, 0x40031, 0x50041, 0x50061, 0x60081, 0x600c1, 0x70101, 0x70181,
+ 0x80201, 0x80301, 0x90401, 0x90601, 0xa0801, 0xa0c01, 0xb1001, 0xb1801, 0xc2001,
+ 0xc3001, 0xd4001, 0xd6001,
+ ];
+
+ const FIXED_LIT_CODE_TAB: [u32; 512] = [
+ 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c0, 0x70108,
+ 0x80060, 0x80020, 0x900a0, 0x80000, 0x80080, 0x80040, 0x900e0, 0x70104, 0x80058,
+ 0x80018, 0x90090, 0x70114, 0x80078, 0x80038, 0x900d0, 0x7010c, 0x80068, 0x80028,
+ 0x900b0, 0x80008, 0x80088, 0x80048, 0x900f0, 0x70102, 0x80054, 0x80014, 0x8011c,
+ 0x70112, 0x80074, 0x80034, 0x900c8, 0x7010a, 0x80064, 0x80024, 0x900a8, 0x80004,
+ 0x80084, 0x80044, 0x900e8, 0x70106, 0x8005c, 0x8001c, 0x90098, 0x70116, 0x8007c,
+ 0x8003c, 0x900d8, 0x7010e, 0x8006c, 0x8002c, 0x900b8, 0x8000c, 0x8008c, 0x8004c,
+ 0x900f8, 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c4,
+ 0x70109, 0x80062, 0x80022, 0x900a4, 0x80002, 0x80082, 0x80042, 0x900e4, 0x70105,
+ 0x8005a, 0x8001a, 0x90094, 0x70115, 0x8007a, 0x8003a, 0x900d4, 0x7010d, 0x8006a,
+ 0x8002a, 0x900b4, 0x8000a, 0x8008a, 0x8004a, 0x900f4, 0x70103, 0x80056, 0x80016,
+ 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cc, 0x7010b, 0x80066, 0x80026, 0x900ac,
+ 0x80006, 0x80086, 0x80046, 0x900ec, 0x70107, 0x8005e, 0x8001e, 0x9009c, 0x70117,
+ 0x8007e, 0x8003e, 0x900dc, 0x7010f, 0x8006e, 0x8002e, 0x900bc, 0x8000e, 0x8008e,
+ 0x8004e, 0x900fc, 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031,
+ 0x900c2, 0x70108, 0x80061, 0x80021, 0x900a2, 0x80001, 0x80081, 0x80041, 0x900e2,
+ 0x70104, 0x80059, 0x80019, 0x90092, 0x70114, 0x80079, 0x80039, 0x900d2, 0x7010c,
+ 0x80069, 0x80029, 0x900b2, 0x80009, 0x80089, 0x80049, 0x900f2, 0x70102, 0x80055,
+ 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900ca, 0x7010a, 0x80065, 0x80025,
+ 0x900aa, 0x80005, 0x80085, 0x80045, 0x900ea, 0x70106, 0x8005d, 0x8001d, 0x9009a,
+ 0x70116, 0x8007d, 0x8003d, 0x900da, 0x7010e, 0x8006d, 0x8002d, 0x900ba, 0x8000d,
+ 0x8008d, 0x8004d, 0x900fa, 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073,
+ 0x80033, 0x900c6, 0x70109, 0x80063, 0x80023, 0x900a6, 0x80003, 0x80083, 0x80043,
+ 0x900e6, 0x70105, 0x8005b, 0x8001b, 0x90096, 0x70115, 0x8007b, 0x8003b, 0x900d6,
+ 0x7010d, 0x8006b, 0x8002b, 0x900b6, 0x8000b, 0x8008b, 0x8004b, 0x900f6, 0x70103,
+ 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900ce, 0x7010b, 0x80067,
+ 0x80027, 0x900ae, 0x80007, 0x80087, 0x80047, 0x900ee, 0x70107, 0x8005f, 0x8001f,
+ 0x9009e, 0x70117, 0x8007f, 0x8003f, 0x900de, 0x7010f, 0x8006f, 0x8002f, 0x900be,
+ 0x8000f, 0x8008f, 0x8004f, 0x900fe, 0x70100, 0x80050, 0x80010, 0x80118, 0x70110,
+ 0x80070, 0x80030, 0x900c1, 0x70108, 0x80060, 0x80020, 0x900a1, 0x80000, 0x80080,
+ 0x80040, 0x900e1, 0x70104, 0x80058, 0x80018, 0x90091, 0x70114, 0x80078, 0x80038,
+ 0x900d1, 0x7010c, 0x80068, 0x80028, 0x900b1, 0x80008, 0x80088, 0x80048, 0x900f1,
+ 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c9, 0x7010a,
+ 0x80064, 0x80024, 0x900a9, 0x80004, 0x80084, 0x80044, 0x900e9, 0x70106, 0x8005c,
+ 0x8001c, 0x90099, 0x70116, 0x8007c, 0x8003c, 0x900d9, 0x7010e, 0x8006c, 0x8002c,
+ 0x900b9, 0x8000c, 0x8008c, 0x8004c, 0x900f9, 0x70101, 0x80052, 0x80012, 0x8011a,
+ 0x70111, 0x80072, 0x80032, 0x900c5, 0x70109, 0x80062, 0x80022, 0x900a5, 0x80002,
+ 0x80082, 0x80042, 0x900e5, 0x70105, 0x8005a, 0x8001a, 0x90095, 0x70115, 0x8007a,
+ 0x8003a, 0x900d5, 0x7010d, 0x8006a, 0x8002a, 0x900b5, 0x8000a, 0x8008a, 0x8004a,
+ 0x900f5, 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cd,
+ 0x7010b, 0x80066, 0x80026, 0x900ad, 0x80006, 0x80086, 0x80046, 0x900ed, 0x70107,
+ 0x8005e, 0x8001e, 0x9009d, 0x70117, 0x8007e, 0x8003e, 0x900dd, 0x7010f, 0x8006e,
+ 0x8002e, 0x900bd, 0x8000e, 0x8008e, 0x8004e, 0x900fd, 0x70100, 0x80051, 0x80011,
+ 0x80119, 0x70110, 0x80071, 0x80031, 0x900c3, 0x70108, 0x80061, 0x80021, 0x900a3,
+ 0x80001, 0x80081, 0x80041, 0x900e3, 0x70104, 0x80059, 0x80019, 0x90093, 0x70114,
+ 0x80079, 0x80039, 0x900d3, 0x7010c, 0x80069, 0x80029, 0x900b3, 0x80009, 0x80089,
+ 0x80049, 0x900f3, 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035,
+ 0x900cb, 0x7010a, 0x80065, 0x80025, 0x900ab, 0x80005, 0x80085, 0x80045, 0x900eb,
+ 0x70106, 0x8005d, 0x8001d, 0x9009b, 0x70116, 0x8007d, 0x8003d, 0x900db, 0x7010e,
+ 0x8006d, 0x8002d, 0x900bb, 0x8000d, 0x8008d, 0x8004d, 0x900fb, 0x70101, 0x80053,
+ 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c7, 0x70109, 0x80063, 0x80023,
+ 0x900a7, 0x80003, 0x80083, 0x80043, 0x900e7, 0x70105, 0x8005b, 0x8001b, 0x90097,
+ 0x70115, 0x8007b, 0x8003b, 0x900d7, 0x7010d, 0x8006b, 0x8002b, 0x900b7, 0x8000b,
+ 0x8008b, 0x8004b, 0x900f7, 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077,
+ 0x80037, 0x900cf, 0x7010b, 0x80067, 0x80027, 0x900af, 0x80007, 0x80087, 0x80047,
+ 0x900ef, 0x70107, 0x8005f, 0x8001f, 0x9009f, 0x70117, 0x8007f, 0x8003f, 0x900df,
+ 0x7010f, 0x8006f, 0x8002f, 0x900bf, 0x8000f, 0x8008f, 0x8004f, 0x900ff,
+ ];
+
+ const FIXED_DIST_CODE_TAB: [u32; 32] = [
+ 0x50000, 0x50010, 0x50008, 0x50018, 0x50004, 0x50014, 0x5000c, 0x5001c, 0x50002,
+ 0x50012, 0x5000a, 0x5001a, 0x50006, 0x50016, 0x5000e, 0x00000, 0x50001, 0x50011,
+ 0x50009, 0x50019, 0x50005, 0x50015, 0x5000d, 0x5001d, 0x50003, 0x50013, 0x5000b,
+ 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000,
+ ];
+ }
+}
+
+pub(crate) mod lzw {
+ use crate::bit_reader::BitReader;
+ use crate::filter::lzw_flate::{PredictorParams, apply_predictor};
+ use crate::object::Dict;
+ use alloc::vec;
+ use alloc::vec::Vec;
+
+ /// Decode a LZW-encoded stream.
+ pub(crate) fn decode(data: &[u8], params: &Dict<'_>) -> Option<Vec<u8>> {
+ let params = PredictorParams::from_params(params);
+
+ let decoded = decode_impl(data, params.early_change)?;
+
+ apply_predictor(decoded, &params)
+ }
+
+ const CLEAR_TABLE: usize = 256;
+ const EOD: usize = 257;
+ const MAX_ENTRIES: usize = 4096;
+ const INITIAL_SIZE: u16 = 258;
+
+ fn decode_impl(data: &[u8], early_change: bool) -> Option<Vec<u8>> {
+ let mut table = Table::new(early_change);
+ let mut bit_size = table.code_length();
+ let mut reader = BitReader::new(data);
+ let mut decoded = vec![];
+ let mut prev = None;
+
+ loop {
+ let next = match reader.read(bit_size) {
+ Some(code) => code as usize,
+ None => {
+ warn!("premature EOF in LZW stream, EOD code missing");
+ return Some(decoded);
+ }
+ };
+
+ match next {
+ CLEAR_TABLE => {
+ table.clear();
+ prev = None;
+ bit_size = table.code_length();
+ }
+ EOD => return Some(decoded),
+ new => {
+ if new > table.size() {
+ warn!("invalid LZW code: {} (table size: {})", new, table.size());
+ return None;
+ }
+
+ if new < table.size() {
+ let entry = table.get(new)?;
+ let first_byte = entry[0];
+ decoded.extend_from_slice(entry);
+
+ if let Some(prev_code) = prev {
+ table.register(prev_code, first_byte);
+ }
+ } else if new == table.size() && prev.is_some() {
+ let prev_code = prev.unwrap();
+ let prev_entry = table.get(prev_code)?;
+ let first_byte = prev_entry[0];
+
+ let new_entry = table.register(prev_code, first_byte)?;
+ decoded.extend_from_slice(new_entry);
+ } else {
+ warn!("LZW decode error: code {new} not found and prev is None");
+ return None;
+ }
+
+ bit_size = table.code_length();
+ prev = Some(new);
+ }
+ }
+ }
+ }
+
+ struct Table {
+ early_change: bool,
+ entries: Vec<Option<Vec<u8>>>,
+ }
+
+ impl Table {
+ fn new(early_change: bool) -> Self {
+ let mut entries: Vec<_> = (0..=255).map(|b| Some(vec![b])).collect();
+
+ // Clear table and EOD don't have any data.
+ entries.push(None); // 256 = CLEAR_TABLE
+ entries.push(None); // 257 = EOD
+
+ Self {
+ early_change,
+ entries,
+ }
+ }
+
+ fn push(&mut self, entry: Vec<u8>) -> Option<&[u8]> {
+ if self.entries.len() >= MAX_ENTRIES {
+ None
+ } else {
+ self.entries.push(Some(entry));
+ self.entries.last()?.as_ref().map(|v| &**v)
+ }
+ }
+
+ fn register(&mut self, prev: usize, new_byte: u8) -> Option<&[u8]> {
+ let prev_entry = self.get(prev)?;
+
+ let mut new_entry = Vec::with_capacity(prev_entry.len() + 1);
+ new_entry.extend(prev_entry);
+ new_entry.push(new_byte);
+ self.push(new_entry)
+ }
+
+ fn get(&self, index: usize) -> Option<&[u8]> {
+ self.entries.get(index)?.as_ref().map(|v| &**v)
+ }
+
+ fn clear(&mut self) {
+ self.entries.truncate(INITIAL_SIZE as usize);
+ }
+
+ fn size(&self) -> usize {
+ self.entries.len()
+ }
+
+ fn code_length(&self) -> u8 {
+ const TEN: usize = 512;
+ const ELEVEN: usize = 1024;
+ const TWELVE: usize = 2048;
+
+ let adjusted = self.entries.len() + (if self.early_change { 1 } else { 0 });
+
+ if adjusted >= TWELVE {
+ 12
+ } else if adjusted >= ELEVEN {
+ 11
+ } else if adjusted >= TEN {
+ 10
+ } else {
+ 9
+ }
+ }
+ }
+}
+
+struct PredictorParams {
+ predictor: u8,
+ colors: u8,
+ bits_per_component: u8,
+ columns: usize,
+ early_change: bool,
+}
+
+impl PredictorParams {
+ fn bits_per_pixel(&self) -> u8 {
+ self.bits_per_component * self.colors
+ }
+
+ fn row_length_in_bytes(&self) -> usize {
+ (self.columns * self.bits_per_pixel() as usize).div_ceil(8)
+ }
+}
+
+impl Default for PredictorParams {
+ fn default() -> Self {
+ Self {
+ predictor: 1,
+ colors: 1,
+ bits_per_component: 8,
+ columns: 1,
+ early_change: true,
+ }
+ }
+}
+
+impl PredictorParams {
+ fn from_params(dict: &Dict<'_>) -> Self {
+ Self {
+ predictor: dict.get(PREDICTOR).unwrap_or(1),
+ colors: dict.get(COLORS).unwrap_or(1),
+ bits_per_component: dict.get(BITS_PER_COMPONENT).unwrap_or(8),
+ columns: dict.get(COLUMNS).unwrap_or(1),
+ early_change: dict.get::<u8>(EARLY_CHANGE).map(|e| e != 0).unwrap_or(true),
+ }
+ }
+}
+
+fn apply_predictor(data: Vec<u8>, params: &PredictorParams) -> Option<Vec<u8>> {
+ match params.predictor {
+ 1 => Some(data),
+ i => {
+ let is_png_predictor = i >= 10;
+
+ let row_len = params.row_length_in_bytes();
+
+ let total_row_len = if is_png_predictor {
+ // + 1 Because each row must start with the predictor that is used for PNG predictors.
+ row_len + 1
+ } else {
+ row_len
+ };
+
+ let num_rows = data.len() / total_row_len;
+
+ if !matches!(params.bits_per_component, 1 | 2 | 4 | 8 | 16) {
+ warn!("invalid bits per component {}", params.bits_per_component);
+
+ return None;
+ }
+
+ let (bit_size, chunk_len) = if is_png_predictor {
+ (
+ 8,
+ (params.colors * params.bits_per_component).div_ceil(8) as usize,
+ )
+ } else {
+ (params.bits_per_component, params.colors as usize)
+ };
+ let zero_row = vec![0; row_len];
+ let mut prev_row = BitChunks::new(&zero_row, bit_size, chunk_len)?;
+ let zero_col = BitChunk::new(0, chunk_len);
+ let mut out = vec![0; num_rows * row_len];
+ let mut writer = BitWriter::new(&mut out, bit_size)?;
+
+ for in_row in data.chunks_exact(total_row_len) {
+ if is_png_predictor {
+ let predictor = in_row[0];
+ let in_data = &in_row[1..];
+ let in_data_chunks = BitChunks::new(in_data, bit_size, chunk_len)?;
+
+ match predictor {
+ 1 => apply::<Sub>(
+ prev_row,
+ zero_col.clone(),
+ zero_col.clone(),
+ in_data_chunks,
+ &mut writer,
+ chunk_len,
+ bit_size,
+ )?,
+ 2 => apply::<Up>(
+ prev_row,
+ zero_col.clone(),
+ zero_col.clone(),
+ in_data_chunks,
+ &mut writer,
+ chunk_len,
+ bit_size,
+ )?,
+ 3 => apply::<Avg>(
+ prev_row,
+ zero_col.clone(),
+ zero_col.clone(),
+ in_data_chunks,
+ &mut writer,
+ chunk_len,
+ bit_size,
+ )?,
+ 4 => apply::<Paeth>(
+ prev_row,
+ zero_col.clone(),
+ zero_col.clone(),
+ in_data_chunks,
+ &mut writer,
+ chunk_len,
+ bit_size,
+ )?,
+ _ => {
+ // Just copy the data.
+ let mut reader = BitReader::new(in_data);
+
+ while let Some(data) = reader.read(bit_size) {
+ writer.write(data);
+ }
+ }
+ }
+ } else if i == 2 {
+ apply::<Sub>(
+ prev_row,
+ zero_col.clone(),
+ zero_col.clone(),
+ BitChunks::new(in_row, bit_size, chunk_len)?,
+ &mut writer,
+ chunk_len,
+ bit_size,
+ );
+ } else {
+ warn!("unknown predictor {i}");
+
+ return None;
+ }
+
+ let (data, new_writer) = writer.split_off();
+ writer = new_writer;
+ prev_row = BitChunks::new(data, bit_size, chunk_len)?;
+ }
+
+ Some(out)
+ }
+ }
+}
+
+fn apply<'a, T: Predictor>(
+ prev_row: BitChunks<'a>,
+ mut prev_col: BitChunk,
+ mut top_left: BitChunk,
+ cur_row: BitChunks<'a>,
+ writer: &mut BitWriter<'a>,
+ chunk_len: usize,
+ bit_size: u8,
+) -> Option<()> {
+ for (cur_row, prev_row) in cur_row.zip(prev_row) {
+ let old_pos = writer.cur_pos();
+
+ for (((cur_row, prev_row), prev_col), top_left) in cur_row
+ .iter()
+ .zip(prev_row.iter())
+ .zip(prev_col.iter())
+ .zip(top_left.iter())
+ {
+ // Note that the wrapping behavior when adding inside the predictors is dependent on the
+ // bit size, so it wouldn't be triggered for bits per component < 16. So we mask out
+ // the bytes manually, which is equivalent to a wrapping add.
+ writer.write(
+ T::predict(cur_row, prev_row, prev_col, top_left) as u32 & bit_mask(bit_size),
+ );
+ }
+
+ prev_col = {
+ let out_data = writer.get_data();
+ let mut reader = BitReader::new_with(out_data, old_pos);
+ BitChunk::from_reader(&mut reader, bit_size, chunk_len).unwrap()
+ };
+
+ top_left = prev_row;
+ }
+
+ Some(())
+}
+
+trait Predictor {
+ fn predict(cur_row: u16, prev_row: u16, prev_col: u16, top_left: u16) -> u16;
+}
+
+struct Sub;
+impl Predictor for Sub {
+ fn predict(cur_row: u16, _: u16, prev_col: u16, _: u16) -> u16 {
+ cur_row.wrapping_add(prev_col)
+ }
+}
+
+struct Up;
+impl Predictor for Up {
+ fn predict(cur_row: u16, prev_row: u16, _: u16, _: u16) -> u16 {
+ cur_row.wrapping_add(prev_row)
+ }
+}
+
+struct Avg;
+impl Predictor for Avg {
+ fn predict(cur_row: u16, prev_row: u16, prev_col: u16, _: u16) -> u16 {
+ cur_row.wrapping_add(((prev_col as u32 + prev_row as u32) / 2) as u16)
+ }
+}
+
+struct Paeth;
+impl Predictor for Paeth {
+ fn predict(cur_row: u16, prev_row: u16, prev_col: u16, top_left: u16) -> u16 {
+ fn paeth(a: u16, b: u16, c: u16) -> u16 {
+ let a = a as i32;
+ let b = b as i32;
+ let c = c as i32;
+
+ let p = a + b - c;
+ let pa = (p - a).abs();
+ let pb = (p - b).abs();
+ let pc = (p - c).abs();
+
+ if pa <= pb && pa <= pc {
+ a as u16
+ } else if pb <= pc {
+ b as u16
+ } else {
+ c as u16
+ }
+ }
+
+ cur_row.wrapping_add(paeth(prev_col, prev_row, top_left))
+ }
+}
+
+#[cfg(test)]
+#[rustfmt::skip]
+mod tests {
+ use crate::filter::lzw_flate::{PredictorParams, apply_predictor, flate, lzw};
+ use crate::object::Dict;
+
+ #[test]
+ fn decode_lzw() {
+ let input = [0x80, 0x0B, 0x60, 0x50, 0x22, 0x0C, 0x0C, 0x85, 0x01];
+ let decoded = lzw::decode(&input, &Dict::default()).unwrap();
+
+ assert_eq!(decoded, vec![45, 45, 45, 45, 45, 65, 45, 45, 45, 66]);
+ }
+
+ #[test]
+ fn decode_flate_zlib() {
+ let input = [
+ 0x78, 0x9c, 0xf3, 0x48, 0xcd, 0xc9, 0xc9, 0x7, 0x0, 0x5, 0x8c, 0x1, 0xf5,
+ ];
+
+ let decoded = flate::decode(&input, &Dict::default()).unwrap();
+ assert_eq!(decoded, b"Hello");
+ }
+
+ #[test]
+ fn decode_flate() {
+ let input = [0xf3, 0x48, 0xcd, 0xc9, 0xc9, 0x7, 0x0];
+
+ let decoded = flate::decode(&input, &Dict::default()).unwrap();
+ assert_eq!(decoded, b"Hello");
+ }
+
+ fn predictor_expected() -> Vec<u8> {
+ vec![
+ // Row 1
+ 127, 127, 127, 125, 129, 127, 123, 130, 128,
+ // Row 2
+ 128, 129, 126, 126, 132, 124, 121, 127, 126,
+ // Row 3
+ 131, 130, 122, 133, 129, 128, 127, 100, 126,
+ ]
+ }
+
+ fn predictor_test(predictor: u8, input: &[u8]) {
+ let params = PredictorParams {
+ predictor,
+ colors: 3,
+ bits_per_component: 8,
+ columns: 3,
+ early_change: false,
+ };
+
+ let expected = predictor_expected();
+ let out = apply_predictor(input.to_vec(), &params).unwrap();
+
+ assert_eq!(expected, out);
+ }
+
+ #[test]
+ fn predictor_sub() {
+ predictor_test(
+ 11,
+ &[
+ // Row 1
+ 1, 127, 127, 127, 254, 2, 0, 254, 1, 1,
+ // Row 2
+ 1, 128, 129, 126, 254, 3, 254, 251, 251, 2,
+ // Row 3
+ 1, 131, 130, 122, 2, 255, 6, 250, 227, 254,
+ ],
+ );
+ }
+
+ #[test]
+ fn predictor_up() {
+ predictor_test(
+ 12,
+ &[
+ // Row 1
+ 2, 127, 127, 127, 125, 129, 127, 123, 130, 128,
+ // Row 2
+ 2, 1, 2, 255, 1, 3, 253, 254, 253, 254,
+ // Row 3
+ 2, 3, 1, 252, 7, 253, 4, 6, 229, 0,
+ ],
+ );
+ }
+
+ #[test]
+ fn predictor_avg() {
+ predictor_test(
+ 13,
+ &[
+ // Row 1
+ 3, 127, 127, 127, 62, 66, 64, 61, 66, 65,
+ // Row 2
+ 3, 65, 66, 63, 0, 3, 254, 253, 252, 0,
+ // Row 3
+ 3, 67, 66, 59, 5, 254, 5, 0, 228, 255,
+ ],
+ );
+ }
+
+ #[test]
+ fn predictor_paeth() {
+ predictor_test(
+ 14,
+ &[
+ // Row 1
+ 4, 127, 127, 127, 254, 2, 0, 254, 1, 1,
+ // Row 2
+ 4, 1, 2, 255, 1, 3, 254, 254, 251, 2,
+ // Row 3
+ 4, 3, 1, 252, 5, 253, 6, 1, 229, 254,
+ ],
+ );
+ }
+}
diff --git a/vendor/hayro-syntax/src/filter/mod.rs b/vendor/hayro-syntax/src/filter/mod.rs
new file mode 100644
index 000000000..31e795e95
--- /dev/null
+++ b/vendor/hayro-syntax/src/filter/mod.rs
@@ -0,0 +1,133 @@
+//! Results from decoding filtered data streams.
+
+mod ascii_85;
+pub(crate) mod ascii_hex;
+#[cfg(feature = "images")]
+mod ccitt;
+#[cfg(feature = "images")]
+mod dct;
+#[cfg(feature = "images")]
+mod jbig2;
+#[cfg(feature = "images")]
+mod jpx;
+mod lzw_flate;
+mod run_length;
+
+use crate::object::Dict;
+use crate::object::Name;
+use crate::object::dict::keys::*;
+use crate::object::stream::{DecodeFailure, FilterResult, ImageDecodeParams};
+use core::ops::Deref;
+
+/// A data filter.
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
+pub enum Filter {
+ /// ASCII hexadecimal encoding.
+ AsciiHexDecode,
+ /// ASCII base-85 encoding.
+ Ascii85Decode,
+ /// Lempel-Ziv-Welch (LZW) compression.
+ LzwDecode,
+ /// DEFLATE compression (zlib/gzip).
+ FlateDecode,
+ /// Run-length encoding compression.
+ RunLengthDecode,
+ /// CCITT Group 3 or Group 4 fax compression.
+ CcittFaxDecode,
+ /// JBIG2 compression for bi-level images.
+ Jbig2Decode,
+ /// JPEG (DCT) compression.
+ DctDecode,
+ /// JPEG 2000 compression.
+ JpxDecode,
+ /// Encryption filter.
+ Crypt,
+}
+
+impl Filter {
+ fn debug_name(&self) -> &'static str {
+ match self {
+ Self::AsciiHexDecode => "ascii_hex",
+ Self::Ascii85Decode => "ascii_85",
+ Self::LzwDecode => "lzw",
+ Self::FlateDecode => "flate",
+ Self::RunLengthDecode => "run-length",
+ Self::CcittFaxDecode => "ccit_fax",
+ Self::Jbig2Decode => "jbig2",
+ Self::DctDecode => "dct",
+ Self::JpxDecode => "jpx",
+ Self::Crypt => "crypt",
+ }
+ }
+
+ pub(crate) fn from_name(name: Name<'_>) -> Option<Self> {
+ match name.deref() {
+ ASCII_HEX_DECODE | ASCII_HEX_DECODE_ABBREVIATION => Some(Self::AsciiHexDecode),
+ ASCII85_DECODE | ASCII85_DECODE_ABBREVIATION => Some(Self::Ascii85Decode),
+ LZW_DECODE | LZW_DECODE_ABBREVIATION => Some(Self::LzwDecode),
+ FLATE_DECODE | FLATE_DECODE_ABBREVIATION => Some(Self::FlateDecode),
+ RUN_LENGTH_DECODE | RUN_LENGTH_DECODE_ABBREVIATION => Some(Self::RunLengthDecode),
+ CCITTFAX_DECODE | CCITTFAX_DECODE_ABBREVIATION => Some(Self::CcittFaxDecode),
+ JBIG2_DECODE => Some(Self::Jbig2Decode),
+ DCT_DECODE | DCT_DECODE_ABBREVIATION => Some(Self::DctDecode),
+ JPX_DECODE => Some(Self::JpxDecode),
+ CRYPT => Some(Self::Crypt),
+ _ => {
+ warn!("unknown filter: {}", name.as_str());
+
+ None
+ }
+ }
+ }
+
+ pub(crate) fn apply(
+ &self,
+ data: &[u8],
+ params: &Dict<'_>,
+ #[cfg_attr(not(feature = "images"), allow(unused))] image_params: &ImageDecodeParams,
+ ) -> Result<FilterResult<'static>, DecodeFailure> {
+ let res = match self {
+ Self::AsciiHexDecode => ascii_hex::decode(data)
+ .map(FilterResult::from_data)
+ .ok_or(DecodeFailure::StreamDecode),
+ Self::Ascii85Decode => ascii_85::decode(data)
+ .map(FilterResult::from_data)
+ .ok_or(DecodeFailure::StreamDecode),
+ Self::RunLengthDecode => run_length::decode(data)
+ .map(FilterResult::from_data)
+ .ok_or(DecodeFailure::StreamDecode),
+ Self::LzwDecode => lzw_flate::lzw::decode(data, params)
+ .map(FilterResult::from_data)
+ .ok_or(DecodeFailure::StreamDecode),
+ Self::FlateDecode => lzw_flate::flate::decode(data, params)
+ .map(FilterResult::from_data)
+ .ok_or(DecodeFailure::StreamDecode),
+ #[cfg(feature = "images")]
+ Self::DctDecode => {
+ dct::decode(data, params, image_params).ok_or(DecodeFailure::ImageDecode)
+ }
+ #[cfg(feature = "images")]
+ Self::CcittFaxDecode => {
+ ccitt::decode(data, params, image_params).ok_or(DecodeFailure::ImageDecode)
+ }
+ #[cfg(feature = "images")]
+ Self::Jbig2Decode => {
+ jbig2::decode(data, params, image_params).ok_or(DecodeFailure::ImageDecode)
+ }
+ #[cfg(feature = "images")]
+ Self::JpxDecode => jpx::decode(data, image_params).ok_or(DecodeFailure::ImageDecode),
+ #[cfg(not(feature = "images"))]
+ Self::DctDecode | Self::CcittFaxDecode | Self::Jbig2Decode | Self::JpxDecode => {
+ warn!("image decoding is not supported (enable the `images` feature)");
+ Err(DecodeFailure::ImageDecode)
+ }
+ _ => Err(DecodeFailure::StreamDecode),
+ };
+
+ if res.is_err() {
+ warn!("failed to apply filter {}", self.debug_name());
+ }
+
+ res
+ }
+}
diff --git a/vendor/hayro-syntax/src/filter/run_length.rs b/vendor/hayro-syntax/src/filter/run_length.rs
new file mode 100644
index 000000000..e66d9ec78
--- /dev/null
+++ b/vendor/hayro-syntax/src/filter/run_length.rs
@@ -0,0 +1,44 @@
+use crate::reader::Reader;
+use alloc::vec;
+use alloc::vec::Vec;
+
+pub(crate) fn decode(data: &[u8]) -> Option<Vec<u8>> {
+ let mut reader = Reader::new(data);
+ let mut decoded = vec![];
+
+ loop {
+ let length = reader.read_byte()?;
+
+ match length {
+ 128 => break,
+ 0..=127 => {
+ // PDFBOX-3990, just abort early if stream is invalid.
+ let Some(bytes) = reader.read_bytes(length as usize + 1) else {
+ break;
+ };
+
+ decoded.extend(bytes);
+ }
+ _ => {
+ let length = 257 - length as usize;
+ decoded.extend([reader.read_byte()?].repeat(length));
+ }
+ }
+ }
+
+ Some(decoded)
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::filter::run_length::decode;
+
+ #[test]
+ fn run_length() {
+ let input = vec![4, 10, 11, 12, 13, 14, 253, 3, 128];
+ assert_eq!(
+ decode(&input).unwrap(),
+ vec![10, 11, 12, 13, 14, 3, 3, 3, 3]
+ );
+ }
+}
diff --git a/vendor/hayro-syntax/src/lib.rs b/vendor/hayro-syntax/src/lib.rs
new file mode 100644
index 000000000..b67652315
--- /dev/null
+++ b/vendor/hayro-syntax/src/lib.rs
@@ -0,0 +1,113 @@
+/*!
+A low-level library for reading PDF files.
+
+This crate implements the `Syntax` chapter of the PDF reference, and therefore
+serves as a very good basis for building various abstractions on top of it, without having to reimplement
+the PDF parsing logic.
+
+This crate does not provide more high-level functionality, such as parsing fonts or color spaces.
+Such functionality is out-of-scope for `hayro-syntax`, since this crate is supposed to be
+as *light-weight* and *application-agnostic* as possible.
+
+Functionality-wise, this crate is therefore close to feature-complete. The main missing feature
+is support for password-protected documents. In addition to that, more low-level APIs might be
+added in the future.
+
+The crate is `no_std` compatible but requires an allocator to be available.
+
+# Example
+This short example shows you how to load a PDF file and iterate over the content streams of all
+pages.
+```rust
+use hayro_syntax::Pdf;
+use std::path::PathBuf;
+
+// First load the data that constitutes the PDF file.
+let data = std::fs::read(
+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../hayro-tests/pdfs/custom/text_with_rise.pdf"),
+)
+.unwrap();
+
+// Then create a new PDF file from it.
+//
+// Here we are just unwrapping in case reading the file failed, but you
+// might instead want to apply proper error handling.
+let pdf = Pdf::new(data).unwrap();
+
+// First access all pages, and then iterate over the operators of each page's
+// content stream and print them.
+let pages = pdf.pages();
+for page in pages.iter() {
+ let mut ops = page.typed_operations();
+
+ while let Some(op) = ops.next() {
+ println!("{op:?}");
+ }
+}
+```
+
+# Safety
+When the `unsafe` feature is disabled, there is only use of `unsafe` in `hayro-syntax`.
+We also unconditionally use the `smallvec` crate which uses unsafe internally, but that's
+it.
+
+For better performance, it is strongly recommended to enable the `unsafe` feature,
+which does result in slightly more unsafe code being, but does give better performance:
+- We will use the `flate2` crate for decoding flate streams.
+- SIMD will be enabled to accelerate decoding of images.
+- `memchr` will be used to accelerate some of the fallback parsing code.
+
+# Features
+The supported features include:
+- Parsing xref tables in all its possible formats, including xref streams.
+- Best-effort attempt at repairing PDF files with broken xref tables.
+- Parsing of all objects types (also in object streams).
+- Parsing and decoding PDF streams.
+- Iterating over pages as well as their content streams in a typed or untyped fashion.
+- The crate is very lightweight, especially in comparison to other PDF crates.
+
+# Limitations
+- There are still a few features missing, for example, support for
+ password-protected PDFs. In addition to that, many properties (like page annotations) are
+ currently not exposed.
+- This crate is for read-only processing, you cannot directly use it to manipulate PDF files.
+ If you need to do that, there are other crates in the Rust ecosystem that are suitable for this.
+*/
+
+#![cfg_attr(not(feature = "std"), no_std)]
+#![deny(missing_docs)]
+
+extern crate alloc;
+
+#[macro_use]
+mod log;
+
+pub(crate) mod math;
+pub(crate) mod sync;
+
+mod data;
+pub(crate) mod filter;
+pub(crate) mod pdf;
+pub(crate) mod trivia;
+pub(crate) mod util;
+
+pub mod content;
+mod crypto;
+pub mod metadata;
+pub mod object;
+pub mod page;
+pub mod transform;
+pub mod xref;
+
+// We only expose them so hayro-interpret can use them, but they are not intended
+// to be used by others
+#[doc(hidden)]
+pub mod bit_reader;
+#[doc(hidden)]
+pub mod byte_reader;
+#[doc(hidden)]
+pub mod reader;
+
+pub use data::PdfData;
+pub use filter::*;
+pub use pdf::*;
diff --git a/vendor/hayro-syntax/src/log.rs b/vendor/hayro-syntax/src/log.rs
new file mode 100644
index 000000000..f359cbe24
--- /dev/null
+++ b/vendor/hayro-syntax/src/log.rs
@@ -0,0 +1,40 @@
+//! Logging macros that optionally forward to the `log` crate.
+
+macro_rules! debug {
+ ($fmt:literal $(, $($arg:expr),* $(,)?)?) => {{
+ #[cfg(feature = "logging")]
+ {
+ ::log::debug!($fmt $(, $($arg),*)?);
+ }
+ #[cfg(not(feature = "logging"))]
+ {
+ $($(let _ = &$arg;)*)?
+ }
+ }};
+}
+
+macro_rules! error {
+ ($fmt:literal $(, $($arg:expr),* $(,)?)?) => {{
+ #[cfg(feature = "logging")]
+ {
+ ::log::error!($fmt $(, $($arg),*)?);
+ }
+ #[cfg(not(feature = "logging"))]
+ {
+ $($(let _ = &$arg;)*)?
+ }
+ }};
+}
+
+macro_rules! warn {
+ ($fmt:literal $(, $($arg:expr),* $(,)?)?) => {{
+ #[cfg(feature = "logging")]
+ {
+ ::log::warn!($fmt $(, $($arg),*)?);
+ }
+ #[cfg(not(feature = "logging"))]
+ {
+ $($(let _ = &$arg;)*)?
+ }
+ }};
+}
diff --git a/vendor/hayro-syntax/src/math.rs b/vendor/hayro-syntax/src/math.rs
new file mode 100644
index 000000000..60bf95e0e
--- /dev/null
+++ b/vendor/hayro-syntax/src/math.rs
@@ -0,0 +1,61 @@
+// Note that these polyfills can be very imprecise, but hopefully good enough
+// for the vast majority of cases.
+
+#[cfg(feature = "images")]
+#[inline(always)]
+pub(crate) fn round_f32(x: f32) -> f32 {
+ #[cfg(feature = "std")]
+ {
+ x.round()
+ }
+ #[cfg(not(feature = "std"))]
+ {
+ if x >= 0.0 {
+ floor_f32(x + 0.5)
+ } else {
+ -floor_f32(-x + 0.5)
+ }
+ }
+}
+
+#[cfg(all(feature = "images", not(feature = "std")))]
+#[inline(always)]
+fn floor_f32(x: f32) -> f32 {
+ let xi = x as i32;
+ let xf = xi as f32;
+ if x < xf { xf - 1.0 } else { xf }
+}
+
+#[inline(always)]
+pub(crate) fn trunc_f64(x: f64) -> f64 {
+ #[cfg(feature = "std")]
+ {
+ x.trunc()
+ }
+ #[cfg(not(feature = "std"))]
+ {
+ x as i64 as f64
+ }
+}
+
+#[inline(always)]
+pub(crate) fn powi_f64(x: f64, n: u32) -> f64 {
+ #[cfg(feature = "std")]
+ {
+ x.powi(n as i32)
+ }
+ #[cfg(not(feature = "std"))]
+ {
+ let mut result = 1.0;
+ let mut base = x;
+ let mut exp = n;
+ while exp > 0 {
+ if exp & 1 == 1 {
+ result *= base;
+ }
+ base *= base;
+ exp >>= 1;
+ }
+ result
+ }
+}
diff --git a/vendor/hayro-syntax/src/metadata.rs b/vendor/hayro-syntax/src/metadata.rs
new file mode 100644
index 000000000..5b86e7d42
--- /dev/null
+++ b/vendor/hayro-syntax/src/metadata.rs
@@ -0,0 +1,43 @@
+//! Reading document metadata.
+
+use crate::object::DateTime;
+use alloc::vec::Vec;
+
+#[derive(Clone, Default, Debug, PartialEq, Eq)]
+/// The metadata of a PDF document.
+pub struct Metadata {
+ /// The creation date of the document.
+ pub creation_date: Option<DateTime>,
+ /// The modification date of the document.
+ pub modification_date: Option<DateTime>,
+ /// The title of the document.
+ ///
+ /// In the vast majority of cases, this is going to be an ASCII string, but it doesn't have to
+ /// be.
+ pub title: Option<Vec<u8>>,
+ /// The author of the document.
+ ///
+ /// In the vast majority of cases, this is going to be an ASCII string, but it doesn't have to
+ /// be.
+ pub author: Option<Vec<u8>>,
+ /// The subject of the document.
+ ///
+ /// In the vast majority of cases, this is going to be an ASCII string, but it doesn't have to
+ /// be.
+ pub subject: Option<Vec<u8>>,
+ /// The keywords of the document.
+ ///
+ /// In the vast majority of cases, this is going to be an ASCII string, but it doesn't have to
+ /// be.
+ pub keywords: Option<Vec<u8>>,
+ /// The creator of the document.
+ ///
+ /// In the vast majority of cases, this is going to be an ASCII string, but it doesn't have to
+ /// be.
+ pub creator: Option<Vec<u8>>,
+ /// The producer of the document.
+ ///
+ /// In the vast majority of cases, this is going to be an ASCII string, but it doesn't have to
+ /// be.
+ pub producer: Option<Vec<u8>>,
+}
diff --git a/vendor/hayro-syntax/src/object/array.rs b/vendor/hayro-syntax/src/object/array.rs
new file mode 100644
index 000000000..332f09ab8
--- /dev/null
+++ b/vendor/hayro-syntax/src/object/array.rs
@@ -0,0 +1,417 @@
+//! Arrays.
+
+use crate::object::macros::object;
+use crate::object::r#ref::MaybeRef;
+use crate::object::{FromBytes, Object, ObjectLike};
+use crate::reader::Reader;
+use crate::reader::{Readable, ReaderContext, ReaderExt, Skippable};
+use alloc::vec::Vec;
+use core::fmt::{Debug, Formatter};
+use core::marker::PhantomData;
+use smallvec::SmallVec;
+
+/// An array of PDF objects.
+#[derive(Clone)]
+pub struct Array<'a> {
+ data: &'a [u8],
+ ctx: ReaderContext<'a>,
+}
+
+// Note that this is not structural equality, i.e. two arrays with the same
+// items are still considered different if they have different whitespaces.
+impl PartialEq for Array<'_> {
+ fn eq(&self, other: &Self) -> bool {
+ self.data == other.data
+ }
+}
+
+impl<'a> Array<'a> {
+ /// Returns an iterator over the objects of the array.
+ pub fn raw_iter(&self) -> ArrayIter<'a> {
+ ArrayIter::new(self.data, &self.ctx)
+ }
+
+ /// Returns an iterator over the resolved objects of the array.
+ #[allow(
+ private_bounds,
+ reason = "users shouldn't be able to implement `ObjectLike` for custom objects."
+ )]
+ pub fn iter<T>(&self) -> ResolvedArrayIter<'a, T>
+ where
+ T: ObjectLike<'a>,
+ {
+ ResolvedArrayIter::new(self.data, &self.ctx)
+ }
+
+ /// Return a flex iterator over the items in the array.
+ pub fn flex_iter(&self) -> FlexArrayIter<'a> {
+ FlexArrayIter::new(self.data, &self.ctx)
+ }
+
+ /// Return the raw data of the array.
+ pub fn data(&self) -> &'a [u8] {
+ self.data
+ }
+}
+
+impl Debug for Array<'_> {
+ fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
+ let mut debug_list = f.debug_list();
+
+ self.raw_iter().for_each(|i| {
+ debug_list.entry(&i);
+ });
+
+ Ok(())
+ }
+}
+
+object!(Array<'a>, Array);
+
+impl Skippable for Array<'_> {
+ fn skip(r: &mut Reader<'_>, is_content_stream: bool) -> Option<()> {
+ r.forward_tag(b"[")?;
+
+ loop {
+ r.skip_white_spaces_and_comments();
+
+ if let Some(()) = r.forward_tag(b"]") {
+ return Some(());
+ } else if is_content_stream {
+ r.skip::<Object<'_>>(true)?;
+ } else {
+ r.skip::<MaybeRef<Object<'_>>>(false)?;
+ }
+ }
+ }
+}
+
+impl Default for Array<'_> {
+ fn default() -> Self {
+ Self::from_bytes(b"[]").unwrap()
+ }
+}
+
+impl<'a> Readable<'a> for Array<'a> {
+ fn read(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<Self> {
+ let bytes = r.skip::<Array<'_>>(ctx.in_content_stream())?;
+
+ Some(Self {
+ data: &bytes[1..bytes.len() - 1],
+ ctx: ctx.clone(),
+ })
+ }
+}
+
+/// An iterator over the items of an array.
+pub struct ArrayIter<'a> {
+ reader: Reader<'a>,
+ ctx: ReaderContext<'a>,
+}
+
+impl<'a> ArrayIter<'a> {
+ fn new(data: &'a [u8], ctx: &ReaderContext<'a>) -> Self {
+ Self {
+ reader: Reader::new(data),
+ ctx: ctx.clone(),
+ }
+ }
+}
+
+impl<'a> Iterator for ArrayIter<'a> {
+ type Item = MaybeRef<Object<'a>>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.reader.skip_white_spaces_and_comments();
+
+ if !self.reader.at_end() {
+ // Objects are already guaranteed to be valid.
+ let item = self
+ .reader
+ .read_with_context::<MaybeRef<Object<'_>>>(&self.ctx)
+ .unwrap();
+ return Some(item);
+ }
+
+ None
+ }
+}
+
+/// An iterator over the array that resolves objects of a specific type.
+pub struct ResolvedArrayIter<'a, T> {
+ flex_iter: FlexArrayIter<'a>,
+ phantom_data: PhantomData<T>,
+}
+
+impl<'a, T> ResolvedArrayIter<'a, T> {
+ fn new(data: &'a [u8], ctx: &ReaderContext<'a>) -> Self {
+ Self {
+ flex_iter: FlexArrayIter::new(data, ctx),
+ phantom_data: PhantomData,
+ }
+ }
+}
+
+impl<'a, T> Iterator for ResolvedArrayIter<'a, T>
+where
+ T: ObjectLike<'a>,
+{
+ type Item = T;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.flex_iter.next::<T>()
+ }
+}
+
+/// An iterator over the array that allows reading a different object each time.
+pub struct FlexArrayIter<'a> {
+ reader: Reader<'a>,
+ ctx: ReaderContext<'a>,
+}
+
+impl<'a> FlexArrayIter<'a> {
+ fn new(data: &'a [u8], ctx: &ReaderContext<'a>) -> Self {
+ Self {
+ reader: Reader::new(data),
+ ctx: ctx.clone(),
+ }
+ }
+
+ #[allow(
+ private_bounds,
+ reason = "users shouldn't be able to implement `ObjectLike` for custom objects."
+ )]
+ #[allow(clippy::should_implement_trait)]
+ /// Try reading the next item as a specific object from the array.
+ pub fn next<T: ObjectLike<'a>>(&mut self) -> Option<T> {
+ self.reader.skip_white_spaces_and_comments();
+
+ if !self.reader.at_end() {
+ return match self.reader.read_with_context::<MaybeRef<T>>(&self.ctx)? {
+ MaybeRef::Ref(r) => self.ctx.xref().get_with::<T>(r.into(), &self.ctx),
+ MaybeRef::NotRef(i) => Some(i),
+ };
+ }
+
+ None
+ }
+}
+
+impl<'a, T: ObjectLike<'a> + Copy + Default, const C: usize> TryFrom<Array<'a>> for [T; C] {
+ type Error = ();
+
+ fn try_from(value: Array<'a>) -> Result<Self, Self::Error> {
+ let mut iter = value.iter::<T>();
+
+ let mut val = [T::default(); C];
+
+ for i in 0..C {
+ val[i] = iter.next().ok_or(())?;
+ }
+
+ if iter.next().is_some() {
+ warn!("found excess elements in array");
+
+ return Err(());
+ }
+
+ Ok(val)
+ }
+}
+
+impl<'a, T: ObjectLike<'a> + Copy + Default, const C: usize> TryFrom<Object<'a>> for [T; C]
+where
+ [T; C]: TryFrom<Array<'a>, Error = ()>,
+{
+ type Error = ();
+
+ fn try_from(value: Object<'a>) -> Result<Self, Self::Error> {
+ match value {
+ Object::Array(a) => a.try_into(),
+ _ => Err(()),
+ }
+ }
+}
+
+impl<'a, T: ObjectLike<'a> + Copy + Default, const C: usize> Readable<'a> for [T; C] {
+ fn read(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<Self> {
+ let array = Array::read(r, ctx)?;
+ array.try_into().ok()
+ }
+}
+
+impl<'a, T: ObjectLike<'a> + Copy + Default, const C: usize> ObjectLike<'a> for [T; C] {}
+
+impl<'a, T: ObjectLike<'a>> TryFrom<Array<'a>> for Vec<T> {
+ type Error = ();
+
+ fn try_from(value: Array<'a>) -> Result<Self, Self::Error> {
+ Ok(value.iter::<T>().collect())
+ }
+}
+
+impl<'a, T: ObjectLike<'a>> TryFrom<Object<'a>> for Vec<T> {
+ type Error = ();
+
+ fn try_from(value: Object<'a>) -> Result<Self, Self::Error> {
+ match value {
+ Object::Array(a) => a.try_into(),
+ _ => Err(()),
+ }
+ }
+}
+
+impl<'a, T: ObjectLike<'a>> Readable<'a> for Vec<T> {
+ fn read(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<Self> {
+ let array = Array::read(r, ctx)?;
+ array.try_into().ok()
+ }
+}
+
+impl<'a, T: ObjectLike<'a>> ObjectLike<'a> for Vec<T> {}
+
+impl<'a, U: ObjectLike<'a>, T: ObjectLike<'a> + smallvec::Array<Item = U>> TryFrom<Array<'a>>
+ for SmallVec<T>
+{
+ type Error = ();
+
+ fn try_from(value: Array<'a>) -> Result<Self, Self::Error> {
+ Ok(value.iter::<U>().collect())
+ }
+}
+
+impl<'a, U: ObjectLike<'a>, T: ObjectLike<'a> + smallvec::Array<Item = U>> TryFrom<Object<'a>>
+ for SmallVec<T>
+{
+ type Error = ();
+
+ fn try_from(value: Object<'a>) -> Result<Self, Self::Error> {
+ match value {
+ Object::Array(a) => a.try_into(),
+ _ => Err(()),
+ }
+ }
+}
+
+impl<'a, U: ObjectLike<'a>, T: ObjectLike<'a> + smallvec::Array<Item = U>> Readable<'a>
+ for SmallVec<T>
+{
+ fn read(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<Self> {
+ let array = Array::read(r, ctx)?;
+ array.try_into().ok()
+ }
+}
+
+impl<'a, U: ObjectLike<'a>, T: ObjectLike<'a> + smallvec::Array<Item = U>> ObjectLike<'a>
+ for SmallVec<T>
+where
+ U: Clone,
+ U: Debug,
+{
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::object::Array;
+ use crate::object::Object;
+ use crate::object::r#ref::{MaybeRef, ObjRef};
+ use crate::reader::Reader;
+ use crate::reader::{ReaderContext, ReaderExt};
+ use crate::xref::XRef;
+
+ fn array_impl(data: &[u8]) -> Option<Vec<Object<'_>>> {
+ Reader::new(data)
+ .read_with_context::<Array<'_>>(&ReaderContext::new(XRef::dummy(), false))
+ .map(|a| a.iter::<Object<'_>>().collect::<Vec<_>>())
+ }
+
+ fn array_ref_impl(data: &[u8]) -> Option<Vec<MaybeRef<Object<'_>>>> {
+ Reader::new(data)
+ .read_with_context::<Array<'_>>(&ReaderContext::new(XRef::dummy(), false))
+ .map(|a| a.raw_iter().collect::<Vec<_>>())
+ }
+
+ #[test]
+ fn empty_array_1() {
+ let res = array_impl(b"[]").unwrap();
+ assert!(res.is_empty());
+ }
+
+ #[test]
+ fn empty_array_2() {
+ let res = array_impl(b"[ \n]").unwrap();
+ assert!(res.is_empty());
+ }
+
+ #[test]
+ fn array_1() {
+ let res = array_impl(b"[34]").unwrap();
+ assert!(matches!(res[0], Object::Number(_)));
+ }
+
+ #[test]
+ fn array_2() {
+ let res = array_impl(b"[true ]").unwrap();
+ assert!(matches!(res[0], Object::Boolean(_)));
+ }
+
+ #[test]
+ fn array_3() {
+ let res = array_impl(b"[true \n false 34.564]").unwrap();
+ assert!(matches!(res[0], Object::Boolean(_)));
+ assert!(matches!(res[1], Object::Boolean(_)));
+ assert!(matches!(res[2], Object::Number(_)));
+ }
+
+ #[test]
+ fn array_4() {
+ let res = array_impl(b"[(A string.) << /Hi 34.35 >>]").unwrap();
+ assert!(matches!(res[0], Object::String(_)));
+ assert!(matches!(res[1], Object::Dict(_)));
+ }
+
+ #[test]
+ fn array_5() {
+ let res = array_impl(b"[[32] 345.6]").unwrap();
+ assert!(matches!(res[0], Object::Array(_)));
+ assert!(matches!(res[1], Object::Number(_)));
+ }
+
+ #[test]
+ fn array_with_ref() {
+ let res = array_ref_impl(b"[345 34 5 R 34.0]").unwrap();
+ assert!(matches!(res[0], MaybeRef::NotRef(Object::Number(_))));
+ assert!(matches!(
+ res[1],
+ MaybeRef::Ref(ObjRef {
+ obj_number: 34,
+ gen_number: 5
+ })
+ ));
+ assert!(matches!(res[2], MaybeRef::NotRef(Object::Number(_))));
+ }
+
+ #[test]
+ fn malformed_ref_is_not_valid_array() {
+ assert!(array_ref_impl(b"[8 0R]").is_none());
+ }
+
+ #[test]
+ fn array_with_single_number_is_valid() {
+ assert!(array_ref_impl(b"[345345345]").is_some());
+ }
+
+ #[test]
+ fn array_with_comment() {
+ let res = array_impl(b"[true % A comment \n false]").unwrap();
+ assert!(matches!(res[0], Object::Boolean(_)));
+ assert!(matches!(res[1], Object::Boolean(_)));
+ }
+
+ #[test]
+ fn array_with_trailing() {
+ let res = array_impl(b"[(Hi) /Test]trialing data").unwrap();
+ assert!(matches!(res[0], Object::String(_)));
+ assert!(matches!(res[1], Object::Name(_)));
+ }
+}
diff --git a/vendor/hayro-syntax/src/object/bool.rs b/vendor/hayro-syntax/src/object/bool.rs
new file mode 100644
index 000000000..8cfb3afb9
--- /dev/null
+++ b/vendor/hayro-syntax/src/object/bool.rs
@@ -0,0 +1,61 @@
+//! Booleans.
+
+use crate::object::Object;
+use crate::object::macros::object;
+use crate::reader::Reader;
+use crate::reader::{Readable, ReaderContext, ReaderExt, Skippable};
+
+impl Skippable for bool {
+ fn skip(r: &mut Reader<'_>, _: bool) -> Option<()> {
+ match r.peek_byte()? {
+ b't' => r.forward_tag(b"true"),
+ b'f' => r.forward_tag(b"false"),
+ _ => None,
+ }
+ }
+}
+
+impl Readable<'_> for bool {
+ fn read(r: &mut Reader<'_>, _: &ReaderContext<'_>) -> Option<Self> {
+ match r.skip::<Self>(true)? {
+ b"true" => Some(true),
+ b"false" => Some(false),
+ _ => None,
+ }
+ }
+}
+
+object!(bool, Boolean);
+
+#[cfg(test)]
+mod tests {
+ use crate::reader::Reader;
+ use crate::reader::ReaderExt;
+
+ #[test]
+ fn bool_true() {
+ assert!(
+ Reader::new("true".as_bytes())
+ .read_without_context::<bool>()
+ .unwrap()
+ );
+ }
+
+ #[test]
+ fn bool_false() {
+ assert!(
+ !Reader::new("false".as_bytes())
+ .read_without_context::<bool>()
+ .unwrap()
+ );
+ }
+
+ #[test]
+ fn bool_trailing() {
+ assert!(
+ Reader::new("trueabdf".as_bytes())
+ .read_without_context::<bool>()
+ .unwrap()
+ );
+ }
+}
diff --git a/vendor/hayro-syntax/src/object/date.rs b/vendor/hayro-syntax/src/object/date.rs
new file mode 100644
index 000000000..364d34d5a
--- /dev/null
+++ b/vendor/hayro-syntax/src/object/date.rs
@@ -0,0 +1,230 @@
+use crate::byte_reader::Reader;
+use core::str::FromStr;
+
+/// A date time.
+#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
+pub struct DateTime {
+ /// The year.
+ pub year: u16,
+ /// The year.
+ pub month: u8,
+ /// The day.
+ pub day: u8,
+ /// The hour.
+ pub hour: u8,
+ /// The minute.
+ pub minute: u8,
+ /// The second.
+ pub second: u8,
+ /// The offset in hours from UTC.
+ pub utc_offset_hour: i8,
+ /// The offset in minutes from UTC.
+ pub utc_offset_minute: u8,
+}
+
+impl DateTime {
+ pub(crate) fn from_bytes(bytes: &[u8]) -> Option<Self> {
+ let mut reader = Reader::new(bytes);
+
+ reader.forward_tag(b"D:")?;
+
+ let read_num = |reader: &mut Reader<'_>, bytes: u8, min: u16, max: u16| -> Option<u16> {
+ if matches!(reader.peek_byte()?, b'-' | b'+' | b'Z') {
+ return None;
+ }
+
+ let num = u16::from_str(core::str::from_utf8(reader.read_bytes(bytes as usize)?).ok()?)
+ .ok()?;
+
+ if num < min || num > max {
+ return None;
+ }
+
+ Some(num)
+ };
+
+ let year = read_num(&mut reader, 4, 0, 9999)?;
+ let month = read_num(&mut reader, 2, 1, 12)
+ .map(|n| n as u8)
+ .unwrap_or(1);
+ let day = read_num(&mut reader, 2, 1, 31)
+ .map(|n| n as u8)
+ .unwrap_or(1);
+ let hour = read_num(&mut reader, 2, 0, 23)
+ .map(|n| n as u8)
+ .unwrap_or(0);
+ let minute = read_num(&mut reader, 2, 0, 59)
+ .map(|n| n as u8)
+ .unwrap_or(0);
+ let second = read_num(&mut reader, 2, 0, 59)
+ .map(|n| n as u8)
+ .unwrap_or(0);
+
+ let (utc_offset_hour, utc_offset_minute) = if !reader.at_end() {
+ let multiplier = match reader.read_byte()? {
+ b'-' => -1,
+ _ => 1,
+ };
+
+ let hour = multiplier
+ * read_num(&mut reader, 2, 0, 23)
+ .map(|n| n as i8)
+ .unwrap_or(0);
+ reader.forward_tag(b"\'");
+ let minute = read_num(&mut reader, 2, 0, 59)
+ .map(|n| n as u8)
+ .unwrap_or(0);
+
+ (hour, minute)
+ } else {
+ (0, 0)
+ };
+
+ Some(Self {
+ year,
+ month,
+ day,
+ hour,
+ minute,
+ second,
+ utc_offset_hour,
+ utc_offset_minute,
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::DateTime;
+
+ #[allow(clippy::too_many_arguments)]
+ fn dt(
+ year: u16,
+ month: u8,
+ day: u8,
+ hour: u8,
+ minute: u8,
+ second: u8,
+ utc_hour: i8,
+ utc_minute: u8,
+ ) -> DateTime {
+ DateTime {
+ year,
+ month,
+ day,
+ hour,
+ minute,
+ second,
+ utc_offset_hour: utc_hour,
+ utc_offset_minute: utc_minute,
+ }
+ }
+
+ fn parse(str: &str) -> DateTime {
+ DateTime::from_bytes(str.as_bytes()).unwrap()
+ }
+
+ #[test]
+ fn year_only_defaults() {
+ assert_eq!(parse("D:2023"), dt(2023, 1, 1, 0, 0, 0, 0, 0));
+ }
+
+ #[test]
+ fn year_month_defaults() {
+ assert_eq!(parse("D:202312"), dt(2023, 12, 1, 0, 0, 0, 0, 0));
+ }
+
+ #[test]
+ fn year_month_day_defaults() {
+ assert_eq!(parse("D:20231225"), dt(2023, 12, 25, 0, 0, 0, 0, 0));
+ }
+
+ #[test]
+ fn ymdh() {
+ assert_eq!(parse("D:2023122514"), dt(2023, 12, 25, 14, 0, 0, 0, 0));
+ }
+
+ #[test]
+ fn ymdhm() {
+ assert_eq!(parse("D:202312251430"), dt(2023, 12, 25, 14, 30, 0, 0, 0));
+ }
+
+ #[test]
+ fn full_local_time() {
+ assert_eq!(
+ parse("D:20231225143015"),
+ dt(2023, 12, 25, 14, 30, 15, 0, 0)
+ );
+ }
+
+ #[test]
+ fn example_from_spec() {
+ assert_eq!(
+ parse("D:199812231952-08'00"),
+ dt(1998, 12, 23, 19, 52, 0, -8, 0)
+ );
+ }
+
+ #[test]
+ fn positive_offset_with_minutes() {
+ assert_eq!(
+ parse("D:20230701120000+05'30"),
+ dt(2023, 7, 1, 12, 0, 0, 5, 30)
+ );
+ }
+
+ #[test]
+ fn utc_z() {
+ assert_eq!(parse("D:20230701120000Z"), dt(2023, 7, 1, 12, 0, 0, 0, 0));
+ }
+
+ #[test]
+ fn utc_z_with_zero_offsets() {
+ assert_eq!(
+ parse("D:20230701120000Z00'00"),
+ dt(2023, 7, 1, 12, 0, 0, 0, 0)
+ );
+ }
+
+ #[test]
+ fn negative_offset_with_minutes() {
+ assert_eq!(
+ parse("D:20230701120000-03'15"),
+ dt(2023, 7, 1, 12, 0, 0, -3, 15)
+ );
+ }
+
+ #[test]
+ fn leap_year() {
+ assert_eq!(
+ parse("D:20000229010203+01'00"),
+ dt(2000, 2, 29, 1, 2, 3, 1, 0)
+ );
+ }
+
+ #[test]
+ fn max_values() {
+ assert_eq!(
+ parse("D:99991231235959+14'00"),
+ dt(9999, 12, 31, 23, 59, 59, 14, 0)
+ );
+ }
+
+ #[test]
+ fn min_values() {
+ assert_eq!(parse("D:00000101000000+00'00"), dt(0, 1, 1, 0, 0, 0, 0, 0));
+ }
+
+ #[test]
+ fn offset_hour_only() {
+ assert_eq!(parse("D:202307011200+02"), dt(2023, 7, 1, 12, 0, 0, 2, 0));
+ }
+
+ #[test]
+ fn offset_negative_zero_hour() {
+ assert_eq!(
+ parse("D:202307011200-00'45"),
+ dt(2023, 7, 1, 12, 0, 0, 0, 45)
+ );
+ }
+}
diff --git a/vendor/hayro-syntax/src/object/dict.rs b/vendor/hayro-syntax/src/object/dict.rs
new file mode 100644
index 000000000..10424eda4
--- /dev/null
+++ b/vendor/hayro-syntax/src/object/dict.rs
@@ -0,0 +1,1153 @@
+//! Dictionaries.
+
+use crate::object::macros::object;
+use crate::object::r#ref::{MaybeRef, ObjRef};
+use crate::object::{Name, ObjectIdentifier};
+use crate::object::{Object, ObjectLike};
+use crate::reader::Reader;
+use crate::reader::{Readable, ReaderContext, ReaderExt, Skippable};
+use crate::sync::Arc;
+use crate::sync::FxHashMap;
+use alloc::format;
+use alloc::vec::Vec;
+use core::fmt::{Debug, Formatter};
+use core::ops::Deref;
+
+/// A dictionary, which is a key-value map, keys being names, and values being any PDF object or
+/// objetc reference.
+#[derive(Clone)]
+pub struct Dict<'a>(Inner<'a>);
+
+#[derive(Clone)]
+enum Inner<'a> {
+ Empty,
+ Some(Arc<Repr<'a>>),
+}
+
+impl Default for Dict<'_> {
+ fn default() -> Self {
+ Self::empty()
+ }
+}
+
+// Note that this is not structural equality, i.e. two dictionaries with the same
+// items are still considered different if they have different whitespaces.
+impl PartialEq for Dict<'_> {
+ fn eq(&self, other: &Self) -> bool {
+ self.data() == other.data()
+ }
+}
+
+impl<'a> Dict<'a> {
+ /// Create a new empty dictionary.
+ pub fn empty() -> Self {
+ Self(Inner::Empty)
+ }
+
+ /// Get the raw bytes underlying to the dictionary.
+ pub fn data(&self) -> &'a [u8] {
+ match &self.0 {
+ Inner::Empty => &[],
+ Inner::Some(repr) => repr.data,
+ }
+ }
+
+ /// Returns the number of entries in the dictionary.
+ pub fn len(&self) -> usize {
+ self.offsets().map_or(0, FxHashMap::len)
+ }
+
+ /// Return whether the dictionary is empty.
+ pub fn is_empty(&self) -> bool {
+ self.offsets().is_none_or(FxHashMap::is_empty)
+ }
+
+ /// Checks whether the dictionary contains an entry with a specific key.
+ pub fn contains_key(&self, key: impl AsRef<[u8]>) -> bool {
+ self.offsets()
+ .is_some_and(|offsets| offsets.contains_key(key.as_ref()))
+ }
+
+ /// Returns the entry of a key as a specific object, or try to resolve it in case it's
+ /// an object reference.
+ #[allow(
+ private_bounds,
+ reason = "users shouldn't be able to implement `ObjectLike` for custom objects."
+ )]
+ pub fn get<T>(&self, key: impl AsRef<[u8]>) -> Option<T>
+ where
+ T: ObjectLike<'a>,
+ {
+ self.get_raw::<T>(key.as_ref())?.resolve(self.ctx())
+ }
+
+ /// Get the object reference linked to a key.
+ pub fn get_ref(&self, key: impl AsRef<[u8]>) -> Option<ObjRef> {
+ let offset = *self.offsets()?.get(key.as_ref())?;
+
+ Reader::new(&self.data()[offset..]).read_with_context::<ObjRef>(self.ctx())
+ }
+
+ /// Returns an iterator over all keys in the dictionary.
+ pub fn keys(&self) -> impl Iterator<Item = Name<'a>> + '_ {
+ self.offsets()
+ .into_iter()
+ .flat_map(|offsets| offsets.keys().cloned())
+ }
+
+ /// An iterator over all entries in the dictionary, sorted by key.
+ pub fn entries(&self) -> impl Iterator<Item = (Name<'a>, MaybeRef<Object<'a>>)> + '_ {
+ let mut sorted_keys = self.keys().collect::<Vec<_>>();
+ sorted_keys.sort_by(|n1, n2| n1.as_ref().cmp(n2.as_ref()));
+ sorted_keys.into_iter().map(|k| {
+ let obj = self.get_raw(k.deref()).unwrap();
+ (k, obj)
+ })
+ }
+
+ /// Return the object identifier of the dict, if it's an indirect object.
+ pub fn obj_id(&self) -> Option<ObjectIdentifier> {
+ self.ctx().obj_number()
+ }
+
+ /// Return the raw entry for a specific key.
+ #[allow(private_bounds)]
+ pub fn get_raw<T>(&self, key: impl AsRef<[u8]>) -> Option<MaybeRef<T>>
+ where
+ T: Readable<'a>,
+ {
+ let offset = *self.offsets()?.get(key.as_ref())?;
+
+ Reader::new(&self.data()[offset..]).read_with_context::<MaybeRef<T>>(self.ctx())
+ }
+
+ pub(crate) fn ctx(&self) -> &ReaderContext<'a> {
+ match &self.0 {
+ Inner::Empty => ReaderContext::dummy_ref(),
+ Inner::Some(repr) => &repr.ctx,
+ }
+ }
+
+ fn offsets(&self) -> Option<&FxHashMap<Name<'a>, usize>> {
+ match &self.0 {
+ Inner::Empty => None,
+ Inner::Some(repr) => Some(&repr.offsets),
+ }
+ }
+}
+
+impl Debug for Dict<'_> {
+ fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
+ let mut debug_struct = f.debug_struct("Dict");
+
+ if let Some(offsets) = self.offsets() {
+ let mut r = Reader::new(self.data());
+
+ for (key, val) in offsets {
+ r.jump(*val);
+ debug_struct.field(
+ &format!("{:?}", key.as_str()),
+ &r.read_with_context::<MaybeRef<Object<'_>>>(&ReaderContext::dummy())
+ .unwrap(),
+ );
+ }
+ }
+ Ok(())
+ }
+}
+
+impl Skippable for Dict<'_> {
+ fn skip(r: &mut Reader<'_>, is_content_stream: bool) -> Option<()> {
+ r.forward_tag(b"<<")?;
+
+ loop {
+ r.skip_white_spaces_and_comments();
+
+ if let Some(()) = r.forward_tag(b">>") {
+ break Some(());
+ } else {
+ let Some(_) = r.skip::<Name<'_>>(is_content_stream) else {
+ // In case there is garbage in-between, be lenient and just try to skip it.
+ r.skip::<Object<'_>>(is_content_stream)?;
+ continue;
+ };
+
+ r.skip_white_spaces_and_comments();
+
+ if is_content_stream {
+ r.skip::<Object<'_>>(is_content_stream)?;
+ } else {
+ r.skip::<MaybeRef<Object<'_>>>(is_content_stream)?;
+ }
+ }
+ }
+ }
+}
+
+impl<'a> Readable<'a> for Dict<'a> {
+ fn read(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<Self> {
+ read_inner(r, ctx, Some(b"<<"), b">>")
+ }
+}
+
+fn read_inner<'a>(
+ r: &mut Reader<'a>,
+ ctx: &ReaderContext<'a>,
+ start_tag: Option<&[u8]>,
+ end_tag: &[u8],
+) -> Option<Dict<'a>> {
+ // TODO: Figure out how to
+ // 1) Make dictionaries easily cloneable without wrapping in Arc.
+ // 2) Maybe have an efficient per-document allocator pool for hashmaps
+ // that can be reused.
+ #[cfg(feature = "std")]
+ let mut offsets = FxHashMap::with_capacity_and_hasher(8, rustc_hash::FxBuildHasher);
+ #[cfg(not(feature = "std"))]
+ let mut offsets = FxHashMap::new();
+
+ let data = parse_dict_with(
+ r,
+ ctx,
+ start_tag,
+ end_tag,
+ #[inline]
+ |name, offset, _| {
+ offsets.insert(name, offset);
+ Some(())
+ },
+ )?;
+
+ Some(Dict(Inner::Some(Arc::new(Repr {
+ data,
+ offsets,
+ ctx: ctx.clone(),
+ }))))
+}
+
+pub(crate) struct DictProbe<'a> {
+ pub(crate) data: &'a [u8],
+ pub(crate) has_root: bool,
+ pub(crate) has_type: bool,
+}
+
+// We use that method during fallback xref parsing, so that we can search for
+// the dictionaries we need without allocating the whole hash map.
+// If the above TODOs are ever resolved, we can probably remove this method.
+pub(crate) fn probe_dict<'a>(
+ r: &mut Reader<'a>,
+ ctx: &ReaderContext<'a>,
+ start_tag: Option<&[u8]>,
+ end_tag: &[u8],
+) -> Option<DictProbe<'a>> {
+ let mut has_root = false;
+ let mut has_type = false;
+
+ let data = parse_dict_with(
+ r,
+ ctx,
+ start_tag,
+ end_tag,
+ #[inline]
+ |name, _, _value_reader| {
+ if name.as_ref() == keys::ROOT {
+ has_root = true;
+ } else if name.as_ref() == keys::TYPE {
+ has_type = true;
+ }
+
+ Some(())
+ },
+ )?;
+
+ Some(DictProbe {
+ data,
+ has_root,
+ has_type,
+ })
+}
+
+fn parse_dict_with<'a, F>(
+ r: &mut Reader<'a>,
+ ctx: &ReaderContext<'a>,
+ start_tag: Option<&[u8]>,
+ end_tag: &[u8],
+ mut on_entry: F,
+) -> Option<&'a [u8]>
+where
+ F: FnMut(Name<'a>, usize, &Reader<'a>) -> Option<()>,
+{
+ let dict_data = r.tail()?;
+ let start_offset = r.offset();
+
+ // Inline image dictionaries don't start with '<<'.
+ if let Some(start_tag) = start_tag {
+ r.forward_tag(start_tag)?;
+ }
+
+ loop {
+ r.skip_white_spaces_and_comments();
+
+ // Normal dictionaries end with '>>', inline image dictionaries end with BD.
+ if let Some(()) = r.peek_tag(end_tag) {
+ r.forward_tag(end_tag)?;
+ let end_offset = r.offset() - start_offset;
+
+ break Some(&dict_data[..end_offset]);
+ } else {
+ let Some(name) = r.read_without_context::<Name<'_>>() else {
+ if start_tag.is_some() {
+ // In case there is garbage in-between, be lenient and just try to skip it.
+ // But only do this if we are parsing a proper dictionary as opposed to an
+ // inline dictionary.
+ r.read::<Object<'_>>(ctx)?;
+ continue;
+ } else {
+ return None;
+ }
+ };
+ r.skip_white_spaces_and_comments();
+
+ let offset = r.offset() - start_offset;
+ // Do note that we are including objects in our dictionary even if they
+ // are the null object, meaning that a call to `contains_key` will return `true`
+ // even if the object is the null object. The PDF reference in theory requires
+ // us to treat them as non-existing. Previously, we included a check to determine
+ // whether the object is `null` before inserting it, but that caused problems
+ // in some test cases where encryption + object streams are involved (as we would
+ // attempt to read an object stream before having resolved the encryption dictionary).
+ on_entry(name, offset, r)?;
+
+ if ctx.in_content_stream() {
+ r.skip::<Object<'_>>(ctx.in_content_stream())?;
+ } else {
+ r.skip::<MaybeRef<Object<'_>>>(ctx.in_content_stream())?;
+ }
+ }
+ }
+}
+
+object!(Dict<'a>, Dict);
+
+struct Repr<'a> {
+ data: &'a [u8],
+ offsets: FxHashMap<Name<'a>, usize>,
+ ctx: ReaderContext<'a>,
+}
+
+pub(crate) struct InlineImageDict<'a>(Dict<'a>);
+
+impl<'a> InlineImageDict<'a> {
+ pub(crate) fn get_dict(&self) -> &Dict<'a> {
+ &self.0
+ }
+}
+
+impl<'a> Readable<'a> for InlineImageDict<'a> {
+ fn read(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<Self> {
+ Some(Self(read_inner(r, ctx, None, b"ID")?))
+ }
+}
+
+/// A collection of possible keys in a PDF dictionary. Copied and adapted from `PDFBox`.
+#[allow(missing_docs)]
+pub mod keys {
+ macro_rules! key {
+ ($i:ident, $e:expr) => {
+ pub const $i: &'static [u8] = $e;
+ };
+ }
+
+ // A
+ key!(A, b"A");
+ key!(AA, b"AA");
+ key!(ABSOLUTE_COLORIMETRIC, b"AbsoluteColorimetric");
+ key!(AC, b"AC");
+ key!(ACRO_FORM, b"AcroForm");
+ key!(ACTUAL_TEXT, b"ActualText");
+ key!(ADBE, b"ADBE");
+ key!(ADBE_PKCS7_DETACHED, b"adbe.pkcs7.detached");
+ key!(ADBE_PKCS7_SHA1, b"adbe.pkcs7.sha1");
+ key!(ADBE_X509_RSA_SHA1, b"adbe.x509.rsa_sha1");
+ key!(ADOBE_PPKLITE, b"Adobe.PPKLite");
+ key!(AESV2, b"AESV2");
+ key!(AESV3, b"AESV3");
+ key!(AF, b"AF");
+ key!(AF_RELATIONSHIP, b"AFRelationship");
+ key!(AFTER, b"After");
+ key!(AI_META_DATA, b"AIMetaData");
+ key!(AIS, b"AIS");
+ key!(ALL_OFF, b"AllOff");
+ key!(ALL_ON, b"AllOn");
+ key!(ALT, b"Alt");
+ key!(ALPHA, b"Alpha");
+ key!(ALTERNATE, b"Alternate");
+ key!(ANNOT, b"Annot");
+ key!(ANNOTS, b"Annots");
+ key!(ANTI_ALIAS, b"AntiAlias");
+ key!(ANY_OFF, b"AnyOff");
+ key!(ANY_ON, b"AnyOn");
+ key!(AP, b"AP");
+ key!(AP_REF, b"APRef");
+ key!(APP, b"App");
+ key!(ART_BOX, b"ArtBox");
+ key!(ARTIFACT, b"Artifact");
+ key!(AS, b"AS");
+ key!(ASCENT, b"Ascent");
+ key!(ASCII_HEX_DECODE, b"ASCIIHexDecode");
+ key!(ASCII_HEX_DECODE_ABBREVIATION, b"AHx");
+ key!(ASCII85_DECODE, b"ASCII85Decode");
+ key!(ASCII85_DECODE_ABBREVIATION, b"A85");
+ key!(ATTACHED, b"Attached");
+ key!(AUTHOR, b"Author");
+ key!(AVG_WIDTH, b"AvgWidth");
+
+ // B
+ key!(B, b"B");
+ key!(BACKGROUND, b"Background");
+ key!(BASE_ENCODING, b"BaseEncoding");
+ key!(BASE_FONT, b"BaseFont");
+ key!(BASE_STATE, b"BaseState");
+ key!(BASE_VERSION, b"BaseVersion");
+ key!(BBOX, b"BBox");
+ key!(BC, b"BC");
+ key!(BE, b"BE");
+ key!(BEAD, b"BEAD");
+ key!(BEFORE, b"Before");
+ key!(BG, b"BG");
+ key!(BITS_PER_COMPONENT, b"BitsPerComponent");
+ key!(BITS_PER_COORDINATE, b"BitsPerCoordinate");
+ key!(BITS_PER_FLAG, b"BitsPerFlag");
+ key!(BITS_PER_SAMPLE, b"BitsPerSample");
+ key!(BL, b"Bl");
+ key!(BLACK_IS_1, b"BlackIs1");
+ key!(BLACK_POINT, b"BlackPoint");
+ key!(BLEED_BOX, b"BleedBox");
+ key!(BM, b"BM");
+ key!(BORDER, b"Border");
+ key!(BOUNDS, b"Bounds");
+ key!(BPC, b"BPC");
+ key!(BS, b"BS");
+ key!(BTN, b"Btn");
+ key!(BYTERANGE, b"ByteRange");
+
+ // C
+ key!(C, b"C");
+ key!(C0, b"C0");
+ key!(C1, b"C1");
+ key!(CA, b"CA");
+ key!(CA_NS, b"ca");
+ key!(CALGRAY, b"CalGray");
+ key!(CALRGB, b"CalRGB");
+ key!(CALCMYK, b"CalCMYK");
+ key!(CAP, b"Cap");
+ key!(CAP_HEIGHT, b"CapHeight");
+ key!(CATALOG, b"Catalog");
+ key!(CCITTFAX_DECODE, b"CCITTFaxDecode");
+ key!(CCITTFAX_DECODE_ABBREVIATION, b"CCF");
+ key!(CENTER_WINDOW, b"CenterWindow");
+ key!(CERT, b"Cert");
+ key!(CERTS, b"Certs");
+ key!(CF, b"CF");
+ key!(CFM, b"CFM");
+ key!(CH, b"Ch");
+ key!(CHAR_PROCS, b"CharProcs");
+ key!(CHAR_SET, b"CharSet");
+ key!(CHECK_SUM, b"CheckSum");
+ key!(CI, b"CI");
+ key!(CICI_SIGNIT, b"CICI.SignIt");
+ key!(CID_FONT_TYPE0, b"CIDFontType0");
+ key!(CID_FONT_TYPE0C, b"CIDFontType0C");
+ key!(CID_FONT_TYPE2, b"CIDFontType2");
+ key!(CID_TO_GID_MAP, b"CIDToGIDMap");
+ key!(CID_SET, b"CIDSet");
+ key!(CIDSYSTEMINFO, b"CIDSystemInfo");
+ key!(CL, b"CL");
+ key!(CLASS_MAP, b"ClassMap");
+ key!(CLR_F, b"ClrF");
+ key!(CLR_FF, b"ClrFf");
+ key!(CMAP, b"CMap");
+ key!(CMAPNAME, b"CMapName");
+ key!(CMYK, b"CMYK");
+ key!(CO, b"CO");
+ key!(COLOR, b"Color");
+ key!(COLLECTION, b"Collection");
+ key!(COLLECTION_ITEM, b"CollectionItem");
+ key!(COLLECTION_FIELD, b"CollectionField");
+ key!(COLLECTION_SCHEMA, b"CollectionSchema");
+ key!(COLLECTION_SORT, b"CollectionSort");
+ key!(COLLECTION_SUBITEM, b"CollectionSubitem");
+ key!(COLOR_BURN, b"ColorBurn");
+ key!(COLOR_DODGE, b"ColorDodge");
+ key!(COLORANTS, b"Colorants");
+ key!(COLORS, b"Colors");
+ key!(COLORSPACE, b"ColorSpace");
+ key!(COLOR_TRANSFORM, b"ColorTransform");
+ key!(COLUMNS, b"Columns");
+ key!(COMPATIBLE, b"Compatible");
+ key!(COMPONENTS, b"Components");
+ key!(CONTACT_INFO, b"ContactInfo");
+ key!(CONTENTS, b"Contents");
+ key!(COORDS, b"Coords");
+ key!(COUNT, b"Count");
+ key!(CP, b"CP");
+ key!(CREATION_DATE, b"CreationDate");
+ key!(CREATOR, b"Creator");
+ key!(CRL, b"CRL");
+ key!(CRLS, b"CRLS");
+ key!(CROP_BOX, b"CropBox");
+ key!(CRYPT, b"Crypt");
+ key!(CS, b"CS");
+ key!(CYX, b"CYX");
+
+ // D
+ key!(D, b"D");
+ key!(DA, b"DA");
+ key!(DARKEN, b"Darken");
+ key!(DATE, b"Date");
+ key!(DCT_DECODE, b"DCTDecode");
+ key!(DCT_DECODE_ABBREVIATION, b"DCT");
+ key!(DECODE, b"Decode");
+ key!(DECODE_PARMS, b"DecodeParms");
+ key!(DEFAULT, b"default");
+ key!(DEFAULT_CMYK, b"DefaultCMYK");
+ key!(DEFAULT_CRYPT_FILTER, b"DefaultCryptFilter");
+ key!(DEFAULT_GRAY, b"DefaultGray");
+ key!(DEFAULT_RGB, b"DefaultRGB");
+ key!(DESC, b"Desc");
+ key!(DESCENDANT_FONTS, b"DescendantFonts");
+ key!(DESCENT, b"Descent");
+ key!(DEST, b"Dest");
+ key!(DEST_OUTPUT_PROFILE, b"DestOutputProfile");
+ key!(DESTS, b"Dests");
+ key!(DEVICE_CMYK, b"DeviceCMYK");
+ key!(DEVICE_GRAY, b"DeviceGray");
+ key!(DEVICE_N, b"DeviceN");
+ key!(DEVICE_RGB, b"DeviceRGB");
+ key!(DI, b"Di");
+ key!(DIFFERENCE, b"Difference");
+ key!(DIFFERENCES, b"Differences");
+ key!(DIGEST_METHOD, b"DigestMethod");
+ key!(DIGEST_RIPEMD160, b"RIPEMD160");
+ key!(DIGEST_SHA1, b"SHA1");
+ key!(DIGEST_SHA256, b"SHA256");
+ key!(DIGEST_SHA384, b"SHA384");
+ key!(DIGEST_SHA512, b"SHA512");
+ key!(DIRECTION, b"Direction");
+ key!(DISPLAY_DOC_TITLE, b"DisplayDocTitle");
+ key!(DL, b"DL");
+ key!(DM, b"Dm");
+ key!(DOC, b"Doc");
+ key!(DOC_CHECKSUM, b"DocChecksum");
+ key!(DOC_TIME_STAMP, b"DocTimeStamp");
+ key!(DOCMDP, b"DocMDP");
+ key!(DOCUMENT, b"Document");
+ key!(DOMAIN, b"Domain");
+ key!(DOS, b"DOS");
+ key!(DP, b"DP");
+ key!(DR, b"DR");
+ key!(DS, b"DS");
+ key!(DSS, b"DSS");
+ key!(DUPLEX, b"Duplex");
+ key!(DUR, b"Dur");
+ key!(DV, b"DV");
+ key!(DW, b"DW");
+ key!(DW2, b"DW2");
+
+ // E
+ key!(E, b"E");
+ key!(EARLY_CHANGE, b"EarlyChange");
+ key!(EF, b"EF");
+ key!(EMBEDDED_FDFS, b"EmbeddedFDFs");
+ key!(EMBEDDED_FILE, b"EmbeddedFile");
+ key!(EMBEDDED_FILES, b"EmbeddedFiles");
+ key!(EMPTY, b"");
+ key!(ENCODE, b"Encode");
+ key!(ENCODED_BYTE_ALIGN, b"EncodedByteAlign");
+ key!(ENCODING, b"Encoding");
+ key!(ENCODING_90MS_RKSJ_H, b"90ms-RKSJ-H");
+ key!(ENCODING_90MS_RKSJ_V, b"90ms-RKSJ-V");
+ key!(ENCODING_ETEN_B5_H, b"ETen-B5-H");
+ key!(ENCODING_ETEN_B5_V, b"ETen-B5-V");
+ key!(ENCRYPT, b"Encrypt");
+ key!(ENCRYPT_META_DATA, b"EncryptMetadata");
+ key!(ENCRYPTED_PAYLOAD, b"EncryptedPayload");
+ key!(END_OF_BLOCK, b"EndOfBlock");
+ key!(END_OF_LINE, b"EndOfLine");
+ key!(ENTRUST_PPKEF, b"Entrust.PPKEF");
+ key!(EXCLUSION, b"Exclusion");
+ key!(EXTENSIONS, b"Extensions");
+ key!(EXTENSION_LEVEL, b"ExtensionLevel");
+ key!(EX_DATA, b"ExData");
+ key!(EXPORT, b"Export");
+ key!(EXPORT_STATE, b"ExportState");
+ key!(EXT_G_STATE, b"ExtGState");
+ key!(EXTEND, b"Extend");
+ key!(EXTENDS, b"Extends");
+
+ // F
+ key!(F, b"F");
+ key!(F_DECODE_PARMS, b"FDecodeParms");
+ key!(F_FILTER, b"FFilter");
+ key!(FB, b"FB");
+ key!(FDF, b"FDF");
+ key!(FF, b"Ff");
+ key!(FIELDS, b"Fields");
+ key!(FILESPEC, b"Filespec");
+ key!(FILTER, b"Filter");
+ key!(FIRST, b"First");
+ key!(FIRST_CHAR, b"FirstChar");
+ key!(FIT_WINDOW, b"FitWindow");
+ key!(FL, b"FL");
+ key!(FLAGS, b"Flags");
+ key!(FLATE_DECODE, b"FlateDecode");
+ key!(FLATE_DECODE_ABBREVIATION, b"Fl");
+ key!(FO, b"Fo");
+ key!(FOLDERS, b"Folders");
+ key!(FONT, b"Font");
+ key!(FONT_BBOX, b"FontBBox");
+ key!(FONT_DESC, b"FontDescriptor");
+ key!(FONT_FAMILY, b"FontFamily");
+ key!(FONT_FILE, b"FontFile");
+ key!(FONT_FILE2, b"FontFile2");
+ key!(FONT_FILE3, b"FontFile3");
+ key!(FONT_MATRIX, b"FontMatrix");
+ key!(FONT_NAME, b"FontName");
+ key!(FONT_STRETCH, b"FontStretch");
+ key!(FONT_WEIGHT, b"FontWeight");
+ key!(FORM, b"Form");
+ key!(FORMTYPE, b"FormType");
+ key!(FRM, b"FRM");
+ key!(FS, b"FS");
+ key!(FT, b"FT");
+ key!(FUNCTION, b"Function");
+ key!(FUNCTION_TYPE, b"FunctionType");
+ key!(FUNCTIONS, b"Functions");
+
+ // G
+ key!(G, b"G");
+ key!(GAMMA, b"Gamma");
+ key!(GROUP, b"Group");
+ key!(GTS_PDFA1, b"GTS_PDFA1");
+
+ // H
+ key!(H, b"H");
+ key!(HARD_LIGHT, b"HardLight");
+ key!(HEIGHT, b"Height");
+ key!(HELV, b"Helv");
+ key!(HIDE_MENUBAR, b"HideMenubar");
+ key!(HIDE_TOOLBAR, b"HideToolbar");
+ key!(HIDE_WINDOWUI, b"HideWindowUI");
+ key!(HUE, b"Hue");
+
+ // I
+ key!(I, b"I");
+ key!(IC, b"IC");
+ key!(ICC_BASED, b"ICCBased");
+ key!(ID, b"ID");
+ key!(ID_TREE, b"IDTree");
+ key!(IDENTITY, b"Identity");
+ key!(IDENTITY_H, b"Identity-H");
+ key!(IDENTITY_V, b"Identity-V");
+ key!(IF, b"IF");
+ key!(ILLUSTRATOR, b"Illustrator");
+ key!(IM, b"IM");
+ key!(IMAGE, b"Image");
+ key!(IMAGE_MASK, b"ImageMask");
+ key!(INDEX, b"Index");
+ key!(INDEXED, b"Indexed");
+ key!(INFO, b"Info");
+ key!(INKLIST, b"InkList");
+ key!(INTENT, b"Intent");
+ key!(INTERPOLATE, b"Interpolate");
+ key!(IRT, b"IRT");
+ key!(IT, b"IT");
+ key!(ITALIC_ANGLE, b"ItalicAngle");
+ key!(ISSUER, b"Issuer");
+ key!(IX, b"IX");
+
+ // J
+ key!(JAVA_SCRIPT, b"JavaScript");
+ key!(JBIG2_DECODE, b"JBIG2Decode");
+ key!(JBIG2_GLOBALS, b"JBIG2Globals");
+ key!(JPX_DECODE, b"JPXDecode");
+ key!(JS, b"JS");
+
+ // K
+ key!(K, b"K");
+ key!(KEYWORDS, b"Keywords");
+ key!(KEY_USAGE, b"KeyUsage");
+ key!(KIDS, b"Kids");
+
+ // L
+ key!(L, b"L");
+ key!(LAB, b"Lab");
+ key!(LANG, b"Lang");
+ key!(LAST, b"Last");
+ key!(LAST_CHAR, b"LastChar");
+ key!(LAST_MODIFIED, b"LastModified");
+ key!(LC, b"LC");
+ key!(LE, b"LE");
+ key!(LEADING, b"Leading");
+ key!(LEGAL_ATTESTATION, b"LegalAttestation");
+ key!(LENGTH, b"Length");
+ key!(LENGTH1, b"Length1");
+ key!(LENGTH2, b"Length2");
+ key!(LENGTH3, b"Length3");
+ key!(LIGHTEN, b"Lighten");
+ key!(LIMITS, b"Limits");
+ key!(LINEARIZED, b"Linearized");
+ key!(LJ, b"LJ");
+ key!(LL, b"LL");
+ key!(LLE, b"LLE");
+ key!(LLO, b"LLO");
+ key!(LOCATION, b"Location");
+ key!(LUMINOSITY, b"Luminosity");
+ key!(LW, b"LW");
+ key!(LZW_DECODE, b"LZWDecode");
+ key!(LZW_DECODE_ABBREVIATION, b"LZW");
+
+ // M
+ key!(M, b"M");
+ key!(MAC, b"Mac");
+ key!(MAC_EXPERT_ENCODING, b"MacExpertEncoding");
+ key!(MAC_ROMAN_ENCODING, b"MacRomanEncoding");
+ key!(MARK_INFO, b"MarkInfo");
+ key!(MASK, b"Mask");
+ key!(MATRIX, b"Matrix");
+ key!(MATTE, b"Matte");
+ key!(MAX_LEN, b"MaxLen");
+ key!(MAX_WIDTH, b"MaxWidth");
+ key!(MCID, b"MCID");
+ key!(MDP, b"MDP");
+ key!(MEDIA_BOX, b"MediaBox");
+ key!(MEASURE, b"Measure");
+ key!(METADATA, b"Metadata");
+ key!(MISSING_WIDTH, b"MissingWidth");
+ key!(MIX, b"Mix");
+ key!(MK, b"MK");
+ key!(ML, b"ML");
+ key!(MM_TYPE1, b"MMType1");
+ key!(MOD_DATE, b"ModDate");
+ key!(MULTIPLY, b"Multiply");
+
+ // N
+ key!(N, b"N");
+ key!(NAME, b"Name");
+ key!(NAMES, b"Names");
+ key!(NAVIGATOR, b"Navigator");
+ key!(NEED_APPEARANCES, b"NeedAppearances");
+ key!(NEW_WINDOW, b"NewWindow");
+ key!(NEXT, b"Next");
+ key!(NM, b"NM");
+ key!(NON_EFONT_NO_WARN, b"NonEFontNoWarn");
+ key!(NON_FULL_SCREEN_PAGE_MODE, b"NonFullScreenPageMode");
+ key!(NONE, b"None");
+ key!(NORMAL, b"Normal");
+ key!(NUMS, b"Nums");
+
+ // O
+ key!(O, b"O");
+ key!(OBJ, b"Obj");
+ key!(OBJR, b"OBJR");
+ key!(OBJ_STM, b"ObjStm");
+ key!(OC, b"OC");
+ key!(OCG, b"OCG");
+ key!(OCGS, b"OCGs");
+ key!(OCMD, b"OCMD");
+ key!(OCPROPERTIES, b"OCProperties");
+ key!(OCSP, b"OCSP");
+ key!(OCSPS, b"OCSPs");
+ key!(OE, b"OE");
+ key!(OID, b"OID");
+ key!(OFF, b"OFF");
+ key!(ON, b"ON");
+ key!(OP, b"OP");
+ key!(OP_NS, b"op");
+ key!(OPEN_ACTION, b"OpenAction");
+ key!(OPEN_TYPE, b"OpenType");
+ key!(OPI, b"OPI");
+ key!(OPM, b"OPM");
+ key!(OPT, b"Opt");
+ key!(ORDER, b"Order");
+ key!(ORDERING, b"Ordering");
+ key!(OS, b"OS");
+ key!(OUTLINES, b"Outlines");
+ key!(OUTPUT_CONDITION, b"OutputCondition");
+ key!(OUTPUT_CONDITION_IDENTIFIER, b"OutputConditionIdentifier");
+ key!(OUTPUT_INTENT, b"OutputIntent");
+ key!(OUTPUT_INTENTS, b"OutputIntents");
+ key!(OVERLAY, b"Overlay");
+
+ // P
+ key!(P, b"P");
+ key!(PA, b"PA");
+ key!(PAGE, b"Page");
+ key!(PAGE_LABELS, b"PageLabels");
+ key!(PAGE_LAYOUT, b"PageLayout");
+ key!(PAGE_MODE, b"PageMode");
+ key!(PAGES, b"Pages");
+ key!(PAINT_TYPE, b"PaintType");
+ key!(PANOSE, b"Panose");
+ key!(PARAMS, b"Params");
+ key!(PARENT, b"Parent");
+ key!(PARENT_TREE, b"ParentTree");
+ key!(PARENT_TREE_NEXT_KEY, b"ParentTreeNextKey");
+ key!(PART, b"Part");
+ key!(PATH, b"Path");
+ key!(PATTERN, b"Pattern");
+ key!(PATTERN_TYPE, b"PatternType");
+ key!(PC, b"PC");
+ key!(PDF_DOC_ENCODING, b"PDFDocEncoding");
+ key!(PERMS, b"Perms");
+ key!(PERCEPTUAL, b"Perceptual");
+ key!(PIECE_INFO, b"PieceInfo");
+ key!(PG, b"Pg");
+ key!(PI, b"PI");
+ key!(PO, b"PO");
+ key!(POPUP, b"Popup");
+ key!(PRE_RELEASE, b"PreRelease");
+ key!(PREDICTOR, b"Predictor");
+ key!(PREV, b"Prev");
+ key!(PRINT, b"Print");
+ key!(PRINT_AREA, b"PrintArea");
+ key!(PRINT_CLIP, b"PrintClip");
+ key!(PRINT_SCALING, b"PrintScaling");
+ key!(PRINT_STATE, b"PrintState");
+ key!(PRIVATE, b"Private");
+ key!(PROC_SET, b"ProcSet");
+ key!(PROCESS, b"Process");
+ key!(PRODUCER, b"Producer");
+ key!(PROP_BUILD, b"Prop_Build");
+ key!(PROPERTIES, b"Properties");
+ key!(PS, b"PS");
+ key!(PT_DATA, b"PtData");
+ key!(PUB_SEC, b"PubSec");
+ key!(PV, b"PV");
+
+ // Q
+ key!(Q, b"Q");
+ key!(QUADPOINTS, b"QuadPoints");
+
+ // R
+ key!(R, b"R");
+ key!(RANGE, b"Range");
+ key!(RC, b"RC");
+ key!(RD, b"RD");
+ key!(REASON, b"Reason");
+ key!(REASONS, b"Reasons");
+ key!(RECIPIENTS, b"Recipients");
+ key!(RECT, b"Rect");
+ key!(REF, b"Ref");
+ key!(REFERENCE, b"Reference");
+ key!(REGISTRY, b"Registry");
+ key!(REGISTRY_NAME, b"RegistryName");
+ key!(RELATIVE_COLORIMETRIC, b"RelativeColorimetric");
+ key!(RENAME, b"Rename");
+ key!(REPEAT, b"Repeat");
+ key!(RES_FORK, b"ResFork");
+ key!(RESOURCES, b"Resources");
+ key!(RGB, b"RGB");
+ key!(RI, b"RI");
+ key!(ROLE_MAP, b"RoleMap");
+ key!(ROOT, b"Root");
+ key!(ROTATE, b"Rotate");
+ key!(ROWS, b"Rows");
+ key!(RT, b"RT");
+ key!(RUN_LENGTH_DECODE, b"RunLengthDecode");
+ key!(RUN_LENGTH_DECODE_ABBREVIATION, b"RL");
+ key!(RV, b"RV");
+
+ // S
+ key!(S, b"S");
+ key!(SA, b"SA");
+ key!(SATURATION, b"Saturation");
+ key!(SCHEMA, b"Schema");
+ key!(SCREEN, b"Screen");
+ key!(SE, b"SE");
+ key!(SEPARATION, b"Separation");
+ key!(SET_F, b"SetF");
+ key!(SET_FF, b"SetFf");
+ key!(SHADING, b"Shading");
+ key!(SHADING_TYPE, b"ShadingType");
+ key!(SIG, b"Sig");
+ key!(SIG_FLAGS, b"SigFlags");
+ key!(SIG_REF, b"SigRef");
+ key!(SIZE, b"Size");
+ key!(SM, b"SM");
+ key!(SMASK, b"SMask");
+ key!(SMASK_IN_DATA, b"SMaskInData");
+ key!(SOFT_LIGHT, b"SoftLight");
+ key!(SORT, b"Sort");
+ key!(SOUND, b"Sound");
+ key!(SPLIT, b"Split");
+ key!(SS, b"SS");
+ key!(ST, b"St");
+ key!(STANDARD_ENCODING, b"StandardEncoding");
+ key!(STATE, b"State");
+ key!(STATE_MODEL, b"StateModel");
+ key!(STATUS, b"Status");
+ key!(STD_CF, b"StdCF");
+ key!(STEM_H, b"StemH");
+ key!(STEM_V, b"StemV");
+ key!(STM_F, b"StmF");
+ key!(STR_F, b"StrF");
+ key!(STRUCT_ELEM, b"StructElem");
+ key!(STRUCT_PARENT, b"StructParent");
+ key!(STRUCT_PARENTS, b"StructParents");
+ key!(STRUCT_TREE_ROOT, b"StructTreeRoot");
+ key!(STYLE, b"Style");
+ key!(SUB_FILTER, b"SubFilter");
+ key!(SUBJ, b"Subj");
+ key!(SUBJECT, b"Subject");
+ key!(SUBJECT_DN, b"SubjectDN");
+ key!(SUBTYPE, b"Subtype");
+ key!(SUPPLEMENT, b"Supplement");
+ key!(SV, b"SV");
+ key!(SV_CERT, b"SVCert");
+ key!(SW, b"SW");
+ key!(SY, b"Sy");
+ key!(SYNCHRONOUS, b"Synchronous");
+ key!(T, b"T");
+ key!(TARGET, b"Target");
+ key!(TEMPLATES, b"Templates");
+ key!(THREAD, b"Thread");
+ key!(THREADS, b"Threads");
+ key!(THREE_DD, b"3DD");
+ key!(THUMB, b"Thumb");
+ key!(TI, b"TI");
+ key!(TILING_TYPE, b"TilingType");
+ key!(TIME_STAMP, b"TimeStamp");
+ key!(TITLE, b"Title");
+ key!(TK, b"TK");
+ key!(TM, b"TM");
+ key!(TO_UNICODE, b"ToUnicode");
+ key!(TR, b"TR");
+ key!(TR2, b"TR2");
+ key!(TRAPPED, b"Trapped");
+ key!(TRANS, b"Trans");
+ key!(TRANSFORM_METHOD, b"TransformMethod");
+ key!(TRANSFORM_PARAMS, b"TransformParams");
+ key!(TRANSPARENCY, b"Transparency");
+ key!(TREF, b"TRef");
+ key!(TRIM_BOX, b"TrimBox");
+ key!(TRUE_TYPE, b"TrueType");
+ key!(TRUSTED_MODE, b"TrustedMode");
+ key!(TU, b"TU");
+ key!(TX, b"Tx");
+ key!(TYPE, b"Type");
+ key!(TYPE0, b"Type0");
+ key!(TYPE1, b"Type1");
+ key!(TYPE1C, b"Type1C");
+ key!(TYPE3, b"Type3");
+
+ // U
+ key!(U, b"U");
+ key!(UE, b"UE");
+ key!(UF, b"UF");
+ key!(UNCHANGED, b"Unchanged");
+ key!(UNIX, b"Unix");
+ key!(URI, b"URI");
+ key!(URL, b"URL");
+ key!(URL_TYPE, b"URLType");
+ key!(USAGE, b"Usage");
+ key!(USE_CMAP, b"UseCMap");
+ key!(USER_UNIT, b"UserUnit");
+
+ // V
+ key!(V, b"V");
+ key!(VE, b"VE");
+ key!(VERISIGN_PPKVS, b"VeriSign.PPKVS");
+ key!(VERSION, b"Version");
+ key!(VERTICES, b"Vertices");
+ key!(VERTICES_PER_ROW, b"VerticesPerRow");
+ key!(VIEW, b"View");
+ key!(VIEW_AREA, b"ViewArea");
+ key!(VIEW_CLIP, b"ViewClip");
+ key!(VIEW_STATE, b"ViewState");
+ key!(VIEWER_PREFERENCES, b"ViewerPreferences");
+ key!(VOLUME, b"Volume");
+ key!(VP, b"VP");
+ key!(VRI, b"VRI");
+
+ // W
+ key!(W, b"W");
+ key!(W2, b"W2");
+ key!(WC, b"WC");
+ key!(WHITE_POINT, b"WhitePoint");
+ key!(WIDGET, b"Widget");
+ key!(WIDTH, b"Width");
+ key!(WIDTHS, b"Widths");
+ key!(WIN, b"Win");
+ key!(WIN_ANSI_ENCODING, b"WinAnsiEncoding");
+ key!(WMODE, b"WMode");
+ key!(WP, b"WP");
+ key!(WS, b"WS");
+
+ // X
+ key!(X, b"X");
+ key!(XFA, b"XFA");
+ key!(X_STEP, b"XStep");
+ key!(XHEIGHT, b"XHeight");
+ key!(XOBJECT, b"XObject");
+ key!(XREF, b"XRef");
+ key!(XREF_STM, b"XRefStm");
+
+ // Y
+ key!(Y, b"Y");
+ key!(Y_STEP, b"YStep");
+ key!(YES, b"Yes");
+
+ // Z
+ key!(ZA_DB, b"ZaDb");
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::object::Number;
+ use crate::object::dict::keys::{COLORSPACE, EXT_G_STATE, FONT, PROC_SET};
+ use crate::object::dict::{Dict, InlineImageDict};
+ use crate::object::string;
+ use crate::object::{Name, ObjRef};
+ use crate::reader::Reader;
+ use crate::reader::{ReaderContext, ReaderExt};
+
+ fn dict_impl(data: &[u8]) -> Option<Dict<'_>> {
+ Reader::new(data).read_with_context::<Dict<'_>>(&ReaderContext::dummy())
+ }
+
+ #[test]
+ fn empty_dict_1() {
+ let dict_data = b"<<>>";
+ let dict = dict_impl(dict_data).unwrap();
+
+ assert_eq!(dict.len(), 0);
+ }
+
+ #[test]
+ fn empty_dict_2() {
+ let dict_data = b"<< \n >>";
+ let dict = dict_impl(dict_data).unwrap();
+
+ assert_eq!(dict.len(), 0);
+ }
+
+ #[test]
+ fn dict_1() {
+ let dict_data = b"<< /Hi 34.0 >>";
+ let dict = dict_impl(dict_data).unwrap();
+
+ assert_eq!(dict.len(), 1);
+ assert!(dict.get::<Number>(Name::new_unescaped(b"Hi")).is_some());
+ }
+
+ #[test]
+ fn dict_2() {
+ let dict_data = b"<< /Hi \n 34.0 /Second true >>";
+ let dict = dict_impl(dict_data).unwrap();
+
+ assert_eq!(dict.len(), 2);
+ assert!(dict.get::<Number>(Name::new_unescaped(b"Hi")).is_some());
+ assert!(dict.get::<bool>(Name::new_unescaped(b"Second")).is_some());
+ }
+
+ #[test]
+ fn dict_complex() {
+ let data = "<< /Type /Example
+/Subtype /DictionaryExample
+/Version 0.01
+/IntegerItem 12
+/StringItem ( a string )
+/Subdictionary << /Item1 0.4
+ /Item2 true
+ /LastItem ( not ! )
+ /VeryLastItem ( OK )
+ >>
+>>";
+
+ let dict = Reader::new(data.as_bytes())
+ .read_with_context::<Dict<'_>>(&ReaderContext::dummy())
+ .unwrap();
+ assert_eq!(dict.len(), 6);
+ assert!(dict.get::<Name<'_>>(Name::new_unescaped(b"Type")).is_some());
+ assert!(
+ dict.get::<Name<'_>>(Name::new_unescaped(b"Subtype"))
+ .is_some()
+ );
+ assert!(
+ dict.get::<Number>(Name::new_unescaped(b"Version"))
+ .is_some()
+ );
+ assert!(
+ dict.get::<i32>(Name::new_unescaped(b"IntegerItem"))
+ .is_some()
+ );
+ assert!(
+ dict.get::<string::String<'_>>(Name::new_unescaped(b"StringItem"))
+ .is_some()
+ );
+ assert!(
+ dict.get::<Dict<'_>>(Name::new_unescaped(b"Subdictionary"))
+ .is_some()
+ );
+ }
+
+ #[test]
+ fn dict_with_trailing() {
+ let dict_data = b"<< /Hi 67.0 >>trailing data";
+ let dict = dict_impl(dict_data).unwrap();
+
+ assert_eq!(dict.len(), 1);
+ }
+
+ #[test]
+ fn dict_with_comment() {
+ let dict_data = b"<< /Hi % A comment \n 67.0 % Another comment \n >>";
+ let dict = dict_impl(dict_data).unwrap();
+
+ assert_eq!(dict.len(), 1);
+ }
+
+ #[test]
+ fn inline_dict() {
+ let dict_data = b"/W 17 /H 17 /CS /RGB /BPC 8 /F [ /A85 /LZW ] ID ";
+
+ let dict = Reader::new(&dict_data[..])
+ .read_with_context::<InlineImageDict<'_>>(&ReaderContext::dummy())
+ .unwrap();
+
+ assert_eq!(dict.get_dict().len(), 5);
+ }
+
+ #[test]
+ fn dict_with_escaped_name() {
+ let dict_data = b"<< /PANTONE#20104#20C 234 >>";
+ let dict = dict_impl(dict_data).unwrap();
+
+ assert!(dict.contains_key("PANTONE 104 C"));
+ }
+
+ #[test]
+ fn garbage_in_between() {
+ let dict_data = b"<<
+/ProcSet [ /PDF /Text ]
+/Font << /F4 31 0 R /F6 23 0 R >>
+/ExtGState << /GS2 14 0 R
+2000
+ /GS3 15 0 R >>
+/ColorSpace << /Cs5 13 0 R >>
+>> ";
+ let dict = dict_impl(dict_data).unwrap();
+
+ assert!(dict.contains_key(PROC_SET));
+ assert!(dict.contains_key(FONT));
+ assert!(dict.contains_key(EXT_G_STATE));
+ assert!(dict.contains_key(COLORSPACE));
+
+ let Some(dict) = dict.get::<Dict<'_>>(EXT_G_STATE) else {
+ panic!("failed to parse ext g state");
+ };
+
+ assert_eq!(dict.get_ref("GS2"), Some(ObjRef::new(14, 0)));
+ assert_eq!(dict.get_ref("GS3"), Some(ObjRef::new(15, 0)));
+ }
+}
diff --git a/vendor/hayro-syntax/src/object/indirect.rs b/vendor/hayro-syntax/src/object/indirect.rs
new file mode 100644
index 000000000..cd0e6ff7a
--- /dev/null
+++ b/vendor/hayro-syntax/src/object/indirect.rs
@@ -0,0 +1,61 @@
+use crate::object::{ObjectIdentifier, ObjectLike};
+use crate::reader::Reader;
+use crate::reader::{Readable, ReaderContext, ReaderExt, Skippable};
+
+#[derive(Debug, Clone)]
+pub(crate) struct IndirectObject<T> {
+ id: ObjectIdentifier,
+ inner: T,
+}
+
+impl<T> IndirectObject<T> {
+ pub(crate) fn get(self) -> T {
+ self.inner
+ }
+
+ pub(crate) fn id(&self) -> &ObjectIdentifier {
+ &self.id
+ }
+}
+
+impl<'a, T> Readable<'a> for IndirectObject<T>
+where
+ T: ObjectLike<'a>,
+{
+ fn read(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<Self> {
+ let mut ctx = ctx.clone();
+ let id = r.read_without_context::<ObjectIdentifier>()?;
+
+ if ctx.parent_chain_contains(&id) {
+ warn!("cycle detected in indirect object: {id:?}");
+
+ return None;
+ }
+
+ ctx.set_obj_number(id);
+ ctx.parent_chain_push(id);
+ r.skip_white_spaces_and_comments();
+ let inner = r.read_with_context::<T>(&ctx)?;
+ r.skip_white_spaces_and_comments();
+ // We are lenient and don't require it.
+ r.forward_tag(b"endobj");
+
+ Some(Self { id, inner })
+ }
+}
+
+impl<T> Skippable for IndirectObject<T>
+where
+ T: Skippable,
+{
+ fn skip(r: &mut Reader<'_>, _: bool) -> Option<()> {
+ r.skip::<ObjectIdentifier>(false)?;
+ r.skip_white_spaces_and_comments();
+ r.skip::<T>(false)?;
+ r.skip_white_spaces_and_comments();
+ // We are lenient and don't require it.
+ r.forward_tag(b"endobj");
+
+ Some(())
+ }
+}
diff --git a/vendor/hayro-syntax/src/object/mod.rs b/vendor/hayro-syntax/src/object/mod.rs
new file mode 100644
index 000000000..d9b4816de
--- /dev/null
+++ b/vendor/hayro-syntax/src/object/mod.rs
@@ -0,0 +1,395 @@
+//! Parsing and reading from PDF objects.
+
+pub use crate::object::array::Array;
+pub use crate::object::date::DateTime;
+pub use crate::object::dict::Dict;
+pub use crate::object::name::Name;
+use crate::object::name::skip_name_like;
+pub use crate::object::null::Null;
+pub use crate::object::number::Number;
+pub use crate::object::rect::Rect;
+pub use crate::object::r#ref::{MaybeRef, ObjRef};
+pub use crate::object::stream::Stream;
+pub use crate::object::string::String;
+use crate::reader::Reader;
+use crate::reader::{Readable, ReaderContext, ReaderExt, Skippable};
+use core::fmt::Debug;
+
+mod bool;
+mod date;
+mod null;
+mod number;
+mod rect;
+mod r#ref;
+mod string;
+mod tuple;
+
+pub(crate) mod indirect;
+pub(crate) mod name;
+
+pub mod array;
+pub mod dict;
+pub mod stream;
+
+/// A trait for PDF objects.
+pub(crate) trait ObjectLike<'a>: TryFrom<Object<'a>> + Readable<'a> + Debug + Clone {}
+
+/// A trait for PDF objects that can be borrowed directly from an [`Object`].
+pub(crate) trait ObjectRefLike<'a>: Sized {
+ fn cast_ref<'b>(obj: &'b Object<'a>) -> Option<&'b Self>;
+}
+
+/// A primitive PDF object.
+#[derive(Debug, Clone, PartialEq)]
+pub enum Object<'a> {
+ /// A null object.
+ Null(Null),
+ /// A boolean object.
+ Boolean(bool),
+ /// A number object.
+ Number(Number),
+ /// A string object.
+ String(String<'a>),
+ /// A name object.
+ Name(Name<'a>),
+ /// A dict object.
+ Dict(Dict<'a>),
+ /// An array object.
+ Array(Array<'a>),
+ /// A stream object.
+ // Can only be an indirect object in theory and thus comes with some caveats,
+ // but we just treat it the same.
+ Stream(Stream<'a>),
+}
+
+impl<'a> Object<'a> {
+ /// Try casting the object to a specific subtype.
+ pub(crate) fn cast<T>(self) -> Option<T>
+ where
+ T: ObjectLike<'a>,
+ {
+ self.try_into().ok()
+ }
+
+ /// Try casting the object to a reference of the specific type.
+ pub(crate) fn cast_ref<T>(&self) -> Option<&T>
+ where
+ T: ObjectRefLike<'a>,
+ {
+ T::cast_ref(self)
+ }
+
+ /// Try casting the object to a dict.
+ #[inline(always)]
+ pub fn into_dict(self) -> Option<Dict<'a>> {
+ self.cast()
+ }
+
+ /// Try casting the object to a name.
+ #[inline(always)]
+ pub fn into_name(self) -> Option<Name<'a>> {
+ self.cast()
+ }
+
+ /// Try casting the object to the null object.
+ #[inline(always)]
+ pub fn into_null(self) -> Option<Null> {
+ self.cast()
+ }
+
+ /// Try casting the object to a bool.
+ #[inline(always)]
+ pub fn into_bool(self) -> Option<bool> {
+ self.cast()
+ }
+
+ /// Try casting the object to a string.
+ #[inline(always)]
+ pub fn into_string(self) -> Option<String<'a>> {
+ self.cast()
+ }
+
+ /// Try casting the object to a stream.
+ #[inline(always)]
+ pub fn into_stream(self) -> Option<Stream<'a>> {
+ self.cast()
+ }
+
+ /// Try casting the object to an array.
+ #[inline(always)]
+ pub fn into_array(self) -> Option<Array<'a>> {
+ self.cast()
+ }
+
+ /// Try casting the object to a u8.
+ #[inline(always)]
+ pub fn into_u8(self) -> Option<u8> {
+ self.cast()
+ }
+
+ /// Try casting the object to a u16.
+ #[inline(always)]
+ pub fn into_u16(self) -> Option<u16> {
+ self.cast()
+ }
+
+ /// Try casting the object to a f32.
+ #[inline(always)]
+ pub fn into_f32(self) -> Option<f32> {
+ self.cast()
+ }
+
+ /// Try casting the object to a i32.
+ #[inline(always)]
+ pub fn into_i32(self) -> Option<i32> {
+ self.cast()
+ }
+
+ /// Try casting the object to a number.
+ #[inline(always)]
+ pub fn into_number(self) -> Option<Number> {
+ self.cast()
+ }
+}
+
+impl<'a> ObjectLike<'a> for Object<'a> {}
+impl<'a> ObjectRefLike<'a> for Object<'a> {
+ fn cast_ref(obj: &Self) -> Option<&Self> {
+ Some(obj)
+ }
+}
+
+impl Skippable for Object<'_> {
+ fn skip(r: &mut Reader<'_>, is_content_stream: bool) -> Option<()> {
+ match r.peek_byte()? {
+ b'n' => Null::skip(r, is_content_stream),
+ b't' | b'f' => bool::skip(r, is_content_stream),
+ b'/' => Name::skip(r, is_content_stream),
+ b'<' => match r.peek_bytes(2)? {
+ // A stream can never appear in a dict/array, so it should never be skipped.
+ b"<<" => Dict::skip(r, is_content_stream),
+ _ => String::skip(r, is_content_stream),
+ },
+ b'(' => String::skip(r, is_content_stream),
+ b'.' | b'+' | b'-' | b'0'..=b'9' => Number::skip(r, is_content_stream),
+ b'[' => Array::skip(r, is_content_stream),
+ // See test case operator-in-TJ-array-0: Be lenient and skip content operators in
+ // array
+ _ => skip_name_like(r, false),
+ }
+ }
+}
+
+impl<'a> Readable<'a> for Object<'a> {
+ fn read(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<Self> {
+ let object = match r.peek_byte()? {
+ b'n' => Self::Null(Null::read(r, ctx)?),
+ b't' | b'f' => Self::Boolean(bool::read(r, ctx)?),
+ b'/' => Self::Name(Name::read(r, ctx)?),
+ b'<' => match r.peek_bytes(2)? {
+ b"<<" => {
+ let mut cloned = r.clone();
+ let dict = Dict::read(&mut cloned, ctx)?;
+ cloned.skip_white_spaces_and_comments();
+
+ if cloned.forward_tag(b"stream").is_some() {
+ Object::Stream(Stream::read(r, ctx)?)
+ } else {
+ r.jump(cloned.offset());
+
+ Object::Dict(dict)
+ }
+ }
+ _ => Self::String(String::read(r, ctx)?),
+ },
+ b'(' => Self::String(String::read(r, ctx)?),
+ b'.' | b'+' | b'-' | b'0'..=b'9' => Self::Number(Number::read(r, ctx)?),
+ b'[' => Self::Array(Array::read(r, ctx)?),
+ // See the comment in `skip`.
+ _ => {
+ skip_name_like(r, false)?;
+ Self::Null(Null)
+ }
+ };
+
+ Some(object)
+ }
+}
+
+/// A trait for objects that can be parsed from a simple byte stream.
+pub trait FromBytes<'a>: Sized {
+ /// Try to read the object from the given bytes.
+ fn from_bytes(b: &'a [u8]) -> Option<Self>;
+}
+
+impl<'a, T: Readable<'a>> FromBytes<'a> for T {
+ fn from_bytes(b: &'a [u8]) -> Option<Self> {
+ Self::from_bytes_impl(b)
+ }
+}
+
+/// An identifier for a PDF object.
+#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
+pub struct ObjectIdentifier {
+ /// The object number.
+ pub obj_number: i32,
+ /// The generation number.
+ pub gen_number: i32,
+}
+
+impl ObjectIdentifier {
+ /// Create a new `ObjectIdentifier`.
+ pub fn new(obj_number: i32, gen_number: i32) -> Self {
+ Self {
+ obj_number,
+ gen_number,
+ }
+ }
+}
+
+impl Readable<'_> for ObjectIdentifier {
+ fn read(r: &mut Reader<'_>, _: &ReaderContext<'_>) -> Option<Self> {
+ let obj_number = r.read_without_context::<i32>()?;
+ r.skip_white_spaces_and_comments();
+ let gen_number = r.read_without_context::<i32>()?;
+ r.skip_white_spaces_and_comments();
+ r.forward_tag(b"obj")?;
+
+ Some(Self {
+ obj_number,
+ gen_number,
+ })
+ }
+}
+
+impl Skippable for ObjectIdentifier {
+ fn skip(r: &mut Reader<'_>, _: bool) -> Option<()> {
+ r.skip::<i32>(false)?;
+ r.skip_white_spaces_and_comments();
+ r.skip::<i32>(false)?;
+ r.skip_white_spaces_and_comments();
+ r.forward_tag(b"obj")?;
+
+ Some(())
+ }
+}
+
+/// A convenience function that extracts a dict and a stream from an object.
+/// If the object is just a dictionary, it will return `None` for the stream.
+/// If the object is a stream, it will return its dictionary as well as the stream
+/// itself.
+pub fn dict_or_stream<'a, 'b>(
+ obj: &'b Object<'a>,
+) -> Option<(&'b Dict<'a>, Option<&'b Stream<'a>>)> {
+ if let Some(stream) = obj.cast_ref::<Stream<'a>>() {
+ Some((stream.dict(), Some(stream)))
+ } else {
+ obj.cast_ref::<Dict<'a>>().map(|dict| (dict, None))
+ }
+}
+
+mod macros {
+ macro_rules! object {
+ ($t:ident $(<$l:lifetime>),*, $s:ident) => {
+ impl<'a> TryFrom<Object<'a>> for $t$(<$l>),* {
+ type Error = ();
+
+ fn try_from(value: Object<'a>) -> core::result::Result<Self, Self::Error> {
+ match value {
+ Object::$s(b) => Ok(b),
+ _ => Err(()),
+ }
+ }
+ }
+
+ impl<'a> crate::object::ObjectLike<'a> for $t$(<$l>),* {}
+
+ impl<'a> crate::object::ObjectRefLike<'a> for $t$(<$l>),* {
+ fn cast_ref<'b>(obj: &'b crate::object::Object<'a>) -> Option<&'b Self> {
+ match obj {
+ crate::object::Object::$s(b) => Some(b),
+ _ => None,
+ }
+ }
+ }
+ };
+ }
+
+ pub(crate) use object;
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::object::{Array, Dict, Name, Null, Number, Object, Stream, String};
+ use crate::reader::Reader;
+ use crate::reader::{ReaderContext, ReaderExt};
+
+ fn object_impl(data: &[u8]) -> Option<Object<'_>> {
+ let mut r = Reader::new(data);
+ r.read_with_context::<Object<'_>>(&ReaderContext::dummy())
+ }
+
+ #[test]
+ fn null() {
+ assert!(matches!(object_impl(b"null").unwrap(), Object::Null(_)));
+ }
+
+ #[test]
+ fn bool() {
+ assert!(matches!(object_impl(b"true").unwrap(), Object::Boolean(_)));
+ }
+
+ #[test]
+ fn number() {
+ assert!(matches!(object_impl(b"34.5").unwrap(), Object::Number(_)));
+ }
+
+ #[test]
+ fn string_1() {
+ assert!(matches!(object_impl(b"(Hi)").unwrap(), Object::String(_)));
+ }
+
+ #[test]
+ fn string_2() {
+ assert!(matches!(object_impl(b"<34>").unwrap(), Object::String(_)));
+ }
+
+ #[test]
+ fn name() {
+ assert!(matches!(object_impl(b"/Name").unwrap(), Object::Name(_)));
+ }
+
+ #[test]
+ fn dict() {
+ assert!(matches!(
+ object_impl(b"<</Entry 45>>").unwrap(),
+ Object::Dict(_)
+ ));
+ }
+
+ #[test]
+ fn array() {
+ assert!(matches!(object_impl(b"[45]").unwrap(), Object::Array(_)));
+ }
+
+ #[test]
+ fn stream() {
+ assert!(matches!(
+ object_impl(b"<< /Length 3 >> stream\nabc\nendstream").unwrap(),
+ Object::Stream(_)
+ ));
+ }
+
+ #[test]
+ #[cfg(target_pointer_width = "64")]
+ fn object_sizes() {
+ assert_eq!(size_of::<Object<'_>>(), 40);
+ assert_eq!(size_of::<Array<'_>>(), 32);
+ assert_eq!(size_of::<Dict<'_>>(), 8);
+ assert_eq!(size_of::<Name<'_>>(), 32);
+ assert_eq!(size_of::<Null>(), 0);
+ assert_eq!(size_of::<Number>(), 16);
+ assert_eq!(size_of::<Stream<'_>>(), 24);
+ assert_eq!(size_of::<String<'_>>(), 32);
+ }
+}
diff --git a/vendor/hayro-syntax/src/object/name.rs b/vendor/hayro-syntax/src/object/name.rs
new file mode 100644
index 000000000..39d9e498a
--- /dev/null
+++ b/vendor/hayro-syntax/src/object/name.rs
@@ -0,0 +1,352 @@
+//! Names.
+
+use crate::filter::ascii_hex::decode_hex_digit;
+use crate::object::Object;
+use crate::object::macros::object;
+use crate::reader::Reader;
+use crate::reader::{Readable, ReaderContext, Skippable};
+use crate::trivia::is_regular_character;
+use core::borrow::Borrow;
+use core::fmt::{self, Debug, Formatter};
+use core::hash::{Hash, Hasher};
+use core::ops::Deref;
+use smallvec::SmallVec;
+
+#[derive(Clone)]
+enum NameInner<'a> {
+ Borrowed(&'a [u8]),
+ Owned(SmallVec<[u8; 23]>),
+}
+
+/// A PDF name object.
+#[derive(Clone)]
+pub struct Name<'a>(NameInner<'a>);
+
+impl<'a> Deref for Name<'a> {
+ type Target = [u8];
+
+ fn deref(&self) -> &Self::Target {
+ self.as_ref()
+ }
+}
+
+impl AsRef<[u8]> for Name<'_> {
+ fn as_ref(&self) -> &[u8] {
+ match &self.0 {
+ NameInner::Borrowed(data) => data,
+ NameInner::Owned(data) => data,
+ }
+ }
+}
+
+impl Borrow<[u8]> for Name<'_> {
+ fn borrow(&self) -> &[u8] {
+ self.as_ref()
+ }
+}
+
+impl PartialEq for Name<'_> {
+ fn eq(&self, other: &Self) -> bool {
+ self.as_ref() == other.as_ref()
+ }
+}
+
+impl Eq for Name<'_> {}
+
+impl Hash for Name<'_> {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ self.as_ref().hash(state);
+ }
+}
+
+impl PartialOrd for Name<'_> {
+ fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
+ Some(self.cmp(other))
+ }
+}
+
+impl Ord for Name<'_> {
+ fn cmp(&self, other: &Self) -> core::cmp::Ordering {
+ self.as_ref().cmp(other.as_ref())
+ }
+}
+
+impl<'a> Name<'a> {
+ /// Create a new name from a sequence of bytes.
+ #[inline]
+ pub fn new(data: &'a [u8]) -> Option<Self> {
+ if !data.contains(&b'#') {
+ Some(Self::new_unescaped(data))
+ } else {
+ Self::new_escaped(data)
+ }
+ }
+
+ /// Create a new name from an unescaped byte sequence.
+ #[inline]
+ pub fn new_unescaped(data: &'a [u8]) -> Self {
+ Self(NameInner::Borrowed(data))
+ }
+
+ /// Create a new name from bytes that may contain escape sequences.
+ #[inline]
+ pub fn new_escaped(data: &'a [u8]) -> Option<Self> {
+ let mut result = SmallVec::new();
+ let mut r = Reader::new(data);
+
+ while let Some(b) = r.read_byte() {
+ if b == b'#' {
+ let hex = r.read_bytes(2)?;
+ result.push(decode_hex_digit(hex[0])? << 4 | decode_hex_digit(hex[1])?);
+ } else {
+ result.push(b);
+ }
+ }
+
+ Some(Self(NameInner::Owned(result)))
+ }
+
+ /// Return a string representation of the name.
+ ///
+ /// Returns a placeholder in case the name is not UTF-8 encoded.
+ pub fn as_str(&self) -> &str {
+ core::str::from_utf8(self.as_ref()).unwrap_or("{non-ascii key}")
+ }
+}
+
+impl Debug for Name<'_> {
+ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
+ match core::str::from_utf8(self.as_ref()) {
+ Ok(s) => <str as Debug>::fmt(s, f),
+ Err(_) => <[u8] as Debug>::fmt(self.as_ref(), f),
+ }
+ }
+}
+
+object!(Name<'a>, Name);
+
+impl Skippable for Name<'_> {
+ fn skip(r: &mut Reader<'_>, _: bool) -> Option<()> {
+ skip_name_like(r, true).map(|_| ())
+ }
+}
+
+impl<'a> Readable<'a> for Name<'a> {
+ fn read(r: &mut Reader<'a>, _: &ReaderContext<'a>) -> Option<Self> {
+ let start = r.offset();
+ skip_name_like(r, true)?;
+ let end = r.offset();
+
+ // Exclude leading solidus.
+ let data = r.range(start + 1..end)?;
+ Self::new(data)
+ }
+}
+
+// This method is shared by `Name` and the parser for content stream operators (which behave like
+// names, except that they aren't preceded by a solidus.
+pub(crate) fn skip_name_like(r: &mut Reader<'_>, solidus: bool) -> Option<()> {
+ // Note that we are not validating hex escape sequences here
+ // (since this method can lie on the hot path), so it's possible
+ // this method will yield invalid names. Validation needs to happen during actual
+ // actual reading.
+ if solidus {
+ r.forward_tag(b"/")?;
+ r.forward_while(is_regular_character);
+ } else {
+ r.forward_while_1(is_regular_character)?;
+ }
+
+ Some(())
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::object::Name;
+ use crate::reader::Reader;
+ use crate::reader::ReaderExt;
+ use std::ops::Deref;
+
+ #[test]
+ fn name_1() {
+ assert_eq!(
+ Reader::new("/".as_bytes())
+ .read_without_context::<Name<'_>>()
+ .unwrap()
+ .deref(),
+ b""
+ );
+ }
+
+ #[test]
+ fn name_2() {
+ assert!(
+ Reader::new("dfg".as_bytes())
+ .read_without_context::<Name<'_>>()
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn name_3() {
+ assert!(
+ Reader::new("/AB#FG".as_bytes())
+ .read_without_context::<Name<'_>>()
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn name_4() {
+ assert_eq!(
+ Reader::new("/Name1".as_bytes())
+ .read_without_context::<Name<'_>>()
+ .unwrap()
+ .deref(),
+ b"Name1"
+ );
+ }
+
+ #[test]
+ fn name_5() {
+ assert_eq!(
+ Reader::new("/ASomewhatLongerName".as_bytes())
+ .read_without_context::<Name<'_>>()
+ .unwrap()
+ .deref(),
+ b"ASomewhatLongerName"
+ );
+ }
+
+ #[test]
+ fn name_6() {
+ assert_eq!(
+ Reader::new("/A;Name_With-Various***Characters?".as_bytes())
+ .read_without_context::<Name<'_>>()
+ .unwrap()
+ .deref(),
+ b"A;Name_With-Various***Characters?"
+ );
+ }
+
+ #[test]
+ fn name_7() {
+ assert_eq!(
+ Reader::new("/1.2".as_bytes())
+ .read_without_context::<Name<'_>>()
+ .unwrap()
+ .deref(),
+ b"1.2"
+ );
+ }
+
+ #[test]
+ fn name_8() {
+ assert_eq!(
+ Reader::new("/$$".as_bytes())
+ .read_without_context::<Name<'_>>()
+ .unwrap()
+ .deref(),
+ b"$$"
+ );
+ }
+
+ #[test]
+ fn name_9() {
+ assert_eq!(
+ Reader::new("/@pattern".as_bytes())
+ .read_without_context::<Name<'_>>()
+ .unwrap()
+ .deref(),
+ b"@pattern"
+ );
+ }
+
+ #[test]
+ fn name_10() {
+ assert_eq!(
+ Reader::new("/.notdef".as_bytes())
+ .read_without_context::<Name<'_>>()
+ .unwrap()
+ .deref(),
+ b".notdef"
+ );
+ }
+
+ #[test]
+ fn name_11() {
+ assert_eq!(
+ Reader::new("/lime#20Green".as_bytes())
+ .read_without_context::<Name<'_>>()
+ .unwrap()
+ .deref(),
+ b"lime Green"
+ );
+ }
+
+ #[test]
+ fn name_12() {
+ assert_eq!(
+ Reader::new("/paired#28#29parentheses".as_bytes())
+ .read_without_context::<Name<'_>>()
+ .unwrap()
+ .deref(),
+ b"paired()parentheses"
+ );
+ }
+
+ #[test]
+ fn name_13() {
+ assert_eq!(
+ Reader::new("/The_Key_of_F#23_Minor".as_bytes())
+ .read_without_context::<Name<'_>>()
+ .unwrap()
+ .deref(),
+ b"The_Key_of_F#_Minor"
+ );
+ }
+
+ #[test]
+ fn name_14() {
+ assert_eq!(
+ Reader::new("/A#42".as_bytes())
+ .read_without_context::<Name<'_>>()
+ .unwrap()
+ .deref(),
+ b"AB"
+ );
+ }
+
+ #[test]
+ fn name_15() {
+ assert_eq!(
+ Reader::new("/A#3b".as_bytes())
+ .read_without_context::<Name<'_>>()
+ .unwrap()
+ .deref(),
+ b"A;"
+ );
+ }
+
+ #[test]
+ fn name_16() {
+ assert_eq!(
+ Reader::new("/A#3B".as_bytes())
+ .read_without_context::<Name<'_>>()
+ .unwrap()
+ .deref(),
+ b"A;"
+ );
+ }
+
+ #[test]
+ fn name_17() {
+ assert_eq!(
+ Reader::new("/k1 ".as_bytes())
+ .read_without_context::<Name<'_>>()
+ .unwrap()
+ .deref(),
+ b"k1"
+ );
+ }
+}
diff --git a/vendor/hayro-syntax/src/object/null.rs b/vendor/hayro-syntax/src/object/null.rs
new file mode 100644
index 000000000..6f025b193
--- /dev/null
+++ b/vendor/hayro-syntax/src/object/null.rs
@@ -0,0 +1,53 @@
+//! The null object.
+
+use crate::object::Object;
+use crate::object::macros::object;
+use crate::reader::Reader;
+use crate::reader::{Readable, ReaderContext, Skippable};
+
+/// The null object.
+#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash)]
+pub struct Null;
+
+object!(Null, Null);
+
+impl Skippable for Null {
+ fn skip(r: &mut Reader<'_>, _: bool) -> Option<()> {
+ r.forward_tag(b"null")
+ }
+}
+
+impl Readable<'_> for Null {
+ fn read(r: &mut Reader<'_>, ctx: &ReaderContext<'_>) -> Option<Self> {
+ Self::skip(r, ctx.in_content_stream())?;
+
+ Some(Self)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::object::Null;
+ use crate::reader::Reader;
+ use crate::reader::ReaderExt;
+
+ #[test]
+ fn null() {
+ assert_eq!(
+ Reader::new("null".as_bytes())
+ .read_without_context::<Null>()
+ .unwrap(),
+ Null
+ );
+ }
+
+ #[test]
+ fn null_trailing() {
+ assert_eq!(
+ Reader::new("nullabs".as_bytes())
+ .read_without_context::<Null>()
+ .unwrap(),
+ Null
+ );
+ }
+}
diff --git a/vendor/hayro-syntax/src/object/number.rs b/vendor/hayro-syntax/src/object/number.rs
new file mode 100644
index 000000000..a2847cd78
--- /dev/null
+++ b/vendor/hayro-syntax/src/object/number.rs
@@ -0,0 +1,540 @@
+//! Numbers.
+
+use crate::math::{powi_f64, trunc_f64};
+use crate::object::macros::object;
+use crate::object::{Object, ObjectLike};
+use crate::reader::Reader;
+use crate::reader::{Readable, ReaderContext, ReaderExt, Skippable};
+use crate::trivia::{is_regular_character, is_white_space_character};
+use core::fmt::Debug;
+
+#[rustfmt::skip]
+static POWERS_OF_10: [f64; 20] = [
+ 1.0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
+ 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
+];
+
+/// A number.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Number(pub(crate) InternalNumber);
+
+impl Number {
+ /// The number zero.
+ pub const ZERO: Self = Self::from_i32(0);
+ /// The number one.
+ pub const ONE: Self = Self::from_i32(1);
+
+ /// Returns the number as a f64.
+ pub fn as_f64(&self) -> f64 {
+ match self.0 {
+ InternalNumber::Real(r) => r,
+ InternalNumber::Integer(i) => i as f64,
+ }
+ }
+
+ /// Returns the number as a f32.
+ pub fn as_f32(&self) -> f32 {
+ match self.0 {
+ InternalNumber::Real(r) => r as f32,
+ InternalNumber::Integer(i) => i as f32,
+ }
+ }
+
+ /// Returns the number as an i64.
+ pub fn as_i64(&self) -> i64 {
+ match self.0 {
+ InternalNumber::Real(r) => {
+ let res = r as i64;
+
+ if !(trunc_f64(r) == r) {
+ debug!("float {r} was truncated to {res}");
+ }
+
+ res
+ }
+ InternalNumber::Integer(i) => i,
+ }
+ }
+
+ /// Create a new `Number` from an f32 number.
+ pub const fn from_f32(num: f32) -> Self {
+ Self(InternalNumber::Real(num as f64))
+ }
+
+ /// Create a new `Number` from an i32 number.
+ pub const fn from_i32(num: i32) -> Self {
+ Self(InternalNumber::Integer(num as i64))
+ }
+}
+
+impl Skippable for Number {
+ fn skip(r: &mut Reader<'_>, _: bool) -> Option<()> {
+ let has_sign = r.forward_if(|b| b == b'+' || b == b'-').is_some();
+
+ // Some PDFs have weird trailing minuses, so try to accept those as well.
+ match r.peek_byte()? {
+ b'.' => {
+ r.read_byte()?;
+ // See PDFJS-9252 - treat a single . as 0.
+ r.forward_while(is_digit_or_minus);
+ }
+ b'0'..=b'9' | b'-' => {
+ r.forward_while_1(is_digit_or_minus)?;
+ if let Some(()) = r.forward_tag(b".") {
+ r.forward_while(is_digit_or_minus);
+ }
+ }
+ // See PDFJS-bug1753983 - accept just + or - as a zero.
+ // ALso see PDFJS-bug1953099, where the sign is followed by a show
+ // text string operand, requiring us to allow '<' and '(' as well.
+ b if has_sign && (is_white_space_character(b) || matches!(b, b'(' | b'<')) => {}
+ _ => return None,
+ }
+
+ // See issue 994. Don't accept numbers that are followed by a regular character.
+ if r.peek_byte().is_some_and(is_regular_character) {
+ return None;
+ }
+
+ Some(())
+ }
+}
+
+impl Readable<'_> for Number {
+ #[inline]
+ fn read(r: &mut Reader<'_>, _: &ReaderContext<'_>) -> Option<Self> {
+ let old_offset = r.offset();
+ read_inner(r).or_else(|| {
+ r.jump(old_offset);
+ None
+ })
+ }
+}
+
+#[inline(always)]
+fn read_inner(r: &mut Reader<'_>) -> Option<Number> {
+ let negative = match r.peek_byte()? {
+ b'-' => {
+ r.forward();
+ true
+ }
+ b'+' => {
+ r.forward();
+ false
+ }
+ _ => false,
+ };
+
+ let mut mantissa: u64 = 0;
+ let mut has_dot = false;
+ let mut decimal_shift: u32 = 0;
+ let mut has_digits = false;
+
+ loop {
+ match r.peek_byte() {
+ Some(b'0'..=b'9') => {
+ let d = r.read_byte().unwrap();
+ mantissa = mantissa
+ // Using `saturating` would arguably be better here, but
+ // profiling showed that it seems to be more expensive, at least
+ // on ARM. Since such large numbers shouldn't appear anyway,
+ // it doesn't really matter a lot what mode we use.
+ .wrapping_mul(10)
+ .wrapping_add((d - b'0') as u64);
+ has_digits = true;
+ if has_dot {
+ decimal_shift += 1;
+ }
+ }
+ Some(b'.') if !has_dot => {
+ r.forward();
+ has_dot = true;
+ }
+ // Some weird PDFs have trailing minus in the fraction of number.
+ Some(b'-') if has_digits => {
+ r.forward();
+ r.forward_while(is_digit_or_minus);
+ break;
+ }
+ _ => break,
+ }
+ }
+
+ if !has_digits {
+ if negative || has_dot {
+ // Treat numbers like just `-`, `+` or `-.` as zero.
+ return Some(Number(InternalNumber::Integer(0)));
+ }
+ return None;
+ }
+
+ // See issue 994. Don't accept numbers that are followed by a regular character
+ // without any white space in-between.
+ if r.peek_byte().is_some_and(is_regular_character) {
+ return None;
+ }
+
+ if !has_dot {
+ let value = if negative {
+ (mantissa as i64).wrapping_neg()
+ } else {
+ mantissa as i64
+ };
+ Some(Number(InternalNumber::Integer(value)))
+ } else {
+ let mut value = mantissa as f64;
+
+ if decimal_shift > 0 {
+ if decimal_shift < POWERS_OF_10.len() as u32 {
+ value /= POWERS_OF_10[decimal_shift as usize];
+ } else {
+ value /= powi_f64(10.0, decimal_shift);
+ }
+ }
+
+ if negative {
+ value = -value;
+ }
+
+ Some(Number(InternalNumber::Real(value)))
+ }
+}
+
+object!(Number, Number);
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) enum InternalNumber {
+ Real(f64),
+ Integer(i64),
+}
+
+macro_rules! int_num {
+ ($i:ident) => {
+ impl Skippable for $i {
+ fn skip(r: &mut Reader<'_>, _: bool) -> Option<()> {
+ r.forward_if(|b| b == b'+' || b == b'-');
+ r.forward_while_1(is_digit)?;
+
+ // We have a float instead of an integer.
+ if r.peek_byte() == Some(b'.') {
+ return None;
+ }
+
+ // See issue 994. Don't accept numbers that are followed by a regular character
+ // without any white space in-between.
+ if r.peek_byte().is_some_and(is_regular_character) {
+ return None;
+ }
+
+ Some(())
+ }
+ }
+
+ impl<'a> Readable<'a> for $i {
+ fn read(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<$i> {
+ r.read::<Number>(ctx)
+ .map(|n| n.as_i64())
+ .and_then(|n| n.try_into().ok())
+ }
+ }
+
+ impl TryFrom<Object<'_>> for $i {
+ type Error = ();
+
+ fn try_from(value: Object<'_>) -> core::result::Result<Self, Self::Error> {
+ match value {
+ Object::Number(n) => n.as_i64().try_into().ok().ok_or(()),
+ _ => Err(()),
+ }
+ }
+ }
+
+ impl<'a> ObjectLike<'a> for $i {}
+ };
+}
+
+int_num!(i32);
+int_num!(i64);
+int_num!(u32);
+int_num!(u16);
+int_num!(usize);
+int_num!(u8);
+
+impl Skippable for f32 {
+ fn skip(r: &mut Reader<'_>, is_content_stream: bool) -> Option<()> {
+ r.skip::<Number>(is_content_stream).map(|_| {})
+ }
+}
+
+impl Readable<'_> for f32 {
+ fn read(r: &mut Reader<'_>, _: &ReaderContext<'_>) -> Option<Self> {
+ r.read_without_context::<Number>()
+ .map(|n| n.as_f64() as Self)
+ }
+}
+
+impl TryFrom<Object<'_>> for f32 {
+ type Error = ();
+
+ fn try_from(value: Object<'_>) -> Result<Self, Self::Error> {
+ match value {
+ Object::Number(n) => Ok(n.as_f64() as Self),
+ _ => Err(()),
+ }
+ }
+}
+
+impl ObjectLike<'_> for f32 {}
+
+impl Skippable for f64 {
+ fn skip(r: &mut Reader<'_>, is_content_stream: bool) -> Option<()> {
+ r.skip::<Number>(is_content_stream).map(|_| {})
+ }
+}
+
+impl Readable<'_> for f64 {
+ fn read(r: &mut Reader<'_>, _: &ReaderContext<'_>) -> Option<Self> {
+ r.read_without_context::<Number>().map(|n| n.as_f64())
+ }
+}
+
+impl TryFrom<Object<'_>> for f64 {
+ type Error = ();
+
+ fn try_from(value: Object<'_>) -> Result<Self, Self::Error> {
+ match value {
+ Object::Number(n) => Ok(n.as_f64()),
+ _ => Err(()),
+ }
+ }
+}
+
+impl ObjectLike<'_> for f64 {}
+
+pub(crate) fn is_digit(byte: u8) -> bool {
+ byte.is_ascii_digit()
+}
+
+pub(crate) fn is_digit_or_minus(byte: u8) -> bool {
+ is_digit(byte) || byte == b'-'
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::object::Number;
+ use crate::reader::Reader;
+ use crate::reader::ReaderExt;
+
+ #[test]
+ fn int_1() {
+ assert_eq!(
+ Reader::new("0".as_bytes())
+ .read_without_context::<i32>()
+ .unwrap(),
+ 0
+ );
+ }
+
+ #[test]
+ fn int_3() {
+ assert_eq!(
+ Reader::new("+32".as_bytes())
+ .read_without_context::<i32>()
+ .unwrap(),
+ 32
+ );
+ }
+
+ #[test]
+ fn int_4() {
+ assert_eq!(
+ Reader::new("-32".as_bytes())
+ .read_without_context::<i32>()
+ .unwrap(),
+ -32
+ );
+ }
+
+ #[test]
+ fn int_6() {
+ assert_eq!(
+ Reader::new("98349".as_bytes())
+ .read_without_context::<i32>()
+ .unwrap(),
+ 98349
+ );
+ }
+
+ #[test]
+ fn int_7() {
+ assert_eq!(
+ Reader::new("003245".as_bytes())
+ .read_without_context::<i32>()
+ .unwrap(),
+ 3245
+ );
+ }
+
+ #[test]
+ fn int_min_does_not_panic() {
+ assert_eq!(
+ Reader::new("-9223372036854775808".as_bytes())
+ .read_without_context::<i64>()
+ .unwrap(),
+ i64::MIN
+ );
+ }
+
+ #[test]
+ fn real_1() {
+ assert_eq!(
+ Reader::new("3".as_bytes())
+ .read_without_context::<f32>()
+ .unwrap(),
+ 3.0
+ );
+ }
+
+ #[test]
+ fn real_3() {
+ assert_eq!(
+ Reader::new("+32".as_bytes())
+ .read_without_context::<f32>()
+ .unwrap(),
+ 32.0
+ );
+ }
+
+ #[test]
+ fn real_4() {
+ assert_eq!(
+ Reader::new("-32".as_bytes())
+ .read_without_context::<f32>()
+ .unwrap(),
+ -32.0
+ );
+ }
+
+ #[test]
+ fn real_5() {
+ assert_eq!(
+ Reader::new("-32.01".as_bytes())
+ .read_without_context::<f32>()
+ .unwrap(),
+ -32.01
+ );
+ }
+
+ #[test]
+ fn real_6() {
+ assert_eq!(
+ Reader::new("-.345".as_bytes())
+ .read_without_context::<f32>()
+ .unwrap(),
+ -0.345
+ );
+ }
+
+ #[test]
+ fn real_7() {
+ assert_eq!(
+ Reader::new("-.00143".as_bytes())
+ .read_without_context::<f32>()
+ .unwrap(),
+ -0.00143
+ );
+ }
+
+ #[test]
+ fn real_8() {
+ assert_eq!(
+ Reader::new("-12.0013".as_bytes())
+ .read_without_context::<f32>()
+ .unwrap(),
+ -12.0013
+ );
+ }
+
+ #[test]
+ fn real_9() {
+ assert_eq!(
+ Reader::new("98349.432534".as_bytes())
+ .read_without_context::<f32>()
+ .unwrap(),
+ 98_349.43
+ );
+ }
+
+ #[test]
+ fn real_10() {
+ assert_eq!(
+ Reader::new("-34534656.34".as_bytes())
+ .read_without_context::<f32>()
+ .unwrap(),
+ -34534656.34
+ );
+ }
+
+ #[test]
+ fn real_failing() {
+ assert!(
+ Reader::new("+abc".as_bytes())
+ .read_without_context::<f32>()
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn number_1() {
+ assert_eq!(
+ Reader::new("+32".as_bytes())
+ .read_without_context::<Number>()
+ .unwrap()
+ .as_f64() as f32,
+ 32.0
+ );
+ }
+
+ #[test]
+ fn number_2() {
+ assert_eq!(
+ Reader::new("-32.01".as_bytes())
+ .read_without_context::<Number>()
+ .unwrap()
+ .as_f64() as f32,
+ -32.01
+ );
+ }
+
+ #[test]
+ fn number_3() {
+ assert_eq!(
+ Reader::new("-.345".as_bytes())
+ .read_without_context::<Number>()
+ .unwrap()
+ .as_f64() as f32,
+ -0.345
+ );
+ }
+
+ #[test]
+ fn large_number() {
+ assert_eq!(
+ Reader::new("38359922".as_bytes())
+ .read_without_context::<Number>()
+ .unwrap()
+ .as_i64(),
+ 38359922
+ );
+ }
+
+ #[test]
+ fn large_number_2() {
+ assert_eq!(
+ Reader::new("4294966260".as_bytes())
+ .read_without_context::<u32>()
+ .unwrap(),
+ 4294966260
+ );
+ }
+}
diff --git a/vendor/hayro-syntax/src/object/rect.rs b/vendor/hayro-syntax/src/object/rect.rs
new file mode 100644
index 000000000..13f46315b
--- /dev/null
+++ b/vendor/hayro-syntax/src/object/rect.rs
@@ -0,0 +1,83 @@
+//! Rectangles.
+
+use crate::object::Array;
+use crate::object::{Object, ObjectLike};
+use crate::reader::{Readable, ReaderContext, ReaderExt};
+
+use crate::reader::Reader;
+
+/// A rectangle.
+#[derive(Copy, Clone, Debug)]
+pub struct Rect {
+ /// The minimum x coordinate.
+ pub x0: f64,
+ /// The minimum y coordinate.
+ pub y0: f64,
+ /// The maximum x coordinate.
+ pub x1: f64,
+ /// The maximum y coordinate.
+ pub y1: f64,
+}
+
+impl Rect {
+ /// The empty rectangle at the origin.
+ pub const ZERO: Self = Self::new(0., 0., 0., 0.);
+
+ /// A new rectangle from minimum and maximum coordinates.
+ #[inline(always)]
+ pub const fn new(x0: f64, y0: f64, x1: f64, y1: f64) -> Self {
+ Self { x0, y0, x1, y1 }
+ }
+
+ /// The intersection of two rectangles.
+ #[inline]
+ pub fn intersect(&self, other: Self) -> Self {
+ let x0 = self.x0.max(other.x0);
+ let y0 = self.y0.max(other.y0);
+ let x1 = self.x1.min(other.x1);
+ let y1 = self.y1.min(other.y1);
+ Self::new(x0, y0, x1.max(x0), y1.max(y0))
+ }
+
+ /// The width of the rectangle.
+ #[inline]
+ pub const fn width(&self) -> f64 {
+ self.x1 - self.x0
+ }
+
+ /// The height of the rectangle.
+ #[inline]
+ pub const fn height(&self) -> f64 {
+ self.y1 - self.y0
+ }
+}
+
+impl<'a> Readable<'a> for Rect {
+ fn read(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<Self> {
+ let arr = r.read::<Array<'_>>(ctx)?;
+ from_arr(&arr)
+ }
+}
+
+fn from_arr(array: &Array<'_>) -> Option<Rect> {
+ let mut iter = array.iter::<f32>();
+ let x0 = iter.next()? as f64;
+ let y0 = iter.next()? as f64;
+ let x1 = iter.next()? as f64;
+ let y1 = iter.next()? as f64;
+
+ Some(Rect::new(x0.min(x1), y0.min(y1), x1.max(x0), y1.max(y0)))
+}
+
+impl TryFrom<Object<'_>> for Rect {
+ type Error = ();
+
+ fn try_from(value: Object<'_>) -> Result<Self, Self::Error> {
+ match value {
+ Object::Array(arr) => from_arr(&arr).ok_or(()),
+ _ => Err(()),
+ }
+ }
+}
+
+impl ObjectLike<'_> for Rect {}
diff --git a/vendor/hayro-syntax/src/object/ref.rs b/vendor/hayro-syntax/src/object/ref.rs
new file mode 100644
index 000000000..71951f4d8
--- /dev/null
+++ b/vendor/hayro-syntax/src/object/ref.rs
@@ -0,0 +1,187 @@
+//! Object references.
+
+use crate::object::ObjectIdentifier;
+use crate::object::ObjectLike;
+use crate::reader::Reader;
+use crate::reader::{Readable, ReaderContext, ReaderExt, Skippable};
+use core::fmt::{Debug, Formatter};
+
+/// A reference to an object.
+#[derive(PartialEq, Eq, Debug, Clone, Copy, Hash)]
+pub struct ObjRef {
+ /// The object number.
+ pub obj_number: i32,
+ /// The generation number.
+ pub gen_number: i32,
+}
+
+impl ObjRef {
+ /// Create a new object reference.
+ pub fn new(obj_number: i32, gen_number: i32) -> Self {
+ Self {
+ obj_number,
+ gen_number,
+ }
+ }
+}
+
+impl From<ObjRef> for ObjectIdentifier {
+ fn from(value: ObjRef) -> Self {
+ Self::new(value.obj_number, value.gen_number)
+ }
+}
+
+impl From<ObjectIdentifier> for ObjRef {
+ fn from(value: ObjectIdentifier) -> Self {
+ Self::new(value.obj_number, value.gen_number)
+ }
+}
+
+impl Skippable for ObjRef {
+ fn skip(r: &mut Reader<'_>, _: bool) -> Option<()> {
+ r.skip::<i32>(false)?;
+ r.skip_white_spaces();
+ r.skip::<i32>(false)?;
+ r.skip_white_spaces();
+ r.forward_tag(b"R")?;
+
+ Some(())
+ }
+}
+
+impl Readable<'_> for ObjRef {
+ fn read(r: &mut Reader<'_>, _: &ReaderContext<'_>) -> Option<Self> {
+ let obj_ref = r.read_without_context::<i32>()?;
+ r.skip_white_spaces();
+ let gen_num = r.read_without_context::<i32>()?;
+ r.skip_white_spaces();
+ r.forward_tag(b"R")?;
+
+ Some(Self::new(obj_ref, gen_num))
+ }
+}
+
+/// A struct that is either an object or a reference to an object.
+#[derive(PartialEq, Eq)]
+pub enum MaybeRef<T> {
+ /// A reference to an object.
+ Ref(ObjRef),
+ /// An object.
+ NotRef(T),
+}
+
+impl<T> MaybeRef<T> {
+ /// If the object is an object reference, return it.
+ pub fn as_obj_ref(&self) -> Option<ObjRef> {
+ match self {
+ Self::Ref(r) => Some(*r),
+ Self::NotRef(_) => None,
+ }
+ }
+}
+
+#[allow(private_bounds)]
+impl<'a, T> MaybeRef<T>
+where
+ T: ObjectLike<'a>,
+{
+ /// Resolve the `MaybeRef` object with the given xref table.
+ pub(crate) fn resolve(self, ctx: &ReaderContext<'a>) -> Option<T> {
+ match self {
+ Self::Ref(r) => ctx.xref().get_with::<T>(r.into(), ctx),
+ Self::NotRef(t) => Some(t),
+ }
+ }
+}
+
+impl<T> TryFrom<MaybeRef<T>> for ObjRef {
+ type Error = ();
+
+ fn try_from(value: MaybeRef<T>) -> Result<Self, Self::Error> {
+ match value {
+ MaybeRef::Ref(r) => Ok(r),
+ MaybeRef::NotRef(_) => Err(()),
+ }
+ }
+}
+
+impl<T> Debug for MaybeRef<T>
+where
+ T: Debug,
+{
+ fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
+ match self {
+ Self::Ref(r) => write!(f, "{r:?}"),
+ Self::NotRef(nr) => write!(f, "{nr:?}"),
+ }
+ }
+}
+
+impl<T> Skippable for MaybeRef<T>
+where
+ T: Skippable,
+{
+ fn skip(r: &mut Reader<'_>, is_content_stream: bool) -> Option<()> {
+ r.skip::<ObjRef>(is_content_stream)
+ .or_else(|| r.skip::<T>(is_content_stream))
+ .map(|_| {})
+ }
+}
+
+impl<'a, T> Readable<'a> for MaybeRef<T>
+where
+ T: Readable<'a>,
+{
+ fn read(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<Self> {
+ if let Some(obj) = r.read::<ObjRef>(ctx) {
+ Some(Self::Ref(obj))
+ } else {
+ Some(Self::NotRef(r.read::<T>(ctx)?))
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::object::ObjRef;
+ use crate::reader::Reader;
+ use crate::reader::ReaderExt;
+
+ #[test]
+ fn ref_1() {
+ assert_eq!(
+ Reader::new("34 1 R".as_bytes())
+ .read_without_context::<ObjRef>()
+ .unwrap(),
+ ObjRef::new(34, 1)
+ );
+ }
+
+ #[test]
+ fn ref_trailing() {
+ assert_eq!(
+ Reader::new("256 0 R (hi)".as_bytes())
+ .read_without_context::<ObjRef>()
+ .unwrap(),
+ ObjRef::new(256, 0)
+ );
+ }
+
+ #[test]
+ fn ref_invalid_1() {
+ assert!(
+ Reader::new("256 R".as_bytes())
+ .read_without_context::<ObjRef>()
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn ref_invalid_2() {
+ assert!(
+ Reader::new("256 257".as_bytes())
+ .read_without_context::<ObjRef>()
+ .is_none()
+ );
+ }
+}
diff --git a/vendor/hayro-syntax/src/object/stream.rs b/vendor/hayro-syntax/src/object/stream.rs
new file mode 100644
index 000000000..8f7cd544d
--- /dev/null
+++ b/vendor/hayro-syntax/src/object/stream.rs
@@ -0,0 +1,388 @@
+//! Streams.
+
+use crate::crypto::DecryptionTarget;
+use crate::filter::Filter;
+use crate::object;
+use crate::object::Dict;
+use crate::object::Name;
+use crate::object::dict::keys::{DECODE_PARMS, DP, F, FILTER, LENGTH, TYPE};
+use crate::object::{Array, ObjectIdentifier};
+use crate::object::{Object, ObjectLike, ObjectRefLike};
+use crate::reader::Reader;
+use crate::reader::{Readable, ReaderContext, ReaderExt, Skippable};
+use crate::trivia::is_white_space_character;
+use crate::util::{OptionLog, find_needle};
+use alloc::borrow::Cow;
+use alloc::vec::Vec;
+use core::fmt::{Debug, Formatter};
+use smallvec::SmallVec;
+
+struct FiltersAndParams<'a> {
+ filters: SmallVec<[Filter; 2]>,
+ params: SmallVec<[Dict<'a>; 2]>,
+}
+
+/// A stream of arbitrary data.
+#[derive(Clone)]
+pub struct Stream<'a> {
+ dict: Dict<'a>,
+ data: &'a [u8],
+}
+
+impl PartialEq for Stream<'_> {
+ fn eq(&self, other: &Self) -> bool {
+ self.dict == other.dict && self.data == other.data
+ }
+}
+
+/// Additional parameters for decoding images.
+#[derive(Clone, PartialEq, Default)]
+pub struct ImageDecodeParams {
+ /// Whether the color space of the image is an indexed color space.
+ pub is_indexed: bool,
+ /// The bits per component of the image, if that information is available.
+ pub bpc: Option<u8>,
+ /// The components per channel of the image, if that information is available.
+ pub num_components: Option<u8>,
+ /// A target resolution for the image. Note that this is only a hint so that
+ /// in case it's possible, a version of the image will be extracted that
+ /// is as close as possible to the hinted dimension.
+ pub target_dimension: Option<(u32, u32)>,
+ /// The width of the image as indicated by the image dictionary.
+ pub width: u32,
+ /// The height of the image as indicated by the image dictionary.
+ pub height: u32,
+}
+
+impl<'a> Stream<'a> {
+ pub(crate) fn new(data: &'a [u8], dict: Dict<'a>) -> Self {
+ Self { dict, data }
+ }
+
+ fn filters_and_params(&self) -> FiltersAndParams<'a> {
+ let mut collected_filters = SmallVec::new();
+ let mut collected_params = SmallVec::new();
+
+ if let Some(filter) = self
+ .dict
+ .get::<Name<'_>>(F)
+ .or_else(|| self.dict.get::<Name<'_>>(FILTER))
+ .and_then(Filter::from_name)
+ {
+ let params = self
+ .dict
+ .get::<Dict<'_>>(DP)
+ .or_else(|| self.dict.get::<Dict<'_>>(DECODE_PARMS))
+ .unwrap_or_default();
+
+ collected_filters.push(filter);
+ collected_params.push(params);
+ } else if let Some(filters) = self
+ .dict
+ .get::<Array<'_>>(F)
+ .or_else(|| self.dict.get::<Array<'_>>(FILTER))
+ {
+ let filters = filters.iter::<Name<'_>>().map(Filter::from_name);
+ let mut params = self
+ .dict
+ .get::<Array<'_>>(DP)
+ .or_else(|| self.dict.get::<Array<'_>>(DECODE_PARMS))
+ .map(|a| a.iter::<Object<'_>>());
+
+ for filter in filters {
+ let params = params
+ .as_mut()
+ .and_then(|p| p.next())
+ .and_then(|p| p.into_dict())
+ .unwrap_or_default();
+
+ if let Some(filter) = filter {
+ collected_filters.push(filter);
+ collected_params.push(params);
+ }
+ }
+ }
+
+ FiltersAndParams {
+ filters: collected_filters,
+ params: collected_params,
+ }
+ }
+
+ /// Return the raw, decrypted data of the stream.
+ ///
+ /// Stream filters will not be applied.
+ pub fn raw_data(&self) -> Cow<'a, [u8]> {
+ let ctx = self.dict.ctx();
+
+ if ctx.xref().needs_decryption(ctx)
+ && self
+ .dict
+ .get::<object::String<'_>>(TYPE)
+ .map(|t| t.as_ref() != b"XRef")
+ .unwrap_or(true)
+ {
+ Cow::Owned(
+ ctx.xref()
+ .decrypt(self.obj_id(), self.data, DecryptionTarget::Stream)
+ // TODO: MAybe an error would be better?
+ .unwrap_or_default(),
+ )
+ } else {
+ Cow::Borrowed(self.data)
+ }
+ }
+
+ /// Return the raw, underlying dictionary of the stream.
+ pub fn dict(&self) -> &Dict<'a> {
+ &self.dict
+ }
+
+ /// Return the object identifier of the stream.
+ pub fn obj_id(&self) -> ObjectIdentifier {
+ self.dict.obj_id().unwrap_or_else(|| {
+ // In theory shouldn't ever happen, but could theoretically be
+ // triggered in a crafted PDF.
+ ObjectIdentifier::new(0, 0)
+ })
+ }
+
+ /// Return the filters that are applied to the stream.
+ pub fn filters(&self) -> SmallVec<[Filter; 2]> {
+ self.filters_and_params().filters
+ }
+
+ /// Return the decoded data of the stream.
+ ///
+ /// Note that the result of this method will not be cached, so calling it multiple
+ /// times is expensive.
+ pub fn decoded(&self) -> Result<Cow<'a, [u8]>, DecodeFailure> {
+ self.decoded_image(&ImageDecodeParams::default())
+ .map(|r| r.data)
+ }
+
+ /// Return the decoded data of the stream, and return image metadata
+ /// if available.
+ pub fn decoded_image(
+ &self,
+ image_params: &ImageDecodeParams,
+ ) -> Result<FilterResult<'a>, DecodeFailure> {
+ let data = self.raw_data();
+ let filters_and_params = self.filters_and_params();
+
+ let mut current: Option<FilterResult<'a>> = None;
+
+ for (filter, params) in filters_and_params
+ .filters
+ .iter()
+ .zip(filters_and_params.params.iter())
+ {
+ let new = filter.apply(
+ current.as_ref().map(|c| c.data.as_ref()).unwrap_or(&data),
+ params,
+ image_params,
+ )?;
+ current = Some(new);
+ }
+
+ Ok(current.unwrap_or(FilterResult {
+ data,
+ image_data: None,
+ }))
+ }
+}
+
+impl Debug for Stream<'_> {
+ fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
+ write!(f, "Stream (len: {:?})", self.data.len())
+ }
+}
+
+impl Skippable for Stream<'_> {
+ fn skip(_: &mut Reader<'_>, _: bool) -> Option<()> {
+ // A stream can never appear in a dict/array, so it should never be skipped.
+ warn!("attempted to skip a stream object");
+
+ None
+ }
+}
+
+impl<'a> Readable<'a> for Stream<'a> {
+ fn read(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<Self> {
+ let dict = r.read_with_context::<Dict<'_>>(ctx)?;
+
+ if dict.contains_key(F) {
+ warn!("encountered stream referencing external file, which is unsupported");
+
+ return None;
+ }
+
+ let offset = r.offset();
+ parse_proper(r, &dict)
+ .or_else(|| {
+ warn!("failed to parse stream, trying to parse it manually");
+
+ r.jump(offset);
+ parse_fallback(r, &dict)
+ })
+ .error_none("was unable to manually parse the stream")
+ }
+}
+
+#[derive(Debug, Copy, Clone)]
+/// A failure that can occur during decoding a data stream.
+pub enum DecodeFailure {
+ /// An image stream failed to decode.
+ ImageDecode,
+ /// A data stream failed to decode.
+ StreamDecode,
+ /// A failure occurred while decrypting a file.
+ Decryption,
+ /// An unknown failure occurred.
+ Unknown,
+}
+
+/// An image color space.
+#[derive(Debug, Copy, Clone)]
+pub enum ImageColorSpace {
+ /// Grayscale color space.
+ Gray,
+ /// RGB color space.
+ Rgb,
+ /// CMYK color space.
+ Cmyk,
+ /// An unknown color space.
+ Unknown(u8),
+}
+
+/// Additional data that is extracted from some image streams.
+pub struct ImageData {
+ /// An optional alpha channel of the image.
+ pub alpha: Option<Vec<u8>>,
+ /// The color space of the image.
+ pub color_space: Option<ImageColorSpace>,
+ /// The bits per component of the image.
+ pub bits_per_component: u8,
+ /// The width of the image.
+ pub width: u32,
+ /// The height of the image.
+ pub height: u32,
+}
+
+/// The result of applying a filter.
+pub struct FilterResult<'a> {
+ /// The decoded data.
+ pub data: Cow<'a, [u8]>,
+ /// Additional data that is extracted from JPX image streams.
+ pub image_data: Option<ImageData>,
+}
+
+impl FilterResult<'_> {
+ pub(crate) fn from_data(data: Vec<u8>) -> Self {
+ Self {
+ data: Cow::Owned(data),
+ image_data: None,
+ }
+ }
+}
+
+fn parse_proper<'a>(r: &mut Reader<'a>, dict: &Dict<'a>) -> Option<Stream<'a>> {
+ let length = dict.get::<u32>(LENGTH)?;
+
+ r.skip_white_spaces_and_comments();
+ r.forward_tag(b"stream")?;
+ r.forward_tag(b"\n")
+ .or_else(|| r.forward_tag(b"\r\n"))
+ .or_else(|| r.forward_tag(b"\r"))?;
+ let data = r.read_bytes(length as usize)?;
+ r.skip_white_spaces();
+ r.forward_tag(b"endstream")?;
+
+ Some(Stream::new(data, dict.clone()))
+}
+
+fn parse_fallback<'a>(r: &mut Reader<'a>, dict: &Dict<'a>) -> Option<Stream<'a>> {
+ let stream_offset = find_needle(r.tail()?, b"stream")?;
+ r.read_bytes(stream_offset)?;
+ r.forward_tag(b"stream")?;
+
+ r.forward_tag(b"\n")
+ .or_else(|| r.forward_tag(b"\r\n"))
+ // Technically not allowed, but no reason to not try it.
+ .or_else(|| r.forward_tag(b"\r"))?;
+
+ let tail = r.tail()?;
+ let endstream_offset = find_needle(tail, b"endstream")?;
+ let data_end = trim_trailing_ascii_whitespace(&tail[..endstream_offset]);
+ let data = tail.get(..data_end)?;
+
+ r.read_bytes(endstream_offset)?;
+ r.skip_white_spaces();
+ r.forward_tag(b"endstream")?;
+
+ Some(Stream::new(data, dict.clone()))
+}
+
+fn trim_trailing_ascii_whitespace(data: &[u8]) -> usize {
+ let mut end = data.len();
+
+ while data
+ .get(end.wrapping_sub(1))
+ .copied()
+ .is_some_and(is_white_space_character)
+ {
+ end -= 1;
+ }
+
+ end
+}
+
+impl<'a> TryFrom<Object<'a>> for Stream<'a> {
+ type Error = ();
+
+ fn try_from(value: Object<'a>) -> Result<Self, Self::Error> {
+ match value {
+ Object::Stream(s) => Ok(s),
+ _ => Err(()),
+ }
+ }
+}
+
+impl<'a> ObjectLike<'a> for Stream<'a> {}
+impl<'a> ObjectRefLike<'a> for Stream<'a> {
+ fn cast_ref<'b>(obj: &'b Object<'a>) -> Option<&'b Self> {
+ match obj {
+ Object::Stream(stream) => Some(stream),
+ _ => None,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::object::Stream;
+ use crate::reader::Reader;
+ use crate::reader::{ReaderContext, ReaderExt};
+
+ #[test]
+ fn stream() {
+ let data = b"<< /Length 10 >> stream\nabcdefghij\nendstream";
+ let mut r = Reader::new(data);
+ let stream = r
+ .read_with_context::<Stream<'_>>(&ReaderContext::dummy())
+ .unwrap();
+
+ assert_eq!(stream.data, b"abcdefghij");
+ }
+
+ #[test]
+ fn stream_fallback() {
+ let data = b"<< /Length 999 >> stream\nabcdefghij\nendstream";
+ let mut r = Reader::new(data);
+ let stream = r
+ .read_with_context::<Stream<'_>>(&ReaderContext::dummy())
+ .unwrap();
+
+ assert_eq!(stream.data, b"abcdefghij");
+ }
+}
diff --git a/vendor/hayro-syntax/src/object/string.rs b/vendor/hayro-syntax/src/object/string.rs
new file mode 100644
index 000000000..c168d5935
--- /dev/null
+++ b/vendor/hayro-syntax/src/object/string.rs
@@ -0,0 +1,548 @@
+//! Strings.
+
+use crate::crypto::DecryptionTarget;
+use crate::filter::ascii_hex;
+use crate::object::Object;
+use crate::object::macros::object;
+use crate::reader::Reader;
+use crate::reader::{Readable, ReaderContext, ReaderExt, Skippable};
+use crate::trivia::is_white_space_character;
+use alloc::vec::Vec;
+use core::borrow::Borrow;
+use core::hash::{Hash, Hasher};
+use core::ops::Deref;
+use smallvec::SmallVec;
+
+#[derive(Clone)]
+enum StringInner<'a> {
+ Borrowed(&'a [u8]),
+ Owned(SmallVec<[u8; 23]>),
+}
+
+impl AsRef<[u8]> for StringInner<'_> {
+ fn as_ref(&self) -> &[u8] {
+ match self {
+ Self::Borrowed(data) => data,
+ Self::Owned(data) => data,
+ }
+ }
+}
+
+/// A PDF string object.
+#[derive(Clone)]
+pub struct String<'a>(StringInner<'a>);
+
+impl<'a> String<'a> {
+ /// Returns the string data as a byte slice.
+ pub fn as_bytes(&self) -> &[u8] {
+ self.as_ref()
+ }
+}
+
+impl Deref for String<'_> {
+ type Target = [u8];
+
+ fn deref(&self) -> &Self::Target {
+ self.as_ref()
+ }
+}
+
+impl AsRef<[u8]> for String<'_> {
+ fn as_ref(&self) -> &[u8] {
+ match &self.0 {
+ StringInner::Borrowed(data) => data,
+ StringInner::Owned(data) => data,
+ }
+ }
+}
+
+impl Borrow<[u8]> for String<'_> {
+ fn borrow(&self) -> &[u8] {
+ self.as_ref()
+ }
+}
+
+impl PartialEq for String<'_> {
+ fn eq(&self, other: &Self) -> bool {
+ self.as_ref() == other.as_ref()
+ }
+}
+
+impl Eq for String<'_> {}
+
+impl Hash for String<'_> {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ self.as_ref().hash(state);
+ }
+}
+
+impl core::fmt::Debug for String<'_> {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ <[u8] as core::fmt::Debug>::fmt(self.as_ref(), f)
+ }
+}
+
+object!(String<'a>, String);
+
+impl Skippable for String<'_> {
+ fn skip(r: &mut Reader<'_>, _: bool) -> Option<()> {
+ match r.peek_byte()? {
+ b'<' => skip_hex(r),
+ b'(' => skip_literal(r),
+ _ => None,
+ }
+ }
+}
+
+impl<'a> Readable<'a> for String<'a> {
+ fn read(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<Self> {
+ let decoded = match r.peek_byte()? {
+ b'<' => StringInner::Owned(read_hex(r)?),
+ b'(' => read_literal(r)?,
+ _ => return None,
+ };
+
+ // Apply decryption if needed.
+ let final_data = if ctx.xref().needs_decryption(ctx) {
+ if let Some(obj_number) = ctx.obj_number() {
+ ctx.xref()
+ .decrypt(obj_number, decoded.as_ref(), DecryptionTarget::String)
+ .map(StringInner::from)
+ .unwrap_or(decoded)
+ } else {
+ decoded
+ }
+ } else {
+ decoded
+ };
+
+ Some(Self(final_data))
+ }
+}
+
+impl From<Vec<u8>> for StringInner<'_> {
+ fn from(value: Vec<u8>) -> Self {
+ Self::Owned(SmallVec::from_vec(value))
+ }
+}
+
+fn skip_hex(r: &mut Reader<'_>) -> Option<()> {
+ r.forward_tag(b"<")?;
+ while let Some(b) = r.peek_byte() {
+ let is_hex = b.is_ascii_hexdigit();
+ let is_whitespace = is_white_space_character(b);
+
+ if !is_hex && !is_whitespace {
+ break;
+ }
+
+ r.read_byte()?;
+ }
+ r.forward_tag(b">")?;
+
+ Some(())
+}
+
+fn read_hex(r: &mut Reader<'_>) -> Option<SmallVec<[u8; 23]>> {
+ let start = r.offset();
+ skip_hex(r)?;
+ let end = r.offset();
+
+ // Exclude outer brackets.
+ let raw = r.range(start + 1..end - 1)?;
+ let decoded = ascii_hex::decode_into(raw)?;
+
+ Some(decoded)
+}
+
+fn skip_literal(r: &mut Reader<'_>) -> Option<()> {
+ r.forward_tag(b"(")?;
+ let mut bracket_counter = 1;
+
+ while bracket_counter > 0 {
+ let byte = r.read_byte()?;
+
+ match byte {
+ b'\\' => {
+ let _ = r.read_byte()?;
+ }
+ b'(' => bracket_counter += 1,
+ b')' => bracket_counter -= 1,
+ _ => {}
+ };
+ }
+
+ Some(())
+}
+
+fn read_literal<'a>(r: &mut Reader<'a>) -> Option<StringInner<'a>> {
+ let start = r.offset();
+ skip_literal(r)?;
+ let end = r.offset();
+
+ // Exclude outer parentheses.
+ let data = r.range(start + 1..end - 1)?;
+
+ if !data.iter().any(|b| matches!(b, b'\\' | b'\n' | b'\r')) {
+ return Some(StringInner::Borrowed(data));
+ }
+
+ let mut r = Reader::new(data);
+ let mut result = SmallVec::new();
+
+ while let Some(byte) = r.read_byte() {
+ match byte {
+ b'\\' => {
+ let next = r.read_byte()?;
+
+ if is_octal_digit(next) {
+ let second = r.read_byte();
+ let third = r.read_byte();
+
+ let bytes = match (second, third) {
+ (Some(n1), Some(n2)) => match (is_octal_digit(n1), is_octal_digit(n2)) {
+ (true, true) => [next, n1, n2],
+ (true, _) => {
+ r.jump(r.offset() - 1);
+ [b'0', next, n1]
+ }
+ _ => {
+ r.jump(r.offset() - 2);
+ [b'0', b'0', next]
+ }
+ },
+ (Some(n1), None) => {
+ if is_octal_digit(n1) {
+ [b'0', next, n1]
+ } else {
+ r.jump(r.offset() - 1);
+ [b'0', b'0', next]
+ }
+ }
+ _ => [b'0', b'0', next],
+ };
+
+ let str = core::str::from_utf8(&bytes).unwrap();
+
+ if let Ok(num) = u8::from_str_radix(str, 8) {
+ result.push(num);
+ } else {
+ warn!("overflow occurred while parsing octal literal string");
+ }
+ } else {
+ match next {
+ b'n' => result.push(0xA),
+ b'r' => result.push(0xD),
+ b't' => result.push(0x9),
+ b'b' => result.push(0x8),
+ b'f' => result.push(0xC),
+ b'(' => result.push(b'('),
+ b')' => result.push(b')'),
+ b'\\' => result.push(b'\\'),
+ b'\n' | b'\r' => {
+ // A conforming reader shall disregard the REVERSE SOLIDUS
+ // and the end-of-line marker following it when reading
+ // the string; the resulting string value shall be
+ // identical to that which would be read if the string
+ // were not split.
+ r.skip_eol_characters();
+ }
+ _ => result.push(next),
+ }
+ }
+ }
+ b'(' | b')' => result.push(byte),
+ // An end-of-line marker appearing within a literal string
+ // without a preceding REVERSE SOLIDUS shall be treated as
+ // a byte value of (0Ah), irrespective of whether the end-of-line
+ // marker was a CARRIAGE RETURN (0Dh), a LINE FEED (0Ah), or both.
+ b'\n' | b'\r' => {
+ result.push(b'\n');
+ r.skip_eol_characters();
+ }
+ other => result.push(other),
+ }
+ }
+
+ Some(StringInner::Owned(result))
+}
+
+fn is_octal_digit(byte: u8) -> bool {
+ matches!(byte, b'0'..=b'7')
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::object::String;
+ use crate::reader::Reader;
+ use crate::reader::ReaderExt;
+
+ #[test]
+ fn hex_string_empty() {
+ assert_eq!(
+ Reader::new(b"<>")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ b""
+ );
+ }
+
+ #[test]
+ fn hex_string_1() {
+ assert_eq!(
+ Reader::new(b"<00010203>")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ &[0x00, 0x01, 0x02, 0x03]
+ );
+ }
+
+ #[test]
+ fn hex_string_2() {
+ assert_eq!(
+ Reader::new(b"<000102034>")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ &[0x00, 0x01, 0x02, 0x03, 0x40]
+ );
+ }
+
+ #[test]
+ fn hex_string_trailing_1() {
+ assert_eq!(
+ Reader::new(b"<000102034>dfgfg4")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ &[0x00, 0x01, 0x02, 0x03, 0x40]
+ );
+ }
+
+ #[test]
+ fn hex_string_trailing_2() {
+ assert_eq!(
+ Reader::new(b"<1 3 4>dfgfg4")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ &[0x13, 0x40]
+ );
+ }
+
+ #[test]
+ fn hex_string_trailing_3() {
+ assert_eq!(
+ Reader::new(b"<1>dfgfg4")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ &[0x10]
+ );
+ }
+
+ #[test]
+ fn hex_string_invalid_1() {
+ assert!(
+ Reader::new(b"<")
+ .read_without_context::<String<'_>>()
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn hex_string_invalid_2() {
+ assert!(
+ Reader::new(b"34AD")
+ .read_without_context::<String<'_>>()
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn literal_string_empty() {
+ assert_eq!(
+ Reader::new(b"()")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ b""
+ );
+ }
+
+ #[test]
+ fn literal_string_1() {
+ assert_eq!(
+ Reader::new(b"(Hi there.)")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ b"Hi there."
+ );
+ }
+
+ #[test]
+ fn literal_string_2() {
+ assert!(
+ Reader::new(b"(Hi \\777)")
+ .read_without_context::<String<'_>>()
+ .is_some()
+ );
+ }
+
+ #[test]
+ fn literal_string_3() {
+ assert_eq!(
+ Reader::new(b"(Hi ) there.)")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ b"Hi "
+ );
+ }
+
+ #[test]
+ fn literal_string_4() {
+ assert_eq!(
+ Reader::new(b"(Hi (()) there)")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ b"Hi (()) there"
+ );
+ }
+
+ #[test]
+ fn literal_string_5() {
+ assert_eq!(
+ Reader::new(b"(Hi \\()")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ b"Hi ("
+ );
+ }
+
+ #[test]
+ fn literal_string_6() {
+ assert_eq!(
+ Reader::new(b"(Hi \\\nthere)")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ b"Hi there"
+ );
+ }
+
+ #[test]
+ fn literal_string_7() {
+ assert_eq!(
+ Reader::new(b"(Hi \\05354)")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ b"Hi +54"
+ );
+ }
+
+ #[test]
+ fn literal_string_8() {
+ assert_eq!(
+ Reader::new(b"(\\3)")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ b"\x03"
+ );
+ }
+
+ #[test]
+ fn literal_string_9() {
+ assert_eq!(
+ Reader::new(b"(\\36)")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ b"\x1e"
+ );
+ }
+
+ #[test]
+ fn literal_string_10() {
+ assert_eq!(
+ Reader::new(b"(\\36ab)")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ b"\x1eab"
+ );
+ }
+
+ #[test]
+ fn literal_string_11() {
+ assert_eq!(
+ Reader::new(b"(\\00Y)")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ b"\0Y"
+ );
+ }
+
+ #[test]
+ fn literal_string_12() {
+ assert_eq!(
+ Reader::new(b"(\\0Y)")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ b"\0Y"
+ );
+ }
+
+ #[test]
+ fn literal_string_trailing() {
+ assert_eq!(
+ Reader::new(b"(Hi there.)abcde")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ b"Hi there."
+ );
+ }
+
+ #[test]
+ fn literal_string_invalid() {
+ assert_eq!(
+ Reader::new(b"(Hi \\778)")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ b"Hi \x3F8"
+ );
+ }
+
+ #[test]
+ fn string_1() {
+ assert_eq!(
+ Reader::new(b"(Hi there.)")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ b"Hi there."
+ );
+ }
+
+ #[test]
+ fn string_2() {
+ assert_eq!(
+ Reader::new(b"<00010203>")
+ .read_without_context::<String<'_>>()
+ .unwrap()
+ .as_bytes(),
+ &[0x00, 0x01, 0x02, 0x03]
+ );
+ }
+}
diff --git a/vendor/hayro-syntax/src/object/tuple.rs b/vendor/hayro-syntax/src/object/tuple.rs
new file mode 100644
index 000000000..4a7190e91
--- /dev/null
+++ b/vendor/hayro-syntax/src/object/tuple.rs
@@ -0,0 +1,174 @@
+use crate::object::r#ref::MaybeRef;
+use crate::object::{Object, ObjectLike};
+use crate::reader::Reader;
+use crate::reader::{Readable, ReaderContext, ReaderExt};
+use core::fmt::Debug;
+// Note that tuples don't correspond to any specific PDF object. Instead, they simply
+// represent a number of PDF objects that are only separated by whitespaces, i.e.
+// in an array. We only have those implementations so that it is easier to iterate
+// over tuples of items in a PDF array, which happens quite often.
+
+impl<'a, T, U> Readable<'a> for (T, U)
+where
+ T: ObjectLike<'a>,
+ U: ObjectLike<'a>,
+{
+ fn read(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<Self> {
+ r.skip_white_spaces_and_comments();
+ let t = r.read::<MaybeRef<T>>(ctx)?.resolve(ctx)?;
+ r.skip_white_spaces_and_comments();
+ let u = r.read::<MaybeRef<U>>(ctx)?.resolve(ctx)?;
+ Some((t, u))
+ }
+}
+
+impl<'a, T, U> TryFrom<Object<'a>> for (T, U)
+where
+ T: ObjectLike<'a>,
+ U: ObjectLike<'a>,
+{
+ type Error = ();
+
+ fn try_from(_: Object<'a>) -> Result<Self, Self::Error> {
+ Err(())
+ }
+}
+
+impl<'a, T, U> ObjectLike<'a> for (T, U)
+where
+ T: ObjectLike<'a> + Debug + Clone,
+ U: ObjectLike<'a> + Debug + Clone,
+{
+}
+
+impl<'a, T, U, V> Readable<'a> for (T, U, V)
+where
+ T: ObjectLike<'a>,
+ U: ObjectLike<'a>,
+ V: ObjectLike<'a>,
+{
+ fn read(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<Self> {
+ r.skip_white_spaces_and_comments();
+ let t = r.read::<MaybeRef<T>>(ctx)?.resolve(ctx)?;
+ r.skip_white_spaces_and_comments();
+ let u = r.read::<MaybeRef<U>>(ctx)?.resolve(ctx)?;
+ r.skip_white_spaces_and_comments();
+ let v = r.read::<MaybeRef<V>>(ctx)?.resolve(ctx)?;
+
+ Some((t, u, v))
+ }
+}
+
+impl<'a, T, U, V> TryFrom<Object<'a>> for (T, U, V)
+where
+ T: ObjectLike<'a>,
+ U: ObjectLike<'a>,
+ V: ObjectLike<'a>,
+{
+ type Error = ();
+
+ fn try_from(_: Object<'a>) -> Result<Self, Self::Error> {
+ Err(())
+ }
+}
+
+impl<'a, T, U, V> ObjectLike<'a> for (T, U, V)
+where
+ T: ObjectLike<'a> + Debug + Clone,
+ U: ObjectLike<'a> + Debug + Clone,
+ V: ObjectLike<'a> + Debug + Clone,
+{
+}
+
+impl<'a, T, U, V, W> Readable<'a> for (T, U, V, W)
+where
+ T: ObjectLike<'a>,
+ U: ObjectLike<'a>,
+ V: ObjectLike<'a>,
+ W: ObjectLike<'a>,
+{
+ fn read(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<Self> {
+ r.skip_white_spaces_and_comments();
+ let t = r.read::<MaybeRef<T>>(ctx)?.resolve(ctx)?;
+ r.skip_white_spaces_and_comments();
+ let u = r.read::<MaybeRef<U>>(ctx)?.resolve(ctx)?;
+ r.skip_white_spaces_and_comments();
+ let v = r.read::<MaybeRef<V>>(ctx)?.resolve(ctx)?;
+ r.skip_white_spaces_and_comments();
+ let w = r.read::<MaybeRef<W>>(ctx)?.resolve(ctx)?;
+
+ Some((t, u, v, w))
+ }
+}
+
+impl<'a, T, U, V, W> TryFrom<Object<'a>> for (T, U, V, W)
+where
+ T: ObjectLike<'a>,
+ U: ObjectLike<'a>,
+ V: ObjectLike<'a>,
+ W: ObjectLike<'a>,
+{
+ type Error = ();
+
+ fn try_from(_: Object<'a>) -> Result<Self, Self::Error> {
+ Err(())
+ }
+}
+
+impl<'a, T, U, V, W> ObjectLike<'a> for (T, U, V, W)
+where
+ T: ObjectLike<'a> + Debug + Clone,
+ U: ObjectLike<'a> + Debug + Clone,
+ V: ObjectLike<'a> + Debug + Clone,
+ W: ObjectLike<'a> + Debug + Clone,
+{
+}
+
+impl<'a, T, U, V, W, X> Readable<'a> for (T, U, V, W, X)
+where
+ T: ObjectLike<'a>,
+ U: ObjectLike<'a>,
+ V: ObjectLike<'a>,
+ W: ObjectLike<'a>,
+ X: ObjectLike<'a>,
+{
+ fn read(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<Self> {
+ r.skip_white_spaces_and_comments();
+ let t = r.read::<MaybeRef<T>>(ctx)?.resolve(ctx)?;
+ r.skip_white_spaces_and_comments();
+ let u = r.read::<MaybeRef<U>>(ctx)?.resolve(ctx)?;
+ r.skip_white_spaces_and_comments();
+ let v = r.read::<MaybeRef<V>>(ctx)?.resolve(ctx)?;
+ r.skip_white_spaces_and_comments();
+ let w = r.read::<MaybeRef<W>>(ctx)?.resolve(ctx)?;
+ r.skip_white_spaces_and_comments();
+ let x = r.read::<MaybeRef<X>>(ctx)?.resolve(ctx)?;
+
+ Some((t, u, v, w, x))
+ }
+}
+
+impl<'a, T, U, V, W, X> TryFrom<Object<'a>> for (T, U, V, W, X)
+where
+ T: ObjectLike<'a>,
+ U: ObjectLike<'a>,
+ V: ObjectLike<'a>,
+ W: ObjectLike<'a>,
+ X: ObjectLike<'a>,
+{
+ type Error = ();
+
+ fn try_from(_: Object<'a>) -> Result<Self, Self::Error> {
+ Err(())
+ }
+}
+
+impl<'a, T, U, V, W, X> ObjectLike<'a> for (T, U, V, W, X)
+where
+ T: ObjectLike<'a> + Debug + Clone,
+ U: ObjectLike<'a> + Debug + Clone,
+ V: ObjectLike<'a> + Debug + Clone,
+ W: ObjectLike<'a> + Debug + Clone,
+ X: ObjectLike<'a> + Debug + Clone,
+{
+}
diff --git a/vendor/hayro-syntax/src/page.rs b/vendor/hayro-syntax/src/page.rs
new file mode 100644
index 000000000..8225780de
--- /dev/null
+++ b/vendor/hayro-syntax/src/page.rs
@@ -0,0 +1,565 @@
+//! Reading the pages of a PDF document.
+
+use crate::content::{TypedIter, UntypedIter};
+use crate::object::Array;
+use crate::object::Dict;
+use crate::object::Name;
+use crate::object::Rect;
+use crate::object::Stream;
+use crate::object::dict::keys::*;
+use crate::object::{Object, ObjectLike};
+use crate::reader::ReaderContext;
+use crate::sync::OnceLock;
+use crate::transform::Transform;
+use crate::util::FloatExt;
+use crate::xref::XRef;
+use alloc::boxed::Box;
+use alloc::collections::BTreeSet;
+use crate::object::ObjectIdentifier;
+use alloc::vec;
+use alloc::vec::Vec;
+use core::ops::Deref;
+
+/// Attributes that can be inherited.
+#[derive(Debug, Clone)]
+struct PagesContext {
+ media_box: Option<Rect>,
+ crop_box: Option<Rect>,
+ rotate: Option<i32>,
+}
+
+impl PagesContext {
+ fn new() -> Self {
+ Self {
+ media_box: None,
+ crop_box: None,
+ rotate: None,
+ }
+ }
+}
+
+/// A structure holding the pages of a PDF document.
+pub struct Pages<'a> {
+ pages: Vec<Page<'a>>,
+ xref: &'a XRef,
+}
+
+impl<'a> Pages<'a> {
+ /// Create a new `Pages` object.
+ pub(crate) fn new(
+ pages_dict: &Dict<'a>,
+ ctx: &ReaderContext<'a>,
+ xref: &'a XRef,
+ ) -> Option<Self> {
+ let mut pages = vec![];
+ let pages_ctx = PagesContext::new();
+ // PrintCraft patch: guard against page-tree cycles (a `/Kids` entry pointing back up
+ // the tree), which otherwise recurse until the stack overflows.
+ let mut visited = BTreeSet::new();
+ resolve_pages(
+ pages_dict,
+ &mut pages,
+ pages_ctx,
+ Resources::new(Dict::empty(), None, ctx),
+ &mut visited,
+ 0,
+ )?;
+
+ Some(Self { pages, xref })
+ }
+
+ /// Create a new `Pages` object by bruteforce-searching.
+ ///
+ /// Of course this could result in the order of pages being messed up, but
+ /// this is still better than nothing.
+ pub(crate) fn new_brute_force(ctx: &ReaderContext<'a>, xref: &'a XRef) -> Option<Self> {
+ let mut pages = vec![];
+
+ for object in xref.objects() {
+ if let Some(dict) = object.into_dict()
+ && let Some(page) = Page::new(
+ &dict,
+ &PagesContext::new(),
+ Resources::new(Dict::empty(), None, ctx),
+ true,
+ )
+ {
+ pages.push(page);
+ }
+ }
+
+ if pages.is_empty() {
+ return None;
+ }
+
+ Some(Self { pages, xref })
+ }
+
+ /// Return the xref table (of the document the pages belong to).
+ pub fn xref(&self) -> &'a XRef {
+ self.xref
+ }
+}
+
+impl<'a> Deref for Pages<'a> {
+ type Target = [Page<'a>];
+
+ fn deref(&self) -> &Self::Target {
+ &self.pages
+ }
+}
+
+/// PrintCraft patch: maximum page-tree depth (direct dictionaries have no id to track).
+const MAX_PAGE_TREE_DEPTH: usize = 256;
+
+fn resolve_pages<'a>(
+ pages_dict: &Dict<'a>,
+ entries: &mut Vec<Page<'a>>,
+ mut ctx: PagesContext,
+ resources: Resources<'a>,
+ visited: &mut BTreeSet<ObjectIdentifier>,
+ depth: usize,
+) -> Option<()> {
+ // PrintCraft patch: skip nodes already visited and absurdly deep trees.
+ if depth > MAX_PAGE_TREE_DEPTH {
+ return None;
+ }
+ if let Some(id) = pages_dict.obj_id()
+ && !visited.insert(id)
+ {
+ return None;
+ }
+ if let Some(media_box) = pages_dict.get::<Rect>(MEDIA_BOX) {
+ ctx.media_box = Some(media_box);
+ }
+
+ if let Some(crop_box) = pages_dict.get::<Rect>(CROP_BOX) {
+ ctx.crop_box = Some(crop_box);
+ }
+
+ if let Some(rotate) = pages_dict.get::<i32>(ROTATE) {
+ ctx.rotate = Some(rotate);
+ }
+
+ let resources = Resources::from_parent(
+ pages_dict.get::<Dict<'_>>(RESOURCES).unwrap_or_default(),
+ resources.clone(),
+ );
+
+ let kids = pages_dict.get::<Array<'a>>(KIDS)?;
+
+ for dict in kids.iter::<Dict<'_>>() {
+ match dict.get::<Name<'_>>(TYPE).as_deref() {
+ Some(PAGES) => {
+ resolve_pages(&dict, entries, ctx.clone(), resources.clone(), visited, depth + 1);
+ }
+ // Let's be lenient and assume it's a `Page` in case it's `None` or something else
+ // (see corpus test case 0083781).
+ _ => {
+ if let Some(page) = Page::new(&dict, &ctx, resources.clone(), false) {
+ entries.push(page);
+ }
+ }
+ }
+ }
+
+ Some(())
+}
+
+/// The rotation of the page.
+#[derive(Debug, Copy, Clone)]
+pub enum Rotation {
+ /// No rotation.
+ None,
+ /// A rotation of 90 degrees.
+ Horizontal,
+ /// A rotation of 180 degrees.
+ Flipped,
+ /// A rotation of 270 degrees.
+ FlippedHorizontal,
+}
+
+/// A PDF page.
+pub struct Page<'a> {
+ inner: Dict<'a>,
+ media_box: Rect,
+ crop_box: Rect,
+ rotation: Rotation,
+ page_streams: OnceLock<Option<Vec<u8>>>,
+ resources: Resources<'a>,
+ ctx: ReaderContext<'a>,
+}
+
+impl<'a> Page<'a> {
+ fn new(
+ dict: &Dict<'a>,
+ ctx: &PagesContext,
+ resources: Resources<'a>,
+ brute_force: bool,
+ ) -> Option<Self> {
+ // In general, pages without content are allowed, but in case we are brute-forcing
+ // we ignore them.
+ if brute_force && !dict.contains_key(CONTENTS) {
+ return None;
+ }
+
+ let media_box = dict.get::<Rect>(MEDIA_BOX).or(ctx.media_box).unwrap_or(A4);
+
+ let crop_box = dict
+ .get::<Rect>(CROP_BOX)
+ .or(ctx.crop_box)
+ .unwrap_or(media_box);
+
+ let rotation = match dict
+ .get::<i32>(ROTATE)
+ .or(ctx.rotate)
+ .unwrap_or(0)
+ .rem_euclid(360)
+ {
+ 0 => Rotation::None,
+ 90 => Rotation::Horizontal,
+ 180 => Rotation::Flipped,
+ 270 => Rotation::FlippedHorizontal,
+ _ => Rotation::None,
+ };
+
+ let ctx = resources.ctx.clone();
+ let resources = Resources::from_parent(
+ dict.get::<Dict<'_>>(RESOURCES).unwrap_or_default(),
+ resources,
+ );
+
+ Some(Self {
+ inner: dict.clone(),
+ media_box,
+ crop_box,
+ rotation,
+ page_streams: OnceLock::new(),
+ resources,
+ ctx,
+ })
+ }
+
+ fn operations_impl(&self) -> Option<UntypedIter<'_>> {
+ let stream = self.page_stream()?;
+ let iter = UntypedIter::new(stream);
+
+ Some(iter)
+ }
+
+ /// Return the decoded content stream of the page.
+ pub fn page_stream(&self) -> Option<&[u8]> {
+ let convert_single = |s: Stream<'_>| {
+ let data = s.decoded().ok()?;
+ Some(data.to_vec())
+ };
+
+ self.page_streams
+ .get_or_init(|| {
+ if let Some(stream) = self.inner.get::<Stream<'_>>(CONTENTS) {
+ convert_single(stream)
+ } else if let Some(array) = self.inner.get::<Array<'_>>(CONTENTS) {
+ let streams = array.iter::<Stream<'_>>().flat_map(convert_single);
+
+ let mut collected = vec![];
+
+ for stream in streams {
+ collected.extend(stream);
+ // Streams must have at least one whitespace in-between.
+ collected.push(b' ');
+ }
+
+ Some(collected)
+ } else {
+ warn!("contents entry of page was neither stream nor array of streams");
+
+ None
+ }
+ })
+ .as_ref()
+ .map(|d| d.as_slice())
+ }
+
+ /// Get the resources of the page.
+ pub fn resources(&self) -> &Resources<'a> {
+ &self.resources
+ }
+
+ /// Get the media box of the page.
+ pub fn media_box(&self) -> Rect {
+ self.media_box
+ }
+
+ /// Get the rotation of the page.
+ pub fn rotation(&self) -> Rotation {
+ self.rotation
+ }
+
+ /// Get the crop box of the page.
+ pub fn crop_box(&self) -> Rect {
+ self.crop_box
+ }
+
+ /// Return the intersection of crop box and media box.
+ pub fn intersected_crop_box(&self) -> Rect {
+ self.crop_box().intersect(self.media_box())
+ }
+
+ /// Return the base dimensions of the page (same as `intersected_crop_box`, but with special
+ /// handling applied for zero-area pages).
+ pub fn base_dimensions(&self) -> (f32, f32) {
+ let crop_box = self.intersected_crop_box();
+
+ if (crop_box.width() as f32).is_nearly_zero() || (crop_box.height() as f32).is_nearly_zero()
+ {
+ (A4.width() as f32, A4.height() as f32)
+ } else {
+ (
+ crop_box.width().max(1.0) as f32,
+ crop_box.height().max(1.0) as f32,
+ )
+ }
+ }
+
+ /// Return the with and height of the page that should be assumed when rendering the page.
+ ///
+ /// Depending on the document, it is either based on the media box or the crop box
+ /// of the page. In addition to that, it also takes the rotation of the page into account.
+ pub fn render_dimensions(&self) -> (f32, f32) {
+ let (mut base_width, mut base_height) = self.base_dimensions();
+
+ if matches!(
+ self.rotation(),
+ Rotation::Horizontal | Rotation::FlippedHorizontal
+ ) {
+ core::mem::swap(&mut base_width, &mut base_height);
+ }
+
+ (base_width, base_height)
+ }
+
+ /// Return an untyped iterator over the operators of the page's content stream.
+ pub fn operations(&self) -> UntypedIter<'_> {
+ self.operations_impl().unwrap_or(UntypedIter::empty())
+ }
+
+ /// Get the raw dictionary of the page.
+ pub fn raw(&self) -> &Dict<'a> {
+ &self.inner
+ }
+
+ /// Get the xref table (of the document the page belongs to).
+ pub fn xref(&self) -> &'a XRef {
+ self.ctx.xref()
+ }
+
+ /// Return a typed iterator over the operators of the page's content stream.
+ pub fn typed_operations(&self) -> TypedIter<'_> {
+ TypedIter::from_untyped(self.operations())
+ }
+
+ /// Return the initial transform that should be applied when rendering.
+ ///
+ /// This accounts for the mismatch between PDF's y-up and most renderers'
+ /// y-down coordinate system, the rotation of the page and the offset of
+ /// the crop box.
+ pub fn initial_transform(&self, invert_y: bool) -> Transform {
+ let crop_box = self.intersected_crop_box();
+ let (_, base_height) = self.base_dimensions();
+ let (width, height) = self.render_dimensions();
+
+ let horizontal_t = Transform::ROTATE_CW_90 * Transform::translate((0.0, -width as f64));
+ let flipped_horizontal_t =
+ Transform::translate((0.0, height as f64)) * Transform::ROTATE_CCW_90;
+
+ let rotation_transform = match self.rotation() {
+ Rotation::None => Transform::IDENTITY,
+ Rotation::Horizontal => {
+ if invert_y {
+ horizontal_t
+ } else {
+ flipped_horizontal_t
+ }
+ }
+ Rotation::Flipped => {
+ Transform::scale(-1.0) * Transform::translate((-width as f64, -height as f64))
+ }
+ Rotation::FlippedHorizontal => {
+ if invert_y {
+ flipped_horizontal_t
+ } else {
+ horizontal_t
+ }
+ }
+ };
+
+ let inversion_transform = if invert_y {
+ Transform::new([1.0, 0.0, 0.0, -1.0, 0.0, base_height as f64])
+ } else {
+ Transform::IDENTITY
+ };
+
+ rotation_transform
+ * inversion_transform
+ * Transform::translate((-crop_box.x0, -crop_box.y0))
+ }
+}
+
+/// A structure keeping track of the resources of a page.
+#[derive(Clone, Debug)]
+pub struct Resources<'a> {
+ parent: Option<Box<Self>>,
+ ctx: ReaderContext<'a>,
+ /// The raw dictionary of external graphics states.
+ pub ext_g_states: Dict<'a>,
+ /// The raw dictionary of fonts.
+ pub fonts: Dict<'a>,
+ /// The raw dictionary of properties.
+ pub properties: Dict<'a>,
+ /// The raw dictionary of color spaces.
+ pub color_spaces: Dict<'a>,
+ /// The raw dictionary of x objects.
+ pub x_objects: Dict<'a>,
+ /// The raw dictionary of patterns.
+ pub patterns: Dict<'a>,
+ /// The raw dictionary of shadings.
+ pub shadings: Dict<'a>,
+}
+
+impl<'a> Resources<'a> {
+ /// Create a new `Resources` object from a dictionary with a parent.
+ pub fn from_parent(resources: Dict<'a>, parent: Self) -> Self {
+ let ctx = parent.ctx.clone();
+
+ Self::new(resources, Some(parent), &ctx)
+ }
+
+ /// Create a new `Resources` object.
+ pub(crate) fn new(resources: Dict<'a>, parent: Option<Self>, ctx: &ReaderContext<'a>) -> Self {
+ let ext_g_states = resources.get::<Dict<'_>>(EXT_G_STATE).unwrap_or_default();
+ let fonts = resources.get::<Dict<'_>>(FONT).unwrap_or_default();
+ let color_spaces = resources.get::<Dict<'_>>(COLORSPACE).unwrap_or_default();
+ let x_objects = resources.get::<Dict<'_>>(XOBJECT).unwrap_or_default();
+ let patterns = resources.get::<Dict<'_>>(PATTERN).unwrap_or_default();
+ let shadings = resources.get::<Dict<'_>>(SHADING).unwrap_or_default();
+ let properties = resources.get::<Dict<'_>>(PROPERTIES).unwrap_or_default();
+
+ let parent = parent.map(Box::new);
+
+ Self {
+ parent,
+ ext_g_states,
+ fonts,
+ color_spaces,
+ properties,
+ x_objects,
+ patterns,
+ shadings,
+ ctx: ctx.clone(),
+ }
+ }
+
+ fn get_resource<T: ObjectLike<'a>>(&self, name: &Name<'_>, dict: &Dict<'a>) -> Option<T> {
+ dict.get::<T>(name.deref())
+ }
+
+ /// Get the parent in the resource, chain, if available.
+ pub fn parent(&self) -> Option<&Self> {
+ self.parent.as_deref()
+ }
+
+ /// Get an external graphics state by name.
+ pub fn get_ext_g_state(&self, name: &Name<'_>) -> Option<Dict<'a>> {
+ self.get_resource::<Dict<'_>>(name, &self.ext_g_states)
+ .or_else(|| self.parent.as_ref().and_then(|p| p.get_ext_g_state(name)))
+ }
+
+ /// Get a color space by name.
+ pub fn get_color_space(&self, name: &Name<'_>) -> Option<Object<'a>> {
+ self.get_resource::<Object<'_>>(name, &self.color_spaces)
+ .or_else(|| self.parent.as_ref().and_then(|p| p.get_color_space(name)))
+ }
+
+ /// Get a font by name.
+ pub fn get_font(&self, name: &Name<'_>) -> Option<Dict<'a>> {
+ self.get_resource::<Dict<'_>>(name, &self.fonts)
+ .or_else(|| self.parent.as_ref().and_then(|p| p.get_font(name)))
+ }
+
+ /// Get a pattern by name.
+ pub fn get_pattern(&self, name: &Name<'_>) -> Option<Object<'a>> {
+ self.get_resource::<Object<'_>>(name, &self.patterns)
+ .or_else(|| self.parent.as_ref().and_then(|p| p.get_pattern(name)))
+ }
+
+ /// Get an x object by name.
+ pub fn get_x_object(&self, name: &Name<'_>) -> Option<Stream<'a>> {
+ self.get_resource::<Stream<'_>>(name, &self.x_objects)
+ .or_else(|| self.parent.as_ref().and_then(|p| p.get_x_object(name)))
+ }
+
+ /// Get a shading by name.
+ pub fn get_shading(&self, name: &Name<'_>) -> Option<Object<'a>> {
+ self.get_resource::<Object<'_>>(name, &self.shadings)
+ .or_else(|| self.parent.as_ref().and_then(|p| p.get_shading(name)))
+ }
+}
+
+// <https://github.com/apache/pdfbox/blob/a53a70db16ea3133994120bcf1e216b9e760c05b/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/common/PDRectangle.java#L38>
+const POINTS_PER_INCH: f64 = 72.0;
+const POINTS_PER_MM: f64 = 1.0 / (10.0 * 2.54) * POINTS_PER_INCH;
+
+/// The dimension of an A4 page.
+pub const A4: Rect = Rect {
+ x0: 0.0,
+ y0: 0.0,
+ x1: 210.0 * POINTS_PER_MM,
+ y1: 297.0 * POINTS_PER_MM,
+};
+
+pub(crate) mod cached {
+ use crate::page::Pages;
+ use crate::reader::ReaderContext;
+ use crate::xref::XRef;
+ use core::ops::Deref;
+
+ // Keep in sync with the implementation in `sync`. We duplicate it here
+ // to make it more visible since we have unsafe code here.
+ #[cfg(feature = "std")]
+ pub(crate) use std::sync::Arc;
+
+ #[cfg(not(feature = "std"))]
+ pub(crate) use alloc::rc::Rc as Arc;
+
+ pub(crate) struct CachedPages {
+ pages: Pages<'static>,
+ // NOTE: `pages` references the data in `xref`, so it's important that `xref`
+ // appears after `pages` in the struct definition to ensure correct drop order.
+ _xref: Arc<XRef>,
+ }
+
+ impl CachedPages {
+ pub(crate) fn new(xref: Arc<XRef>) -> Option<Self> {
+ // SAFETY:
+ // - The XRef's location is stable in memory:
+ // - We wrapped it in a `Arc` (or `Rc` in `no_std`), which implements `StableDeref`.
+ // - The struct owns the `Arc`, ensuring that the inner value is not dropped during the whole
+ // duration.
+ // - The internal 'static lifetime is not leaked because its rewritten
+ // to the self-lifetime in `pages()`.
+ let xref_reference: &'static XRef = unsafe { core::mem::transmute(xref.deref()) };
+
+ let ctx = ReaderContext::new(xref_reference, false);
+ let pages = xref_reference
+ .get_with(xref.trailer_data().pages_ref, &ctx)
+ .and_then(|p| Pages::new(&p, &ctx, xref_reference))
+ .or_else(|| Pages::new_brute_force(&ctx, xref_reference))?;
+
+ Some(Self { pages, _xref: xref })
+ }
+
+ pub(crate) fn get(&self) -> &Pages<'_> {
+ &self.pages
+ }
+ }
+}
diff --git a/vendor/hayro-syntax/src/pdf.rs b/vendor/hayro-syntax/src/pdf.rs
new file mode 100644
index 000000000..c196cb14a
--- /dev/null
+++ b/vendor/hayro-syntax/src/pdf.rs
@@ -0,0 +1,185 @@
+//! The starting point for reading PDF files.
+
+use crate::PdfData;
+use crate::object::Object;
+use crate::page::Pages;
+use crate::page::cached::CachedPages;
+use crate::reader::Reader;
+use crate::sync::Arc;
+use crate::xref::{XRef, XRefError, fallback, root_xref};
+
+pub use crate::crypto::DecryptionError;
+use crate::metadata::Metadata;
+
+/// A PDF file.
+pub struct Pdf {
+ xref: Arc<XRef>,
+ header_version: PdfVersion,
+ pages: CachedPages,
+ data: PdfData,
+}
+
+/// An error that occurred while loading a PDF file.
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
+pub enum LoadPdfError {
+ /// An error occurred while processing an encrypted document.
+ Decryption(DecryptionError),
+ /// The PDF was invalid or could not be parsed due to some other unknown reason.
+ Invalid,
+}
+
+#[allow(clippy::len_without_is_empty)]
+impl Pdf {
+ /// Try to read the given PDF file.
+ ///
+ /// Returns `Err` if it was unable to read it.
+ pub fn new(data: impl Into<PdfData>) -> Result<Self, LoadPdfError> {
+ Self::new_with_password(data, "")
+ }
+
+ /// Try to read the given PDF file with a password.
+ ///
+ /// Returns `Err` if it was unable to read it or if the password is incorrect.
+ pub fn new_with_password(
+ data: impl Into<PdfData>,
+ password: &str,
+ ) -> Result<Self, LoadPdfError> {
+ let data = data.into();
+ let password = password.as_bytes();
+ let version = find_version(data.as_ref()).unwrap_or(PdfVersion::Pdf10);
+ let xref = match root_xref(data.clone(), password) {
+ Ok(x) => x,
+ Err(e) => match e {
+ XRefError::Unknown => {
+ fallback(data.clone(), password).ok_or(LoadPdfError::Invalid)?
+ }
+ XRefError::Encryption(e) => return Err(LoadPdfError::Decryption(e)),
+ },
+ };
+ let xref = Arc::new(xref);
+
+ let pages = CachedPages::new(xref.clone()).ok_or(LoadPdfError::Invalid)?;
+
+ Ok(Self {
+ xref,
+ header_version: version,
+ pages,
+ data,
+ })
+ }
+
+ /// Return the number of objects present in the PDF file.
+ pub fn len(&self) -> usize {
+ self.xref.len()
+ }
+
+ /// Return an iterator over all objects defined in the PDF file.
+ pub fn objects(&self) -> impl IntoIterator<Item = Object<'_>> {
+ self.xref.objects()
+ }
+
+ /// Return the version of the PDF file.
+ pub fn version(&self) -> PdfVersion {
+ self.xref
+ .trailer_data()
+ .version
+ .unwrap_or(self.header_version)
+ }
+
+ /// Return the underlying data of the PDF file.
+ pub fn data(&self) -> &PdfData {
+ &self.data
+ }
+
+ /// Return the pages of the PDF file.
+ pub fn pages(&self) -> &Pages<'_> {
+ self.pages.get()
+ }
+
+ /// Return the xref of the PDF file.
+ pub fn xref(&self) -> &XRef {
+ &self.xref
+ }
+
+ /// Return the metadata in the document information dictionary of the document.
+ pub fn metadata(&self) -> &Metadata {
+ self.xref.metadata()
+ }
+}
+
+fn find_version(data: &[u8]) -> Option<PdfVersion> {
+ let data = &data[..data.len().min(2000)];
+ let mut r = Reader::new(data);
+
+ while r.forward_tag(b"%PDF-").is_none() {
+ r.read_byte()?;
+ }
+
+ PdfVersion::from_bytes(r.tail()?)
+}
+
+/// The version of a PDF document.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
+pub enum PdfVersion {
+ /// PDF 1.0.
+ Pdf10,
+ /// PDF 1.1.
+ Pdf11,
+ /// PDF 1.2.
+ Pdf12,
+ /// PDF 1.3.
+ Pdf13,
+ /// PDF 1.4.
+ Pdf14,
+ /// PDF 1.5.
+ Pdf15,
+ /// PDF 1.6.
+ Pdf16,
+ /// PDF 1.7.
+ Pdf17,
+ /// PDF 2.0.
+ Pdf20,
+}
+
+impl PdfVersion {
+ pub(crate) fn from_bytes(bytes: &[u8]) -> Option<Self> {
+ match bytes.get(..3)? {
+ b"1.0" => Some(Self::Pdf10),
+ b"1.1" => Some(Self::Pdf11),
+ b"1.2" => Some(Self::Pdf12),
+ b"1.3" => Some(Self::Pdf13),
+ b"1.4" => Some(Self::Pdf14),
+ b"1.5" => Some(Self::Pdf15),
+ b"1.6" => Some(Self::Pdf16),
+ b"1.7" => Some(Self::Pdf17),
+ b"2.0" => Some(Self::Pdf20),
+ _ => None,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::pdf::{Pdf, PdfVersion};
+
+ #[test]
+ fn issue_49() {
+ let _ = Pdf::new(Vec::new());
+ }
+
+ #[test]
+ fn pdf_version_header() {
+ let data = std::fs::read("../hayro-tests/downloads/pdfjs/alphatrans.pdf").unwrap();
+ let pdf = Pdf::new(data).unwrap();
+
+ assert_eq!(pdf.version(), PdfVersion::Pdf17);
+ }
+
+ #[test]
+ fn pdf_version_catalog() {
+ let data = std::fs::read("../hayro-tests/downloads/pdfbox/2163.pdf").unwrap();
+ let pdf = Pdf::new(data).unwrap();
+
+ assert_eq!(pdf.version(), PdfVersion::Pdf14);
+ }
+}
diff --git a/vendor/hayro-syntax/src/reader.rs b/vendor/hayro-syntax/src/reader.rs
new file mode 100644
index 000000000..818f767f7
--- /dev/null
+++ b/vendor/hayro-syntax/src/reader.rs
@@ -0,0 +1,241 @@
+//! Reading bytes and PDF objects from data.
+
+use crate::object::ObjectIdentifier;
+use crate::sync::Arc;
+use crate::trivia::{Comment, is_eol_character, is_white_space_character};
+use crate::xref::XRef;
+use smallvec::{SmallVec, smallvec};
+
+pub use crate::byte_reader::Reader;
+
+/// Extension trait for the `Reader` struct.
+pub trait ReaderExt<'a> {
+ fn read<T: Readable<'a>>(&mut self, ctx: &ReaderContext<'a>) -> Option<T>;
+ fn read_with_context<T: Readable<'a>>(&mut self, ctx: &ReaderContext<'a>) -> Option<T>;
+ fn read_without_context<T: Readable<'a>>(&mut self) -> Option<T>;
+ fn skip<T: Skippable>(&mut self, is_content_stream: bool) -> Option<&'a [u8]>;
+ fn skip_white_spaces(&mut self);
+ fn read_white_space(&mut self) -> Option<()>;
+ fn skip_eol_characters(&mut self);
+ fn skip_white_spaces_and_comments(&mut self);
+}
+
+impl<'a> ReaderExt<'a> for Reader<'a> {
+ // Note: If `PLAIN` is true, it means that the data we are about to read _might_ contain
+ // an object reference instead of an actual object. if `PLAIN` is false, then an object
+ // reference cannot occur. The main reason we make this distinction is that when parsing
+ // a number, we cannot unambiguously distinguish whether it's a real number or the
+ // start of an object reference. In content streams, object references cannot appear,
+ // so in order to speed this up we set `PLAIN` to false, meaning that as soon as we
+ // encounter a number we know it's a number, and don't need to do a look-ahead to ensure
+ // that it's not an object reference.
+ #[inline]
+ fn read<T: Readable<'a>>(&mut self, ctx: &ReaderContext<'a>) -> Option<T> {
+ let old_offset = self.offset;
+
+ T::read(self, ctx).or_else(|| {
+ self.offset = old_offset;
+
+ None
+ })
+ }
+
+ #[inline]
+ fn read_with_context<T: Readable<'a>>(&mut self, ctx: &ReaderContext<'a>) -> Option<T> {
+ self.read::<T>(ctx)
+ }
+
+ #[inline]
+ fn read_without_context<T: Readable<'a>>(&mut self) -> Option<T> {
+ self.read::<T>(ReaderContext::dummy_ref())
+ }
+
+ #[inline]
+ fn skip<T: Skippable>(&mut self, is_content_stream: bool) -> Option<&'a [u8]> {
+ let old_offset = self.offset;
+
+ T::skip(self, is_content_stream).or_else(|| {
+ self.offset = old_offset;
+ None
+ })?;
+
+ self.data.get(old_offset..self.offset)
+ }
+
+ #[inline]
+ fn skip_white_spaces(&mut self) {
+ while let Some(b) = self.peek_byte() {
+ if is_white_space_character(b) {
+ self.forward();
+ } else {
+ return;
+ }
+ }
+ }
+
+ #[inline]
+ fn read_white_space(&mut self) -> Option<()> {
+ if is_white_space_character(self.peek_byte()?) {
+ let w = self.read_byte()?;
+
+ if w == b'\r' && self.peek_byte().is_some_and(|b| b == b'\n') {
+ self.read_byte()?;
+ }
+
+ return Some(());
+ }
+
+ None
+ }
+
+ #[inline]
+ fn skip_eol_characters(&mut self) {
+ while let Some(b) = self.peek_byte() {
+ if is_eol_character(b) {
+ self.forward();
+ } else {
+ return;
+ }
+ }
+ }
+
+ #[inline]
+ fn skip_white_spaces_and_comments(&mut self) {
+ while let Some(b) = self.peek_byte() {
+ if is_white_space_character(b) {
+ self.skip_white_spaces();
+ } else if b == b'%' {
+ Comment::skip(self, true);
+ } else {
+ return;
+ }
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+struct ReaderContextData<'a> {
+ xref: &'a XRef,
+ in_content_stream: bool,
+ in_object_stream: bool,
+ obj_number: Option<ObjectIdentifier>,
+ parent_chain: SmallVec<[ObjectIdentifier; 8]>,
+}
+
+#[derive(Clone, Debug)]
+enum ReaderContextInner<'a> {
+ Shared(Arc<ReaderContextData<'a>>),
+ Dummy { in_content_stream: bool },
+}
+
+/// Context for reading PDF objects.
+#[derive(Clone, Debug)]
+pub struct ReaderContext<'a>(ReaderContextInner<'a>);
+
+impl<'a> ReaderContext<'a> {
+ pub(crate) fn new(xref: &'a XRef, in_content_stream: bool) -> Self {
+ Self(ReaderContextInner::Shared(Arc::new(ReaderContextData {
+ xref,
+ in_content_stream,
+ obj_number: None,
+ in_object_stream: false,
+ parent_chain: smallvec![],
+ })))
+ }
+
+ pub fn dummy() -> Self {
+ Self(ReaderContextInner::Dummy {
+ in_content_stream: false,
+ })
+ }
+
+ pub(crate) fn dummy_ref() -> &'static Self {
+ &Self(ReaderContextInner::Dummy {
+ in_content_stream: true,
+ })
+ }
+
+ #[inline]
+ pub(crate) fn xref(&self) -> &'a XRef {
+ match &self.0 {
+ ReaderContextInner::Shared(inner) => inner.xref,
+ ReaderContextInner::Dummy { .. } => XRef::dummy(),
+ }
+ }
+
+ #[inline]
+ pub(crate) fn in_content_stream(&self) -> bool {
+ match &self.0 {
+ ReaderContextInner::Shared(inner) => inner.in_content_stream,
+ ReaderContextInner::Dummy { in_content_stream } => *in_content_stream,
+ }
+ }
+
+ #[inline]
+ pub(crate) fn in_object_stream(&self) -> bool {
+ match &self.0 {
+ ReaderContextInner::Shared(inner) => inner.in_object_stream,
+ ReaderContextInner::Dummy { .. } => false,
+ }
+ }
+
+ #[inline]
+ pub(crate) fn obj_number(&self) -> Option<ObjectIdentifier> {
+ match &self.0 {
+ ReaderContextInner::Shared(inner) => inner.obj_number,
+ ReaderContextInner::Dummy { .. } => None,
+ }
+ }
+
+ #[inline]
+ pub(crate) fn set_obj_number(&mut self, id: ObjectIdentifier) {
+ match &mut self.0 {
+ ReaderContextInner::Shared(inner) => Arc::make_mut(inner).obj_number = Some(id),
+ ReaderContextInner::Dummy { .. } => {}
+ }
+ }
+
+ #[inline]
+ pub(crate) fn set_in_content_stream(&mut self, val: bool) {
+ match &mut self.0 {
+ ReaderContextInner::Shared(inner) => Arc::make_mut(inner).in_content_stream = val,
+ ReaderContextInner::Dummy { in_content_stream } => *in_content_stream = val,
+ }
+ }
+
+ #[inline]
+ pub(crate) fn set_in_object_stream(&mut self, val: bool) {
+ match &mut self.0 {
+ ReaderContextInner::Shared(inner) => Arc::make_mut(inner).in_object_stream = val,
+ ReaderContextInner::Dummy { .. } => {}
+ }
+ }
+
+ #[inline]
+ pub(crate) fn parent_chain_contains(&self, id: &ObjectIdentifier) -> bool {
+ match &self.0 {
+ ReaderContextInner::Shared(inner) => inner.parent_chain.contains(id),
+ ReaderContextInner::Dummy { .. } => false,
+ }
+ }
+
+ #[inline]
+ pub(crate) fn parent_chain_push(&mut self, id: ObjectIdentifier) {
+ match &mut self.0 {
+ ReaderContextInner::Shared(inner) => Arc::make_mut(inner).parent_chain.push(id),
+ ReaderContextInner::Dummy { .. } => {}
+ }
+ }
+}
+
+pub trait Readable<'a>: Sized {
+ fn read(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<Self>;
+ fn from_bytes_impl(b: &'a [u8]) -> Option<Self> {
+ let mut r = Reader::new(b);
+ Self::read(&mut r, &ReaderContext::dummy())
+ }
+}
+
+pub trait Skippable {
+ fn skip(r: &mut Reader<'_>, is_content_stream: bool) -> Option<()>;
+}
diff --git a/vendor/hayro-syntax/src/sync.rs b/vendor/hayro-syntax/src/sync.rs
new file mode 100644
index 000000000..dd4d93cec
--- /dev/null
+++ b/vendor/hayro-syntax/src/sync.rs
@@ -0,0 +1,108 @@
+#[cfg(feature = "std")]
+pub(crate) use std::collections::HashMap;
+
+#[cfg(not(feature = "std"))]
+pub(crate) use alloc::collections::BTreeMap as HashMap;
+
+#[cfg(feature = "std")]
+pub(crate) use rustc_hash::FxHashMap;
+
+#[cfg(not(feature = "std"))]
+pub(crate) use alloc::collections::BTreeMap as FxHashMap;
+
+// Keep in sync with the implementation in `page`.
+#[cfg(feature = "std")]
+pub(crate) use std::sync::Arc;
+
+#[cfg(not(feature = "std"))]
+pub(crate) use alloc::rc::Rc as Arc;
+
+#[cfg(feature = "std")]
+pub(crate) use std::sync::OnceLock;
+
+#[cfg(not(feature = "std"))]
+pub(crate) use core::cell::OnceCell as OnceLock;
+
+#[cfg(feature = "std")]
+pub(crate) use std::sync::Mutex;
+
+#[cfg(not(feature = "std"))]
+pub(crate) use core::cell::RefCell as Mutex;
+
+#[cfg(feature = "std")]
+pub(crate) use std::sync::RwLock;
+
+#[cfg(not(feature = "std"))]
+pub(crate) use core::cell::RefCell as RwLock;
+
+#[cfg(feature = "std")]
+pub(crate) type MutexGuard<'a, T> = std::sync::MutexGuard<'a, T>;
+
+#[cfg(not(feature = "std"))]
+pub(crate) type MutexGuard<'a, T> = core::cell::RefMut<'a, T>;
+
+#[cfg(feature = "std")]
+pub(crate) type RwLockReadGuard<'a, T> = std::sync::RwLockReadGuard<'a, T>;
+
+#[cfg(not(feature = "std"))]
+pub(crate) type RwLockReadGuard<'a, T> = core::cell::Ref<'a, T>;
+
+#[cfg(feature = "std")]
+pub(crate) type RwLockWriteGuard<'a, T> = std::sync::RwLockWriteGuard<'a, T>;
+
+#[cfg(not(feature = "std"))]
+pub(crate) type RwLockWriteGuard<'a, T> = core::cell::RefMut<'a, T>;
+
+pub(crate) trait MutexExt<T> {
+ fn get(&self) -> MutexGuard<'_, T>;
+}
+
+#[cfg(feature = "std")]
+impl<T> MutexExt<T> for Mutex<T> {
+ fn get(&self) -> MutexGuard<'_, T> {
+ self.lock().unwrap()
+ }
+}
+
+#[cfg(not(feature = "std"))]
+impl<T> MutexExt<T> for Mutex<T> {
+ fn get(&self) -> MutexGuard<'_, T> {
+ self.borrow_mut()
+ }
+}
+
+pub(crate) trait RwLockExt<T> {
+ fn get(&self) -> RwLockReadGuard<'_, T>;
+ fn try_get(&self) -> Option<RwLockReadGuard<'_, T>>;
+ fn try_put(&self) -> Option<RwLockWriteGuard<'_, T>>;
+}
+
+#[cfg(feature = "std")]
+impl<T> RwLockExt<T> for RwLock<T> {
+ fn get(&self) -> RwLockReadGuard<'_, T> {
+ self.read().unwrap()
+ }
+
+ fn try_get(&self) -> Option<RwLockReadGuard<'_, T>> {
+ self.try_read().ok()
+ }
+
+ fn try_put(&self) -> Option<RwLockWriteGuard<'_, T>> {
+ self.try_write().ok()
+ }
+}
+
+#[cfg(not(feature = "std"))]
+impl<T> RwLockExt<T> for RwLock<T> {
+ fn get(&self) -> RwLockReadGuard<'_, T> {
+ self.borrow()
+ }
+
+ fn try_get(&self) -> Option<RwLockReadGuard<'_, T>> {
+ Some(self.borrow())
+ }
+
+ fn try_put(&self) -> Option<RwLockWriteGuard<'_, T>> {
+ Some(self.borrow_mut())
+ }
+}
diff --git a/vendor/hayro-syntax/src/transform.rs b/vendor/hayro-syntax/src/transform.rs
new file mode 100644
index 000000000..f9b4a5e75
--- /dev/null
+++ b/vendor/hayro-syntax/src/transform.rs
@@ -0,0 +1,56 @@
+// Copyright 2018 the Kurbo Authors
+// SPDX-License-Identifier: Apache-2.0 OR MIT
+
+//! 2D affine transformations.
+
+use core::ops::Mul;
+
+/// A 2D affine transform.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Transform([f64; 6]);
+
+impl Transform {
+ /// The identity transform.
+ pub const IDENTITY: Self = Self::scale(1.0);
+
+ #[inline(always)]
+ pub(crate) const fn new(c: [f64; 6]) -> Self {
+ Self(c)
+ }
+
+ #[inline(always)]
+ pub(crate) const fn scale(s: f64) -> Self {
+ Self([s, 0.0, 0.0, s, 0.0, 0.0])
+ }
+
+ pub(crate) const ROTATE_CW_90: Self = Self::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0]);
+
+ pub(crate) const ROTATE_CCW_90: Self = Self::new([0.0, -1.0, 1.0, 0.0, 0.0, 0.0]);
+
+ #[inline(always)]
+ pub(crate) const fn translate(p: (f64, f64)) -> Self {
+ Self([1.0, 0.0, 0.0, 1.0, p.0, p.1])
+ }
+
+ /// Get the coefficients of the transform.
+ #[inline(always)]
+ pub const fn as_coeffs(self) -> [f64; 6] {
+ self.0
+ }
+}
+
+impl Mul for Transform {
+ type Output = Self;
+
+ #[inline]
+ fn mul(self, other: Self) -> Self {
+ Self([
+ self.0[0] * other.0[0] + self.0[2] * other.0[1],
+ self.0[1] * other.0[0] + self.0[3] * other.0[1],
+ self.0[0] * other.0[2] + self.0[2] * other.0[3],
+ self.0[1] * other.0[2] + self.0[3] * other.0[3],
+ self.0[0] * other.0[4] + self.0[2] * other.0[5] + self.0[4],
+ self.0[1] * other.0[4] + self.0[3] * other.0[5] + self.0[5],
+ ])
+ }
+}
diff --git a/vendor/hayro-syntax/src/trivia.rs b/vendor/hayro-syntax/src/trivia.rs
new file mode 100644
index 000000000..0097dc996
--- /dev/null
+++ b/vendor/hayro-syntax/src/trivia.rs
@@ -0,0 +1,83 @@
+//! Comments and white spaces.
+
+use crate::reader::Reader;
+use crate::reader::{Readable, ReaderContext, ReaderExt, Skippable};
+
+const fn build_regular_character_table() -> [bool; 256] {
+ let mut table = [true; 256];
+
+ // Whitespace characters.
+ table[0x00] = false;
+ table[0x09] = false;
+ table[0x0a] = false;
+ table[0x0c] = false;
+ table[0x0d] = false;
+ table[0x20] = false;
+
+ // Delimiter characters.
+ table[b'(' as usize] = false;
+ table[b')' as usize] = false;
+ table[b'<' as usize] = false;
+ table[b'>' as usize] = false;
+ table[b'[' as usize] = false;
+ table[b']' as usize] = false;
+ table[b'{' as usize] = false;
+ table[b'}' as usize] = false;
+ table[b'/' as usize] = false;
+ table[b'%' as usize] = false;
+
+ table
+}
+
+const REGULAR_CHARACTER_TABLE: [bool; 256] = build_regular_character_table();
+
+const fn build_white_space_table() -> [bool; 256] {
+ let mut table = [false; 256];
+
+ table[0x00] = true;
+ table[0x09] = true;
+ table[0x0a] = true;
+ table[0x0c] = true;
+ table[0x0d] = true;
+ table[0x20] = true;
+
+ table
+}
+
+const WHITE_SPACE_CHARACTER_TABLE: [bool; 256] = build_white_space_table();
+
+#[inline(always)]
+pub(crate) fn is_white_space_character(char: u8) -> bool {
+ WHITE_SPACE_CHARACTER_TABLE[char as usize]
+}
+
+#[inline(always)]
+pub(crate) fn is_regular_character(char: u8) -> bool {
+ REGULAR_CHARACTER_TABLE[char as usize]
+}
+
+#[inline(always)]
+pub(crate) fn is_eol_character(char: u8) -> bool {
+ matches!(char, 0x0a | 0x0d)
+}
+
+#[derive(Debug, Eq, PartialEq, Clone, Hash)]
+pub(crate) struct Comment<'a>(pub(crate) &'a [u8]);
+
+impl Skippable for Comment<'_> {
+ fn skip(r: &mut Reader<'_>, _: bool) -> Option<()> {
+ r.forward_tag(b"%")?;
+ r.forward_while(|b| !is_eol_character(b));
+
+ Some(())
+ }
+}
+
+impl<'a> Readable<'a> for Comment<'a> {
+ fn read(r: &mut Reader<'a>, _: &ReaderContext<'_>) -> Option<Self> {
+ let bytes = r.skip::<Comment<'_>>(false)?;
+ let bytes = bytes.get(1..bytes.len()).unwrap();
+
+ Some(Comment(bytes))
+ }
+}
diff --git a/vendor/hayro-syntax/src/util.rs b/vendor/hayro-syntax/src/util.rs
new file mode 100644
index 000000000..ec04b39a6
--- /dev/null
+++ b/vendor/hayro-syntax/src/util.rs
@@ -0,0 +1,211 @@
+use crate::sync::OnceLock;
+use alloc::boxed::Box;
+use alloc::vec::Vec;
+use core::ops::Sub;
+use smallvec::{Array, SmallVec};
+
+pub(crate) trait OptionLog {
+ fn error_none(self, f: &str) -> Self;
+}
+
+impl<T> OptionLog for Option<T> {
+ fn error_none(self, _f: &str) -> Self {
+ self.or_else(|| {
+ error!("{_f}");
+
+ None
+ })
+ }
+}
+
+const SCALAR_NEARLY_ZERO: f32 = 1.0 / (1 << 12) as f32;
+
+/// A number of useful methods for f32 numbers.
+pub(crate) trait FloatExt: Sized + Sub<f32, Output = f32> + Copy {
+ /// Whether the number is approximately 0.
+ fn is_nearly_zero(&self) -> bool {
+ self.is_nearly_zero_within_tolerance(SCALAR_NEARLY_ZERO)
+ }
+
+ /// Whether the number is approximately 0, with a given tolerance.
+ fn is_nearly_zero_within_tolerance(&self, tolerance: f32) -> bool;
+}
+
+impl FloatExt for f32 {
+ fn is_nearly_zero_within_tolerance(&self, tolerance: f32) -> bool {
+ debug_assert!(tolerance >= 0.0, "tolerance must be non-negative");
+
+ self.abs() <= tolerance
+ }
+}
+
+pub(crate) trait ByteBuf: Default {
+ fn with_capacity(capacity: usize) -> Self;
+ fn push(&mut self, byte: u8);
+}
+
+impl ByteBuf for Vec<u8> {
+ fn with_capacity(capacity: usize) -> Self {
+ Self::with_capacity(capacity)
+ }
+
+ fn push(&mut self, byte: u8) {
+ Self::push(self, byte);
+ }
+}
+
+impl<A> ByteBuf for SmallVec<A>
+where
+ A: Array<Item = u8>,
+{
+ fn with_capacity(capacity: usize) -> Self {
+ Self::with_capacity(capacity)
+ }
+
+ fn push(&mut self, byte: u8) {
+ Self::push(self, byte);
+ }
+}
+
+#[cfg(feature = "unsafe")]
+pub(crate) fn find_needle(haystack: &[u8], needle: &[u8]) -> Option<usize> {
+ memchr::memmem::find(haystack, needle)
+}
+
+#[cfg(feature = "unsafe")]
+pub(crate) fn findr_needle(haystack: &[u8], needle: &[u8]) -> Option<usize> {
+ memchr::memmem::rfind(haystack, needle)
+}
+
+#[cfg(not(feature = "unsafe"))]
+pub(crate) fn find_needle(haystack: &[u8], needle: &[u8]) -> Option<usize> {
+ if needle.is_empty() {
+ return Some(0);
+ }
+
+ let first = needle[0];
+ let mut i = 0;
+
+ while i + needle.len() <= haystack.len() {
+ while haystack.get(i).copied()? != first {
+ i += 1;
+ if i + needle.len() > haystack.len() {
+ return None;
+ }
+ }
+
+ if haystack.get(i..)?.starts_with(needle) {
+ return Some(i);
+ }
+
+ i += 1;
+ }
+
+ None
+}
+
+#[cfg(not(feature = "unsafe"))]
+pub(crate) fn findr_needle(haystack: &[u8], needle: &[u8]) -> Option<usize> {
+ if needle.is_empty() {
+ return Some(haystack.len());
+ }
+
+ if needle.len() > haystack.len() {
+ return None;
+ }
+
+ let first = needle[0];
+ let mut i = haystack.len() - needle.len();
+
+ loop {
+ while haystack.get(i).copied()? != first {
+ i = i.checked_sub(1)?;
+ }
+
+ if haystack.get(i..)?.starts_with(needle) {
+ return Some(i);
+ }
+
+ i = i.checked_sub(1)?;
+ }
+}
+
+/// Allows to store elements at an index with an `&self` reference.
+///
+/// This is similar to a thread-safe arena data structure, but with less moving
+/// parts and no unsafe code. It's based on the segment list presented in
+/// <https://matklad.github.io/2023/04/23/data-oriented-parallel-value-interner.html>
+///
+/// Indices should be used in order. Usage of higher indices implies more memory
+/// usage (even if lower indices are not in use).
+///
+/// The capacity is limited at 2^C - 1. Calling `get_or_init` with a higher
+/// index will lead to a panic.
+pub(crate) struct SegmentList<T, const C: usize>([OnceLock<Box<[OnceLock<T>]>>; C]);
+
+impl<T, const C: usize> SegmentList<T, C> {
+ pub(crate) fn new() -> Self {
+ Self(core::array::from_fn(|_| OnceLock::new()))
+ }
+
+ pub(crate) fn get(&self, i: usize) -> Option<&T> {
+ let (s, k) = self.locate(i);
+ let segment = self.0[s as usize].get()?;
+ segment.get(k)?.get()
+ }
+
+ #[track_caller]
+ pub(crate) fn get_or_init(&self, i: usize, f: impl FnOnce() -> T) -> &T {
+ let (s, k) = self.locate(i);
+ let segment = self
+ .0
+ .get(s as usize)
+ .expect("segment list is out of capacity")
+ .get_or_init(|| {
+ (0..2_usize.pow(s))
+ .map(|_| OnceLock::new())
+ .collect::<Vec<_>>()
+ .into_boxed_slice()
+ });
+ segment[k].get_or_init(f)
+ }
+
+ fn locate(&self, i: usize) -> (u32, usize) {
+ let power = (i + 2).next_power_of_two() / 2;
+ let s = power.trailing_zeros();
+ let k = i - ((1 << s) - 1);
+ (s, k)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_segment_list() {
+ let e = SegmentList::<String, 10>::new();
+
+ // Ensure that it works.
+ for i in 0..500 {
+ e.get_or_init(i, || format!("{i}"));
+ }
+ for i in 0..500 {
+ assert_eq!(e.get(i), Some(&format!("{i}")));
+ }
+
+ // Ensure that all slots in the first 8 segments are actually in use,
+ // i.e. we didn't overallocate.
+ for s in 0..8 {
+ assert!(e.0[s].get().unwrap().iter().all(|s| s.get().is_some()));
+ }
+ }
+
+ #[test]
+ fn test_findr_needle() {
+ assert_eq!(findr_needle(b"abc foo def foo xyz", b"foo"), Some(12));
+ assert_eq!(findr_needle(b"abc", b""), Some(3));
+ assert_eq!(findr_needle(b"abc", b"abcd"), None);
+ assert_eq!(findr_needle(b"abc", b"z"), None);
+ }
+}
diff --git a/vendor/hayro-syntax/src/xref.rs b/vendor/hayro-syntax/src/xref.rs
new file mode 100644
index 000000000..0b3d5fa8b
--- /dev/null
+++ b/vendor/hayro-syntax/src/xref.rs
@@ -0,0 +1,1154 @@
+//! Reading and querying the xref table of a PDF file.
+
+use crate::crypto::{DecryptionError, DecryptionTarget, Decryptor, get};
+use crate::data::Data;
+use crate::metadata::Metadata;
+use crate::object::Name;
+use crate::object::ObjectIdentifier;
+use crate::object::Stream;
+use crate::object::dict::keys::{
+ AUTHOR, CREATION_DATE, CREATOR, ENCRYPT, FIRST, ID, INDEX, INFO, KEYWORDS, MOD_DATE, N,
+ OCPROPERTIES, PAGES, PREV, PRODUCER, ROOT, SIZE, SUBJECT, TITLE, TYPE, VERSION, W, XREF_STM,
+};
+use crate::object::dict::probe_dict;
+use crate::object::indirect::IndirectObject;
+use crate::object::{Array, MaybeRef};
+use crate::object::{DateTime, Dict};
+use crate::object::{Object, ObjectLike};
+use crate::pdf::PdfVersion;
+use crate::reader::Reader;
+use crate::reader::{Readable, ReaderContext, ReaderExt};
+use crate::sync::{Arc, FxHashMap, RwLock, RwLockExt};
+use crate::trivia::is_white_space_character;
+use crate::util::findr_needle;
+use crate::{PdfData, object};
+use alloc::collections::BTreeSet;
+use alloc::vec;
+use alloc::vec::Vec;
+use core::cmp::max;
+use core::iter;
+use core::ops::Deref;
+
+pub(crate) const XREF_ENTRY_LEN: usize = 20;
+
+#[derive(Debug, Copy, Clone)]
+pub(crate) enum XRefError {
+ Unknown,
+ Encryption(DecryptionError),
+}
+
+/// Parse the "root" xref from the PDF.
+pub(crate) fn root_xref(data: PdfData, password: &[u8]) -> Result<XRef, XRefError> {
+ let mut xref_map = FxHashMap::default();
+ let xref_pos = find_last_xref_pos(data.as_ref()).ok_or(XRefError::Unknown)?;
+ let trailer =
+ populate_xref_impl(data.as_ref(), xref_pos, &mut xref_map).ok_or(XRefError::Unknown)?;
+
+ XRef::new(
+ data.clone(),
+ xref_map,
+ XRefInput::TrailerDictData(trailer),
+ false,
+ password,
+ )
+}
+
+/// Try to manually parse the PDF to build an xref table and trailer dictionary.
+pub(crate) fn fallback(data: PdfData, password: &[u8]) -> Option<XRef> {
+ warn!("xref table was invalid, trying to manually build xref table");
+ let (xref_map, xref_input) = fallback_xref_map(&data, password);
+
+ if let Some(xref_input) = xref_input {
+ warn!("rebuild xref table with {} entries", xref_map.len());
+
+ XRef::new(data.clone(), xref_map, xref_input, true, password).ok()
+ } else {
+ warn!("couldn't find trailer dictionary, failed to rebuild xref table");
+
+ None
+ }
+}
+
+fn fallback_xref_map<'a>(data: &'a PdfData, password: &[u8]) -> (XrefMap, Option<XRefInput<'a>>) {
+ fallback_xref_map_inner(data, ReaderContext::dummy(), true, password)
+}
+
+fn fallback_xref_map_inner<'a>(
+ data: &'a PdfData,
+ mut dummy_ctx: ReaderContext<'a>,
+ recurse: bool,
+ password: &[u8],
+) -> (XrefMap, Option<XRefInput<'a>>) {
+ let mut xref_map = FxHashMap::default();
+ let mut trailer_dicts = vec![];
+ let mut root_ref = None;
+
+ let mut r = Reader::new(data.as_ref());
+
+ let mut last_obj_num = None;
+
+ loop {
+ let cur_pos = r.offset();
+
+ let mut old_r = r.clone();
+
+ // First try to check if we have an object identifier.
+ if r.peek_byte().is_some_and(|b: u8| b.is_ascii_digit()) {
+ if let Some(obj_id) = r.read::<ObjectIdentifier>(&dummy_ctx) {
+ let mut cloned = r.clone();
+ // Check that the object following it is actually valid before inserting it.
+ cloned.skip_white_spaces_and_comments();
+ if cloned.skip::<Object<'_>>(false).is_some() {
+ xref_map.insert(obj_id, EntryType::Normal(cur_pos));
+ last_obj_num = Some(obj_id);
+ dummy_ctx.set_obj_number(obj_id);
+ }
+ } else {
+ // There must be a white space before the next object number.
+ r.forward_while(|b| !is_white_space_character(b));
+ }
+ } else {
+ // Then, try to check whether we have a dictionary, in particular a trailer
+ // dictionary.
+ let mut probe_reader = r.clone();
+ if r.peek_bytes(2).is_some_and(|b| b == b"<<")
+ && let Some(probe) =
+ { probe_dict(&mut probe_reader, &dummy_ctx, Some(b"<<"), b">>") }
+ {
+ r = probe_reader;
+ if probe.has_root || probe.has_type {
+ let mut dict_reader = Reader::new(probe.data);
+ if let Some(dict) = dict_reader.read_with_context::<Dict<'_>>(&dummy_ctx) {
+ if probe.has_root && dict.contains_key(ROOT) {
+ trailer_dicts.push(dict.clone());
+ }
+
+ if dict
+ .get::<Name<'_>>(TYPE)
+ .is_some_and(|n| n.as_str() == "Catalog")
+ {
+ root_ref = last_obj_num;
+ }
+
+ if let Some(stream) = old_r.read::<Stream<'_>>(&dummy_ctx)
+ && dict.get::<Name<'_>>(TYPE).as_deref() == Some(b"ObjStm")
+ && let Some(data) = stream.decoded().ok()
+ && let Some(last_obj_num) = last_obj_num
+ && let Some(obj_stream) = ObjectStream::new(stream, &data, &dummy_ctx)
+ {
+ for (idx, (obj_num, _)) in obj_stream.offsets.iter().enumerate() {
+ let id = ObjectIdentifier::new(*obj_num as i32, 0);
+ // If we already found an entry for that object number that was not
+ // inside an object stream. Somewhat arbitrary and maybe
+ // we can do better, but that seems to work for the current
+ // set of tests.
+ if xref_map
+ .get(&id)
+ .is_none_or(|e| !matches!(e, &EntryType::Normal(_)))
+ {
+ xref_map.insert(
+ id,
+ EntryType::ObjStream(
+ last_obj_num.obj_number as u32,
+ idx as u32,
+ ),
+ );
+ }
+ }
+ }
+ }
+ }
+ } else {
+ // We can skip everything until the next white space character,
+ // as there cannot possibly be any new dictionary/object identifier
+ // until then.
+ let old_pos = r.offset;
+ r.forward_while(|b| !is_white_space_character(b));
+ if r.offset == old_pos {
+ r.read_byte();
+ }
+ }
+ }
+
+ if r.at_end() {
+ break;
+ }
+ }
+
+ // Try to choose the right trailer dict by doing basic validation.
+ let mut trailer_dict = None;
+
+ for dict in trailer_dicts {
+ if let Some(root_id) = dict.get_raw::<Dict<'_>>(ROOT) {
+ let check = |dict: &Dict<'_>| -> bool { dict.contains_key(PAGES) };
+
+ match root_id {
+ MaybeRef::Ref(r) => match xref_map.get(&r.into()) {
+ Some(EntryType::Normal(offset)) => {
+ let mut reader = Reader::new(&data.as_ref()[*offset..]);
+
+ if let Some(obj) =
+ reader.read_with_context::<IndirectObject<Dict<'_>>>(&dummy_ctx)
+ && {
+ let obj = obj.get();
+ check(&obj)
+ }
+ {
+ trailer_dict = Some(dict);
+ }
+ }
+ Some(EntryType::ObjStream(obj_num, idx)) => {
+ if let Some(EntryType::Normal(offset)) =
+ xref_map.get(&ObjectIdentifier::new(*obj_num as i32, 0))
+ {
+ let mut reader = Reader::new(&data.as_ref()[*offset..]);
+
+ if let Some(stream) =
+ reader.read_with_context::<IndirectObject<Stream<'_>>>(&dummy_ctx)
+ && {
+ let stream = stream.get();
+ if let Some(data) = stream.decoded().ok()
+ && let Some(object_stream) =
+ ObjectStream::new(stream, &data, &dummy_ctx)
+ && let Some(obj) = object_stream.get::<Dict<'_>>(*idx)
+ {
+ check(&obj)
+ } else {
+ false
+ }
+ }
+ {
+ trailer_dict = Some(dict);
+ }
+ }
+ }
+ _ => {}
+ },
+ MaybeRef::NotRef(d) => {
+ if check(&d) {
+ trailer_dict = Some(dict);
+ }
+ }
+ }
+ }
+ }
+
+ let has_encryption = trailer_dict
+ .as_ref()
+ .is_some_and(|t| t.contains_key(ENCRYPT));
+
+ if has_encryption && recurse {
+ // The problem is that in this case, we have used a dummy reader context which does not have
+ // a decryptor. Therefore, we were unable to decrypt any of the object streams and missed
+ // all objects that are inside of such a stream. Therefore, we need to redo the process
+ // using a `ReaderContext` that does have the ability to decrypt.
+ if let Ok(xref) = XRef::new(
+ data.clone(),
+ xref_map.clone(),
+ XRefInput::TrailerDictData(trailer_dict.as_ref().map(|d| d.data()).unwrap()),
+ true,
+ password,
+ ) {
+ let ctx = ReaderContext::new(&xref, false);
+ let (patched_map, _) = fallback_xref_map_inner(data, ctx, false, password);
+ xref_map = patched_map;
+ }
+ }
+
+ if let Some(trailer_dict_data) = trailer_dict.map(|d| d.data()) {
+ (
+ xref_map,
+ Some(XRefInput::TrailerDictData(trailer_dict_data)),
+ )
+ } else if let Some(root_ref) = root_ref {
+ (xref_map, Some(XRefInput::RootRef(root_ref)))
+ } else {
+ (xref_map, None)
+ }
+}
+
+const DUMMY_XREF: XRef = XRef(Inner::Dummy);
+
+/// An xref table.
+#[derive(Debug, Clone)]
+pub struct XRef(Inner);
+
+impl XRef {
+ fn new(
+ data: PdfData,
+ xref_map: XrefMap,
+ input: XRefInput<'_>,
+ repaired: bool,
+ password: &[u8],
+ ) -> Result<Self, XRefError> {
+ // This is a bit hacky, but the problem is we can't read the resolved trailer dictionary
+ // before we actually created the xref struct. So we first create it using dummy data
+ // and then populate the data.
+ let trailer_data = TrailerData::dummy();
+
+ let mut xref = Self(Inner::Some(Arc::new(SomeRepr {
+ data: Arc::new(Data::new(data)),
+ map: Arc::new(RwLock::new(MapRepr { xref_map, repaired })),
+ decryptor: Arc::new(Decryptor::None),
+ has_ocgs: false,
+ metadata: Arc::new(Metadata::default()),
+ trailer_data,
+ password: password.to_vec(),
+ })));
+
+ // We read the trailer twice, once to determine the encryption used and then a second
+ // time to resolve the catalog dictionary, etc. This allows us to support catalog dictionaries
+ // that are stored in an encrypted object stream.
+
+ let decryptor = {
+ match input {
+ XRefInput::TrailerDictData(trailer_dict_data) => {
+ let mut r = Reader::new(trailer_dict_data);
+
+ let trailer_dict = r
+ .read_with_context::<Dict<'_>>(&ReaderContext::new(&xref, false))
+ .ok_or(XRefError::Unknown)?;
+
+ get_decryptor(&trailer_dict, password)?
+ }
+ XRefInput::RootRef(_) => Decryptor::None,
+ }
+ };
+
+ match &mut xref.0 {
+ Inner::Dummy => unreachable!(),
+ Inner::Some(r) => {
+ let mutable = Arc::make_mut(r);
+ mutable.decryptor = Arc::new(decryptor.clone());
+ }
+ }
+
+ let (trailer_data, has_ocgs, metadata) = match input {
+ XRefInput::TrailerDictData(trailer_dict_data) => {
+ let mut r = Reader::new(trailer_dict_data);
+
+ let trailer_dict = r
+ .read_with_context::<Dict<'_>>(&ReaderContext::new(&xref, false))
+ .ok_or(XRefError::Unknown)?;
+
+ let root_ref = trailer_dict.get_ref(ROOT).ok_or(XRefError::Unknown)?;
+ let root = trailer_dict
+ .get::<Dict<'_>>(ROOT)
+ .ok_or(XRefError::Unknown)?;
+ let metadata = trailer_dict
+ .get::<Dict<'_>>(INFO)
+ .map(|d| parse_metadata(&d))
+ .unwrap_or_default();
+ let pages_ref = root.get_ref(PAGES).ok_or(XRefError::Unknown)?;
+ let has_ocgs = root.get::<Dict<'_>>(OCPROPERTIES).is_some();
+ let version = root
+ .get::<Name<'_>>(VERSION)
+ .and_then(|v| PdfVersion::from_bytes(v.deref()));
+
+ let td = TrailerData {
+ pages_ref: pages_ref.into(),
+ root_ref: root_ref.into(),
+ version,
+ };
+
+ (td, has_ocgs, metadata)
+ }
+ XRefInput::RootRef(root_ref) => {
+ let root = xref.get::<Dict<'_>>(root_ref).ok_or(XRefError::Unknown)?;
+ let pages_ref = root.get_ref(PAGES).ok_or(XRefError::Unknown)?;
+
+ let td = TrailerData {
+ pages_ref: pages_ref.into(),
+ root_ref,
+ version: None,
+ };
+
+ (td, false, Metadata::default())
+ }
+ };
+
+ match &mut xref.0 {
+ Inner::Dummy => unreachable!(),
+ Inner::Some(r) => {
+ let mutable = Arc::make_mut(r);
+ mutable.trailer_data = trailer_data;
+ mutable.decryptor = Arc::new(decryptor);
+ mutable.has_ocgs = has_ocgs;
+ mutable.metadata = Arc::new(metadata);
+ }
+ }
+
+ Ok(xref)
+ }
+
+ fn is_repaired(&self) -> bool {
+ match &self.0 {
+ Inner::Dummy => false,
+ Inner::Some(r) => {
+ let locked = r.map.get();
+ locked.repaired
+ }
+ }
+ }
+
+ pub(crate) fn dummy() -> &'static Self {
+ &DUMMY_XREF
+ }
+
+ pub(crate) fn len(&self) -> usize {
+ match &self.0 {
+ Inner::Dummy => 0,
+ Inner::Some(r) => r.map.get().xref_map.len(),
+ }
+ }
+
+ pub(crate) fn trailer_data(&self) -> &TrailerData {
+ match &self.0 {
+ Inner::Dummy => unreachable!(),
+ Inner::Some(r) => &r.trailer_data,
+ }
+ }
+
+ pub(crate) fn metadata(&self) -> &Metadata {
+ match &self.0 {
+ Inner::Dummy => unreachable!(),
+ Inner::Some(r) => &r.metadata,
+ }
+ }
+
+ /// Return the object ID of the root dictionary.
+ pub fn root_id(&self) -> ObjectIdentifier {
+ self.trailer_data().root_ref
+ }
+
+ /// Whether the PDF has optional content groups.
+ pub fn has_optional_content_groups(&self) -> bool {
+ match &self.0 {
+ Inner::Dummy => false,
+ Inner::Some(r) => r.has_ocgs,
+ }
+ }
+
+ pub(crate) fn objects(&self) -> impl IntoIterator<Item = Object<'_>> + '_ {
+ match &self.0 {
+ Inner::Dummy => unimplemented!(),
+ Inner::Some(r) => {
+ let locked = r.map.get();
+ let mut elements = locked
+ .xref_map
+ .iter()
+ .map(|(id, e)| {
+ let offset = match e {
+ EntryType::Normal(o) => (*o, 0),
+ EntryType::ObjStream(id, index) => {
+ if let Some(EntryType::Normal(offset)) =
+ locked.xref_map.get(&ObjectIdentifier::new(*id as i32, 0))
+ {
+ (*offset, *index)
+ } else {
+ (usize::MAX, 0)
+ }
+ }
+ };
+
+ (*id, offset)
+ })
+ .collect::<Vec<_>>();
+
+ // Try to yield in the order the objects appeared in the
+ // PDF.
+ elements.sort_by(|e1, e2| e1.1.cmp(&e2.1));
+
+ let mut iter = elements.into_iter();
+
+ iter::from_fn(move || {
+ for next in iter.by_ref() {
+ if let Some(obj) = self.get_with(next.0, &ReaderContext::new(self, false)) {
+ return Some(obj);
+ } else {
+ // Skip invalid objects.
+ continue;
+ }
+ }
+
+ None
+ })
+ }
+ }
+ }
+
+ pub(crate) fn repair(&self) {
+ let Inner::Some(r) = &self.0 else {
+ unreachable!();
+ };
+
+ let mut locked = r.map.try_put().unwrap();
+ assert!(!locked.repaired);
+
+ let (xref_map, _) = fallback_xref_map(r.data.get(), &r.password);
+ locked.xref_map = xref_map;
+ locked.repaired = true;
+ }
+
+ #[inline]
+ pub(crate) fn needs_decryption(&self, ctx: &ReaderContext<'_>) -> bool {
+ match &self.0 {
+ Inner::Dummy => false,
+ Inner::Some(r) => {
+ if matches!(r.decryptor.as_ref(), Decryptor::None) {
+ false
+ } else {
+ !ctx.in_content_stream() && !ctx.in_object_stream()
+ }
+ }
+ }
+ }
+
+ #[inline]
+ pub(crate) fn decrypt(
+ &self,
+ id: ObjectIdentifier,
+ data: &[u8],
+ target: DecryptionTarget,
+ ) -> Option<Vec<u8>> {
+ match &self.0 {
+ Inner::Dummy => Some(data.to_vec()),
+ Inner::Some(r) => r.decryptor.decrypt(id, data, target),
+ }
+ }
+
+ /// Return the object with the given identifier.
+ #[allow(private_bounds)]
+ pub fn get<'a, T>(&'a self, id: ObjectIdentifier) -> Option<T>
+ where
+ T: ObjectLike<'a>,
+ {
+ let ctx = ReaderContext::new(self, false);
+ self.get_with(id, &ctx)
+ }
+
+ /// Return the object with the given identifier.
+ #[allow(private_bounds)]
+ pub(crate) fn get_with<'a, T>(
+ &'a self,
+ id: ObjectIdentifier,
+ ctx: &ReaderContext<'a>,
+ ) -> Option<T>
+ where
+ T: ObjectLike<'a>,
+ {
+ let Inner::Some(repr) = &self.0 else {
+ return None;
+ };
+
+ let locked = repr.map.try_get().unwrap();
+
+ let mut r = Reader::new(repr.data.get().as_ref());
+
+ let entry = *locked.xref_map.get(&id).or({
+ // An indirect reference to an undefined object shall not be considered an error by a PDF processor; it
+ // shall be treated as a reference to the null object.
+ None
+ })?;
+ drop(locked);
+
+ let mut ctx = ctx.clone();
+ ctx.set_obj_number(id);
+ ctx.set_in_content_stream(false);
+
+ match entry {
+ EntryType::Normal(offset) => {
+ ctx.set_in_object_stream(false);
+ r.jump(offset);
+
+ if let Some(object) = r.read_with_context::<IndirectObject<T>>(&ctx) {
+ if object.id() == &id {
+ return Some(object.get());
+ }
+ } else {
+ // There is a valid object at the offset, it's just not of the type the caller
+ // expected, which is fine.
+ if r.skip::<IndirectObject<Object<'_>>>(false).is_some() {
+ return None;
+ }
+ };
+
+ // The xref table is broken, try to repair if not already repaired.
+ if self.is_repaired() {
+ error!(
+ "attempt was made at repairing xref, but object {id:?} still couldn't be read"
+ );
+
+ None
+ } else {
+ warn!("broken xref, attempting to repair");
+
+ self.repair();
+
+ // Now try reading again.
+ self.get_with::<T>(id, &ctx)
+ }
+ }
+ EntryType::ObjStream(obj_stram_gen_num, index) => {
+ // Generation number is implicitly 0.
+ let obj_stream_id = ObjectIdentifier::new(obj_stram_gen_num as i32, 0);
+
+ if obj_stream_id == id {
+ warn!("cycle detected in object stream");
+
+ return None;
+ }
+
+ let stream = self.get_with::<Stream<'_>>(obj_stream_id, &ctx)?;
+ let data = repr.data.get_with(obj_stream_id, &ctx)?;
+ let object_stream = ObjectStream::new(stream, data, &ctx)?;
+ object_stream.get(index)
+ }
+ }
+ }
+}
+
+/// An input that is passed to the xref constructor so that we can fully resolve
+/// the PDF.
+#[derive(Debug, Copy, Clone)]
+pub(crate) enum XRefInput<'a> {
+ /// This option is going to be uesd in 99.999% of the case. It contains the
+ /// raw data of the trailer dictionary which is then going to be processed.
+ TrailerDictData(&'a [u8]),
+ /// In case the trailer dictionary could not be read (for example because
+ /// it is cut-off), we just pass the object ID of the root dictionary
+ /// in case we have found one, and try our best to build the PDF just
+ /// with the information we have there.
+ ///
+ /// Note that this won't work if the document is encrypted, as we
+ /// can't access the crypto dictionary.
+ RootRef(ObjectIdentifier),
+}
+
+pub(crate) fn find_last_xref_pos(data: &[u8]) -> Option<usize> {
+ let needle = b"startxref";
+ let pos = findr_needle(data, needle)?;
+ let mut finder = Reader::new(data);
+ finder.jump(pos);
+ finder.forward_tag(needle)?;
+ finder.skip_white_spaces_and_comments();
+ finder.read_without_context::<i32>()?.try_into().ok()
+}
+
+/// A type of xref entry.
+#[derive(Debug, PartialEq, Eq, Clone, Copy)]
+enum EntryType {
+ /// An indirect object that is at a specific offset in the original data.
+ Normal(usize),
+ /// An indirect object that is part of an object stream. First number indicates the object
+ /// number of the _object stream_ (the generation number is always 0), the second number indicates
+ /// the index in the object stream.
+ ObjStream(u32, u32),
+}
+
+type XrefMap = FxHashMap<ObjectIdentifier, EntryType>;
+
+/// Representation of a proper xref table.
+#[derive(Debug)]
+struct MapRepr {
+ xref_map: XrefMap,
+ repaired: bool,
+}
+
+#[derive(Debug, Copy, Clone)]
+pub(crate) struct TrailerData {
+ pub(crate) pages_ref: ObjectIdentifier,
+ pub(crate) root_ref: ObjectIdentifier,
+ pub(crate) version: Option<PdfVersion>,
+}
+
+impl TrailerData {
+ pub(crate) fn dummy() -> Self {
+ Self {
+ pages_ref: ObjectIdentifier::new(0, 0),
+ root_ref: ObjectIdentifier::new(0, 0),
+ version: None,
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+struct SomeRepr {
+ data: Arc<Data>,
+ map: Arc<RwLock<MapRepr>>,
+ metadata: Arc<Metadata>,
+ decryptor: Arc<Decryptor>,
+ has_ocgs: bool,
+ password: Vec<u8>,
+ trailer_data: TrailerData,
+}
+
+#[derive(Debug, Clone)]
+enum Inner {
+ /// A dummy xref table that doesn't have any entries.
+ Dummy,
+ /// A proper xref table.
+ Some(Arc<SomeRepr>),
+}
+
+#[derive(Debug)]
+struct XRefEntry {
+ offset: usize,
+ gen_number: i32,
+ used: bool,
+}
+
+impl XRefEntry {
+ pub(crate) fn read(data: &[u8]) -> Option<Self> {
+ #[inline(always)]
+ fn parse_u32(data: &[u8]) -> Option<u32> {
+ let mut accum = 0_u32;
+
+ for byte in data {
+ accum = accum.checked_mul(10)?;
+
+ match *byte {
+ b'0'..=b'9' => accum = accum.checked_add((*byte - b'0') as u32)?,
+ _ => return None,
+ }
+ }
+
+ Some(accum)
+ }
+
+ let offset = parse_u32(&data[0..10])? as usize;
+ let gen_number = i32::try_from(parse_u32(&data[11..16])?).ok()?;
+
+ let used = data[17] == b'n';
+
+ Some(Self {
+ offset,
+ gen_number,
+ used,
+ })
+ }
+}
+
+fn populate_xref_impl<'a>(data: &'a [u8], pos: usize, xref_map: &mut XrefMap) -> Option<&'a [u8]> {
+ let mut visited = BTreeSet::new();
+ populate_xref_impl_inner(data, pos, xref_map, &mut visited)
+}
+
+/// Maximum number of allowed xref `Prev` pointers before we abort.
+const MAX_XREF_CHAIN_DEPTH: usize = 256;
+
+fn populate_xref_impl_inner<'a>(
+ data: &'a [u8],
+ pos: usize,
+ xref_map: &mut XrefMap,
+ visited: &mut BTreeSet<usize>,
+) -> Option<&'a [u8]> {
+ if !visited.insert(pos) {
+ warn!("circular xref PREV chain detected at offset {}", pos);
+
+ return None;
+ }
+
+ if visited.len() > MAX_XREF_CHAIN_DEPTH {
+ warn!(
+ "xref PREV chain exceeds maximum depth of {}",
+ MAX_XREF_CHAIN_DEPTH
+ );
+
+ return None;
+ }
+
+ let mut reader = Reader::new(data);
+ reader.jump(pos);
+ // In case the position points to before the object number of a xref stream.
+ reader.skip_white_spaces_and_comments();
+
+ let mut r2 = reader.clone();
+ if reader
+ .clone()
+ .read_without_context::<ObjectIdentifier>()
+ .is_some()
+ {
+ populate_from_xref_stream(data, &mut r2, xref_map, visited)
+ } else {
+ populate_from_xref_table(data, &mut r2, xref_map, visited)
+ }
+}
+
+pub(super) struct SubsectionHeader {
+ pub(super) start: u32,
+ pub(super) num_entries: u32,
+}
+
+impl Readable<'_> for SubsectionHeader {
+ fn read(r: &mut Reader<'_>, _: &ReaderContext<'_>) -> Option<Self> {
+ r.skip_white_spaces();
+ let start = r.read_without_context::<u32>()?;
+ r.skip_white_spaces();
+ let num_entries = r.read_without_context::<u32>()?;
+ r.skip_white_spaces();
+
+ Some(Self { start, num_entries })
+ }
+}
+
+/// Populate the xref table, and return the trailer dict.
+fn populate_from_xref_table<'a>(
+ data: &'a [u8],
+ reader: &mut Reader<'a>,
+ insert_map: &mut XrefMap,
+ visited: &mut BTreeSet<usize>,
+) -> Option<&'a [u8]> {
+ let trailer = {
+ let mut reader = reader.clone();
+ read_xref_table_trailer(&mut reader, &ReaderContext::dummy())?
+ };
+
+ reader.skip_white_spaces();
+ reader.forward_tag(b"xref")?;
+ reader.skip_white_spaces();
+
+ let mut max_obj = 0;
+
+ if let Some(prev) = trailer.get::<i32>(PREV) {
+ // First insert the entries from any previous xref tables.
+ populate_xref_impl_inner(data, prev as usize, insert_map, visited)?;
+ }
+
+ // In hybrid files, entries in `XRefStm` should have higher priority, therefore we insert them
+ // after looking at `PREV`.
+ if let Some(xref_stm) = trailer.get::<i32>(XREF_STM) {
+ populate_xref_impl_inner(data, xref_stm as usize, insert_map, visited)?;
+ }
+
+ while let Some(header) = reader.read_without_context::<SubsectionHeader>() {
+ reader.skip_white_spaces();
+
+ let start = header.start;
+ let end = start.checked_add(header.num_entries)?;
+
+ for obj_number in start..end {
+ max_obj = max(max_obj, obj_number);
+ let bytes = reader.read_bytes(XREF_ENTRY_LEN)?;
+ let entry = XRefEntry::read(bytes)?;
+
+ // Specification says we should ignore any object number > SIZE, but probably
+ // not important?
+ if entry.used {
+ insert_map.insert(
+ ObjectIdentifier::new(obj_number as i32, entry.gen_number),
+ EntryType::Normal(entry.offset),
+ );
+ }
+ }
+ }
+
+ Some(trailer.data())
+}
+
+fn populate_from_xref_stream<'a>(
+ data: &'a [u8],
+ reader: &mut Reader<'a>,
+ insert_map: &mut XrefMap,
+ visited: &mut BTreeSet<usize>,
+) -> Option<&'a [u8]> {
+ let stream = reader
+ .read_with_context::<IndirectObject<Stream<'_>>>(&ReaderContext::dummy())?
+ .get();
+
+ if let Some(prev) = stream.dict().get::<i32>(PREV) {
+ // First insert the entries from any previous xref tables.
+ let _ = populate_xref_impl_inner(data, prev as usize, insert_map, visited)?;
+ }
+
+ let size = stream.dict().get::<u32>(SIZE)?;
+
+ let [f1_len, f2_len, f3_len] = stream.dict().get::<[u8; 3]>(W)?;
+
+ if f2_len > size_of::<u64>() as u8 {
+ error!("xref offset length is larger than the allowed limit");
+
+ return None;
+ }
+
+ // Do such files exist?
+ if f1_len != 1 {
+ warn!("first field in xref stream was longer than 1");
+ }
+
+ let xref_data = stream.decoded().ok()?;
+ let mut xref_reader = Reader::new(xref_data.as_ref());
+
+ if let Some(arr) = stream.dict().get::<Array<'_>>(INDEX) {
+ let iter = arr.iter::<(u32, u32)>();
+
+ for (start, num_elements) in iter {
+ xref_stream_subsection(
+ &mut xref_reader,
+ start,
+ num_elements,
+ f1_len,
+ f2_len,
+ f3_len,
+ insert_map,
+ )?;
+ }
+ } else {
+ xref_stream_subsection(
+ &mut xref_reader,
+ 0,
+ size,
+ f1_len,
+ f2_len,
+ f3_len,
+ insert_map,
+ )?;
+ }
+
+ Some(stream.dict().data())
+}
+
+fn xref_stream_num(data: &[u8]) -> Option<u32> {
+ Some(match data.len() {
+ 0 => return None,
+ 1 => u8::from_be(data[0]) as u32,
+ 2 => u16::from_be_bytes(data[0..2].try_into().ok()?) as u32,
+ 3 => u32::from_be_bytes([0, data[0], data[1], data[2]]),
+ 4 => u32::from_be_bytes(data[0..4].try_into().ok()?),
+ 8 => {
+ if let Ok(num) = u32::try_from(u64::from_be_bytes(data[0..8].try_into().ok()?)) {
+ return Some(num);
+ } else {
+ warn!("xref stream number is too large");
+
+ return None;
+ }
+ }
+ _n => {
+ warn!("invalid xref stream number {_n}");
+
+ return None;
+ }
+ })
+}
+
+fn xref_stream_subsection<'a>(
+ xref_reader: &mut Reader<'a>,
+ start: u32,
+ num_elements: u32,
+ f1_len: u8,
+ f2_len: u8,
+ f3_len: u8,
+ insert_map: &mut XrefMap,
+) -> Option<()> {
+ for i in 0..num_elements {
+ let f_type = if f1_len == 0 {
+ 1
+ } else {
+ // We assume a length of 1.
+ xref_reader.read_bytes(1)?[0]
+ };
+
+ let obj_number = start + i;
+
+ match f_type {
+ // We don't care about free objects.
+ 0 => {
+ xref_reader.skip_bytes(f2_len as usize + f3_len as usize)?;
+ }
+ 1 => {
+ let offset = if f2_len > 0 {
+ let data = xref_reader.read_bytes(f2_len as usize)?;
+ xref_stream_num(data)?
+ } else {
+ 0
+ };
+
+ let gen_number = if f3_len > 0 {
+ let data = xref_reader.read_bytes(f3_len as usize)?;
+ xref_stream_num(data)?
+ } else {
+ 0
+ };
+
+ insert_map.insert(
+ ObjectIdentifier::new(obj_number as i32, gen_number as i32),
+ EntryType::Normal(offset as usize),
+ );
+ }
+ 2 => {
+ let obj_stream_number = {
+ let data = xref_reader.read_bytes(f2_len as usize)?;
+ xref_stream_num(data)?
+ };
+ let gen_number = 0;
+ let index = if f3_len > 0 {
+ let data = xref_reader.read_bytes(f3_len as usize)?;
+ xref_stream_num(data)?
+ } else {
+ 0
+ };
+
+ insert_map.insert(
+ ObjectIdentifier::new(obj_number as i32, gen_number),
+ EntryType::ObjStream(obj_stream_number, index),
+ );
+ }
+ _ => {
+ warn!("xref has unknown field type {f_type}");
+
+ return None;
+ }
+ }
+ }
+
+ Some(())
+}
+
+fn read_xref_table_trailer<'a>(
+ reader: &mut Reader<'a>,
+ ctx: &ReaderContext<'a>,
+) -> Option<Dict<'a>> {
+ reader.skip_white_spaces();
+ reader.forward_tag(b"xref")?;
+ reader.skip_white_spaces();
+
+ while let Some(header) = reader.read_without_context::<SubsectionHeader>() {
+ let len = XREF_ENTRY_LEN.checked_mul(header.num_entries as usize)?;
+ reader.jump(reader.offset().checked_add(len)?);
+ }
+
+ reader.skip_white_spaces();
+ reader.forward_tag(b"trailer")?;
+ reader.skip_white_spaces();
+
+ reader.read_with_context::<Dict<'_>>(ctx)
+}
+
+fn get_decryptor(trailer_dict: &Dict<'_>, password: &[u8]) -> Result<Decryptor, XRefError> {
+ if let Some(encryption_dict) = trailer_dict.get::<Dict<'_>>(ENCRYPT) {
+ let id = if let Some(id) = trailer_dict
+ .get::<Array<'_>>(ID)
+ .and_then(|a| a.flex_iter().next::<object::String<'_>>())
+ {
+ id.to_vec()
+ } else {
+ // Assume an empty ID entry.
+ vec![]
+ };
+
+ get(&encryption_dict, &id, password).map_err(XRefError::Encryption)
+ } else {
+ Ok(Decryptor::None)
+ }
+}
+
+struct ObjectStream<'a> {
+ data: &'a [u8],
+ ctx: ReaderContext<'a>,
+ offsets: Vec<(u32, usize)>,
+}
+
+impl<'a> ObjectStream<'a> {
+ fn new(inner: Stream<'_>, data: &'a [u8], ctx: &ReaderContext<'a>) -> Option<Self> {
+ let num_objects = inner.dict().get::<usize>(N)?;
+ let first_offset = inner.dict().get::<usize>(FIRST)?;
+
+ let mut r = Reader::new(data);
+
+ let mut offsets = vec![];
+
+ for _ in 0..num_objects {
+ r.skip_white_spaces_and_comments();
+ // Skip object number
+ let obj_num = r.read_without_context::<u32>()?;
+ r.skip_white_spaces_and_comments();
+ let relative_offset = r.read_without_context::<usize>()?;
+ offsets.push((obj_num, first_offset + relative_offset));
+ }
+
+ let mut ctx = ctx.clone();
+ ctx.set_in_object_stream(true);
+
+ Some(Self { data, ctx, offsets })
+ }
+
+ fn get<T>(&self, index: u32) -> Option<T>
+ where
+ T: ObjectLike<'a>,
+ {
+ let offset = self.offsets.get(index as usize)?.1;
+ let mut r = Reader::new(self.data);
+ r.jump(offset);
+ r.skip_white_spaces_and_comments();
+
+ r.read_with_context::<T>(&self.ctx)
+ }
+}
+
+fn parse_metadata(info_dict: &Dict<'_>) -> Metadata {
+ Metadata {
+ creation_date: info_dict
+ .get::<object::String<'_>>(CREATION_DATE)
+ .and_then(|c| DateTime::from_bytes(&c)),
+ modification_date: info_dict
+ .get::<object::String<'_>>(MOD_DATE)
+ .and_then(|c| DateTime::from_bytes(&c)),
+ title: info_dict
+ .get::<object::String<'_>>(TITLE)
+ .map(|t| t.to_vec()),
+ author: info_dict
+ .get::<object::String<'_>>(AUTHOR)
+ .map(|t| t.to_vec()),
+ subject: info_dict
+ .get::<object::String<'_>>(SUBJECT)
+ .map(|t| t.to_vec()),
+ keywords: info_dict
+ .get::<object::String<'_>>(KEYWORDS)
+ .map(|t| t.to_vec()),
+ creator: info_dict
+ .get::<object::String<'_>>(CREATOR)
+ .map(|t| t.to_vec()),
+ producer: info_dict
+ .get::<object::String<'_>>(PRODUCER)
+ .map(|t| t.to_vec()),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn circular_prev_chain() {
+ let mut pdf = b"%PDF-1.0\n1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n".to_vec();
+ let expected_xref_pos = pdf.len();
+ pdf.extend_from_slice(
+ format!(
+ "xref\n\
+ 0 1\n\
+ 0000000000 65535 f \r\n\
+ trailer\n<< /Size 1 /Root 1 0 R /Prev {expected_xref_pos} >>\n\
+ startxref\n{expected_xref_pos}\n%%EOF"
+ )
+ .as_bytes(),
+ );
+
+ let mut xref_map = FxHashMap::default();
+ let xref_pos = find_last_xref_pos(pdf.as_ref()).unwrap();
+ let _result = populate_xref_impl(pdf.as_ref(), xref_pos, &mut xref_map);
+ }
+
+ #[test]
+ fn find_last_xref_uses_last_startxref() {
+ let pdf = b"%PDF-1.0\nstartxref\n5\n%%EOF\nstartxref\n42\n%%EOF";
+ assert_eq!(find_last_xref_pos(pdf), Some(42));
+ }
+
+ #[test]
+ fn xref_table_trailer_rejects_overflowing_entry_skip() {
+ let data = b"xref\n0 999999999999999999999\ntrailer\n<<>>";
+ let mut reader = Reader::new(data);
+ assert!(read_xref_table_trailer(&mut reader, &ReaderContext::dummy()).is_none());
+ }
+}