Skip to content
Merged
Prev Previous commit
Next Next commit
Optimize disp_str for ASCII characters
Since every ASCII character is known to display as single width, we can
avoid not only the Unicode data lookup in `disp_str` but also the one
hidden in `str_width` for them.

Signed-off-by: Matt Wozniski <mwozniski@bloomberg.net>
  • Loading branch information
godlygeek committed Jun 8, 2024
commit 07b3302e1aa2e3765f121c10a3340e15c18f2a0f
16 changes: 11 additions & 5 deletions Lib/_pyrepl/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
def disp_str(buffer: str) -> tuple[str, list[int]]:
"""disp_str(buffer:string) -> (string, [int])

Return the string that should be the printed represenation of
Return the string that should be the printed representation of
|buffer| and a list detailing where the characters of |buffer|
get used up. E.g.:

Expand All @@ -52,11 +52,17 @@ def disp_str(buffer: str) -> tuple[str, list[int]]:
b: list[int] = []
s: list[str] = []
for c in buffer:
if ord(c) > 128 and unicodedata.category(c).startswith("C"):
if ord(c) < 128:
s.append(c)
b.append(1)
elif unicodedata.category(c).startswith("C"):
c = r"\u%04x" % ord(c)
s.append(c)
b.append(wlen(c))
b.extend([0] * (len(c) - 1))
s.append(c)
b.append(str_width(c))
b.extend([0] * (len(c) - 1))
else:
s.append(c)
b.append(str_width(c))
return "".join(s), b


Expand Down