Skip to content

Commit

Permalink
Improve and slightly change hex formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
kg583 committed Nov 23, 2024
1 parent 170e063 commit 2192f25
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
5 changes: 5 additions & 0 deletions tests/tivars.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,11 @@ def test_truthiness(self):
test_program.clear()
self.assertEqual(bool(test_program), True)

def test_hex(self):
test_program = TIEntry.open("tests/data/var/Program.8xp")
self.assertEqual(f"{test_program}", "setDate(1")
self.assertEqual(f"{test_program:-2X:}", "0300:EF00:31")


class TokenizationTests(unittest.TestCase):
def test_load_from_file(self):
Expand Down
15 changes: 10 additions & 5 deletions tivars/var.py
Original file line number Diff line number Diff line change
Expand Up @@ -431,19 +431,24 @@ def __format__(self, format_spec: str) -> str:
:return: A string representation of this entry
"""

if match := re.fullmatch(r"(?P<sep>\D)?(?P<width>\d+)?x", format_spec):
if match := re.fullmatch(r"(?P<width>[+-]?\d+)?(?P<case>[xX])(?P<sep>\D)?", format_spec):
match match["sep"], match["width"]:
case None, None:
return self.calc_data.hex()
string = self.calc_data.hex()

case sep, None:
return self.calc_data.hex(sep)
string = self.calc_data.hex(sep)

case None, width:
return self.calc_data.hex(" ", int(width))
string = self.calc_data.hex(" ", int(width))

case sep, width:
return self.calc_data.hex(sep, int(width))
string = self.calc_data.hex(sep, int(width))

return string if match["case"] == "x" else string.upper()

elif not format_spec:
return super().__str__()

else:
raise TypeError(f"unsupported format string passed to {type(self)}.__format__")
Expand Down

0 comments on commit 2192f25

Please sign in to comment.