Skip to content

Commit

Permalink
StringVariable.format_value() inline translate
Browse files Browse the repository at this point in the history
Do translation of escapable string values inline in format_value(). This
removes a bit of function call overhead.

The control-flow is further optimized to avoid calling translate when
the incoming value is None.
  • Loading branch information
jpgrayson committed Dec 15, 2020
1 parent 278c393 commit e0f7781
Showing 1 changed file with 12 additions and 17 deletions.
29 changes: 12 additions & 17 deletions vcd/writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -664,11 +664,19 @@ def format_value(self, value: StringValue, check: bool = True) -> str:
"""
if value is None:
value = ''
if check and not isinstance(value, str):
value_str = ''
elif check and not isinstance(value, str):
raise ValueError(f'Invalid string value ({value!r})')

value_str = _escape_string(value)
else:
value_str = value.translate(
{
9: "\\t",
10: "\\n",
13: "\\r",
32: "\\x20",
92: "\\\\",
}
)
return f's{value_str} {self.ident}'


Expand Down Expand Up @@ -815,16 +823,3 @@ 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 e0f7781

Please sign in to comment.