Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix error in randomInt with large Ints #58

Merged
merged 2 commits into from
Oct 28, 2016
Merged

Fix error in randomInt with large Ints #58

merged 2 commits into from
Oct 28, 2016

Conversation

moogle19
Copy link
Contributor

The initialisation of the UInt32 in randomInt failed, when max - min + 1 was bigger than UInt32.max.
This can happen because Int is a Int64 on 64-bit systems.

I replaced arc4random_uniform with arc4random_buf which just fills the Int with random bits.

To transform the random number to a positive one, I used & Int.max to set the first bit to 0 (which is faster than abs())

randomInt crashed with a runtime error when the difference between the
min and max value was bigger than UInt32.
@moogle19
Copy link
Contributor Author

The second commit adds a check for the range between max and min. When this is bigger than Int.max, then max - min fails (because it gets too big).
I simply check if max is bigger than 0 and if max - Int.max is bigger than min. Then we don't need to cap the random number.

@vadymmarkov vadymmarkov merged commit 192de94 into vadymmarkov:master Oct 28, 2016
@vadymmarkov
Copy link
Owner

@moogle19 Thanks 👍

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.

None yet

2 participants