Skip to content

Commit 4e47bf4

Browse files
committed
Add bytearray.decode() for CPython compatibility
CPython has a `decode()` method on `bytearray`. This adds that method using the code from `bytes.decode`. Test program: ```python byte_boi = bytes([0x6D, 0x65, 0x65, 0x70]) print(byte_boi) # b'meep' byte_boi_str = byte_boi.decode("utf-8") print(byte_boi_str) # meep byte_array_boi = bytearray(byte_boi) print(byte_array_boi) # bytearray(b'meep') byte_array_boi_str = byte_array_boi.decode("utf-8") print(byte_array_boi_str) # meep print(byte_array_boi_str == byte_boi_str) # True ```
1 parent bd78ab3 commit 4e47bf4

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

py/objarray.c

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ STATIC mp_obj_t array_iterator_new(mp_obj_t array_in, mp_obj_iter_buf_t *iter_bu
6363
STATIC mp_obj_t array_append(mp_obj_t self_in, mp_obj_t arg);
6464
STATIC mp_obj_t array_extend(mp_obj_t self_in, mp_obj_t arg_in);
6565
STATIC mp_int_t array_get_buffer(mp_obj_t o_in, mp_buffer_info_t *bufinfo, mp_uint_t flags);
66+
STATIC mp_obj_t array_decode(size_t n_args, const mp_obj_t *args);
67+
6668

6769
/******************************************************************************/
6870
// array
@@ -546,10 +548,30 @@ STATIC mp_int_t array_get_buffer(mp_obj_t o_in, mp_buffer_info_t *bufinfo, mp_ui
546548
return 0;
547549
}
548550

551+
552+
#if MICROPY_CPYTHON_COMPAT
553+
// Directly lifted from objstr.c
554+
STATIC mp_obj_t array_decode(size_t n_args, const mp_obj_t *args) {
555+
mp_obj_t new_args[2];
556+
if (n_args == 1) {
557+
new_args[0] = args[0];
558+
new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
559+
args = new_args;
560+
n_args++;
561+
}
562+
return mp_obj_str_make_new(&mp_type_str, n_args, args, NULL);
563+
}
564+
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(array_decode_obj, 1, 3, array_decode);
565+
#endif
566+
567+
549568
#if MICROPY_PY_BUILTINS_BYTEARRAY || MICROPY_PY_ARRAY
550569
STATIC const mp_rom_map_elem_t array_locals_dict_table[] = {
551570
{ MP_ROM_QSTR(MP_QSTR_append), MP_ROM_PTR(&array_append_obj) },
552571
{ MP_ROM_QSTR(MP_QSTR_extend), MP_ROM_PTR(&array_extend_obj) },
572+
#if MICROPY_CPYTHON_COMPAT
573+
{ MP_ROM_QSTR(MP_QSTR_decode), MP_ROM_PTR(&array_decode_obj) },
574+
#endif
553575
};
554576

555577
STATIC MP_DEFINE_CONST_DICT(array_locals_dict, array_locals_dict_table);

0 commit comments

Comments
 (0)