{-# OPTIONS_HADDOCK hide #-}

-- |
-- Module: Crypto.Entropy
-- Copyright: (c) 2026 Jared Tobin
-- License: MIT
-- Maintainer: Jared Tobin <jared@ppad.tech>
--
-- Entropy from the operating system, via getentropy(3).

module Crypto.Entropy (
    fill
  ) where

import Data.Word (Word8)
import Foreign.C.Types (CInt(..), CSize(..))
import Foreign.Ptr (Ptr)

-- getentropy may block until the system CSPRNG is seeded, so the call
-- is safe rather than unsafe
foreign import ccall safe "getentropy"
  c_getentropy :: Ptr Word8 -> CSize -> IO CInt

-- | Fill the destination with the given number of bytes (at most 256)
--   of entropy from the operating system, returning 'False' on
--   failure.
fill :: Ptr Word8 -> Int -> IO Bool
fill :: Ptr Word8 -> Int -> IO Bool
fill Ptr Word8
dst Int
n = do
  r <- Ptr Word8 -> CSize -> IO CInt
c_getentropy Ptr Word8
dst (Int -> CSize
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
n)
  pure $! r == 0