Skip to content

Commit 1619583

Browse files
Sarbatorepre-commit-ci[bot]cclauss
authored
feat(hashes): add Jenkins-One-At-A-Time function (#14560)
* Add joaat function for non-cryptographic hashing Implement the Jenkins-One-At-A-Time hash function. * Add doctest for joaat function Added doctest examples for the joaat function and included a main block to run tests. * Refactor joaat function variable names for prevent shadowing * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Rename function to jenkins_one_at_a_time * updating DIRECTORY.md --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: cclauss <cclauss@users.noreply.github.com>
1 parent 185ef19 commit 1619583

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

‎DIRECTORY.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -703,6 +703,7 @@
703703
* [Enigma Machine](hashes/enigma_machine.py)
704704
* [Fletcher16](hashes/fletcher16.py)
705705
* [Hamming Code](hashes/hamming_code.py)
706+
* [Jenkins One At A Time](hashes/jenkins_one_at_a_time.py)
706707
* [Luhn](hashes/luhn.py)
707708
* [Md5](hashes/md5.py)
708709
* [Sdbm](hashes/sdbm.py)

‎hashes/jenkins_one_at_a_time.py‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
The Bob Jenkins hash is a fast, non-cryptographic hash function
3+
designed for general-purpose use, such as hash table lookups.
4+
5+
https://en.wikipedia.org/wiki/Jenkins_hash_function
6+
"""
7+
8+
9+
def jenkins_one_at_a_time(key: str) -> int:
10+
"""
11+
Calculate Jenkins One-at-a-Time hash for a key.
12+
13+
>>> jenkins_one_at_a_time("apple")
14+
2297466611
15+
>>> jenkins_one_at_a_time("test")
16+
1064684737
17+
>>> jenkins_one_at_a_time("")
18+
0
19+
"""
20+
hash_value = 0
21+
mask = 0xFFFFFFFF
22+
key_bytes = key.encode("utf-8")
23+
24+
for byte in key_bytes:
25+
hash_value = (hash_value + byte) & mask
26+
hash_value = (hash_value + (hash_value << 10)) & mask
27+
hash_value = (hash_value ^ (hash_value >> 6)) & mask
28+
29+
hash_value = (hash_value + (hash_value << 3)) & mask
30+
hash_value = (hash_value ^ (hash_value >> 11)) & mask
31+
hash_value = (hash_value + (hash_value << 15)) & mask
32+
33+
return hash_value
34+
35+
36+
if __name__ == "__main__":
37+
import doctest
38+
39+
doctest.testmod()

0 commit comments

Comments
 (0)