Skip to content

Commit 507db0e

Browse files
committed
Cache toUnicodeCMap characters
1 parent 86b0944 commit 507db0e

1 file changed

Lines changed: 15 additions & 8 deletions

File tree

src/Document/CMap/ToUnicode/ToUnicodeCMap.php

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,12 @@
55
use PrinsFrank\PdfParser\Exception\InvalidArgumentException;
66
use PrinsFrank\PdfParser\Exception\PdfParserException;
77

8-
readonly class ToUnicodeCMap {
8+
class ToUnicodeCMap {
99
/** @var list<BFRange|BFChar> */
10-
private array $bfCharRangeInfo;
10+
private readonly array $bfCharRangeInfo;
11+
12+
/** @var array<int, string> */
13+
private array $charCache = [];
1114

1215
/**
1316
* @no-named-arguments
@@ -17,8 +20,8 @@
1720
* @throws InvalidArgumentException
1821
*/
1922
public function __construct(
20-
public array $codeSpaceRanges,
21-
public int $byteSize,
23+
public readonly array $codeSpaceRanges,
24+
public readonly int $byteSize,
2225
BFRange|BFChar ...$bfCharRangeInfo,
2326
) {
2427
$this->bfCharRangeInfo = $bfCharRangeInfo;
@@ -41,25 +44,29 @@ public function textToUnicode(string $characterGroup): string {
4144

4245
/** @throws PdfParserException */
4346
protected function charToUnicode(int $characterCode): ?string {
47+
if (array_key_exists($characterCode, $this->charCache)) {
48+
return $this->charCache[$characterCode];
49+
}
50+
4451
$char = null;
4552
foreach ($this->bfCharRangeInfo as $bfCharRangeInfo) {
4653
if (!$bfCharRangeInfo->containsCharacterCode($characterCode)) {
4754
continue;
4855
}
4956

5057
if (($char = $bfCharRangeInfo->toUnicode($characterCode)) !== "\0") { // Some characters map to NULL in one BFRange and to an actual character in another
51-
return $char;
58+
return $this->charCache[$characterCode] = $char;
5259
}
5360
}
5461

5562
if ($char === "\0") {
56-
return $char; // Only return NULL when it is the only character this is mapped to
63+
return $this->charCache[$characterCode] = $char; // Only return NULL when it is the only character this is mapped to
5764
}
5865

5966
if ($characterCode === 0) {
60-
return '';
67+
return $this->charCache[$characterCode] = '';
6168
}
6269

63-
return null;
70+
return $this->charCache[$characterCode] = null;
6471
}
6572
}

0 commit comments

Comments
 (0)