Skip to content

Commit

Permalink
random: Optimize Randomizer::getBytesFromString() (#14894)
Browse files Browse the repository at this point in the history
Co-authored-by: Tim Düsterhus <tim@bastelstu.be>
  • Loading branch information
SakiTakamachi and TimWolla committed Jul 20, 2024
1 parent 68ae477 commit 1fc2ddc
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion ext/random/randomizer.c
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,8 @@ PHP_METHOD(Random_Randomizer, getBytesFromString)
mask |= mask >> 1;
mask |= mask >> 2;
mask |= mask >> 4;
// Expand the lowest byte into all bytes.
mask *= 0x0101010101010101;

int failures = 0;
while (total_size < length) {
Expand All @@ -440,8 +442,10 @@ PHP_METHOD(Random_Randomizer, getBytesFromString)
RETURN_THROWS();
}

uint64_t offsets = result.result & mask;
for (size_t i = 0; i < result.size; i++) {
uint64_t offset = (result.result >> (i * 8)) & mask;
uint64_t offset = offsets & 0xff;
offsets >>= 8;

if (offset > max_offset) {
if (++failures > PHP_RANDOM_RANGE_ATTEMPTS) {
Expand Down

0 comments on commit 1fc2ddc

Please sign in to comment.