65 lines
2.1 KiB
PHP
65 lines
2.1 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
require_once __DIR__ . '/../../backend/php/NiroRawSnappy.php';
|
|
|
|
function checkSnappy(bool $condition, string $message): void
|
|
{
|
|
if (!$condition) {
|
|
throw new RuntimeException($message);
|
|
}
|
|
}
|
|
|
|
/** Independent literal-only reader for synthetic encoder tests. */
|
|
function readLiteralSnappy(string $encoded): string
|
|
{
|
|
$position = 0;
|
|
$length = 0;
|
|
$shift = 0;
|
|
do {
|
|
checkSnappy($position < strlen($encoded) && $shift <= 28, 'invalid varint');
|
|
$byte = ord($encoded[$position++]);
|
|
$length |= ($byte & 0x7f) << $shift;
|
|
$shift += 7;
|
|
} while (($byte & 0x80) !== 0);
|
|
|
|
$output = '';
|
|
while ($position < strlen($encoded)) {
|
|
$tag = ord($encoded[$position++]);
|
|
checkSnappy(($tag & 3) === 0, 'non-literal tag');
|
|
$size = $tag >> 2;
|
|
if ($size >= 60) {
|
|
$count = $size - 59;
|
|
checkSnappy($position + $count <= strlen($encoded), 'truncated size');
|
|
$size = 0;
|
|
for ($i = 0; $i < $count; ++$i) {
|
|
$size |= ord($encoded[$position++]) << ($i * 8);
|
|
}
|
|
}
|
|
++$size;
|
|
checkSnappy($position + $size <= strlen($encoded), 'truncated literal');
|
|
$output .= substr($encoded, $position, $size);
|
|
$position += $size;
|
|
}
|
|
checkSnappy(strlen($output) === $length, 'uncompressed length mismatch');
|
|
return $output;
|
|
}
|
|
|
|
$cases = ['', 'a', "synthetic\0payload"];
|
|
foreach ([60, 61, 255, 256, 65535, 65536, 65537, 131073] as $length) {
|
|
$cases[] = str_repeat('x', $length);
|
|
}
|
|
foreach ($cases as $plain) {
|
|
$encoded = NiroRawSnappy::encodeLiteral($plain);
|
|
checkSnappy(readLiteralSnappy($encoded) === $plain, 'round trip failed');
|
|
checkSnappy($encoded === NiroRawSnappy::encodeLiteral($plain), 'not deterministic');
|
|
}
|
|
$rejected = false;
|
|
try {
|
|
NiroRawSnappy::encodeLiteral(str_repeat('x', 8 * 1024 * 1024 + 1));
|
|
} catch (InvalidArgumentException $expected) {
|
|
$rejected = true;
|
|
}
|
|
checkSnappy($rejected, 'oversized input was accepted');
|
|
echo 'NiroRawSnappyTest passed cases=' . count($cases) . PHP_EOL;
|