terminalwriter: optimize get_line_width() a bit

This function is called a lot when printing a lot of text, and is very
slow -- this speeds it up a bit.
This commit is contained in:
Ran Benita 2020-04-29 15:28:26 +03:00
parent 6c1b6a09b8
commit 9a59970cad
1 changed files with 6 additions and 9 deletions

View File

@ -3,6 +3,7 @@ import os
import shutil import shutil
import sys import sys
import unicodedata import unicodedata
from functools import lru_cache
from io import StringIO from io import StringIO
@ -33,19 +34,15 @@ def get_terminal_width() -> int:
return width return width
char_width = { @lru_cache(100)
"A": 1, # "Ambiguous" def char_width(c: str) -> int:
"F": 2, # Fullwidth # Fullwidth and Wide -> 2, all else (including Ambiguous) -> 1.
"H": 1, # Halfwidth return 2 if unicodedata.east_asian_width(c) in ("F", "W") else 1
"N": 1, # Neutral
"Na": 1, # Narrow
"W": 2, # Wide
}
def get_line_width(text): def get_line_width(text):
text = unicodedata.normalize("NFC", text) text = unicodedata.normalize("NFC", text)
return sum(char_width.get(unicodedata.east_asian_width(c), 1) for c in text) return sum(char_width(c) for c in text)
# XXX unify with _escaped func below # XXX unify with _escaped func below