File: RandomSource.hs

package info (click to toggle)
haskell-hashable 1.2.1.0-5
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 196 kB
  • ctags: 39
  • sloc: haskell: 975; ansic: 456; makefile: 3
file content (32 lines) | stat: -rw-r--r-- 932 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
{-# LANGUAGE CPP, ForeignFunctionInterface #-}
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702
{-# LANGUAGE Trustworthy #-}
#endif

module Data.Hashable.RandomSource
    (
      getRandomBytes
    , getRandomBytes_
    ) where

import Data.ByteString as B
import Data.ByteString.Internal (create)
import Foreign.C.Error (throwErrnoIfMinus1_)
#if MIN_VERSION_base(4,5,0)
import Foreign.C.Types (CInt(CInt))
#else
import Foreign.C.Types (CInt)
#endif
import Foreign.Ptr (Ptr)

getRandomBytes :: Int -> IO ByteString
getRandomBytes nbytes
    | nbytes <= 0 = return B.empty
    | otherwise = create nbytes $ flip (getRandomBytes_ "getRandomBytes") nbytes

getRandomBytes_ :: String -> Ptr a -> Int -> IO ()
getRandomBytes_ what ptr nbytes = do
  throwErrnoIfMinus1_ what $ c_getRandomBytes ptr (fromIntegral nbytes)

foreign import ccall unsafe "hashable_getRandomBytes" c_getRandomBytes
    :: Ptr a -> CInt -> IO CInt