Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
--TEST--
Random: Randomizer: shuffleArray(): Engine throwing on an array with holes
--FILE--
<?php

use Random\Engine;
use Random\Randomizer;

final class ThrowingEngine implements Engine
{
public function __construct(private int $calls) {}

public function generate(): string
{
if ($this->calls-- <= 0) {
throw new Exception('Error');
}

return "\x01\x00\x00\x00\x00\x00\x00\x00";
}
}

foreach ([0, 1] as $calls) {
$array = [new stdClass, new stdClass, new stdClass, new stdClass];
unset($array[1]);

try {
(new Randomizer(new ThrowingEngine($calls)))->shuffleArray($array);
} catch (Exception $e) {
echo $e->getMessage(), PHP_EOL;
}

var_dump($array);
}

?>
--EXPECTF--
Error
array(3) {
[0]=>
object(stdClass)#%d (0) {
}
[2]=>
object(stdClass)#%d (0) {
}
[3]=>
object(stdClass)#%d (0) {
}
}
Error
array(3) {
[0]=>
object(stdClass)#%d (0) {
}
[2]=>
object(stdClass)#%d (0) {
}
[3]=>
object(stdClass)#%d (0) {
}
}
10 changes: 7 additions & 3 deletions ext/standard/array.c
Original file line number Diff line number Diff line change
Expand Up @@ -3302,6 +3302,10 @@ PHPAPI bool php_array_data_shuffle(php_random_algo_with_state engine, zval *arra
j++;
}
}
/* Truncate the stale slots left by compaction before the engine can throw. */
hash->nNumUsed = n_elems;
hash->nInternalPointer = 0;
hash->nNextFreeElement = n_elems;
while (--n_left) {
rnd_idx = algo->range(state, 0, n_left);
if (EG(exception)) {
Expand Down Expand Up @@ -3330,6 +3334,9 @@ PHPAPI bool php_array_data_shuffle(php_random_algo_with_state engine, zval *arra
j++;
}
}
hash->nNumUsed = n_elems;
hash->nInternalPointer = 0;
hash->nNextFreeElement = n_elems;
while (--n_left) {
rnd_idx = algo->range(state, 0, n_left);
if (EG(exception)) {
Expand All @@ -3343,9 +3350,6 @@ PHPAPI bool php_array_data_shuffle(php_random_algo_with_state engine, zval *arra
}
}
}
hash->nNumUsed = n_elems;
hash->nInternalPointer = 0;
hash->nNextFreeElement = n_elems;

return true;
}
Expand Down
Loading