Files
craft-libs/vendor/hayro-postscript/src/string/ascii_hex.rs
T
aiongg 2eca9b3a53 pdf: vendor hayro-postscript and skip << and >> runs without recursion (#263)
hayro-postscript 0.1.0 is the token scanner hayro-cmap uses for the
CMap streams PDFs embed. Its object reader skipped each `<<` or `>>`
by calling itself again, so a stream holding a long run of `<` or `>`
bytes recursed once per pair and aborted the process with a stack
overflow.

Vendor the crates.io package unchanged and patch `object::read` to
skip those runs in a loop, returning the same next object as before.
Wire it in like the other Hayro crates: workspace exclude,
[patch.crates-io] entry, SOURCE.json with registry and local hashes,
the backend test script, NOTICE, ATTRIBUTION.md and the reader README.

Tests cover a million `<` and a million `>` bytes, `<< /A 1 >>` and
nested `<<<< /X >>>>` runs.
2026-10-23 23:31:35 -04:00

60 lines
1.6 KiB
Rust

// Keep in sync with `hayro-syntax/src/filter/ascii_hex.rs`.
use crate::reader::is_whitespace;
use alloc::vec::Vec;
pub(crate) fn decode_into(data: &[u8], out: &mut Vec<u8>) -> Option<()> {
let has_whitespace = data.iter().any(|&b| is_whitespace(b));
out.reserve(data.len().div_ceil(2));
if !has_whitespace {
// Fast path, don't need to worry about white spaces.
let mut i = 0;
while i + 1 < data.len() {
out.push(decode_hex_digit(data[i])? << 4 | decode_hex_digit(data[i + 1])?);
i += 2;
}
if i < data.len() {
out.push(decode_hex_digit(data[i])? << 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_whitespace(b) {
return Some(b);
}
}
};
loop {
match (read_byte(), read_byte()) {
(Some(hi), Some(lo)) => {
out.push(decode_hex_digit(hi)? << 4 | decode_hex_digit(lo)?);
}
(Some(hi), None) => {
out.push(decode_hex_digit(hi)? << 4);
break;
}
(None, _) => break,
}
}
}
Some(())
}
#[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,
}
}