

#include "crypto/rand.h"
#include "internal/common.h"


uint32_t ossl_rand_uniform_uint32(OSSL_LIB_CTX *ctx, uint32_t upper, int *err)
{
    uint32_t i, f;      
    uint32_t f2, rand;  
    uint64_t prod;      
    const int max_followup_iterations = 10;
    int j;

    if (!ossl_assert(upper > 0)) {
        *err = 0;
        return 0;
    }
    if (ossl_unlikely(upper == 1))
        return 0;

    
    if (RAND_bytes_ex(ctx, (unsigned char *)&rand, sizeof(rand), 0) <= 0) {
        *err = 1;
        return 0;
    }

    
    prod = (uint64_t)upper * rand;
    i = prod >> 32;
    f = prod & 0xffffffff;
    if (ossl_likely(f <= 1 + ~upper))    
        return i;

    
    for (j = 0; j < max_followup_iterations; j++) {
        if (RAND_bytes_ex(ctx, (unsigned char *)&rand, sizeof(rand), 0) <= 0) {
            *err = 1;
            return 0;
        }
        prod = (uint64_t)upper * rand;
        f2 = prod >> 32;
        f += f2;
        
        if (f < f2)
            return i + 1;
        
        if (ossl_likely(f != 0xffffffff))
            return i;
        
        f = prod & 0xffffffff;
    }
    
    return i;
}

uint32_t ossl_rand_range_uint32(OSSL_LIB_CTX *ctx, uint32_t lower, uint32_t upper,
                                int *err)
{
    if (!ossl_assert(lower < upper)) {
        *err = 1;
        return 0;
    }
    return lower + ossl_rand_uniform_uint32(ctx, upper - lower, err);
}
