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

Commit bca0135

Browse files
committed
allow hash function names in Multihash
1 parent 1ba6f92 commit bca0135

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

multihash.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ class Func(Enum):
2828
blake2b = 0x40
2929
blake2s = 0x41
3030

31+
_func_from_name = {f.name.replace('_', '-'): f for f in Func}
32+
3133

3234
class Multihash(namedtuple('Multihash', 'func length digest')):
3335
"""A named tuple representing multihash function, length and digest.
@@ -40,11 +42,15 @@ class Multihash(namedtuple('Multihash', 'func length digest')):
4042
>>> mh == (mh.func, mh.length, mh.digest)
4143
True
4244
43-
Although it can also be its integer value (the function code):
45+
Although it can also be its integer value (the function code) or its
46+
string name (the function name):
4447
4548
>>> mhfc = Multihash(Func.sha1.value, mh.length, mh.digest)
4649
>>> mhfc == mh
4750
True
51+
>>> mhfn = Multihash('sha2-256', 32, b'...')
52+
>>> mhfn.func is Func.sha2_256
53+
True
4854
4955
Application-specific codes (0x00-0x0f) are accepted. Other codes raise
5056
`ValueError`:
@@ -65,6 +71,8 @@ def __new__(cls, func, length, digest):
6571
except ValueError as ve:
6672
if _is_app_specific_func(func):
6773
f = int(func) # application-specific function code
74+
elif func in _func_from_name:
75+
f = _func_from_name[func] # function name
6876
else:
6977
raise ValueError("invalid hash function code", func)
7078
return super(cls, Multihash).__new__(cls, f, length, digest)

0 commit comments

Comments
 (0)