Debian Codegraph @

ext/-test-/random/loop.c

raw
1 #include "ruby/random.h"
2
3 static const uint32_t max_seeds = 1024;
4
5 typedef struct {
6 rb_random_t base;
7 uint32_t num, idx, *buf;
8 } rand_loop_t;
9
10 RB_RANDOM_INTERFACE_DECLARE_WITH_REAL(loop);
11 static const rb_random_interface_t random_loop_if = {
12 32,
13 RB_RANDOM_INTERFACE_DEFINE_WITH_REAL(loop)
14 };
15
16 RB_RANDOM_DEFINE_INIT_INT32_FUNC(loop)
17 static size_t
18 random_loop_memsize(const void *ptr)
19 {
20 const rand_loop_t *r = ptr;
21 return sizeof(*r) + r->num * sizeof(r->buf[0]);
22 }
23
24 static rb_random_data_type_t random_loop_type = {
25 "random/loop",
26 {
27 rb_random_mark,
28 RUBY_TYPED_DEFAULT_FREE,
29 random_loop_memsize,
30 },
31 RB_RANDOM_PARENT,
32 (void *)&random_loop_if,
33 RUBY_TYPED_FREE_IMMEDIATELY
34 };
35
36
37 static VALUE
38 loop_alloc(VALUE klass)
39 {
40 rand_loop_t *rnd;
41 VALUE obj = TypedData_Make_Struct(klass, rand_loop_t, &random_loop_type, rnd);
42 rb_random_base_init(&rnd->base);
43 return obj;
44 }
45
46 static void
47 loop_init(rb_random_t *rnd, const uint32_t *buf, size_t len)
48 {
49 rand_loop_t *r = (rand_loop_t *)rnd;
50
51 if (len > max_seeds) len = max_seeds;
52
53 REALLOC_N(r->buf, uint32_t, len);
54 MEMCPY(r->buf, buf, uint32_t, (r->num = (uint32_t)len));
55 }
56
57 static void
58 loop_get_bytes(rb_random_t *rnd, void *p, size_t n)
59 {
60 uint8_t *buf = p;
61 while (n > 0) {
62 uint32_t x = loop_get_int32(rnd);
63 switch (n % 4) {
64 case 0:
65 *buf++ = (uint8_t)x;
66 n--;
67 /* FALLTHROUGH */
68 case 3:
69 *buf++ = (uint8_t)x;
70 n--;
71 /* FALLTHROUGH */
72 case 2:
73 *buf++ = (uint8_t)x;
74 n--;
75 /* FALLTHROUGH */
76 case 1:
77 *buf++ = (uint8_t)x;
78 n--;
79 }
80 }
81 }
82
83 static uint32_t
84 loop_get_int32(rb_random_t *rnd)
85 {
86 rand_loop_t *r = (rand_loop_t *)rnd;
87 if (r->idx < r->num) {
88 uint32_t x = r->buf[r->idx++];
89 if (r->idx >= r->num) r->idx = 0;
90 return x;
91 }
92 else if (r->num) {
93 return r->buf[r->idx = 0];
94 }
95 return 0;
96 }
97
98 static double
99 loop_get_real(rb_random_t *rnd, int excl)
100 {
101 uint32_t a = loop_get_int32(rnd);
102 return ldexp(a, -16);
103 }
104
105 void
106 Init_random_loop(VALUE mod, VALUE base)
107 {
108 VALUE c = rb_define_class_under(mod, "Loop", base);
109 rb_define_alloc_func(c, loop_alloc);
110 RB_RANDOM_DATA_INIT_PARENT(random_loop_type);
111 }