[$argument, null], $argument <= 0xFF => [CBORObject::LENGTH_1_BYTE, chr($argument)], $argument <= 0xFFFF => [CBORObject::LENGTH_2_BYTES, pack('n', $argument)], $argument <= 0xFFFFFFFF => [CBORObject::LENGTH_4_BYTES, pack('N', $argument)], default => [CBORObject::LENGTH_8_BYTES, pack('J', $argument)], }; } /** * @return array{int, null|string} the additional information and its payload */ private static function payloadForBigInteger(BigInteger $argument): array { if ($argument->isLessThanOrEqualTo(BigInteger::of(PHP_INT_MAX))) { return self::payloadForInt($argument->toInt()); } return [CBORObject::LENGTH_8_BYTES, self::hex2bin(str_pad($argument->toBase(16), 16, '0', STR_PAD_LEFT))]; } /** * The argument carried by a decoded head. * * A CBOR argument is unsigned, so a negative result cannot be one: it reports that the argument sits above * PHP_INT_MAX and has no PHP integer representation, and the caller shall fall back to brick/math. */ private static function argumentFromPayload(string $data): int { $length = strlen($data); if ($length > 8) { return -1; } $argument = 0; for ($i = 0; $i < $length; ++$i) { $argument = ($argument << 8) | ord($data[$i]); } // Only the eighth byte can carry the argument past PHP_INT_MAX, where the shift wraps it into the sign bit. return $argument; } private static function hex2bin(string $data): string { $result = hex2bin($data); if ($result === false) { throw new InvalidArgumentException('Unable to convert the data'); } return $result; } }