aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/library.js30
-rw-r--r--tests/test_core.py61
2 files changed, 44 insertions, 47 deletions
diff --git a/src/library.js b/src/library.js
index 3df61724..d55f9c0c 100644
--- a/src/library.js
+++ b/src/library.js
@@ -3445,13 +3445,31 @@ LibraryManager.library = {
return limit;
},
- // Use browser's Math.random(). We can't set a seed, though.
- srand: function(seed) {}, // XXX ignored
+ __rand_seed: 'allocate([0x0273459b, 0, 0, 0], "i32", ALLOC_STATIC)',
+ srand__deps: ['__rand_seed'],
+ srand: function(seed) {
+ {{{ makeSetValue('___rand_seed', 0, 'seed', 'i32') }}}
+ },
+ rand_r__deps: ['__rand_seed'],
+ rand_r: function(seed) {
+ var val = {{{ makeGetValue('___rand_seed', 0, 'i32') }}};
+ // calculate val * 31010991 + 0x676e6177
+ // i32 multiplication will be rounded by javascript
+ var valh = val >> 16;
+ var vall = val & 0xffff;
+
+ var c = 31010991;
+ var ch = c >> 16;
+ var cl = c & 0xffff;
+
+ val = (((valh * cl + vall * ch) << 16) + vall * cl + 0x676e6177) & 0x7fffffff;
+
+ {{{ makeSetValue('___rand_seed', 0, 'val', 'i32') }}}
+ return val;
+ },
+ rand__deps: ['rand_r'],
rand: function() {
- return Math.floor(Math.random()*0x80000000);
- },
- rand_r: function(seed) { // XXX ignores the seed
- return Math.floor(Math.random()*0x80000000);
+ return _rand_r(___rand_seed);
},
drand48: function() {
diff --git a/tests/test_core.py b/tests/test_core.py
index 67e316e4..099da365 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -6576,48 +6576,27 @@ ok
''', post_build=self.dlfcn_post_build)
def test_rand(self):
- return self.skip('rand() is now random') # FIXME
-
- 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());
+ src = r'''#include <stdlib.h>
+#include <stdio.h>
+int main()
+{
+ srand(0xdeadbeef);
+ for(int i = 0; i < 10; ++i)
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_run(src, re.sub(r'(^|\n)\s+', r'\1', expected))
+ return 0;
+}
+'''
+ expected = '''2073540312
+730128159
+1365227432
+1337224527
+792390264
+1952655743
+983994184
+1982845871
+1210574360
+1479617503'''
+ self.do_run(src, expected)
def test_strtod(self):
if self.emcc_args is None: return self.skip('needs emcc for libc')