Skip to content
This repository was archived by the owner on Apr 19, 2024. It is now read-only.

Commit 1ba6f92

Browse files
committed
allow application-specific hash function codes in Multihash
1 parent 7e978eb commit 1ba6f92

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

multihash.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,12 @@
55

66
from collections import namedtuple
77
from enum import Enum
8+
from numbers import Integral
9+
10+
11+
def _is_app_specific_func(code):
12+
"""Is the given hash function integer `code` application-specific?"""
13+
return isinstance(code, Integral) and (0x00 <= code <= 0x0f)
814

915

1016
class Func(Enum):
@@ -39,14 +45,28 @@ class Multihash(namedtuple('Multihash', 'func length digest')):
3945
>>> mhfc = Multihash(Func.sha1.value, mh.length, mh.digest)
4046
>>> mhfc == mh
4147
True
48+
49+
Application-specific codes (0x00-0x0f) are accepted. Other codes raise
50+
`ValueError`:
51+
52+
>>> mhfc = Multihash(0x01, 4, b'...')
53+
>>> mhfc.func
54+
1
55+
>>> mhfc = Multihash(1234, 4, b'...')
56+
Traceback (most recent call last):
57+
...
58+
ValueError: ('invalid hash function code', 1234)
4259
"""
4360
__slots__ = ()
4461

4562
def __new__(cls, func, length, digest):
4663
try:
4764
f = Func(func)
4865
except ValueError as ve:
49-
raise ValueError("invalid hash function code", func)
66+
if _is_app_specific_func(func):
67+
f = int(func) # application-specific function code
68+
else:
69+
raise ValueError("invalid hash function code", func)
5070
return super(cls, Multihash).__new__(cls, f, length, digest)
5171

5272

0 commit comments

Comments
 (0)