Added SDL_srand(), SDL_rand(), and SDL_rand_r() (thanks @JKaniarz!)

These are simple random functions that should not be used for serious random number generation.

Fixes https://github.com/libsdl-org/SDL/issues/4968
This commit is contained in:
Sam Lantinga
2024-06-16 07:20:11 -07:00
parent 9cb4bb92f6
commit d1d484ddbe
23 changed files with 203 additions and 89 deletions

View File

@@ -1259,6 +1259,52 @@ extern SDL_DECLSPEC int SDLCALL SDL_vswprintf(SDL_OUT_Z_CAP(maxlen) wchar_t *tex
extern SDL_DECLSPEC int SDLCALL SDL_asprintf(char **strp, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2);
extern SDL_DECLSPEC int SDLCALL SDL_vasprintf(char **strp, SDL_PRINTF_FORMAT_STRING const char *fmt, va_list ap) SDL_PRINTF_VARARG_FUNCV(2);
/**
* Seed the pseudo-random number generator
*
* \param seed the value to use as a random number seed, or 0 to use SDL_GetPerformanceCounter()
*
* \threadsafety This should be called on the same thread that calls SDL_rand()
*
* \since This function is available since SDL 3.0.0.
*
* \sa SDL_rand
*/
extern SDL_DECLSPEC void SDLCALL SDL_srand(Uint64 seed);
/**
* Get a pseudo-random number.
*
* There are no guarantees as to the quality of the random sequence produced, and this should not be used for cryptography or anything that requires good random distribution. There are many random number libraries available with different characteristics and you should pick one of those to meet any serious needs.
*
* \returns a random value in the range of [0-SDL_MAX_UINT32]
*
* \threadsafety All calls should be from from a single thread, use SDL_rand_r() when using multiple threads.
*
* \since This function is available since SDL 3.0.0.
*
* \sa SDL_rand_r
* \sa SDL_srand
*/
extern SDL_DECLSPEC Uint32 SDLCALL SDL_rand(void);
/**
* Get a pseudo-random number.
*
* There are no guarantees as to the quality of the random sequence produced, and this should not be used for cryptography or anything that requires good random distribution. There are many random number libraries available with different characteristics and you should pick one of those to meet any serious needs.
*
* \param state a pointer to a 64-bit seed value that will be updated with each call to SDL_rand_r(). If the value of the seed is 0, it will be initialized with SDL_GetPerformanceCounter().
* \returns a random value in the range of [0-SDL_MAX_UINT32], or 0 if state is NULL.
*
* \threadsafety This can be called from any thread, however each thread should pass its own state pointer.
*
* \since This function is available since SDL 3.0.0.
*
* \sa SDL_rand
*/
extern SDL_DECLSPEC Uint32 SDLCALL SDL_rand_r(Uint64 *state);
#ifndef SDL_PI_D
#define SDL_PI_D 3.141592653589793238462643383279502884 /**< pi (double) */
#endif