From d6c53fd0af4c395459f89a4e3fa9c5988c27ec32 Mon Sep 17 00:00:00 2001 From: Sam T Date: Mon, 8 Apr 2013 02:59:45 +0400 Subject: + mk newtype for info hash --- src/Data/Torrent/InfoHash.hs | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/Data/Torrent/InfoHash.hs (limited to 'src/Data/Torrent/InfoHash.hs') diff --git a/src/Data/Torrent/InfoHash.hs b/src/Data/Torrent/InfoHash.hs new file mode 100644 index 00000000..448e9a5a --- /dev/null +++ b/src/Data/Torrent/InfoHash.hs @@ -0,0 +1,41 @@ +module Data.Torrent.InfoHash + ( InfoHash (getInfoHash) + + -- ^ Construction + , hash, hashlazy + + -- ^ Extra + , ppHex + ) where + +import Control.Applicative +import Data.Foldable +import Data.ByteString (ByteString) +import qualified Data.ByteString as B +import qualified Data.ByteString.Char8 as BC +import qualified Data.ByteString.Builder as B +import qualified Data.ByteString.Builder.Prim as B +import qualified Data.ByteString.Lazy as Lazy +import Data.Serialize +import qualified Crypto.Hash.SHA1 as C + +-- | Exactly 20 bytes long SHA1 hash. +newtype InfoHash = InfoHash { getInfoHash :: ByteString } + deriving (Eq, Ord) + +instance Show InfoHash where + show = BC.unpack . ppHex + +instance Serialize InfoHash where + put = putByteString . getInfoHash + get = InfoHash <$> getBytes 20 + +hash :: ByteString -> InfoHash +hash = InfoHash . C.hash + +hashlazy :: Lazy.ByteString -> InfoHash +hashlazy = InfoHash . C.hashlazy + +ppHex :: InfoHash -> ByteString +ppHex = Lazy.toStrict . B.toLazyByteString . + foldMap (B.primFixed B.word8HexFixed) . B.unpack . getInfoHash -- cgit v1.2.3