Skip to content

Commit

Permalink
Fix zero-capacity lists (exaloop#420)
Browse files Browse the repository at this point in the history
  • Loading branch information
arshajii authored Jul 12, 2023
1 parent 0226a73 commit d12800c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
4 changes: 4 additions & 0 deletions stdlib/internal/types/collections/list.codon
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down
18 changes: 18 additions & 0 deletions test/core/containers.codon
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit d12800c

Please sign in to comment.