libmp: avoid temporary buffer allocation in mprand()

This commit is contained in:
cinap_lenrek 2016-12-28 18:19:52 +01:00
parent 7755561ae1
commit 45512020d2

View file

@ -6,31 +6,20 @@ mpint*
mprand(int bits, void (*gen)(uchar*, int), mpint *b) mprand(int bits, void (*gen)(uchar*, int), mpint *b)
{ {
mpdigit mask; mpdigit mask;
int n, m;
uchar *p;
n = DIGITS(bits);
if(b == nil){ if(b == nil){
b = mpnew(bits); b = mpnew(bits);
setmalloctag(b, getcallerpc(&bits)); setmalloctag(b, getcallerpc(&bits));
}else }else
mpbits(b, bits); mpbits(b, bits);
p = malloc(n*Dbytes); b->sign = 1;
if(p == nil) b->top = DIGITS(bits);
sysfatal("mprand: %r"); (*gen)((uchar*)b->p, b->top*Dbytes);
(*gen)(p, n*Dbytes);
betomp(p, n*Dbytes, b);
free(p);
// make sure we don't give too many bits mask = ((mpdigit)1 << (bits%Dbits))-1;
m = bits%Dbits; if(mask != 0)
if(m == 0) b->p[b->top-1] &= mask;
return b;
mask = 1;
mask <<= m;
mask--;
b->p[n-1] &= mask;
return mpnorm(b); return mpnorm(b);
} }