xref: /PHP-8.2/ext/random/tests/engines.inc (revision f7d426cc)
1<?php
2
3namespace Random\Engine\Test;
4
5use Random\Engine;
6
7final 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
28final 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
40final 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?>
75