Skip to content

Instantly share code, notes, and snippets.

@stormbrew
Last active August 29, 2015 14:03
Show Gist options
  • Save stormbrew/ccf533c1263e02d0bbf7 to your computer and use it in GitHub Desktop.
Save stormbrew/ccf533c1263e02d0bbf7 to your computer and use it in GitHub Desktop.
Twitter algorithmic code review
<?php
function getRandomRangedBytes($length, $max) {
// inspired by: http://stackoverflow.com/a/2999130/3803650
// This safely generates a series of random bytes that are all within
// the range [0,$max) with an even distribution
$divisor = intval(255/$max);
$results = array();
// This looks like it could be a loop that never terminates,
// but that would only be true if openssl was not returning us
// a uniform distribution of bytes, in which case we probably have
// bigger problems.
while (count($results) < $length) {
// generate bytes
$input = unpack("C*", openssl_random_pseudo_bytes($length - count($results)));
foreach ($input as $byte) {
// reject any byte that's >= to $max as it would
// skew the distribution.
$val = intval($byte / $divisor);
if ($val < $max) {
$results[] = $val;
}
}
}
return $results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment