fix infinite loop

This commit is contained in:
Will McGugan 2021-11-13 09:04:12 +00:00
parent 77158a57ee
commit 8a74a97563
3 changed files with 17 additions and 2 deletions

View File

@ -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

View File

@ -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] + " "

View File

@ -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
)