File: Conduit.hs

package info (click to toggle)
haskell-crypton-conduit 0.2.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 100 kB
  • sloc: haskell: 243; makefile: 3
file content (48 lines) | stat: -rw-r--r-- 1,573 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
{-# LANGUAGE RankNTypes, BangPatterns #-}
-- |
-- Module      : Crypto.Hash.Conduit
-- License     : BSD-style
-- Maintainer  : Vincent Hanquez <vincent@snarc.org>
-- Stability   : experimental
-- Portability : unknown
--
-- A module containing Conduit facilities for hash based functions.
--
-- this module is vaguely similar to the crypto-conduit part related to hash
-- on purpose, as to provide an upgrade path. The api documentation is pulled
-- directly from this package and adapted, and thus are originally
-- copyright Felipe Lessa.
--
module Crypto.Hash.Conduit
    ( -- * Cryptographic hash functions
      sinkHash
    , hashFile
    ) where

import Crypto.Hash
import qualified Data.ByteString as B

import Data.Conduit
import Data.Conduit.Binary (sourceFile)

import Control.Monad.IO.Class (MonadIO, liftIO)

-- | A 'Sink' that hashes a stream of 'B.ByteString'@s@ and
-- creates a digest @d@.
sinkHash :: (Monad m, HashAlgorithm hash) => ConduitT B.ByteString o m (Digest hash)
sinkHash = sink hashInit
  where sink ctx = do
            b <- await
            case b of
                Nothing -> return $! hashFinalize ctx
                Just bs -> sink $! hashUpdate ctx bs

-- | Hashes the whole contents of the given file in constant
-- memory.  This function is just a convenient wrapper around
-- 'sinkHash' defined as:
--
-- @
-- hashFile fp = 'liftIO' $ 'runConduitRes' ('sourceFile' fp '.|' 'sinkHash')
-- @
hashFile :: (MonadIO m, HashAlgorithm hash) => FilePath -> m (Digest hash)
hashFile fp = liftIO $ runConduitRes (sourceFile fp .| sinkHash)