diff options
author | Qu Wenruo <quwenruo@cn.fujitsu.com> | 2016-05-26 10:56:50 +0800 |
---|---|---|
committer | David Sterba <dsterba@suse.com> | 2016-06-01 16:43:25 +0200 |
commit | 17239a9c89dec5576784675edd205264535c1557 (patch) | |
tree | a4568be7e1095f342a36ff1e6c1b0b108f831d80 /utils.h | |
parent | ee0908ee81e55d730402cd4931513579b34ea792 (diff) |
btrfs-progs: utils: Introduce new pseudo random API
David has reported some quite chaos usage of pseudo random numbers.
Like using static srand seed, or even calling rand() without setting
seed correctly.
The new pseudo random API will initialize the random seed on its first
calling and use uniformly distributed pseudo random number generator as
backend.
Signed-off-by: Qu Wenruo <quwenruo@cn.fujitsu.com>
[ renamed variables and functions, added prefixes ]
Signed-off-by: David Sterba <dsterba@suse.com>
Diffstat (limited to 'utils.h')
-rw-r--r-- | utils.h | 34 |
1 files changed, 34 insertions, 0 deletions
@@ -337,4 +337,38 @@ static inline int error_on(int condition, const char *fmt, ...) return 1; } +/* Pseudo random number generator wrappers */ +u32 rand_u32(void); + +static inline int rand_int(void) +{ + return (int)(rand_u32()); +} + +static inline u64 rand_u64(void) +{ + u64 ret = 0; + + ret += rand_u32(); + ret <<= 32; + ret += rand_u32(); + return ret; +} + +static inline u16 rand_u16(void) +{ + return (u16)(rand_u32()); +} + +static inline u8 rand_u8(void) +{ + return (u8)(rand_u32()); +} + +/* Return random number in range [0, limit) */ +unsigned int rand_range(unsigned int upper); + +/* Also allow setting the seed manually */ +void init_rand_seed(u64 seed); + #endif |