8000 extmod/modbtree: Implement __contains__ operation. · alexbartlow/circuitpython@3eb532e · GitHub
[go: up one dir, main page]

Skip to content

Commit 3eb532e

Browse files
committed
extmod/modbtree: Implement __contains__ operation.
1 parent 8766bc0 commit 3eb532e

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

extmod/modbtree.c

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131

3232
#include "py/nlr.h"
3333
#include "py/runtime.h"
34+
#include "py/runtime0.h"
3435
#include "py/stream.h"
3536

3637
#if MICROPY_PY_BTREE
@@ -292,6 +293,24 @@ STATIC mp_obj_t btree_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
292293
}
293294
}
294295

296+
STATIC mp_obj_t btree_binary_op(mp_uint_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
297+
mp_obj_btree_t *self = MP_OBJ_TO_PTR(lhs_in);
298+
switch (op) {
299+
case MP_BINARY_OP_IN: {
300+
mp_uint_t v;
301+
DBT key, val;
302+
key.data = (void*)mp_obj_str_get_data(rhs_in, &v);
303+
key.size = v;
304+
int res = __bt_get(self->db, &key, &val, 0);
305+
CHECK_ERROR(res);
306+
return mp_obj_new_bool(res != RET_SPECIAL);
307+
}
308+
default:
309+
// op not supported
310+
return MP_OBJ_NULL;
311+
}
312+
}
313+
295314
STATIC const mp_rom_map_elem_t btree_locals_dict_table[] = {
296315
{ MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&btree_close_obj) },
297316
{ MP_ROM_QSTR(MP_QSTR_get), MP_ROM_PTR(&btree_get_obj) },
@@ -311,6 +330,7 @@ STATIC const mp_obj_type_t btree_type = {
311330
.print = btree_print,
312331
.getiter = btree_getiter,
313332
.iternext = btree_iternext,
333+
.binary_op = btree_binary_op,
314334
.subscr = btree_subscr,
315335
.locals_dict = (void*)&btree_locals_dict,
316336
};

tests/extmod/btree1.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,5 +62,8 @@
6262
for k in db:
6363
print(k)
6464

65+
print("foo1", "foo1" in db)
66+
print("foo2", "foo2" in db)
67+
6568
db.close()
6669
f.close()

tests/extmod/btree1.py.exp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,5 @@ KeyError
3030
b'bar1'
3131
b'foo1'
3232
b'foo3'
33+
foo1 True
34+
foo2 False

0 commit comments

Comments
 (0)
0