Skip to content

Commit d8cbbca

Browse files
committed
py: Fix builtin ord so that it can handle bytes values >= 0x80.
Addresses issue adafruit#1188.
1 parent 404b68d commit d8cbbca

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

py/modbuiltins.c

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -351,9 +351,12 @@ STATIC mp_obj_t mp_builtin_ord(mp_obj_t o_in) {
351351
mp_uint_t len;
352352
const char *str = mp_obj_str_get_data(o_in, &len);
353353
#if MICROPY_PY_BUILTINS_STR_UNICODE
354-
len = unichar_charlen(str, len);
355-
if (len == 1) {
356-
if (MP_OBJ_IS_STR(o_in) && UTF8_IS_NONASCII(*str)) {
354+
if (MP_OBJ_IS_STR(o_in)) {
355+
len = unichar_charlen(str, len);
356+
if (len == 1) {
357+
if (!UTF8_IS_NONASCII(*str)) {
358+
goto return_first_byte;
359+
}
357360
mp_int_t ord = *str++ & 0x7F;
358361
for (mp_int_t mask = 0x40; ord & mask; mask >>= 1) {
359362
ord &= ~mask;
@@ -362,8 +365,12 @@ STATIC mp_obj_t mp_builtin_ord(mp_obj_t o_in) {
362365
ord = (ord << 6) | (*str++ & 0x3F);
363366
}
364367
return mp_obj_new_int(ord);
365-
} else {
366-
return mp_obj_new_int(((const byte*)str)[0]);
368+
}
369+
} else {
370+
// a bytes object
371+
if (len == 1) {
372+
return_first_byte:
373+
return MP_OBJ_NEW_SMALL_INT(((const byte*)str)[0]);
367374
}
368375
}
369376
#else

tests/basics/builtin_ord.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,16 @@
77
except TypeError:
88
print("TypeError")
99

10+
# bytes also work in ord
11+
12+
print(ord(b'a'))
13+
print(ord(b'\x00'))
14+
print(ord(b'\x01'))
15+
print(ord(b'\x7f'))
16+
print(ord(b'\x80'))
17+
print(ord(b'\xff'))
18+
19+
try:
20+
ord(b'')
21+
except TypeError:
22+
print("TypeError")

0 commit comments

Comments
 (0)