96713c505b09b9faf7f646fa374c81cc81193c8d
[cascardo/ovs.git] / lib / random.c
1 /*
2  * Copyright (c) 2008, 2009 Nicira Networks.
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 #include <config.h>
18 #include "random.h"
19
20 #include <errno.h>
21 #include <stdlib.h>
22 #include <sys/time.h>
23
24 #include "util.h"
25
26 void
27 random_init(void)
28 {
29     static bool inited = false;
30     if (!inited) {
31         struct timeval tv;
32         inited = true;
33         if (gettimeofday(&tv, NULL) < 0) {
34             ovs_fatal(errno, "gettimeofday");
35         }
36         srand(tv.tv_sec ^ tv.tv_usec);
37     }
38 }
39
40 void
41 random_bytes(void *p_, size_t n)
42 {
43     uint8_t *p = p_;
44     random_init();
45     while (n--) {
46         *p++ = rand();
47     }
48 }
49
50 uint8_t
51 random_uint8(void)
52 {
53     random_init();
54     return rand();
55 }
56
57 uint16_t
58 random_uint16(void)
59 {
60     if (RAND_MAX >= UINT16_MAX) {
61         random_init();
62         return rand();
63     } else {
64         uint16_t x;
65         random_bytes(&x, sizeof x);
66         return x;
67     }
68 }
69
70 uint32_t
71 random_uint32(void)
72 {
73     if (RAND_MAX >= UINT32_MAX) {
74         random_init();
75         return rand();
76     } else if (RAND_MAX == INT32_MAX) {
77         random_init();
78         return rand() | ((rand() & 1u) << 31);
79     } else {
80         uint32_t x;
81         random_bytes(&x, sizeof x);
82         return x;
83     }
84 }
85
86 int
87 random_range(int max) 
88 {
89     return random_uint32() % max;
90 }