PocketMine-MP 5.35.1 git-e32e836dad793a3a3c8ddd8927c00e112b1e576a
Loading...
Searching...
No Matches
PacketBatch.php
1<?php
2
3/*
4 * This file is part of BedrockProtocol.
5 * Copyright (C) 2014-2022 PocketMine Team <https://github.com/pmmp/BedrockProtocol>
6 *
7 * BedrockProtocol is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Lesser General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 */
12
13declare(strict_types=1);
14
15namespace pocketmine\network\mcpe\protocol\serializer;
16
17use pmmp\encoding\ByteBufferReader;
18use pmmp\encoding\ByteBufferWriter;
19use pmmp\encoding\DataDecodeException;
20use pmmp\encoding\VarInt;
24use function strlen;
25
27
28 private function __construct(){
29 //NOOP
30 }
31
36 final public static function decodeRaw(ByteBufferReader $in) : \Generator{
37 $c = 0;
38 while($in->getUnreadLength() > 0){
39 try{
40 $length = VarInt::readUnsignedInt($in);
41 $buffer = $in->readByteArray($length);
42 }catch(DataDecodeException $e){
43 throw new PacketDecodeException("Error decoding packet $c in batch: " . $e->getMessage(), 0, $e);
44 }
45 yield $buffer;
46 $c++;
47 }
48 }
49
54 final public static function encodeRaw(ByteBufferWriter $out, array $packets) : void{
55 foreach($packets as $packet){
56 VarInt::writeUnsignedInt($out, strlen($packet));
57 $out->writeByteArray($packet);
58 }
59 }
60
65 final public static function decodePackets(ByteBufferReader $in, PacketPool $packetPool) : \Generator{
66 $c = 0;
67 foreach(self::decodeRaw($in) as $packetBuffer){
68 $packet = $packetPool->getPacket($packetBuffer);
69 if($packet !== null){
70 try{
71 //TODO: this could use a view with a start and end offset to avoid extra string allocations
72 //currently ByteBufferReader doesn't support this
73 $packet->decode(new ByteBufferReader($packetBuffer));
74 }catch(PacketDecodeException $e){
75 throw new PacketDecodeException("Error decoding packet $c in batch: " . $e->getMessage(), 0, $e);
76 }
77 yield $packet;
78 }else{
79 throw new PacketDecodeException("Unknown packet $c in batch");
80 }
81 $c++;
82 }
83 }
84
89 final public static function encodePackets(ByteBufferWriter $out, array $packets) : void{
90 foreach($packets as $packet){
91 $serializer = new ByteBufferWriter();
92 $packet->encode($serializer);
93 //this may require a copy, so don't call it twice
94 $packetBuffer = $serializer->getData();
95 VarInt::writeUnsignedInt($out, strlen($packetBuffer));
96 $out->writeByteArray($packetBuffer);
97 }
98 }
99}
static decodePackets(ByteBufferReader $in, PacketPool $packetPool)
static encodePackets(ByteBufferWriter $out, array $packets)
static encodeRaw(ByteBufferWriter $out, array $packets)