@@ -77,6 +77,66 @@ def reset(cls):
77
77
# Maps hashlib names to multihash-supported functions.
78
78
cls ._func_from_hash = {h .name : f for (f , h ) in cls ._func_hash .items ()}
79
79
80
+ @classmethod
81
+ def get_funcs (cls ):
82
+ """Return a set of registered functions.
83
+
84
+ Standard multihash functions are represented as members of `Func`,
85
+ while application-specific functions are integers.
86
+
87
+ >>> FuncHash.reset()
88
+ >>> FuncHash.get_funcs() == set(Func)
89
+ True
90
+ """
91
+ return {func for func in cls ._func_hash }
92
+
93
+ @classmethod
94
+ def register (cls , code , name , new ):
95
+ """Add an application-specific function to the registry.
96
+
97
+ Registers a function with the given `code` (an integer) and `name` (a
98
+ string) to be used with the given hashlib-compatible `new`
99
+ constructor. Existing functions are replaced. Registering a function
100
+ with a `code` not in the application-specific range (0x00-0xff) raises
101
+ a `ValueError`.
102
+
103
+ >>> import hashlib
104
+ >>> FuncHash.register(0x03, 'md5', hashlib.md5)
105
+ >>> FuncHash.hash_from_func(0x03).name == 'md5'
106
+ True
107
+ >>> FuncHash.reset()
108
+ >>> 0x03 in FuncHash.get_funcs()
109
+ False
110
+ """
111
+ if not _is_app_specific_func (code ):
112
+ raise ValueError (
113
+ "only application-specific functions can be registered" )
114
+ cls ._func_hash [code ] = cls ._hash (name , new )
115
+ cls ._func_from_hash [name ] = code
116
+
117
+ @classmethod
118
+ def unregister (cls , code ):
119
+ """Remove an application-specific function from the registry.
120
+
121
+ Unregisters the function with the given `code` (an integer). If the
122
+ function is not registered, a `KeyError` is raised. Unregistering a
123
+ function with a `code` not in the application-specific range
124
+ (0x00-0xff) raises a `ValueError`.
125
+
126
+ >>> import hashlib
127
+ >>> FuncHash.register(0x03, 'md5', hashlib.md5)
128
+ >>> 0x03 in FuncHash.get_funcs()
129
+ True
130
+ >>> FuncHash.unregister(0x03)
131
+ >>> 0x03 in FuncHash.get_funcs()
132
+ False
133
+ """
134
+ if code in Func :
135
+ raise ValueError (
136
+ "only application-specific functions can be unregistered" )
137
+ hash = cls ._func_hash .pop (code )
138
+ del cls ._func_from_hash [hash .name ]
139
+
80
140
@classmethod
81
141
def func_from_hash (cls , hash ):
82
142
"""Return the multihash `Func` for the hashlib-compatible `hash` object.
0 commit comments