module_random.c
Go to the documentation of this file.
1 
7 #include <stdlib.h>
8 #include <time.h>
9 #include <sys/time.h>
10 #include <kuroko/vm.h>
11 #include <kuroko/util.h>
12 
13 static uint32_t x = 123456789;
14 static uint32_t y = 362436069;
15 static uint32_t z = 521288629;
16 static uint32_t w = 88675123;
17 
18 static int _rand(void) {
19  uint32_t t;
20 
21  t = x ^ (x << 11);
22  x = y; y = z; z = w;
23  w = w ^ (w >> 19) ^ t ^ (t >> 8);
24 
25  return (w & RAND_MAX);
26 }
27 
28 void _srand(unsigned int seed) {
29  x = 123456789 ^ (seed << 16) ^ (seed >> 16);
30  y = 362436069;
31  z = 521288629;
32  w = 88675123;
33 }
34 
35 KRK_Function(random) {
36  FUNCTION_TAKES_NONE();
37 
38  double r = (double)_rand() / (double)(RAND_MAX);
39 
40  return FLOATING_VAL(r);
41 }
42 
43 KRK_Function(seed) {
44  FUNCTION_TAKES_AT_MOST(1);
45  int seed;
46 
47  if (argc > 0) {
48  CHECK_ARG(0,int,krk_integer_type,_seed);
49  seed = _seed;
50  } else {
51  struct timeval tv;
52  gettimeofday(&tv,NULL);
53 
54  seed = tv.tv_sec ^ tv.tv_usec;
55  }
56 
57  _srand(seed);
58  return NONE_VAL();
59 }
60 
61 KRK_Module(random) {
62  KRK_DOC(module, "Functions for generating pseudo-random numbers.");
63 
64  BIND_FUNC(module, random);
65  BIND_FUNC(module, seed);
66 
67  FUNC_NAME(krk,seed)(0,NULL,0);
68 }
KRK_Module(socket)
Utilities for creating native bindings.
#define KRK_DOC(thing, text)
Attach documentation to a thing of various types.
Definition: util.h:304
Core API for the bytecode virtual machine.