Move random number generator from Math.random to jerry-libc, replace the logic with call to rand in Math.random.

JerryScript-DCO-1.0-Signed-off-by: Ruben Ayrapetyan r.ayrapetyan@samsung.com
This commit is contained in:
Ruben Ayrapetyan
2015-06-15 22:08:24 +03:00
parent 30277153b9
commit 6d6c913bdc
3 changed files with 68 additions and 18 deletions
+11
View File
@@ -25,4 +25,15 @@
extern EXTERN_C void __attribute__ ((noreturn)) exit (int);
extern EXTERN_C void __attribute__ ((noreturn)) abort (void);
/**
* Maximum integer that could be returned by random number generator
*
* See also:
* rand
*/
#define RAND_MAX (0x7fffffffu)
extern EXTERN_C int rand (void);
extern EXTERN_C void srand (unsigned int);
#endif /* !JERRY_LIBC_STDLIB_H */
+40
View File
@@ -24,6 +24,11 @@
#include "jerry-libc-defs.h"
/**
* State of pseudo-random number generator
*/
static unsigned int libc_random_gen_state[4] = { 1455997910, 1999515274, 1234451287, 1949149569 };
/**
* Standard file descriptors
*/
@@ -326,3 +331,38 @@ isxdigit (int c)
{
return isdigit (c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
}
/**
* Generate pseudo-random integer
*
* Note:
* The function implements George Marsaglia's XorShift random number generator
*
* @return integer in range [0; RAND_MAX]
*/
int
rand (void)
{
uint32_t intermediate = libc_random_gen_state[0] ^ (libc_random_gen_state[0] << 11);
intermediate ^= intermediate >> 8;
libc_random_gen_state[0] = libc_random_gen_state[1];
libc_random_gen_state[1] = libc_random_gen_state[2];
libc_random_gen_state[2] = libc_random_gen_state[3];
libc_random_gen_state[3] ^= libc_random_gen_state[3] >> 19;
libc_random_gen_state[3] ^= intermediate;
uint32_t ret = libc_random_gen_state[3] % (RAND_MAX + 1u);
return (int32_t) ret;
} /* rand */
/**
* Initialize pseudo-random number generator with the specified seed value
*/
void
srand (unsigned int seed) /**< new seed */
{
libc_random_gen_state[3] = seed;
} /* srand */