Skip to content

Commit

Permalink
Refactor cache key in Text.render.
Browse files Browse the repository at this point in the history
For a reason similar to that of 7fbcc6d, we need to use the style indices as cache keys here and not the styles themselves because styles that have the same link/meta will have different link IDs, but have the same hash, so there will be cache collisions that we need to avoid.
  • Loading branch information
rodrigogiraoserrao committed Sep 26, 2023
1 parent 7fbcc6d commit 7eb7c92
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions rich/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -746,18 +746,19 @@ def render(self, console: "Console", end: str = "") -> Iterable["Segment"]:
stack_append = stack.append
stack_pop = stack.remove

style_cache: Dict[Tuple[Style, ...], Style] = {}
style_cache: Dict[Tuple[int, ...], Style] = {}
style_cache_get = style_cache.get
combine = Style.combine

def get_current_style() -> Style:
"""Construct current style from stack."""
styles = tuple(style_map[_style_id] for _style_id in sorted(stack))
cached_style = style_cache_get(styles)
cache_key = tuple(sorted(stack))
cached_style = style_cache_get(cache_key)
if cached_style is not None:
return cached_style
styles = tuple(style_map[_style_id] for _style_id in sorted(stack))
current_style = combine(styles)
style_cache[styles] = current_style
style_cache[cache_key] = current_style
return current_style

for (offset, leaving, style_id), (next_offset, _, _) in zip(spans, spans[1:]):
Expand Down

0 comments on commit 7eb7c92

Please sign in to comment.