Fix zero-capacity lists ()

auto-jit
A. R. Shajii 2023-07-12 10:19:24 -04:00 committed by GitHub
parent 0226a73370
commit d12800c855
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 0 deletions
stdlib/internal/types/collections

View File

@ -9,6 +9,8 @@ class List:
self.len = 0
def __init__(self, capacity: int):
if capacity < 0:
capacity = 0
self.arr = Array[T](capacity)
self.len = 0
@ -372,6 +374,8 @@ class List:
def _resize_if_full(self):
if self.len == self.arr.len:
new_cap = (1 + 3 * self.len) // 2
if new_cap <= 0:
new_cap = 1
self._resize(new_cap)
def __hash__(self) -> int:

View File

@ -299,6 +299,24 @@ def test_list():
assert list(reversed(list('abc'))) == ['c', 'b', 'a']
assert list(list('abc')[::-1]) == ['c', 'b', 'a']
assert list(reversed(List[str]())) == List[str]()
# https://github.com/exaloop/codon/issues/402
b1 = [1 for _ in range(0)]
b2 = [str(x) for x in b1]
b3 = List[float](capacity=0)
b4 = List[float](capacity=-1)
assert len(b1) == 0
assert len(b2) == 0
assert len(b3) == 0
assert len(b4) == 0
b1.append(42)
b2.append('a')
b3.append(4.2)
b4.append(2.4)
assert b1 == [42]
assert b2 == ['a']
assert b3 == [4.2]
assert b4 == [2.4]
test_list()
@test