Skip to content

Commit 103d5aa

Browse files
committed
Refactor jerry-libc's rand() and srand()
* Making sure that the type of the state variables is OK (`uint32_t` instead of `unsigned int`). * Making sure that globals are accessed as rarely as possible in `rand`, and getting type conversions OK. * Fixing `srand` to write all state variables and thus indeed generate the same random sequence. JerryScript-DCO-1.0-Signed-off-by: Akos Kiss akiss@inf.u-szeged.hu
1 parent 13bee3c commit 103d5aa

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

jerry-libc/jerry-libc.c

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
/**
2929
* State of pseudo-random number generator
3030
*/
31-
static unsigned int libc_random_gen_state[4] = { 1455997910, 1999515274, 1234451287, 1949149569 };
31+
static uint32_t libc_random_gen_state[4] = { 1455997910, 1999515274, 1234451287, 1949149569 };
3232

3333
/**
3434
* Standard file descriptors
@@ -240,7 +240,8 @@ strlen (const char *s)
240240
int
241241
rand (void)
242242
{
243-
uint32_t intermediate = libc_random_gen_state[0] ^ (libc_random_gen_state[0] << 11);
243+
uint32_t intermediate = libc_random_gen_state[0];
244+
intermediate ^= intermediate << 11;
244245
intermediate ^= intermediate >> 8;
245246

246247
libc_random_gen_state[0] = libc_random_gen_state[1];
@@ -250,9 +251,7 @@ rand (void)
250251
libc_random_gen_state[3] ^= libc_random_gen_state[3] >> 19;
251252
libc_random_gen_state[3] ^= intermediate;
252253

253-
uint32_t ret = libc_random_gen_state[3] % (RAND_MAX + 1u);
254-
255-
return (int32_t) ret;
254+
return libc_random_gen_state[3] % (RAND_MAX + 1u);
256255
} /* rand */
257256

258257
/**
@@ -261,5 +260,8 @@ rand (void)
261260
void
262261
srand (unsigned int seed) /**< new seed */
263262
{
263+
libc_random_gen_state[0] =
264+
libc_random_gen_state[1] =
265+
libc_random_gen_state[2] =
264266
libc_random_gen_state[3] = seed;
265267
} /* srand */

0 commit comments

Comments
 (0)