diff --git a/hashes/adler32.py b/hashes/adler32.py index 38d76ab12aa0..94d71e5ad574 100644 --- a/hashes/adler32.py +++ b/hashes/adler32.py @@ -11,20 +11,66 @@ MOD_ADLER = 65521 -def adler32(plain_text: str) -> int: +def adler32(data: bytes | bytearray | memoryview) -> int: """ Function implements adler-32 hash. - Iterates and evaluates a new value for each character + Iterates and evaluates a new value for each byte of the input. - >>> adler32('Algorithms') + Unlike the former str API, this function requires bytes-like data. Encode text + explicitly (for example, with text.encode("utf-8")) before calling it. + + Args: + data: Byte data to calculate the hash for (bytes, bytearray, or memoryview) + + Returns: + Adler-32 checksum as a 32-bit integer + + Raises: + TypeError: If data is not a bytes-like object + + >>> adler32(b'Algorithms') + 363791387 + + >>> adler32(b'Wikipedia') == 0x11E60398 + True + + >>> import zlib + + >>> adler32(b'go adler em all') == zlib.adler32(b'go adler em all') + True + + The previous implementation summed Unicode code points instead of UTF-8 bytes. + + >>> data = '€100'.encode('utf-8') + >>> adler32(data) == zlib.adler32(data) + True + + >>> adler32(b'') == zlib.adler32(b'') + True + + >>> adler32(bytearray(b'Algorithms')) 363791387 - >>> adler32('go adler em all') - 708642122 + >>> adler32(memoryview(b'Algorithms')) + 363791387 + + >>> adler32('not bytes') + Traceback (most recent call last): + ... + TypeError: data must be bytes-like, not str + + >>> adler32(123) + Traceback (most recent call last): + ... + TypeError: data must be bytes-like, not int """ + if not isinstance(data, (bytes, bytearray, memoryview)): + msg = f"data must be bytes-like, not {type(data).__name__}" + raise TypeError(msg) + a = 1 b = 0 - for plain_chr in plain_text: - a = (a + ord(plain_chr)) % MOD_ADLER + for byte in data: + a = (a + byte) % MOD_ADLER b = (b + a) % MOD_ADLER return (b << 16) | a