[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]

Re: [libvirt] [PATCH v2] Add virRandom() API to generate numbers with non-power-of-2 limit

On 08/14/2012 05:13 AM, Daniel P. Berrange wrote:
> From: "Daniel P. Berrange" <berrange redhat com>
> 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]

> +uint32_t virRandomInt(uint32_t max)
> +{
> +    double val = virRandom();
> +    return val * max;

I just realized this always goes through the slower path of using a
double; it might be worth doing a quick filter for a power of 2, and
forward that directly through virRandomBits(); I'll propose a followup
patch.  I find it easier to write virRandomInt(256) than
virRandomBits(8), for example.

Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org

Attachment: signature.asc
Description: OpenPGP digital signature

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]