Coding style.

- Don't waste memory by storing sub-strings.
This commit is contained in:
Andrew Hamilton 2021-07-11 16:41:06 +10:00
parent 071096821c
commit e6380bb1d7

View file

@ -220,17 +220,15 @@ class TermStr(collections.UserString):
for index, style in enumerate(self.style): for index, style in enumerate(self.style):
if style != last_style: if style != last_style:
if last_style is not None: if last_style is not None:
result.append( result.append((last_style, last_index, index))
(last_style, self.data[last_index:index], last_index))
last_style, last_index = style, index last_style, last_index = style, index
result.append( result.append((last_style, last_index, len(self.style)))
(last_style, self.data[last_index:len(self.style)], last_index))
return result return result
def __str__(self): def __str__(self):
return "".join(_join_lists( return "".join(_join_lists(
[style.code_for_term, str_] [style.code_for_term, self.data[start_index:end_index]]
for style, str_, position in self._partition_style) + for style, start_index, end_index in self._partition_style) +
[terminal.ESC + terminal.normal]) [terminal.ESC + terminal.normal])
def __repr__(self): def __repr__(self):
@ -314,9 +312,9 @@ class TermStr(collections.UserString):
# Below are extra methods useful for termstrs. # Below are extra methods useful for termstrs.
def transform_style(self, transform_func): def transform_style(self, transform_func):
new_style = tuple(_join_lists([transform_func(style)] * len(str_) new_style = tuple(_join_lists(
for style, str_, position [transform_func(style)] * (end_index - start_index)
in self._partition_style)) for style, start_index, end_index in self._partition_style))
return self.__class__(self.data, new_style) return self.__class__(self.data, new_style)
def bold(self): def bold(self):
@ -357,9 +355,9 @@ class TermStr(collections.UserString):
def as_html(self): def as_html(self):
result = [] result = []
styles = set() styles = set()
for style, str_, position in self._partition_style: for style, start_index, end_index in self._partition_style:
styles.add(style) styles.add(style)
encoded = str(html.escape(str_).encode( encoded = str(html.escape(self.data[start_index:end_index]).encode(
"ascii", "xmlcharrefreplace"))[2:-1] "ascii", "xmlcharrefreplace"))[2:-1]
encoded = encoded.replace("\\\\", "\\") encoded = encoded.replace("\\\\", "\\")
result.append(f'<span class="S{id(style):d}">{encoded}</span>') result.append(f'<span class="S{id(style):d}">{encoded}</span>')