Skip to content

Commit ca19e21

Browse files
authored
Merge pull request #22 from ChrisPappalardo/add-missing-type-annotations
added missing type annotations
2 parents 1e2dace + 99db3f4 commit ca19e21

File tree

5 files changed

+86
-41
lines changed

5 files changed

+86
-41
lines changed

adafruit_hashlib/__init__.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,13 @@
2222
* Adafruit CircuitPython firmware for the supported boards:
2323
https://github.com/adafruit/circuitpython/releases
2424
"""
25+
26+
try:
27+
from typing import List, Optional, Union
28+
except ImportError:
29+
pass
30+
31+
2532
try:
2633
from hashlib import md5, sha1, sha224, sha256, sha512
2734
from hashlib import sha3_384 as sha384
@@ -38,7 +45,7 @@
3845
ALGOS_AVAIL = ["sha1", "md5", "sha224", "sha256", "sha384", "sha512"]
3946

4047

41-
def new(algo, data=b""):
48+
def new(algo, data: Optional[bytes] = b"") -> Union[md5, sha1, sha224, sha256, sha512]:
4249
"""Creates a new hashlib object.
4350
4451
:param str algo: Name of the desired algorithm.
@@ -52,7 +59,7 @@ def new(algo, data=b""):
5259

5360

5461
@property
55-
def algorithms_available():
62+
def algorithms_available() -> List[str]:
5663
"""Returns a list containing the names of the hash
5764
algorithms that are available in this module.
5865
"""

adafruit_hashlib/_md5.py

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,12 @@
4343
"""
4444
# pylint: disable=invalid-name,missing-function-docstring,too-many-arguments
4545

46+
try:
47+
from typing import Optional, Tuple
48+
except ImportError:
49+
# suppress because typing does not exist on circuitpython
50+
pass
51+
4652
import binascii
4753
import struct
4854
from micropython import const
@@ -73,26 +79,26 @@
7379
# F, G, H and I are basic MD5 functions.
7480

7581

76-
def F(x, y, z):
82+
def F(x: int, y: int, z: int) -> int:
7783
return (x & y) | ((~x) & z)
7884

7985

80-
def G(x, y, z):
86+
def G(x: int, y: int, z: int) -> int:
8187
return (x & z) | (y & (~z))
8288

8389

84-
def H(x, y, z):
90+
def H(x: int, y: int, z: int) -> int:
8591
return x ^ y ^ z
8692

8793

88-
def I(x, y, z):
94+
def I(x: int, y: int, z: int) -> int:
8995
return y ^ (x | (~z))
9096

9197

9298
# ROTATE_LEFT rotates x left n bits.
9399

94100

95-
def ROTATE_LEFT(x, n):
101+
def ROTATE_LEFT(x: int, n: int) -> int:
96102
x = x & 0xFFFFFFFF
97103
return ((x << n) | (x >> (32 - n))) & 0xFFFFFFFF
98104

@@ -101,43 +107,43 @@ def ROTATE_LEFT(x, n):
101107
# Rotation is separate from addition to prevent recomputation.
102108

103109

104-
def FF(a, b, c, d, x, s, ac):
110+
def FF(a: int, b: int, c: int, d: int, x: int, s: int, ac: int) -> int:
105111
a = a + F(b, c, d) + x + ac
106112
a = ROTATE_LEFT(a, s)
107113
a = a + b
108114
return a
109115

110116

111-
def GG(a, b, c, d, x, s, ac):
117+
def GG(a: int, b: int, c: int, d: int, x: int, s: int, ac: int) -> int:
112118
a = a + G(b, c, d) + x + ac
113119
a = ROTATE_LEFT(a, s)
114120
a = a + b
115121
return a
116122

117123

118-
def HH(a, b, c, d, x, s, ac):
124+
def HH(a: int, b: int, c: int, d: int, x: int, s: int, ac: int) -> int:
119125
a = a + H(b, c, d) + x + ac
120126
a = ROTATE_LEFT(a, s)
121127
a = a + b
122128
return a
123129

124130

125-
def II(a, b, c, d, x, s, ac):
131+
def II(a: int, b: int, c: int, d: int, x: int, s: int, ac: int) -> int:
126132
a = a + I(b, c, d) + x + ac
127133
a = ROTATE_LEFT(a, s)
128134
a = a + b
129135
return a
130136

131137

132-
def encode(data, length):
138+
def encode(data: Tuple[int], length: int) -> bytes:
133139
"""Encodes input (UINT4) into output (unsigned char). Assumes length is
134140
a multiple of 4.
135141
"""
136142
k = length >> 2
137143
return struct.pack(*("%iI" % k,) + tuple(data[:k]))
138144

139145

140-
def decode(data, length):
146+
def decode(data: bytes, length: int) -> Tuple[int]:
141147
"""Decodes input (unsigned char) into output (UINT4). Assumes length is
142148
a multiple of 4.
143149
"""
@@ -152,7 +158,7 @@ class md5:
152158
block_size = 64
153159
name = "md5"
154160

155-
def __init__(self, string=b""):
161+
def __init__(self, string: Optional[bytes] = b""):
156162
"""Constructs an MD5 hash object."""
157163
self.count = 0
158164
self.buffer = b""
@@ -163,7 +169,7 @@ def __init__(self, string=b""):
163169
if string:
164170
self.update(string)
165171

166-
def update(self, data):
172+
def update(self, data: bytes):
167173
"""Update the hash object with the bytes-like object."""
168174
data_len = len(data)
169175

@@ -231,7 +237,7 @@ def copy(self):
231237
new.state = self.state
232238
return new
233239

234-
def _transform(self, block):
240+
def _transform(self, block: bytes):
235241
"""MD5 basic transformation. Transforms state based on block."""
236242
# pylint: disable=invalid-name,too-many-statements
237243
a, b, c, d = self.state

adafruit_hashlib/_sha1.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,13 @@
1919
from io import BytesIO
2020
from micropython import const
2121

22+
try:
23+
from typing import Optional, Tuple, Union
24+
except ImportError:
25+
# suppress because typing does not exist on circuitpython
26+
pass
27+
28+
2229
# SHA Block size and message digest sizes, in bytes.
2330
SHA_BLOCKSIZE = 64
2431
SHA_DIGESTSIZE = 20
@@ -30,7 +37,7 @@
3037
K3 = const(0xCA62C1D6)
3138

3239

33-
def _getbuf(data):
40+
def _getbuf(data: Union[str, bytes]) -> bytes:
3441
"""Converts data into ascii,
3542
returns bytes of data.
3643
:param str bytes bytearray data: Data to convert.
@@ -41,7 +48,7 @@ def _getbuf(data):
4148
return bytes(data)
4249

