Skip to content

random: Optimize Randomizer::getBytesFromString() #14894

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

Merged
merged 3 commits into from
Jul 20, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Improve clarity of the mask expansion
  • Loading branch information
TimWolla authored Jul 20, 2024
commit 2fd607f96f615eac4a462ede37769ae12152f35a
6 changes: 3 additions & 3 deletions ext/random/randomizer.c
Original file line number Diff line number Diff line change
Expand Up @@ -431,9 +431,9 @@ PHP_METHOD(Random_Randomizer, getBytesFromString)
mask |= mask >> 1;
mask |= mask >> 2;
mask |= mask >> 4;
// Expand the lowest byte into all bytes.
mask *= 0x0101010101010101;

/* Example: if mask is 0xAB, will be 0xABABABABABABABAB */
uint64_t mask_repeat = (~((uint64_t) 0) / 0xff) * mask;
int failures = 0;
while (total_size < length) {
php_random_result result = engine.algo->generate(engine.state);
Expand All @@ -442,7 +442,7 @@ PHP_METHOD(Random_Randomizer, getBytesFromString)
RETURN_THROWS();
}

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