From 6ad999176c319f42e88bf075bbe126ce887ce777 Mon Sep 17 00:00:00 2001 From: Maxim Kerstens Date: Mon, 9 Nov 2026 11:23:53 +0100 Subject: [PATCH 1/3] Add readable JSON flavor and decode both flavors like upstream Add ReadableJson::encode() and ReadableJson::toJson(), matching the upstream skir-client toJson(value, "readable") and toJsonCode(value, "readable") output, including two-space indentation and JavaScript number formatting. DenseJson::decode() and DenseJson::fromJson() now accept both flavors and follow upstream fromJson coercion: unknown enum variants and names decode to UNKNOWN, constant/wrapper shape changes are tolerated, null structs decode to defaults, and invalid strings, bytes and int64 values are rejected. Dense encoding now wraps int32 values, clamps int64, hash64 and timestamp values and writes JSON the way JSON.stringify does. Type traversal is shared by an internal JsonCodec. Expected values in the tests were generated with the upstream skir-client package. --- README.md | 26 +- src/DenseJson.php | 471 +----------------------- src/Exceptions/SkirRuntimeException.php | 5 + src/Internal/JsonCodec.php | 409 ++++++++++++++++++++ src/Internal/JsonFlavor.php | 12 + src/Internal/JsonWriter.php | 165 +++++++++ src/Internal/LargeInteger.php | 170 +++++++++ src/Internal/Numbers.php | 126 +++++++ src/Internal/TypeValues.php | 225 +++++++++++ src/ReadableJson.php | 34 ++ tests/DenseJsonTest.php | 225 +++++------ tests/ReadableJsonTest.php | 162 ++++++++ tests/UpstreamVectors.php | 387 +++++++++++++++++++ 13 files changed, 1820 insertions(+), 597 deletions(-) create mode 100644 src/Internal/JsonCodec.php create mode 100644 src/Internal/JsonFlavor.php create mode 100644 src/Internal/JsonWriter.php create mode 100644 src/Internal/LargeInteger.php create mode 100644 src/Internal/Numbers.php create mode 100644 src/Internal/TypeValues.php create mode 100644 src/ReadableJson.php create mode 100644 tests/ReadableJsonTest.php create mode 100644 tests/UpstreamVectors.php diff --git a/README.md b/README.md index 4915c71..61f106e 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,8 @@ composer require php-skir/runtime ## What it provides -- `DenseJson` for encoding and decoding Skir dense JSON values. +- `DenseJson` for encoding Skir dense JSON values and decoding JSON values of either flavor. +- `ReadableJson` for encoding Skir readable JSON values. - `Type`, `Field`, and `Variant` descriptors for generated DTO metadata. - `EnumValue` for Skir enum constants and wrapper variants. - `MethodDescriptor` for generated SkirRPC method metadata. @@ -46,6 +47,29 @@ $data = DenseJson::fromJson($user, $json); Struct values are encoded as field-number indexed arrays. Removed fields and sparse field numbers are preserved so generated DTOs can stay compatible with existing Skir schemas. +`DenseJson::fromJson()` and `DenseJson::decode()` accept both the dense and the readable flavor, like the upstream Skir runtimes. + +## Readable JSON + +```php +use Skir\Runtime\ReadableJson; + +$json = ReadableJson::toJson($user, [ + 'id' => 1, + 'name' => 'Jane', +]); +// { +// "id": 1, +// "name": "Jane" +// } + +$data = DenseJson::fromJson($user, $json); +``` + +The readable flavor matches upstream `toJsonCode(value, "readable")`: structs become objects keyed by field name with default-valued fields omitted, constant enum variants become lower-case names, wrapper variants become `{"kind": ..., "value": ...}`, timestamps become `{"unix_millis": ..., "formatted": ...}` and bytes become `hex:` strings. Because field names are part of the output, prefer the dense flavor for anything that is persisted. + +`ReadableJson::encode()` returns the JSON-compatible PHP value. A struct whose fields all hold their default value is returned as an empty `stdClass` so it still encodes as `{}`. + ## Current scope This runtime does not register routes, discover procedures, or make HTTP calls. Those concerns belong in the `php-skir/server` and `php-skir/client` packages. diff --git a/src/DenseJson.php b/src/DenseJson.php index 4d12985..9c651dd 100644 --- a/src/DenseJson.php +++ b/src/DenseJson.php @@ -4,23 +4,26 @@ namespace Skir\Runtime; -use DateTimeInterface; use JsonException; use Skir\Runtime\Exceptions\SkirRuntimeException; +use Skir\Runtime\Internal\JsonCodec; +use Skir\Runtime\Internal\JsonFlavor; +use Skir\Runtime\Internal\JsonWriter; final class DenseJson { - private const int MAX_SAFE_JAVASCRIPT_INTEGER = 9_007_199_254_740_991; - public static function toJson(Type $type, mixed $value): string { try { - return json_encode(self::encode($type, $value), JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES); + return JsonWriter::write(self::encode($type, $value)); } catch (JsonException $exception) { throw SkirRuntimeException::invalidDenseJson($exception->getMessage(), $exception); } } + /** + * Accepts both the dense and the readable JSON flavor. + */ public static function fromJson(Type $type, string $json): mixed { try { @@ -34,464 +37,14 @@ public static function fromJson(Type $type, string $json): mixed public static function encode(Type $type, mixed $value): mixed { - return self::encodeValue($type, $value); + return JsonCodec::encode($type, $value, JsonFlavor::Dense); } + /** + * Accepts both the dense and the readable JSON flavor. + */ public static function decode(Type $type, mixed $value): mixed { - return self::decodeValue($type, $value); - } - - private static function encodeValue(Type $type, mixed $value): mixed - { - return match ($type->kind) { - TypeKind::Bool => $value ? 1 : 0, - TypeKind::Int32 => (int) $value, - TypeKind::Int64, TypeKind::Hash64 => self::encodeLargeInteger($value), - TypeKind::Float32, TypeKind::Float64 => self::encodeFloat((float) $value), - TypeKind::Timestamp => self::encodeTimestamp($value), - TypeKind::String => (string) $value, - TypeKind::Bytes => base64_encode((string) $value), - TypeKind::Optional => $value === null ? null : self::encodeValue(self::requireItemType($type), $value), - TypeKind::Array => self::encodeArray($type, $value), - TypeKind::Struct => self::encodeStruct($type, $value), - TypeKind::Enum => self::encodeEnum($type, $value), - }; - } - - private static function decodeValue(Type $type, mixed $value): mixed - { - if ($value === 0) { - return self::decodeZero($type); - } - - return match ($type->kind) { - TypeKind::Bool => (bool) $value, - TypeKind::Int32 => (int) $value, - TypeKind::Int64, TypeKind::Hash64 => $value, - TypeKind::Float32, TypeKind::Float64 => self::decodeFloat($value), - TypeKind::Timestamp => (int) $value, - TypeKind::String => (string) $value, - TypeKind::Bytes => self::decodeBytes($value), - TypeKind::Optional => $value === null ? null : self::decodeValue(self::requireItemType($type), $value), - TypeKind::Array => self::decodeArray($type, $value), - TypeKind::Struct => self::decodeStruct($type, $value), - TypeKind::Enum => self::decodeEnum($type, $value), - }; - } - - private static function encodeLargeInteger(mixed $value): int|string - { - if (is_int($value)) { - return abs($value) <= self::MAX_SAFE_JAVASCRIPT_INTEGER ? $value : (string) $value; - } - - if (is_string($value)) { - return self::isSafeIntegerString($value) ? (int) $value : $value; - } - - throw SkirRuntimeException::invalidValue('Skir int64/hash64 values must be integers or integer strings.'); - } - - private static function encodeFloat(float $value): float|string - { - if (is_nan($value)) { - return 'NaN'; - } - - if ($value === INF) { - return 'Infinity'; - } - - if ($value === -INF) { - return '-Infinity'; - } - - return $value; - } - - private static function decodeFloat(mixed $value): float - { - return match ($value) { - 'NaN' => NAN, - 'Infinity' => INF, - '-Infinity' => -INF, - default => (float) $value, - }; - } - - private static function encodeTimestamp(mixed $value): int - { - if ($value instanceof DateTimeInterface) { - return ((int) $value->format('U')) * 1000 + ((int) $value->format('v')); - } - - return (int) $value; - } - - private static function decodeBytes(mixed $value): string - { - $decoded = base64_decode((string) $value, true); - - if ($decoded === false) { - throw SkirRuntimeException::invalidValue('Skir bytes values must be valid base64 strings.'); - } - - return $decoded; - } - - private static function encodeArray(Type $type, mixed $value): array - { - if (! is_array($value)) { - throw SkirRuntimeException::invalidValue('Skir array values must be PHP arrays.'); - } - - $itemType = self::requireItemType($type); - - return array_map( - fn (mixed $item): mixed => self::encodeValue($itemType, $item), - array_values($value), - ); - } - - private static function decodeArray(Type $type, mixed $value): array - { - if (! is_array($value)) { - throw SkirRuntimeException::invalidValue('Skir array JSON values must be arrays.'); - } - - $itemType = self::requireItemType($type); - - return array_map( - fn (mixed $item): mixed => self::decodeValue($itemType, $item), - array_values($value), - ); - } - - private static function encodeStruct(Type $type, mixed $value): array - { - if (! is_array($value)) { - throw SkirRuntimeException::invalidValue('Skir struct values must be associative arrays.'); - } - - $encodedFields = []; - - foreach ($type->fields as $field) { - $encodedFields[$field->number] = self::encodeField($field, $value); - } - - ksort($encodedFields); - - if ($encodedFields !== []) { - $lastNumber = max(array_keys($encodedFields)); - - for ($number = 0; $number <= $lastNumber; $number++) { - if (! array_key_exists($number, $encodedFields)) { - $encodedFields[$number] = 0; - } - } - - ksort($encodedFields); - } - - while ($encodedFields !== []) { - $lastNumber = array_key_last($encodedFields); - $field = self::fieldWithNumber($type, $lastNumber); - $encodedDefault = $field === null - ? 0 - : self::encodedDefaultForField($field); - - if ($encodedFields[$lastNumber] !== $encodedDefault) { - break; - } - - unset($encodedFields[$lastNumber]); - } - - return array_values($encodedFields); - } - - private static function decodeStruct(Type $type, mixed $value): array - { - if (! is_array($value)) { - throw SkirRuntimeException::invalidValue('Skir struct JSON values must be arrays.'); - } - - $decoded = []; - - foreach ($type->fields as $field) { - if ($field->removed) { - continue; - } - - $fieldValue = array_key_exists($field->number, $value) - ? $value[$field->number] - : self::defaultValue(self::requireFieldType($field)); - - $decoded[$field->name] = array_key_exists($field->number, $value) - ? self::decodeValue(self::requireFieldType($field), $fieldValue) - : $fieldValue; - } - - return $decoded; - } - - private static function encodeField(Field $field, array $value): mixed - { - if ($field->removed) { - return 0; - } - - $fieldType = self::requireFieldType($field); - $fieldValue = array_key_exists($field->name, $value) - ? $value[$field->name] - : self::defaultValue($fieldType); - - return self::encodeValue($fieldType, $fieldValue); - } - - private static function encodedDefaultForField(Field $field): mixed - { - if ($field->removed) { - return 0; - } - - $fieldType = self::requireFieldType($field); - - return self::encodeValue($fieldType, self::defaultValue($fieldType)); - } - - private static function encodeEnum(Type $type, mixed $value): int|array - { - if (! $value instanceof EnumValue) { - throw SkirRuntimeException::invalidValue('Skir enum values must be EnumValue instances.'); - } - - if ($value->name === 'UNKNOWN') { - return 0; - } - - $variant = self::variantWithName($type, $value->name); - - if (! $value->wrapper) { - return $variant->number; - } - - if (! $variant->isWrapper()) { - throw SkirRuntimeException::invalidValue("Skir enum variant [{$value->name}] does not carry a payload."); - } - - return [ - $variant->number, - self::encodeValue($variant->payloadType, $value->value), - ]; - } - - private static function decodeEnum(Type $type, mixed $value): EnumValue - { - if ($value === 0) { - return EnumValue::constant('UNKNOWN'); - } - - if (! is_array($value)) { - return self::decodeScalarEnum($type, $value); - } - - if (count($value) !== 2) { - throw SkirRuntimeException::invalidValue('Skir enum wrapper JSON values must contain exactly a variant number and payload.'); - } - - if (! array_is_list($value)) { - throw SkirRuntimeException::invalidValue('Skir enum wrapper JSON values must contain exactly a variant number and payload.'); - } - - $variantNumber = self::decodeEnumVariantNumber($value[0]); - $variant = self::variantWithNumber($type, $variantNumber); - - if (! $variant->isWrapper()) { - throw SkirRuntimeException::invalidValue("Skir enum variant [{$variant->name}] does not carry a payload."); - } - - return EnumValue::wrapper($variant->name, self::decodeValue($variant->payloadType, $value[1])); - } - - private static function decodeScalarEnum(Type $type, mixed $value): EnumValue - { - $variantNumber = self::decodeEnumVariantNumber($value); - - if ($variantNumber === 0) { - return EnumValue::constant('UNKNOWN'); - } - - $variant = self::variantWithNumber($type, $variantNumber); - - if ($variant->isWrapper()) { - if (! is_int($value)) { - throw SkirRuntimeException::invalidValue("Skir enum wrapper variant [{$variant->name}] must be encoded as a wrapper array."); - } - } - - return EnumValue::constant($variant->name); - } - - private static function decodeEnumVariantNumber(mixed $value): int - { - if (is_int($value)) { - return self::requireSafeEnumVariantNumber($value); - } - - if (is_float($value)) { - if (! is_finite($value)) { - self::throwInvalidEnumVariantNumber(); - } - - if (floor($value) !== $value) { - self::throwInvalidEnumVariantNumber(); - } - - if ($value < -self::MAX_SAFE_JAVASCRIPT_INTEGER) { - self::throwInvalidEnumVariantNumber(); - } - - if ($value > self::MAX_SAFE_JAVASCRIPT_INTEGER) { - self::throwInvalidEnumVariantNumber(); - } - - return (int) $value; - } - - if (is_string($value)) { - if (preg_match('/^-?(0|[1-9]\d*)$/', $value) !== 1) { - self::throwInvalidEnumVariantNumber(); - } - - $variantNumber = (int) $value; - - if ((string) $variantNumber !== $value) { - self::throwInvalidEnumVariantNumber(); - } - - return self::requireSafeEnumVariantNumber($variantNumber); - } - - self::throwInvalidEnumVariantNumber(); - } - - private static function requireSafeEnumVariantNumber(int $value): int - { - if ($value < -self::MAX_SAFE_JAVASCRIPT_INTEGER) { - self::throwInvalidEnumVariantNumber(); - } - - if ($value > self::MAX_SAFE_JAVASCRIPT_INTEGER) { - self::throwInvalidEnumVariantNumber(); - } - - return $value; - } - - private static function throwInvalidEnumVariantNumber(): never - { - throw SkirRuntimeException::invalidValue('Skir enum variant numbers must be safe integer-equivalent values.'); - } - - private static function decodeZero(Type $type): mixed - { - if ($type->kind === TypeKind::Optional) { - return self::decodeValue(self::requireItemType($type), 0); - } - - return self::defaultValue($type); - } - - private static function defaultValue(Type $type): mixed - { - return match ($type->kind) { - TypeKind::Bool => false, - TypeKind::Int32, TypeKind::Int64, TypeKind::Hash64, TypeKind::Timestamp => 0, - TypeKind::Float32, TypeKind::Float64 => 0.0, - TypeKind::String, TypeKind::Bytes => '', - TypeKind::Optional => null, - TypeKind::Array => [], - TypeKind::Struct => self::defaultStructValue($type), - TypeKind::Enum => EnumValue::constant('UNKNOWN'), - }; - } - - private static function defaultStructValue(Type $type): array - { - $defaults = []; - - foreach ($type->fields as $field) { - if ($field->removed) { - continue; - } - - $defaults[$field->name] = self::defaultValue(self::requireFieldType($field)); - } - - return $defaults; - } - - private static function requireItemType(Type $type): Type - { - if ($type->itemType === null) { - throw SkirRuntimeException::invalidValue("Skir [{$type->kind->value}] type does not define an item type."); - } - - return $type->itemType; - } - - private static function requireFieldType(Field $field): Type - { - if ($field->type === null) { - throw SkirRuntimeException::invalidValue("Skir field [{$field->number}] does not define a type."); - } - - return $field->type; - } - - private static function fieldWithNumber(Type $type, int $number): ?Field - { - foreach ($type->fields as $field) { - if ($field->number === $number) { - return $field; - } - } - - return null; - } - - private static function variantWithName(Type $type, string $name): Variant - { - foreach ($type->variants as $variant) { - if ($variant->name === $name) { - return $variant; - } - } - - throw SkirRuntimeException::invalidValue("Skir enum variant [{$name}] is not defined."); - } - - private static function variantWithNumber(Type $type, int $number): Variant - { - foreach ($type->variants as $variant) { - if ($variant->number === $number) { - return $variant; - } - } - - throw SkirRuntimeException::invalidValue("Skir enum variant [{$number}] is not defined."); - } - - private static function isSafeIntegerString(string $value): bool - { - if (! preg_match('/^-?\d+$/', $value)) { - throw SkirRuntimeException::invalidValue('Skir int64/hash64 string values must contain only digits.'); - } - - $integer = (int) $value; - - return (string) $integer === $value && abs($integer) <= self::MAX_SAFE_JAVASCRIPT_INTEGER; + return JsonCodec::decode($type, $value); } } diff --git a/src/Exceptions/SkirRuntimeException.php b/src/Exceptions/SkirRuntimeException.php index 7c4aa6c..7205a04 100644 --- a/src/Exceptions/SkirRuntimeException.php +++ b/src/Exceptions/SkirRuntimeException.php @@ -14,6 +14,11 @@ public static function invalidDenseJson(string $message, ?Throwable $previous = return new self("Invalid dense JSON: {$message}", previous: $previous); } + public static function invalidReadableJson(string $message, ?Throwable $previous = null): self + { + return new self("Invalid readable JSON: {$message}", previous: $previous); + } + public static function invalidValue(string $message): self { return new self($message); diff --git a/src/Internal/JsonCodec.php b/src/Internal/JsonCodec.php new file mode 100644 index 0000000..d886e29 --- /dev/null +++ b/src/Internal/JsonCodec.php @@ -0,0 +1,409 @@ +kind) { + TypeKind::Bool => self::encodeBool($value, $flavor), + TypeKind::Int32 => Numbers::toInt32($value), + TypeKind::Int64 => LargeInteger::int64ToJson($value), + TypeKind::Hash64 => LargeInteger::hash64ToJson($value), + TypeKind::Float32, TypeKind::Float64 => self::encodeFloat((float) $value), + TypeKind::Timestamp => self::encodeTimestamp(Numbers::timestampMillis($value), $flavor), + TypeKind::String => (string) $value, + TypeKind::Bytes => self::encodeBytes((string) $value, $flavor), + TypeKind::Optional => $value === null ? null : self::encode(TypeValues::itemType($type), $value, $flavor), + TypeKind::Array => self::encodeArray($type, $value, $flavor), + TypeKind::Struct => $flavor === JsonFlavor::Readable + ? self::encodeReadableStruct($type, TypeValues::requireStructValue($value)) + : self::encodeDenseStruct($type, TypeValues::requireStructValue($value)), + TypeKind::Enum => self::encodeEnum($type, $value, $flavor), + }; + } + + public static function decode(Type $type, mixed $value): mixed + { + if ($value instanceof stdClass) { + $value = (array) $value; + } + + if (in_array($value, [0, 0.0], true)) { + return TypeValues::defaultValue($type->kind === TypeKind::Optional ? TypeValues::itemType($type) : $type); + } + + return match ($type->kind) { + TypeKind::Bool => self::decodeBool($value), + TypeKind::Int32 => Numbers::toInt32($value), + TypeKind::Int64, TypeKind::Hash64 => LargeInteger::fromJson($value), + TypeKind::Float32, TypeKind::Float64 => (float) Numbers::toNumber($value), + TypeKind::Timestamp => self::decodeTimestamp($value), + TypeKind::String => self::decodeString($value), + TypeKind::Bytes => self::decodeBytes($value), + TypeKind::Optional => $value === null ? null : self::decode(TypeValues::itemType($type), $value), + TypeKind::Array => self::decodeArray($type, $value), + TypeKind::Struct => self::decodeStruct($type, $value), + TypeKind::Enum => self::decodeEnum($type, $value), + }; + } + + private static function encodeBool(mixed $value, JsonFlavor $flavor): bool|int + { + if ($flavor === JsonFlavor::Readable) { + return (bool) $value; + } + + return $value ? 1 : 0; + } + + private static function encodeFloat(float $value): float|string + { + if (is_nan($value)) { + return 'NaN'; + } + + if ($value === INF) { + return 'Infinity'; + } + + if ($value === -INF) { + return '-Infinity'; + } + + return $value; + } + + /** + * @return int|array{unix_millis: int, formatted: string} + */ + private static function encodeTimestamp(int $unixMillis, JsonFlavor $flavor): int|array + { + if ($flavor === JsonFlavor::Dense) { + return $unixMillis; + } + + return [ + 'unix_millis' => $unixMillis, + 'formatted' => self::formatIsoTimestamp($unixMillis), + ]; + } + + private static function formatIsoTimestamp(int $unixMillis): string + { + $millis = $unixMillis % 1000; + $seconds = intdiv($unixMillis, 1000); + + if ($millis < 0) { + $millis += 1000; + $seconds--; + } + + $dateTime = new DateTimeImmutable("@{$seconds}"); + + return sprintf('%s-%s.%03dZ', self::formatIsoYear((int) $dateTime->format('Y')), $dateTime->format('m-d\TH:i:s'), $millis); + } + + private static function formatIsoYear(int $year): string + { + if ($year < 0) { + return sprintf('%+07d', $year); + } + + if ($year > 9999) { + return sprintf('%+07d', $year); + } + + return sprintf('%04d', $year); + } + + private static function encodeBytes(string $value, JsonFlavor $flavor): string + { + if ($flavor === JsonFlavor::Readable) { + return 'hex:'.bin2hex($value); + } + + return base64_encode($value); + } + + /** + * @return array + */ + private static function encodeArray(Type $type, mixed $value, JsonFlavor $flavor): array + { + if (! is_array($value)) { + throw SkirRuntimeException::invalidValue('Skir array values must be PHP arrays.'); + } + + $itemType = TypeValues::itemType($type); + + return array_map( + fn (mixed $item): mixed => self::encode($itemType, $item, $flavor), + array_values($value), + ); + } + + /** + * @param array $value + * @return array + */ + private static function encodeDenseStruct(Type $type, array $value): array + { + $slotCount = TypeValues::structSlotCount($type, $value); + $slots = array_fill(0, $slotCount, 0); + + foreach ($type->fields as $field) { + if ($field->removed) { + continue; + } + + if ($field->number >= $slotCount) { + break; + } + + $slots[$field->number] = self::encode( + TypeValues::fieldType($field), + TypeValues::fieldValue($field, $value), + JsonFlavor::Dense, + ); + } + + return $slots; + } + + /** + * @param array $value + * @return array|stdClass + */ + private static function encodeReadableStruct(Type $type, array $value): array|stdClass + { + $encodedFields = []; + + foreach ($type->fields as $field) { + if ($field->removed) { + continue; + } + + $fieldType = TypeValues::fieldType($field); + $fieldValue = TypeValues::fieldValue($field, $value); + + if (TypeValues::isDefault($fieldType, $fieldValue)) { + continue; + } + + $encodedFields[$field->name] = self::encode($fieldType, $fieldValue, JsonFlavor::Readable); + } + + return $encodedFields === [] ? new stdClass : $encodedFields; + } + + private static function encodeEnum(Type $type, mixed $value, JsonFlavor $flavor): mixed + { + if (! $value instanceof EnumValue) { + throw SkirRuntimeException::invalidValue('Skir enum values must be EnumValue instances.'); + } + + if ($value->name === TypeValues::UNKNOWN_VARIANT) { + return $flavor === JsonFlavor::Readable ? 'unknown' : 0; + } + + $variant = TypeValues::variantWithName($type, $value->name); + + if (! $value->wrapper) { + return $flavor === JsonFlavor::Readable ? strtolower($variant->name) : $variant->number; + } + + if (! $variant->isWrapper()) { + throw SkirRuntimeException::invalidValue("Skir enum variant [{$value->name}] does not carry a payload."); + } + + $payload = self::encode($variant->payloadType, $value->value, $flavor); + + if ($flavor === JsonFlavor::Readable) { + return ['kind' => $variant->name, 'value' => $payload]; + } + + return [$variant->number, $payload]; + } + + private static function decodeBool(mixed $value): bool + { + if (is_array($value)) { + return true; + } + + return (bool) $value; + } + + private static function decodeTimestamp(mixed $value): int + { + if (is_array($value)) { + if (! array_key_exists('unix_millis', $value)) { + throw SkirRuntimeException::invalidValue('Skir readable timestamp JSON values must contain [unix_millis].'); + } + + return Numbers::timestampMillis($value['unix_millis']); + } + + if (is_int($value) || is_float($value) || is_string($value)) { + return Numbers::timestampMillis($value); + } + + throw SkirRuntimeException::invalidValue('Skir timestamp JSON values must be numbers, strings or objects.'); + } + + private static function decodeString(mixed $value): string + { + if (! is_string($value)) { + throw SkirRuntimeException::invalidValue('Skir string JSON values must be strings.'); + } + + return $value; + } + + private static function decodeBytes(mixed $value): string + { + if (! is_string($value)) { + throw SkirRuntimeException::invalidValue('Skir bytes JSON values must be strings.'); + } + + if (str_starts_with($value, 'hex:')) { + return self::decodeHex(substr($value, 4)); + } + + $decoded = base64_decode($value, true); + + if ($decoded === false) { + throw SkirRuntimeException::invalidValue('Skir bytes values must be valid base64 strings.'); + } + + return $decoded; + } + + private static function decodeHex(string $hex): string + { + $evenLengthHex = substr($hex, 0, intdiv(strlen($hex), 2) * 2); + + if (preg_match('/^[0-9a-fA-F]*$/', $evenLengthHex) !== 1) { + throw SkirRuntimeException::invalidValue('Skir bytes values prefixed with [hex:] must be valid hexadecimal strings.'); + } + + return (string) hex2bin($evenLengthHex); + } + + /** + * @return array + */ + private static function decodeArray(Type $type, mixed $value): array + { + if (! is_array($value)) { + throw SkirRuntimeException::invalidValue('Skir array JSON values must be arrays.'); + } + + if (! array_is_list($value)) { + throw SkirRuntimeException::invalidValue('Skir array JSON values must be arrays.'); + } + + $itemType = TypeValues::itemType($type); + + return array_map( + fn (mixed $item): mixed => self::decode($itemType, $item), + $value, + ); + } + + /** + * Dense structs arrive as lists indexed by field number, readable structs as + * objects keyed by field name; upstream also accepts field numbers as object keys. + * + * @return array + */ + private static function decodeStruct(Type $type, mixed $value): array + { + if (in_array($value, [null, false, ''], true)) { + return TypeValues::defaultValue($type); + } + + if (! is_array($value)) { + throw SkirRuntimeException::invalidValue('Skir struct JSON values must be arrays or objects.'); + } + + $decoded = TypeValues::defaultValue($type); + + foreach ($value as $key => $fieldValue) { + $field = TypeValues::fieldWithKey($type, $key); + + if ($field === null) { + continue; + } + + $decoded[$field->name] = self::decode(TypeValues::fieldType($field), $fieldValue); + } + + return $decoded; + } + + private static function decodeEnum(Type $type, mixed $value): EnumValue + { + if (is_array($value)) { + return self::decodeEnumWithPayload($type, $value); + } + + if (is_bool($value)) { + throw SkirRuntimeException::invalidValue('Skir enum JSON values must be numbers, strings, arrays or objects.'); + } + + if ($value === null) { + throw SkirRuntimeException::invalidValue('Skir enum JSON values must be numbers, strings, arrays or objects.'); + } + + $variant = TypeValues::variantWithKey($type, $value); + + if ($variant === null) { + return EnumValue::constant(TypeValues::UNKNOWN_VARIANT); + } + + if ($variant->isWrapper()) { + return EnumValue::wrapper($variant->name, TypeValues::defaultValue($variant->payloadType)); + } + + return EnumValue::constant($variant->name); + } + + /** + * @param array $value + */ + private static function decodeEnumWithPayload(Type $type, array $value): EnumValue + { + $isDense = array_is_list($value); + $variant = TypeValues::variantWithKey($type, $isDense ? $value[0] ?? null : $value['kind'] ?? null); + + if ($variant === null) { + return EnumValue::constant(TypeValues::UNKNOWN_VARIANT); + } + + if (! $variant->isWrapper()) { + return EnumValue::constant($variant->name); + } + + $payload = $isDense ? $value[1] ?? null : $value['value'] ?? null; + + return EnumValue::wrapper($variant->name, self::decode($variant->payloadType, $payload)); + } +} diff --git a/src/Internal/JsonFlavor.php b/src/Internal/JsonFlavor.php new file mode 100644 index 0000000..2d0e60b --- /dev/null +++ b/src/Internal/JsonFlavor.php @@ -0,0 +1,12 @@ + 'null', + is_bool($value) => $value ? 'true' : 'false', + is_int($value) => (string) $value, + is_float($value) => self::writeFloat($value), + is_string($value) => json_encode($value, self::STRING_FLAGS), + $value instanceof stdClass => self::writeObject((array) $value, $indent, $indentation), + is_array($value) => array_is_list($value) + ? self::writeList($value, $indent, $indentation) + : self::writeObject($value, $indent, $indentation), + default => throw SkirRuntimeException::invalidValue('Only JSON-compatible values can be written as JSON.'), + }; + } + + /** + * @param array $items + * + * @throws JsonException + */ + private static function writeList(array $items, string $indent, string $indentation): string + { + $innerIndentation = "{$indentation}{$indent}"; + $entries = array_map( + fn (mixed $item): string => self::writeValue($item, $indent, $innerIndentation), + $items, + ); + + return self::writeContainer('[', $entries, ']', $indent, $indentation); + } + + /** + * @param array $properties + * + * @throws JsonException + */ + private static function writeObject(array $properties, string $indent, string $indentation): string + { + $innerIndentation = "{$indentation}{$indent}"; + $separator = $indent === '' ? ':' : ': '; + $entries = []; + + foreach ($properties as $name => $value) { + $entries[] = json_encode((string) $name, self::STRING_FLAGS) + .$separator + .self::writeValue($value, $indent, $innerIndentation); + } + + return self::writeContainer('{', $entries, '}', $indent, $indentation); + } + + /** + * @param array $entries + */ + private static function writeContainer(string $open, array $entries, string $close, string $indent, string $indentation): string + { + if ($entries === []) { + return "{$open}{$close}"; + } + + if ($indent === '') { + return $open.implode(',', $entries).$close; + } + + $innerIndentation = "{$indentation}{$indent}"; + + return "{$open}\n{$innerIndentation}".implode(",\n{$innerIndentation}", $entries)."\n{$indentation}{$close}"; + } + + /** + * Formats a float like ECMAScript's Number::toString. + */ + private static function writeFloat(float $value): string + { + if (! is_finite($value)) { + return 'null'; + } + + if ($value === 0.0) { + return '0'; + } + + [$digits, $decimalPointPosition] = self::shortestDigits(abs($value)); + $sign = $value < 0 ? '-' : ''; + $digitCount = strlen($digits); + + if ($decimalPointPosition <= 21) { + if ($digitCount <= $decimalPointPosition) { + return $sign.$digits.str_repeat('0', $decimalPointPosition - $digitCount); + } + + if ($decimalPointPosition > 0) { + return $sign.substr($digits, 0, $decimalPointPosition).'.'.substr($digits, $decimalPointPosition); + } + } + + if ($decimalPointPosition > -6) { + if ($decimalPointPosition <= 0) { + return "{$sign}0.".str_repeat('0', -$decimalPointPosition).$digits; + } + } + + $exponent = $decimalPointPosition - 1; + $exponentSign = $exponent < 0 ? '-' : '+'; + $mantissa = $digitCount === 1 ? $digits : $digits[0].'.'.substr($digits, 1); + + return "{$sign}{$mantissa}e{$exponentSign}".abs($exponent); + } + + /** + * Returns the shortest digit string that round-trips to the given positive float, + * and the position of the decimal point relative to those digits. + * + * @return array{0: string, 1: int} + */ + private static function shortestDigits(float $value): array + { + for ($precision = 0; $precision < 17; $precision++) { + $scientific = sprintf("%.{$precision}e", $value); + + if ((float) $scientific === $value) { + break; + } + } + + [$mantissa, $exponent] = explode('e', $scientific); + $digits = rtrim(str_replace('.', '', $mantissa), '0'); + + return [$digits, (int) $exponent + 1]; + } +} diff --git a/src/Internal/LargeInteger.php b/src/Internal/LargeInteger.php new file mode 100644 index 0000000..fdea05b --- /dev/null +++ b/src/Internal/LargeInteger.php @@ -0,0 +1,170 @@ + 0) { + return self::MAX_HASH64; + } + + return $value; + } + + public static function int64ToJson(mixed $value): int|string + { + $int64 = self::clampInt64(self::normalize($value)); + + return self::isSafeInteger($int64) ? $int64 : (string) $int64; + } + + public static function hash64ToJson(mixed $value): int|string + { + $hash64 = self::clampHash64(self::normalize($value)); + + if (is_int($hash64)) { + return $hash64 <= Numbers::MAX_SAFE_INTEGER ? $hash64 : (string) $hash64; + } + + return $hash64; + } + + /** + * Returns the 64 bits of an unsigned hash64 value as a (possibly negative) PHP int. + */ + public static function hash64Bits(int|string $hash64): int + { + if (is_int($hash64)) { + return $hash64; + } + + $high = 0; + $low = 0; + + foreach (str_split($hash64) as $digit) { + $low = $low * 10 + (int) $digit; + $high = $high * 10 + ($low >> 32); + $low &= 0xFFFF_FFFF; + } + + return ($high << 32) | $low; + } + + public static function fromUnsignedBits(int $bits): int|string + { + return $bits >= 0 ? $bits : sprintf('%u', $bits); + } + + private static function isSafeInteger(int $value): bool + { + return abs($value) <= Numbers::MAX_SAFE_INTEGER; + } + + private static function parseIntegerString(string $value): int|string|null + { + if (preg_match('/^([+-]?)0*(\d+)$/', $value, $matches) !== 1) { + return null; + } + + $digits = $matches[2]; + $canonical = $matches[1] === '-' && $digits !== '0' ? "-{$digits}" : $digits; + $integer = filter_var($canonical, FILTER_VALIDATE_INT); + + return $integer === false ? $canonical : $integer; + } + + private static function compareUnsignedDecimals(string $left, string $right): int + { + return [strlen($left), $left] <=> [strlen($right), $right]; + } +} diff --git a/src/Internal/Numbers.php b/src/Internal/Numbers.php new file mode 100644 index 0000000..b54cee7 --- /dev/null +++ b/src/Internal/Numbers.php @@ -0,0 +1,126 @@ += 0x8000_0000 ? $low32Bits - 0x1_0000_0000 : $low32Bits; + } + + public static function isZero(mixed $value): bool + { + return in_array(self::toNumber($value), [0, 0.0], true); + } + + public static function roundHalfUp(float $value): float + { + $floor = floor($value); + + return $value - $floor >= 0.5 ? $floor + 1 : $floor; + } + + public static function timestampMillis(mixed $value): int + { + if ($value instanceof DateTimeInterface) { + return self::clampTimestampMillis(((int) $value->format('U')) * 1000 + ((int) $value->format('v'))); + } + + return self::clampTimestampMillis(self::toNumber($value)); + } + + private static function clampTimestampMillis(int|float $millis): int + { + if (is_nan($millis)) { + throw SkirRuntimeException::invalidValue('Skir timestamp values must be numbers of milliseconds.'); + } + + if ($millis <= -self::MAX_TIMESTAMP_MILLIS) { + return -self::MAX_TIMESTAMP_MILLIS; + } + + if ($millis >= self::MAX_TIMESTAMP_MILLIS) { + return self::MAX_TIMESTAMP_MILLIS; + } + + return is_float($millis) ? (int) self::roundHalfUp($millis) : $millis; + } + + private static function stringToNumber(string $value): int|float + { + if ($value === '') { + return 0; + } + + if (is_numeric($value)) { + return $value + 0; + } + + return match ($value) { + 'Infinity', '+Infinity' => INF, + '-Infinity' => -INF, + default => NAN, + }; + } + + private static function floatToInt32Range(float $value): int + { + if (! is_finite($value)) { + return 0; + } + + $truncated = $value < 0 ? ceil($value) : floor($value); + + return (int) fmod($truncated, self::TWO_TO_THE_32); + } +} diff --git a/src/Internal/TypeValues.php b/src/Internal/TypeValues.php new file mode 100644 index 0000000..087c359 --- /dev/null +++ b/src/Internal/TypeValues.php @@ -0,0 +1,225 @@ +kind) { + TypeKind::Bool => false, + TypeKind::Int32, TypeKind::Int64, TypeKind::Hash64, TypeKind::Timestamp => 0, + TypeKind::Float32, TypeKind::Float64 => 0.0, + TypeKind::String, TypeKind::Bytes => '', + TypeKind::Optional => null, + TypeKind::Array => [], + TypeKind::Struct => self::defaultStructValue($type), + TypeKind::Enum => EnumValue::constant(self::UNKNOWN_VARIANT), + }; + } + + public static function isDefault(Type $type, mixed $value): bool + { + return match ($type->kind) { + TypeKind::Bool => ! $value, + TypeKind::Int32, TypeKind::Float32, TypeKind::Float64 => Numbers::isZero($value), + TypeKind::Int64, TypeKind::Hash64 => LargeInteger::normalize($value) === 0, + TypeKind::Timestamp => Numbers::timestampMillis($value) === 0, + TypeKind::String, TypeKind::Bytes => (string) $value === '', + TypeKind::Optional => $value === null, + TypeKind::Array => $value === [], + TypeKind::Struct => self::structSlotCount($type, self::requireStructValue($value)) === 0, + TypeKind::Enum => $value instanceof EnumValue && $value->name === self::UNKNOWN_VARIANT, + }; + } + + /** + * Number of slots needed to encode the struct: one past the highest field holding a non-default value. + * + * @param array $value + */ + public static function structSlotCount(Type $type, array $value): int + { + foreach (array_reverse($type->fields) as $field) { + if ($field->removed) { + continue; + } + + if (! self::isDefault(self::fieldType($field), self::fieldValue($field, $value))) { + return $field->number + 1; + } + } + + return 0; + } + + /** + * @return array + */ + public static function requireStructValue(mixed $value): array + { + if (! is_array($value)) { + throw SkirRuntimeException::invalidValue('Skir struct values must be associative arrays.'); + } + + return $value; + } + + /** + * @param array $value + */ + public static function fieldValue(Field $field, array $value): mixed + { + return array_key_exists($field->name, $value) + ? $value[$field->name] + : self::defaultValue(self::fieldType($field)); + } + + public static function itemType(Type $type): Type + { + return $type->itemType + ?? throw SkirRuntimeException::invalidValue("Skir [{$type->kind->value}] type does not define an item type."); + } + + public static function fieldType(Field $field): Type + { + return $field->type + ?? throw SkirRuntimeException::invalidValue("Skir field [{$field->number}] does not define a type."); + } + + public static function fieldWithKey(Type $type, int|string $key): ?Field + { + foreach ($type->fields as $field) { + if ($field->removed) { + continue; + } + + if ($field->number === $key) { + return $field; + } + + if ($field->name === $key) { + return $field; + } + } + + return null; + } + + public static function variantWithName(Type $type, string $name): Variant + { + foreach ($type->variants as $variant) { + if ($variant->name === $name) { + return $variant; + } + } + + throw SkirRuntimeException::invalidValue("Skir enum variant [{$name}] is not defined."); + } + + public static function variantWithNumber(Type $type, int $number): ?Variant + { + foreach ($type->variants as $variant) { + if ($variant->number === $number) { + return $variant; + } + } + + return null; + } + + /** + * Resolves a variant the way upstream resolves JSON enum keys: by number, by + * exact name, or by the upper or lower case name of a constant variant. + */ + public static function variantWithKey(Type $type, mixed $key): ?Variant + { + if (is_int($key)) { + return self::variantWithNumber($type, $key); + } + + if (is_float($key)) { + return self::variantWithIntegralFloat($type, $key); + } + + if (! is_string($key)) { + return null; + } + + if (preg_match('/^(0|-?[1-9]\d*)$/', $key) === 1) { + return self::variantWithNumber($type, (int) $key); + } + + return self::variantWithReadableName($type, $key); + } + + /** + * @return array + */ + private static function defaultStructValue(Type $type): array + { + $defaults = []; + + foreach ($type->fields as $field) { + if ($field->removed) { + continue; + } + + $defaults[$field->name] = self::defaultValue(self::fieldType($field)); + } + + return $defaults; + } + + private static function variantWithIntegralFloat(Type $type, float $key): ?Variant + { + if (floor($key) !== $key) { + return null; + } + + if (abs($key) > Numbers::MAX_SAFE_INTEGER) { + return null; + } + + return self::variantWithNumber($type, (int) $key); + } + + private static function variantWithReadableName(Type $type, string $name): ?Variant + { + foreach ($type->variants as $variant) { + if ($variant->name === $name) { + return $variant; + } + + if ($variant->isWrapper()) { + continue; + } + + if (strtolower($variant->name) === $name) { + return $variant; + } + + if (strtoupper($variant->name) === $name) { + return $variant; + } + } + + return null; + } +} diff --git a/src/ReadableJson.php b/src/ReadableJson.php new file mode 100644 index 0000000..998c70e --- /dev/null +++ b/src/ReadableJson.php @@ -0,0 +1,34 @@ +getMessage(), $exception); + } + } +} diff --git a/tests/DenseJsonTest.php b/tests/DenseJsonTest.php index 7ff8dba..fc08a6e 100644 --- a/tests/DenseJsonTest.php +++ b/tests/DenseJsonTest.php @@ -5,6 +5,7 @@ namespace Skir\Runtime\Tests; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\DataProviderExternal; use PHPUnit\Framework\TestCase; use Skir\Runtime\DenseJson; use Skir\Runtime\EnumValue; @@ -28,11 +29,30 @@ public function test_it_encodes_primitive_values(): void $this->assertSame('"AQID"', DenseJson::toJson(Type::bytes(), "\x01\x02\x03")); } + public function test_it_wraps_and_clamps_integers_like_upstream(): void + { + $this->assertSame('1', DenseJson::toJson(Type::int32(), 4_294_967_297)); + $this->assertSame('-2147483648', DenseJson::toJson(Type::int32(), 2_147_483_648)); + $this->assertSame('"9223372036854775807"', DenseJson::toJson(Type::int64(), '99999999999999999999')); + $this->assertSame('42', DenseJson::toJson(Type::int64(), '0042')); + $this->assertSame('0', DenseJson::toJson(Type::hash64(), -5)); + $this->assertSame('"18446744073709551615"', DenseJson::toJson(Type::hash64(), '99999999999999999999')); + } + + public function test_it_rejects_non_integer_int64_values(): void + { + $this->expectException(SkirRuntimeException::class); + $this->expectExceptionMessage('Skir int64/hash64 string values must contain only digits.'); + + DenseJson::toJson(Type::int64(), '12abc'); + } + public function test_it_preserves_permissive_primitive_wire_coercion(): void { $this->assertTrue(DenseJson::fromJson(Type::bool(), '"false"')); $this->assertSame(0, DenseJson::fromJson(Type::int32(), '"not-a-number"')); - $this->assertSame('9223372036854775807', DenseJson::fromJson(Type::int64(), '"9223372036854775807"')); + $this->assertSame(PHP_INT_MAX, DenseJson::fromJson(Type::int64(), '"9223372036854775807"')); + $this->assertSame('18446744073709551615', DenseJson::fromJson(Type::hash64(), '"18446744073709551615"')); $this->assertSame(2.5, DenseJson::fromJson(Type::float64(), '"2.5"')); $this->assertSame(1743682787000, DenseJson::fromJson(Type::timestamp(), '"1743682787000"')); $this->assertSame("\x01\x02\x03", DenseJson::fromJson(Type::bytes(), '"AQID"')); @@ -146,177 +166,108 @@ public function test_it_encodes_and_decodes_enum_variants(): void ); } - #[DataProvider('compatibleEnumWrapperVariantNumbers')] - public function test_it_normalizes_integer_equivalent_enum_wrapper_variant_numbers(string $json): void - { - $subscriptionStatus = Type::enum([ - Variant::wrapper('premium_since', 2, Type::timestamp()), - ]); - - $this->assertEquals( - EnumValue::wrapper('premium_since', 1743682787000), - DenseJson::fromJson($subscriptionStatus, $json), - ); - } - - /** - * @return iterable - */ - public static function compatibleEnumWrapperVariantNumbers(): iterable - { - yield 'numeric string' => ['["2",1743682787000]']; - yield 'integral float' => ['[2.0,1743682787000]']; - } - - #[DataProvider('compatibleScalarEnumVariantNumbers')] - public function test_it_normalizes_integer_equivalent_scalar_enum_variant_numbers(string $json): void + #[DataProviderExternal(UpstreamVectors::class, 'decoding')] + public function test_it_decodes_both_json_flavors_like_upstream(string $type, string $json, string $expectedDenseJson): void { - $subscriptionStatus = Type::enum([ - Variant::constant('free', 1), - ]); + $skirType = UpstreamVectors::type($type); - $this->assertEquals( - EnumValue::constant('free'), - DenseJson::fromJson($subscriptionStatus, $json), - ); + $this->assertSame($expectedDenseJson, DenseJson::toJson($skirType, DenseJson::fromJson($skirType, $json))); } - /** - * @return iterable - */ - public static function compatibleScalarEnumVariantNumbers(): iterable + #[DataProviderExternal(UpstreamVectors::class, 'encoding')] + public function test_it_matches_upstream_dense_json_code(string $type, string $denseJson, string $expectedDenseJson, string $expectedReadableJson): void { - yield 'numeric string' => ['"1"']; - yield 'integral float' => ['1.0']; - } + $skirType = UpstreamVectors::type($type); - #[DataProvider('compatibleUnknownEnumVariantNumbers')] - public function test_it_preserves_unknown_for_integer_equivalent_zero_values(string $json): void - { - $subscriptionStatus = Type::enum([ - Variant::constant('free', 1), - ]); - - $this->assertEquals( - EnumValue::constant('UNKNOWN'), - DenseJson::fromJson($subscriptionStatus, $json), - ); + $this->assertSame($expectedDenseJson, DenseJson::toJson($skirType, DenseJson::fromJson($skirType, $denseJson))); } - /** - * @return iterable - */ - public static function compatibleUnknownEnumVariantNumbers(): iterable + public function test_it_decodes_readable_structs_keyed_by_field_name(): void { - yield 'numeric string zero' => ['"0"']; - yield 'integral float zero' => ['0.0']; - } + $decoded = DenseJson::fromJson(UpstreamVectors::user(), '{"user_id":400,"name":"Jane","unknown":1,"created_at":{"unix_millis":5,"formatted":"x"},"avatar":"hex:0102","status":"free","address":{"city":"Antwerp"}}'); - #[DataProvider('invalidScalarEnumVariantNumbers')] - public function test_it_rejects_invalid_scalar_enum_variant_numbers(string $json): void - { - $subscriptionStatus = Type::enum([ - Variant::constant('free', 1), - ]); - - $this->expectException(SkirRuntimeException::class); - $this->expectExceptionMessage('Skir enum variant numbers must be safe integer-equivalent values.'); - - DenseJson::fromJson($subscriptionStatus, $json); - } - - /** - * @return iterable - */ - public static function invalidScalarEnumVariantNumbers(): iterable - { - yield 'nonnumeric string' => ['"premium_since"']; - yield 'non-integral float' => ['1.5']; - yield 'non-finite float' => ['1e309']; - yield 'out-of-range integer' => ['9007199254740992']; - yield 'out-of-range string' => ['"9007199254740992"']; - yield 'noncanonical numeric string' => ['"1.0"']; - } - - public function test_it_does_not_extend_scalar_normalization_to_wrapper_variants(): void - { - $subscriptionStatus = Type::enum([ - Variant::wrapper('premium_since', 2, Type::timestamp()), - ]); - - $this->expectException(SkirRuntimeException::class); - $this->expectExceptionMessage('Skir enum wrapper variant [premium_since] must be encoded as a wrapper array.'); - - DenseJson::fromJson($subscriptionStatus, '"2"'); + $this->assertEquals([ + 'user_id' => 400, + 'name' => 'Jane', + 'nickname' => null, + 'tags' => [], + 'created_at' => 5, + 'avatar' => "\x01\x02", + 'score' => 0.0, + 'big' => 0, + 'hash' => 0, + 'active' => false, + 'status' => EnumValue::constant('free'), + 'address' => ['city' => 'Antwerp'], + 'matrix' => [], + ], $decoded); } - public function test_it_preserves_native_integer_scalar_wrapper_variant_behavior(): void + public function test_it_decodes_json_objects_given_as_std_class(): void { - $subscriptionStatus = Type::enum([ - Variant::wrapper('premium_since', 2, Type::timestamp()), - ]); + $decoded = DenseJson::decode(UpstreamVectors::status(), json_decode('{"kind":"trial","value":{"city":"Paris"}}')); - $this->assertEquals( - EnumValue::constant('premium_since'), - DenseJson::fromJson($subscriptionStatus, '2'), - ); + $this->assertEquals(EnumValue::wrapper('trial', ['city' => 'Paris']), $decoded); } - public function test_it_decodes_numeric_key_json_objects_as_enum_wrapper_tuples(): void + public function test_it_decodes_readable_enums(): void { - $subscriptionStatus = Type::enum([ - Variant::wrapper('premium_since', 2, Type::timestamp()), - ]); + $status = UpstreamVectors::status(); + $this->assertEquals(EnumValue::constant('free'), DenseJson::fromJson($status, '"free"')); + $this->assertEquals(EnumValue::constant('free'), DenseJson::fromJson($status, '"FREE"')); + $this->assertEquals(EnumValue::constant('UNKNOWN'), DenseJson::fromJson($status, '"unknown"')); + $this->assertEquals(EnumValue::constant('UNKNOWN'), DenseJson::fromJson($status, '"not_a_variant"')); + $this->assertEquals(EnumValue::wrapper('premium_since', 0), DenseJson::fromJson($status, '"premium_since"')); $this->assertEquals( - EnumValue::wrapper('premium_since', 1743682787000), - DenseJson::fromJson($subscriptionStatus, '{"0":2,"1":1743682787000}'), + EnumValue::wrapper('premium_since', 1_743_682_787_000), + DenseJson::fromJson($status, '{"kind":"premium_since","value":{"unix_millis":1743682787000,"formatted":"2025-04-03T12:19:47.000Z"}}'), ); } - public function test_it_rejects_out_of_range_float_variant_numbers_before_integer_casting(): void + public function test_it_decodes_enum_values_that_changed_shape_like_upstream(): void { - $subscriptionStatus = Type::enum([ - Variant::wrapper('premium_since', 4096, Type::timestamp()), - ]); - - $this->expectException(SkirRuntimeException::class); - $this->expectExceptionMessage('Skir enum variant numbers must be safe integer-equivalent values.'); + $status = UpstreamVectors::status(); - DenseJson::fromJson($subscriptionStatus, '[18446744073709555712,1743682787000]'); + $this->assertEquals(EnumValue::wrapper('premium_since', 0), DenseJson::fromJson($status, '2')); + $this->assertEquals(EnumValue::constant('free'), DenseJson::fromJson($status, '[1,1743682787000]')); + $this->assertEquals(EnumValue::constant('UNKNOWN'), DenseJson::fromJson($status, '[99,1743682787000]')); } - #[DataProvider('malformedEnumWrappers')] - public function test_it_rejects_malformed_enum_wrappers(string $json, string $message): void + #[DataProvider('jsonValuesRejectedByUpstream')] + public function test_it_rejects_json_values_upstream_rejects(string $type, string $json): void { - $subscriptionStatus = Type::enum([ - Variant::constant('free', 1), - Variant::wrapper('premium_since', 2, Type::timestamp()), - ]); - $this->expectException(SkirRuntimeException::class); - $this->expectExceptionMessage($message); - DenseJson::fromJson($subscriptionStatus, $json); + DenseJson::fromJson(UpstreamVectors::type($type), $json); } /** * @return iterable */ - public static function malformedEnumWrappers(): iterable + public static function jsonValuesRejectedByUpstream(): iterable { - yield 'empty tuple' => ['[]', 'Skir enum wrapper JSON values must contain exactly a variant number and payload.']; - yield 'missing payload' => ['[2]', 'Skir enum wrapper JSON values must contain exactly a variant number and payload.']; - yield 'excess tuple element' => ['[2,1743682787000,"extra"]', 'Skir enum wrapper JSON values must contain exactly a variant number and payload.']; - yield 'named-key object' => ['{"variant":2,"payload":1743682787000}', 'Skir enum wrapper JSON values must contain exactly a variant number and payload.']; - yield 'sparse numeric-key object' => ['{"0":2,"2":1743682787000}', 'Skir enum wrapper JSON values must contain exactly a variant number and payload.']; - yield 'non-integral variant number' => ['[2.5,1743682787000]', 'Skir enum variant numbers must be safe integer-equivalent values.']; - yield 'non-finite variant number' => ['[1e309,1743682787000]', 'Skir enum variant numbers must be safe integer-equivalent values.']; - yield 'out-of-range integer variant number' => ['[9007199254740992,1743682787000]', 'Skir enum variant numbers must be safe integer-equivalent values.']; - yield 'out-of-range string variant number' => ['["9007199254740992",1743682787000]', 'Skir enum variant numbers must be safe integer-equivalent values.']; - yield 'noncanonical numeric string' => ['["2.0",1743682787000]', 'Skir enum variant numbers must be safe integer-equivalent values.']; - yield 'unknown variant number' => ['[99,1743682787000]', 'Skir enum variant [99] is not defined.']; - yield 'constant variant with payload' => ['[1,1743682787000]', 'Skir enum variant [free] does not carry a payload.']; + yield 'string from number' => ['string', '5']; + yield 'string from null' => ['string', 'null']; + yield 'string from array' => ['string', '[]']; + yield 'string from bool' => ['string', 'true']; + yield 'enum from null' => ['status', 'null']; + yield 'enum from bool' => ['status', 'true']; + yield 'array from string' => ['matrix', '"x"']; + yield 'array from object' => ['matrix', '{"a":1}']; + yield 'array from null' => ['matrix', 'null']; + yield 'struct from string' => ['address', '"x"']; + yield 'struct from bool' => ['address', 'true']; + yield 'struct from number' => ['address', '5']; + yield 'int64 from text' => ['int64', '"abc"']; + yield 'int64 from null' => ['int64', 'null']; + yield 'int64 from decimal string' => ['int64', '"1.5"']; + yield 'timestamp from text' => ['timestamp', '"abc"']; + yield 'timestamp from null' => ['timestamp', 'null']; + yield 'bytes from number' => ['bytes', '5']; + yield 'bytes from invalid hex' => ['bytes', '"hex:zz"']; + yield 'bytes from invalid base64' => ['bytes', '"!!!"']; + yield 'bytes from null' => ['bytes', 'null']; } public function test_it_decodes_zero_as_default_for_forward_compatibility(): void diff --git a/tests/ReadableJsonTest.php b/tests/ReadableJsonTest.php new file mode 100644 index 0000000..ffc4444 --- /dev/null +++ b/tests/ReadableJsonTest.php @@ -0,0 +1,162 @@ +assertSame($expectedReadableJson, ReadableJson::toJson($skirType, $value)); + } + + #[DataProviderExternal(UpstreamVectors::class, 'encoding')] + public function test_readable_json_round_trips_through_dense_json_decoding(string $type, string $denseJson, string $expectedDenseJson, string $expectedReadableJson): void + { + $skirType = UpstreamVectors::type($type); + $value = DenseJson::fromJson($skirType, $denseJson); + + $fromCode = DenseJson::fromJson($skirType, ReadableJson::toJson($skirType, $value)); + $fromValue = DenseJson::decode($skirType, ReadableJson::encode($skirType, $value)); + + $this->assertSame($expectedDenseJson, DenseJson::toJson($skirType, $fromCode)); + $this->assertSame($expectedDenseJson, DenseJson::toJson($skirType, $fromValue)); + } + + public function test_it_encodes_primitives(): void + { + $this->assertTrue(ReadableJson::encode(Type::bool(), true)); + $this->assertFalse(ReadableJson::encode(Type::bool(), 0)); + $this->assertSame(-5, ReadableJson::encode(Type::int32(), -5)); + $this->assertSame(1, ReadableJson::encode(Type::int32(), 4_294_967_297)); + $this->assertSame(9_007_199_254_740_991, ReadableJson::encode(Type::int64(), 9_007_199_254_740_991)); + $this->assertSame('9007199254740992', ReadableJson::encode(Type::int64(), 9_007_199_254_740_992)); + $this->assertSame('9223372036854775807', ReadableJson::encode(Type::int64(), '99999999999999999999')); + $this->assertSame('-9223372036854775808', ReadableJson::encode(Type::int64(), '-99999999999999999999')); + $this->assertSame('18446744073709551615', ReadableJson::encode(Type::hash64(), '99999999999999999999')); + $this->assertSame(0, ReadableJson::encode(Type::hash64(), -5)); + $this->assertSame('NaN', ReadableJson::encode(Type::float64(), NAN)); + $this->assertSame('-Infinity', ReadableJson::encode(Type::float32(), -INF)); + $this->assertSame('hex:0102ff', ReadableJson::encode(Type::bytes(), "\x01\x02\xff")); + $this->assertNull(ReadableJson::encode(Type::optional(Type::string()), null)); + } + + public function test_it_encodes_timestamps_with_unix_millis_and_an_iso_string(): void + { + $expected = [ + 'unix_millis' => 1_743_682_787_123, + 'formatted' => '2025-04-03T12:19:47.123Z', + ]; + + $this->assertSame($expected, ReadableJson::encode(Type::timestamp(), 1_743_682_787_123)); + $this->assertSame($expected, ReadableJson::encode( + Type::timestamp(), + new DateTimeImmutable('2025-04-03T12:19:47.123Z'), + )); + } + + public function test_it_clamps_timestamps_to_the_javascript_date_range(): void + { + $this->assertSame([ + 'unix_millis' => 8_640_000_000_000_000, + 'formatted' => '+275760-09-13T00:00:00.000Z', + ], ReadableJson::encode(Type::timestamp(), PHP_INT_MAX)); + } + + public function test_it_encodes_structs_as_objects_keyed_by_field_name_without_default_fields(): void + { + $encoded = ReadableJson::encode(UpstreamVectors::user(), [ + 'user_id' => 400, + 'name' => 'Jane', + 'nickname' => null, + 'tags' => [], + 'status' => EnumValue::constant('free'), + 'address' => ['city' => ''], + ]); + + $this->assertSame([ + 'user_id' => 400, + 'name' => 'Jane', + 'status' => 'free', + ], $encoded); + } + + public function test_it_encodes_structs_with_only_default_values_as_empty_objects(): void + { + $encoded = ReadableJson::encode(UpstreamVectors::address(), ['city' => '']); + + $this->assertEquals(new stdClass, $encoded); + $this->assertSame('{}', ReadableJson::toJson(UpstreamVectors::address(), [])); + } + + public function test_it_ignores_values_given_for_removed_fields(): void + { + $type = Type::struct([ + Field::value('name', 0, Type::string()), + Field::removed(1), + ]); + + $this->assertSame(['name' => 'Jane'], ReadableJson::encode($type, ['name' => 'Jane', 1 => 'removed'])); + } + + public function test_it_encodes_enums(): void + { + $status = UpstreamVectors::status(); + + $this->assertSame('unknown', ReadableJson::encode($status, EnumValue::constant('UNKNOWN'))); + $this->assertSame('free', ReadableJson::encode($status, EnumValue::constant('free'))); + $this->assertSame( + ['kind' => 'premium_since', 'value' => ['unix_millis' => 0, 'formatted' => '1970-01-01T00:00:00.000Z']], + ReadableJson::encode($status, EnumValue::wrapper('premium_since', 0)), + ); + $this->assertEquals( + ['kind' => 'trial', 'value' => new stdClass], + ReadableJson::encode($status, EnumValue::wrapper('trial', [])), + ); + } + + public function test_it_lowercases_constant_variant_names_but_not_wrapper_variant_names(): void + { + $type = Type::enum([ + Variant::constant('ACTIVE', 1), + Variant::wrapper('Custom', 2, Type::string()), + ]); + + $this->assertSame('active', ReadableJson::encode($type, EnumValue::constant('ACTIVE'))); + $this->assertSame(['kind' => 'Custom', 'value' => 'x'], ReadableJson::encode($type, EnumValue::wrapper('Custom', 'x'))); + $this->assertEquals(EnumValue::constant('ACTIVE'), DenseJson::fromJson($type, '"active"')); + } + + public function test_it_rejects_undefined_enum_variants(): void + { + $this->expectException(SkirRuntimeException::class); + $this->expectExceptionMessage('Skir enum variant [missing] is not defined.'); + + ReadableJson::encode(UpstreamVectors::status(), EnumValue::constant('missing')); + } + + public function test_it_uses_package_scoped_exceptions_for_values_that_cannot_be_encoded_as_json(): void + { + $this->expectException(SkirRuntimeException::class); + $this->expectExceptionMessage('Invalid readable JSON: Malformed UTF-8 characters, possibly incorrectly encoded'); + + ReadableJson::toJson(Type::string(), "\xB1\x31"); + } +} diff --git a/tests/UpstreamVectors.php b/tests/UpstreamVectors.php new file mode 100644 index 0000000..6de07b2 --- /dev/null +++ b/tests/UpstreamVectors.php @@ -0,0 +1,387 @@ + Type::bool(), + 'int32' => Type::int32(), + 'int64' => Type::int64(), + 'hash64' => Type::hash64(), + 'float32' => Type::float32(), + 'float64' => Type::float64(), + 'timestamp' => Type::timestamp(), + 'string' => Type::string(), + 'bytes' => Type::bytes(), + 'optionalString' => Type::optional(Type::string()), + 'matrix' => Type::array(Type::array(Type::int32())), + 'address' => self::address(), + 'addresses' => Type::array(self::address()), + 'status' => self::status(), + 'user' => self::user(), + }; + } + + public static function address(): Type + { + return Type::struct([ + Field::value('city', 0, Type::string()), + ]); + } + + public static function status(): Type + { + return Type::enum([ + Variant::constant('free', 1), + Variant::wrapper('premium_since', 2, Type::timestamp()), + Variant::wrapper('trial', 3, self::address()), + Variant::wrapper('big', 300, Type::string()), + ]); + } + + public static function user(): Type + { + return Type::struct([ + Field::value('user_id', 0, Type::int32()), + Field::removed(1), + Field::value('name', 2, Type::string()), + Field::value('nickname', 3, Type::optional(Type::string())), + Field::value('tags', 4, Type::array(Type::string())), + Field::value('created_at', 5, Type::timestamp()), + Field::value('avatar', 6, Type::bytes()), + Field::value('score', 7, Type::float64()), + Field::value('big', 8, Type::int64()), + Field::value('hash', 9, Type::hash64()), + Field::value('active', 10, Type::bool()), + Field::value('status', 11, self::status()), + Field::value('address', 12, self::address()), + Field::value('matrix', 13, Type::array(Type::array(Type::int32()))), + ]); + } + + /** + * Upstream fromJson(input) followed by toJson(value, "dense"). + * + * @return iterable + */ + public static function decoding(): iterable + { + $vectors = [ + ['bool', 'true', '1'], + ['bool', 'false', '0'], + ['bool', '1', '1'], + ['bool', '0', '0'], + ['bool', '"0"', '0'], + ['bool', '"false"', '1'], + ['bool', '""', '0'], + ['bool', 'null', '0'], + ['bool', '[]', '1'], + ['bool', '{}', '1'], + ['int32', '42', '42'], + ['int32', '-7', '-7'], + ['int32', '2.9', '2'], + ['int32', '-2.9', '-2'], + ['int32', '"12"', '12'], + ['int32', '"not-a-number"', '0'], + ['int32', '4294967297', '1'], + ['int32', '2147483648', '-2147483648'], + ['int32', 'true', '1'], + ['int32', 'null', '0'], + ['int32', '"1e3"', '1000'], + ['int32', '" 5 "', '5'], + ['int64', '42', '42'], + ['int64', '"9007199254740993"', '"9007199254740993"'], + ['int64', '"-9223372036854775808"', '"-9223372036854775808"'], + ['int64', '"99999999999999999999"', '"9223372036854775807"'], + ['int64', '2.5', '3'], + ['int64', '-2.5', '-2'], + ['int64', '1e20', '"9223372036854775807"'], + ['int64', '"0042"', '42'], + ['int64', '"+7"', '7'], + ['int64', 'true', '1'], + ['int64', '""', '0'], + ['hash64', '"18446744073709551615"', '"18446744073709551615"'], + ['hash64', '7', '7'], + ['hash64', '"9223372036854775808"', '"9223372036854775808"'], + ['float64', '1.5', '1.5'], + ['float64', '"NaN"', '"NaN"'], + ['float64', '"Infinity"', '"Infinity"'], + ['float64', '"-Infinity"', '"-Infinity"'], + ['float64', '"2.5"', '2.5'], + ['float64', '"abc"', '"NaN"'], + ['float64', 'null', '0'], + ['float64', 'true', '1'], + ['float64', '""', '0'], + ['float64', '1e300', '1e+300'], + ['timestamp', '1743682787123', '1743682787123'], + ['timestamp', '"1743682787123"', '1743682787123'], + ['timestamp', '{"unix_millis":1743682787123,"formatted":"ignored"}', '1743682787123'], + ['timestamp', '1e20', '8640000000000000'], + ['timestamp', '-1e20', '-8640000000000000'], + ['timestamp', '2.5', '3'], + ['timestamp', '-2.5', '-2'], + ['string', '"Hello"', '"Hello"'], + ['string', '""', '""'], + ['string', '0', '""'], + ['bytes', '"AQID"', '"AQID"'], + ['bytes', '"hex:0102ff"', '"AQL/"'], + ['bytes', '"hex:ABCD"', '"q80="'], + ['bytes', '"hex:"', '""'], + ['bytes', '"hex:abc"', '"qw=="'], + ['bytes', '0', '""'], + ['bytes', '""', '""'], + ['optionalString', 'null', 'null'], + ['optionalString', '"x"', '"x"'], + ['optionalString', '0', '""'], + ['matrix', '[[1,2],[],[3]]', '[[1,2],[],[3]]'], + ['matrix', '0', '[]'], + ['matrix', '[0,[1]]', '[[],[1]]'], + ['address', '[]', '[]'], + ['address', '{}', '[]'], + ['address', '["Antwerp"]', '["Antwerp"]'], + ['address', '{"city":"Antwerp"}', '["Antwerp"]'], + ['address', '{"city":"Antwerp","zzz":1}', '["Antwerp"]'], + ['address', '{"0":"Antwerp"}', '["Antwerp"]'], + ['address', 'null', '[]'], + ['address', '0', '[]'], + ['address', '["Antwerp","extra",3]', '["Antwerp"]'], + ['address', 'false', '[]'], + ['address', '""', '[]'], + ['status', '0', '0'], + ['status', '1', '1'], + ['status', '2', '[2,0]'], + ['status', '3', '[3,[]]'], + ['status', '4', '0'], + ['status', '99', '0'], + ['status', '"1"', '1'], + ['status', '"2"', '[2,0]'], + ['status', '"free"', '1'], + ['status', '"FREE"', '1'], + ['status', '"Free"', '0'], + ['status', '"unknown"', '0'], + ['status', '"UNKNOWN"', '0'], + ['status', '"premium_since"', '[2,0]'], + ['status', '"PREMIUM_SINCE"', '0'], + ['status', '"trial"', '[3,[]]'], + ['status', '"nope"', '0'], + ['status', '"1.0"', '0'], + ['status', '"01"', '0'], + ['status', '1.0', '1'], + ['status', '1.5', '0'], + ['status', '[2,1743682787000]', '[2,1743682787000]'], + ['status', '[1,5]', '1'], + ['status', '[99,5]', '0'], + ['status', '[4,5]', '0'], + ['status', '[]', '0'], + ['status', '[3]', '[3,[]]'], + ['status', '[2,1743682787000,"extra"]', '[2,1743682787000]'], + ['status', '["2",5]', '[2,5]'], + ['status', '[2.0,5]', '[2,5]'], + ['status', '{"kind":"free"}', '1'], + ['status', '{"kind":"FREE","value":5}', '1'], + ['status', '{"kind":"premium_since","value":{"unix_millis":7,"formatted":"x"}}', '[2,7]'], + ['status', '{"kind":"premium_since","value":7}', '[2,7]'], + ['status', '{"kind":"trial","value":{"city":"X"}}', '[3,["X"]]'], + ['status', '{"kind":"trial"}', '[3,[]]'], + ['status', '{"kind":"nope","value":1}', '0'], + ['status', '{"kind":2,"value":9}', '[2,9]'], + ['status', '{"kind":"2","value":9}', '[2,9]'], + ['status', '{"kind":300,"value":"s"}', '[300,"s"]'], + ['status', '[300,"s"]', '[300,"s"]'], + ['status', '{}', '0'], + ['status', '{"variant":2,"payload":5}', '0'], + ['status', '{"0":2,"2":5}', '0'], + ['user', '[400,0,"Jane"]', '[400,0,"Jane"]'], + ['user', '{"user_id":400,"name":"Jane","nickname":null,"tags":["a"],"created_at":{"unix_millis":1743682787123,"formatted":"x"},"avatar":"hex:0102ff","score":"NaN","big":"9007199254740993","hash":"18446744073709551615","active":true,"status":{"kind":"premium_since","value":{"unix_millis":5,"formatted":"x"}},"address":{"city":"Antwerp","zzz":1},"matrix":[[1],[2,3]],"unknown_field":5}', '[400,0,"Jane",null,["a"],1743682787123,"AQL/","NaN","9007199254740993","18446744073709551615",1,[2,5],["Antwerp"],[[1],[2,3]]]'], + ['user', '{"2":"Jane","1":"removed","99":1}', '[0,0,"Jane"]'], + ['user', '{"name":"Jane","user_id":0,"address":null}', '[0,0,"Jane"]'], + ['user', '[400,"removed","Jane",null,0,0,0,0,0,0,0,0,0,0,"extra"]', '[400,0,"Jane"]'], + ]; + + foreach ($vectors as [$type, $json, $expectedDenseJson]) { + yield "{$type} {$json}" => [$type, $json, $expectedDenseJson]; + } + } + + /** + * Upstream fromJson(denseJson) followed by toJsonCode(value, "dense") and toJsonCode(value, "readable"). + * + * @return iterable + */ + public static function encoding(): iterable + { + $vectors = [ + ['bool', '1', '1', 'true'], + ['bool', '0', '0', 'false'], + ['int32', '-5', '-5', '-5'], + ['int32', '0', '0', '0'], + ['int64', '42', '42', '42'], + ['int64', '"9007199254740993"', '"9007199254740993"', '"9007199254740993"'], + ['int64', '"-9007199254740993"', '"-9007199254740993"', '"-9007199254740993"'], + ['int64', '"9223372036854775807"', '"9223372036854775807"', '"9223372036854775807"'], + ['hash64', '"18446744073709551615"', '"18446744073709551615"', '"18446744073709551615"'], + ['hash64', '9007199254740991', '9007199254740991', '9007199254740991'], + ['hash64', '"9007199254740992"', '"9007199254740992"', '"9007199254740992"'], + ['float32', '1.5', '1.5', '1.5'], + ['float64', '0', '0', '0'], + ['float64', '-0', '0', '0'], + ['float64', '"NaN"', '"NaN"', '"NaN"'], + ['float64', '"Infinity"', '"Infinity"', '"Infinity"'], + ['float64', '"-Infinity"', '"-Infinity"', '"-Infinity"'], + ['float64', '1e21', '1e+21', '1e+21'], + ['float64', '1e20', '100000000000000000000', '100000000000000000000'], + ['float64', '1e-7', '1e-7', '1e-7'], + ['float64', '0.000001', '0.000001', '0.000001'], + ['float64', '123.456', '123.456', '123.456'], + ['float64', '5e-324', '5e-324', '5e-324'], + ['float64', '1.7976931348623157e308', '1.7976931348623157e+308', '1.7976931348623157e+308'], + ['float64', '0.30000000000000004', '0.30000000000000004', '0.30000000000000004'], + ['float64', '123456789012345680000', '123456789012345680000', '123456789012345680000'], + ['float64', '1.23e25', '1.23e+25', '1.23e+25'], + ['float64', '-1.5e-10', '-1.5e-10', '-1.5e-10'], + ['float64', '100', '100', '100'], + ['float64', '1e15', '1000000000000000', '1000000000000000'], + ['timestamp', '0', '0', '{ + "unix_millis": 0, + "formatted": "1970-01-01T00:00:00.000Z" +}'], + ['timestamp', '1743682787123', '1743682787123', '{ + "unix_millis": 1743682787123, + "formatted": "2025-04-03T12:19:47.123Z" +}'], + ['timestamp', '-1', '-1', '{ + "unix_millis": -1, + "formatted": "1969-12-31T23:59:59.999Z" +}'], + ['timestamp', '-62167219200000', '-62167219200000', '{ + "unix_millis": -62167219200000, + "formatted": "0000-01-01T00:00:00.000Z" +}'], + ['timestamp', '-62167219200001', '-62167219200001', '{ + "unix_millis": -62167219200001, + "formatted": "-000001-12-31T23:59:59.999Z" +}'], + ['timestamp', '253402300800000', '253402300800000', '{ + "unix_millis": 253402300800000, + "formatted": "+010000-01-01T00:00:00.000Z" +}'], + ['timestamp', '8640000000000000', '8640000000000000', '{ + "unix_millis": 8640000000000000, + "formatted": "+275760-09-13T00:00:00.000Z" +}'], + ['timestamp', '-8640000000000000', '-8640000000000000', '{ + "unix_millis": -8640000000000000, + "formatted": "-271821-04-20T00:00:00.000Z" +}'], + ['string', '"Hello"', '"Hello"', '"Hello"'], + ['string', '"h\\u00e9llo/ \\u2028 \\u0001\\u001f\\u007f \\"q\\" \\\\ \\t\\n\\b\\f\\r <&>\'"', '"héllo/ 
 \\u0001\\u001f \\"q\\" \\\\ \\t\\n\\b\\f\\r <&>\'"', '"héllo/ 
 \\u0001\\u001f \\"q\\" \\\\ \\t\\n\\b\\f\\r <&>\'"'], + ['string', '"\\ud83d\\ude00"', '"😀"', '"😀"'], + ['bytes', '"AQL/"', '"AQL/"', '"hex:0102ff"'], + ['bytes', '""', '""', '"hex:"'], + ['optionalString', 'null', 'null', 'null'], + ['optionalString', '"x"', '"x"', '"x"'], + ['matrix', '[[1,2],[],[3]]', '[[1,2],[],[3]]', '[ + [ + 1, + 2 + ], + [], + [ + 3 + ] +]'], + ['matrix', '[]', '[]', '[]'], + ['addresses', '[[],["x"]]', '[[],["x"]]', '[ + {}, + { + "city": "x" + } +]'], + ['address', '[]', '[]', '{}'], + ['status', '0', '0', '"unknown"'], + ['status', '1', '1', '"free"'], + ['status', '[2,1743682787000]', '[2,1743682787000]', '{ + "kind": "premium_since", + "value": { + "unix_millis": 1743682787000, + "formatted": "2025-04-03T12:19:47.000Z" + } +}'], + ['status', '[3,[]]', '[3,[]]', '{ + "kind": "trial", + "value": {} +}'], + ['status', '[3,["Paris"]]', '[3,["Paris"]]', '{ + "kind": "trial", + "value": { + "city": "Paris" + } +}'], + ['status', '[300,"s"]', '[300,"s"]', '{ + "kind": "big", + "value": "s" +}'], + ['user', '[]', '[]', '{}'], + ['user', '[0,0,"",null]', '[]', '{}'], + ['user', '[0,0,"",null,[],0,"","NaN"]', '[0,0,"",null,[],0,"","NaN"]', '{ + "score": "NaN" +}'], + ['user', '[0,0,"",null,[],0,"",-0]', '[]', '{}'], + ['user', '[400,0,"Jane","jj",["a","b/c"],1743682787123,"AQID",2.5,"9007199254740993","18446744073709551615",1,[2,1743682787000],["Antwerp"],[[1,2],[],[3]]]', '[400,0,"Jane","jj",["a","b/c"],1743682787123,"AQID",2.5,"9007199254740993","18446744073709551615",1,[2,1743682787000],["Antwerp"],[[1,2],[],[3]]]', '{ + "user_id": 400, + "name": "Jane", + "nickname": "jj", + "tags": [ + "a", + "b/c" + ], + "created_at": { + "unix_millis": 1743682787123, + "formatted": "2025-04-03T12:19:47.123Z" + }, + "avatar": "hex:010203", + "score": 2.5, + "big": "9007199254740993", + "hash": "18446744073709551615", + "active": true, + "status": { + "kind": "premium_since", + "value": { + "unix_millis": 1743682787000, + "formatted": "2025-04-03T12:19:47.000Z" + } + }, + "address": { + "city": "Antwerp" + }, + "matrix": [ + [ + 1, + 2 + ], + [], + [ + 3 + ] + ] +}'], + ]; + + foreach ($vectors as [$type, $denseJson, $expectedDenseJson, $expectedReadableJson]) { + yield "{$type} {$denseJson}" => [$type, $denseJson, $expectedDenseJson, $expectedReadableJson]; + } + } +} From bdc083b212d3829ebf43881838e823917f89deeb Mon Sep 17 00:00:00 2001 From: Maxim Kerstens Date: Mon, 9 Nov 2026 11:26:57 +0100 Subject: [PATCH 2/3] Add Skir binary format Add BinaryFormat::encode() and BinaryFormat::decode(), byte-for-byte compatible with the upstream skir-client toBytes() and fromBytes(), including the "skir" header, the variable-length number wires, the UTF-16 based string length prefix sizing, struct slot trimming and skipping of unrecognized struct slots and enum payloads. Expected bytes in the tests were generated with the upstream skir-client package. --- README.md | 16 + src/BinaryFormat.php | 536 ++++++++++++++++++++++++ src/Exceptions/SkirRuntimeException.php | 5 + src/Internal/BinaryReader.php | 60 +++ tests/BinaryFormatTest.php | 107 +++++ tests/UpstreamVectors.php | 153 +++++++ 6 files changed, 877 insertions(+) create mode 100644 src/BinaryFormat.php create mode 100644 src/Internal/BinaryReader.php create mode 100644 tests/BinaryFormatTest.php diff --git a/README.md b/README.md index 61f106e..31d73ad 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ composer require php-skir/runtime - `DenseJson` for encoding Skir dense JSON values and decoding JSON values of either flavor. - `ReadableJson` for encoding Skir readable JSON values. +- `BinaryFormat` for encoding and decoding the Skir binary format. - `Type`, `Field`, and `Variant` descriptors for generated DTO metadata. - `EnumValue` for Skir enum constants and wrapper variants. - `MethodDescriptor` for generated SkirRPC method metadata. @@ -70,6 +71,21 @@ The readable flavor matches upstream `toJsonCode(value, "readable")`: structs be `ReadableJson::encode()` returns the JSON-compatible PHP value. A struct whose fields all hold their default value is returned as an empty `stdClass` so it still encodes as `{}`. +## Binary format + +```php +use Skir\Runtime\BinaryFormat; + +$bytes = BinaryFormat::encode($user, [ + 'id' => 1, + 'name' => 'Jane', +]); + +$data = BinaryFormat::decode($user, $bytes); +``` + +The output is byte-for-byte identical to upstream `toBytes()`, including the leading `skir` header, and `decode()` accepts anything upstream `fromBytes()` accepts. + ## Current scope This runtime does not register routes, discover procedures, or make HTTP calls. Those concerns belong in the `php-skir/server` and `php-skir/client` packages. diff --git a/src/BinaryFormat.php b/src/BinaryFormat.php new file mode 100644 index 0000000..5232b6d --- /dev/null +++ b/src/BinaryFormat.php @@ -0,0 +1,536 @@ +remaining() !== 0) { + throw SkirRuntimeException::invalidBinary('Trailing or truncated binary data'); + } + + return $value; + } + + private static function encodeValue(Type $type, mixed $value): string + { + return match ($type->kind) { + TypeKind::Bool => $value ? "\x01" : "\x00", + TypeKind::Int32 => self::encodeInt32(Numbers::toInt32($value)), + TypeKind::Int64 => self::encodeInt64(LargeInteger::clampInt64(LargeInteger::normalize($value))), + TypeKind::Hash64 => self::encodeHash64(LargeInteger::clampHash64(LargeInteger::normalize($value))), + TypeKind::Float32 => self::encodeFloat((float) $value, 240, 'g', self::FLOAT32_NAN), + TypeKind::Float64 => self::encodeFloat((float) $value, 241, 'e', self::FLOAT64_NAN), + TypeKind::Timestamp => self::encodeTimestamp(Numbers::timestampMillis($value)), + TypeKind::String => self::encodeString((string) $value), + TypeKind::Bytes => self::encodeBytes((string) $value), + TypeKind::Optional => $value === null ? "\xff" : self::encodeValue(TypeValues::itemType($type), $value), + TypeKind::Array => self::encodeArray($type, $value), + TypeKind::Struct => self::encodeStruct($type, TypeValues::requireStructValue($value)), + TypeKind::Enum => self::encodeEnum($type, $value), + }; + } + + private static function decodeValue(Type $type, BinaryReader $reader): mixed + { + return match ($type->kind) { + TypeKind::Bool => self::decodeBool(self::decodeNumber($reader)), + TypeKind::Int32 => Numbers::toInt32(self::decodeNumber($reader)), + TypeKind::Int64, TypeKind::Hash64 => self::decodeLargeInteger(self::decodeNumber($reader)), + TypeKind::Float32, TypeKind::Float64 => (float) Numbers::toNumber(self::decodeNumber($reader)), + TypeKind::Timestamp => Numbers::timestampMillis(self::decodeNumber($reader)), + TypeKind::String => self::decodeString($reader), + TypeKind::Bytes => self::decodeBytes($reader), + TypeKind::Optional => self::decodeOptional($type, $reader), + TypeKind::Array => self::decodeArray($type, $reader), + TypeKind::Struct => self::decodeStruct($type, $reader), + TypeKind::Enum => self::decodeEnum($type, $reader), + }; + } + + private static function encodeInt32(int $value): string + { + if ($value < -65_536) { + return "\xed".pack('V', $value); + } + + if ($value < -256) { + return "\xec".pack('v', $value + 65_536); + } + + if ($value < 0) { + return "\xeb".chr($value + 256); + } + + return self::encodeUint32($value); + } + + private static function encodeInt64(int $value): string + { + if ($value < -2_147_483_648) { + return "\xee".pack('P', $value); + } + + if ($value > 2_147_483_647) { + return "\xee".pack('P', $value); + } + + return self::encodeInt32($value); + } + + private static function encodeHash64(int|string $value): string + { + if (is_string($value)) { + return "\xea".pack('P', LargeInteger::hash64Bits($value)); + } + + if ($value >= 4_294_967_296) { + return "\xea".pack('P', $value); + } + + return self::encodeUint32($value); + } + + private static function encodeUint32(int $value): string + { + if ($value < 232) { + return chr($value); + } + + if ($value < 65_536) { + return "\xe8".pack('v', $value); + } + + if ($value < 4_294_967_296) { + return "\xe9".pack('V', $value); + } + + throw SkirRuntimeException::invalidValue("Skir binary lengths and variant numbers must be below 2^32, got [{$value}]."); + } + + private static function encodeFloat(float $value, int $wire, string $packFormat, string $nanBytes): string + { + if ($value === 0.0) { + return "\x00"; + } + + if (is_nan($value)) { + return chr($wire).$nanBytes; + } + + return chr($wire).pack($packFormat, $value); + } + + private static function encodeTimestamp(int $unixMillis): string + { + if ($unixMillis === 0) { + return "\x00"; + } + + return "\xef".pack('P', $unixMillis); + } + + /** + * Upstream sizes the length prefix from the worst-case UTF-8 length of the + * UTF-16 string (3 bytes per code unit), not from the actual length. + */ + private static function encodeString(string $value): string + { + if ($value === '') { + return "\xf2"; + } + + if (preg_match('//u', $value) !== 1) { + throw SkirRuntimeException::invalidValue('Skir string values must be valid UTF-8.'); + } + + $maxEncodedLength = self::utf16Length($value) * 3; + $length = strlen($value); + + $lengthPrefix = match (true) { + $maxEncodedLength < 232 => chr($length), + $maxEncodedLength < 65_536 => "\xe8".pack('v', $length), + default => "\xe9".pack('V', $length), + }; + + return "\xf3{$lengthPrefix}{$value}"; + } + + private static function utf16Length(string $utf8): int + { + $continuationBytes = preg_match_all('/[\x80-\xBF]/', $utf8); + $fourByteSequences = preg_match_all('/[\xF0-\xF7]/', $utf8); + + return strlen($utf8) - $continuationBytes + $fourByteSequences; + } + + private static function encodeBytes(string $value): string + { + if ($value === '') { + return "\xf4"; + } + + return "\xf5".self::encodeUint32(strlen($value)).$value; + } + + private static function encodeArrayLength(int $length): string + { + if ($length <= 3) { + return chr(246 + $length); + } + + return "\xfa".self::encodeUint32($length); + } + + private static function encodeArray(Type $type, mixed $value): string + { + if (! is_array($value)) { + throw SkirRuntimeException::invalidValue('Skir array values must be PHP arrays.'); + } + + $itemType = TypeValues::itemType($type); + $encoded = self::encodeArrayLength(count($value)); + + foreach ($value as $item) { + $encoded .= self::encodeValue($itemType, $item); + } + + return $encoded; + } + + /** + * @param array $value + */ + private static function encodeStruct(Type $type, array $value): string + { + $slotCount = TypeValues::structSlotCount($type, $value); + $encoded = self::encodeArrayLength($slotCount); + + for ($number = 0; $number < $slotCount; $number++) { + $field = TypeValues::fieldWithKey($type, $number); + + $encoded .= $field === null + ? "\x00" + : self::encodeValue(TypeValues::fieldType($field), TypeValues::fieldValue($field, $value)); + } + + return $encoded; + } + + private static function encodeEnum(Type $type, mixed $value): string + { + if (! $value instanceof EnumValue) { + throw SkirRuntimeException::invalidValue('Skir enum values must be EnumValue instances.'); + } + + if ($value->name === TypeValues::UNKNOWN_VARIANT) { + return "\x00"; + } + + $variant = TypeValues::variantWithName($type, $value->name); + + if (! $value->wrapper) { + return self::encodeUint32($variant->number); + } + + if (! $variant->isWrapper()) { + throw SkirRuntimeException::invalidValue("Skir enum variant [{$value->name}] does not carry a payload."); + } + + $header = $variant->number < 5 + ? chr(250 + $variant->number) + : "\xf8".self::encodeUint32($variant->number); + + return $header.self::encodeValue($variant->payloadType, $value->value); + } + + /** + * Returns an int, a float, or a decimal string for unsigned 64-bit values above PHP_INT_MAX. + */ + private static function decodeNumber(BinaryReader $reader): int|float|string + { + $wire = $reader->readUint8(); + + return match (true) { + $wire < 232 => $wire, + $wire === 232 => $reader->readFormatted('v', 2), + $wire === 233 => $reader->readFormatted('V', 4), + $wire === 234 => LargeInteger::fromUnsignedBits($reader->readFormatted('P', 8)), + $wire === 235 => $reader->readUint8() - 256, + $wire === 236 => $reader->readFormatted('v', 2) - 65_536, + $wire === 237 => Numbers::toInt32($reader->readFormatted('V', 4)), + $wire === 238, $wire === 239 => $reader->readFormatted('P', 8), + $wire === 240 => $reader->readFormatted('g', 4), + $wire === 241 => $reader->readFormatted('e', 8), + default => throw SkirRuntimeException::invalidBinary("Invalid numeric wire tag: {$wire}"), + }; + } + + private static function decodeUint32(BinaryReader $reader): int + { + $wire = $reader->peekUint8(); + + if ($wire > 233) { + throw SkirRuntimeException::invalidBinary("Invalid unsigned length or variant tag: {$wire}"); + } + + return self::decodeNumber($reader); + } + + private static function decodeArrayLength(int $wire, BinaryReader $reader): int + { + if ($wire < 246) { + throw SkirRuntimeException::invalidBinary("Invalid array wire tag: {$wire}"); + } + + if ($wire > 250) { + throw SkirRuntimeException::invalidBinary("Invalid array wire tag: {$wire}"); + } + + $length = $wire === 250 ? self::decodeUint32($reader) : $wire - 246; + + if ($length > $reader->remaining()) { + throw SkirRuntimeException::invalidBinary('Truncated binary array'); + } + + return $length; + } + + private static function decodeBool(int|float|string $number): bool + { + if (is_float($number)) { + return ! is_nan($number) && $number !== 0.0; + } + + return $number !== 0; + } + + private static function decodeLargeInteger(int|float|string $number): int|string + { + if (is_float($number)) { + return LargeInteger::fromFloat($number); + } + + return $number; + } + + private static function decodeString(BinaryReader $reader): string + { + $wire = $reader->readUint8(); + + if ($wire === 0) { + return ''; + } + + if ($wire === 242) { + return ''; + } + + if ($wire !== 243) { + throw SkirRuntimeException::invalidBinary("Invalid string wire tag: {$wire}"); + } + + $value = $reader->read(self::decodeUint32($reader)); + + if (preg_match('//u', $value) !== 1) { + throw SkirRuntimeException::invalidBinary('Skir string values must be valid UTF-8.'); + } + + return $value; + } + + private static function decodeBytes(BinaryReader $reader): string + { + $wire = $reader->readUint8(); + + if ($wire === 0) { + return ''; + } + + if ($wire === 244) { + return ''; + } + + if ($wire !== 245) { + throw SkirRuntimeException::invalidBinary("Invalid bytes wire tag: {$wire}"); + } + + return $reader->read(self::decodeUint32($reader)); + } + + private static function decodeOptional(Type $type, BinaryReader $reader): mixed + { + if ($reader->peekUint8() === 255) { + $reader->readUint8(); + + return null; + } + + return self::decodeValue(TypeValues::itemType($type), $reader); + } + + /** + * @return array + */ + private static function decodeArray(Type $type, BinaryReader $reader): array + { + $wire = $reader->readUint8(); + + if ($wire === 0) { + return []; + } + + $length = self::decodeArrayLength($wire, $reader); + $itemType = TypeValues::itemType($type); + $items = []; + + for ($index = 0; $index < $length; $index++) { + $items[] = self::decodeValue($itemType, $reader); + } + + return $items; + } + + /** + * @return array + */ + private static function decodeStruct(Type $type, BinaryReader $reader): array + { + $decoded = TypeValues::defaultValue($type); + $wire = $reader->readUint8(); + + if ($wire === 0) { + return $decoded; + } + + $slotCount = self::decodeArrayLength($wire, $reader); + + for ($number = 0; $number < $slotCount; $number++) { + $field = TypeValues::fieldWithKey($type, $number); + + if ($field === null) { + self::skipValue($reader); + + continue; + } + + $decoded[$field->name] = self::decodeValue(TypeValues::fieldType($field), $reader); + } + + return $decoded; + } + + private static function decodeEnum(Type $type, BinaryReader $reader): EnumValue + { + $wire = $reader->peekUint8(); + + if ($wire < 242) { + return self::decodeEnumConstant($type, self::decodeUint32($reader)); + } + + $reader->readUint8(); + + if ($wire === 248) { + return self::decodeEnumWrapper($type, self::decodeUint32($reader), $reader); + } + + if ($wire < 251) { + throw SkirRuntimeException::invalidBinary("Invalid enum wire tag: {$wire}"); + } + + if ($wire > 254) { + throw SkirRuntimeException::invalidBinary("Invalid enum wire tag: {$wire}"); + } + + return self::decodeEnumWrapper($type, $wire - 250, $reader); + } + + private static function decodeEnumConstant(Type $type, int $number): EnumValue + { + $variant = TypeValues::variantWithNumber($type, $number); + + if ($variant === null) { + return EnumValue::constant(TypeValues::UNKNOWN_VARIANT); + } + + if ($variant->isWrapper()) { + return EnumValue::wrapper($variant->name, TypeValues::defaultValue($variant->payloadType)); + } + + return EnumValue::constant($variant->name); + } + + private static function decodeEnumWrapper(Type $type, int $number, BinaryReader $reader): EnumValue + { + $variant = TypeValues::variantWithNumber($type, $number); + + if ($variant === null) { + self::skipValue($reader); + + return EnumValue::constant(TypeValues::UNKNOWN_VARIANT); + } + + if (! $variant->isWrapper()) { + self::skipValue($reader); + + return EnumValue::constant($variant->name); + } + + return EnumValue::wrapper($variant->name, self::decodeValue($variant->payloadType, $reader)); + } + + private static function skipValue(BinaryReader $reader): void + { + $wire = $reader->readUint8(); + + match ($wire) { + 232, 236 => $reader->read(2), + 233, 237, 240 => $reader->read(4), + 234, 238, 239, 241 => $reader->read(8), + 235 => $reader->read(1), + 243, 245 => $reader->read(self::decodeUint32($reader)), + 247, 251, 252, 253, 254 => self::skipValues($reader, 1), + 248 => self::skipValues($reader, 2), + 249 => self::skipValues($reader, 3), + 250 => self::skipValues($reader, self::decodeArrayLength($wire, $reader)), + default => null, + }; + } + + private static function skipValues(BinaryReader $reader, int $count): void + { + for ($index = 0; $index < $count; $index++) { + self::skipValue($reader); + } + } +} diff --git a/src/Exceptions/SkirRuntimeException.php b/src/Exceptions/SkirRuntimeException.php index 7205a04..da4d191 100644 --- a/src/Exceptions/SkirRuntimeException.php +++ b/src/Exceptions/SkirRuntimeException.php @@ -19,6 +19,11 @@ public static function invalidReadableJson(string $message, ?Throwable $previous return new self("Invalid readable JSON: {$message}", previous: $previous); } + public static function invalidBinary(string $message): self + { + return new self("Invalid Skir binary data: {$message}"); + } + public static function invalidValue(string $message): self { return new self($message); diff --git a/src/Internal/BinaryReader.php b/src/Internal/BinaryReader.php new file mode 100644 index 0000000..2517936 --- /dev/null +++ b/src/Internal/BinaryReader.php @@ -0,0 +1,60 @@ +requireAvailable(1); + + return ord($this->bytes[$this->offset]); + } + + public function readUint8(): int + { + $byte = $this->peekUint8(); + $this->offset++; + + return $byte; + } + + public function read(int $length): string + { + $this->requireAvailable($length); + $bytes = substr($this->bytes, $this->offset, $length); + $this->offset += $length; + + return $bytes; + } + + /** + * @return int|float + */ + public function readFormatted(string $unpackFormat, int $length): mixed + { + return unpack($unpackFormat, $this->read($length))[1]; + } + + public function remaining(): int + { + return strlen($this->bytes) - $this->offset; + } + + private function requireAvailable(int $length): void + { + if ($length > $this->remaining()) { + throw SkirRuntimeException::invalidBinary('Truncated binary payload'); + } + } +} diff --git a/tests/BinaryFormatTest.php b/tests/BinaryFormatTest.php new file mode 100644 index 0000000..0b020ce --- /dev/null +++ b/tests/BinaryFormatTest.php @@ -0,0 +1,107 @@ +assertSame($expectedHex, bin2hex($bytes)); + } + + #[DataProviderExternal(UpstreamVectors::class, 'binaryEncoding')] + public function test_it_round_trips_upstream_bytes(string $type, string $denseJson, string $expectedHex): void + { + $skirType = UpstreamVectors::type($type); + + $decoded = BinaryFormat::decode($skirType, (string) hex2bin($expectedHex)); + + $this->assertSame($expectedHex, bin2hex(BinaryFormat::encode($skirType, $decoded))); + } + + #[DataProviderExternal(UpstreamVectors::class, 'binaryDecoding')] + public function test_it_decodes_like_upstream(string $type, string $hex, string $expected): void + { + $skirType = UpstreamVectors::type($type); + + if (str_starts_with($expected, 'THROWS ')) { + $this->expectException(SkirRuntimeException::class); + $this->expectExceptionMessage(substr($expected, strlen('THROWS '))); + } + + $decoded = BinaryFormat::decode($skirType, (string) hex2bin($hex)); + + $this->assertSame($expected, DenseJson::toJson($skirType, $decoded)); + } + + public function test_it_sizes_string_length_prefixes_from_the_utf16_length_like_upstream(): void + { + $this->assertStringStartsWith('736b6972f3e855557878', bin2hex(BinaryFormat::encode(Type::string(), str_repeat('x', 21_845)))); + $this->assertStringStartsWith('736b6972f3e956550000', bin2hex(BinaryFormat::encode(Type::string(), str_repeat('x', 21_846)))); + } + + public function test_it_round_trips_php_values(): void + { + $user = UpstreamVectors::user(); + $value = DenseJson::fromJson($user, '[400,0,"Jane","jj",["a"],1743682787123,"AQID",2.5,"9007199254740993","18446744073709551615",1,[2,1743682787000],["Antwerp"],[[1,2],[],[3]]]'); + + $this->assertEquals($value, BinaryFormat::decode($user, BinaryFormat::encode($user, $value))); + $this->assertEquals( + EnumValue::wrapper('big', 's'), + BinaryFormat::decode(UpstreamVectors::status(), BinaryFormat::encode(UpstreamVectors::status(), EnumValue::wrapper('big', 's'))), + ); + } + + #[DataProvider('invalidBinaryPayloads')] + public function test_it_rejects_invalid_binary_payloads(string $type, string $hex, string $message): void + { + $this->expectException(SkirRuntimeException::class); + $this->expectExceptionMessage($message); + + BinaryFormat::decode(UpstreamVectors::type($type), (string) hex2bin($hex)); + } + + /** + * @return iterable + */ + public static function invalidBinaryPayloads(): iterable + { + yield 'empty payload' => ['bool', '', 'Invalid skir binary header']; + yield 'wrong header' => ['bool', '736b6971', 'Invalid skir binary header']; + yield 'header only' => ['bool', '736b6972', 'Truncated binary payload']; + yield 'trailing data' => ['bool', '736b69720000', 'Trailing or truncated binary data']; + yield 'string wire for a number' => ['bool', '736b6972f2', 'Invalid numeric wire tag: 242']; + yield 'truncated string' => ['string', '736b6972f305', 'Truncated binary payload']; + yield 'number wire for a string' => ['string', '736b6972f1', 'Invalid string wire tag: 241']; + yield 'truncated array' => ['matrix', '736b6972fa05', 'Truncated binary array']; + yield 'array wire for an enum' => ['status', '736b6972f9', 'Invalid enum wire tag: 249']; + yield 'hash wire for an enum number' => ['status', '736b6972ea', 'Invalid unsigned length or variant tag: 234']; + yield 'string wire for bytes' => ['bytes', '736b6972f3', 'Invalid bytes wire tag: 243']; + yield 'truncated number' => ['int32', '736b6972e8', 'Truncated binary payload']; + yield 'invalid utf-8' => ['string', '736b6972f301ff', 'Skir string values must be valid UTF-8.']; + } + + public function test_it_rejects_invalid_utf8_strings_when_encoding(): void + { + $this->expectException(SkirRuntimeException::class); + $this->expectExceptionMessage('Skir string values must be valid UTF-8.'); + + BinaryFormat::encode(Type::string(), "\xB1\x31"); + } +} diff --git a/tests/UpstreamVectors.php b/tests/UpstreamVectors.php index 6de07b2..455a6f5 100644 --- a/tests/UpstreamVectors.php +++ b/tests/UpstreamVectors.php @@ -384,4 +384,157 @@ public static function encoding(): iterable yield "{$type} {$denseJson}" => [$type, $denseJson, $expectedDenseJson, $expectedReadableJson]; } } + + /** + * Upstream fromJson(denseJson) followed by toBytes(value), as hex. + * + * @return iterable + */ + public static function binaryEncoding(): iterable + { + $vectors = [ + ['bool', '1', '736b697201'], + ['bool', '0', '736b697200'], + ['int32', '0', '736b697200'], + ['int32', '1', '736b697201'], + ['int32', '231', '736b6972e7'], + ['int32', '232', '736b6972e8e800'], + ['int32', '65535', '736b6972e8ffff'], + ['int32', '65536', '736b6972e900000100'], + ['int32', '2147483647', '736b6972e9ffffff7f'], + ['int32', '-1', '736b6972ebff'], + ['int32', '-256', '736b6972eb00'], + ['int32', '-257', '736b6972ecfffe'], + ['int32', '-65536', '736b6972ec0000'], + ['int32', '-65537', '736b6972edfffffeff'], + ['int32', '-2147483648', '736b6972ed00000080'], + ['int64', '0', '736b697200'], + ['int64', '5', '736b697205'], + ['int64', '2147483647', '736b6972e9ffffff7f'], + ['int64', '2147483648', '736b6972ee0000008000000000'], + ['int64', '-2147483648', '736b6972ed00000080'], + ['int64', '-2147483649', '736b6972eeffffff7fffffffff'], + ['int64', '"9223372036854775807"', '736b6972eeffffffffffffff7f'], + ['int64', '"-9223372036854775808"', '736b6972ee0000000000000080'], + ['int64', '"9007199254740993"', '736b6972ee0100000000002000'], + ['hash64', '0', '736b697200'], + ['hash64', '231', '736b6972e7'], + ['hash64', '232', '736b6972e8e800'], + ['hash64', '65536', '736b6972e900000100'], + ['hash64', '4294967295', '736b6972e9ffffffff'], + ['hash64', '4294967296', '736b6972ea0000000001000000'], + ['hash64', '"9223372036854775808"', '736b6972ea0000000000000080'], + ['hash64', '"18446744073709551615"', '736b6972eaffffffffffffffff'], + ['float32', '0', '736b697200'], + ['float32', '1.5', '736b6972f00000c03f'], + ['float32', '1.1', '736b6972f0cdcc8c3f'], + ['float32', '"NaN"', '736b6972f00000c07f'], + ['float32', '"-Infinity"', '736b6972f0000080ff'], + ['float64', '0', '736b697200'], + ['float64', '-0', '736b697200'], + ['float64', '1.5', '736b6972f1000000000000f83f'], + ['float64', '"NaN"', '736b6972f1000000000000f87f'], + ['float64', '"Infinity"', '736b6972f1000000000000f07f'], + ['float64', '1e300', '736b6972f19c7500883ce4377e'], + ['timestamp', '0', '736b697200'], + ['timestamp', '1743682787123', '736b6972ef33d797fb95010000'], + ['timestamp', '-1', '736b6972efffffffffffffffff'], + ['timestamp', '8640000000000000', '736b6972ef0000dcc208b21e00'], + ['string', '""', '736b6972f2'], + ['string', '"Hello"', '736b6972f30548656c6c6f'], + ['string', '"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"', '736b6972f34d6161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161'], + ['string', '"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"', '736b6972f3e84e00616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161'], + ['string', '"éééééééééééééééééééééééééééééééééééééééé"', '736b6972f350c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9'], + ['string', '"\\ud83d\\ude00"', '736b6972f304f09f9880'], + ['bytes', '""', '736b6972f4'], + ['bytes', '"AQL/"', '736b6972f5030102ff'], + ['optionalString', 'null', '736b6972ff'], + ['optionalString', '""', '736b6972f2'], + ['optionalString', '"x"', '736b6972f30178'], + ['matrix', '[]', '736b6972f6'], + ['matrix', '[[1,2],[],[3]]', '736b6972f9f80102f6f703'], + ['matrix', '[[],[],[],[]]', '736b6972fa04f6f6f6f6'], + ['address', '[]', '736b6972f6'], + ['address', '["Antwerp"]', '736b6972f7f307416e7477657270'], + ['addresses', '[[],["x"]]', '736b6972f8f6f7f30178'], + ['status', '0', '736b697200'], + ['status', '1', '736b697201'], + ['status', '[2,1743682787000]', '736b6972fcefb8d697fb95010000'], + ['status', '[3,[]]', '736b6972fdf6'], + ['status', '[3,["Paris"]]', '736b6972fdf7f3055061726973'], + ['status', '[300,"s"]', '736b6972f8e82c01f30173'], + ['user', '[]', '736b6972f6'], + ['user', '[400,0,"Jane"]', '736b6972f9e8900100f3044a616e65'], + ['user', '[0,0,"",null,[],0,"","NaN"]', '736b6972fa080000f2fff600f4f1000000000000f87f'], + ['user', '[400,0,"Jane","jj",["a","b/c"],1743682787123,"AQID",2.5,"9007199254740993","18446744073709551615",1,[2,1743682787000],["Antwerp"],[[1,2],[],[3]]]', '736b6972fa0ee8900100f3044a616e65f3026a6af8f30161f303622f63ef33d797fb95010000f503010203f10000000000000440ee0100000000002000eaffffffffffffffff01fcefb8d697fb95010000f7f307416e7477657270f9f80102f6f703'], + ]; + + foreach ($vectors as [$type, $denseJson, $expectedHex]) { + yield "{$type} {$denseJson}" => [$type, $denseJson, $expectedHex]; + } + } + + /** + * Upstream fromBytes(bytes) followed by toJson(value, "dense"), or the error upstream throws. + * + * @return iterable + */ + public static function binaryDecoding(): iterable + { + $vectors = [ + ['bool', '736b697200', '0'], + ['bool', '736b697201', '1'], + ['bool', '736b6972e80100', '1'], + ['bool', '736b6972f00000c07f', '0'], + ['bool', '736b6972eb00', '1'], + ['int32', '736b6972ea0000000001000000', '0'], + ['int32', '736b6972f00000c03f', '1'], + ['int32', '736b6972f1cdcccccccccc0440', '2'], + ['int32', '736b6972ee0100000001000000', '1'], + ['int64', '736b6972eaffffffffffffffff', '"9223372036854775807"'], + ['int64', '736b6972f1000000000000f83f', '2'], + ['int64', '736b6972ed00000080', '-2147483648'], + ['hash64', '736b6972eeffffffffffffffff', '0'], + ['hash64', '736b6972eaffffffffffffffff', '"18446744073709551615"'], + ['float64', '736b697205', '5'], + ['float64', '736b6972ee0100000000000000', '1'], + ['float64', '736b6972eaffffffffffffffff', '18446744073709552000'], + ['timestamp', '736b6972e9ffffffff', '4294967295'], + ['timestamp', '736b6972eeffffffffffffff7f', '8640000000000000'], + ['timestamp', '736b6972f1000000000000f83f', '2'], + ['string', '736b697200', '""'], + ['string', '736b6972f2', '""'], + ['string', '736b6972f30161', '"a"'], + ['bytes', '736b697200', '""'], + ['bytes', '736b6972f4', '""'], + ['bytes', '736b6972f50201ff', '"Af8="'], + ['optionalString', '736b6972ff', 'null'], + ['optionalString', '736b697200', '""'], + ['optionalString', '736b6972f30161', '"a"'], + ['matrix', '736b697200', '[]'], + ['matrix', '736b6972f6', '[]'], + ['matrix', '736b6972f7f80102', '[[1,2]]'], + ['status', '736b697200', '0'], + ['status', '736b697201', '1'], + ['status', '736b697202', '[2,0]'], + ['status', '736b697263', '0'], + ['status', '736b6972fc05', '[2,5]'], + ['status', '736b6972fb05', '1'], + ['status', '736b6972fdf7f30158', '[3,["X"]]'], + ['status', '736b6972fef3016b', '0'], + ['status', '736b6972f8e82c01f30173', '[300,"s"]'], + ['status', '736b6972f863f30173', '0'], + ['status', '736b6972fdf7', 'THROWS Truncated binary array'], + ['address', '736b697200', '[]'], + ['address', '736b6972f6', '[]'], + ['address', '736b6972f7f30158', '["X"]'], + ['address', '736b6972fa04f30158f9010203eaffffffffffffffff05', '["X"]'], + ['user', '736b6972f9e99001000001f30158', '[400,0,"X"]'], + ['user', '736b6972f9e990010000f9010203f30158', '[400,0,"X"]'], + ]; + + foreach ($vectors as [$type, $hex, $expected]) { + yield "{$type} {$hex}" => [$type, $hex, $expected]; + } + } } From 2bbc248f0761473a736e0f49b47dbd432359e484 Mon Sep 17 00:00:00 2001 From: Maxim Kerstens Date: Mon, 9 Nov 2026 11:31:53 +0100 Subject: [PATCH 3/3] Reject non-string values for string and bytes types Encoding cast them with (string), turning arrays into a PHP warning instead of a SkirRuntimeException. --- src/BinaryFormat.php | 4 ++-- src/Internal/JsonCodec.php | 4 ++-- src/Internal/TypeValues.php | 16 +++++++++++++++- tests/DenseJsonTest.php | 12 ++++++++++++ 4 files changed, 31 insertions(+), 5 deletions(-) diff --git a/src/BinaryFormat.php b/src/BinaryFormat.php index 5232b6d..3460498 100644 --- a/src/BinaryFormat.php +++ b/src/BinaryFormat.php @@ -52,8 +52,8 @@ private static function encodeValue(Type $type, mixed $value): string TypeKind::Float32 => self::encodeFloat((float) $value, 240, 'g', self::FLOAT32_NAN), TypeKind::Float64 => self::encodeFloat((float) $value, 241, 'e', self::FLOAT64_NAN), TypeKind::Timestamp => self::encodeTimestamp(Numbers::timestampMillis($value)), - TypeKind::String => self::encodeString((string) $value), - TypeKind::Bytes => self::encodeBytes((string) $value), + TypeKind::String => self::encodeString(TypeValues::requireString($value)), + TypeKind::Bytes => self::encodeBytes(TypeValues::requireString($value)), TypeKind::Optional => $value === null ? "\xff" : self::encodeValue(TypeValues::itemType($type), $value), TypeKind::Array => self::encodeArray($type, $value), TypeKind::Struct => self::encodeStruct($type, TypeValues::requireStructValue($value)), diff --git a/src/Internal/JsonCodec.php b/src/Internal/JsonCodec.php index d886e29..38a5887 100644 --- a/src/Internal/JsonCodec.php +++ b/src/Internal/JsonCodec.php @@ -28,8 +28,8 @@ public static function encode(Type $type, mixed $value, JsonFlavor $flavor): mix TypeKind::Hash64 => LargeInteger::hash64ToJson($value), TypeKind::Float32, TypeKind::Float64 => self::encodeFloat((float) $value), TypeKind::Timestamp => self::encodeTimestamp(Numbers::timestampMillis($value), $flavor), - TypeKind::String => (string) $value, - TypeKind::Bytes => self::encodeBytes((string) $value, $flavor), + TypeKind::String => TypeValues::requireString($value), + TypeKind::Bytes => self::encodeBytes(TypeValues::requireString($value), $flavor), TypeKind::Optional => $value === null ? null : self::encode(TypeValues::itemType($type), $value, $flavor), TypeKind::Array => self::encodeArray($type, $value, $flavor), TypeKind::Struct => $flavor === JsonFlavor::Readable diff --git a/src/Internal/TypeValues.php b/src/Internal/TypeValues.php index 087c359..bdd3ed4 100644 --- a/src/Internal/TypeValues.php +++ b/src/Internal/TypeValues.php @@ -10,6 +10,7 @@ use Skir\Runtime\Type; use Skir\Runtime\TypeKind; use Skir\Runtime\Variant; +use Stringable; /** * Format-independent knowledge about Skir types shared by every serializer. @@ -34,6 +35,19 @@ public static function defaultValue(Type $type): mixed }; } + public static function requireString(mixed $value): string + { + if (is_string($value)) { + return $value; + } + + if ($value instanceof Stringable) { + return (string) $value; + } + + throw SkirRuntimeException::invalidValue('Expected a string, got '.get_debug_type($value).'.'); + } + public static function isDefault(Type $type, mixed $value): bool { return match ($type->kind) { @@ -41,7 +55,7 @@ public static function isDefault(Type $type, mixed $value): bool TypeKind::Int32, TypeKind::Float32, TypeKind::Float64 => Numbers::isZero($value), TypeKind::Int64, TypeKind::Hash64 => LargeInteger::normalize($value) === 0, TypeKind::Timestamp => Numbers::timestampMillis($value) === 0, - TypeKind::String, TypeKind::Bytes => (string) $value === '', + TypeKind::String, TypeKind::Bytes => self::requireString($value) === '', TypeKind::Optional => $value === null, TypeKind::Array => $value === [], TypeKind::Struct => self::structSlotCount($type, self::requireStructValue($value)) === 0, diff --git a/tests/DenseJsonTest.php b/tests/DenseJsonTest.php index fc08a6e..b3b8fb2 100644 --- a/tests/DenseJsonTest.php +++ b/tests/DenseJsonTest.php @@ -336,4 +336,16 @@ public function test_it_rejects_invalid_dense_json_values(): void DenseJson::fromJson(Type::array(Type::string()), '"not-array"'); } + + public function test_it_rejects_non_string_values_for_string_and_bytes_types(): void + { + foreach ([Type::string(), Type::bytes()] as $type) { + try { + DenseJson::toJson($type, ['not', 'a', 'string']); + $this->fail('Expected a non-string value to be rejected.'); + } catch (SkirRuntimeException $exception) { + $this->assertSame('Expected a string, got array.', $exception->getMessage()); + } + } + } }