Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions hashes/adler32.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
def adler32(plain_text: str) -> int:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: there is another open PR for the same issue that changes the signature to bytes (this one keeps str and is backward compatible). The two overlap, so it may be worth coordinating with the maintainers, so only one is merged. This approach avoids breaking callers that pass strings, which I'd consider a plus.

"""
Function implements adler-32 hash.
Iterates and evaluates a new value for each character
Iterates over the UTF-8 bytes of the input text.

>>> adler32('Algorithms')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fix is correct: I compared it with zlib.adler32(text.encode()) on "€100", "héllo", "日本語" and an emoji, and all matched. But the doctests only cover ASCII, so nothing would catch this bug again. Please add non-ASCII doctests with the literal expected values, e.g.:

>>> adler32('€100')
196018850
>>> adler32('héllo')
192152348
>>> adler32('日本語')
556009089

You could also compare against zlib: >>> import zlib then >>> adler32('€100') == zlib.adler32('€100'.encode()), which shows the property being fixed.

363791387
Expand All @@ -24,7 +24,7 @@ def adler32(plain_text: str) -> int:
"""
a = 1
b = 0
for plain_chr in plain_text:
a = (a + ord(plain_chr)) % MOD_ADLER
for plain_byte in plain_text.encode("utf-8"):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good: encode() is evaluated once before the loop, and UTF-8 matches what zlib.adler32 gets when callers pass text.encode(). One suggestion: say in the docstring that the checksum is over the UTF-8 bytes, so non-ASCII results match zlib. That is the behaviour change, so documenting it helps. Line 17 already says "UTF-8 bytes", which is a good start.

a = (a + plain_byte) % MOD_ADLER
b = (b + a) % MOD_ADLER
return (b << 16) | a