Skip to content

Commit 646eb9a

Browse files
committed
py: memoryview: implement memoryview.cast if CPYTHON_COMPAT
1 parent 5d15493 commit 646eb9a

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

py/objarray.c

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,24 @@ STATIC mp_obj_t memoryview_make_new(const mp_obj_type_t *type_in, size_t n_args,
238238

239239
return MP_OBJ_FROM_PTR(self);
240240
}
241+
242+
STATIC mp_obj_t memoryview_cast(const mp_obj_t self_in, const mp_obj_t typecode_in) {
243+
mp_obj_array_t *self = MP_OBJ_TO_PTR(self_in);
244+
const char *typecode = mp_obj_str_get_str(typecode_in);
245+
size_t element_size = mp_binary_get_size('@', typecode[0], NULL);
246+
size_t bytelen = self->len * mp_binary_get_size('@', self->typecode & ~MP_OBJ_ARRAY_TYPECODE_FLAG_RW, NULL);
247+
if (bytelen % element_size != 0) {
248+
mp_raise_TypeError(translate("memoryview: length is not a multiple of itemsize"));
249+
}
250+
mp_obj_array_t *result = MP_OBJ_TO_PTR(mp_obj_new_memoryview(*typecode, bytelen / element_size, self->items));
251+
252+
// test if the object can be written to
253+
if (self->typecode & MP_OBJ_ARRAY_TYPECODE_FLAG_RW) {
254+
result->typecode |= MP_OBJ_ARRAY_TYPECODE_FLAG_RW; // indicate writable buffer
255+
}
256+
return MP_OBJ_FROM_PTR(result);
257+
}
258+
STATIC MP_DEFINE_CONST_FUN_OBJ_2(memoryview_cast_obj, memoryview_cast);
241259
#endif
242260

243261
STATIC mp_obj_t array_unary_op(mp_unary_op_t op, mp_obj_t o_in) {
@@ -691,6 +709,15 @@ const mp_obj_type_t mp_type_bytearray = {
691709
#endif
692710

693711
#if MICROPY_PY_BUILTINS_MEMORYVIEW
712+
713+
#if MICROPY_CPYTHON_COMPAT
714+
STATIC const mp_rom_map_elem_t memoryview_locals_dict_table[] = {
715+
{ MP_ROM_QSTR(MP_QSTR_cast), MP_ROM_PTR(&memoryview_cast_obj) },
716+
};
717+
718+
STATIC MP_DEFINE_CONST_DICT(memoryview_locals_dict, memoryview_locals_dict_table);
719+
#endif
720+
694721
const mp_obj_type_t mp_type_memoryview = {
695722
{ &mp_type_type },
696723
.name = MP_QSTR_memoryview,
@@ -700,6 +727,9 @@ const mp_obj_type_t mp_type_memoryview = {
700727
.binary_op = array_binary_op,
701728
.subscr = array_subscr,
702729
.buffer_p = { .get_buffer = array_get_buffer },
730+
#if MICROPY_CPYTHON_COMPAT
731+
.locals_dict = (mp_obj_dict_t*)&memoryview_locals_dict,
732+
#endif
703733
};
704734
#endif
705735

0 commit comments

Comments
 (0)