]> git.lizzy.rs Git - uwu-nolambda.git/blob - random.c
Fix typo in README.md
[uwu-nolambda.git] / random.c
1 #include <stdlib.h>
2 #include "api/vm.h"
3 #include "api/util.h"
4 #include "api/int.h"
5 #include "api/nil.h"
6 #include "common/err.h"
7
8 UwUVMValue uwu_random(UwUVMArgs *args)
9 {
10         uwuutil_require_exact("random.random", args, 2);
11
12         UwUVMValue value0 = uwuvm_get_arg(args, 0);
13
14         if (value0.type != &uwuint_type)
15                 error("type error: random.random requires an integer as $1\n");
16
17         UwUVMValue value1 = uwuvm_get_arg(args, 1);
18
19         if (value1.type != &uwuint_type)
20                 error("type error: random.random requires an integer as $2\n");
21
22         long min = uwuint_get(value0);
23         long max = uwuint_get(value1) + 1;
24
25         long range = max - min;
26
27         if (range < 0)
28                 error("type error: range passed to random.random is empty\n");
29
30         if (range > RAND_MAX)
31                 error("type error: range passed to random.random is bigger than random.max");
32
33         return uwuint_create(min + rand() % range);
34 }
35
36 UwUVMValue uwu_max(UwUVMArgs *args)
37 {
38         uwuutil_require_exact("random.max", args, 0);
39         return uwuint_create(RAND_MAX);
40 }
41
42 UwUVMValue uwu_seed(UwUVMArgs *args)
43 {
44         uwuutil_require_exact("random.seed", args, 1);
45
46         UwUVMValue value = uwuvm_get_arg(args, 0);
47
48         if (value.type != &uwuint_type)
49                 error("type error: random.seed requires an integer as $1\n");
50
51         srand(uwuint_get(value) % RAND_MAX);
52         return uwunil_create();
53 }