Skip to content

Commit

Permalink
improve Tuple iteration
Browse files Browse the repository at this point in the history
  • Loading branch information
awmorgan committed Dec 1, 2024
1 parent 7d18427 commit f72d799
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 15 deletions.
1 change: 1 addition & 0 deletions include/Cello.h
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,7 @@ struct String {
struct Tuple {
var* items;
size_t len;
size_t iter;
};

struct Range {
Expand Down
24 changes: 10 additions & 14 deletions src/Tuple.c
Original file line number Diff line number Diff line change
Expand Up @@ -152,33 +152,29 @@ static size_t Tuple_Len(var self) {

static var Tuple_Iter_Init(var self) {
struct Tuple* t = self;
t->iter = 0;
return t->items[0];
}

static var Tuple_Iter_Next(var self, var curr) {
struct Tuple* t = self;
size_t i = 0;
while (t->items[i] isnt Terminal) {
if (t->items[i] is curr) { return t->items[i+1]; }
i++;
}
return Terminal;
if (t->items[t->iter] is Terminal) { return Terminal; }
t->iter++;
return t->items[t->iter];
}

static var Tuple_Iter_Last(var self) {
struct Tuple* t = self;
return t->items[Tuple_Len(t)-1];
size_t len = Tuple_Len(t);
if (len is 0) { return Terminal; }
return t->items[len-1];
}

static var Tuple_Iter_Prev(var self, var curr) {
struct Tuple* t = self;
if (curr is t->items[0]) { return Terminal; }
size_t i = 0;
while (t->items[i] isnt Terminal) {
if (t->items[i] is curr) { return t->items[i-1]; }
i++;
}
return Terminal;
if (t->iter is 0) { return Terminal; }
t->iter--;
return t->items[t->iter];
}

static var Tuple_Get(var self, var key) {
Expand Down
5 changes: 4 additions & 1 deletion tests/test.c
Original file line number Diff line number Diff line change
Expand Up @@ -2495,10 +2495,13 @@ PT_FUNC(test_tuple_hash) {
PT_FUNC(test_tuple_iter) {

size_t i = 0;
foreach (x in tuple($I(10), $I(20), $I(30))) {
var y = $I(0);
foreach (x in tuple($I(10), $I(20), $I(30), y, y)) {
if (i is 0) { PT_ASSERT(eq(x, $I(10))); }
if (i is 1) { PT_ASSERT(eq(x, $I(20))); }
if (i is 2) { PT_ASSERT(eq(x, $I(30))); }
if (i is 3) { PT_ASSERT(eq(x, y)); }
if (i is 4) { PT_ASSERT(eq(x, y)); }
i++;
}

Expand Down

0 comments on commit f72d799

Please sign in to comment.