Revert "gatomic: statically assert that our assumptions hold"
[platform/upstream/glib.git] / glib / grand.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
16  */
17
18 /* Originally developed and coded by Makoto Matsumoto and Takuji
19  * Nishimura.  Please mail <matumoto@math.keio.ac.jp>, if you're using
20  * code from this file in your own programs or libraries.
21  * Further information on the Mersenne Twister can be found at
22  * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
23  * This code was adapted to glib by Sebastian Wilhelmi.
24  */
25
26 /*
27  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
28  * file for a list of people on the GLib Team.  See the ChangeLog
29  * files for a list of changes.  These files are distributed with
30  * GLib at ftp://ftp.gtk.org/pub/gtk/.
31  */
32
33 /*
34  * MT safe
35  */
36
37 #include "config.h"
38 #define _CRT_RAND_S
39
40 #include <math.h>
41 #include <errno.h>
42 #include <stdio.h>
43 #include <string.h>
44 #include <sys/types.h>
45 #include "grand.h"
46
47 #include "genviron.h"
48 #include "gmain.h"
49 #include "gmem.h"
50 #include "gtestutils.h"
51 #include "gthread.h"
52
53 #ifdef G_OS_UNIX
54 #include <unistd.h>
55 #endif
56
57 #ifdef G_OS_WIN32
58 #include <stdlib.h>
59 #endif
60
61 /**
62  * SECTION:random_numbers
63  * @title: Random Numbers
64  * @short_description: pseudo-random number generator
65  *
66  * The following functions allow you to use a portable, fast and good
67  * pseudo-random number generator (PRNG).
68  * 
69  * Do not use this API for cryptographic purposes such as key
70  * generation, nonces, salts or one-time pads.
71  *
72  * This PRNG is suitable for non-cryptographic use such as in games
73  * (shuffling a card deck, generating levels), generating data for
74  * a test suite, etc. If you need random data for cryptographic
75  * purposes, it is recommended to use platform-specific APIs such
76  * as `/dev/random` on UNIX, or CryptGenRandom() on Windows.
77  *
78  * GRand uses the Mersenne Twister PRNG, which was originally
79  * developed by Makoto Matsumoto and Takuji Nishimura. Further
80  * information can be found at
81  * [this page](http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html).
82  *
83  * If you just need a random number, you simply call the g_random_*
84  * functions, which will create a globally used #GRand and use the
85  * according g_rand_* functions internally. Whenever you need a
86  * stream of reproducible random numbers, you better create a
87  * #GRand yourself and use the g_rand_* functions directly, which
88  * will also be slightly faster. Initializing a #GRand with a
89  * certain seed will produce exactly the same series of random
90  * numbers on all platforms. This can thus be used as a seed for
91  * e.g. games.
92  *
93  * The g_rand*_range functions will return high quality equally
94  * distributed random numbers, whereas for example the
95  * `(g_random_int()%max)` approach often
96  * doesn't yield equally distributed numbers.
97  *
98  * GLib changed the seeding algorithm for the pseudo-random number
99  * generator Mersenne Twister, as used by #GRand. This was necessary,
100  * because some seeds would yield very bad pseudo-random streams.
101  * Also the pseudo-random integers generated by g_rand*_int_range()
102  * will have a slightly better equal distribution with the new
103  * version of GLib.
104  *
105  * The original seeding and generation algorithms, as found in
106  * GLib 2.0.x, can be used instead of the new ones by setting the
107  * environment variable `G_RANDOM_VERSION` to the value of '2.0'.
108  * Use the GLib-2.0 algorithms only if you have sequences of numbers
109  * generated with Glib-2.0 that you need to reproduce exactly.
110  */
111
112 /**
113  * GRand:
114  *
115  * The GRand struct is an opaque data structure. It should only be
116  * accessed through the g_rand_* functions.
117  **/
118
119 G_LOCK_DEFINE_STATIC (global_random);
120
121 /* Period parameters */  
122 #define N 624
123 #define M 397
124 #define MATRIX_A 0x9908b0df   /* constant vector a */
125 #define UPPER_MASK 0x80000000 /* most significant w-r bits */
126 #define LOWER_MASK 0x7fffffff /* least significant r bits */
127
128 /* Tempering parameters */   
129 #define TEMPERING_MASK_B 0x9d2c5680
130 #define TEMPERING_MASK_C 0xefc60000
131 #define TEMPERING_SHIFT_U(y)  (y >> 11)
132 #define TEMPERING_SHIFT_S(y)  (y << 7)
133 #define TEMPERING_SHIFT_T(y)  (y << 15)
134 #define TEMPERING_SHIFT_L(y)  (y >> 18)
135
136 static guint
137 get_random_version (void)
138 {
139   static gsize initialized = FALSE;
140   static guint random_version;
141
142   if (g_once_init_enter (&initialized))
143     {
144       const gchar *version_string = g_getenv ("G_RANDOM_VERSION");
145       if (!version_string || version_string[0] == '\000' || 
146           strcmp (version_string, "2.2") == 0)
147         random_version = 22;
148       else if (strcmp (version_string, "2.0") == 0)
149         random_version = 20;
150       else
151         {
152           g_warning ("Unknown G_RANDOM_VERSION \"%s\". Using version 2.2.",
153                      version_string);
154           random_version = 22;
155         }
156       g_once_init_leave (&initialized, TRUE);
157     }
158   
159   return random_version;
160 }
161
162 struct _GRand
163 {
164   guint32 mt[N]; /* the array for the state vector  */
165   guint mti; 
166 };
167
168 /**
169  * g_rand_new_with_seed:
170  * @seed: a value to initialize the random number generator
171  * 
172  * Creates a new random number generator initialized with @seed.
173  * 
174  * Returns: the new #GRand
175  **/
176 GRand*
177 g_rand_new_with_seed (guint32 seed)
178 {
179   GRand *rand = g_new0 (GRand, 1);
180   g_rand_set_seed (rand, seed);
181   return rand;
182 }
183
184 /**
185  * g_rand_new_with_seed_array:
186  * @seed: an array of seeds to initialize the random number generator
187  * @seed_length: an array of seeds to initialize the random number
188  *     generator
189  * 
190  * Creates a new random number generator initialized with @seed.
191  * 
192  * Returns: the new #GRand
193  *
194  * Since: 2.4
195  */
196 GRand*
197 g_rand_new_with_seed_array (const guint32 *seed,
198                             guint          seed_length)
199 {
200   GRand *rand = g_new0 (GRand, 1);
201   g_rand_set_seed_array (rand, seed, seed_length);
202   return rand;
203 }
204
205 /**
206  * g_rand_new:
207  * 
208  * Creates a new random number generator initialized with a seed taken
209  * either from `/dev/urandom` (if existing) or from the current time
210  * (as a fallback).
211  *
212  * On Windows, the seed is taken from rand_s().
213  * 
214  * Returns: the new #GRand
215  */
216 GRand* 
217 g_rand_new (void)
218 {
219   guint32 seed[4];
220 #ifdef G_OS_UNIX
221   static gboolean dev_urandom_exists = TRUE;
222   GTimeVal now;
223
224   if (dev_urandom_exists)
225     {
226       FILE* dev_urandom;
227
228       do
229         {
230           dev_urandom = fopen("/dev/urandom", "rb");
231         }
232       while G_UNLIKELY (dev_urandom == NULL && errno == EINTR);
233
234       if (dev_urandom)
235         {
236           int r;
237
238           setvbuf (dev_urandom, NULL, _IONBF, 0);
239           do
240             {
241               errno = 0;
242               r = fread (seed, sizeof (seed), 1, dev_urandom);
243             }
244           while G_UNLIKELY (errno == EINTR);
245
246           if (r != 1)
247             dev_urandom_exists = FALSE;
248
249           fclose (dev_urandom);
250         }       
251       else
252         dev_urandom_exists = FALSE;
253     }
254
255   if (!dev_urandom_exists)
256     {  
257       g_get_current_time (&now);
258       seed[0] = now.tv_sec;
259       seed[1] = now.tv_usec;
260       seed[2] = getpid ();
261       seed[3] = getppid ();
262     }
263 #else /* G_OS_WIN32 */
264   gint i;
265
266   for (i = 0; i < G_N_ELEMENTS (seed); i++)
267     rand_s (&seed[i]);
268 #endif
269
270   return g_rand_new_with_seed_array (seed, 4);
271 }
272
273 /**
274  * g_rand_free:
275  * @rand_: a #GRand
276  *
277  * Frees the memory allocated for the #GRand.
278  */
279 void
280 g_rand_free (GRand *rand)
281 {
282   g_return_if_fail (rand != NULL);
283
284   g_free (rand);
285 }
286
287 /**
288  * g_rand_copy:
289  * @rand_: a #GRand
290  *
291  * Copies a #GRand into a new one with the same exact state as before.
292  * This way you can take a snapshot of the random number generator for
293  * replaying later.
294  *
295  * Returns: the new #GRand
296  *
297  * Since: 2.4
298  */
299 GRand*
300 g_rand_copy (GRand *rand)
301 {
302   GRand* new_rand;
303
304   g_return_val_if_fail (rand != NULL, NULL);
305
306   new_rand = g_new0 (GRand, 1);
307   memcpy (new_rand, rand, sizeof (GRand));
308
309   return new_rand;
310 }
311
312 /**
313  * g_rand_set_seed:
314  * @rand_: a #GRand
315  * @seed: a value to reinitialize the random number generator
316  *
317  * Sets the seed for the random number generator #GRand to @seed.
318  */
319 void
320 g_rand_set_seed (GRand   *rand,
321                  guint32  seed)
322 {
323   g_return_if_fail (rand != NULL);
324
325   switch (get_random_version ())
326     {
327     case 20:
328       /* setting initial seeds to mt[N] using         */
329       /* the generator Line 25 of Table 1 in          */
330       /* [KNUTH 1981, The Art of Computer Programming */
331       /*    Vol. 2 (2nd Ed.), pp102]                  */
332       
333       if (seed == 0) /* This would make the PRNG produce only zeros */
334         seed = 0x6b842128; /* Just set it to another number */
335       
336       rand->mt[0]= seed;
337       for (rand->mti=1; rand->mti<N; rand->mti++)
338         rand->mt[rand->mti] = (69069 * rand->mt[rand->mti-1]);
339       
340       break;
341     case 22:
342       /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
343       /* In the previous version (see above), MSBs of the    */
344       /* seed affect only MSBs of the array mt[].            */
345       
346       rand->mt[0]= seed;
347       for (rand->mti=1; rand->mti<N; rand->mti++)
348         rand->mt[rand->mti] = 1812433253UL * 
349           (rand->mt[rand->mti-1] ^ (rand->mt[rand->mti-1] >> 30)) + rand->mti; 
350       break;
351     default:
352       g_assert_not_reached ();
353     }
354 }
355
356 /**
357  * g_rand_set_seed_array:
358  * @rand_: a #GRand
359  * @seed: array to initialize with
360  * @seed_length: length of array
361  *
362  * Initializes the random number generator by an array of longs.
363  * Array can be of arbitrary size, though only the first 624 values
364  * are taken.  This function is useful if you have many low entropy
365  * seeds, or if you require more then 32 bits of actual entropy for
366  * your application.
367  *
368  * Since: 2.4
369  */
370 void
371 g_rand_set_seed_array (GRand         *rand,
372                        const guint32 *seed,
373                        guint          seed_length)
374 {
375   int i, j, k;
376
377   g_return_if_fail (rand != NULL);
378   g_return_if_fail (seed_length >= 1);
379
380   g_rand_set_seed (rand, 19650218UL);
381
382   i=1; j=0;
383   k = (N>seed_length ? N : seed_length);
384   for (; k; k--)
385     {
386       rand->mt[i] = (rand->mt[i] ^
387                      ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1664525UL))
388               + seed[j] + j; /* non linear */
389       rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
390       i++; j++;
391       if (i>=N)
392         {
393           rand->mt[0] = rand->mt[N-1];
394           i=1;
395         }
396       if (j>=seed_length)
397         j=0;
398     }
399   for (k=N-1; k; k--)
400     {
401       rand->mt[i] = (rand->mt[i] ^
402                      ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1566083941UL))
403               - i; /* non linear */
404       rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
405       i++;
406       if (i>=N)
407         {
408           rand->mt[0] = rand->mt[N-1];
409           i=1;
410         }
411     }
412
413   rand->mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ 
414 }
415
416 /**
417  * g_rand_boolean:
418  * @rand_: a #GRand
419  *
420  * Returns a random #gboolean from @rand_.
421  * This corresponds to a unbiased coin toss.
422  *
423  * Returns: a random #gboolean
424  */
425 /**
426  * g_rand_int:
427  * @rand_: a #GRand
428  *
429  * Returns the next random #guint32 from @rand_ equally distributed over
430  * the range [0..2^32-1].
431  *
432  * Returns: a random number
433  */
434 guint32
435 g_rand_int (GRand *rand)
436 {
437   guint32 y;
438   static const guint32 mag01[2]={0x0, MATRIX_A};
439   /* mag01[x] = x * MATRIX_A  for x=0,1 */
440
441   g_return_val_if_fail (rand != NULL, 0);
442
443   if (rand->mti >= N) { /* generate N words at one time */
444     int kk;
445     
446     for (kk = 0; kk < N - M; kk++) {
447       y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
448       rand->mt[kk] = rand->mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
449     }
450     for (; kk < N - 1; kk++) {
451       y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
452       rand->mt[kk] = rand->mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
453     }
454     y = (rand->mt[N-1]&UPPER_MASK)|(rand->mt[0]&LOWER_MASK);
455     rand->mt[N-1] = rand->mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
456     
457     rand->mti = 0;
458   }
459   
460   y = rand->mt[rand->mti++];
461   y ^= TEMPERING_SHIFT_U(y);
462   y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
463   y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
464   y ^= TEMPERING_SHIFT_L(y);
465   
466   return y; 
467 }
468
469 /* transform [0..2^32] -> [0..1] */
470 #define G_RAND_DOUBLE_TRANSFORM 2.3283064365386962890625e-10
471
472 /**
473  * g_rand_int_range:
474  * @rand_: a #GRand
475  * @begin: lower closed bound of the interval
476  * @end: upper open bound of the interval
477  *
478  * Returns the next random #gint32 from @rand_ equally distributed over
479  * the range [@begin..@end-1].
480  *
481  * Returns: a random number
482  */
483 gint32 
484 g_rand_int_range (GRand  *rand,
485                   gint32  begin,
486                   gint32  end)
487 {
488   guint32 dist = end - begin;
489   guint32 random;
490
491   g_return_val_if_fail (rand != NULL, begin);
492   g_return_val_if_fail (end > begin, begin);
493
494   switch (get_random_version ())
495     {
496     case 20:
497       if (dist <= 0x10000L) /* 2^16 */
498         {
499           /* This method, which only calls g_rand_int once is only good
500            * for (end - begin) <= 2^16, because we only have 32 bits set
501            * from the one call to g_rand_int ().
502            *
503            * We are using (trans + trans * trans), because g_rand_int only
504            * covers [0..2^32-1] and thus g_rand_int * trans only covers
505            * [0..1-2^-32], but the biggest double < 1 is 1-2^-52. 
506            */
507           
508           gdouble double_rand = g_rand_int (rand) * 
509             (G_RAND_DOUBLE_TRANSFORM +
510              G_RAND_DOUBLE_TRANSFORM * G_RAND_DOUBLE_TRANSFORM);
511           
512           random = (gint32) (double_rand * dist);
513         }
514       else
515         {
516           /* Now we use g_rand_double_range (), which will set 52 bits
517            * for us, so that it is safe to round and still get a decent
518            * distribution
519            */
520           random = (gint32) g_rand_double_range (rand, 0, dist);
521         }
522       break;
523     case 22:
524       if (dist == 0)
525         random = 0;
526       else 
527         {
528           /* maxvalue is set to the predecessor of the greatest
529            * multiple of dist less or equal 2^32.
530            */
531           guint32 maxvalue;
532           if (dist <= 0x80000000u) /* 2^31 */
533             {
534               /* maxvalue = 2^32 - 1 - (2^32 % dist) */
535               guint32 leftover = (0x80000000u % dist) * 2;
536               if (leftover >= dist) leftover -= dist;
537               maxvalue = 0xffffffffu - leftover;
538             }
539           else
540             maxvalue = dist - 1;
541           
542           do
543             random = g_rand_int (rand);
544           while (random > maxvalue);
545           
546           random %= dist;
547         }
548       break;
549     default:
550       random = 0;               /* Quiet GCC */
551       g_assert_not_reached ();
552     }      
553  
554   return begin + random;
555 }
556
557 /**
558  * g_rand_double:
559  * @rand_: a #GRand
560  *
561  * Returns the next random #gdouble from @rand_ equally distributed over
562  * the range [0..1).
563  *
564  * Returns: a random number
565  */
566 gdouble 
567 g_rand_double (GRand *rand)
568 {    
569   /* We set all 52 bits after the point for this, not only the first
570      32. Thats why we need two calls to g_rand_int */
571   gdouble retval = g_rand_int (rand) * G_RAND_DOUBLE_TRANSFORM;
572   retval = (retval + g_rand_int (rand)) * G_RAND_DOUBLE_TRANSFORM;
573
574   /* The following might happen due to very bad rounding luck, but
575    * actually this should be more than rare, we just try again then */
576   if (retval >= 1.0) 
577     return g_rand_double (rand);
578
579   return retval;
580 }
581
582 /**
583  * g_rand_double_range:
584  * @rand_: a #GRand
585  * @begin: lower closed bound of the interval
586  * @end: upper open bound of the interval
587  *
588  * Returns the next random #gdouble from @rand_ equally distributed over
589  * the range [@begin..@end).
590  *
591  * Returns: a random number
592  */
593 gdouble 
594 g_rand_double_range (GRand   *rand,
595                      gdouble  begin,
596                      gdouble  end)
597 {
598   gdouble r;
599
600   r = g_rand_double (rand);
601
602   return r * end - (r - 1) * begin;
603 }
604
605 static GRand *
606 get_global_random (void)
607 {
608   static GRand *global_random;
609
610   /* called while locked */
611   if (!global_random)
612     global_random = g_rand_new ();
613
614   return global_random;
615 }
616
617 /**
618  * g_random_boolean:
619  *
620  * Returns a random #gboolean.
621  * This corresponds to a unbiased coin toss.
622  *
623  * Returns: a random #gboolean
624  */
625 /**
626  * g_random_int:
627  *
628  * Return a random #guint32 equally distributed over the range
629  * [0..2^32-1].
630  *
631  * Returns: a random number
632  */
633 guint32
634 g_random_int (void)
635 {
636   guint32 result;
637   G_LOCK (global_random);
638   result = g_rand_int (get_global_random ());
639   G_UNLOCK (global_random);
640   return result;
641 }
642
643 /**
644  * g_random_int_range:
645  * @begin: lower closed bound of the interval
646  * @end: upper open bound of the interval
647  *
648  * Returns a random #gint32 equally distributed over the range
649  * [@begin..@end-1].
650  *
651  * Returns: a random number
652  */
653 gint32 
654 g_random_int_range (gint32 begin,
655                     gint32 end)
656 {
657   gint32 result;
658   G_LOCK (global_random);
659   result = g_rand_int_range (get_global_random (), begin, end);
660   G_UNLOCK (global_random);
661   return result;
662 }
663
664 /**
665  * g_random_double:
666  *
667  * Returns a random #gdouble equally distributed over the range [0..1).
668  *
669  * Returns: a random number
670  */
671 gdouble 
672 g_random_double (void)
673 {
674   double result;
675   G_LOCK (global_random);
676   result = g_rand_double (get_global_random ());
677   G_UNLOCK (global_random);
678   return result;
679 }
680
681 /**
682  * g_random_double_range:
683  * @begin: lower closed bound of the interval
684  * @end: upper open bound of the interval
685  *
686  * Returns a random #gdouble equally distributed over the range
687  * [@begin..@end).
688  *
689  * Returns: a random number
690  */
691 gdouble 
692 g_random_double_range (gdouble begin,
693                        gdouble end)
694 {
695   double result;
696   G_LOCK (global_random);
697   result = g_rand_double_range (get_global_random (), begin, end);
698   G_UNLOCK (global_random);
699   return result;
700 }
701
702 /**
703  * g_random_set_seed:
704  * @seed: a value to reinitialize the global random number generator
705  * 
706  * Sets the seed for the global random number generator, which is used
707  * by the g_random_* functions, to @seed.
708  */
709 void
710 g_random_set_seed (guint32 seed)
711 {
712   G_LOCK (global_random);
713   g_rand_set_seed (get_global_random (), seed);
714   G_UNLOCK (global_random);
715 }