@@ -31,6 +31,7 @@ module Data.Digest.Pure.MD5
31
31
, md5
32
32
, md5Update
33
33
, md5Finalize
34
+ , md5DigestBytes
34
35
-- * Crypto-API interface
35
36
, Hash (.. )
36
37
) where
@@ -39,6 +40,9 @@ import qualified Data.ByteString as B
39
40
import qualified Data.ByteString.Lazy as L
40
41
import Data.ByteString.Unsafe (unsafeDrop ,unsafeUseAsCString )
41
42
import Data.ByteString.Internal
43
+ #if MIN_VERSION_binary(0,8,3)
44
+ import Data.ByteString.Builder.Extra as B
45
+ #endif
42
46
import Data.Bits
43
47
import Data.List
44
48
import Data.Word
@@ -252,19 +256,42 @@ getNthWord n = right . G.runGet G.getWord32le . B.drop (n * sizeOf (undefined ::
252
256
right x = case x of Right y -> y
253
257
#endif
254
258
259
+ -- | The raw bytes of an 'MD5Digest'. It is always 16 bytes long.
260
+ --
261
+ -- You can also use the 'Binary' or 'S.Serialize' instances to output the raw
262
+ -- bytes. Alternatively you can use 'show' to prodce the standard hex
263
+ -- representation.
264
+ --
265
+ md5DigestBytes :: MD5Digest -> B. ByteString
266
+ md5DigestBytes (MD5Digest h) = md5PartialBytes h
267
+
268
+ md5PartialBytes :: MD5Partial -> B. ByteString
269
+ md5PartialBytes =
270
+ toBs . (put :: MD5Partial -> Put )
271
+ where
272
+ toBs :: Put -> B. ByteString
273
+ #if MIN_VERSION_binary(0,8,3)
274
+ -- with later binary versions we can control the buffer size precisely:
275
+ toBs = L. toStrict
276
+ . B. toLazyByteStringWith (B. untrimmedStrategy 16 0 ) L. empty
277
+ . execPut
278
+ #else
279
+ toBs = B. concat . L. toChunks . runPut
280
+ -- note L.toStrict is only in newer bytestring versions
281
+ #endif
282
+
255
283
----- Some quick and dirty instances follow -----
256
284
257
285
instance Show MD5Digest where
258
286
show (MD5Digest h) = show h
259
287
260
288
instance Show MD5Partial where
261
- show (MD5Par a b c d) =
262
- let bs = runPut $ putWord32be d >> putWord32be c >>
263
- putWord32be b >> putWord32be a
289
+ show md5par =
290
+ let bs = md5PartialBytes md5par
264
291
in foldl' (\ str w -> let cx = showHex w str
265
292
in if length cx < length str + 2
266
293
then ' 0' : cx
267
- else cx) " " (L . unpack bs )
294
+ else cx) " " (B . unpack ( B. reverse bs) )
268
295
269
296
instance Binary MD5Digest where
270
297
put (MD5Digest p) = put p
0 commit comments