Skip to content

Commit

Permalink
Limit expected number of characters to nencoding
Browse files Browse the repository at this point in the history
  • Loading branch information
radarhere committed Jun 27, 2022
1 parent ce486e7 commit 0b6a65a
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 10 deletions.
Binary file added Tests/fonts/10x20-ISO8859-1-fewer-characters.pcf
Binary file not shown.
8 changes: 8 additions & 0 deletions Tests/test_font_pcf.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,14 @@ def test_sanity(request, tmp_path):
save_font(request, tmp_path)


def test_less_than_256_characters():
with open("Tests/fonts/10x20-ISO8859-1-fewer-characters.pcf", "rb") as test_file:
font = PcfFontFile.PcfFontFile(test_file)
assert isinstance(font, FontFile.FontFile)
# check the number of characters in the font
assert len([_f for _f in font.glyph if _f]) == 127


def test_invalid_file():
with open("Tests/images/flower.jpg", "rb") as fp:
with pytest.raises(SyntaxError):
Expand Down
16 changes: 6 additions & 10 deletions src/PIL/PcfFontFile.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,7 @@ def __init__(self, fp, charset_encoding="iso8859-1"):
#
# create glyph structure

for ch in range(256):
ix = encoding[ch]
for ch, ix in enumerate(encoding):
if ix is not None:
x, y, l, r, w, a, d, f = metrics[ix]
glyph = (w, 0), (l, d - y, x + l, d), (0, 0, x, y), bitmaps[ix]
Expand Down Expand Up @@ -219,22 +218,21 @@ def _load_bitmaps(self, metrics):
return bitmaps

def _load_encoding(self):

# map character code to bitmap index
encoding = [None] * 256

fp, format, i16, i32 = self._getformat(PCF_BDF_ENCODINGS)

first_col, last_col = i16(fp.read(2)), i16(fp.read(2))
first_row, last_row = i16(fp.read(2)), i16(fp.read(2))

i16(fp.read(2)) # default

nencoding = (last_col - first_col + 1) * (last_row - first_row + 1)
nencoding = min(256, (last_col - first_col + 1) * (last_row - first_row + 1))

# map character code to bitmap index
encoding = [None] * nencoding

encoding_offsets = [i16(fp.read(2)) for _ in range(nencoding)]

for i in range(first_col, len(encoding)):
for i in range(first_col, nencoding):
try:
encoding_offset = encoding_offsets[
ord(bytearray([i]).decode(self.charset_encoding))
Expand All @@ -244,7 +242,5 @@ def _load_encoding(self):
except UnicodeDecodeError:
# character is not supported in selected encoding
pass
except IndexError:
break

return encoding

0 comments on commit 0b6a65a

Please sign in to comment.