@@ -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
@@ -249,19 +253,42 @@ getNthWord n = right . G.runGet G.getWord32le . B.drop (n * sizeOf (undefined ::
249
253
right x = case x of Right y -> y
250
254
#endif
251
255
256
+ -- | The raw bytes of an 'MD5Digest'. It is always 16 bytes long.
257
+ --
258
+ -- You can also use the 'Binary' or 'S.Serialize' instances to output the raw
259
+ -- bytes. Alternatively you can use 'show' to prodce the standard hex
260
+ -- representation.
261
+ --
262
+ md5DigestBytes :: MD5Digest -> B. ByteString
263
+ md5DigestBytes (MD5Digest h) = md5PartialBytes h
264
+
265
+ md5PartialBytes :: MD5Partial -> B. ByteString
266
+ md5PartialBytes =
267
+ toBs . (put :: MD5Partial -> Put )
268
+ where
269
+ toBs :: Put -> B. ByteString
270
+ #if MIN_VERSION_binary(0,8,3)
271
+ -- with later binary versions we can control the buffer size precisely:
272
+ toBs = L. toStrict
273
+ . B. toLazyByteStringWith (B. untrimmedStrategy 16 0 ) L. empty
274
+ . execPut
275
+ #else
276
+ toBs = B. concat . L. toChunks . runPut
277
+ -- note L.toStrict is only in newer bytestring versions
278
+ #endif
279
+
252
280
----- Some quick and dirty instances follow -----
253
281
254
282
instance Show MD5Digest where
255
283
show (MD5Digest h) = show h
256
284
257
285
instance Show MD5Partial where
258
- show (MD5Par a b c d) =
259
- let bs = runPut $ putWord32be d >> putWord32be c >>
260
- putWord32be b >> putWord32be a
286
+ show md5par =
287
+ let bs = md5PartialBytes md5par
261
288
in foldl' (\ str w -> let cx = showHex w str
262
289
in if length cx < length str + 2
263
290
then ' 0' : cx
264
- else cx) " " (L . unpack bs )
291
+ else cx) " " (B . unpack ( B. reverse bs) )
265
292
266
293
instance Binary MD5Digest where
267
294
put (MD5Digest p) = put p
0 commit comments