nim-random
nim-random copied to clipboard
randomInt may fail for large ranges
In randomIntImpl() there is # We're assuming 0 < max <= int64.high
. An assert would be better. It might catch that randomInt(low(int), high(int)) would call randomIntImpl() with too high of a value (if it don't overflows first, I've not checked). Actually, think that ranges up to uint64.high - 2 are probably fine, but I'm not sure.
This needs to be documented at least. Related to this issue
This is an internal function, and the assumption can never be violated on any system supported by Nim as far as I'm aware.
There are two calls to it: with a (converted) Positive
which is ≤ int.high
≤ int64.high
, and with 2^53 < 2^63-1 = int64.high
Feel free to reopen if you have information on the contrary
Ok, there will be a overflow inside proc randomInt*(rng: var RNG; min, max: int)
when max - min > int64.high
. So it indeed will not reach randomIntImpl()
, but the title remains true, randomInt will fail for large ranges. I can't test because I don't know how to call your library that I instaled via nimble, as "import random" imports the std lib random.
I looked at this issue just now and I can tell you the implementation would be really ugly and not worth it in my opinion. It is a big hack just to extent the valid range by one bit. The far better solution if you want random bits in an int64
is to call random.next
and cast the result to an int64
.