Last active
October 10, 2020 19:24
-
-
Save truemedian/2f8fe78613a92288a27f5f48ceeba4e0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local uv = require 'uv' | |
local bit = require 'bit' | |
-- Generates cryptographically secure integers in the range [min, max). | |
function math.uvrandom(min, max) | |
assert(min, 'expected lower bound') | |
assert(max, 'expected upper bound') | |
assert(max > min, 'expected max > min') | |
local range = max - min | |
local log256range = math.ceil(math.log(range, 256)) -- number of bytes required to store range | |
local bytes = uv.random(log256range * 2) -- get double the bytes required so we can distribute evenly with modulo | |
local random = 0 | |
for i = 1, #bytes do | |
random = bit.lshift(random, 8) + bytes:byte(i, i) | |
end | |
return random % range + min | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment