* uniformly distributed in the interval %$[2^{b - 1}, 2^b)$%.
* The result is then ORred with the given @or@ value. This
* will often be 1, to make the result odd.
+ *
+ * The length @b@ may be zero; but %$\texttt{or} \ge 2^b$% is
+ * not permitted.
*/
mp *mprand(mp *d, unsigned b, grand *r, mpw or)
{
size_t sz = (b + 7) >> 3;
arena *a = (d && (d->f & MP_BURN)) ? arena_secure : arena_global;
- octet *v = x_alloc(a, sz);
+ octet *v;
unsigned m;
+ assert(b >= MPW_BITS || !(or >> b));
+
+ /* --- Special case --- */
+
+ if (!b) return (MP_ZERO);
+
/* --- Fill buffer with random data --- */
+ v = x_alloc(a, sz);
r->ops->fill(r, v, sz);
/* --- Force into the correct range --- *
/* --- Mask, load and return --- */
d = mp_loadb(d, v, sz);
- d->v[0] |= or;
+ if (or) {
+ assert(d->sz);
+ if (!MP_LEN(d)) d->vl = d->v + 1;
+ d->v[0] |= or;
+ }
memset(v, 0, sz);
x_free(a, v);
return (d);
* interval %$[0, l)$%.
*
* Use: Generates a uniformly-distributed pseudorandom number in the
- * appropriate range.
+ * appropriate range. We must have %$l > 0$%.
*/
mp *mprand_range(mp *d, mp *l, grand *r, mpw or)
* As usual, the number of iterations expected is two.
*/
+ assert(MP_POSP(l));
b = ((b - 1) & 7) + 1;
m = (1 << b) - 1;
do {