##// END OF EJS Templates
util: add a helper class to compute digests...
Mike Hommey -
r22962:4d58f408 default
parent child Browse files
Show More
@@ -117,6 +117,72 def md5(s=''):
117 117 md5 = _md5
118 118 return _md5(s)
119 119
120 DIGESTS = {
121 'md5': md5,
122 'sha1': sha1,
123 }
124 # List of digest types from strongest to weakest
125 DIGESTS_BY_STRENGTH = ['sha1', 'md5']
126
127 try:
128 import hashlib
129 DIGESTS.update({
130 'sha512': hashlib.sha512,
131 })
132 DIGESTS_BY_STRENGTH.insert(0, 'sha512')
133 except ImportError:
134 pass
135
136 for k in DIGESTS_BY_STRENGTH:
137 assert k in DIGESTS
138
139 class digester(object):
140 """helper to compute digests.
141
142 This helper can be used to compute one or more digests given their name.
143
144 >>> d = digester(['md5', 'sha1'])
145 >>> d.update('foo')
146 >>> [k for k in sorted(d)]
147 ['md5', 'sha1']
148 >>> d['md5']
149 'acbd18db4cc2f85cedef654fccc4a4d8'
150 >>> d['sha1']
151 '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33'
152 >>> digester.preferred(['md5', 'sha1'])
153 'sha1'
154 """
155
156 def __init__(self, digests, s=''):
157 self._hashes = {}
158 for k in digests:
159 if k not in DIGESTS:
160 raise Abort(_('unknown digest type: %s') % k)
161 self._hashes[k] = DIGESTS[k]()
162 if s:
163 self.update(s)
164
165 def update(self, data):
166 for h in self._hashes.values():
167 h.update(data)
168
169 def __getitem__(self, key):
170 if key not in DIGESTS:
171 raise Abort(_('unknown digest type: %s') % k)
172 return self._hashes[key].hexdigest()
173
174 def __iter__(self):
175 return iter(self._hashes)
176
177 @staticmethod
178 def preferred(supported):
179 """returns the strongest digest type in both supported and DIGESTS."""
180
181 for k in DIGESTS_BY_STRENGTH:
182 if k in supported:
183 return k
184 return None
185
120 186 try:
121 187 buffer = buffer
122 188 except NameError:
General Comments 0
You need to be logged in to leave comments. Login now