aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormax99x <max99x@gmail.com>2011-08-23 11:17:50 +0300
committermax99x <max99x@gmail.com>2011-08-23 11:17:50 +0300
commit7eb19241b1ff145a51912bfa02ffda7d913494d3 (patch)
tree7bc82982326d55af9733050a10e5dbd83e09b20a
parentdc1e8a0fb689436866d253036090e9fe7d4f3d73 (diff)
Implemented rand(), rand_r() and srand() using a simple Linear Congruential Generator.
-rw-r--r--src/library.js22
-rw-r--r--tests/runner.py42
2 files changed, 64 insertions, 0 deletions
diff --git a/src/library.js b/src/library.js
index 634f98dc..a7ac6fc0 100644
--- a/src/library.js
+++ b/src/library.js
@@ -3472,6 +3472,28 @@ LibraryManager.library = {
return limit;
},
+ // A glibc-like implementation of the C random number generation functions:
+ // http://pubs.opengroup.org/onlinepubs/000095399/functions/rand.html
+ __rand_state: 42,
+ srand__deps: ['__rand_state'],
+ srand: function(seed) {
+ // void srand(unsigned seed);
+ ___rand_state = seed;
+ },
+ rand__deps: ['__rand_state'],
+ rand: function() {
+ // int rand(void);
+ ___rand_state = (1103515245 * ___rand_state + 12345) % 0x100000000;
+ return ___rand_state & 0x7FFFFFFF;
+ },
+ rand_r: function(seed) {
+ // int rand_r(unsigned *seed);
+ var state = {{{ makeGetValue('seed', 0, 'i32') }}};
+ state = (1103515245 * state + 12345) % 0x100000000;
+ {{{ makeSetValue('seed', 0, 'state', 'i32') }}}
+ return state & 0x7FFFFFFF;
+ },
+
// ==========================================================================
// string.h
// ==========================================================================
diff --git a/tests/runner.py b/tests/runner.py
index 438726af..77aa0d4f 100644
--- a/tests/runner.py
+++ b/tests/runner.py
@@ -2043,6 +2043,48 @@ if 'benchmark' not in sys.argv:
output_nicerizer=lambda x: x.replace('\n', '*'),
post_build=add_pre_run_and_checks)
+ def test_rand(self):
+ src = r'''
+ #include <stdio.h>
+ #include <stdlib.h>
+
+ int main() {
+ printf("%d\n", rand());
+ printf("%d\n", rand());
+
+ srand(123);
+ printf("%d\n", rand());
+ printf("%d\n", rand());
+ srand(123);
+ printf("%d\n", rand());
+ printf("%d\n", rand());
+
+ unsigned state = 0;
+ int r;
+ r = rand_r(&state);
+ printf("%d, %u\n", r, state);
+ r = rand_r(&state);
+ printf("%d, %u\n", r, state);
+ state = 0;
+ r = rand_r(&state);
+ printf("%d, %u\n", r, state);
+
+ return 0;
+ }
+ '''
+ expected = '''
+ 1250496027
+ 1116302336
+ 440917656
+ 1476150784
+ 440917656
+ 1476150784
+ 12345, 12345
+ 1406932606, 3554416254
+ 12345, 12345
+ '''
+ self.do_test(src, re.sub(r'(^|\n)\s+', r'\1', expected))
+
def test_strtod(self):
src = r'''
#include <stdio.h>