Skip to content

Add composer library /example snippets to make it easier for projects to automatically choose simdjson if supported #85

@TysonAndre

Description

@TysonAndre
// namespace goes here

/**
 * JSON decoder
 */
final class Decoder
{
    private static $simdjsonEnabled = false;

    public static function setAllowSimdjson(bool $allow): void
    {
        self::$simdjsonEnabled = $allow && self::hasWorkingSimdjson();
    }

    public static function hasWorkingSimdjson(): bool
    {
        return version_compare(phpversion('simdjson') ?: '0', '2.1.0', '>=') &&
             class_exists('SimdJsonException');
    }

    /**
     * JSON decodes the given json string $msg
     *
     * @throws JsonException
     */
    public static function jsonDecode(string $msg, bool $associative = false)
    {
        if (self::$simdjsonEnabled) {
            try {
                return simdjson_decode($msg, $associative);
            } catch (\Exception $e) {
                // Assume errors are rare and fall through, to return the exact same Error messages
            }
        }
        $decoded = \json_decode($msg, $associative);
        if (\json_last_error() !== \JSON_ERROR_NONE) {
            throw new \JsonException(\json_last_error_msg(), \json_last_error());  // requires symfony/polyfill-php73 before php 7.3
        }
        return $decoded;
    }
}

Decoder::setAllowSimdjson(true);
use ...\Decoder;
var_export(Decoder::jsonDecode('{"a":"b"}', true));

https://github.com/crazyxman/simdjson_php/tree/master/benchmark - for applications that work with long json strings, the extra method call would be worth it

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions