Merge pull request #1683 from willmcgugan/fix-infinite-loop

fix infinite loop
This commit is contained in:
Will McGugan 2021-11-13 09:09:09 +00:00 committed by GitHub
commit e9e4bee4af
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 21 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 progress speed not updating when total doesn't change
- Fixed superfluous new line in Status https://github.com/willmcgugan/rich/issues/1662 - 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 ## [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: def set_cell_size(text: str, total: int) -> str:
"""Set the length of a string to fit within given number of cells.""" """Set the length of a string to fit within given number of cells."""
if not total:
return ""
cell_size = cell_len(text) cell_size = cell_len(text)
if cell_size == total: if cell_size == total:
return text return text
@ -81,12 +83,12 @@ def set_cell_size(text: str, total: int) -> str:
return text + " " * (total - cell_size) return text + " " * (total - cell_size)
start = 0 start = 0
end = cell_size end = len(text)
# Binary search until we find the right size # Binary search until we find the right size
while True: while True:
pos = (start + end) // 2 pos = (start + end) // 2
before = text[:pos] before = text[: pos + 1]
before_len = cell_len(before) before_len = cell_len(before)
if before_len == total + 1 and cell_len(before[-1]) == 2: if before_len == total + 1 and cell_len(before[-1]) == 2:
return before[:-1] + " " return before[:-1] + " "

View File

@ -2,6 +2,10 @@ from rich import cells
def test_set_cell_size(): def test_set_cell_size():
assert cells.set_cell_size("foo", 0) == ""
assert cells.set_cell_size("f", 0) == ""
assert cells.set_cell_size("", 0) == ""
assert cells.set_cell_size("😽😽", 0) == ""
assert cells.set_cell_size("foo", 2) == "fo" assert cells.set_cell_size("foo", 2) == "fo"
assert cells.set_cell_size("foo", 3) == "foo" assert cells.set_cell_size("foo", 3) == "foo"
assert cells.set_cell_size("foo", 4) == "foo " assert cells.set_cell_size("foo", 4) == "foo "
@ -9,3 +13,15 @@ def test_set_cell_size():
assert cells.set_cell_size("😽😽", 3) == "😽 " assert cells.set_cell_size("😽😽", 3) == "😽 "
assert cells.set_cell_size("😽😽", 2) == "😽" assert cells.set_cell_size("😽😽", 2) == "😽"
assert cells.set_cell_size("😽😽", 1) == " " 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
)