From 8a74a97563dad3437ce537ed07dc72e031c54638 Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Sat, 13 Nov 2021 09:04:12 +0000 Subject: [PATCH] fix infinite loop --- CHANGELOG.md | 1 + rich/cells.py | 6 ++++-- tests/test_cells.py | 12 ++++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 804769d4..34ac4965 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fixed progress speed not updating when total doesn't change - Fixed superfluous new line in Status https://github.com/willmcgugan/rich/issues/1662 +- Fixed infinite loop in set_cell_size https://github.com/willmcgugan/rich/issues/1682 ## [10.13.0] - 2021-11-07 diff --git a/rich/cells.py b/rich/cells.py index 7f9c0c16..b02f4b86 100644 --- a/rich/cells.py +++ b/rich/cells.py @@ -74,6 +74,8 @@ def _get_codepoint_cell_size(codepoint: int) -> int: def set_cell_size(text: str, total: int) -> str: """Set the length of a string to fit within given number of cells.""" + if not total: + return "" cell_size = cell_len(text) if cell_size == total: return text @@ -81,12 +83,12 @@ def set_cell_size(text: str, total: int) -> str: return text + " " * (total - cell_size) start = 0 - end = cell_size + end = len(text) # Binary search until we find the right size while True: pos = (start + end) // 2 - before = text[:pos] + before = text[: pos + 1] before_len = cell_len(before) if before_len == total + 1 and cell_len(before[-1]) == 2: return before[:-1] + " " diff --git a/tests/test_cells.py b/tests/test_cells.py index 06de4372..7633944b 100644 --- a/tests/test_cells.py +++ b/tests/test_cells.py @@ -9,3 +9,15 @@ def test_set_cell_size(): assert cells.set_cell_size("😽😽", 3) == "😽 " assert cells.set_cell_size("😽😽", 2) == "😽" assert cells.set_cell_size("😽😽", 1) == " " + + +def test_set_cell_size_infinite(): + for size in range(38): + assert ( + cells.cell_len( + cells.set_cell_size( + "เป็นเกมที่ต้องมีความอดทนมากที่สุดตั้งเเต่เคยเล่นมา", size + ) + ) + == size + )