File: Entropy.hs

package info (click to toggle)
haskell-foundation 0.0.30-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 932 kB
  • sloc: haskell: 9,124; ansic: 570; makefile: 7
file content (43 lines) | stat: -rw-r--r-- 1,237 bytes parent folder | download | duplicates (4)
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
-- |
-- Module      : Foundation.System.Entropy
-- License     : BSD-style
-- Maintainer  : Foundation
-- Stability   : stable
-- Portability : good
--
{-# LANGUAGE CPP #-}
module Foundation.System.Entropy
    ( getEntropy
    ) where


import           Basement.Compat.Base
import           Basement.Types.OffsetSize
import qualified Basement.UArray.Mutable as A
import qualified Basement.UArray as A
import           Control.Exception
import           Foreign.Ptr
import           Foundation.Numerical

import           Foundation.System.Entropy.Common
#ifdef mingw32_HOST_OS
import           Foundation.System.Entropy.Windows
#else
import           Foundation.System.Entropy.Unix
#endif

-- | Get some of the system entropy
getEntropy :: CountOf Word8 -> IO (A.UArray Word8)
getEntropy n@(CountOf x) = do
    m <- A.newPinned n
    bracket entropyOpen entropyClose $ \ctx -> A.withMutablePtr m $ loop ctx x
    A.unsafeFreeze m
  where
    loop :: EntropyCtx -> Int -> Ptr Word8 -> IO ()
    loop _   0 _ = return ()
    loop ctx i p = do
        let chSz = min entropyMaximumSize i
        r <- entropyGather ctx p chSz
        if r
            then loop ctx (i-chSz) (p `plusPtr` chSz)
            else throwIO EntropySystemMissing