diff --git a/src/Pdf/PdfFont.php b/src/Pdf/PdfFont.php index 9d570dc..9081cb5 100644 --- a/src/Pdf/PdfFont.php +++ b/src/Pdf/PdfFont.php @@ -130,6 +130,7 @@ public function reset(): void $this->usedGlyphs = []; $this->writerRegistrations = new \WeakMap; $this->decodeCache = []; + $this->recentDecodes = []; } /** @@ -372,16 +373,31 @@ public function supportsText(string $text): bool private bool $indicShapingEnabled = true; /** - * Bounded LRU cache for decodeUtf8 results - TextMeasurer - * (Engine layout) repeatedly calls on the same words while measuring - * line-fits, justification, etc. + * decodeUtf8 results for short strings - words, numbers, labels - which + * come back throughout a document: layout measures the same words over + * and over. Oldest out first once DECODE_CACHE_MAX are held. * * @var array> */ private array $decodeCache = []; + /** + * decodeUtf8 results for longer strings, such as a whole line drawn at + * once. These mostly come back within the same draw (shaped, then + * encoded), so a few recent ones are enough. Each entry costs ~400 + * bytes per character, so they stay out of the large cache. + * + * @var array> + */ + private array $recentDecodes = []; + private const DECODE_CACHE_MAX = 2048; + private const RECENT_DECODES_MAX = 16; + + /** Strings up to this many bytes go in the large cache. */ + private const SHORT_STRING_MAX_BYTES = 32; + /** * Disable Arabic shaping (for debug or if font handles * shaping itself via GSUB rather than Presentation Forms B). @@ -423,12 +439,12 @@ public function disableIndicShaping(): void */ public function decodeUtf8(string $utf8): array { - // Memo cache. TextMeasurer repeatedly calls decodeUtf8 - // on the same words during layout passes; without cache the pipeline - // (utf8 to cps + Arabic/Indic shape + Bidi + cmap + rphf) runs - // every time and blows memory. Bounded FIFO cap = 2048 entries. - if (isset($this->decodeCache[$utf8])) { - return $this->decodeCache[$utf8]; + // The pipeline below (utf8 to cps + Arabic/Indic shape + Bidi + + // cmap + rphf) is cached; see $decodeCache and $recentDecodes. + $short = strlen($utf8) <= self::SHORT_STRING_MAX_BYTES; + $cached = $short ? ($this->decodeCache[$utf8] ?? null) : ($this->recentDecodes[$utf8] ?? null); + if ($cached !== null) { + return $cached; } $cps = self::utf8ToCps($utf8); @@ -470,11 +486,19 @@ public function decodeUtf8(string $utf8): array } } - // Bounded FIFO eviction: drop oldest entry when reached cap. - if (count($this->decodeCache) >= self::DECODE_CACHE_MAX) { - array_shift($this->decodeCache); + // Drop the oldest entry at the cap. unset, not array_shift: a key + // like "1" is stored as an integer, and array_shift would renumber it. + if ($short) { + if (count($this->decodeCache) >= self::DECODE_CACHE_MAX) { + unset($this->decodeCache[array_key_first($this->decodeCache)]); + } + $this->decodeCache[$utf8] = $out; + } else { + if (count($this->recentDecodes) >= self::RECENT_DECODES_MAX) { + unset($this->recentDecodes[array_key_first($this->recentDecodes)]); + } + $this->recentDecodes[$utf8] = $out; } - $this->decodeCache[$utf8] = $out; return $out; } diff --git a/tests/Pdf/PdfFontDecodeCacheTest.php b/tests/Pdf/PdfFontDecodeCacheTest.php new file mode 100644 index 0000000..d3de3df --- /dev/null +++ b/tests/Pdf/PdfFontDecodeCacheTest.php @@ -0,0 +1,131 @@ +font = new PdfFont(TtfFile::fromFile($path)); + } + + #[Test] + public function numeric_words_keep_their_glyphs_after_the_cache_evicts(): void + { + $expected = []; + foreach (['1', '15', '21', '42'] as $word) { + $expected[$word] = $this->font->decodeUtf8($word); + } + // Fill the cache past its cap so the oldest entries are evicted. + for ($i = 0; $i < self::CACHE_MAX + 10; $i++) { + $this->font->decodeUtf8("w$i"); + $this->font->decodeUtf8((string) (1000 + $i)); + } + + foreach ($expected as $word => $glyphs) { + // Array keys come back as ints too: "1" is 1. + self::assertSame($glyphs, $this->font->decodeUtf8((string) $word), "glyphs of \"$word\""); + } + } + + #[Test] + public function a_numeric_word_still_cached_is_not_confused_with_another(): void + { + // "1" and "15" stay in the cache while a string key ahead of them + // is evicted — the case that renumbered "15" to key 1. + $this->font->decodeUtf8('first'); + $one = $this->font->decodeUtf8('1'); + $this->font->decodeUtf8('15'); + for ($i = 0; $i < self::CACHE_MAX - 2; $i++) { + $this->font->decodeUtf8("w$i"); + } + + self::assertCount(1, $one); + self::assertSame($one, $this->font->decodeUtf8('1')); + self::assertCount(2, $this->font->decodeUtf8('15')); + } + + #[Test] + public function long_lines_stay_out_of_the_word_cache(): void + { + $word = $this->font->decodeUtf8('invoice'); + for ($i = 0; $i < self::CACHE_MAX + 10; $i++) { + $this->font->decodeUtf8("Line $i of a paragraph drawn as one run of text."); + } + + self::assertSame(['invoice'], array_keys($this->cache('decodeCache'))); + self::assertCount(16, $this->cache('recentDecodes')); + self::assertSame($word, $this->font->decodeUtf8('invoice')); + } + + #[Test] + public function a_line_decoded_again_soon_is_served_from_the_cache(): void + { + $line = 'A line of text drawn once to shape it, then again to encode it.'; + $glyphs = $this->font->decodeUtf8($line); + for ($i = 0; $i < 15; $i++) { + $this->font->decodeUtf8("Another line of text, number $i of fifteen."); + } + + self::assertArrayHasKey($line, $this->cache('recentDecodes')); + self::assertSame($glyphs, $this->font->decodeUtf8($line)); + } + + #[Test] + public function cached_glyphs_match_a_fresh_decode_on_either_side_of_the_cutoff(): void + { + $path = __DIR__.'/../../.cache/fonts/liberation-fonts-ttf-2.1.5/LiberationSans-Regular.ttf'; + $strings = [str_repeat('a', 32), str_repeat('b', 33), str_repeat('é', 16), str_repeat('é', 17)]; + foreach ($strings as $s) { + $this->font->decodeUtf8($s); + } + + foreach ($strings as $s) { + $fresh = new PdfFont(TtfFile::fromFile($path)); + self::assertSame($fresh->decodeUtf8($s), $this->font->decodeUtf8($s), $s); + } + self::assertCount(2, $this->cache('decodeCache')); + self::assertCount(2, $this->cache('recentDecodes')); + } + + #[Test] + public function reset_empties_both_caches(): void + { + $this->font->decodeUtf8('word'); + $this->font->decodeUtf8('A line long enough to skip the word cache entirely.'); + $this->font->reset(); + + self::assertSame([], $this->cache('decodeCache')); + self::assertSame([], $this->cache('recentDecodes')); + } + + /** @return array */ + private function cache(string $name): array + { + return (new \ReflectionProperty(PdfFont::class, $name))->getValue($this->font); + } +}