2
0

pg_prng.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*-------------------------------------------------------------------------
  2. *
  3. * Pseudo-Random Number Generator
  4. *
  5. * Copyright (c) 2021-2022, PostgreSQL Global Development Group
  6. *
  7. * src/include/common/pg_prng.h
  8. *
  9. *-------------------------------------------------------------------------
  10. */
  11. #ifndef PG_PRNG_H
  12. #define PG_PRNG_H
  13. /*
  14. * State vector for PRNG generation. Callers should treat this as an
  15. * opaque typedef, but we expose its definition to allow it to be
  16. * embedded in other structs.
  17. */
  18. typedef struct pg_prng_state
  19. {
  20. uint64 s0,
  21. s1;
  22. } pg_prng_state;
  23. /*
  24. * Callers not needing local PRNG series may use this global state vector,
  25. * after initializing it with one of the pg_prng_...seed functions.
  26. */
  27. extern PGDLLIMPORT pg_prng_state pg_global_prng_state;
  28. extern void pg_prng_seed(pg_prng_state *state, uint64 seed);
  29. extern void pg_prng_fseed(pg_prng_state *state, double fseed);
  30. extern bool pg_prng_seed_check(pg_prng_state *state);
  31. /*
  32. * Initialize the PRNG state from the pg_strong_random source,
  33. * taking care that we don't produce all-zeroes. If this returns false,
  34. * caller should initialize the PRNG state from some other random seed,
  35. * using pg_prng_[f]seed.
  36. *
  37. * We implement this as a macro, so that the pg_strong_random() call is
  38. * in the caller. If it were in pg_prng.c, programs using pg_prng.c
  39. * but not needing strong seeding would nonetheless be forced to pull in
  40. * pg_strong_random.c and thence OpenSSL.
  41. */
  42. #define pg_prng_strong_seed(state) \
  43. (pg_strong_random((void *) (state), sizeof(pg_prng_state)) ? \
  44. pg_prng_seed_check(state) : false)
  45. extern uint64 pg_prng_uint64(pg_prng_state *state);
  46. extern uint64 pg_prng_uint64_range(pg_prng_state *state, uint64 rmin, uint64 rmax);
  47. extern int64 pg_prng_int64(pg_prng_state *state);
  48. extern int64 pg_prng_int64p(pg_prng_state *state);
  49. extern uint32 pg_prng_uint32(pg_prng_state *state);
  50. extern int32 pg_prng_int32(pg_prng_state *state);
  51. extern int32 pg_prng_int32p(pg_prng_state *state);
  52. extern double pg_prng_double(pg_prng_state *state);
  53. extern bool pg_prng_bool(pg_prng_state *state);
  54. #endif /* PG_PRNG_H */