Skip to content

Commit e96075c

Browse files
committed
Loop optimization
1 parent 07de452 commit e96075c

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

ext/random/randomizer.c

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,6 @@ PHP_METHOD(Random_Randomizer, getBytes)
278278

279279
zend_string *retval;
280280
zend_long user_length;
281-
size_t total_size = 0;
282281

283282
ZEND_PARSE_PARAMETERS_START(1, 1)
284283
Z_PARAM_LONG(user_length)
@@ -293,32 +292,34 @@ PHP_METHOD(Random_Randomizer, getBytes)
293292
retval = zend_string_alloc(length, 0);
294293
char *rptr = ZSTR_VAL(retval);
295294

296-
while (total_size < length) {
295+
size_t to_read = length;
296+
while (to_read > 0) {
297297
php_random_result result = engine.algo->generate(engine.state);
298298
if (EG(exception)) {
299299
zend_string_free(retval);
300300
RETURN_THROWS();
301301
}
302302
uint64_t tmp_ret = result.result;
303-
if (length - total_size >= sizeof(uint64_t) && result.size == sizeof(uint64_t)) {
303+
if (to_read >= sizeof(uint64_t) && result.size == sizeof(uint64_t)) {
304304
#ifdef WORDS_BIGENDIAN
305305
tmp_ret = RANDOM_BSWAP64(tmp_ret);
306306
#endif
307307
memcpy(rptr, &tmp_ret, sizeof(uint64_t));
308-
total_size += sizeof(uint64_t);
308+
to_read -= sizeof(uint64_t);
309309
rptr += sizeof(uint64_t);
310310
} else {
311311
for (size_t i = 0; i < result.size; i++) {
312-
rptr[total_size++] = tmp_ret & 0xff;
312+
*rptr++ = tmp_ret & 0xff;
313313
tmp_ret >>= 8;
314-
if (total_size >= length) {
314+
to_read--;
315+
if (to_read == 0) {
315316
break;
316317
}
317318
}
318319
}
319320
}
320321

321-
rptr[length] = '\0';
322+
*rptr = '\0';
322323
RETURN_STR(retval);
323324
}
324325
/* }}} */

0 commit comments

Comments
 (0)