8 * 1024 * 1024) { throw new InvalidArgumentException('Snappy input exceeds limit'); } $encoded = self::varint($length); $offset = 0; while ($offset < $length) { $chunkLength = min(65536, $length - $offset); $encoded .= self::literalTag($chunkLength); $encoded .= substr($plain, $offset, $chunkLength); $offset += $chunkLength; } return $encoded; } private static function varint(int $value): string { $encoded = ''; do { $byte = $value & 0x7f; $value >>= 7; if ($value !== 0) { $byte |= 0x80; } $encoded .= chr($byte); } while ($value !== 0); return $encoded; } private static function literalTag(int $length): string { if ($length < 1 || $length > 65536) { throw new InvalidArgumentException('Invalid Snappy literal length'); } if ($length <= 60) { return chr(($length - 1) << 2); } $value = $length - 1; $bytes = ''; while ($value !== 0) { $bytes .= chr($value & 0xff); $value >>= 8; } return chr((59 + strlen($bytes)) << 2) . $bytes; } }