forked from NetherGamesMC/libproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MultiCompressor.php
73 lines (57 loc) · 1.98 KB
/
MultiCompressor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
declare(strict_types=1);
namespace libproxy;
use ErrorException;
use pocketmine\network\mcpe\compression\Compressor;
use pocketmine\network\mcpe\compression\DecompressionException;
use pocketmine\network\mcpe\compression\ZlibCompressor;
use pocketmine\utils\BinaryDataException;
use pocketmine\utils\BinaryStream;
use pocketmine\utils\SingletonTrait;
use function zstd_uncompress;
class MultiCompressor implements Compressor
{
public const METHOD_ZLIB = 0x00;
public const METHOD_ZSTD = 0x01;
/** @var ZlibCompressor */
private ZlibCompressor $zlibCompressor;
use SingletonTrait;
public function __construct()
{
$this->zlibCompressor = ZlibCompressor::getInstance();
}
public function getCompressionThreshold(): ?int
{
return $this->zlibCompressor->getCompressionThreshold();
}
public function decompress(string $payload): string
{
$stream = new BinaryStream($payload);
try {
$method = $stream->getByte();
try {
$result = match ($method) {
self::METHOD_ZLIB => $this->zlibCompressor->decompress($stream->getRemaining()),
self::METHOD_ZSTD => zstd_uncompress($stream->getRemaining()),
default => throw new DecompressionException("Decompression method not found"),
};
} catch (ErrorException $exception) {
throw new DecompressionException('Failed to decompress data', 0, $exception);
}
} catch (BinaryDataException $exception) {
throw new DecompressionException("Decompression method is invalid");
}
if ($result === false) {
throw new DecompressionException("Failed to decompress data");
}
return $result;
}
/**
* @param string $payload
* @return string
*/
public function compress(string $payload): string
{
return $this->zlibCompressor->compress($payload);
}
}