23
23
24
24
"""
25
25
try :
26
+ from typing import Union
27
+ from circuitpython_typing import ReadableBuffer
26
28
from binascii import hexlify , unhexlify
27
29
except ImportError :
28
30
pass
@@ -63,11 +65,12 @@ class Error(Exception):
63
65
64
66
if not "unhexlify" in globals ():
65
67
# pylint: disable=function-redefined
66
- def unhexlify (hexstr : str ) -> bytes :
68
+ def unhexlify (hexstr : Union [ str , ReadableBuffer ] ) -> bytes :
67
69
"""Return the binary data represented by hexstr.
68
- :param str hexstr: Hexadecimal string.
69
70
71
+ :param str|ReadableBuffer hexstr: Hexadecimal string.
70
72
"""
73
+
71
74
if len (hexstr ) % 2 != 0 :
72
75
raise Error ("Odd-length string" )
73
76
@@ -76,18 +79,18 @@ def unhexlify(hexstr: str) -> bytes:
76
79
77
80
if not "hexlify" in globals ():
78
81
# pylint: disable=function-redefined
79
- def hexlify (data : bytes ) -> bytes :
82
+ def hexlify (data : ReadableBuffer ) -> bytes :
80
83
"""Return the hexadecimal representation of the
81
84
binary data. Every byte of data is converted into
82
85
the corresponding 2-digit hex representation.
83
86
The returned bytes object is therefore twice
84
87
as long as the length of data.
85
88
86
89
:param bytes data: Binary data, as bytes.
87
-
88
90
"""
89
91
if not data :
90
92
raise TypeError ("Data provided is zero-length" )
93
+
91
94
data = "" .join ("%02x" % i for i in data )
92
95
return bytes (data , "utf-8" )
93
96
@@ -106,12 +109,12 @@ def _transform(n: int) -> str:
106
109
assert len (TABLE_A2B_B64 ) == 256
107
110
108
111
109
- def a2b_base64 (b64_data : bytes ) -> bytes :
112
+ def a2b_base64 (b64_data : ReadableBuffer ) -> bytes :
110
113
"""Convert a block of base64 data back to binary and return the binary data.
111
114
112
115
:param bytes b64_data: Base64 data.
113
-
114
116
"""
117
+
115
118
res = []
116
119
quad_pos = 0
117
120
leftchar = 0
@@ -148,12 +151,12 @@ def a2b_base64(b64_data: bytes) -> bytes:
148
151
return b"" .join (res )
149
152
150
153
151
- def b2a_base64 (bin_data : bytes ) -> bytes :
154
+ def b2a_base64 (bin_data : ReadableBuffer ) -> bytes :
152
155
"""Convert binary data to a line of ASCII characters in base64 coding.
153
156
154
- :param bytes bin_data: Binary data string, as bytes
155
-
157
+ :param ReadableBuffer bin_data: Binary data string, as bytes
156
158
"""
159
+
157
160
newlength = (len (bin_data ) + 2 ) // 3
158
161
newlength = newlength * 4 + 1
159
162
res = []
0 commit comments