Skip to content

fix(randx): use upper bound in Between - #512

Merged
adamdecaf merged 1 commit into
moov-io:masterfrom
SashaMIT:fix/randx-between-upper-bound
Aug 12, 2026
Merged

fix(randx): use upper bound in Between#512
adamdecaf merged 1 commit into
moov-io:masterfrom
SashaMIT:fix/randx-between-upper-bound

Conversation

@SashaMIT

Copy link
Copy Markdown
Contributor

Problem

randx.Between(lower, upper) never reads upper. It passes lower as the exclusive maximum to crypto/rand.Int and then adds lower to the result, so the returned value falls in [lower, 2*lower) instead of [lower, upper).

The existing test only passes because [100, 200) loosely overlaps the asserted range of [100, 250].

Additionally, when lower == 0, crypto/rand.Int is called with a maximum of 0 and panics, so any caller doing Between(0, n) crashes the process.

Fix

  • Compute the range as upper - lower, draw from [0, upper-lower), and shift the result by lower, yielding a uniform value in [lower, upper).
  • Return an explicit error when upper <= lower instead of panicking inside crypto/rand. This matches the package's existing style where Between returns errors and Must panics on them.

Tests

  • TestBetween and TestMust now assert both bounds tightly over 1000 samples (lower <= n < upper).
  • TestBetween_ZeroLower covers lower == 0, which previously panicked.
  • TestBetween_InvalidBounds and TestMust_Panics cover the upper <= lower error path.

Verified that the new tests fail against the old implementation (the zero-lower test panics in crypto/rand.Int).

Made with Cursor

Between passed lower as the exclusive maximum to crypto/rand.Int and
never read upper, so it returned values in [lower, 2*lower) instead of
[lower, upper). With lower == 0 the call panics in crypto/rand.

Compute the range as upper-lower and shift the result by lower, and
return an error when upper <= lower. Extend tests to assert both
bounds tightly over 1000 samples, cover lower == 0, and cover invalid
bounds.
@adamdecaf
adamdecaf merged commit 15a7bb1 into moov-io:master Aug 12, 2026
14 checks passed
@SashaMIT

Copy link
Copy Markdown
Contributor Author

Thanks for the merge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants