Skip to content

Commit

Permalink
[psCharStrings] Shorten output of encodeFloat
Browse files Browse the repository at this point in the history
  • Loading branch information
dscorbett committed May 8, 2024
1 parent 6db3cee commit 92bd376
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 3 deletions.
20 changes: 20 additions & 0 deletions Lib/fontTools/misc/psCharStrings.py
Expand Up @@ -275,6 +275,24 @@ def encodeFloat(f):
s = s[1:]
elif s[:3] == "-0.":
s = "-" + s[2:]
elif s.endswith("000"):
significantDigits = s.rstrip("0")
s = "%sE%d" % (significantDigits, len(s) - len(significantDigits))
else:
dotIndex = s.find(".")
eIndex = s.find("E")
if dotIndex != -1 and eIndex != -1:
integerPart = s[:dotIndex]
fractionalPart = s[dotIndex + 1 : eIndex]
exponent = int(s[eIndex + 1 :])
newExponent = exponent - len(fractionalPart)
if newExponent == 1:
s = "%s%s0" % (integerPart, fractionalPart)
else:
s = "%s%sE%d" % (integerPart, fractionalPart, newExponent)
if s.startswith((".0", "-.0")):
sign, s = s.split(".", 1)
s = "%s%sE-%d" % (sign, s.lstrip("0"), len(s))
nibbles = []
while s:
c = s[0]
Expand All @@ -286,6 +304,8 @@ def encodeFloat(f):
c = "E-"
elif c2 == "+":
s = s[1:]
if s.startswith("0"):
s = s[1:]
nibbles.append(realNibblesDict[c])
nibbles.append(0xF)
if len(nibbles) % 2:
Expand Down
19 changes: 16 additions & 3 deletions Tests/misc/psCharStrings_test.py
Expand Up @@ -87,9 +87,22 @@ def test_encodeFloat(self):
(1.0, "1e 1f"), # 1
(-1.0, "1e e1 ff"), # -1
(98765.37e2, "1e 98 76 53 7f"), # 9876537
(1234567890.0, "1e 1a 23 45 67 9b 09 ff"), # 1234567890
(9.876537e-4, "1e a0 00 98 76 53 7f"), # 9.876537e-24
(9.876537e4, "1e 98 76 5a 37 ff"), # 9.876537e+24
(1234567890.0, "1e 12 34 56 79 b2 ff"), # 12345679E2
(9.876537e-4, "1e 98 76 53 7c 10 ff"), # 9876537E-10
(9.876537e4, "1e 98 76 5a 37 ff"), # 98765.37
(1000.0, "1e 1b 3f"), # 1E3
(-1000.0, "1e e1 b3 ff"), # -1E3
(1e8, "1e 1b 8f"), # 1E8
(1e-5, "1e 1c 5f"), # 1E-5
(1.2e8, "1e 12 b7 ff"), # 12E7
(1.2345e-5, "1e 12 34 5c 9f"), # 12345E-9
(9.0987654e8, "1e 90 98 76 54 0f"), # 909876540
(0.1, "1e a1 ff"), # .1
(-0.1, "1e ea 1f"), # -.1
(0.01, "1e 1c 2f"), # 1e-2
(-0.01, "1e e1 c2 ff"), # -1e-2
(0.0123, "1e 12 3c 4f"), # 123e-4
(-0.0123, "1e e1 23 c4 ff"), # -123e-4
]

for sample in testNums:
Expand Down
Binary file modified Tests/ttLib/tables/data/C_F_F_.bin
Binary file not shown.

0 comments on commit 92bd376

Please sign in to comment.