py/objarray: Detect bytearray(str) without an encoding. · csamuelson/circuitpython@2c8dab7 · GitHub
Skip to content

Commit 2c8dab7

Browse files
jimmodpgeorge
authored andcommitted
py/objarray: Detect bytearray(str) without an encoding.
This prevents a very subtle bug caused by writing e.g. `bytearray('\xfd')` which gives you `(0xc3, 0xbd)`. This work was funded through GitHub Sponsors. Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
1 parent f8b0ae3 commit 2c8dab7

4 files changed

Lines changed: 18 additions & 1 deletion

File tree

py/objarray.c

Lines changed: 8 additions & 0 deletions

py/objstr.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,11 @@ STATIC mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, size
233233

234234
if (mp_obj_is_str(args[0])) {
235235
if (n_args < 2 || n_args > 3) {
236+
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
236237
goto wrong_args;
238+
#else
239+
mp_raise_TypeError(MP_ERROR_TEXT("string argument without an encoding"));
240+
#endif
237241
}
238242
GET_STR_DATA_LEN(args[0], str_data, str_len);
239243
GET_STR_HASH(args[0], str_hash);

tests/basics/bytearray_construct.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,8 @@
55
print(bytearray('12345', 'utf-8', 'strict'))
66
print(bytearray((1, 2)))
77
print(bytearray([1, 2]))
8+
9+
try:
10+
print(bytearray('1234'))
11+
except TypeError:
12+
print("TypeError")

tests/micropython/viper_addr.py

Lines changed: 1 addition & 1 deletion

0 commit comments

Comments
 (0)