Skip to content

Commit

Permalink
Escape all special characters when emitting GTKWave strings.
Browse files Browse the repository at this point in the history
Fixes #17.
  • Loading branch information
whitequark authored and jpgrayson committed Dec 15, 2020
1 parent fead949 commit 278c393
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 10 deletions.
20 changes: 13 additions & 7 deletions tests/test_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -923,11 +923,12 @@ def test_vcd_string_var(capsys):
vcd.change(v0, 1, 'hello')
vcd.change(v0, 2, '')
vcd.change(v0, 3, 'world')
with pytest.raises(ValueError):
vcd.change(v0, 4, 'no string allowed')
vcd.change(v0, 4, None)
vcd.change(v0, 5, '!')
vcd.dump_off(6)
vcd.change(v0, 4, 'spaces are\tok')
vcd.change(v0, 5, 'newlines\r\ntoo')
vcd.change(v0, 6, 'slash\\slash')
vcd.change(v0, 7, None)
vcd.change(v0, 8, '!')
vcd.dump_off(8)
expected = [
'#0',
'$dumpvars',
Expand All @@ -941,10 +942,15 @@ def test_vcd_string_var(capsys):
'#3',
'sworld !',
'#4',
's !',
'sspaces\\x20are\\tok !',
'#5',
's! !',
'snewlines\\r\\ntoo !',
'#6',
'sslash\\\\slash !',
'#7',
's !',
'#8',
's! !',
'$dumpoff',
'$end',
]
Expand Down
20 changes: 17 additions & 3 deletions vcd/writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -665,10 +665,11 @@ def format_value(self, value: StringValue, check: bool = True) -> str:
"""
if value is None:
value = ''
if check and (not isinstance(value, str) or ' ' in value):
raise ValueError(f'Invalid string value ({value})')
if check and not isinstance(value, str):
raise ValueError(f'Invalid string value ({value!r})')

return f's{value} {self.ident}'
value_str = _escape_string(value)
return f's{value_str} {self.ident}'


class RealVariable(Variable[RealValue]):
Expand Down Expand Up @@ -814,3 +815,16 @@ def _encode_identifier(v: int) -> str:
encoded += chr((v % 94) + 33)
v //= 94
return encoded


def _escape_string(v: str) -> str:
"""Escape special characters for GTKWave."""
return v.translate(
{
9: "\\t",
10: "\\n",
13: "\\r",
32: "\\x20",
92: "\\\\",
}
)

0 comments on commit 278c393

Please sign in to comment.