|
5 | 5 |
|
6 | 6 | from collections import namedtuple
|
7 | 7 | 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) |
8 | 14 |
|
9 | 15 |
|
10 | 16 | class Func(Enum):
|
@@ -39,14 +45,28 @@ class Multihash(namedtuple('Multihash', 'func length digest')):
|
39 | 45 | >>> mhfc = Multihash(Func.sha1.value, mh.length, mh.digest)
|
40 | 46 | >>> mhfc == mh
|
41 | 47 | 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) |
42 | 59 | """
|
43 | 60 | __slots__ = ()
|
44 | 61 |
|
45 | 62 | def __new__(cls, func, length, digest):
|
46 | 63 | try:
|
47 | 64 | f = Func(func)
|
48 | 65 | 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) |
50 | 70 | return super(cls, Multihash).__new__(cls, f, length, digest)
|
51 | 71 |
|
52 | 72 |
|
|
0 commit comments