PocketMine-MP 5.23.3 git-f7687af337d001ddbcc47b8e773f014a33faa662
Loading...
Searching...
No Matches
ZlibCompressor.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\network\mcpe\compression;
25
27use pocketmine\utils\SingletonTrait;
29use function function_exists;
30use function libdeflate_deflate_compress;
31use function strlen;
32use function zlib_decode;
33use function zlib_encode;
34use const ZLIB_ENCODING_RAW;
35
36final class ZlibCompressor implements Compressor{
37 use SingletonTrait;
38
39 public const DEFAULT_LEVEL = 7;
40 public const DEFAULT_THRESHOLD = 256;
41 public const DEFAULT_MAX_DECOMPRESSION_SIZE = 8 * 1024 * 1024;
42
46 private static function make() : self{
47 return new self(self::DEFAULT_LEVEL, self::DEFAULT_THRESHOLD, self::DEFAULT_MAX_DECOMPRESSION_SIZE);
48 }
49
50 public function __construct(
51 private int $level,
52 private ?int $minCompressionSize,
53 private int $maxDecompressionSize
54 ){}
55
56 public function getCompressionThreshold() : ?int{
57 return $this->minCompressionSize;
58 }
59
63 public function decompress(string $payload) : string{
64 $result = @zlib_decode($payload, $this->maxDecompressionSize);
65 if($result === false){
66 throw new DecompressionException("Failed to decompress data");
67 }
68 return $result;
69 }
70
71 public function compress(string $payload) : string{
72 $compressible = $this->minCompressionSize !== null && strlen($payload) >= $this->minCompressionSize;
73 $level = $compressible ? $this->level : 0;
74
75 return function_exists('libdeflate_deflate_compress') ?
76 libdeflate_deflate_compress($payload, $level) :
77 Utils::assumeNotFalse(zlib_encode($payload, ZLIB_ENCODING_RAW, $level), "ZLIB compression failed");
78 }
79
80 public function getNetworkId() : int{
81 return CompressionAlgorithm::ZLIB;
82 }
83}