Debian Codegraph @

test/Common/ReedSolomonCodecTest.php

raw
1 <?php
2 declare(strict_types = 1);
3
4 namespace BaconQrCodeTest\Common;
5
6 use BaconQrCode\Common\ReedSolomonCodec;
7 use PHPUnit\Framework\Attributes\DataProvider;
8 use PHPUnit\Framework\TestCase;
9 use SplFixedArray;
10
11 class ReedSolomonCodecTest extends TestCase
12 {
13 public static function tabs() : array
14 {
15 return [
16 [2, 0x7, 1, 1, 1],
17 [3, 0xb, 1, 1, 2],
18 [4, 0x13, 1, 1, 4],
19 [5, 0x25, 1, 1, 6],
20 [6, 0x43, 1, 1, 8],
21 [7, 0x89, 1, 1, 10],
22 [8, 0x11d, 1, 1, 32],
23 ];
24 }
25
26 #[DataProvider('tabs')]
27 public function testCodec(int $symbolSize, int $generatorPoly, int $firstRoot, int $primitive, int $numRoots) : void
28 {
29 mt_srand(0xdeadbeef);
30
31 $blockSize = (1 << $symbolSize) - 1;
32 $dataSize = $blockSize - $numRoots;
33 $codec = new ReedSolomonCodec($symbolSize, $generatorPoly, $firstRoot, $primitive, $numRoots, 0);
34
35 for ($errors = 0; $errors <= $numRoots / 2; ++$errors) {
36 // Load block with random data and encode
37 $block = SplFixedArray::fromArray(array_fill(0, $blockSize, 0), false);
38
39 for ($i = 0; $i < $dataSize; ++$i) {
40 $block[$i] = mt_rand(0, $blockSize);
41 }
42
43 // Make temporary copy
44 $tBlock = clone $block;
45 $parity = SplFixedArray::fromArray(array_fill(0, $numRoots, 0), false);
46 $errorLocations = SplFixedArray::fromArray(array_fill(0, $blockSize, 0), false);
47 $erasures = [];
48
49 // Create parity
50 $codec->encode($block, $parity);
51
52 // Copy parity into test blocks
53 for ($i = 0; $i < $numRoots; ++$i) {
54 $block[$i + $dataSize] = $parity[$i];
55 $tBlock[$i + $dataSize] = $parity[$i];
56 }
57
58 // Seed with errors
59 for ($i = 0; $i < $errors; ++$i) {
60 $errorValue = mt_rand(1, $blockSize);
61
62 do {
63 $errorLocation = mt_rand(0, $blockSize - 1);
64 } while (0 !== $errorLocations[$errorLocation]);
65
66 $errorLocations[$errorLocation] = 1;
67
68 if (mt_rand(0, 1)) {
69 $erasures[] = $errorLocation;
70 }
71
72 $tBlock[$errorLocation] ^= $errorValue;
73 }
74
75 $erasures = SplFixedArray::fromArray($erasures, false);
76
77 // Decode the errored block
78 $foundErrors = $codec->decode($tBlock, $erasures);
79
80 if ($errors > 0 && null === $foundErrors) {
81 $this->assertSame($block, $tBlock, 'Decoder failed to correct errors');
82 }
83
84 $this->assertSame($errors, $foundErrors, 'Found errors do not equal expected errors');
85
86 for ($i = 0; $i < $foundErrors; ++$i) {
87 if (0 === $errorLocations[$erasures[$i]]) {
88 $this->fail(sprintf('Decoder indicates error in location %d without error', $erasures[$i]));
89 }
90 }
91
92 $this->assertEquals($block, $tBlock, 'Decoder did not correct errors');
93 }
94 }
95 }