Ne.app NeANT
The Ne.app NeANT User module of the NeANT distribution.
random.cpp
Go to the documentation of this file.
1
42#define _RWSTD_LIB_SRC
43
44#include <rw/_defs.h>
45
46#ifdef _RWSTD_REENTRANT
47# include <rw/_mutex.h>
48#endif // _RWSTD_REENTRANT
49
50#include <stddef.h> // for size_t
51
52
54
55
56#ifndef _RWSTD_NO_EXT_PORTABLE_RANDOM_SEQUENCE
57
58// generator produces the same sequence of random numbers
59// irrespective of the architecture and width of integers
60typedef _RWSTD_UINT32_T __rw_random_t;
61
62#else // if defined (_RWSTD_NO_EXT_PORTABLE_RANDOM_SEQUENCE)
63
64// generator may produces a different sequence of random numbers
65// on different architectures (depending on the width of size_t)
66typedef _RWSTD_SIZE_T __rw_random_t;
67
68#endif // _RWSTD_NO_EXT_PORTABLE_RANDOM_SEQUENCE
69
70
71static _RWSTD_THREAD __rw_random_t
72__rw_table [55];
73
74static _RWSTD_THREAD __rw_random_t
75__rw_inx [2];
76
77static const __rw_random_t
78__rw_table_size = __rw_random_t (sizeof __rw_table / sizeof *__rw_table);
79
80
81static void
82__rw_seed ( __rw_random_t seed)
83{
84 __rw_table [__rw_table_size - 1] = seed;
85
86 _RWSTD_SIZE_T i;
87
88 __rw_random_t k = 1;
89
90 for (i = 0; i != __rw_table_size - 1; ++i) {
91 const _RWSTD_SIZE_T ii = 21U * i % __rw_table_size;
92 __rw_table [ii] = k;
93 k = seed - k;
94 seed = __rw_table [ii];
95 }
96
97 for (i = 0; i != 4U; ++i) {
98 for (_RWSTD_SIZE_T ii = 0; ii != __rw_table_size; ++ii)
99 __rw_table [i] =
100 __rw_table [i] - __rw_table [(i + 31U) % __rw_table_size];
101 }
102
103 __rw_inx [0] = 0U;
104 __rw_inx [1] = __rw_table_size * 2U / 3U - 1U;
105}
106
107
108struct _RandGuardT;
109
110_RWSTD_EXPORT _RWSTD_SIZE_T
111__rw_rand (_RWSTD_SIZE_T limit)
112{
113 _RWSTD_ASSERT (0 != limit);
114
115#ifdef _RWSTD_NO_TLS
116
117 _RWSTD_MT_STATIC_GUARD (_RandGuardT);
118
119#endif // _RWSTD_NO_TLS
120
121 if (0 == __rw_inx [0] && 0 == __rw_inx [1])
122 __rw_seed (161803398U);
123
124 __rw_table [++__rw_inx [0] %= __rw_table_size] -=
125 __rw_table [++__rw_inx [1] %= __rw_table_size];
126
127 return __rw_table [__rw_inx [0]] % limit;
128
129}
130
131
132} // namespace __rw
#define i
Definition 17.names.cpp:126
#define k
Definition 17.names.cpp:128
#define U
Definition 17.names.cpp:164
#define _RWSTD_THREAD
Definition TLS.cpp:30
#define _RWSTD_EXPORT
Definition _defs.h:485
#define _RWSTD_NAMESPACE(name)
Definition _defs.h:567
#define _RWSTD_ASSERT(ignore)
Definition _defs.h:1108
#define _RWSTD_MT_STATIC_GUARD(name)
Definition _defs.h:696