py/objstr: Skip whitespace in bytes.fromhex().

Skip whitespace characters between pairs of hex numbers.
This makes `bytes.fromhex()` compatible with cpython.

Includes simple test in `tests/basic/builtin_str_hex.py`.

Signed-off-by: Glenn Moloney <glenn.moloney@gmail.com>
This commit is contained in:
Glenn Moloney
2024-08-13 08:38:20 +10:00
parent e9814e987b
commit 6367099f83
3 changed files with 36 additions and 16 deletions

View File

@@ -20,5 +20,20 @@ for x in (
"08090a0b0c0d0e0f",
"7f80ff",
"313233344142434461626364",
"ab\tcd\n ef ",
"ab cd ef",
"ab cd ef ",
" ab cd ef ",
# Invalid hex strings:
"abcde", # Odd number of hex digits
"ab cd e",
"a b cd ef", # Spaces between hex pairs
"ab cd e f ",
"abga", # Invalid hex digits
"ab_cd",
"ab:cd",
):
print(bytes.fromhex(x))
try:
print(bytes.fromhex(x))
except ValueError as e:
print("ValueError:", e)

View File

@@ -26,3 +26,14 @@ b'\x00\x01\x02\x03\x04\x05\x06\x07'
b'\x08\t\n\x0b\x0c\r\x0e\x0f'
b'\x7f\x80\xff'
b'1234ABCDabcd'
b'\xab\xcd\xef'
b'\xab\xcd\xef'
b'\xab\xcd\xef'
b'\xab\xcd\xef'
ValueError: non-hex digit
ValueError: non-hex digit
ValueError: non-hex digit
ValueError: non-hex digit
ValueError: non-hex digit
ValueError: non-hex digit
ValueError: non-hex digit