8000 make sets iterable · ronc/micropython@0ce03b4 · GitHub
[go: up one dir, main page]

Skip to content< 8000 /a>

Commit 0ce03b4

Browse files
committed
make sets iterable
1 parent 69a818d commit 0ce03b4

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

py/objset.c

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,14 @@ typedef struct _mp_obj_set_t {
1515
mp_set_t set;
1616
} mp_obj_set_t;
1717

18+
typedef struct _mp_obj_set_it_t {
19+
mp_obj_base_t base;
20+
mp_obj_set_t *set;
21+
machine_uint_t cur;
22+
} mp_obj_set_it_t;
23+
24+
static mp_obj_t set_it_iternext(mp_obj_t self_in);
25+
1826
void set_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in) {
1927
mp_obj_set_t *self = self_in;
2028
bool first = true;
@@ -54,11 +62,42 @@ static mp_obj_t set_make_new(mp_obj_t type_in, int n_args, const mp_obj_t *args)
5462
}
5563
}
5664

65+
const mp_obj_type_t set_it_type = {
66+
{ &mp_const_type },
67+
"set_iterator",
68+
.iternext = set_it_iternext,
69+
};
70+
71+
static mp_obj_t set_it_iternext(mp_obj_t self_in) {
72+
assert(MP_OBJ_IS_TYPE(self_in, &set_it_type));
73+
mp_obj_set_it_t *self = self_in;
74+
machine_uint_t max = self->set->set.alloc;
75+
mp_obj_t *table = self->set->set.table;
76+
77+
for (machine_uint_t i = self->cur; i < max; i++) {
78+
if (table[i] != NULL) {
79+
self->cur = i + 1;
80+
return table[i];
81+
}
82+
}
83+
84+
return mp_const_stop_iteration;
85+
}
86+
87+
static mp_obj_t set_getiter(mp_obj_t set_in) {
88+
mp_obj_set_it_t *o = m_new_obj(mp_obj_set_it_t);
89+
o->base.type = &set_it_type;
90+
o->set = (mp_obj_set_t *)set_in;
91+
o->cur = 0;
92+
return o;
93+
}
94+
5795
const mp_obj_type_t set_type = {
5896
{ &mp_const_type },
5997
"set",
6098
.print = set_print,
6199
.make_new = set_make_new,
100+
.getiter = set_getiter,
62101
};
63102

64103
mp_obj_t mp_obj_new_set(int n_args, mp_obj_t *items) {

tests/basics/tests/set_iter.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
s = {1, 2, 3, 4}
2+
l = list(s)
3+
l.sort()
4+
print(l)
5+

0 commit comments

Comments
 (0)
0