PacketBatch is now immutable

This commit is contained in:
Dylan K. Taylor 2020-07-22 15:37:06 +01:00
parent 798efc370c
commit 8402465fd2

View File

@ -30,18 +30,11 @@ use pocketmine\utils\BinaryDataException;
class PacketBatch{ class PacketBatch{
/** @var PacketSerializer */ /** @var string */
private $serializer; private $buffer;
public function __construct(?string $buffer = null){ public function __construct(string $buffer){
$this->serializer = new PacketSerializer($buffer ?? ""); $this->buffer = $buffer;
}
/**
* @throws BinaryDataException
*/
public function getPacket(PacketPool $packetPool) : Packet{
return $packetPool->getPacket($this->serializer->getString());
} }
/** /**
@ -49,10 +42,11 @@ class PacketBatch{
* @phpstan-return \Generator<int, Packet, void, void> * @phpstan-return \Generator<int, Packet, void, void>
*/ */
public function getPackets(PacketPool $packetPool, int $max) : \Generator{ public function getPackets(PacketPool $packetPool, int $max) : \Generator{
for($c = 0; $c < $max and !$this->serializer->feof(); ++$c){ $serializer = new PacketSerializer($this->buffer);
yield $c => $packetPool->getPacket($this->serializer->getString()); for($c = 0; $c < $max and !$serializer->feof(); ++$c){
yield $c => $packetPool->getPacket($serializer->getString());
} }
if(!$this->serializer->feof()){ if(!$serializer->feof()){
throw new PacketDecodeException("Reached limit of $max packets in a single batch"); throw new PacketDecodeException("Reached limit of $max packets in a single batch");
} }
} }
@ -65,19 +59,15 @@ class PacketBatch{
* @return PacketBatch * @return PacketBatch
*/ */
public static function fromPackets(Packet ...$packets) : self{ public static function fromPackets(Packet ...$packets) : self{
$result = new self(); $serializer = new PacketSerializer();
foreach($packets as $packet){ foreach($packets as $packet){
$packet->encode(); $packet->encode();
$result->serializer->putString($packet->getSerializer()->getBuffer()); $serializer->putString($packet->getSerializer()->getBuffer());
} }
return $result; return new self($serializer->getBuffer());
} }
public function getBuffer() : string{ public function getBuffer() : string{
return $this->serializer->getBuffer(); return $this->buffer;
}
public function feof() : bool{
return $this->serializer->feof();
} }
} }