packages feed

crypto-rng-0.3.0.2: src/Crypto/RNG/Class.hs

module Crypto.RNG.Class
  ( CryptoRNG(..)
  ) where

import Control.Monad.Trans
import Data.ByteString qualified as BS
import System.Random qualified as R

-- | Monads carrying around the RNG state.
class Monad m => CryptoRNG m where
  -- | Generate a given number of cryptographically secure random bytes.
  randomBytes :: Int -> m BS.ByteString

  -- | Generate a cryptographically secure value uniformly distributed over all
  -- possible values of that type.
  random :: R.Uniform a => m a

  -- | Generate a cryptographically secure value in a given, closed range.
  randomR :: R.UniformRange a => (a, a) -> m a

-- | Generic, overlapping instance.
instance {-# OVERLAPPABLE #-}
  ( Monad (t m)
  , MonadTrans t
  , CryptoRNG m
  ) => CryptoRNG (t m) where
    randomBytes = lift . randomBytes
    random      = lift random
    randomR     = lift . randomR