Skip to content

Commit 4c87142

Browse files
author
Thomas M. DuBuisson
committed
Merge branch 'master' of github.com:TomMD/pureMD5
2 parents e7e77ba + bc23a75 commit 4c87142

File tree

1 file changed

+31
-4
lines changed

1 file changed

+31
-4
lines changed

Data/Digest/Pure/MD5.hs

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ module Data.Digest.Pure.MD5
3131
, md5
3232
, md5Update
3333
, md5Finalize
34+
, md5DigestBytes
3435
-- * Crypto-API interface
3536
, Hash(..)
3637
) where
@@ -39,6 +40,9 @@ import qualified Data.ByteString as B
3940
import qualified Data.ByteString.Lazy as L
4041
import Data.ByteString.Unsafe (unsafeDrop,unsafeUseAsCString)
4142
import Data.ByteString.Internal
43+
#if MIN_VERSION_binary(0,8,3)
44+
import Data.ByteString.Builder.Extra as B
45+
#endif
4246
import Data.Bits
4347
import Data.List
4448
import Data.Word
@@ -252,19 +256,42 @@ getNthWord n = right . G.runGet G.getWord32le . B.drop (n * sizeOf (undefined ::
252256
right x = case x of Right y -> y
253257
#endif
254258

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+
255283
----- Some quick and dirty instances follow -----
256284

257285
instance Show MD5Digest where
258286
show (MD5Digest h) = show h
259287

260288
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
264291
in foldl' (\str w -> let cx = showHex w str
265292
in if length cx < length str + 2
266293
then '0':cx
267-
else cx) "" (L.unpack bs)
294+
else cx) "" (B.unpack (B.reverse bs))
268295

269296
instance Binary MD5Digest where
270297
put (MD5Digest p) = put p

0 commit comments

Comments
 (0)