@@ -270,6 +270,43 @@ PHP_METHOD(Random_Randomizer, getInt)
270
270
}
271
271
/* }}} */
272
272
273
+ static zend_always_inline char * bulk_convert_generated_result_to_char_32 (char * ptr , uint64_t result , size_t * to_read )
274
+ {
275
+ if (* to_read >= sizeof (uint32_t )) {
276
+ uint32_t tmp = (uint32_t ) result ;
277
+ #ifdef WORDS_BIGENDIAN
278
+ tmp = RANDOM_BSWAP32 (tmp );
279
+ #endif
280
+ memcpy (ptr , & tmp , sizeof (uint32_t ));
281
+ ptr += sizeof (uint32_t );
282
+ * to_read -= sizeof (uint32_t );
283
+ } else {
284
+ while (* to_read > 0 ) {
285
+ * ptr ++ = result & 0xff ;
286
+ result >>= 8 ;
287
+ * to_read -= 1 ;
288
+ }
289
+ }
290
+
291
+ return ptr ;
292
+ }
293
+
294
+ static zend_always_inline char * bulk_convert_generated_result_to_char_64 (char * ptr , uint64_t result , size_t * to_read )
295
+ {
296
+ if (* to_read >= sizeof (uint64_t )) {
297
+ #ifdef WORDS_BIGENDIAN
298
+ result = RANDOM_BSWAP64 (result );
299
+ #endif
300
+ memcpy (ptr , & result , sizeof (uint64_t ));
301
+ ptr += sizeof (uint64_t );
302
+ * to_read -= sizeof (uint64_t );
303
+ } else {
304
+ ptr = bulk_convert_generated_result_to_char_32 (ptr , result , to_read );
305
+ }
306
+
307
+ return ptr ;
308
+ }
309
+
273
310
/* {{{ Generate random bytes string in ordered length */
274
311
PHP_METHOD (Random_Randomizer , getBytes )
275
312
{
@@ -278,7 +315,6 @@ PHP_METHOD(Random_Randomizer, getBytes)
278
315
279
316
zend_string * retval ;
280
317
zend_long user_length ;
281
- size_t total_size = 0 ;
282
318
283
319
ZEND_PARSE_PARAMETERS_START (1 , 1 )
284
320
Z_PARAM_LONG (user_length )
@@ -291,17 +327,28 @@ PHP_METHOD(Random_Randomizer, getBytes)
291
327
292
328
size_t length = (size_t )user_length ;
293
329
retval = zend_string_alloc (length , 0 );
330
+ char * rptr = ZSTR_VAL (retval );
294
331
295
- while (total_size < length ) {
332
+ size_t to_read = length ;
333
+ while (to_read > 0 ) {
296
334
php_random_result result = engine .algo -> generate (engine .state );
297
335
if (EG (exception )) {
298
336
zend_string_free (retval );
299
337
RETURN_THROWS ();
300
338
}
301
- for (size_t i = 0 ; i < result .size ; i ++ ) {
302
- ZSTR_VAL (retval )[total_size ++ ] = (result .result >> (i * 8 )) & 0xff ;
303
- if (total_size >= length ) {
304
- break ;
339
+ if (EXPECTED (result .size == sizeof (uint64_t ))) {
340
+ rptr = bulk_convert_generated_result_to_char_64 (rptr , result .result , & to_read );
341
+ } else if (EXPECTED (result .size == sizeof (uint32_t ))){
342
+ rptr = bulk_convert_generated_result_to_char_32 (rptr , result .result , & to_read );
343
+ } else {
344
+ uint64_t tmp_ret = result .result ;
345
+ for (size_t i = 0 ; i < result .size ; i ++ ) {
346
+ * rptr ++ = tmp_ret & 0xff ;
347
+ tmp_ret >>= 8 ;
348
+ to_read -- ;
349
+ if (to_read == 0 ) {
350
+ break ;
351
+ }
305
352
}
306
353
}
307
354
}
0 commit comments