@@ -238,6 +238,24 @@ STATIC mp_obj_t memoryview_make_new(const mp_obj_type_t *type_in, size_t n_args,
238
238
239
239
return MP_OBJ_FROM_PTR (self );
240
240
}
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 );
241
259
#endif
242
260
243
261
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 = {
691
709
#endif
692
710
693
711
#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
+
694
721
const mp_obj_type_t mp_type_memoryview = {
695
722
{ & mp_type_type },
696
723
.name = MP_QSTR_memoryview ,
@@ -700,6 +727,9 @@ const mp_obj_type_t mp_type_memoryview = {
700
727
.binary_op = array_binary_op ,
701
728
.subscr = array_subscr ,
702
729
.buffer_p = { .get_buffer = array_get_buffer },
730
+ #if MICROPY_CPYTHON_COMPAT
731
+ .locals_dict = (mp_obj_dict_t * )& memoryview_locals_dict ,
732
+ #endif
703
733
};
704
734
#endif
705
735
0 commit comments