Improved varint write performance (#126)

This commit is contained in:
Dylan K. Taylor 2016-11-26 15:07:27 +00:00 committed by GitHub
parent 763ef7f937
commit 1b543b2c16

View File

@ -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");
}
}