Skip to content

Commit

Permalink
Add CRC32CHash.checksum property
Browse files Browse the repository at this point in the history
This is not part of hashlib's interface, but it makes it easy to compare
the internal checksum kept by the hash object against an int value
provided somehow else.

Signed-off-by: Rodrigo Tobar <[email protected]>
  • Loading branch information
rtobar committed Aug 13, 2024
1 parent 1c081a1 commit d4b9549
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

* Added a `gil_relese_mode` parameter to the `CRC32CHash` constructor
used by all underlying `crc32c` function calls (#51).
* Added `CRC32CHash.checksum` auxiliary property.

## [2.6]

Expand Down
4 changes: 3 additions & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,15 @@ It can be set to the following values:
On top of the ``crc32c`` function,
a ``CRC32CHash(data=b"", gil_release_mode=-1)`` class is also offered.
It is modelled after the "hash objects" of the ``hashlib`` module
of the standard library:
of the standard library. It also offers a ``checksum`` property:

.. code-block:: python
crc32c_hash = crc32c.CRC32CHash()
crc32c_hash.update(b'hello')
crc32c_hash.update(b' world')
print(crc32c_hash.checksum == crc32c.crc32c(b'hello world'))
# True
print(crc32c_hash.digest())
# b'\xc9\x94e\xaa'
digest_as_int = int.from_bytes(crc32c_hash.digest(), "big")
Expand Down
7 changes: 7 additions & 0 deletions src/crc32c/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@ def name(self) -> str:
"""
return "crc32c"

@property
def checksum(self) -> int:
"""
The checksum calculated so far. Not part of the hashlib interface.
"""
return self._checksum

def __init__(self, data: Buffer = b"", gil_release_mode: int = -1) -> None:
"""
Initialise the hash object with an optional bytes-like object.
Expand Down
1 change: 1 addition & 0 deletions test/test_crc32c.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ def test_copy(self) -> None:
class TestSpecificValues:
@staticmethod
def _check_values(crc32c_hash: crc32c.CRC32CHash, crc: int) -> None:
assert crc32c_hash.checksum == crc
assert int.from_bytes(crc32c_hash.digest(), "big") == crc
assert len(crc32c_hash.digest()) == 4
assert int(crc32c_hash.hexdigest(), 16) == crc
Expand Down

0 comments on commit d4b9549

Please sign in to comment.