4350

44-
def _left_rotate(n, b):
51+
def _left_rotate(n: int, b: int) -> int:
4552
"""Left rotate a 32-bit integer, n, by b bits.
4653
:param int n: 32-bit integer
4754
:param int b: Desired rotation amount, in bits.
@@ -51,7 +58,9 @@ def _left_rotate(n, b):
5158

5259

5360
# pylint: disable=invalid-name, too-many-arguments
54-
def _hash_computation(chunk, h0, h1, h2, h3, h4):
61+
def _hash_computation(
62+
chunk: bytes, h0: int, h1: int, h2: int, h3: int, h4: int
63+
) -> Tuple[int, int, int, int, int]:
5564
"""Processes 64-bit chunk of data and returns new digest variables.
5665
Per FIPS [6.1.2]
5766
:param bytes bytearray chunk: 64-bit bytearray
@@ -118,7 +127,7 @@ class sha1:
118127
block_size = SHA_BLOCKSIZE
119128
name = "sha1"
120129

121-
def __init__(self, data=None):
130+
def __init__(self, data: Optional[Union[str, bytes]] = None):
122131
"""Construct a SHA-1 hash object.
123132
:param bytes data: Optional data to process
124133
@@ -159,7 +168,7 @@ def _create_digest(self):
159168
return h
160169
return _hash_computation(message[64:], *h)
161170

162-
def update(self, data):
171+
def update(self, data: Optional[Union[str, bytes]]):
163172
"""Updates the hash object with bytes-like object, data.
164173
:param bytes data: bytearray or bytes object
165174

