kopia lustrzana https://github.com/micropython/micropython
Merge 18f813785a
into 01c31ea804
commit
f19b729153
28
py/objstr.c
28
py/objstr.c
|
@ -2014,27 +2014,23 @@ mp_obj_t mp_obj_bytes_fromhex(mp_obj_t type_in, mp_obj_t data) {
|
||||||
mp_buffer_info_t bufinfo;
|
mp_buffer_info_t bufinfo;
|
||||||
mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ);
|
mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ);
|
||||||
|
|
||||||
if ((bufinfo.len & 1) != 0) {
|
|
||||||
mp_raise_ValueError(MP_ERROR_TEXT("odd-length string"));
|
|
||||||
}
|
|
||||||
vstr_t vstr;
|
vstr_t vstr;
|
||||||
vstr_init_len(&vstr, bufinfo.len / 2);
|
vstr_init_len(&vstr, bufinfo.len / 2);
|
||||||
byte *in = bufinfo.buf, *out = (byte *)vstr.buf;
|
byte *in = bufinfo.buf, *out = (byte *)vstr.buf;
|
||||||
byte hex_byte = 0;
|
byte *in_end = in + bufinfo.len;
|
||||||
for (mp_uint_t i = bufinfo.len; i--;) {
|
mp_uint_t hex_ch, x1, x2;
|
||||||
byte hex_ch = *in++;
|
while (in < in_end) {
|
||||||
if (unichar_isxdigit(hex_ch)) {
|
hex_ch = *in++;
|
||||||
hex_byte += unichar_xdigit_value(hex_ch);
|
if (!unichar_isspace(hex_ch)) {
|
||||||
} else {
|
x1 = unichar_xdigit_value(hex_ch);
|
||||||
mp_raise_ValueError(MP_ERROR_TEXT("non-hex digit found"));
|
x2 = (in < in_end) ? unichar_xdigit_value(*in++) : 0xff;
|
||||||
}
|
if ((x1 | x2) & ~0xf) { // if (x1 > 0xf || x2 > 0xf) {}
|
||||||
if (i & 1) {
|
mp_raise_ValueError(MP_ERROR_TEXT("non-hex or odd number of digits"));
|
||||||
hex_byte <<= 4;
|
}
|
||||||
} else {
|
*out++ = (byte)((x1 << 4) | x2);
|
||||||
*out++ = hex_byte;
|
|
||||||
hex_byte = 0;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
vstr.len = out - (byte *)vstr.buf; // Length may be shorter due to whitespace chars in input
|
||||||
return mp_obj_new_str_type_from_vstr(MP_OBJ_TO_PTR(type_in), &vstr);
|
return mp_obj_new_str_type_from_vstr(MP_OBJ_TO_PTR(type_in), &vstr);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -20,5 +20,7 @@ for x in (
|
||||||
"08090a0b0c0d0e0f",
|
"08090a0b0c0d0e0f",
|
||||||
"7f80ff",
|
"7f80ff",
|
||||||
"313233344142434461626364",
|
"313233344142434461626364",
|
||||||
|
"ab cd ef",
|
||||||
|
"ab\tcd\n ef ",
|
||||||
):
|
):
|
||||||
print(bytes.fromhex(x))
|
print(bytes.fromhex(x))
|
||||||
|
|
|
@ -26,3 +26,5 @@ b'\x00\x01\x02\x03\x04\x05\x06\x07'
|
||||||
b'\x08\t\n\x0b\x0c\r\x0e\x0f'
|
b'\x08\t\n\x0b\x0c\r\x0e\x0f'
|
||||||
b'\x7f\x80\xff'
|
b'\x7f\x80\xff'
|
||||||
b'1234ABCDabcd'
|
b'1234ABCDabcd'
|
||||||
|
b'\xab\xcd\xef'
|
||||||
|
b'\xab\xcd\xef'
|
||||||
|
|
Ładowanie…
Reference in New Issue