xref: /haiku/headers/private/kernel/util/Random.h (revision 83b1a68c52ba3e0e8796282759f694b7fdddf06d)
1 /*
2  * Copyright 2013 Haiku, Inc. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Paweł Dziepak, pdziepak@quarnos.org
7  */
8 #ifndef KERNEL_UTIL_RANDOM_H
9 #define KERNEL_UTIL_RANDOM_H
10 
11 
12 #include <smp.h>
13 #include <SupportDefs.h>
14 
15 
16 #define MAX_FAST_RANDOM_VALUE		0x7fff
17 #define MAX_RANDOM_VALUE			0x7fffffffu
18 #define MAX_SECURE_RANDOM_VALUE		0xffffffffu
19 
20 static const int	kFastRandomShift		= 15;
21 static const int	kRandomShift			= 31;
22 static const int	kSecureRandomShift		= 32;
23 
24 #ifdef __cplusplus
25 extern "C" {
26 #endif
27 
28 unsigned int	fast_random_value(void);
29 unsigned int	random_value(void);
30 unsigned int	secure_random_value(void);
31 
32 #ifdef __cplusplus
33 }
34 #endif
35 
36 
37 #ifdef __cplusplus
38 
39 template<typename T>
40 T
41 fast_get_random()
42 {
43 	size_t shift = 0;
44 	T random = 0;
45 	while (shift < sizeof(T) * 8) {
46 		random |= (T)fast_random_value() << shift;
47 		shift += kFastRandomShift;
48 	}
49 
50 	return random;
51 }
52 
53 
54 template<typename T>
55 T
56 get_random()
57 {
58 	size_t shift = 0;
59 	T random = 0;
60 	while (shift < sizeof(T) * 8) {
61 		random |= (T)random_value() << shift;
62 		shift += kRandomShift;
63 	}
64 
65 	return random;
66 }
67 
68 
69 template<typename T>
70 T
71 secure_get_random()
72 {
73 	size_t shift = 0;
74 	T random = 0;
75 	while (shift < sizeof(T) * 8) {
76 		random |= (T)secure_random_value() << shift;
77 		shift += kSecureRandomShift;
78 	}
79 
80 	return random;
81 }
82 
83 
84 #endif	// __cplusplus
85 
86 #endif	// KERNEL_UTIL_RANDOM_H
87 
88