summaryrefslogtreecommitdiff
path: root/src/librandom/rrandom_readint.c
blob: 6a34de21f90386a2955903b9487cb8894e8b8e5a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/* ISC license. */

#include <skalibs/uint.h>
#include <skalibs/bytestr.h>
#include <skalibs/unirandom.h>
#include "random-internal.h"
#include <skalibs/rrandom.h>

unsigned int rrandom_readint (rrandom *z, unsigned int n, unsigned int (*f) (unirandom *, char *, unsigned int))
{
  if (!n) return 0 ;
  else
  {
    unsigned int i = n, nchars = random_nchars(n), m = random_mask2(n-1) ;
    char tmp[UINT_PACK] ;
    while (i >= n)
    {
      if (rrandom_read(z, tmp, nchars, f) < nchars) return 0 ;
      byte_zero(tmp + nchars, UINT_PACK - nchars) ;
      uint_unpack(tmp, &i) ;
      i &= m ;
    }
    return i ;
  }
}