mirror of
https://gitlab.com/libvirt/libvirt.git
synced 2024-08-28 11:31:16 +00:00
Add virRandom() API to generate numbers with non-power-of-2 limit
The current virRandomBits() API is only usable if the caller wants a random number in the range [0, n-1) where n is a power of two. This adds a virRandom() API which generates a double in the range [0.0,1.0) with 48 bits of entropy. It then also adds a virRandomInt(uint32_t max) API which generates an unsigned in the range [0,@max) Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
This commit is contained in:
parent
0a6504d40c
commit
aa5bd8b9b9
@ -1641,8 +1641,10 @@ virPidFileDeletePath;
|
|||||||
|
|
||||||
|
|
||||||
# virrandom.h
|
# virrandom.h
|
||||||
|
virRandom;
|
||||||
virRandomBits;
|
virRandomBits;
|
||||||
virRandomGenerateWWN;
|
virRandomGenerateWWN;
|
||||||
|
virRandomInt;
|
||||||
|
|
||||||
|
|
||||||
# virsocketaddr.h
|
# virsocketaddr.h
|
||||||
|
@ -23,6 +23,7 @@
|
|||||||
|
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <inttypes.h>
|
#include <inttypes.h>
|
||||||
|
#include <math.h>
|
||||||
|
|
||||||
#include "virrandom.h"
|
#include "virrandom.h"
|
||||||
#include "threads.h"
|
#include "threads.h"
|
||||||
@ -108,6 +109,37 @@ uint64_t virRandomBits(int nbits)
|
|||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* virRandom:
|
||||||
|
*
|
||||||
|
* Generate an evenly distributed random number between [0.0,1.0)
|
||||||
|
*
|
||||||
|
* Return: a random number with 48 bits of entropy
|
||||||
|
*/
|
||||||
|
double virRandom(void)
|
||||||
|
{
|
||||||
|
uint64_t val = virRandomBits(48);
|
||||||
|
|
||||||
|
return ldexp(val, -48);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* virRandomInt:
|
||||||
|
* @max: upper limit
|
||||||
|
*
|
||||||
|
* Generate an evenly distributed random integer between [0, @max)
|
||||||
|
*
|
||||||
|
* Return: a random number between [0,@max)
|
||||||
|
*/
|
||||||
|
uint32_t virRandomInt(uint32_t max)
|
||||||
|
{
|
||||||
|
double val = virRandom();
|
||||||
|
return val * max;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
#define QUMRANET_OUI "001a4a"
|
#define QUMRANET_OUI "001a4a"
|
||||||
#define VMWARE_OUI "000569"
|
#define VMWARE_OUI "000569"
|
||||||
#define MICROSOFT_OUI "0050f2"
|
#define MICROSOFT_OUI "0050f2"
|
||||||
|
@ -25,6 +25,8 @@
|
|||||||
# include "internal.h"
|
# include "internal.h"
|
||||||
|
|
||||||
uint64_t virRandomBits(int nbits);
|
uint64_t virRandomBits(int nbits);
|
||||||
|
double virRandom(void);
|
||||||
|
uint32_t virRandomInt(uint32_t max);
|
||||||
int virRandomGenerateWWN(char **wwn, const char *virt_type);
|
int virRandomGenerateWWN(char **wwn, const char *virt_type);
|
||||||
|
|
||||||
#endif /* __VIR_RANDOM_H__ */
|
#endif /* __VIR_RANDOM_H__ */
|
||||||
|
Loading…
Reference in New Issue
Block a user