adafruit_hashlib/_sha256.py

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,13 @@
1111
"""
1212
# pylint: disable=invalid-name, unnecessary-lambda, unnecessary-lambda-assignment, missing-docstring
1313

14+
try:
15+
from typing import Dict, List, Optional, Tuple, Union
16+
except ImportError:
17+
# suppress because typing does not exist on circuitpython
18+
pass
19+
20+
1421
# SHA Block size and message digest sizes, in bytes.
1522
SHA_BLOCKSIZE = 64
1623
SHA_DIGESTSIZE = 32
@@ -42,7 +49,7 @@ def new_shaobject():
4249
Gamma1 = lambda x: (S(x, 17) ^ S(x, 19) ^ R(x, 10))
4350

4451
# pylint: disable=too-many-statements
45-
def sha_transform(sha_info):
52+
def sha_transform(sha_info: Dict[str, Union[List[int], int]]) -> None:
4653
W = []
4754

4855
d = sha_info["data"]
@@ -59,7 +66,9 @@ def sha_transform(sha_info):
5966
ss = sha_info["digest"][:]
6067

6168
# pylint: disable=too-many-arguments, line-too-long
62-
def RND(a, b, c, d, e, f, g, h, i, ki):
69+
def RND(
70+
a: int, b: int, c: int, d: int, e: int, f: int, g: int, h: int, i: int, ki: int
71+
) -> Tuple[int, int]:
6372
"""Compress"""
6473
t0 = h + Sigma1(e) + Ch(e, f, g) + ki + W[i]
6574
t1 = Sigma0(a) + Maj(a, b, c)
@@ -267,7 +276,7 @@ def RND(a, b, c, d, e, f, g, h, i, ki):
267276
sha_info["digest"] = dig
268277

269278

270-
def sha_init():
279+
def sha_init() -> Dict[str, Union[List[int], int]]:
271280
"""Initialize the SHA digest."""
272281
sha_info = new_shaobject()
273282
sha_info["digest"] = [
@@ -287,7 +296,7 @@ def sha_init():
287296
return sha_info
288297

289298

290-
def sha224_init():
299+
def sha224_init() -> Dict[str, Union[List[int], int]]:
291300
"""Initialize a SHA224 digest."""
292301
sha_info = new_shaobject()
293302
sha_info["digest"] = [
@@ -307,13 +316,15 @@ def sha224_init():
307316
return sha_info
308317

309318

310-
def getbuf(string):
319+
def getbuf(string: Union[str, bytes]) -> bytes:
311320
if isinstance(string, str):
312321
return string.encode("ascii")
313322
return bytes(string)
314323

315324

316-
def sha_update(sha_info, buffer):
325+
def sha_update(
326+
sha_info: Dict[str, Union[List[int], int]], buffer: Union[str, bytes]
327+
) -> None:
317328
"""Update the SHA digest.
318329
:param dict sha_info: SHA Digest.
319330
:param str buffer: SHA buffer size.
@@ -360,7 +371,7 @@ def sha_update(sha_info, buffer):
360371
sha_info["local"] = size
361372

362373

363-
def sha_final(sha_info):
374+
def sha_final(sha_info: Dict[str, Union[List[int], int]]) -> bytes:
364375
"""Finish computing the SHA Digest."""
365376
lo_bit_count = sha_info["count_lo"]
366377
hi_bit_count = sha_info["count_hi"]
@@ -401,13 +412,13 @@ class sha256:
401412
block_size = SHA_BLOCKSIZE
402413
name = "sha256"
403414

404-
def __init__(self, s=None):
415+
def __init__(self, s: Optional[Union[str, bytes]] = None):
405416
"""Constructs a SHA256 hash object."""
406417
self._sha = sha_init()
407418
if s:
408419
sha_update(self._sha, getbuf(s))
409420

410-
def update(self, s):
421+
def update(self, s: Union[str, bytes]):
411422
"""Updates the hash object with a bytes-like object, s."""
412423
sha_update(self._sha, getbuf(s))
413424

@@ -434,7 +445,7 @@ class sha224(sha256):
434445
digest_size = digestsize = 28
435446
name = "sha224"
436447

437-
def __init__(self, s=None):
448+
def __init__(self, s: Optional[Union[str, bytes]] = None):
438449
"""Constructs a SHA224 hash object."""
439450
self._sha = sha224_init()
440451
if s:

0 commit comments

Comments
 (0)