| Copyright | (c) 2026 Jared Tobin |
|---|---|
| License | MIT |
| Maintainer | Jared Tobin <jared@ppad.tech> |
| Safe Haskell | None |
| Language | Haskell2010 |
Crypto.PRNG.Pure
Description
A fast, non-cryptographic pseudorandom number generator, xoshiro256++, as an immutable value.
This is the generator of Crypto.PRNG, with the same output for the
same seed, but threaded through code explicitly: each function
returns its result along with the next generator. Generators are
values, so using one twice yields the same output twice; derive
non-overlapping streams via jump or long_jump.
When these functions are inlined into a strict loop, GHC keeps the
generator's state in registers and allocates nothing, which is
several times faster than the mutable generator. Bind results with
case or bang patterns rather than lazy lets. Called where GHC
can't inline or specialise them, e.g. via a lazy fold or an
unspecialised class method, each draw allocates, and the mutable
Crypto.PRNG may be faster.
Its output is predictable from a small sample; use Crypto.CSPRNG for anything that must be unpredictable.
Synopsis
- data Gen
- data Draw a = Draw !a !Gen
- new :: Word64 -> Gen
- new_system :: IO (Maybe Gen)
- from_state :: Word64 -> Word64 -> Word64 -> Word64 -> Maybe Gen
- word64 :: Gen -> Draw Word64
- word64_range :: Word64 -> Word64 -> Gen -> Draw Word64
- int_range :: Int -> Int -> Gen -> Draw Int
- double :: Gen -> Draw Double
- jump :: Gen -> Gen
- long_jump :: Gen -> Gen
Generator
Create a generator from a 64-bit seed, expanded to the full 256-bit state via splitmix64, per the xoshiro authors' recommendation.
>>>let Draw w _ = word64 (new 42)>>>w15021278609987233951
new_system :: IO (Maybe Gen) Source #
Create a generator with a 256-bit state drawn from the operating
system's entropy source, returning Nothing if that fails.
>>>Just gen <- new_system
from_state :: Word64 -> Word64 -> Word64 -> Word64 -> Maybe Gen Source #
Create a generator from the given 256-bit state, returning
Nothing if it is all zero.
>>>let Just gen = from_state 1 2 3 4>>>let Draw w _ = word64 gen>>>w41943041
Output
word64 :: Gen -> Draw Word64 Source #
Generate a uniformly-distributed Word64.
>>>let Just gen = from_state 1 2 3 4>>>let Draw a g1 = word64 gen>>>let Draw b _ = word64 g1>>>(a, b)(41943041,58720359)
int_range :: Int -> Int -> Gen -> Draw Int Source #
Generate a uniformly-distributed Int in the given inclusive
range, whose bounds may be given in either order.
The result is unbiased, via Lemire's method: an occasional draw is rejected and replaced, so the number of words consumed varies.
>>>let Draw x _ = int_range (-10) 10 (new 42)>>>x7
Streams
Advance a generator by 2 ^ 128 outputs.
Repeated jumps yield up to 2 ^ 128 non-overlapping streams of 2 ^ 128 outputs each, e.g. one per thread.
>>>let gens = take 4 (iterate jump (new 42))