2 * libsortnetwork - src/sn_random.c
3 * Copyright (C) 2008-2010 Florian octo Forster
5 * This library is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU Lesser General Public License as published by
7 * the Free Software Foundation; either version 2.1 of the License, or (at
8 * your option) any later version.
10 * This library is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
15 * You should have received a copy of the GNU Lesser General Public License
16 * along with this library; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 * Florian octo Forster <ff at octo.it>
23 #ifndef _ISOC99_SOURCE
24 # define _ISOC99_SOURCE
26 #ifndef _POSIX_C_SOURCE
27 # define _POSIX_C_SOURCE 200112L
32 #include <sys/types.h>
40 #include "sn_random.h"
42 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
43 static unsigned int seed0;
44 static unsigned int seed1;
45 static int have_init = 0;
47 static int read_dev_random (void *buffer, size_t buffer_size)
52 char *buffer_position;
55 fd = open ("/dev/urandom", O_RDONLY);
62 buffer_position = (char *) buffer;
63 yet_to_read = buffer_size;
65 while (yet_to_read > 0)
67 status = read (fd, (void *) buffer_position, yet_to_read);
73 fprintf (stderr, "read_dev_random: read failed.\n");
77 buffer_position += status;
78 yet_to_read -= (size_t) status;
86 } /* int read_dev_random */
88 static void do_init (void)
93 read_dev_random (&seed0, sizeof (seed0));
94 read_dev_random (&seed1, sizeof (seed1));
98 int sn_random_init (void)
111 pthread_mutex_lock (&lock);
115 r0 = rand_r (&seed0);
116 r1 = rand_r (&seed1);
118 pthread_mutex_unlock (&lock);
121 } /* int sn_random */
123 int sn_true_random (void)
128 status = read_dev_random (&ret, sizeof (ret));
130 return (sn_random ());
133 } /* int sn_true_random */
135 int sn_bounded_random (int min, int max)
149 range = 1 + max - min;
150 rand = min + (int) (((double) range)
151 * (((double) sn_random ()) / (((double) RAND_MAX) + 1.0)));
153 assert (rand >= min);
154 assert (rand <= max);
157 } /* int sn_bounded_random */
159 double sn_double_random (void)
161 return (((double) sn_random ()) / (((double) RAND_MAX) + 1.0));
162 } /* double sn_double_random */
164 /* vim: set shiftwidth=2 softtabstop=2 : */