Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
TysonAndre opened this issue Oct 14, 2022 · 0 comments
Assignees

Comments

@TysonAndre
Copy link
Collaborator

// 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

@TysonAndre TysonAndre self-assigned this Oct 14, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant