util: introduce kernel utils for pseudorandom number generation

Currently there are two generators. The fast one is the same one the scheduler
is using. The standard one is the same algorithm libroot's rand() uses. Should
there be a need for more cryptographically PRNG MD4 or MD5 might be a good
candidates.
This commit is contained in:
Pawel Dziepak
2013-04-11 04:34:59 +02:00
parent feae2b5a00
commit 6003243ef3
3 changed files with 124 additions and 0 deletions
+69
View File
@@ -0,0 +1,69 @@
/*
* Copyright 2013 Haiku, Inc. All rights reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Paweł Dziepak, [email protected]
*/
#ifndef KERNEL_UTIL_RANDOM_H
#define KERNEL_UTIL_RANDOM_H
#include <smp.h>
#include <SupportDefs.h>
#define MAX_FAST_RANDOM_VALUE 0x7fff
#define MAX_RANDOM_VALUE 0x7fffffffu
const int kFastRandomShift = 15;
const int kRandomShift = 31;
#ifdef __cplusplus
extern "C" {
#endif
unsigned int fast_random_value(void);
unsigned int random_value(void);
#ifdef __cplusplus
}
#endif
#ifdef __cplusplus
template<typename T>
T
fast_get_random()
{
size_t shift = 0;
T random = 0;
while (shift < sizeof(T) * 8) {
random |= (T)fast_random_value() << shift;
shift += kFastRandomShift;
}
return random;
}
template<typename T>
T
get_random()
{
size_t shift = 0;
T random = 0;
while (shift < sizeof(T) * 8) {
random |= (T)random_value() << shift;
shift += kRandomShift;
}
return random;
}
#endif // __cplusplus
#endif // KERNEL_UTIL_RANDOM_H