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 seed;
44 static int have_init = 0;
46 static int read_dev_random (void *buffer, size_t buffer_size)
51 char *buffer_position;
54 fd = open ("/dev/random", O_RDONLY);
61 buffer_position = (char *) buffer;
62 yet_to_read = buffer_size;
64 while (yet_to_read > 0)
66 status = read (fd, (void *) buffer_position, yet_to_read);
72 fprintf (stderr, "read_dev_random: read failed.\n");
76 buffer_position += status;
77 yet_to_read -= (size_t) status;
85 } /* int read_dev_random */
87 static void do_init (void)
91 status = read_dev_random (&seed, sizeof (seed));
100 pthread_mutex_lock (&lock);
105 ret = rand_r (&seed);
107 pthread_mutex_unlock (&lock);
110 } /* int sn_random */
112 int sn_true_random (void)
117 status = read_dev_random (&ret, sizeof (ret));
119 return (sn_random ());
122 } /* int sn_true_random */
124 int sn_bounded_random (int min, int max)
138 range = 1 + max - min;
139 rand = min + (int) (((double) range)
140 * (((double) sn_random ()) / (((double) RAND_MAX) + 1.0)));
142 assert (rand >= min);
143 assert (rand <= max);
146 } /* int sn_bounded_random */
148 double sn_double_random (void)
150 return (((double) sn_random ()) / (((double) RAND_MAX) + 1.0));
151 } /* double sn_double_random */
153 /* vim: set shiftwidth=2 softtabstop=2 : */