random: Clean Up the Mt19937 state struct (#13577)

* random: Make Mt19937's `mode` field an enum

* random: Reorder the `php_random_status_state_mt19937` struct

Empirical testing did not show any differences in performance, but it makes
sense to me to put the `count` field (which is accessed for every invocation of
Mt19937) at the beginning of the struct, keeping it near the values from the
state array that are returned first, resulting in only a single cache line load
if only a small amount of numbers are requested.

It naturally follows to also put the `mode` field there and move the
humongous state array to the end.

* random: Remove the `MT_N` constant

`MT_N` is an awfully generic name that bleeds into every file including
`php_random.h`. As it's an implementation detail, remove it entirely to keep
`php_random.h` clean.

To prevent the state struct from diverging from the implementation, the size of
the state vector is statically verified. Furthermore there are phpt tests
verifying the Mt19937 output across a reload, revealing when the state vector
is reloaded too early or too late.
This commit is contained in:
Tim Düsterhus 2024-03-04 19:51:01 +01:00 committed by GitHub
parent 650a8fb098
commit 06569bbd04
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 19 additions and 15 deletions

View file

@ -45,10 +45,10 @@ PHPAPI double php_combined_lcg(void);
# define PHP_MT_RAND_MAX ((zend_long) (0x7FFFFFFF)) /* (1<<31) - 1 */
# define MT_RAND_MT19937 0
# define MT_RAND_PHP 1
# define MT_N (624)
enum php_random_mt19937_mode {
MT_RAND_MT19937 = 0,
MT_RAND_PHP = 1,
};
#define PHP_RANDOM_RANGE_ATTEMPTS (50)
@ -71,9 +71,9 @@ typedef struct _php_random_status_state_combinedlcg {
} php_random_status_state_combinedlcg;
typedef struct _php_random_status_state_mt19937 {
uint32_t state[MT_N];
uint32_t count;
uint8_t mode;
enum php_random_mt19937_mode mode;
uint32_t state[624];
} php_random_status_state_mt19937;
typedef struct _php_random_status_state_pcgoneseq128xslrr64 {