Skip to content

Commit

Permalink
use functools cache to improve performance
Browse files Browse the repository at this point in the history
  • Loading branch information
andersonhc committed May 7, 2024
1 parent d7d0ab2 commit 1f3eb9f
Showing 1 changed file with 3 additions and 7 deletions.
10 changes: 3 additions & 7 deletions fpdf/fonts.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from bisect import bisect_left
from collections import defaultdict
from dataclasses import dataclass, replace
from functools import lru_cache
from typing import List, Optional, Tuple, Union

from fontTools import ttLib
Expand Down Expand Up @@ -449,8 +450,6 @@ def __init__(self, font: TTFFont, identities: List[int]):
glyph = self.get_glyph(unicode=x)
if glyph:
self._char_id_per_glyph[glyph] = int(x)
# This is a cache to speed things up:
self._char_id_per_unicode = {}

def __repr__(self):
return (
Expand All @@ -465,10 +464,8 @@ def items(self):
for glyph, char_id in self._char_id_per_glyph.items():
yield glyph, char_id

@lru_cache(maxsize=128)
def pick(self, unicode: int):
cache_hit = self._char_id_per_unicode.get(unicode)
if cache_hit:
return cache_hit
glyph = self.get_glyph(unicode=unicode)
if glyph is None and unicode not in self.font.missing_glyphs:
self.font.missing_glyphs.append(unicode)
Expand All @@ -484,10 +481,9 @@ def pick_glyph(self, glyph):
char_id = self._next
self._char_id_per_glyph[glyph] = char_id
self._next += 1
# Fill cache:
self._char_id_per_unicode[glyph.unicode] = char_id
return char_id

@lru_cache(maxsize=128)
def get_glyph(
self, glyph=None, unicode=None, glyph_name=None, glyph_width=None
) -> Glyph:
Expand Down

0 comments on commit 1f3eb9f

Please sign in to comment.