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
20static const int	kFastRandomShift		= 15;
21static const int	kRandomShift			= 31;
22static const int	kSecureRandomShift		= 32;
23
24#ifdef __cplusplus
25extern "C" {
26#endif
27
28unsigned int	fast_random_value(void);
29unsigned int	random_value(void);
30unsigned int	secure_random_value(void);
31
32#ifdef __cplusplus
33}
34#endif
35
36
37#ifdef __cplusplus
38
39template<typename T>
40T
41fast_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
54template<typename T>
55T
56get_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
69template<typename T>
70T
71secure_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