|
3 | 3 | from __future__ import annotations |
4 | 4 |
|
5 | 5 | import codecs |
| 6 | +import string |
6 | 7 | from typing import Any, Callable |
7 | 8 |
|
8 | 9 |
|
@@ -61,18 +62,45 @@ def _decorated(self, *args, **kwargs): |
61 | 62 | return _decorated |
62 | 63 |
|
63 | 64 |
|
64 | | -def integer(number: int | str | bytes, *args) -> int: |
| 65 | +def integer(number: str | bytes, base=10) -> int: |
65 | 66 | """ |
66 | | - In Python 3 int() is broken. |
67 | | - >>> int(bytearray(b'1_0')) |
| 67 | + The native Python integer parsing from string allows to many forms which are not allowed by the protocol. |
| 68 | +
|
| 69 | + >>> integer(bytearray(b'10')) |
| 70 | + 10 |
| 71 | + >>> integer(b'5a', 16) |
| 72 | + 90 |
| 73 | + >>> integer(bytearray(b'1_0')) |
| 74 | + Traceback (most recent call last): |
| 75 | + ... |
| 76 | + ValueError: |
| 77 | + >>> integer(bytearray(b' 10')) |
| 78 | + Traceback (most recent call last): |
| 79 | + ... |
| 80 | + ValueError: |
| 81 | + >>> integer(bytearray(b'\t10')) |
| 82 | + Traceback (most recent call last): |
| 83 | + ... |
| 84 | + ValueError: |
| 85 | + >>> integer(bytearray(b'\v10')) |
| 86 | + Traceback (most recent call last): |
| 87 | + ... |
| 88 | + ValueError: |
| 89 | + >>> integer(bytearray(b'\f10')) |
| 90 | + Traceback (most recent call last): |
| 91 | + ... |
| 92 | + ValueError: |
| 93 | + >>> integer(bytearray(b'10 \t\v\f')) |
68 | 94 | Traceback (most recent call last): |
69 | 95 | ... |
70 | 96 | ValueError: |
71 | 97 | """ |
72 | | - num = int(number, *args) |
73 | | - if (isinstance(number, str) and '_' in number) or (isinstance(number, (bytes, bytearray)) and b' ' in number): |
74 | | - raise ValueError() |
75 | | - return num |
| 98 | + if isinstance(number, int): |
| 99 | + return int(number) |
| 100 | + if not number.isdigit(): |
| 101 | + if base != 16 or number.strip(string.hexdigits if isinstance(string, str) else string.hexdigits.encode('ASCII')): |
| 102 | + raise ValueError() |
| 103 | + return int(number, base) |
76 | 104 |
|
77 | 105 |
|
78 | 106 | class IFile: |
|
0 commit comments