Skip to content

Commit

Permalink
Use a set to represent supported character codes
Browse files Browse the repository at this point in the history
  • Loading branch information
jparise committed Dec 30, 2021
1 parent b42b564 commit 332e432
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
5 changes: 3 additions & 2 deletions tests/test_chars.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import unittest

from vesta.chars import CHARCODES
from vesta.chars import CHARMAP
from vesta.chars import COLS
from vesta.chars import ROWS
from vesta.chars import Color
Expand All @@ -11,11 +12,11 @@

class EncodeTests(unittest.TestCase):
def test_printable_characters(self):
for c in CHARCODES:
for c in CHARMAP:
encode(c)

def test_character_codes(self):
for i in range(0, 70):
for i in CHARCODES:
encode(f"{{{i}}}")

def test_bad_characters(self):
Expand Down
10 changes: 7 additions & 3 deletions vesta/chars.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
ROWS = 6
COLS = 22
PRINTABLE = " ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$() - +&=;: '\"%,. /? °"
CHARCODES = {c: idx for idx, c in enumerate(PRINTABLE) if idx == 0 or c != " "}
CHARMAP = {c: idx for idx, c in enumerate(PRINTABLE) if idx == 0 or c != " "}


class Color(enum.IntEnum):
Expand All @@ -38,6 +38,10 @@ def __new__(cls, value: int, ansi: str):
# fmt: on


#: The set of all supported character codes.
CHARCODES = frozenset(CHARMAP.values()).union(Color)


def encode(s: str) -> List[int]:
"""Encodes a string as a list of character codes.
Expand Down Expand Up @@ -65,11 +69,11 @@ def encode(s: str) -> List[int]:
skip_to = i + 4
else:
raise ValueError(f"{i+1}: missing }} at index {i+2} or {i+3}")
if not (0 <= out[-1] <= 69):
if out[-1] not in CHARCODES:
raise ValueError(f"{i+2}: unsupported character code: {out[-1]}")
else:
try:
out.append(CHARCODES[c])
out.append(CHARMAP[c])
except KeyError:
raise ValueError(f"{i+1}: unsupported character: {c}")

Expand Down

0 comments on commit 332e432

Please sign in to comment.