From 1b543b2c16c5b8216f409c64d11554d9d158491f Mon Sep 17 00:00:00 2001 From: "Dylan K. Taylor" Date: Sat, 26 Nov 2016 15:07:27 +0000 Subject: [PATCH] Improved varint write performance (#126) --- src/pocketmine/utils/Binary.php | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/src/pocketmine/utils/Binary.php b/src/pocketmine/utils/Binary.php index 290c69ebf..e3a7cd528 100644 --- a/src/pocketmine/utils/Binary.php +++ b/src/pocketmine/utils/Binary.php @@ -468,23 +468,19 @@ class Binary{ return self::writeUnsignedVarInt(($v << 1) ^ ($v >> (PHP_INT_SIZE === 8 ? 63 : 31))); } - public static function writeUnsignedVarInt($v){ + public static function writeUnsignedVarInt($value){ $buf = ""; - $loops = 0; - do{ - if($loops > 9){ - throw new \InvalidArgumentException("Varint cannot be longer than 10 bytes!"); //for safety reasons + for($i = 0; $i < 10; ++$i){ + if(($value >> 7) !== 0){ + $buf .= chr($value | 0x80); //Let chr() take the last byte of this, it's faster than adding another & 0x7f. + }else{ + $buf .= chr($value & 0x7f); + return $buf; } - $w = $v & 0x7f; - if(($v >> 7) !== 0){ - $w = $v | 0x80; - } - $buf .= self::writeByte($w); - $v = (($v >> 7) & (PHP_INT_MAX >> 6)); //PHP really needs a logical right-shift operator - ++$loops; - }while($v); - return $buf; + $value = (($value >> 7) & (PHP_INT_MAX >> 6)); //PHP really needs a logical right-shift operator + } + + throw new \InvalidArgumentException("Value too large to be encoded as a varint"); } - }