Skip to content

Commit 4d35da2

Browse files
committed
Add engines.inc for ext/random tests
1 parent 4fb3052 commit 4d35da2

File tree

2 files changed

+77
-12
lines changed

2 files changed

+77
-12
lines changed

ext/random/tests/02_engine/user_compatibility.phpt

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,10 @@ Random: Engine: Native engines can be wrapped without changing their sequence
66
use Random\Engine;
77
use Random\Engine\Mt19937;
88
use Random\Engine\PcgOneseq128XslRr64;
9+
use Random\Engine\Test\TestWrapperEngine;
910
use Random\Engine\Xoshiro256StarStar;
1011

11-
class WrapperEngine implements Engine
12-
{
13-
public function __construct(private readonly Engine $engine)
14-
{
15-
}
16-
17-
public function generate(): string
18-
{
19-
return $this->engine->generate();
20-
}
21-
}
12+
include __DIR__ . "/../engines.inc";
2213

2314
$engines = [];
2415
$engines[] = new Mt19937(1234);
@@ -29,7 +20,7 @@ foreach ($engines as $engine) {
2920
echo $engine::class, PHP_EOL;
3021

3122
$native_engine = clone $engine;
32-
$user_engine = new WrapperEngine(clone $engine);
23+
$user_engine = new TestWrapperEngine(clone $engine);
3324

3425
for ($i = 0; $i < 10_000; $i++) {
3526
if ($native_engine->generate() !== $user_engine->generate()) {

ext/random/tests/engines.inc

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
<?php
2+
3+
namespace Random\Engine\Test;
4+
5+
use Random\Engine;
6+
7+
final class TestShaEngine implements Engine
8+
{
9+
private string $state;
10+
11+
public function __construct(?string $state = null)
12+
{
13+
if ($state !== null) {
14+
$this->state = $state;
15+
} else {
16+
$this->state = random_bytes(20);
17+
}
18+
}
19+
20+
public function generate(): string
21+
{
22+
$this->state = sha1($this->state, true);
23+
24+
return substr($this->state, 0, 8);
25+
}
26+
}
27+
28+
final class TestWrapperEngine implements Engine
29+
{
30+
public function __construct(private readonly Engine $engine)
31+
{
32+
}
33+
34+
public function generate(): string
35+
{
36+
return $this->engine->generate();
37+
}
38+
}
39+
40+
final class TestXoshiro128PlusPlusEngine implements Engine
41+
{
42+
public function __construct(
43+
private int $s0,
44+
private int $s1,
45+
private int $s2,
46+
private int $s3
47+
) {
48+
}
49+
50+
private static function rotl($x, $k)
51+
{
52+
return (($x << $k) | ($x >> (32 - $k))) & 0xFFFFFFFF;
53+
}
54+
55+
public function generate(): string
56+
{
57+
$result = (self::rotl(($this->s0 + $this->s3) & 0xFFFFFFFF, 7) + $this->s0) & 0xFFFFFFFF;
58+
59+
$t = ($this->s1 << 9) & 0xFFFFFFFF;
60+
61+
$this->s2 ^= $this->s0;
62+
$this->s3 ^= $this->s1;
63+
$this->s1 ^= $this->s2;
64+
$this->s0 ^= $this->s3;
65+
66+
$this->s2 ^= $t;
67+
68+
$this->s3 = self::rotl($this->s3, 11);
69+
70+
return pack('V', $result);
71+
}
72+
}
73+
74+
?>

0 commit comments

Comments
 (0)