Skip to content

Commit

Permalink
Fix list reversal
Browse files Browse the repository at this point in the history
lst->data is NULL for a 0 length list, which we can't copy, so got to
check!

And for reversed() we have to actually return the reversed copy of the
list, not the original! ;)

Add some tests for it...
  • Loading branch information
plajjan committed Aug 28, 2023
1 parent e659bcd commit 384142a
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@
- Fix module import check [#1420]
- Avoid segfault when exception `error_message` is not set [#1422]
- Bump Zig version to v0.11.0 [#1421]
- Fix `reversed([])` which would `SIGILL` in dev mode [#1455]
- Fix `reversed([1,2,3])` which now returns reversed result [#1455]
- Previous code did the reversal but returned the original value :P


## [0.16.0] (2023-07-03)
Expand Down
7 changes: 4 additions & 3 deletions base/builtin/list.c
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,8 @@ B_list B_listD_copy(B_list lst) {
int len = lst->length;
B_list res = B_listD_new(len);
res->length = len;
memcpy(res->data, lst->data, len*sizeof($WORD));
if (len > 0)
memcpy(res->data, lst->data, len*sizeof($WORD));
return res;
}

Expand Down Expand Up @@ -447,8 +448,8 @@ B_NoneType B_SequenceD_listD_reverse(B_SequenceD_list wit, B_list lst) {

B_Iterator B_SequenceD_listD___reversed__(B_SequenceD_list wit, B_list lst) {
B_list copy = B_listD_copy(lst);
B_SequenceD_listD_reverse(wit,copy);
return B_CollectionD_SequenceD_listD___iter__((B_CollectionD_SequenceD_list)wit->W_Collection, lst);
B_SequenceD_listD_reverse(wit, copy);
return B_CollectionD_SequenceD_listD___iter__((B_CollectionD_SequenceD_list)wit->W_Collection, copy);
}

B_NoneType B_SequenceD_listD_insert(B_SequenceD_list wit, B_list lst, B_int n, $WORD elem) {
Expand Down
15 changes: 15 additions & 0 deletions test/builtins_auto/list.act
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,21 @@ actor main(env):
print("Unexpected result of list.reverse():", l)
await async env.exit(1)

lr = list(reversed([]))
if lr != []:
print("Unexpected result of reversed([]):", lr)
await async env.exit(1)

lr2 = list(reversed([1]))
if lr2 != [1]:
print("Unexpected result of reversed([]):", lr2)
await async env.exit(1)

lr3 = list(reversed([1,2,3]))
if lr3 != [3,2,1]:
print("Unexpected result of reversed([1,2,3]):", lr3)
await async env.exit(1)

del l[1]
if l != [56, 3, 2, 37, 1, 0]:
print("Unexpected result of del list[1]:", l)
Expand Down

0 comments on commit 384142a

Please sign in to comment.