[
  {
    "path": ".gitattributes",
    "content": "include/yyjson/* linguist-vendored\n"
  },
  {
    "path": ".github/actions/manylinux/action.yaml",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2024-2025)\n\nname: manylinux\n\ninputs:\n  arch:\n    required: true\n  interpreter:\n    required: true\n  features:\n    required: true\n  compatibility:\n    required: true\n\nruns:\n  using: \"composite\"\n  steps:\n\n    - name: Build and test\n      shell: bash\n      run: |\n        set -eou pipefail\n\n        mkdir dist\n\n        export PYTHON=\"${{ inputs.interpreter }}\"\n        if [[ \"${PYTHON}\" == *t ]]; then\n          export PYTHON_PACKAGE=\"$(echo ${PYTHON} | sed 's/.$//')-freethreading\"\n        else\n          export PYTHON_PACKAGE=\"${PYTHON}\"\n        fi\n\n        export TARGET=\"${{ inputs.arch }}-unknown-linux-gnu\"\n        export PATH=\"$PWD/.venv:$HOME/.cargo/bin:$PATH\"\n\n        ./script/install-fedora\n\n        source \"${VENV}/bin/activate\"\n\n        maturin build \\\n          --release \\\n          --strip \\\n          --features=\"${{ inputs.features }}\" \\\n          --compatibility=\"${{ inputs.compatibility }}\" \\\n          --interpreter=\"${PYTHON}\" \\\n          --target=\"${TARGET}\"\n\n        uv pip install ${CARGO_TARGET_DIR}/wheels/orjson*.whl\n\n        export PYTHONMALLOC=\"debug\"\n        pytest -v test\n        ./integration/run thread\n        ./integration/run http\n        ./integration/run init\n\n        cp ${CARGO_TARGET_DIR}/wheels/orjson*.whl dist\n"
  },
  {
    "path": ".github/workflows/artifact.yaml",
    "content": "# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2022-2026), messense (2022), Dominic LoBue (2022)\n\nname: artifact\non: push\nenv:\n  FORCE_COLOR: \"1\"\n  ORJSON_BUILD_FREETHREADED: \"1\"\n  PIP_DISABLE_PIP_VERSION_CHECK: \"1\"\n  RUST_TOOLCHAIN: \"nightly-2026-01-28\"\n  RUST_TOOLCHAIN_STABLE: \"1.89\"\n  UNSAFE_PYO3_BUILD_FREE_THREADED: \"1\"\n  UNSAFE_PYO3_SKIP_VERSION_CHECK: \"1\"\n  UV_LINK_MODE: \"copy\"\njobs:\n\n  sdist:\n    runs-on: ubuntu-24.04\n    timeout-minutes: 10\n    strategy:\n      fail-fast: false\n    steps:\n\n    - uses: actions/setup-python@v6\n      with:\n        python-version: \"3.14\"\n\n    - name: rustup stable\n      run: |\n        curl https://sh.rustup.rs -sSf | sh -s -- --default-toolchain \"${RUST_TOOLCHAIN_STABLE}\" -y\n        rustup default \"${RUST_TOOLCHAIN_STABLE}\"\n\n    - uses: actions/checkout@v6\n\n    - name: Cargo.toml and pyproject.toml version must match\n      run: ./script/check-version\n\n    - run: python3 -m pip install --user --upgrade pip \"maturin>=1.10,<2\" wheel\n\n    - name: Vendor dependencies\n      run: |\n        maturin build\n        cargo fetch\n        mkdir .cargo\n        cp ci/sdist.toml .cargo/config.toml\n        cargo vendor include/cargo --versioned-dirs\n\n    - run: maturin sdist --out=dist\n\n    - run: python3 -m pip install --user dist/orjson*.tar.gz\n      env:\n        CARGO_NET_OFFLINE: \"true\"\n\n    - run: python3 -m pip install --user -r test/requirements.txt -r integration/requirements.txt mypy\n\n    - run: pytest -v test\n      env:\n        PYTHONMALLOC: \"debug\"\n\n    - run: ./integration/run thread\n    - run: ./integration/run http\n    - run: ./integration/run init\n    - run: ./integration/run typestubs\n\n    - name: Store sdist\n      uses: actions/upload-artifact@v5\n      with:\n        name: orjson_sdist\n        path: dist\n        overwrite: true\n        retention-days: 1\n        if-no-files-found: \"error\"\n        compression-level: 0\n\n  manylinux:\n    name: \"manylinux_${{ matrix.arch.arch }}_${{ matrix.python.interpreter }}\"\n    runs-on: \"${{ matrix.arch.runner }}\"\n    container:\n      image: fedora:rawhide\n    timeout-minutes: 10\n    strategy:\n      fail-fast: false\n      matrix:\n        python: [\n          { interpreter: 'python3.14', compatibility: \"manylinux_2_17\", publish: true },\n          { interpreter: 'python3.13', compatibility: \"manylinux_2_17\", publish: true },\n          { interpreter: 'python3.12', compatibility: \"manylinux_2_17\", publish: true },\n          { interpreter: 'python3.11', compatibility: \"manylinux_2_17\", publish: true },\n          { interpreter: 'python3.10', compatibility: \"manylinux_2_17\", publish: true },\n        ]\n        arch: [\n          { runner: \"ubuntu-24.04\", arch: \"x86_64\", features: \"avx512\", },\n          { runner: \"ubuntu-24.04-arm\", arch: \"aarch64\", features: \"generic_simd\" },\n        ]\n    env:\n      CARGO_TARGET_DIR: \"/tmp/orjson\"\n      CC: \"clang\"\n      CFLAGS: \"-O2 -fstrict-aliasing -fno-plt -emit-llvm\"\n      LDFLAGS: \"-fuse-ld=lld -Wl,-plugin-opt=also-emit-llvm -Wl,--as-needed -Wl,-zrelro,-znow\"\n      RUSTFLAGS: \"-Z unstable-options -C panic=immediate-abort -C linker=clang -C link-arg=-fuse-ld=lld -C linker-plugin-lto -C link-arg=-Wl,-zrelro,-znow -Z mir-opt-level=4 -Z threads=4 -D warnings\"\n      VENV: \".venv\"\n    steps:\n\n      - name: CPU info\n        run: cat /proc/cpuinfo\n\n      - run: dnf install --setopt=install_weak_deps=false -y git-core\n\n      - uses: actions/checkout@v6\n\n      - name: Build and test\n        uses: ./.github/actions/manylinux\n        with:\n          arch: \"${{ matrix.arch.arch }}\"\n          interpreter: \"${{ matrix.python.interpreter }}\"\n          features: \"${{ matrix.arch.features }}\"\n          compatibility: \"${{ matrix.python.compatibility }}\"\n\n      - name: Store wheels\n        if: matrix.python.publish == true\n        uses: actions/upload-artifact@v5\n        with:\n          name: \"orjson_manylinux_${{ matrix.arch.arch }}_${{ matrix.python.interpreter }}_${{ matrix.python.compatibility }}\"\n          path: dist\n          overwrite: true\n          retention-days: 1\n\n      - name: Debug\n        env:\n          CARGO_TARGET_DIR: \"/tmp/orjson\"\n          PYTHON: \"${{ matrix.python.interpreter }}\"\n          TARGET: \"${{ matrix.arch.arch }}-unknown-linux-gnu\"\n        run: |\n          export PATH=\"$PWD/.venv:$HOME/.cargo/bin:$PATH\"\n          source .venv/bin/activate\n          script/debug\n\n  manylinux_cross:\n    runs-on: ubuntu-24.04\n    timeout-minutes: 10\n    strategy:\n      fail-fast: false\n      matrix:\n        python: [\n          { interpreter: 'python3.14', abi: 'cp314-cp314', manylinux: 'manylinux_2_17', publish: true },\n          { interpreter: 'python3.13', abi: 'cp313-cp313', manylinux: 'manylinux_2_17', publish: true },\n          { interpreter: 'python3.12', abi: 'cp312-cp312', manylinux: 'manylinux_2_17', publish: true },\n          { interpreter: 'python3.11', abi: 'cp311-cp311', manylinux: 'manylinux_2_17', publish: true },\n          { interpreter: 'python3.10', abi: 'cp310-cp310', manylinux: 'manylinux_2_17', publish: true },\n        ]\n        target: [\n          {\n            arch: 'i686',\n            cflags: '-Os -fstrict-aliasing',\n            features: 'no_panic',\n            rustflags: '-Z unstable-options -C panic=immediate-abort -Z mir-opt-level=4 -D warnings',\n            target: 'i686-unknown-linux-gnu',\n          },\n          {\n            arch: 'armv7',\n            cflags: '-Os -fstrict-aliasing',\n            features: 'no_panic',\n            rustflags: '-Z unstable-options -C panic=immediate-abort -Z mir-opt-level=4 -D warnings -C opt-level=s',\n            target: 'armv7-unknown-linux-gnueabihf',\n          },\n          {\n            arch: 'ppc64le',\n            cflags: '-Os -fstrict-aliasing',\n            features: 'generic_simd,no_panic',\n            rustflags: '-Z unstable-options -C panic=immediate-abort -Z mir-opt-level=4 -D warnings',\n            target: 'powerpc64le-unknown-linux-gnu',\n          },\n          {\n            arch: 's390x',\n            cflags: '-Os -fstrict-aliasing -march=z10',\n            features: 'no_panic',\n            rustflags: '-Z unstable-options -C panic=immediate-abort -Z mir-opt-level=4 -D warnings -C target-cpu=z10',\n            target: 's390x-unknown-linux-gnu',\n          },\n        ]\n    steps:\n    - uses: actions/checkout@v6\n\n    - name: build-std\n      run: |\n        mkdir .cargo\n        cp ci/config.toml .cargo/config.toml\n\n    - name: Build\n      uses: PyO3/maturin-action@v1\n      env:\n        PYO3_CROSS_LIB_DIR: \"/opt/python/${{ matrix.python.abi }}\"\n        CFLAGS: \"${{ matrix.target.cflags }}\"\n        LDFLAGS: \"-Wl,--as-needed\"\n        RUSTFLAGS: \"${{ matrix.target.rustflags }}\"\n      with:\n        target: \"${{ matrix.target.target }}\"\n        rust-toolchain: \"${{ env.RUST_TOOLCHAIN }}\"\n        rustup-components: rust-src\n        manylinux: \"${{ matrix.python.manylinux }}\"\n        args: --release --strip --out=dist --features=${{ matrix.target.features }} -i ${{ matrix.python.interpreter }}\n\n    - name: Store wheels\n      if: matrix.python.publish == true\n      uses: actions/upload-artifact@v5\n      with:\n        name: \"orjson_manylinux_${{ matrix.target.arch }}_${{ matrix.python.interpreter }}\"\n        path: dist\n        overwrite: true\n        retention-days: 1\n        if-no-files-found: \"error\"\n        compression-level: 0\n\n    - name: setup-qemu-container\n      if: \"matrix.target.arch == 's390x' || matrix.target.arch == 'ppc64le'\"\n      uses: sandervocke/setup-qemu-container@v1\n      with:\n        container: registry.fedoraproject.org/fedora:43\n        arch: ${{ matrix.target.arch }}\n        podman_args: \"-v .:/orjson -v /tmp:/tmp --workdir /orjson\"\n\n    - name: setup-shell-wrapper\n      uses: sandervocke/setup-shell-wrapper@v1\n\n    - name: Emulated Test\n      if: \"matrix.target.arch == 's390x' || matrix.target.arch == 'ppc64le'\"\n      shell: wrap-shell {0}\n      env:\n        WRAP_SHELL: run-in-container.sh\n      run: |\n        set -eou pipefail\n\n        dnf install --setopt=install_weak_deps=false -y ${{ matrix.python.interpreter }} python3-uv\n\n        uv venv --python ${{ matrix.python.interpreter }}\n        source .venv/bin/activate\n\n        uv pip install -r test/requirements.txt\n        uv pip install dist/orjson*.whl\n\n        pytest -v test\n\n  musllinux_amd64:\n    runs-on: ubuntu-24.04\n    timeout-minutes: 10\n    strategy:\n      fail-fast: false\n      matrix:\n        python: [\n          { version: '3.14', pytest: '1', publish: true },\n          { version: '3.13', pytest: '1', publish: true },\n          { version: '3.12', pytest: '1', publish: true },\n          { version: '3.11', pytest: '0', publish: true },\n          { version: '3.10', pytest: '0', publish: true },\n        ]\n        platform:\n          - target: x86_64-unknown-linux-musl\n            arch: x86_64\n            platform: linux/amd64\n            features: avx512,unwind\n          - target: i686-unknown-linux-musl\n            arch: i686\n            platform: linux/386\n            features: unwind\n    steps:\n    - uses: actions/checkout@v6\n\n    - name: build-std\n      run: |\n        mkdir .cargo\n        cp ci/config.toml .cargo/config.toml\n\n    - name: Build\n      uses: PyO3/maturin-action@v1\n      env:\n        CC: \"gcc\"\n        CFLAGS: \"-O2\"\n        LDFLAGS: \"-Wl,--as-needed\"\n        RUSTFLAGS: \"-Z unstable-options -C panic=immediate-abort -Z mir-opt-level=4 -Z threads=2 -D warnings -C target-feature=-crt-static\"\n      with:\n        rust-toolchain: \"${{ env.RUST_TOOLCHAIN }}\"\n        rustup-components: rust-src\n        target: \"${{ matrix.platform.target }}\"\n        manylinux: musllinux_1_2\n        args: --release --strip --out=dist --features=${{ matrix.platform.features }} -i python${{ matrix.python.version }}\n\n    - name: Test\n      uses: addnab/docker-run-action@v3\n      with:\n        image: \"quay.io/pypa/musllinux_1_2_${{ matrix.platform.arch }}:2026.01.28-1\"\n        options: -v ${{ github.workspace }}:/io -w /io\n        run: |\n          apk add tzdata\n          sed -i '/^psutil/d' test/requirements.txt # missing 3.11, 3.12 wheels\n          sed -i '/^numpy/d' test/requirements.txt\n\n          python${{ matrix.python.version }} -m venv venv\n          venv/bin/pip install -U pip wheel\n          venv/bin/pip install orjson --no-index --find-links dist/ --force-reinstall\n\n          # segfault on starting pytest after January 2025 on 3.11 and older; artifact works fine\n          if [ ${{ matrix.python.pytest }} == '1' ]; then\n            venv/bin/pip install -r test/requirements.txt\n            PYTHONMALLOC=\"debug\" venv/bin/python -m pytest -v test\n          fi\n\n    - name: Store wheels\n      if: matrix.python.publish == true\n      uses: actions/upload-artifact@v5\n      with:\n        name: orjson_musllinux_${{ matrix.platform.arch }}_${{ matrix.python.version }}\n        path: dist\n        overwrite: true\n        retention-days: 1\n        if-no-files-found: \"error\"\n        compression-level: 0\n\n  musllinux_aarch64:\n    runs-on: ubuntu-24.04-arm\n    timeout-minutes: 10\n    strategy:\n      fail-fast: false\n      matrix:\n        python: [\n          { version: '3.14', publish: true },\n          { version: '3.13', publish: true },\n          { version: '3.12', publish: true },\n          { version: '3.11', publish: true },\n          { version: '3.10', publish: true },\n        ]\n        platform:\n          - target: aarch64-unknown-linux-musl\n            arch: aarch64\n            platform: linux/arm64\n            features: generic_simd,no_panic,unwind\n          - target: armv7-unknown-linux-musleabihf\n            arch: armv7l\n            platform: linux/arm/v7\n            features: no_panic\n    steps:\n    - uses: actions/checkout@v6\n\n    - name: build-std\n      run: |\n        mkdir .cargo\n        cp ci/config.toml .cargo/config.toml\n\n    - name: Build\n      uses: PyO3/maturin-action@v1\n      env:\n        CC: \"gcc\"\n        CFLAGS: \"-O2\"\n        LDFLAGS: \"-Wl,--as-needed\"\n        RUSTFLAGS: \"-Z unstable-options -C panic=immediate-abort -Z mir-opt-level=4 -Z threads=2 -D warnings -C target-feature=-crt-static\"\n      with:\n        rust-toolchain: \"${{ env.RUST_TOOLCHAIN }}\"\n        rustup-components: rust-src\n        target: \"${{ matrix.platform.target }}\"\n        manylinux: musllinux_1_2\n        args: --release --strip --out=dist --features=${{ matrix.platform.features }} -i python${{ matrix.python.version }}\n\n    - name: Test\n      uses: addnab/docker-run-action@v3\n      with:\n        image: \"quay.io/pypa/musllinux_1_2_${{ matrix.platform.arch }}:2026.01.28-1\"\n        options: -v ${{ github.workspace }}:/io -w /io\n        run: |\n          apk add tzdata\n          sed -i '/^psutil/d' test/requirements.txt # missing 3.11, 3.12 wheels\n          sed -i '/^numpy/d' test/requirements.txt\n\n          python${{ matrix.python.version }} -m venv venv\n          venv/bin/pip install -U pip wheel\n          venv/bin/pip install -r test/requirements.txt\n          venv/bin/pip install orjson --no-index --find-links dist/ --force-reinstall\n          export PYTHONMALLOC=\"debug\"\n          venv/bin/python -m pytest -v test\n\n    - name: Store wheels\n      if: matrix.python.publish == true\n      uses: actions/upload-artifact@v5\n      with:\n        name: orjson_musllinux_${{ matrix.platform.arch }}_${{ matrix.python.version }}\n        path: dist\n        overwrite: true\n        retention-days: 1\n        if-no-files-found: \"error\"\n        compression-level: 0\n\n  macos_aarch64:\n    runs-on: macos-26\n    timeout-minutes: 10\n    strategy:\n      fail-fast: false\n      matrix:\n        python: [\n          { version: '3.14', macosx_target: \"15.0\", publish: true },\n          { version: '3.13', macosx_target: \"15.0\", publish: true },\n          { version: '3.12', macosx_target: \"15.0\", publish: true },\n          { version: '3.11', macosx_target: \"15.0\", publish: true },\n        ]\n    env:\n      CC: \"clang\"\n      LDFLAGS: \"-Wl,--as-needed\"\n      CFLAGS: \"-O2 -fstrict-aliasing -fno-plt -mcpu=apple-m1 -mtune=generic\"\n      RUSTFLAGS: \"-Z unstable-options -C panic=immediate-abort -Z mir-opt-level=4 -Z threads=3 -D warnings\"\n      PATH: \"/Users/runner/work/orjson/orjson/.venv/bin:/Users/runner/.cargo/bin:/usr/local/opt/curl/bin:/usr/local/bin:/usr/local/sbin:/Users/runner/bin:/Library/Frameworks/Python.framework/Versions/Current/bin:/usr/bin:/bin:/usr/sbin:/sbin\"\n    steps:\n\n    - name: CPU info\n      run: sysctl -a | grep brand\n\n    - uses: actions/checkout@v6\n\n    - uses: actions/setup-python@v6\n      with:\n        allow-prereleases: true\n        python-version: \"${{ matrix.python.version }}\"\n\n    - uses: dtolnay/rust-toolchain@master\n      with:\n        toolchain: \"${{ env.RUST_TOOLCHAIN }}\"\n        targets: \"aarch64-apple-darwin\"\n        components: \"rust-src\"\n\n    - name: Build environment\n      run: |\n        cargo fetch --target aarch64-apple-darwin &\n\n        export PATH=$HOME/.cargo/bin:$HOME/.local/bin:$PATH\n\n        curl -LsSf https://astral.sh/uv/install.sh | sh\n        uv venv --python python${{ matrix.python.version }}\n        uv pip install --upgrade \"maturin>=1.10,<2\" -r test/requirements.txt -r integration/requirements.txt\n\n        mkdir .cargo\n        cp ci/config.toml .cargo/config.toml\n\n    - name: maturin\n      run: |\n        export PATH=$HOME/.cargo/bin:$HOME/.local/bin:$PATH\n\n        MACOSX_DEPLOYMENT_TARGET=\"${{ matrix.python.macosx_target }}\" \\\n        PYO3_CROSS_LIB_DIR=$(python -c \"import sysconfig;print(sysconfig.get_config_var('LIBDIR'))\") \\\n        maturin build \\\n          --release \\\n          --strip \\\n          --features=generic_simd,no_panic \\\n          --interpreter python${{ matrix.python.version }} \\\n          --target=aarch64-apple-darwin\n        uv pip install target/wheels/orjson*.whl\n\n    - run: pytest -v test\n      env:\n        PYTHONMALLOC: \"debug\"\n\n    - run: source .venv/bin/activate && ./integration/run thread\n    - run: source .venv/bin/activate && ./integration/run http\n    - run: source .venv/bin/activate && ./integration/run init\n\n    - name: Store wheels\n      if: matrix.python.publish == true\n      uses: actions/upload-artifact@v5\n      with:\n        name: orjson_macos_aarch64_${{ matrix.python.version }}\n        path: target/wheels\n        overwrite: true\n        retention-days: 1\n        if-no-files-found: \"error\"\n        compression-level: 0\n\n  macos_universal2_aarch64:\n    runs-on: macos-26\n    timeout-minutes: 10\n    strategy:\n      fail-fast: false\n      matrix:\n        python: [\n          { version: '3.14', macosx_target: \"10.15\", publish: true },\n          { version: '3.13', macosx_target: \"10.15\", publish: true },\n          { version: '3.12', macosx_target: \"10.15\", publish: true },\n          { version: '3.11', macosx_target: \"10.15\", publish: true },\n          { version: '3.10', macosx_target: \"10.15\", publish: true },\n        ]\n    env:\n      CC: \"clang\"\n      CFLAGS: \"-O2 -fstrict-aliasing\"\n      LDFLAGS: \"-Wl,--as-needed\"\n      CFLAGS_x86_64_apple_darwin: \"-O2 -fstrict-aliasing -fno-plt -march=x86-64-v2 -mtune=generic\"\n      CFLAGS_aarch64_apple_darwin: \"-O2 -fstrict-aliasing -fno-plt -mcpu=apple-m1 -mtune=generic\"\n      RUSTFLAGS: \"-Z unstable-options -C panic=immediate-abort -Z mir-opt-level=4 -Z threads=3 -D warnings\"\n      PATH: \"/Users/runner/work/orjson/orjson/.venv/bin:/Users/runner/.cargo/bin:/usr/local/opt/curl/bin:/usr/local/bin:/usr/local/sbin:/Users/runner/bin:/Library/Frameworks/Python.framework/Versions/Current/bin:/usr/bin:/bin:/usr/sbin:/sbin\"\n    steps:\n\n    - name: CPU info\n      run: sysctl -a | grep brand\n\n    - uses: actions/checkout@v6\n\n    - uses: actions/setup-python@v6\n      with:\n        allow-prereleases: true\n        python-version: \"${{ matrix.python.version }}\"\n\n    - uses: dtolnay/rust-toolchain@master\n      with:\n        toolchain: \"${{ env.RUST_TOOLCHAIN }}\"\n        targets: \"aarch64-apple-darwin, x86_64-apple-darwin\"\n        components: \"rust-src\"\n\n    - name: Build environment\n      run: |\n        cargo fetch --target aarch64-apple-darwin &\n\n        export PATH=$HOME/.cargo/bin:$HOME/.local/bin:$PATH\n\n        curl -LsSf https://astral.sh/uv/install.sh | sh\n        uv venv --python python${{ matrix.python.version }}\n        uv pip install --upgrade \"maturin>=1.10,<2\" -r test/requirements.txt -r integration/requirements.txt\n\n        mkdir .cargo\n        cp ci/config.toml .cargo/config.toml\n\n    - name: maturin\n      run: |\n        export PATH=$HOME/.cargo/bin:$HOME/.local/bin:$PATH\n\n        MACOSX_DEPLOYMENT_TARGET=\"${{ matrix.python.macosx_target }}\" \\\n        PYO3_CROSS_LIB_DIR=$(python -c \"import sysconfig;print(sysconfig.get_config_var('LIBDIR'))\") \\\n        maturin build \\\n          --release \\\n          --strip \\\n          --features=generic_simd,no_panic \\\n          --interpreter python${{ matrix.python.version }} \\\n          --target=universal2-apple-darwin\n        uv pip install target/wheels/orjson*.whl\n\n    - run: pytest -v test\n      env:\n        PYTHONMALLOC: \"debug\"\n\n    - run: source .venv/bin/activate && ./integration/run thread\n    - run: source .venv/bin/activate && ./integration/run http\n    - run: source .venv/bin/activate && ./integration/run init\n\n    - name: Store wheels\n      if: matrix.python.publish == true\n      uses: actions/upload-artifact@v5\n      with:\n        name: orjson_universal2_aarch64_${{ matrix.python.version }}\n        path: target/wheels\n        overwrite: true\n        retention-days: 1\n        if-no-files-found: \"error\"\n        compression-level: 0\n\n  windows_amd64:\n    runs-on: windows-2025\n    timeout-minutes: 10\n    strategy:\n      fail-fast: false\n      matrix:\n        python: [\n          { version: '3.14', publish: true },\n          { version: '3.13', publish: true },\n          { version: '3.12', publish: true },\n          { version: '3.11', publish: true },\n          { version: '3.10', publish: true },\n        ]\n        platform: [\n          { arch: \"x64\", target: \"x86_64-pc-windows-msvc\", features: \"avx512,no_panic\" },\n          { arch: \"x86\", target: \"i686-pc-windows-msvc\", features: \"no_panic\" },\n        ]\n    env:\n      CFLAGS: \"-O2\"\n      LDFLAGS: \"-Wl,--as-needed\"\n      RUSTFLAGS: \"-Z unstable-options -C panic=immediate-abort -Z mir-opt-level=4 -D warnings\"\n    steps:\n\n    - name: CPU info\n      shell: pwsh\n      run: Get-WmiObject -Class Win32_Processor -ComputerName. | Select-Object -Property Name, NumberOfCores, NumberOfLogicalProcessors\n\n    - uses: actions/checkout@v6\n\n    - uses: actions/setup-python@v6\n      with:\n        allow-prereleases: true\n        python-version: \"${{ matrix.python.version }}\"\n        architecture: \"${{ matrix.platform.arch }}\"\n\n    - uses: dtolnay/rust-toolchain@master\n      with:\n        toolchain: \"${{ env.RUST_TOOLCHAIN }}\"\n        targets: \"${{ matrix.platform.target }}\"\n        components: \"rust-src\"\n\n    - name: Build environment\n      run: |\n        cargo fetch --target \"${{ matrix.platform.target }}\" &\n\n        python.exe -m pip install --upgrade pip \"maturin>=1.10,<2\" wheel\n        python.exe -m pip install -r test\\requirements.txt\n\n        mkdir .cargo\n        cp ci\\config.toml .cargo\\config.toml\n\n    - name: maturin\n      run: |\n        maturin.exe build --release --strip --features=\"${{ matrix.platform.features }}\" --target=\"${{ matrix.platform.target }}\"\n        python.exe -m pip install orjson --no-index --find-links target\\wheels\n\n    - run: python.exe -m pytest -s -rxX -v test\n      env:\n        PYTHONMALLOC: \"debug\"\n\n    - name: Store wheels\n      if: matrix.python.publish == true\n      uses: actions/upload-artifact@v5\n      with:\n        name: orjson_windows_amd64_${{ matrix.platform.arch }}_${{ matrix.python.version }}\n        path: target\\wheels\n        overwrite: true\n        retention-days: 1\n        if-no-files-found: \"error\"\n        compression-level: 0\n\n  windows_aarch64:\n    runs-on: windows-11-arm\n    timeout-minutes: 10\n    strategy:\n      fail-fast: false\n      matrix:\n        python: [\n          { version: '3.14', publish: true },\n          { version: '3.13', publish: true },\n          { version: '3.12', publish: true },\n          { version: '3.11', publish: true },\n        ]\n    env:\n      CFLAGS: \"-O2\"\n      LDFLAGS: \"-Wl,--as-needed\"\n      RUSTFLAGS: \"-Z unstable-options -C panic=immediate-abort -Z mir-opt-level=4 -D warnings\"\n      TARGET: \"aarch64-pc-windows-msvc\"\n    steps:\n\n    - name: CPU info\n      shell: pwsh\n      run: Get-WmiObject -Class Win32_Processor -ComputerName. | Select-Object -Property Name, NumberOfCores, NumberOfLogicalProcessors\n\n    - uses: actions/checkout@v6\n\n    - uses: actions/setup-python@v6\n      with:\n        allow-prereleases: true\n        python-version: \"${{ matrix.python.version }}\"\n        architecture: \"arm64\"\n\n    # from maturin\n    - shell: pwsh\n      run: |\n        Invoke-WebRequest -Uri \"https://static.rust-lang.org/rustup/dist/$env:TARGET/rustup-init.exe\" -OutFile rustup-init.exe\n        .\\rustup-init.exe --default-toolchain \"$env:RUST_TOOLCHAIN-$env:TARGET\" --profile minimal --component rust-src -y\n        \"$env:USERPROFILE\\.cargo\\bin\" | Out-File -Append -Encoding ascii $env:GITHUB_PATH\n        \"CARGO_HOME=$env:USERPROFILE\\.cargo\" | Out-File -Append -Encoding ascii $env:GITHUB_ENV\n\n    - name: Build environment\n      run: |\n        cargo fetch --target \"$\" &\n\n        python.exe -m sysconfig\n        python.exe -m pip install --upgrade pip \"maturin>=1.10,<2\" wheel\n        python.exe -m pip install -r test\\requirements.txt\n\n        mkdir .cargo\n        cp ci\\config.toml .cargo\\config.toml\n\n    - name: maturin\n      run: |\n        maturin.exe build --release --strip --features=generic_simd,no_panic --target=\"$env:TARGET\"\n        python.exe -m pip install orjson --no-index --find-links target\\wheels\n\n    - run: python.exe -m pytest -s -rxX -v test\n      env:\n        PYTHONMALLOC: \"debug\"\n\n    - name: Store wheels\n      if: matrix.python.publish == true\n      uses: actions/upload-artifact@v5\n      with:\n        name: orjson_windows_aarch64_${{ matrix.python.version }}\n        path: target\\wheels\n        overwrite: true\n        retention-days: 1\n        if-no-files-found: \"error\"\n        compression-level: 0\n\n  pypi:\n    name: PyPI\n    runs-on: ubuntu-24.04\n    timeout-minutes: 10\n    needs: [\n      macos_aarch64,\n      macos_universal2_aarch64,\n      manylinux,\n      manylinux_cross,\n      musllinux_aarch64,\n      musllinux_amd64,\n      sdist,\n      windows_aarch64,\n      windows_amd64,\n    ]\n    environment:\n      name: PyPI\n      url: https://pypi.org/p/orjson\n    permissions:\n      id-token: write\n    steps:\n      - uses: actions/checkout@v6\n\n      - uses: actions/download-artifact@v5\n        with:\n          merge-multiple: true\n          path: dist/\n          pattern: orjson_*\n\n      - run: ls -1 dist/\n\n      - uses: actions/setup-python@v6\n        with:\n          python-version: \"3.14\"\n\n      - run: ./script/check-pypi dist\n\n      - name: Publish distribution to PyPI\n        if: \"startsWith(github.ref, 'refs/tags/')\"\n        uses: pypa/gh-action-pypi-publish@release/v1\n        with:\n          attestations: true\n          packages-dir: dist\n          skip-existing: true\n          verbose: true\n"
  },
  {
    "path": ".github/workflows/lint.yaml",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2023-2025)\n\nname: lint\non: push\nenv:\n  FORCE_COLOR: \"1\"\n  PIP_DISABLE_PIP_VERSION_CHECK: \"1\"\njobs:\n  lint:\n    runs-on: ubuntu-24.04\n    steps:\n    - uses: actions/setup-python@v6\n      with:\n        python-version: \"3.14\"\n\n    - uses: actions/checkout@v6\n\n    - run: curl https://sh.rustup.rs -sSf | sh -s -- --default-toolchain=stable --profile=default -y\n    - run: pip install -r requirements-lint.txt\n\n    - run: cargo fmt\n    - run: ./script/lint\n\n    - run: git diff --exit-code\n"
  },
  {
    "path": ".github/workflows/unusual.yaml",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2023-2026)\n\nname: unusual\non: push\nenv:\n  FORCE_COLOR: \"1\"\n  PIP_DISABLE_PIP_VERSION_CHECK: \"1\"\njobs:\n\n  unusual:\n    runs-on: ubuntu-24.04\n    strategy:\n      fail-fast: false\n      matrix:\n        cfg: [\n          { rust: \"1.89\", python: \"3.15\", version_check: \"1\" },\n          { rust: \"1.89\", python: \"3.14\", version_check: \"0\" },\n          { rust: \"1.89\", python: \"3.10\", version_check: \"0\" },\n        ]\n    steps:\n    - run: curl https://sh.rustup.rs -sSf | sh -s -- --default-toolchain ${{ matrix.cfg.rust }} --profile minimal -y\n\n    - uses: actions/setup-python@v5\n      with:\n        python-version: '${{ matrix.cfg.python }}'\n        allow-prereleases: true\n\n    - run: python -m pip install --user --upgrade pip \"maturin>=1.10,<2\" wheel\n\n    - uses: actions/checkout@v6\n\n    - name: build\n      run: |\n        PATH=\"$HOME/.cargo/bin:$PATH\" UNSAFE_PYO3_SKIP_VERSION_CHECK=\"${{ matrix.cfg.version_check }}\" \\\n          maturin build \\\n          --profile=dev \\\n          --interpreter python${{ matrix.cfg.python }} \\\n          --target=x86_64-unknown-linux-gnu\n\n    - run: python -m pip install --user target/wheels/orjson*.whl\n    - run: python -m pip install --user -r test/requirements.txt -r integration/requirements.txt\n\n    - run: pytest -s -rxX -v test\n      timeout-minutes: 4\n      env:\n        PYTHONMALLOC: \"debug\"\n\n    - run: ./integration/run thread\n      timeout-minutes: 2\n\n    - run: ./integration/run http\n      timeout-minutes: 2\n\n    - run: ./integration/run init\n      timeout-minutes: 2\n"
  },
  {
    "path": ".gitignore",
    "content": "*.patch\n/.benchmarks\n/.coverage\n/.mypy_cache\n/.pytest_cache\n/.venv*\n/build\n/include/cargo\n/perf.*\n/target\n/vendor\n__pycache__\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Changelog\n\n\n## 3.11.7 - 2026-02-02\n\n### Changed\n\n- Use a faster library to serialize `float`. Users with byte-exact regression\ntests should note positive exponents are now written using a `+`, e.g.,\n`1.2e+30` instead of `1.2e30`. Both formats are spec-compliant.\n- ABI compatibility with CPython 3.15 alpha 5 free-threading.\n\n\n## 3.11.6 - 2026-01-29\n\n### Changed\n\n- orjson now includes code licensed under the Mozilla Public License 2.0 (MPL-2.0).\n- Drop support for Python 3.9.\n- ABI compatibility with CPython 3.15 alpha 5.\n- Build now depends on Rust 1.89 or later instead of 1.85.\n\n### Fixed\n\n- Fix sporadic crash serializing deeply nested `list` of `dict`.\n\n\n## 3.11.5 - 2025-12-06\n\n### Changed\n\n- Show simple error message instead of traceback when attempting to\nbuild on unsupported Python versions.\n\n\n## 3.11.4 - 2025-10-24\n\n### Changed\n\n- ABI compatibility with CPython 3.15 alpha 1.\n- Publish PyPI wheels for 3.14 and manylinux i686, manylinux arm7,\nmanylinux ppc64le, manylinux s390x.\n- Build now requires a C compiler.\n\n\n## 3.11.3 - 2025-08-26\n\n### Fixed\n\n- Fix PyPI project metadata when using maturin 1.9.2 or later.\n\n\n## 3.11.2 - 2025-08-12\n\n### Fixed\n\n- Fix build using Rust 1.89 on amd64.\n\n### Changed\n\n- Build now depends on Rust 1.85 or later instead of 1.82.\n\n\n## 3.11.1 - 2025-07-25\n\n### Changed\n\n- Publish PyPI wheels for CPython 3.14.\n\n### Fixed\n\n- Fix `str` on big-endian architectures. This was introduced in 3.11.0.\n\n\n## 3.11.0 - 2025-07-15\n\n### Changed\n\n- Use a deserialization buffer allocated per request instead of a shared\nbuffer allocated on import.\n- ABI compatibility with CPython 3.14 beta 4.\n\n\n## 3.10.18 - 2025-04-29\n\n### Fixed\n\n- Fix incorrect escaping of the vertical tabulation character. This was\nintroduced in 3.10.17.\n\n\n## 3.10.17 - 2025-04-29\n\n### Changed\n\n- Publish PyPI Windows aarch64/arm64 wheels.\n- ABI compatibility with CPython 3.14 alpha 7.\n- Fix incompatibility running on Python 3.13 using WASM.\n\n\n## 3.10.16 - 2025-03-24\n\n### Changed\n\n- Improve performance of serialization on amd64 machines with AVX-512.\n- ABI compatibility with CPython 3.14 alpha 6.\n- Drop support for Python 3.8.\n- Publish additional PyPI wheels for macOS that target only aarch64, macOS 15,\nand recent Python.\n\n\n## 3.10.15 - 2025-01-08\n\n### Changed\n\n- Publish PyPI manylinux aarch64 wheels built and tested on aarch64.\n- Publish PyPI musllinux aarch64 and arm7l wheels built and tested on aarch64.\n- Publish PyPI manylinux Python 3.13 wheels for i686, arm7l, ppc64le, and s390x.\n\n\n## 3.10.14 - 2024-12-29\n\n### Changed\n\n- Specify build system dependency on `maturin>=1,<2` again.\n- Allocate memory using `PyMem_Malloc()` and similar APIs for integration\nwith pymalloc, mimalloc, and tracemalloc.\n- Source distribution does not ship compressed test documents and relevant\ntests skip if fixtures are not present.\n- Build now depends on Rust 1.82 or later instead of 1.72.\n\n\n## 3.10.13 - 2024-12-29\n\n### Changed\n\n- Fix compatibility with maturin introducing a breaking change in 1.8.0 and\nspecify a fixed version of maturin. Projects relying on any previous version\nbeing buildable from source by end users (via PEP 517) must upgrade to at\nleast this version.\n\n\n## 3.10.12 - 2024-11-23\n\n### Changed\n\n- Publish PyPI manylinux i686 wheels.\n- Publish PyPI musllinux i686 and arm7l wheels.\n- Publish PyPI macOS wheels for Python 3.10 or later built on macOS 15.\n- Publish PyPI Windows wheels using trusted publishing.\n\n\n## 3.10.11 - 2024-11-01\n\n### Changed\n\n- Improve performance of UUIDs.\n- Publish PyPI wheels with trusted publishing and PEP 740 attestations.\n- Include text of licenses for vendored dependencies.\n\n\n## 3.10.10 - 2024-10-22\n\n### Fixed\n\n- Fix `int` serialization on `s390x`. This was introduced in 3.10.8.\n\n### Changed\n\n- Publish aarch64 manylinux_2_17 wheel for 3.13 to PyPI.\n\n\n## 3.10.9 - 2024-10-19\n\n### Fixed\n\n- Fix `int` serialization on 32-bit Python 3.8, 3.9, 3.10. This was\nintroduced in 3.10.8.\n\n\n## 3.10.8 - 2024-10-19\n\n### Changed\n\n- `int` serialization no longer chains `OverflowError` to the\nthe `__cause__` attribute of `orjson.JSONEncodeError` when range exceeded.\n- Compatibility with CPython 3.14 alpha 1.\n- Improve performance.\n\n\n## 3.10.7 - 2024-08-08\n\n### Changed\n\n- Improve performance of stable Rust amd64 builds.\n\n\n## 3.10.6 - 2024-07-02\n\n### Changed\n\n- Improve performance.\n\n\n## 3.10.5 - 2024-06-13\n\n### Changed\n\n- Improve performance.\n\n\n## 3.10.4 - 2024-06-10\n\n### Changed\n\n- Improve performance.\n\n\n## 3.10.3 - 2024-05-03\n\n### Changed\n\n- `manylinux` amd64 builds include runtime-detected AVX-512 `str`\nimplementation.\n- Tests now compatible with numpy v2.\n\n\n## 3.10.2 - 2024-05-01\n\n### Fixed\n\n- Fix crash serializing `str` introduced in 3.10.1.\n\n### Changed\n\n- Improve performance.\n- Drop support for arm7.\n\n\n## 3.10.1 - 2024-04-15\n\n### Fixed\n\n- Serializing `numpy.ndarray` with non-native endianness raises\n`orjson.JSONEncodeError`.\n\n### Changed\n\n- Improve performance of serializing.\n\n\n## 3.10.0 - 2024-03-27\n\n### Changed\n\n- Support serializing `numpy.float16` (`numpy.half`).\n- sdist uses metadata 2.3 instead of 2.1.\n- Improve Windows PyPI builds.\n\n\n## 3.9.15 - 2024-02-23\n\n### Fixed\n\n- Implement recursion limit of 1024 on `orjson.loads()`.\n- Use byte-exact read on `str` formatting SIMD path to avoid crash.\n\n\n## 3.9.14 - 2024-02-14\n\n### Fixed\n\n- Fix crash serializing `str` introduced in 3.9.11.\n\n### Changed\n\n- Build now depends on Rust 1.72 or later.\n\n\n## 3.9.13 - 2024-02-03\n\n### Fixed\n\n- Serialization `str` escape uses only 128-bit SIMD.\n- Fix compatibility with CPython 3.13 alpha 3.\n\n### Changed\n\n- Publish `musllinux_1_2` instead of `musllinux_1_1` wheels.\n- Serialization uses small integer optimization in CPython 3.12 or later.\n\n\n## 3.9.12 - 2024-01-18\n\n### Changed\n\n- Update benchmarks in README.\n\n### Fixed\n\n- Minimal `musllinux_1_1` build due to sporadic CI failure.\n\n\n## 3.9.11 - 2024-01-18\n\n### Changed\n\n- Improve performance of serializing. `str` is significantly faster. Documents\nusing `dict`, `list`, and `tuple` are somewhat faster.\n\n\n## 3.9.10 - 2023-10-26\n\n### Fixed\n\n- Fix debug assert failure on 3.12 `--profile=dev` build.\n\n\n## 3.9.9 - 2023-10-12\n\n### Changed\n\n- `orjson` module metadata explicitly marks subinterpreters as not supported.\n\n\n## 3.9.8 - 2023-10-10\n\n### Changed\n\n- Improve performance.\n- Drop support for Python 3.7.\n\n\n## 3.9.7 - 2023-09-08\n\n### Fixed\n\n- Fix crash in `orjson.loads()` due to non-reentrant handling of persistent\nbuffer. This was introduced in 3.9.3.\n- Handle some FFI removals in CPython 3.13.\n\n\n## 3.9.6 - 2023-09-07\n\n### Fixed\n\n- Fix numpy reference leak on unsupported array dtype.\n- Fix numpy.datetime64 reference handling.\n\n### Changed\n\n- Minor performance improvements.\n\n\n## 3.9.5 - 2023-08-16\n\n### Fixed\n\n- Remove futex from module import and initialization path.\n\n\n## 3.9.4 - 2023-08-07\n\n### Fixed\n\n- Fix hash builder using default values.\n- Fix non-release builds of orjson copying large deserialization buffer\nfrom stack to heap. This was introduced in 3.9.3.\n\n\n## 3.9.3 - 2023-08-06\n\n### Fixed\n\n- Fix compatibility with CPython 3.12.\n\n### Changed\n\n- Support i686/x86 32-bit Python installs on Windows.\n\n\n## 3.9.2 - 2023-07-07\n\n### Fixed\n\n- Fix the `__cause__` exception on `orjson.JSONEncodeError` possibly being\ndenormalized, i.e., of type `str` instead of `Exception`.\n\n\n## 3.9.1 - 2023-06-09\n\n### Fixed\n\n- Fix memory leak on chained tracebacks of exceptions raised in `default`. This\nwas introduced in 3.8.12.\n\n\n## 3.9.0 - 2023-06-01\n\n### Added\n\n- `orjson.Fragment` includes already-serialized JSON in a document.\n\n\n## 3.8.14 - 2023-05-25\n\n### Changed\n\n- PyPI `manylinux` wheels are compiled for `x86-64` instead of `x86-64-v2`.\n\n\n## 3.8.13 - 2023-05-23\n\n### Changed\n\n- Source distribution contains all source code required for an offline build.\n- PyPI macOS wheels use a `MACOSX_DEPLOYMENT_TARGET` of 10.15 instead of 11.\n- Build uses maturin v1.\n\n\n## 3.8.12 - 2023-05-07\n\n### Changed\n\n- Exceptions raised in `default` are now chained as the `__cause__` attribute\non `orjson.JSONEncodeError`.\n\n\n## 3.8.11 - 2023-04-27\n\n### Changed\n\n- `orjson.loads()` on an empty document has a specific error message.\n- PyPI `manylinux_2_28_x86_64` wheels are compiled for `x86-64-v2`.\n- PyPI macOS wheels are only `universal2` and compiled for\n`x86-64-v2` and `apple-m1`.\n\n\n## 3.8.10 - 2023-04-09\n\n### Fixed\n\n- Fix compatibility with CPython 3.12.0a7.\n- Fix compatibility with big-endian architectures.\n- Fix crash in serialization.\n\n### Changed\n\n- Publish musllinux 3.11 wheels.\n- Publish s390x wheels.\n\n\n## 3.8.9 - 2023-03-28\n\n### Fixed\n\n- Fix parallel initialization of orjson.\n\n\n## 3.8.8 - 2023-03-20\n\n### Changed\n\n- Publish ppc64le wheels.\n\n\n## 3.8.7 - 2023-02-28\n\n### Fixed\n\n- Use serialization backend introduced in 3.8.4 only on well-tested\nplatforms such as glibc, macOS by default.\n\n\n## 3.8.6 - 2023-02-09\n\n### Fixed\n\n- Fix crash serializing when using musl libc.\n\n### Changed\n\n- Make `python-dateutil` optional in tests.\n- Handle failure to load system timezones in tests.\n\n\n## 3.8.5 - 2023-01-10\n\n### Fixed\n\n- Fix `orjson.dumps()` invalid output on Windows.\n\n\n## 3.8.4 - 2023-01-04\n\n### Changed\n\n- Improve performance.\n\n\n## 3.8.3 - 2022-12-02\n\n### Fixed\n\n- `orjson.dumps()` accepts `option=None` per `Optional[int]` type.\n\n\n## 3.8.2 - 2022-11-20\n\n### Fixed\n\n- Fix tests on 32-bit for `numpy.intp` and `numpy.uintp`.\n\n### Changed\n\n- Build now depends on rustc 1.60 or later.\n- Support building with maturin 0.13 or 0.14.\n\n\n## 3.8.1 - 2022-10-25\n\n### Changed\n\n- Build maintenance for Python 3.11.\n\n\n## 3.8.0 - 2022-08-27\n\n### Changed\n\n- Support serializing `numpy.int16` and `numpy.uint16`.\n\n\n## 3.7.12 - 2022-08-14\n\n### Fixed\n\n- Fix datetime regression tests for tzinfo 2022b.\n\n### Changed\n\n- Improve performance.\n\n\n## 3.7.11 - 2022-07-31\n\n### Fixed\n\n- Revert `dict` iterator implementation introduced in 3.7.9.\n\n\n## 3.7.10 - 2022-07-30\n\n### Fixed\n\n- Fix serializing `dict` with deleted final item. This was introduced in 3.7.9.\n\n\n## 3.7.9 - 2022-07-29\n\n### Changed\n\n- Improve performance of serializing.\n- Improve performance of serializing pretty-printed (`orjson.OPT_INDENT_2`)\nto be much nearer to compact.\n- Improve performance of deserializing `str` input.\n- orjson now requires Rust 1.57 instead of 1.54 to build.\n\n\n## 3.7.8 - 2022-07-19\n\n### Changed\n\n- Build makes best effort instead of requiring \"--features\".\n- Build using maturin 0.13.\n\n\n## 3.7.7 - 2022-07-06\n\n### Changed\n\n- Support Python 3.11.\n\n\n## 3.7.6 - 2022-07-03\n\n### Changed\n\n- Handle unicode changes in CPython 3.12.\n- Build PyPI macOS wheels on 10.15 instead of 12 for compatibility.\n\n\n## 3.7.5 - 2022-06-28\n\n### Fixed\n\n- Fix issue serializing dicts that had keys popped and replaced. This was\nintroduced in 3.7.4.\n\n\n## 3.7.4 - 2022-06-28\n\n### Changed\n\n- Improve performance.\n\n### Fixed\n\n- Fix deallocation of `orjson.JSONDecodeError`.\n\n\n## 3.7.3 - 2022-06-23\n\n\n## Changed\n\n- Improve build.\n- Publish aarch64 musllinux wheels.\n\n\n## 3.7.2 - 2022-06-07\n\n\n## Changed\n\n- Improve deserialization performance.\n\n\n## 3.7.1 - 2022-06-03\n\n### Fixed\n\n- Type stubs for `orjson.JSONDecodeError` now inherit from\n`json.JSONDecodeError` instead of `ValueError`\n- Null-terminate the internal buffer of `orjson.dumps()` output.\n\n\n## 3.7.0 - 2022-06-03\n\n### Changed\n\n- Improve deserialization performance significantly through the use of a new\nbackend. PyPI wheels for manylinux_2_28 and macOS have it enabled. Packagers\nare advised to see the README.\n\n\n## 3.6.9 - 2022-06-01\n\n### Changed\n\n- Improve serialization and deserialization performance.\n\n\n## 3.6.8 - 2022-04-15\n\n### Fixed\n\n- Fix serialization of `numpy.datetime64(\"NaT\")` to raise on an\nunsupported type.\n\n\n## 3.6.7 - 2022-02-14\n\n### Changed\n\n- Improve performance of deserializing almost-empty documents.\n- Publish arm7l `manylinux_2_17` wheels to PyPI.\n- Publish amd4 `musllinux_1_1` wheels to PyPI.\n\n### Fixed\n\n- Fix build requiring `python` on `PATH`.\n\n\n## 3.6.6 - 2022-01-21\n\n### Changed\n\n- Improve performance of serializing `datetime.datetime` using `tzinfo` that\nare `zoneinfo.ZoneInfo`.\n\n### Fixed\n\n- Fix invalid indexing in line and column number reporting in\n`JSONDecodeError`.\n- Fix `orjson.OPT_STRICT_INTEGER` not raising an error on\nvalues exceeding a 64-bit integer maximum.\n\n\n## 3.6.5 - 2021-12-05\n\n### Fixed\n\n- Fix build on macOS aarch64 CPython 3.10.\n- Fix build issue on 32-bit.\n\n\n## 3.6.4 - 2021-10-01\n\n### Fixed\n\n- Fix serialization of `dataclass` inheriting from `abc.ABC` and\nusing `__slots__`.\n- Decrement refcount for numpy `PyArrayInterface`.\n- Fix build on recent versions of Rust nightly.\n\n\n## 3.6.3 - 2021-08-20\n\n### Fixed\n\n- Fix build on aarch64 using the Rust stable channel.\n\n\n## 3.6.2 - 2021-08-17\n\n### Changed\n\n- `orjson` now compiles on Rust stable 1.54.0 or above. Use of some SIMD\nusage is now disabled by default and packagers are advised to add\n`--cargo-extra-args=\"--features=unstable-simd\"` to the `maturin build` command\n if they continue to use nightly.\n- `orjson` built with `--features=unstable-simd` adds UTF-8 validation\nimplementations that use AVX2 or SSE4.2.\n- Drop support for Python 3.6.\n\n\n## 3.6.1 - 2021-08-04\n\n### Changed\n\n- `orjson` now includes a `pyi` type stubs file.\n- Publish manylinux_2_24 wheels instead of manylinux2014.\n\n### Fixed\n\n- Fix compilation on latest Rust nightly.\n\n\n## 3.6.0 - 2021-07-08\n\n### Added\n\n- `orjson.dumps()` serializes `numpy.datetime64` instances as RFC 3339\nstrings.\n\n\n## 3.5.4 - 2021-06-30\n\n### Fixed\n\n- Fix memory leak serializing `datetime.datetime` with `tzinfo`.\n- Fix wrong error message when serializing an unsupported numpy type\nwithout default specified.\n\n### Changed\n\n- Publish python3.10 and python3.9 manylinux_2_24 wheels.\n\n\n## 3.5.3 - 2021-06-01\n\n### Fixed\n\n- `orjson.JSONDecodeError` now has `pos`, `lineno`, and `colno`.\n- Fix build on recent versions of Rust nightly.\n\n\n## 3.5.2 - 2021-04-15\n\n### Changed\n\n- Improve serialization and deserialization performance.\n- `orjson.dumps()` serializes individual `numpy.bool_` objects.\n\n\n## 3.5.1 - 2021-03-06\n\n### Changed\n\n- Publish `universal2` wheels for macOS supporting Apple Silicon (aarch64).\n\n\n## 3.5.0 - 2021-02-24\n\n### Added\n\n- `orjson.loads()` supports reading from `memoryview` objects.\n\n### Fixed\n\n- `datetime.datetime` and `datetime.date` zero pad years less than 1000 to\nfour digits.\n- sdist pins maturin 0.9.0 to avoid breaks in later 0.9.x.\n\n### Changed\n\n- `orjson.dumps()` when given a non-C contiguous `numpy.ndarray` has\nan error message suggesting to use `default`.\n\n\n## 3.4.8 - 2021-02-04\n\n### Fixed\n\n- aarch64 manylinux2014 wheels are now compatible with glibc 2.17.\n\n### Changed\n\n- Fix build warnings on ppcle64.\n\n\n## 3.4.7 - 2021-01-19\n\n### Changed\n\n- Use vectorcall APIs for method calls on python3.9 and above.\n- Publish python3.10 wheels for Linux on amd64 and aarch64.\n\n\n## 3.4.6 - 2020-12-07\n\n### Fixed\n\n- Fix compatibility with debug builds of CPython.\n\n\n## 3.4.5 - 2020-12-02\n\n### Fixed\n\n- Fix deserializing long strings on processors without AVX2.\n\n\n## 3.4.4 - 2020-11-25\n\n### Changed\n\n- `orjson.dumps()` serializes integers up to a 64-bit unsigned integer's\nmaximum. It was previously the maximum of a 64-bit signed integer.\n\n\n## 3.4.3 - 2020-10-30\n\n### Fixed\n\n- Fix regression in parsing similar `dict` keys.\n\n\n## 3.4.2 - 2020-10-29\n\n### Changed\n\n- Improve deserialization performance.\n- Publish Windows python3.9 wheel.\n- Disable unsupported SIMD features on non-x86, non-ARM targets\n\n\n## 3.4.1 - 2020-10-20\n\n### Fixed\n\n- Fix `orjson.dumps.__module__` and `orjson.loads.__module__` not being the\n`str` \"orjson\".\n\n### Changed\n\n- Publish macos python3.9 wheel.\n- More packaging documentation.\n\n\n## 3.4.0 - 2020-09-25\n\n### Added\n\n- Serialize `numpy.uint8` and `numpy.int8` instances.\n\n### Fixed\n\n- Fix serializing `numpy.empty()` instances.\n\n### Changed\n\n- No longer publish `manylinux1` wheels due to tooling dropping support.\n\n\n## 3.3.1 - 2020-08-17\n\n### Fixed\n\n- Fix failure to deserialize some latin1 strings on some platforms. This\nwas introduced in 3.2.0.\n- Fix annotation of optional parameters on `orjson.dumps()` for `help()`.\n\n### Changed\n\n- Publish `manylinux2014` wheels for amd64 in addition to `manylinux1`.\n\n\n## 3.3.0 - 2020-07-24\n\n### Added\n\n- `orjson.dumps()` now serializes individual numpy floats and integers, e.g.,\n`numpy.float64(1.0)`.\n- `orjson.OPT_PASSTHROUGH_DATACLASS` causes `orjson.dumps()` to pass\n`dataclasses.dataclass` instances to `default`.\n\n\n## 3.2.2 - 2020-07-13\n\n### Fixed\n\n- Fix serializing `dataclasses.dataclass` that have no attributes.\n\n### Changed\n\n- Improve deserialization performance of `str`.\n\n\n## 3.2.1 - 2020-07-03\n\n### Fixed\n\n- Fix `orjson.dumps(..., **{})` raising `TypeError` on python3.6.\n\n\n## 3.2.0 - 2020-06-30\n\n### Added\n\n- `orjson.OPT_APPEND_NEWLINE` appends a newline to output.\n\n### Changed\n\n- Improve deserialization performance of `str`.\n\n\n## 3.1.2 - 2020-06-23\n\n### Fixed\n\n- Fix serializing zero-dimension `numpy.ndarray`.\n\n\n## 3.1.1 - 2020-06-20\n\n### Fixed\n\n- Fix repeated serialization of `str` that are ASCII-only and have a legacy\n(non-compact) layout.\n\n\n## 3.1.0 - 2020-06-08\n\n### Added\n\n- `orjson.OPT_PASSTHROUGH_SUBCLASS` causes `orjson.dumps()` to pass\nsubclasses of builtin types to `default` so the caller can customize the\noutput.\n- `orjson.OPT_PASSTHROUGH_DATETIME` causes `orjson.dumps()` to pass\n`datetime` objects to `default` so the caller can customize the\noutput.\n\n\n## 3.0.2 - 2020-05-27\n\n### Changed\n\n- `orjson.dumps()` does not serialize `dataclasses.dataclass` attributes\nthat begin with a leading underscore, e.g., `_attr`. This is because of the\nPython idiom that a leading underscores marks an attribute as \"private.\"\n- `orjson.dumps()` does not serialize `dataclasses.dataclass` attributes that\nare `InitVar` or `ClassVar` whether using `__slots__` or not.\n\n\n## 3.0.1 - 2020-05-19\n\n### Fixed\n\n- `orjson.dumps()` raises an exception if the object to be serialized\nis not given as a positional argument. `orjson.dumps({})` is intended and ok\nwhile `orjson.dumps(obj={})` is an error. This makes it consistent with the\ndocumentation, `help()` annotation, and type annotation.\n- Fix orphan reference in exception creation that leaks memory until the\ngarbage collector runs.\n\n### Changed\n\n- Improve serialization performance marginally by using the fastcall/vectorcall\ncalling convention on python3.7 and above.\n- Reduce build time.\n\n\n## 3.0.0 - 2020-05-01\n\n### Added\n\n- `orjson.dumps()` serializes subclasses of `str`, `int`, `list`, and `dict`.\n\n### Changed\n\n- `orjson.dumps()` serializes `dataclasses.dataclass` and `uuid.UUID`\ninstances by default. The options `OPT_SERIALIZE_DATACLASS` and\n`OPT_SERIALIZE_UUID` can still be specified but have no effect.\n\n\n## 2.6.8 - 2020-04-30\n\n### Changed\n\n- The source distribution vendors a forked dependency.\n\n\n## 2.6.7 - 2020-04-30\n\n### Fixed\n\n- Fix integer overflows in debug builds.\n\n### Changed\n\n- The source distribution sets the recommended RUSTFLAGS in `.cargo/config`.\n\n\n## 2.6.6 - 2020-04-24\n\n### Fixed\n\n- Import `numpy` only on first use of `OPT_SERIALIZE_NUMPY` to reduce\ninterpreter start time when not used.\n- Reduce build time by half.\n\n\n## 2.6.5 - 2020-04-08\n\n### Fixed\n\n- Fix deserialization raising `JSONDecodeError` on some valid negative\nfloats with large exponents.\n\n\n## 2.6.4 - 2020-04-08\n\n### Changed\n\n- Improve deserialization performance of floats by about 40%.\n\n\n## 2.6.3 - 2020-04-01\n\n### Changed\n\n- Serialize `enum.Enum` objects.\n- Minor performance improvements.\n\n\n## 2.6.2 - 2020-03-27\n\n### Changed\n\n- Publish python3.9 `manylinux2014` wheel instead of `manylinux1` for `x86_64`.\n- Publish python3.9 `manylinux2014` wheel for `aarch64`.\n\n### Fixed\n\n- Fix compilation failure on 32-bit.\n\n\n## 2.6.1 - 2020-03-19\n\n### Changed\n\n- Serialization is 10-20% faster and uses about 50% less memory by writing\ndirectly to the returned `bytes` object.\n\n\n## 2.6.0 - 2020-03-10\n\n### Added\n\n- `orjson.dumps()` pretty prints with an indentation of two spaces if\n`option=orjson.OPT_INDENT_2` is specified.\n\n\n## 2.5.2 - 2020-03-07\n\n### Changed\n\n- Publish `manylinux2014` wheels for `aarch64`.\n- numpy support now includes `numpy.uint32` and `numpy.uint64`.\n\n\n## 2.5.1 - 2020-02-24\n\n### Changed\n\n- `manylinux1` wheels for 3.6, 3.7, and 3.8 are now compliant with the spec by\nnot depending on glibc 2.18.\n\n\n## 2.5.0 - 2020-02-19\n\n### Added\n\n- `orjson.dumps()` serializes `dict` keys of type other than `str` if\n`option=orjson.OPT_NON_STR_KEYS` is specified.\n\n\n## 2.4.0 - 2020-02-14\n\n### Added\n\n- `orjson.dumps()` serializes `numpy.ndarray` instances if\n`option=orjson.OPT_SERIALIZE_NUMPY` is specified.\n\n### Fixed\n\n- Fix `dataclasses.dataclass` attributes that are `dict` to be effected by\n`orjson.OPT_SORT_KEYS`.\n\n\n## 2.3.0 - 2020-02-12\n\n### Added\n\n- `orjson.dumps()` serializes `dict` instances sorted by keys, equivalent to\n`sort_keys` in other implementations, if `option=orjson.OPT_SORT_KEYS` is\nspecified.\n\n### Changed\n\n- `dataclasses.dataclass` instances without `__slots__` now serialize faster.\n\n### Fixed\n\n- Fix documentation on `default`, in particular documenting the need to raise\nan exception if the type cannot be handled.\n\n\n## 2.2.2 - 2020-02-10\n\n### Changed\n\n- Performance improvements to serializing a list containing elements of the\nsame type.\n\n\n## 2.2.1 - 2020-02-04\n\n### Fixed\n\n- `orjson.loads()` rejects floats that do not have a digit following\nthe decimal, e.g., `-2.`, `2.e-3`.\n\n### Changed\n\n- Build Linux, macOS, and Windows wheels on more recent distributions.\n\n\n## 2.2.0 - 2020-01-22\n\n### Added\n\n- `orjson.dumps()` serializes `uuid.UUID` instances if\n`option=orjson.OPT_SERIALIZE_UUID` is specified.\n\n### Changed\n\n- Minor performance improvements.\n- Publish Python 3.9 wheel for Linux.\n\n\n## 2.1.4 - 2020-01-08\n\n### Fixed\n\n- Specify a text signature for `orjson.loads()`.\n\n### Changed\n\n- Improve documentation.\n\n\n## 2.1.3 - 2019-11-12\n\n### Changed\n\n- Publish Python 3.8 wheels for macOS and Windows.\n\n\n## 2.1.2 - 2019-11-07\n\n### Changed\n\n- The recursion limit of `default` on `orjson.dumps()` has been increased from\n5 to 254.\n\n\n## 2.1.1 - 2019-10-29\n\n### Changed\n\n- Publish `manylinux1` wheels instead of `manylinux2010`.\n\n\n## 2.1.0 - 2019-10-24\n\n### Added\n\n- `orjson.dumps()` serializes `dataclasses.dataclass` instances if\n`option=orjson.OPT_SERIALIZE_DATACLASS` is specified.\n- `orjson.dumps()` accepts `orjson.OPT_UTC_Z` to serialize UTC as \"Z\" instead\nof \"+00:00\".\n- `orjson.dumps()` accepts `orjson.OPT_OMIT_MICROSECONDS` to not serialize\nthe `microseconds` attribute of `datetime.datetime` and `datetime.time`\ninstances.\n- `orjson.loads()` accepts `bytearray`.\n\n### Changed\n\n- Drop support for Python 3.5.\n- Publish `manylinux2010` wheels instead of `manylinux1`.\n\n\n## 2.0.11 - 2019-10-01\n\n### Changed\n\n- Publish Python 3.8 wheel for Linux.\n\n\n## 2.0.10 - 2019-09-25\n\n### Changed\n\n- Performance improvements and lower memory usage in deserialization\nby creating only one `str` object for repeated map keys.\n\n\n## 2.0.9 - 2019-09-22\n\n### Changed\n\n- Minor performance improvements.\n\n### Fixed\n\n- Fix inaccurate zero padding in serialization of microseconds on\n`datetime.time` objects.\n\n\n## 2.0.8 - 2019-09-18\n\n### Fixed\n\n- Fix inaccurate zero padding in serialization of microseconds on\n`datetime.datetime` objects.\n\n\n## 2.0.7 - 2019-08-29\n\n### Changed\n\n- Publish PEP 517 source distribution.\n\n### Fixed\n\n- `orjson.dumps()` raises `JSONEncodeError` on circular references.\n\n\n## 2.0.6 - 2019-05-11\n\n### Changed\n\n- Performance improvements.\n\n\n## 2.0.5 - 2019-04-19\n\n### Fixed\n\n- Fix inaccuracy in deserializing some `float` values, e.g.,\n31.245270191439438 was parsed to 31.24527019143944. Serialization was\nunaffected.\n\n\n## 2.0.4 - 2019-04-02\n\n### Changed\n\n- `orjson.dumps()` now serializes `datetime.datetime` objects without a\n`tzinfo` rather than raising `JSONEncodeError`.\n\n\n## 2.0.3 - 2019-03-23\n\n### Changed\n\n- `orjson.loads()` uses SSE2 to validate `bytes` input.\n\n\n## 2.0.2 - 2019-03-12\n\n### Changed\n\n- Support Python 3.5.\n\n\n## 2.0.1 - 2019-02-05\n\n### Changed\n\n- Publish Windows wheel.\n\n\n## 2.0.0 - 2019-01-28\n\n### Added\n\n- `orjson.dumps()` accepts a `default` callable to serialize arbitrary\ntypes.\n- `orjson.dumps()` accepts `datetime.datetime`, `datetime.date`,\nand `datetime.time`. Each is serialized to an RFC 3339 string.\n- `orjson.dumps(..., option=orjson.OPT_NAIVE_UTC)` allows serializing\n`datetime.datetime` objects that do not have a timezone set as UTC.\n- `orjson.dumps(..., option=orjson.OPT_STRICT_INTEGER)` available to\nraise an error on integer values outside the 53-bit range of all JSON\nimplementations.\n\n### Changed\n\n- `orjson.dumps()` no longer accepts `bytes`.\n\n\n## 1.3.1 - 2019-01-03\n\n### Fixed\n\n- Handle invalid UTF-8 in str.\n\n\n## 1.3.0 - 2019-01-02\n\n### Changed\n\n- Performance improvements of 15-25% on serialization, 10% on deserialization.\n\n\n## 1.2.1 - 2018-12-31\n\n### Fixed\n\n- Fix memory leak in deserializing dict.\n\n\n## 1.2.0 - 2018-12-16\n\n### Changed\n\n- Performance improvements.\n\n\n## 1.1.0 - 2018-12-04\n\n### Changed\n\n- Performance improvements.\n\n### Fixed\n\n- Dict key can only be str.\n\n\n## 1.0.1 - 2018-11-26\n\n### Fixed\n\n- pyo3 bugfix update.\n\n\n## 1.0.0 - 2018-11-23\n\n### Added\n\n- `orjson.dumps()` function.\n- `orjson.loads()` function.\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"orjson\"\nversion = \"3.11.7\"\nauthors = [\"ijl <ijl@mailbox.org>\"]\ndescription = \"Fast, correct Python JSON library supporting dataclasses, datetimes, and numpy\"\nrepository = \"https://github.com/ijl/orjson\"\nedition = \"2024\"\nresolver = \"3\"\nrust-version = \"1.89\"\nlicense = \"MPL-2.0 AND (Apache-2.0 OR MIT)\"\nkeywords = [\"fast\", \"json\", \"dataclass\", \"dataclasses\", \"datetime\", \"rfc\", \"8259\", \"3339\"]\ninclude = [\n    \"Cargo.toml\",\n    \"CHANGELOG.md\",\n    \"include/yyjson\",\n    \"LICENSE-APACHE\",\n    \"LICENSE-MIT\",\n    \"LICENSE-MPL-2.0\",\n    \"pyproject.toml\",\n    \"README.md\",\n    \"src\",\n    \"test/*.py\",\n    \"test/requirements.txt\",\n]\n\n[lib]\nname = \"orjson\"\ncrate-type = [\"cdylib\"]\n\n[features]\ndefault = []\n\n# Avoid bundling libgcc on musl.\nunwind = [\"unwinding\"]\n\n# Features detected by build.rs. Do not specify.\navx512 = []\ncold_path = []\ngeneric_simd = []\ninline_int = []\ninline_str = []\nno_panic = [\"zmij/no-panic\"]\noptimize = []\n\n[dependencies]\nassociative-cache = { version = \"2\", default-features = false }\nbytes = { version = \"1\", default-features = false }\nbytecount = { version = \"^0.6.7\", default-features = false, features = [\"runtime-dispatch-simd\"] }\nencoding_rs = { version = \"0.8\", default-features = false }\nhalf = { version = \"2\", default-features = false }\nitoa = { version = \"1\", default-features = false }\nitoap = { version = \"1\", default-features = false, features = [\"std\", \"simd\"] }\njiff = { version = \"^0.2\", default-features = false }\nonce_cell = { version = \"1\", default-features = false, features = [\"alloc\", \"race\"] }\npyo3-ffi = { version = \"0.28\", default-features = false }\nserde = { version = \"1\", default-features = false }\nserde_json = { version = \"1\", default-features = false, features = [\"std\"] }\nsimdutf8 = { version = \"0.1\", default-features = false, features = [\"std\", \"public_imp\", \"aarch64_neon\"] }\nsmallvec = { version = \"^1.11\", default-features = false, features = [\"union\", \"write\"] }\nunwinding = { version = \"=0.2.8\", default-features = false, features = [\"unwinder\"], optional = true }\nuuid = { version = \"1\", default-features = false }\nxxhash-rust = { version = \"^0.8\", default-features = false, features = [\"xxh3\"] }\nzmij = { version = \"1\", default-features = false }\n\n[build-dependencies]\ncc = { version = \"1\" }\npyo3-build-config = { version = \"0.28\" }\nversion_check = { version = \"0.9\" }\n\n[profile.dev]\ncodegen-units = 1\ndebug = 2\ndebug-assertions = true\nincremental = false\nlto = \"off\"\nopt-level = 3\noverflow-checks = true\n\n[profile.release]\ncodegen-units = 1\ndebug = false\nincremental = false\nlto = \"fat\"\nopt-level = 3\npanic = \"abort\"\n\n[profile.release.build-override]\nopt-level = 0\n"
  },
  {
    "path": "LICENSE-APACHE",
    "content": "                              Apache License\n                        Version 2.0, January 2004\n                     http://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n   \"License\" shall mean the terms and conditions for use, reproduction,\n   and distribution as defined by Sections 1 through 9 of this document.\n\n   \"Licensor\" shall mean the copyright owner or entity authorized by\n   the copyright owner that is granting the License.\n\n   \"Legal Entity\" shall mean the union of the acting entity and all\n   other entities that control, are controlled by, or are under common\n   control with that entity. For the purposes of this definition,\n   \"control\" means (i) the power, direct or indirect, to cause the\n   direction or management of such entity, whether by contract or\n   otherwise, or (ii) ownership of fifty percent (50%) or more of the\n   outstanding shares, or (iii) beneficial ownership of such entity.\n\n   \"You\" (or \"Your\") shall mean an individual or Legal Entity\n   exercising permissions granted by this License.\n\n   \"Source\" form shall mean the preferred form for making modifications,\n   including but not limited to software source code, documentation\n   source, and configuration files.\n\n   \"Object\" form shall mean any form resulting from mechanical\n   transformation or translation of a Source form, including but\n   not limited to compiled object code, generated documentation,\n   and conversions to other media types.\n\n   \"Work\" shall mean the work of authorship, whether in Source or\n   Object form, made available under the License, as indicated by a\n   copyright notice that is included in or attached to the work\n   (an example is provided in the Appendix below).\n\n   \"Derivative Works\" shall mean any work, whether in Source or Object\n   form, that is based on (or derived from) the Work and for which the\n   editorial revisions, annotations, elaborations, or other modifications\n   represent, as a whole, an original work of authorship. For the purposes\n   of this License, Derivative Works shall not include works that remain\n   separable from, or merely link (or bind by name) to the interfaces of,\n   the Work and Derivative Works thereof.\n\n   \"Contribution\" shall mean any work of authorship, including\n   the original version of the Work and any modifications or additions\n   to that Work or Derivative Works thereof, that is intentionally\n   submitted to Licensor for inclusion in the Work by the copyright owner\n   or by an individual or Legal Entity authorized to submit on behalf of\n   the copyright owner. For the purposes of this definition, \"submitted\"\n   means any form of electronic, verbal, or written communication sent\n   to the Licensor or its representatives, including but not limited to\n   communication on electronic mailing lists, source code control systems,\n   and issue tracking systems that are managed by, or on behalf of, the\n   Licensor for the purpose of discussing and improving the Work, but\n   excluding communication that is conspicuously marked or otherwise\n   designated in writing by the copyright owner as \"Not a Contribution.\"\n\n   \"Contributor\" shall mean Licensor and any individual or Legal Entity\n   on behalf of whom a Contribution has been received by Licensor and\n   subsequently incorporated within the Work.\n\n2. Grant of Copyright License. Subject to the terms and conditions of\n   this License, each Contributor hereby grants to You a perpetual,\n   worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n   copyright license to reproduce, prepare Derivative Works of,\n   publicly display, publicly perform, sublicense, and distribute the\n   Work and such Derivative Works in Source or Object form.\n\n3. Grant of Patent License. Subject to the terms and conditions of\n   this License, each Contributor hereby grants to You a perpetual,\n   worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n   (except as stated in this section) patent license to make, have made,\n   use, offer to sell, sell, import, and otherwise transfer the Work,\n   where such license applies only to those patent claims licensable\n   by such Contributor that are necessarily infringed by their\n   Contribution(s) alone or by combination of their Contribution(s)\n   with the Work to which such Contribution(s) was submitted. If You\n   institute patent litigation against any entity (including a\n   cross-claim or counterclaim in a lawsuit) alleging that the Work\n   or a Contribution incorporated within the Work constitutes direct\n   or contributory patent infringement, then any patent licenses\n   granted to You under this License for that Work shall terminate\n   as of the date such litigation is filed.\n\n4. Redistribution. You may reproduce and distribute copies of the\n   Work or Derivative Works thereof in any medium, with or without\n   modifications, and in Source or Object form, provided that You\n   meet the following conditions:\n\n   (a) You must give any other recipients of the Work or\n       Derivative Works a copy of this License; and\n\n   (b) You must cause any modified files to carry prominent notices\n       stating that You changed the files; and\n\n   (c) You must retain, in the Source form of any Derivative Works\n       that You distribute, all copyright, patent, trademark, and\n       attribution notices from the Source form of the Work,\n       excluding those notices that do not pertain to any part of\n       the Derivative Works; and\n\n   (d) If the Work includes a \"NOTICE\" text file as part of its\n       distribution, then any Derivative Works that You distribute must\n       include a readable copy of the attribution notices contained\n       within such NOTICE file, excluding those notices that do not\n       pertain to any part of the Derivative Works, in at least one\n       of the following places: within a NOTICE text file distributed\n       as part of the Derivative Works; within the Source form or\n       documentation, if provided along with the Derivative Works; or,\n       within a display generated by the Derivative Works, if and\n       wherever such third-party notices normally appear. The contents\n       of the NOTICE file are for informational purposes only and\n       do not modify the License. You may add Your own attribution\n       notices within Derivative Works that You distribute, alongside\n       or as an addendum to the NOTICE text from the Work, provided\n       that such additional attribution notices cannot be construed\n       as modifying the License.\n\n   You may add Your own copyright statement to Your modifications and\n   may provide additional or different license terms and conditions\n   for use, reproduction, or distribution of Your modifications, or\n   for any such Derivative Works as a whole, provided Your use,\n   reproduction, and distribution of the Work otherwise complies with\n   the conditions stated in this License.\n\n5. Submission of Contributions. Unless You explicitly state otherwise,\n   any Contribution intentionally submitted for inclusion in the Work\n   by You to the Licensor shall be under the terms and conditions of\n   this License, without any additional terms or conditions.\n   Notwithstanding the above, nothing herein shall supersede or modify\n   the terms of any separate license agreement you may have executed\n   with Licensor regarding such Contributions.\n\n6. Trademarks. This License does not grant permission to use the trade\n   names, trademarks, service marks, or product names of the Licensor,\n   except as required for reasonable and customary use in describing the\n   origin of the Work and reproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty. Unless required by applicable law or\n   agreed to in writing, Licensor provides the Work (and each\n   Contributor provides its Contributions) on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n   implied, including, without limitation, any warranties or conditions\n   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n   PARTICULAR PURPOSE. You are solely responsible for determining the\n   appropriateness of using or redistributing the Work and assume any\n   risks associated with Your exercise of permissions under this License.\n\n8. Limitation of Liability. In no event and under no legal theory,\n   whether in tort (including negligence), contract, or otherwise,\n   unless required by applicable law (such as deliberate and grossly\n   negligent acts) or agreed to in writing, shall any Contributor be\n   liable to You for damages, including any direct, indirect, special,\n   incidental, or consequential damages of any character arising as a\n   result of this License or out of the use or inability to use the\n   Work (including but not limited to damages for loss of goodwill,\n   work stoppage, computer failure or malfunction, or any and all\n   other commercial damages or losses), even if such Contributor\n   has been advised of the possibility of such damages.\n\n9. Accepting Warranty or Additional Liability. While redistributing\n   the Work or Derivative Works thereof, You may choose to offer,\n   and charge a fee for, acceptance of support, warranty, indemnity,\n   or other liability obligations and/or rights consistent with this\n   License. However, in accepting such obligations, You may act only\n   on Your own behalf and on Your sole responsibility, not on behalf\n   of any other Contributor, and only if You agree to indemnify,\n   defend, and hold each Contributor harmless for any liability\n   incurred by, or claims asserted against, such Contributor by reason\n   of your accepting any such warranty or additional liability.\n\nEND OF TERMS AND CONDITIONS\n\nAPPENDIX: How to apply the Apache License to your work.\n\n   To apply the Apache License to your work, attach the following\n   boilerplate notice, with the fields enclosed by brackets \"[]\"\n   replaced with your own identifying information. (Don't include\n   the brackets!)  The text should be enclosed in the appropriate\n   comment syntax for the file format. We also recommend that a\n   file or class name and description of purpose be included on the\n   same \"printed page\" as the copyright notice for easier\n   identification within third-party archives.\n\nCopyright [yyyy] [name of copyright owner]\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n"
  },
  {
    "path": "LICENSE-MIT",
    "content": "Permission is hereby granted, free of charge, to any\nperson obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the\nSoftware without restriction, including without\nlimitation the rights to use, copy, modify, merge,\npublish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software\nis furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice\nshall be included in all copies or substantial portions\nof the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\nANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\nTO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\nSHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\nIN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "LICENSE-MPL-2.0",
    "content": "Mozilla Public License Version 2.0\n==================================\n\n1. Definitions\n--------------\n\n1.1. \"Contributor\"\n    means each individual or legal entity that creates, contributes to\n    the creation of, or owns Covered Software.\n\n1.2. \"Contributor Version\"\n    means the combination of the Contributions of others (if any) used\n    by a Contributor and that particular Contributor's Contribution.\n\n1.3. \"Contribution\"\n    means Covered Software of a particular Contributor.\n\n1.4. \"Covered Software\"\n    means Source Code Form to which the initial Contributor has attached\n    the notice in Exhibit A, the Executable Form of such Source Code\n    Form, and Modifications of such Source Code Form, in each case\n    including portions thereof.\n\n1.5. \"Incompatible With Secondary Licenses\"\n    means\n\n    (a) that the initial Contributor has attached the notice described\n        in Exhibit B to the Covered Software; or\n\n    (b) that the Covered Software was made available under the terms of\n        version 1.1 or earlier of the License, but not also under the\n        terms of a Secondary License.\n\n1.6. \"Executable Form\"\n    means any form of the work other than Source Code Form.\n\n1.7. \"Larger Work\"\n    means a work that combines Covered Software with other material, in \n    a separate file or files, that is not Covered Software.\n\n1.8. \"License\"\n    means this document.\n\n1.9. \"Licensable\"\n    means having the right to grant, to the maximum extent possible,\n    whether at the time of the initial grant or subsequently, any and\n    all of the rights conveyed by this License.\n\n1.10. \"Modifications\"\n    means any of the following:\n\n    (a) any file in Source Code Form that results from an addition to,\n        deletion from, or modification of the contents of Covered\n        Software; or\n\n    (b) any new file in Source Code Form that contains any Covered\n        Software.\n\n1.11. \"Patent Claims\" of a Contributor\n    means any patent claim(s), including without limitation, method,\n    process, and apparatus claims, in any patent Licensable by such\n    Contributor that would be infringed, but for the grant of the\n    License, by the making, using, selling, offering for sale, having\n    made, import, or transfer of either its Contributions or its\n    Contributor Version.\n\n1.12. \"Secondary License\"\n    means either the GNU General Public License, Version 2.0, the GNU\n    Lesser General Public License, Version 2.1, the GNU Affero General\n    Public License, Version 3.0, or any later versions of those\n    licenses.\n\n1.13. \"Source Code Form\"\n    means the form of the work preferred for making modifications.\n\n1.14. \"You\" (or \"Your\")\n    means an individual or a legal entity exercising rights under this\n    License. For legal entities, \"You\" includes any entity that\n    controls, is controlled by, or is under common control with You. For\n    purposes of this definition, \"control\" means (a) the power, direct\n    or indirect, to cause the direction or management of such entity,\n    whether by contract or otherwise, or (b) ownership of more than\n    fifty percent (50%) of the outstanding shares or beneficial\n    ownership of such entity.\n\n2. License Grants and Conditions\n--------------------------------\n\n2.1. Grants\n\nEach Contributor hereby grants You a world-wide, royalty-free,\nnon-exclusive license:\n\n(a) under intellectual property rights (other than patent or trademark)\n    Licensable by such Contributor to use, reproduce, make available,\n    modify, display, perform, distribute, and otherwise exploit its\n    Contributions, either on an unmodified basis, with Modifications, or\n    as part of a Larger Work; and\n\n(b) under Patent Claims of such Contributor to make, use, sell, offer\n    for sale, have made, import, and otherwise transfer either its\n    Contributions or its Contributor Version.\n\n2.2. Effective Date\n\nThe licenses granted in Section 2.1 with respect to any Contribution\nbecome effective for each Contribution on the date the Contributor first\ndistributes such Contribution.\n\n2.3. Limitations on Grant Scope\n\nThe licenses granted in this Section 2 are the only rights granted under\nthis License. No additional rights or licenses will be implied from the\ndistribution or licensing of Covered Software under this License.\nNotwithstanding Section 2.1(b) above, no patent license is granted by a\nContributor:\n\n(a) for any code that a Contributor has removed from Covered Software;\n    or\n\n(b) for infringements caused by: (i) Your and any other third party's\n    modifications of Covered Software, or (ii) the combination of its\n    Contributions with other software (except as part of its Contributor\n    Version); or\n\n(c) under Patent Claims infringed by Covered Software in the absence of\n    its Contributions.\n\nThis License does not grant any rights in the trademarks, service marks,\nor logos of any Contributor (except as may be necessary to comply with\nthe notice requirements in Section 3.4).\n\n2.4. Subsequent Licenses\n\nNo Contributor makes additional grants as a result of Your choice to\ndistribute the Covered Software under a subsequent version of this\nLicense (see Section 10.2) or under the terms of a Secondary License (if\npermitted under the terms of Section 3.3).\n\n2.5. Representation\n\nEach Contributor represents that the Contributor believes its\nContributions are its original creation(s) or it has sufficient rights\nto grant the rights to its Contributions conveyed by this License.\n\n2.6. Fair Use\n\nThis License is not intended to limit any rights You have under\napplicable copyright doctrines of fair use, fair dealing, or other\nequivalents.\n\n2.7. Conditions\n\nSections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted\nin Section 2.1.\n\n3. Responsibilities\n-------------------\n\n3.1. Distribution of Source Form\n\nAll distribution of Covered Software in Source Code Form, including any\nModifications that You create or to which You contribute, must be under\nthe terms of this License. You must inform recipients that the Source\nCode Form of the Covered Software is governed by the terms of this\nLicense, and how they can obtain a copy of this License. You may not\nattempt to alter or restrict the recipients' rights in the Source Code\nForm.\n\n3.2. Distribution of Executable Form\n\nIf You distribute Covered Software in Executable Form then:\n\n(a) such Covered Software must also be made available in Source Code\n    Form, as described in Section 3.1, and You must inform recipients of\n    the Executable Form how they can obtain a copy of such Source Code\n    Form by reasonable means in a timely manner, at a charge no more\n    than the cost of distribution to the recipient; and\n\n(b) You may distribute such Executable Form under the terms of this\n    License, or sublicense it under different terms, provided that the\n    license for the Executable Form does not attempt to limit or alter\n    the recipients' rights in the Source Code Form under this License.\n\n3.3. Distribution of a Larger Work\n\nYou may create and distribute a Larger Work under terms of Your choice,\nprovided that You also comply with the requirements of this License for\nthe Covered Software. If the Larger Work is a combination of Covered\nSoftware with a work governed by one or more Secondary Licenses, and the\nCovered Software is not Incompatible With Secondary Licenses, this\nLicense permits You to additionally distribute such Covered Software\nunder the terms of such Secondary License(s), so that the recipient of\nthe Larger Work may, at their option, further distribute the Covered\nSoftware under the terms of either this License or such Secondary\nLicense(s).\n\n3.4. Notices\n\nYou may not remove or alter the substance of any license notices\n(including copyright notices, patent notices, disclaimers of warranty,\nor limitations of liability) contained within the Source Code Form of\nthe Covered Software, except that You may alter any license notices to\nthe extent required to remedy known factual inaccuracies.\n\n3.5. Application of Additional Terms\n\nYou may choose to offer, and to charge a fee for, warranty, support,\nindemnity or liability obligations to one or more recipients of Covered\nSoftware. However, You may do so only on Your own behalf, and not on\nbehalf of any Contributor. You must make it absolutely clear that any\nsuch warranty, support, indemnity, or liability obligation is offered by\nYou alone, and You hereby agree to indemnify every Contributor for any\nliability incurred by such Contributor as a result of warranty, support,\nindemnity or liability terms You offer. You may include additional\ndisclaimers of warranty and limitations of liability specific to any\njurisdiction.\n\n4. Inability to Comply Due to Statute or Regulation\n---------------------------------------------------\n\nIf it is impossible for You to comply with any of the terms of this\nLicense with respect to some or all of the Covered Software due to\nstatute, judicial order, or regulation then You must: (a) comply with\nthe terms of this License to the maximum extent possible; and (b)\ndescribe the limitations and the code they affect. Such description must\nbe placed in a text file included with all distributions of the Covered\nSoftware under this License. Except to the extent prohibited by statute\nor regulation, such description must be sufficiently detailed for a\nrecipient of ordinary skill to be able to understand it.\n\n5. Termination\n--------------\n\n5.1. The rights granted under this License will terminate automatically\nif You fail to comply with any of its terms. However, if You become\ncompliant, then the rights granted under this License from a particular\nContributor are reinstated (a) provisionally, unless and until such\nContributor explicitly and finally terminates Your grants, and (b) on an\nongoing basis, if such Contributor fails to notify You of the\nnon-compliance by some reasonable means prior to 60 days after You have\ncome back into compliance. Moreover, Your grants from a particular\nContributor are reinstated on an ongoing basis if such Contributor\nnotifies You of the non-compliance by some reasonable means, this is the\nfirst time You have received notice of non-compliance with this License\nfrom such Contributor, and You become compliant prior to 30 days after\nYour receipt of the notice.\n\n5.2. If You initiate litigation against any entity by asserting a patent\ninfringement claim (excluding declaratory judgment actions,\ncounter-claims, and cross-claims) alleging that a Contributor Version\ndirectly or indirectly infringes any patent, then the rights granted to\nYou by any and all Contributors for the Covered Software under Section\n2.1 of this License shall terminate.\n\n5.3. In the event of termination under Sections 5.1 or 5.2 above, all\nend user license agreements (excluding distributors and resellers) which\nhave been validly granted by You or Your distributors under this License\nprior to termination shall survive termination.\n\n************************************************************************\n*                                                                      *\n*  6. Disclaimer of Warranty                                           *\n*  -------------------------                                           *\n*                                                                      *\n*  Covered Software is provided under this License on an \"as is\"       *\n*  basis, without warranty of any kind, either expressed, implied, or  *\n*  statutory, including, without limitation, warranties that the       *\n*  Covered Software is free of defects, merchantable, fit for a        *\n*  particular purpose or non-infringing. The entire risk as to the     *\n*  quality and performance of the Covered Software is with You.        *\n*  Should any Covered Software prove defective in any respect, You     *\n*  (not any Contributor) assume the cost of any necessary servicing,   *\n*  repair, or correction. This disclaimer of warranty constitutes an   *\n*  essential part of this License. No use of any Covered Software is   *\n*  authorized under this License except under this disclaimer.         *\n*                                                                      *\n************************************************************************\n\n************************************************************************\n*                                                                      *\n*  7. Limitation of Liability                                          *\n*  --------------------------                                          *\n*                                                                      *\n*  Under no circumstances and under no legal theory, whether tort      *\n*  (including negligence), contract, or otherwise, shall any           *\n*  Contributor, or anyone who distributes Covered Software as          *\n*  permitted above, be liable to You for any direct, indirect,         *\n*  special, incidental, or consequential damages of any character      *\n*  including, without limitation, damages for lost profits, loss of    *\n*  goodwill, work stoppage, computer failure or malfunction, or any    *\n*  and all other commercial damages or losses, even if such party      *\n*  shall have been informed of the possibility of such damages. This   *\n*  limitation of liability shall not apply to liability for death or   *\n*  personal injury resulting from such party's negligence to the       *\n*  extent applicable law prohibits such limitation. Some               *\n*  jurisdictions do not allow the exclusion or limitation of           *\n*  incidental or consequential damages, so this exclusion and          *\n*  limitation may not apply to You.                                    *\n*                                                                      *\n************************************************************************\n\n8. Litigation\n-------------\n\nAny litigation relating to this License may be brought only in the\ncourts of a jurisdiction where the defendant maintains its principal\nplace of business and such litigation shall be governed by laws of that\njurisdiction, without reference to its conflict-of-law provisions.\nNothing in this Section shall prevent a party's ability to bring\ncross-claims or counter-claims.\n\n9. Miscellaneous\n----------------\n\nThis License represents the complete agreement concerning the subject\nmatter hereof. If any provision of this License is held to be\nunenforceable, such provision shall be reformed only to the extent\nnecessary to make it enforceable. Any law or regulation which provides\nthat the language of a contract shall be construed against the drafter\nshall not be used to construe this License against a Contributor.\n\n10. Versions of the License\n---------------------------\n\n10.1. New Versions\n\nMozilla Foundation is the license steward. Except as provided in Section\n10.3, no one other than the license steward has the right to modify or\npublish new versions of this License. Each version will be given a\ndistinguishing version number.\n\n10.2. Effect of New Versions\n\nYou may distribute the Covered Software under the terms of the version\nof the License under which You originally received the Covered Software,\nor under the terms of any subsequent version published by the license\nsteward.\n\n10.3. Modified Versions\n\nIf you create software not governed by this License, and you want to\ncreate a new license for such software, you may create and use a\nmodified version of this License if you rename the license and remove\nany references to the name of the license steward (except to note that\nsuch modified license differs from this License).\n\n10.4. Distributing Source Code Form that is Incompatible With Secondary\nLicenses\n\nIf You choose to distribute Source Code Form that is Incompatible With\nSecondary Licenses under the terms of this version of the License, the\nnotice described in Exhibit B of this License must be attached.\n\nExhibit A - Source Code Form License Notice\n-------------------------------------------\n\n  This Source Code Form is subject to the terms of the Mozilla Public\n  License, v. 2.0. If a copy of the MPL was not distributed with this\n  file, You can obtain one at https://mozilla.org/MPL/2.0/.\n\nIf it is not possible or desirable to put the notice in a particular\nfile, then You may include the notice in a location (such as a LICENSE\nfile in a relevant directory) where a recipient would be likely to look\nfor such a notice.\n\nYou may add additional accurate notices of copyright ownership.\n\nExhibit B - \"Incompatible With Secondary Licenses\" Notice\n---------------------------------------------------------\n\n  This Source Code Form is \"Incompatible With Secondary Licenses\", as\n  defined by the Mozilla Public License, v. 2.0.\n"
  },
  {
    "path": "README.md",
    "content": "# orjson\n\norjson is a fast, correct JSON library for Python. It\n[benchmarks](https://github.com/ijl/orjson?tab=readme-ov-file#performance) as the fastest Python\nlibrary for JSON and is more correct than the standard json library or other\nthird-party libraries. It serializes\n[dataclass](https://github.com/ijl/orjson?tab=readme-ov-file#dataclass),\n[datetime](https://github.com/ijl/orjson?tab=readme-ov-file#datetime),\n[numpy](https://github.com/ijl/orjson?tab=readme-ov-file#numpy), and\n[UUID](https://github.com/ijl/orjson?tab=readme-ov-file#uuid) instances natively.\n\n[orjson.dumps()](https://github.com/ijl/orjson?tab=readme-ov-file#serialize) is\nsomething like 10x as fast as `json`, serializes\ncommon types and subtypes, has a `default` parameter for the caller to specify\nhow to serialize arbitrary types, and has a number of flags controlling output.\n\n[orjson.loads()](https://github.com/ijl/orjson?tab=readme-ov-file#deserialize)\nis something like 2x as fast as `json`, and is strictly compliant with UTF-8 and\nRFC 8259 (\"The JavaScript Object Notation (JSON) Data Interchange Format\").\n\nReading from and writing to files, line-delimited JSON files, and so on is\nnot provided by the library.\n\norjson supports CPython 3.10, 3.11, 3.12, 3.13, 3.14, and 3.15.\n\nIt distributes amd64/x86_64/x64, i686/x86, aarch64/arm64/armv8, arm7,\nppc64le/POWER8, and s390x wheels for Linux, amd64 and aarch64 wheels\nfor macOS, and amd64, i686, and aarch64 wheels for Windows.\n\nWheels published to PyPI for amd64 run on x86-64-v1 (2003)\nor later, but will at runtime use AVX-512 if available for a\nsignificant performance benefit; aarch64 wheels run on ARMv8-A (2011) or\nlater.\n\norjson does not and will not support PyPy, embedded Python builds for\nAndroid/iOS, or PEP 554 subinterpreters.\n\norjson may support PEP 703 free-threading when it is stable.\n\nReleases follow semantic versioning and serializing a new object type\nwithout an opt-in flag is considered a breaking change.\n\norjson contains source code licensed under the Mozilla Public License 2.0,\nApache 2.0, and MIT licenses. The repository from which PyPI artifacts are\npublished is [github.com/ijl/orjson](https://github.com/ijl/orjson) and an\nalternative repository is [codeberg.org/ijl/orjson](https://codeberg.org/ijl/orjson).\nThere is no open issue tracker or pull requests due to signal-to-noise ratio.\nThere is a [CHANGELOG](https://github.com/ijl/orjson/blob/master/CHANGELOG.md)\navailable in the repository.\n\n1. [Usage](https://github.com/ijl/orjson?tab=readme-ov-file#usage)\n    1. [Install](https://github.com/ijl/orjson?tab=readme-ov-file#install)\n    2. [Quickstart](https://github.com/ijl/orjson?tab=readme-ov-file#quickstart)\n    3. [Migrating](https://github.com/ijl/orjson?tab=readme-ov-file#migrating)\n    4. [Serialize](https://github.com/ijl/orjson?tab=readme-ov-file#serialize)\n        1. [default](https://github.com/ijl/orjson?tab=readme-ov-file#default)\n        2. [option](https://github.com/ijl/orjson?tab=readme-ov-file#option)\n        3. [Fragment](https://github.com/ijl/orjson?tab=readme-ov-file#fragment)\n    5. [Deserialize](https://github.com/ijl/orjson?tab=readme-ov-file#deserialize)\n2. [Types](https://github.com/ijl/orjson?tab=readme-ov-file#types)\n    1. [dataclass](https://github.com/ijl/orjson?tab=readme-ov-file#dataclass)\n    2. [datetime](https://github.com/ijl/orjson?tab=readme-ov-file#datetime)\n    3. [enum](https://github.com/ijl/orjson?tab=readme-ov-file#enum)\n    4. [float](https://github.com/ijl/orjson?tab=readme-ov-file#float)\n    5. [int](https://github.com/ijl/orjson?tab=readme-ov-file#int)\n    6. [numpy](https://github.com/ijl/orjson?tab=readme-ov-file#numpy)\n    7. [str](https://github.com/ijl/orjson?tab=readme-ov-file#str)\n    8. [uuid](https://github.com/ijl/orjson?tab=readme-ov-file#uuid)\n3. [Testing](https://github.com/ijl/orjson?tab=readme-ov-file#testing)\n4. [Performance](https://github.com/ijl/orjson?tab=readme-ov-file#performance)\n    1. [Latency](https://github.com/ijl/orjson?tab=readme-ov-file#latency)\n    2. [Reproducing](https://github.com/ijl/orjson?tab=readme-ov-file#reproducing)\n5. [Questions](https://github.com/ijl/orjson?tab=readme-ov-file#questions)\n6. [Packaging](https://github.com/ijl/orjson?tab=readme-ov-file#packaging)\n7. [License](https://github.com/ijl/orjson?tab=readme-ov-file#license)\n\n## Usage\n\n### Install\n\nTo install a wheel from PyPI, install the `orjson` package.\n\nIn `requirements.in` or `requirements.txt` format, specify:\n\n```txt\norjson >= 3.10,<4\n```\n\nIn `pyproject.toml` format, specify:\n\n```toml\norjson = \"^3.10\"\n```\n\nTo build a wheel, see [packaging](https://github.com/ijl/orjson?tab=readme-ov-file#packaging).\n\n### Quickstart\n\nThis is an example of serializing, with options specified, and deserializing:\n\n```python\n>>> import orjson, datetime, numpy\n>>> data = {\n    \"type\": \"job\",\n    \"created_at\": datetime.datetime(1970, 1, 1),\n    \"status\": \"🆗\",\n    \"payload\": numpy.array([[1, 2], [3, 4]]),\n}\n>>> orjson.dumps(data, option=orjson.OPT_NAIVE_UTC | orjson.OPT_SERIALIZE_NUMPY)\nb'{\"type\":\"job\",\"created_at\":\"1970-01-01T00:00:00+00:00\",\"status\":\"\\xf0\\x9f\\x86\\x97\",\"payload\":[[1,2],[3,4]]}'\n>>> orjson.loads(_)\n{'type': 'job', 'created_at': '1970-01-01T00:00:00+00:00', 'status': '🆗', 'payload': [[1, 2], [3, 4]]}\n```\n\n### Migrating\n\norjson version 3 serializes more types than version 2. Subclasses of `str`,\n`int`, `dict`, and `list` are now serialized. This is faster and more similar\nto the standard library. It can be disabled with\n`orjson.OPT_PASSTHROUGH_SUBCLASS`.`dataclasses.dataclass` instances\nare now serialized by default and cannot be customized in a\n`default` function unless `option=orjson.OPT_PASSTHROUGH_DATACLASS` is\nspecified. `uuid.UUID` instances are serialized by default.\nFor any type that is now serialized,\nimplementations in a `default` function and options enabling them can be\nremoved but do not need to be. There was no change in deserialization.\n\nTo migrate from the standard library, the largest difference is that\n`orjson.dumps` returns `bytes` and `json.dumps` returns a `str`.\n\nUsers with `dict` objects using non-`str` keys should specify `option=orjson.OPT_NON_STR_KEYS`.\n\n`sort_keys` is replaced by `option=orjson.OPT_SORT_KEYS`.\n\n`indent` is replaced by `option=orjson.OPT_INDENT_2` and other levels of indentation are not\nsupported.\n\n`ensure_ascii` is probably not relevant today and UTF-8 characters cannot be\nescaped to ASCII.\n\n### Serialize\n\n```python\ndef dumps(\n    __obj: Any,\n    default: Optional[Callable[[Any], Any]] = ...,\n    option: Optional[int] = ...,\n) -> bytes: ...\n```\n\n`dumps()` serializes Python objects to JSON.\n\nIt natively serializes\n`str`, `dict`, `list`, `tuple`, `int`, `float`, `bool`, `None`,\n`dataclasses.dataclass`, `typing.TypedDict`, `datetime.datetime`,\n`datetime.date`, `datetime.time`, `uuid.UUID`, `numpy.ndarray`, and\n`orjson.Fragment` instances. It supports arbitrary types through `default`. It\nserializes subclasses of `str`, `int`, `dict`, `list`,\n`dataclasses.dataclass`, and `enum.Enum`. It does not serialize subclasses\nof `tuple` to avoid serializing `namedtuple` objects as arrays. To avoid\nserializing subclasses, specify the option `orjson.OPT_PASSTHROUGH_SUBCLASS`.\n\nThe output is a `bytes` object containing UTF-8.\n\nThe global interpreter lock (GIL) is held for the duration of the call.\n\nIt raises `JSONEncodeError` on an unsupported type. This exception message\ndescribes the invalid object with the error message\n`Type is not JSON serializable: ...`. To fix this, specify\n[default](https://github.com/ijl/orjson?tab=readme-ov-file#default).\n\nIt raises `JSONEncodeError` on a `str` that contains invalid UTF-8.\n\nIt raises `JSONEncodeError` on an integer that exceeds 64 bits by default or,\nwith `OPT_STRICT_INTEGER`, 53 bits.\n\nIt raises `JSONEncodeError` if a `dict` has a key of a type other than `str`,\nunless `OPT_NON_STR_KEYS` is specified.\n\nIt raises `JSONEncodeError` if the output of `default` recurses to handling by\n`default` more than 254 levels deep.\n\nIt raises `JSONEncodeError` on circular references.\n\nIt raises `JSONEncodeError`  if a `tzinfo` on a datetime object is\nunsupported.\n\n`JSONEncodeError` is a subclass of `TypeError`. This is for compatibility\nwith the standard library.\n\nIf the failure was caused by an exception in `default` then\n`JSONEncodeError` chains the original exception as `__cause__`.\n\n#### default\n\nTo serialize a subclass or arbitrary types, specify `default` as a\ncallable that returns a supported type. `default` may be a function,\nlambda, or callable class instance. To specify that a type was not\nhandled by `default`, raise an exception such as `TypeError`.\n\n```python\n>>> import orjson, decimal\n>>>\ndef default(obj):\n    if isinstance(obj, decimal.Decimal):\n        return str(obj)\n    raise TypeError\n\n>>> orjson.dumps(decimal.Decimal(\"0.0842389659712649442845\"))\nJSONEncodeError: Type is not JSON serializable: decimal.Decimal\n>>> orjson.dumps(decimal.Decimal(\"0.0842389659712649442845\"), default=default)\nb'\"0.0842389659712649442845\"'\n>>> orjson.dumps({1, 2}, default=default)\norjson.JSONEncodeError: Type is not JSON serializable: set\n```\n\nThe `default` callable may return an object that itself\nmust be handled by `default` up to 254 times before an exception\nis raised.\n\nIt is important that `default` raise an exception if a type cannot be handled.\nPython otherwise implicitly returns `None`, which appears to the caller\nlike a legitimate value and is serialized:\n\n```python\n>>> import orjson, json\n>>>\ndef default(obj):\n    if isinstance(obj, decimal.Decimal):\n        return str(obj)\n\n>>> orjson.dumps({\"set\":{1, 2}}, default=default)\nb'{\"set\":null}'\n>>> json.dumps({\"set\":{1, 2}}, default=default)\n'{\"set\":null}'\n```\n\n#### option\n\nTo modify how data is serialized, specify `option`. Each `option` is an integer\nconstant in `orjson`. To specify multiple options, mask them together, e.g.,\n`option=orjson.OPT_STRICT_INTEGER | orjson.OPT_NAIVE_UTC`.\n\n##### OPT_APPEND_NEWLINE\n\nAppend `\\n` to the output. This is a convenience and optimization for the\npattern of `dumps(...) + \"\\n\"`. `bytes` objects are immutable and this\npattern copies the original contents.\n\n```python\n>>> import orjson\n>>> orjson.dumps([])\nb\"[]\"\n>>> orjson.dumps([], option=orjson.OPT_APPEND_NEWLINE)\nb\"[]\\n\"\n```\n\n##### OPT_INDENT_2\n\nPretty-print output with an indent of two spaces. This is equivalent to\n`indent=2` in the standard library. Pretty printing is slower and the output\nlarger. This option is compatible with all other options.\n\n```python\n>>> import orjson\n>>> orjson.dumps({\"a\": \"b\", \"c\": {\"d\": True}, \"e\": [1, 2]})\nb'{\"a\":\"b\",\"c\":{\"d\":true},\"e\":[1,2]}'\n>>> orjson.dumps(\n    {\"a\": \"b\", \"c\": {\"d\": True}, \"e\": [1, 2]},\n    option=orjson.OPT_INDENT_2\n)\nb'{\\n  \"a\": \"b\",\\n  \"c\": {\\n    \"d\": true\\n  },\\n  \"e\": [\\n    1,\\n    2\\n  ]\\n}'\n```\n\nIf displayed, the indentation and linebreaks appear like this:\n\n```json\n{\n  \"a\": \"b\",\n  \"c\": {\n    \"d\": true\n  },\n  \"e\": [\n    1,\n    2\n  ]\n}\n```\n\nThis measures serializing the github.json fixture as compact (52KiB) or\npretty (64KiB):\n\n| Library   |   compact (ms) |   pretty (ms) |   vs. orjson |\n|-----------|----------------|---------------|--------------|\n| orjson    |           0.01 |          0.02 |            1 |\n| json      |           0.13 |          0.54 |           34 |\n\nThis measures serializing the citm_catalog.json fixture, more of a worst\ncase due to the amount of nesting and newlines, as compact (489KiB) or\npretty (1.1MiB):\n\n| Library   |   compact (ms) |   pretty (ms) |   vs. orjson |\n|-----------|----------------|---------------|--------------|\n| orjson    |           0.25 |          0.45 |          1   |\n| json      |           3.01 |         24.42 |         54.4 |\n\nThis can be reproduced using the `pyindent` script.\n\n##### OPT_NAIVE_UTC\n\nSerialize `datetime.datetime` objects without a `tzinfo` as UTC. This\nhas no effect on `datetime.datetime` objects that have `tzinfo` set.\n\n```python\n>>> import orjson, datetime\n>>> orjson.dumps(\n        datetime.datetime(1970, 1, 1, 0, 0, 0),\n    )\nb'\"1970-01-01T00:00:00\"'\n>>> orjson.dumps(\n        datetime.datetime(1970, 1, 1, 0, 0, 0),\n        option=orjson.OPT_NAIVE_UTC,\n    )\nb'\"1970-01-01T00:00:00+00:00\"'\n```\n\n##### OPT_NON_STR_KEYS\n\nSerialize `dict` keys of type other than `str`. This allows `dict` keys\nto be one of `str`, `int`, `float`, `bool`, `None`, `datetime.datetime`,\n`datetime.date`, `datetime.time`, `enum.Enum`, and `uuid.UUID`. For comparison,\nthe standard library serializes `str`, `int`, `float`, `bool` or `None` by\ndefault. orjson benchmarks as being faster at serializing non-`str` keys\nthan other libraries. This option is slower for `str` keys than the default.\n\n```python\n>>> import orjson, datetime, uuid\n>>> orjson.dumps(\n        {uuid.UUID(\"7202d115-7ff3-4c81-a7c1-2a1f067b1ece\"): [1, 2, 3]},\n        option=orjson.OPT_NON_STR_KEYS,\n    )\nb'{\"7202d115-7ff3-4c81-a7c1-2a1f067b1ece\":[1,2,3]}'\n>>> orjson.dumps(\n        {datetime.datetime(1970, 1, 1, 0, 0, 0): [1, 2, 3]},\n        option=orjson.OPT_NON_STR_KEYS | orjson.OPT_NAIVE_UTC,\n    )\nb'{\"1970-01-01T00:00:00+00:00\":[1,2,3]}'\n```\n\nThese types are generally serialized how they would be as\nvalues, e.g., `datetime.datetime` is still an RFC 3339 string and respects\noptions affecting it. The exception is that `int` serialization does not\nrespect `OPT_STRICT_INTEGER`.\n\nThis option has the risk of creating duplicate keys. This is because non-`str`\nobjects may serialize to the same `str` as an existing key, e.g.,\n`{\"1\": true, 1: false}`. The last key to be inserted to the `dict` will be\nserialized last and a JSON deserializer will presumably take the last\noccurrence of a key (in the above, `false`). The first value will be lost.\n\nThis option is compatible with `orjson.OPT_SORT_KEYS`. If sorting is used,\nnote the sort is unstable and will be unpredictable for duplicate keys.\n\n```python\n>>> import orjson, datetime\n>>> orjson.dumps(\n    {\"other\": 1, datetime.date(1970, 1, 5): 2, datetime.date(1970, 1, 3): 3},\n    option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SORT_KEYS\n)\nb'{\"1970-01-03\":3,\"1970-01-05\":2,\"other\":1}'\n```\n\nThis measures serializing 589KiB of JSON comprising a `list` of 100 `dict`\nin which each `dict` has both 365 randomly-sorted `int` keys representing epoch\ntimestamps as well as one `str` key and the value for each key is a\nsingle integer. In \"str keys\", the keys were converted to `str` before\nserialization, and orjson still specifes `option=orjson.OPT_NON_STR_KEYS`\n(which is always somewhat slower).\n\n| Library   |   str keys (ms) |   int keys (ms) | int keys sorted (ms)   |\n|-----------|-----------------|-----------------|------------------------|\n| orjson    |            0.5  |            0.93 | 2.08                   |\n| json      |            2.72 |            3.59 |                        |\n\njson is blank because it\nraises `TypeError` on attempting to sort before converting all keys to `str`.\nThis can be reproduced using the `pynonstr` script.\n\n##### OPT_OMIT_MICROSECONDS\n\nDo not serialize the `microsecond` field on `datetime.datetime` and\n`datetime.time` instances.\n\n```python\n>>> import orjson, datetime\n>>> orjson.dumps(\n        datetime.datetime(1970, 1, 1, 0, 0, 0, 1),\n    )\nb'\"1970-01-01T00:00:00.000001\"'\n>>> orjson.dumps(\n        datetime.datetime(1970, 1, 1, 0, 0, 0, 1),\n        option=orjson.OPT_OMIT_MICROSECONDS,\n    )\nb'\"1970-01-01T00:00:00\"'\n```\n\n##### OPT_PASSTHROUGH_DATACLASS\n\nPassthrough `dataclasses.dataclass` instances to `default`. This allows\ncustomizing their output but is much slower.\n\n\n```python\n>>> import orjson, dataclasses\n>>>\n@dataclasses.dataclass\nclass User:\n    id: str\n    name: str\n    password: str\n\ndef default(obj):\n    if isinstance(obj, User):\n        return {\"id\": obj.id, \"name\": obj.name}\n    raise TypeError\n\n>>> orjson.dumps(User(\"3b1\", \"asd\", \"zxc\"))\nb'{\"id\":\"3b1\",\"name\":\"asd\",\"password\":\"zxc\"}'\n>>> orjson.dumps(User(\"3b1\", \"asd\", \"zxc\"), option=orjson.OPT_PASSTHROUGH_DATACLASS)\nTypeError: Type is not JSON serializable: User\n>>> orjson.dumps(\n        User(\"3b1\", \"asd\", \"zxc\"),\n        option=orjson.OPT_PASSTHROUGH_DATACLASS,\n        default=default,\n    )\nb'{\"id\":\"3b1\",\"name\":\"asd\"}'\n```\n\n##### OPT_PASSTHROUGH_DATETIME\n\nPassthrough `datetime.datetime`, `datetime.date`, and `datetime.time` instances\nto `default`. This allows serializing datetimes to a custom format, e.g.,\nHTTP dates:\n\n```python\n>>> import orjson, datetime\n>>>\ndef default(obj):\n    if isinstance(obj, datetime.datetime):\n        return obj.strftime(\"%a, %d %b %Y %H:%M:%S GMT\")\n    raise TypeError\n\n>>> orjson.dumps({\"created_at\": datetime.datetime(1970, 1, 1)})\nb'{\"created_at\":\"1970-01-01T00:00:00\"}'\n>>> orjson.dumps({\"created_at\": datetime.datetime(1970, 1, 1)}, option=orjson.OPT_PASSTHROUGH_DATETIME)\nTypeError: Type is not JSON serializable: datetime.datetime\n>>> orjson.dumps(\n        {\"created_at\": datetime.datetime(1970, 1, 1)},\n        option=orjson.OPT_PASSTHROUGH_DATETIME,\n        default=default,\n    )\nb'{\"created_at\":\"Thu, 01 Jan 1970 00:00:00 GMT\"}'\n```\n\nThis does not affect datetimes in `dict` keys if using OPT_NON_STR_KEYS.\n\n##### OPT_PASSTHROUGH_SUBCLASS\n\nPassthrough subclasses of builtin types to `default`.\n\n```python\n>>> import orjson\n>>>\nclass Secret(str):\n    pass\n\ndef default(obj):\n    if isinstance(obj, Secret):\n        return \"******\"\n    raise TypeError\n\n>>> orjson.dumps(Secret(\"zxc\"))\nb'\"zxc\"'\n>>> orjson.dumps(Secret(\"zxc\"), option=orjson.OPT_PASSTHROUGH_SUBCLASS)\nTypeError: Type is not JSON serializable: Secret\n>>> orjson.dumps(Secret(\"zxc\"), option=orjson.OPT_PASSTHROUGH_SUBCLASS, default=default)\nb'\"******\"'\n```\n\nThis does not affect serializing subclasses as `dict` keys if using\nOPT_NON_STR_KEYS.\n\n##### OPT_SERIALIZE_DATACLASS\n\nThis is deprecated and has no effect in version 3. In version 2 this was\nrequired to serialize  `dataclasses.dataclass` instances. For more, see\n[dataclass](https://github.com/ijl/orjson?tab=readme-ov-file#dataclass).\n\n##### OPT_SERIALIZE_NUMPY\n\nSerialize `numpy.ndarray` instances. For more, see\n[numpy](https://github.com/ijl/orjson?tab=readme-ov-file#numpy).\n\n##### OPT_SERIALIZE_UUID\n\nThis is deprecated and has no effect in version 3. In version 2 this was\nrequired to serialize `uuid.UUID` instances. For more, see\n[UUID](https://github.com/ijl/orjson?tab=readme-ov-file#UUID).\n\n##### OPT_SORT_KEYS\n\nSerialize `dict` keys in sorted order. The default is to serialize in an\nunspecified order. This is equivalent to `sort_keys=True` in the standard\nlibrary.\n\nThis can be used to ensure the order is deterministic for hashing or tests.\nIt has a substantial performance penalty and is not recommended in general.\n\n```python\n>>> import orjson\n>>> orjson.dumps({\"b\": 1, \"c\": 2, \"a\": 3})\nb'{\"b\":1,\"c\":2,\"a\":3}'\n>>> orjson.dumps({\"b\": 1, \"c\": 2, \"a\": 3}, option=orjson.OPT_SORT_KEYS)\nb'{\"a\":3,\"b\":1,\"c\":2}'\n```\n\nThis measures serializing the twitter.json fixture unsorted and sorted:\n\n| Library   |   unsorted (ms) |   sorted (ms) |   vs. orjson |\n|-----------|-----------------|---------------|--------------|\n| orjson    |            0.11 |          0.3  |          1   |\n| json      |            1.36 |          1.93 |          6.4 |\n\nThe benchmark can be reproduced using the `pysort` script.\n\nThe sorting is not collation/locale-aware:\n\n```python\n>>> import orjson\n>>> orjson.dumps({\"a\": 1, \"ä\": 2, \"A\": 3}, option=orjson.OPT_SORT_KEYS)\nb'{\"A\":3,\"a\":1,\"\\xc3\\xa4\":2}'\n```\n\nThis is the same sorting behavior as the standard library.\n\n`dataclass` also serialize as maps but this has no effect on them.\n\n##### OPT_STRICT_INTEGER\n\nEnforce 53-bit limit on integers. The limit is otherwise 64 bits, the same as\nthe Python standard library. For more, see [int](https://github.com/ijl/orjson?tab=readme-ov-file#int).\n\n##### OPT_UTC_Z\n\nSerialize a UTC timezone on `datetime.datetime` instances as `Z` instead\nof `+00:00`.\n\n```python\n>>> import orjson, datetime, zoneinfo\n>>> orjson.dumps(\n        datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=zoneinfo.ZoneInfo(\"UTC\")),\n    )\nb'\"1970-01-01T00:00:00+00:00\"'\n>>> orjson.dumps(\n        datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=zoneinfo.ZoneInfo(\"UTC\")),\n        option=orjson.OPT_UTC_Z\n    )\nb'\"1970-01-01T00:00:00Z\"'\n```\n\n#### Fragment\n\n`orjson.Fragment` includes already-serialized JSON in a document. This is an\nefficient way to include JSON blobs from a cache, JSONB field, or separately\nserialized object without first deserializing to Python objects via `loads()`.\n\n```python\n>>> import orjson\n>>> orjson.dumps({\"key\": \"zxc\", \"data\": orjson.Fragment(b'{\"a\": \"b\", \"c\": 1}')})\nb'{\"key\":\"zxc\",\"data\":{\"a\": \"b\", \"c\": 1}}'\n```\n\nIt does no reformatting: `orjson.OPT_INDENT_2` will not affect a\ncompact blob nor will a pretty-printed JSON blob be rewritten as compact.\n\nThe input must be `bytes` or `str` and given as a positional argument.\n\nThis raises `orjson.JSONEncodeError` if a `str` is given and the input is\nnot valid UTF-8. It otherwise does no validation and it is possible to\nwrite invalid JSON. This does not escape characters. The implementation is\ntested to not crash if given invalid strings or invalid JSON.\n\n### Deserialize\n\n```python\ndef loads(__obj: Union[bytes, bytearray, memoryview, str]) -> Any: ...\n```\n\n`loads()` deserializes JSON to Python objects. It deserializes to `dict`,\n`list`, `int`, `float`, `str`, `bool`, and `None` objects.\n\n`bytes`, `bytearray`, `memoryview`, and `str` input are accepted. If the input\nexists as a `memoryview`, `bytearray`, or `bytes` object, it is recommended to\npass these directly rather than creating an unnecessary `str` object. That is,\n`orjson.loads(b\"{}\")` instead of `orjson.loads(b\"{}\".decode(\"utf-8\"))`. This\nhas lower memory usage and lower latency.\n\nThe input must be valid UTF-8.\n\norjson maintains a cache of map keys for the duration of the process. This\ncauses a net reduction in memory usage by avoiding duplicate strings. The\nkeys must be at most 64 bytes to be cached and 2048 entries are stored.\n\nThe global interpreter lock (GIL) is held for the duration of the call.\n\nIt raises `JSONDecodeError` if given an invalid type or invalid\nJSON. This includes if the input contains `NaN`, `Infinity`, or `-Infinity`,\nwhich the standard library allows, but is not valid JSON.\n\nIt raises `JSONDecodeError` if a combination of array or object recurses\n1024 levels deep.\n\nIt raises `JSONDecodeError` if unable to allocate a buffer large enough\nto parse the document.\n\n`JSONDecodeError` is a subclass of `json.JSONDecodeError` and `ValueError`.\nThis is for compatibility with the standard library.\n\n## Types\n\n### dataclass\n\norjson serializes instances of `dataclasses.dataclass` natively. It serializes\ninstances 40-50x as fast as other libraries and avoids a severe slowdown seen\nin other libraries compared to serializing `dict`.\n\nIt is supported to pass all variants of dataclasses, including dataclasses\nusing `__slots__`, frozen dataclasses, those with optional or default\nattributes, and subclasses. There is a performance benefit to not\nusing `__slots__`.\n\n| Library   |   dict (ms) |   dataclass (ms) |   vs. orjson |\n|-----------|-------------|------------------|--------------|\n| orjson    |        0.43 |             0.95 |            1 |\n| json      |        5.81 |            38.32 |           40 |\n\nThis measures serializing 555KiB of JSON, orjson natively and other libraries\nusing `default` to serialize the output of `dataclasses.asdict()`. This can be\nreproduced using the `pydataclass` script.\n\nDataclasses are serialized as maps, with every attribute serialized and in\nthe order given on class definition:\n\n```python\n>>> import dataclasses, orjson, typing\n\n@dataclasses.dataclass\nclass Member:\n    id: int\n    active: bool = dataclasses.field(default=False)\n\n@dataclasses.dataclass\nclass Object:\n    id: int\n    name: str\n    members: typing.List[Member]\n\n>>> orjson.dumps(Object(1, \"a\", [Member(1, True), Member(2)]))\nb'{\"id\":1,\"name\":\"a\",\"members\":[{\"id\":1,\"active\":true},{\"id\":2,\"active\":false}]}'\n```\n\n### datetime\n\norjson serializes `datetime.datetime` objects to\n[RFC 3339](https://tools.ietf.org/html/rfc3339) format,\ne.g., \"1970-01-01T00:00:00+00:00\". This is a subset of ISO 8601 and is\ncompatible with `isoformat()` in the standard library.\n\n```python\n>>> import orjson, datetime, zoneinfo\n>>> orjson.dumps(\n    datetime.datetime(2018, 12, 1, 2, 3, 4, 9, tzinfo=zoneinfo.ZoneInfo(\"Australia/Adelaide\"))\n)\nb'\"2018-12-01T02:03:04.000009+10:30\"'\n>>> orjson.dumps(\n    datetime.datetime(2100, 9, 1, 21, 55, 2).replace(tzinfo=zoneinfo.ZoneInfo(\"UTC\"))\n)\nb'\"2100-09-01T21:55:02+00:00\"'\n>>> orjson.dumps(\n    datetime.datetime(2100, 9, 1, 21, 55, 2)\n)\nb'\"2100-09-01T21:55:02\"'\n```\n\n`datetime.datetime` supports instances with a `tzinfo` that is `None`,\n`datetime.timezone.utc`, a timezone instance from the standard library `zoneinfo`\nmodule, or a timezone instance from the third-party `pendulum`, `pytz`, or\n`dateutil`/`arrow` libraries.\n\nIt is fastest to use the standard library's `zoneinfo.ZoneInfo` for timezones.\n\n`datetime.time` objects must not have a `tzinfo`.\n\n```python\n>>> import orjson, datetime\n>>> orjson.dumps(datetime.time(12, 0, 15, 290))\nb'\"12:00:15.000290\"'\n```\n\n`datetime.date` objects will always serialize.\n\n```python\n>>> import orjson, datetime\n>>> orjson.dumps(datetime.date(1900, 1, 2))\nb'\"1900-01-02\"'\n```\n\nErrors with `tzinfo` result in `JSONEncodeError` being raised.\n\nTo disable serialization of `datetime` objects specify the option\n`orjson.OPT_PASSTHROUGH_DATETIME`.\n\nTo use \"Z\" suffix instead of \"+00:00\" to indicate UTC (\"Zulu\") time, use the option\n`orjson.OPT_UTC_Z`.\n\nTo assume datetimes without timezone are UTC, use the option `orjson.OPT_NAIVE_UTC`.\n\n### enum\n\norjson serializes enums natively. Options apply to their values.\n\n```python\n>>> import enum, datetime, orjson\n>>>\nclass DatetimeEnum(enum.Enum):\n    EPOCH = datetime.datetime(1970, 1, 1, 0, 0, 0)\n>>> orjson.dumps(DatetimeEnum.EPOCH)\nb'\"1970-01-01T00:00:00\"'\n>>> orjson.dumps(DatetimeEnum.EPOCH, option=orjson.OPT_NAIVE_UTC)\nb'\"1970-01-01T00:00:00+00:00\"'\n```\n\nEnums with members that are not supported types can be serialized using\n`default`:\n\n```python\n>>> import enum, orjson\n>>>\nclass Custom:\n    def __init__(self, val):\n        self.val = val\n\ndef default(obj):\n    if isinstance(obj, Custom):\n        return obj.val\n    raise TypeError\n\nclass CustomEnum(enum.Enum):\n    ONE = Custom(1)\n\n>>> orjson.dumps(CustomEnum.ONE, default=default)\nb'1'\n```\n\n### float\n\norjson serializes and deserializes double precision floats with no loss of\nprecision and consistent rounding.\n\n`orjson.dumps()` serializes Nan, Infinity, and -Infinity, which are not\ncompliant JSON, as `null`:\n\n```python\n>>> import orjson, json\n>>> orjson.dumps([float(\"NaN\"), float(\"Infinity\"), float(\"-Infinity\")])\nb'[null,null,null]'\n>>> json.dumps([float(\"NaN\"), float(\"Infinity\"), float(\"-Infinity\")])\n'[NaN, Infinity, -Infinity]'\n```\n\n### int\n\norjson serializes and deserializes 64-bit integers by default. The range\nsupported is a signed 64-bit integer's minimum (-9223372036854775807) to\nan unsigned 64-bit integer's maximum (18446744073709551615). This\nis widely compatible, but there are implementations\nthat only support 53-bits for integers, e.g.,\nweb browsers. For those implementations, `dumps()` can be configured to\nraise a `JSONEncodeError` on values exceeding the 53-bit range.\n\n```python\n>>> import orjson\n>>> orjson.dumps(9007199254740992)\nb'9007199254740992'\n>>> orjson.dumps(9007199254740992, option=orjson.OPT_STRICT_INTEGER)\nJSONEncodeError: Integer exceeds 53-bit range\n>>> orjson.dumps(-9007199254740992, option=orjson.OPT_STRICT_INTEGER)\nJSONEncodeError: Integer exceeds 53-bit range\n```\n\n### numpy\n\norjson natively serializes `numpy.ndarray` and individual\n`numpy.float64`, `numpy.float32`, `numpy.float16` (`numpy.half`),\n`numpy.int64`, `numpy.int32`, `numpy.int16`, `numpy.int8`,\n`numpy.uint64`, `numpy.uint32`, `numpy.uint16`, `numpy.uint8`,\n`numpy.uintp`, `numpy.intp`, `numpy.datetime64`, and `numpy.bool`\ninstances.\n\norjson is compatible with both numpy v1 and v2.\n\norjson is faster than all compared libraries at serializing\nnumpy instances. Serializing numpy data requires specifying\n`option=orjson.OPT_SERIALIZE_NUMPY`.\n\n```python\n>>> import orjson, numpy\n>>> orjson.dumps(\n        numpy.array([[1, 2, 3], [4, 5, 6]]),\n        option=orjson.OPT_SERIALIZE_NUMPY,\n)\nb'[[1,2,3],[4,5,6]]'\n```\n\nThe array must be a contiguous C array (`C_CONTIGUOUS`) and one of the\nsupported datatypes.\n\nNote a difference between serializing `numpy.float32` using `ndarray.tolist()`\nor `orjson.dumps(..., option=orjson.OPT_SERIALIZE_NUMPY)`: `tolist()` converts\nto a `double` before serializing and orjson's native path does not. This\ncan result in different rounding.\n\n`numpy.datetime64` instances are serialized as RFC 3339 strings and\ndatetime options affect them.\n\n```python\n>>> import orjson, numpy\n>>> orjson.dumps(\n        numpy.datetime64(\"2021-01-01T00:00:00.172\"),\n        option=orjson.OPT_SERIALIZE_NUMPY,\n)\nb'\"2021-01-01T00:00:00.172000\"'\n>>> orjson.dumps(\n        numpy.datetime64(\"2021-01-01T00:00:00.172\"),\n        option=(\n            orjson.OPT_SERIALIZE_NUMPY |\n            orjson.OPT_NAIVE_UTC |\n            orjson.OPT_OMIT_MICROSECONDS\n        ),\n)\nb'\"2021-01-01T00:00:00+00:00\"'\n```\n\nIf an array is not a contiguous C array, contains an unsupported datatype,\nor contains a `numpy.datetime64` using an unsupported representation\n(e.g., picoseconds), orjson falls through to `default`. In `default`,\n`obj.tolist()` can be specified.\n\nIf an array is not in the native endianness, e.g., an array of big-endian values\non a little-endian system, `orjson.JSONEncodeError`  is raised.\n\nIf an array is malformed, `orjson.JSONEncodeError` is raised.\n\nThis measures serializing 92MiB of JSON from an `numpy.ndarray` with\ndimensions of `(50000, 100)` and `numpy.float64` values:\n\n| Library   | Latency (ms)   |   RSS diff (MiB) |   vs. orjson |\n|-----------|----------------|------------------|--------------|\n| orjson    | 105            |              105 |          1   |\n| json      | 1,481          |              295 |         14.2 |\n\nThis measures serializing 100MiB of JSON from an `numpy.ndarray` with\ndimensions of `(100000, 100)` and `numpy.int32` values:\n\n| Library   |   Latency (ms) |   RSS diff (MiB) |   vs. orjson |\n|-----------|----------------|------------------|--------------|\n| orjson    |             68 |              119 |          1   |\n| json      |            684 |              501 |         10.1 |\n\nThis measures serializing 105MiB of JSON from an `numpy.ndarray` with\ndimensions of `(100000, 200)` and `numpy.bool` values:\n\n| Library   |   Latency (ms) |   RSS diff (MiB) |   vs. orjson |\n|-----------|----------------|------------------|--------------|\n| orjson    |             50 |              125 |          1   |\n| json      |            573 |              398 |         11.5 |\n\nIn these benchmarks, orjson serializes natively and `json` serializes\n`ndarray.tolist()` via `default`. The RSS column measures peak memory\nusage during serialization. This can be reproduced using the `pynumpy` script.\n\norjson does not have an installation or compilation dependency on numpy. The\nimplementation is independent, reading `numpy.ndarray` using\n`PyArrayInterface`.\n\n### str\n\norjson is strict about UTF-8 conformance. This is stricter than the standard\nlibrary's json module, which will serialize and deserialize UTF-16 surrogates,\ne.g., \"\\ud800\", that are invalid UTF-8.\n\nIf `orjson.dumps()` is given a `str` that does not contain valid UTF-8,\n`orjson.JSONEncodeError` is raised. If `loads()` receives invalid UTF-8,\n`orjson.JSONDecodeError` is raised.\n\n```python\n>>> import orjson, json\n>>> orjson.dumps('\\ud800')\nJSONEncodeError: str is not valid UTF-8: surrogates not allowed\n>>> json.dumps('\\ud800')\n'\"\\\\ud800\"'\n>>> orjson.loads('\"\\\\ud800\"')\nJSONDecodeError: unexpected end of hex escape at line 1 column 8: line 1 column 1 (char 0)\n>>> json.loads('\"\\\\ud800\"')\n'\\ud800'\n```\n\nTo make a best effort at deserializing bad input, first decode `bytes` using\nthe `replace` or `lossy` argument for `errors`:\n\n```python\n>>> import orjson\n>>> orjson.loads(b'\"\\xed\\xa0\\x80\"')\nJSONDecodeError: str is not valid UTF-8: surrogates not allowed\n>>> orjson.loads(b'\"\\xed\\xa0\\x80\"'.decode(\"utf-8\", \"replace\"))\n'���'\n```\n\n### uuid\n\norjson serializes `uuid.UUID` instances to\n[RFC 4122](https://tools.ietf.org/html/rfc4122) format, e.g.,\n\"f81d4fae-7dec-11d0-a765-00a0c91e6bf6\".\n\n``` python\n>>> import orjson, uuid\n>>> orjson.dumps(uuid.uuid5(uuid.NAMESPACE_DNS, \"python.org\"))\nb'\"886313e1-3b8a-5372-9b90-0c9aee199e5d\"'\n```\n\n## Testing\n\nThe library has comprehensive tests. There are tests against fixtures in the\n[JSONTestSuite](https://github.com/nst/JSONTestSuite) and\n[nativejson-benchmark](https://github.com/miloyip/nativejson-benchmark)\nrepositories. It is tested to not crash against the\n[Big List of Naughty Strings](https://github.com/minimaxir/big-list-of-naughty-strings).\nIt is tested to not leak memory. It is tested to not crash\nagainst and not accept invalid UTF-8. There are integration tests\nexercising the library's use in web servers (gunicorn using multiprocess/forked\nworkers) and when multithreaded.\n\norjson is the most correct of the compared libraries. This graph shows how each\nlibrary handles a combined 342 JSON fixtures from the\n[JSONTestSuite](https://github.com/nst/JSONTestSuite) and\n[nativejson-benchmark](https://github.com/miloyip/nativejson-benchmark) tests:\n\n| Library    |   Invalid JSON documents not rejected |   Valid JSON documents not deserialized |\n|------------|---------------------------------------|-----------------------------------------|\n| orjson     |                                     0 |                                       0 |\n| json       |                                    17 |                                       0 |\n\nThis shows that all libraries deserialize valid JSON but only orjson\ncorrectly rejects the given invalid JSON fixtures. Errors are largely due to\naccepting invalid strings and numbers.\n\nThe graph above can be reproduced using the `pycorrectness` script.\n\n## Performance\n\nSerialization and deserialization performance of orjson is consistently better\nthan the standard library's `json`. The graphs below illustrate a few commonly\nused documents.\n\n### Latency\n\n![Serialization](doc/serialization.png)\n\n![Deserialization](doc/deserialization.png)\n\n#### twitter.json serialization\n\n| Library   |   Median latency (milliseconds) |   Operations per second |   Relative (latency) |\n|-----------|---------------------------------|-------------------------|----------------------|\n| orjson    |                             0.1 |                    8453 |                  1   |\n| json      |                             1.3 |                     765 |                 11.1 |\n\n#### twitter.json deserialization\n\n| Library   |   Median latency (milliseconds) |   Operations per second |   Relative (latency) |\n|-----------|---------------------------------|-------------------------|----------------------|\n| orjson    |                             0.5 |                    1889 |                  1   |\n| json      |                             2.2 |                     453 |                  4.2 |\n\n#### github.json serialization\n\n| Library   |   Median latency (milliseconds) |   Operations per second |   Relative (latency) |\n|-----------|---------------------------------|-------------------------|----------------------|\n| orjson    |                            0.01 |                  103693 |                  1   |\n| json      |                            0.13 |                    7648 |                 13.6 |\n\n#### github.json deserialization\n\n| Library   |   Median latency (milliseconds) |   Operations per second |   Relative (latency) |\n|-----------|---------------------------------|-------------------------|----------------------|\n| orjson    |                            0.04 |                   23264 |                  1   |\n| json      |                            0.1  |                   10430 |                  2.2 |\n\n#### citm_catalog.json serialization\n\n| Library   |   Median latency (milliseconds) |   Operations per second |   Relative (latency) |\n|-----------|---------------------------------|-------------------------|----------------------|\n| orjson    |                             0.3 |                    3975 |                  1   |\n| json      |                             3   |                     338 |                 11.8 |\n\n#### citm_catalog.json deserialization\n\n| Library   |   Median latency (milliseconds) |   Operations per second |   Relative (latency) |\n|-----------|---------------------------------|-------------------------|----------------------|\n| orjson    |                             1.3 |                     781 |                  1   |\n| json      |                             4   |                     250 |                  3.1 |\n\n#### canada.json serialization\n\n| Library   |   Median latency (milliseconds) |   Operations per second |   Relative (latency) |\n|-----------|---------------------------------|-------------------------|----------------------|\n| orjson    |                             2.5 |                     399 |                  1   |\n| json      |                            29.8 |                      33 |                 11.9 |\n\n#### canada.json deserialization\n\n| Library   |   Median latency (milliseconds) |   Operations per second |   Relative (latency) |\n|-----------|---------------------------------|-------------------------|----------------------|\n| orjson    |                               3 |                     333 |                    1 |\n| json      |                              18 |                      55 |                    6 |\n\n### Reproducing\n\nThe above was measured using Python 3.11.10 in a Fedora 42 container on an\nx86-64-v4 machine using the\n`orjson-3.10.11-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl`\nartifact on PyPI. The latency results can be reproduced using the `pybench` script.\n\n## Questions\n\n### Will it deserialize to dataclasses, UUIDs, decimals, etc or support object_hook?\n\nNo. This requires a schema specifying what types are expected and how to\nhandle errors etc. This is addressed by data validation libraries a\nlevel above this.\n\n### Will it serialize to `str`?\n\nNo. `bytes` is the correct type for a serialized blob.\n\n### Will it support NDJSON or JSONL?\n\nNo. [orjsonl](https://github.com/umarbutler/orjsonl) may be appropriate.\n\n### Will it support JSON5 or RJSON?\n\nNo, it supports RFC 8259.\n\n### How do I depend on orjson in a Rust project?\n\norjson is only shipped as a Python module. The project should depend on\n`orjson` in its own Python requirements and should obtain pointers to\nfunctions and objects using the normal `PyImport_*` APIs.\n\n## Packaging\n\nTo package orjson requires at least [Rust](https://www.rust-lang.org/) 1.89,\na C compiler, and the [maturin](https://github.com/PyO3/maturin) build tool.\nThe recommended build command is:\n\n```sh\nmaturin build --release --strip\n```\n\nThe project's own CI tests against `nightly-2026-01-28` and stable 1.89. It\nis prudent to pin the nightly version because that channel can introduce\nbreaking changes. There is a significant performance benefit to using\nnightly.\n\norjson is tested on native hardware for amd64, aarch64, and i686 on Linux. It is\ncross-compiled and may be tested via emulation for arm7, ppc64le, and s390x. It\nis tested for aarch64 on macOS and cross-compiles for amd64. For\nWindows it is tested on amd64, i686, and aarch64.\n\nThere are no runtime dependencies other than libc.\n\nThe source distribution on PyPI contains all dependencies' source and can be\nbuilt without network access. The file can be downloaded from\n`https://files.pythonhosted.org/packages/source/o/orjson/orjson-${version}.tar.gz`.\n\norjson's tests are included in the source distribution on PyPI. The tests\nrequire only `pytest`. There are optional packages such as `pytz` and `numpy`\nlisted in `test/requirements.txt` and used in ~10% of tests. Not having these\ndependencies causes the tests needing them to skip. Tests can be run\nwith `pytest -q test`.\n\n## License\n\norjson was written by ijl <<ijl@mailbox.org>>, copyright 2018 - 2026, with\nsome source files available under the Mozilla Public License 2.0 and some\navailable under your choice of the Apache 2 license or MIT license.\n"
  },
  {
    "path": "bench/__init__.py",
    "content": ""
  },
  {
    "path": "bench/benchmark_dumps.py",
    "content": "# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2020-2026), Aarni Koskela (2021)\n\nfrom json import loads as json_loads\n\nimport pytest\n\nfrom .data import FIXTURE_AS_OBJECTS, FIXTURE_NAMES, LIBRARIES\n\n\n@pytest.mark.parametrize(\"library\", LIBRARIES)\n@pytest.mark.parametrize(\"fixture\", FIXTURE_NAMES)\ndef test_dumps(benchmark, fixture, library):\n    dumper, _ = LIBRARIES[library]\n    benchmark.group = f\"{fixture} serialization\"\n    benchmark.extra_info[\"lib\"] = library\n    data = FIXTURE_AS_OBJECTS[fixture]\n    benchmark.extra_info[\"correct\"] = json_loads(dumper(data)) == data  # type: ignore\n    benchmark(dumper, data)\n"
  },
  {
    "path": "bench/benchmark_loads.py",
    "content": "# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2020-2026), Aarni Koskela (2021)\n\nfrom json import loads as json_loads\n\nimport pytest\n\nfrom .data import FIXTURE_AS_BYTES, FIXTURE_NAMES, LIBRARIES\n\n\n@pytest.mark.parametrize(\"fixture\", FIXTURE_NAMES)\n@pytest.mark.parametrize(\"library\", LIBRARIES)\ndef test_loads(benchmark, fixture, library):\n    dumper, loader = LIBRARIES[library]\n    benchmark.group = f\"{fixture} deserialization\"\n    benchmark.extra_info[\"lib\"] = library\n    data = FIXTURE_AS_BYTES[fixture]\n    correct = json_loads(dumper(loader(data))) == json_loads(data)  # type: ignore\n    benchmark.extra_info[\"correct\"] = correct\n    benchmark(loader, data)\n"
  },
  {
    "path": "bench/data.py",
    "content": "# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2019-2026), Aarni Koskela (2021)\n\nimport gc\nfrom json import dumps as _json_dumps\nfrom json import loads as json_loads\n\nfrom orjson import dumps as orjson_dumps\nfrom orjson import loads as orjson_loads\n\nfrom .util import read_fixture\n\n\ndef json_dumps(obj):\n    return _json_dumps(obj).encode(\"utf-8\")\n\n\nLIBRARIES = {\n    \"orjson\": (orjson_dumps, orjson_loads),\n    \"json\": (json_dumps, json_loads),\n}\n\n\nFIXTURE_NAMES = (\n    \"canada.json\",\n    \"citm_catalog.json\",\n    \"github.json\",\n    \"twitter.json\",\n)\n\nFIXTURE_AS_BYTES = {name: read_fixture(f\"{name}.xz\") for name in FIXTURE_NAMES}\n\nFIXTURE_AS_OBJECTS = {\n    name: orjson_loads(FIXTURE_AS_BYTES[name]) for name in FIXTURE_NAMES\n}\n\n\nif hasattr(gc, \"freeze\"):\n    gc.freeze()\nif hasattr(gc, \"collect\"):\n    gc.collect()\nif hasattr(gc, \"disable\"):\n    gc.disable()\n"
  },
  {
    "path": "bench/requirements.txt",
    "content": "memory-profiler; python_version<\"3.15\" and implementation_name==\"cpython\"\npandas; python_version<\"3.15\" and implementation_name==\"cpython\"\npytest-benchmark\npytest-random-order\nseaborn; python_version<\"3.15\" and implementation_name==\"cpython\"\ntabulate\n"
  },
  {
    "path": "bench/run_func",
    "content": "#!/usr/bin/env python3\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2018-2025), Aarni Koskela (2021)\n\nimport sys\nimport lzma\nimport os\nimport gc\n\nif hasattr(os, \"sched_setaffinity\"):\n    os.sched_setaffinity(os.getpid(), {0, 1})\n\nfrom orjson import dumps, loads\n\nfilename = sys.argv[1]\nn = int(sys.argv[3]) if len(sys.argv) >= 4 else 1000\n\nwith lzma.open(filename, \"r\") as fileh:\n    file_bytes = fileh.read()\n\nif hasattr(gc, \"freeze\"):\n    gc.freeze()\nif hasattr(gc, \"collect\"):\n    gc.collect()\nif hasattr(gc, \"disable\"):\n    gc.disable()\n\nif sys.argv[2] == \"dumps\":\n    file_obj = loads(file_bytes)\n    for _ in range(n):\n        _ = dumps(file_obj)\nelif sys.argv[2] == \"loads\":\n    for _ in range(n):\n        _ = loads(file_bytes)\n"
  },
  {
    "path": "bench/util.py",
    "content": "# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2018-2022), Aarni Koskela (2021)\n\nimport lzma\nimport os\nfrom pathlib import Path\n\ndirname = os.path.join(os.path.dirname(__file__), \"../data\")\n\nif hasattr(os, \"sched_setaffinity\"):\n    os.sched_setaffinity(os.getpid(), {0, 1})\n\n\ndef read_fixture(filename: str) -> bytes:\n    path = Path(dirname, filename)\n    if path.suffix == \".xz\":\n        contents = lzma.decompress(path.read_bytes())\n    else:\n        contents = path.read_bytes()\n    return contents\n"
  },
  {
    "path": "build.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2021-2026)\n\nfn main() {\n    let python_config = pyo3_build_config::get();\n\n    if python_config.is_free_threaded() && std::env::var(\"ORJSON_BUILD_FREETHREADED\").is_err() {\n        not_supported(\"free-threaded Python\")\n    }\n\n    #[allow(unused_variables)]\n    let is_64_bit_python = matches!(python_config.pointer_width, Some(64));\n\n    match python_config.implementation {\n        pyo3_build_config::PythonImplementation::CPython => {\n            println!(\"cargo:rustc-cfg=CPython\");\n            #[cfg(any(target_arch = \"x86_64\", target_arch = \"aarch64\"))]\n            if is_64_bit_python {\n                println!(\"cargo:rustc-cfg=feature=\\\"inline_int\\\"\");\n                #[cfg(target_endian = \"little\")]\n                println!(\"cargo:rustc-cfg=feature=\\\"inline_str\\\"\");\n            }\n        }\n        pyo3_build_config::PythonImplementation::GraalPy => not_supported(\"GraalPy\"),\n        pyo3_build_config::PythonImplementation::PyPy => not_supported(\"PyPy\"),\n    }\n\n    for cfg in python_config.build_script_outputs() {\n        println!(\"{cfg}\");\n    }\n\n    println!(\"cargo:rerun-if-changed=build.rs\");\n    println!(\"cargo:rerun-if-changed=include/yyjson/*\");\n    println!(\"cargo:rerun-if-env-changed=CC\");\n    println!(\"cargo:rerun-if-env-changed=CFLAGS\");\n    println!(\"cargo:rerun-if-env-changed=LDFLAGS\");\n    println!(\"cargo:rerun-if-env-changed=ORJSON_BUILD_FREETHREADED\");\n    println!(\"cargo:rerun-if-env-changed=RUSTFLAGS\");\n    println!(\"cargo:rustc-check-cfg=cfg(cold_path)\");\n    println!(\"cargo:rustc-check-cfg=cfg(CPython)\");\n    println!(\"cargo:rustc-check-cfg=cfg(GraalPy)\");\n    println!(\"cargo:rustc-check-cfg=cfg(optimize)\");\n    println!(\"cargo:rustc-check-cfg=cfg(Py_3_10)\");\n    println!(\"cargo:rustc-check-cfg=cfg(Py_3_11)\");\n    println!(\"cargo:rustc-check-cfg=cfg(Py_3_12)\");\n    println!(\"cargo:rustc-check-cfg=cfg(Py_3_13)\");\n    println!(\"cargo:rustc-check-cfg=cfg(Py_3_14)\");\n    println!(\"cargo:rustc-check-cfg=cfg(Py_3_15)\");\n    println!(\"cargo:rustc-check-cfg=cfg(Py_GIL_DISABLED)\");\n    println!(\"cargo:rustc-check-cfg=cfg(PyPy)\");\n\n    #[cfg(all(target_arch = \"x86_64\", not(target_os = \"macos\")))]\n    if is_64_bit_python {\n        println!(\"cargo:rustc-cfg=feature=\\\"avx512\\\"\");\n    }\n\n    #[cfg(target_arch = \"aarch64\")]\n    if version_check::supports_feature(\"portable_simd\").unwrap_or(false) {\n        println!(\"cargo:rustc-cfg=feature=\\\"generic_simd\\\"\");\n    }\n\n    if version_check::supports_feature(\"cold_path\").unwrap_or(false) {\n        println!(\"cargo:rustc-cfg=feature=\\\"cold_path\\\"\");\n    }\n\n    if version_check::supports_feature(\"optimize_attribute\").unwrap_or(false) {\n        println!(\"cargo:rustc-cfg=feature=\\\"optimize\\\"\");\n    }\n\n    cc::Build::new()\n        .file(\"include/yyjson/yyjson.c\")\n        .include(\"include/yyjson\")\n        .define(\"YYJSON_DISABLE_NON_STANDARD\", \"1\")\n        .define(\"YYJSON_DISABLE_UTF8_VALIDATION\", \"1\")\n        .define(\"YYJSON_DISABLE_UTILS\", \"1\")\n        .define(\"YYJSON_DISABLE_WRITER\", \"1\")\n        .compile(\"yyjson\")\n}\n\nfn not_supported(flavor: &str) {\n    let version = env!(\"CARGO_PKG_VERSION\");\n    eprintln!(\"\\n\\n\\norjson v{version} does not support {flavor}\\n\\n\\n\");\n    std::process::exit(1);\n}\n"
  },
  {
    "path": "ci/config.toml",
    "content": "[unstable]\nbuild-std = [\"core\", \"std\", \"alloc\", \"proc_macro\", \"panic_abort\"]\ntrim-paths = true\n\n[target.x86_64-apple-darwin]\nlinker = \"clang\"\nrustflags = [\"-C\", \"target-cpu=x86-64-v2\", \"-Z\", \"tune-cpu=generic\"]\n\n[target.aarch64-apple-darwin]\nlinker = \"clang\"\nrustflags = [\"-C\", \"target-cpu=apple-m1\", \"-Z\", \"tune-cpu=generic\"]\n"
  },
  {
    "path": "ci/sdist.toml",
    "content": "[source.crates-io]\nreplace-with = \"vendored-sources\"\n\n[source.vendored-sources]\ndirectory = \"include/cargo\"\n"
  },
  {
    "path": "data/jsonchecker/fail01.json",
    "content": "\"A JSON payload should be an object or array, not a string.\""
  },
  {
    "path": "data/jsonchecker/fail02.json",
    "content": "[\"Unclosed array\""
  },
  {
    "path": "data/jsonchecker/fail03.json",
    "content": "{unquoted_key: \"keys must be quoted\"}"
  },
  {
    "path": "data/jsonchecker/fail04.json",
    "content": "[\"extra comma\",]"
  },
  {
    "path": "data/jsonchecker/fail05.json",
    "content": "[\"double extra comma\",,]"
  },
  {
    "path": "data/jsonchecker/fail06.json",
    "content": "[   , \"<-- missing value\"]"
  },
  {
    "path": "data/jsonchecker/fail07.json",
    "content": "[\"Comma after the close\"],"
  },
  {
    "path": "data/jsonchecker/fail08.json",
    "content": "[\"Extra close\"]]"
  },
  {
    "path": "data/jsonchecker/fail09.json",
    "content": "{\"Extra comma\": true,}"
  },
  {
    "path": "data/jsonchecker/fail10.json",
    "content": "{\"Extra value after close\": true} \"misplaced quoted value\""
  },
  {
    "path": "data/jsonchecker/fail11.json",
    "content": "{\"Illegal expression\": 1 + 2}"
  },
  {
    "path": "data/jsonchecker/fail12.json",
    "content": "{\"Illegal invocation\": alert()}"
  },
  {
    "path": "data/jsonchecker/fail13.json",
    "content": "{\"Numbers cannot have leading zeroes\": 013}"
  },
  {
    "path": "data/jsonchecker/fail14.json",
    "content": "{\"Numbers cannot be hex\": 0x14}"
  },
  {
    "path": "data/jsonchecker/fail15.json",
    "content": "[\"Illegal backslash escape: \\x15\"]"
  },
  {
    "path": "data/jsonchecker/fail16.json",
    "content": "[\\naked]"
  },
  {
    "path": "data/jsonchecker/fail17.json",
    "content": "[\"Illegal backslash escape: \\017\"]"
  },
  {
    "path": "data/jsonchecker/fail18.json",
    "content": "[[[[[[[[[[[[[[[[[[[[\"Too deep\"]]]]]]]]]]]]]]]]]]]]"
  },
  {
    "path": "data/jsonchecker/fail19.json",
    "content": "{\"Missing colon\" null}"
  },
  {
    "path": "data/jsonchecker/fail20.json",
    "content": "{\"Double colon\":: null}"
  },
  {
    "path": "data/jsonchecker/fail21.json",
    "content": "{\"Comma instead of colon\", null}"
  },
  {
    "path": "data/jsonchecker/fail22.json",
    "content": "[\"Colon instead of comma\": false]"
  },
  {
    "path": "data/jsonchecker/fail23.json",
    "content": "[\"Bad value\", truth]"
  },
  {
    "path": "data/jsonchecker/fail24.json",
    "content": "['single quote']"
  },
  {
    "path": "data/jsonchecker/fail25.json",
    "content": "[\"\ttab\tcharacter\tin\tstring\t\"]"
  },
  {
    "path": "data/jsonchecker/fail26.json",
    "content": "[\"tab\\   character\\   in\\  string\\  \"]"
  },
  {
    "path": "data/jsonchecker/fail27.json",
    "content": "[\"line\nbreak\"]"
  },
  {
    "path": "data/jsonchecker/fail28.json",
    "content": "[\"line\\\nbreak\"]"
  },
  {
    "path": "data/jsonchecker/fail29.json",
    "content": "[0e]"
  },
  {
    "path": "data/jsonchecker/fail30.json",
    "content": "[0e+]"
  },
  {
    "path": "data/jsonchecker/fail31.json",
    "content": "[0e+-1]"
  },
  {
    "path": "data/jsonchecker/fail32.json",
    "content": "{\"Comma instead if closing brace\": true,"
  },
  {
    "path": "data/jsonchecker/fail33.json",
    "content": "[\"mismatch\"}"
  },
  {
    "path": "data/jsonchecker/pass01.json",
    "content": "[\n    \"JSON Test Pattern pass1\",\n    {\"object with 1 member\":[\"array with 1 element\"]},\n    {},\n    [],\n    -42,\n    true,\n    false,\n    null,\n    {\n        \"integer\": 1234567890,\n        \"real\": -9876.543210,\n        \"e\": 0.123456789e-12,\n        \"E\": 1.234567890E+34,\n        \"\":  23456789012E66,\n        \"zero\": 0,\n        \"one\": 1,\n        \"space\": \" \",\n        \"quote\": \"\\\"\",\n        \"backslash\": \"\\\\\",\n        \"controls\": \"\\b\\f\\n\\r\\t\",\n        \"slash\": \"/ & \\/\",\n        \"alpha\": \"abcdefghijklmnopqrstuvwyz\",\n        \"ALPHA\": \"ABCDEFGHIJKLMNOPQRSTUVWYZ\",\n        \"digit\": \"0123456789\",\n        \"0123456789\": \"digit\",\n        \"special\": \"`1~!@#$%^&*()_+-={':[,]}|;.</>?\",\n        \"hex\": \"\\u0123\\u4567\\u89AB\\uCDEF\\uabcd\\uef4A\",\n        \"true\": true,\n        \"false\": false,\n        \"null\": null,\n        \"array\":[  ],\n        \"object\":{  },\n        \"address\": \"50 St. James Street\",\n        \"url\": \"http://www.JSON.org/\",\n        \"comment\": \"// /* <!-- --\",\n        \"# -- --> */\": \" \",\n        \" s p a c e d \" :[1,2 , 3\n\n,\n\n4 , 5        ,          6           ,7        ],\"compact\":[1,2,3,4,5,6,7],\n        \"jsontext\": \"{\\\"object with 1 member\\\":[\\\"array with 1 element\\\"]}\",\n        \"quotes\": \"&#34; \\u0022 %22 0x22 034 &#x22;\",\n        \"\\/\\\\\\\"\\uCAFE\\uBABE\\uAB98\\uFCDE\\ubcda\\uef4A\\b\\f\\n\\r\\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?\"\n: \"A key can be any string\"\n    },\n    0.5 ,98.6\n,\n99.44\n,\n\n1066,\n1e1,\n0.1e1,\n1e-1,\n1e00,2e+00,2e-00\n,\"rosebud\"]"
  },
  {
    "path": "data/jsonchecker/pass02.json",
    "content": "[[[[[[[[[[[[[[[[[[[\"Not too deep\"]]]]]]]]]]]]]]]]]]]"
  },
  {
    "path": "data/jsonchecker/pass03.json",
    "content": "{\n    \"JSON Test Pattern pass3\": {\n        \"The outermost value\": \"must be an object or array.\",\n        \"In this test\": \"It is an object.\"\n    }\n}\n"
  },
  {
    "path": "data/parsing/i_number_double_huge_neg_exp.json",
    "content": "[123.456e-789]"
  },
  {
    "path": "data/parsing/i_number_huge_exp.json",
    "content": "[0.4e00669999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999969999999006]"
  },
  {
    "path": "data/parsing/i_number_neg_int_huge_exp.json",
    "content": "[-1e+9999]"
  },
  {
    "path": "data/parsing/i_number_pos_double_huge_exp.json",
    "content": "[1.5e+9999]"
  },
  {
    "path": "data/parsing/i_number_real_neg_overflow.json",
    "content": "[-123123e100000]"
  },
  {
    "path": "data/parsing/i_number_real_pos_overflow.json",
    "content": "[123123e100000]"
  },
  {
    "path": "data/parsing/i_number_real_underflow.json",
    "content": "[123e-10000000]"
  },
  {
    "path": "data/parsing/i_number_too_big_neg_int.json",
    "content": "[-123123123123123123123123123123]"
  },
  {
    "path": "data/parsing/i_number_too_big_pos_int.json",
    "content": "[100000000000000000000]"
  },
  {
    "path": "data/parsing/i_number_very_big_negative_int.json",
    "content": "[-237462374673276894279832749832423479823246327846]"
  },
  {
    "path": "data/parsing/i_object_key_lone_2nd_surrogate.json",
    "content": "{\"\\uDFAA\":0}"
  },
  {
    "path": "data/parsing/i_string_1st_surrogate_but_2nd_missing.json",
    "content": "[\"\\uDADA\"]"
  },
  {
    "path": "data/parsing/i_string_1st_valid_surrogate_2nd_invalid.json",
    "content": "[\"\\uD888\\u1234\"]"
  },
  {
    "path": "data/parsing/i_string_UTF-8_invalid_sequence.json",
    "content": "[\"日ш\"]"
  },
  {
    "path": "data/parsing/i_string_UTF8_surrogate_U+D800.json",
    "content": "[\"\"]"
  },
  {
    "path": "data/parsing/i_string_incomplete_surrogate_and_escape_valid.json",
    "content": "[\"\\uD800\\n\"]"
  },
  {
    "path": "data/parsing/i_string_incomplete_surrogate_pair.json",
    "content": "[\"\\uDd1ea\"]"
  },
  {
    "path": "data/parsing/i_string_incomplete_surrogates_escape_valid.json",
    "content": "[\"\\uD800\\uD800\\n\"]"
  },
  {
    "path": "data/parsing/i_string_invalid_lonely_surrogate.json",
    "content": "[\"\\ud800\"]"
  },
  {
    "path": "data/parsing/i_string_invalid_surrogate.json",
    "content": "[\"\\ud800abc\"]"
  },
  {
    "path": "data/parsing/i_string_invalid_utf-8.json",
    "content": "[\"\"]"
  },
  {
    "path": "data/parsing/i_string_inverted_surrogates_U+1D11E.json",
    "content": "[\"\\uDd1e\\uD834\"]"
  },
  {
    "path": "data/parsing/i_string_iso_latin_1.json",
    "content": "[\"\"]"
  },
  {
    "path": "data/parsing/i_string_lone_second_surrogate.json",
    "content": "[\"\\uDFAA\"]"
  },
  {
    "path": "data/parsing/i_string_lone_utf8_continuation_byte.json",
    "content": "[\"\"]"
  },
  {
    "path": "data/parsing/i_string_not_in_unicode_range.json",
    "content": "[\"\"]"
  },
  {
    "path": "data/parsing/i_string_overlong_sequence_2_bytes.json",
    "content": "[\"\"]"
  },
  {
    "path": "data/parsing/i_string_overlong_sequence_6_bytes.json",
    "content": "[\"\"]"
  },
  {
    "path": "data/parsing/i_string_overlong_sequence_6_bytes_null.json",
    "content": "[\"\"]"
  },
  {
    "path": "data/parsing/i_string_truncated-utf-8.json",
    "content": "[\"\"]"
  },
  {
    "path": "data/parsing/i_structure_UTF-8_BOM_empty_object.json",
    "content": "﻿{}"
  },
  {
    "path": "data/parsing/n_array_1_true_without_comma.json",
    "content": "[1 true]"
  },
  {
    "path": "data/parsing/n_array_a_invalid_utf8.json",
    "content": "[a]"
  },
  {
    "path": "data/parsing/n_array_colon_instead_of_comma.json",
    "content": "[\"\": 1]"
  },
  {
    "path": "data/parsing/n_array_comma_after_close.json",
    "content": "[\"\"],"
  },
  {
    "path": "data/parsing/n_array_comma_and_number.json",
    "content": "[,1]"
  },
  {
    "path": "data/parsing/n_array_double_comma.json",
    "content": "[1,,2]"
  },
  {
    "path": "data/parsing/n_array_double_extra_comma.json",
    "content": "[\"x\",,]"
  },
  {
    "path": "data/parsing/n_array_extra_close.json",
    "content": "[\"x\"]]"
  },
  {
    "path": "data/parsing/n_array_extra_comma.json",
    "content": "[\"\",]"
  },
  {
    "path": "data/parsing/n_array_incomplete.json",
    "content": "[\"x\""
  },
  {
    "path": "data/parsing/n_array_incomplete_invalid_value.json",
    "content": "[x"
  },
  {
    "path": "data/parsing/n_array_inner_array_no_comma.json",
    "content": "[3[4]]"
  },
  {
    "path": "data/parsing/n_array_invalid_utf8.json",
    "content": "[]"
  },
  {
    "path": "data/parsing/n_array_items_separated_by_semicolon.json",
    "content": "[1:2]"
  },
  {
    "path": "data/parsing/n_array_just_comma.json",
    "content": "[,]"
  },
  {
    "path": "data/parsing/n_array_just_minus.json",
    "content": "[-]"
  },
  {
    "path": "data/parsing/n_array_missing_value.json",
    "content": "[   , \"\"]"
  },
  {
    "path": "data/parsing/n_array_newlines_unclosed.json",
    "content": "[\"a\",\n4\n,1,"
  },
  {
    "path": "data/parsing/n_array_number_and_comma.json",
    "content": "[1,]"
  },
  {
    "path": "data/parsing/n_array_number_and_several_commas.json",
    "content": "[1,,]"
  },
  {
    "path": "data/parsing/n_array_spaces_vertical_tab_formfeed.json",
    "content": "[\"\u000ba\"\\f]"
  },
  {
    "path": "data/parsing/n_array_star_inside.json",
    "content": "[*]"
  },
  {
    "path": "data/parsing/n_array_unclosed.json",
    "content": "[\"\""
  },
  {
    "path": "data/parsing/n_array_unclosed_trailing_comma.json",
    "content": "[1,"
  },
  {
    "path": "data/parsing/n_array_unclosed_with_new_lines.json",
    "content": "[1,\n1\n,1"
  },
  {
    "path": "data/parsing/n_array_unclosed_with_object_inside.json",
    "content": "[{}"
  },
  {
    "path": "data/parsing/n_incomplete_false.json",
    "content": "[fals]"
  },
  {
    "path": "data/parsing/n_incomplete_null.json",
    "content": "[nul]"
  },
  {
    "path": "data/parsing/n_incomplete_true.json",
    "content": "[tru]"
  },
  {
    "path": "data/parsing/n_number_++.json",
    "content": "[++1234]"
  },
  {
    "path": "data/parsing/n_number_+1.json",
    "content": "[+1]"
  },
  {
    "path": "data/parsing/n_number_+Inf.json",
    "content": "[+Inf]"
  },
  {
    "path": "data/parsing/n_number_-01.json",
    "content": "[-01]"
  },
  {
    "path": "data/parsing/n_number_-1.0..json",
    "content": "[-1.0.]"
  },
  {
    "path": "data/parsing/n_number_-2..json",
    "content": "[-2.]"
  },
  {
    "path": "data/parsing/n_number_-NaN.json",
    "content": "[-NaN]"
  },
  {
    "path": "data/parsing/n_number_.-1.json",
    "content": "[.-1]"
  },
  {
    "path": "data/parsing/n_number_.2e-3.json",
    "content": "[.2e-3]"
  },
  {
    "path": "data/parsing/n_number_0.1.2.json",
    "content": "[0.1.2]"
  },
  {
    "path": "data/parsing/n_number_0.3e+.json",
    "content": "[0.3e+]"
  },
  {
    "path": "data/parsing/n_number_0.3e.json",
    "content": "[0.3e]"
  },
  {
    "path": "data/parsing/n_number_0.e1.json",
    "content": "[0.e1]"
  },
  {
    "path": "data/parsing/n_number_0_capital_E+.json",
    "content": "[0E+]"
  },
  {
    "path": "data/parsing/n_number_0_capital_E.json",
    "content": "[0E]"
  },
  {
    "path": "data/parsing/n_number_0e+.json",
    "content": "[0e+]"
  },
  {
    "path": "data/parsing/n_number_0e.json",
    "content": "[0e]"
  },
  {
    "path": "data/parsing/n_number_1.0e+.json",
    "content": "[1.0e+]"
  },
  {
    "path": "data/parsing/n_number_1.0e-.json",
    "content": "[1.0e-]"
  },
  {
    "path": "data/parsing/n_number_1.0e.json",
    "content": "[1.0e]"
  },
  {
    "path": "data/parsing/n_number_1_000.json",
    "content": "[1 000.0]"
  },
  {
    "path": "data/parsing/n_number_1eE2.json",
    "content": "[1eE2]"
  },
  {
    "path": "data/parsing/n_number_2.e+3.json",
    "content": "[2.e+3]"
  },
  {
    "path": "data/parsing/n_number_2.e-3.json",
    "content": "[2.e-3]"
  },
  {
    "path": "data/parsing/n_number_2.e3.json",
    "content": "[2.e3]"
  },
  {
    "path": "data/parsing/n_number_9.e+.json",
    "content": "[9.e+]"
  },
  {
    "path": "data/parsing/n_number_Inf.json",
    "content": "[Inf]"
  },
  {
    "path": "data/parsing/n_number_NaN.json",
    "content": "[NaN]"
  },
  {
    "path": "data/parsing/n_number_U+FF11_fullwidth_digit_one.json",
    "content": "[１]"
  },
  {
    "path": "data/parsing/n_number_expression.json",
    "content": "[1+2]"
  },
  {
    "path": "data/parsing/n_number_hex_1_digit.json",
    "content": "[0x1]"
  },
  {
    "path": "data/parsing/n_number_hex_2_digits.json",
    "content": "[0x42]"
  },
  {
    "path": "data/parsing/n_number_infinity.json",
    "content": "[Infinity]"
  },
  {
    "path": "data/parsing/n_number_invalid+-.json",
    "content": "[0e+-1]"
  },
  {
    "path": "data/parsing/n_number_invalid-negative-real.json",
    "content": "[-123.123foo]"
  },
  {
    "path": "data/parsing/n_number_invalid-utf-8-in-bigger-int.json",
    "content": "[123]"
  },
  {
    "path": "data/parsing/n_number_invalid-utf-8-in-exponent.json",
    "content": "[1e1]"
  },
  {
    "path": "data/parsing/n_number_invalid-utf-8-in-int.json",
    "content": "[0]\n"
  },
  {
    "path": "data/parsing/n_number_minus_infinity.json",
    "content": "[-Infinity]"
  },
  {
    "path": "data/parsing/n_number_minus_sign_with_trailing_garbage.json",
    "content": "[-foo]"
  },
  {
    "path": "data/parsing/n_number_minus_space_1.json",
    "content": "[- 1]"
  },
  {
    "path": "data/parsing/n_number_neg_int_starting_with_zero.json",
    "content": "[-012]"
  },
  {
    "path": "data/parsing/n_number_neg_real_without_int_part.json",
    "content": "[-.123]"
  },
  {
    "path": "data/parsing/n_number_neg_with_garbage_at_end.json",
    "content": "[-1x]"
  },
  {
    "path": "data/parsing/n_number_real_garbage_after_e.json",
    "content": "[1ea]"
  },
  {
    "path": "data/parsing/n_number_real_with_invalid_utf8_after_e.json",
    "content": "[1e]"
  },
  {
    "path": "data/parsing/n_number_real_without_fractional_part.json",
    "content": "[1.]"
  },
  {
    "path": "data/parsing/n_number_starting_with_dot.json",
    "content": "[.123]"
  },
  {
    "path": "data/parsing/n_number_with_alpha.json",
    "content": "[1.2a-3]"
  },
  {
    "path": "data/parsing/n_number_with_alpha_char.json",
    "content": "[1.8011670033376514H-308]"
  },
  {
    "path": "data/parsing/n_number_with_leading_zero.json",
    "content": "[012]"
  },
  {
    "path": "data/parsing/n_object_bad_value.json",
    "content": "[\"x\", truth]"
  },
  {
    "path": "data/parsing/n_object_bracket_key.json",
    "content": "{[: \"x\"}\n"
  },
  {
    "path": "data/parsing/n_object_comma_instead_of_colon.json",
    "content": "{\"x\", null}"
  },
  {
    "path": "data/parsing/n_object_double_colon.json",
    "content": "{\"x\"::\"b\"}"
  },
  {
    "path": "data/parsing/n_object_emoji.json",
    "content": "{🇨🇭}"
  },
  {
    "path": "data/parsing/n_object_garbage_at_end.json",
    "content": "{\"a\":\"a\" 123}"
  },
  {
    "path": "data/parsing/n_object_key_with_single_quotes.json",
    "content": "{key: 'value'}"
  },
  {
    "path": "data/parsing/n_object_lone_continuation_byte_in_key_and_trailing_comma.json",
    "content": "{\"\":\"0\",}"
  },
  {
    "path": "data/parsing/n_object_missing_colon.json",
    "content": "{\"a\" b}"
  },
  {
    "path": "data/parsing/n_object_missing_key.json",
    "content": "{:\"b\"}"
  },
  {
    "path": "data/parsing/n_object_missing_semicolon.json",
    "content": "{\"a\" \"b\"}"
  },
  {
    "path": "data/parsing/n_object_missing_value.json",
    "content": "{\"a\":"
  },
  {
    "path": "data/parsing/n_object_no-colon.json",
    "content": "{\"a\""
  },
  {
    "path": "data/parsing/n_object_non_string_key.json",
    "content": "{1:1}"
  },
  {
    "path": "data/parsing/n_object_non_string_key_but_huge_number_instead.json",
    "content": "{9999E9999:1}"
  },
  {
    "path": "data/parsing/n_object_repeated_null_null.json",
    "content": "{null:null,null:null}"
  },
  {
    "path": "data/parsing/n_object_several_trailing_commas.json",
    "content": "{\"id\":0,,,,,}"
  },
  {
    "path": "data/parsing/n_object_single_quote.json",
    "content": "{'a':0}"
  },
  {
    "path": "data/parsing/n_object_trailing_comma.json",
    "content": "{\"id\":0,}"
  },
  {
    "path": "data/parsing/n_object_trailing_comment.json",
    "content": "{\"a\":\"b\"}/**/"
  },
  {
    "path": "data/parsing/n_object_trailing_comment_open.json",
    "content": "{\"a\":\"b\"}/**//"
  },
  {
    "path": "data/parsing/n_object_trailing_comment_slash_open.json",
    "content": "{\"a\":\"b\"}//"
  },
  {
    "path": "data/parsing/n_object_trailing_comment_slash_open_incomplete.json",
    "content": "{\"a\":\"b\"}/"
  },
  {
    "path": "data/parsing/n_object_two_commas_in_a_row.json",
    "content": "{\"a\":\"b\",,\"c\":\"d\"}"
  },
  {
    "path": "data/parsing/n_object_unquoted_key.json",
    "content": "{a: \"b\"}"
  },
  {
    "path": "data/parsing/n_object_unterminated-value.json",
    "content": "{\"a\":\"a"
  },
  {
    "path": "data/parsing/n_object_with_single_string.json",
    "content": "{ \"foo\" : \"bar\", \"a\" }"
  },
  {
    "path": "data/parsing/n_object_with_trailing_garbage.json",
    "content": "{\"a\":\"b\"}#"
  },
  {
    "path": "data/parsing/n_single_space.json",
    "content": " "
  },
  {
    "path": "data/parsing/n_string_1_surrogate_then_escape.json",
    "content": "[\"\\uD800\\\"]"
  },
  {
    "path": "data/parsing/n_string_1_surrogate_then_escape_u.json",
    "content": "[\"\\uD800\\u\"]"
  },
  {
    "path": "data/parsing/n_string_1_surrogate_then_escape_u1.json",
    "content": "[\"\\uD800\\u1\"]"
  },
  {
    "path": "data/parsing/n_string_1_surrogate_then_escape_u1x.json",
    "content": "[\"\\uD800\\u1x\"]"
  },
  {
    "path": "data/parsing/n_string_accentuated_char_no_quotes.json",
    "content": "[é]"
  },
  {
    "path": "data/parsing/n_string_escape_x.json",
    "content": "[\"\\x00\"]"
  },
  {
    "path": "data/parsing/n_string_escaped_backslash_bad.json",
    "content": "[\"\\\\\\\"]"
  },
  {
    "path": "data/parsing/n_string_escaped_ctrl_char_tab.json",
    "content": "[\"\\\t\"]"
  },
  {
    "path": "data/parsing/n_string_escaped_emoji.json",
    "content": "[\"\\🌀\"]"
  },
  {
    "path": "data/parsing/n_string_incomplete_escape.json",
    "content": "[\"\\\"]"
  },
  {
    "path": "data/parsing/n_string_incomplete_escaped_character.json",
    "content": "[\"\\u00A\"]"
  },
  {
    "path": "data/parsing/n_string_incomplete_surrogate.json",
    "content": "[\"\\uD834\\uDd\"]"
  },
  {
    "path": "data/parsing/n_string_incomplete_surrogate_escape_invalid.json",
    "content": "[\"\\uD800\\uD800\\x\"]"
  },
  {
    "path": "data/parsing/n_string_invalid-utf-8-in-escape.json",
    "content": "[\"\\u\"]"
  },
  {
    "path": "data/parsing/n_string_invalid_backslash_esc.json",
    "content": "[\"\\a\"]"
  },
  {
    "path": "data/parsing/n_string_invalid_unicode_escape.json",
    "content": "[\"\\uqqqq\"]"
  },
  {
    "path": "data/parsing/n_string_invalid_utf8_after_escape.json",
    "content": "[\"\\\"]"
  },
  {
    "path": "data/parsing/n_string_leading_uescaped_thinspace.json",
    "content": "[\\u0020\"asd\"]"
  },
  {
    "path": "data/parsing/n_string_no_quotes_with_bad_escape.json",
    "content": "[\\n]"
  },
  {
    "path": "data/parsing/n_string_single_doublequote.json",
    "content": "\""
  },
  {
    "path": "data/parsing/n_string_single_quote.json",
    "content": "['single quote']"
  },
  {
    "path": "data/parsing/n_string_single_string_no_double_quotes.json",
    "content": "abc"
  },
  {
    "path": "data/parsing/n_string_start_escape_unclosed.json",
    "content": "[\"\\"
  },
  {
    "path": "data/parsing/n_string_unescaped_newline.json",
    "content": "[\"new\nline\"]"
  },
  {
    "path": "data/parsing/n_string_unescaped_tab.json",
    "content": "[\"\t\"]"
  },
  {
    "path": "data/parsing/n_string_unicode_CapitalU.json",
    "content": "\"\\UA66D\""
  },
  {
    "path": "data/parsing/n_string_with_trailing_garbage.json",
    "content": "\"\"x"
  },
  {
    "path": "data/parsing/n_structure_U+2060_word_joined.json",
    "content": "[⁠]"
  },
  {
    "path": "data/parsing/n_structure_UTF8_BOM_no_data.json",
    "content": "﻿"
  },
  {
    "path": "data/parsing/n_structure_angle_bracket_..json",
    "content": "<.>"
  },
  {
    "path": "data/parsing/n_structure_angle_bracket_null.json",
    "content": "[<null>]"
  },
  {
    "path": "data/parsing/n_structure_array_trailing_garbage.json",
    "content": "[1]x"
  },
  {
    "path": "data/parsing/n_structure_array_with_extra_array_close.json",
    "content": "[1]]"
  },
  {
    "path": "data/parsing/n_structure_array_with_unclosed_string.json",
    "content": "[\"asd]"
  },
  {
    "path": "data/parsing/n_structure_ascii-unicode-identifier.json",
    "content": "aå"
  },
  {
    "path": "data/parsing/n_structure_capitalized_True.json",
    "content": "[True]"
  },
  {
    "path": "data/parsing/n_structure_close_unopened_array.json",
    "content": "1]"
  },
  {
    "path": "data/parsing/n_structure_comma_instead_of_closing_brace.json",
    "content": "{\"x\": true,"
  },
  {
    "path": "data/parsing/n_structure_double_array.json",
    "content": "[][]"
  },
  {
    "path": "data/parsing/n_structure_end_array.json",
    "content": "]"
  },
  {
    "path": "data/parsing/n_structure_incomplete_UTF8_BOM.json",
    "content": "{}"
  },
  {
    "path": "data/parsing/n_structure_lone-invalid-utf-8.json",
    "content": ""
  },
  {
    "path": "data/parsing/n_structure_lone-open-bracket.json",
    "content": "["
  },
  {
    "path": "data/parsing/n_structure_no_data.json",
    "content": ""
  },
  {
    "path": "data/parsing/n_structure_number_with_trailing_garbage.json",
    "content": "2@"
  },
  {
    "path": "data/parsing/n_structure_object_followed_by_closing_object.json",
    "content": "{}}"
  },
  {
    "path": "data/parsing/n_structure_object_unclosed_no_value.json",
    "content": "{\"\":"
  },
  {
    "path": "data/parsing/n_structure_object_with_comment.json",
    "content": "{\"a\":/*comment*/\"b\"}"
  },
  {
    "path": "data/parsing/n_structure_object_with_trailing_garbage.json",
    "content": "{\"a\": true} \"x\""
  },
  {
    "path": "data/parsing/n_structure_open_array_apostrophe.json",
    "content": "['"
  },
  {
    "path": "data/parsing/n_structure_open_array_comma.json",
    "content": "[,"
  },
  {
    "path": "data/parsing/n_structure_open_array_open_object.json",
    "content": "[{"
  },
  {
    "path": "data/parsing/n_structure_open_array_open_string.json",
    "content": "[\"a"
  },
  {
    "path": "data/parsing/n_structure_open_array_string.json",
    "content": "[\"a\""
  },
  {
    "path": "data/parsing/n_structure_open_object.json",
    "content": "{"
  },
  {
    "path": "data/parsing/n_structure_open_object_close_array.json",
    "content": "{]"
  },
  {
    "path": "data/parsing/n_structure_open_object_comma.json",
    "content": "{,"
  },
  {
    "path": "data/parsing/n_structure_open_object_open_array.json",
    "content": "{["
  },
  {
    "path": "data/parsing/n_structure_open_object_open_string.json",
    "content": "{\"a"
  },
  {
    "path": "data/parsing/n_structure_open_object_string_with_apostrophes.json",
    "content": "{'a'"
  },
  {
    "path": "data/parsing/n_structure_open_open.json",
    "content": "[\"\\{[\"\\{[\"\\{[\"\\{"
  },
  {
    "path": "data/parsing/n_structure_single_eacute.json",
    "content": ""
  },
  {
    "path": "data/parsing/n_structure_single_star.json",
    "content": "*"
  },
  {
    "path": "data/parsing/n_structure_trailing_#.json",
    "content": "{\"a\":\"b\"}#{}"
  },
  {
    "path": "data/parsing/n_structure_uescaped_LF_before_string.json",
    "content": "[\\u000A\"\"]"
  },
  {
    "path": "data/parsing/n_structure_unclosed_array.json",
    "content": "[1"
  },
  {
    "path": "data/parsing/n_structure_unclosed_array_partial_null.json",
    "content": "[ false, nul"
  },
  {
    "path": "data/parsing/n_structure_unclosed_array_unfinished_false.json",
    "content": "[ true, fals"
  },
  {
    "path": "data/parsing/n_structure_unclosed_array_unfinished_true.json",
    "content": "[ false, tru"
  },
  {
    "path": "data/parsing/n_structure_unclosed_object.json",
    "content": "{\"asd\":\"asd\""
  },
  {
    "path": "data/parsing/n_structure_unicode-identifier.json",
    "content": "å"
  },
  {
    "path": "data/parsing/n_structure_whitespace_U+2060_word_joiner.json",
    "content": "[⁠]"
  },
  {
    "path": "data/parsing/n_structure_whitespace_formfeed.json",
    "content": "[\f]"
  },
  {
    "path": "data/parsing/y_array_arraysWithSpaces.json",
    "content": "[[]   ]"
  },
  {
    "path": "data/parsing/y_array_empty-string.json",
    "content": "[\"\"]"
  },
  {
    "path": "data/parsing/y_array_empty.json",
    "content": "[]"
  },
  {
    "path": "data/parsing/y_array_ending_with_newline.json",
    "content": "[\"a\"]"
  },
  {
    "path": "data/parsing/y_array_false.json",
    "content": "[false]"
  },
  {
    "path": "data/parsing/y_array_heterogeneous.json",
    "content": "[null, 1, \"1\", {}]"
  },
  {
    "path": "data/parsing/y_array_null.json",
    "content": "[null]"
  },
  {
    "path": "data/parsing/y_array_with_1_and_newline.json",
    "content": "[1\n]"
  },
  {
    "path": "data/parsing/y_array_with_leading_space.json",
    "content": " [1]"
  },
  {
    "path": "data/parsing/y_array_with_several_null.json",
    "content": "[1,null,null,null,2]"
  },
  {
    "path": "data/parsing/y_array_with_trailing_space.json",
    "content": "[2] "
  },
  {
    "path": "data/parsing/y_number.json",
    "content": "[123e65]"
  },
  {
    "path": "data/parsing/y_number_0e+1.json",
    "content": "[0e+1]"
  },
  {
    "path": "data/parsing/y_number_0e1.json",
    "content": "[0e1]"
  },
  {
    "path": "data/parsing/y_number_after_space.json",
    "content": "[ 4]"
  },
  {
    "path": "data/parsing/y_number_double_close_to_zero.json",
    "content": "[-0.000000000000000000000000000000000000000000000000000000000000000000000000000001]\n"
  },
  {
    "path": "data/parsing/y_number_int_with_exp.json",
    "content": "[20e1]"
  },
  {
    "path": "data/parsing/y_number_minus_zero.json",
    "content": "[-0]"
  },
  {
    "path": "data/parsing/y_number_negative_int.json",
    "content": "[-123]"
  },
  {
    "path": "data/parsing/y_number_negative_one.json",
    "content": "[-1]"
  },
  {
    "path": "data/parsing/y_number_negative_zero.json",
    "content": "[-0]"
  },
  {
    "path": "data/parsing/y_number_real_capital_e.json",
    "content": "[1E22]"
  },
  {
    "path": "data/parsing/y_number_real_capital_e_neg_exp.json",
    "content": "[1E-2]"
  },
  {
    "path": "data/parsing/y_number_real_capital_e_pos_exp.json",
    "content": "[1E+2]"
  },
  {
    "path": "data/parsing/y_number_real_exponent.json",
    "content": "[123e45]"
  },
  {
    "path": "data/parsing/y_number_real_fraction_exponent.json",
    "content": "[123.456e78]"
  },
  {
    "path": "data/parsing/y_number_real_neg_exp.json",
    "content": "[1e-2]"
  },
  {
    "path": "data/parsing/y_number_real_pos_exponent.json",
    "content": "[1e+2]"
  },
  {
    "path": "data/parsing/y_number_simple_int.json",
    "content": "[123]"
  },
  {
    "path": "data/parsing/y_number_simple_real.json",
    "content": "[123.456789]"
  },
  {
    "path": "data/parsing/y_object.json",
    "content": "{\"asd\":\"sdf\", \"dfg\":\"fgh\"}"
  },
  {
    "path": "data/parsing/y_object_basic.json",
    "content": "{\"asd\":\"sdf\"}"
  },
  {
    "path": "data/parsing/y_object_duplicated_key.json",
    "content": "{\"a\":\"b\",\"a\":\"c\"}"
  },
  {
    "path": "data/parsing/y_object_duplicated_key_and_value.json",
    "content": "{\"a\":\"b\",\"a\":\"b\"}"
  },
  {
    "path": "data/parsing/y_object_empty.json",
    "content": "{}"
  },
  {
    "path": "data/parsing/y_object_empty_key.json",
    "content": "{\"\":0}"
  },
  {
    "path": "data/parsing/y_object_escaped_null_in_key.json",
    "content": "{\"foo\\u0000bar\": 42}"
  },
  {
    "path": "data/parsing/y_object_extreme_numbers.json",
    "content": "{ \"min\": -1.0e+28, \"max\": 1.0e+28 }"
  },
  {
    "path": "data/parsing/y_object_long_strings.json",
    "content": "{\"x\":[{\"id\": \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"}], \"id\": \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"}"
  },
  {
    "path": "data/parsing/y_object_simple.json",
    "content": "{\"a\":[]}"
  },
  {
    "path": "data/parsing/y_object_string_unicode.json",
    "content": "{\"title\":\"\\u041f\\u043e\\u043b\\u0442\\u043e\\u0440\\u0430 \\u0417\\u0435\\u043c\\u043b\\u0435\\u043a\\u043e\\u043f\\u0430\" }"
  },
  {
    "path": "data/parsing/y_object_with_newlines.json",
    "content": "{\n\"a\": \"b\"\n}"
  },
  {
    "path": "data/parsing/y_string_1_2_3_bytes_UTF-8_sequences.json",
    "content": "[\"\\u0060\\u012a\\u12AB\"]"
  },
  {
    "path": "data/parsing/y_string_accepted_surrogate_pair.json",
    "content": "[\"\\uD801\\udc37\"]"
  },
  {
    "path": "data/parsing/y_string_accepted_surrogate_pairs.json",
    "content": "[\"\\ud83d\\ude39\\ud83d\\udc8d\"]"
  },
  {
    "path": "data/parsing/y_string_allowed_escapes.json",
    "content": "[\"\\\"\\\\\\/\\b\\f\\n\\r\\t\"]"
  },
  {
    "path": "data/parsing/y_string_backslash_and_u_escaped_zero.json",
    "content": "[\"\\\\u0000\"]"
  },
  {
    "path": "data/parsing/y_string_backslash_doublequotes.json",
    "content": "[\"\\\"\"]"
  },
  {
    "path": "data/parsing/y_string_comments.json",
    "content": "[\"a/*b*/c/*d//e\"]"
  },
  {
    "path": "data/parsing/y_string_double_escape_a.json",
    "content": "[\"\\\\a\"]"
  },
  {
    "path": "data/parsing/y_string_double_escape_n.json",
    "content": "[\"\\\\n\"]"
  },
  {
    "path": "data/parsing/y_string_escaped_control_character.json",
    "content": "[\"\\u0012\"]"
  },
  {
    "path": "data/parsing/y_string_escaped_noncharacter.json",
    "content": "[\"\\uFFFF\"]"
  },
  {
    "path": "data/parsing/y_string_in_array.json",
    "content": "[\"asd\"]"
  },
  {
    "path": "data/parsing/y_string_in_array_with_leading_space.json",
    "content": "[ \"asd\"]"
  },
  {
    "path": "data/parsing/y_string_last_surrogates_1_and_2.json",
    "content": "[\"\\uDBFF\\uDFFF\"]"
  },
  {
    "path": "data/parsing/y_string_nbsp_uescaped.json",
    "content": "[\"new\\u00A0line\"]"
  },
  {
    "path": "data/parsing/y_string_nonCharacterInUTF-8_U+10FFFF.json",
    "content": "[\"􏿿\"]"
  },
  {
    "path": "data/parsing/y_string_nonCharacterInUTF-8_U+FFFF.json",
    "content": "[\"￿\"]"
  },
  {
    "path": "data/parsing/y_string_null_escape.json",
    "content": "[\"\\u0000\"]"
  },
  {
    "path": "data/parsing/y_string_one-byte-utf-8.json",
    "content": "[\"\\u002c\"]"
  },
  {
    "path": "data/parsing/y_string_pi.json",
    "content": "[\"π\"]"
  },
  {
    "path": "data/parsing/y_string_reservedCharacterInUTF-8_U+1BFFF.json",
    "content": "[\"𛿿\"]"
  },
  {
    "path": "data/parsing/y_string_simple_ascii.json",
    "content": "[\"asd \"]"
  },
  {
    "path": "data/parsing/y_string_space.json",
    "content": "\" \""
  },
  {
    "path": "data/parsing/y_string_surrogates_U+1D11E_MUSICAL_SYMBOL_G_CLEF.json",
    "content": "[\"\\uD834\\uDd1e\"]"
  },
  {
    "path": "data/parsing/y_string_three-byte-utf-8.json",
    "content": "[\"\\u0821\"]"
  },
  {
    "path": "data/parsing/y_string_two-byte-utf-8.json",
    "content": "[\"\\u0123\"]"
  },
  {
    "path": "data/parsing/y_string_u+2028_line_sep.json",
    "content": "[\" \"]"
  },
  {
    "path": "data/parsing/y_string_u+2029_par_sep.json",
    "content": "[\" \"]"
  },
  {
    "path": "data/parsing/y_string_uEscape.json",
    "content": "[\"\\u0061\\u30af\\u30EA\\u30b9\"]"
  },
  {
    "path": "data/parsing/y_string_uescaped_newline.json",
    "content": "[\"new\\u000Aline\"]"
  },
  {
    "path": "data/parsing/y_string_unescaped_char_delete.json",
    "content": "[\"\"]"
  },
  {
    "path": "data/parsing/y_string_unicode.json",
    "content": "[\"\\uA66D\"]"
  },
  {
    "path": "data/parsing/y_string_unicodeEscapedBackslash.json",
    "content": "[\"\\u005C\"]"
  },
  {
    "path": "data/parsing/y_string_unicode_2.json",
    "content": "[\"⍂㈴⍂\"]"
  },
  {
    "path": "data/parsing/y_string_unicode_U+10FFFE_nonchar.json",
    "content": "[\"\\uDBFF\\uDFFE\"]"
  },
  {
    "path": "data/parsing/y_string_unicode_U+1FFFE_nonchar.json",
    "content": "[\"\\uD83F\\uDFFE\"]"
  },
  {
    "path": "data/parsing/y_string_unicode_U+200B_ZERO_WIDTH_SPACE.json",
    "content": "[\"\\u200B\"]"
  },
  {
    "path": "data/parsing/y_string_unicode_U+2064_invisible_plus.json",
    "content": "[\"\\u2064\"]"
  },
  {
    "path": "data/parsing/y_string_unicode_U+FDD0_nonchar.json",
    "content": "[\"\\uFDD0\"]"
  },
  {
    "path": "data/parsing/y_string_unicode_U+FFFE_nonchar.json",
    "content": "[\"\\uFFFE\"]"
  },
  {
    "path": "data/parsing/y_string_unicode_escaped_double_quote.json",
    "content": "[\"\\u0022\"]"
  },
  {
    "path": "data/parsing/y_string_utf8.json",
    "content": "[\"€𝄞\"]"
  },
  {
    "path": "data/parsing/y_string_with_del_character.json",
    "content": "[\"aa\"]"
  },
  {
    "path": "data/parsing/y_structure_lonely_false.json",
    "content": "false"
  },
  {
    "path": "data/parsing/y_structure_lonely_int.json",
    "content": "42"
  },
  {
    "path": "data/parsing/y_structure_lonely_negative_real.json",
    "content": "-0.1"
  },
  {
    "path": "data/parsing/y_structure_lonely_null.json",
    "content": "null"
  },
  {
    "path": "data/parsing/y_structure_lonely_string.json",
    "content": "\"asd\""
  },
  {
    "path": "data/parsing/y_structure_lonely_true.json",
    "content": "true"
  },
  {
    "path": "data/parsing/y_structure_string_empty.json",
    "content": "\"\""
  },
  {
    "path": "data/parsing/y_structure_trailing_newline.json",
    "content": "[\"a\"]\n"
  },
  {
    "path": "data/parsing/y_structure_true_in_array.json",
    "content": "[true]"
  },
  {
    "path": "data/parsing/y_structure_whitespace_array.json",
    "content": " [] "
  },
  {
    "path": "data/roundtrip/roundtrip01.json",
    "content": "[null]"
  },
  {
    "path": "data/roundtrip/roundtrip02.json",
    "content": "[true]"
  },
  {
    "path": "data/roundtrip/roundtrip03.json",
    "content": "[false]"
  },
  {
    "path": "data/roundtrip/roundtrip04.json",
    "content": "[0]"
  },
  {
    "path": "data/roundtrip/roundtrip05.json",
    "content": "[\"foo\"]"
  },
  {
    "path": "data/roundtrip/roundtrip06.json",
    "content": "[]"
  },
  {
    "path": "data/roundtrip/roundtrip07.json",
    "content": "{}"
  },
  {
    "path": "data/roundtrip/roundtrip08.json",
    "content": "[0,1]"
  },
  {
    "path": "data/roundtrip/roundtrip09.json",
    "content": "{\"foo\":\"bar\"}"
  },
  {
    "path": "data/roundtrip/roundtrip10.json",
    "content": "{\"a\":null,\"foo\":\"bar\"}"
  },
  {
    "path": "data/roundtrip/roundtrip11.json",
    "content": "[-1]"
  },
  {
    "path": "data/roundtrip/roundtrip12.json",
    "content": "[-2147483648]"
  },
  {
    "path": "data/roundtrip/roundtrip13.json",
    "content": "[-1234567890123456789]"
  },
  {
    "path": "data/roundtrip/roundtrip14.json",
    "content": "[-9223372036854775808]"
  },
  {
    "path": "data/roundtrip/roundtrip15.json",
    "content": "[1]"
  },
  {
    "path": "data/roundtrip/roundtrip16.json",
    "content": "[2147483647]"
  },
  {
    "path": "data/roundtrip/roundtrip17.json",
    "content": "[4294967295]"
  },
  {
    "path": "data/roundtrip/roundtrip18.json",
    "content": "[1234567890123456789]"
  },
  {
    "path": "data/roundtrip/roundtrip19.json",
    "content": "[9223372036854775807]"
  },
  {
    "path": "data/roundtrip/roundtrip20.json",
    "content": "[0.0]"
  },
  {
    "path": "data/roundtrip/roundtrip21.json",
    "content": "[-0.0]"
  },
  {
    "path": "data/roundtrip/roundtrip22.json",
    "content": "[1.2345]"
  },
  {
    "path": "data/roundtrip/roundtrip23.json",
    "content": "[-1.2345]"
  },
  {
    "path": "data/roundtrip/roundtrip24.json",
    "content": "[5e-324]"
  },
  {
    "path": "data/roundtrip/roundtrip25.json",
    "content": "[2.225073858507201e-308]"
  },
  {
    "path": "data/roundtrip/roundtrip26.json",
    "content": "[2.2250738585072014e-308]"
  },
  {
    "path": "data/roundtrip/roundtrip27.json",
    "content": "[1.7976931348623157e308]"
  },
  {
    "path": "data/transform/number_1.0.json",
    "content": "[1.0]"
  },
  {
    "path": "data/transform/number_1.000000000000000005.json",
    "content": "[1.000000000000000005]"
  },
  {
    "path": "data/transform/number_1000000000000000.json",
    "content": "[1000000000000000]\n"
  },
  {
    "path": "data/transform/number_10000000000000000999.json",
    "content": "[10000000000000000999]"
  },
  {
    "path": "data/transform/number_1e-999.json",
    "content": "[1E-999]"
  },
  {
    "path": "data/transform/number_1e6.json",
    "content": "[1E6]"
  },
  {
    "path": "data/transform/object_key_nfc_nfd.json",
    "content": "{\"é\":\"NFC\",\"é\":\"NFD\"}"
  },
  {
    "path": "data/transform/object_key_nfd_nfc.json",
    "content": "{\"é\":\"NFD\",\"é\":\"NFC\"}"
  },
  {
    "path": "data/transform/object_same_key_different_values.json",
    "content": "{\"a\":1,\"a\":2}"
  },
  {
    "path": "data/transform/object_same_key_same_value.json",
    "content": "{\"a\":1,\"a\":1}"
  },
  {
    "path": "data/transform/object_same_key_unclear_values.json",
    "content": "{\"a\":0, \"a\":-0}\n"
  },
  {
    "path": "data/transform/string_1_escaped_invalid_codepoint.json",
    "content": "[\"\\uD800\"]"
  },
  {
    "path": "data/transform/string_1_invalid_codepoint.json",
    "content": "[\"\"]"
  },
  {
    "path": "data/transform/string_2_escaped_invalid_codepoints.json",
    "content": "[\"\\uD800\\uD800\"]"
  },
  {
    "path": "data/transform/string_2_invalid_codepoints.json",
    "content": "[\"\"]"
  },
  {
    "path": "data/transform/string_3_escaped_invalid_codepoints.json",
    "content": "[\"\\uD800\\uD800\\uD800\"]"
  },
  {
    "path": "data/transform/string_3_invalid_codepoints.json",
    "content": "[\"\"]"
  },
  {
    "path": "data/transform/string_with_escaped_NULL.json",
    "content": "[\"A\\u0000B\"]"
  },
  {
    "path": "include/yyjson/yyjson.c",
    "content": "/*==============================================================================\n Copyright (c) 2020 YaoYuan <ibireme@gmail.com>\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n *============================================================================*/\n\n#include \"yyjson.h\"\n#include <math.h>\n\n\n\n/*==============================================================================\n * Warning Suppress\n *============================================================================*/\n\n#if defined(__clang__)\n#   pragma clang diagnostic ignored \"-Wunused-function\"\n#   pragma clang diagnostic ignored \"-Wunused-parameter\"\n#   pragma clang diagnostic ignored \"-Wunused-label\"\n#   pragma clang diagnostic ignored \"-Wunused-macros\"\n#   pragma clang diagnostic ignored \"-Wunused-variable\"\n#elif defined(__GNUC__)\n#   pragma GCC diagnostic ignored \"-Wunused-function\"\n#   pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#   pragma GCC diagnostic ignored \"-Wunused-label\"\n#   pragma GCC diagnostic ignored \"-Wunused-macros\"\n#   pragma GCC diagnostic ignored \"-Wunused-variable\"\n#elif defined(_MSC_VER)\n#   pragma warning(disable:4100) /* unreferenced formal parameter */\n#   pragma warning(disable:4101) /* unreferenced variable */\n#   pragma warning(disable:4102) /* unreferenced label */\n#   pragma warning(disable:4127) /* conditional expression is constant */\n#   pragma warning(disable:4706) /* assignment within conditional expression */\n#endif\n\n\n\n/*==============================================================================\n * Version\n *============================================================================*/\n\nuint32_t yyjson_version(void) {\n    return YYJSON_VERSION_HEX;\n}\n\n\n\n/*==============================================================================\n * Flags\n *============================================================================*/\n\n/* msvc intrinsic */\n#if YYJSON_MSC_VER >= 1400\n#   include <intrin.h>\n#   if defined(_M_AMD64) || defined(_M_ARM64)\n#       define MSC_HAS_BIT_SCAN_64 1\n#       pragma intrinsic(_BitScanForward64)\n#       pragma intrinsic(_BitScanReverse64)\n#   else\n#       define MSC_HAS_BIT_SCAN_64 0\n#   endif\n#   if defined(_M_AMD64) || defined(_M_ARM64) || \\\n        defined(_M_IX86) || defined(_M_ARM)\n#       define MSC_HAS_BIT_SCAN 1\n#       pragma intrinsic(_BitScanForward)\n#       pragma intrinsic(_BitScanReverse)\n#   else\n#       define MSC_HAS_BIT_SCAN 0\n#   endif\n#   if defined(_M_AMD64)\n#       define MSC_HAS_UMUL128 1\n#       pragma intrinsic(_umul128)\n#   else\n#       define MSC_HAS_UMUL128 0\n#   endif\n#else\n#   define MSC_HAS_BIT_SCAN_64 0\n#   define MSC_HAS_BIT_SCAN 0\n#   define MSC_HAS_UMUL128 0\n#endif\n\n/* gcc builtin */\n#if yyjson_has_builtin(__builtin_clzll) || yyjson_gcc_available(3, 4, 0)\n#   define GCC_HAS_CLZLL 1\n#else\n#   define GCC_HAS_CLZLL 0\n#endif\n\n#if yyjson_has_builtin(__builtin_ctzll) || yyjson_gcc_available(3, 4, 0)\n#   define GCC_HAS_CTZLL 1\n#else\n#   define GCC_HAS_CTZLL 0\n#endif\n\n/* int128 type */\n#if defined(__SIZEOF_INT128__) && (__SIZEOF_INT128__ == 16) && \\\n    (defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER))\n#    define YYJSON_HAS_INT128 1\n#else\n#    define YYJSON_HAS_INT128 0\n#endif\n\n/* IEEE 754 floating-point binary representation */\n#if defined(__STDC_IEC_559__) || defined(__STDC_IEC_60559_BFP__)\n#   define YYJSON_HAS_IEEE_754 1\n#elif (FLT_RADIX == 2) && (DBL_MANT_DIG == 53) && (DBL_DIG == 15) && \\\n     (DBL_MIN_EXP == -1021) && (DBL_MAX_EXP == 1024) && \\\n     (DBL_MIN_10_EXP == -307) && (DBL_MAX_10_EXP == 308)\n#   define YYJSON_HAS_IEEE_754 1\n#else\n#   define YYJSON_HAS_IEEE_754 0\n#endif\n\n/*\n Correct rounding in double number computations.\n \n On the x86 architecture, some compilers may use x87 FPU instructions for\n floating-point arithmetic. The x87 FPU loads all floating point number as\n 80-bit double-extended precision internally, then rounds the result to original\n precision, which may produce inaccurate results. For a more detailed\n explanation, see the paper: https://arxiv.org/abs/cs/0701192\n \n Here are some examples of double precision calculation error:\n \n     2877.0 / 1e6   == 0.002877,  but x87 returns 0.0028770000000000002\n     43683.0 * 1e21 == 4.3683e25, but x87 returns 4.3683000000000004e25\n \n Here are some examples of compiler flags to generate x87 instructions on x86:\n \n     clang -m32 -mno-sse\n     gcc/icc -m32 -mfpmath=387\n     msvc /arch:SSE or /arch:IA32\n \n If we are sure that there's no similar error described above, we can define the\n YYJSON_DOUBLE_MATH_CORRECT as 1 to enable the fast path calculation. This is\n not an accurate detection, it's just try to avoid the error at compile-time.\n An accurate detection can be done at run-time:\n \n     bool is_double_math_correct(void) {\n         volatile double r = 43683.0;\n         r *= 1e21;\n         return r == 4.3683e25;\n     }\n \n See also: utils.h in https://github.com/google/double-conversion/\n */\n#if !defined(FLT_EVAL_METHOD) && defined(__FLT_EVAL_METHOD__)\n#    define FLT_EVAL_METHOD __FLT_EVAL_METHOD__\n#endif\n\n#if defined(FLT_EVAL_METHOD) && FLT_EVAL_METHOD != 0 && FLT_EVAL_METHOD != 1\n#    define YYJSON_DOUBLE_MATH_CORRECT 0\n#elif defined(i386) || defined(__i386) || defined(__i386__) || \\\n    defined(_X86_) || defined(__X86__) || defined(_M_IX86) || \\\n    defined(__I86__) || defined(__IA32__) || defined(__THW_INTEL)\n#   if (defined(_MSC_VER) && defined(_M_IX86_FP) && _M_IX86_FP == 2) || \\\n        (defined(__SSE2_MATH__) && __SSE2_MATH__)\n#       define YYJSON_DOUBLE_MATH_CORRECT 1\n#   else\n#       define YYJSON_DOUBLE_MATH_CORRECT 0\n#   endif\n#elif defined(__mc68000__) || defined(__pnacl__) || defined(__native_client__)\n#   define YYJSON_DOUBLE_MATH_CORRECT 0\n#else\n#   define YYJSON_DOUBLE_MATH_CORRECT 1\n#endif\n\n/* endian */\n#if yyjson_has_include(<sys/types.h>)\n#    include <sys/types.h> /* POSIX */\n#endif\n#if yyjson_has_include(<endian.h>)\n#    include <endian.h> /* Linux */\n#elif yyjson_has_include(<sys/endian.h>)\n#    include <sys/endian.h> /* BSD, Android */\n#elif yyjson_has_include(<machine/endian.h>)\n#    include <machine/endian.h> /* BSD, Darwin */\n#endif\n\n#define YYJSON_BIG_ENDIAN       4321\n#define YYJSON_LITTLE_ENDIAN    1234\n\n#if defined(BYTE_ORDER) && BYTE_ORDER\n#   if defined(BIG_ENDIAN) && (BYTE_ORDER == BIG_ENDIAN)\n#       define YYJSON_ENDIAN YYJSON_BIG_ENDIAN\n#   elif defined(LITTLE_ENDIAN) && (BYTE_ORDER == LITTLE_ENDIAN)\n#       define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN\n#   endif\n\n#elif defined(__BYTE_ORDER) && __BYTE_ORDER\n#   if defined(__BIG_ENDIAN) && (__BYTE_ORDER == __BIG_ENDIAN)\n#       define YYJSON_ENDIAN YYJSON_BIG_ENDIAN\n#   elif defined(__LITTLE_ENDIAN) && (__BYTE_ORDER == __LITTLE_ENDIAN)\n#       define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN\n#   endif\n\n#elif defined(__BYTE_ORDER__) && __BYTE_ORDER__\n#   if defined(__ORDER_BIG_ENDIAN__) && \\\n        (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)\n#       define YYJSON_ENDIAN YYJSON_BIG_ENDIAN\n#   elif defined(__ORDER_LITTLE_ENDIAN__) && \\\n        (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)\n#       define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN\n#   endif\n\n#elif (defined(__LITTLE_ENDIAN__) && __LITTLE_ENDIAN__ == 1) || \\\n    defined(__i386) || defined(__i386__) || \\\n    defined(_X86_) || defined(__X86__) || \\\n    defined(_M_IX86) || defined(__THW_INTEL__) || \\\n    defined(__x86_64) || defined(__x86_64__) || \\\n    defined(__amd64) || defined(__amd64__) || \\\n    defined(_M_AMD64) || defined(_M_X64) || \\\n    defined(_M_ARM) || defined(_M_ARM64) || \\\n    defined(__ARMEL__) || defined(__THUMBEL__) || defined(__AARCH64EL__) || \\\n    defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__) || \\\n    defined(__EMSCRIPTEN__) || defined(__wasm__) || \\\n    defined(__loongarch__)\n#   define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN\n\n#elif (defined(__BIG_ENDIAN__) && __BIG_ENDIAN__ == 1) || \\\n    defined(__ARMEB__) || defined(__THUMBEB__) || defined(__AARCH64EB__) || \\\n    defined(_MIPSEB) || defined(__MIPSEB) || defined(__MIPSEB__) || \\\n    defined(__or1k__) || defined(__OR1K__)\n#   define YYJSON_ENDIAN YYJSON_BIG_ENDIAN\n\n#else\n#   define YYJSON_ENDIAN 0 /* unknown endian, detect at run-time */\n#endif\n\n/*\n This macro controls how yyjson handles unaligned memory accesses.\n \n By default, yyjson uses `memcpy()` for memory copying. This takes advantage of\n the compiler's automatic optimizations to generate unaligned memory access\n instructions when the target architecture supports it.\n \n However, for some older compilers or architectures where `memcpy()` isn't\n optimized well and may generate unnecessary function calls, consider defining\n this macro as 1. In such cases, yyjson switches to manual byte-by-byte access,\n potentially improving performance. An example of the generated assembly code on\n the ARM platform can be found here: https://godbolt.org/z/334jjhxPT\n \n As this flag has already been enabled for some common architectures in the\n following code, users typically don't need to manually specify it. If users are\n unsure about it, please review the generated assembly code or perform actual\n benchmark to make an informed decision.\n */\n#ifndef YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS\n#   if defined(__ia64) || defined(_IA64) || defined(__IA64__) ||  \\\n        defined(__ia64__) || defined(_M_IA64) || defined(__itanium__)\n#       define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* Itanium */\n#   elif (defined(__arm__) || defined(__arm64__) || defined(__aarch64__)) && \\\n        (defined(__GNUC__) || defined(__clang__)) && \\\n        (!defined(__ARM_FEATURE_UNALIGNED) || !__ARM_FEATURE_UNALIGNED)\n#       define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* ARM */\n#   elif defined(__sparc) || defined(__sparc__)\n#       define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* SPARC */\n#   elif defined(__mips) || defined(__mips__) || defined(__MIPS__)\n#       define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* MIPS */\n#   elif defined(__m68k__) || defined(M68000)\n#       define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* M68K */\n#   else\n#       define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 0\n#   endif\n#endif\n\n/*\n Estimated initial ratio of the JSON data (data_size / value_count).\n For example:\n    \n    data:        {\"id\":12345678,\"name\":\"Harry\"}\n    data_size:   30\n    value_count: 5\n    ratio:       6\n    \n yyjson uses dynamic memory with a growth factor of 1.5 when reading and writing\n JSON, the ratios below are used to determine the initial memory size.\n \n A too large ratio will waste memory, and a too small ratio will cause multiple\n memory growths and degrade performance. Currently, these ratios are generated\n with some commonly used JSON datasets.\n */\n#define YYJSON_READER_ESTIMATED_PRETTY_RATIO 16\n#define YYJSON_READER_ESTIMATED_MINIFY_RATIO 6\n#define YYJSON_WRITER_ESTIMATED_PRETTY_RATIO 32\n#define YYJSON_WRITER_ESTIMATED_MINIFY_RATIO 18\n\n/* The initial and maximum size of the memory pool's chunk in yyjson_mut_doc. */\n#define YYJSON_MUT_DOC_STR_POOL_INIT_SIZE   0x100\n#define YYJSON_MUT_DOC_STR_POOL_MAX_SIZE    0x10000000\n#define YYJSON_MUT_DOC_VAL_POOL_INIT_SIZE   (0x10 * sizeof(yyjson_mut_val))\n#define YYJSON_MUT_DOC_VAL_POOL_MAX_SIZE    (0x1000000 * sizeof(yyjson_mut_val))\n\n/* The minimum size of the dynamic allocator's chunk. */\n#define YYJSON_ALC_DYN_MIN_SIZE             0x1000\n\n/* Default value for compile-time options. */\n#ifndef YYJSON_DISABLE_READER\n#define YYJSON_DISABLE_READER 0\n#endif\n#ifndef YYJSON_DISABLE_WRITER\n#define YYJSON_DISABLE_WRITER 0\n#endif\n#ifndef YYJSON_DISABLE_UTILS\n#define YYJSON_DISABLE_UTILS 0\n#endif\n#ifndef YYJSON_DISABLE_FAST_FP_CONV\n#define YYJSON_DISABLE_FAST_FP_CONV 0\n#endif\n#ifndef YYJSON_DISABLE_NON_STANDARD\n#define YYJSON_DISABLE_NON_STANDARD 0\n#endif\n#ifndef YYJSON_DISABLE_UTF8_VALIDATION\n#define YYJSON_DISABLE_UTF8_VALIDATION 0\n#endif\n#ifndef YYJSON_READER_CONTAINER_RECURSION_LIMIT\n#define YYJSON_READER_CONTAINER_RECURSION_LIMIT 1024\n#endif\n\n/*==============================================================================\n * Macros\n *============================================================================*/\n\n/* Macros used for loop unrolling and other purpose. */\n#define repeat2(x)  { x x }\n#define repeat3(x)  { x x x }\n#define repeat4(x)  { x x x x }\n#define repeat8(x)  { x x x x x x x x }\n#define repeat16(x) { x x x x x x x x x x x x x x x x }\n\n#define repeat2_incr(x)   { x(0)  x(1) }\n#define repeat4_incr(x)   { x(0)  x(1)  x(2)  x(3) }\n#define repeat8_incr(x)   { x(0)  x(1)  x(2)  x(3)  x(4)  x(5)  x(6)  x(7)  }\n#define repeat16_incr(x)  { x(0)  x(1)  x(2)  x(3)  x(4)  x(5)  x(6)  x(7)  \\\n                            x(8)  x(9)  x(10) x(11) x(12) x(13) x(14) x(15) }\n\n#define repeat_in_1_18(x) { x(1)  x(2)  x(3)  x(4)  x(5)  x(6)  x(7)  x(8)  \\\n                            x(9)  x(10) x(11) x(12) x(13) x(14) x(15) x(16) \\\n                            x(17) x(18) }\n\n/* Macros used to provide branch prediction information for compiler. */\n#undef  likely\n#define likely(x)       yyjson_likely(x)\n#undef  unlikely\n#define unlikely(x)     yyjson_unlikely(x)\n\n/* Macros used to provide inline information for compiler. */\n#undef  static_inline\n#define static_inline   static yyjson_inline\n#undef  static_noinline\n#define static_noinline static yyjson_noinline\n\n/* Macros for min and max. */\n#undef  yyjson_min\n#define yyjson_min(x, y) ((x) < (y) ? (x) : (y))\n#undef  yyjson_max\n#define yyjson_max(x, y) ((x) > (y) ? (x) : (y))\n\n/* Used to write u64 literal for C89 which doesn't support \"ULL\" suffix. */\n#undef  U64\n#define U64(hi, lo) ((((u64)hi##UL) << 32U) + lo##UL)\n\n/* Used to cast away (remove) const qualifier. */\n#define constcast(type) (type)(void *)(size_t)(const void *)\n\n/* flag test */\n#define has_read_flag(_flag) false\n#define has_write_flag(_flag) unlikely(write_flag_eq(flg, YYJSON_WRITE_##_flag))\n\nstatic_inline bool read_flag_eq(yyjson_read_flag flg, yyjson_read_flag chk) {\n#if YYJSON_DISABLE_NON_STANDARD\n    if (chk == YYJSON_READ_ALLOW_INF_AND_NAN ||\n        chk == YYJSON_READ_ALLOW_COMMENTS ||\n        chk == YYJSON_READ_ALLOW_TRAILING_COMMAS ||\n        chk == YYJSON_READ_ALLOW_INVALID_UNICODE)\n        return false; /* this should be evaluated at compile-time */\n#endif\n    return (flg & chk) != 0;\n}\n\nstatic_inline bool write_flag_eq(yyjson_write_flag flg, yyjson_write_flag chk) {\n#if YYJSON_DISABLE_NON_STANDARD\n    if (chk == YYJSON_WRITE_ALLOW_INF_AND_NAN ||\n        chk == YYJSON_WRITE_ALLOW_INVALID_UNICODE)\n        return false; /* this should be evaluated at compile-time */\n#endif\n    return (flg & chk) != 0;\n}\n\n\n\n/*==============================================================================\n * Integer Constants\n *============================================================================*/\n\n/* U64 constant values */\n#undef  U64_MAX\n#define U64_MAX         U64(0xFFFFFFFF, 0xFFFFFFFF)\n#undef  I64_MAX\n#define I64_MAX         U64(0x7FFFFFFF, 0xFFFFFFFF)\n#undef  USIZE_MAX\n#define USIZE_MAX       ((usize)(~(usize)0))\n\n/* Maximum number of digits for reading u32/u64/usize safety (not overflow). */\n#undef  U32_SAFE_DIG\n#define U32_SAFE_DIG    9   /* u32 max is 4294967295, 10 digits */\n#undef  U64_SAFE_DIG\n#define U64_SAFE_DIG    19  /* u64 max is 18446744073709551615, 20 digits */\n#undef  USIZE_SAFE_DIG\n#define USIZE_SAFE_DIG  (sizeof(usize) == 8 ? U64_SAFE_DIG : U32_SAFE_DIG)\n\n\n\n/*==============================================================================\n * IEEE-754 Double Number Constants\n *============================================================================*/\n\n/* Inf raw value (positive) */\n#define F64_RAW_INF U64(0x7FF00000, 0x00000000)\n\n/* NaN raw value (quiet NaN, no payload, no sign) */\n#if defined(__hppa__) || (defined(__mips__) && !defined(__mips_nan2008))\n#define F64_RAW_NAN U64(0x7FF7FFFF, 0xFFFFFFFF)\n#else\n#define F64_RAW_NAN U64(0x7FF80000, 0x00000000)\n#endif\n\n/* double number bits */\n#define F64_BITS 64\n\n/* double number exponent part bits */\n#define F64_EXP_BITS 11\n\n/* double number significand part bits */\n#define F64_SIG_BITS 52\n\n/* double number significand part bits (with 1 hidden bit) */\n#define F64_SIG_FULL_BITS 53\n\n/* double number significand bit mask */\n#define F64_SIG_MASK U64(0x000FFFFF, 0xFFFFFFFF)\n\n/* double number exponent bit mask */\n#define F64_EXP_MASK U64(0x7FF00000, 0x00000000)\n\n/* double number exponent bias */\n#define F64_EXP_BIAS 1023\n\n/* double number significant digits count in decimal */\n#define F64_DEC_DIG 17\n\n/* max significant digits count in decimal when reading double number */\n#define F64_MAX_DEC_DIG 768\n\n/* maximum decimal power of double number (1.7976931348623157e308) */\n#define F64_MAX_DEC_EXP 308\n\n/* minimum decimal power of double number (4.9406564584124654e-324) */\n#define F64_MIN_DEC_EXP (-324)\n\n/* maximum binary power of double number */\n#define F64_MAX_BIN_EXP 1024\n\n/* minimum binary power of double number */\n#define F64_MIN_BIN_EXP (-1021)\n\n\n\n/*==============================================================================\n * Types\n *============================================================================*/\n\n/** Type define for primitive types. */\ntypedef float       f32;\ntypedef double      f64;\ntypedef int8_t      i8;\ntypedef uint8_t     u8;\ntypedef int16_t     i16;\ntypedef uint16_t    u16;\ntypedef int32_t     i32;\ntypedef uint32_t    u32;\ntypedef int64_t     i64;\ntypedef uint64_t    u64;\ntypedef size_t      usize;\n\n/** 128-bit integer, used by floating-point number reader and writer. */\n#if YYJSON_HAS_INT128\n__extension__ typedef __int128          i128;\n__extension__ typedef unsigned __int128 u128;\n#endif\n\n/** 16/32/64-bit vector */\ntypedef struct v16 { char c[2]; } v16;\ntypedef struct v32 { char c[4]; } v32;\ntypedef struct v64 { char c[8]; } v64;\n\n/** 16/32/64-bit vector union */\ntypedef union v16_uni { v16 v; u16 u; } v16_uni;\ntypedef union v32_uni { v32 v; u32 u; } v32_uni;\ntypedef union v64_uni { v64 v; u64 u; } v64_uni;\n\n\n\n/*==============================================================================\n * Load/Store Utils\n *============================================================================*/\n\n#if YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS\n\n#define byte_move_idx(x) ((char *)dst)[x] = ((const char *)src)[x];\n\nstatic_inline void byte_copy_2(void *dst, const void *src) {\n    repeat2_incr(byte_move_idx)\n}\n\nstatic_inline void byte_copy_4(void *dst, const void *src) {\n    repeat4_incr(byte_move_idx)\n}\n\nstatic_inline void byte_copy_8(void *dst, const void *src) {\n    repeat8_incr(byte_move_idx)\n}\n\nstatic_inline void byte_copy_16(void *dst, const void *src) {\n    repeat16_incr(byte_move_idx)\n}\n\nstatic_inline void byte_move_2(void *dst, const void *src) {\n    repeat2_incr(byte_move_idx)\n}\n\nstatic_inline void byte_move_4(void *dst, const void *src) {\n    repeat4_incr(byte_move_idx)\n}\n\nstatic_inline void byte_move_8(void *dst, const void *src) {\n    repeat8_incr(byte_move_idx)\n}\n\nstatic_inline void byte_move_16(void *dst, const void *src) {\n    repeat16_incr(byte_move_idx)\n}\n\nstatic_inline bool byte_match_2(void *buf, const char *pat) {\n    return\n    ((char *)buf)[0] == ((const char *)pat)[0] &&\n    ((char *)buf)[1] == ((const char *)pat)[1];\n}\n\nstatic_inline bool byte_match_4(void *buf, const char *pat) {\n    return\n    ((char *)buf)[0] == ((const char *)pat)[0] &&\n    ((char *)buf)[1] == ((const char *)pat)[1] &&\n    ((char *)buf)[2] == ((const char *)pat)[2] &&\n    ((char *)buf)[3] == ((const char *)pat)[3];\n}\n\nstatic_inline u16 byte_load_2(const void *src) {\n    v16_uni uni;\n    uni.v.c[0] = ((const char *)src)[0];\n    uni.v.c[1] = ((const char *)src)[1];\n    return uni.u;\n}\n\nstatic_inline u32 byte_load_3(const void *src) {\n    v32_uni uni;\n    uni.v.c[0] = ((const char *)src)[0];\n    uni.v.c[1] = ((const char *)src)[1];\n    uni.v.c[2] = ((const char *)src)[2];\n    uni.v.c[3] = 0;\n    return uni.u;\n}\n\nstatic_inline u32 byte_load_4(const void *src) {\n    v32_uni uni;\n    uni.v.c[0] = ((const char *)src)[0];\n    uni.v.c[1] = ((const char *)src)[1];\n    uni.v.c[2] = ((const char *)src)[2];\n    uni.v.c[3] = ((const char *)src)[3];\n    return uni.u;\n}\n\n#undef byte_move_expr\n\n#else\n\nstatic_inline void byte_copy_2(void *dst, const void *src) {\n    memcpy(dst, src, 2);\n}\n\nstatic_inline void byte_copy_4(void *dst, const void *src) {\n    memcpy(dst, src, 4);\n}\n\nstatic_inline void byte_copy_8(void *dst, const void *src) {\n    memcpy(dst, src, 8);\n}\n\nstatic_inline void byte_copy_16(void *dst, const void *src) {\n    memcpy(dst, src, 16);\n}\n\nstatic_inline void byte_move_2(void *dst, const void *src) {\n    u16 tmp;\n    memcpy(&tmp, src, 2);\n    memcpy(dst, &tmp, 2);\n}\n\nstatic_inline void byte_move_4(void *dst, const void *src) {\n    u32 tmp;\n    memcpy(&tmp, src, 4);\n    memcpy(dst, &tmp, 4);\n}\n\nstatic_inline void byte_move_8(void *dst, const void *src) {\n    u64 tmp;\n    memcpy(&tmp, src, 8);\n    memcpy(dst, &tmp, 8);\n}\n\nstatic_inline void byte_move_16(void *dst, const void *src) {\n    char *pdst = (char *)dst;\n    const char *psrc = (const char *)src;\n    u64 tmp1, tmp2;\n    memcpy(&tmp1, psrc, 8);\n    memcpy(&tmp2, psrc + 8, 8);\n    memcpy(pdst, &tmp1, 8);\n    memcpy(pdst + 8, &tmp2, 8);\n}\n\nstatic_inline bool byte_match_2(void *buf, const char *pat) {\n    v16_uni u1, u2;\n    memcpy(&u1, buf, 2);\n    memcpy(&u2, pat, 2);\n    return u1.u == u2.u;\n}\n\nstatic_inline bool byte_match_4(void *buf, const char *pat) {\n    v32_uni u1, u2;\n    memcpy(&u1, buf, 4);\n    memcpy(&u2, pat, 4);\n    return u1.u == u2.u;\n}\n\nstatic_inline u16 byte_load_2(const void *src) {\n    v16_uni uni;\n    memcpy(&uni, src, 2);\n    return uni.u;\n}\n\nstatic_inline u32 byte_load_3(const void *src) {\n    v32_uni uni;\n    memcpy(&uni, src, 2);\n    uni.v.c[2] = ((const char *)src)[2];\n    uni.v.c[3] = 0;\n    return uni.u;\n}\n\nstatic_inline u32 byte_load_4(const void *src) {\n    v32_uni uni;\n    memcpy(&uni, src, 4);\n    return uni.u;\n}\n\n#endif\n\n\n\n/*==============================================================================\n * Number Utils\n * These functions are used to detect and convert NaN and Inf numbers.\n *============================================================================*/\n\n/** Convert raw binary to double. */\nstatic_inline f64 f64_from_raw(u64 u) {\n    /* use memcpy to avoid violating the strict aliasing rule */\n    f64 f;\n    memcpy(&f, &u, 8);\n    return f;\n}\n\n/** Convert double to raw binary. */\nstatic_inline u64 f64_to_raw(f64 f) {\n    /* use memcpy to avoid violating the strict aliasing rule */\n    u64 u;\n    memcpy(&u, &f, 8);\n    return u;\n}\n\n/** Get raw 'infinity' with sign. */\nstatic_inline u64 f64_raw_get_inf(bool sign) {\n#if YYJSON_HAS_IEEE_754\n    return F64_RAW_INF | ((u64)sign << 63);\n#elif defined(INFINITY)\n    return f64_to_raw(sign ? -INFINITY : INFINITY);\n#else\n    return f64_to_raw(sign ? -HUGE_VAL : HUGE_VAL);\n#endif\n}\n\n/** Get raw 'nan' with sign. */\nstatic_inline u64 f64_raw_get_nan(bool sign) {\n#if YYJSON_HAS_IEEE_754\n    return F64_RAW_NAN | ((u64)sign << 63);\n#elif defined(NAN)\n    return f64_to_raw(sign ? (f64)-NAN : (f64)NAN);\n#else\n    return f64_to_raw((sign ? -0.0 : 0.0) / 0.0);\n#endif\n}\n\n/**\n Convert normalized u64 (highest bit is 1) to f64.\n \n Some compiler (such as Microsoft Visual C++ 6.0) do not support converting\n number from u64 to f64. This function will first convert u64 to i64 and then\n to f64, with `to nearest` rounding mode.\n */\nstatic_inline f64 normalized_u64_to_f64(u64 val) {\n#if YYJSON_U64_TO_F64_NO_IMPL\n    i64 sig = (i64)((val >> 1) | (val & 1));\n    return ((f64)sig) * (f64)2.0;\n#else\n    return (f64)val;\n#endif\n}\n\n\n\n/*==============================================================================\n * Size Utils\n * These functions are used for memory allocation.\n *============================================================================*/\n\n/** Returns whether the size is overflow after increment. */\nstatic_inline bool size_add_is_overflow(usize size, usize add) {\n    return size > (size + add);\n}\n\n/** Returns whether the size is power of 2 (size should not be 0). */\nstatic_inline bool size_is_pow2(usize size) {\n    return (size & (size - 1)) == 0;\n}\n\n/** Align size upwards (may overflow). */\nstatic_inline usize size_align_up(usize size, usize align) {\n    if (size_is_pow2(align)) {\n        return (size + (align - 1)) & ~(align - 1);\n    } else {\n        return size + align - (size + align - 1) % align - 1;\n    }\n}\n\n/** Align size downwards. */\nstatic_inline usize size_align_down(usize size, usize align) {\n    if (size_is_pow2(align)) {\n        return size & ~(align - 1);\n    } else {\n        return size - (size % align);\n    }\n}\n\n/** Align address upwards (may overflow). */\nstatic_inline void *mem_align_up(void *mem, usize align) {\n    usize size;\n    memcpy(&size, &mem, sizeof(usize));\n    size = size_align_up(size, align);\n    memcpy(&mem, &size, sizeof(usize));\n    return mem;\n}\n\n\n\n/*==============================================================================\n * Bits Utils\n * These functions are used by the floating-point number reader and writer.\n *============================================================================*/\n\n/** Returns the number of leading 0-bits in value (input should not be 0). */\nstatic_inline u32 u64_lz_bits(u64 v) {\n#if GCC_HAS_CLZLL\n    return (u32)__builtin_clzll(v);\n#elif MSC_HAS_BIT_SCAN_64\n    unsigned long r;\n    _BitScanReverse64(&r, v);\n    return (u32)63 - (u32)r;\n#elif MSC_HAS_BIT_SCAN\n    unsigned long hi, lo;\n    bool hi_set = _BitScanReverse(&hi, (u32)(v >> 32)) != 0;\n    _BitScanReverse(&lo, (u32)v);\n    hi |= 32;\n    return (u32)63 - (u32)(hi_set ? hi : lo);\n#else\n    /*\n     branchless, use de Bruijn sequences\n     see: https://www.chessprogramming.org/BitScan\n     */\n    const u8 table[64] = {\n        63, 16, 62,  7, 15, 36, 61,  3,  6, 14, 22, 26, 35, 47, 60,  2,\n         9,  5, 28, 11, 13, 21, 42, 19, 25, 31, 34, 40, 46, 52, 59,  1,\n        17,  8, 37,  4, 23, 27, 48, 10, 29, 12, 43, 20, 32, 41, 53, 18,\n        38, 24, 49, 30, 44, 33, 54, 39, 50, 45, 55, 51, 56, 57, 58,  0\n    };\n    v |= v >> 1;\n    v |= v >> 2;\n    v |= v >> 4;\n    v |= v >> 8;\n    v |= v >> 16;\n    v |= v >> 32;\n    return table[(v * U64(0x03F79D71, 0xB4CB0A89)) >> 58];\n#endif\n}\n\n/** Returns the number of trailing 0-bits in value (input should not be 0). */\nstatic_inline u32 u64_tz_bits(u64 v) {\n#if GCC_HAS_CTZLL\n    return (u32)__builtin_ctzll(v);\n#elif MSC_HAS_BIT_SCAN_64\n    unsigned long r;\n    _BitScanForward64(&r, v);\n    return (u32)r;\n#elif MSC_HAS_BIT_SCAN\n    unsigned long lo, hi;\n    bool lo_set = _BitScanForward(&lo, (u32)(v)) != 0;\n    _BitScanForward(&hi, (u32)(v >> 32));\n    hi += 32;\n    return lo_set ? lo : hi;\n#else\n    /*\n     branchless, use de Bruijn sequences\n     see: https://www.chessprogramming.org/BitScan\n     */\n    const u8 table[64] = {\n         0,  1,  2, 53,  3,  7, 54, 27,  4, 38, 41,  8, 34, 55, 48, 28,\n        62,  5, 39, 46, 44, 42, 22,  9, 24, 35, 59, 56, 49, 18, 29, 11,\n        63, 52,  6, 26, 37, 40, 33, 47, 61, 45, 43, 21, 23, 58, 17, 10,\n        51, 25, 36, 32, 60, 20, 57, 16, 50, 31, 19, 15, 30, 14, 13, 12\n    };\n    return table[((v & (~v + 1)) * U64(0x022FDD63, 0xCC95386D)) >> 58];\n#endif\n}\n\n\n\n/*==============================================================================\n * 128-bit Integer Utils\n * These functions are used by the floating-point number reader and writer.\n *============================================================================*/\n\n/** Multiplies two 64-bit unsigned integers (a * b),\n    returns the 128-bit result as 'hi' and 'lo'. */\nstatic_inline void u128_mul(u64 a, u64 b, u64 *hi, u64 *lo) {\n#if YYJSON_HAS_INT128\n    u128 m = (u128)a * b;\n    *hi = (u64)(m >> 64);\n    *lo = (u64)(m);\n#elif MSC_HAS_UMUL128\n    *lo = _umul128(a, b, hi);\n#else\n    u32 a0 = (u32)(a), a1 = (u32)(a >> 32);\n    u32 b0 = (u32)(b), b1 = (u32)(b >> 32);\n    u64 p00 = (u64)a0 * b0, p01 = (u64)a0 * b1;\n    u64 p10 = (u64)a1 * b0, p11 = (u64)a1 * b1;\n    u64 m0 = p01 + (p00 >> 32);\n    u32 m00 = (u32)(m0), m01 = (u32)(m0 >> 32);\n    u64 m1 = p10 + m00;\n    u32 m10 = (u32)(m1), m11 = (u32)(m1 >> 32);\n    *hi = p11 + m01 + m11;\n    *lo = ((u64)m10 << 32) | (u32)p00;\n#endif\n}\n\n/** Multiplies two 64-bit unsigned integers and add a value (a * b + c),\n    returns the 128-bit result as 'hi' and 'lo'. */\nstatic_inline void u128_mul_add(u64 a, u64 b, u64 c, u64 *hi, u64 *lo) {\n#if YYJSON_HAS_INT128\n    u128 m = (u128)a * b + c;\n    *hi = (u64)(m >> 64);\n    *lo = (u64)(m);\n#else\n    u64 h, l, t;\n    u128_mul(a, b, &h, &l);\n    t = l + c;\n    h += (u64)(((t < l) | (t < c)));\n    *hi = h;\n    *lo = t;\n#endif\n}\n\n\n\n/*==============================================================================\n * File Utils\n * These functions are used to read and write JSON files.\n *============================================================================*/\n\n#define YYJSON_FOPEN_EXT\n#if !defined(_MSC_VER) && defined(__GLIBC__) && defined(__GLIBC_PREREQ)\n#   if __GLIBC_PREREQ(2, 7)\n#       undef YYJSON_FOPEN_EXT\n#       define YYJSON_FOPEN_EXT \"e\" /* glibc extension to enable O_CLOEXEC */\n#   endif\n#endif\n\nstatic_inline FILE *fopen_safe(const char *path, const char *mode) {\n#if YYJSON_MSC_VER >= 1400\n    FILE *file = NULL;\n    if (fopen_s(&file, path, mode) != 0) return NULL;\n    return file;\n#else\n    return fopen(path, mode);\n#endif\n}\n\nstatic_inline FILE *fopen_readonly(const char *path) {\n    return fopen_safe(path, \"rb\" YYJSON_FOPEN_EXT);\n}\n\nstatic_inline FILE *fopen_writeonly(const char *path) {\n    return fopen_safe(path, \"wb\" YYJSON_FOPEN_EXT);\n}\n\nstatic_inline usize fread_safe(void *buf, usize size, FILE *file) {\n#if YYJSON_MSC_VER >= 1400\n    return fread_s(buf, size, 1, size, file);\n#else\n    return fread(buf, 1, size, file);\n#endif\n}\n\n\n\n/*==============================================================================\n * Default Memory Allocator\n * This is a simple libc memory allocator wrapper.\n *============================================================================*/\n\nstatic void *default_malloc(void *ctx, usize size) {\n    return malloc(size);\n}\n\nstatic void *default_realloc(void *ctx, void *ptr, usize old_size, usize size) {\n    return realloc(ptr, size);\n}\n\nstatic void default_free(void *ctx, void *ptr) {\n    free(ptr);\n}\n\nstatic const yyjson_alc YYJSON_DEFAULT_ALC = {\n    default_malloc,\n    default_realloc,\n    default_free,\n    NULL\n};\n\n\n\n/*==============================================================================\n * Null Memory Allocator\n *\n * This allocator is just a placeholder to ensure that the internal\n * malloc/realloc/free function pointers are not null.\n *============================================================================*/\n\nstatic void *null_malloc(void *ctx, usize size) {\n    return NULL;\n}\n\nstatic void *null_realloc(void *ctx, void *ptr, usize old_size, usize size) {\n    return NULL;\n}\n\nstatic void null_free(void *ctx, void *ptr) {\n    return;\n}\n\nstatic const yyjson_alc YYJSON_NULL_ALC = {\n    null_malloc,\n    null_realloc,\n    null_free,\n    NULL\n};\n\n\n\n/*==============================================================================\n * Pool Memory Allocator\n *\n * This allocator is initialized with a fixed-size buffer.\n * The buffer is split into multiple memory chunks for memory allocation.\n *============================================================================*/\n\n/** memory chunk header */\ntypedef struct pool_chunk {\n    usize size; /* chunk memory size, include chunk header */\n    struct pool_chunk *next; /* linked list, nullable */\n    /* char mem[]; flexible array member */\n} pool_chunk;\n\n/** allocator ctx header */\ntypedef struct pool_ctx {\n    usize size; /* total memory size, include ctx header */\n    pool_chunk *free_list; /* linked list, nullable */\n    /* pool_chunk chunks[]; flexible array member */\n} pool_ctx;\n\n/** align up the input size to chunk size */\nstatic_inline void pool_size_align(usize *size) {\n    *size = size_align_up(*size, sizeof(pool_chunk)) + sizeof(pool_chunk);\n}\n\nstatic void *pool_malloc(void *ctx_ptr, usize size) {\n    /* assert(size != 0) */\n    pool_ctx *ctx = (pool_ctx *)ctx_ptr;\n    pool_chunk *next, *prev = NULL, *cur = ctx->free_list;\n    \n    if (unlikely(size >= ctx->size)) return NULL;\n    pool_size_align(&size);\n    \n    while (cur) {\n        if (cur->size < size) {\n            /* not enough space, try next chunk */\n            prev = cur;\n            cur = cur->next;\n            continue;\n        }\n        if (cur->size >= size + sizeof(pool_chunk) * 2) {\n            /* too much space, split this chunk */\n            next = (pool_chunk *)(void *)((u8 *)cur + size);\n            next->size = cur->size - size;\n            next->next = cur->next;\n            cur->size = size;\n        } else {\n            /* just enough space, use whole chunk */\n            next = cur->next;\n        }\n        if (prev) prev->next = next;\n        else ctx->free_list = next;\n        return (void *)(cur + 1);\n    }\n    return NULL;\n}\n\nstatic void pool_free(void *ctx_ptr, void *ptr) {\n    /* assert(ptr != NULL) */\n    pool_ctx *ctx = (pool_ctx *)ctx_ptr;\n    pool_chunk *cur = ((pool_chunk *)ptr) - 1;\n    pool_chunk *prev = NULL, *next = ctx->free_list;\n    \n    while (next && next < cur) {\n        prev = next;\n        next = next->next;\n    }\n    if (prev) prev->next = cur;\n    else ctx->free_list = cur;\n    cur->next = next;\n    \n    if (next && ((u8 *)cur + cur->size) == (u8 *)next) {\n        /* merge cur to higher chunk */\n        cur->size += next->size;\n        cur->next = next->next;\n    }\n    if (prev && ((u8 *)prev + prev->size) == (u8 *)cur) {\n        /* merge cur to lower chunk */\n        prev->size += cur->size;\n        prev->next = cur->next;\n    }\n}\n\nstatic void *pool_realloc(void *ctx_ptr, void *ptr,\n                          usize old_size, usize size) {\n    /* assert(ptr != NULL && size != 0 && old_size < size) */\n    pool_ctx *ctx = (pool_ctx *)ctx_ptr;\n    pool_chunk *cur = ((pool_chunk *)ptr) - 1, *prev, *next, *tmp;\n    \n    /* check size */\n    if (unlikely(size >= ctx->size)) return NULL;\n    pool_size_align(&old_size);\n    pool_size_align(&size);\n    if (unlikely(old_size == size)) return ptr;\n    \n    /* find next and prev chunk */\n    prev = NULL;\n    next = ctx->free_list;\n    while (next && next < cur) {\n        prev = next;\n        next = next->next;\n    }\n    \n    if ((u8 *)cur + cur->size == (u8 *)next && cur->size + next->size >= size) {\n        /* merge to higher chunk if they are contiguous */\n        usize free_size = cur->size + next->size - size;\n        if (free_size > sizeof(pool_chunk) * 2) {\n            tmp = (pool_chunk *)(void *)((u8 *)cur + size);\n            if (prev) prev->next = tmp;\n            else ctx->free_list = tmp;\n            tmp->next = next->next;\n            tmp->size = free_size;\n            cur->size = size;\n        } else {\n            if (prev) prev->next = next->next;\n            else ctx->free_list = next->next;\n            cur->size += next->size;\n        }\n        return ptr;\n    } else {\n        /* fallback to malloc and memcpy */\n        void *new_ptr = pool_malloc(ctx_ptr, size - sizeof(pool_chunk));\n        if (new_ptr) {\n            memcpy(new_ptr, ptr, cur->size - sizeof(pool_chunk));\n            pool_free(ctx_ptr, ptr);\n        }\n        return new_ptr;\n    }\n}\n\nbool yyjson_alc_pool_init(yyjson_alc *alc, void *buf, usize size) {\n    pool_chunk *chunk;\n    pool_ctx *ctx;\n    \n    if (unlikely(!alc)) return false;\n    *alc = YYJSON_NULL_ALC;\n    if (size < sizeof(pool_ctx) * 4) return false;\n    ctx = (pool_ctx *)mem_align_up(buf, sizeof(pool_ctx));\n    if (unlikely(!ctx)) return false;\n    size -= (usize)((u8 *)ctx - (u8 *)buf);\n    size = size_align_down(size, sizeof(pool_ctx));\n    \n    chunk = (pool_chunk *)(ctx + 1);\n    chunk->size = size - sizeof(pool_ctx);\n    chunk->next = NULL;\n    ctx->size = size;\n    ctx->free_list = chunk;\n    \n    alc->malloc = pool_malloc;\n    alc->realloc = pool_realloc;\n    alc->free = pool_free;\n    alc->ctx = (void *)ctx;\n    return true;\n}\n\n\n\n/*==============================================================================\n * Dynamic Memory Allocator\n *\n * This allocator allocates memory on demand and does not immediately release\n * unused memory. Instead, it places the unused memory into a freelist for\n * potential reuse in the future. It is only when the entire allocator is\n * destroyed that all previously allocated memory is released at once.\n *============================================================================*/\n\n/** memory chunk header */\ntypedef struct dyn_chunk {\n    usize size; /* chunk size, include header */\n    struct dyn_chunk *next;\n    /* char mem[]; flexible array member */\n} dyn_chunk;\n\n/** allocator ctx header */\ntypedef struct {\n    dyn_chunk free_list; /* dummy header, sorted from small to large */\n    dyn_chunk used_list; /* dummy header */\n} dyn_ctx;\n\n/** align up the input size to chunk size */\nstatic_inline bool dyn_size_align(usize *size) {\n    usize alc_size = *size + sizeof(dyn_chunk);\n    alc_size = size_align_up(alc_size, YYJSON_ALC_DYN_MIN_SIZE);\n    if (unlikely(alc_size < *size)) return false; /* overflow */\n    *size = alc_size;\n    return true;\n}\n\n/** remove a chunk from list (the chunk must already be in the list) */\nstatic_inline void dyn_chunk_list_remove(dyn_chunk *list, dyn_chunk *chunk) {\n    dyn_chunk *prev = list, *cur;\n    for (cur = prev->next; cur; cur = cur->next) {\n        if (cur == chunk) {\n            prev->next = cur->next;\n            cur->next = NULL;\n            return;\n        }\n        prev = cur;\n    }\n}\n\n/** add a chunk to list header (the chunk must not be in the list) */\nstatic_inline void dyn_chunk_list_add(dyn_chunk *list, dyn_chunk *chunk) {\n    chunk->next = list->next;\n    list->next = chunk;\n}\n\nstatic void *dyn_malloc(void *ctx_ptr, usize size) {\n    /* assert(size != 0) */\n    const yyjson_alc def = YYJSON_DEFAULT_ALC;\n    dyn_ctx *ctx = (dyn_ctx *)ctx_ptr;\n    dyn_chunk *chunk, *prev, *next;\n    if (unlikely(!dyn_size_align(&size))) return NULL;\n    \n    /* freelist is empty, create new chunk */\n    if (!ctx->free_list.next) {\n        chunk = (dyn_chunk *)def.malloc(def.ctx, size);\n        if (unlikely(!chunk)) return NULL;\n        chunk->size = size;\n        chunk->next = NULL;\n        dyn_chunk_list_add(&ctx->used_list, chunk);\n        return (void *)(chunk + 1);\n    }\n    \n    /* find a large enough chunk, or resize the largest chunk */\n    prev = &ctx->free_list;\n    while (true) {\n        chunk = prev->next;\n        if (chunk->size >= size) { /* enough size, reuse this chunk */\n            prev->next = chunk->next;\n            dyn_chunk_list_add(&ctx->used_list, chunk);\n            return (void *)(chunk + 1);\n        }\n        if (!chunk->next) { /* resize the largest chunk */\n            chunk = (dyn_chunk *)def.realloc(def.ctx, chunk, chunk->size, size);\n            if (unlikely(!chunk)) return NULL;\n            prev->next = NULL;\n            chunk->size = size;\n            dyn_chunk_list_add(&ctx->used_list, chunk);\n            return (void *)(chunk + 1);\n        }\n        prev = chunk;\n    }\n}\n\nstatic void *dyn_realloc(void *ctx_ptr, void *ptr,\n                          usize old_size, usize size) {\n    /* assert(ptr != NULL && size != 0 && old_size < size) */\n    const yyjson_alc def = YYJSON_DEFAULT_ALC;\n    dyn_ctx *ctx = (dyn_ctx *)ctx_ptr;\n    dyn_chunk *prev, *next, *new_chunk;\n    dyn_chunk *chunk = (dyn_chunk *)ptr - 1;\n    if (unlikely(!dyn_size_align(&size))) return NULL;\n    if (chunk->size >= size) return ptr;\n    \n    dyn_chunk_list_remove(&ctx->used_list, chunk);\n    new_chunk = (dyn_chunk *)def.realloc(def.ctx, chunk, chunk->size, size);\n    if (likely(new_chunk)) {\n        new_chunk->size = size;\n        chunk = new_chunk;\n    }\n    dyn_chunk_list_add(&ctx->used_list, chunk);\n    return new_chunk ? (void *)(new_chunk + 1) : NULL;\n}\n\nstatic void dyn_free(void *ctx_ptr, void *ptr) {\n    /* assert(ptr != NULL) */\n    dyn_ctx *ctx = (dyn_ctx *)ctx_ptr;\n    dyn_chunk *chunk = (dyn_chunk *)ptr - 1, *prev;\n    \n    dyn_chunk_list_remove(&ctx->used_list, chunk);\n    for (prev = &ctx->free_list; prev; prev = prev->next) {\n        if (!prev->next || prev->next->size >= chunk->size) {\n            chunk->next = prev->next;\n            prev->next = chunk;\n            break;\n        }\n    }\n}\n\nyyjson_alc *yyjson_alc_dyn_new(void) {\n    const yyjson_alc def = YYJSON_DEFAULT_ALC;\n    usize hdr_len = sizeof(yyjson_alc) + sizeof(dyn_ctx);\n    yyjson_alc *alc = (yyjson_alc *)def.malloc(def.ctx, hdr_len);\n    dyn_ctx *ctx = (dyn_ctx *)(void *)(alc + 1);\n    if (unlikely(!alc)) return NULL;\n    alc->malloc = dyn_malloc;\n    alc->realloc = dyn_realloc;\n    alc->free = dyn_free;\n    alc->ctx = alc + 1;\n    memset(ctx, 0, sizeof(*ctx));\n    return alc;\n}\n\nvoid yyjson_alc_dyn_free(yyjson_alc *alc) {\n    const yyjson_alc def = YYJSON_DEFAULT_ALC;\n    dyn_ctx *ctx = (dyn_ctx *)(void *)(alc + 1);\n    dyn_chunk *chunk, *next;\n    if (unlikely(!alc)) return;\n    for (chunk = ctx->free_list.next; chunk; chunk = next) {\n        next = chunk->next;\n        def.free(def.ctx, chunk);\n    }\n    for (chunk = ctx->used_list.next; chunk; chunk = next) {\n        next = chunk->next;\n        def.free(def.ctx, chunk);\n    }\n    def.free(def.ctx, alc);\n}\n\n\n\n/*==============================================================================\n * JSON document and value\n *============================================================================*/\n\nstatic_inline void unsafe_yyjson_str_pool_release(yyjson_str_pool *pool,\n                                                  yyjson_alc *alc) {\n    yyjson_str_chunk *chunk = pool->chunks, *next;\n    while (chunk) {\n        next = chunk->next;\n        alc->free(alc->ctx, chunk);\n        chunk = next;\n    }\n}\n\nstatic_inline void unsafe_yyjson_val_pool_release(yyjson_val_pool *pool,\n                                                  yyjson_alc *alc) {\n    yyjson_val_chunk *chunk = pool->chunks, *next;\n    while (chunk) {\n        next = chunk->next;\n        alc->free(alc->ctx, chunk);\n        chunk = next;\n    }\n}\n\nbool unsafe_yyjson_str_pool_grow(yyjson_str_pool *pool,\n                                 const yyjson_alc *alc, usize len) {\n    yyjson_str_chunk *chunk;\n    usize size, max_len;\n    \n    /* create a new chunk */\n    max_len = USIZE_MAX - sizeof(yyjson_str_chunk);\n    if (unlikely(len > max_len)) return false;\n    size = len + sizeof(yyjson_str_chunk);\n    size = yyjson_max(pool->chunk_size, size);\n    chunk = (yyjson_str_chunk *)alc->malloc(alc->ctx, size);\n    if (unlikely(!chunk)) return false;\n    \n    /* insert the new chunk as the head of the linked list */\n    chunk->next = pool->chunks;\n    chunk->chunk_size = size;\n    pool->chunks = chunk;\n    pool->cur = (char *)chunk + sizeof(yyjson_str_chunk);\n    pool->end = (char *)chunk + size;\n    \n    /* the next chunk is twice the size of the current one */\n    size = yyjson_min(pool->chunk_size * 2, pool->chunk_size_max);\n    if (size < pool->chunk_size) size = pool->chunk_size_max; /* overflow */\n    pool->chunk_size = size;\n    return true;\n}\n\nbool unsafe_yyjson_val_pool_grow(yyjson_val_pool *pool,\n                                 const yyjson_alc *alc, usize count) {\n    yyjson_val_chunk *chunk;\n    usize size, max_count;\n    \n    /* create a new chunk */\n    max_count = USIZE_MAX / sizeof(yyjson_mut_val) - 1;\n    if (unlikely(count > max_count)) return false;\n    size = (count + 1) * sizeof(yyjson_mut_val);\n    size = yyjson_max(pool->chunk_size, size);\n    chunk = (yyjson_val_chunk *)alc->malloc(alc->ctx, size);\n    if (unlikely(!chunk)) return false;\n    \n    /* insert the new chunk as the head of the linked list */\n    chunk->next = pool->chunks;\n    chunk->chunk_size = size;\n    pool->chunks = chunk;\n    pool->cur = (yyjson_mut_val *)(void *)((u8 *)chunk) + 1;\n    pool->end = (yyjson_mut_val *)(void *)((u8 *)chunk + size);\n    \n    /* the next chunk is twice the size of the current one */\n    size = yyjson_min(pool->chunk_size * 2, pool->chunk_size_max);\n    if (size < pool->chunk_size) size = pool->chunk_size_max; /* overflow */\n    pool->chunk_size = size;\n    return true;\n}\n\nbool yyjson_mut_doc_set_str_pool_size(yyjson_mut_doc *doc, size_t len) {\n    usize max_size = USIZE_MAX - sizeof(yyjson_str_chunk);\n    if (!doc || !len || len > max_size) return false;\n    doc->str_pool.chunk_size = len + sizeof(yyjson_str_chunk);\n    return true;\n}\n\nbool yyjson_mut_doc_set_val_pool_size(yyjson_mut_doc *doc, size_t count) {\n    usize max_count = USIZE_MAX / sizeof(yyjson_mut_val) - 1;\n    if (!doc || !count || count > max_count) return false;\n    doc->val_pool.chunk_size = (count + 1) * sizeof(yyjson_mut_val);\n    return true;\n}\n\nvoid yyjson_mut_doc_free(yyjson_mut_doc *doc) {\n    if (doc) {\n        yyjson_alc alc = doc->alc;\n        memset(&doc->alc, 0, sizeof(alc));\n        unsafe_yyjson_str_pool_release(&doc->str_pool, &alc);\n        unsafe_yyjson_val_pool_release(&doc->val_pool, &alc);\n        alc.free(alc.ctx, doc);\n    }\n}\n\nyyjson_mut_doc *yyjson_mut_doc_new(const yyjson_alc *alc) {\n    yyjson_mut_doc *doc;\n    if (!alc) alc = &YYJSON_DEFAULT_ALC;\n    doc = (yyjson_mut_doc *)alc->malloc(alc->ctx, sizeof(yyjson_mut_doc));\n    if (!doc) return NULL;\n    memset(doc, 0, sizeof(yyjson_mut_doc));\n    \n    doc->alc = *alc;\n    doc->str_pool.chunk_size = YYJSON_MUT_DOC_STR_POOL_INIT_SIZE;\n    doc->str_pool.chunk_size_max = YYJSON_MUT_DOC_STR_POOL_MAX_SIZE;\n    doc->val_pool.chunk_size = YYJSON_MUT_DOC_VAL_POOL_INIT_SIZE;\n    doc->val_pool.chunk_size_max = YYJSON_MUT_DOC_VAL_POOL_MAX_SIZE;\n    return doc;\n}\n\nyyjson_mut_doc *yyjson_doc_mut_copy(yyjson_doc *doc, const yyjson_alc *alc) {\n    yyjson_mut_doc *m_doc;\n    yyjson_mut_val *m_val;\n    \n    if (!doc || !doc->root) return NULL;\n    m_doc = yyjson_mut_doc_new(alc);\n    if (!m_doc) return NULL;\n    m_val = yyjson_val_mut_copy(m_doc, doc->root);\n    if (!m_val) {\n        yyjson_mut_doc_free(m_doc);\n        return NULL;\n    }\n    yyjson_mut_doc_set_root(m_doc, m_val);\n    return m_doc;\n}\n\nyyjson_mut_doc *yyjson_mut_doc_mut_copy(yyjson_mut_doc *doc,\n                                        const yyjson_alc *alc) {\n    yyjson_mut_doc *m_doc;\n    yyjson_mut_val *m_val;\n    \n    if (!doc) return NULL;\n    if (!doc->root) return yyjson_mut_doc_new(alc);\n    \n    m_doc = yyjson_mut_doc_new(alc);\n    if (!m_doc) return NULL;\n    m_val = yyjson_mut_val_mut_copy(m_doc, doc->root);\n    if (!m_val) {\n        yyjson_mut_doc_free(m_doc);\n        return NULL;\n    }\n    yyjson_mut_doc_set_root(m_doc, m_val);\n    return m_doc;\n}\n\nyyjson_mut_val *yyjson_val_mut_copy(yyjson_mut_doc *m_doc,\n                                    yyjson_val *i_vals) {\n    /*\n     The immutable object or array stores all sub-values in a contiguous memory,\n     We copy them to another contiguous memory as mutable values,\n     then reconnect the mutable values with the original relationship.\n     */\n    usize i_vals_len;\n    yyjson_mut_val *m_vals, *m_val;\n    yyjson_val *i_val, *i_end;\n    \n    if (!m_doc || !i_vals) return NULL;\n    i_end = unsafe_yyjson_get_next(i_vals);\n    i_vals_len = (usize)(unsafe_yyjson_get_next(i_vals) - i_vals);\n    m_vals = unsafe_yyjson_mut_val(m_doc, i_vals_len);\n    if (!m_vals) return NULL;\n    i_val = i_vals;\n    m_val = m_vals;\n    \n    for (; i_val < i_end; i_val++, m_val++) {\n        yyjson_type type = unsafe_yyjson_get_type(i_val);\n        m_val->tag = i_val->tag;\n        m_val->uni.u64 = i_val->uni.u64;\n        if (type == YYJSON_TYPE_STR || type == YYJSON_TYPE_RAW) {\n            const char *str = i_val->uni.str;\n            usize str_len = unsafe_yyjson_get_len(i_val);\n            m_val->uni.str = unsafe_yyjson_mut_strncpy(m_doc, str, str_len);\n            if (!m_val->uni.str) return NULL;\n        } else if (type == YYJSON_TYPE_ARR) {\n            usize len = unsafe_yyjson_get_len(i_val);\n            if (len > 0) {\n                yyjson_val *ii_val = i_val + 1, *ii_next;\n                yyjson_mut_val *mm_val = m_val + 1, *mm_ctn = m_val, *mm_next;\n                while (len-- > 1) {\n                    ii_next = unsafe_yyjson_get_next(ii_val);\n                    mm_next = mm_val + (ii_next - ii_val);\n                    mm_val->next = mm_next;\n                    ii_val = ii_next;\n                    mm_val = mm_next;\n                }\n                mm_val->next = mm_ctn + 1;\n                mm_ctn->uni.ptr = mm_val;\n            }\n        } else if (type == YYJSON_TYPE_OBJ) {\n            usize len = unsafe_yyjson_get_len(i_val);\n            if (len > 0) {\n                yyjson_val *ii_key = i_val + 1, *ii_nextkey;\n                yyjson_mut_val *mm_key = m_val + 1, *mm_ctn = m_val;\n                yyjson_mut_val *mm_nextkey;\n                while (len-- > 1) {\n                    ii_nextkey = unsafe_yyjson_get_next(ii_key + 1);\n                    mm_nextkey = mm_key + (ii_nextkey - ii_key);\n                    mm_key->next = mm_key + 1;\n                    mm_key->next->next = mm_nextkey;\n                    ii_key = ii_nextkey;\n                    mm_key = mm_nextkey;\n                }\n                mm_key->next = mm_key + 1;\n                mm_key->next->next = mm_ctn + 1;\n                mm_ctn->uni.ptr = mm_key;\n            }\n        }\n    }\n    \n    return m_vals;\n}\n\nstatic yyjson_mut_val *unsafe_yyjson_mut_val_mut_copy(yyjson_mut_doc *m_doc,\n                                                      yyjson_mut_val *m_vals) {\n    /*\n     The mutable object or array stores all sub-values in a circular linked\n     list, so we can traverse them in the same loop. The traversal starts from\n     the last item, continues with the first item in a list, and ends with the\n     second to last item, which needs to be linked to the last item to close the\n     circle.\n     */\n    yyjson_mut_val *m_val = unsafe_yyjson_mut_val(m_doc, 1);\n    if (unlikely(!m_val)) return NULL;\n    m_val->tag = m_vals->tag;\n    \n    switch (unsafe_yyjson_get_type(m_vals)) {\n        case YYJSON_TYPE_OBJ:\n        case YYJSON_TYPE_ARR:\n            if (unsafe_yyjson_get_len(m_vals) > 0) {\n                yyjson_mut_val *last = (yyjson_mut_val *)m_vals->uni.ptr;\n                yyjson_mut_val *next = last->next, *prev;\n                prev = unsafe_yyjson_mut_val_mut_copy(m_doc, last);\n                if (!prev) return NULL;\n                m_val->uni.ptr = (void *)prev;\n                while (next != last) {\n                    prev->next = unsafe_yyjson_mut_val_mut_copy(m_doc, next);\n                    if (!prev->next) return NULL;\n                    prev = prev->next;\n                    next = next->next;\n                }\n                prev->next = (yyjson_mut_val *)m_val->uni.ptr;\n            }\n            break;\n        \n        case YYJSON_TYPE_RAW:\n        case YYJSON_TYPE_STR: {\n            const char *str = m_vals->uni.str;\n            usize str_len = unsafe_yyjson_get_len(m_vals);\n            m_val->uni.str = unsafe_yyjson_mut_strncpy(m_doc, str, str_len);\n            if (!m_val->uni.str) return NULL;\n            break;\n        }\n        \n        default:\n            m_val->uni = m_vals->uni;\n            break;\n    }\n    \n    return m_val;\n}\n\nyyjson_mut_val *yyjson_mut_val_mut_copy(yyjson_mut_doc *doc,\n                                        yyjson_mut_val *val) {\n    if (doc && val) return unsafe_yyjson_mut_val_mut_copy(doc, val);\n    return NULL;\n}\n\n/* Count the number of values and the total length of the strings. */\nstatic void yyjson_mut_stat(yyjson_mut_val *val,\n                            usize *val_sum, usize *str_sum) {\n    yyjson_type type = unsafe_yyjson_get_type(val);\n    *val_sum += 1;\n    if (type == YYJSON_TYPE_ARR || type == YYJSON_TYPE_OBJ) {\n        yyjson_mut_val *child = (yyjson_mut_val *)val->uni.ptr;\n        usize len = unsafe_yyjson_get_len(val), i;\n        len <<= (u8)(type == YYJSON_TYPE_OBJ);\n        *val_sum += len;\n        for (i = 0; i < len; i++) {\n            yyjson_type stype = unsafe_yyjson_get_type(child);\n            if (stype == YYJSON_TYPE_STR || stype == YYJSON_TYPE_RAW) {\n                *str_sum += unsafe_yyjson_get_len(child) + 1;\n            } else if (stype == YYJSON_TYPE_ARR || stype == YYJSON_TYPE_OBJ) {\n                yyjson_mut_stat(child, val_sum, str_sum);\n                *val_sum -= 1;\n            }\n            child = child->next;\n        }\n    } else if (type == YYJSON_TYPE_STR || type == YYJSON_TYPE_RAW) {\n        *str_sum += unsafe_yyjson_get_len(val) + 1;\n    }\n}\n\n/* Copy mutable values to immutable value pool. */\nstatic usize yyjson_imut_copy(yyjson_val **val_ptr, char **buf_ptr,\n                              yyjson_mut_val *mval) {\n    yyjson_val *val = *val_ptr;\n    yyjson_type type = unsafe_yyjson_get_type(mval);\n    if (type == YYJSON_TYPE_ARR || type == YYJSON_TYPE_OBJ) {\n        yyjson_mut_val *child = (yyjson_mut_val *)mval->uni.ptr;\n        usize len = unsafe_yyjson_get_len(mval), i;\n        usize val_sum = 1;\n        if (type == YYJSON_TYPE_OBJ) {\n            if (len) child = child->next->next;\n            len <<= 1;\n        } else {\n            if (len) child = child->next;\n        }\n        *val_ptr = val + 1;\n        for (i = 0; i < len; i++) {\n            val_sum += yyjson_imut_copy(val_ptr, buf_ptr, child);\n            child = child->next;\n        }\n        val->tag = mval->tag;\n        val->uni.ofs = val_sum * sizeof(yyjson_val);\n        return val_sum;\n    } else if (type == YYJSON_TYPE_STR || type == YYJSON_TYPE_RAW) {\n        char *buf = *buf_ptr;\n        usize len = unsafe_yyjson_get_len(mval);\n        memcpy((void *)buf, (const void *)mval->uni.str, len);\n        buf[len] = '\\0';\n        val->tag = mval->tag;\n        val->uni.str = buf;\n        *val_ptr = val + 1;\n        *buf_ptr = buf + len + 1;\n        return 1;\n    } else {\n        val->tag = mval->tag;\n        val->uni = mval->uni;\n        *val_ptr = val + 1;\n        return 1;\n    }\n}\n\nyyjson_doc *yyjson_mut_doc_imut_copy(yyjson_mut_doc *mdoc,\n                                     const yyjson_alc *alc) {\n    if (!mdoc) return NULL;\n    return yyjson_mut_val_imut_copy(mdoc->root, alc);\n}\n\nyyjson_doc *yyjson_mut_val_imut_copy(yyjson_mut_val *mval,\n                                     const yyjson_alc *alc) {\n    usize val_num = 0, str_sum = 0, hdr_size, buf_size;\n    yyjson_doc *doc = NULL;\n    yyjson_val *val_hdr = NULL;\n    \n    /* This value should be NULL here. Setting a non-null value suppresses\n       warning from the clang analyzer. */\n    char *str_hdr = (char *)(void *)&str_sum;\n    if (!mval) return NULL;\n    if (!alc) alc = &YYJSON_DEFAULT_ALC;\n    \n    /* traverse the input value to get pool size */\n    yyjson_mut_stat(mval, &val_num, &str_sum);\n    \n    /* create doc and val pool */\n    hdr_size = size_align_up(sizeof(yyjson_doc), sizeof(yyjson_val));\n    buf_size = hdr_size + val_num * sizeof(yyjson_val);\n    doc = (yyjson_doc *)alc->malloc(alc->ctx, buf_size);\n    if (!doc) return NULL;\n    memset(doc, 0, sizeof(yyjson_doc));\n    val_hdr = (yyjson_val *)(void *)((char *)(void *)doc + hdr_size);\n    doc->root = val_hdr;\n    doc->alc = *alc;\n    \n    /* create str pool */\n    if (str_sum > 0) {\n        str_hdr = (char *)alc->malloc(alc->ctx, str_sum);\n        doc->str_pool = str_hdr;\n        if (!str_hdr) {\n            alc->free(alc->ctx, (void *)doc);\n            return NULL;\n        }\n    }\n    \n    /* copy vals and strs */\n    doc->val_read = yyjson_imut_copy(&val_hdr, &str_hdr, mval);\n    doc->dat_read = str_sum + 1;\n    return doc;\n}\n\nstatic_inline bool unsafe_yyjson_num_equals(void *lhs, void *rhs) {\n    yyjson_val_uni *luni = &((yyjson_val *)lhs)->uni;\n    yyjson_val_uni *runi = &((yyjson_val *)rhs)->uni;\n    yyjson_subtype lt = unsafe_yyjson_get_subtype(lhs);\n    yyjson_subtype rt = unsafe_yyjson_get_subtype(rhs);\n    if (lt == rt) return luni->u64 == runi->u64;\n    if (lt == YYJSON_SUBTYPE_SINT && rt == YYJSON_SUBTYPE_UINT) {\n        return luni->i64 >= 0 && luni->u64 == runi->u64;\n    }\n    if (lt == YYJSON_SUBTYPE_UINT && rt == YYJSON_SUBTYPE_SINT) {\n        return runi->i64 >= 0 && luni->u64 == runi->u64;\n    }\n    return false;\n}\n\nstatic_inline bool unsafe_yyjson_str_equals(void *lhs, void *rhs) {\n    usize len = unsafe_yyjson_get_len(lhs);\n    if (len != unsafe_yyjson_get_len(rhs)) return false;\n    return !memcmp(unsafe_yyjson_get_str(lhs),\n                   unsafe_yyjson_get_str(rhs), len);\n}\n\nbool unsafe_yyjson_equals(yyjson_val *lhs, yyjson_val *rhs) {\n    yyjson_type type = unsafe_yyjson_get_type(lhs);\n    if (type != unsafe_yyjson_get_type(rhs)) return false;\n    \n    switch (type) {\n        case YYJSON_TYPE_OBJ: {\n            usize len = unsafe_yyjson_get_len(lhs);\n            if (len != unsafe_yyjson_get_len(rhs)) return false;\n            if (len > 0) {\n                yyjson_obj_iter iter;\n                yyjson_obj_iter_init(rhs, &iter);\n                lhs = unsafe_yyjson_get_first(lhs);\n                while (len-- > 0) {\n                    rhs = yyjson_obj_iter_getn(&iter, lhs->uni.str,\n                                               unsafe_yyjson_get_len(lhs));\n                    if (!rhs) return false;\n                    if (!unsafe_yyjson_equals(lhs + 1, rhs)) return false;\n                    lhs = unsafe_yyjson_get_next(lhs + 1);\n                }\n            }\n            /* yyjson allows duplicate keys, so the check may be inaccurate */\n            return true;\n        }\n        \n        case YYJSON_TYPE_ARR: {\n            usize len = unsafe_yyjson_get_len(lhs);\n            if (len != unsafe_yyjson_get_len(rhs)) return false;\n            if (len > 0) {\n                lhs = unsafe_yyjson_get_first(lhs);\n                rhs = unsafe_yyjson_get_first(rhs);\n                while (len-- > 0) {\n                    if (!unsafe_yyjson_equals(lhs, rhs)) return false;\n                    lhs = unsafe_yyjson_get_next(lhs);\n                    rhs = unsafe_yyjson_get_next(rhs);\n                }\n            }\n            return true;\n        }\n        \n        case YYJSON_TYPE_NUM:\n            return unsafe_yyjson_num_equals(lhs, rhs);\n        \n        case YYJSON_TYPE_RAW:\n        case YYJSON_TYPE_STR:\n            return unsafe_yyjson_str_equals(lhs, rhs);\n        \n        case YYJSON_TYPE_NULL:\n        case YYJSON_TYPE_BOOL:\n            return lhs->tag == rhs->tag;\n        \n        default:\n            return false;\n    }\n}\n\nbool unsafe_yyjson_mut_equals(yyjson_mut_val *lhs, yyjson_mut_val *rhs) {\n    yyjson_type type = unsafe_yyjson_get_type(lhs);\n    if (type != unsafe_yyjson_get_type(rhs)) return false;\n    \n    switch (type) {\n        case YYJSON_TYPE_OBJ: {\n            usize len = unsafe_yyjson_get_len(lhs);\n            if (len != unsafe_yyjson_get_len(rhs)) return false;\n            if (len > 0) {\n                yyjson_mut_obj_iter iter;\n                yyjson_mut_obj_iter_init(rhs, &iter);\n                lhs = (yyjson_mut_val *)lhs->uni.ptr;\n                while (len-- > 0) {\n                    rhs = yyjson_mut_obj_iter_getn(&iter, lhs->uni.str,\n                                                   unsafe_yyjson_get_len(lhs));\n                    if (!rhs) return false;\n                    if (!unsafe_yyjson_mut_equals(lhs->next, rhs)) return false;\n                    lhs = lhs->next->next;\n                }\n            }\n            /* yyjson allows duplicate keys, so the check may be inaccurate */\n            return true;\n        }\n        \n        case YYJSON_TYPE_ARR: {\n            usize len = unsafe_yyjson_get_len(lhs);\n            if (len != unsafe_yyjson_get_len(rhs)) return false;\n            if (len > 0) {\n                lhs = (yyjson_mut_val *)lhs->uni.ptr;\n                rhs = (yyjson_mut_val *)rhs->uni.ptr;\n                while (len-- > 0) {\n                    if (!unsafe_yyjson_mut_equals(lhs, rhs)) return false;\n                    lhs = lhs->next;\n                    rhs = rhs->next;\n                }\n            }\n            return true;\n        }\n        \n        case YYJSON_TYPE_NUM:\n            return unsafe_yyjson_num_equals(lhs, rhs);\n        \n        case YYJSON_TYPE_RAW:\n        case YYJSON_TYPE_STR:\n            return unsafe_yyjson_str_equals(lhs, rhs);\n        \n        case YYJSON_TYPE_NULL:\n        case YYJSON_TYPE_BOOL:\n            return lhs->tag == rhs->tag;\n        \n        default:\n            return false;\n    }\n}\n\n\n\n#if !YYJSON_DISABLE_UTILS\n\n/*==============================================================================\n * JSON Pointer API (RFC 6901)\n *============================================================================*/\n\n/**\n Get a token from JSON pointer string.\n @param ptr [in,out]\n                in:  string that points to current token prefix `/`\n                out: string that points to next token prefix `/`, or string end\n @param end [in] end of the entire JSON Pointer string\n @param len [out] unescaped token length\n @param esc [out] number of escaped characters in this token\n @return head of the token, or NULL if syntax error\n */\nstatic_inline const char *ptr_next_token(const char **ptr, const char *end,\n                                         usize *len, usize *esc) {\n    const char *hdr = *ptr + 1;\n    const char *cur = hdr;\n    /* skip unescaped characters */\n    while (cur < end && *cur != '/' && *cur != '~') cur++;\n    if (likely(cur == end || *cur != '~')) {\n        /* no escaped characters, return */\n        *ptr = cur;\n        *len = (usize)(cur - hdr);\n        *esc = 0;\n        return hdr;\n    } else {\n        /* handle escaped characters */\n        usize esc_num = 0;\n        while (cur < end && *cur != '/') {\n            if (*cur++ == '~') {\n                if (cur == end || (*cur != '0' && *cur != '1')) {\n                    *ptr = cur - 1;\n                    return NULL;\n                }\n                esc_num++;\n            }\n        }\n        *ptr = cur;\n        *len = (usize)(cur - hdr) - esc_num;\n        *esc = esc_num;\n        return hdr;\n    }\n}\n\n/**\n Convert token string to index.\n @param cur [in]  token head\n @param len [in]  token length\n @param idx [out] the index number, or USIZE_MAX if token is '-'\n @return true if token is a valid array index\n */\nstatic_inline bool ptr_token_to_idx(const char *cur, usize len, usize *idx) {\n    const char *end = cur + len;\n    usize num = 0, add;\n    if (unlikely(len == 0 || len > USIZE_SAFE_DIG)) return false;\n    if (*cur == '0') {\n        if (unlikely(len > 1)) return false;\n        *idx = 0;\n        return true;\n    }\n    if (*cur == '-') {\n        if (unlikely(len > 1)) return false;\n        *idx = USIZE_MAX;\n        return true;\n    }\n    for (; cur < end && (add = (usize)((u8)*cur - (u8)'0')) <= 9; cur++) {\n        num = num * 10 + add;\n    }\n    if (unlikely(num == 0 || cur < end)) return false;\n    *idx = num;\n    return true;\n}\n\n/**\n Compare JSON key with token.\n @param key a string key (yyjson_val or yyjson_mut_val)\n @param token a JSON pointer token\n @param len unescaped token length\n @param esc number of escaped characters in this token\n @return true if `str` is equals to `token`\n */\nstatic_inline bool ptr_token_eq(void *key,\n                                const char *token, usize len, usize esc) {\n    yyjson_val *val = (yyjson_val *)key;\n    if (unsafe_yyjson_get_len(val) != len) return false;\n    if (likely(!esc)) {\n        return memcmp(val->uni.str, token, len) == 0;\n    } else {\n        const char *str = val->uni.str;\n        for (; len-- > 0; token++, str++) {\n            if (*token == '~') {\n                if (*str != (*++token == '0' ? '~' : '/')) return false;\n            } else {\n                if (*str != *token) return false;\n            }\n        }\n        return true;\n    }\n}\n\n/**\n Get a value from array by token.\n @param arr   an array, should not be NULL or non-array type\n @param token a JSON pointer token\n @param len   unescaped token length\n @param esc   number of escaped characters in this token\n @return value at index, or NULL if token is not index or index is out of range\n */\nstatic_inline yyjson_val *ptr_arr_get(yyjson_val *arr, const char *token,\n                                      usize len, usize esc) {\n    yyjson_val *val = unsafe_yyjson_get_first(arr);\n    usize num = unsafe_yyjson_get_len(arr), idx = 0;\n    if (unlikely(num == 0)) return NULL;\n    if (unlikely(!ptr_token_to_idx(token, len, &idx))) return NULL;\n    if (unlikely(idx >= num)) return NULL;\n    if (unsafe_yyjson_arr_is_flat(arr)) {\n        return val + idx;\n    } else {\n        while (idx-- > 0) val = unsafe_yyjson_get_next(val);\n        return val;\n    }\n}\n\n/**\n Get a value from object by token.\n @param obj   [in] an object, should not be NULL or non-object type\n @param token [in] a JSON pointer token\n @param len   [in] unescaped token length\n @param esc   [in] number of escaped characters in this token\n @return value associated with the token, or NULL if no value\n */\nstatic_inline yyjson_val *ptr_obj_get(yyjson_val *obj, const char *token,\n                                      usize len, usize esc) {\n    yyjson_val *key = unsafe_yyjson_get_first(obj);\n    usize num = unsafe_yyjson_get_len(obj);\n    if (unlikely(num == 0)) return NULL;\n    for (; num > 0; num--, key = unsafe_yyjson_get_next(key + 1)) {\n        if (ptr_token_eq(key, token, len, esc)) return key + 1;\n    }\n    return NULL;\n}\n\n/**\n Get a value from array by token.\n @param arr   [in] an array, should not be NULL or non-array type\n @param token [in] a JSON pointer token\n @param len   [in] unescaped token length\n @param esc   [in] number of escaped characters in this token\n @param pre   [out] previous (sibling) value of the returned value\n @param last  [out] whether index is last\n @return value at index, or NULL if token is not index or index is out of range\n */\nstatic_inline yyjson_mut_val *ptr_mut_arr_get(yyjson_mut_val *arr,\n                                              const char *token,\n                                              usize len, usize esc,\n                                              yyjson_mut_val **pre,\n                                              bool *last) {\n    yyjson_mut_val *val = (yyjson_mut_val *)arr->uni.ptr; /* last (tail) */\n    usize num = unsafe_yyjson_get_len(arr), idx;\n    if (last) *last = false;\n    if (false) *pre = NULL;\n    if (unlikely(num == 0)) {\n        if (last && len == 1 && (*token == '0' || *token == '-')) *last = true;\n        return NULL;\n    }\n    if (unlikely(!ptr_token_to_idx(token, len, &idx))) return NULL;\n    if (last) *last = (idx == num || idx == USIZE_MAX);\n    if (unlikely(idx >= num)) return NULL;\n    while (idx-- > 0) val = val->next;\n    *pre = val;\n    return val->next;\n}\n\n/**\n Get a value from object by token.\n @param obj   [in] an object, should not be NULL or non-object type\n @param token [in] a JSON pointer token\n @param len   [in] unescaped token length\n @param esc   [in] number of escaped characters in this token\n @param pre   [out] previous (sibling) key of the returned value's key\n @return value associated with the token, or NULL if no value\n */\nstatic_inline yyjson_mut_val *ptr_mut_obj_get(yyjson_mut_val *obj,\n                                              const char *token,\n                                              usize len, usize esc,\n                                              yyjson_mut_val **pre) {\n    yyjson_mut_val *pre_key = (yyjson_mut_val *)obj->uni.ptr, *key;\n    usize num = unsafe_yyjson_get_len(obj);\n    if (false) *pre = NULL;\n    if (unlikely(num == 0)) return NULL;\n    for (; num > 0; num--, pre_key = key) {\n        key = pre_key->next->next;\n        if (ptr_token_eq(key, token, len, esc)) {\n            *pre = pre_key;\n            return key->next;\n        }\n    }\n    return NULL;\n}\n\n/**\n Create a string value with JSON pointer token.\n @param token [in] a JSON pointer token\n @param len   [in] unescaped token length\n @param esc   [in] number of escaped characters in this token\n @param doc   [in] used for memory allocation when creating value\n @return new string value, or NULL if memory allocation failed\n */\nstatic_inline yyjson_mut_val *ptr_new_key(const char *token,\n                                          usize len, usize esc,\n                                          yyjson_mut_doc *doc) {\n    const char *src = token;\n    if (likely(!esc)) {\n        return yyjson_mut_strncpy(doc, src, len);\n    } else {\n        const char *end = src + len + esc;\n        char *dst = unsafe_yyjson_mut_str_alc(doc, len + esc);\n        char *str = dst;\n        if (unlikely(!dst)) return NULL;\n        for (; src < end; src++, dst++) {\n            if (*src != '~') *dst = *src;\n            else *dst = (*++src == '0' ? '~' : '/');\n        }\n        *dst = '\\0';\n        return yyjson_mut_strn(doc, str, len);\n    }\n}\n\n/* macros for yyjson_ptr */\n#define return_err(_ret, _code, _pos, _msg) do { \\\n    if (err) { \\\n        err->code = YYJSON_PTR_ERR_##_code; \\\n        err->msg = _msg; \\\n        err->pos = (usize)(_pos); \\\n    } \\\n    return _ret; \\\n} while (false)\n\n#define return_err_resolve(_ret, _pos) \\\n    return_err(_ret, RESOLVE, _pos, \"JSON pointer cannot be resolved\")\n#define return_err_syntax(_ret, _pos) \\\n    return_err(_ret, SYNTAX, _pos, \"invalid escaped character\")\n#define return_err_alloc(_ret) \\\n    return_err(_ret, MEMORY_ALLOCATION, 0, \"failed to create value\")\n\nyyjson_val *unsafe_yyjson_ptr_getx(yyjson_val *val,\n                                   const char *ptr, size_t ptr_len,\n                                   yyjson_ptr_err *err) {\n    \n    const char *hdr = ptr, *end = ptr + ptr_len, *token;\n    usize len, esc;\n    yyjson_type type;\n    \n    while (true) {\n        token = ptr_next_token(&ptr, end, &len, &esc);\n        if (unlikely(!token)) return_err_syntax(NULL, ptr - hdr);\n        type = unsafe_yyjson_get_type(val);\n        if (type == YYJSON_TYPE_OBJ) {\n            val = ptr_obj_get(val, token, len, esc);\n        } else if (type == YYJSON_TYPE_ARR) {\n            val = ptr_arr_get(val, token, len, esc);\n        } else {\n            val = NULL;\n        }\n        if (!val) return_err_resolve(NULL, token - hdr);\n        if (ptr == end) return val;\n    }\n}\n\nyyjson_mut_val *unsafe_yyjson_mut_ptr_getx(yyjson_mut_val *val,\n                                           const char *ptr,\n                                           size_t ptr_len,\n                                           yyjson_ptr_ctx *ctx,\n                                           yyjson_ptr_err *err) {\n    \n    const char *hdr = ptr, *end = ptr + ptr_len, *token;\n    usize len, esc;\n    yyjson_mut_val *ctn, *pre = NULL;\n    yyjson_type type;\n    bool idx_is_last = false;\n    \n    while (true) {\n        token = ptr_next_token(&ptr, end, &len, &esc);\n        if (unlikely(!token)) return_err_syntax(NULL, ptr - hdr);\n        ctn = val;\n        type = unsafe_yyjson_get_type(val);\n        if (type == YYJSON_TYPE_OBJ) {\n            val = ptr_mut_obj_get(val, token, len, esc, &pre);\n        } else if (type == YYJSON_TYPE_ARR) {\n            val = ptr_mut_arr_get(val, token, len, esc, &pre, &idx_is_last);\n        } else {\n            val = NULL;\n        }\n        if (ctx && (ptr == end)) {\n            if (type == YYJSON_TYPE_OBJ ||\n                (type == YYJSON_TYPE_ARR && (val || idx_is_last))) {\n                ctx->ctn = ctn;\n                ctx->pre = pre;\n            }\n        }\n        if (!val) return_err_resolve(NULL, token - hdr);\n        if (ptr == end) return val;\n    }\n}\n\nbool unsafe_yyjson_mut_ptr_putx(yyjson_mut_val *val,\n                                const char *ptr, size_t ptr_len,\n                                yyjson_mut_val *new_val,\n                                yyjson_mut_doc *doc,\n                                bool create_parent, bool insert_new,\n                                yyjson_ptr_ctx *ctx,\n                                yyjson_ptr_err *err) {\n    \n    const char *hdr = ptr, *end = ptr + ptr_len, *token;\n    usize token_len, esc, ctn_len;\n    yyjson_mut_val *ctn, *key, *pre = NULL;\n    yyjson_mut_val *sep_ctn = NULL, *sep_key = NULL, *sep_val = NULL;\n    yyjson_type ctn_type;\n    bool idx_is_last = false;\n    \n    /* skip exist parent nodes */\n    while (true) {\n        token = ptr_next_token(&ptr, end, &token_len, &esc);\n        if (unlikely(!token)) return_err_syntax(false, ptr - hdr);\n        ctn = val;\n        ctn_type = unsafe_yyjson_get_type(ctn);\n        if (ctn_type == YYJSON_TYPE_OBJ) {\n            val = ptr_mut_obj_get(ctn, token, token_len, esc, &pre);\n        } else if (ctn_type == YYJSON_TYPE_ARR) {\n            val = ptr_mut_arr_get(ctn, token, token_len, esc, &pre,\n                                  &idx_is_last);\n        } else return_err_resolve(false, token - hdr);\n        if (!val) break;\n        if (ptr == end) break; /* is last token */\n    }\n    \n    /* create parent nodes if not exist */\n    if (unlikely(ptr != end)) { /* not last token */\n        if (!create_parent) return_err_resolve(false, token - hdr);\n        \n        /* add value at last index if container is array */\n        if (ctn_type == YYJSON_TYPE_ARR) {\n            if (!idx_is_last || !insert_new) {\n                return_err_resolve(false, token - hdr);\n            }\n            val = yyjson_mut_obj(doc);\n            if (!val) return_err_alloc(false);\n            \n            /* delay attaching until all operations are completed */\n            sep_ctn = ctn;\n            sep_key = NULL;\n            sep_val = val;\n            \n            /* move to next token */\n            ctn = val;\n            val = NULL;\n            ctn_type = YYJSON_TYPE_OBJ;\n            token = ptr_next_token(&ptr, end, &token_len, &esc);\n            if (unlikely(!token)) return_err_resolve(false, token - hdr);\n        }\n        \n        /* container is object, create parent nodes */\n        while (ptr != end) { /* not last token */\n            key = ptr_new_key(token, token_len, esc, doc);\n            if (!key) return_err_alloc(false);\n            val = yyjson_mut_obj(doc);\n            if (!val) return_err_alloc(false);\n            \n            /* delay attaching until all operations are completed */\n            if (!sep_ctn) {\n                sep_ctn = ctn;\n                sep_key = key;\n                sep_val = val;\n            } else {\n                yyjson_mut_obj_add(ctn, key, val);\n            }\n            \n            /* move to next token */\n            ctn = val;\n            val = NULL;\n            token = ptr_next_token(&ptr, end, &token_len, &esc);\n            if (unlikely(!token)) return_err_syntax(false, ptr - hdr);\n        }\n    }\n    \n    /* JSON pointer is resolved, insert or replace target value */\n    ctn_len = unsafe_yyjson_get_len(ctn);\n    if (ctn_type == YYJSON_TYPE_OBJ) {\n        if (ctx) ctx->ctn = ctn;\n        if (!val || insert_new) {\n            /* insert new key-value pair */\n            key = ptr_new_key(token, token_len, esc, doc);\n            if (unlikely(!key)) return_err_alloc(false);\n            if (ctx) ctx->pre = ctn_len ? (yyjson_mut_val *)ctn->uni.ptr : key;\n            unsafe_yyjson_mut_obj_add(ctn, key, new_val, ctn_len);\n        } else {\n            /* replace exist value */\n            key = pre->next->next;\n            if (ctx) ctx->pre = pre;\n            if (ctx) ctx->old = val;\n            yyjson_mut_obj_put(ctn, key, new_val);\n        }\n    } else {\n        /* array */\n        if (ctx && (val || idx_is_last)) ctx->ctn = ctn;\n        if (insert_new) {\n            /* append new value */\n            if (val) {\n                pre->next = new_val;\n                new_val->next = val;\n                if (ctx) ctx->pre = pre;\n                unsafe_yyjson_set_len(ctn, ctn_len + 1);\n            } else if (idx_is_last) {\n                if (ctx) ctx->pre = ctn_len ?\n                    (yyjson_mut_val *)ctn->uni.ptr : new_val;\n                yyjson_mut_arr_append(ctn, new_val);\n            } else {\n                return_err_resolve(false, token - hdr);\n            }\n        } else {\n            /* replace exist value */\n            if (!val) return_err_resolve(false, token - hdr);\n            if (ctn_len > 1) {\n                new_val->next = val->next;\n                pre->next = new_val;\n                if (ctn->uni.ptr == val) ctn->uni.ptr = new_val;\n            } else {\n                new_val->next = new_val;\n                ctn->uni.ptr = new_val;\n                pre = new_val;\n            }\n            if (ctx) ctx->pre = pre;\n            if (ctx) ctx->old = val;\n        }\n    }\n    \n    /* all operations are completed, attach the new components to the target */\n    if (unlikely(sep_ctn)) {\n        if (sep_key) yyjson_mut_obj_add(sep_ctn, sep_key, sep_val);\n        else yyjson_mut_arr_append(sep_ctn, sep_val);\n    }\n    return true;\n}\n\nyyjson_mut_val *unsafe_yyjson_mut_ptr_replacex(\n    yyjson_mut_val *val, const char *ptr, size_t len, yyjson_mut_val *new_val,\n    yyjson_ptr_ctx *ctx, yyjson_ptr_err *err) {\n    \n    yyjson_mut_val *cur_val;\n    yyjson_ptr_ctx cur_ctx;\n    memset(&cur_ctx, 0, sizeof(cur_ctx));\n    if (!ctx) ctx = &cur_ctx;\n    cur_val = unsafe_yyjson_mut_ptr_getx(val, ptr, len, ctx, err);\n    if (!cur_val) return NULL;\n    \n    if (yyjson_mut_is_obj(ctx->ctn)) {\n        yyjson_mut_val *key = ctx->pre->next->next;\n        yyjson_mut_obj_put(ctx->ctn, key, new_val);\n    } else {\n        yyjson_ptr_ctx_replace(ctx, new_val);\n    }\n    ctx->old = cur_val;\n    return cur_val;\n}\n\nyyjson_mut_val *unsafe_yyjson_mut_ptr_removex(yyjson_mut_val *val,\n                                              const char *ptr,\n                                              size_t len,\n                                              yyjson_ptr_ctx *ctx,\n                                              yyjson_ptr_err *err) {\n    yyjson_mut_val *cur_val;\n    yyjson_ptr_ctx cur_ctx;\n    memset(&cur_ctx, 0, sizeof(cur_ctx));\n    if (!ctx) ctx = &cur_ctx;\n    cur_val = unsafe_yyjson_mut_ptr_getx(val, ptr, len, ctx, err);\n    if (cur_val) {\n        if (yyjson_mut_is_obj(ctx->ctn)) {\n            yyjson_mut_val *key = ctx->pre->next->next;\n            yyjson_mut_obj_put(ctx->ctn, key, NULL);\n        } else {\n            yyjson_ptr_ctx_remove(ctx);\n        }\n        ctx->pre = NULL;\n        ctx->old = cur_val;\n    }\n    return cur_val;\n}\n\n/* macros for yyjson_ptr */\n#undef return_err\n#undef return_err_resolve\n#undef return_err_syntax\n#undef return_err_alloc\n\n\n\n/*==============================================================================\n * JSON Patch API (RFC 6902)\n *============================================================================*/\n\n/* JSON Patch operation */\ntypedef enum patch_op {\n    PATCH_OP_ADD,       /* path, value */\n    PATCH_OP_REMOVE,    /* path */\n    PATCH_OP_REPLACE,   /* path, value */\n    PATCH_OP_MOVE,      /* from, path */\n    PATCH_OP_COPY,      /* from, path */\n    PATCH_OP_TEST,      /* path, value */\n    PATCH_OP_NONE       /* invalid */\n} patch_op;\n\nstatic patch_op patch_op_get(yyjson_val *op) {\n    const char *str = op->uni.str;\n    switch (unsafe_yyjson_get_len(op)) {\n        case 3:\n            if (!memcmp(str, \"add\", 3)) return PATCH_OP_ADD;\n            return PATCH_OP_NONE;\n        case 4:\n            if (!memcmp(str, \"move\", 4)) return PATCH_OP_MOVE;\n            if (!memcmp(str, \"copy\", 4)) return PATCH_OP_COPY;\n            if (!memcmp(str, \"test\", 4)) return PATCH_OP_TEST;\n            return PATCH_OP_NONE;\n        case 6:\n            if (!memcmp(str, \"remove\", 6)) return PATCH_OP_REMOVE;\n            return PATCH_OP_NONE;\n        case 7:\n            if (!memcmp(str, \"replace\", 7)) return PATCH_OP_REPLACE;\n            return PATCH_OP_NONE;\n        default:\n            return PATCH_OP_NONE;\n    }\n}\n\n/* macros for yyjson_patch */\n#define return_err(_code, _msg) do { \\\n    if (err->ptr.code == YYJSON_PTR_ERR_MEMORY_ALLOCATION) { \\\n        err->code = YYJSON_PATCH_ERROR_MEMORY_ALLOCATION; \\\n        err->msg = _msg; \\\n        memset(&err->ptr, 0, sizeof(yyjson_ptr_err)); \\\n    } else { \\\n        err->code = YYJSON_PATCH_ERROR_##_code; \\\n        err->msg = _msg; \\\n        err->idx = iter.idx ? iter.idx - 1 : 0; \\\n    } \\\n    return NULL; \\\n} while (false)\n\n#define return_err_copy() \\\n    return_err(MEMORY_ALLOCATION, \"failed to copy value\")\n#define return_err_key(_key) \\\n    return_err(MISSING_KEY, \"missing key \" _key)\n#define return_err_val(_key) \\\n    return_err(INVALID_MEMBER, \"invalid member \" _key)\n\n#define ptr_get(_ptr) yyjson_mut_ptr_getx( \\\n    root, _ptr->uni.str, _ptr##_len, NULL, &err->ptr)\n#define ptr_add(_ptr, _val) yyjson_mut_ptr_addx( \\\n    root, _ptr->uni.str, _ptr##_len, _val, doc, false, NULL, &err->ptr)\n#define ptr_remove(_ptr) yyjson_mut_ptr_removex( \\\n    root, _ptr->uni.str, _ptr##_len, NULL, &err->ptr)\n#define ptr_replace(_ptr, _val)yyjson_mut_ptr_replacex( \\\n    root, _ptr->uni.str, _ptr##_len, _val, NULL, &err->ptr)\n    \nyyjson_mut_val *yyjson_patch(yyjson_mut_doc *doc,\n                             yyjson_val *orig,\n                             yyjson_val *patch,\n                             yyjson_patch_err *err) {\n\n    yyjson_mut_val *root;\n    yyjson_val *obj;\n    yyjson_arr_iter iter;\n    yyjson_patch_err err_tmp;\n    if (!err) err = &err_tmp;\n    memset(err, 0, sizeof(*err));\n    memset(&iter, 0, sizeof(iter));\n    \n    if (unlikely(!doc || !orig || !patch)) {\n        return_err(INVALID_PARAMETER, \"input parameter is NULL\");\n    }\n    if (unlikely(!yyjson_is_arr(patch))) {\n        return_err(INVALID_PARAMETER, \"input patch is not array\");\n    }\n    root = yyjson_val_mut_copy(doc, orig);\n    if (unlikely(!root)) return_err_copy();\n    \n    /* iterate through the patch array */\n    yyjson_arr_iter_init(patch, &iter);\n    while ((obj = yyjson_arr_iter_next(&iter))) {\n        patch_op op_enum;\n        yyjson_val *op, *path, *from = NULL, *value;\n        yyjson_mut_val *val = NULL, *test;\n        usize path_len, from_len = 0;\n        if (unlikely(!unsafe_yyjson_is_obj(obj))) {\n            return_err(INVALID_OPERATION, \"JSON patch operation is not object\");\n        }\n        \n        /* get required member: op */\n        op = yyjson_obj_get(obj, \"op\");\n        if (unlikely(!op)) return_err_key(\"`op`\");\n        if (unlikely(!yyjson_is_str(op))) return_err_val(\"`op`\");\n        op_enum = patch_op_get(op);\n        \n        /* get required member: path */\n        path = yyjson_obj_get(obj, \"path\");\n        if (unlikely(!path)) return_err_key(\"`path`\");\n        if (unlikely(!yyjson_is_str(path))) return_err_val(\"`path`\");\n        path_len = unsafe_yyjson_get_len(path);\n        \n        /* get required member: value, from */\n        switch ((int)op_enum) {\n            case PATCH_OP_ADD: case PATCH_OP_REPLACE: case PATCH_OP_TEST:\n                value = yyjson_obj_get(obj, \"value\");\n                if (unlikely(!value)) return_err_key(\"`value`\");\n                val = yyjson_val_mut_copy(doc, value);\n                if (unlikely(!val)) return_err_copy();\n                break;\n            case PATCH_OP_MOVE: case PATCH_OP_COPY:\n                from = yyjson_obj_get(obj, \"from\");\n                if (unlikely(!from)) return_err_key(\"`from`\");\n                if (unlikely(!yyjson_is_str(from))) return_err_val(\"`from`\");\n                from_len = unsafe_yyjson_get_len(from);\n                break;\n            default:\n                break;\n        }\n        \n        /* perform an operation */\n        switch ((int)op_enum) {\n            case PATCH_OP_ADD: /* add(path, val) */\n                if (unlikely(path_len == 0)) { root = val; break; }\n                if (unlikely(!ptr_add(path, val))) {\n                    return_err(POINTER, \"failed to add `path`\");\n                }\n                break;\n            case PATCH_OP_REMOVE: /* remove(path) */\n                if (unlikely(!ptr_remove(path))) {\n                    return_err(POINTER, \"failed to remove `path`\");\n                }\n                break;\n            case PATCH_OP_REPLACE: /* replace(path, val) */\n                if (unlikely(path_len == 0)) { root = val; break; }\n                if (unlikely(!ptr_replace(path, val))) {\n                    return_err(POINTER, \"failed to replace `path`\");\n                }\n                break;\n            case PATCH_OP_MOVE: /* val = remove(from), add(path, val) */\n                if (unlikely(from_len == 0 && path_len == 0)) break;\n                val = ptr_remove(from);\n                if (unlikely(!val)) {\n                    return_err(POINTER, \"failed to remove `from`\");\n                }\n                if (unlikely(path_len == 0)) { root = val; break; }\n                if (unlikely(!ptr_add(path, val))) {\n                    return_err(POINTER, \"failed to add `path`\");\n                }\n                break;\n            case PATCH_OP_COPY: /* val = get(from).copy, add(path, val) */\n                val = ptr_get(from);\n                if (unlikely(!val)) {\n                    return_err(POINTER, \"failed to get `from`\");\n                }\n                if (unlikely(path_len == 0)) { root = val; break; }\n                val = yyjson_mut_val_mut_copy(doc, val);\n                if (unlikely(!val)) return_err_copy();\n                if (unlikely(!ptr_add(path, val))) {\n                    return_err(POINTER, \"failed to add `path`\");\n                }\n                break;\n            case PATCH_OP_TEST: /* test = get(path), test.eq(val) */\n                test = ptr_get(path);\n                if (unlikely(!test)) {\n                    return_err(POINTER, \"failed to get `path`\");\n                }\n                if (unlikely(!yyjson_mut_equals(val, test))) {\n                    return_err(EQUAL, \"failed to test equal\");\n                }\n                break;\n            default:\n                return_err(INVALID_MEMBER, \"unsupported `op`\");\n        }\n    }\n    return root;\n}\n\nyyjson_mut_val *yyjson_mut_patch(yyjson_mut_doc *doc,\n                                 yyjson_mut_val *orig,\n                                 yyjson_mut_val *patch,\n                                 yyjson_patch_err *err) {\n    yyjson_mut_val *root, *obj;\n    yyjson_mut_arr_iter iter;\n    yyjson_patch_err err_tmp;\n    if (!err) err = &err_tmp;\n    memset(err, 0, sizeof(*err));\n    memset(&iter, 0, sizeof(iter));\n    \n    if (unlikely(!doc || !orig || !patch)) {\n        return_err(INVALID_PARAMETER, \"input parameter is NULL\");\n    }\n    if (unlikely(!yyjson_mut_is_arr(patch))) {\n        return_err(INVALID_PARAMETER, \"input patch is not array\");\n    }\n    root = yyjson_mut_val_mut_copy(doc, orig);\n    if (unlikely(!root)) return_err_copy();\n    \n    /* iterate through the patch array */\n    yyjson_mut_arr_iter_init(patch, &iter);\n    while ((obj = yyjson_mut_arr_iter_next(&iter))) {\n        patch_op op_enum;\n        yyjson_mut_val *op, *path, *from = NULL, *value;\n        yyjson_mut_val *val = NULL, *test;\n        usize path_len, from_len = 0;\n        if (!unsafe_yyjson_is_obj(obj)) {\n            return_err(INVALID_OPERATION, \"JSON patch operation is not object\");\n        }\n        \n        /* get required member: op */\n        op = yyjson_mut_obj_get(obj, \"op\");\n        if (unlikely(!op)) return_err_key(\"`op`\");\n        if (unlikely(!yyjson_mut_is_str(op))) return_err_val(\"`op`\");\n        op_enum = patch_op_get((yyjson_val *)(void *)op);\n        \n        /* get required member: path */\n        path = yyjson_mut_obj_get(obj, \"path\");\n        if (unlikely(!path)) return_err_key(\"`path`\");\n        if (unlikely(!yyjson_mut_is_str(path))) return_err_val(\"`path`\");\n        path_len = unsafe_yyjson_get_len(path);\n        \n        /* get required member: value, from */\n        switch ((int)op_enum) {\n            case PATCH_OP_ADD: case PATCH_OP_REPLACE: case PATCH_OP_TEST:\n                value = yyjson_mut_obj_get(obj, \"value\");\n                if (unlikely(!value)) return_err_key(\"`value`\");\n                val = yyjson_mut_val_mut_copy(doc, value);\n                if (unlikely(!val)) return_err_copy();\n                break;\n            case PATCH_OP_MOVE: case PATCH_OP_COPY:\n                from = yyjson_mut_obj_get(obj, \"from\");\n                if (unlikely(!from)) return_err_key(\"`from`\");\n                if (unlikely(!yyjson_mut_is_str(from))) {\n                    return_err_val(\"`from`\");\n                }\n                from_len = unsafe_yyjson_get_len(from);\n                break;\n            default:\n                break;\n        }\n        \n        /* perform an operation */\n        switch ((int)op_enum) {\n            case PATCH_OP_ADD: /* add(path, val) */\n                if (unlikely(path_len == 0)) { root = val; break; }\n                if (unlikely(!ptr_add(path, val))) {\n                    return_err(POINTER, \"failed to add `path`\");\n                }\n                break;\n            case PATCH_OP_REMOVE: /* remove(path) */\n                if (unlikely(!ptr_remove(path))) {\n                    return_err(POINTER, \"failed to remove `path`\");\n                }\n                break;\n            case PATCH_OP_REPLACE: /* replace(path, val) */\n                if (unlikely(path_len == 0)) { root = val; break; }\n                if (unlikely(!ptr_replace(path, val))) {\n                    return_err(POINTER, \"failed to replace `path`\");\n                }\n                break;\n            case PATCH_OP_MOVE: /* val = remove(from), add(path, val) */\n                if (unlikely(from_len == 0 && path_len == 0)) break;\n                val = ptr_remove(from);\n                if (unlikely(!val)) {\n                    return_err(POINTER, \"failed to remove `from`\");\n                }\n                if (unlikely(path_len == 0)) { root = val; break; }\n                if (unlikely(!ptr_add(path, val))) {\n                    return_err(POINTER, \"failed to add `path`\");\n                }\n                break;\n            case PATCH_OP_COPY: /* val = get(from).copy, add(path, val) */\n                val = ptr_get(from);\n                if (unlikely(!val)) {\n                    return_err(POINTER, \"failed to get `from`\");\n                }\n                if (unlikely(path_len == 0)) { root = val; break; }\n                val = yyjson_mut_val_mut_copy(doc, val);\n                if (unlikely(!val)) return_err_copy();\n                if (unlikely(!ptr_add(path, val))) {\n                    return_err(POINTER, \"failed to add `path`\");\n                }\n                break;\n            case PATCH_OP_TEST: /* test = get(path), test.eq(val) */\n                test = ptr_get(path);\n                if (unlikely(!test)) {\n                    return_err(POINTER, \"failed to get `path`\");\n                }\n                if (unlikely(!yyjson_mut_equals(val, test))) {\n                    return_err(EQUAL, \"failed to test equal\");\n                }\n                break;\n            default:\n                return_err(INVALID_MEMBER, \"unsupported `op`\");\n        }\n    }\n    return root;\n}\n\n/* macros for yyjson_patch */\n#undef return_err\n#undef return_err_copy\n#undef return_err_key\n#undef return_err_val\n#undef ptr_get\n#undef ptr_add\n#undef ptr_remove\n#undef ptr_replace\n\n\n\n/*==============================================================================\n * JSON Merge-Patch API (RFC 7386)\n *============================================================================*/\n\nyyjson_mut_val *yyjson_merge_patch(yyjson_mut_doc *doc,\n                                   yyjson_val *orig,\n                                   yyjson_val *patch) {\n    usize idx, max;\n    yyjson_val *key, *orig_val, *patch_val, local_orig;\n    yyjson_mut_val *builder, *mut_key, *mut_val, *merged_val;\n    \n    if (unlikely(!yyjson_is_obj(patch))) {\n        return yyjson_val_mut_copy(doc, patch);\n    }\n    \n    builder = yyjson_mut_obj(doc);\n    if (unlikely(!builder)) return NULL;\n    \n    memset(&local_orig, 0, sizeof(local_orig));\n    if (!yyjson_is_obj(orig)) {\n        orig = &local_orig;\n        orig->tag = builder->tag;\n        orig->uni = builder->uni;\n    }\n    \n    /* If orig is contributing, copy any items not modified by the patch */\n    if (orig != &local_orig) {\n        yyjson_obj_foreach(orig, idx, max, key, orig_val) {\n            patch_val = yyjson_obj_getn(patch,\n                                        unsafe_yyjson_get_str(key),\n                                        unsafe_yyjson_get_len(key));\n            if (!patch_val) {\n                mut_key = yyjson_val_mut_copy(doc, key);\n                mut_val = yyjson_val_mut_copy(doc, orig_val);\n                if (!yyjson_mut_obj_add(builder, mut_key, mut_val)) return NULL;\n            }\n        }\n    }\n\n    /* Merge items modified by the patch. */\n    yyjson_obj_foreach(patch, idx, max, key, patch_val) {\n        /* null indicates the field is removed. */\n        if (unsafe_yyjson_is_null(patch_val)) {\n            continue;\n        }\n        mut_key = yyjson_val_mut_copy(doc, key);\n        orig_val = yyjson_obj_getn(orig,\n                                   unsafe_yyjson_get_str(key),\n                                   unsafe_yyjson_get_len(key));\n        merged_val = yyjson_merge_patch(doc, orig_val, patch_val);\n        if (!yyjson_mut_obj_add(builder, mut_key, merged_val)) return NULL;\n    }\n    \n    return builder;\n}\n\nyyjson_mut_val *yyjson_mut_merge_patch(yyjson_mut_doc *doc,\n                                       yyjson_mut_val *orig,\n                                       yyjson_mut_val *patch) {\n    usize idx, max;\n    yyjson_mut_val *key, *orig_val, *patch_val, local_orig;\n    yyjson_mut_val *builder, *mut_key, *mut_val, *merged_val;\n    \n    if (unlikely(!yyjson_mut_is_obj(patch))) {\n        return yyjson_mut_val_mut_copy(doc, patch);\n    }\n    \n    builder = yyjson_mut_obj(doc);\n    if (unlikely(!builder)) return NULL;\n    \n    memset(&local_orig, 0, sizeof(local_orig));\n    if (!yyjson_mut_is_obj(orig)) {\n        orig = &local_orig;\n        orig->tag = builder->tag;\n        orig->uni = builder->uni;\n    }\n    \n    /* If orig is contributing, copy any items not modified by the patch */\n    if (orig != &local_orig) {\n        yyjson_mut_obj_foreach(orig, idx, max, key, orig_val) {\n            patch_val = yyjson_mut_obj_getn(patch,\n                                            unsafe_yyjson_get_str(key),\n                                            unsafe_yyjson_get_len(key));\n            if (!patch_val) {\n                mut_key = yyjson_mut_val_mut_copy(doc, key);\n                mut_val = yyjson_mut_val_mut_copy(doc, orig_val);\n                if (!yyjson_mut_obj_add(builder, mut_key, mut_val)) return NULL;\n            }\n        }\n    }\n\n    /* Merge items modified by the patch. */\n    yyjson_mut_obj_foreach(patch, idx, max, key, patch_val) {\n        /* null indicates the field is removed. */\n        if (unsafe_yyjson_is_null(patch_val)) {\n            continue;\n        }\n        mut_key = yyjson_mut_val_mut_copy(doc, key);\n        orig_val = yyjson_mut_obj_getn(orig,\n                                       unsafe_yyjson_get_str(key),\n                                       unsafe_yyjson_get_len(key));\n        merged_val = yyjson_mut_merge_patch(doc, orig_val, patch_val);\n        if (!yyjson_mut_obj_add(builder, mut_key, merged_val)) return NULL;\n    }\n    \n    return builder;\n}\n\n#endif /* YYJSON_DISABLE_UTILS */\n\n\n\n/*==============================================================================\n * Power10 Lookup Table\n * These data are used by the floating-point number reader and writer.\n *============================================================================*/\n\n#if (!YYJSON_DISABLE_READER || !YYJSON_DISABLE_WRITER) && \\\n    (!YYJSON_DISABLE_FAST_FP_CONV)\n\n/** Minimum decimal exponent in pow10_sig_table. */\n#define POW10_SIG_TABLE_MIN_EXP -343\n\n/** Maximum decimal exponent in pow10_sig_table. */\n#define POW10_SIG_TABLE_MAX_EXP 324\n\n/** Minimum exact decimal exponent in pow10_sig_table */\n#define POW10_SIG_TABLE_MIN_EXACT_EXP 0\n\n/** Maximum exact decimal exponent in pow10_sig_table */\n#define POW10_SIG_TABLE_MAX_EXACT_EXP 55\n\n/** Normalized significant 128 bits of pow10, no rounded up (size: 10.4KB).\n    This lookup table is used by both the double number reader and writer.\n    (generate with misc/make_tables.c) */\nstatic const u64 pow10_sig_table[] = {\n    U64(0xBF29DCAB, 0xA82FDEAE), U64(0x7432EE87, 0x3880FC33), /* ~= 10^-343 */\n    U64(0xEEF453D6, 0x923BD65A), U64(0x113FAA29, 0x06A13B3F), /* ~= 10^-342 */\n    U64(0x9558B466, 0x1B6565F8), U64(0x4AC7CA59, 0xA424C507), /* ~= 10^-341 */\n    U64(0xBAAEE17F, 0xA23EBF76), U64(0x5D79BCF0, 0x0D2DF649), /* ~= 10^-340 */\n    U64(0xE95A99DF, 0x8ACE6F53), U64(0xF4D82C2C, 0x107973DC), /* ~= 10^-339 */\n    U64(0x91D8A02B, 0xB6C10594), U64(0x79071B9B, 0x8A4BE869), /* ~= 10^-338 */\n    U64(0xB64EC836, 0xA47146F9), U64(0x9748E282, 0x6CDEE284), /* ~= 10^-337 */\n    U64(0xE3E27A44, 0x4D8D98B7), U64(0xFD1B1B23, 0x08169B25), /* ~= 10^-336 */\n    U64(0x8E6D8C6A, 0xB0787F72), U64(0xFE30F0F5, 0xE50E20F7), /* ~= 10^-335 */\n    U64(0xB208EF85, 0x5C969F4F), U64(0xBDBD2D33, 0x5E51A935), /* ~= 10^-334 */\n    U64(0xDE8B2B66, 0xB3BC4723), U64(0xAD2C7880, 0x35E61382), /* ~= 10^-333 */\n    U64(0x8B16FB20, 0x3055AC76), U64(0x4C3BCB50, 0x21AFCC31), /* ~= 10^-332 */\n    U64(0xADDCB9E8, 0x3C6B1793), U64(0xDF4ABE24, 0x2A1BBF3D), /* ~= 10^-331 */\n    U64(0xD953E862, 0x4B85DD78), U64(0xD71D6DAD, 0x34A2AF0D), /* ~= 10^-330 */\n    U64(0x87D4713D, 0x6F33AA6B), U64(0x8672648C, 0x40E5AD68), /* ~= 10^-329 */\n    U64(0xA9C98D8C, 0xCB009506), U64(0x680EFDAF, 0x511F18C2), /* ~= 10^-328 */\n    U64(0xD43BF0EF, 0xFDC0BA48), U64(0x0212BD1B, 0x2566DEF2), /* ~= 10^-327 */\n    U64(0x84A57695, 0xFE98746D), U64(0x014BB630, 0xF7604B57), /* ~= 10^-326 */\n    U64(0xA5CED43B, 0x7E3E9188), U64(0x419EA3BD, 0x35385E2D), /* ~= 10^-325 */\n    U64(0xCF42894A, 0x5DCE35EA), U64(0x52064CAC, 0x828675B9), /* ~= 10^-324 */\n    U64(0x818995CE, 0x7AA0E1B2), U64(0x7343EFEB, 0xD1940993), /* ~= 10^-323 */\n    U64(0xA1EBFB42, 0x19491A1F), U64(0x1014EBE6, 0xC5F90BF8), /* ~= 10^-322 */\n    U64(0xCA66FA12, 0x9F9B60A6), U64(0xD41A26E0, 0x77774EF6), /* ~= 10^-321 */\n    U64(0xFD00B897, 0x478238D0), U64(0x8920B098, 0x955522B4), /* ~= 10^-320 */\n    U64(0x9E20735E, 0x8CB16382), U64(0x55B46E5F, 0x5D5535B0), /* ~= 10^-319 */\n    U64(0xC5A89036, 0x2FDDBC62), U64(0xEB2189F7, 0x34AA831D), /* ~= 10^-318 */\n    U64(0xF712B443, 0xBBD52B7B), U64(0xA5E9EC75, 0x01D523E4), /* ~= 10^-317 */\n    U64(0x9A6BB0AA, 0x55653B2D), U64(0x47B233C9, 0x2125366E), /* ~= 10^-316 */\n    U64(0xC1069CD4, 0xEABE89F8), U64(0x999EC0BB, 0x696E840A), /* ~= 10^-315 */\n    U64(0xF148440A, 0x256E2C76), U64(0xC00670EA, 0x43CA250D), /* ~= 10^-314 */\n    U64(0x96CD2A86, 0x5764DBCA), U64(0x38040692, 0x6A5E5728), /* ~= 10^-313 */\n    U64(0xBC807527, 0xED3E12BC), U64(0xC6050837, 0x04F5ECF2), /* ~= 10^-312 */\n    U64(0xEBA09271, 0xE88D976B), U64(0xF7864A44, 0xC633682E), /* ~= 10^-311 */\n    U64(0x93445B87, 0x31587EA3), U64(0x7AB3EE6A, 0xFBE0211D), /* ~= 10^-310 */\n    U64(0xB8157268, 0xFDAE9E4C), U64(0x5960EA05, 0xBAD82964), /* ~= 10^-309 */\n    U64(0xE61ACF03, 0x3D1A45DF), U64(0x6FB92487, 0x298E33BD), /* ~= 10^-308 */\n    U64(0x8FD0C162, 0x06306BAB), U64(0xA5D3B6D4, 0x79F8E056), /* ~= 10^-307 */\n    U64(0xB3C4F1BA, 0x87BC8696), U64(0x8F48A489, 0x9877186C), /* ~= 10^-306 */\n    U64(0xE0B62E29, 0x29ABA83C), U64(0x331ACDAB, 0xFE94DE87), /* ~= 10^-305 */\n    U64(0x8C71DCD9, 0xBA0B4925), U64(0x9FF0C08B, 0x7F1D0B14), /* ~= 10^-304 */\n    U64(0xAF8E5410, 0x288E1B6F), U64(0x07ECF0AE, 0x5EE44DD9), /* ~= 10^-303 */\n    U64(0xDB71E914, 0x32B1A24A), U64(0xC9E82CD9, 0xF69D6150), /* ~= 10^-302 */\n    U64(0x892731AC, 0x9FAF056E), U64(0xBE311C08, 0x3A225CD2), /* ~= 10^-301 */\n    U64(0xAB70FE17, 0xC79AC6CA), U64(0x6DBD630A, 0x48AAF406), /* ~= 10^-300 */\n    U64(0xD64D3D9D, 0xB981787D), U64(0x092CBBCC, 0xDAD5B108), /* ~= 10^-299 */\n    U64(0x85F04682, 0x93F0EB4E), U64(0x25BBF560, 0x08C58EA5), /* ~= 10^-298 */\n    U64(0xA76C5823, 0x38ED2621), U64(0xAF2AF2B8, 0x0AF6F24E), /* ~= 10^-297 */\n    U64(0xD1476E2C, 0x07286FAA), U64(0x1AF5AF66, 0x0DB4AEE1), /* ~= 10^-296 */\n    U64(0x82CCA4DB, 0x847945CA), U64(0x50D98D9F, 0xC890ED4D), /* ~= 10^-295 */\n    U64(0xA37FCE12, 0x6597973C), U64(0xE50FF107, 0xBAB528A0), /* ~= 10^-294 */\n    U64(0xCC5FC196, 0xFEFD7D0C), U64(0x1E53ED49, 0xA96272C8), /* ~= 10^-293 */\n    U64(0xFF77B1FC, 0xBEBCDC4F), U64(0x25E8E89C, 0x13BB0F7A), /* ~= 10^-292 */\n    U64(0x9FAACF3D, 0xF73609B1), U64(0x77B19161, 0x8C54E9AC), /* ~= 10^-291 */\n    U64(0xC795830D, 0x75038C1D), U64(0xD59DF5B9, 0xEF6A2417), /* ~= 10^-290 */\n    U64(0xF97AE3D0, 0xD2446F25), U64(0x4B057328, 0x6B44AD1D), /* ~= 10^-289 */\n    U64(0x9BECCE62, 0x836AC577), U64(0x4EE367F9, 0x430AEC32), /* ~= 10^-288 */\n    U64(0xC2E801FB, 0x244576D5), U64(0x229C41F7, 0x93CDA73F), /* ~= 10^-287 */\n    U64(0xF3A20279, 0xED56D48A), U64(0x6B435275, 0x78C1110F), /* ~= 10^-286 */\n    U64(0x9845418C, 0x345644D6), U64(0x830A1389, 0x6B78AAA9), /* ~= 10^-285 */\n    U64(0xBE5691EF, 0x416BD60C), U64(0x23CC986B, 0xC656D553), /* ~= 10^-284 */\n    U64(0xEDEC366B, 0x11C6CB8F), U64(0x2CBFBE86, 0xB7EC8AA8), /* ~= 10^-283 */\n    U64(0x94B3A202, 0xEB1C3F39), U64(0x7BF7D714, 0x32F3D6A9), /* ~= 10^-282 */\n    U64(0xB9E08A83, 0xA5E34F07), U64(0xDAF5CCD9, 0x3FB0CC53), /* ~= 10^-281 */\n    U64(0xE858AD24, 0x8F5C22C9), U64(0xD1B3400F, 0x8F9CFF68), /* ~= 10^-280 */\n    U64(0x91376C36, 0xD99995BE), U64(0x23100809, 0xB9C21FA1), /* ~= 10^-279 */\n    U64(0xB5854744, 0x8FFFFB2D), U64(0xABD40A0C, 0x2832A78A), /* ~= 10^-278 */\n    U64(0xE2E69915, 0xB3FFF9F9), U64(0x16C90C8F, 0x323F516C), /* ~= 10^-277 */\n    U64(0x8DD01FAD, 0x907FFC3B), U64(0xAE3DA7D9, 0x7F6792E3), /* ~= 10^-276 */\n    U64(0xB1442798, 0xF49FFB4A), U64(0x99CD11CF, 0xDF41779C), /* ~= 10^-275 */\n    U64(0xDD95317F, 0x31C7FA1D), U64(0x40405643, 0xD711D583), /* ~= 10^-274 */\n    U64(0x8A7D3EEF, 0x7F1CFC52), U64(0x482835EA, 0x666B2572), /* ~= 10^-273 */\n    U64(0xAD1C8EAB, 0x5EE43B66), U64(0xDA324365, 0x0005EECF), /* ~= 10^-272 */\n    U64(0xD863B256, 0x369D4A40), U64(0x90BED43E, 0x40076A82), /* ~= 10^-271 */\n    U64(0x873E4F75, 0xE2224E68), U64(0x5A7744A6, 0xE804A291), /* ~= 10^-270 */\n    U64(0xA90DE353, 0x5AAAE202), U64(0x711515D0, 0xA205CB36), /* ~= 10^-269 */\n    U64(0xD3515C28, 0x31559A83), U64(0x0D5A5B44, 0xCA873E03), /* ~= 10^-268 */\n    U64(0x8412D999, 0x1ED58091), U64(0xE858790A, 0xFE9486C2), /* ~= 10^-267 */\n    U64(0xA5178FFF, 0x668AE0B6), U64(0x626E974D, 0xBE39A872), /* ~= 10^-266 */\n    U64(0xCE5D73FF, 0x402D98E3), U64(0xFB0A3D21, 0x2DC8128F), /* ~= 10^-265 */\n    U64(0x80FA687F, 0x881C7F8E), U64(0x7CE66634, 0xBC9D0B99), /* ~= 10^-264 */\n    U64(0xA139029F, 0x6A239F72), U64(0x1C1FFFC1, 0xEBC44E80), /* ~= 10^-263 */\n    U64(0xC9874347, 0x44AC874E), U64(0xA327FFB2, 0x66B56220), /* ~= 10^-262 */\n    U64(0xFBE91419, 0x15D7A922), U64(0x4BF1FF9F, 0x0062BAA8), /* ~= 10^-261 */\n    U64(0x9D71AC8F, 0xADA6C9B5), U64(0x6F773FC3, 0x603DB4A9), /* ~= 10^-260 */\n    U64(0xC4CE17B3, 0x99107C22), U64(0xCB550FB4, 0x384D21D3), /* ~= 10^-259 */\n    U64(0xF6019DA0, 0x7F549B2B), U64(0x7E2A53A1, 0x46606A48), /* ~= 10^-258 */\n    U64(0x99C10284, 0x4F94E0FB), U64(0x2EDA7444, 0xCBFC426D), /* ~= 10^-257 */\n    U64(0xC0314325, 0x637A1939), U64(0xFA911155, 0xFEFB5308), /* ~= 10^-256 */\n    U64(0xF03D93EE, 0xBC589F88), U64(0x793555AB, 0x7EBA27CA), /* ~= 10^-255 */\n    U64(0x96267C75, 0x35B763B5), U64(0x4BC1558B, 0x2F3458DE), /* ~= 10^-254 */\n    U64(0xBBB01B92, 0x83253CA2), U64(0x9EB1AAED, 0xFB016F16), /* ~= 10^-253 */\n    U64(0xEA9C2277, 0x23EE8BCB), U64(0x465E15A9, 0x79C1CADC), /* ~= 10^-252 */\n    U64(0x92A1958A, 0x7675175F), U64(0x0BFACD89, 0xEC191EC9), /* ~= 10^-251 */\n    U64(0xB749FAED, 0x14125D36), U64(0xCEF980EC, 0x671F667B), /* ~= 10^-250 */\n    U64(0xE51C79A8, 0x5916F484), U64(0x82B7E127, 0x80E7401A), /* ~= 10^-249 */\n    U64(0x8F31CC09, 0x37AE58D2), U64(0xD1B2ECB8, 0xB0908810), /* ~= 10^-248 */\n    U64(0xB2FE3F0B, 0x8599EF07), U64(0x861FA7E6, 0xDCB4AA15), /* ~= 10^-247 */\n    U64(0xDFBDCECE, 0x67006AC9), U64(0x67A791E0, 0x93E1D49A), /* ~= 10^-246 */\n    U64(0x8BD6A141, 0x006042BD), U64(0xE0C8BB2C, 0x5C6D24E0), /* ~= 10^-245 */\n    U64(0xAECC4991, 0x4078536D), U64(0x58FAE9F7, 0x73886E18), /* ~= 10^-244 */\n    U64(0xDA7F5BF5, 0x90966848), U64(0xAF39A475, 0x506A899E), /* ~= 10^-243 */\n    U64(0x888F9979, 0x7A5E012D), U64(0x6D8406C9, 0x52429603), /* ~= 10^-242 */\n    U64(0xAAB37FD7, 0xD8F58178), U64(0xC8E5087B, 0xA6D33B83), /* ~= 10^-241 */\n    U64(0xD5605FCD, 0xCF32E1D6), U64(0xFB1E4A9A, 0x90880A64), /* ~= 10^-240 */\n    U64(0x855C3BE0, 0xA17FCD26), U64(0x5CF2EEA0, 0x9A55067F), /* ~= 10^-239 */\n    U64(0xA6B34AD8, 0xC9DFC06F), U64(0xF42FAA48, 0xC0EA481E), /* ~= 10^-238 */\n    U64(0xD0601D8E, 0xFC57B08B), U64(0xF13B94DA, 0xF124DA26), /* ~= 10^-237 */\n    U64(0x823C1279, 0x5DB6CE57), U64(0x76C53D08, 0xD6B70858), /* ~= 10^-236 */\n    U64(0xA2CB1717, 0xB52481ED), U64(0x54768C4B, 0x0C64CA6E), /* ~= 10^-235 */\n    U64(0xCB7DDCDD, 0xA26DA268), U64(0xA9942F5D, 0xCF7DFD09), /* ~= 10^-234 */\n    U64(0xFE5D5415, 0x0B090B02), U64(0xD3F93B35, 0x435D7C4C), /* ~= 10^-233 */\n    U64(0x9EFA548D, 0x26E5A6E1), U64(0xC47BC501, 0x4A1A6DAF), /* ~= 10^-232 */\n    U64(0xC6B8E9B0, 0x709F109A), U64(0x359AB641, 0x9CA1091B), /* ~= 10^-231 */\n    U64(0xF867241C, 0x8CC6D4C0), U64(0xC30163D2, 0x03C94B62), /* ~= 10^-230 */\n    U64(0x9B407691, 0xD7FC44F8), U64(0x79E0DE63, 0x425DCF1D), /* ~= 10^-229 */\n    U64(0xC2109436, 0x4DFB5636), U64(0x985915FC, 0x12F542E4), /* ~= 10^-228 */\n    U64(0xF294B943, 0xE17A2BC4), U64(0x3E6F5B7B, 0x17B2939D), /* ~= 10^-227 */\n    U64(0x979CF3CA, 0x6CEC5B5A), U64(0xA705992C, 0xEECF9C42), /* ~= 10^-226 */\n    U64(0xBD8430BD, 0x08277231), U64(0x50C6FF78, 0x2A838353), /* ~= 10^-225 */\n    U64(0xECE53CEC, 0x4A314EBD), U64(0xA4F8BF56, 0x35246428), /* ~= 10^-224 */\n    U64(0x940F4613, 0xAE5ED136), U64(0x871B7795, 0xE136BE99), /* ~= 10^-223 */\n    U64(0xB9131798, 0x99F68584), U64(0x28E2557B, 0x59846E3F), /* ~= 10^-222 */\n    U64(0xE757DD7E, 0xC07426E5), U64(0x331AEADA, 0x2FE589CF), /* ~= 10^-221 */\n    U64(0x9096EA6F, 0x3848984F), U64(0x3FF0D2C8, 0x5DEF7621), /* ~= 10^-220 */\n    U64(0xB4BCA50B, 0x065ABE63), U64(0x0FED077A, 0x756B53A9), /* ~= 10^-219 */\n    U64(0xE1EBCE4D, 0xC7F16DFB), U64(0xD3E84959, 0x12C62894), /* ~= 10^-218 */\n    U64(0x8D3360F0, 0x9CF6E4BD), U64(0x64712DD7, 0xABBBD95C), /* ~= 10^-217 */\n    U64(0xB080392C, 0xC4349DEC), U64(0xBD8D794D, 0x96AACFB3), /* ~= 10^-216 */\n    U64(0xDCA04777, 0xF541C567), U64(0xECF0D7A0, 0xFC5583A0), /* ~= 10^-215 */\n    U64(0x89E42CAA, 0xF9491B60), U64(0xF41686C4, 0x9DB57244), /* ~= 10^-214 */\n    U64(0xAC5D37D5, 0xB79B6239), U64(0x311C2875, 0xC522CED5), /* ~= 10^-213 */\n    U64(0xD77485CB, 0x25823AC7), U64(0x7D633293, 0x366B828B), /* ~= 10^-212 */\n    U64(0x86A8D39E, 0xF77164BC), U64(0xAE5DFF9C, 0x02033197), /* ~= 10^-211 */\n    U64(0xA8530886, 0xB54DBDEB), U64(0xD9F57F83, 0x0283FDFC), /* ~= 10^-210 */\n    U64(0xD267CAA8, 0x62A12D66), U64(0xD072DF63, 0xC324FD7B), /* ~= 10^-209 */\n    U64(0x8380DEA9, 0x3DA4BC60), U64(0x4247CB9E, 0x59F71E6D), /* ~= 10^-208 */\n    U64(0xA4611653, 0x8D0DEB78), U64(0x52D9BE85, 0xF074E608), /* ~= 10^-207 */\n    U64(0xCD795BE8, 0x70516656), U64(0x67902E27, 0x6C921F8B), /* ~= 10^-206 */\n    U64(0x806BD971, 0x4632DFF6), U64(0x00BA1CD8, 0xA3DB53B6), /* ~= 10^-205 */\n    U64(0xA086CFCD, 0x97BF97F3), U64(0x80E8A40E, 0xCCD228A4), /* ~= 10^-204 */\n    U64(0xC8A883C0, 0xFDAF7DF0), U64(0x6122CD12, 0x8006B2CD), /* ~= 10^-203 */\n    U64(0xFAD2A4B1, 0x3D1B5D6C), U64(0x796B8057, 0x20085F81), /* ~= 10^-202 */\n    U64(0x9CC3A6EE, 0xC6311A63), U64(0xCBE33036, 0x74053BB0), /* ~= 10^-201 */\n    U64(0xC3F490AA, 0x77BD60FC), U64(0xBEDBFC44, 0x11068A9C), /* ~= 10^-200 */\n    U64(0xF4F1B4D5, 0x15ACB93B), U64(0xEE92FB55, 0x15482D44), /* ~= 10^-199 */\n    U64(0x99171105, 0x2D8BF3C5), U64(0x751BDD15, 0x2D4D1C4A), /* ~= 10^-198 */\n    U64(0xBF5CD546, 0x78EEF0B6), U64(0xD262D45A, 0x78A0635D), /* ~= 10^-197 */\n    U64(0xEF340A98, 0x172AACE4), U64(0x86FB8971, 0x16C87C34), /* ~= 10^-196 */\n    U64(0x9580869F, 0x0E7AAC0E), U64(0xD45D35E6, 0xAE3D4DA0), /* ~= 10^-195 */\n    U64(0xBAE0A846, 0xD2195712), U64(0x89748360, 0x59CCA109), /* ~= 10^-194 */\n    U64(0xE998D258, 0x869FACD7), U64(0x2BD1A438, 0x703FC94B), /* ~= 10^-193 */\n    U64(0x91FF8377, 0x5423CC06), U64(0x7B6306A3, 0x4627DDCF), /* ~= 10^-192 */\n    U64(0xB67F6455, 0x292CBF08), U64(0x1A3BC84C, 0x17B1D542), /* ~= 10^-191 */\n    U64(0xE41F3D6A, 0x7377EECA), U64(0x20CABA5F, 0x1D9E4A93), /* ~= 10^-190 */\n    U64(0x8E938662, 0x882AF53E), U64(0x547EB47B, 0x7282EE9C), /* ~= 10^-189 */\n    U64(0xB23867FB, 0x2A35B28D), U64(0xE99E619A, 0x4F23AA43), /* ~= 10^-188 */\n    U64(0xDEC681F9, 0xF4C31F31), U64(0x6405FA00, 0xE2EC94D4), /* ~= 10^-187 */\n    U64(0x8B3C113C, 0x38F9F37E), U64(0xDE83BC40, 0x8DD3DD04), /* ~= 10^-186 */\n    U64(0xAE0B158B, 0x4738705E), U64(0x9624AB50, 0xB148D445), /* ~= 10^-185 */\n    U64(0xD98DDAEE, 0x19068C76), U64(0x3BADD624, 0xDD9B0957), /* ~= 10^-184 */\n    U64(0x87F8A8D4, 0xCFA417C9), U64(0xE54CA5D7, 0x0A80E5D6), /* ~= 10^-183 */\n    U64(0xA9F6D30A, 0x038D1DBC), U64(0x5E9FCF4C, 0xCD211F4C), /* ~= 10^-182 */\n    U64(0xD47487CC, 0x8470652B), U64(0x7647C320, 0x0069671F), /* ~= 10^-181 */\n    U64(0x84C8D4DF, 0xD2C63F3B), U64(0x29ECD9F4, 0x0041E073), /* ~= 10^-180 */\n    U64(0xA5FB0A17, 0xC777CF09), U64(0xF4681071, 0x00525890), /* ~= 10^-179 */\n    U64(0xCF79CC9D, 0xB955C2CC), U64(0x7182148D, 0x4066EEB4), /* ~= 10^-178 */\n    U64(0x81AC1FE2, 0x93D599BF), U64(0xC6F14CD8, 0x48405530), /* ~= 10^-177 */\n    U64(0xA21727DB, 0x38CB002F), U64(0xB8ADA00E, 0x5A506A7C), /* ~= 10^-176 */\n    U64(0xCA9CF1D2, 0x06FDC03B), U64(0xA6D90811, 0xF0E4851C), /* ~= 10^-175 */\n    U64(0xFD442E46, 0x88BD304A), U64(0x908F4A16, 0x6D1DA663), /* ~= 10^-174 */\n    U64(0x9E4A9CEC, 0x15763E2E), U64(0x9A598E4E, 0x043287FE), /* ~= 10^-173 */\n    U64(0xC5DD4427, 0x1AD3CDBA), U64(0x40EFF1E1, 0x853F29FD), /* ~= 10^-172 */\n    U64(0xF7549530, 0xE188C128), U64(0xD12BEE59, 0xE68EF47C), /* ~= 10^-171 */\n    U64(0x9A94DD3E, 0x8CF578B9), U64(0x82BB74F8, 0x301958CE), /* ~= 10^-170 */\n    U64(0xC13A148E, 0x3032D6E7), U64(0xE36A5236, 0x3C1FAF01), /* ~= 10^-169 */\n    U64(0xF18899B1, 0xBC3F8CA1), U64(0xDC44E6C3, 0xCB279AC1), /* ~= 10^-168 */\n    U64(0x96F5600F, 0x15A7B7E5), U64(0x29AB103A, 0x5EF8C0B9), /* ~= 10^-167 */\n    U64(0xBCB2B812, 0xDB11A5DE), U64(0x7415D448, 0xF6B6F0E7), /* ~= 10^-166 */\n    U64(0xEBDF6617, 0x91D60F56), U64(0x111B495B, 0x3464AD21), /* ~= 10^-165 */\n    U64(0x936B9FCE, 0xBB25C995), U64(0xCAB10DD9, 0x00BEEC34), /* ~= 10^-164 */\n    U64(0xB84687C2, 0x69EF3BFB), U64(0x3D5D514F, 0x40EEA742), /* ~= 10^-163 */\n    U64(0xE65829B3, 0x046B0AFA), U64(0x0CB4A5A3, 0x112A5112), /* ~= 10^-162 */\n    U64(0x8FF71A0F, 0xE2C2E6DC), U64(0x47F0E785, 0xEABA72AB), /* ~= 10^-161 */\n    U64(0xB3F4E093, 0xDB73A093), U64(0x59ED2167, 0x65690F56), /* ~= 10^-160 */\n    U64(0xE0F218B8, 0xD25088B8), U64(0x306869C1, 0x3EC3532C), /* ~= 10^-159 */\n    U64(0x8C974F73, 0x83725573), U64(0x1E414218, 0xC73A13FB), /* ~= 10^-158 */\n    U64(0xAFBD2350, 0x644EEACF), U64(0xE5D1929E, 0xF90898FA), /* ~= 10^-157 */\n    U64(0xDBAC6C24, 0x7D62A583), U64(0xDF45F746, 0xB74ABF39), /* ~= 10^-156 */\n    U64(0x894BC396, 0xCE5DA772), U64(0x6B8BBA8C, 0x328EB783), /* ~= 10^-155 */\n    U64(0xAB9EB47C, 0x81F5114F), U64(0x066EA92F, 0x3F326564), /* ~= 10^-154 */\n    U64(0xD686619B, 0xA27255A2), U64(0xC80A537B, 0x0EFEFEBD), /* ~= 10^-153 */\n    U64(0x8613FD01, 0x45877585), U64(0xBD06742C, 0xE95F5F36), /* ~= 10^-152 */\n    U64(0xA798FC41, 0x96E952E7), U64(0x2C481138, 0x23B73704), /* ~= 10^-151 */\n    U64(0xD17F3B51, 0xFCA3A7A0), U64(0xF75A1586, 0x2CA504C5), /* ~= 10^-150 */\n    U64(0x82EF8513, 0x3DE648C4), U64(0x9A984D73, 0xDBE722FB), /* ~= 10^-149 */\n    U64(0xA3AB6658, 0x0D5FDAF5), U64(0xC13E60D0, 0xD2E0EBBA), /* ~= 10^-148 */\n    U64(0xCC963FEE, 0x10B7D1B3), U64(0x318DF905, 0x079926A8), /* ~= 10^-147 */\n    U64(0xFFBBCFE9, 0x94E5C61F), U64(0xFDF17746, 0x497F7052), /* ~= 10^-146 */\n    U64(0x9FD561F1, 0xFD0F9BD3), U64(0xFEB6EA8B, 0xEDEFA633), /* ~= 10^-145 */\n    U64(0xC7CABA6E, 0x7C5382C8), U64(0xFE64A52E, 0xE96B8FC0), /* ~= 10^-144 */\n    U64(0xF9BD690A, 0x1B68637B), U64(0x3DFDCE7A, 0xA3C673B0), /* ~= 10^-143 */\n    U64(0x9C1661A6, 0x51213E2D), U64(0x06BEA10C, 0xA65C084E), /* ~= 10^-142 */\n    U64(0xC31BFA0F, 0xE5698DB8), U64(0x486E494F, 0xCFF30A62), /* ~= 10^-141 */\n    U64(0xF3E2F893, 0xDEC3F126), U64(0x5A89DBA3, 0xC3EFCCFA), /* ~= 10^-140 */\n    U64(0x986DDB5C, 0x6B3A76B7), U64(0xF8962946, 0x5A75E01C), /* ~= 10^-139 */\n    U64(0xBE895233, 0x86091465), U64(0xF6BBB397, 0xF1135823), /* ~= 10^-138 */\n    U64(0xEE2BA6C0, 0x678B597F), U64(0x746AA07D, 0xED582E2C), /* ~= 10^-137 */\n    U64(0x94DB4838, 0x40B717EF), U64(0xA8C2A44E, 0xB4571CDC), /* ~= 10^-136 */\n    U64(0xBA121A46, 0x50E4DDEB), U64(0x92F34D62, 0x616CE413), /* ~= 10^-135 */\n    U64(0xE896A0D7, 0xE51E1566), U64(0x77B020BA, 0xF9C81D17), /* ~= 10^-134 */\n    U64(0x915E2486, 0xEF32CD60), U64(0x0ACE1474, 0xDC1D122E), /* ~= 10^-133 */\n    U64(0xB5B5ADA8, 0xAAFF80B8), U64(0x0D819992, 0x132456BA), /* ~= 10^-132 */\n    U64(0xE3231912, 0xD5BF60E6), U64(0x10E1FFF6, 0x97ED6C69), /* ~= 10^-131 */\n    U64(0x8DF5EFAB, 0xC5979C8F), U64(0xCA8D3FFA, 0x1EF463C1), /* ~= 10^-130 */\n    U64(0xB1736B96, 0xB6FD83B3), U64(0xBD308FF8, 0xA6B17CB2), /* ~= 10^-129 */\n    U64(0xDDD0467C, 0x64BCE4A0), U64(0xAC7CB3F6, 0xD05DDBDE), /* ~= 10^-128 */\n    U64(0x8AA22C0D, 0xBEF60EE4), U64(0x6BCDF07A, 0x423AA96B), /* ~= 10^-127 */\n    U64(0xAD4AB711, 0x2EB3929D), U64(0x86C16C98, 0xD2C953C6), /* ~= 10^-126 */\n    U64(0xD89D64D5, 0x7A607744), U64(0xE871C7BF, 0x077BA8B7), /* ~= 10^-125 */\n    U64(0x87625F05, 0x6C7C4A8B), U64(0x11471CD7, 0x64AD4972), /* ~= 10^-124 */\n    U64(0xA93AF6C6, 0xC79B5D2D), U64(0xD598E40D, 0x3DD89BCF), /* ~= 10^-123 */\n    U64(0xD389B478, 0x79823479), U64(0x4AFF1D10, 0x8D4EC2C3), /* ~= 10^-122 */\n    U64(0x843610CB, 0x4BF160CB), U64(0xCEDF722A, 0x585139BA), /* ~= 10^-121 */\n    U64(0xA54394FE, 0x1EEDB8FE), U64(0xC2974EB4, 0xEE658828), /* ~= 10^-120 */\n    U64(0xCE947A3D, 0xA6A9273E), U64(0x733D2262, 0x29FEEA32), /* ~= 10^-119 */\n    U64(0x811CCC66, 0x8829B887), U64(0x0806357D, 0x5A3F525F), /* ~= 10^-118 */\n    U64(0xA163FF80, 0x2A3426A8), U64(0xCA07C2DC, 0xB0CF26F7), /* ~= 10^-117 */\n    U64(0xC9BCFF60, 0x34C13052), U64(0xFC89B393, 0xDD02F0B5), /* ~= 10^-116 */\n    U64(0xFC2C3F38, 0x41F17C67), U64(0xBBAC2078, 0xD443ACE2), /* ~= 10^-115 */\n    U64(0x9D9BA783, 0x2936EDC0), U64(0xD54B944B, 0x84AA4C0D), /* ~= 10^-114 */\n    U64(0xC5029163, 0xF384A931), U64(0x0A9E795E, 0x65D4DF11), /* ~= 10^-113 */\n    U64(0xF64335BC, 0xF065D37D), U64(0x4D4617B5, 0xFF4A16D5), /* ~= 10^-112 */\n    U64(0x99EA0196, 0x163FA42E), U64(0x504BCED1, 0xBF8E4E45), /* ~= 10^-111 */\n    U64(0xC06481FB, 0x9BCF8D39), U64(0xE45EC286, 0x2F71E1D6), /* ~= 10^-110 */\n    U64(0xF07DA27A, 0x82C37088), U64(0x5D767327, 0xBB4E5A4C), /* ~= 10^-109 */\n    U64(0x964E858C, 0x91BA2655), U64(0x3A6A07F8, 0xD510F86F), /* ~= 10^-108 */\n    U64(0xBBE226EF, 0xB628AFEA), U64(0x890489F7, 0x0A55368B), /* ~= 10^-107 */\n    U64(0xEADAB0AB, 0xA3B2DBE5), U64(0x2B45AC74, 0xCCEA842E), /* ~= 10^-106 */\n    U64(0x92C8AE6B, 0x464FC96F), U64(0x3B0B8BC9, 0x0012929D), /* ~= 10^-105 */\n    U64(0xB77ADA06, 0x17E3BBCB), U64(0x09CE6EBB, 0x40173744), /* ~= 10^-104 */\n    U64(0xE5599087, 0x9DDCAABD), U64(0xCC420A6A, 0x101D0515), /* ~= 10^-103 */\n    U64(0x8F57FA54, 0xC2A9EAB6), U64(0x9FA94682, 0x4A12232D), /* ~= 10^-102 */\n    U64(0xB32DF8E9, 0xF3546564), U64(0x47939822, 0xDC96ABF9), /* ~= 10^-101 */\n    U64(0xDFF97724, 0x70297EBD), U64(0x59787E2B, 0x93BC56F7), /* ~= 10^-100 */\n    U64(0x8BFBEA76, 0xC619EF36), U64(0x57EB4EDB, 0x3C55B65A), /* ~= 10^-99 */\n    U64(0xAEFAE514, 0x77A06B03), U64(0xEDE62292, 0x0B6B23F1), /* ~= 10^-98 */\n    U64(0xDAB99E59, 0x958885C4), U64(0xE95FAB36, 0x8E45ECED), /* ~= 10^-97 */\n    U64(0x88B402F7, 0xFD75539B), U64(0x11DBCB02, 0x18EBB414), /* ~= 10^-96 */\n    U64(0xAAE103B5, 0xFCD2A881), U64(0xD652BDC2, 0x9F26A119), /* ~= 10^-95 */\n    U64(0xD59944A3, 0x7C0752A2), U64(0x4BE76D33, 0x46F0495F), /* ~= 10^-94 */\n    U64(0x857FCAE6, 0x2D8493A5), U64(0x6F70A440, 0x0C562DDB), /* ~= 10^-93 */\n    U64(0xA6DFBD9F, 0xB8E5B88E), U64(0xCB4CCD50, 0x0F6BB952), /* ~= 10^-92 */\n    U64(0xD097AD07, 0xA71F26B2), U64(0x7E2000A4, 0x1346A7A7), /* ~= 10^-91 */\n    U64(0x825ECC24, 0xC873782F), U64(0x8ED40066, 0x8C0C28C8), /* ~= 10^-90 */\n    U64(0xA2F67F2D, 0xFA90563B), U64(0x72890080, 0x2F0F32FA), /* ~= 10^-89 */\n    U64(0xCBB41EF9, 0x79346BCA), U64(0x4F2B40A0, 0x3AD2FFB9), /* ~= 10^-88 */\n    U64(0xFEA126B7, 0xD78186BC), U64(0xE2F610C8, 0x4987BFA8), /* ~= 10^-87 */\n    U64(0x9F24B832, 0xE6B0F436), U64(0x0DD9CA7D, 0x2DF4D7C9), /* ~= 10^-86 */\n    U64(0xC6EDE63F, 0xA05D3143), U64(0x91503D1C, 0x79720DBB), /* ~= 10^-85 */\n    U64(0xF8A95FCF, 0x88747D94), U64(0x75A44C63, 0x97CE912A), /* ~= 10^-84 */\n    U64(0x9B69DBE1, 0xB548CE7C), U64(0xC986AFBE, 0x3EE11ABA), /* ~= 10^-83 */\n    U64(0xC24452DA, 0x229B021B), U64(0xFBE85BAD, 0xCE996168), /* ~= 10^-82 */\n    U64(0xF2D56790, 0xAB41C2A2), U64(0xFAE27299, 0x423FB9C3), /* ~= 10^-81 */\n    U64(0x97C560BA, 0x6B0919A5), U64(0xDCCD879F, 0xC967D41A), /* ~= 10^-80 */\n    U64(0xBDB6B8E9, 0x05CB600F), U64(0x5400E987, 0xBBC1C920), /* ~= 10^-79 */\n    U64(0xED246723, 0x473E3813), U64(0x290123E9, 0xAAB23B68), /* ~= 10^-78 */\n    U64(0x9436C076, 0x0C86E30B), U64(0xF9A0B672, 0x0AAF6521), /* ~= 10^-77 */\n    U64(0xB9447093, 0x8FA89BCE), U64(0xF808E40E, 0x8D5B3E69), /* ~= 10^-76 */\n    U64(0xE7958CB8, 0x7392C2C2), U64(0xB60B1D12, 0x30B20E04), /* ~= 10^-75 */\n    U64(0x90BD77F3, 0x483BB9B9), U64(0xB1C6F22B, 0x5E6F48C2), /* ~= 10^-74 */\n    U64(0xB4ECD5F0, 0x1A4AA828), U64(0x1E38AEB6, 0x360B1AF3), /* ~= 10^-73 */\n    U64(0xE2280B6C, 0x20DD5232), U64(0x25C6DA63, 0xC38DE1B0), /* ~= 10^-72 */\n    U64(0x8D590723, 0x948A535F), U64(0x579C487E, 0x5A38AD0E), /* ~= 10^-71 */\n    U64(0xB0AF48EC, 0x79ACE837), U64(0x2D835A9D, 0xF0C6D851), /* ~= 10^-70 */\n    U64(0xDCDB1B27, 0x98182244), U64(0xF8E43145, 0x6CF88E65), /* ~= 10^-69 */\n    U64(0x8A08F0F8, 0xBF0F156B), U64(0x1B8E9ECB, 0x641B58FF), /* ~= 10^-68 */\n    U64(0xAC8B2D36, 0xEED2DAC5), U64(0xE272467E, 0x3D222F3F), /* ~= 10^-67 */\n    U64(0xD7ADF884, 0xAA879177), U64(0x5B0ED81D, 0xCC6ABB0F), /* ~= 10^-66 */\n    U64(0x86CCBB52, 0xEA94BAEA), U64(0x98E94712, 0x9FC2B4E9), /* ~= 10^-65 */\n    U64(0xA87FEA27, 0xA539E9A5), U64(0x3F2398D7, 0x47B36224), /* ~= 10^-64 */\n    U64(0xD29FE4B1, 0x8E88640E), U64(0x8EEC7F0D, 0x19A03AAD), /* ~= 10^-63 */\n    U64(0x83A3EEEE, 0xF9153E89), U64(0x1953CF68, 0x300424AC), /* ~= 10^-62 */\n    U64(0xA48CEAAA, 0xB75A8E2B), U64(0x5FA8C342, 0x3C052DD7), /* ~= 10^-61 */\n    U64(0xCDB02555, 0x653131B6), U64(0x3792F412, 0xCB06794D), /* ~= 10^-60 */\n    U64(0x808E1755, 0x5F3EBF11), U64(0xE2BBD88B, 0xBEE40BD0), /* ~= 10^-59 */\n    U64(0xA0B19D2A, 0xB70E6ED6), U64(0x5B6ACEAE, 0xAE9D0EC4), /* ~= 10^-58 */\n    U64(0xC8DE0475, 0x64D20A8B), U64(0xF245825A, 0x5A445275), /* ~= 10^-57 */\n    U64(0xFB158592, 0xBE068D2E), U64(0xEED6E2F0, 0xF0D56712), /* ~= 10^-56 */\n    U64(0x9CED737B, 0xB6C4183D), U64(0x55464DD6, 0x9685606B), /* ~= 10^-55 */\n    U64(0xC428D05A, 0xA4751E4C), U64(0xAA97E14C, 0x3C26B886), /* ~= 10^-54 */\n    U64(0xF5330471, 0x4D9265DF), U64(0xD53DD99F, 0x4B3066A8), /* ~= 10^-53 */\n    U64(0x993FE2C6, 0xD07B7FAB), U64(0xE546A803, 0x8EFE4029), /* ~= 10^-52 */\n    U64(0xBF8FDB78, 0x849A5F96), U64(0xDE985204, 0x72BDD033), /* ~= 10^-51 */\n    U64(0xEF73D256, 0xA5C0F77C), U64(0x963E6685, 0x8F6D4440), /* ~= 10^-50 */\n    U64(0x95A86376, 0x27989AAD), U64(0xDDE70013, 0x79A44AA8), /* ~= 10^-49 */\n    U64(0xBB127C53, 0xB17EC159), U64(0x5560C018, 0x580D5D52), /* ~= 10^-48 */\n    U64(0xE9D71B68, 0x9DDE71AF), U64(0xAAB8F01E, 0x6E10B4A6), /* ~= 10^-47 */\n    U64(0x92267121, 0x62AB070D), U64(0xCAB39613, 0x04CA70E8), /* ~= 10^-46 */\n    U64(0xB6B00D69, 0xBB55C8D1), U64(0x3D607B97, 0xC5FD0D22), /* ~= 10^-45 */\n    U64(0xE45C10C4, 0x2A2B3B05), U64(0x8CB89A7D, 0xB77C506A), /* ~= 10^-44 */\n    U64(0x8EB98A7A, 0x9A5B04E3), U64(0x77F3608E, 0x92ADB242), /* ~= 10^-43 */\n    U64(0xB267ED19, 0x40F1C61C), U64(0x55F038B2, 0x37591ED3), /* ~= 10^-42 */\n    U64(0xDF01E85F, 0x912E37A3), U64(0x6B6C46DE, 0xC52F6688), /* ~= 10^-41 */\n    U64(0x8B61313B, 0xBABCE2C6), U64(0x2323AC4B, 0x3B3DA015), /* ~= 10^-40 */\n    U64(0xAE397D8A, 0xA96C1B77), U64(0xABEC975E, 0x0A0D081A), /* ~= 10^-39 */\n    U64(0xD9C7DCED, 0x53C72255), U64(0x96E7BD35, 0x8C904A21), /* ~= 10^-38 */\n    U64(0x881CEA14, 0x545C7575), U64(0x7E50D641, 0x77DA2E54), /* ~= 10^-37 */\n    U64(0xAA242499, 0x697392D2), U64(0xDDE50BD1, 0xD5D0B9E9), /* ~= 10^-36 */\n    U64(0xD4AD2DBF, 0xC3D07787), U64(0x955E4EC6, 0x4B44E864), /* ~= 10^-35 */\n    U64(0x84EC3C97, 0xDA624AB4), U64(0xBD5AF13B, 0xEF0B113E), /* ~= 10^-34 */\n    U64(0xA6274BBD, 0xD0FADD61), U64(0xECB1AD8A, 0xEACDD58E), /* ~= 10^-33 */\n    U64(0xCFB11EAD, 0x453994BA), U64(0x67DE18ED, 0xA5814AF2), /* ~= 10^-32 */\n    U64(0x81CEB32C, 0x4B43FCF4), U64(0x80EACF94, 0x8770CED7), /* ~= 10^-31 */\n    U64(0xA2425FF7, 0x5E14FC31), U64(0xA1258379, 0xA94D028D), /* ~= 10^-30 */\n    U64(0xCAD2F7F5, 0x359A3B3E), U64(0x096EE458, 0x13A04330), /* ~= 10^-29 */\n    U64(0xFD87B5F2, 0x8300CA0D), U64(0x8BCA9D6E, 0x188853FC), /* ~= 10^-28 */\n    U64(0x9E74D1B7, 0x91E07E48), U64(0x775EA264, 0xCF55347D), /* ~= 10^-27 */\n    U64(0xC6120625, 0x76589DDA), U64(0x95364AFE, 0x032A819D), /* ~= 10^-26 */\n    U64(0xF79687AE, 0xD3EEC551), U64(0x3A83DDBD, 0x83F52204), /* ~= 10^-25 */\n    U64(0x9ABE14CD, 0x44753B52), U64(0xC4926A96, 0x72793542), /* ~= 10^-24 */\n    U64(0xC16D9A00, 0x95928A27), U64(0x75B7053C, 0x0F178293), /* ~= 10^-23 */\n    U64(0xF1C90080, 0xBAF72CB1), U64(0x5324C68B, 0x12DD6338), /* ~= 10^-22 */\n    U64(0x971DA050, 0x74DA7BEE), U64(0xD3F6FC16, 0xEBCA5E03), /* ~= 10^-21 */\n    U64(0xBCE50864, 0x92111AEA), U64(0x88F4BB1C, 0xA6BCF584), /* ~= 10^-20 */\n    U64(0xEC1E4A7D, 0xB69561A5), U64(0x2B31E9E3, 0xD06C32E5), /* ~= 10^-19 */\n    U64(0x9392EE8E, 0x921D5D07), U64(0x3AFF322E, 0x62439FCF), /* ~= 10^-18 */\n    U64(0xB877AA32, 0x36A4B449), U64(0x09BEFEB9, 0xFAD487C2), /* ~= 10^-17 */\n    U64(0xE69594BE, 0xC44DE15B), U64(0x4C2EBE68, 0x7989A9B3), /* ~= 10^-16 */\n    U64(0x901D7CF7, 0x3AB0ACD9), U64(0x0F9D3701, 0x4BF60A10), /* ~= 10^-15 */\n    U64(0xB424DC35, 0x095CD80F), U64(0x538484C1, 0x9EF38C94), /* ~= 10^-14 */\n    U64(0xE12E1342, 0x4BB40E13), U64(0x2865A5F2, 0x06B06FB9), /* ~= 10^-13 */\n    U64(0x8CBCCC09, 0x6F5088CB), U64(0xF93F87B7, 0x442E45D3), /* ~= 10^-12 */\n    U64(0xAFEBFF0B, 0xCB24AAFE), U64(0xF78F69A5, 0x1539D748), /* ~= 10^-11 */\n    U64(0xDBE6FECE, 0xBDEDD5BE), U64(0xB573440E, 0x5A884D1B), /* ~= 10^-10 */\n    U64(0x89705F41, 0x36B4A597), U64(0x31680A88, 0xF8953030), /* ~= 10^-9 */\n    U64(0xABCC7711, 0x8461CEFC), U64(0xFDC20D2B, 0x36BA7C3D), /* ~= 10^-8 */\n    U64(0xD6BF94D5, 0xE57A42BC), U64(0x3D329076, 0x04691B4C), /* ~= 10^-7 */\n    U64(0x8637BD05, 0xAF6C69B5), U64(0xA63F9A49, 0xC2C1B10F), /* ~= 10^-6 */\n    U64(0xA7C5AC47, 0x1B478423), U64(0x0FCF80DC, 0x33721D53), /* ~= 10^-5 */\n    U64(0xD1B71758, 0xE219652B), U64(0xD3C36113, 0x404EA4A8), /* ~= 10^-4 */\n    U64(0x83126E97, 0x8D4FDF3B), U64(0x645A1CAC, 0x083126E9), /* ~= 10^-3 */\n    U64(0xA3D70A3D, 0x70A3D70A), U64(0x3D70A3D7, 0x0A3D70A3), /* ~= 10^-2 */\n    U64(0xCCCCCCCC, 0xCCCCCCCC), U64(0xCCCCCCCC, 0xCCCCCCCC), /* ~= 10^-1 */\n    U64(0x80000000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^0 */\n    U64(0xA0000000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^1 */\n    U64(0xC8000000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^2 */\n    U64(0xFA000000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^3 */\n    U64(0x9C400000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^4 */\n    U64(0xC3500000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^5 */\n    U64(0xF4240000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^6 */\n    U64(0x98968000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^7 */\n    U64(0xBEBC2000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^8 */\n    U64(0xEE6B2800, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^9 */\n    U64(0x9502F900, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^10 */\n    U64(0xBA43B740, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^11 */\n    U64(0xE8D4A510, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^12 */\n    U64(0x9184E72A, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^13 */\n    U64(0xB5E620F4, 0x80000000), U64(0x00000000, 0x00000000), /* == 10^14 */\n    U64(0xE35FA931, 0xA0000000), U64(0x00000000, 0x00000000), /* == 10^15 */\n    U64(0x8E1BC9BF, 0x04000000), U64(0x00000000, 0x00000000), /* == 10^16 */\n    U64(0xB1A2BC2E, 0xC5000000), U64(0x00000000, 0x00000000), /* == 10^17 */\n    U64(0xDE0B6B3A, 0x76400000), U64(0x00000000, 0x00000000), /* == 10^18 */\n    U64(0x8AC72304, 0x89E80000), U64(0x00000000, 0x00000000), /* == 10^19 */\n    U64(0xAD78EBC5, 0xAC620000), U64(0x00000000, 0x00000000), /* == 10^20 */\n    U64(0xD8D726B7, 0x177A8000), U64(0x00000000, 0x00000000), /* == 10^21 */\n    U64(0x87867832, 0x6EAC9000), U64(0x00000000, 0x00000000), /* == 10^22 */\n    U64(0xA968163F, 0x0A57B400), U64(0x00000000, 0x00000000), /* == 10^23 */\n    U64(0xD3C21BCE, 0xCCEDA100), U64(0x00000000, 0x00000000), /* == 10^24 */\n    U64(0x84595161, 0x401484A0), U64(0x00000000, 0x00000000), /* == 10^25 */\n    U64(0xA56FA5B9, 0x9019A5C8), U64(0x00000000, 0x00000000), /* == 10^26 */\n    U64(0xCECB8F27, 0xF4200F3A), U64(0x00000000, 0x00000000), /* == 10^27 */\n    U64(0x813F3978, 0xF8940984), U64(0x40000000, 0x00000000), /* == 10^28 */\n    U64(0xA18F07D7, 0x36B90BE5), U64(0x50000000, 0x00000000), /* == 10^29 */\n    U64(0xC9F2C9CD, 0x04674EDE), U64(0xA4000000, 0x00000000), /* == 10^30 */\n    U64(0xFC6F7C40, 0x45812296), U64(0x4D000000, 0x00000000), /* == 10^31 */\n    U64(0x9DC5ADA8, 0x2B70B59D), U64(0xF0200000, 0x00000000), /* == 10^32 */\n    U64(0xC5371912, 0x364CE305), U64(0x6C280000, 0x00000000), /* == 10^33 */\n    U64(0xF684DF56, 0xC3E01BC6), U64(0xC7320000, 0x00000000), /* == 10^34 */\n    U64(0x9A130B96, 0x3A6C115C), U64(0x3C7F4000, 0x00000000), /* == 10^35 */\n    U64(0xC097CE7B, 0xC90715B3), U64(0x4B9F1000, 0x00000000), /* == 10^36 */\n    U64(0xF0BDC21A, 0xBB48DB20), U64(0x1E86D400, 0x00000000), /* == 10^37 */\n    U64(0x96769950, 0xB50D88F4), U64(0x13144480, 0x00000000), /* == 10^38 */\n    U64(0xBC143FA4, 0xE250EB31), U64(0x17D955A0, 0x00000000), /* == 10^39 */\n    U64(0xEB194F8E, 0x1AE525FD), U64(0x5DCFAB08, 0x00000000), /* == 10^40 */\n    U64(0x92EFD1B8, 0xD0CF37BE), U64(0x5AA1CAE5, 0x00000000), /* == 10^41 */\n    U64(0xB7ABC627, 0x050305AD), U64(0xF14A3D9E, 0x40000000), /* == 10^42 */\n    U64(0xE596B7B0, 0xC643C719), U64(0x6D9CCD05, 0xD0000000), /* == 10^43 */\n    U64(0x8F7E32CE, 0x7BEA5C6F), U64(0xE4820023, 0xA2000000), /* == 10^44 */\n    U64(0xB35DBF82, 0x1AE4F38B), U64(0xDDA2802C, 0x8A800000), /* == 10^45 */\n    U64(0xE0352F62, 0xA19E306E), U64(0xD50B2037, 0xAD200000), /* == 10^46 */\n    U64(0x8C213D9D, 0xA502DE45), U64(0x4526F422, 0xCC340000), /* == 10^47 */\n    U64(0xAF298D05, 0x0E4395D6), U64(0x9670B12B, 0x7F410000), /* == 10^48 */\n    U64(0xDAF3F046, 0x51D47B4C), U64(0x3C0CDD76, 0x5F114000), /* == 10^49 */\n    U64(0x88D8762B, 0xF324CD0F), U64(0xA5880A69, 0xFB6AC800), /* == 10^50 */\n    U64(0xAB0E93B6, 0xEFEE0053), U64(0x8EEA0D04, 0x7A457A00), /* == 10^51 */\n    U64(0xD5D238A4, 0xABE98068), U64(0x72A49045, 0x98D6D880), /* == 10^52 */\n    U64(0x85A36366, 0xEB71F041), U64(0x47A6DA2B, 0x7F864750), /* == 10^53 */\n    U64(0xA70C3C40, 0xA64E6C51), U64(0x999090B6, 0x5F67D924), /* == 10^54 */\n    U64(0xD0CF4B50, 0xCFE20765), U64(0xFFF4B4E3, 0xF741CF6D), /* == 10^55 */\n    U64(0x82818F12, 0x81ED449F), U64(0xBFF8F10E, 0x7A8921A4), /* ~= 10^56 */\n    U64(0xA321F2D7, 0x226895C7), U64(0xAFF72D52, 0x192B6A0D), /* ~= 10^57 */\n    U64(0xCBEA6F8C, 0xEB02BB39), U64(0x9BF4F8A6, 0x9F764490), /* ~= 10^58 */\n    U64(0xFEE50B70, 0x25C36A08), U64(0x02F236D0, 0x4753D5B4), /* ~= 10^59 */\n    U64(0x9F4F2726, 0x179A2245), U64(0x01D76242, 0x2C946590), /* ~= 10^60 */\n    U64(0xC722F0EF, 0x9D80AAD6), U64(0x424D3AD2, 0xB7B97EF5), /* ~= 10^61 */\n    U64(0xF8EBAD2B, 0x84E0D58B), U64(0xD2E08987, 0x65A7DEB2), /* ~= 10^62 */\n    U64(0x9B934C3B, 0x330C8577), U64(0x63CC55F4, 0x9F88EB2F), /* ~= 10^63 */\n    U64(0xC2781F49, 0xFFCFA6D5), U64(0x3CBF6B71, 0xC76B25FB), /* ~= 10^64 */\n    U64(0xF316271C, 0x7FC3908A), U64(0x8BEF464E, 0x3945EF7A), /* ~= 10^65 */\n    U64(0x97EDD871, 0xCFDA3A56), U64(0x97758BF0, 0xE3CBB5AC), /* ~= 10^66 */\n    U64(0xBDE94E8E, 0x43D0C8EC), U64(0x3D52EEED, 0x1CBEA317), /* ~= 10^67 */\n    U64(0xED63A231, 0xD4C4FB27), U64(0x4CA7AAA8, 0x63EE4BDD), /* ~= 10^68 */\n    U64(0x945E455F, 0x24FB1CF8), U64(0x8FE8CAA9, 0x3E74EF6A), /* ~= 10^69 */\n    U64(0xB975D6B6, 0xEE39E436), U64(0xB3E2FD53, 0x8E122B44), /* ~= 10^70 */\n    U64(0xE7D34C64, 0xA9C85D44), U64(0x60DBBCA8, 0x7196B616), /* ~= 10^71 */\n    U64(0x90E40FBE, 0xEA1D3A4A), U64(0xBC8955E9, 0x46FE31CD), /* ~= 10^72 */\n    U64(0xB51D13AE, 0xA4A488DD), U64(0x6BABAB63, 0x98BDBE41), /* ~= 10^73 */\n    U64(0xE264589A, 0x4DCDAB14), U64(0xC696963C, 0x7EED2DD1), /* ~= 10^74 */\n    U64(0x8D7EB760, 0x70A08AEC), U64(0xFC1E1DE5, 0xCF543CA2), /* ~= 10^75 */\n    U64(0xB0DE6538, 0x8CC8ADA8), U64(0x3B25A55F, 0x43294BCB), /* ~= 10^76 */\n    U64(0xDD15FE86, 0xAFFAD912), U64(0x49EF0EB7, 0x13F39EBE), /* ~= 10^77 */\n    U64(0x8A2DBF14, 0x2DFCC7AB), U64(0x6E356932, 0x6C784337), /* ~= 10^78 */\n    U64(0xACB92ED9, 0x397BF996), U64(0x49C2C37F, 0x07965404), /* ~= 10^79 */\n    U64(0xD7E77A8F, 0x87DAF7FB), U64(0xDC33745E, 0xC97BE906), /* ~= 10^80 */\n    U64(0x86F0AC99, 0xB4E8DAFD), U64(0x69A028BB, 0x3DED71A3), /* ~= 10^81 */\n    U64(0xA8ACD7C0, 0x222311BC), U64(0xC40832EA, 0x0D68CE0C), /* ~= 10^82 */\n    U64(0xD2D80DB0, 0x2AABD62B), U64(0xF50A3FA4, 0x90C30190), /* ~= 10^83 */\n    U64(0x83C7088E, 0x1AAB65DB), U64(0x792667C6, 0xDA79E0FA), /* ~= 10^84 */\n    U64(0xA4B8CAB1, 0xA1563F52), U64(0x577001B8, 0x91185938), /* ~= 10^85 */\n    U64(0xCDE6FD5E, 0x09ABCF26), U64(0xED4C0226, 0xB55E6F86), /* ~= 10^86 */\n    U64(0x80B05E5A, 0xC60B6178), U64(0x544F8158, 0x315B05B4), /* ~= 10^87 */\n    U64(0xA0DC75F1, 0x778E39D6), U64(0x696361AE, 0x3DB1C721), /* ~= 10^88 */\n    U64(0xC913936D, 0xD571C84C), U64(0x03BC3A19, 0xCD1E38E9), /* ~= 10^89 */\n    U64(0xFB587849, 0x4ACE3A5F), U64(0x04AB48A0, 0x4065C723), /* ~= 10^90 */\n    U64(0x9D174B2D, 0xCEC0E47B), U64(0x62EB0D64, 0x283F9C76), /* ~= 10^91 */\n    U64(0xC45D1DF9, 0x42711D9A), U64(0x3BA5D0BD, 0x324F8394), /* ~= 10^92 */\n    U64(0xF5746577, 0x930D6500), U64(0xCA8F44EC, 0x7EE36479), /* ~= 10^93 */\n    U64(0x9968BF6A, 0xBBE85F20), U64(0x7E998B13, 0xCF4E1ECB), /* ~= 10^94 */\n    U64(0xBFC2EF45, 0x6AE276E8), U64(0x9E3FEDD8, 0xC321A67E), /* ~= 10^95 */\n    U64(0xEFB3AB16, 0xC59B14A2), U64(0xC5CFE94E, 0xF3EA101E), /* ~= 10^96 */\n    U64(0x95D04AEE, 0x3B80ECE5), U64(0xBBA1F1D1, 0x58724A12), /* ~= 10^97 */\n    U64(0xBB445DA9, 0xCA61281F), U64(0x2A8A6E45, 0xAE8EDC97), /* ~= 10^98 */\n    U64(0xEA157514, 0x3CF97226), U64(0xF52D09D7, 0x1A3293BD), /* ~= 10^99 */\n    U64(0x924D692C, 0xA61BE758), U64(0x593C2626, 0x705F9C56), /* ~= 10^100 */\n    U64(0xB6E0C377, 0xCFA2E12E), U64(0x6F8B2FB0, 0x0C77836C), /* ~= 10^101 */\n    U64(0xE498F455, 0xC38B997A), U64(0x0B6DFB9C, 0x0F956447), /* ~= 10^102 */\n    U64(0x8EDF98B5, 0x9A373FEC), U64(0x4724BD41, 0x89BD5EAC), /* ~= 10^103 */\n    U64(0xB2977EE3, 0x00C50FE7), U64(0x58EDEC91, 0xEC2CB657), /* ~= 10^104 */\n    U64(0xDF3D5E9B, 0xC0F653E1), U64(0x2F2967B6, 0x6737E3ED), /* ~= 10^105 */\n    U64(0x8B865B21, 0x5899F46C), U64(0xBD79E0D2, 0x0082EE74), /* ~= 10^106 */\n    U64(0xAE67F1E9, 0xAEC07187), U64(0xECD85906, 0x80A3AA11), /* ~= 10^107 */\n    U64(0xDA01EE64, 0x1A708DE9), U64(0xE80E6F48, 0x20CC9495), /* ~= 10^108 */\n    U64(0x884134FE, 0x908658B2), U64(0x3109058D, 0x147FDCDD), /* ~= 10^109 */\n    U64(0xAA51823E, 0x34A7EEDE), U64(0xBD4B46F0, 0x599FD415), /* ~= 10^110 */\n    U64(0xD4E5E2CD, 0xC1D1EA96), U64(0x6C9E18AC, 0x7007C91A), /* ~= 10^111 */\n    U64(0x850FADC0, 0x9923329E), U64(0x03E2CF6B, 0xC604DDB0), /* ~= 10^112 */\n    U64(0xA6539930, 0xBF6BFF45), U64(0x84DB8346, 0xB786151C), /* ~= 10^113 */\n    U64(0xCFE87F7C, 0xEF46FF16), U64(0xE6126418, 0x65679A63), /* ~= 10^114 */\n    U64(0x81F14FAE, 0x158C5F6E), U64(0x4FCB7E8F, 0x3F60C07E), /* ~= 10^115 */\n    U64(0xA26DA399, 0x9AEF7749), U64(0xE3BE5E33, 0x0F38F09D), /* ~= 10^116 */\n    U64(0xCB090C80, 0x01AB551C), U64(0x5CADF5BF, 0xD3072CC5), /* ~= 10^117 */\n    U64(0xFDCB4FA0, 0x02162A63), U64(0x73D9732F, 0xC7C8F7F6), /* ~= 10^118 */\n    U64(0x9E9F11C4, 0x014DDA7E), U64(0x2867E7FD, 0xDCDD9AFA), /* ~= 10^119 */\n    U64(0xC646D635, 0x01A1511D), U64(0xB281E1FD, 0x541501B8), /* ~= 10^120 */\n    U64(0xF7D88BC2, 0x4209A565), U64(0x1F225A7C, 0xA91A4226), /* ~= 10^121 */\n    U64(0x9AE75759, 0x6946075F), U64(0x3375788D, 0xE9B06958), /* ~= 10^122 */\n    U64(0xC1A12D2F, 0xC3978937), U64(0x0052D6B1, 0x641C83AE), /* ~= 10^123 */\n    U64(0xF209787B, 0xB47D6B84), U64(0xC0678C5D, 0xBD23A49A), /* ~= 10^124 */\n    U64(0x9745EB4D, 0x50CE6332), U64(0xF840B7BA, 0x963646E0), /* ~= 10^125 */\n    U64(0xBD176620, 0xA501FBFF), U64(0xB650E5A9, 0x3BC3D898), /* ~= 10^126 */\n    U64(0xEC5D3FA8, 0xCE427AFF), U64(0xA3E51F13, 0x8AB4CEBE), /* ~= 10^127 */\n    U64(0x93BA47C9, 0x80E98CDF), U64(0xC66F336C, 0x36B10137), /* ~= 10^128 */\n    U64(0xB8A8D9BB, 0xE123F017), U64(0xB80B0047, 0x445D4184), /* ~= 10^129 */\n    U64(0xE6D3102A, 0xD96CEC1D), U64(0xA60DC059, 0x157491E5), /* ~= 10^130 */\n    U64(0x9043EA1A, 0xC7E41392), U64(0x87C89837, 0xAD68DB2F), /* ~= 10^131 */\n    U64(0xB454E4A1, 0x79DD1877), U64(0x29BABE45, 0x98C311FB), /* ~= 10^132 */\n    U64(0xE16A1DC9, 0xD8545E94), U64(0xF4296DD6, 0xFEF3D67A), /* ~= 10^133 */\n    U64(0x8CE2529E, 0x2734BB1D), U64(0x1899E4A6, 0x5F58660C), /* ~= 10^134 */\n    U64(0xB01AE745, 0xB101E9E4), U64(0x5EC05DCF, 0xF72E7F8F), /* ~= 10^135 */\n    U64(0xDC21A117, 0x1D42645D), U64(0x76707543, 0xF4FA1F73), /* ~= 10^136 */\n    U64(0x899504AE, 0x72497EBA), U64(0x6A06494A, 0x791C53A8), /* ~= 10^137 */\n    U64(0xABFA45DA, 0x0EDBDE69), U64(0x0487DB9D, 0x17636892), /* ~= 10^138 */\n    U64(0xD6F8D750, 0x9292D603), U64(0x45A9D284, 0x5D3C42B6), /* ~= 10^139 */\n    U64(0x865B8692, 0x5B9BC5C2), U64(0x0B8A2392, 0xBA45A9B2), /* ~= 10^140 */\n    U64(0xA7F26836, 0xF282B732), U64(0x8E6CAC77, 0x68D7141E), /* ~= 10^141 */\n    U64(0xD1EF0244, 0xAF2364FF), U64(0x3207D795, 0x430CD926), /* ~= 10^142 */\n    U64(0x8335616A, 0xED761F1F), U64(0x7F44E6BD, 0x49E807B8), /* ~= 10^143 */\n    U64(0xA402B9C5, 0xA8D3A6E7), U64(0x5F16206C, 0x9C6209A6), /* ~= 10^144 */\n    U64(0xCD036837, 0x130890A1), U64(0x36DBA887, 0xC37A8C0F), /* ~= 10^145 */\n    U64(0x80222122, 0x6BE55A64), U64(0xC2494954, 0xDA2C9789), /* ~= 10^146 */\n    U64(0xA02AA96B, 0x06DEB0FD), U64(0xF2DB9BAA, 0x10B7BD6C), /* ~= 10^147 */\n    U64(0xC83553C5, 0xC8965D3D), U64(0x6F928294, 0x94E5ACC7), /* ~= 10^148 */\n    U64(0xFA42A8B7, 0x3ABBF48C), U64(0xCB772339, 0xBA1F17F9), /* ~= 10^149 */\n    U64(0x9C69A972, 0x84B578D7), U64(0xFF2A7604, 0x14536EFB), /* ~= 10^150 */\n    U64(0xC38413CF, 0x25E2D70D), U64(0xFEF51385, 0x19684ABA), /* ~= 10^151 */\n    U64(0xF46518C2, 0xEF5B8CD1), U64(0x7EB25866, 0x5FC25D69), /* ~= 10^152 */\n    U64(0x98BF2F79, 0xD5993802), U64(0xEF2F773F, 0xFBD97A61), /* ~= 10^153 */\n    U64(0xBEEEFB58, 0x4AFF8603), U64(0xAAFB550F, 0xFACFD8FA), /* ~= 10^154 */\n    U64(0xEEAABA2E, 0x5DBF6784), U64(0x95BA2A53, 0xF983CF38), /* ~= 10^155 */\n    U64(0x952AB45C, 0xFA97A0B2), U64(0xDD945A74, 0x7BF26183), /* ~= 10^156 */\n    U64(0xBA756174, 0x393D88DF), U64(0x94F97111, 0x9AEEF9E4), /* ~= 10^157 */\n    U64(0xE912B9D1, 0x478CEB17), U64(0x7A37CD56, 0x01AAB85D), /* ~= 10^158 */\n    U64(0x91ABB422, 0xCCB812EE), U64(0xAC62E055, 0xC10AB33A), /* ~= 10^159 */\n    U64(0xB616A12B, 0x7FE617AA), U64(0x577B986B, 0x314D6009), /* ~= 10^160 */\n    U64(0xE39C4976, 0x5FDF9D94), U64(0xED5A7E85, 0xFDA0B80B), /* ~= 10^161 */\n    U64(0x8E41ADE9, 0xFBEBC27D), U64(0x14588F13, 0xBE847307), /* ~= 10^162 */\n    U64(0xB1D21964, 0x7AE6B31C), U64(0x596EB2D8, 0xAE258FC8), /* ~= 10^163 */\n    U64(0xDE469FBD, 0x99A05FE3), U64(0x6FCA5F8E, 0xD9AEF3BB), /* ~= 10^164 */\n    U64(0x8AEC23D6, 0x80043BEE), U64(0x25DE7BB9, 0x480D5854), /* ~= 10^165 */\n    U64(0xADA72CCC, 0x20054AE9), U64(0xAF561AA7, 0x9A10AE6A), /* ~= 10^166 */\n    U64(0xD910F7FF, 0x28069DA4), U64(0x1B2BA151, 0x8094DA04), /* ~= 10^167 */\n    U64(0x87AA9AFF, 0x79042286), U64(0x90FB44D2, 0xF05D0842), /* ~= 10^168 */\n    U64(0xA99541BF, 0x57452B28), U64(0x353A1607, 0xAC744A53), /* ~= 10^169 */\n    U64(0xD3FA922F, 0x2D1675F2), U64(0x42889B89, 0x97915CE8), /* ~= 10^170 */\n    U64(0x847C9B5D, 0x7C2E09B7), U64(0x69956135, 0xFEBADA11), /* ~= 10^171 */\n    U64(0xA59BC234, 0xDB398C25), U64(0x43FAB983, 0x7E699095), /* ~= 10^172 */\n    U64(0xCF02B2C2, 0x1207EF2E), U64(0x94F967E4, 0x5E03F4BB), /* ~= 10^173 */\n    U64(0x8161AFB9, 0x4B44F57D), U64(0x1D1BE0EE, 0xBAC278F5), /* ~= 10^174 */\n    U64(0xA1BA1BA7, 0x9E1632DC), U64(0x6462D92A, 0x69731732), /* ~= 10^175 */\n    U64(0xCA28A291, 0x859BBF93), U64(0x7D7B8F75, 0x03CFDCFE), /* ~= 10^176 */\n    U64(0xFCB2CB35, 0xE702AF78), U64(0x5CDA7352, 0x44C3D43E), /* ~= 10^177 */\n    U64(0x9DEFBF01, 0xB061ADAB), U64(0x3A088813, 0x6AFA64A7), /* ~= 10^178 */\n    U64(0xC56BAEC2, 0x1C7A1916), U64(0x088AAA18, 0x45B8FDD0), /* ~= 10^179 */\n    U64(0xF6C69A72, 0xA3989F5B), U64(0x8AAD549E, 0x57273D45), /* ~= 10^180 */\n    U64(0x9A3C2087, 0xA63F6399), U64(0x36AC54E2, 0xF678864B), /* ~= 10^181 */\n    U64(0xC0CB28A9, 0x8FCF3C7F), U64(0x84576A1B, 0xB416A7DD), /* ~= 10^182 */\n    U64(0xF0FDF2D3, 0xF3C30B9F), U64(0x656D44A2, 0xA11C51D5), /* ~= 10^183 */\n    U64(0x969EB7C4, 0x7859E743), U64(0x9F644AE5, 0xA4B1B325), /* ~= 10^184 */\n    U64(0xBC4665B5, 0x96706114), U64(0x873D5D9F, 0x0DDE1FEE), /* ~= 10^185 */\n    U64(0xEB57FF22, 0xFC0C7959), U64(0xA90CB506, 0xD155A7EA), /* ~= 10^186 */\n    U64(0x9316FF75, 0xDD87CBD8), U64(0x09A7F124, 0x42D588F2), /* ~= 10^187 */\n    U64(0xB7DCBF53, 0x54E9BECE), U64(0x0C11ED6D, 0x538AEB2F), /* ~= 10^188 */\n    U64(0xE5D3EF28, 0x2A242E81), U64(0x8F1668C8, 0xA86DA5FA), /* ~= 10^189 */\n    U64(0x8FA47579, 0x1A569D10), U64(0xF96E017D, 0x694487BC), /* ~= 10^190 */\n    U64(0xB38D92D7, 0x60EC4455), U64(0x37C981DC, 0xC395A9AC), /* ~= 10^191 */\n    U64(0xE070F78D, 0x3927556A), U64(0x85BBE253, 0xF47B1417), /* ~= 10^192 */\n    U64(0x8C469AB8, 0x43B89562), U64(0x93956D74, 0x78CCEC8E), /* ~= 10^193 */\n    U64(0xAF584166, 0x54A6BABB), U64(0x387AC8D1, 0x970027B2), /* ~= 10^194 */\n    U64(0xDB2E51BF, 0xE9D0696A), U64(0x06997B05, 0xFCC0319E), /* ~= 10^195 */\n    U64(0x88FCF317, 0xF22241E2), U64(0x441FECE3, 0xBDF81F03), /* ~= 10^196 */\n    U64(0xAB3C2FDD, 0xEEAAD25A), U64(0xD527E81C, 0xAD7626C3), /* ~= 10^197 */\n    U64(0xD60B3BD5, 0x6A5586F1), U64(0x8A71E223, 0xD8D3B074), /* ~= 10^198 */\n    U64(0x85C70565, 0x62757456), U64(0xF6872D56, 0x67844E49), /* ~= 10^199 */\n    U64(0xA738C6BE, 0xBB12D16C), U64(0xB428F8AC, 0x016561DB), /* ~= 10^200 */\n    U64(0xD106F86E, 0x69D785C7), U64(0xE13336D7, 0x01BEBA52), /* ~= 10^201 */\n    U64(0x82A45B45, 0x0226B39C), U64(0xECC00246, 0x61173473), /* ~= 10^202 */\n    U64(0xA34D7216, 0x42B06084), U64(0x27F002D7, 0xF95D0190), /* ~= 10^203 */\n    U64(0xCC20CE9B, 0xD35C78A5), U64(0x31EC038D, 0xF7B441F4), /* ~= 10^204 */\n    U64(0xFF290242, 0xC83396CE), U64(0x7E670471, 0x75A15271), /* ~= 10^205 */\n    U64(0x9F79A169, 0xBD203E41), U64(0x0F0062C6, 0xE984D386), /* ~= 10^206 */\n    U64(0xC75809C4, 0x2C684DD1), U64(0x52C07B78, 0xA3E60868), /* ~= 10^207 */\n    U64(0xF92E0C35, 0x37826145), U64(0xA7709A56, 0xCCDF8A82), /* ~= 10^208 */\n    U64(0x9BBCC7A1, 0x42B17CCB), U64(0x88A66076, 0x400BB691), /* ~= 10^209 */\n    U64(0xC2ABF989, 0x935DDBFE), U64(0x6ACFF893, 0xD00EA435), /* ~= 10^210 */\n    U64(0xF356F7EB, 0xF83552FE), U64(0x0583F6B8, 0xC4124D43), /* ~= 10^211 */\n    U64(0x98165AF3, 0x7B2153DE), U64(0xC3727A33, 0x7A8B704A), /* ~= 10^212 */\n    U64(0xBE1BF1B0, 0x59E9A8D6), U64(0x744F18C0, 0x592E4C5C), /* ~= 10^213 */\n    U64(0xEDA2EE1C, 0x7064130C), U64(0x1162DEF0, 0x6F79DF73), /* ~= 10^214 */\n    U64(0x9485D4D1, 0xC63E8BE7), U64(0x8ADDCB56, 0x45AC2BA8), /* ~= 10^215 */\n    U64(0xB9A74A06, 0x37CE2EE1), U64(0x6D953E2B, 0xD7173692), /* ~= 10^216 */\n    U64(0xE8111C87, 0xC5C1BA99), U64(0xC8FA8DB6, 0xCCDD0437), /* ~= 10^217 */\n    U64(0x910AB1D4, 0xDB9914A0), U64(0x1D9C9892, 0x400A22A2), /* ~= 10^218 */\n    U64(0xB54D5E4A, 0x127F59C8), U64(0x2503BEB6, 0xD00CAB4B), /* ~= 10^219 */\n    U64(0xE2A0B5DC, 0x971F303A), U64(0x2E44AE64, 0x840FD61D), /* ~= 10^220 */\n    U64(0x8DA471A9, 0xDE737E24), U64(0x5CEAECFE, 0xD289E5D2), /* ~= 10^221 */\n    U64(0xB10D8E14, 0x56105DAD), U64(0x7425A83E, 0x872C5F47), /* ~= 10^222 */\n    U64(0xDD50F199, 0x6B947518), U64(0xD12F124E, 0x28F77719), /* ~= 10^223 */\n    U64(0x8A5296FF, 0xE33CC92F), U64(0x82BD6B70, 0xD99AAA6F), /* ~= 10^224 */\n    U64(0xACE73CBF, 0xDC0BFB7B), U64(0x636CC64D, 0x1001550B), /* ~= 10^225 */\n    U64(0xD8210BEF, 0xD30EFA5A), U64(0x3C47F7E0, 0x5401AA4E), /* ~= 10^226 */\n    U64(0x8714A775, 0xE3E95C78), U64(0x65ACFAEC, 0x34810A71), /* ~= 10^227 */\n    U64(0xA8D9D153, 0x5CE3B396), U64(0x7F1839A7, 0x41A14D0D), /* ~= 10^228 */\n    U64(0xD31045A8, 0x341CA07C), U64(0x1EDE4811, 0x1209A050), /* ~= 10^229 */\n    U64(0x83EA2B89, 0x2091E44D), U64(0x934AED0A, 0xAB460432), /* ~= 10^230 */\n    U64(0xA4E4B66B, 0x68B65D60), U64(0xF81DA84D, 0x5617853F), /* ~= 10^231 */\n    U64(0xCE1DE406, 0x42E3F4B9), U64(0x36251260, 0xAB9D668E), /* ~= 10^232 */\n    U64(0x80D2AE83, 0xE9CE78F3), U64(0xC1D72B7C, 0x6B426019), /* ~= 10^233 */\n    U64(0xA1075A24, 0xE4421730), U64(0xB24CF65B, 0x8612F81F), /* ~= 10^234 */\n    U64(0xC94930AE, 0x1D529CFC), U64(0xDEE033F2, 0x6797B627), /* ~= 10^235 */\n    U64(0xFB9B7CD9, 0xA4A7443C), U64(0x169840EF, 0x017DA3B1), /* ~= 10^236 */\n    U64(0x9D412E08, 0x06E88AA5), U64(0x8E1F2895, 0x60EE864E), /* ~= 10^237 */\n    U64(0xC491798A, 0x08A2AD4E), U64(0xF1A6F2BA, 0xB92A27E2), /* ~= 10^238 */\n    U64(0xF5B5D7EC, 0x8ACB58A2), U64(0xAE10AF69, 0x6774B1DB), /* ~= 10^239 */\n    U64(0x9991A6F3, 0xD6BF1765), U64(0xACCA6DA1, 0xE0A8EF29), /* ~= 10^240 */\n    U64(0xBFF610B0, 0xCC6EDD3F), U64(0x17FD090A, 0x58D32AF3), /* ~= 10^241 */\n    U64(0xEFF394DC, 0xFF8A948E), U64(0xDDFC4B4C, 0xEF07F5B0), /* ~= 10^242 */\n    U64(0x95F83D0A, 0x1FB69CD9), U64(0x4ABDAF10, 0x1564F98E), /* ~= 10^243 */\n    U64(0xBB764C4C, 0xA7A4440F), U64(0x9D6D1AD4, 0x1ABE37F1), /* ~= 10^244 */\n    U64(0xEA53DF5F, 0xD18D5513), U64(0x84C86189, 0x216DC5ED), /* ~= 10^245 */\n    U64(0x92746B9B, 0xE2F8552C), U64(0x32FD3CF5, 0xB4E49BB4), /* ~= 10^246 */\n    U64(0xB7118682, 0xDBB66A77), U64(0x3FBC8C33, 0x221DC2A1), /* ~= 10^247 */\n    U64(0xE4D5E823, 0x92A40515), U64(0x0FABAF3F, 0xEAA5334A), /* ~= 10^248 */\n    U64(0x8F05B116, 0x3BA6832D), U64(0x29CB4D87, 0xF2A7400E), /* ~= 10^249 */\n    U64(0xB2C71D5B, 0xCA9023F8), U64(0x743E20E9, 0xEF511012), /* ~= 10^250 */\n    U64(0xDF78E4B2, 0xBD342CF6), U64(0x914DA924, 0x6B255416), /* ~= 10^251 */\n    U64(0x8BAB8EEF, 0xB6409C1A), U64(0x1AD089B6, 0xC2F7548E), /* ~= 10^252 */\n    U64(0xAE9672AB, 0xA3D0C320), U64(0xA184AC24, 0x73B529B1), /* ~= 10^253 */\n    U64(0xDA3C0F56, 0x8CC4F3E8), U64(0xC9E5D72D, 0x90A2741E), /* ~= 10^254 */\n    U64(0x88658996, 0x17FB1871), U64(0x7E2FA67C, 0x7A658892), /* ~= 10^255 */\n    U64(0xAA7EEBFB, 0x9DF9DE8D), U64(0xDDBB901B, 0x98FEEAB7), /* ~= 10^256 */\n    U64(0xD51EA6FA, 0x85785631), U64(0x552A7422, 0x7F3EA565), /* ~= 10^257 */\n    U64(0x8533285C, 0x936B35DE), U64(0xD53A8895, 0x8F87275F), /* ~= 10^258 */\n    U64(0xA67FF273, 0xB8460356), U64(0x8A892ABA, 0xF368F137), /* ~= 10^259 */\n    U64(0xD01FEF10, 0xA657842C), U64(0x2D2B7569, 0xB0432D85), /* ~= 10^260 */\n    U64(0x8213F56A, 0x67F6B29B), U64(0x9C3B2962, 0x0E29FC73), /* ~= 10^261 */\n    U64(0xA298F2C5, 0x01F45F42), U64(0x8349F3BA, 0x91B47B8F), /* ~= 10^262 */\n    U64(0xCB3F2F76, 0x42717713), U64(0x241C70A9, 0x36219A73), /* ~= 10^263 */\n    U64(0xFE0EFB53, 0xD30DD4D7), U64(0xED238CD3, 0x83AA0110), /* ~= 10^264 */\n    U64(0x9EC95D14, 0x63E8A506), U64(0xF4363804, 0x324A40AA), /* ~= 10^265 */\n    U64(0xC67BB459, 0x7CE2CE48), U64(0xB143C605, 0x3EDCD0D5), /* ~= 10^266 */\n    U64(0xF81AA16F, 0xDC1B81DA), U64(0xDD94B786, 0x8E94050A), /* ~= 10^267 */\n    U64(0x9B10A4E5, 0xE9913128), U64(0xCA7CF2B4, 0x191C8326), /* ~= 10^268 */\n    U64(0xC1D4CE1F, 0x63F57D72), U64(0xFD1C2F61, 0x1F63A3F0), /* ~= 10^269 */\n    U64(0xF24A01A7, 0x3CF2DCCF), U64(0xBC633B39, 0x673C8CEC), /* ~= 10^270 */\n    U64(0x976E4108, 0x8617CA01), U64(0xD5BE0503, 0xE085D813), /* ~= 10^271 */\n    U64(0xBD49D14A, 0xA79DBC82), U64(0x4B2D8644, 0xD8A74E18), /* ~= 10^272 */\n    U64(0xEC9C459D, 0x51852BA2), U64(0xDDF8E7D6, 0x0ED1219E), /* ~= 10^273 */\n    U64(0x93E1AB82, 0x52F33B45), U64(0xCABB90E5, 0xC942B503), /* ~= 10^274 */\n    U64(0xB8DA1662, 0xE7B00A17), U64(0x3D6A751F, 0x3B936243), /* ~= 10^275 */\n    U64(0xE7109BFB, 0xA19C0C9D), U64(0x0CC51267, 0x0A783AD4), /* ~= 10^276 */\n    U64(0x906A617D, 0x450187E2), U64(0x27FB2B80, 0x668B24C5), /* ~= 10^277 */\n    U64(0xB484F9DC, 0x9641E9DA), U64(0xB1F9F660, 0x802DEDF6), /* ~= 10^278 */\n    U64(0xE1A63853, 0xBBD26451), U64(0x5E7873F8, 0xA0396973), /* ~= 10^279 */\n    U64(0x8D07E334, 0x55637EB2), U64(0xDB0B487B, 0x6423E1E8), /* ~= 10^280 */\n    U64(0xB049DC01, 0x6ABC5E5F), U64(0x91CE1A9A, 0x3D2CDA62), /* ~= 10^281 */\n    U64(0xDC5C5301, 0xC56B75F7), U64(0x7641A140, 0xCC7810FB), /* ~= 10^282 */\n    U64(0x89B9B3E1, 0x1B6329BA), U64(0xA9E904C8, 0x7FCB0A9D), /* ~= 10^283 */\n    U64(0xAC2820D9, 0x623BF429), U64(0x546345FA, 0x9FBDCD44), /* ~= 10^284 */\n    U64(0xD732290F, 0xBACAF133), U64(0xA97C1779, 0x47AD4095), /* ~= 10^285 */\n    U64(0x867F59A9, 0xD4BED6C0), U64(0x49ED8EAB, 0xCCCC485D), /* ~= 10^286 */\n    U64(0xA81F3014, 0x49EE8C70), U64(0x5C68F256, 0xBFFF5A74), /* ~= 10^287 */\n    U64(0xD226FC19, 0x5C6A2F8C), U64(0x73832EEC, 0x6FFF3111), /* ~= 10^288 */\n    U64(0x83585D8F, 0xD9C25DB7), U64(0xC831FD53, 0xC5FF7EAB), /* ~= 10^289 */\n    U64(0xA42E74F3, 0xD032F525), U64(0xBA3E7CA8, 0xB77F5E55), /* ~= 10^290 */\n    U64(0xCD3A1230, 0xC43FB26F), U64(0x28CE1BD2, 0xE55F35EB), /* ~= 10^291 */\n    U64(0x80444B5E, 0x7AA7CF85), U64(0x7980D163, 0xCF5B81B3), /* ~= 10^292 */\n    U64(0xA0555E36, 0x1951C366), U64(0xD7E105BC, 0xC332621F), /* ~= 10^293 */\n    U64(0xC86AB5C3, 0x9FA63440), U64(0x8DD9472B, 0xF3FEFAA7), /* ~= 10^294 */\n    U64(0xFA856334, 0x878FC150), U64(0xB14F98F6, 0xF0FEB951), /* ~= 10^295 */\n    U64(0x9C935E00, 0xD4B9D8D2), U64(0x6ED1BF9A, 0x569F33D3), /* ~= 10^296 */\n    U64(0xC3B83581, 0x09E84F07), U64(0x0A862F80, 0xEC4700C8), /* ~= 10^297 */\n    U64(0xF4A642E1, 0x4C6262C8), U64(0xCD27BB61, 0x2758C0FA), /* ~= 10^298 */\n    U64(0x98E7E9CC, 0xCFBD7DBD), U64(0x8038D51C, 0xB897789C), /* ~= 10^299 */\n    U64(0xBF21E440, 0x03ACDD2C), U64(0xE0470A63, 0xE6BD56C3), /* ~= 10^300 */\n    U64(0xEEEA5D50, 0x04981478), U64(0x1858CCFC, 0xE06CAC74), /* ~= 10^301 */\n    U64(0x95527A52, 0x02DF0CCB), U64(0x0F37801E, 0x0C43EBC8), /* ~= 10^302 */\n    U64(0xBAA718E6, 0x8396CFFD), U64(0xD3056025, 0x8F54E6BA), /* ~= 10^303 */\n    U64(0xE950DF20, 0x247C83FD), U64(0x47C6B82E, 0xF32A2069), /* ~= 10^304 */\n    U64(0x91D28B74, 0x16CDD27E), U64(0x4CDC331D, 0x57FA5441), /* ~= 10^305 */\n    U64(0xB6472E51, 0x1C81471D), U64(0xE0133FE4, 0xADF8E952), /* ~= 10^306 */\n    U64(0xE3D8F9E5, 0x63A198E5), U64(0x58180FDD, 0xD97723A6), /* ~= 10^307 */\n    U64(0x8E679C2F, 0x5E44FF8F), U64(0x570F09EA, 0xA7EA7648), /* ~= 10^308 */\n    U64(0xB201833B, 0x35D63F73), U64(0x2CD2CC65, 0x51E513DA), /* ~= 10^309 */\n    U64(0xDE81E40A, 0x034BCF4F), U64(0xF8077F7E, 0xA65E58D1), /* ~= 10^310 */\n    U64(0x8B112E86, 0x420F6191), U64(0xFB04AFAF, 0x27FAF782), /* ~= 10^311 */\n    U64(0xADD57A27, 0xD29339F6), U64(0x79C5DB9A, 0xF1F9B563), /* ~= 10^312 */\n    U64(0xD94AD8B1, 0xC7380874), U64(0x18375281, 0xAE7822BC), /* ~= 10^313 */\n    U64(0x87CEC76F, 0x1C830548), U64(0x8F229391, 0x0D0B15B5), /* ~= 10^314 */\n    U64(0xA9C2794A, 0xE3A3C69A), U64(0xB2EB3875, 0x504DDB22), /* ~= 10^315 */\n    U64(0xD433179D, 0x9C8CB841), U64(0x5FA60692, 0xA46151EB), /* ~= 10^316 */\n    U64(0x849FEEC2, 0x81D7F328), U64(0xDBC7C41B, 0xA6BCD333), /* ~= 10^317 */\n    U64(0xA5C7EA73, 0x224DEFF3), U64(0x12B9B522, 0x906C0800), /* ~= 10^318 */\n    U64(0xCF39E50F, 0xEAE16BEF), U64(0xD768226B, 0x34870A00), /* ~= 10^319 */\n    U64(0x81842F29, 0xF2CCE375), U64(0xE6A11583, 0x00D46640), /* ~= 10^320 */\n    U64(0xA1E53AF4, 0x6F801C53), U64(0x60495AE3, 0xC1097FD0), /* ~= 10^321 */\n    U64(0xCA5E89B1, 0x8B602368), U64(0x385BB19C, 0xB14BDFC4), /* ~= 10^322 */\n    U64(0xFCF62C1D, 0xEE382C42), U64(0x46729E03, 0xDD9ED7B5), /* ~= 10^323 */\n    U64(0x9E19DB92, 0xB4E31BA9), U64(0x6C07A2C2, 0x6A8346D1)  /* ~= 10^324 */\n};\n\n/**\n Get the cached pow10 value from pow10_sig_table.\n @param exp10 The exponent of pow(10, e). This value must in range\n              POW10_SIG_TABLE_MIN_EXP to POW10_SIG_TABLE_MAX_EXP.\n @param hi    The highest 64 bits of pow(10, e).\n @param lo    The lower 64 bits after `hi`.\n */\nstatic_inline void pow10_table_get_sig(i32 exp10, u64 *hi, u64 *lo) {\n    i32 idx = exp10 - (POW10_SIG_TABLE_MIN_EXP);\n    *hi = pow10_sig_table[idx * 2];\n    *lo = pow10_sig_table[idx * 2 + 1];\n}\n\n/**\n Get the exponent (base 2) for highest 64 bits significand in pow10_sig_table.\n */\nstatic_inline void pow10_table_get_exp(i32 exp10, i32 *exp2) {\n    /* e2 = floor(log2(pow(10, e))) - 64 + 1 */\n    /*    = floor(e * log2(10) - 63)         */\n    *exp2 = (exp10 * 217706 - 4128768) >> 16;\n}\n\n#endif\n\n\n\n/*==============================================================================\n * JSON Character Matcher\n *============================================================================*/\n\n/** Character type */\ntypedef u8 char_type;\n\n/** Whitespace character: ' ', '\\\\t', '\\\\n', '\\\\r'. */\nstatic const char_type CHAR_TYPE_SPACE      = 1 << 0;\n\n/** Number character: '-', [0-9]. */\nstatic const char_type CHAR_TYPE_NUMBER     = 1 << 1;\n\n/** JSON Escaped character: '\"', '\\', [0x00-0x1F]. */\nstatic const char_type CHAR_TYPE_ESC_ASCII  = 1 << 2;\n\n/** Non-ASCII character: [0x80-0xFF]. */\nstatic const char_type CHAR_TYPE_NON_ASCII  = 1 << 3;\n\n/** JSON container character: '{', '['. */\nstatic const char_type CHAR_TYPE_CONTAINER  = 1 << 4;\n\n/** Comment character: '/'. */\nstatic const char_type CHAR_TYPE_COMMENT    = 1 << 5;\n\n/** Line end character: '\\\\n', '\\\\r', '\\0'. */\nstatic const char_type CHAR_TYPE_LINE_END   = 1 << 6;\n\n/** Hexadecimal numeric character: [0-9a-fA-F]. */\nstatic const char_type CHAR_TYPE_HEX        = 1 << 7;\n\n/** Character type table (generate with misc/make_tables.c) */\nstatic const char_type char_table[256] = {\n    0x44, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,\n    0x04, 0x05, 0x45, 0x04, 0x04, 0x45, 0x04, 0x04,\n    0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,\n    0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,\n    0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x20,\n    0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82,\n    0x82, 0x82, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x10, 0x04, 0x00, 0x00, 0x00,\n    0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\n    0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,\n    0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,\n    0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,\n    0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,\n    0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,\n    0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,\n    0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,\n    0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,\n    0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,\n    0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,\n    0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,\n    0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,\n    0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,\n    0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,\n    0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,\n    0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08\n};\n\n/** Match a character with specified type. */\nstatic_inline bool char_is_type(u8 c, char_type type) {\n    return (char_table[c] & type) != 0;\n}\n\n/** Match a whitespace: ' ', '\\\\t', '\\\\n', '\\\\r'. */\nstatic_inline bool char_is_space(u8 c) {\n    return char_is_type(c, (char_type)CHAR_TYPE_SPACE);\n}\n\n/** Match a whitespace or comment: ' ', '\\\\t', '\\\\n', '\\\\r', '/'. */\nstatic_inline bool char_is_space_or_comment(u8 c) {\n    return char_is_type(c, (char_type)(CHAR_TYPE_SPACE | CHAR_TYPE_COMMENT));\n}\n\n/** Match a JSON number: '-', [0-9]. */\nstatic_inline bool char_is_number(u8 c) {\n    return char_is_type(c, (char_type)CHAR_TYPE_NUMBER);\n}\n\n/** Match a JSON container: '{', '['. */\nstatic_inline bool char_is_container(u8 c) {\n    return char_is_type(c, (char_type)CHAR_TYPE_CONTAINER);\n}\n\n/** Match a stop character in ASCII string: '\"', '\\', [0x00-0x1F,0x80-0xFF]. */\nstatic_inline bool char_is_ascii_stop(u8 c) {\n    return char_is_type(c, (char_type)(CHAR_TYPE_ESC_ASCII |\n                                       CHAR_TYPE_NON_ASCII));\n}\n\n/** Match a line end character: '\\\\n', '\\\\r', '\\0'. */\nstatic_inline bool char_is_line_end(u8 c) {\n    return char_is_type(c, (char_type)CHAR_TYPE_LINE_END);\n}\n\n/** Match a hexadecimal numeric character: [0-9a-fA-F]. */\nstatic_inline bool char_is_hex(u8 c) {\n    return char_is_type(c, (char_type)CHAR_TYPE_HEX);\n}\n\n\n\n/*==============================================================================\n * Digit Character Matcher\n *============================================================================*/\n\n/** Digit type */\ntypedef u8 digi_type;\n\n/** Digit: '0'. */\nstatic const digi_type DIGI_TYPE_ZERO       = 1 << 0;\n\n/** Digit: [1-9]. */\nstatic const digi_type DIGI_TYPE_NONZERO    = 1 << 1;\n\n/** Plus sign (positive): '+'. */\nstatic const digi_type DIGI_TYPE_POS        = 1 << 2;\n\n/** Minus sign (negative): '-'. */\nstatic const digi_type DIGI_TYPE_NEG        = 1 << 3;\n\n/** Decimal point: '.' */\nstatic const digi_type DIGI_TYPE_DOT        = 1 << 4;\n\n/** Exponent sign: 'e, 'E'. */\nstatic const digi_type DIGI_TYPE_EXP        = 1 << 5;\n\n/** Digit type table (generate with misc/make_tables.c) */\nstatic const digi_type digi_table[256] = {\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x04, 0x00, 0x08, 0x10, 0x00,\n    0x01, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,\n    0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n};\n\n/** Match a character with specified type. */\nstatic_inline bool digi_is_type(u8 d, digi_type type) {\n    return (digi_table[d] & type) != 0;\n}\n\n/** Match a sign: '+', '-' */\nstatic_inline bool digi_is_sign(u8 d) {\n    return digi_is_type(d, (digi_type)(DIGI_TYPE_POS | DIGI_TYPE_NEG));\n}\n\n/** Match a none zero digit: [1-9] */\nstatic_inline bool digi_is_nonzero(u8 d) {\n    return digi_is_type(d, (digi_type)DIGI_TYPE_NONZERO);\n}\n\n/** Match a digit: [0-9] */\nstatic_inline bool digi_is_digit(u8 d) {\n    return digi_is_type(d, (digi_type)(DIGI_TYPE_ZERO | DIGI_TYPE_NONZERO));\n}\n\n/** Match an exponent sign: 'e', 'E'. */\nstatic_inline bool digi_is_exp(u8 d) {\n    return digi_is_type(d, (digi_type)DIGI_TYPE_EXP);\n}\n\n/** Match a floating point indicator: '.', 'e', 'E'. */\nstatic_inline bool digi_is_fp(u8 d) {\n    return digi_is_type(d, (digi_type)(DIGI_TYPE_DOT | DIGI_TYPE_EXP));\n}\n\n/** Match a digit or floating point indicator: [0-9], '.', 'e', 'E'. */\nstatic_inline bool digi_is_digit_or_fp(u8 d) {\n    return digi_is_type(d, (digi_type)(DIGI_TYPE_ZERO | DIGI_TYPE_NONZERO |\n                                       DIGI_TYPE_DOT | DIGI_TYPE_EXP));\n}\n\n\n\n#if !YYJSON_DISABLE_READER\n\n/*==============================================================================\n * Hex Character Reader\n * This function is used by JSON reader to read escaped characters.\n *============================================================================*/\n\n/**\n This table is used to convert 4 hex character sequence to a number.\n A valid hex character [0-9A-Fa-f] will mapped to it's raw number [0x00, 0x0F],\n an invalid hex character will mapped to [0xF0].\n (generate with misc/make_tables.c)\n */\nstatic const u8 hex_conv_table[256] = {\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n    0x08, 0x09, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,\n    0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0\n};\n\n/**\n Scans an escaped character sequence as a UTF-16 code unit (branchless).\n e.g. \"\\\\u005C\" should pass \"005C\" as `cur`.\n \n This requires the string has 4-byte zero padding.\n */\nstatic_inline bool read_hex_u16(const u8 *cur, u16 *val) {\n    u16 c0, c1, c2, c3, t0, t1;\n    c0 = hex_conv_table[cur[0]];\n    c1 = hex_conv_table[cur[1]];\n    c2 = hex_conv_table[cur[2]];\n    c3 = hex_conv_table[cur[3]];\n    t0 = (u16)((c0 << 8) | c2);\n    t1 = (u16)((c1 << 8) | c3);\n    *val = (u16)((t0 << 4) | t1);\n    return ((t0 | t1) & (u16)0xF0F0) == 0;\n}\n\n\n\n/*==============================================================================\n * JSON Reader Utils\n * These functions are used by JSON reader to read literals and comments.\n *============================================================================*/\n\n/** Read 'true' literal, '*cur' should be 't'. */\nstatic_inline bool read_true(u8 **ptr, yyjson_val *val) {\n    u8 *cur = *ptr;\n    u8 **end = ptr;\n    if (likely(byte_match_4(cur, \"true\"))) {\n        val->tag = YYJSON_TYPE_BOOL | YYJSON_SUBTYPE_TRUE;\n        *end = cur + 4;\n        return true;\n    }\n    return false;\n}\n\n/** Read 'false' literal, '*cur' should be 'f'. */\nstatic_inline bool read_false(u8 **ptr, yyjson_val *val) {\n    u8 *cur = *ptr;\n    u8 **end = ptr;\n    if (likely(byte_match_4(cur + 1, \"alse\"))) {\n        val->tag = YYJSON_TYPE_BOOL | YYJSON_SUBTYPE_FALSE;\n        *end = cur + 5;\n        return true;\n    }\n    return false;\n}\n\n/** Read 'null' literal, '*cur' should be 'n'. */\nstatic_inline bool read_null(u8 **ptr, yyjson_val *val) {\n    u8 *cur = *ptr;\n    u8 **end = ptr;\n    if (likely(byte_match_4(cur, \"null\"))) {\n        val->tag = YYJSON_TYPE_NULL;\n        *end = cur + 4;\n        return true;\n    }\n    return false;\n}\n\n/** Read 'Inf' or 'Infinity' literal (ignoring case). */\nstatic_inline bool read_inf(bool sign, u8 **ptr, u8 **pre, yyjson_val *val) {\n    u8 *hdr = *ptr - sign;\n    u8 *cur = *ptr;\n    u8 **end = ptr;\n    if ((cur[0] == 'I' || cur[0] == 'i') &&\n        (cur[1] == 'N' || cur[1] == 'n') &&\n        (cur[2] == 'F' || cur[2] == 'f')) {\n        if ((cur[3] == 'I' || cur[3] == 'i') &&\n            (cur[4] == 'N' || cur[4] == 'n') &&\n            (cur[5] == 'I' || cur[5] == 'i') &&\n            (cur[6] == 'T' || cur[6] == 't') &&\n            (cur[7] == 'Y' || cur[7] == 'y')) {\n            cur += 8;\n        } else {\n            cur += 3;\n        }\n        *end = cur;\n        if (false) {\n            /* add null-terminator for previous raw string */\n            if (*pre) **pre = '\\0';\n            *pre = cur;\n            val->tag = ((u64)(cur - hdr) << YYJSON_TAG_BIT) | YYJSON_TYPE_RAW;\n            val->uni.str = (const char *)hdr;\n        } else {\n            val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL;\n            val->uni.u64 = f64_raw_get_inf(sign);\n        }\n        return true;\n    }\n    return false;\n}\n\n/** Read 'NaN' literal (ignoring case). */\nstatic_inline bool read_nan(bool sign, u8 **ptr, u8 **pre, yyjson_val *val) {\n    u8 *hdr = *ptr - sign;\n    u8 *cur = *ptr;\n    u8 **end = ptr;\n    if ((cur[0] == 'N' || cur[0] == 'n') &&\n        (cur[1] == 'A' || cur[1] == 'a') &&\n        (cur[2] == 'N' || cur[2] == 'n')) {\n        cur += 3;\n        *end = cur;\n        if (false) {\n            /* add null-terminator for previous raw string */\n            if (*pre) **pre = '\\0';\n            *pre = cur;\n            val->tag = ((u64)(cur - hdr) << YYJSON_TAG_BIT) | YYJSON_TYPE_RAW;\n            val->uni.str = (const char *)hdr;\n        } else {\n            val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL;\n            val->uni.u64 = f64_raw_get_nan(sign);\n        }\n        return true;\n    }\n    return false;\n}\n\n/** Read a JSON number as raw string. */\nstatic_noinline bool read_number_raw(u8 **ptr,\n                                     u8 **pre,\n                                     yyjson_read_flag flg,\n                                     yyjson_val *val,\n                                     const char **msg) {\n    \n#define return_err(_pos, _msg) do { \\\n    *msg = _msg; \\\n    *end = _pos; \\\n    return false; \\\n} while (false)\n    \n#define return_raw() do { \\\n    val->tag = ((u64)(cur - hdr) << YYJSON_TAG_BIT) | YYJSON_TYPE_RAW; \\\n    val->uni.str = (const char *)hdr; \\\n    *pre = cur; *end = cur; return true; \\\n} while (false)\n    \n    u8 *hdr = *ptr;\n    u8 *cur = *ptr;\n    u8 **end = ptr;\n    \n    /* add null-terminator for previous raw string */\n    if (*pre) **pre = '\\0';\n    \n    /* skip sign */\n    cur += (*cur == '-');\n    \n    /* read first digit, check leading zero */\n    if (unlikely(!digi_is_digit(*cur))) {\n        return_err(cur, \"no digit after minus sign\");\n    }\n    \n    /* read integral part */\n    if (*cur == '0') {\n        cur++;\n        if (unlikely(digi_is_digit(*cur))) {\n            return_err(cur - 1, \"number with leading zero is not allowed\");\n        }\n        if (!digi_is_fp(*cur)) return_raw();\n    } else {\n        while (digi_is_digit(*cur)) cur++;\n        if (!digi_is_fp(*cur)) return_raw();\n    }\n    \n    /* read fraction part */\n    if (*cur == '.') {\n        cur++;\n        if (!digi_is_digit(*cur++)) {\n            return_err(cur, \"no digit after decimal point\");\n        }\n        while (digi_is_digit(*cur)) cur++;\n    }\n    \n    /* read exponent part */\n    if (digi_is_exp(*cur)) {\n        cur += 1 + digi_is_sign(cur[1]);\n        if (!digi_is_digit(*cur++)) {\n            return_err(cur, \"no digit after exponent sign\");\n        }\n        while (digi_is_digit(*cur)) cur++;\n    }\n    \n    return_raw();\n    \n#undef return_err\n#undef return_raw\n}\n\n/**\n Skips spaces and comments as many as possible.\n \n It will return false in these cases:\n    1. No character is skipped. The 'end' pointer is set as input cursor.\n    2. A multiline comment is not closed. The 'end' pointer is set as the head\n       of this comment block.\n */\nstatic_noinline bool skip_spaces_and_comments(u8 **ptr) {\n    u8 *hdr = *ptr;\n    u8 *cur = *ptr;\n    u8 **end = ptr;\n    while (true) {\n        if (byte_match_2(cur, \"/*\")) {\n            hdr = cur;\n            cur += 2;\n            while (true) {\n                if (byte_match_2(cur, \"*/\")) {\n                    cur += 2;\n                    break;\n                }\n                if (*cur == 0) {\n                    *end = hdr;\n                    return false;\n                }\n                cur++;\n            }\n            continue;\n        }\n        if (byte_match_2(cur, \"//\")) {\n            cur += 2;\n            while (!char_is_line_end(*cur)) cur++;\n            continue;\n        }\n        if (char_is_space(*cur)) {\n            cur += 1;\n            while (char_is_space(*cur)) cur++;\n            continue;\n        }\n        break;\n    }\n    *end = cur;\n    return hdr != cur;\n}\n\n/**\n Check truncated string.\n Returns true if `cur` match `str` but is truncated.\n */\nstatic_inline bool is_truncated_str(u8 *cur, u8 *end,\n                                    const char *str,\n                                    bool case_sensitive) {\n    usize len = strlen(str);\n    if (cur + len <= end || end <= cur) return false;\n    if (case_sensitive) {\n        return memcmp(cur, str, (usize)(end - cur)) == 0;\n    }\n    for (; cur < end; cur++, str++) {\n        if ((*cur != (u8)*str) && (*cur != (u8)*str - 'a' + 'A')) {\n            return false;\n        }\n    }\n    return true;\n}\n\n/**\n Check truncated JSON on parsing errors.\n Returns true if the input is valid but truncated.\n */\nstatic_noinline bool is_truncated_end(u8 *hdr, u8 *cur, u8 *end,\n                                      yyjson_read_code code) {\n    if (cur >= end) return true;\n    if (code == YYJSON_READ_ERROR_LITERAL) {\n        if (is_truncated_str(cur, end, \"true\", true) ||\n            is_truncated_str(cur, end, \"false\", true) ||\n            is_truncated_str(cur, end, \"null\", true)) {\n            return true;\n        }\n    }\n    if (code == YYJSON_READ_ERROR_UNEXPECTED_CHARACTER ||\n        code == YYJSON_READ_ERROR_INVALID_NUMBER ||\n        code == YYJSON_READ_ERROR_LITERAL) {\n        if (false) {\n            if (*cur == '-') cur++;\n            if (is_truncated_str(cur, end, \"infinity\", false) ||\n                is_truncated_str(cur, end, \"nan\", false)) {\n                return true;\n            }\n        }\n    }\n    if (code == YYJSON_READ_ERROR_UNEXPECTED_CONTENT) {\n        if (false) {\n            if (hdr + 3 <= cur &&\n                is_truncated_str(cur - 3, end, \"infinity\", false)) {\n                return true; /* e.g. infin would be read as inf + in */\n            }\n        }\n    }\n    if (code == YYJSON_READ_ERROR_INVALID_STRING) {\n        usize len = (usize)(end - cur);\n        \n        /* unicode escape sequence */\n        if (*cur == '\\\\') {\n            if (len == 1) return true;\n            if (len <= 5) {\n                if (*++cur != 'u') return false;\n                for (++cur; cur < end; cur++) {\n                    if (!char_is_hex(*cur)) return false;\n                }\n                return true;\n            }\n            return false;\n        }\n        \n        /* 2 to 4 bytes UTF-8, see `read_string()` for details. */\n        if (*cur & 0x80) {\n            u8 c0 = cur[0], c1 = cur[1], c2 = cur[2];\n            if (len == 1) {\n                /* 2 bytes UTF-8, truncated */\n                if ((c0 & 0xE0) == 0xC0 && (c0 & 0x1E) != 0x00) return true;\n                /* 3 bytes UTF-8, truncated */\n                if ((c0 & 0xF0) == 0xE0) return true;\n                /* 4 bytes UTF-8, truncated */\n                if ((c0 & 0xF8) == 0xF0 && (c0 & 0x07) <= 0x04) return true;\n            }\n            if (len == 2) {\n                /* 3 bytes UTF-8, truncated */\n                if ((c0 & 0xF0) == 0xE0 &&\n                    (c1 & 0xC0) == 0x80) {\n                    u8 pat = (u8)(((c0 & 0x0F) << 1) | ((c1 & 0x20) >> 5));\n                    return 0x01 <= pat && pat != 0x1B;\n                }\n                /* 4 bytes UTF-8, truncated */\n                if ((c0 & 0xF8) == 0xF0 &&\n                    (c1 & 0xC0) == 0x80) {\n                    u8 pat = (u8)(((c0 & 0x07) << 2) | ((c1 & 0x30) >> 4));\n                    return 0x01 <= pat && pat <= 0x10;\n                }\n            }\n            if (len == 3) {\n                /* 4 bytes UTF-8, truncated */\n                if ((c0 & 0xF8) == 0xF0 &&\n                    (c1 & 0xC0) == 0x80 &&\n                    (c2 & 0xC0) == 0x80) {\n                    u8 pat = (u8)(((c0 & 0x07) << 2) | ((c1 & 0x30) >> 4));\n                    return 0x01 <= pat && pat <= 0x10;\n                }\n            }\n        }\n    }\n    return false;\n}\n\n\n\n#if YYJSON_HAS_IEEE_754 && !YYJSON_DISABLE_FAST_FP_CONV /* FP_READER */\n\n/*==============================================================================\n * BigInt For Floating Point Number Reader\n *\n * The bigint algorithm is used by floating-point number reader to get correctly\n * rounded result for numbers with lots of digits. This part of code is rarely\n * used for common numbers.\n *============================================================================*/\n\n/** Maximum exponent of exact pow10 */\n#define U64_POW10_MAX_EXP 19\n\n/** Table: [ 10^0, ..., 10^19 ] (generate with misc/make_tables.c) */\nstatic const u64 u64_pow10_table[U64_POW10_MAX_EXP + 1] = {\n    U64(0x00000000, 0x00000001), U64(0x00000000, 0x0000000A),\n    U64(0x00000000, 0x00000064), U64(0x00000000, 0x000003E8),\n    U64(0x00000000, 0x00002710), U64(0x00000000, 0x000186A0),\n    U64(0x00000000, 0x000F4240), U64(0x00000000, 0x00989680),\n    U64(0x00000000, 0x05F5E100), U64(0x00000000, 0x3B9ACA00),\n    U64(0x00000002, 0x540BE400), U64(0x00000017, 0x4876E800),\n    U64(0x000000E8, 0xD4A51000), U64(0x00000918, 0x4E72A000),\n    U64(0x00005AF3, 0x107A4000), U64(0x00038D7E, 0xA4C68000),\n    U64(0x002386F2, 0x6FC10000), U64(0x01634578, 0x5D8A0000),\n    U64(0x0DE0B6B3, 0xA7640000), U64(0x8AC72304, 0x89E80000)\n};\n\n/** Maximum numbers of chunks used by a bigint (58 is enough here). */\n#define BIGINT_MAX_CHUNKS 64\n\n/** Unsigned arbitrarily large integer */\ntypedef struct bigint {\n    u32 used; /* used chunks count, should not be 0 */\n    u64 bits[BIGINT_MAX_CHUNKS]; /* chunks */\n} bigint;\n\n/**\n Evaluate 'big += val'.\n @param big A big number (can be 0).\n @param val An unsigned integer (can be 0).\n */\nstatic_inline void bigint_add_u64(bigint *big, u64 val) {\n    u32 idx, max;\n    u64 num = big->bits[0];\n    u64 add = num + val;\n    big->bits[0] = add;\n    if (likely((add >= num) || (add >= val))) return;\n    for ((void)(idx = 1), max = big->used; idx < max; idx++) {\n        if (likely(big->bits[idx] != U64_MAX)) {\n            big->bits[idx] += 1;\n            return;\n        }\n        big->bits[idx] = 0;\n    }\n    big->bits[big->used++] = 1;\n}\n\n/**\n Evaluate 'big *= val'.\n @param big A big number (can be 0).\n @param val An unsigned integer (cannot be 0).\n */\nstatic_inline void bigint_mul_u64(bigint *big, u64 val) {\n    u32 idx = 0, max = big->used;\n    u64 hi, lo, carry = 0;\n    for (; idx < max; idx++) {\n        if (big->bits[idx]) break;\n    }\n    for (; idx < max; idx++) {\n        u128_mul_add(big->bits[idx], val, carry, &hi, &lo);\n        big->bits[idx] = lo;\n        carry = hi;\n    }\n    if (carry) big->bits[big->used++] = carry;\n}\n\n/**\n Evaluate 'big *= 2^exp'.\n @param big A big number (can be 0).\n @param exp An exponent integer (can be 0).\n */\nstatic_inline void bigint_mul_pow2(bigint *big, u32 exp) {\n    u32 shft = exp % 64;\n    u32 move = exp / 64;\n    u32 idx = big->used;\n    if (unlikely(shft == 0)) {\n        for (; idx > 0; idx--) {\n            big->bits[idx + move - 1] = big->bits[idx - 1];\n        }\n        big->used += move;\n        while (move) big->bits[--move] = 0;\n    } else {\n        big->bits[idx] = 0;\n        for (; idx > 0; idx--) {\n            u64 num = big->bits[idx] << shft;\n            num |= big->bits[idx - 1] >> (64 - shft);\n            big->bits[idx + move] = num;\n        }\n        big->bits[move] = big->bits[0] << shft;\n        big->used += move + (big->bits[big->used + move] > 0);\n        while (move) big->bits[--move] = 0;\n    }\n}\n\n/**\n Evaluate 'big *= 10^exp'.\n @param big A big number (can be 0).\n @param exp An exponent integer (cannot be 0).\n */\nstatic_inline void bigint_mul_pow10(bigint *big, i32 exp) {\n    for (; exp >= U64_POW10_MAX_EXP; exp -= U64_POW10_MAX_EXP) {\n        bigint_mul_u64(big, u64_pow10_table[U64_POW10_MAX_EXP]);\n    }\n    if (exp) {\n        bigint_mul_u64(big, u64_pow10_table[exp]);\n    }\n}\n\n/**\n Compare two bigint.\n @return -1 if 'a < b', +1 if 'a > b', 0 if 'a == b'.\n */\nstatic_inline i32 bigint_cmp(bigint *a, bigint *b) {\n    u32 idx = a->used;\n    if (a->used < b->used) return -1;\n    if (a->used > b->used) return +1;\n    while (idx-- > 0) {\n        u64 av = a->bits[idx];\n        u64 bv = b->bits[idx];\n        if (av < bv) return -1;\n        if (av > bv) return +1;\n    }\n    return 0;\n}\n\n/**\n Evaluate 'big = val'.\n @param big A big number (can be 0).\n @param val An unsigned integer (can be 0).\n */\nstatic_inline void bigint_set_u64(bigint *big, u64 val) {\n    big->used = 1;\n    big->bits[0] = val;\n}\n\n/** Set a bigint with floating point number string. */\nstatic_noinline void bigint_set_buf(bigint *big, u64 sig, i32 *exp,\n                                    u8 *sig_cut, u8 *sig_end, u8 *dot_pos) {\n    \n    if (unlikely(!sig_cut)) {\n        /* no digit cut, set significant part only */\n        bigint_set_u64(big, sig);\n        return;\n        \n    } else {\n        /* some digits were cut, read them from 'sig_cut' to 'sig_end' */\n        u8 *hdr = sig_cut;\n        u8 *cur = hdr;\n        u32 len = 0;\n        u64 val = 0;\n        bool dig_big_cut = false;\n        bool has_dot = (hdr < dot_pos) & (dot_pos < sig_end);\n        u32 dig_len_total = U64_SAFE_DIG + (u32)(sig_end - hdr) - has_dot;\n        \n        sig -= (*sig_cut >= '5'); /* sig was rounded before */\n        if (dig_len_total > F64_MAX_DEC_DIG) {\n            dig_big_cut = true;\n            sig_end -= dig_len_total - (F64_MAX_DEC_DIG + 1);\n            sig_end -= (dot_pos + 1 == sig_end);\n            dig_len_total = (F64_MAX_DEC_DIG + 1);\n        }\n        *exp -= (i32)dig_len_total - U64_SAFE_DIG;\n        \n        big->used = 1;\n        big->bits[0] = sig;\n        while (cur < sig_end) {\n            if (likely(cur != dot_pos)) {\n                val = val * 10 + (u8)(*cur++ - '0');\n                len++;\n                if (unlikely(cur == sig_end && dig_big_cut)) {\n                    /* The last digit must be non-zero,    */\n                    /* set it to '1' for correct rounding. */\n                    val = val - (val % 10) + 1;\n                }\n                if (len == U64_SAFE_DIG || cur == sig_end) {\n                    bigint_mul_pow10(big, (i32)len);\n                    bigint_add_u64(big, val);\n                    val = 0;\n                    len = 0;\n                }\n            } else {\n                cur++;\n            }\n        }\n    }\n}\n\n\n\n/*==============================================================================\n * Diy Floating Point\n *============================================================================*/\n\n/** \"Do It Yourself Floating Point\" struct. */\ntypedef struct diy_fp {\n    u64 sig; /* significand */\n    i32 exp; /* exponent, base 2 */\n    i32 pad; /* padding, useless */\n} diy_fp;\n\n/** Get cached rounded diy_fp with pow(10, e) The input value must in range\n    [POW10_SIG_TABLE_MIN_EXP, POW10_SIG_TABLE_MAX_EXP]. */\nstatic_inline diy_fp diy_fp_get_cached_pow10(i32 exp10) {\n    diy_fp fp;\n    u64 sig_ext;\n    pow10_table_get_sig(exp10, &fp.sig, &sig_ext);\n    pow10_table_get_exp(exp10, &fp.exp);\n    fp.sig += (sig_ext >> 63);\n    return fp;\n}\n\n/** Returns fp * fp2. */\nstatic_inline diy_fp diy_fp_mul(diy_fp fp, diy_fp fp2) {\n    u64 hi, lo;\n    u128_mul(fp.sig, fp2.sig, &hi, &lo);\n    fp.sig = hi + (lo >> 63);\n    fp.exp += fp2.exp + 64;\n    return fp;\n}\n\n/** Convert diy_fp to IEEE-754 raw value. */\nstatic_inline u64 diy_fp_to_ieee_raw(diy_fp fp) {\n    u64 sig = fp.sig;\n    i32 exp = fp.exp;\n    u32 lz_bits;\n    if (unlikely(fp.sig == 0)) return 0;\n    \n    lz_bits = u64_lz_bits(sig);\n    sig <<= lz_bits;\n    sig >>= F64_BITS - F64_SIG_FULL_BITS;\n    exp -= (i32)lz_bits;\n    exp += F64_BITS - F64_SIG_FULL_BITS;\n    exp += F64_SIG_BITS;\n    \n    if (unlikely(exp >= F64_MAX_BIN_EXP)) {\n        /* overflow */\n        return F64_RAW_INF;\n    } else if (likely(exp >= F64_MIN_BIN_EXP - 1)) {\n        /* normal */\n        exp += F64_EXP_BIAS;\n        return ((u64)exp << F64_SIG_BITS) | (sig & F64_SIG_MASK);\n    } else if (likely(exp >= F64_MIN_BIN_EXP - F64_SIG_FULL_BITS)) {\n        /* subnormal */\n        return sig >> (F64_MIN_BIN_EXP - exp - 1);\n    } else {\n        /* underflow */\n        return 0;\n    }\n}\n\n\n\n/*==============================================================================\n * JSON Number Reader (IEEE-754)\n *============================================================================*/\n\n/** Maximum exact pow10 exponent for double value. */\n#define F64_POW10_EXP_MAX_EXACT 22\n\n/** Cached pow10 table. */\nstatic const f64 f64_pow10_table[] = {\n    1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12,\n    1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22\n};\n\n/**\n Read a JSON number.\n \n 1. This function assume that the floating-point number is in IEEE-754 format.\n 2. This function support uint64/int64/double number. If an integer number\n    cannot fit in uint64/int64, it will returns as a double number. If a double\n    number is infinite, the return value is based on flag.\n 3. This function (with inline attribute) may generate a lot of instructions.\n */\nstatic_inline bool read_number(u8 **ptr,\n                               yyjson_val *val,\n                               const char **msg) {\n    \n#define return_err(_pos, _msg) do { \\\n    *msg = _msg; \\\n    *end = _pos; \\\n    return false; \\\n} while (false)\n    \n#define return_0() do { \\\n    val->tag = YYJSON_TYPE_NUM | (u8)((u8)sign << 3); \\\n    val->uni.u64 = 0; \\\n    *end = cur; return true; \\\n} while (false)\n\n#define return_i64(_v) do { \\\n    val->tag = YYJSON_TYPE_NUM | (u8)((u8)sign << 3); \\\n    val->uni.u64 = (u64)(sign ? (u64)(~(_v) + 1) : (u64)(_v)); \\\n    *end = cur; return true; \\\n} while (false)\n    \n#define return_f64(_v) do { \\\n    val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL; \\\n    val->uni.f64 = sign ? -(f64)(_v) : (f64)(_v); \\\n    *end = cur; return true; \\\n} while (false)\n    \n#define return_f64_bin(_v) do { \\\n    val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL; \\\n    val->uni.u64 = ((u64)sign << 63) | (u64)(_v); \\\n    *end = cur; return true; \\\n} while (false)\n    \n#define return_inf() do { \\\n    if (false) return_f64_bin(F64_RAW_INF); \\\n    else return_err(hdr, \"number is infinity when parsed as double\"); \\\n} while (false)\n    \n    u8 *sig_cut = NULL; /* significant part cutting position for long number */\n    u8 *sig_end = NULL; /* significant part ending position */\n    u8 *dot_pos = NULL; /* decimal point position */\n    \n    u64 sig = 0; /* significant part of the number */\n    i32 exp = 0; /* exponent part of the number */\n    \n    bool exp_sign; /* temporary exponent sign from literal part */\n    i64 exp_sig = 0; /* temporary exponent number from significant part */\n    i64 exp_lit = 0; /* temporary exponent number from exponent literal part */\n    u64 num; /* temporary number for reading */\n    u8 *tmp; /* temporary cursor for reading */\n    \n    u8 *hdr = *ptr;\n    u8 *cur = *ptr;\n    u8 **end = ptr;\n    bool sign;\n    \n    sign = (*hdr == '-');\n    cur += sign;\n    \n    /* begin with a leading zero or non-digit */\n    if (unlikely(!digi_is_nonzero(*cur))) { /* 0 or non-digit char */\n        if (unlikely(*cur != '0')) { /* non-digit char */\n            return_err(cur, \"no digit after minus sign\");\n        }\n        /* begin with 0 */\n        if (likely(!digi_is_digit_or_fp(*++cur))) return_0();\n        if (likely(*cur == '.')) {\n            dot_pos = cur++;\n            if (unlikely(!digi_is_digit(*cur))) {\n                return_err(cur, \"no digit after decimal point\");\n            }\n            while (unlikely(*cur == '0')) cur++;\n            if (likely(digi_is_digit(*cur))) {\n                /* first non-zero digit after decimal point */\n                sig = (u64)(*cur - '0'); /* read first digit */\n                cur--;\n                goto digi_frac_1; /* continue read fraction part */\n            }\n        }\n        if (unlikely(digi_is_digit(*cur))) {\n            return_err(cur - 1, \"number with leading zero is not allowed\");\n        }\n        if (unlikely(digi_is_exp(*cur))) { /* 0 with any exponent is still 0 */\n            cur += (usize)1 + digi_is_sign(cur[1]);\n            if (unlikely(!digi_is_digit(*cur))) {\n                return_err(cur, \"no digit after exponent sign\");\n            }\n            while (digi_is_digit(*++cur));\n        }\n        return_f64_bin(0);\n    }\n    \n    /* begin with non-zero digit */\n    sig = (u64)(*cur - '0');\n    \n    /*\n     Read integral part, same as the following code.\n     \n         for (int i = 1; i <= 18; i++) {\n            num = cur[i] - '0';\n            if (num <= 9) sig = num + sig * 10;\n            else goto digi_sepr_i;\n         }\n     */\n#define expr_intg(i) \\\n    if (likely((num = (u64)(cur[i] - (u8)'0')) <= 9)) sig = num + sig * 10; \\\n    else { goto digi_sepr_##i; }\n    repeat_in_1_18(expr_intg)\n#undef expr_intg\n    \n    \n    cur += 19; /* skip continuous 19 digits */\n    if (!digi_is_digit_or_fp(*cur)) {\n        /* this number is an integer consisting of 19 digits */\n        if (sign && (sig > ((u64)1 << 63))) { /* overflow */\n            return_f64(normalized_u64_to_f64(sig));\n        }\n        return_i64(sig);\n    }\n    goto digi_intg_more; /* read more digits in integral part */\n    \n    \n    /* process first non-digit character */\n#define expr_sepr(i) \\\n    digi_sepr_##i: \\\n    if (likely(!digi_is_fp(cur[i]))) { cur += i; return_i64(sig); } \\\n    dot_pos = cur + i; \\\n    if (likely(cur[i] == '.')) goto digi_frac_##i; \\\n    cur += i; sig_end = cur; goto digi_exp_more;\n    repeat_in_1_18(expr_sepr)\n#undef expr_sepr\n    \n    \n    /* read fraction part */\n#define expr_frac(i) \\\n    digi_frac_##i: \\\n    if (likely((num = (u64)(cur[i + 1] - (u8)'0')) <= 9)) \\\n        sig = num + sig * 10; \\\n    else { goto digi_stop_##i; }\n    repeat_in_1_18(expr_frac)\n#undef expr_frac\n    \n    cur += 20; /* skip 19 digits and 1 decimal point */\n    if (!digi_is_digit(*cur)) goto digi_frac_end; /* fraction part end */\n    goto digi_frac_more; /* read more digits in fraction part */\n    \n    \n    /* significant part end */\n#define expr_stop(i) \\\n    digi_stop_##i: \\\n    cur += i + 1; \\\n    goto digi_frac_end;\n    repeat_in_1_18(expr_stop)\n#undef expr_stop\n    \n    \n    /* read more digits in integral part */\ndigi_intg_more:\n    if (digi_is_digit(*cur)) {\n        if (!digi_is_digit_or_fp(cur[1])) {\n            /* this number is an integer consisting of 20 digits */\n            num = (u64)(*cur - '0');\n            if ((sig < (U64_MAX / 10)) ||\n                (sig == (U64_MAX / 10) && num <= (U64_MAX % 10))) {\n                sig = num + sig * 10;\n                cur++;\n                /* convert to double if overflow */\n                if (sign) {\n                    return_f64(normalized_u64_to_f64(sig));\n                }\n                return_i64(sig);\n            }\n        }\n    }\n    \n    if (digi_is_exp(*cur)) {\n        dot_pos = cur;\n        goto digi_exp_more;\n    }\n    \n    if (*cur == '.') {\n        dot_pos = cur++;\n        if (!digi_is_digit(*cur)) {\n            return_err(cur, \"no digit after decimal point\");\n        }\n    }\n    \n    \n    /* read more digits in fraction part */\ndigi_frac_more:\n    sig_cut = cur; /* too large to fit in u64, excess digits need to be cut */\n    sig += (*cur >= '5'); /* round */\n    while (digi_is_digit(*++cur));\n    if (!dot_pos) {\n        dot_pos = cur;\n        if (*cur == '.') {\n            if (!digi_is_digit(*++cur)) {\n                return_err(cur, \"no digit after decimal point\");\n            }\n            while (digi_is_digit(*cur)) cur++;\n        }\n    }\n    exp_sig = (i64)(dot_pos - sig_cut);\n    exp_sig += (dot_pos < sig_cut);\n    \n    /* ignore trailing zeros */\n    tmp = cur - 1;\n    while (*tmp == '0' || *tmp == '.') tmp--;\n    if (tmp < sig_cut) {\n        sig_cut = NULL;\n    } else {\n        sig_end = cur;\n    }\n    \n    if (digi_is_exp(*cur)) goto digi_exp_more;\n    goto digi_exp_finish;\n    \n    \n    /* fraction part end */\ndigi_frac_end:\n    if (unlikely(dot_pos + 1 == cur)) {\n        return_err(cur, \"no digit after decimal point\");\n    }\n    sig_end = cur;\n    exp_sig = -(i64)((u64)(cur - dot_pos) - 1);\n    if (likely(!digi_is_exp(*cur))) {\n        if (unlikely(exp_sig < F64_MIN_DEC_EXP - 19)) {\n            return_f64_bin(0); /* underflow */\n        }\n        exp = (i32)exp_sig;\n        goto digi_finish;\n    } else {\n        goto digi_exp_more;\n    }\n    \n    \n    /* read exponent part */\ndigi_exp_more:\n    exp_sign = (*++cur == '-');\n    cur += digi_is_sign(*cur);\n    if (unlikely(!digi_is_digit(*cur))) {\n        return_err(cur, \"no digit after exponent sign\");\n    }\n    while (*cur == '0') cur++;\n    \n    /* read exponent literal */\n    tmp = cur;\n    while (digi_is_digit(*cur)) {\n        exp_lit = (i64)((u8)(*cur++ - '0') + (u64)exp_lit * 10);\n    }\n    if (unlikely(cur - tmp >= U64_SAFE_DIG)) {\n        if (exp_sign) {\n            return_f64_bin(0); /* underflow */\n        } else {\n            return_inf(); /* overflow */\n        }\n    }\n    exp_sig += exp_sign ? -exp_lit : exp_lit;\n    \n    \n    /* validate exponent value */\ndigi_exp_finish:\n    if (unlikely(exp_sig < F64_MIN_DEC_EXP - 19)) {\n        return_f64_bin(0); /* underflow */\n    }\n    if (unlikely(exp_sig > F64_MAX_DEC_EXP)) {\n        return_inf(); /* overflow */\n    }\n    exp = (i32)exp_sig;\n    \n    \n    /* all digit read finished */\ndigi_finish:\n    \n    /*\n     Fast path 1:\n     \n     1. The floating-point number calculation should be accurate, see the\n        comments of macro `YYJSON_DOUBLE_MATH_CORRECT`.\n     2. Correct rounding should be performed (fegetround() == FE_TONEAREST).\n     3. The input of floating point number calculation does not lose precision,\n        which means: 64 - leading_zero(input) - trailing_zero(input) < 53.\n    \n     We don't check all available inputs here, because that would make the code\n     more complicated, and not friendly to branch predictor.\n     */\n#if YYJSON_DOUBLE_MATH_CORRECT\n    if (sig < ((u64)1 << 53) &&\n        exp >= -F64_POW10_EXP_MAX_EXACT &&\n        exp <= +F64_POW10_EXP_MAX_EXACT) {\n        f64 dbl = (f64)sig;\n        if (exp < 0) {\n            dbl /= f64_pow10_table[-exp];\n        } else {\n            dbl *= f64_pow10_table[+exp];\n        }\n        return_f64(dbl);\n    }\n#endif\n    \n    /*\n     Fast path 2:\n     \n     To keep it simple, we only accept normal number here,\n     let the slow path to handle subnormal and infinity number.\n     */\n    if (likely(!sig_cut &&\n               exp > -F64_MAX_DEC_EXP + 1 &&\n               exp < +F64_MAX_DEC_EXP - 20)) {\n        /*\n         The result value is exactly equal to (sig * 10^exp),\n         the exponent part (10^exp) can be converted to (sig2 * 2^exp2).\n         \n         The sig2 can be an infinite length number, only the highest 128 bits\n         is cached in the pow10_sig_table.\n         \n         Now we have these bits:\n         sig1 (normalized 64bit)        : aaaaaaaa\n         sig2 (higher 64bit)            : bbbbbbbb\n         sig2_ext (lower 64bit)         : cccccccc\n         sig2_cut (extra unknown bits)  : dddddddddddd....\n         \n         And the calculation process is:\n         ----------------------------------------\n                 aaaaaaaa *\n                 bbbbbbbbccccccccdddddddddddd....\n         ----------------------------------------\n         abababababababab +\n                 acacacacacacacac +\n                         adadadadadadadadadad....\n         ----------------------------------------\n         [hi____][lo____] +\n                 [hi2___][lo2___] +\n                         [unknown___________....]\n         ----------------------------------------\n         \n         The addition with carry may affect higher bits, but if there is a 0\n         in higher bits, the bits higher than 0 will not be affected.\n         \n         `lo2` + `unknown` may get a carry bit and may affect `hi2`, the max\n         value of `hi2` is 0xFFFFFFFFFFFFFFFE, so `hi2` will not overflow.\n         \n         `lo` + `hi2` may also get a carry bit and may affect `hi`, but only\n         the highest significant 53 bits of `hi` is needed. If there is a 0\n         in the lower bits of `hi`, then all the following bits can be dropped.\n         \n         To convert the result to IEEE-754 double number, we need to perform\n         correct rounding:\n         1. if bit 54 is 0, round down,\n         2. if bit 54 is 1 and any bit beyond bit 54 is 1, round up,\n         3. if bit 54 is 1 and all bits beyond bit 54 are 0, round to even,\n            as the extra bits is unknown, this case will not be handled here.\n         */\n        \n        u64 raw;\n        u64 sig1, sig2, sig2_ext, hi, lo, hi2, lo2, add, bits;\n        i32 exp2;\n        u32 lz;\n        bool exact = false, carry, round_up;\n        \n        /* convert (10^exp) to (sig2 * 2^exp2) */\n        pow10_table_get_sig(exp, &sig2, &sig2_ext);\n        pow10_table_get_exp(exp, &exp2);\n        \n        /* normalize and multiply */\n        lz = u64_lz_bits(sig);\n        sig1 = sig << lz;\n        exp2 -= (i32)lz;\n        u128_mul(sig1, sig2, &hi, &lo);\n        \n        /*\n         The `hi` is in range [0x4000000000000000, 0xFFFFFFFFFFFFFFFE],\n         To get normalized value, `hi` should be shifted to the left by 0 or 1.\n         \n         The highest significant 53 bits is used by IEEE-754 double number,\n         and the bit 54 is used to detect rounding direction.\n         \n         The lowest (64 - 54 - 1) bits is used to check whether it contains 0.\n         */\n        bits = hi & (((u64)1 << (64 - 54 - 1)) - 1);\n        if (bits - 1 < (((u64)1 << (64 - 54 - 1)) - 2)) {\n            /*\n             (bits != 0 && bits != 0x1FF) => (bits - 1 < 0x1FF - 1)\n             The `bits` is not zero, so we don't need to check `round to even`\n             case. The `bits` contains bit `0`, so we can drop the extra bits\n             after `0`.\n             */\n            exact = true;\n            \n        } else {\n            /*\n             (bits == 0 || bits == 0x1FF)\n             The `bits` is filled with all `0` or all `1`, so we need to check\n             lower bits with another 64-bit multiplication.\n             */\n            u128_mul(sig1, sig2_ext, &hi2, &lo2);\n            \n            add = lo + hi2;\n            if (add + 1 > (u64)1) {\n                /*\n                 (add != 0 && add != U64_MAX) => (add + 1 > 1)\n                 The `add` is not zero, so we don't need to check `round to\n                 even` case. The `add` contains bit `0`, so we can drop the\n                 extra bits after `0`. The `hi` cannot be U64_MAX, so it will\n                 not overflow.\n                 */\n                carry = add < lo || add < hi2;\n                hi += carry;\n                exact = true;\n            }\n        }\n        \n        if (exact) {\n            /* normalize */\n            lz = hi < ((u64)1 << 63);\n            hi <<= lz;\n            exp2 -= (i32)lz;\n            exp2 += 64;\n            \n            /* test the bit 54 and get rounding direction */\n            round_up = (hi & ((u64)1 << (64 - 54))) > (u64)0;\n            hi += (round_up ? ((u64)1 << (64 - 54)) : (u64)0);\n            \n            /* test overflow */\n            if (hi < ((u64)1 << (64 - 54))) {\n                hi = ((u64)1 << 63);\n                exp2 += 1;\n            }\n            \n            /* This is a normal number, convert it to IEEE-754 format. */\n            hi >>= F64_BITS - F64_SIG_FULL_BITS;\n            exp2 += F64_BITS - F64_SIG_FULL_BITS + F64_SIG_BITS;\n            exp2 += F64_EXP_BIAS;\n            raw = ((u64)exp2 << F64_SIG_BITS) | (hi & F64_SIG_MASK);\n            return_f64_bin(raw);\n        }\n    }\n    \n    /*\n     Slow path: read double number exactly with diyfp.\n     1. Use cached diyfp to get an approximation value.\n     2. Use bigcomp to check the approximation value if needed.\n     \n     This algorithm refers to google's double-conversion project:\n     https://github.com/google/double-conversion\n     */\n    {\n        const i32 ERR_ULP_LOG = 3;\n        const i32 ERR_ULP = 1 << ERR_ULP_LOG;\n        const i32 ERR_CACHED_POW = ERR_ULP / 2;\n        const i32 ERR_MUL_FIXED = ERR_ULP / 2;\n        const i32 DIY_SIG_BITS = 64;\n        const i32 EXP_BIAS = F64_EXP_BIAS + F64_SIG_BITS;\n        const i32 EXP_SUBNORMAL = -EXP_BIAS + 1;\n        \n        u64 fp_err;\n        u32 bits;\n        i32 order_of_magnitude;\n        i32 effective_significand_size;\n        i32 precision_digits_count;\n        u64 precision_bits;\n        u64 half_way;\n        \n        u64 raw;\n        diy_fp fp, fp_upper;\n        bigint big_full, big_comp;\n        i32 cmp;\n        \n        fp.sig = sig;\n        fp.exp = 0;\n        fp_err = sig_cut ? (u64)(ERR_ULP / 2) : (u64)0;\n        \n        /* normalize */\n        bits = u64_lz_bits(fp.sig);\n        fp.sig <<= bits;\n        fp.exp -= (i32)bits;\n        fp_err <<= bits;\n        \n        /* multiply and add error */\n        fp = diy_fp_mul(fp, diy_fp_get_cached_pow10(exp));\n        fp_err += (u64)ERR_CACHED_POW + (fp_err != 0) + (u64)ERR_MUL_FIXED;\n        \n        /* normalize */\n        bits = u64_lz_bits(fp.sig);\n        fp.sig <<= bits;\n        fp.exp -= (i32)bits;\n        fp_err <<= bits;\n        \n        /* effective significand */\n        order_of_magnitude = DIY_SIG_BITS + fp.exp;\n        if (likely(order_of_magnitude >= EXP_SUBNORMAL + F64_SIG_FULL_BITS)) {\n            effective_significand_size = F64_SIG_FULL_BITS;\n        } else if (order_of_magnitude <= EXP_SUBNORMAL) {\n            effective_significand_size = 0;\n        } else {\n            effective_significand_size = order_of_magnitude - EXP_SUBNORMAL;\n        }\n        \n        /* precision digits count */\n        precision_digits_count = DIY_SIG_BITS - effective_significand_size;\n        if (unlikely(precision_digits_count + ERR_ULP_LOG >= DIY_SIG_BITS)) {\n            i32 shr = (precision_digits_count + ERR_ULP_LOG) - DIY_SIG_BITS + 1;\n            fp.sig >>= shr;\n            fp.exp += shr;\n            fp_err = (fp_err >> shr) + 1 + (u32)ERR_ULP;\n            precision_digits_count -= shr;\n        }\n        \n        /* half way */\n        precision_bits = fp.sig & (((u64)1 << precision_digits_count) - 1);\n        precision_bits *= (u32)ERR_ULP;\n        half_way = (u64)1 << (precision_digits_count - 1);\n        half_way *= (u32)ERR_ULP;\n        \n        /* rounding */\n        fp.sig >>= precision_digits_count;\n        fp.sig += (precision_bits >= half_way + fp_err);\n        fp.exp += precision_digits_count;\n        \n        /* get IEEE double raw value */\n        raw = diy_fp_to_ieee_raw(fp);\n        if (unlikely(raw == F64_RAW_INF)) return_inf();\n        if (likely(precision_bits <= half_way - fp_err ||\n                   precision_bits >= half_way + fp_err)) {\n            return_f64_bin(raw); /* number is accurate */\n        }\n        /* now the number is the correct value, or the next lower value */\n        \n        /* upper boundary */\n        if (raw & F64_EXP_MASK) {\n            fp_upper.sig = (raw & F64_SIG_MASK) + ((u64)1 << F64_SIG_BITS);\n            fp_upper.exp = (i32)((raw & F64_EXP_MASK) >> F64_SIG_BITS);\n        } else {\n            fp_upper.sig = (raw & F64_SIG_MASK);\n            fp_upper.exp = 1;\n        }\n        fp_upper.exp -= F64_EXP_BIAS + F64_SIG_BITS;\n        fp_upper.sig <<= 1;\n        fp_upper.exp -= 1;\n        fp_upper.sig += 1; /* add half ulp */\n        \n        /* compare with bigint */\n        bigint_set_buf(&big_full, sig, &exp, sig_cut, sig_end, dot_pos);\n        bigint_set_u64(&big_comp, fp_upper.sig);\n        if (exp >= 0) {\n            bigint_mul_pow10(&big_full, +exp);\n        } else {\n            bigint_mul_pow10(&big_comp, -exp);\n        }\n        if (fp_upper.exp > 0) {\n            bigint_mul_pow2(&big_comp, (u32)+fp_upper.exp);\n        } else {\n            bigint_mul_pow2(&big_full, (u32)-fp_upper.exp);\n        }\n        cmp = bigint_cmp(&big_full, &big_comp);\n        if (likely(cmp != 0)) {\n            /* round down or round up */\n            raw += (cmp > 0);\n        } else {\n            /* falls midway, round to even */\n            raw += (raw & 1);\n        }\n        \n        if (unlikely(raw == F64_RAW_INF)) return_inf();\n        return_f64_bin(raw);\n    }\n    \n#undef return_err\n#undef return_inf\n#undef return_0\n#undef return_i64\n#undef return_f64\n#undef return_f64_bin\n#undef return_raw\n}\n\n\n\n#else /* FP_READER */\n\n/**\n Read a JSON number.\n This is a fallback function if the custom number reader is disabled.\n This function use libc's strtod() to read floating-point number.\n */\nstatic_inline bool read_number(u8 **ptr,\n                               yyjson_val *val,\n                               const char **msg) {\n    \n#define return_err(_pos, _msg) do { \\\n    *msg = _msg; \\\n    *end = _pos; \\\n    return false; \\\n} while (false)\n    \n#define return_0() do { \\\n    val->tag = YYJSON_TYPE_NUM | (u64)((u8)sign << 3); \\\n    val->uni.u64 = 0; \\\n    *end = cur; return true; \\\n} while (false)\n\n#define return_i64(_v) do { \\\n    val->tag = YYJSON_TYPE_NUM | (u64)((u8)sign << 3); \\\n    val->uni.u64 = (u64)(sign ? (u64)(~(_v) + 1) : (u64)(_v)); \\\n    *end = cur; return true; \\\n} while (false)\n    \n#define return_f64(_v) do { \\\n    val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL; \\\n    val->uni.f64 = sign ? -(f64)(_v) : (f64)(_v); \\\n    *end = cur; return true; \\\n} while (false)\n    \n#define return_f64_bin(_v) do { \\\n    val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL; \\\n    val->uni.u64 = ((u64)sign << 63) | (u64)(_v); \\\n    *end = cur; return true; \\\n} while (false)\n    \n#define return_inf() do { \\\n    if (false) return_f64_bin(F64_RAW_INF); \\\n    else return_err(hdr, \"number is infinity when parsed as double\"); \\\n} while (false)\n    \n    u64 sig, num;\n    u8 *hdr = *ptr;\n    u8 *cur = *ptr;\n    u8 **end = ptr;\n    u8 *dot = NULL;\n    u8 *f64_end = NULL;\n    bool sign;\n    \n    /* read number as raw string if has `YYJSON_READ_NUMBER_AS_RAW` flag */\n    if (unlikely(false)) {\n        return read_number_raw(ptr, pre, flg, val, msg);\n    }\n    \n    sign = (*hdr == '-');\n    cur += sign;\n    sig = (u8)(*cur - '0');\n    \n    /* read first digit, check leading zero */\n    if (unlikely(!digi_is_digit(*cur))) {\n        return_err(cur, \"no digit after minus sign\");\n    }\n    if (*cur == '0') {\n        cur++;\n        if (unlikely(digi_is_digit(*cur))) {\n            return_err(cur - 1, \"number with leading zero is not allowed\");\n        }\n        if (!digi_is_fp(*cur)) return_0();\n        goto read_double;\n    }\n    \n    /* read continuous digits, up to 19 characters */\n#define expr_intg(i) \\\n    if (likely((num = (u64)(cur[i] - (u8)'0')) <= 9)) sig = num + sig * 10; \\\n    else { cur += i; goto intg_end; }\n    repeat_in_1_18(expr_intg)\n#undef expr_intg\n    \n    /* here are 19 continuous digits, skip them */\n    cur += 19;\n    if (digi_is_digit(cur[0]) && !digi_is_digit_or_fp(cur[1])) {\n        /* this number is an integer consisting of 20 digits */\n        num = (u8)(*cur - '0');\n        if ((sig < (U64_MAX / 10)) ||\n            (sig == (U64_MAX / 10) && num <= (U64_MAX % 10))) {\n            sig = num + sig * 10;\n            cur++;\n            if (sign) {\n                if (false) return_raw();\n                return_f64(normalized_u64_to_f64(sig));\n            }\n            return_i64(sig);\n        }\n    }\n    \nintg_end:\n    /* continuous digits ended */\n    if (!digi_is_digit_or_fp(*cur)) {\n        /* this number is an integer consisting of 1 to 19 digits */\n        if (sign && (sig > ((u64)1 << 63))) {\n            if (false) return_raw();\n            return_f64(normalized_u64_to_f64(sig));\n        }\n        return_i64(sig);\n    }\n    \nread_double:\n    /* this number should be read as double */\n    while (digi_is_digit(*cur)) cur++;\n    if (*cur == '.') {\n        /* skip fraction part */\n        dot = cur;\n        cur++;\n        if (!digi_is_digit(*cur)) {\n            return_err(cur, \"no digit after decimal point\");\n        }\n        cur++;\n        while (digi_is_digit(*cur)) cur++;\n    }\n    if (digi_is_exp(*cur)) {\n        /* skip exponent part */\n        cur += 1 + digi_is_sign(cur[1]);\n        if (!digi_is_digit(*cur)) {\n            return_err(cur, \"no digit after exponent sign\");\n        }\n        cur++;\n        while (digi_is_digit(*cur)) cur++;\n    }\n    \n    /*\n     libc's strtod() is used to parse the floating-point number.\n     \n     Note that the decimal point character used by strtod() is locale-dependent,\n     and the rounding direction may affected by fesetround().\n     \n     For currently known locales, (en, zh, ja, ko, am, he, hi) use '.' as the\n     decimal point, while other locales use ',' as the decimal point.\n     \n     Here strtod() is called twice for different locales, but if another thread\n     happens calls setlocale() between two strtod(), parsing may still fail.\n     */\n    val->uni.f64 = strtod((const char *)hdr, (char **)&f64_end);\n    if (unlikely(f64_end != cur)) {\n        /* replace '.' with ',' for locale */\n        bool cut = (*cur == ',');\n        if (cut) *cur = ' ';\n        if (dot) *dot = ',';\n        val->uni.f64 = strtod((const char *)hdr, (char **)&f64_end);\n        /* restore ',' to '.' */\n        if (cut) *cur = ',';\n        if (dot) *dot = '.';\n        if (unlikely(f64_end != cur)) {\n            return_err(hdr, \"strtod() failed to parse the number\");\n        }\n    }\n    if (unlikely(val->uni.f64 >= HUGE_VAL || val->uni.f64 <= -HUGE_VAL)) {\n        return_inf();\n    }\n    val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL;\n    *end = cur;\n    return true;\n    \n#undef return_err\n#undef return_0\n#undef return_i64\n#undef return_f64\n#undef return_f64_bin\n#undef return_inf\n#undef return_raw\n}\n\n#endif /* FP_READER */\n\n\n\n/*==============================================================================\n * JSON String Reader\n *============================================================================*/\n\n/**\n Read a JSON string.\n @param ptr The head pointer of string before '\"' prefix (inout).\n @param lst JSON last position.\n @param inv Allow invalid unicode.\n @param val The string value to be written.\n @param msg The error message pointer.\n @return Whether success.\n */\nstatic_inline bool read_string(u8 **ptr,\n                               u8 *lst,\n                               yyjson_val *val,\n                               const char **msg) {\n    /*\n     Each unicode code point is encoded as 1 to 4 bytes in UTF-8 encoding,\n     we use 4-byte mask and pattern value to validate UTF-8 byte sequence,\n     this requires the input data to have 4-byte zero padding.\n     ---------------------------------------------------\n     1 byte\n     unicode range [U+0000, U+007F]\n     unicode min   [.......0]\n     unicode max   [.1111111]\n     bit pattern   [0.......]\n     ---------------------------------------------------\n     2 byte\n     unicode range [U+0080, U+07FF]\n     unicode min   [......10 ..000000]\n     unicode max   [...11111 ..111111]\n     bit require   [...xxxx. ........] (1E 00)\n     bit mask      [xxx..... xx......] (E0 C0)\n     bit pattern   [110..... 10......] (C0 80)\n     ---------------------------------------------------\n     3 byte\n     unicode range [U+0800, U+FFFF]\n     unicode min   [........ ..100000 ..000000]\n     unicode max   [....1111 ..111111 ..111111]\n     bit require   [....xxxx ..x..... ........] (0F 20 00)\n     bit mask      [xxxx.... xx...... xx......] (F0 C0 C0)\n     bit pattern   [1110.... 10...... 10......] (E0 80 80)\n     ---------------------------------------------------\n     3 byte invalid (reserved for surrogate halves)\n     unicode range [U+D800, U+DFFF]\n     unicode min   [....1101 ..100000 ..000000]\n     unicode max   [....1101 ..111111 ..111111]\n     bit mask      [....xxxx ..x..... ........] (0F 20 00)\n     bit pattern   [....1101 ..1..... ........] (0D 20 00)\n     ---------------------------------------------------\n     4 byte\n     unicode range [U+10000, U+10FFFF]\n     unicode min   [........ ...10000 ..000000 ..000000]\n     unicode max   [.....100 ..001111 ..111111 ..111111]\n     bit require   [.....xxx ..xx.... ........ ........] (07 30 00 00)\n     bit mask      [xxxxx... xx...... xx...... xx......] (F8 C0 C0 C0)\n     bit pattern   [11110... 10...... 10...... 10......] (F0 80 80 80)\n     ---------------------------------------------------\n     */\n#if YYJSON_ENDIAN == YYJSON_BIG_ENDIAN\n    const u32 b1_mask = 0x80000000UL;\n    const u32 b1_patt = 0x00000000UL;\n    const u32 b2_mask = 0xE0C00000UL;\n    const u32 b2_patt = 0xC0800000UL;\n    const u32 b2_requ = 0x1E000000UL;\n    const u32 b3_mask = 0xF0C0C000UL;\n    const u32 b3_patt = 0xE0808000UL;\n    const u32 b3_requ = 0x0F200000UL;\n    const u32 b3_erro = 0x0D200000UL;\n    const u32 b4_mask = 0xF8C0C0C0UL;\n    const u32 b4_patt = 0xF0808080UL;\n    const u32 b4_requ = 0x07300000UL;\n    const u32 b4_err0 = 0x04000000UL;\n    const u32 b4_err1 = 0x03300000UL;\n#elif YYJSON_ENDIAN == YYJSON_LITTLE_ENDIAN\n    const u32 b1_mask = 0x00000080UL;\n    const u32 b1_patt = 0x00000000UL;\n    const u32 b2_mask = 0x0000C0E0UL;\n    const u32 b2_patt = 0x000080C0UL;\n    const u32 b2_requ = 0x0000001EUL;\n    const u32 b3_mask = 0x00C0C0F0UL;\n    const u32 b3_patt = 0x008080E0UL;\n    const u32 b3_requ = 0x0000200FUL;\n    const u32 b3_erro = 0x0000200DUL;\n    const u32 b4_mask = 0xC0C0C0F8UL;\n    const u32 b4_patt = 0x808080F0UL;\n    const u32 b4_requ = 0x00003007UL;\n    const u32 b4_err0 = 0x00000004UL;\n    const u32 b4_err1 = 0x00003003UL;\n#else\n    /* this should be evaluated at compile-time */\n    v32_uni b1_mask_uni = {{ 0x80, 0x00, 0x00, 0x00 }};\n    v32_uni b1_patt_uni = {{ 0x00, 0x00, 0x00, 0x00 }};\n    v32_uni b2_mask_uni = {{ 0xE0, 0xC0, 0x00, 0x00 }};\n    v32_uni b2_patt_uni = {{ 0xC0, 0x80, 0x00, 0x00 }};\n    v32_uni b2_requ_uni = {{ 0x1E, 0x00, 0x00, 0x00 }};\n    v32_uni b3_mask_uni = {{ 0xF0, 0xC0, 0xC0, 0x00 }};\n    v32_uni b3_patt_uni = {{ 0xE0, 0x80, 0x80, 0x00 }};\n    v32_uni b3_requ_uni = {{ 0x0F, 0x20, 0x00, 0x00 }};\n    v32_uni b3_erro_uni = {{ 0x0D, 0x20, 0x00, 0x00 }};\n    v32_uni b4_mask_uni = {{ 0xF8, 0xC0, 0xC0, 0xC0 }};\n    v32_uni b4_patt_uni = {{ 0xF0, 0x80, 0x80, 0x80 }};\n    v32_uni b4_requ_uni = {{ 0x07, 0x30, 0x00, 0x00 }};\n    v32_uni b4_err0_uni = {{ 0x04, 0x00, 0x00, 0x00 }};\n    v32_uni b4_err1_uni = {{ 0x03, 0x30, 0x00, 0x00 }};\n    u32 b1_mask = b1_mask_uni.u;\n    u32 b1_patt = b1_patt_uni.u;\n    u32 b2_mask = b2_mask_uni.u;\n    u32 b2_patt = b2_patt_uni.u;\n    u32 b2_requ = b2_requ_uni.u;\n    u32 b3_mask = b3_mask_uni.u;\n    u32 b3_patt = b3_patt_uni.u;\n    u32 b3_requ = b3_requ_uni.u;\n    u32 b3_erro = b3_erro_uni.u;\n    u32 b4_mask = b4_mask_uni.u;\n    u32 b4_patt = b4_patt_uni.u;\n    u32 b4_requ = b4_requ_uni.u;\n    u32 b4_err0 = b4_err0_uni.u;\n    u32 b4_err1 = b4_err1_uni.u;\n#endif\n    \n#define is_valid_seq_1(uni) ( \\\n    ((uni & b1_mask) == b1_patt) \\\n)\n\n#define is_valid_seq_2(uni) ( \\\n    ((uni & b2_mask) == b2_patt) && \\\n    ((uni & b2_requ)) \\\n)\n    \n#define is_valid_seq_3(uni) ( \\\n    ((uni & b3_mask) == b3_patt) && \\\n    ((tmp = (uni & b3_requ))) && \\\n    ((tmp != b3_erro)) \\\n)\n    \n#define is_valid_seq_4(uni) ( \\\n    ((uni & b4_mask) == b4_patt) && \\\n    ((tmp = (uni & b4_requ))) && \\\n    ((tmp & b4_err0) == 0 || (tmp & b4_err1) == 0) \\\n)\n    \n#define return_err(_end, _msg) do { \\\n    *msg = _msg; \\\n    *end = _end; \\\n    return false; \\\n} while (false)\n    \n    u8 *cur = *ptr;\n    u8 **end = ptr;\n    u8 *src = ++cur, *dst;\n    u16 hi, lo;\n    u32 uni, tmp;\n    \nskip_ascii:\n    /* Most strings have no escaped characters, so we can jump them quickly. */\n    \nskip_ascii_begin:\n    /*\n     We want to make loop unrolling, as shown in the following code. Some\n     compiler may not generate instructions as expected, so we rewrite it with\n     explicit goto statements. We hope the compiler can generate instructions\n     like this: https://godbolt.org/z/8vjsYq\n     \n         while (true) repeat16({\n            if (likely(!(char_is_ascii_stop(*src)))) src++;\n            else break;\n         })\n     */\n#define expr_jump(i) \\\n    if (likely(!char_is_ascii_stop(src[i]))) {} \\\n    else goto skip_ascii_stop##i;\n    \n#define expr_stop(i) \\\n    skip_ascii_stop##i: \\\n    src += i; \\\n    goto skip_ascii_end;\n    \n    repeat16_incr(expr_jump)\n    src += 16;\n    goto skip_ascii_begin;\n    repeat16_incr(expr_stop)\n    \n#undef expr_jump\n#undef expr_stop\n    \nskip_ascii_end:\n    \n    /*\n     GCC may store src[i] in a register at each line of expr_jump(i) above.\n     These instructions are useless and will degrade performance.\n     This inline asm is a hint for gcc: \"the memory has been modified,\n     do not cache it\".\n     \n     MSVC, Clang, ICC can generate expected instructions without this hint.\n     */\n#if YYJSON_IS_REAL_GCC\n    __asm__ volatile(\"\":\"=m\"(*src));\n#endif\n    if (likely(*src == '\"')) {\n        val->tag = ((u64)(src - cur) << YYJSON_TAG_BIT) |\n                    (u64)(YYJSON_TYPE_STR);\n        val->uni.str = (const char *)cur;\n        *src = '\\0';\n        *end = src + 1;\n        return true;\n    }\n    \nskip_utf8:\n    if (*src & 0x80) { /* non-ASCII character */\n        /*\n         Non-ASCII character appears here, which means that the text is likely\n         to be written in non-English or emoticons. According to some common\n         data set statistics, byte sequences of the same length may appear\n         consecutively. We process the byte sequences of the same length in each\n         loop, which is more friendly to branch prediction.\n         */\n#if YYJSON_DISABLE_UTF8_VALIDATION\n        while (true) repeat8({\n            if (likely((*src & 0xF0) == 0xE0)) src += 3;\n            else break;\n        })\n        if (*src < 0x80) goto skip_ascii;\n        while (true) repeat8({\n            if (likely((*src & 0xE0) == 0xC0)) src += 2;\n            else break;\n        })\n        while (true) repeat8({\n            if (likely((*src & 0xF8) == 0xF0)) src += 4;\n            else break;\n        })\n#else\n        uni = byte_load_4(src);\n        while (is_valid_seq_3(uni)) {\n            src += 3;\n            uni = byte_load_4(src);\n        }\n        if (is_valid_seq_1(uni)) goto skip_ascii;\n        while (is_valid_seq_2(uni)) {\n            src += 2;\n            uni = byte_load_4(src);\n        }\n        while (is_valid_seq_4(uni)) {\n            src += 4;\n            uni = byte_load_4(src);\n        }\n#endif\n        goto skip_ascii;\n    }\n    \n    /* The escape character appears, we need to copy it. */\n    dst = src;\ncopy_escape:\n    if (likely(*src == '\\\\')) {\n        switch (*++src) {\n            case '\"':  *dst++ = '\"';  src++; break;\n            case '\\\\': *dst++ = '\\\\'; src++; break;\n            case '/':  *dst++ = '/';  src++; break;\n            case 'b':  *dst++ = '\\b'; src++; break;\n            case 'f':  *dst++ = '\\f'; src++; break;\n            case 'n':  *dst++ = '\\n'; src++; break;\n            case 'r':  *dst++ = '\\r'; src++; break;\n            case 't':  *dst++ = '\\t'; src++; break;\n            case 'u':\n                if (unlikely(!read_hex_u16(++src, &hi))) {\n                    return_err(src - 2, \"invalid escaped sequence in string\");\n                }\n                src += 4;\n                if (likely((hi & 0xF800) != 0xD800)) {\n                    /* a BMP character */\n                    if (hi >= 0x800) {\n                        *dst++ = (u8)(0xE0 | (hi >> 12));\n                        *dst++ = (u8)(0x80 | ((hi >> 6) & 0x3F));\n                        *dst++ = (u8)(0x80 | (hi & 0x3F));\n                    } else if (hi >= 0x80) {\n                        *dst++ = (u8)(0xC0 | (hi >> 6));\n                        *dst++ = (u8)(0x80 | (hi & 0x3F));\n                    } else {\n                        *dst++ = (u8)hi;\n                    }\n                } else {\n                    /* a non-BMP character, represented as a surrogate pair */\n                    if (unlikely((hi & 0xFC00) != 0xD800)) {\n                        return_err(src - 6, \"invalid high surrogate in string\");\n                    }\n                    if (unlikely(!byte_match_2(src, \"\\\\u\"))) {\n                        return_err(src, \"no low surrogate in string\");\n                    }\n                    if (unlikely(!read_hex_u16(src + 2, &lo))) {\n                        return_err(src, \"invalid escaped sequence in string\");\n                    }\n                    if (unlikely((lo & 0xFC00) != 0xDC00)) {\n                        return_err(src, \"invalid low surrogate in string\");\n                    }\n                    uni = ((((u32)hi - 0xD800) << 10) |\n                            ((u32)lo - 0xDC00)) + 0x10000;\n                    *dst++ = (u8)(0xF0 | (uni >> 18));\n                    *dst++ = (u8)(0x80 | ((uni >> 12) & 0x3F));\n                    *dst++ = (u8)(0x80 | ((uni >> 6) & 0x3F));\n                    *dst++ = (u8)(0x80 | (uni & 0x3F));\n                    src += 6;\n                }\n                break;\n            default: return_err(src, \"invalid escaped character in string\");\n        }\n    } else if (likely(*src == '\"')) {\n        val->tag = ((u64)(dst - cur) << YYJSON_TAG_BIT) | YYJSON_TYPE_STR;\n        val->uni.str = (const char *)cur;\n        *end = src + 1;\n        return true;\n    } else {\n        return_err(src, \"unexpected control character in string\");\n    }\n    \ncopy_ascii:\n    /*\n     Copy continuous ASCII, loop unrolling, same as the following code:\n     \n         while (true) repeat16({\n            if (unlikely(char_is_ascii_stop(*src))) break;\n            *dst++ = *src++;\n         })\n     */\n#if YYJSON_IS_REAL_GCC\n#   define expr_jump(i) \\\n    if (likely(!(char_is_ascii_stop(src[i])))) {} \\\n    else { __asm__ volatile(\"\":\"=m\"(src[i])); goto copy_ascii_stop_##i; }\n#else\n#   define expr_jump(i) \\\n    if (likely(!(char_is_ascii_stop(src[i])))) {} \\\n    else { goto copy_ascii_stop_##i; }\n#endif\n    repeat16_incr(expr_jump)\n#undef expr_jump\n    \n    byte_move_16(dst, src);\n    src += 16;\n    dst += 16;\n    goto copy_ascii;\n    \n    /*\n     The memory will be moved forward by at least 1 byte. So the `byte_move`\n     can be one byte more than needed to reduce the number of instructions.\n     */\ncopy_ascii_stop_0:\n    goto copy_utf8;\ncopy_ascii_stop_1:\n    byte_move_2(dst, src);\n    src += 1;\n    dst += 1;\n    goto copy_utf8;\ncopy_ascii_stop_2:\n    byte_move_2(dst, src);\n    src += 2;\n    dst += 2;\n    goto copy_utf8;\ncopy_ascii_stop_3:\n    byte_move_4(dst, src);\n    src += 3;\n    dst += 3;\n    goto copy_utf8;\ncopy_ascii_stop_4:\n    byte_move_4(dst, src);\n    src += 4;\n    dst += 4;\n    goto copy_utf8;\ncopy_ascii_stop_5:\n    byte_move_4(dst, src);\n    byte_move_2(dst + 4, src + 4);\n    src += 5;\n    dst += 5;\n    goto copy_utf8;\ncopy_ascii_stop_6:\n    byte_move_4(dst, src);\n    byte_move_2(dst + 4, src + 4);\n    src += 6;\n    dst += 6;\n    goto copy_utf8;\ncopy_ascii_stop_7:\n    byte_move_8(dst, src);\n    src += 7;\n    dst += 7;\n    goto copy_utf8;\ncopy_ascii_stop_8:\n    byte_move_8(dst, src);\n    src += 8;\n    dst += 8;\n    goto copy_utf8;\ncopy_ascii_stop_9:\n    byte_move_8(dst, src);\n    byte_move_2(dst + 8, src + 8);\n    src += 9;\n    dst += 9;\n    goto copy_utf8;\ncopy_ascii_stop_10:\n    byte_move_8(dst, src);\n    byte_move_2(dst + 8, src + 8);\n    src += 10;\n    dst += 10;\n    goto copy_utf8;\ncopy_ascii_stop_11:\n    byte_move_8(dst, src);\n    byte_move_4(dst + 8, src + 8);\n    src += 11;\n    dst += 11;\n    goto copy_utf8;\ncopy_ascii_stop_12:\n    byte_move_8(dst, src);\n    byte_move_4(dst + 8, src + 8);\n    src += 12;\n    dst += 12;\n    goto copy_utf8;\ncopy_ascii_stop_13:\n    byte_move_8(dst, src);\n    byte_move_4(dst + 8, src + 8);\n    byte_move_2(dst + 12, src + 12);\n    src += 13;\n    dst += 13;\n    goto copy_utf8;\ncopy_ascii_stop_14:\n    byte_move_8(dst, src);\n    byte_move_4(dst + 8, src + 8);\n    byte_move_2(dst + 12, src + 12);\n    src += 14;\n    dst += 14;\n    goto copy_utf8;\ncopy_ascii_stop_15:\n    byte_move_16(dst, src);\n    src += 15;\n    dst += 15;\n    goto copy_utf8;\n    \ncopy_utf8:\n    if (*src & 0x80) { /* non-ASCII character */\n        uni = byte_load_4(src);\n#if YYJSON_DISABLE_UTF8_VALIDATION\n        while (true) repeat4({\n            if ((uni & b3_mask) == b3_patt) {\n                byte_copy_4(dst, &uni);\n                dst += 3;\n                src += 3;\n                uni = byte_load_4(src);\n            } else break;\n        })\n        if ((uni & b1_mask) == b1_patt) goto copy_ascii;\n        while (true) repeat4({\n            if ((uni & b2_mask) == b2_patt) {\n                byte_copy_2(dst, &uni);\n                dst += 2;\n                src += 2;\n                uni = byte_load_4(src);\n            } else break;\n        })\n        while (true) repeat4({\n            if ((uni & b4_mask) == b4_patt) {\n                byte_copy_4(dst, &uni);\n                dst += 4;\n                src += 4;\n                uni = byte_load_4(src);\n            } else break;\n        })\n#else\n        while (is_valid_seq_3(uni)) {\n            byte_copy_4(dst, &uni);\n            dst += 3;\n            src += 3;\n            uni = byte_load_4(src);\n        }\n        if (is_valid_seq_1(uni)) goto copy_ascii;\n        while (is_valid_seq_2(uni)) {\n            byte_copy_2(dst, &uni);\n            dst += 2;\n            src += 2;\n            uni = byte_load_4(src);\n        }\n        while (is_valid_seq_4(uni)) {\n            byte_copy_4(dst, &uni);\n            dst += 4;\n            src += 4;\n            uni = byte_load_4(src);\n        }\n#endif\n        goto copy_ascii;\n    }\n    goto copy_escape;\n    \n#undef return_err\n#undef is_valid_seq_1\n#undef is_valid_seq_2\n#undef is_valid_seq_3\n#undef is_valid_seq_4\n}\n\n\n\n/*==============================================================================\n * JSON Reader Implementation\n *\n * We use goto statements to build the finite state machine (FSM).\n * The FSM's state was held by program counter (PC) and the 'goto' make the\n * state transitions.\n *============================================================================*/\n\n/** Read single value JSON document. */\nstatic_noinline yyjson_doc *read_root_single(u8 *hdr,\n                                             u8 *cur,\n                                             u8 *end,\n                                             yyjson_alc alc,\n                                             yyjson_read_err *err) {\n    \n#define return_err(_pos, _code, _msg) do { \\\n    if (is_truncated_end(hdr, _pos, end, YYJSON_READ_ERROR_##_code)) { \\\n        err->pos = (usize)(end - hdr); \\\n        err->code = YYJSON_READ_ERROR_UNEXPECTED_END; \\\n        err->msg = \"unexpected end of data\"; \\\n    } else { \\\n        err->pos = (usize)(_pos - hdr); \\\n        err->code = YYJSON_READ_ERROR_##_code; \\\n        err->msg = _msg; \\\n    } \\\n    if (val_hdr) alc.free(alc.ctx, (void *)val_hdr); \\\n    return NULL; \\\n} while (false)\n    \n    usize hdr_len; /* value count used by doc */\n    usize alc_num; /* value count capacity */\n    yyjson_val *val_hdr; /* the head of allocated values */\n    yyjson_val *val; /* current value */\n    yyjson_doc *doc; /* the JSON document, equals to val_hdr */\n    const char *msg; /* error message */\n    \n    hdr_len = sizeof(yyjson_doc) / sizeof(yyjson_val);\n    hdr_len += (sizeof(yyjson_doc) % sizeof(yyjson_val)) > 0;\n    alc_num = hdr_len + 1; /* single value */\n    \n    val_hdr = (yyjson_val *)alc.malloc(alc.ctx, alc_num * sizeof(yyjson_val));\n    if (unlikely(!val_hdr)) goto fail_alloc;\n    val = val_hdr + hdr_len;\n    \n    if (char_is_number(*cur)) {\n        if (likely(read_number(&cur, val, &msg))) goto doc_end;\n        goto fail_number;\n    }\n    if (*cur == '\"') {\n        if (likely(read_string(&cur, end, val, &msg))) goto doc_end;\n        goto fail_string;\n    }\n    if (*cur == 't') {\n        if (likely(read_true(&cur, val))) goto doc_end;\n        goto fail_literal;\n    }\n    if (*cur == 'f') {\n        if (likely(read_false(&cur, val))) goto doc_end;\n        goto fail_literal;\n    }\n    if (*cur == 'n') {\n        if (likely(read_null(&cur, val))) goto doc_end;\n        if (false) {\n            if (read_nan(false, &cur, 0, val)) goto doc_end;\n        }\n        goto fail_literal;\n    }\n    goto fail_character;\n    \ndoc_end:\n    /* check invalid contents after json document */\n    if (unlikely(cur < end) && !has_read_flag(STOP_WHEN_DONE)) {\n        if (false) {\n            if (!skip_spaces_and_comments(&cur)) {\n                if (byte_match_2(cur, \"/*\")) goto fail_comment;\n            }\n        } else {\n            while (char_is_space(*cur)) cur++;\n        }\n        if (unlikely(cur < end)) goto fail_garbage;\n    }\n    \n    doc = (yyjson_doc *)val_hdr;\n    doc->root = val_hdr + hdr_len;\n    doc->alc = alc;\n    doc->dat_read = (usize)(cur - hdr);\n    doc->val_read = 1;\n    doc->str_pool = (char *)hdr;\n    return doc;\n    \nfail_string:\n    return_err(cur, INVALID_STRING, msg);\nfail_number:\n    return_err(cur, INVALID_NUMBER, msg);\nfail_alloc:\n    return_err(cur, MEMORY_ALLOCATION, \"memory allocation failed\");\nfail_literal:\n    return_err(cur, LITERAL, \"invalid literal\");\nfail_comment:\n    return_err(cur, INVALID_COMMENT, \"unclosed multiline comment\");\nfail_character:\n    return_err(cur, UNEXPECTED_CHARACTER, \"unexpected character\");\nfail_garbage:\n    return_err(cur, UNEXPECTED_CONTENT, \"unexpected content after document\");\nfail_recursion:\n    return_err(cur, RECURSION_DEPTH, \"array and object recursion depth exceeded\");\n    \n#undef return_err\n}\n\n/** Read JSON document (accept all style, but optimized for minify). */\nstatic_inline yyjson_doc *read_root_minify(u8 *hdr,\n                                           u8 *cur,\n                                           u8 *end,\n                                           yyjson_alc alc,\n                                           yyjson_read_err *err) {\n    \n#define return_err(_pos, _code, _msg) do { \\\n    if (is_truncated_end(hdr, _pos, end, YYJSON_READ_ERROR_##_code)) { \\\n        err->pos = (usize)(end - hdr); \\\n        err->code = YYJSON_READ_ERROR_UNEXPECTED_END; \\\n        err->msg = \"unexpected end of data\"; \\\n    } else { \\\n        err->pos = (usize)(_pos - hdr); \\\n        err->code = YYJSON_READ_ERROR_##_code; \\\n        err->msg = _msg; \\\n    } \\\n    if (val_hdr) alc.free(alc.ctx, (void *)val_hdr); \\\n    return NULL; \\\n} while (false)\n    \n#define val_incr() do { \\\n    val++; \\\n    if (unlikely(val >= val_end)) { \\\n        usize alc_old = alc_len; \\\n        alc_len += alc_len / 2; \\\n        if ((sizeof(usize) < 8) && (alc_len >= alc_max)) goto fail_alloc; \\\n        val_tmp = (yyjson_val *)alc.realloc(alc.ctx, (void *)val_hdr, \\\n            alc_old * sizeof(yyjson_val), \\\n            alc_len * sizeof(yyjson_val)); \\\n        if ((!val_tmp)) goto fail_alloc; \\\n        val = val_tmp + (usize)(val - val_hdr); \\\n        ctn = val_tmp + (usize)(ctn - val_hdr); \\\n        val_hdr = val_tmp; \\\n        val_end = val_tmp + (alc_len - 2); \\\n    } \\\n} while (false)\n    \n    usize dat_len; /* data length in bytes, hint for allocator */\n    usize hdr_len; /* value count used by yyjson_doc */\n    usize alc_len; /* value count allocated */\n    usize alc_max; /* maximum value count for allocator */\n    usize ctn_len; /* the number of elements in current container */\n    yyjson_val *val_hdr; /* the head of allocated values */\n    yyjson_val *val_end; /* the end of allocated values */\n    yyjson_val *val_tmp; /* temporary pointer for realloc */\n    yyjson_val *val; /* current JSON value */\n    yyjson_val *ctn; /* current container */\n    yyjson_val *ctn_parent; /* parent of current container */\n    yyjson_doc *doc; /* the JSON document, equals to val_hdr */\n    const char *msg; /* error message */\n\n    u32 container_depth = 0; /* limit on number of open array and map */\n    bool raw; /* read number as raw */\n    bool inv; /* allow invalid unicode */\n    \n    dat_len = has_read_flag(STOP_WHEN_DONE) ? 256 : (usize)(end - cur);\n    hdr_len = sizeof(yyjson_doc) / sizeof(yyjson_val);\n    hdr_len += (sizeof(yyjson_doc) % sizeof(yyjson_val)) > 0;\n    alc_max = USIZE_MAX / sizeof(yyjson_val);\n    alc_len = hdr_len + (dat_len / YYJSON_READER_ESTIMATED_MINIFY_RATIO) + 4;\n    alc_len = yyjson_min(alc_len, alc_max);\n    \n    val_hdr = (yyjson_val *)alc.malloc(alc.ctx, alc_len * sizeof(yyjson_val));\n    if (unlikely(!val_hdr)) goto fail_alloc;\n    val_end = val_hdr + (alc_len - 2); /* padding for key-value pair reading */\n    val = val_hdr + hdr_len;\n    ctn = val;\n    ctn_len = 0;\n\n    if (*cur++ == '{') {\n        ctn->tag = YYJSON_TYPE_OBJ;\n        ctn->uni.ofs = 0;\n        goto obj_key_begin;\n    } else {\n        ctn->tag = YYJSON_TYPE_ARR;\n        ctn->uni.ofs = 0;\n        goto arr_val_begin;\n    }\n    \narr_begin:\n    container_depth++;\n    if (unlikely(container_depth >= YYJSON_READER_CONTAINER_RECURSION_LIMIT)) {\n        goto fail_recursion;\n    }\n\n    /* save current container */\n    ctn->tag = (((u64)ctn_len + 1) << YYJSON_TAG_BIT) |\n               (ctn->tag & YYJSON_TAG_MASK);\n    \n    /* create a new array value, save parent container offset */\n    val_incr();\n    val->tag = YYJSON_TYPE_ARR;\n    val->uni.ofs = (usize)((u8 *)val - (u8 *)ctn);\n    \n    /* push the new array value as current container */\n    ctn = val;\n    ctn_len = 0;\n    \narr_val_begin:\n    if (*cur == '{') {\n        cur++;\n        goto obj_begin;\n    }\n    if (*cur == '[') {\n        cur++;\n        goto arr_begin;\n    }\n    if (char_is_number(*cur)) {\n        val_incr();\n        ctn_len++;\n        if (likely(read_number(&cur, val, &msg))) goto arr_val_end;\n        goto fail_number;\n    }\n    if (*cur == '\"') {\n        val_incr();\n        ctn_len++;\n        if (likely(read_string(&cur, end, val, &msg))) goto arr_val_end;\n        goto fail_string;\n    }\n    if (*cur == 't') {\n        val_incr();\n        ctn_len++;\n        if (likely(read_true(&cur, val))) goto arr_val_end;\n        goto fail_literal;\n    }\n    if (*cur == 'f') {\n        val_incr();\n        ctn_len++;\n        if (likely(read_false(&cur, val))) goto arr_val_end;\n        goto fail_literal;\n    }\n    if (*cur == 'n') {\n        val_incr();\n        ctn_len++;\n        if (likely(read_null(&cur, val))) goto arr_val_end;\n        goto fail_literal;\n    }\n    if (*cur == ']') {\n        cur++;\n        if (likely(ctn_len == 0)) goto arr_end;\n        while (*cur != ',') cur--;\n        goto fail_trailing_comma;\n    }\n    if (char_is_space(*cur)) {\n        while (char_is_space(*++cur));\n        goto arr_val_begin;\n    }\n    goto fail_character;\n    \narr_val_end:\n    if (*cur == ',') {\n        cur++;\n        goto arr_val_begin;\n    }\n    if (*cur == ']') {\n        cur++;\n        goto arr_end;\n    }\n    if (char_is_space(*cur)) {\n        while (char_is_space(*++cur));\n        goto arr_val_end;\n    }\n    if (false) {\n        if (skip_spaces_and_comments(&cur)) goto arr_val_end;\n        if (byte_match_2(cur, \"/*\")) goto fail_comment;\n    }\n    goto fail_character;\n    \narr_end:\n    container_depth--;\n\n    /* get parent container */\n    ctn_parent = (yyjson_val *)(void *)((u8 *)ctn - ctn->uni.ofs);\n    \n    /* save the next sibling value offset */\n    ctn->uni.ofs = (usize)((u8 *)val - (u8 *)ctn) + sizeof(yyjson_val);\n    ctn->tag = ((ctn_len) << YYJSON_TAG_BIT) | YYJSON_TYPE_ARR;\n    if (unlikely(ctn == ctn_parent)) goto doc_end;\n    \n    /* pop parent as current container */\n    ctn = ctn_parent;\n    ctn_len = (usize)(ctn->tag >> YYJSON_TAG_BIT);\n    if ((ctn->tag & YYJSON_TYPE_MASK) == YYJSON_TYPE_OBJ) {\n        goto obj_val_end;\n    } else {\n        goto arr_val_end;\n    }\n    \nobj_begin:\n    container_depth++;\n    if (unlikely(container_depth >= YYJSON_READER_CONTAINER_RECURSION_LIMIT)) {\n        goto fail_recursion;\n    }\n\n    /* push container */\n    ctn->tag = (((u64)ctn_len + 1) << YYJSON_TAG_BIT) |\n               (ctn->tag & YYJSON_TAG_MASK);\n    val_incr();\n    val->tag = YYJSON_TYPE_OBJ;\n    /* offset to the parent */\n    val->uni.ofs = (usize)((u8 *)val - (u8 *)ctn);\n    ctn = val;\n    ctn_len = 0;\n    \nobj_key_begin:\n    if (likely(*cur == '\"')) {\n        val_incr();\n        ctn_len++;\n        if (likely(read_string(&cur, end, val, &msg))) goto obj_key_end;\n        goto fail_string;\n    }\n    if (likely(*cur == '}')) {\n        cur++;\n        if (likely(ctn_len == 0)) goto obj_end;\n        while (*cur != ',') cur--;\n        goto fail_trailing_comma;\n    }\n    if (char_is_space(*cur)) {\n        while (char_is_space(*++cur));\n        goto obj_key_begin;\n    }\n    if (false) {\n        if (skip_spaces_and_comments(&cur)) goto obj_key_begin;\n        if (byte_match_2(cur, \"/*\")) goto fail_comment;\n    }\n    goto fail_character;\n    \nobj_key_end:\n    if (*cur == ':') {\n        cur++;\n        goto obj_val_begin;\n    }\n    if (char_is_space(*cur)) {\n        while (char_is_space(*++cur));\n        goto obj_key_end;\n    }\n    if (false) {\n        if (skip_spaces_and_comments(&cur)) goto obj_key_end;\n        if (byte_match_2(cur, \"/*\")) goto fail_comment;\n    }\n    goto fail_character;\n    \nobj_val_begin:\n    if (*cur == '\"') {\n        val++;\n        ctn_len++;\n        if (likely(read_string(&cur, end, val, &msg))) goto obj_val_end;\n        goto fail_string;\n    }\n    if (char_is_number(*cur)) {\n        val++;\n        ctn_len++;\n        if (likely(read_number(&cur, val, &msg))) goto obj_val_end;\n        goto fail_number;\n    }\n    if (*cur == '{') {\n        cur++;\n        goto obj_begin;\n    }\n    if (*cur == '[') {\n        cur++;\n        goto arr_begin;\n    }\n    if (*cur == 't') {\n        val++;\n        ctn_len++;\n        if (likely(read_true(&cur, val))) goto obj_val_end;\n        goto fail_literal;\n    }\n    if (*cur == 'f') {\n        val++;\n        ctn_len++;\n        if (likely(read_false(&cur, val))) goto obj_val_end;\n        goto fail_literal;\n    }\n    if (*cur == 'n') {\n        val++;\n        ctn_len++;\n        if (likely(read_null(&cur, val))) goto obj_val_end;\n        goto fail_literal;\n    }\n    if (char_is_space(*cur)) {\n        while (char_is_space(*++cur));\n        goto obj_val_begin;\n    }\n    goto fail_character;\n    \nobj_val_end:\n    if (likely(*cur == ',')) {\n        cur++;\n        goto obj_key_begin;\n    }\n    if (likely(*cur == '}')) {\n        cur++;\n        goto obj_end;\n    }\n    if (char_is_space(*cur)) {\n        while (char_is_space(*++cur));\n        goto obj_val_end;\n    }\n    if (false) {\n        if (skip_spaces_and_comments(&cur)) goto obj_val_end;\n        if (byte_match_2(cur, \"/*\")) goto fail_comment;\n    }\n    goto fail_character;\n    \nobj_end:\n    container_depth--;\n\n    /* pop container */\n    ctn_parent = (yyjson_val *)(void *)((u8 *)ctn - ctn->uni.ofs);\n    /* point to the next value */\n    ctn->uni.ofs = (usize)((u8 *)val - (u8 *)ctn) + sizeof(yyjson_val);\n    ctn->tag = (ctn_len << (YYJSON_TAG_BIT - 1)) | YYJSON_TYPE_OBJ;\n    if (unlikely(ctn == ctn_parent)) goto doc_end;\n    ctn = ctn_parent;\n    ctn_len = (usize)(ctn->tag >> YYJSON_TAG_BIT);\n    if ((ctn->tag & YYJSON_TYPE_MASK) == YYJSON_TYPE_OBJ) {\n        goto obj_val_end;\n    } else {\n        goto arr_val_end;\n    }\n    \ndoc_end:\n    /* check invalid contents after json document */\n    if (unlikely(cur < end) && !has_read_flag(STOP_WHEN_DONE)) {\n        if (false) {\n            skip_spaces_and_comments(&cur);\n            if (byte_match_2(cur, \"/*\")) goto fail_comment;\n        } else {\n            while (char_is_space(*cur)) cur++;\n        }\n        if (unlikely(cur < end)) goto fail_garbage;\n    }\n    \n    doc = (yyjson_doc *)val_hdr;\n    doc->root = val_hdr + hdr_len;\n    doc->alc = alc;\n    doc->dat_read = (usize)(cur - hdr);\n    doc->val_read = (usize)((val - doc->root) + 1);\n    doc->str_pool = has_read_flag(INSITU) ? NULL : (char *)hdr;\n    return doc;\n    \nfail_string:\n    return_err(cur, INVALID_STRING, msg);\nfail_number:\n    return_err(cur, INVALID_NUMBER, msg);\nfail_alloc:\n    return_err(cur, MEMORY_ALLOCATION, \"memory allocation failed\");\nfail_trailing_comma:\n    return_err(cur, JSON_STRUCTURE, \"trailing comma is not allowed\");\nfail_literal:\n    return_err(cur, LITERAL, \"invalid literal\");\nfail_comment:\n    return_err(cur, INVALID_COMMENT, \"unclosed multiline comment\");\nfail_character:\n    return_err(cur, UNEXPECTED_CHARACTER, \"unexpected character\");\nfail_garbage:\n    return_err(cur, UNEXPECTED_CONTENT, \"unexpected content after document\");\nfail_recursion:\n    return_err(cur, RECURSION_DEPTH, \"array and object recursion depth exceeded\");\n    \n#undef val_incr\n#undef return_err\n}\n\n/** Read JSON document (accept all style, but optimized for pretty). */\nstatic_inline yyjson_doc *read_root_pretty(u8 *hdr,\n                                           u8 *cur,\n                                           u8 *end,\n                                           yyjson_alc alc,\n                                           yyjson_read_err *err) {\n    \n#define return_err(_pos, _code, _msg) do { \\\n    if (is_truncated_end(hdr, _pos, end, YYJSON_READ_ERROR_##_code)) { \\\n        err->pos = (usize)(end - hdr); \\\n        err->code = YYJSON_READ_ERROR_UNEXPECTED_END; \\\n        err->msg = \"unexpected end of data\"; \\\n    } else { \\\n        err->pos = (usize)(_pos - hdr); \\\n        err->code = YYJSON_READ_ERROR_##_code; \\\n        err->msg = _msg; \\\n    } \\\n    if (val_hdr) alc.free(alc.ctx, (void *)val_hdr); \\\n    return NULL; \\\n} while (false)\n    \n#define val_incr() do { \\\n    val++; \\\n    if (unlikely(val >= val_end)) { \\\n        usize alc_old = alc_len; \\\n        alc_len += alc_len / 2; \\\n        if ((sizeof(usize) < 8) && (alc_len >= alc_max)) goto fail_alloc; \\\n        val_tmp = (yyjson_val *)alc.realloc(alc.ctx, (void *)val_hdr, \\\n            alc_old * sizeof(yyjson_val), \\\n            alc_len * sizeof(yyjson_val)); \\\n        if ((!val_tmp)) goto fail_alloc; \\\n        val = val_tmp + (usize)(val - val_hdr); \\\n        ctn = val_tmp + (usize)(ctn - val_hdr); \\\n        val_hdr = val_tmp; \\\n        val_end = val_tmp + (alc_len - 2); \\\n    } \\\n} while (false)\n    \n    usize dat_len; /* data length in bytes, hint for allocator */\n    usize hdr_len; /* value count used by yyjson_doc */\n    usize alc_len; /* value count allocated */\n    usize alc_max; /* maximum value count for allocator */\n    usize ctn_len; /* the number of elements in current container */\n    yyjson_val *val_hdr; /* the head of allocated values */\n    yyjson_val *val_end; /* the end of allocated values */\n    yyjson_val *val_tmp; /* temporary pointer for realloc */\n    yyjson_val *val; /* current JSON value */\n    yyjson_val *ctn; /* current container */\n    yyjson_val *ctn_parent; /* parent of current container */\n    yyjson_doc *doc; /* the JSON document, equals to val_hdr */\n    const char *msg; /* error message */\n\n    u32 container_depth = 0; /* limit on number of open array and map */\n    \n    dat_len = has_read_flag(STOP_WHEN_DONE) ? 256 : (usize)(end - cur);\n    hdr_len = sizeof(yyjson_doc) / sizeof(yyjson_val);\n    hdr_len += (sizeof(yyjson_doc) % sizeof(yyjson_val)) > 0;\n    alc_max = USIZE_MAX / sizeof(yyjson_val);\n    alc_len = hdr_len + (dat_len / YYJSON_READER_ESTIMATED_PRETTY_RATIO) + 4;\n    alc_len = yyjson_min(alc_len, alc_max);\n    \n    val_hdr = (yyjson_val *)alc.malloc(alc.ctx, alc_len * sizeof(yyjson_val));\n    if (unlikely(!val_hdr)) goto fail_alloc;\n    val_end = val_hdr + (alc_len - 2); /* padding for key-value pair reading */\n    val = val_hdr + hdr_len;\n    ctn = val;\n    ctn_len = 0;\n    \n    if (*cur++ == '{') {\n        ctn->tag = YYJSON_TYPE_OBJ;\n        ctn->uni.ofs = 0;\n        if (*cur == '\\n') cur++;\n        goto obj_key_begin;\n    } else {\n        ctn->tag = YYJSON_TYPE_ARR;\n        ctn->uni.ofs = 0;\n        if (*cur == '\\n') cur++;\n        goto arr_val_begin;\n    }\n    \narr_begin:\n    container_depth++;\n    if (unlikely(container_depth >= YYJSON_READER_CONTAINER_RECURSION_LIMIT)) {\n        goto fail_recursion;\n    }\n\n    /* save current container */\n    ctn->tag = (((u64)ctn_len + 1) << YYJSON_TAG_BIT) |\n               (ctn->tag & YYJSON_TAG_MASK);\n    \n    /* create a new array value, save parent container offset */\n    val_incr();\n    val->tag = YYJSON_TYPE_ARR;\n    val->uni.ofs = (usize)((u8 *)val - (u8 *)ctn);\n    \n    /* push the new array value as current container */\n    ctn = val;\n    ctn_len = 0;\n    if (*cur == '\\n') cur++;\n    \narr_val_begin:\n#if YYJSON_IS_REAL_GCC\n    while (true) repeat16({\n        if (byte_match_2(cur, \"  \")) cur += 2;\n        else break;\n    })\n#else\n    while (true) repeat16({\n        if (likely(byte_match_2(cur, \"  \"))) cur += 2;\n        else break;\n    })\n#endif\n    \n    if (*cur == '{') {\n        cur++;\n        goto obj_begin;\n    }\n    if (*cur == '[') {\n        cur++;\n        goto arr_begin;\n    }\n    if (char_is_number(*cur)) {\n        val_incr();\n        ctn_len++;\n        if (likely(read_number(&cur, val, &msg))) goto arr_val_end;\n        goto fail_number;\n    }\n    if (*cur == '\"') {\n        val_incr();\n        ctn_len++;\n        if (likely(read_string(&cur, end, val, &msg))) goto arr_val_end;\n        goto fail_string;\n    }\n    if (*cur == 't') {\n        val_incr();\n        ctn_len++;\n        if (likely(read_true(&cur, val))) goto arr_val_end;\n        goto fail_literal;\n    }\n    if (*cur == 'f') {\n        val_incr();\n        ctn_len++;\n        if (likely(read_false(&cur, val))) goto arr_val_end;\n        goto fail_literal;\n    }\n    if (*cur == 'n') {\n        val_incr();\n        ctn_len++;\n        if (likely(read_null(&cur, val))) goto arr_val_end;\n        if (false) {\n            if (read_nan(false, &cur, 0, val)) goto arr_val_end;\n        }\n        goto fail_literal;\n    }\n    if (*cur == ']') {\n        cur++;\n        if (likely(ctn_len == 0)) goto arr_end;\n        while (*cur != ',') cur--;\n        goto fail_trailing_comma;\n    }\n    if (char_is_space(*cur)) {\n        while (char_is_space(*++cur));\n        goto arr_val_begin;\n    }\n    goto fail_character;\n    \narr_val_end:\n    if (byte_match_2(cur, \",\\n\")) {\n        cur += 2;\n        goto arr_val_begin;\n    }\n    if (*cur == ',') {\n        cur++;\n        goto arr_val_begin;\n    }\n    if (*cur == ']') {\n        cur++;\n        goto arr_end;\n    }\n    if (char_is_space(*cur)) {\n        while (char_is_space(*++cur));\n        goto arr_val_end;\n    }\n    if (false) {\n        if (skip_spaces_and_comments(&cur)) goto arr_val_end;\n        if (byte_match_2(cur, \"/*\")) goto fail_comment;\n    }\n    goto fail_character;\n    \narr_end:\n    container_depth--;\n\n    /* get parent container */\n    ctn_parent = (yyjson_val *)(void *)((u8 *)ctn - ctn->uni.ofs);\n    \n    /* save the next sibling value offset */\n    ctn->uni.ofs = (usize)((u8 *)val - (u8 *)ctn) + sizeof(yyjson_val);\n    ctn->tag = ((ctn_len) << YYJSON_TAG_BIT) | YYJSON_TYPE_ARR;\n    if (unlikely(ctn == ctn_parent)) goto doc_end;\n    \n    /* pop parent as current container */\n    ctn = ctn_parent;\n    ctn_len = (usize)(ctn->tag >> YYJSON_TAG_BIT);\n    if (*cur == '\\n') cur++;\n    if ((ctn->tag & YYJSON_TYPE_MASK) == YYJSON_TYPE_OBJ) {\n        goto obj_val_end;\n    } else {\n        goto arr_val_end;\n    }\n    \nobj_begin:\n    container_depth++;\n    if (unlikely(container_depth >= YYJSON_READER_CONTAINER_RECURSION_LIMIT)) {\n        goto fail_recursion;\n    }\n\n    /* push container */\n    ctn->tag = (((u64)ctn_len + 1) << YYJSON_TAG_BIT) |\n               (ctn->tag & YYJSON_TAG_MASK);\n    val_incr();\n    val->tag = YYJSON_TYPE_OBJ;\n    /* offset to the parent */\n    val->uni.ofs = (usize)((u8 *)val - (u8 *)ctn);\n    ctn = val;\n    ctn_len = 0;\n    if (*cur == '\\n') cur++;\n    \nobj_key_begin:\n#if YYJSON_IS_REAL_GCC\n    while (true) repeat16({\n        if (byte_match_2(cur, \"  \")) cur += 2;\n        else break;\n    })\n#else\n    while (true) repeat16({\n        if (likely(byte_match_2(cur, \"  \"))) cur += 2;\n        else break;\n    })\n#endif\n    if (likely(*cur == '\"')) {\n        val_incr();\n        ctn_len++;\n        if (likely(read_string(&cur, end, val, &msg))) goto obj_key_end;\n        goto fail_string;\n    }\n    if (likely(*cur == '}')) {\n        cur++;\n        if (likely(ctn_len == 0)) goto obj_end;\n        while (*cur != ',') cur--;\n        goto fail_trailing_comma;\n    }\n    if (char_is_space(*cur)) {\n        while (char_is_space(*++cur));\n        goto obj_key_begin;\n    }\n    if (false) {\n        if (skip_spaces_and_comments(&cur)) goto obj_key_begin;\n        if (byte_match_2(cur, \"/*\")) goto fail_comment;\n    }\n    goto fail_character;\n    \nobj_key_end:\n    if (byte_match_2(cur, \": \")) {\n        cur += 2;\n        goto obj_val_begin;\n    }\n    if (*cur == ':') {\n        cur++;\n        goto obj_val_begin;\n    }\n    if (char_is_space(*cur)) {\n        while (char_is_space(*++cur));\n        goto obj_key_end;\n    }\n    goto fail_character;\n    \nobj_val_begin:\n    if (*cur == '\"') {\n        val++;\n        ctn_len++;\n        if (likely(read_string(&cur, end, val, &msg))) goto obj_val_end;\n        goto fail_string;\n    }\n    if (char_is_number(*cur)) {\n        val++;\n        ctn_len++;\n        if (likely(read_number(&cur, val, &msg))) goto obj_val_end;\n        goto fail_number;\n    }\n    if (*cur == '{') {\n        cur++;\n        goto obj_begin;\n    }\n    if (*cur == '[') {\n        cur++;\n        goto arr_begin;\n    }\n    if (*cur == 't') {\n        val++;\n        ctn_len++;\n        if (likely(read_true(&cur, val))) goto obj_val_end;\n        goto fail_literal;\n    }\n    if (*cur == 'f') {\n        val++;\n        ctn_len++;\n        if (likely(read_false(&cur, val))) goto obj_val_end;\n        goto fail_literal;\n    }\n    if (*cur == 'n') {\n        val++;\n        ctn_len++;\n        if (likely(read_null(&cur, val))) goto obj_val_end;\n        goto fail_literal;\n    }\n    if (char_is_space(*cur)) {\n        while (char_is_space(*++cur));\n        goto obj_val_begin;\n    }\n    goto fail_character;\n    \nobj_val_end:\n    if (byte_match_2(cur, \",\\n\")) {\n        cur += 2;\n        goto obj_key_begin;\n    }\n    if (likely(*cur == ',')) {\n        cur++;\n        goto obj_key_begin;\n    }\n    if (likely(*cur == '}')) {\n        cur++;\n        goto obj_end;\n    }\n    if (char_is_space(*cur)) {\n        while (char_is_space(*++cur));\n        goto obj_val_end;\n    }\n    goto fail_character;\n    \nobj_end:\n    container_depth--;\n\n    /* pop container */\n    ctn_parent = (yyjson_val *)(void *)((u8 *)ctn - ctn->uni.ofs);\n    /* point to the next value */\n    ctn->uni.ofs = (usize)((u8 *)val - (u8 *)ctn) + sizeof(yyjson_val);\n    ctn->tag = (ctn_len << (YYJSON_TAG_BIT - 1)) | YYJSON_TYPE_OBJ;\n    if (unlikely(ctn == ctn_parent)) goto doc_end;\n    ctn = ctn_parent;\n    ctn_len = (usize)(ctn->tag >> YYJSON_TAG_BIT);\n    if (*cur == '\\n') cur++;\n    if ((ctn->tag & YYJSON_TYPE_MASK) == YYJSON_TYPE_OBJ) {\n        goto obj_val_end;\n    } else {\n        goto arr_val_end;\n    }\n    \ndoc_end:\n    /* check invalid contents after json document */\n    if (unlikely(cur < end) && !has_read_flag(STOP_WHEN_DONE)) {\n        if (false) {\n            skip_spaces_and_comments(&cur);\n            if (byte_match_2(cur, \"/*\")) goto fail_comment;\n        } else {\n            while (char_is_space(*cur)) cur++;\n        }\n        if (unlikely(cur < end)) goto fail_garbage;\n    }\n    \n    doc = (yyjson_doc *)val_hdr;\n    doc->root = val_hdr + hdr_len;\n    doc->alc = alc;\n    doc->dat_read = (usize)(cur - hdr);\n    doc->val_read = (usize)((val - val_hdr)) - hdr_len + 1;\n    doc->str_pool = has_read_flag(INSITU) ? NULL : (char *)hdr;\n    return doc;\n    \nfail_string:\n    return_err(cur, INVALID_STRING, msg);\nfail_number:\n    return_err(cur, INVALID_NUMBER, msg);\nfail_alloc:\n    return_err(cur, MEMORY_ALLOCATION, \"memory allocation failed\");\nfail_trailing_comma:\n    return_err(cur, JSON_STRUCTURE, \"trailing comma is not allowed\");\nfail_literal:\n    return_err(cur, LITERAL, \"invalid literal\");\nfail_comment:\n    return_err(cur, INVALID_COMMENT, \"unclosed multiline comment\");\nfail_character:\n    return_err(cur, UNEXPECTED_CHARACTER, \"unexpected character\");\nfail_garbage:\n    return_err(cur, UNEXPECTED_CONTENT, \"unexpected content after document\");\nfail_recursion:\n    return_err(cur, RECURSION_DEPTH, \"array and object recursion depth exceeded\");\n    \n#undef val_incr\n#undef return_err\n}\n\n\n\n/*==============================================================================\n * JSON Reader Entrance\n *============================================================================*/\n\nyyjson_doc *yyjson_read_opts(char *dat,\n                             usize len,\n                             const yyjson_alc *alc_ptr,\n                             yyjson_read_err *err) {\n    \n#define return_err(_pos, _code, _msg) do { \\\n    err->pos = (usize)(_pos); \\\n    err->msg = _msg; \\\n    err->code = YYJSON_READ_ERROR_##_code; \\\n    if (!has_read_flag(INSITU) && hdr) alc.free(alc.ctx, (void *)hdr); \\\n    return NULL; \\\n} while (false)\n    yyjson_alc alc;\n    yyjson_doc *doc;\n    u8 *hdr = NULL, *end, *cur;\n\n    if (!alc_ptr) {\n        alc = YYJSON_DEFAULT_ALC;\n    } else {\n        alc = *alc_ptr;\n    }\n\n    hdr = (u8 *)alc.malloc(alc.ctx, len + YYJSON_PADDING_SIZE);\n    end = hdr + len;\n    cur = hdr;\n    memcpy(hdr, dat, len);\n    memset(end, 0, YYJSON_PADDING_SIZE);\n    \n    /* skip empty contents before json document */\n    if (unlikely(char_is_space_or_comment(*cur))) {\n        if (likely(char_is_space(*cur))) {\n            while (char_is_space(*++cur));\n        }\n        if (unlikely(cur >= end)) {\n            return_err(0, EMPTY_CONTENT, \"input data is empty\");\n        }\n    }\n    \n    /* read json document */\n    if (likely(char_is_container(*cur))) {\n        if (char_is_space(cur[1]) && char_is_space(cur[2])) {\n            doc = read_root_pretty(hdr, cur, end, alc, err);\n        } else {\n            doc = read_root_minify(hdr, cur, end, alc, err);\n        }\n    } else {\n        doc = read_root_single(hdr, cur, end, alc, err);\n    }\n    \n    /* check result */\n    if (unlikely(!doc)) {\n        alc.free(alc.ctx, (void *)hdr);\n    }\n    return doc;\n    \n#undef return_err\n}\n\nyyjson_doc *yyjson_read_file(const char *path,\n                             yyjson_read_flag flg,\n                             const yyjson_alc *alc_ptr,\n                             yyjson_read_err *err) {\n#define return_err(_code, _msg) do { \\\n    err->pos = 0; \\\n    err->msg = _msg; \\\n    err->code = YYJSON_READ_ERROR_##_code; \\\n    return NULL; \\\n} while (false)\n    \n\n    yyjson_doc *doc;\n    FILE *file;\n    \n\n    if (unlikely(!path)) return_err(INVALID_PARAMETER, \"input path is NULL\");\n    \n    file = fopen_readonly(path);\n    if (unlikely(!file)) return_err(FILE_OPEN, \"file opening failed\");\n    \n    doc = yyjson_read_fp(file, flg, alc_ptr, err);\n    fclose(file);\n    return doc;\n    \n#undef return_err\n}\n\nyyjson_doc *yyjson_read_fp(FILE *file,\n                           yyjson_read_flag flg,\n                           const yyjson_alc *alc_ptr,\n                           yyjson_read_err *err) {\n#define return_err(_code, _msg) do { \\\n    err->pos = 0; \\\n    err->msg = _msg; \\\n    err->code = YYJSON_READ_ERROR_##_code; \\\n    if (buf) alc.free(alc.ctx, buf); \\\n    return NULL; \\\n} while (false)\n    \n\n    yyjson_alc alc = alc_ptr ? *alc_ptr : YYJSON_DEFAULT_ALC;\n    yyjson_doc *doc;\n    \n    long file_size = 0, file_pos;\n    void *buf = NULL;\n    usize buf_size = 0;\n    \n    /* validate input parameters */\n\n    if (unlikely(!file)) return_err(INVALID_PARAMETER, \"input file is NULL\");\n    \n    /* get current position */\n    file_pos = ftell(file);\n    if (file_pos != -1) {\n        /* get total file size, may fail */\n        if (fseek(file, 0, SEEK_END) == 0) file_size = ftell(file);\n        /* reset to original position, may fail */\n        if (fseek(file, file_pos, SEEK_SET) != 0) file_size = 0;\n        /* get file size from current postion to end */\n        if (file_size > 0) file_size -= file_pos;\n    }\n    \n    /* read file */\n    if (file_size > 0) {\n        /* read the entire file in one call */\n        buf_size = (usize)file_size + YYJSON_PADDING_SIZE;\n        buf = alc.malloc(alc.ctx, buf_size);\n        if (buf == NULL) {\n            return_err(MEMORY_ALLOCATION, \"fail to alloc memory\");\n        }\n        if (fread_safe(buf, (usize)file_size, file) != (usize)file_size) {\n            return_err(FILE_READ, \"file reading failed\");\n        }\n    } else {\n        /* failed to get file size, read it as a stream */\n        usize chunk_min = (usize)64;\n        usize chunk_max = (usize)512 * 1024 * 1024;\n        usize chunk_now = chunk_min;\n        usize read_size;\n        void *tmp;\n        \n        buf_size = YYJSON_PADDING_SIZE;\n        while (true) {\n            if (buf_size + chunk_now < buf_size) { /* overflow */\n                return_err(MEMORY_ALLOCATION, \"fail to alloc memory\");\n            }\n            buf_size += chunk_now;\n            if (!buf) {\n                buf = alc.malloc(alc.ctx, buf_size);\n                if (!buf) return_err(MEMORY_ALLOCATION, \"fail to alloc memory\");\n            } else {\n                tmp = alc.realloc(alc.ctx, buf, buf_size - chunk_now, buf_size);\n                if (!tmp) return_err(MEMORY_ALLOCATION, \"fail to alloc memory\");\n                buf = tmp;\n            }\n            tmp = ((u8 *)buf) + buf_size - YYJSON_PADDING_SIZE - chunk_now;\n            read_size = fread_safe(tmp, chunk_now, file);\n            file_size += (long)read_size;\n            if (read_size != chunk_now) break;\n            \n            chunk_now *= 2;\n            if (chunk_now > chunk_max) chunk_now = chunk_max;\n        }\n    }\n    \n    /* read JSON */\n    memset((u8 *)buf + file_size, 0, YYJSON_PADDING_SIZE);\n    flg |= YYJSON_READ_INSITU;\n    doc = yyjson_read_opts((char *)buf, (usize)file_size, &alc, err);\n    if (doc) {\n        doc->str_pool = (char *)buf;\n        return doc;\n    } else {\n        alc.free(alc.ctx, buf);\n        return NULL;\n    }\n    \n#undef return_err\n}\n\nconst char *yyjson_read_number(const char *dat,\n                               yyjson_val *val,\n                               yyjson_read_flag flg,\n                               const yyjson_alc *alc,\n                               yyjson_read_err *err) {\n#define return_err(_pos, _code, _msg) do { \\\n    err->pos = _pos > hdr ? (usize)(_pos - hdr) : 0; \\\n    err->msg = _msg; \\\n    err->code = YYJSON_READ_ERROR_##_code; \\\n    return NULL; \\\n} while (false)\n    \n    u8 *hdr = constcast(u8 *)dat, *cur = hdr;\n    bool raw; /* read number as raw */\n    u8 *raw_end; /* raw end for null-terminator */\n    u8 **pre; /* previous raw end pointer */\n    const char *msg;\n\n    \n#if !YYJSON_HAS_IEEE_754 || YYJSON_DISABLE_FAST_FP_CONV\n    u8 buf[128];\n    usize dat_len;\n#endif\n    \n\n    if (unlikely(!dat)) {\n        return_err(cur, INVALID_PARAMETER, \"input data is NULL\");\n    }\n    if (unlikely(!val)) {\n        return_err(cur, INVALID_PARAMETER, \"output value is NULL\");\n    }\n    \n#if !YYJSON_HAS_IEEE_754 || YYJSON_DISABLE_FAST_FP_CONV\n    if (!alc) alc = &YYJSON_DEFAULT_ALC;\n    dat_len = strlen(dat);\n    if (dat_len < sizeof(buf)) {\n        memcpy(buf, dat, dat_len + 1);\n        hdr = buf;\n        cur = hdr;\n    } else {\n        hdr = (u8 *)alc->malloc(alc->ctx, dat_len + 1);\n        cur = hdr;\n        if (unlikely(!hdr)) {\n            return_err(cur, MEMORY_ALLOCATION, \"memory allocation failed\");\n        }\n        memcpy(hdr, dat, dat_len + 1);\n    }\n    hdr[dat_len] = 0;\n#endif\n    \n#if !YYJSON_HAS_IEEE_754 || YYJSON_DISABLE_FAST_FP_CONV\n    if (!read_number(&cur, val, &msg)) {\n        if (dat_len >= sizeof(buf)) alc->free(alc->ctx, hdr);\n        return_err(cur, INVALID_NUMBER, msg);\n    }\n    if (dat_len >= sizeof(buf)) alc->free(alc->ctx, hdr);\n    if (yyjson_is_raw(val)) val->uni.str = dat;\n    return dat + (cur - hdr);\n#else\n    if (!read_number(&cur, val, &msg)) {\n        return_err(cur, INVALID_NUMBER, msg);\n    }\n    return (const char *)cur;\n#endif\n    \n#undef return_err\n}\n\n#endif /* YYJSON_DISABLE_READER */\n\n\n\n#if !YYJSON_DISABLE_WRITER\n\n/*==============================================================================\n * Integer Writer\n *\n * The maximum value of uint32_t is 4294967295 (10 digits),\n * these digits are named as 'aabbccddee' here.\n *\n * Although most compilers may convert the \"division by constant value\" into\n * \"multiply and shift\", manual conversion can still help some compilers\n * generate fewer and better instructions.\n *\n * Reference:\n * Division by Invariant Integers using Multiplication, 1994.\n * https://gmplib.org/~tege/divcnst-pldi94.pdf\n * Improved division by invariant integers, 2011.\n * https://gmplib.org/~tege/division-paper.pdf\n *============================================================================*/\n\n/** Digit table from 00 to 99. */\nyyjson_align(2)\nstatic const char digit_table[200] = {\n    '0', '0', '0', '1', '0', '2', '0', '3', '0', '4',\n    '0', '5', '0', '6', '0', '7', '0', '8', '0', '9',\n    '1', '0', '1', '1', '1', '2', '1', '3', '1', '4',\n    '1', '5', '1', '6', '1', '7', '1', '8', '1', '9',\n    '2', '0', '2', '1', '2', '2', '2', '3', '2', '4',\n    '2', '5', '2', '6', '2', '7', '2', '8', '2', '9',\n    '3', '0', '3', '1', '3', '2', '3', '3', '3', '4',\n    '3', '5', '3', '6', '3', '7', '3', '8', '3', '9',\n    '4', '0', '4', '1', '4', '2', '4', '3', '4', '4',\n    '4', '5', '4', '6', '4', '7', '4', '8', '4', '9',\n    '5', '0', '5', '1', '5', '2', '5', '3', '5', '4',\n    '5', '5', '5', '6', '5', '7', '5', '8', '5', '9',\n    '6', '0', '6', '1', '6', '2', '6', '3', '6', '4',\n    '6', '5', '6', '6', '6', '7', '6', '8', '6', '9',\n    '7', '0', '7', '1', '7', '2', '7', '3', '7', '4',\n    '7', '5', '7', '6', '7', '7', '7', '8', '7', '9',\n    '8', '0', '8', '1', '8', '2', '8', '3', '8', '4',\n    '8', '5', '8', '6', '8', '7', '8', '8', '8', '9',\n    '9', '0', '9', '1', '9', '2', '9', '3', '9', '4',\n    '9', '5', '9', '6', '9', '7', '9', '8', '9', '9'\n};\n\nstatic_inline u8 *write_u32_len_8(u32 val, u8 *buf) {\n    u32 aa, bb, cc, dd, aabb, ccdd;                 /* 8 digits: aabbccdd */\n    aabb = (u32)(((u64)val * 109951163) >> 40);     /* (val / 10000) */\n    ccdd = val - aabb * 10000;                      /* (val % 10000) */\n    aa = (aabb * 5243) >> 19;                       /* (aabb / 100) */\n    cc = (ccdd * 5243) >> 19;                       /* (ccdd / 100) */\n    bb = aabb - aa * 100;                           /* (aabb % 100) */\n    dd = ccdd - cc * 100;                           /* (ccdd % 100) */\n    byte_copy_2(buf + 0, digit_table + aa * 2);\n    byte_copy_2(buf + 2, digit_table + bb * 2);\n    byte_copy_2(buf + 4, digit_table + cc * 2);\n    byte_copy_2(buf + 6, digit_table + dd * 2);\n    return buf + 8;\n}\n\nstatic_inline u8 *write_u32_len_4(u32 val, u8 *buf) {\n    u32 aa, bb;                                     /* 4 digits: aabb */\n    aa = (val * 5243) >> 19;                        /* (val / 100) */\n    bb = val - aa * 100;                            /* (val % 100) */\n    byte_copy_2(buf + 0, digit_table + aa * 2);\n    byte_copy_2(buf + 2, digit_table + bb * 2);\n    return buf + 4;\n}\n\nstatic_inline u8 *write_u32_len_1_8(u32 val, u8 *buf) {\n    u32 aa, bb, cc, dd, aabb, bbcc, ccdd, lz;\n    \n    if (val < 100) {                                /* 1-2 digits: aa */\n        lz = val < 10;                              /* leading zero: 0 or 1 */\n        byte_copy_2(buf + 0, digit_table + val * 2 + lz);\n        buf -= lz;\n        return buf + 2;\n        \n    } else if (val < 10000) {                       /* 3-4 digits: aabb */\n        aa = (val * 5243) >> 19;                    /* (val / 100) */\n        bb = val - aa * 100;                        /* (val % 100) */\n        lz = aa < 10;                               /* leading zero: 0 or 1 */\n        byte_copy_2(buf + 0, digit_table + aa * 2 + lz);\n        buf -= lz;\n        byte_copy_2(buf + 2, digit_table + bb * 2);\n        return buf + 4;\n        \n    } else if (val < 1000000) {                     /* 5-6 digits: aabbcc */\n        aa = (u32)(((u64)val * 429497) >> 32);      /* (val / 10000) */\n        bbcc = val - aa * 10000;                    /* (val % 10000) */\n        bb = (bbcc * 5243) >> 19;                   /* (bbcc / 100) */\n        cc = bbcc - bb * 100;                       /* (bbcc % 100) */\n        lz = aa < 10;                               /* leading zero: 0 or 1 */\n        byte_copy_2(buf + 0, digit_table + aa * 2 + lz);\n        buf -= lz;\n        byte_copy_2(buf + 2, digit_table + bb * 2);\n        byte_copy_2(buf + 4, digit_table + cc * 2);\n        return buf + 6;\n        \n    } else {                                        /* 7-8 digits: aabbccdd */\n        aabb = (u32)(((u64)val * 109951163) >> 40); /* (val / 10000) */\n        ccdd = val - aabb * 10000;                  /* (val % 10000) */\n        aa = (aabb * 5243) >> 19;                   /* (aabb / 100) */\n        cc = (ccdd * 5243) >> 19;                   /* (ccdd / 100) */\n        bb = aabb - aa * 100;                       /* (aabb % 100) */\n        dd = ccdd - cc * 100;                       /* (ccdd % 100) */\n        lz = aa < 10;                               /* leading zero: 0 or 1 */\n        byte_copy_2(buf + 0, digit_table + aa * 2 + lz);\n        buf -= lz;\n        byte_copy_2(buf + 2, digit_table + bb * 2);\n        byte_copy_2(buf + 4, digit_table + cc * 2);\n        byte_copy_2(buf + 6, digit_table + dd * 2);\n        return buf + 8;\n    }\n}\n\nstatic_inline u8 *write_u64_len_5_8(u32 val, u8 *buf) {\n    u32 aa, bb, cc, dd, aabb, bbcc, ccdd, lz;\n    \n    if (val < 1000000) {                            /* 5-6 digits: aabbcc */\n        aa = (u32)(((u64)val * 429497) >> 32);      /* (val / 10000) */\n        bbcc = val - aa * 10000;                    /* (val % 10000) */\n        bb = (bbcc * 5243) >> 19;                   /* (bbcc / 100) */\n        cc = bbcc - bb * 100;                       /* (bbcc % 100) */\n        lz = aa < 10;                               /* leading zero: 0 or 1 */\n        byte_copy_2(buf + 0, digit_table + aa * 2 + lz);\n        buf -= lz;\n        byte_copy_2(buf + 2, digit_table + bb * 2);\n        byte_copy_2(buf + 4, digit_table + cc * 2);\n        return buf + 6;\n        \n    } else {                                        /* 7-8 digits: aabbccdd */\n        aabb = (u32)(((u64)val * 109951163) >> 40); /* (val / 10000) */\n        ccdd = val - aabb * 10000;                  /* (val % 10000) */\n        aa = (aabb * 5243) >> 19;                   /* (aabb / 100) */\n        cc = (ccdd * 5243) >> 19;                   /* (ccdd / 100) */\n        bb = aabb - aa * 100;                       /* (aabb % 100) */\n        dd = ccdd - cc * 100;                       /* (ccdd % 100) */\n        lz = aa < 10;                               /* leading zero: 0 or 1 */\n        byte_copy_2(buf + 0, digit_table + aa * 2 + lz);\n        buf -= lz;\n        byte_copy_2(buf + 2, digit_table + bb * 2);\n        byte_copy_2(buf + 4, digit_table + cc * 2);\n        byte_copy_2(buf + 6, digit_table + dd * 2);\n        return buf + 8;\n    }\n}\n\nstatic_inline u8 *write_u64(u64 val, u8 *buf) {\n    u64 tmp, hgh;\n    u32 mid, low;\n    \n    if (val < 100000000) {                          /* 1-8 digits */\n        buf = write_u32_len_1_8((u32)val, buf);\n        return buf;\n        \n    } else if (val < (u64)100000000 * 100000000) {  /* 9-16 digits */\n        hgh = val / 100000000;                      /* (val / 100000000) */\n        low = (u32)(val - hgh * 100000000);         /* (val % 100000000) */\n        buf = write_u32_len_1_8((u32)hgh, buf);\n        buf = write_u32_len_8(low, buf);\n        return buf;\n        \n    } else {                                        /* 17-20 digits */\n        tmp = val / 100000000;                      /* (val / 100000000) */\n        low = (u32)(val - tmp * 100000000);         /* (val % 100000000) */\n        hgh = (u32)(tmp / 10000);                   /* (tmp / 10000) */\n        mid = (u32)(tmp - hgh * 10000);             /* (tmp % 10000) */\n        buf = write_u64_len_5_8((u32)hgh, buf);\n        buf = write_u32_len_4(mid, buf);\n        buf = write_u32_len_8(low, buf);\n        return buf;\n    }\n}\n\n\n\n/*==============================================================================\n * Number Writer\n *============================================================================*/\n\n#if YYJSON_HAS_IEEE_754 && !YYJSON_DISABLE_FAST_FP_CONV  /* FP_WRITER */\n\n/** Trailing zero count table for number 0 to 99.\n    (generate with misc/make_tables.c) */\nstatic const u8 dec_trailing_zero_table[] = {\n    2, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    1, 0, 0, 0, 0, 0, 0, 0, 0, 0\n};\n\n/** Write an unsigned integer with a length of 1 to 16. */\nstatic_inline u8 *write_u64_len_1_to_16(u64 val, u8 *buf) {\n    u64 hgh;\n    u32 low;\n    if (val < 100000000) {                          /* 1-8 digits */\n        buf = write_u32_len_1_8((u32)val, buf);\n        return buf;\n    } else {                                        /* 9-16 digits */\n        hgh = val / 100000000;                      /* (val / 100000000) */\n        low = (u32)(val - hgh * 100000000);         /* (val % 100000000) */\n        buf = write_u32_len_1_8((u32)hgh, buf);\n        buf = write_u32_len_8(low, buf);\n        return buf;\n    }\n}\n\n/** Write an unsigned integer with a length of 1 to 17. */\nstatic_inline u8 *write_u64_len_1_to_17(u64 val, u8 *buf) {\n    u64 hgh;\n    u32 mid, low, one;\n    if (val >= (u64)100000000 * 10000000) {         /* len: 16 to 17 */\n        hgh = val / 100000000;                      /* (val / 100000000) */\n        low = (u32)(val - hgh * 100000000);         /* (val % 100000000) */\n        one = (u32)(hgh / 100000000);               /* (hgh / 100000000) */\n        mid = (u32)(hgh - (u64)one * 100000000);    /* (hgh % 100000000) */\n        *buf = (u8)((u8)one + (u8)'0');\n        buf += one > 0;\n        buf = write_u32_len_8(mid, buf);\n        buf = write_u32_len_8(low, buf);\n        return buf;\n    } else if (val >= (u64)100000000){              /* len: 9 to 15 */\n        hgh = val / 100000000;                      /* (val / 100000000) */\n        low = (u32)(val - hgh * 100000000);         /* (val % 100000000) */\n        buf = write_u32_len_1_8((u32)hgh, buf);\n        buf = write_u32_len_8(low, buf);\n        return buf;\n    } else { /* len: 1 to 8 */\n        buf = write_u32_len_1_8((u32)val, buf);\n        return buf;\n    }\n}\n\n/**\n Write an unsigned integer with a length of 15 to 17 with trailing zero trimmed.\n These digits are named as \"aabbccddeeffgghhii\" here.\n For example, input 1234567890123000, output \"1234567890123\".\n */\nstatic_inline u8 *write_u64_len_15_to_17_trim(u8 *buf, u64 sig) {\n    bool lz;                                        /* leading zero */\n    u32 tz1, tz2, tz;                               /* trailing zero */\n    \n    u32 abbccddee = (u32)(sig / 100000000);\n    u32 ffgghhii = (u32)(sig - (u64)abbccddee * 100000000);\n    u32 abbcc = abbccddee / 10000;                  /* (abbccddee / 10000) */\n    u32 ddee = abbccddee - abbcc * 10000;           /* (abbccddee % 10000) */\n    u32 abb = (u32)(((u64)abbcc * 167773) >> 24);   /* (abbcc / 100) */\n    u32 a = (abb * 41) >> 12;                       /* (abb / 100) */\n    u32 bb = abb - a * 100;                         /* (abb % 100) */\n    u32 cc = abbcc - abb * 100;                     /* (abbcc % 100) */\n    \n    /* write abbcc */\n    buf[0] = (u8)(a + '0');\n    buf += a > 0;\n    lz = bb < 10 && a == 0;\n    byte_copy_2(buf + 0, digit_table + bb * 2 + lz);\n    buf -= lz;\n    byte_copy_2(buf + 2, digit_table + cc * 2);\n    \n    if (ffgghhii) {\n        u32 dd = (ddee * 5243) >> 19;               /* (ddee / 100) */\n        u32 ee = ddee - dd * 100;                   /* (ddee % 100) */\n        u32 ffgg = (u32)(((u64)ffgghhii * 109951163) >> 40); /* (val / 10000) */\n        u32 hhii = ffgghhii - ffgg * 10000;         /* (val % 10000) */\n        u32 ff = (ffgg * 5243) >> 19;               /* (aabb / 100) */\n        u32 gg = ffgg - ff * 100;                   /* (aabb % 100) */\n        byte_copy_2(buf + 4, digit_table + dd * 2);\n        byte_copy_2(buf + 6, digit_table + ee * 2);\n        byte_copy_2(buf + 8, digit_table + ff * 2);\n        byte_copy_2(buf + 10, digit_table + gg * 2);\n        if (hhii) {\n            u32 hh = (hhii * 5243) >> 19;           /* (ccdd / 100) */\n            u32 ii = hhii - hh * 100;               /* (ccdd % 100) */\n            byte_copy_2(buf + 12, digit_table + hh * 2);\n            byte_copy_2(buf + 14, digit_table + ii * 2);\n            tz1 = dec_trailing_zero_table[hh];\n            tz2 = dec_trailing_zero_table[ii];\n            tz = ii ? tz2 : (tz1 + 2);\n            buf += 16 - tz;\n            return buf;\n        } else {\n            tz1 = dec_trailing_zero_table[ff];\n            tz2 = dec_trailing_zero_table[gg];\n            tz = gg ? tz2 : (tz1 + 2);\n            buf += 12 - tz;\n            return buf;\n        }\n    } else {\n        if (ddee) {\n            u32 dd = (ddee * 5243) >> 19;           /* (ddee / 100) */\n            u32 ee = ddee - dd * 100;               /* (ddee % 100) */\n            byte_copy_2(buf + 4, digit_table + dd * 2);\n            byte_copy_2(buf + 6, digit_table + ee * 2);\n            tz1 = dec_trailing_zero_table[dd];\n            tz2 = dec_trailing_zero_table[ee];\n            tz = ee ? tz2 : (tz1 + 2);\n            buf += 8 - tz;\n            return buf;\n        } else {\n            tz1 = dec_trailing_zero_table[bb];\n            tz2 = dec_trailing_zero_table[cc];\n            tz = cc ? tz2 : (tz1 + tz2);\n            buf += 4 - tz;\n            return buf;\n        }\n    }\n}\n\n/** Write a signed integer in the range -324 to 308. */\nstatic_inline u8 *write_f64_exp(i32 exp, u8 *buf) {\n    buf[0] = '-';\n    buf += exp < 0;\n    exp = exp < 0 ? -exp : exp;\n    if (exp < 100) {\n        u32 lz = exp < 10;\n        byte_copy_2(buf + 0, digit_table + (u32)exp * 2 + lz);\n        return buf + 2 - lz;\n    } else {\n        u32 hi = ((u32)exp * 656) >> 16;            /* exp / 100 */\n        u32 lo = (u32)exp - hi * 100;               /* exp % 100 */\n        buf[0] = (u8)((u8)hi + (u8)'0');\n        byte_copy_2(buf + 1, digit_table + lo * 2);\n        return buf + 3;\n    }\n}\n\n/** Multiplies 128-bit integer and returns highest 64-bit rounded value. */\nstatic_inline u64 round_to_odd(u64 hi, u64 lo, u64 cp) {\n    u64 x_hi, x_lo, y_hi, y_lo;\n    u128_mul(cp, lo, &x_hi, &x_lo);\n    u128_mul_add(cp, hi, x_hi, &y_hi, &y_lo);\n    return y_hi | (y_lo > 1);\n}\n\n/**\n Convert double number from binary to decimal.\n The output significand is shortest decimal but may have trailing zeros.\n \n This function use the Schubfach algorithm:\n Raffaello Giulietti, The Schubfach way to render doubles (5th version), 2022.\n https://drive.google.com/file/d/1gp5xv4CAa78SVgCeWfGqqI4FfYYYuNFb\n https://mail.openjdk.java.net/pipermail/core-libs-dev/2021-November/083536.html\n https://github.com/openjdk/jdk/pull/3402 (Java implementation)\n https://github.com/abolz/Drachennest (C++ implementation)\n \n See also:\n Dragonbox: A New Floating-Point Binary-to-Decimal Conversion Algorithm, 2022.\n https://github.com/jk-jeon/dragonbox/blob/master/other_files/Dragonbox.pdf\n https://github.com/jk-jeon/dragonbox\n \n @param sig_raw The raw value of significand in IEEE 754 format.\n @param exp_raw The raw value of exponent in IEEE 754 format.\n @param sig_bin The decoded value of significand in binary.\n @param exp_bin The decoded value of exponent in binary.\n @param sig_dec The output value of significand in decimal.\n @param exp_dec The output value of exponent in decimal.\n @warning The input double number should not be 0, inf, nan.\n */\nstatic_inline void f64_bin_to_dec(u64 sig_raw, u32 exp_raw,\n                                  u64 sig_bin, i32 exp_bin,\n                                  u64 *sig_dec, i32 *exp_dec) {\n    \n    bool is_even, regular_spacing, u_inside, w_inside, round_up;\n    u64 s, sp, cb, cbl, cbr, vb, vbl, vbr, pow10hi, pow10lo, upper, lower, mid;\n    i32 k, h, exp10;\n    \n    is_even = !(sig_bin & 1);\n    regular_spacing = (sig_raw == 0 && exp_raw > 1);\n    \n    cbl = 4 * sig_bin - 2 + regular_spacing;\n    cb  = 4 * sig_bin;\n    cbr = 4 * sig_bin + 2;\n    \n    /* exp_bin: [-1074, 971]                                                  */\n    /* k = regular_spacing ? floor(log10(pow(2, exp_bin)))                    */\n    /*                     : floor(log10(pow(2, exp_bin) * 3.0 / 4.0))        */\n    /*   = regular_spacing ? floor(exp_bin * log10(2))                        */\n    /*                     : floor(exp_bin * log10(2) + log10(3.0 / 4.0))     */\n    k = (i32)(exp_bin * 315653 - (regular_spacing ? 131237 : 0)) >> 20;\n    \n    /* k: [-324, 292]                                                         */\n    /* h = exp_bin + floor(log2(pow(10, e)))                                  */\n    /*   = exp_bin + floor(log2(10) * e)                                      */\n    exp10 = -k;\n    h = exp_bin + ((exp10 * 217707) >> 16) + 1;\n    \n    pow10_table_get_sig(exp10, &pow10hi, &pow10lo);\n    pow10lo += (exp10 < POW10_SIG_TABLE_MIN_EXACT_EXP ||\n                exp10 > POW10_SIG_TABLE_MAX_EXACT_EXP);\n    vbl = round_to_odd(pow10hi, pow10lo, cbl << h);\n    vb  = round_to_odd(pow10hi, pow10lo, cb  << h);\n    vbr = round_to_odd(pow10hi, pow10lo, cbr << h);\n    \n    lower = vbl + !is_even;\n    upper = vbr - !is_even;\n    \n    s = vb / 4;\n    if (s >= 10) {\n        sp = s / 10;\n        u_inside = (lower <= 40 * sp);\n        w_inside = (upper >= 40 * sp + 40);\n        if (u_inside != w_inside) {\n            *sig_dec = sp + w_inside;\n            *exp_dec = k + 1;\n            return;\n        }\n    }\n    \n    u_inside = (lower <= 4 * s);\n    w_inside = (upper >= 4 * s + 4);\n    \n    mid = 4 * s + 2;\n    round_up = (vb > mid) || (vb == mid && (s & 1) != 0);\n    \n    *sig_dec = s + ((u_inside != w_inside) ? w_inside : round_up);\n    *exp_dec = k;\n}\n\n/**\n Write a double number (requires 32 bytes buffer).\n \n We follows the ECMAScript specification to print floating point numbers,\n but with the following changes:\n 1. Keep the negative sign of 0.0 to preserve input information.\n 2. Keep decimal point to indicate the number is floating point.\n 3. Remove positive sign of exponent part.\n */\nstatic_inline u8 *write_f64_raw(u8 *buf, u64 raw, yyjson_write_flag flg) {\n    u64 sig_bin, sig_dec, sig_raw;\n    i32 exp_bin, exp_dec, sig_len, dot_pos, i, max;\n    u32 exp_raw, hi, lo;\n    u8 *hdr, *num_hdr, *num_end, *dot_end;\n    bool sign;\n    \n    /* decode raw bytes from IEEE-754 double format. */\n    sign = (bool)(raw >> (F64_BITS - 1));\n    sig_raw = raw & F64_SIG_MASK;\n    exp_raw = (u32)((raw & F64_EXP_MASK) >> F64_SIG_BITS);\n    \n    /* return inf and nan */\n    if (unlikely(exp_raw == ((u32)1 << F64_EXP_BITS) - 1)) {\n        if (has_write_flag(INF_AND_NAN_AS_NULL)) {\n            byte_copy_4(buf, \"null\");\n            return buf + 4;\n        }\n        else if (has_write_flag(ALLOW_INF_AND_NAN)) {\n            if (sig_raw == 0) {\n                buf[0] = '-';\n                buf += sign;\n                byte_copy_8(buf, \"Infinity\");\n                buf += 8;\n                return buf;\n            } else {\n                byte_copy_4(buf, \"NaN\");\n                return buf + 3;\n            }\n        }\n        return NULL;\n    }\n    \n    /* add sign for all finite double value, including 0.0 and inf */\n    buf[0] = '-';\n    buf += sign;\n    hdr = buf;\n    \n    /* return zero */\n    if ((raw << 1) == 0) {\n        byte_copy_4(buf, \"0.0\");\n        buf += 3;\n        return buf;\n    }\n    \n    if (likely(exp_raw != 0)) {\n        /* normal number */\n        sig_bin = sig_raw | ((u64)1 << F64_SIG_BITS);\n        exp_bin = (i32)exp_raw - F64_EXP_BIAS - F64_SIG_BITS;\n        \n        /* fast path for small integer number without fraction */\n        if (-F64_SIG_BITS <= exp_bin && exp_bin <= 0) {\n            if (u64_tz_bits(sig_bin) >= (u32)-exp_bin) {\n                /* number is integer in range 1 to 0x1FFFFFFFFFFFFF */\n                sig_dec = sig_bin >> -exp_bin;\n                buf = write_u64_len_1_to_16(sig_dec, buf);\n                byte_copy_2(buf, \".0\");\n                buf += 2;\n                return buf;\n            }\n        }\n        \n        /* binary to decimal */\n        f64_bin_to_dec(sig_raw, exp_raw, sig_bin, exp_bin, &sig_dec, &exp_dec);\n        \n        /* the sig length is 15 to 17 */\n        sig_len = 17;\n        sig_len -= (sig_dec < (u64)100000000 * 100000000);\n        sig_len -= (sig_dec < (u64)100000000 * 10000000);\n        \n        /* the decimal point position relative to the first digit */\n        dot_pos = sig_len + exp_dec;\n        \n        if (-6 < dot_pos && dot_pos <= 21) {\n            /* no need to write exponent part */\n            if (dot_pos <= 0) {\n                /* dot before first digit */\n                /* such as 0.1234, 0.000001234 */\n                num_hdr = hdr + (2 - dot_pos);\n                num_end = write_u64_len_15_to_17_trim(num_hdr, sig_dec);\n                hdr[0] = '0';\n                hdr[1] = '.';\n                hdr += 2;\n                max = -dot_pos;\n                for (i = 0; i < max; i++) hdr[i] = '0';\n                return num_end;\n            } else {\n                /* dot after first digit */\n                /* such as 1.234, 1234.0, 123400000000000000000.0 */\n                memset(hdr +  0, '0', 8);\n                memset(hdr +  8, '0', 8);\n                memset(hdr + 16, '0', 8);\n                num_hdr = hdr + 1;\n                num_end = write_u64_len_15_to_17_trim(num_hdr, sig_dec);\n                for (i = 0; i < dot_pos; i++) hdr[i] = hdr[i + 1];\n                hdr[dot_pos] = '.';\n                dot_end = hdr + dot_pos + 2;\n                return dot_end < num_end ? num_end : dot_end;\n            }\n        } else {\n            /* write with scientific notation */\n            /* such as 1.234e56 */\n            u8 *end = write_u64_len_15_to_17_trim(buf + 1, sig_dec);\n            end -= (end == buf + 2); /* remove '.0', e.g. 2.0e34 -> 2e34 */\n            exp_dec += sig_len - 1;\n            hdr[0] = hdr[1];\n            hdr[1] = '.';\n            end[0] = 'e';\n            buf = write_f64_exp(exp_dec, end + 1);\n            return buf;\n        }\n        \n    } else {\n        /* subnormal number */\n        sig_bin = sig_raw;\n        exp_bin = 1 - F64_EXP_BIAS - F64_SIG_BITS;\n        \n        /* binary to decimal */\n        f64_bin_to_dec(sig_raw, exp_raw, sig_bin, exp_bin, &sig_dec, &exp_dec);\n        \n        /* write significand part */\n        buf = write_u64_len_1_to_17(sig_dec, buf + 1);\n        hdr[0] = hdr[1];\n        hdr[1] = '.';\n        do {\n            buf--;\n            exp_dec++;\n        } while (*buf == '0');\n        exp_dec += (i32)(buf - hdr - 2);\n        buf += (*buf != '.');\n        buf[0] = 'e';\n        buf++;\n        \n        /* write exponent part */\n        buf[0] = '-';\n        buf++;\n        exp_dec = -exp_dec;\n        hi = ((u32)exp_dec * 656) >> 16; /* exp / 100 */\n        lo = (u32)exp_dec - hi * 100; /* exp % 100 */\n        buf[0] = (u8)((u8)hi + (u8)'0');\n        byte_copy_2(buf + 1, digit_table + lo * 2);\n        buf += 3;\n        return buf;\n    }\n}\n\n#else /* FP_WRITER */\n\n/** Write a double number (requires 32 bytes buffer). */\nstatic_inline u8 *write_f64_raw(u8 *buf, u64 raw, yyjson_write_flag flg) {\n    /*\n     For IEEE 754, `DBL_DECIMAL_DIG` is 17 for round-trip.\n     For non-IEEE formats, 17 is used to avoid buffer overflow,\n     round-trip is not guaranteed.\n     */\n#if defined(DBL_DECIMAL_DIG) && DBL_DECIMAL_DIG != 17\n    int dig = DBL_DECIMAL_DIG > 17 ? 17 : DBL_DECIMAL_DIG;\n#else\n    int dig = 17;\n#endif\n    \n    /*\n     The snprintf() function is locale-dependent. For currently known locales,\n     (en, zh, ja, ko, am, he, hi) use '.' as the decimal point, while other\n     locales use ',' as the decimal point. we need to replace ',' with '.'\n     to avoid the locale setting.\n     */\n    f64 val = f64_from_raw(raw);\n#if YYJSON_MSC_VER >= 1400\n    int len = sprintf_s((char *)buf, 32, \"%.*g\", dig, val);\n#elif defined(snprintf) || (YYJSON_STDC_VER >= 199901L)\n    int len = snprintf((char *)buf, 32, \"%.*g\", dig, val);\n#else\n    int len = sprintf((char *)buf, \"%.*g\", dig, val);\n#endif\n    \n    u8 *cur = buf;\n    if (unlikely(len < 1)) return NULL;\n    cur += (*cur == '-');\n    if (unlikely(!digi_is_digit(*cur))) {\n        /* nan, inf, or bad output */\n        if (has_write_flag(INF_AND_NAN_AS_NULL)) {\n            byte_copy_4(buf, \"null\");\n            return buf + 4;\n        }\n        else if (has_write_flag(ALLOW_INF_AND_NAN)) {\n            if (*cur == 'i') {\n                byte_copy_8(cur, \"Infinity\");\n                cur += 8;\n                return cur;\n            } else if (*cur == 'n') {\n                byte_copy_4(buf, \"NaN\");\n                return buf + 3;\n            }\n        }\n        return NULL;\n    } else {\n        /* finite number */\n        int i = 0;\n        bool fp = false;\n        for (; i < len; i++) {\n            if (buf[i] == ',') buf[i] = '.';\n            if (digi_is_fp((u8)buf[i])) fp = true;\n        }\n        if (!fp) {\n            buf[len++] = '.';\n            buf[len++] = '0';\n        }\n    }\n    return buf + len;\n}\n\n#endif /* FP_WRITER */\n\n/** Write a JSON number (requires 32 bytes buffer). */\nstatic_inline u8 *write_number(u8 *cur, yyjson_val *val,\n                               yyjson_write_flag flg) {\n    if (val->tag & YYJSON_SUBTYPE_REAL) {\n        u64 raw = val->uni.u64;\n        return write_f64_raw(cur, raw, flg);\n    } else {\n        u64 pos = val->uni.u64;\n        u64 neg = ~pos + 1;\n        usize sgn = ((val->tag & YYJSON_SUBTYPE_SINT) > 0) & ((i64)pos < 0);\n        *cur = '-';\n        return write_u64(sgn ? neg : pos, cur + sgn);\n    }\n}\n\n\n\n/*==============================================================================\n * String Writer\n *============================================================================*/\n\n/** Character encode type, if (type > CHAR_ENC_ERR_1) bytes = type / 2; */\ntypedef u8 char_enc_type;\n#define CHAR_ENC_CPY_1  0 /* 1-byte UTF-8, copy. */\n#define CHAR_ENC_ERR_1  1 /* 1-byte UTF-8, error. */\n#define CHAR_ENC_ESC_A  2 /* 1-byte ASCII, escaped as '\\x'. */\n#define CHAR_ENC_ESC_1  3 /* 1-byte UTF-8, escaped as '\\uXXXX'. */\n#define CHAR_ENC_CPY_2  4 /* 2-byte UTF-8, copy. */\n#define CHAR_ENC_ESC_2  5 /* 2-byte UTF-8, escaped as '\\uXXXX'. */\n#define CHAR_ENC_CPY_3  6 /* 3-byte UTF-8, copy. */\n#define CHAR_ENC_ESC_3  7 /* 3-byte UTF-8, escaped as '\\uXXXX'. */\n#define CHAR_ENC_CPY_4  8 /* 4-byte UTF-8, copy. */\n#define CHAR_ENC_ESC_4  9 /* 4-byte UTF-8, escaped as '\\uXXXX\\uXXXX'. */\n\n/** Character encode type table: don't escape unicode, don't escape '/'.\n    (generate with misc/make_tables.c) */\nstatic const char_enc_type enc_table_cpy[256] = {\n    3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 2, 2, 3, 3,\n    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n    0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n    4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,\n    4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,\n    6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,\n    8, 8, 8, 8, 8, 8, 8, 8, 1, 1, 1, 1, 1, 1, 1, 1\n};\n\n/** Character encode type table: don't escape unicode, escape '/'.\n    (generate with misc/make_tables.c) */\nstatic const char_enc_type enc_table_cpy_slash[256] = {\n    3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 2, 2, 3, 3,\n    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n    0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n    4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,\n    4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,\n    6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,\n    8, 8, 8, 8, 8, 8, 8, 8, 1, 1, 1, 1, 1, 1, 1, 1\n};\n\n/** Character encode type table: escape unicode, don't escape '/'.\n    (generate with misc/make_tables.c) */\nstatic const char_enc_type enc_table_esc[256] = {\n    3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 2, 2, 3, 3,\n    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n    0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n    9, 9, 9, 9, 9, 9, 9, 9, 1, 1, 1, 1, 1, 1, 1, 1\n};\n\n/** Character encode type table: escape unicode, escape '/'.\n    (generate with misc/make_tables.c) */\nstatic const char_enc_type enc_table_esc_slash[256] = {\n    3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 2, 2, 3, 3,\n    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n    0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n    9, 9, 9, 9, 9, 9, 9, 9, 1, 1, 1, 1, 1, 1, 1, 1\n};\n\n/** Escaped hex character table: [\"00\" \"01\" \"02\" ... \"FD\" \"FE\" \"FF\"].\n    (generate with misc/make_tables.c) */\nyyjson_align(2)\nstatic const u8 esc_hex_char_table[512] = {\n    '0', '0', '0', '1', '0', '2', '0', '3',\n    '0', '4', '0', '5', '0', '6', '0', '7',\n    '0', '8', '0', '9', '0', 'A', '0', 'B',\n    '0', 'C', '0', 'D', '0', 'E', '0', 'F',\n    '1', '0', '1', '1', '1', '2', '1', '3',\n    '1', '4', '1', '5', '1', '6', '1', '7',\n    '1', '8', '1', '9', '1', 'A', '1', 'B',\n    '1', 'C', '1', 'D', '1', 'E', '1', 'F',\n    '2', '0', '2', '1', '2', '2', '2', '3',\n    '2', '4', '2', '5', '2', '6', '2', '7',\n    '2', '8', '2', '9', '2', 'A', '2', 'B',\n    '2', 'C', '2', 'D', '2', 'E', '2', 'F',\n    '3', '0', '3', '1', '3', '2', '3', '3',\n    '3', '4', '3', '5', '3', '6', '3', '7',\n    '3', '8', '3', '9', '3', 'A', '3', 'B',\n    '3', 'C', '3', 'D', '3', 'E', '3', 'F',\n    '4', '0', '4', '1', '4', '2', '4', '3',\n    '4', '4', '4', '5', '4', '6', '4', '7',\n    '4', '8', '4', '9', '4', 'A', '4', 'B',\n    '4', 'C', '4', 'D', '4', 'E', '4', 'F',\n    '5', '0', '5', '1', '5', '2', '5', '3',\n    '5', '4', '5', '5', '5', '6', '5', '7',\n    '5', '8', '5', '9', '5', 'A', '5', 'B',\n    '5', 'C', '5', 'D', '5', 'E', '5', 'F',\n    '6', '0', '6', '1', '6', '2', '6', '3',\n    '6', '4', '6', '5', '6', '6', '6', '7',\n    '6', '8', '6', '9', '6', 'A', '6', 'B',\n    '6', 'C', '6', 'D', '6', 'E', '6', 'F',\n    '7', '0', '7', '1', '7', '2', '7', '3',\n    '7', '4', '7', '5', '7', '6', '7', '7',\n    '7', '8', '7', '9', '7', 'A', '7', 'B',\n    '7', 'C', '7', 'D', '7', 'E', '7', 'F',\n    '8', '0', '8', '1', '8', '2', '8', '3',\n    '8', '4', '8', '5', '8', '6', '8', '7',\n    '8', '8', '8', '9', '8', 'A', '8', 'B',\n    '8', 'C', '8', 'D', '8', 'E', '8', 'F',\n    '9', '0', '9', '1', '9', '2', '9', '3',\n    '9', '4', '9', '5', '9', '6', '9', '7',\n    '9', '8', '9', '9', '9', 'A', '9', 'B',\n    '9', 'C', '9', 'D', '9', 'E', '9', 'F',\n    'A', '0', 'A', '1', 'A', '2', 'A', '3',\n    'A', '4', 'A', '5', 'A', '6', 'A', '7',\n    'A', '8', 'A', '9', 'A', 'A', 'A', 'B',\n    'A', 'C', 'A', 'D', 'A', 'E', 'A', 'F',\n    'B', '0', 'B', '1', 'B', '2', 'B', '3',\n    'B', '4', 'B', '5', 'B', '6', 'B', '7',\n    'B', '8', 'B', '9', 'B', 'A', 'B', 'B',\n    'B', 'C', 'B', 'D', 'B', 'E', 'B', 'F',\n    'C', '0', 'C', '1', 'C', '2', 'C', '3',\n    'C', '4', 'C', '5', 'C', '6', 'C', '7',\n    'C', '8', 'C', '9', 'C', 'A', 'C', 'B',\n    'C', 'C', 'C', 'D', 'C', 'E', 'C', 'F',\n    'D', '0', 'D', '1', 'D', '2', 'D', '3',\n    'D', '4', 'D', '5', 'D', '6', 'D', '7',\n    'D', '8', 'D', '9', 'D', 'A', 'D', 'B',\n    'D', 'C', 'D', 'D', 'D', 'E', 'D', 'F',\n    'E', '0', 'E', '1', 'E', '2', 'E', '3',\n    'E', '4', 'E', '5', 'E', '6', 'E', '7',\n    'E', '8', 'E', '9', 'E', 'A', 'E', 'B',\n    'E', 'C', 'E', 'D', 'E', 'E', 'E', 'F',\n    'F', '0', 'F', '1', 'F', '2', 'F', '3',\n    'F', '4', 'F', '5', 'F', '6', 'F', '7',\n    'F', '8', 'F', '9', 'F', 'A', 'F', 'B',\n    'F', 'C', 'F', 'D', 'F', 'E', 'F', 'F'\n};\n\n/** Escaped single character table. (generate with misc/make_tables.c) */\nyyjson_align(2)\nstatic const u8 esc_single_char_table[512] = {\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    '\\\\', 'b', '\\\\', 't', '\\\\', 'n', ' ', ' ',\n    '\\\\', 'f', '\\\\', 'r', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', '\\\\', '\"', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', '\\\\', '/',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    '\\\\', '\\\\', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',\n    ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '\n};\n\n/** Returns the encode table with options. */\nstatic_inline const char_enc_type *get_enc_table_with_flag(\n    yyjson_read_flag flg) {\n    if (has_write_flag(ESCAPE_UNICODE)) {\n        if (has_write_flag(ESCAPE_SLASHES)) {\n            return enc_table_esc_slash;\n        } else {\n            return enc_table_esc;\n        }\n    } else {\n        if (has_write_flag(ESCAPE_SLASHES)) {\n            return enc_table_cpy_slash;\n        } else {\n            return enc_table_cpy;\n        }\n    }\n}\n\n/** Write raw string. */\nstatic_inline u8 *write_raw(u8 *cur, const u8 *raw, usize raw_len) {\n    memcpy(cur, raw, raw_len);\n    return cur + raw_len;\n}\n\n/**\n Write string no-escape.\n @param cur Buffer cursor.\n @param str A UTF-8 string, null-terminator is not required.\n @param str_len Length of string in bytes.\n @return The buffer cursor after string.\n */\nstatic_inline u8 *write_string_noesc(u8 *cur, const u8 *str, usize str_len) {\n    *cur++ = '\"';\n    while (str_len >= 16) {\n        byte_copy_16(cur, str);\n        cur += 16;\n        str += 16;\n        str_len -= 16;\n    }\n    while (str_len >= 4) {\n        byte_copy_4(cur, str);\n        cur += 4;\n        str += 4;\n        str_len -= 4;\n    }\n    while (str_len) {\n        *cur++ = *str++;\n        str_len -= 1;\n    }\n    *cur++ = '\"';\n    return cur;\n}\n\n/**\n Write UTF-8 string (requires len * 6 + 2 bytes buffer).\n @param cur Buffer cursor.\n @param esc Escape unicode.\n @param inv Allow invalid unicode.\n @param str A UTF-8 string, null-terminator is not required.\n @param str_len Length of string in bytes.\n @param enc_table Encode type table for character.\n @return The buffer cursor after string, or NULL on invalid unicode.\n */\nstatic_inline u8 *write_string(u8 *cur, bool esc, bool inv,\n                               const u8 *str, usize str_len,\n                               const char_enc_type *enc_table) {\n    \n    /* UTF-8 character mask and pattern, see `read_string()` for details. */\n#if YYJSON_ENDIAN == YYJSON_BIG_ENDIAN\n    const u16 b2_mask = 0xE0C0UL;\n    const u16 b2_patt = 0xC080UL;\n    const u16 b2_requ = 0x1E00UL;\n    const u32 b3_mask = 0xF0C0C000UL;\n    const u32 b3_patt = 0xE0808000UL;\n    const u32 b3_requ = 0x0F200000UL;\n    const u32 b3_erro = 0x0D200000UL;\n    const u32 b4_mask = 0xF8C0C0C0UL;\n    const u32 b4_patt = 0xF0808080UL;\n    const u32 b4_requ = 0x07300000UL;\n    const u32 b4_err0 = 0x04000000UL;\n    const u32 b4_err1 = 0x03300000UL;\n#elif YYJSON_ENDIAN == YYJSON_LITTLE_ENDIAN\n    const u16 b2_mask = 0xC0E0UL;\n    const u16 b2_patt = 0x80C0UL;\n    const u16 b2_requ = 0x001EUL;\n    const u32 b3_mask = 0x00C0C0F0UL;\n    const u32 b3_patt = 0x008080E0UL;\n    const u32 b3_requ = 0x0000200FUL;\n    const u32 b3_erro = 0x0000200DUL;\n    const u32 b4_mask = 0xC0C0C0F8UL;\n    const u32 b4_patt = 0x808080F0UL;\n    const u32 b4_requ = 0x00003007UL;\n    const u32 b4_err0 = 0x00000004UL;\n    const u32 b4_err1 = 0x00003003UL;\n#else\n    /* this should be evaluated at compile-time */\n    v16_uni b2_mask_uni = {{ 0xE0, 0xC0 }};\n    v16_uni b2_patt_uni = {{ 0xC0, 0x80 }};\n    v16_uni b2_requ_uni = {{ 0x1E, 0x00 }};\n    v32_uni b3_mask_uni = {{ 0xF0, 0xC0, 0xC0, 0x00 }};\n    v32_uni b3_patt_uni = {{ 0xE0, 0x80, 0x80, 0x00 }};\n    v32_uni b3_requ_uni = {{ 0x0F, 0x20, 0x00, 0x00 }};\n    v32_uni b3_erro_uni = {{ 0x0D, 0x20, 0x00, 0x00 }};\n    v32_uni b4_mask_uni = {{ 0xF8, 0xC0, 0xC0, 0xC0 }};\n    v32_uni b4_patt_uni = {{ 0xF0, 0x80, 0x80, 0x80 }};\n    v32_uni b4_requ_uni = {{ 0x07, 0x30, 0x00, 0x00 }};\n    v32_uni b4_err0_uni = {{ 0x04, 0x00, 0x00, 0x00 }};\n    v32_uni b4_err1_uni = {{ 0x03, 0x30, 0x00, 0x00 }};\n    u16 b2_mask = b2_mask_uni.u;\n    u16 b2_patt = b2_patt_uni.u;\n    u16 b2_requ = b2_requ_uni.u;\n    u32 b3_mask = b3_mask_uni.u;\n    u32 b3_patt = b3_patt_uni.u;\n    u32 b3_requ = b3_requ_uni.u;\n    u32 b3_erro = b3_erro_uni.u;\n    u32 b4_mask = b4_mask_uni.u;\n    u32 b4_patt = b4_patt_uni.u;\n    u32 b4_requ = b4_requ_uni.u;\n    u32 b4_err0 = b4_err0_uni.u;\n    u32 b4_err1 = b4_err1_uni.u;\n#endif\n    \n#define is_valid_seq_2(uni) ( \\\n    ((uni & b2_mask) == b2_patt) && \\\n    ((uni & b2_requ)) \\\n)\n    \n#define is_valid_seq_3(uni) ( \\\n    ((uni & b3_mask) == b3_patt) && \\\n    ((tmp = (uni & b3_requ))) && \\\n    ((tmp != b3_erro)) \\\n)\n    \n#define is_valid_seq_4(uni) ( \\\n    ((uni & b4_mask) == b4_patt) && \\\n    ((tmp = (uni & b4_requ))) && \\\n    ((tmp & b4_err0) == 0 || (tmp & b4_err1) == 0) \\\n)\n    \n    /* The replacement character U+FFFD, used to indicate invalid character. */\n    const v32 rep = {{ 'F', 'F', 'F', 'D' }};\n    const v32 pre = {{ '\\\\', 'u', '0', '0' }};\n    \n    const u8 *src = str;\n    const u8 *end = str + str_len;\n    *cur++ = '\"';\n    \ncopy_ascii:\n    /*\n     Copy continuous ASCII, loop unrolling, same as the following code:\n     \n         while (end > src) (\n            if (unlikely(enc_table[*src])) break;\n            *cur++ = *src++;\n         );\n     */\n#define expr_jump(i) \\\n    if (unlikely(enc_table[src[i]])) goto stop_char_##i;\n    \n#define expr_stop(i) \\\n    stop_char_##i: \\\n    memcpy(cur, src, i); \\\n    cur += i; src += i; goto copy_utf8;\n    \n    while (end - src >= 16) {\n        repeat16_incr(expr_jump)\n        byte_copy_16(cur, src);\n        cur += 16; src += 16;\n    }\n    \n    while (end - src >= 4) {\n        repeat4_incr(expr_jump)\n        byte_copy_4(cur, src);\n        cur += 4; src += 4;\n    }\n    \n    while (end > src) {\n        expr_jump(0)\n        *cur++ = *src++;\n    }\n    \n    *cur++ = '\"';\n    return cur;\n    \n    repeat16_incr(expr_stop)\n    \n#undef expr_jump\n#undef expr_stop\n    \ncopy_utf8:\n    if (unlikely(src + 4 > end)) {\n        if (end == src) goto copy_end;\n        if (end - src < enc_table[*src] / 2) goto err_one;\n    }\n    switch (enc_table[*src]) {\n        case CHAR_ENC_CPY_1: {\n            *cur++ = *src++;\n            goto copy_ascii;\n        }\n        case CHAR_ENC_CPY_2: {\n            u16 v;\n#if YYJSON_DISABLE_UTF8_VALIDATION\n            byte_copy_2(cur, src);\n#else\n            v = byte_load_2(src);\n            if (unlikely(!is_valid_seq_2(v))) goto err_cpy;\n            byte_copy_2(cur, src);\n#endif\n            cur += 2;\n            src += 2;\n            goto copy_utf8;\n        }\n        case CHAR_ENC_CPY_3: {\n            u32 v, tmp;\n#if YYJSON_DISABLE_UTF8_VALIDATION\n            if (likely(src + 4 <= end)) {\n                byte_copy_4(cur, src);\n            } else {\n                byte_copy_2(cur, src);\n                cur[2] = src[2];\n            }\n#else\n            if (likely(src + 4 <= end)) {\n                v = byte_load_4(src);\n                if (unlikely(!is_valid_seq_3(v))) goto err_cpy;\n                byte_copy_4(cur, src);\n            } else {\n                v = byte_load_3(src);\n                if (unlikely(!is_valid_seq_3(v))) goto err_cpy;\n                byte_copy_4(cur, &v);\n            }\n#endif\n            cur += 3;\n            src += 3;\n            goto copy_utf8;\n        }\n        case CHAR_ENC_CPY_4: {\n            u32 v, tmp;\n#if YYJSON_DISABLE_UTF8_VALIDATION\n            byte_copy_4(cur, src);\n#else\n            v = byte_load_4(src);\n            if (unlikely(!is_valid_seq_4(v))) goto err_cpy;\n            byte_copy_4(cur, src);\n#endif\n            cur += 4;\n            src += 4;\n            goto copy_utf8;\n        }\n        case CHAR_ENC_ESC_A: {\n            byte_copy_2(cur, &esc_single_char_table[*src * 2]);\n            cur += 2;\n            src += 1;\n            goto copy_utf8;\n        }\n        case CHAR_ENC_ESC_1: {\n            byte_copy_4(cur + 0, &pre);\n            byte_copy_2(cur + 4, &esc_hex_char_table[*src * 2]);\n            cur += 6;\n            src += 1;\n            goto copy_utf8;\n        }\n        case CHAR_ENC_ESC_2: {\n            u16 u, v;\n#if !YYJSON_DISABLE_UTF8_VALIDATION\n            v = byte_load_2(src);\n            if (unlikely(!is_valid_seq_2(v))) goto err_esc;\n#endif\n            u = (u16)(((u16)(src[0] & 0x1F) << 6) |\n                      ((u16)(src[1] & 0x3F) << 0));\n            byte_copy_2(cur + 0, &pre);\n            byte_copy_2(cur + 2, &esc_hex_char_table[(u >> 8) * 2]);\n            byte_copy_2(cur + 4, &esc_hex_char_table[(u & 0xFF) * 2]);\n            cur += 6;\n            src += 2;\n            goto copy_utf8;\n        }\n        case CHAR_ENC_ESC_3: {\n            u16 u;\n            u32 v, tmp;\n#if !YYJSON_DISABLE_UTF8_VALIDATION\n            v = byte_load_3(src);\n            if (unlikely(!is_valid_seq_3(v))) goto err_esc;\n#endif\n            u = (u16)(((u16)(src[0] & 0x0F) << 12) |\n                      ((u16)(src[1] & 0x3F) << 6) |\n                      ((u16)(src[2] & 0x3F) << 0));\n            byte_copy_2(cur + 0, &pre);\n            byte_copy_2(cur + 2, &esc_hex_char_table[(u >> 8) * 2]);\n            byte_copy_2(cur + 4, &esc_hex_char_table[(u & 0xFF) * 2]);\n            cur += 6;\n            src += 3;\n            goto copy_utf8;\n        }\n        case CHAR_ENC_ESC_4: {\n            u32 hi, lo, u, v, tmp;\n#if !YYJSON_DISABLE_UTF8_VALIDATION\n            v = byte_load_4(src);\n            if (unlikely(!is_valid_seq_4(v))) goto err_esc;\n#endif\n            u = ((u32)(src[0] & 0x07) << 18) |\n                ((u32)(src[1] & 0x3F) << 12) |\n                ((u32)(src[2] & 0x3F) << 6) |\n                ((u32)(src[3] & 0x3F) << 0);\n            u -= 0x10000;\n            hi = (u >> 10) + 0xD800;\n            lo = (u & 0x3FF) + 0xDC00;\n            byte_copy_2(cur + 0, &pre);\n            byte_copy_2(cur + 2, &esc_hex_char_table[(hi >> 8) * 2]);\n            byte_copy_2(cur + 4, &esc_hex_char_table[(hi & 0xFF) * 2]);\n            byte_copy_2(cur + 6, &pre);\n            byte_copy_2(cur + 8, &esc_hex_char_table[(lo >> 8) * 2]);\n            byte_copy_2(cur + 10, &esc_hex_char_table[(lo & 0xFF) * 2]);\n            cur += 12;\n            src += 4;\n            goto copy_utf8;\n        }\n        case CHAR_ENC_ERR_1: {\n            goto err_one;\n        }\n        default: break;\n    }\n    \ncopy_end:\n    *cur++ = '\"';\n    return cur;\n    \nerr_one:\n    if (esc) goto err_esc;\n    else goto err_cpy;\n    \nerr_cpy:\n    if (!inv) return NULL;\n    *cur++ = *src++;\n    goto copy_utf8;\n    \nerr_esc:\n    if (!inv) return NULL;\n    byte_copy_2(cur + 0, &pre);\n    byte_copy_4(cur + 2, &rep);\n    cur += 6;\n    src += 1;\n    goto copy_utf8;\n    \n#undef is_valid_seq_2\n#undef is_valid_seq_3\n#undef is_valid_seq_4\n}\n\n\n\n/*==============================================================================\n * Writer Utilities\n *============================================================================*/\n\n/** Write null (requires 8 bytes buffer). */\nstatic_inline u8 *write_null(u8 *cur) {\n    v64 v = {{ 'n', 'u', 'l', 'l', ',', '\\n', 0, 0 }};\n    byte_copy_8(cur, &v);\n    return cur + 4;\n}\n\n/** Write bool (requires 8 bytes buffer). */\nstatic_inline u8 *write_bool(u8 *cur, bool val) {\n    v64 v0 = {{ 'f', 'a', 'l', 's', 'e', ',', '\\n', 0 }};\n    v64 v1 = {{ 't', 'r', 'u', 'e', ',', '\\n', 0, 0 }};\n    if (val) {\n        byte_copy_8(cur, &v1);\n    } else {\n        byte_copy_8(cur, &v0);\n    }\n    return cur + 5 - val;\n}\n\n/** Write indent (requires level x 4 bytes buffer).\n    Param spaces should not larger than 4. */\nstatic_inline u8 *write_indent(u8 *cur, usize level, usize spaces) {\n    while (level-- > 0) {\n        byte_copy_4(cur, \"    \");\n        cur += spaces;\n    }\n    return cur;\n}\n\n/** Write data to file pointer. */\nstatic bool write_dat_to_fp(FILE *fp, u8 *dat, usize len,\n                            yyjson_write_err *err) {\n    if (fwrite(dat, len, 1, fp) != 1) {\n        err->msg = \"file writing failed\";\n        err->code = YYJSON_WRITE_ERROR_FILE_WRITE;\n        return false;\n    }\n    return true;\n}\n\n/** Write data to file. */\nstatic bool write_dat_to_file(const char *path, u8 *dat, usize len,\n                              yyjson_write_err *err) {\n    \n#define return_err(_code, _msg) do { \\\n    err->msg = _msg; \\\n    err->code = YYJSON_WRITE_ERROR_##_code; \\\n    if (file) fclose(file); \\\n    return false; \\\n} while (false)\n    \n    FILE *file = fopen_writeonly(path);\n    if (file == NULL) {\n        return_err(FILE_OPEN, \"file opening failed\");\n    }\n    if (fwrite(dat, len, 1, file) != 1) {\n        return_err(FILE_WRITE, \"file writing failed\");\n    }\n    if (fclose(file) != 0) {\n        file = NULL;\n        return_err(FILE_WRITE, \"file closing failed\");\n    }\n    return true;\n    \n#undef return_err\n}\n\n\n\n/*==============================================================================\n * JSON Writer Implementation\n *============================================================================*/\n\ntypedef struct yyjson_write_ctx {\n    usize tag;\n} yyjson_write_ctx;\n\nstatic_inline void yyjson_write_ctx_set(yyjson_write_ctx *ctx,\n                                        usize size, bool is_obj) {\n    ctx->tag = (size << 1) | (usize)is_obj;\n}\n\nstatic_inline void yyjson_write_ctx_get(yyjson_write_ctx *ctx,\n                                        usize *size, bool *is_obj) {\n    usize tag = ctx->tag;\n    *size = tag >> 1;\n    *is_obj = (bool)(tag & 1);\n}\n\n/** Write single JSON value. */\nstatic_inline u8 *yyjson_write_single(yyjson_val *val,\n                                      yyjson_write_flag flg,\n                                      yyjson_alc alc,\n                                      usize *dat_len,\n                                      yyjson_write_err *err) {\n    \n#define return_err(_code, _msg) do { \\\n    if (hdr) alc.free(alc.ctx, (void *)hdr); \\\n    *dat_len = 0; \\\n    err->code = YYJSON_WRITE_ERROR_##_code; \\\n    err->msg = _msg; \\\n    return NULL; \\\n} while (false)\n    \n#define incr_len(_len) do { \\\n    hdr = (u8 *)alc.malloc(alc.ctx, _len); \\\n    if (!hdr) goto fail_alloc; \\\n    cur = hdr; \\\n} while (false)\n    \n#define check_str_len(_len) do { \\\n    if ((sizeof(usize) < 8) && (_len >= (USIZE_MAX - 16) / 6)) \\\n        goto fail_alloc; \\\n} while (false)\n    \n    u8 *hdr = NULL, *cur;\n    usize str_len;\n    const u8 *str_ptr;\n    const char_enc_type *enc_table = get_enc_table_with_flag(flg);\n    bool cpy = (enc_table == enc_table_cpy);\n    bool esc = has_write_flag(ESCAPE_UNICODE) != 0;\n    bool inv = has_write_flag(ALLOW_INVALID_UNICODE) != 0;\n    bool newline = has_write_flag(NEWLINE_AT_END) != 0;\n    const usize end_len = 2; /* '\\n' and '\\0' */\n    \n    switch (unsafe_yyjson_get_type(val)) {\n        case YYJSON_TYPE_RAW:\n            str_len = unsafe_yyjson_get_len(val);\n            str_ptr = (const u8 *)unsafe_yyjson_get_str(val);\n            check_str_len(str_len);\n            incr_len(str_len + end_len);\n            cur = write_raw(cur, str_ptr, str_len);\n            break;\n            \n        case YYJSON_TYPE_STR:\n            str_len = unsafe_yyjson_get_len(val);\n            str_ptr = (const u8 *)unsafe_yyjson_get_str(val);\n            check_str_len(str_len);\n            incr_len(str_len * 6 + 2 + end_len);\n            if (likely(cpy) && unsafe_yyjson_get_subtype(val)) {\n                cur = write_string_noesc(cur, str_ptr, str_len);\n            } else {\n                cur = write_string(cur, esc, inv, str_ptr, str_len, enc_table);\n                if (unlikely(!cur)) goto fail_str;\n            }\n            break;\n            \n        case YYJSON_TYPE_NUM:\n            incr_len(32 + end_len);\n            cur = write_number(cur, val, flg);\n            if (unlikely(!cur)) goto fail_num;\n            break;\n            \n        case YYJSON_TYPE_BOOL:\n            incr_len(8);\n            cur = write_bool(cur, unsafe_yyjson_get_bool(val));\n            break;\n            \n        case YYJSON_TYPE_NULL:\n            incr_len(8);\n            cur = write_null(cur);\n            break;\n            \n        case YYJSON_TYPE_ARR:\n            incr_len(2 + end_len);\n            byte_copy_2(cur, \"[]\");\n            cur += 2;\n            break;\n            \n        case YYJSON_TYPE_OBJ:\n            incr_len(2 + end_len);\n            byte_copy_2(cur, \"{}\");\n            cur += 2;\n            break;\n            \n        default:\n            goto fail_type;\n    }\n    \n    if (newline) *cur++ = '\\n';\n    *cur = '\\0';\n    *dat_len = (usize)(cur - hdr);\n    memset(err, 0, sizeof(yyjson_write_err));\n    return hdr;\n    \nfail_alloc:\n    return_err(MEMORY_ALLOCATION, \"memory allocation failed\");\nfail_type:\n    return_err(INVALID_VALUE_TYPE, \"invalid JSON value type\");\nfail_num:\n    return_err(NAN_OR_INF, \"nan or inf number is not allowed\");\nfail_str:\n    return_err(INVALID_STRING, \"invalid utf-8 encoding in string\");\n    \n#undef return_err\n#undef check_str_len\n#undef incr_len\n}\n\n/** Write JSON document minify.\n    The root of this document should be a non-empty container. */\nstatic_inline u8 *yyjson_write_minify(const yyjson_val *root,\n                                      const yyjson_write_flag flg,\n                                      const yyjson_alc alc,\n                                      usize *dat_len,\n                                      yyjson_write_err *err) {\n    \n#define return_err(_code, _msg) do { \\\n    *dat_len = 0; \\\n    err->code = YYJSON_WRITE_ERROR_##_code; \\\n    err->msg = _msg; \\\n    if (hdr) alc.free(alc.ctx, hdr); \\\n    return NULL; \\\n} while (false)\n    \n#define incr_len(_len) do { \\\n    ext_len = (usize)(_len); \\\n    if (unlikely((u8 *)(cur + ext_len) >= (u8 *)ctx)) { \\\n        alc_inc = yyjson_max(alc_len / 2, ext_len); \\\n        alc_inc = size_align_up(alc_inc, sizeof(yyjson_write_ctx)); \\\n        if ((sizeof(usize) < 8) && size_add_is_overflow(alc_len, alc_inc)) \\\n            goto fail_alloc; \\\n        alc_len += alc_inc; \\\n        tmp = (u8 *)alc.realloc(alc.ctx, hdr, alc_len - alc_inc, alc_len); \\\n        if (unlikely(!tmp)) goto fail_alloc; \\\n        ctx_len = (usize)(end - (u8 *)ctx); \\\n        ctx_tmp = (yyjson_write_ctx *)(void *)(tmp + (alc_len - ctx_len)); \\\n        memmove((void *)ctx_tmp, (void *)(tmp + ((u8 *)ctx - hdr)), ctx_len); \\\n        ctx = ctx_tmp; \\\n        cur = tmp + (cur - hdr); \\\n        end = tmp + alc_len; \\\n        hdr = tmp; \\\n    } \\\n} while (false)\n    \n#define check_str_len(_len) do { \\\n    if ((sizeof(usize) < 8) && (_len >= (USIZE_MAX - 16) / 6)) \\\n        goto fail_alloc; \\\n} while (false)\n    \n    yyjson_val *val;\n    yyjson_type val_type;\n    usize ctn_len, ctn_len_tmp;\n    bool ctn_obj, ctn_obj_tmp, is_key;\n    u8 *hdr, *cur, *end, *tmp;\n    yyjson_write_ctx *ctx, *ctx_tmp;\n    usize alc_len, alc_inc, ctx_len, ext_len, str_len;\n    const u8 *str_ptr;\n    const char_enc_type *enc_table = get_enc_table_with_flag(flg);\n    bool cpy = (enc_table == enc_table_cpy);\n    bool esc = has_write_flag(ESCAPE_UNICODE) != 0;\n    bool inv = has_write_flag(ALLOW_INVALID_UNICODE) != 0;\n    bool newline = has_write_flag(NEWLINE_AT_END) != 0;\n    \n    alc_len = root->uni.ofs / sizeof(yyjson_val);\n    alc_len = alc_len * YYJSON_WRITER_ESTIMATED_MINIFY_RATIO + 64;\n    alc_len = size_align_up(alc_len, sizeof(yyjson_write_ctx));\n    hdr = (u8 *)alc.malloc(alc.ctx, alc_len);\n    if (!hdr) goto fail_alloc;\n    cur = hdr;\n    end = hdr + alc_len;\n    ctx = (yyjson_write_ctx *)(void *)end;\n    \ndoc_begin:\n    val = constcast(yyjson_val *)root;\n    val_type = unsafe_yyjson_get_type(val);\n    ctn_obj = (val_type == YYJSON_TYPE_OBJ);\n    ctn_len = unsafe_yyjson_get_len(val) << (u8)ctn_obj;\n    *cur++ = (u8)('[' | ((u8)ctn_obj << 5));\n    val++;\n    \nval_begin:\n    val_type = unsafe_yyjson_get_type(val);\n    if (val_type == YYJSON_TYPE_STR) {\n        is_key = ((u8)ctn_obj & (u8)~ctn_len);\n        str_len = unsafe_yyjson_get_len(val);\n        str_ptr = (const u8 *)unsafe_yyjson_get_str(val);\n        check_str_len(str_len);\n        incr_len(str_len * 6 + 16);\n        if (likely(cpy) && unsafe_yyjson_get_subtype(val)) {\n            cur = write_string_noesc(cur, str_ptr, str_len);\n        } else {\n            cur = write_string(cur, esc, inv, str_ptr, str_len, enc_table);\n            if (unlikely(!cur)) goto fail_str;\n        }\n        *cur++ = is_key ? ':' : ',';\n        goto val_end;\n    }\n    if (val_type == YYJSON_TYPE_NUM) {\n        incr_len(32);\n        cur = write_number(cur, val, flg);\n        if (unlikely(!cur)) goto fail_num;\n        *cur++ = ',';\n        goto val_end;\n    }\n    if ((val_type & (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) ==\n                    (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) {\n        ctn_len_tmp = unsafe_yyjson_get_len(val);\n        ctn_obj_tmp = (val_type == YYJSON_TYPE_OBJ);\n        incr_len(16);\n        if (unlikely(ctn_len_tmp == 0)) {\n            /* write empty container */\n            *cur++ = (u8)('[' | ((u8)ctn_obj_tmp << 5));\n            *cur++ = (u8)(']' | ((u8)ctn_obj_tmp << 5));\n            *cur++ = ',';\n            goto val_end;\n        } else {\n            /* push context, setup new container */\n            yyjson_write_ctx_set(--ctx, ctn_len, ctn_obj);\n            ctn_len = ctn_len_tmp << (u8)ctn_obj_tmp;\n            ctn_obj = ctn_obj_tmp;\n            *cur++ = (u8)('[' | ((u8)ctn_obj << 5));\n            val++;\n            goto val_begin;\n        }\n    }\n    if (val_type == YYJSON_TYPE_BOOL) {\n        incr_len(16);\n        cur = write_bool(cur, unsafe_yyjson_get_bool(val));\n        cur++;\n        goto val_end;\n    }\n    if (val_type == YYJSON_TYPE_NULL) {\n        incr_len(16);\n        cur = write_null(cur);\n        cur++;\n        goto val_end;\n    }\n    if (val_type == YYJSON_TYPE_RAW) {\n        str_len = unsafe_yyjson_get_len(val);\n        str_ptr = (const u8 *)unsafe_yyjson_get_str(val);\n        check_str_len(str_len);\n        incr_len(str_len + 2);\n        cur = write_raw(cur, str_ptr, str_len);\n        *cur++ = ',';\n        goto val_end;\n    }\n    goto fail_type;\n    \nval_end:\n    val++;\n    ctn_len--;\n    if (unlikely(ctn_len == 0)) goto ctn_end;\n    goto val_begin;\n    \nctn_end:\n    cur--;\n    *cur++ = (u8)(']' | ((u8)ctn_obj << 5));\n    *cur++ = ',';\n    if (unlikely((u8 *)ctx >= end)) goto doc_end;\n    yyjson_write_ctx_get(ctx++, &ctn_len, &ctn_obj);\n    ctn_len--;\n    if (likely(ctn_len > 0)) {\n        goto val_begin;\n    } else {\n        goto ctn_end;\n    }\n    \ndoc_end:\n    if (newline) {\n        incr_len(2);\n        *(cur - 1) = '\\n';\n        cur++;\n    }\n    *--cur = '\\0';\n    *dat_len = (usize)(cur - hdr);\n    memset(err, 0, sizeof(yyjson_write_err));\n    return hdr;\n    \nfail_alloc:\n    return_err(MEMORY_ALLOCATION, \"memory allocation failed\");\nfail_type:\n    return_err(INVALID_VALUE_TYPE, \"invalid JSON value type\");\nfail_num:\n    return_err(NAN_OR_INF, \"nan or inf number is not allowed\");\nfail_str:\n    return_err(INVALID_STRING, \"invalid utf-8 encoding in string\");\n    \n#undef return_err\n#undef incr_len\n#undef check_str_len\n}\n\n/** Write JSON document pretty.\n    The root of this document should be a non-empty container. */\nstatic_inline u8 *yyjson_write_pretty(const yyjson_val *root,\n                                      const yyjson_write_flag flg,\n                                      const yyjson_alc alc,\n                                      usize *dat_len,\n                                      yyjson_write_err *err) {\n    \n#define return_err(_code, _msg) do { \\\n    *dat_len = 0; \\\n    err->code = YYJSON_WRITE_ERROR_##_code; \\\n    err->msg = _msg; \\\n    if (hdr) alc.free(alc.ctx, hdr); \\\n    return NULL; \\\n} while (false)\n    \n#define incr_len(_len) do { \\\n    ext_len = (usize)(_len); \\\n    if (unlikely((u8 *)(cur + ext_len) >= (u8 *)ctx)) { \\\n        alc_inc = yyjson_max(alc_len / 2, ext_len); \\\n        alc_inc = size_align_up(alc_inc, sizeof(yyjson_write_ctx)); \\\n        if ((sizeof(usize) < 8) && size_add_is_overflow(alc_len, alc_inc)) \\\n            goto fail_alloc; \\\n        alc_len += alc_inc; \\\n        tmp = (u8 *)alc.realloc(alc.ctx, hdr, alc_len - alc_inc, alc_len); \\\n        if (unlikely(!tmp)) goto fail_alloc; \\\n        ctx_len = (usize)(end - (u8 *)ctx); \\\n        ctx_tmp = (yyjson_write_ctx *)(void *)(tmp + (alc_len - ctx_len)); \\\n        memmove((void *)ctx_tmp, (void *)(tmp + ((u8 *)ctx - hdr)), ctx_len); \\\n        ctx = ctx_tmp; \\\n        cur = tmp + (cur - hdr); \\\n        end = tmp + alc_len; \\\n        hdr = tmp; \\\n    } \\\n} while (false)\n    \n#define check_str_len(_len) do { \\\n    if ((sizeof(usize) < 8) && (_len >= (USIZE_MAX - 16) / 6)) \\\n        goto fail_alloc; \\\n} while (false)\n    \n    yyjson_val *val;\n    yyjson_type val_type;\n    usize ctn_len, ctn_len_tmp;\n    bool ctn_obj, ctn_obj_tmp, is_key, no_indent;\n    u8 *hdr, *cur, *end, *tmp;\n    yyjson_write_ctx *ctx, *ctx_tmp;\n    usize alc_len, alc_inc, ctx_len, ext_len, str_len, level;\n    const u8 *str_ptr;\n    const char_enc_type *enc_table = get_enc_table_with_flag(flg);\n    bool cpy = (enc_table == enc_table_cpy);\n    bool esc = has_write_flag(ESCAPE_UNICODE) != 0;\n    bool inv = has_write_flag(ALLOW_INVALID_UNICODE) != 0;\n    usize spaces = has_write_flag(PRETTY_TWO_SPACES) ? 2 : 4;\n    bool newline = has_write_flag(NEWLINE_AT_END) != 0;\n    \n    alc_len = root->uni.ofs / sizeof(yyjson_val);\n    alc_len = alc_len * YYJSON_WRITER_ESTIMATED_PRETTY_RATIO + 64;\n    alc_len = size_align_up(alc_len, sizeof(yyjson_write_ctx));\n    hdr = (u8 *)alc.malloc(alc.ctx, alc_len);\n    if (!hdr) goto fail_alloc;\n    cur = hdr;\n    end = hdr + alc_len;\n    ctx = (yyjson_write_ctx *)(void *)end;\n    \ndoc_begin:\n    val = constcast(yyjson_val *)root;\n    val_type = unsafe_yyjson_get_type(val);\n    ctn_obj = (val_type == YYJSON_TYPE_OBJ);\n    ctn_len = unsafe_yyjson_get_len(val) << (u8)ctn_obj;\n    *cur++ = (u8)('[' | ((u8)ctn_obj << 5));\n    *cur++ = '\\n';\n    val++;\n    level = 1;\n    \nval_begin:\n    val_type = unsafe_yyjson_get_type(val);\n    if (val_type == YYJSON_TYPE_STR) {\n        is_key = (bool)((u8)ctn_obj & (u8)~ctn_len);\n        no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);\n        str_len = unsafe_yyjson_get_len(val);\n        str_ptr = (const u8 *)unsafe_yyjson_get_str(val);\n        check_str_len(str_len);\n        incr_len(str_len * 6 + 16 + (no_indent ? 0 : level * 4));\n        cur = write_indent(cur, no_indent ? 0 : level, spaces);\n        if (likely(cpy) && unsafe_yyjson_get_subtype(val)) {\n            cur = write_string_noesc(cur, str_ptr, str_len);\n        } else {\n            cur = write_string(cur, esc, inv, str_ptr, str_len, enc_table);\n            if (unlikely(!cur)) goto fail_str;\n        }\n        *cur++ = is_key ? ':' : ',';\n        *cur++ = is_key ? ' ' : '\\n';\n        goto val_end;\n    }\n    if (val_type == YYJSON_TYPE_NUM) {\n        no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);\n        incr_len(32 + (no_indent ? 0 : level * 4));\n        cur = write_indent(cur, no_indent ? 0 : level, spaces);\n        cur = write_number(cur, val, flg);\n        if (unlikely(!cur)) goto fail_num;\n        *cur++ = ',';\n        *cur++ = '\\n';\n        goto val_end;\n    }\n    if ((val_type & (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) ==\n                    (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) {\n        no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);\n        ctn_len_tmp = unsafe_yyjson_get_len(val);\n        ctn_obj_tmp = (val_type == YYJSON_TYPE_OBJ);\n        if (unlikely(ctn_len_tmp == 0)) {\n            /* write empty container */\n            incr_len(16 + (no_indent ? 0 : level * 4));\n            cur = write_indent(cur, no_indent ? 0 : level, spaces);\n            *cur++ = (u8)('[' | ((u8)ctn_obj_tmp << 5));\n            *cur++ = (u8)(']' | ((u8)ctn_obj_tmp << 5));\n            *cur++ = ',';\n            *cur++ = '\\n';\n            goto val_end;\n        } else {\n            /* push context, setup new container */\n            incr_len(32 + (no_indent ? 0 : level * 4));\n            yyjson_write_ctx_set(--ctx, ctn_len, ctn_obj);\n            ctn_len = ctn_len_tmp << (u8)ctn_obj_tmp;\n            ctn_obj = ctn_obj_tmp;\n            cur = write_indent(cur, no_indent ? 0 : level, spaces);\n            level++;\n            *cur++ = (u8)('[' | ((u8)ctn_obj << 5));\n            *cur++ = '\\n';\n            val++;\n            goto val_begin;\n        }\n    }\n    if (val_type == YYJSON_TYPE_BOOL) {\n        no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);\n        incr_len(16 + (no_indent ? 0 : level * 4));\n        cur = write_indent(cur, no_indent ? 0 : level, spaces);\n        cur = write_bool(cur, unsafe_yyjson_get_bool(val));\n        cur += 2;\n        goto val_end;\n    }\n    if (val_type == YYJSON_TYPE_NULL) {\n        no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);\n        incr_len(16 + (no_indent ? 0 : level * 4));\n        cur = write_indent(cur, no_indent ? 0 : level, spaces);\n        cur = write_null(cur);\n        cur += 2;\n        goto val_end;\n    }\n    if (val_type == YYJSON_TYPE_RAW) {\n        str_len = unsafe_yyjson_get_len(val);\n        str_ptr = (const u8 *)unsafe_yyjson_get_str(val);\n        check_str_len(str_len);\n        incr_len(str_len + 3);\n        cur = write_raw(cur, str_ptr, str_len);\n        *cur++ = ',';\n        *cur++ = '\\n';\n        goto val_end;\n    }\n    goto fail_type;\n    \nval_end:\n    val++;\n    ctn_len--;\n    if (unlikely(ctn_len == 0)) goto ctn_end;\n    goto val_begin;\n    \nctn_end:\n    cur -= 2;\n    *cur++ = '\\n';\n    incr_len(level * 4);\n    cur = write_indent(cur, --level, spaces);\n    *cur++ = (u8)(']' | ((u8)ctn_obj << 5));\n    if (unlikely((u8 *)ctx >= end)) goto doc_end;\n    yyjson_write_ctx_get(ctx++, &ctn_len, &ctn_obj);\n    ctn_len--;\n    *cur++ = ',';\n    *cur++ = '\\n';\n    if (likely(ctn_len > 0)) {\n        goto val_begin;\n    } else {\n        goto ctn_end;\n    }\n    \ndoc_end:\n    if (newline) {\n        incr_len(2);\n        *cur++ = '\\n';\n    }\n    *cur = '\\0';\n    *dat_len = (usize)(cur - hdr);\n    memset(err, 0, sizeof(yyjson_write_err));\n    return hdr;\n    \nfail_alloc:\n    return_err(MEMORY_ALLOCATION, \"memory allocation failed\");\nfail_type:\n    return_err(INVALID_VALUE_TYPE, \"invalid JSON value type\");\nfail_num:\n    return_err(NAN_OR_INF, \"nan or inf number is not allowed\");\nfail_str:\n    return_err(INVALID_STRING, \"invalid utf-8 encoding in string\");\n    \n#undef return_err\n#undef incr_len\n#undef check_str_len\n}\n\nchar *yyjson_val_write_opts(const yyjson_val *val,\n                            yyjson_write_flag flg,\n                            const yyjson_alc *alc_ptr,\n                            usize *dat_len,\n                            yyjson_write_err *err) {\n    yyjson_write_err dummy_err;\n    usize dummy_dat_len;\n    yyjson_alc alc = alc_ptr ? *alc_ptr : YYJSON_DEFAULT_ALC;\n    yyjson_val *root = constcast(yyjson_val *)val;\n    \n    err = err ? err : &dummy_err;\n    dat_len = dat_len ? dat_len : &dummy_dat_len;\n    \n    if (unlikely(!root)) {\n        *dat_len = 0;\n        err->msg = \"input JSON is NULL\";\n        err->code = YYJSON_READ_ERROR_INVALID_PARAMETER;\n        return NULL;\n    }\n    \n    if (!unsafe_yyjson_is_ctn(root) || unsafe_yyjson_get_len(root) == 0) {\n        return (char *)yyjson_write_single(root, flg, alc, dat_len, err);\n    } else if (flg & (YYJSON_WRITE_PRETTY | YYJSON_WRITE_PRETTY_TWO_SPACES)) {\n        return (char *)yyjson_write_pretty(root, flg, alc, dat_len, err);\n    } else {\n        return (char *)yyjson_write_minify(root, flg, alc, dat_len, err);\n    }\n}\n\nchar *yyjson_write_opts(const yyjson_doc *doc,\n                        yyjson_write_flag flg,\n                        const yyjson_alc *alc_ptr,\n                        usize *dat_len,\n                        yyjson_write_err *err) {\n    yyjson_val *root = doc ? doc->root : NULL;\n    return yyjson_val_write_opts(root, flg, alc_ptr, dat_len, err);\n}\n\nbool yyjson_val_write_file(const char *path,\n                           const yyjson_val *val,\n                           yyjson_write_flag flg,\n                           const yyjson_alc *alc_ptr,\n                           yyjson_write_err *err) {\n    yyjson_write_err dummy_err;\n    u8 *dat;\n    usize dat_len = 0;\n    yyjson_val *root = constcast(yyjson_val *)val;\n    bool suc;\n    \n    alc_ptr = alc_ptr ? alc_ptr : &YYJSON_DEFAULT_ALC;\n    err = err ? err : &dummy_err;\n    if (unlikely(!path || !*path)) {\n        err->msg = \"input path is invalid\";\n        err->code = YYJSON_READ_ERROR_INVALID_PARAMETER;\n        return false;\n    }\n    \n    dat = (u8 *)yyjson_val_write_opts(root, flg, alc_ptr, &dat_len, err);\n    if (unlikely(!dat)) return false;\n    suc = write_dat_to_file(path, dat, dat_len, err);\n    alc_ptr->free(alc_ptr->ctx, dat);\n    return suc;\n}\n\nbool yyjson_val_write_fp(FILE *fp,\n                         const yyjson_val *val,\n                         yyjson_write_flag flg,\n                         const yyjson_alc *alc_ptr,\n                         yyjson_write_err *err) {\n    yyjson_write_err dummy_err;\n    u8 *dat;\n    usize dat_len = 0;\n    yyjson_val *root = constcast(yyjson_val *)val;\n    bool suc;\n    \n    alc_ptr = alc_ptr ? alc_ptr : &YYJSON_DEFAULT_ALC;\n    err = err ? err : &dummy_err;\n    if (unlikely(!fp)) {\n        err->msg = \"input fp is invalid\";\n        err->code = YYJSON_READ_ERROR_INVALID_PARAMETER;\n        return false;\n    }\n    \n    dat = (u8 *)yyjson_val_write_opts(root, flg, alc_ptr, &dat_len, err);\n    if (unlikely(!dat)) return false;\n    suc = write_dat_to_fp(fp, dat, dat_len, err);\n    alc_ptr->free(alc_ptr->ctx, dat);\n    return suc;\n}\n\nbool yyjson_write_file(const char *path,\n                       const yyjson_doc *doc,\n                       yyjson_write_flag flg,\n                       const yyjson_alc *alc_ptr,\n                       yyjson_write_err *err) {\n    yyjson_val *root = doc ? doc->root : NULL;\n    return yyjson_val_write_file(path, root, flg, alc_ptr, err);\n}\n\nbool yyjson_write_fp(FILE *fp,\n                    const yyjson_doc *doc,\n                    yyjson_write_flag flg,\n                     const yyjson_alc *alc_ptr,\n                    yyjson_write_err *err) {\n    yyjson_val *root = doc ? doc->root : NULL;\n    return yyjson_val_write_fp(fp, root, flg, alc_ptr, err);\n}\n\n\n\n/*==============================================================================\n * Mutable JSON Writer Implementation\n *============================================================================*/\n\ntypedef struct yyjson_mut_write_ctx {\n    usize tag;\n    yyjson_mut_val *ctn;\n} yyjson_mut_write_ctx;\n\nstatic_inline void yyjson_mut_write_ctx_set(yyjson_mut_write_ctx *ctx,\n                                            yyjson_mut_val *ctn,\n                                            usize size, bool is_obj) {\n    ctx->tag = (size << 1) | (usize)is_obj;\n    ctx->ctn = ctn;\n}\n\nstatic_inline void yyjson_mut_write_ctx_get(yyjson_mut_write_ctx *ctx,\n                                            yyjson_mut_val **ctn,\n                                            usize *size, bool *is_obj) {\n    usize tag = ctx->tag;\n    *size = tag >> 1;\n    *is_obj = (bool)(tag & 1);\n    *ctn = ctx->ctn;\n}\n\n/** Get the estimated number of values for the mutable JSON document. */\nstatic_inline usize yyjson_mut_doc_estimated_val_num(\n    const yyjson_mut_doc *doc) {\n    usize sum = 0;\n    yyjson_val_chunk *chunk = doc->val_pool.chunks;\n    while (chunk) {\n        sum += chunk->chunk_size / sizeof(yyjson_mut_val) - 1;\n        if (chunk == doc->val_pool.chunks) {\n            sum -= (usize)(doc->val_pool.end - doc->val_pool.cur);\n        }\n        chunk = chunk->next;\n    }\n    return sum;\n}\n\n/** Write single JSON value. */\nstatic_inline u8 *yyjson_mut_write_single(yyjson_mut_val *val,\n                                          yyjson_write_flag flg,\n                                          yyjson_alc alc,\n                                          usize *dat_len,\n                                          yyjson_write_err *err) {\n    return yyjson_write_single((yyjson_val *)val, flg, alc, dat_len, err);\n}\n\n/** Write JSON document minify.\n    The root of this document should be a non-empty container. */\nstatic_inline u8 *yyjson_mut_write_minify(const yyjson_mut_val *root,\n                                          usize estimated_val_num,\n                                          yyjson_write_flag flg,\n                                          yyjson_alc alc,\n                                          usize *dat_len,\n                                          yyjson_write_err *err) {\n    \n#define return_err(_code, _msg) do { \\\n    *dat_len = 0; \\\n    err->code = YYJSON_WRITE_ERROR_##_code; \\\n    err->msg = _msg; \\\n    if (hdr) alc.free(alc.ctx, hdr); \\\n    return NULL; \\\n} while (false)\n    \n#define incr_len(_len) do { \\\n    ext_len = (usize)(_len); \\\n    if (unlikely((u8 *)(cur + ext_len) >= (u8 *)ctx)) { \\\n        alc_inc = yyjson_max(alc_len / 2, ext_len); \\\n        alc_inc = size_align_up(alc_inc, sizeof(yyjson_mut_write_ctx)); \\\n        if ((sizeof(usize) < 8) && size_add_is_overflow(alc_len, alc_inc)) \\\n            goto fail_alloc; \\\n        alc_len += alc_inc; \\\n        tmp = (u8 *)alc.realloc(alc.ctx, hdr, alc_len - alc_inc, alc_len); \\\n        if (unlikely(!tmp)) goto fail_alloc; \\\n        ctx_len = (usize)(end - (u8 *)ctx); \\\n        ctx_tmp = (yyjson_mut_write_ctx *)(void *)(tmp + (alc_len - ctx_len)); \\\n        memmove((void *)ctx_tmp, (void *)(tmp + ((u8 *)ctx - hdr)), ctx_len); \\\n        ctx = ctx_tmp; \\\n        cur = tmp + (cur - hdr); \\\n        end = tmp + alc_len; \\\n        hdr = tmp; \\\n    } \\\n} while (false)\n    \n#define check_str_len(_len) do { \\\n    if ((sizeof(usize) < 8) && (_len >= (USIZE_MAX - 16) / 6)) \\\n        goto fail_alloc; \\\n} while (false)\n    \n    yyjson_mut_val *val, *ctn;\n    yyjson_type val_type;\n    usize ctn_len, ctn_len_tmp;\n    bool ctn_obj, ctn_obj_tmp, is_key;\n    u8 *hdr, *cur, *end, *tmp;\n    yyjson_mut_write_ctx *ctx, *ctx_tmp;\n    usize alc_len, alc_inc, ctx_len, ext_len, str_len;\n    const u8 *str_ptr;\n    const char_enc_type *enc_table = get_enc_table_with_flag(flg);\n    bool cpy = (enc_table == enc_table_cpy);\n    bool esc = has_write_flag(ESCAPE_UNICODE) != 0;\n    bool inv = has_write_flag(ALLOW_INVALID_UNICODE) != 0;\n    bool newline = has_write_flag(NEWLINE_AT_END) != 0;\n    \n    alc_len = estimated_val_num * YYJSON_WRITER_ESTIMATED_MINIFY_RATIO + 64;\n    alc_len = size_align_up(alc_len, sizeof(yyjson_mut_write_ctx));\n    hdr = (u8 *)alc.malloc(alc.ctx, alc_len);\n    if (!hdr) goto fail_alloc;\n    cur = hdr;\n    end = hdr + alc_len;\n    ctx = (yyjson_mut_write_ctx *)(void *)end;\n    \ndoc_begin:\n    val = constcast(yyjson_mut_val *)root;\n    val_type = unsafe_yyjson_get_type(val);\n    ctn_obj = (val_type == YYJSON_TYPE_OBJ);\n    ctn_len = unsafe_yyjson_get_len(val) << (u8)ctn_obj;\n    *cur++ = (u8)('[' | ((u8)ctn_obj << 5));\n    ctn = val;\n    val = (yyjson_mut_val *)val->uni.ptr; /* tail */\n    val = ctn_obj ? val->next->next : val->next;\n    \nval_begin:\n    val_type = unsafe_yyjson_get_type(val);\n    if (val_type == YYJSON_TYPE_STR) {\n        is_key = ((u8)ctn_obj & (u8)~ctn_len);\n        str_len = unsafe_yyjson_get_len(val);\n        str_ptr = (const u8 *)unsafe_yyjson_get_str(val);\n        check_str_len(str_len);\n        incr_len(str_len * 6 + 16);\n        if (likely(cpy) && unsafe_yyjson_get_subtype(val)) {\n            cur = write_string_noesc(cur, str_ptr, str_len);\n        } else {\n            cur = write_string(cur, esc, inv, str_ptr, str_len, enc_table);\n            if (unlikely(!cur)) goto fail_str;\n        }\n        *cur++ = is_key ? ':' : ',';\n        goto val_end;\n    }\n    if (val_type == YYJSON_TYPE_NUM) {\n        incr_len(32);\n        cur = write_number(cur, (yyjson_val *)val, flg);\n        if (unlikely(!cur)) goto fail_num;\n        *cur++ = ',';\n        goto val_end;\n    }\n    if ((val_type & (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) ==\n                    (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) {\n        ctn_len_tmp = unsafe_yyjson_get_len(val);\n        ctn_obj_tmp = (val_type == YYJSON_TYPE_OBJ);\n        incr_len(16);\n        if (unlikely(ctn_len_tmp == 0)) {\n            /* write empty container */\n            *cur++ = (u8)('[' | ((u8)ctn_obj_tmp << 5));\n            *cur++ = (u8)(']' | ((u8)ctn_obj_tmp << 5));\n            *cur++ = ',';\n            goto val_end;\n        } else {\n            /* push context, setup new container */\n            yyjson_mut_write_ctx_set(--ctx, ctn, ctn_len, ctn_obj);\n            ctn_len = ctn_len_tmp << (u8)ctn_obj_tmp;\n            ctn_obj = ctn_obj_tmp;\n            *cur++ = (u8)('[' | ((u8)ctn_obj << 5));\n            ctn = val;\n            val = (yyjson_mut_val *)ctn->uni.ptr; /* tail */\n            val = ctn_obj ? val->next->next : val->next;\n            goto val_begin;\n        }\n    }\n    if (val_type == YYJSON_TYPE_BOOL) {\n        incr_len(16);\n        cur = write_bool(cur, unsafe_yyjson_get_bool(val));\n        cur++;\n        goto val_end;\n    }\n    if (val_type == YYJSON_TYPE_NULL) {\n        incr_len(16);\n        cur = write_null(cur);\n        cur++;\n        goto val_end;\n    }\n    if (val_type == YYJSON_TYPE_RAW) {\n        str_len = unsafe_yyjson_get_len(val);\n        str_ptr = (const u8 *)unsafe_yyjson_get_str(val);\n        check_str_len(str_len);\n        incr_len(str_len + 2);\n        cur = write_raw(cur, str_ptr, str_len);\n        *cur++ = ',';\n        goto val_end;\n    }\n    goto fail_type;\n    \nval_end:\n    ctn_len--;\n    if (unlikely(ctn_len == 0)) goto ctn_end;\n    val = val->next;\n    goto val_begin;\n    \nctn_end:\n    cur--;\n    *cur++ = (u8)(']' | ((u8)ctn_obj << 5));\n    *cur++ = ',';\n    if (unlikely((u8 *)ctx >= end)) goto doc_end;\n    val = ctn->next;\n    yyjson_mut_write_ctx_get(ctx++, &ctn, &ctn_len, &ctn_obj);\n    ctn_len--;\n    if (likely(ctn_len > 0)) {\n        goto val_begin;\n    } else {\n        goto ctn_end;\n    }\n    \ndoc_end:\n    if (newline) {\n        incr_len(2);\n        *(cur - 1) = '\\n';\n        cur++;\n    }\n    *--cur = '\\0';\n    *dat_len = (usize)(cur - hdr);\n    err->code = YYJSON_WRITE_SUCCESS;\n    err->msg = \"success\";\n    return hdr;\n    \nfail_alloc:\n    return_err(MEMORY_ALLOCATION, \"memory allocation failed\");\nfail_type:\n    return_err(INVALID_VALUE_TYPE, \"invalid JSON value type\");\nfail_num:\n    return_err(NAN_OR_INF, \"nan or inf number is not allowed\");\nfail_str:\n    return_err(INVALID_STRING, \"invalid utf-8 encoding in string\");\n    \n#undef return_err\n#undef incr_len\n#undef check_str_len\n}\n\n/** Write JSON document pretty.\n    The root of this document should be a non-empty container. */\nstatic_inline u8 *yyjson_mut_write_pretty(const yyjson_mut_val *root,\n                                          usize estimated_val_num,\n                                          yyjson_write_flag flg,\n                                          yyjson_alc alc,\n                                          usize *dat_len,\n                                          yyjson_write_err *err) {\n    \n#define return_err(_code, _msg) do { \\\n    *dat_len = 0; \\\n    err->code = YYJSON_WRITE_ERROR_##_code; \\\n    err->msg = _msg; \\\n    if (hdr) alc.free(alc.ctx, hdr); \\\n    return NULL; \\\n} while (false)\n    \n#define incr_len(_len) do { \\\n    ext_len = (usize)(_len); \\\n    if (unlikely((u8 *)(cur + ext_len) >= (u8 *)ctx)) { \\\n        alc_inc = yyjson_max(alc_len / 2, ext_len); \\\n        alc_inc = size_align_up(alc_inc, sizeof(yyjson_mut_write_ctx)); \\\n        if ((sizeof(usize) < 8) && size_add_is_overflow(alc_len, alc_inc)) \\\n            goto fail_alloc; \\\n        alc_len += alc_inc; \\\n        tmp = (u8 *)alc.realloc(alc.ctx, hdr, alc_len - alc_inc, alc_len); \\\n        if (unlikely(!tmp)) goto fail_alloc; \\\n        ctx_len = (usize)(end - (u8 *)ctx); \\\n        ctx_tmp = (yyjson_mut_write_ctx *)(void *)(tmp + (alc_len - ctx_len)); \\\n        memmove((void *)ctx_tmp, (void *)(tmp + ((u8 *)ctx - hdr)), ctx_len); \\\n        ctx = ctx_tmp; \\\n        cur = tmp + (cur - hdr); \\\n        end = tmp + alc_len; \\\n        hdr = tmp; \\\n    } \\\n} while (false)\n    \n#define check_str_len(_len) do { \\\n    if ((sizeof(usize) < 8) && (_len >= (USIZE_MAX - 16) / 6)) \\\n        goto fail_alloc; \\\n} while (false)\n    \n    yyjson_mut_val *val, *ctn;\n    yyjson_type val_type;\n    usize ctn_len, ctn_len_tmp;\n    bool ctn_obj, ctn_obj_tmp, is_key, no_indent;\n    u8 *hdr, *cur, *end, *tmp;\n    yyjson_mut_write_ctx *ctx, *ctx_tmp;\n    usize alc_len, alc_inc, ctx_len, ext_len, str_len, level;\n    const u8 *str_ptr;\n    const char_enc_type *enc_table = get_enc_table_with_flag(flg);\n    bool cpy = (enc_table == enc_table_cpy);\n    bool esc = has_write_flag(ESCAPE_UNICODE) != 0;\n    bool inv = has_write_flag(ALLOW_INVALID_UNICODE) != 0;\n    usize spaces = has_write_flag(PRETTY_TWO_SPACES) ? 2 : 4;\n    bool newline = has_write_flag(NEWLINE_AT_END) != 0;\n    \n    alc_len = estimated_val_num * YYJSON_WRITER_ESTIMATED_PRETTY_RATIO + 64;\n    alc_len = size_align_up(alc_len, sizeof(yyjson_mut_write_ctx));\n    hdr = (u8 *)alc.malloc(alc.ctx, alc_len);\n    if (!hdr) goto fail_alloc;\n    cur = hdr;\n    end = hdr + alc_len;\n    ctx = (yyjson_mut_write_ctx *)(void *)end;\n    \ndoc_begin:\n    val = constcast(yyjson_mut_val *)root;\n    val_type = unsafe_yyjson_get_type(val);\n    ctn_obj = (val_type == YYJSON_TYPE_OBJ);\n    ctn_len = unsafe_yyjson_get_len(val) << (u8)ctn_obj;\n    *cur++ = (u8)('[' | ((u8)ctn_obj << 5));\n    *cur++ = '\\n';\n    ctn = val;\n    val = (yyjson_mut_val *)val->uni.ptr; /* tail */\n    val = ctn_obj ? val->next->next : val->next;\n    level = 1;\n    \nval_begin:\n    val_type = unsafe_yyjson_get_type(val);\n    if (val_type == YYJSON_TYPE_STR) {\n        is_key = (bool)((u8)ctn_obj & (u8)~ctn_len);\n        no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);\n        str_len = unsafe_yyjson_get_len(val);\n        str_ptr = (const u8 *)unsafe_yyjson_get_str(val);\n        check_str_len(str_len);\n        incr_len(str_len * 6 + 16 + (no_indent ? 0 : level * 4));\n        cur = write_indent(cur, no_indent ? 0 : level, spaces);\n        if (likely(cpy) && unsafe_yyjson_get_subtype(val)) {\n            cur = write_string_noesc(cur, str_ptr, str_len);\n        } else {\n            cur = write_string(cur, esc, inv, str_ptr, str_len, enc_table);\n            if (unlikely(!cur)) goto fail_str;\n        }\n        *cur++ = is_key ? ':' : ',';\n        *cur++ = is_key ? ' ' : '\\n';\n        goto val_end;\n    }\n    if (val_type == YYJSON_TYPE_NUM) {\n        no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);\n        incr_len(32 + (no_indent ? 0 : level * 4));\n        cur = write_indent(cur, no_indent ? 0 : level, spaces);\n        cur = write_number(cur, (yyjson_val *)val, flg);\n        if (unlikely(!cur)) goto fail_num;\n        *cur++ = ',';\n        *cur++ = '\\n';\n        goto val_end;\n    }\n    if ((val_type & (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) ==\n                    (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) {\n        no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);\n        ctn_len_tmp = unsafe_yyjson_get_len(val);\n        ctn_obj_tmp = (val_type == YYJSON_TYPE_OBJ);\n        if (unlikely(ctn_len_tmp == 0)) {\n            /* write empty container */\n            incr_len(16 + (no_indent ? 0 : level * 4));\n            cur = write_indent(cur, no_indent ? 0 : level, spaces);\n            *cur++ = (u8)('[' | ((u8)ctn_obj_tmp << 5));\n            *cur++ = (u8)(']' | ((u8)ctn_obj_tmp << 5));\n            *cur++ = ',';\n            *cur++ = '\\n';\n            goto val_end;\n        } else {\n            /* push context, setup new container */\n            incr_len(32 + (no_indent ? 0 : level * 4));\n            yyjson_mut_write_ctx_set(--ctx, ctn, ctn_len, ctn_obj);\n            ctn_len = ctn_len_tmp << (u8)ctn_obj_tmp;\n            ctn_obj = ctn_obj_tmp;\n            cur = write_indent(cur, no_indent ? 0 : level, spaces);\n            level++;\n            *cur++ = (u8)('[' | ((u8)ctn_obj << 5));\n            *cur++ = '\\n';\n            ctn = val;\n            val = (yyjson_mut_val *)ctn->uni.ptr; /* tail */\n            val = ctn_obj ? val->next->next : val->next;\n            goto val_begin;\n        }\n    }\n    if (val_type == YYJSON_TYPE_BOOL) {\n        no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);\n        incr_len(16 + (no_indent ? 0 : level * 4));\n        cur = write_indent(cur, no_indent ? 0 : level, spaces);\n        cur = write_bool(cur, unsafe_yyjson_get_bool(val));\n        cur += 2;\n        goto val_end;\n    }\n    if (val_type == YYJSON_TYPE_NULL) {\n        no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);\n        incr_len(16 + (no_indent ? 0 : level * 4));\n        cur = write_indent(cur, no_indent ? 0 : level, spaces);\n        cur = write_null(cur);\n        cur += 2;\n        goto val_end;\n    }\n    if (val_type == YYJSON_TYPE_RAW) {\n        str_len = unsafe_yyjson_get_len(val);\n        str_ptr = (const u8 *)unsafe_yyjson_get_str(val);\n        check_str_len(str_len);\n        incr_len(str_len + 3);\n        cur = write_raw(cur, str_ptr, str_len);\n        *cur++ = ',';\n        *cur++ = '\\n';\n        goto val_end;\n    }\n    goto fail_type;\n    \nval_end:\n    ctn_len--;\n    if (unlikely(ctn_len == 0)) goto ctn_end;\n    val = val->next;\n    goto val_begin;\n    \nctn_end:\n    cur -= 2;\n    *cur++ = '\\n';\n    incr_len(level * 4);\n    cur = write_indent(cur, --level, spaces);\n    *cur++ = (u8)(']' | ((u8)ctn_obj << 5));\n    if (unlikely((u8 *)ctx >= end)) goto doc_end;\n    val = ctn->next;\n    yyjson_mut_write_ctx_get(ctx++, &ctn, &ctn_len, &ctn_obj);\n    ctn_len--;\n    *cur++ = ',';\n    *cur++ = '\\n';\n    if (likely(ctn_len > 0)) {\n        goto val_begin;\n    } else {\n        goto ctn_end;\n    }\n    \ndoc_end:\n    if (newline) {\n        incr_len(2);\n        *cur++ = '\\n';\n    }\n    *cur = '\\0';\n    *dat_len = (usize)(cur - hdr);\n    err->code = YYJSON_WRITE_SUCCESS;\n    err->msg = \"success\";\n    return hdr;\n    \nfail_alloc:\n    return_err(MEMORY_ALLOCATION, \"memory allocation failed\");\nfail_type:\n    return_err(INVALID_VALUE_TYPE, \"invalid JSON value type\");\nfail_num:\n    return_err(NAN_OR_INF, \"nan or inf number is not allowed\");\nfail_str:\n    return_err(INVALID_STRING, \"invalid utf-8 encoding in string\");\n    \n#undef return_err\n#undef incr_len\n#undef check_str_len\n}\n\nstatic char *yyjson_mut_write_opts_impl(const yyjson_mut_val *val,\n                                        usize estimated_val_num,\n                                        yyjson_write_flag flg,\n                                        const yyjson_alc *alc_ptr,\n                                        usize *dat_len,\n                                        yyjson_write_err *err) {\n    yyjson_write_err dummy_err;\n    usize dummy_dat_len;\n    yyjson_alc alc = alc_ptr ? *alc_ptr : YYJSON_DEFAULT_ALC;\n    yyjson_mut_val *root = constcast(yyjson_mut_val *)val;\n    \n    err = err ? err : &dummy_err;\n    dat_len = dat_len ? dat_len : &dummy_dat_len;\n    \n    if (unlikely(!root)) {\n        *dat_len = 0;\n        err->msg = \"input JSON is NULL\";\n        err->code = YYJSON_WRITE_ERROR_INVALID_PARAMETER;\n        return NULL;\n    }\n    \n    if (!unsafe_yyjson_is_ctn(root) || unsafe_yyjson_get_len(root) == 0) {\n        return (char *)yyjson_mut_write_single(root, flg, alc, dat_len, err);\n    } else if (flg & (YYJSON_WRITE_PRETTY | YYJSON_WRITE_PRETTY_TWO_SPACES)) {\n        return (char *)yyjson_mut_write_pretty(root, estimated_val_num,\n                                               flg, alc, dat_len, err);\n    } else {\n        return (char *)yyjson_mut_write_minify(root, estimated_val_num,\n                                               flg, alc, dat_len, err);\n    }\n}\n\nchar *yyjson_mut_val_write_opts(const yyjson_mut_val *val,\n                                yyjson_write_flag flg,\n                                const yyjson_alc *alc_ptr,\n                                usize *dat_len,\n                                yyjson_write_err *err) {\n    return yyjson_mut_write_opts_impl(val, 0, flg, alc_ptr, dat_len, err);\n}\n\nchar *yyjson_mut_write_opts(const yyjson_mut_doc *doc,\n                            yyjson_write_flag flg,\n                            const yyjson_alc *alc_ptr,\n                            usize *dat_len,\n                            yyjson_write_err *err) {\n    yyjson_mut_val *root;\n    usize estimated_val_num;\n    if (likely(doc)) {\n        root = doc->root;\n        estimated_val_num = yyjson_mut_doc_estimated_val_num(doc);\n    } else {\n        root = NULL;\n        estimated_val_num = 0;\n    }\n    return yyjson_mut_write_opts_impl(root, estimated_val_num,\n                                      flg, alc_ptr, dat_len, err);\n}\n\nbool yyjson_mut_val_write_file(const char *path,\n                               const yyjson_mut_val *val,\n                               yyjson_write_flag flg,\n                               const yyjson_alc *alc_ptr,\n                               yyjson_write_err *err) {\n    yyjson_write_err dummy_err;\n    u8 *dat;\n    usize dat_len = 0;\n    yyjson_mut_val *root = constcast(yyjson_mut_val *)val;\n    bool suc;\n    \n    alc_ptr = alc_ptr ? alc_ptr : &YYJSON_DEFAULT_ALC;\n    err = err ? err : &dummy_err;\n    if (unlikely(!path || !*path)) {\n        err->msg = \"input path is invalid\";\n        err->code = YYJSON_WRITE_ERROR_INVALID_PARAMETER;\n        return false;\n    }\n    \n    dat = (u8 *)yyjson_mut_val_write_opts(root, flg, alc_ptr, &dat_len, err);\n    if (unlikely(!dat)) return false;\n    suc = write_dat_to_file(path, dat, dat_len, err);\n    alc_ptr->free(alc_ptr->ctx, dat);\n    return suc;\n}\n\nbool yyjson_mut_val_write_fp(FILE *fp,\n                             const yyjson_mut_val *val,\n                             yyjson_write_flag flg,\n                             const yyjson_alc *alc_ptr,\n                             yyjson_write_err *err) {\n    yyjson_write_err dummy_err;\n    u8 *dat;\n    usize dat_len = 0;\n    yyjson_mut_val *root = constcast(yyjson_mut_val *)val;\n    bool suc;\n    \n    alc_ptr = alc_ptr ? alc_ptr : &YYJSON_DEFAULT_ALC;\n    err = err ? err : &dummy_err;\n    if (unlikely(!fp)) {\n        err->msg = \"input fp is invalid\";\n        err->code = YYJSON_WRITE_ERROR_INVALID_PARAMETER;\n        return false;\n    }\n    \n    dat = (u8 *)yyjson_mut_val_write_opts(root, flg, alc_ptr, &dat_len, err);\n    if (unlikely(!dat)) return false;\n    suc = write_dat_to_fp(fp, dat, dat_len, err);\n    alc_ptr->free(alc_ptr->ctx, dat);\n    return suc;\n}\n\nbool yyjson_mut_write_file(const char *path,\n                           const yyjson_mut_doc *doc,\n                           yyjson_write_flag flg,\n                           const yyjson_alc *alc_ptr,\n                           yyjson_write_err *err) {\n    yyjson_mut_val *root = doc ? doc->root : NULL;\n    return yyjson_mut_val_write_file(path, root, flg, alc_ptr, err);\n}\n\nbool yyjson_mut_write_fp(FILE *fp,\n                         const yyjson_mut_doc *doc,\n                         yyjson_write_flag flg,\n                         const yyjson_alc *alc_ptr,\n                         yyjson_write_err *err) {\n    yyjson_mut_val *root = doc ? doc->root : NULL;\n    return yyjson_mut_val_write_fp(fp, root, flg, alc_ptr, err);\n}\n\n#endif /* YYJSON_DISABLE_WRITER */\n"
  },
  {
    "path": "include/yyjson/yyjson.h",
    "content": "/*==============================================================================\n Copyright (c) 2020 YaoYuan <ibireme@gmail.com>\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n *============================================================================*/\n\n/** \n @file yyjson.h\n @date 2019-03-09\n @author YaoYuan\n */\n\n#ifndef YYJSON_H\n#define YYJSON_H\n\n\n\n/*==============================================================================\n * Header Files\n *============================================================================*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stddef.h>\n#include <limits.h>\n#include <string.h>\n#include <float.h>\n\n\n\n/*==============================================================================\n * Compile-time Options\n *============================================================================*/\n\n/*\n Define as 1 to disable JSON reader if JSON parsing is not required.\n \n This will disable these functions at compile-time:\n    - yyjson_read()\n    - yyjson_read_opts()\n    - yyjson_read_file()\n    - yyjson_read_number()\n    - yyjson_mut_read_number()\n \n This will reduce the binary size by about 60%.\n */\n#ifndef YYJSON_DISABLE_READER\n#endif\n\n/*\n Define as 1 to disable JSON writer if JSON serialization is not required.\n \n This will disable these functions at compile-time:\n    - yyjson_write()\n    - yyjson_write_file()\n    - yyjson_write_opts()\n    - yyjson_val_write()\n    - yyjson_val_write_file()\n    - yyjson_val_write_opts()\n    - yyjson_mut_write()\n    - yyjson_mut_write_file()\n    - yyjson_mut_write_opts()\n    - yyjson_mut_val_write()\n    - yyjson_mut_val_write_file()\n    - yyjson_mut_val_write_opts()\n \n This will reduce the binary size by about 30%.\n */\n#ifndef YYJSON_DISABLE_WRITER\n#endif\n\n/*\n Define as 1 to disable JSON Pointer, JSON Patch and JSON Merge Patch supports.\n \n This will disable these functions at compile-time:\n    - yyjson_ptr_xxx()\n    - yyjson_mut_ptr_xxx()\n    - yyjson_doc_ptr_xxx()\n    - yyjson_mut_doc_ptr_xxx()\n    - yyjson_patch()\n    - yyjson_mut_patch()\n    - yyjson_merge_patch()\n    - yyjson_mut_merge_patch()\n */\n#ifndef YYJSON_DISABLE_UTILS\n#endif\n\n/*\n Define as 1 to disable the fast floating-point number conversion in yyjson,\n and use libc's `strtod/snprintf` instead.\n \n This will reduce the binary size by about 30%, but significantly slow down the\n floating-point read/write speed.\n */\n#ifndef YYJSON_DISABLE_FAST_FP_CONV\n#endif\n\n/*\n Define as 1 to disable non-standard JSON support at compile-time:\n    - Reading and writing inf/nan literal, such as `NaN`, `-Infinity`.\n    - Single line and multiple line comments.\n    - Single trailing comma at the end of an object or array.\n    - Invalid unicode in string value.\n \n This will also invalidate these run-time options:\n    - YYJSON_READ_ALLOW_INF_AND_NAN\n    - YYJSON_READ_ALLOW_COMMENTS\n    - YYJSON_READ_ALLOW_TRAILING_COMMAS\n    - YYJSON_READ_ALLOW_INVALID_UNICODE\n    - YYJSON_WRITE_ALLOW_INF_AND_NAN\n    - YYJSON_WRITE_ALLOW_INVALID_UNICODE\n \n This will reduce the binary size by about 10%, and speed up the reading and\n writing speed by about 2% to 6%.\n */\n#ifndef YYJSON_DISABLE_NON_STANDARD\n#endif\n\n/*\n Define as 1 to disable UTF-8 validation at compile time.\n \n If all input strings are guaranteed to be valid UTF-8 encoding (for example,\n some language's String object has already validated the encoding), using this\n flag can avoid redundant UTF-8 validation in yyjson.\n \n This flag can speed up the reading and writing speed of non-ASCII encoded\n strings by about 3% to 7%.\n \n Note: If this flag is used while passing in illegal UTF-8 strings, the\n following errors may occur:\n - Escaped characters may be ignored when parsing JSON strings.\n - Ending quotes may be ignored when parsing JSON strings, causing the string\n   to be concatenated to the next value.\n - When accessing `yyjson_mut_val` for serialization, the string ending may be\n   accessed out of bounds, causing a segmentation fault.\n */\n#ifndef YYJSON_DISABLE_UTF8_VALIDATION\n#endif\n\n/*\n Define as 1 to indicate that the target architecture does not support unaligned\n memory access. Please refer to the comments in the C file for details.\n */\n#ifndef YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS\n#endif\n\n/* Define as 1 to export symbols when building this library as Windows DLL. */\n#ifndef YYJSON_EXPORTS\n#endif\n\n/* Define as 1 to import symbols when using this library as Windows DLL. */\n#ifndef YYJSON_IMPORTS\n#endif\n\n/* Define as 1 to include <stdint.h> for compiler which doesn't support C99. */\n#ifndef YYJSON_HAS_STDINT_H\n#endif\n\n/* Define as 1 to include <stdbool.h> for compiler which doesn't support C99. */\n#ifndef YYJSON_HAS_STDBOOL_H\n#endif\n\n\n\n/*==============================================================================\n * Compiler Macros\n *============================================================================*/\n\n/** compiler version (MSVC) */\n#ifdef _MSC_VER\n#   define YYJSON_MSC_VER _MSC_VER\n#else\n#   define YYJSON_MSC_VER 0\n#endif\n\n/** compiler version (GCC) */\n#ifdef __GNUC__\n#   define YYJSON_GCC_VER __GNUC__\n#   if defined(__GNUC_PATCHLEVEL__)\n#       define yyjson_gcc_available(major, minor, patch) \\\n            ((__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) \\\n            >= (major * 10000 + minor * 100 + patch))\n#   else\n#       define yyjson_gcc_available(major, minor, patch) \\\n            ((__GNUC__ * 10000 + __GNUC_MINOR__ * 100) \\\n            >= (major * 10000 + minor * 100 + patch))\n#   endif\n#else\n#   define YYJSON_GCC_VER 0\n#   define yyjson_gcc_available(major, minor, patch) 0\n#endif\n\n/** real gcc check */\n#if !defined(__clang__) && !defined(__INTEL_COMPILER) && !defined(__ICC) && \\\n    defined(__GNUC__)\n#   define YYJSON_IS_REAL_GCC 1\n#else\n#   define YYJSON_IS_REAL_GCC 0\n#endif\n\n/** C version (STDC) */\n#if defined(__STDC__) && (__STDC__ >= 1) && defined(__STDC_VERSION__)\n#   define YYJSON_STDC_VER __STDC_VERSION__\n#else\n#   define YYJSON_STDC_VER 0\n#endif\n\n/** C++ version */\n#if defined(__cplusplus)\n#   define YYJSON_CPP_VER __cplusplus\n#else\n#   define YYJSON_CPP_VER 0\n#endif\n\n/** compiler builtin check (since gcc 10.0, clang 2.6, icc 2021) */\n#ifndef yyjson_has_builtin\n#   ifdef __has_builtin\n#       define yyjson_has_builtin(x) __has_builtin(x)\n#   else\n#       define yyjson_has_builtin(x) 0\n#   endif\n#endif\n\n/** compiler attribute check (since gcc 5.0, clang 2.9, icc 17) */\n#ifndef yyjson_has_attribute\n#   ifdef __has_attribute\n#       define yyjson_has_attribute(x) __has_attribute(x)\n#   else\n#       define yyjson_has_attribute(x) 0\n#   endif\n#endif\n\n/** compiler feature check (since clang 2.6, icc 17) */\n#ifndef yyjson_has_feature\n#   ifdef __has_feature\n#       define yyjson_has_feature(x) __has_feature(x)\n#   else\n#       define yyjson_has_feature(x) 0\n#   endif\n#endif\n\n/** include check (since gcc 5.0, clang 2.7, icc 16, msvc 2017 15.3) */\n#ifndef yyjson_has_include\n#   ifdef __has_include\n#       define yyjson_has_include(x) __has_include(x)\n#   else\n#       define yyjson_has_include(x) 0\n#   endif\n#endif\n\n/** inline for compiler */\n#ifndef yyjson_inline\n#   if YYJSON_MSC_VER >= 1200\n#       define yyjson_inline __forceinline\n#   elif defined(_MSC_VER)\n#       define yyjson_inline __inline\n#   elif yyjson_has_attribute(always_inline) || YYJSON_GCC_VER >= 4\n#       define yyjson_inline __inline__ __attribute__((always_inline))\n#   elif defined(__clang__) || defined(__GNUC__)\n#       define yyjson_inline __inline__\n#   elif defined(__cplusplus) || YYJSON_STDC_VER >= 199901L\n#       define yyjson_inline inline\n#   else\n#       define yyjson_inline\n#   endif\n#endif\n\n/** noinline for compiler */\n#ifndef yyjson_noinline\n#   if YYJSON_MSC_VER >= 1400\n#       define yyjson_noinline __declspec(noinline)\n#   elif yyjson_has_attribute(noinline) || YYJSON_GCC_VER >= 4\n#       define yyjson_noinline __attribute__((noinline))\n#   else\n#       define yyjson_noinline\n#   endif\n#endif\n\n/** align for compiler */\n#ifndef yyjson_align\n#   if YYJSON_MSC_VER >= 1300\n#       define yyjson_align(x) __declspec(align(x))\n#   elif yyjson_has_attribute(aligned) || defined(__GNUC__)\n#       define yyjson_align(x) __attribute__((aligned(x)))\n#   elif YYJSON_CPP_VER >= 201103L\n#       define yyjson_align(x) alignas(x)\n#   else\n#       define yyjson_align(x)\n#   endif\n#endif\n\n/** likely for compiler */\n#ifndef yyjson_likely\n#   if yyjson_has_builtin(__builtin_expect) || \\\n    (YYJSON_GCC_VER >= 4 && YYJSON_GCC_VER != 5)\n#       define yyjson_likely(expr) __builtin_expect(!!(expr), 1)\n#   else\n#       define yyjson_likely(expr) (expr)\n#   endif\n#endif\n\n/** unlikely for compiler */\n#ifndef yyjson_unlikely\n#   if yyjson_has_builtin(__builtin_expect) || \\\n    (YYJSON_GCC_VER >= 4 && YYJSON_GCC_VER != 5)\n#       define yyjson_unlikely(expr) __builtin_expect(!!(expr), 0)\n#   else\n#       define yyjson_unlikely(expr) (expr)\n#   endif\n#endif\n\n/** compile-time constant check for compiler */\n#ifndef yyjson_constant_p\n#   if yyjson_has_builtin(__builtin_constant_p) || (YYJSON_GCC_VER >= 3)\n#       define YYJSON_HAS_CONSTANT_P 1\n#       define yyjson_constant_p(value) __builtin_constant_p(value)\n#   else\n#       define YYJSON_HAS_CONSTANT_P 0\n#       define yyjson_constant_p(value) 0\n#   endif\n#endif\n\n/** deprecate warning */\n#ifndef yyjson_deprecated\n#   if YYJSON_MSC_VER >= 1400\n#       define yyjson_deprecated(msg) __declspec(deprecated(msg))\n#   elif yyjson_has_feature(attribute_deprecated_with_message) || \\\n        (YYJSON_GCC_VER > 4 || (YYJSON_GCC_VER == 4 && __GNUC_MINOR__ >= 5))\n#       define yyjson_deprecated(msg) __attribute__((deprecated(msg)))\n#   elif YYJSON_GCC_VER >= 3\n#       define yyjson_deprecated(msg) __attribute__((deprecated))\n#   else\n#       define yyjson_deprecated(msg)\n#   endif\n#endif\n\n/** function export */\n#ifndef yyjson_api\n#   if defined(_WIN32)\n#       if defined(YYJSON_EXPORTS) && YYJSON_EXPORTS\n#           define yyjson_api __declspec(dllexport)\n#       elif defined(YYJSON_IMPORTS) && YYJSON_IMPORTS\n#           define yyjson_api __declspec(dllimport)\n#       else\n#           define yyjson_api\n#       endif\n#   elif yyjson_has_attribute(visibility) || YYJSON_GCC_VER >= 4\n#       define yyjson_api __attribute__((visibility(\"default\")))\n#   else\n#       define yyjson_api\n#   endif\n#endif\n\n/** inline function export */\n#ifndef yyjson_api_inline\n#   define yyjson_api_inline static yyjson_inline\n#endif\n\n/** stdint (C89 compatible) */\n#if (defined(YYJSON_HAS_STDINT_H) && YYJSON_HAS_STDINT_H) || \\\n    YYJSON_MSC_VER >= 1600 || YYJSON_STDC_VER >= 199901L || \\\n    defined(_STDINT_H) || defined(_STDINT_H_) || \\\n    defined(__CLANG_STDINT_H) || defined(_STDINT_H_INCLUDED) || \\\n    yyjson_has_include(<stdint.h>)\n#   include <stdint.h>\n#elif defined(_MSC_VER)\n#   if _MSC_VER < 1300\n        typedef signed char         int8_t;\n        typedef signed short        int16_t;\n        typedef signed int          int32_t;\n        typedef unsigned char       uint8_t;\n        typedef unsigned short      uint16_t;\n        typedef unsigned int        uint32_t;\n        typedef signed __int64      int64_t;\n        typedef unsigned __int64    uint64_t;\n#   else\n        typedef signed __int8       int8_t;\n        typedef signed __int16      int16_t;\n        typedef signed __int32      int32_t;\n        typedef unsigned __int8     uint8_t;\n        typedef unsigned __int16    uint16_t;\n        typedef unsigned __int32    uint32_t;\n        typedef signed __int64      int64_t;\n        typedef unsigned __int64    uint64_t;\n#   endif\n#else\n#   if UCHAR_MAX == 0xFFU\n        typedef signed char     int8_t;\n        typedef unsigned char   uint8_t;\n#   else\n#       error cannot find 8-bit integer type\n#   endif\n#   if USHRT_MAX == 0xFFFFU\n        typedef unsigned short  uint16_t;\n        typedef signed short    int16_t;\n#   elif UINT_MAX == 0xFFFFU\n        typedef unsigned int    uint16_t;\n        typedef signed int      int16_t;\n#   else\n#       error cannot find 16-bit integer type\n#   endif\n#   if UINT_MAX == 0xFFFFFFFFUL\n        typedef unsigned int    uint32_t;\n        typedef signed int      int32_t;\n#   elif ULONG_MAX == 0xFFFFFFFFUL\n        typedef unsigned long   uint32_t;\n        typedef signed long     int32_t;\n#   elif USHRT_MAX == 0xFFFFFFFFUL\n        typedef unsigned short  uint32_t;\n        typedef signed short    int32_t;\n#   else\n#       error cannot find 32-bit integer type\n#   endif\n#   if defined(__INT64_TYPE__) && defined(__UINT64_TYPE__)\n        typedef __INT64_TYPE__  int64_t;\n        typedef __UINT64_TYPE__ uint64_t;\n#   elif defined(__GNUC__) || defined(__clang__)\n#       if !defined(_SYS_TYPES_H) && !defined(__int8_t_defined)\n        __extension__ typedef long long             int64_t;\n#       endif\n        __extension__ typedef unsigned long long    uint64_t;\n#   elif defined(_LONG_LONG) || defined(__MWERKS__) || defined(_CRAYC) || \\\n        defined(__SUNPRO_C) || defined(__SUNPRO_CC)\n        typedef long long           int64_t;\n        typedef unsigned long long  uint64_t;\n#   elif (defined(__BORLANDC__) && __BORLANDC__ > 0x460) || \\\n        defined(__WATCOM_INT64__) || defined (__alpha) || defined (__DECC)\n        typedef __int64             int64_t;\n        typedef unsigned __int64    uint64_t;\n#   else\n#       error cannot find 64-bit integer type\n#   endif\n#endif\n\n/** stdbool (C89 compatible) */\n#if (defined(YYJSON_HAS_STDBOOL_H) && YYJSON_HAS_STDBOOL_H) || \\\n    (yyjson_has_include(<stdbool.h>) && !defined(__STRICT_ANSI__)) || \\\n    YYJSON_MSC_VER >= 1800 || YYJSON_STDC_VER >= 199901L\n#   include <stdbool.h>\n#elif !defined(__bool_true_false_are_defined)\n#   define __bool_true_false_are_defined 1\n#   if defined(__cplusplus)\n#       if defined(__GNUC__) && !defined(__STRICT_ANSI__)\n#           define _Bool bool\n#           if __cplusplus < 201103L\n#               define bool bool\n#               define false false\n#               define true true\n#           endif\n#       endif\n#   else\n#       define bool unsigned char\n#       define true 1\n#       define false 0\n#   endif\n#endif\n\n/** char bit check */\n#if defined(CHAR_BIT)\n#   if CHAR_BIT != 8\n#       error non 8-bit char is not supported\n#   endif\n#endif\n\n/**\n Microsoft Visual C++ 6.0 doesn't support converting number from u64 to f64:\n error C2520: conversion from unsigned __int64 to double not implemented.\n */\n#ifndef YYJSON_U64_TO_F64_NO_IMPL\n#   if (0 < YYJSON_MSC_VER) && (YYJSON_MSC_VER <= 1200)\n#       define YYJSON_U64_TO_F64_NO_IMPL 1\n#   else\n#       define YYJSON_U64_TO_F64_NO_IMPL 0\n#   endif\n#endif\n\n\n\n/*==============================================================================\n * Compile Hint Begin\n *============================================================================*/\n\n/* extern \"C\" begin */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/* warning suppress begin */\n#if defined(__clang__)\n#   pragma clang diagnostic push\n#   pragma clang diagnostic ignored \"-Wunused-function\"\n#   pragma clang diagnostic ignored \"-Wunused-parameter\"\n#elif defined(__GNUC__)\n#   if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)\n#   pragma GCC diagnostic push\n#   endif\n#   pragma GCC diagnostic ignored \"-Wunused-function\"\n#   pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#elif defined(_MSC_VER)\n#   pragma warning(push)\n#   pragma warning(disable:4800) /* 'int': forcing value to 'true' or 'false' */\n#endif\n\n\n\n/*==============================================================================\n * Version\n *============================================================================*/\n\n/** The major version of yyjson. */\n#define YYJSON_VERSION_MAJOR  0\n\n/** The minor version of yyjson. */\n#define YYJSON_VERSION_MINOR  9\n\n/** The patch version of yyjson. */\n#define YYJSON_VERSION_PATCH  0\n\n/** The version of yyjson in hex: `(major << 16) | (minor << 8) | (patch)`. */\n#define YYJSON_VERSION_HEX    0x000900\n\n/** The version string of yyjson. */\n#define YYJSON_VERSION_STRING \"0.9.0\"\n\n/** The version of yyjson in hex, same as `YYJSON_VERSION_HEX`. */\nyyjson_api uint32_t yyjson_version(void);\n\n\n\n/*==============================================================================\n * JSON Types\n *============================================================================*/\n\n/** Type of a JSON value (3 bit). */\ntypedef uint8_t yyjson_type;\n/** No type, invalid. */\n#define YYJSON_TYPE_NONE        ((uint8_t)0)        /* _____000 */\n/** Raw string type, no subtype. */\n#define YYJSON_TYPE_RAW         ((uint8_t)1)        /* _____001 */\n/** Null type: `null` literal, no subtype. */\n#define YYJSON_TYPE_NULL        ((uint8_t)2)        /* _____010 */\n/** Boolean type, subtype: TRUE, FALSE. */\n#define YYJSON_TYPE_BOOL        ((uint8_t)3)        /* _____011 */\n/** Number type, subtype: UINT, SINT, REAL. */\n#define YYJSON_TYPE_NUM         ((uint8_t)4)        /* _____100 */\n/** String type, subtype: NONE, NOESC. */\n#define YYJSON_TYPE_STR         ((uint8_t)5)        /* _____101 */\n/** Array type, no subtype. */\n#define YYJSON_TYPE_ARR         ((uint8_t)6)        /* _____110 */\n/** Object type, no subtype. */\n#define YYJSON_TYPE_OBJ         ((uint8_t)7)        /* _____111 */\n\n/** Subtype of a JSON value (2 bit). */\ntypedef uint8_t yyjson_subtype;\n/** No subtype. */\n#define YYJSON_SUBTYPE_NONE     ((uint8_t)(0 << 3)) /* ___00___ */\n/** False subtype: `false` literal. */\n#define YYJSON_SUBTYPE_FALSE    ((uint8_t)(0 << 3)) /* ___00___ */\n/** True subtype: `true` literal. */\n#define YYJSON_SUBTYPE_TRUE     ((uint8_t)(1 << 3)) /* ___01___ */\n/** Unsigned integer subtype: `uint64_t`. */\n#define YYJSON_SUBTYPE_UINT     ((uint8_t)(0 << 3)) /* ___00___ */\n/** Signed integer subtype: `int64_t`. */\n#define YYJSON_SUBTYPE_SINT     ((uint8_t)(1 << 3)) /* ___01___ */\n/** Real number subtype: `double`. */\n#define YYJSON_SUBTYPE_REAL     ((uint8_t)(2 << 3)) /* ___10___ */\n/** String that do not need to be escaped for writing (internal use). */\n#define YYJSON_SUBTYPE_NOESC    ((uint8_t)(1 << 3)) /* ___01___ */\n\n/** The mask used to extract the type of a JSON value. */\n#define YYJSON_TYPE_MASK        ((uint8_t)0x07)     /* _____111 */\n/** The number of bits used by the type. */\n#define YYJSON_TYPE_BIT         ((uint8_t)3)\n/** The mask used to extract the subtype of a JSON value. */\n#define YYJSON_SUBTYPE_MASK     ((uint8_t)0x18)     /* ___11___ */\n/** The number of bits used by the subtype. */\n#define YYJSON_SUBTYPE_BIT      ((uint8_t)2)\n/** The mask used to extract the reserved bits of a JSON value. */\n#define YYJSON_RESERVED_MASK    ((uint8_t)0xE0)     /* 111_____ */\n/** The number of reserved bits. */\n#define YYJSON_RESERVED_BIT     ((uint8_t)3)\n/** The mask used to extract the tag of a JSON value. */\n#define YYJSON_TAG_MASK         ((uint8_t)0xFF)     /* 11111111 */\n/** The number of bits used by the tag. */\n#define YYJSON_TAG_BIT          ((uint8_t)8)\n\n/** Padding size for JSON reader. */\n#define YYJSON_PADDING_SIZE     4\n\n\n\n/*==============================================================================\n * Allocator\n *============================================================================*/\n\n/**\n A memory allocator.\n \n Typically you don't need to use it, unless you want to customize your own\n memory allocator.\n */\ntypedef struct yyjson_alc {\n    /** Same as libc's malloc(size), should not be NULL. */\n    void *(*malloc)(void *ctx, size_t size);\n    /** Same as libc's realloc(ptr, size), should not be NULL. */\n    void *(*realloc)(void *ctx, void *ptr, size_t old_size, size_t size);\n    /** Same as libc's free(ptr), should not be NULL. */\n    void (*free)(void *ctx, void *ptr);\n    /** A context for malloc/realloc/free, can be NULL. */\n    void *ctx;\n} yyjson_alc;\n\n/**\n A pool allocator uses fixed length pre-allocated memory.\n \n This allocator may be used to avoid malloc/realloc calls. The pre-allocated \n memory should be held by the caller. The maximum amount of memory required to\n read a JSON can be calculated using the `yyjson_read_max_memory_usage()`\n function, but the amount of memory required to write a JSON cannot be directly \n calculated.\n \n This is not a general-purpose allocator. It is designed to handle a single JSON\n data at a time. If it is used for overly complex memory tasks, such as parsing\n multiple JSON documents using the same allocator but releasing only a few of\n them, it may cause memory fragmentation, resulting in performance degradation\n and memory waste.\n \n @param alc The allocator to be initialized.\n    If this parameter is NULL, the function will fail and return false.\n    If `buf` or `size` is invalid, this will be set to an empty allocator.\n @param buf The buffer memory for this allocator.\n    If this parameter is NULL, the function will fail and return false.\n @param size The size of `buf`, in bytes.\n    If this parameter is less than 8 words (32/64 bytes on 32/64-bit OS), the\n    function will fail and return false.\n @return true if the `alc` has been successfully initialized.\n \n @par Example\n @code\n    // parse JSON with stack memory\n    char buf[1024];\n    yyjson_alc alc;\n    yyjson_alc_pool_init(&alc, buf, 1024);\n    \n    const char *json = \"{\\\"name\\\":\\\"Helvetica\\\",\\\"size\\\":16}\"\n    yyjson_doc *doc = yyjson_read_opts(json, strlen(json), 0, &alc, NULL);\n    // the memory of `doc` is on the stack\n @endcode\n \n @warning This Allocator is not thread-safe.\n */\nyyjson_api bool yyjson_alc_pool_init(yyjson_alc *alc, void *buf, size_t size);\n\n/**\n A dynamic allocator.\n \n This allocator has a similar usage to the pool allocator above. However, when\n there is not enough memory, this allocator will dynamically request more memory\n using libc's `malloc` function, and frees it all at once when it is destroyed.\n \n @return A new dynamic allocator, or NULL if memory allocation failed.\n @note The returned value should be freed with `yyjson_alc_dyn_free()`.\n \n @warning This Allocator is not thread-safe.\n */\nyyjson_api yyjson_alc *yyjson_alc_dyn_new(void);\n\n/**\n Free a dynamic allocator which is created by `yyjson_alc_dyn_new()`.\n @param alc The dynamic allocator to be destroyed.\n */\nyyjson_api void yyjson_alc_dyn_free(yyjson_alc *alc);\n\n\n\n/*==============================================================================\n * JSON Structure\n *============================================================================*/\n\n/**\n An immutable document for reading JSON.\n This document holds memory for all its JSON values and strings. When it is no\n longer used, the user should call `yyjson_doc_free()` to free its memory.\n */\ntypedef struct yyjson_doc yyjson_doc;\n\n/**\n An immutable value for reading JSON.\n A JSON Value has the same lifetime as its document. The memory is held by its\n document and and cannot be freed alone.\n */\ntypedef struct yyjson_val yyjson_val;\n\n/**\n A mutable document for building JSON.\n This document holds memory for all its JSON values and strings. When it is no\n longer used, the user should call `yyjson_mut_doc_free()` to free its memory.\n */\ntypedef struct yyjson_mut_doc yyjson_mut_doc;\n\n/**\n A mutable value for building JSON.\n A JSON Value has the same lifetime as its document. The memory is held by its\n document and and cannot be freed alone.\n */\ntypedef struct yyjson_mut_val yyjson_mut_val;\n\n\n\n/*==============================================================================\n * JSON Reader API\n *============================================================================*/\n\n/** Run-time options for JSON reader. */\ntypedef uint32_t yyjson_read_flag;\n\n/** Default option (RFC 8259 compliant):\n    - Read positive integer as uint64_t.\n    - Read negative integer as int64_t.\n    - Read floating-point number as double with round-to-nearest mode.\n    - Read integer which cannot fit in uint64_t or int64_t as double.\n    - Report error if double number is infinity.\n    - Report error if string contains invalid UTF-8 character or BOM.\n    - Report error on trailing commas, comments, inf and nan literals. */\nstatic const yyjson_read_flag YYJSON_READ_NOFLAG                = 0;\n\n/** Read the input data in-situ.\n    This option allows the reader to modify and use input data to store string\n    values, which can increase reading speed slightly.\n    The caller should hold the input data before free the document.\n    The input data must be padded by at least `YYJSON_PADDING_SIZE` bytes.\n    For example: `[1,2]` should be `[1,2]\\0\\0\\0\\0`, input length should be 5. */\nstatic const yyjson_read_flag YYJSON_READ_INSITU                = 1 << 0;\n\n/** Stop when done instead of issuing an error if there's additional content\n    after a JSON document. This option may be used to parse small pieces of JSON\n    in larger data, such as `NDJSON`. */\nstatic const yyjson_read_flag YYJSON_READ_STOP_WHEN_DONE        = 1 << 1;\n\n/** Allow single trailing comma at the end of an object or array,\n    such as `[1,2,3,]`, `{\"a\":1,\"b\":2,}` (non-standard). */\nstatic const yyjson_read_flag YYJSON_READ_ALLOW_TRAILING_COMMAS = 1 << 2;\n\n/** Allow C-style single line and multiple line comments (non-standard). */\nstatic const yyjson_read_flag YYJSON_READ_ALLOW_COMMENTS        = 1 << 3;\n\n/** Allow inf/nan number and literal, case-insensitive,\n    such as 1e999, NaN, inf, -Infinity (non-standard). */\nstatic const yyjson_read_flag YYJSON_READ_ALLOW_INF_AND_NAN     = 1 << 4;\n\n/** Read all numbers as raw strings (value with `YYJSON_TYPE_RAW` type),\n    inf/nan literal is also read as raw with `ALLOW_INF_AND_NAN` flag. */\nstatic const yyjson_read_flag YYJSON_READ_NUMBER_AS_RAW         = 1 << 5;\n\n/** Allow reading invalid unicode when parsing string values (non-standard).\n    Invalid characters will be allowed to appear in the string values, but\n    invalid escape sequences will still be reported as errors.\n    This flag does not affect the performance of correctly encoded strings.\n    \n    @warning Strings in JSON values may contain incorrect encoding when this\n    option is used, you need to handle these strings carefully to avoid security\n    risks. */\nstatic const yyjson_read_flag YYJSON_READ_ALLOW_INVALID_UNICODE = 1 << 6;\n\n/** Read big numbers as raw strings. These big numbers include integers that\n    cannot be represented by `int64_t` and `uint64_t`, and floating-point\n    numbers that cannot be represented by finite `double`.\n    The flag will be overridden by `YYJSON_READ_NUMBER_AS_RAW` flag. */\nstatic const yyjson_read_flag YYJSON_READ_BIGNUM_AS_RAW         = 1 << 7;\n\n\n\n/** Result code for JSON reader. */\ntypedef uint32_t yyjson_read_code;\n\n/** Success, no error. */\nstatic const yyjson_read_code YYJSON_READ_SUCCESS                       = 0;\n\n/** Invalid parameter, such as NULL input string or 0 input length. */\nstatic const yyjson_read_code YYJSON_READ_ERROR_INVALID_PARAMETER       = 1;\n\n/** Memory allocation failure occurs. */\nstatic const yyjson_read_code YYJSON_READ_ERROR_MEMORY_ALLOCATION       = 2;\n\n/** Input JSON string is empty. */\nstatic const yyjson_read_code YYJSON_READ_ERROR_EMPTY_CONTENT           = 3;\n\n/** Unexpected content after document, such as `[123]abc`. */\nstatic const yyjson_read_code YYJSON_READ_ERROR_UNEXPECTED_CONTENT      = 4;\n\n/** Unexpected ending, such as `[123`. */\nstatic const yyjson_read_code YYJSON_READ_ERROR_UNEXPECTED_END          = 5;\n\n/** Unexpected character inside the document, such as `[abc]`. */\nstatic const yyjson_read_code YYJSON_READ_ERROR_UNEXPECTED_CHARACTER    = 6;\n\n/** Invalid JSON structure, such as `[1,]`. */\nstatic const yyjson_read_code YYJSON_READ_ERROR_JSON_STRUCTURE          = 7;\n\n/** Invalid comment, such as unclosed multi-line comment. */\nstatic const yyjson_read_code YYJSON_READ_ERROR_INVALID_COMMENT         = 8;\n\n/** Invalid number, such as `123.e12`, `000`. */\nstatic const yyjson_read_code YYJSON_READ_ERROR_INVALID_NUMBER          = 9;\n\n/** Invalid string, such as invalid escaped character inside a string. */\nstatic const yyjson_read_code YYJSON_READ_ERROR_INVALID_STRING          = 10;\n\n/** Invalid JSON literal, such as `truu`. */\nstatic const yyjson_read_code YYJSON_READ_ERROR_LITERAL                 = 11;\n\n/** Failed to open a file. */\nstatic const yyjson_read_code YYJSON_READ_ERROR_FILE_OPEN               = 12;\n\n/** Failed to read a file. */\nstatic const yyjson_read_code YYJSON_READ_ERROR_FILE_READ               = 13;\n\n/** Document exceeded YYJSON_READER_CONTAINER_RECURSION_LIMIT.  */\nstatic const yyjson_read_code YYJSON_READ_ERROR_RECURSION_DEPTH         = 14;\n\n/** Error information for JSON reader. */\ntypedef struct yyjson_read_err {\n    /** Error code, see `yyjson_read_code` for all possible values. */\n    yyjson_read_code code;\n    /** Error message, constant, no need to free (NULL if success). */\n    const char *msg;\n    /** Error byte position for input data (0 if success). */\n    size_t pos;\n} yyjson_read_err;\n\n\n\n/**\n Read JSON with options.\n \n This function is thread-safe when:\n 1. The `dat` is not modified by other threads.\n 2. The `alc` is thread-safe or NULL.\n \n @param dat The JSON data (UTF-8 without BOM), null-terminator is not required.\n    If this parameter is NULL, the function will fail and return NULL.\n    The `dat` will not be modified without the flag `YYJSON_READ_INSITU`, so you\n    can pass a `const char *` string and case it to `char *` if you don't use\n    the `YYJSON_READ_INSITU` flag.\n @param len The length of JSON data in bytes.\n    If this parameter is 0, the function will fail and return NULL.\n @param alc The memory allocator used by JSON reader.\n    Pass NULL to use the libc's default allocator.\n @param err A pointer to receive error information.\n    Pass NULL if you don't need error information.\n @return A new JSON document, or NULL if an error occurs.\n    When it's no longer needed, it should be freed with `yyjson_doc_free()`.\n */\nyyjson_api yyjson_doc *yyjson_read_opts(char *dat,\n                                        size_t len,\n                                        const yyjson_alc *alc,\n                                        yyjson_read_err *err);\n\n/**\n Read a JSON file.\n \n This function is thread-safe when:\n 1. The file is not modified by other threads.\n 2. The `alc` is thread-safe or NULL.\n \n @param path The JSON file's path.\n    If this path is NULL or invalid, the function will fail and return NULL.\n @param flg The JSON read options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n @param alc The memory allocator used by JSON reader.\n    Pass NULL to use the libc's default allocator.\n @param err A pointer to receive error information.\n    Pass NULL if you don't need error information.\n @return A new JSON document, or NULL if an error occurs.\n    When it's no longer needed, it should be freed with `yyjson_doc_free()`.\n \n @warning On 32-bit operating system, files larger than 2GB may fail to read.\n */\nyyjson_api yyjson_doc *yyjson_read_file(const char *path,\n                                        yyjson_read_flag flg,\n                                        const yyjson_alc *alc,\n                                        yyjson_read_err *err);\n\n/**\n Read JSON from a file pointer.\n \n @param fp The file pointer.\n    The data will be read from the current position of the FILE to the end.\n    If this fp is NULL or invalid, the function will fail and return NULL.\n @param flg The JSON read options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n @param alc The memory allocator used by JSON reader.\n    Pass NULL to use the libc's default allocator.\n @param err A pointer to receive error information.\n    Pass NULL if you don't need error information.\n @return A new JSON document, or NULL if an error occurs.\n    When it's no longer needed, it should be freed with `yyjson_doc_free()`.\n \n @warning On 32-bit operating system, files larger than 2GB may fail to read.\n */\nyyjson_api yyjson_doc *yyjson_read_fp(FILE *fp,\n                                      yyjson_read_flag flg,\n                                      const yyjson_alc *alc,\n                                      yyjson_read_err *err);\n\n/**\n Read a JSON string.\n \n This function is thread-safe.\n \n @param dat The JSON data (UTF-8 without BOM), null-terminator is not required.\n    If this parameter is NULL, the function will fail and return NULL.\n @param len The length of JSON data in bytes.\n    If this parameter is 0, the function will fail and return NULL.\n @param flg The JSON read options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n @return A new JSON document, or NULL if an error occurs.\n    When it's no longer needed, it should be freed with `yyjson_doc_free()`.\n */\nyyjson_api_inline yyjson_doc *yyjson_read(const char *dat,\n                                          size_t len,\n                                          yyjson_read_flag flg) {\n    flg &= ~YYJSON_READ_INSITU; /* const string cannot be modified */\n    return yyjson_read_opts((char *)(void *)(size_t)(const void *)dat,\n                            len, NULL, NULL);\n}\n\n/**\n Returns the size of maximum memory usage to read a JSON data.\n \n You may use this value to avoid malloc() or calloc() call inside the reader\n to get better performance, or read multiple JSON with one piece of memory.\n \n @param len The length of JSON data in bytes.\n @param flg The JSON read options.\n @return The maximum memory size to read this JSON, or 0 if overflow.\n \n @par Example\n @code\n    // read multiple JSON with same pre-allocated memory\n    \n    char *dat1, *dat2, *dat3; // JSON data\n    size_t len1, len2, len3; // JSON length\n    size_t max_len = MAX(len1, MAX(len2, len3));\n    yyjson_doc *doc;\n    \n    // use one allocator for multiple JSON\n    size_t size = yyjson_read_max_memory_usage(max_len, 0);\n    void *buf = malloc(size);\n    yyjson_alc alc;\n    yyjson_alc_pool_init(&alc, buf, size);\n    \n    // no more alloc() or realloc() call during reading\n    doc = yyjson_read_opts(dat1, len1, 0, &alc, NULL);\n    yyjson_doc_free(doc);\n    doc = yyjson_read_opts(dat2, len2, 0, &alc, NULL);\n    yyjson_doc_free(doc);\n    doc = yyjson_read_opts(dat3, len3, 0, &alc, NULL);\n    yyjson_doc_free(doc);\n    \n    free(buf);\n @endcode\n @see yyjson_alc_pool_init()\n */\nyyjson_api_inline size_t yyjson_read_max_memory_usage(size_t len,\n                                                      yyjson_read_flag flg) {\n    /*\n     1. The max value count is (json_size / 2 + 1),\n        for example: \"[1,2,3,4]\" size is 9, value count is 5.\n     2. Some broken JSON may cost more memory during reading, but fail at end,\n        for example: \"[[[[[[[[\".\n     3. yyjson use 16 bytes per value, see struct yyjson_val.\n     4. yyjson use dynamic memory with a growth factor of 1.5.\n     \n     The max memory size is (json_size / 2 * 16 * 1.5 + padding).\n     */\n    size_t mul = (size_t)12 + !(flg & YYJSON_READ_INSITU);\n    size_t pad = 256;\n    size_t max = (size_t)(~(size_t)0);\n    if (flg & YYJSON_READ_STOP_WHEN_DONE) len = len < 256 ? 256 : len;\n    if (len >= (max - pad - mul) / mul) return 0;\n    return len * mul + pad;\n}\n\n/**\n Read a JSON number.\n\n This function is thread-safe when data is not modified by other threads.\n\n @param dat The JSON data (UTF-8 without BOM), null-terminator is required.\n    If this parameter is NULL, the function will fail and return NULL.\n @param val The output value where result is stored.\n    If this parameter is NULL, the function will fail and return NULL.\n    The value will hold either UINT or SINT or REAL number;\n @param flg The JSON read options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n    Supports `YYJSON_READ_NUMBER_AS_RAW` and `YYJSON_READ_ALLOW_INF_AND_NAN`.\n @param alc The memory allocator used for long number.\n    It is only used when the built-in floating point reader is disabled.\n    Pass NULL to use the libc's default allocator.\n @param err A pointer to receive error information.\n    Pass NULL if you don't need error information.\n @return If successful, a pointer to the character after the last character\n    used in the conversion, NULL if an error occurs.\n */\nyyjson_api const char *yyjson_read_number(const char *dat,\n                                          yyjson_val *val,\n                                          yyjson_read_flag flg,\n                                          const yyjson_alc *alc,\n                                          yyjson_read_err *err);\n\n/**\n Read a JSON number.\n\n This function is thread-safe when data is not modified by other threads.\n\n @param dat The JSON data (UTF-8 without BOM), null-terminator is required.\n    If this parameter is NULL, the function will fail and return NULL.\n @param val The output value where result is stored.\n    If this parameter is NULL, the function will fail and return NULL.\n    The value will hold either UINT or SINT or REAL number;\n @param flg The JSON read options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n    Supports `YYJSON_READ_NUMBER_AS_RAW` and `YYJSON_READ_ALLOW_INF_AND_NAN`.\n @param alc The memory allocator used for long number.\n    It is only used when the built-in floating point reader is disabled.\n    Pass NULL to use the libc's default allocator.\n @param err A pointer to receive error information.\n    Pass NULL if you don't need error information.\n @return If successful, a pointer to the character after the last character\n    used in the conversion, NULL if an error occurs.\n */\nyyjson_api_inline const char *yyjson_mut_read_number(const char *dat,\n                                                     yyjson_mut_val *val,\n                                                     yyjson_read_flag flg,\n                                                     const yyjson_alc *alc,\n                                                     yyjson_read_err *err) {\n    return yyjson_read_number(dat, (yyjson_val *)val, flg, alc, err);\n}\n\n\n/*==============================================================================\n * JSON Writer API\n *============================================================================*/\n\n/** Run-time options for JSON writer. */\ntypedef uint32_t yyjson_write_flag;\n\n/** Default option:\n    - Write JSON minify.\n    - Report error on inf or nan number.\n    - Report error on invalid UTF-8 string.\n    - Do not escape unicode or slash. */\nstatic const yyjson_write_flag YYJSON_WRITE_NOFLAG                  = 0;\n\n/** Write JSON pretty with 4 space indent. */\nstatic const yyjson_write_flag YYJSON_WRITE_PRETTY                  = 1 << 0;\n\n/** Escape unicode as `uXXXX`, make the output ASCII only. */\nstatic const yyjson_write_flag YYJSON_WRITE_ESCAPE_UNICODE          = 1 << 1;\n\n/** Escape '/' as '\\/'. */\nstatic const yyjson_write_flag YYJSON_WRITE_ESCAPE_SLASHES          = 1 << 2;\n\n/** Write inf and nan number as 'Infinity' and 'NaN' literal (non-standard). */\nstatic const yyjson_write_flag YYJSON_WRITE_ALLOW_INF_AND_NAN       = 1 << 3;\n\n/** Write inf and nan number as null literal.\n    This flag will override `YYJSON_WRITE_ALLOW_INF_AND_NAN` flag. */\nstatic const yyjson_write_flag YYJSON_WRITE_INF_AND_NAN_AS_NULL     = 1 << 4;\n\n/** Allow invalid unicode when encoding string values (non-standard).\n    Invalid characters in string value will be copied byte by byte.\n    If `YYJSON_WRITE_ESCAPE_UNICODE` flag is also set, invalid character will be\n    escaped as `U+FFFD` (replacement character).\n    This flag does not affect the performance of correctly encoded strings. */\nstatic const yyjson_write_flag YYJSON_WRITE_ALLOW_INVALID_UNICODE   = 1 << 5;\n\n/** Write JSON pretty with 2 space indent.\n    This flag will override `YYJSON_WRITE_PRETTY` flag. */\nstatic const yyjson_write_flag YYJSON_WRITE_PRETTY_TWO_SPACES       = 1 << 6;\n\n/** Adds a newline character `\\n` at the end of the JSON.\n    This can be helpful for text editors or NDJSON. */\nstatic const yyjson_write_flag YYJSON_WRITE_NEWLINE_AT_END          = 1 << 7;\n\n\n\n/** Result code for JSON writer */\ntypedef uint32_t yyjson_write_code;\n\n/** Success, no error. */\nstatic const yyjson_write_code YYJSON_WRITE_SUCCESS                     = 0;\n\n/** Invalid parameter, such as NULL document. */\nstatic const yyjson_write_code YYJSON_WRITE_ERROR_INVALID_PARAMETER     = 1;\n\n/** Memory allocation failure occurs. */\nstatic const yyjson_write_code YYJSON_WRITE_ERROR_MEMORY_ALLOCATION     = 2;\n\n/** Invalid value type in JSON document. */\nstatic const yyjson_write_code YYJSON_WRITE_ERROR_INVALID_VALUE_TYPE    = 3;\n\n/** NaN or Infinity number occurs. */\nstatic const yyjson_write_code YYJSON_WRITE_ERROR_NAN_OR_INF            = 4;\n\n/** Failed to open a file. */\nstatic const yyjson_write_code YYJSON_WRITE_ERROR_FILE_OPEN             = 5;\n\n/** Failed to write a file. */\nstatic const yyjson_write_code YYJSON_WRITE_ERROR_FILE_WRITE            = 6;\n\n/** Invalid unicode in string. */\nstatic const yyjson_write_code YYJSON_WRITE_ERROR_INVALID_STRING        = 7;\n\n/** Error information for JSON writer. */\ntypedef struct yyjson_write_err {\n    /** Error code, see `yyjson_write_code` for all possible values. */\n    yyjson_write_code code;\n    /** Error message, constant, no need to free (NULL if success). */\n    const char *msg;\n} yyjson_write_err;\n\n\n\n/*==============================================================================\n * JSON Document Writer API\n *============================================================================*/\n\n/**\n Write a document to JSON string with options.\n \n This function is thread-safe when:\n The `alc` is thread-safe or NULL.\n \n @param doc The JSON document.\n    If this doc is NULL or has no root, the function will fail and return false.\n @param flg The JSON write options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n @param alc The memory allocator used by JSON writer.\n    Pass NULL to use the libc's default allocator.\n @param len A pointer to receive output length in bytes (not including the\n    null-terminator). Pass NULL if you don't need length information.\n @param err A pointer to receive error information.\n    Pass NULL if you don't need error information.\n @return A new JSON string, or NULL if an error occurs.\n    This string is encoded as UTF-8 with a null-terminator.\n    When it's no longer needed, it should be freed with free() or alc->free().\n */\nyyjson_api char *yyjson_write_opts(const yyjson_doc *doc,\n                                   yyjson_write_flag flg,\n                                   const yyjson_alc *alc,\n                                   size_t *len,\n                                   yyjson_write_err *err);\n\n/**\n Write a document to JSON file with options.\n \n This function is thread-safe when:\n 1. The file is not accessed by other threads.\n 2. The `alc` is thread-safe or NULL.\n\n @param path The JSON file's path.\n    If this path is NULL or invalid, the function will fail and return false.\n    If this file is not empty, the content will be discarded.\n @param doc The JSON document.\n    If this doc is NULL or has no root, the function will fail and return false.\n @param flg The JSON write options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n @param alc The memory allocator used by JSON writer.\n    Pass NULL to use the libc's default allocator.\n @param err A pointer to receive error information.\n    Pass NULL if you don't need error information.\n @return true if successful, false if an error occurs.\n \n @warning On 32-bit operating system, files larger than 2GB may fail to write.\n */\nyyjson_api bool yyjson_write_file(const char *path,\n                                  const yyjson_doc *doc,\n                                  yyjson_write_flag flg,\n                                  const yyjson_alc *alc,\n                                  yyjson_write_err *err);\n\n/**\n Write a document to file pointer with options.\n \n @param fp The file pointer.\n    The data will be written to the current position of the file.\n    If this fp is NULL or invalid, the function will fail and return false.\n @param doc The JSON document.\n    If this doc is NULL or has no root, the function will fail and return false.\n @param flg The JSON write options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n @param alc The memory allocator used by JSON writer.\n    Pass NULL to use the libc's default allocator.\n @param err A pointer to receive error information.\n    Pass NULL if you don't need error information.\n @return true if successful, false if an error occurs.\n \n @warning On 32-bit operating system, files larger than 2GB may fail to write.\n */\nyyjson_api bool yyjson_write_fp(FILE *fp,\n                                const yyjson_doc *doc,\n                                yyjson_write_flag flg,\n                                const yyjson_alc *alc,\n                                yyjson_write_err *err);\n\n/**\n Write a document to JSON string.\n \n This function is thread-safe.\n \n @param doc The JSON document.\n    If this doc is NULL or has no root, the function will fail and return false.\n @param flg The JSON write options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n @param len A pointer to receive output length in bytes (not including the\n    null-terminator). Pass NULL if you don't need length information.\n @return A new JSON string, or NULL if an error occurs.\n    This string is encoded as UTF-8 with a null-terminator.\n    When it's no longer needed, it should be freed with free().\n */\nyyjson_api_inline char *yyjson_write(const yyjson_doc *doc,\n                                     yyjson_write_flag flg,\n                                     size_t *len) {\n    return yyjson_write_opts(doc, flg, NULL, len, NULL);\n}\n\n\n\n/**\n Write a document to JSON string with options.\n \n This function is thread-safe when:\n 1. The `doc` is not modified by other threads.\n 2. The `alc` is thread-safe or NULL.\n\n @param doc The mutable JSON document.\n    If this doc is NULL or has no root, the function will fail and return false.\n @param flg The JSON write options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n @param alc The memory allocator used by JSON writer.\n    Pass NULL to use the libc's default allocator.\n @param len A pointer to receive output length in bytes (not including the\n    null-terminator). Pass NULL if you don't need length information.\n @param err A pointer to receive error information.\n    Pass NULL if you don't need error information.\n @return A new JSON string, or NULL if an error occurs.\n    This string is encoded as UTF-8 with a null-terminator.\n    When it's no longer needed, it should be freed with free() or alc->free().\n */\nyyjson_api char *yyjson_mut_write_opts(const yyjson_mut_doc *doc,\n                                       yyjson_write_flag flg,\n                                       const yyjson_alc *alc,\n                                       size_t *len,\n                                       yyjson_write_err *err);\n\n/**\n Write a document to JSON file with options.\n \n This function is thread-safe when:\n 1. The file is not accessed by other threads.\n 2. The `doc` is not modified by other threads.\n 3. The `alc` is thread-safe or NULL.\n \n @param path The JSON file's path.\n    If this path is NULL or invalid, the function will fail and return false.\n    If this file is not empty, the content will be discarded.\n @param doc The mutable JSON document.\n    If this doc is NULL or has no root, the function will fail and return false.\n @param flg The JSON write options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n @param alc The memory allocator used by JSON writer.\n    Pass NULL to use the libc's default allocator.\n @param err A pointer to receive error information.\n    Pass NULL if you don't need error information.\n @return true if successful, false if an error occurs.\n \n @warning On 32-bit operating system, files larger than 2GB may fail to write.\n */\nyyjson_api bool yyjson_mut_write_file(const char *path,\n                                      const yyjson_mut_doc *doc,\n                                      yyjson_write_flag flg,\n                                      const yyjson_alc *alc,\n                                      yyjson_write_err *err);\n\n/**\n Write a document to file pointer with options.\n \n @param fp The file pointer.\n    The data will be written to the current position of the file.\n    If this fp is NULL or invalid, the function will fail and return false.\n @param doc The mutable JSON document.\n    If this doc is NULL or has no root, the function will fail and return false.\n @param flg The JSON write options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n @param alc The memory allocator used by JSON writer.\n    Pass NULL to use the libc's default allocator.\n @param err A pointer to receive error information.\n    Pass NULL if you don't need error information.\n @return true if successful, false if an error occurs.\n \n @warning On 32-bit operating system, files larger than 2GB may fail to write.\n */\nyyjson_api bool yyjson_mut_write_fp(FILE *fp,\n                                    const yyjson_mut_doc *doc,\n                                    yyjson_write_flag flg,\n                                    const yyjson_alc *alc,\n                                    yyjson_write_err *err);\n\n/**\n Write a document to JSON string.\n \n This function is thread-safe when:\n The `doc` is not modified by other threads.\n \n @param doc The JSON document.\n    If this doc is NULL or has no root, the function will fail and return false.\n @param flg The JSON write options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n @param len A pointer to receive output length in bytes (not including the\n    null-terminator). Pass NULL if you don't need length information.\n @return A new JSON string, or NULL if an error occurs.\n    This string is encoded as UTF-8 with a null-terminator.\n    When it's no longer needed, it should be freed with free().\n */\nyyjson_api_inline char *yyjson_mut_write(const yyjson_mut_doc *doc,\n                                         yyjson_write_flag flg,\n                                         size_t *len) {\n    return yyjson_mut_write_opts(doc, flg, NULL, len, NULL);\n}\n\n\n\n/*==============================================================================\n * JSON Value Writer API\n *============================================================================*/\n\n/**\n Write a value to JSON string with options.\n \n This function is thread-safe when:\n The `alc` is thread-safe or NULL.\n \n @param val The JSON root value.\n    If this parameter is NULL, the function will fail and return NULL.\n @param flg The JSON write options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n @param alc The memory allocator used by JSON writer.\n    Pass NULL to use the libc's default allocator.\n @param len A pointer to receive output length in bytes (not including the\n    null-terminator). Pass NULL if you don't need length information.\n @param err A pointer to receive error information.\n    Pass NULL if you don't need error information.\n @return A new JSON string, or NULL if an error occurs.\n    This string is encoded as UTF-8 with a null-terminator.\n    When it's no longer needed, it should be freed with free() or alc->free().\n */\nyyjson_api char *yyjson_val_write_opts(const yyjson_val *val,\n                                       yyjson_write_flag flg,\n                                       const yyjson_alc *alc,\n                                       size_t *len,\n                                       yyjson_write_err *err);\n\n/**\n Write a value to JSON file with options.\n \n This function is thread-safe when:\n 1. The file is not accessed by other threads.\n 2. The `alc` is thread-safe or NULL.\n \n @param path The JSON file's path.\n    If this path is NULL or invalid, the function will fail and return false.\n    If this file is not empty, the content will be discarded.\n @param val The JSON root value.\n    If this parameter is NULL, the function will fail and return NULL.\n @param flg The JSON write options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n @param alc The memory allocator used by JSON writer.\n    Pass NULL to use the libc's default allocator.\n @param err A pointer to receive error information.\n    Pass NULL if you don't need error information.\n @return true if successful, false if an error occurs.\n \n @warning On 32-bit operating system, files larger than 2GB may fail to write.\n */\nyyjson_api bool yyjson_val_write_file(const char *path,\n                                      const yyjson_val *val,\n                                      yyjson_write_flag flg,\n                                      const yyjson_alc *alc,\n                                      yyjson_write_err *err);\n\n/**\n Write a value to file pointer with options.\n \n @param fp The file pointer.\n    The data will be written to the current position of the file.\n    If this path is NULL or invalid, the function will fail and return false.\n @param val The JSON root value.\n    If this parameter is NULL, the function will fail and return NULL.\n @param flg The JSON write options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n @param alc The memory allocator used by JSON writer.\n    Pass NULL to use the libc's default allocator.\n @param err A pointer to receive error information.\n    Pass NULL if you don't need error information.\n @return true if successful, false if an error occurs.\n \n @warning On 32-bit operating system, files larger than 2GB may fail to write.\n */\nyyjson_api bool yyjson_val_write_fp(FILE *fp,\n                                    const yyjson_val *val,\n                                    yyjson_write_flag flg,\n                                    const yyjson_alc *alc,\n                                    yyjson_write_err *err);\n\n/**\n Write a value to JSON string.\n \n This function is thread-safe.\n \n @param val The JSON root value.\n    If this parameter is NULL, the function will fail and return NULL.\n @param flg The JSON write options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n @param len A pointer to receive output length in bytes (not including the\n    null-terminator). Pass NULL if you don't need length information.\n @return A new JSON string, or NULL if an error occurs.\n    This string is encoded as UTF-8 with a null-terminator.\n    When it's no longer needed, it should be freed with free().\n */\nyyjson_api_inline char *yyjson_val_write(const yyjson_val *val,\n                                         yyjson_write_flag flg,\n                                         size_t *len) {\n    return yyjson_val_write_opts(val, flg, NULL, len, NULL);\n}\n\n/**\n Write a value to JSON string with options.\n \n This function is thread-safe when:\n 1. The `val` is not modified by other threads.\n 2. The `alc` is thread-safe or NULL.\n \n @param val The mutable JSON root value.\n    If this parameter is NULL, the function will fail and return NULL.\n @param flg The JSON write options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n @param alc The memory allocator used by JSON writer.\n    Pass NULL to use the libc's default allocator.\n @param len A pointer to receive output length in bytes (not including the\n    null-terminator). Pass NULL if you don't need length information.\n @param err A pointer to receive error information.\n    Pass NULL if you don't need error information.\n @return  A new JSON string, or NULL if an error occurs.\n    This string is encoded as UTF-8 with a null-terminator.\n    When it's no longer needed, it should be freed with free() or alc->free().\n */\nyyjson_api char *yyjson_mut_val_write_opts(const yyjson_mut_val *val,\n                                           yyjson_write_flag flg,\n                                           const yyjson_alc *alc,\n                                           size_t *len,\n                                           yyjson_write_err *err);\n\n/**\n Write a value to JSON file with options.\n \n This function is thread-safe when:\n 1. The file is not accessed by other threads.\n 2. The `val` is not modified by other threads.\n 3. The `alc` is thread-safe or NULL.\n \n @param path The JSON file's path.\n    If this path is NULL or invalid, the function will fail and return false.\n    If this file is not empty, the content will be discarded.\n @param val The mutable JSON root value.\n    If this parameter is NULL, the function will fail and return NULL.\n @param flg The JSON write options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n @param alc The memory allocator used by JSON writer.\n    Pass NULL to use the libc's default allocator.\n @param err A pointer to receive error information.\n    Pass NULL if you don't need error information.\n @return true if successful, false if an error occurs.\n \n @warning On 32-bit operating system, files larger than 2GB may fail to write.\n */\nyyjson_api bool yyjson_mut_val_write_file(const char *path,\n                                          const yyjson_mut_val *val,\n                                          yyjson_write_flag flg,\n                                          const yyjson_alc *alc,\n                                          yyjson_write_err *err);\n\n/**\n Write a value to JSON file with options.\n \n @param fp The file pointer.\n    The data will be written to the current position of the file.\n    If this path is NULL or invalid, the function will fail and return false.\n @param val The mutable JSON root value.\n    If this parameter is NULL, the function will fail and return NULL.\n @param flg The JSON write options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n @param alc The memory allocator used by JSON writer.\n    Pass NULL to use the libc's default allocator.\n @param err A pointer to receive error information.\n    Pass NULL if you don't need error information.\n @return true if successful, false if an error occurs.\n \n @warning On 32-bit operating system, files larger than 2GB may fail to write.\n */\nyyjson_api bool yyjson_mut_val_write_fp(FILE *fp,\n                                        const yyjson_mut_val *val,\n                                        yyjson_write_flag flg,\n                                        const yyjson_alc *alc,\n                                        yyjson_write_err *err);\n\n/**\n Write a value to JSON string.\n \n This function is thread-safe when:\n The `val` is not modified by other threads.\n \n @param val The JSON root value.\n    If this parameter is NULL, the function will fail and return NULL.\n @param flg The JSON write options.\n    Multiple options can be combined with `|` operator. 0 means no options.\n @param len A pointer to receive output length in bytes (not including the\n    null-terminator). Pass NULL if you don't need length information.\n @return A new JSON string, or NULL if an error occurs.\n    This string is encoded as UTF-8 with a null-terminator.\n    When it's no longer needed, it should be freed with free().\n */\nyyjson_api_inline char *yyjson_mut_val_write(const yyjson_mut_val *val,\n                                             yyjson_write_flag flg,\n                                             size_t *len) {\n    return yyjson_mut_val_write_opts(val, flg, NULL, len, NULL);\n}\n\n\n\n/*==============================================================================\n * JSON Document API\n *============================================================================*/\n\n/** Returns the root value of this JSON document.\n    Returns NULL if `doc` is NULL. */\nyyjson_api_inline yyjson_val *yyjson_doc_get_root(yyjson_doc *doc);\n\n/** Returns read size of input JSON data.\n    Returns 0 if `doc` is NULL.\n    For example: the read size of `[1,2,3]` is 7 bytes.  */\nyyjson_api_inline size_t yyjson_doc_get_read_size(yyjson_doc *doc);\n\n/** Returns total value count in this JSON document.\n    Returns 0 if `doc` is NULL.\n    For example: the value count of `[1,2,3]` is 4. */\nyyjson_api_inline size_t yyjson_doc_get_val_count(yyjson_doc *doc);\n\n/** Release the JSON document and free the memory.\n    After calling this function, the `doc` and all values from the `doc` are no\n    longer available. This function will do nothing if the `doc` is NULL. */\nyyjson_api void yyjson_doc_free(yyjson_doc *doc);\n\n\n\n/*==============================================================================\n * JSON Value Type API\n *============================================================================*/\n\n/** Returns whether the JSON value is raw.\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_is_raw(yyjson_val *val);\n\n/** Returns whether the JSON value is `null`.\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_is_null(yyjson_val *val);\n\n/** Returns whether the JSON value is `true`.\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_is_true(yyjson_val *val);\n\n/** Returns whether the JSON value is `false`.\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_is_false(yyjson_val *val);\n\n/** Returns whether the JSON value is bool (true/false).\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_is_bool(yyjson_val *val);\n\n/** Returns whether the JSON value is unsigned integer (uint64_t).\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_is_uint(yyjson_val *val);\n\n/** Returns whether the JSON value is signed integer (int64_t).\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_is_sint(yyjson_val *val);\n\n/** Returns whether the JSON value is integer (uint64_t/int64_t).\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_is_int(yyjson_val *val);\n\n/** Returns whether the JSON value is real number (double).\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_is_real(yyjson_val *val);\n\n/** Returns whether the JSON value is number (uint64_t/int64_t/double).\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_is_num(yyjson_val *val);\n\n/** Returns whether the JSON value is string.\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_is_str(yyjson_val *val);\n\n/** Returns whether the JSON value is array.\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_is_arr(yyjson_val *val);\n\n/** Returns whether the JSON value is object.\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_is_obj(yyjson_val *val);\n\n/** Returns whether the JSON value is container (array/object).\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_is_ctn(yyjson_val *val);\n\n\n\n/*==============================================================================\n * JSON Value Content API\n *============================================================================*/\n\n/** Returns the JSON value's type.\n    Returns YYJSON_TYPE_NONE if `val` is NULL. */\nyyjson_api_inline yyjson_type yyjson_get_type(yyjson_val *val);\n\n/** Returns the JSON value's subtype.\n    Returns YYJSON_SUBTYPE_NONE if `val` is NULL. */\nyyjson_api_inline yyjson_subtype yyjson_get_subtype(yyjson_val *val);\n\n/** Returns the JSON value's tag.\n    Returns 0 if `val` is NULL. */\nyyjson_api_inline uint8_t yyjson_get_tag(yyjson_val *val);\n\n/** Returns the JSON value's type description.\n    The return value should be one of these strings: \"raw\", \"null\", \"string\",\n    \"array\", \"object\", \"true\", \"false\", \"uint\", \"sint\", \"real\", \"unknown\". */\nyyjson_api_inline const char *yyjson_get_type_desc(yyjson_val *val);\n\n/** Returns the content if the value is raw.\n    Returns NULL if `val` is NULL or type is not raw. */\nyyjson_api_inline const char *yyjson_get_raw(yyjson_val *val);\n\n/** Returns the content if the value is bool.\n    Returns NULL if `val` is NULL or type is not bool. */\nyyjson_api_inline bool yyjson_get_bool(yyjson_val *val);\n\n/** Returns the content and cast to uint64_t.\n    Returns 0 if `val` is NULL or type is not integer(sint/uint). */\nyyjson_api_inline uint64_t yyjson_get_uint(yyjson_val *val);\n\n/** Returns the content and cast to int64_t.\n    Returns 0 if `val` is NULL or type is not integer(sint/uint). */\nyyjson_api_inline int64_t yyjson_get_sint(yyjson_val *val);\n\n/** Returns the content and cast to int.\n    Returns 0 if `val` is NULL or type is not integer(sint/uint). */\nyyjson_api_inline int yyjson_get_int(yyjson_val *val);\n\n/** Returns the content if the value is real number, or 0.0 on error.\n    Returns 0.0 if `val` is NULL or type is not real(double). */\nyyjson_api_inline double yyjson_get_real(yyjson_val *val);\n\n/** Returns the content and typecast to `double` if the value is number.\n    Returns 0.0 if `val` is NULL or type is not number(uint/sint/real). */\nyyjson_api_inline double yyjson_get_num(yyjson_val *val);\n\n/** Returns the content if the value is string.\n    Returns NULL if `val` is NULL or type is not string. */\nyyjson_api_inline const char *yyjson_get_str(yyjson_val *val);\n\n/** Returns the content length (string length, array size, object size.\n    Returns 0 if `val` is NULL or type is not string/array/object. */\nyyjson_api_inline size_t yyjson_get_len(yyjson_val *val);\n\n/** Returns whether the JSON value is equals to a string.\n    Returns false if input is NULL or type is not string. */\nyyjson_api_inline bool yyjson_equals_str(yyjson_val *val, const char *str);\n\n/** Returns whether the JSON value is equals to a string.\n    The `str` should be a UTF-8 string, null-terminator is not required.\n    Returns false if input is NULL or type is not string. */\nyyjson_api_inline bool yyjson_equals_strn(yyjson_val *val, const char *str,\n                                          size_t len);\n\n/** Returns whether two JSON values are equal (deep compare).\n    Returns false if input is NULL.\n    @note the result may be inaccurate if object has duplicate keys.\n    @warning This function is recursive and may cause a stack overflow\n        if the object level is too deep. */\nyyjson_api_inline bool yyjson_equals(yyjson_val *lhs, yyjson_val *rhs);\n\n/** Set the value to raw.\n    Returns false if input is NULL or `val` is object or array.\n    @warning This will modify the `immutable` value, use with caution. */\nyyjson_api_inline bool yyjson_set_raw(yyjson_val *val,\n                                      const char *raw, size_t len);\n\n/** Set the value to null.\n    Returns false if input is NULL or `val` is object or array.\n    @warning This will modify the `immutable` value, use with caution. */\nyyjson_api_inline bool yyjson_set_null(yyjson_val *val);\n\n/** Set the value to bool.\n    Returns false if input is NULL or `val` is object or array.\n    @warning This will modify the `immutable` value, use with caution. */\nyyjson_api_inline bool yyjson_set_bool(yyjson_val *val, bool num);\n\n/** Set the value to uint.\n    Returns false if input is NULL or `val` is object or array.\n    @warning This will modify the `immutable` value, use with caution. */\nyyjson_api_inline bool yyjson_set_uint(yyjson_val *val, uint64_t num);\n\n/** Set the value to sint.\n    Returns false if input is NULL or `val` is object or array.\n    @warning This will modify the `immutable` value, use with caution. */\nyyjson_api_inline bool yyjson_set_sint(yyjson_val *val, int64_t num);\n\n/** Set the value to int.\n    Returns false if input is NULL or `val` is object or array.\n    @warning This will modify the `immutable` value, use with caution. */\nyyjson_api_inline bool yyjson_set_int(yyjson_val *val, int num);\n\n/** Set the value to real.\n    Returns false if input is NULL or `val` is object or array.\n    @warning This will modify the `immutable` value, use with caution. */\nyyjson_api_inline bool yyjson_set_real(yyjson_val *val, double num);\n\n/** Set the value to string (null-terminated).\n    Returns false if input is NULL or `val` is object or array.\n    @warning This will modify the `immutable` value, use with caution. */\nyyjson_api_inline bool yyjson_set_str(yyjson_val *val, const char *str);\n\n/** Set the value to string (with length).\n    Returns false if input is NULL or `val` is object or array.\n    @warning This will modify the `immutable` value, use with caution. */\nyyjson_api_inline bool yyjson_set_strn(yyjson_val *val,\n                                       const char *str, size_t len);\n\n\n\n/*==============================================================================\n * JSON Array API\n *============================================================================*/\n\n/** Returns the number of elements in this array.\n    Returns 0 if `arr` is NULL or type is not array. */\nyyjson_api_inline size_t yyjson_arr_size(yyjson_val *arr);\n\n/** Returns the element at the specified position in this array.\n    Returns NULL if array is NULL/empty or the index is out of bounds.\n    @warning This function takes a linear search time if array is not flat.\n        For example: `[1,{},3]` is flat, `[1,[2],3]` is not flat. */\nyyjson_api_inline yyjson_val *yyjson_arr_get(yyjson_val *arr, size_t idx);\n\n/** Returns the first element of this array.\n    Returns NULL if `arr` is NULL/empty or type is not array. */\nyyjson_api_inline yyjson_val *yyjson_arr_get_first(yyjson_val *arr);\n\n/** Returns the last element of this array.\n    Returns NULL if `arr` is NULL/empty or type is not array.\n    @warning This function takes a linear search time if array is not flat.\n        For example: `[1,{},3]` is flat, `[1,[2],3]` is not flat.*/\nyyjson_api_inline yyjson_val *yyjson_arr_get_last(yyjson_val *arr);\n\n\n\n/*==============================================================================\n * JSON Array Iterator API\n *============================================================================*/\n\n/**\n A JSON array iterator.\n \n @par Example\n @code\n    yyjson_val *val;\n    yyjson_arr_iter iter = yyjson_arr_iter_with(arr);\n    while ((val = yyjson_arr_iter_next(&iter))) {\n        your_func(val);\n    }\n @endcode\n */\ntypedef struct yyjson_arr_iter {\n    size_t idx; /**< next value's index */\n    size_t max; /**< maximum index (arr.size) */\n    yyjson_val *cur; /**< next value */\n} yyjson_arr_iter;\n\n/**\n Initialize an iterator for this array.\n \n @param arr The array to be iterated over.\n    If this parameter is NULL or not an array, `iter` will be set to empty.\n @param iter The iterator to be initialized.\n    If this parameter is NULL, the function will fail and return false.\n @return true if the `iter` has been successfully initialized.\n \n @note The iterator does not need to be destroyed.\n */\nyyjson_api_inline bool yyjson_arr_iter_init(yyjson_val *arr,\n                                            yyjson_arr_iter *iter);\n\n/**\n Create an iterator with an array , same as `yyjson_arr_iter_init()`.\n \n @param arr The array to be iterated over.\n    If this parameter is NULL or not an array, an empty iterator will returned.\n @return A new iterator for the array.\n \n @note The iterator does not need to be destroyed.\n */\nyyjson_api_inline yyjson_arr_iter yyjson_arr_iter_with(yyjson_val *arr);\n\n/**\n Returns whether the iteration has more elements.\n If `iter` is NULL, this function will return false.\n */\nyyjson_api_inline bool yyjson_arr_iter_has_next(yyjson_arr_iter *iter);\n\n/**\n Returns the next element in the iteration, or NULL on end.\n If `iter` is NULL, this function will return NULL.\n */\nyyjson_api_inline yyjson_val *yyjson_arr_iter_next(yyjson_arr_iter *iter);\n\n/**\n Macro for iterating over an array.\n It works like iterator, but with a more intuitive API.\n \n @par Example\n @code\n    size_t idx, max;\n    yyjson_val *val;\n    yyjson_arr_foreach(arr, idx, max, val) {\n        your_func(idx, val);\n    }\n @endcode\n */\n#define yyjson_arr_foreach(arr, idx, max, val) \\\n    for ((idx) = 0, \\\n        (max) = yyjson_arr_size(arr), \\\n        (val) = yyjson_arr_get_first(arr); \\\n        (idx) < (max); \\\n        (idx)++, \\\n        (val) = unsafe_yyjson_get_next(val))\n\n\n\n/*==============================================================================\n * JSON Object API\n *============================================================================*/\n\n/** Returns the number of key-value pairs in this object.\n    Returns 0 if `obj` is NULL or type is not object. */\nyyjson_api_inline size_t yyjson_obj_size(yyjson_val *obj);\n\n/** Returns the value to which the specified key is mapped.\n    Returns NULL if this object contains no mapping for the key.\n    Returns NULL if `obj/key` is NULL, or type is not object.\n    \n    The `key` should be a null-terminated UTF-8 string.\n    \n    @warning This function takes a linear search time. */\nyyjson_api_inline yyjson_val *yyjson_obj_get(yyjson_val *obj, const char *key);\n\n/** Returns the value to which the specified key is mapped.\n    Returns NULL if this object contains no mapping for the key.\n    Returns NULL if `obj/key` is NULL, or type is not object.\n    \n    The `key` should be a UTF-8 string, null-terminator is not required.\n    The `key_len` should be the length of the key, in bytes.\n    \n    @warning This function takes a linear search time. */\nyyjson_api_inline yyjson_val *yyjson_obj_getn(yyjson_val *obj, const char *key,\n                                              size_t key_len);\n\n\n\n/*==============================================================================\n * JSON Object Iterator API\n *============================================================================*/\n\n/**\n A JSON object iterator.\n \n @par Example\n @code\n    yyjson_val *key, *val;\n    yyjson_obj_iter iter = yyjson_obj_iter_with(obj);\n    while ((key = yyjson_obj_iter_next(&iter))) {\n        val = yyjson_obj_iter_get_val(key);\n        your_func(key, val);\n    }\n @endcode\n \n If the ordering of the keys is known at compile-time, you can use this method\n to speed up value lookups:\n @code\n    // {\"k1\":1, \"k2\": 3, \"k3\": 3}\n    yyjson_val *key, *val;\n    yyjson_obj_iter iter = yyjson_obj_iter_with(obj);\n    yyjson_val *v1 = yyjson_obj_iter_get(&iter, \"k1\");\n    yyjson_val *v3 = yyjson_obj_iter_get(&iter, \"k3\");\n @endcode\n @see yyjson_obj_iter_get() and yyjson_obj_iter_getn()\n */\ntypedef struct yyjson_obj_iter {\n    size_t idx; /**< next key's index */\n    size_t max; /**< maximum key index (obj.size) */\n    yyjson_val *cur; /**< next key */\n    yyjson_val *obj; /**< the object being iterated */\n} yyjson_obj_iter;\n\n/**\n Initialize an iterator for this object.\n \n @param obj The object to be iterated over.\n    If this parameter is NULL or not an object, `iter` will be set to empty.\n @param iter The iterator to be initialized.\n    If this parameter is NULL, the function will fail and return false.\n @return true if the `iter` has been successfully initialized.\n \n @note The iterator does not need to be destroyed.\n */\nyyjson_api_inline bool yyjson_obj_iter_init(yyjson_val *obj,\n                                            yyjson_obj_iter *iter);\n\n/**\n Create an iterator with an object, same as `yyjson_obj_iter_init()`.\n \n @param obj The object to be iterated over.\n    If this parameter is NULL or not an object, an empty iterator will returned.\n @return A new iterator for the object.\n \n @note The iterator does not need to be destroyed.\n */\nyyjson_api_inline yyjson_obj_iter yyjson_obj_iter_with(yyjson_val *obj);\n\n/**\n Returns whether the iteration has more elements.\n If `iter` is NULL, this function will return false.\n */\nyyjson_api_inline bool yyjson_obj_iter_has_next(yyjson_obj_iter *iter);\n\n/**\n Returns the next key in the iteration, or NULL on end.\n If `iter` is NULL, this function will return NULL.\n */\nyyjson_api_inline yyjson_val *yyjson_obj_iter_next(yyjson_obj_iter *iter);\n\n/**\n Returns the value for key inside the iteration.\n If `iter` is NULL, this function will return NULL.\n */\nyyjson_api_inline yyjson_val *yyjson_obj_iter_get_val(yyjson_val *key);\n\n/**\n Iterates to a specified key and returns the value.\n \n This function does the same thing as `yyjson_obj_get()`, but is much faster\n if the ordering of the keys is known at compile-time and you are using the same\n order to look up the values. If the key exists in this object, then the\n iterator will stop at the next key, otherwise the iterator will not change and\n NULL is returned.\n \n @param iter The object iterator, should not be NULL.\n @param key The key, should be a UTF-8 string with null-terminator.\n @return The value to which the specified key is mapped.\n    NULL if this object contains no mapping for the key or input is invalid.\n \n @warning This function takes a linear search time if the key is not nearby.\n */\nyyjson_api_inline yyjson_val *yyjson_obj_iter_get(yyjson_obj_iter *iter,\n                                                  const char *key);\n\n/**\n Iterates to a specified key and returns the value.\n\n This function does the same thing as `yyjson_obj_getn()`, but is much faster\n if the ordering of the keys is known at compile-time and you are using the same\n order to look up the values. If the key exists in this object, then the\n iterator will stop at the next key, otherwise the iterator will not change and\n NULL is returned.\n \n @param iter The object iterator, should not be NULL.\n @param key The key, should be a UTF-8 string, null-terminator is not required.\n @param key_len The the length of `key`, in bytes.\n @return The value to which the specified key is mapped.\n    NULL if this object contains no mapping for the key or input is invalid.\n \n @warning This function takes a linear search time if the key is not nearby.\n */\nyyjson_api_inline yyjson_val *yyjson_obj_iter_getn(yyjson_obj_iter *iter,\n                                                   const char *key,\n                                                   size_t key_len);\n\n/**\n Macro for iterating over an object.\n It works like iterator, but with a more intuitive API.\n \n @par Example\n @code\n    size_t idx, max;\n    yyjson_val *key, *val;\n    yyjson_obj_foreach(obj, idx, max, key, val) {\n        your_func(key, val);\n    }\n @endcode\n */\n#define yyjson_obj_foreach(obj, idx, max, key, val) \\\n    for ((idx) = 0, \\\n        (max) = yyjson_obj_size(obj), \\\n        (key) = (obj) ? unsafe_yyjson_get_first(obj) : NULL, \\\n        (val) = (key) + 1; \\\n        (idx) < (max); \\\n        (idx)++, \\\n        (key) = unsafe_yyjson_get_next(val), \\\n        (val) = (key) + 1)\n\n\n\n/*==============================================================================\n * Mutable JSON Document API\n *============================================================================*/\n\n/** Returns the root value of this JSON document.\n    Returns NULL if `doc` is NULL. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_get_root(yyjson_mut_doc *doc);\n\n/** Sets the root value of this JSON document.\n    Pass NULL to clear root value of the document. */\nyyjson_api_inline void yyjson_mut_doc_set_root(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *root);\n\n/**\n Set the string pool size for a mutable document.\n This function does not allocate memory immediately, but uses the size when\n the next memory allocation is needed.\n \n If the caller knows the approximate bytes of strings that the document needs to\n store (e.g. copy string with `yyjson_mut_strcpy` function), setting a larger\n size can avoid multiple memory allocations and improve performance.\n \n @param doc The mutable document.\n @param len The desired string pool size in bytes (total string length).\n @return true if successful, false if size is 0 or overflow.\n */\nyyjson_api bool yyjson_mut_doc_set_str_pool_size(yyjson_mut_doc *doc,\n                                                 size_t len);\n\n/**\n Set the value pool size for a mutable document.\n This function does not allocate memory immediately, but uses the size when\n the next memory allocation is needed.\n \n If the caller knows the approximate number of values that the document needs to\n store (e.g. create new value with `yyjson_mut_xxx` functions), setting a larger\n size can avoid multiple memory allocations and improve performance.\n \n @param doc The mutable document.\n @param count The desired value pool size (number of `yyjson_mut_val`).\n @return true if successful, false if size is 0 or overflow.\n */\nyyjson_api bool yyjson_mut_doc_set_val_pool_size(yyjson_mut_doc *doc,\n                                                 size_t count);\n\n/** Release the JSON document and free the memory.\n    After calling this function, the `doc` and all values from the `doc` are no\n    longer available. This function will do nothing if the `doc` is NULL.  */\nyyjson_api void yyjson_mut_doc_free(yyjson_mut_doc *doc);\n\n/** Creates and returns a new mutable JSON document, returns NULL on error.\n    If allocator is NULL, the default allocator will be used. */\nyyjson_api yyjson_mut_doc *yyjson_mut_doc_new(const yyjson_alc *alc);\n\n/** Copies and returns a new mutable document from input, returns NULL on error.\n    This makes a `deep-copy` on the immutable document.\n    If allocator is NULL, the default allocator will be used.\n    @note `imut_doc` -> `mut_doc`. */\nyyjson_api yyjson_mut_doc *yyjson_doc_mut_copy(yyjson_doc *doc,\n                                               const yyjson_alc *alc);\n\n/** Copies and returns a new mutable document from input, returns NULL on error.\n    This makes a `deep-copy` on the mutable document.\n    If allocator is NULL, the default allocator will be used.\n    @note `mut_doc` -> `mut_doc`. */\nyyjson_api yyjson_mut_doc *yyjson_mut_doc_mut_copy(yyjson_mut_doc *doc,\n                                                   const yyjson_alc *alc);\n\n/** Copies and returns a new mutable value from input, returns NULL on error.\n    This makes a `deep-copy` on the immutable value.\n    The memory was managed by mutable document.\n    @note `imut_val` -> `mut_val`. */\nyyjson_api yyjson_mut_val *yyjson_val_mut_copy(yyjson_mut_doc *doc,\n                                               yyjson_val *val);\n\n/** Copies and returns a new mutable value from input, returns NULL on error.\n    This makes a `deep-copy` on the mutable value.\n    The memory was managed by mutable document.\n    @note `mut_val` -> `mut_val`.\n    @warning This function is recursive and may cause a stack overflow\n        if the object level is too deep. */\nyyjson_api yyjson_mut_val *yyjson_mut_val_mut_copy(yyjson_mut_doc *doc,\n                                                   yyjson_mut_val *val);\n\n/** Copies and returns a new immutable document from input,\n    returns NULL on error. This makes a `deep-copy` on the mutable document.\n    The returned document should be freed with `yyjson_doc_free()`.\n    @note `mut_doc` -> `imut_doc`.\n    @warning This function is recursive and may cause a stack overflow\n        if the object level is too deep. */\nyyjson_api yyjson_doc *yyjson_mut_doc_imut_copy(yyjson_mut_doc *doc,\n                                                const yyjson_alc *alc);\n\n/** Copies and returns a new immutable document from input,\n    returns NULL on error. This makes a `deep-copy` on the mutable value.\n    The returned document should be freed with `yyjson_doc_free()`.\n    @note `mut_val` -> `imut_doc`.\n    @warning This function is recursive and may cause a stack overflow\n        if the object level is too deep. */\nyyjson_api yyjson_doc *yyjson_mut_val_imut_copy(yyjson_mut_val *val,\n                                                const yyjson_alc *alc);\n\n\n\n/*==============================================================================\n * Mutable JSON Value Type API\n *============================================================================*/\n\n/** Returns whether the JSON value is raw.\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_mut_is_raw(yyjson_mut_val *val);\n\n/** Returns whether the JSON value is `null`.\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_mut_is_null(yyjson_mut_val *val);\n\n/** Returns whether the JSON value is `true`.\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_mut_is_true(yyjson_mut_val *val);\n\n/** Returns whether the JSON value is `false`.\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_mut_is_false(yyjson_mut_val *val);\n\n/** Returns whether the JSON value is bool (true/false).\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_mut_is_bool(yyjson_mut_val *val);\n\n/** Returns whether the JSON value is unsigned integer (uint64_t).\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_mut_is_uint(yyjson_mut_val *val);\n\n/** Returns whether the JSON value is signed integer (int64_t).\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_mut_is_sint(yyjson_mut_val *val);\n\n/** Returns whether the JSON value is integer (uint64_t/int64_t).\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_mut_is_int(yyjson_mut_val *val);\n\n/** Returns whether the JSON value is real number (double).\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_mut_is_real(yyjson_mut_val *val);\n\n/** Returns whether the JSON value is number (uint/sint/real).\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_mut_is_num(yyjson_mut_val *val);\n\n/** Returns whether the JSON value is string.\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_mut_is_str(yyjson_mut_val *val);\n\n/** Returns whether the JSON value is array.\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_mut_is_arr(yyjson_mut_val *val);\n\n/** Returns whether the JSON value is object.\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_mut_is_obj(yyjson_mut_val *val);\n\n/** Returns whether the JSON value is container (array/object).\n    Returns false if `val` is NULL. */\nyyjson_api_inline bool yyjson_mut_is_ctn(yyjson_mut_val *val);\n\n\n\n/*==============================================================================\n * Mutable JSON Value Content API\n *============================================================================*/\n\n/** Returns the JSON value's type.\n    Returns `YYJSON_TYPE_NONE` if `val` is NULL. */\nyyjson_api_inline yyjson_type yyjson_mut_get_type(yyjson_mut_val *val);\n\n/** Returns the JSON value's subtype.\n    Returns `YYJSON_SUBTYPE_NONE` if `val` is NULL. */\nyyjson_api_inline yyjson_subtype yyjson_mut_get_subtype(yyjson_mut_val *val);\n\n/** Returns the JSON value's tag.\n    Returns 0 if `val` is NULL. */\nyyjson_api_inline uint8_t yyjson_mut_get_tag(yyjson_mut_val *val);\n\n/** Returns the JSON value's type description.\n    The return value should be one of these strings: \"raw\", \"null\", \"string\",\n    \"array\", \"object\", \"true\", \"false\", \"uint\", \"sint\", \"real\", \"unknown\". */\nyyjson_api_inline const char *yyjson_mut_get_type_desc(yyjson_mut_val *val);\n\n/** Returns the content if the value is raw.\n    Returns NULL if `val` is NULL or type is not raw. */\nyyjson_api_inline const char *yyjson_mut_get_raw(yyjson_mut_val *val);\n\n/** Returns the content if the value is bool.\n    Returns NULL if `val` is NULL or type is not bool. */\nyyjson_api_inline bool yyjson_mut_get_bool(yyjson_mut_val *val);\n\n/** Returns the content and cast to uint64_t.\n    Returns 0 if `val` is NULL or type is not integer(sint/uint). */\nyyjson_api_inline uint64_t yyjson_mut_get_uint(yyjson_mut_val *val);\n\n/** Returns the content and cast to int64_t.\n    Returns 0 if `val` is NULL or type is not integer(sint/uint). */\nyyjson_api_inline int64_t yyjson_mut_get_sint(yyjson_mut_val *val);\n\n/** Returns the content and cast to int.\n    Returns 0 if `val` is NULL or type is not integer(sint/uint). */\nyyjson_api_inline int yyjson_mut_get_int(yyjson_mut_val *val);\n\n/** Returns the content if the value is real number.\n    Returns 0.0 if `val` is NULL or type is not real(double). */\nyyjson_api_inline double yyjson_mut_get_real(yyjson_mut_val *val);\n\n/** Returns the content and typecast to `double` if the value is number.\n    Returns 0.0 if `val` is NULL or type is not number(uint/sint/real). */\nyyjson_api_inline double yyjson_mut_get_num(yyjson_mut_val *val);\n\n/** Returns the content if the value is string.\n    Returns NULL if `val` is NULL or type is not string. */\nyyjson_api_inline const char *yyjson_mut_get_str(yyjson_mut_val *val);\n\n/** Returns the content length (string length, array size, object size.\n    Returns 0 if `val` is NULL or type is not string/array/object. */\nyyjson_api_inline size_t yyjson_mut_get_len(yyjson_mut_val *val);\n\n/** Returns whether the JSON value is equals to a string.\n    The `str` should be a null-terminated UTF-8 string.\n    Returns false if input is NULL or type is not string. */\nyyjson_api_inline bool yyjson_mut_equals_str(yyjson_mut_val *val,\n                                             const char *str);\n\n/** Returns whether the JSON value is equals to a string.\n    The `str` should be a UTF-8 string, null-terminator is not required.\n    Returns false if input is NULL or type is not string. */\nyyjson_api_inline bool yyjson_mut_equals_strn(yyjson_mut_val *val,\n                                              const char *str, size_t len);\n\n/** Returns whether two JSON values are equal (deep compare).\n    Returns false if input is NULL.\n    @note the result may be inaccurate if object has duplicate keys.\n    @warning This function is recursive and may cause a stack overflow\n        if the object level is too deep. */\nyyjson_api_inline bool yyjson_mut_equals(yyjson_mut_val *lhs,\n                                         yyjson_mut_val *rhs);\n\n/** Set the value to raw.\n    Returns false if input is NULL.\n    @warning This function should not be used on an existing object or array. */\nyyjson_api_inline bool yyjson_mut_set_raw(yyjson_mut_val *val,\n                                          const char *raw, size_t len);\n\n/** Set the value to null.\n    Returns false if input is NULL.\n    @warning This function should not be used on an existing object or array. */\nyyjson_api_inline bool yyjson_mut_set_null(yyjson_mut_val *val);\n\n/** Set the value to bool.\n    Returns false if input is NULL.\n    @warning This function should not be used on an existing object or array. */\nyyjson_api_inline bool yyjson_mut_set_bool(yyjson_mut_val *val, bool num);\n\n/** Set the value to uint.\n    Returns false if input is NULL.\n    @warning This function should not be used on an existing object or array. */\nyyjson_api_inline bool yyjson_mut_set_uint(yyjson_mut_val *val, uint64_t num);\n\n/** Set the value to sint.\n    Returns false if input is NULL.\n    @warning This function should not be used on an existing object or array. */\nyyjson_api_inline bool yyjson_mut_set_sint(yyjson_mut_val *val, int64_t num);\n\n/** Set the value to int.\n    Returns false if input is NULL.\n    @warning This function should not be used on an existing object or array. */\nyyjson_api_inline bool yyjson_mut_set_int(yyjson_mut_val *val, int num);\n\n/** Set the value to real.\n    Returns false if input is NULL.\n    @warning This function should not be used on an existing object or array. */\nyyjson_api_inline bool yyjson_mut_set_real(yyjson_mut_val *val, double num);\n\n/** Set the value to string (null-terminated).\n    Returns false if input is NULL.\n    @warning This function should not be used on an existing object or array. */\nyyjson_api_inline bool yyjson_mut_set_str(yyjson_mut_val *val, const char *str);\n\n/** Set the value to string (with length).\n    Returns false if input is NULL.\n    @warning This function should not be used on an existing object or array. */\nyyjson_api_inline bool yyjson_mut_set_strn(yyjson_mut_val *val,\n                                           const char *str, size_t len);\n\n/** Set the value to array.\n    Returns false if input is NULL.\n    @warning This function should not be used on an existing object or array. */\nyyjson_api_inline bool yyjson_mut_set_arr(yyjson_mut_val *val);\n\n/** Set the value to array.\n    Returns false if input is NULL.\n    @warning This function should not be used on an existing object or array. */\nyyjson_api_inline bool yyjson_mut_set_obj(yyjson_mut_val *val);\n\n\n\n/*==============================================================================\n * Mutable JSON Value Creation API\n *============================================================================*/\n\n/** Creates and returns a raw value, returns NULL on error.\n    The `str` should be a null-terminated UTF-8 string.\n    \n    @warning The input string is not copied, you should keep this string\n        unmodified for the lifetime of this JSON document. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_raw(yyjson_mut_doc *doc,\n                                                 const char *str);\n\n/** Creates and returns a raw value, returns NULL on error.\n    The `str` should be a UTF-8 string, null-terminator is not required.\n    \n    @warning The input string is not copied, you should keep this string\n        unmodified for the lifetime of this JSON document. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_rawn(yyjson_mut_doc *doc,\n                                                  const char *str,\n                                                  size_t len);\n\n/** Creates and returns a raw value, returns NULL on error.\n    The `str` should be a null-terminated UTF-8 string.\n    The input string is copied and held by the document. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_rawcpy(yyjson_mut_doc *doc,\n                                                    const char *str);\n\n/** Creates and returns a raw value, returns NULL on error.\n    The `str` should be a UTF-8 string, null-terminator is not required.\n    The input string is copied and held by the document. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_rawncpy(yyjson_mut_doc *doc,\n                                                     const char *str,\n                                                     size_t len);\n\n/** Creates and returns a null value, returns NULL on error. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_null(yyjson_mut_doc *doc);\n\n/** Creates and returns a true value, returns NULL on error. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_true(yyjson_mut_doc *doc);\n\n/** Creates and returns a false value, returns NULL on error. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_false(yyjson_mut_doc *doc);\n\n/** Creates and returns a bool value, returns NULL on error. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_bool(yyjson_mut_doc *doc,\n                                                  bool val);\n\n/** Creates and returns an unsigned integer value, returns NULL on error. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_uint(yyjson_mut_doc *doc,\n                                                  uint64_t num);\n\n/** Creates and returns a signed integer value, returns NULL on error. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_sint(yyjson_mut_doc *doc,\n                                                  int64_t num);\n\n/** Creates and returns a signed integer value, returns NULL on error. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_int(yyjson_mut_doc *doc,\n                                                 int64_t num);\n\n/** Creates and returns an real number value, returns NULL on error. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_real(yyjson_mut_doc *doc,\n                                                  double num);\n\n/** Creates and returns a string value, returns NULL on error.\n    The `str` should be a null-terminated UTF-8 string.\n    @warning The input string is not copied, you should keep this string\n        unmodified for the lifetime of this JSON document. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_str(yyjson_mut_doc *doc,\n                                                 const char *str);\n\n/** Creates and returns a string value, returns NULL on error.\n    The `str` should be a UTF-8 string, null-terminator is not required.\n    @warning The input string is not copied, you should keep this string\n        unmodified for the lifetime of this JSON document. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_strn(yyjson_mut_doc *doc,\n                                                  const char *str,\n                                                  size_t len);\n\n/** Creates and returns a string value, returns NULL on error.\n    The `str` should be a null-terminated UTF-8 string.\n    The input string is copied and held by the document. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_strcpy(yyjson_mut_doc *doc,\n                                                    const char *str);\n\n/** Creates and returns a string value, returns NULL on error.\n    The `str` should be a UTF-8 string, null-terminator is not required.\n    The input string is copied and held by the document. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_strncpy(yyjson_mut_doc *doc,\n                                                     const char *str,\n                                                     size_t len);\n\n\n\n/*==============================================================================\n * Mutable JSON Array API\n *============================================================================*/\n\n/** Returns the number of elements in this array.\n    Returns 0 if `arr` is NULL or type is not array. */\nyyjson_api_inline size_t yyjson_mut_arr_size(yyjson_mut_val *arr);\n\n/** Returns the element at the specified position in this array.\n    Returns NULL if array is NULL/empty or the index is out of bounds.\n    @warning This function takes a linear search time. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_get(yyjson_mut_val *arr,\n                                                     size_t idx);\n\n/** Returns the first element of this array.\n    Returns NULL if `arr` is NULL/empty or type is not array. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_get_first(yyjson_mut_val *arr);\n\n/** Returns the last element of this array.\n    Returns NULL if `arr` is NULL/empty or type is not array. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_get_last(yyjson_mut_val *arr);\n\n\n\n/*==============================================================================\n * Mutable JSON Array Iterator API\n *============================================================================*/\n\n/**\n A mutable JSON array iterator.\n \n @warning You should not modify the array while iterating over it, but you can\n    use `yyjson_mut_arr_iter_remove()` to remove current value.\n \n @par Example\n @code\n    yyjson_mut_val *val;\n    yyjson_mut_arr_iter iter = yyjson_mut_arr_iter_with(arr);\n    while ((val = yyjson_mut_arr_iter_next(&iter))) {\n        your_func(val);\n        if (your_val_is_unused(val)) {\n            yyjson_mut_arr_iter_remove(&iter);\n        }\n    }\n @endcode\n */\ntypedef struct yyjson_mut_arr_iter {\n    size_t idx; /**< next value's index */\n    size_t max; /**< maximum index (arr.size) */\n    yyjson_mut_val *cur; /**< current value */\n    yyjson_mut_val *pre; /**< previous value */\n    yyjson_mut_val *arr; /**< the array being iterated */\n} yyjson_mut_arr_iter;\n\n/**\n Initialize an iterator for this array.\n \n @param arr The array to be iterated over.\n    If this parameter is NULL or not an array, `iter` will be set to empty.\n @param iter The iterator to be initialized.\n    If this parameter is NULL, the function will fail and return false.\n @return true if the `iter` has been successfully initialized.\n \n @note The iterator does not need to be destroyed.\n */\nyyjson_api_inline bool yyjson_mut_arr_iter_init(yyjson_mut_val *arr,\n    yyjson_mut_arr_iter *iter);\n\n/**\n Create an iterator with an array , same as `yyjson_mut_arr_iter_init()`.\n \n @param arr The array to be iterated over.\n    If this parameter is NULL or not an array, an empty iterator will returned.\n @return A new iterator for the array.\n \n @note The iterator does not need to be destroyed.\n */\nyyjson_api_inline yyjson_mut_arr_iter yyjson_mut_arr_iter_with(\n    yyjson_mut_val *arr);\n\n/**\n Returns whether the iteration has more elements.\n If `iter` is NULL, this function will return false.\n */\nyyjson_api_inline bool yyjson_mut_arr_iter_has_next(\n    yyjson_mut_arr_iter *iter);\n\n/**\n Returns the next element in the iteration, or NULL on end.\n If `iter` is NULL, this function will return NULL.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_iter_next(\n    yyjson_mut_arr_iter *iter);\n\n/**\n Removes and returns current element in the iteration.\n If `iter` is NULL, this function will return NULL.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_iter_remove(\n    yyjson_mut_arr_iter *iter);\n\n/**\n Macro for iterating over an array.\n It works like iterator, but with a more intuitive API.\n \n @warning You should not modify the array while iterating over it.\n \n @par Example\n @code\n    size_t idx, max;\n    yyjson_mut_val *val;\n    yyjson_mut_arr_foreach(arr, idx, max, val) {\n        your_func(idx, val);\n    }\n @endcode\n */\n#define yyjson_mut_arr_foreach(arr, idx, max, val) \\\n    for ((idx) = 0, \\\n        (max) = yyjson_mut_arr_size(arr), \\\n        (val) = yyjson_mut_arr_get_first(arr); \\\n        (idx) < (max); \\\n        (idx)++, \\\n        (val) = (val)->next)\n\n\n\n/*==============================================================================\n * Mutable JSON Array Creation API\n *============================================================================*/\n\n/**\n Creates and returns an empty mutable array.\n @param doc A mutable document, used for memory allocation only.\n @return The new array. NULL if input is NULL or memory allocation failed.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr(yyjson_mut_doc *doc);\n\n/**\n Creates and returns a new mutable array with the given boolean values.\n \n @param doc A mutable document, used for memory allocation only.\n    If this parameter is NULL, the function will fail and return NULL.\n @param vals A C array of boolean values.\n @param count The value count. If this value is 0, an empty array will return.\n @return The new array. NULL if input is invalid or memory allocation failed.\n \n @par Example\n @code\n    const bool vals[3] = { true, false, true };\n    yyjson_mut_val *arr = yyjson_mut_arr_with_bool(doc, vals, 3);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_bool(\n    yyjson_mut_doc *doc, const bool *vals, size_t count);\n\n/**\n Creates and returns a new mutable array with the given sint numbers.\n \n @param doc A mutable document, used for memory allocation only.\n    If this parameter is NULL, the function will fail and return NULL.\n @param vals A C array of sint numbers.\n @param count The number count. If this value is 0, an empty array will return.\n @return The new array. NULL if input is invalid or memory allocation failed.\n \n @par Example\n @code\n    const int64_t vals[3] = { -1, 0, 1 };\n    yyjson_mut_val *arr = yyjson_mut_arr_with_sint64(doc, vals, 3);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_sint(\n    yyjson_mut_doc *doc, const int64_t *vals, size_t count);\n\n/**\n Creates and returns a new mutable array with the given uint numbers.\n \n @param doc A mutable document, used for memory allocation only.\n    If this parameter is NULL, the function will fail and return NULL.\n @param vals A C array of uint numbers.\n @param count The number count. If this value is 0, an empty array will return.\n @return The new array. NULL if input is invalid or memory allocation failed.\n \n @par Example\n @code\n    const uint64_t vals[3] = { 0, 1, 0 };\n    yyjson_mut_val *arr = yyjson_mut_arr_with_uint(doc, vals, 3);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_uint(\n    yyjson_mut_doc *doc, const uint64_t *vals, size_t count);\n\n/**\n Creates and returns a new mutable array with the given real numbers.\n \n @param doc A mutable document, used for memory allocation only.\n    If this parameter is NULL, the function will fail and return NULL.\n @param vals A C array of real numbers.\n @param count The number count. If this value is 0, an empty array will return.\n @return The new array. NULL if input is invalid or memory allocation failed.\n \n @par Example\n @code\n    const double vals[3] = { 0.1, 0.2, 0.3 };\n    yyjson_mut_val *arr = yyjson_mut_arr_with_real(doc, vals, 3);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_real(\n    yyjson_mut_doc *doc, const double *vals, size_t count);\n\n/**\n Creates and returns a new mutable array with the given int8 numbers.\n \n @param doc A mutable document, used for memory allocation only.\n    If this parameter is NULL, the function will fail and return NULL.\n @param vals A C array of int8 numbers.\n @param count The number count. If this value is 0, an empty array will return.\n @return The new array. NULL if input is invalid or memory allocation failed.\n \n @par Example\n @code\n    const int8_t vals[3] = { -1, 0, 1 };\n    yyjson_mut_val *arr = yyjson_mut_arr_with_sint8(doc, vals, 3);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_sint8(\n    yyjson_mut_doc *doc, const int8_t *vals, size_t count);\n\n/**\n Creates and returns a new mutable array with the given int16 numbers.\n \n @param doc A mutable document, used for memory allocation only.\n    If this parameter is NULL, the function will fail and return NULL.\n @param vals A C array of int16 numbers.\n @param count The number count. If this value is 0, an empty array will return.\n @return The new array. NULL if input is invalid or memory allocation failed.\n \n @par Example\n @code\n    const int16_t vals[3] = { -1, 0, 1 };\n    yyjson_mut_val *arr = yyjson_mut_arr_with_sint16(doc, vals, 3);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_sint16(\n    yyjson_mut_doc *doc, const int16_t *vals, size_t count);\n\n/**\n Creates and returns a new mutable array with the given int32 numbers.\n \n @param doc A mutable document, used for memory allocation only.\n    If this parameter is NULL, the function will fail and return NULL.\n @param vals A C array of int32 numbers.\n @param count The number count. If this value is 0, an empty array will return.\n @return The new array. NULL if input is invalid or memory allocation failed.\n \n @par Example\n @code\n    const int32_t vals[3] = { -1, 0, 1 };\n    yyjson_mut_val *arr = yyjson_mut_arr_with_sint32(doc, vals, 3);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_sint32(\n    yyjson_mut_doc *doc, const int32_t *vals, size_t count);\n\n/**\n Creates and returns a new mutable array with the given int64 numbers.\n \n @param doc A mutable document, used for memory allocation only.\n    If this parameter is NULL, the function will fail and return NULL.\n @param vals A C array of int64 numbers.\n @param count The number count. If this value is 0, an empty array will return.\n @return The new array. NULL if input is invalid or memory allocation failed.\n \n @par Example\n @code\n    const int64_t vals[3] = { -1, 0, 1 };\n    yyjson_mut_val *arr = yyjson_mut_arr_with_sint64(doc, vals, 3);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_sint64(\n    yyjson_mut_doc *doc, const int64_t *vals, size_t count);\n\n/**\n Creates and returns a new mutable array with the given uint8 numbers.\n \n @param doc A mutable document, used for memory allocation only.\n    If this parameter is NULL, the function will fail and return NULL.\n @param vals A C array of uint8 numbers.\n @param count The number count. If this value is 0, an empty array will return.\n @return The new array. NULL if input is invalid or memory allocation failed.\n \n @par Example\n @code\n    const uint8_t vals[3] = { 0, 1, 0 };\n    yyjson_mut_val *arr = yyjson_mut_arr_with_uint8(doc, vals, 3);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_uint8(\n    yyjson_mut_doc *doc, const uint8_t *vals, size_t count);\n\n/**\n Creates and returns a new mutable array with the given uint16 numbers.\n \n @param doc A mutable document, used for memory allocation only.\n    If this parameter is NULL, the function will fail and return NULL.\n @param vals A C array of uint16 numbers.\n @param count The number count. If this value is 0, an empty array will return.\n @return The new array. NULL if input is invalid or memory allocation failed.\n \n @par Example\n @code\n    const uint16_t vals[3] = { 0, 1, 0 };\n    yyjson_mut_val *arr = yyjson_mut_arr_with_uint16(doc, vals, 3);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_uint16(\n    yyjson_mut_doc *doc, const uint16_t *vals, size_t count);\n\n/**\n Creates and returns a new mutable array with the given uint32 numbers.\n \n @param doc A mutable document, used for memory allocation only.\n    If this parameter is NULL, the function will fail and return NULL.\n @param vals A C array of uint32 numbers.\n @param count The number count. If this value is 0, an empty array will return.\n @return The new array. NULL if input is invalid or memory allocation failed.\n \n @par Example\n @code\n    const uint32_t vals[3] = { 0, 1, 0 };\n    yyjson_mut_val *arr = yyjson_mut_arr_with_uint32(doc, vals, 3);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_uint32(\n    yyjson_mut_doc *doc, const uint32_t *vals, size_t count);\n\n/**\n Creates and returns a new mutable array with the given uint64 numbers.\n \n @param doc A mutable document, used for memory allocation only.\n    If this parameter is NULL, the function will fail and return NULL.\n @param vals A C array of uint64 numbers.\n @param count The number count. If this value is 0, an empty array will return.\n @return The new array. NULL if input is invalid or memory allocation failed.\n \n @par Example\n @code\n     const uint64_t vals[3] = { 0, 1, 0 };\n     yyjson_mut_val *arr = yyjson_mut_arr_with_uint64(doc, vals, 3);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_uint64(\n    yyjson_mut_doc *doc, const uint64_t *vals, size_t count);\n\n/**\n Creates and returns a new mutable array with the given float numbers.\n \n @param doc A mutable document, used for memory allocation only.\n    If this parameter is NULL, the function will fail and return NULL.\n @param vals A C array of float numbers.\n @param count The number count. If this value is 0, an empty array will return.\n @return The new array. NULL if input is invalid or memory allocation failed.\n \n @par Example\n @code\n    const float vals[3] = { -1.0f, 0.0f, 1.0f };\n    yyjson_mut_val *arr = yyjson_mut_arr_with_float(doc, vals, 3);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_float(\n    yyjson_mut_doc *doc, const float *vals, size_t count);\n\n/**\n Creates and returns a new mutable array with the given double numbers.\n \n @param doc A mutable document, used for memory allocation only.\n    If this parameter is NULL, the function will fail and return NULL.\n @param vals A C array of double numbers.\n @param count The number count. If this value is 0, an empty array will return.\n @return The new array. NULL if input is invalid or memory allocation failed.\n \n @par Example\n @code\n    const double vals[3] = { -1.0, 0.0, 1.0 };\n    yyjson_mut_val *arr = yyjson_mut_arr_with_double(doc, vals, 3);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_double(\n    yyjson_mut_doc *doc, const double *vals, size_t count);\n\n/**\n Creates and returns a new mutable array with the given strings, these strings\n will not be copied.\n \n @param doc A mutable document, used for memory allocation only.\n    If this parameter is NULL, the function will fail and return NULL.\n @param vals A C array of UTF-8 null-terminator strings.\n    If this array contains NULL, the function will fail and return NULL.\n @param count The number of values in `vals`.\n    If this value is 0, an empty array will return.\n @return The new array. NULL if input is invalid or memory allocation failed.\n \n @warning The input strings are not copied, you should keep these strings\n    unmodified for the lifetime of this JSON document. If these strings will be\n    modified, you should use `yyjson_mut_arr_with_strcpy()` instead.\n \n @par Example\n @code\n    const char *vals[3] = { \"a\", \"b\", \"c\" };\n    yyjson_mut_val *arr = yyjson_mut_arr_with_str(doc, vals, 3);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_str(\n    yyjson_mut_doc *doc, const char **vals, size_t count);\n\n/**\n Creates and returns a new mutable array with the given strings and string\n lengths, these strings will not be copied.\n \n @param doc A mutable document, used for memory allocation only.\n    If this parameter is NULL, the function will fail and return NULL.\n @param vals A C array of UTF-8 strings, null-terminator is not required.\n    If this array contains NULL, the function will fail and return NULL.\n @param lens A C array of string lengths, in bytes.\n @param count The number of strings in `vals`.\n    If this value is 0, an empty array will return.\n @return The new array. NULL if input is invalid or memory allocation failed.\n \n @warning The input strings are not copied, you should keep these strings\n    unmodified for the lifetime of this JSON document. If these strings will be\n    modified, you should use `yyjson_mut_arr_with_strncpy()` instead.\n \n @par Example\n @code\n    const char *vals[3] = { \"a\", \"bb\", \"c\" };\n    const size_t lens[3] = { 1, 2, 1 };\n    yyjson_mut_val *arr = yyjson_mut_arr_with_strn(doc, vals, lens, 3);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_strn(\n    yyjson_mut_doc *doc, const char **vals, const size_t *lens, size_t count);\n\n/**\n Creates and returns a new mutable array with the given strings, these strings\n will be copied.\n \n @param doc A mutable document, used for memory allocation only.\n    If this parameter is NULL, the function will fail and return NULL.\n @param vals A C array of UTF-8 null-terminator strings.\n    If this array contains NULL, the function will fail and return NULL.\n @param count The number of values in `vals`.\n    If this value is 0, an empty array will return.\n @return The new array. NULL if input is invalid or memory allocation failed.\n \n @par Example\n @code\n    const char *vals[3] = { \"a\", \"b\", \"c\" };\n    yyjson_mut_val *arr = yyjson_mut_arr_with_strcpy(doc, vals, 3);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_strcpy(\n    yyjson_mut_doc *doc, const char **vals, size_t count);\n\n/**\n Creates and returns a new mutable array with the given strings and string\n lengths, these strings will be copied.\n \n @param doc A mutable document, used for memory allocation only.\n    If this parameter is NULL, the function will fail and return NULL.\n @param vals A C array of UTF-8 strings, null-terminator is not required.\n    If this array contains NULL, the function will fail and return NULL.\n @param lens A C array of string lengths, in bytes.\n @param count The number of strings in `vals`.\n    If this value is 0, an empty array will return.\n @return The new array. NULL if input is invalid or memory allocation failed.\n \n @par Example\n @code\n    const char *vals[3] = { \"a\", \"bb\", \"c\" };\n    const size_t lens[3] = { 1, 2, 1 };\n    yyjson_mut_val *arr = yyjson_mut_arr_with_strn(doc, vals, lens, 3);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_strncpy(\n    yyjson_mut_doc *doc, const char **vals, const size_t *lens, size_t count);\n\n\n\n/*==============================================================================\n * Mutable JSON Array Modification API\n *============================================================================*/\n\n/**\n Inserts a value into an array at a given index.\n @param arr The array to which the value is to be inserted.\n    Returns false if it is NULL or not an array.\n @param val The value to be inserted. Returns false if it is NULL.\n @param idx The index to which to insert the new value.\n    Returns false if the index is out of range.\n @return Whether successful.\n @warning This function takes a linear search time.\n */\nyyjson_api_inline bool yyjson_mut_arr_insert(yyjson_mut_val *arr,\n                                             yyjson_mut_val *val, size_t idx);\n\n/**\n Inserts a value at the end of the array.\n @param arr The array to which the value is to be inserted.\n    Returns false if it is NULL or not an array.\n @param val The value to be inserted. Returns false if it is NULL.\n @return Whether successful.\n */\nyyjson_api_inline bool yyjson_mut_arr_append(yyjson_mut_val *arr,\n                                             yyjson_mut_val *val);\n\n/**\n Inserts a value at the head of the array.\n @param arr The array to which the value is to be inserted.\n    Returns false if it is NULL or not an array.\n @param val The value to be inserted. Returns false if it is NULL.\n @return    Whether successful.\n */\nyyjson_api_inline bool yyjson_mut_arr_prepend(yyjson_mut_val *arr,\n                                              yyjson_mut_val *val);\n\n/**\n Replaces a value at index and returns old value.\n @param arr The array to which the value is to be replaced.\n    Returns false if it is NULL or not an array.\n @param idx The index to which to replace the value.\n    Returns false if the index is out of range.\n @param val The new value to replace. Returns false if it is NULL.\n @return Old value, or NULL on error.\n @warning This function takes a linear search time.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_replace(yyjson_mut_val *arr,\n                                                         size_t idx,\n                                                         yyjson_mut_val *val);\n\n/**\n Removes and returns a value at index.\n @param arr The array from which the value is to be removed.\n    Returns false if it is NULL or not an array.\n @param idx The index from which to remove the value.\n    Returns false if the index is out of range.\n @return Old value, or NULL on error.\n @warning This function takes a linear search time.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_remove(yyjson_mut_val *arr,\n                                                        size_t idx);\n\n/**\n Removes and returns the first value in this array.\n @param arr The array from which the value is to be removed.\n    Returns false if it is NULL or not an array.\n @return The first value, or NULL on error.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_remove_first(\n    yyjson_mut_val *arr);\n\n/**\n Removes and returns the last value in this array.\n @param arr The array from which the value is to be removed.\n    Returns false if it is NULL or not an array.\n @return The last value, or NULL on error.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_remove_last(\n    yyjson_mut_val *arr);\n\n/**\n Removes all values within a specified range in the array.\n @param arr The array from which the value is to be removed.\n    Returns false if it is NULL or not an array.\n @param idx The start index of the range (0 is the first).\n @param len The number of items in the range (can be 0).\n @return Whether successful.\n @warning This function takes a linear search time.\n */\nyyjson_api_inline bool yyjson_mut_arr_remove_range(yyjson_mut_val *arr,\n                                                   size_t idx, size_t len);\n\n/**\n Removes all values in this array.\n @param arr The array from which all of the values are to be removed.\n    Returns false if it is NULL or not an array.\n @return Whether successful.\n */\nyyjson_api_inline bool yyjson_mut_arr_clear(yyjson_mut_val *arr);\n\n/**\n Rotates values in this array for the given number of times.\n For example: `[1,2,3,4,5]` rotate 2 is `[3,4,5,1,2]`.\n @param arr The array to be rotated.\n @param idx Index (or times) to rotate.\n @warning This function takes a linear search time.\n */\nyyjson_api_inline bool yyjson_mut_arr_rotate(yyjson_mut_val *arr,\n                                             size_t idx);\n\n\n\n/*==============================================================================\n * Mutable JSON Array Modification Convenience API\n *============================================================================*/\n\n/**\n Adds a value at the end of the array.\n @param arr The array to which the value is to be inserted.\n    Returns false if it is NULL or not an array.\n @param val The value to be inserted. Returns false if it is NULL.\n @return Whether successful.\n */\nyyjson_api_inline bool yyjson_mut_arr_add_val(yyjson_mut_val *arr,\n                                              yyjson_mut_val *val);\n\n/**\n Adds a `null` value at the end of the array.\n @param doc The `doc` is only used for memory allocation.\n @param arr The array to which the value is to be inserted.\n    Returns false if it is NULL or not an array.\n @return Whether successful.\n */\nyyjson_api_inline bool yyjson_mut_arr_add_null(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *arr);\n\n/**\n Adds a `true` value at the end of the array.\n @param doc The `doc` is only used for memory allocation.\n @param arr The array to which the value is to be inserted.\n    Returns false if it is NULL or not an array.\n @return Whether successful.\n */\nyyjson_api_inline bool yyjson_mut_arr_add_true(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *arr);\n\n/**\n Adds a `false` value at the end of the array.\n @param doc The `doc` is only used for memory allocation.\n @param arr The array to which the value is to be inserted.\n    Returns false if it is NULL or not an array.\n @return Whether successful.\n */\nyyjson_api_inline bool yyjson_mut_arr_add_false(yyjson_mut_doc *doc,\n                                                yyjson_mut_val *arr);\n\n/**\n Adds a bool value at the end of the array.\n @param doc The `doc` is only used for memory allocation.\n @param arr The array to which the value is to be inserted.\n    Returns false if it is NULL or not an array.\n @param val The bool value to be added.\n @return Whether successful.\n */\nyyjson_api_inline bool yyjson_mut_arr_add_bool(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *arr,\n                                               bool val);\n\n/**\n Adds an unsigned integer value at the end of the array.\n @param doc The `doc` is only used for memory allocation.\n @param arr The array to which the value is to be inserted.\n    Returns false if it is NULL or not an array.\n @param num The number to be added.\n @return Whether successful.\n */\nyyjson_api_inline bool yyjson_mut_arr_add_uint(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *arr,\n                                               uint64_t num);\n\n/**\n Adds a signed integer value at the end of the array.\n @param doc The `doc` is only used for memory allocation.\n @param arr The array to which the value is to be inserted.\n    Returns false if it is NULL or not an array.\n @param num The number to be added.\n @return Whether successful.\n */\nyyjson_api_inline bool yyjson_mut_arr_add_sint(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *arr,\n                                               int64_t num);\n\n/**\n Adds a integer value at the end of the array.\n @param doc The `doc` is only used for memory allocation.\n @param arr The array to which the value is to be inserted.\n    Returns false if it is NULL or not an array.\n @param num The number to be added.\n @return Whether successful.\n */\nyyjson_api_inline bool yyjson_mut_arr_add_int(yyjson_mut_doc *doc,\n                                              yyjson_mut_val *arr,\n                                              int64_t num);\n\n/**\n Adds a double value at the end of the array.\n @param doc The `doc` is only used for memory allocation.\n @param arr The array to which the value is to be inserted.\n    Returns false if it is NULL or not an array.\n @param num The number to be added.\n @return Whether successful.\n */\nyyjson_api_inline bool yyjson_mut_arr_add_real(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *arr,\n                                               double num);\n\n/**\n Adds a string value at the end of the array (no copy).\n @param doc The `doc` is only used for memory allocation.\n @param arr The array to which the value is to be inserted.\n    Returns false if it is NULL or not an array.\n @param str A null-terminated UTF-8 string.\n @return Whether successful.\n @warning The input string is not copied, you should keep this string unmodified\n    for the lifetime of this JSON document.\n */\nyyjson_api_inline bool yyjson_mut_arr_add_str(yyjson_mut_doc *doc,\n                                              yyjson_mut_val *arr,\n                                              const char *str);\n\n/**\n Adds a string value at the end of the array (no copy).\n @param doc The `doc` is only used for memory allocation.\n @param arr The array to which the value is to be inserted.\n    Returns false if it is NULL or not an array.\n @param str A UTF-8 string, null-terminator is not required.\n @param len The length of the string, in bytes.\n @return Whether successful.\n @warning The input string is not copied, you should keep this string unmodified\n    for the lifetime of this JSON document.\n */\nyyjson_api_inline bool yyjson_mut_arr_add_strn(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *arr,\n                                               const char *str,\n                                               size_t len);\n\n/**\n Adds a string value at the end of the array (copied).\n @param doc The `doc` is only used for memory allocation.\n @param arr The array to which the value is to be inserted.\n    Returns false if it is NULL or not an array.\n @param str A null-terminated UTF-8 string.\n @return Whether successful.\n */\nyyjson_api_inline bool yyjson_mut_arr_add_strcpy(yyjson_mut_doc *doc,\n                                                 yyjson_mut_val *arr,\n                                                 const char *str);\n\n/**\n Adds a string value at the end of the array (copied).\n @param doc The `doc` is only used for memory allocation.\n @param arr The array to which the value is to be inserted.\n    Returns false if it is NULL or not an array.\n @param str A UTF-8 string, null-terminator is not required.\n @param len The length of the string, in bytes.\n @return Whether successful.\n */\nyyjson_api_inline bool yyjson_mut_arr_add_strncpy(yyjson_mut_doc *doc,\n                                                  yyjson_mut_val *arr,\n                                                  const char *str,\n                                                  size_t len);\n\n/**\n Creates and adds a new array at the end of the array.\n @param doc The `doc` is only used for memory allocation.\n @param arr The array to which the value is to be inserted.\n    Returns false if it is NULL or not an array.\n @return The new array, or NULL on error.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_add_arr(yyjson_mut_doc *doc,\n                                                         yyjson_mut_val *arr);\n\n/**\n Creates and adds a new object at the end of the array.\n @param doc The `doc` is only used for memory allocation.\n @param arr The array to which the value is to be inserted.\n    Returns false if it is NULL or not an array.\n @return The new object, or NULL on error.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_add_obj(yyjson_mut_doc *doc,\n                                                         yyjson_mut_val *arr);\n\n\n\n/*==============================================================================\n * Mutable JSON Object API\n *============================================================================*/\n\n/** Returns the number of key-value pairs in this object.\n    Returns 0 if `obj` is NULL or type is not object. */\nyyjson_api_inline size_t yyjson_mut_obj_size(yyjson_mut_val *obj);\n\n/** Returns the value to which the specified key is mapped.\n    Returns NULL if this object contains no mapping for the key.\n    Returns NULL if `obj/key` is NULL, or type is not object.\n    \n    The `key` should be a null-terminated UTF-8 string.\n    \n    @warning This function takes a linear search time. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_get(yyjson_mut_val *obj,\n                                                     const char *key);\n\n/** Returns the value to which the specified key is mapped.\n    Returns NULL if this object contains no mapping for the key.\n    Returns NULL if `obj/key` is NULL, or type is not object.\n    \n    The `key` should be a UTF-8 string, null-terminator is not required.\n    The `key_len` should be the length of the key, in bytes.\n    \n    @warning This function takes a linear search time. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_getn(yyjson_mut_val *obj,\n                                                      const char *key,\n                                                      size_t key_len);\n\n\n\n/*==============================================================================\n * Mutable JSON Object Iterator API\n *============================================================================*/\n\n/**\n A mutable JSON object iterator.\n \n @warning You should not modify the object while iterating over it, but you can\n    use `yyjson_mut_obj_iter_remove()` to remove current value.\n \n @par Example\n @code\n    yyjson_mut_val *key, *val;\n    yyjson_mut_obj_iter iter = yyjson_mut_obj_iter_with(obj);\n    while ((key = yyjson_mut_obj_iter_next(&iter))) {\n        val = yyjson_mut_obj_iter_get_val(key);\n        your_func(key, val);\n        if (your_val_is_unused(key, val)) {\n            yyjson_mut_obj_iter_remove(&iter);\n        }\n    }\n @endcode\n \n If the ordering of the keys is known at compile-time, you can use this method\n to speed up value lookups:\n @code\n    // {\"k1\":1, \"k2\": 3, \"k3\": 3}\n    yyjson_mut_val *key, *val;\n    yyjson_mut_obj_iter iter = yyjson_mut_obj_iter_with(obj);\n    yyjson_mut_val *v1 = yyjson_mut_obj_iter_get(&iter, \"k1\");\n    yyjson_mut_val *v3 = yyjson_mut_obj_iter_get(&iter, \"k3\");\n @endcode\n @see `yyjson_mut_obj_iter_get()` and `yyjson_mut_obj_iter_getn()`\n */\ntypedef struct yyjson_mut_obj_iter {\n    size_t idx; /**< next key's index */\n    size_t max; /**< maximum key index (obj.size) */\n    yyjson_mut_val *cur; /**< current key */\n    yyjson_mut_val *pre; /**< previous key */\n    yyjson_mut_val *obj; /**< the object being iterated */\n} yyjson_mut_obj_iter;\n\n/**\n Initialize an iterator for this object.\n \n @param obj The object to be iterated over.\n    If this parameter is NULL or not an array, `iter` will be set to empty.\n @param iter The iterator to be initialized.\n    If this parameter is NULL, the function will fail and return false.\n @return true if the `iter` has been successfully initialized.\n \n @note The iterator does not need to be destroyed.\n */\nyyjson_api_inline bool yyjson_mut_obj_iter_init(yyjson_mut_val *obj,\n    yyjson_mut_obj_iter *iter);\n\n/**\n Create an iterator with an object, same as `yyjson_obj_iter_init()`.\n \n @param obj The object to be iterated over.\n    If this parameter is NULL or not an object, an empty iterator will returned.\n @return A new iterator for the object.\n \n @note The iterator does not need to be destroyed.\n */\nyyjson_api_inline yyjson_mut_obj_iter yyjson_mut_obj_iter_with(\n    yyjson_mut_val *obj);\n\n/**\n Returns whether the iteration has more elements.\n If `iter` is NULL, this function will return false.\n */\nyyjson_api_inline bool yyjson_mut_obj_iter_has_next(\n    yyjson_mut_obj_iter *iter);\n\n/**\n Returns the next key in the iteration, or NULL on end.\n If `iter` is NULL, this function will return NULL.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_iter_next(\n    yyjson_mut_obj_iter *iter);\n\n/**\n Returns the value for key inside the iteration.\n If `iter` is NULL, this function will return NULL.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_iter_get_val(\n    yyjson_mut_val *key);\n\n/**\n Removes current key-value pair in the iteration, returns the removed value.\n If `iter` is NULL, this function will return NULL.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_iter_remove(\n    yyjson_mut_obj_iter *iter);\n\n/**\n Iterates to a specified key and returns the value.\n \n This function does the same thing as `yyjson_mut_obj_get()`, but is much faster\n if the ordering of the keys is known at compile-time and you are using the same\n order to look up the values. If the key exists in this object, then the\n iterator will stop at the next key, otherwise the iterator will not change and\n NULL is returned.\n \n @param iter The object iterator, should not be NULL.\n @param key The key, should be a UTF-8 string with null-terminator.\n @return The value to which the specified key is mapped.\n    NULL if this object contains no mapping for the key or input is invalid.\n \n @warning This function takes a linear search time if the key is not nearby.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_iter_get(\n    yyjson_mut_obj_iter *iter, const char *key);\n\n/**\n Iterates to a specified key and returns the value.\n \n This function does the same thing as `yyjson_mut_obj_getn()` but is much faster\n if the ordering of the keys is known at compile-time and you are using the same\n order to look up the values. If the key exists in this object, then the\n iterator will stop at the next key, otherwise the iterator will not change and\n NULL is returned.\n \n @param iter The object iterator, should not be NULL.\n @param key The key, should be a UTF-8 string, null-terminator is not required.\n @param key_len The the length of `key`, in bytes.\n @return The value to which the specified key is mapped.\n    NULL if this object contains no mapping for the key or input is invalid.\n \n @warning This function takes a linear search time if the key is not nearby.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_iter_getn(\n    yyjson_mut_obj_iter *iter, const char *key, size_t key_len);\n\n/**\n Macro for iterating over an object.\n It works like iterator, but with a more intuitive API.\n \n @warning You should not modify the object while iterating over it.\n \n @par Example\n @code\n    size_t idx, max;\n    yyjson_val *key, *val;\n    yyjson_obj_foreach(obj, idx, max, key, val) {\n        your_func(key, val);\n    }\n @endcode\n */\n#define yyjson_mut_obj_foreach(obj, idx, max, key, val) \\\n    for ((idx) = 0, \\\n        (max) = yyjson_mut_obj_size(obj), \\\n        (key) = (max) ? ((yyjson_mut_val *)(obj)->uni.ptr)->next->next : NULL, \\\n        (val) = (key) ? (key)->next : NULL; \\\n        (idx) < (max); \\\n        (idx)++, \\\n        (key) = (val)->next, \\\n        (val) = (key)->next)\n\n\n\n/*==============================================================================\n * Mutable JSON Object Creation API\n *============================================================================*/\n\n/** Creates and returns a mutable object, returns NULL on error. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj(yyjson_mut_doc *doc);\n\n/**\n Creates and returns a mutable object with keys and values, returns NULL on\n error. The keys and values are not copied. The strings should be a\n null-terminated UTF-8 string.\n \n @warning The input string is not copied, you should keep this string\n    unmodified for the lifetime of this JSON document.\n \n @par Example\n @code\n    const char *keys[2] = { \"id\", \"name\" };\n    const char *vals[2] = { \"01\", \"Harry\" };\n    yyjson_mut_val *obj = yyjson_mut_obj_with_str(doc, keys, vals, 2);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_with_str(yyjson_mut_doc *doc,\n                                                          const char **keys,\n                                                          const char **vals,\n                                                          size_t count);\n\n/**\n Creates and returns a mutable object with key-value pairs and pair count,\n returns NULL on error. The keys and values are not copied. The strings should\n be a null-terminated UTF-8 string.\n \n @warning The input string is not copied, you should keep this string\n    unmodified for the lifetime of this JSON document.\n \n @par Example\n @code\n    const char *kv_pairs[4] = { \"id\", \"01\", \"name\", \"Harry\" };\n    yyjson_mut_val *obj = yyjson_mut_obj_with_kv(doc, kv_pairs, 2);\n @endcode\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_with_kv(yyjson_mut_doc *doc,\n                                                         const char **kv_pairs,\n                                                         size_t pair_count);\n\n\n\n/*==============================================================================\n * Mutable JSON Object Modification API\n *============================================================================*/\n\n/**\n Adds a key-value pair at the end of the object.\n This function allows duplicated key in one object.\n @param obj The object to which the new key-value pair is to be added.\n @param key The key, should be a string which is created by `yyjson_mut_str()`,\n    `yyjson_mut_strn()`, `yyjson_mut_strcpy()` or `yyjson_mut_strncpy()`.\n @param val The value to add to the object.\n @return Whether successful.\n */\nyyjson_api_inline bool yyjson_mut_obj_add(yyjson_mut_val *obj,\n                                          yyjson_mut_val *key,\n                                          yyjson_mut_val *val);\n/**\n Sets a key-value pair at the end of the object.\n This function may remove all key-value pairs for the given key before add.\n @param obj The object to which the new key-value pair is to be added.\n @param key The key, should be a string which is created by `yyjson_mut_str()`,\n    `yyjson_mut_strn()`, `yyjson_mut_strcpy()` or `yyjson_mut_strncpy()`.\n @param val The value to add to the object. If this value is null, the behavior\n    is same as `yyjson_mut_obj_remove()`.\n @return Whether successful.\n */\nyyjson_api_inline bool yyjson_mut_obj_put(yyjson_mut_val *obj,\n                                          yyjson_mut_val *key,\n                                          yyjson_mut_val *val);\n\n/**\n Inserts a key-value pair to the object at the given position.\n This function allows duplicated key in one object.\n @param obj The object to which the new key-value pair is to be added.\n @param key The key, should be a string which is created by `yyjson_mut_str()`,\n    `yyjson_mut_strn()`, `yyjson_mut_strcpy()` or `yyjson_mut_strncpy()`.\n @param val The value to add to the object.\n @param idx The index to which to insert the new pair.\n @return Whether successful.\n */\nyyjson_api_inline bool yyjson_mut_obj_insert(yyjson_mut_val *obj,\n                                             yyjson_mut_val *key,\n                                             yyjson_mut_val *val,\n                                             size_t idx);\n\n/**\n Removes all key-value pair from the object with given key.\n @param obj The object from which the key-value pair is to be removed.\n @param key The key, should be a string value.\n @return The first matched value, or NULL if no matched value.\n @warning This function takes a linear search time.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_remove(yyjson_mut_val *obj,\n                                                        yyjson_mut_val *key);\n\n/**\n Removes all key-value pair from the object with given key.\n @param obj The object from which the key-value pair is to be removed.\n @param key The key, should be a UTF-8 string with null-terminator.\n @return The first matched value, or NULL if no matched value.\n @warning This function takes a linear search time.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_remove_key(\n    yyjson_mut_val *obj, const char *key);\n\n/**\n Removes all key-value pair from the object with given key.\n @param obj The object from which the key-value pair is to be removed.\n @param key The key, should be a UTF-8 string, null-terminator is not required.\n @param key_len The length of the key.\n @return The first matched value, or NULL if no matched value.\n @warning This function takes a linear search time.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_remove_keyn(\n    yyjson_mut_val *obj, const char *key, size_t key_len);\n\n/**\n Removes all key-value pairs in this object.\n @param obj The object from which all of the values are to be removed.\n @return Whether successful.\n */\nyyjson_api_inline bool yyjson_mut_obj_clear(yyjson_mut_val *obj);\n\n/**\n Replaces value from the object with given key.\n If the key is not exist, or the value is NULL, it will fail.\n @param obj The object to which the value is to be replaced.\n @param key The key, should be a string value.\n @param val The value to replace into the object.\n @return Whether successful.\n @warning This function takes a linear search time.\n */\nyyjson_api_inline bool yyjson_mut_obj_replace(yyjson_mut_val *obj,\n                                              yyjson_mut_val *key,\n                                              yyjson_mut_val *val);\n\n/**\n Rotates key-value pairs in the object for the given number of times.\n For example: `{\"a\":1,\"b\":2,\"c\":3,\"d\":4}` rotate 1 is\n `{\"b\":2,\"c\":3,\"d\":4,\"a\":1}`.\n @param obj The object to be rotated.\n @param idx Index (or times) to rotate.\n @return Whether successful.\n @warning This function takes a linear search time.\n */\nyyjson_api_inline bool yyjson_mut_obj_rotate(yyjson_mut_val *obj,\n                                             size_t idx);\n\n\n\n/*==============================================================================\n * Mutable JSON Object Modification Convenience API\n *============================================================================*/\n\n/** Adds a `null` value at the end of the object.\n    The `key` should be a null-terminated UTF-8 string.\n    This function allows duplicated key in one object.\n    \n    @warning The key string is not copied, you should keep the string\n        unmodified for the lifetime of this JSON document. */\nyyjson_api_inline bool yyjson_mut_obj_add_null(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *obj,\n                                               const char *key);\n\n/** Adds a `true` value at the end of the object.\n    The `key` should be a null-terminated UTF-8 string.\n    This function allows duplicated key in one object.\n    \n    @warning The key string is not copied, you should keep the string\n        unmodified for the lifetime of this JSON document. */\nyyjson_api_inline bool yyjson_mut_obj_add_true(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *obj,\n                                               const char *key);\n\n/** Adds a `false` value at the end of the object.\n    The `key` should be a null-terminated UTF-8 string.\n    This function allows duplicated key in one object.\n    \n    @warning The key string is not copied, you should keep the string\n        unmodified for the lifetime of this JSON document. */\nyyjson_api_inline bool yyjson_mut_obj_add_false(yyjson_mut_doc *doc,\n                                                yyjson_mut_val *obj,\n                                                const char *key);\n\n/** Adds a bool value at the end of the object.\n    The `key` should be a null-terminated UTF-8 string.\n    This function allows duplicated key in one object.\n    \n    @warning The key string is not copied, you should keep the string\n        unmodified for the lifetime of this JSON document. */\nyyjson_api_inline bool yyjson_mut_obj_add_bool(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *obj,\n                                               const char *key, bool val);\n\n/** Adds an unsigned integer value at the end of the object.\n    The `key` should be a null-terminated UTF-8 string.\n    This function allows duplicated key in one object.\n    \n    @warning The key string is not copied, you should keep the string\n        unmodified for the lifetime of this JSON document. */\nyyjson_api_inline bool yyjson_mut_obj_add_uint(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *obj,\n                                               const char *key, uint64_t val);\n\n/** Adds a signed integer value at the end of the object.\n    The `key` should be a null-terminated UTF-8 string.\n    This function allows duplicated key in one object.\n    \n    @warning The key string is not copied, you should keep the string\n        unmodified for the lifetime of this JSON document. */\nyyjson_api_inline bool yyjson_mut_obj_add_sint(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *obj,\n                                               const char *key, int64_t val);\n\n/** Adds an int value at the end of the object.\n    The `key` should be a null-terminated UTF-8 string.\n    This function allows duplicated key in one object.\n    \n    @warning The key string is not copied, you should keep the string\n        unmodified for the lifetime of this JSON document. */\nyyjson_api_inline bool yyjson_mut_obj_add_int(yyjson_mut_doc *doc,\n                                              yyjson_mut_val *obj,\n                                              const char *key, int64_t val);\n\n/** Adds a double value at the end of the object.\n    The `key` should be a null-terminated UTF-8 string.\n    This function allows duplicated key in one object.\n    \n    @warning The key string is not copied, you should keep the string\n        unmodified for the lifetime of this JSON document. */\nyyjson_api_inline bool yyjson_mut_obj_add_real(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *obj,\n                                               const char *key, double val);\n\n/** Adds a string value at the end of the object.\n    The `key` and `val` should be null-terminated UTF-8 strings.\n    This function allows duplicated key in one object.\n    \n    @warning The key/value strings are not copied, you should keep these strings\n        unmodified for the lifetime of this JSON document. */\nyyjson_api_inline bool yyjson_mut_obj_add_str(yyjson_mut_doc *doc,\n                                              yyjson_mut_val *obj,\n                                              const char *key, const char *val);\n\n/** Adds a string value at the end of the object.\n    The `key` should be a null-terminated UTF-8 string.\n    The `val` should be a UTF-8 string, null-terminator is not required.\n    The `len` should be the length of the `val`, in bytes.\n    This function allows duplicated key in one object.\n    \n    @warning The key/value strings are not copied, you should keep these strings\n        unmodified for the lifetime of this JSON document. */\nyyjson_api_inline bool yyjson_mut_obj_add_strn(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *obj,\n                                               const char *key,\n                                               const char *val, size_t len);\n\n/** Adds a string value at the end of the object.\n    The `key` and `val` should be null-terminated UTF-8 strings.\n    The value string is copied.\n    This function allows duplicated key in one object.\n    \n    @warning The key string is not copied, you should keep the string\n        unmodified for the lifetime of this JSON document. */\nyyjson_api_inline bool yyjson_mut_obj_add_strcpy(yyjson_mut_doc *doc,\n                                                 yyjson_mut_val *obj,\n                                                 const char *key,\n                                                 const char *val);\n\n/** Adds a string value at the end of the object.\n    The `key` should be a null-terminated UTF-8 string.\n    The `val` should be a UTF-8 string, null-terminator is not required.\n    The `len` should be the length of the `val`, in bytes.\n    This function allows duplicated key in one object.\n    \n    @warning The key strings are not copied, you should keep these strings\n        unmodified for the lifetime of this JSON document. */\nyyjson_api_inline bool yyjson_mut_obj_add_strncpy(yyjson_mut_doc *doc,\n                                                  yyjson_mut_val *obj,\n                                                  const char *key,\n                                                  const char *val, size_t len);\n\n/**\n Creates and adds a new array to the target object.\n The `key` should be a null-terminated UTF-8 string.\n This function allows duplicated key in one object.\n \n @warning The key string is not copied, you should keep these strings\n          unmodified for the lifetime of this JSON document.\n @return The new array, or NULL on error.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_add_arr(yyjson_mut_doc *doc,\n                                                         yyjson_mut_val *obj,\n                                                         const char *key);\n\n/**\n Creates and adds a new object to the target object.\n The `key` should be a null-terminated UTF-8 string.\n This function allows duplicated key in one object.\n \n @warning The key string is not copied, you should keep these strings\n          unmodified for the lifetime of this JSON document.\n @return The new object, or NULL on error.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_add_obj(yyjson_mut_doc *doc,\n                                                         yyjson_mut_val *obj,\n                                                         const char *key);\n\n/** Adds a JSON value at the end of the object.\n    The `key` should be a null-terminated UTF-8 string.\n    This function allows duplicated key in one object.\n    \n    @warning The key string is not copied, you should keep the string\n        unmodified for the lifetime of this JSON document. */\nyyjson_api_inline bool yyjson_mut_obj_add_val(yyjson_mut_doc *doc,\n                                              yyjson_mut_val *obj,\n                                              const char *key,\n                                              yyjson_mut_val *val);\n\n/** Removes all key-value pairs for the given key.\n    Returns the first value to which the specified key is mapped or NULL if this\n    object contains no mapping for the key.\n    The `key` should be a null-terminated UTF-8 string.\n    \n    @warning This function takes a linear search time. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_remove_str(\n    yyjson_mut_val *obj, const char *key);\n\n/** Removes all key-value pairs for the given key.\n    Returns the first value to which the specified key is mapped or NULL if this\n    object contains no mapping for the key.\n    The `key` should be a UTF-8 string, null-terminator is not required.\n    The `len` should be the length of the key, in bytes.\n    \n    @warning This function takes a linear search time. */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_remove_strn(\n    yyjson_mut_val *obj, const char *key, size_t len);\n\n/** Replaces all matching keys with the new key.\n    Returns true if at least one key was renamed.\n    The `key` and `new_key` should be a null-terminated UTF-8 string.\n    The `new_key` is copied and held by doc.\n    \n    @warning This function takes a linear search time.\n    If `new_key` already exists, it will cause duplicate keys.\n */\nyyjson_api_inline bool yyjson_mut_obj_rename_key(yyjson_mut_doc *doc,\n                                                 yyjson_mut_val *obj,\n                                                 const char *key,\n                                                 const char *new_key);\n\n/** Replaces all matching keys with the new key.\n    Returns true if at least one key was renamed.\n    The `key` and `new_key` should be a UTF-8 string,\n    null-terminator is not required. The `new_key` is copied and held by doc.\n    \n    @warning This function takes a linear search time.\n    If `new_key` already exists, it will cause duplicate keys.\n */\nyyjson_api_inline bool yyjson_mut_obj_rename_keyn(yyjson_mut_doc *doc,\n                                                  yyjson_mut_val *obj,\n                                                  const char *key,\n                                                  size_t len,\n                                                  const char *new_key,\n                                                  size_t new_len);\n\n\n\n/*==============================================================================\n * JSON Pointer API (RFC 6901)\n * https://tools.ietf.org/html/rfc6901\n *============================================================================*/\n\n/** JSON Pointer error code. */\ntypedef uint32_t yyjson_ptr_code;\n\n/** No JSON pointer error. */\nstatic const yyjson_ptr_code YYJSON_PTR_ERR_NONE = 0;\n\n/** Invalid input parameter, such as NULL input. */\nstatic const yyjson_ptr_code YYJSON_PTR_ERR_PARAMETER = 1;\n\n/** JSON pointer syntax error, such as invalid escape, token no prefix. */\nstatic const yyjson_ptr_code YYJSON_PTR_ERR_SYNTAX = 2;\n\n/** JSON pointer resolve failed, such as index out of range, key not found. */\nstatic const yyjson_ptr_code YYJSON_PTR_ERR_RESOLVE = 3;\n\n/** Document's root is NULL, but it is required for the function call. */\nstatic const yyjson_ptr_code YYJSON_PTR_ERR_NULL_ROOT = 4;\n\n/** Cannot set root as the target is not a document. */\nstatic const yyjson_ptr_code YYJSON_PTR_ERR_SET_ROOT = 5;\n\n/** The memory allocation failed and a new value could not be created. */\nstatic const yyjson_ptr_code YYJSON_PTR_ERR_MEMORY_ALLOCATION = 6;\n\n/** Error information for JSON pointer. */\ntypedef struct yyjson_ptr_err {\n    /** Error code, see `yyjson_ptr_code` for all possible values. */\n    yyjson_ptr_code code;\n    /** Error message, constant, no need to free (NULL if no error). */\n    const char *msg;\n    /** Error byte position for input JSON pointer (0 if no error). */\n    size_t pos;\n} yyjson_ptr_err;\n\n/**\n A context for JSON pointer operation.\n \n This struct stores the context of JSON Pointer operation result. The struct\n can be used with three helper functions: `ctx_append()`, `ctx_replace()`, and\n `ctx_remove()`, which perform the corresponding operations on the container\n without re-parsing the JSON Pointer.\n \n For example:\n @code\n    // doc before: {\"a\":[0,1,null]}\n    // ptr: \"/a/2\"\n    val = yyjson_mut_doc_ptr_getx(doc, ptr, strlen(ptr), &ctx, &err);\n    if (yyjson_is_null(val)) {\n        yyjson_ptr_ctx_remove(&ctx);\n    }\n    // doc after: {\"a\":[0,1]}\n @endcode\n */\ntypedef struct yyjson_ptr_ctx {\n    /**\n     The container (parent) of the target value. It can be either an array or\n     an object. If the target location has no value, but all its parent\n     containers exist, and the target location can be used to insert a new\n     value, then `ctn` is the parent container of the target location.\n     Otherwise, `ctn` is NULL.\n     */\n    yyjson_mut_val *ctn;\n    /**\n     The previous sibling of the target value. It can be either a value in an\n     array or a key in an object. As the container is a `circular linked list`\n     of elements, `pre` is the previous node of the target value. If the\n     operation is `add` or `set`, then `pre` is the previous node of the new\n     value, not the original target value. If the target value does not exist,\n     `pre` is NULL.\n     */\n    yyjson_mut_val *pre;\n    /**\n     The removed value if the operation is `set`, `replace` or `remove`. It can\n     be used to restore the original state of the document if needed.\n     */\n    yyjson_mut_val *old;\n} yyjson_ptr_ctx;\n\n/**\n Get value by a JSON Pointer.\n @param doc The JSON document to be queried.\n @param ptr The JSON pointer string (UTF-8 with null-terminator).\n @return The value referenced by the JSON pointer.\n    NULL if `doc` or `ptr` is NULL, or the JSON pointer cannot be resolved.\n */\nyyjson_api_inline yyjson_val *yyjson_doc_ptr_get(yyjson_doc *doc,\n                                                 const char *ptr);\n\n/**\n Get value by a JSON Pointer.\n @param doc The JSON document to be queried.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @return The value referenced by the JSON pointer.\n    NULL if `doc` or `ptr` is NULL, or the JSON pointer cannot be resolved.\n */\nyyjson_api_inline yyjson_val *yyjson_doc_ptr_getn(yyjson_doc *doc,\n                                                  const char *ptr, size_t len);\n\n/**\n Get value by a JSON Pointer.\n @param doc The JSON document to be queried.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @param err A pointer to store the error information, or NULL if not needed.\n @return The value referenced by the JSON pointer.\n    NULL if `doc` or `ptr` is NULL, or the JSON pointer cannot be resolved.\n */\nyyjson_api_inline yyjson_val *yyjson_doc_ptr_getx(yyjson_doc *doc,\n                                                  const char *ptr, size_t len,\n                                                  yyjson_ptr_err *err);\n\n/**\n Get value by a JSON Pointer.\n @param val The JSON value to be queried.\n @param ptr The JSON pointer string (UTF-8 with null-terminator).\n @return The value referenced by the JSON pointer.\n    NULL if `val` or `ptr` is NULL, or the JSON pointer cannot be resolved.\n */\nyyjson_api_inline yyjson_val *yyjson_ptr_get(yyjson_val *val,\n                                             const char *ptr);\n\n/**\n Get value by a JSON Pointer.\n @param val The JSON value to be queried.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @return The value referenced by the JSON pointer.\n    NULL if `val` or `ptr` is NULL, or the JSON pointer cannot be resolved.\n */\nyyjson_api_inline yyjson_val *yyjson_ptr_getn(yyjson_val *val,\n                                              const char *ptr, size_t len);\n\n/**\n Get value by a JSON Pointer.\n @param val The JSON value to be queried.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @param err A pointer to store the error information, or NULL if not needed.\n @return The value referenced by the JSON pointer.\n    NULL if `val` or `ptr` is NULL, or the JSON pointer cannot be resolved.\n */\nyyjson_api_inline yyjson_val *yyjson_ptr_getx(yyjson_val *val,\n                                              const char *ptr, size_t len,\n                                              yyjson_ptr_err *err);\n\n/**\n Get value by a JSON Pointer.\n @param doc The JSON document to be queried.\n @param ptr The JSON pointer string (UTF-8 with null-terminator).\n @return The value referenced by the JSON pointer.\n    NULL if `doc` or `ptr` is NULL, or the JSON pointer cannot be resolved.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_ptr_get(yyjson_mut_doc *doc,\n                                                         const char *ptr);\n\n/**\n Get value by a JSON Pointer.\n @param doc The JSON document to be queried.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @return The value referenced by the JSON pointer.\n    NULL if `doc` or `ptr` is NULL, or the JSON pointer cannot be resolved.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_ptr_getn(yyjson_mut_doc *doc,\n                                                          const char *ptr,\n                                                          size_t len);\n\n/**\n Get value by a JSON Pointer.\n @param doc The JSON document to be queried.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @param ctx A pointer to store the result context, or NULL if not needed.\n @param err A pointer to store the error information, or NULL if not needed.\n @return The value referenced by the JSON pointer.\n    NULL if `doc` or `ptr` is NULL, or the JSON pointer cannot be resolved.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_ptr_getx(yyjson_mut_doc *doc,\n                                                          const char *ptr,\n                                                          size_t len,\n                                                          yyjson_ptr_ctx *ctx,\n                                                          yyjson_ptr_err *err);\n\n/**\n Get value by a JSON Pointer.\n @param val The JSON value to be queried.\n @param ptr The JSON pointer string (UTF-8 with null-terminator).\n @return The value referenced by the JSON pointer.\n    NULL if `val` or `ptr` is NULL, or the JSON pointer cannot be resolved.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_ptr_get(yyjson_mut_val *val,\n                                                     const char *ptr);\n\n/**\n Get value by a JSON Pointer.\n @param val The JSON value to be queried.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @return The value referenced by the JSON pointer.\n    NULL if `val` or `ptr` is NULL, or the JSON pointer cannot be resolved.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_ptr_getn(yyjson_mut_val *val,\n                                                      const char *ptr,\n                                                      size_t len);\n\n/**\n Get value by a JSON Pointer.\n @param val The JSON value to be queried.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @param ctx A pointer to store the result context, or NULL if not needed.\n @param err A pointer to store the error information, or NULL if not needed.\n @return The value referenced by the JSON pointer.\n    NULL if `val` or `ptr` is NULL, or the JSON pointer cannot be resolved.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_ptr_getx(yyjson_mut_val *val,\n                                                      const char *ptr,\n                                                      size_t len,\n                                                      yyjson_ptr_ctx *ctx,\n                                                      yyjson_ptr_err *err);\n\n/**\n Add (insert) value by a JSON pointer.\n @param doc The target JSON document.\n @param ptr The JSON pointer string (UTF-8 with null-terminator).\n @param new_val The value to be added.\n @return true if JSON pointer is valid and new value is added, false otherwise.\n @note The parent nodes will be created if they do not exist.\n */\nyyjson_api_inline bool yyjson_mut_doc_ptr_add(yyjson_mut_doc *doc,\n                                              const char *ptr,\n                                              yyjson_mut_val *new_val);\n\n/**\n Add (insert) value by a JSON pointer.\n @param doc The target JSON document.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @param new_val The value to be added.\n @return true if JSON pointer is valid and new value is added, false otherwise.\n @note The parent nodes will be created if they do not exist.\n */\nyyjson_api_inline bool yyjson_mut_doc_ptr_addn(yyjson_mut_doc *doc,\n                                               const char *ptr, size_t len,\n                                               yyjson_mut_val *new_val);\n\n/**\n Add (insert) value by a JSON pointer.\n @param doc The target JSON document.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @param new_val The value to be added.\n @param create_parent Whether to create parent nodes if not exist.\n @param ctx A pointer to store the result context, or NULL if not needed.\n @param err A pointer to store the error information, or NULL if not needed.\n @return true if JSON pointer is valid and new value is added, false otherwise.\n */\nyyjson_api_inline bool yyjson_mut_doc_ptr_addx(yyjson_mut_doc *doc,\n                                               const char *ptr, size_t len,\n                                               yyjson_mut_val *new_val,\n                                               bool create_parent,\n                                               yyjson_ptr_ctx *ctx,\n                                               yyjson_ptr_err *err);\n\n/**\n Add (insert) value by a JSON pointer.\n @param val The target JSON value.\n @param ptr The JSON pointer string (UTF-8 with null-terminator).\n @param doc Only used to create new values when needed.\n @param new_val The value to be added.\n @return true if JSON pointer is valid and new value is added, false otherwise.\n @note The parent nodes will be created if they do not exist.\n */\nyyjson_api_inline bool yyjson_mut_ptr_add(yyjson_mut_val *val,\n                                          const char *ptr,\n                                          yyjson_mut_val *new_val,\n                                          yyjson_mut_doc *doc);\n\n/**\n Add (insert) value by a JSON pointer.\n @param val The target JSON value.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @param doc Only used to create new values when needed.\n @param new_val The value to be added.\n @return true if JSON pointer is valid and new value is added, false otherwise.\n @note The parent nodes will be created if they do not exist.\n */\nyyjson_api_inline bool yyjson_mut_ptr_addn(yyjson_mut_val *val,\n                                           const char *ptr, size_t len,\n                                           yyjson_mut_val *new_val,\n                                           yyjson_mut_doc *doc);\n\n/**\n Add (insert) value by a JSON pointer.\n @param val The target JSON value.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @param doc Only used to create new values when needed.\n @param new_val The value to be added.\n @param create_parent Whether to create parent nodes if not exist.\n @param ctx A pointer to store the result context, or NULL if not needed.\n @param err A pointer to store the error information, or NULL if not needed.\n @return true if JSON pointer is valid and new value is added, false otherwise.\n */\nyyjson_api_inline bool yyjson_mut_ptr_addx(yyjson_mut_val *val,\n                                           const char *ptr, size_t len,\n                                           yyjson_mut_val *new_val,\n                                           yyjson_mut_doc *doc,\n                                           bool create_parent,\n                                           yyjson_ptr_ctx *ctx,\n                                           yyjson_ptr_err *err);\n\n/**\n Set value by a JSON pointer.\n @param doc The target JSON document.\n @param ptr The JSON pointer string (UTF-8 with null-terminator).\n @param new_val The value to be set, pass NULL to remove.\n @return true if JSON pointer is valid and new value is set, false otherwise.\n @note The parent nodes will be created if they do not exist.\n    If the target value already exists, it will be replaced by the new value.\n */\nyyjson_api_inline bool yyjson_mut_doc_ptr_set(yyjson_mut_doc *doc,\n                                              const char *ptr,\n                                              yyjson_mut_val *new_val);\n\n/**\n Set value by a JSON pointer.\n @param doc The target JSON document.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @param new_val The value to be set, pass NULL to remove.\n @return true if JSON pointer is valid and new value is set, false otherwise.\n @note The parent nodes will be created if they do not exist.\n    If the target value already exists, it will be replaced by the new value.\n */\nyyjson_api_inline bool yyjson_mut_doc_ptr_setn(yyjson_mut_doc *doc,\n                                               const char *ptr, size_t len,\n                                               yyjson_mut_val *new_val);\n\n/**\n Set value by a JSON pointer.\n @param doc The target JSON document.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @param new_val The value to be set, pass NULL to remove.\n @param create_parent Whether to create parent nodes if not exist.\n @param ctx A pointer to store the result context, or NULL if not needed.\n @param err A pointer to store the error information, or NULL if not needed.\n @return true if JSON pointer is valid and new value is set, false otherwise.\n @note If the target value already exists, it will be replaced by the new value.\n */\nyyjson_api_inline bool yyjson_mut_doc_ptr_setx(yyjson_mut_doc *doc,\n                                               const char *ptr, size_t len,\n                                               yyjson_mut_val *new_val,\n                                               bool create_parent,\n                                               yyjson_ptr_ctx *ctx,\n                                               yyjson_ptr_err *err);\n\n/**\n Set value by a JSON pointer.\n @param val The target JSON value.\n @param ptr The JSON pointer string (UTF-8 with null-terminator).\n @param new_val The value to be set, pass NULL to remove.\n @param doc Only used to create new values when needed.\n @return true if JSON pointer is valid and new value is set, false otherwise.\n @note The parent nodes will be created if they do not exist.\n    If the target value already exists, it will be replaced by the new value.\n */\nyyjson_api_inline bool yyjson_mut_ptr_set(yyjson_mut_val *val,\n                                          const char *ptr,\n                                          yyjson_mut_val *new_val,\n                                          yyjson_mut_doc *doc);\n\n/**\n Set value by a JSON pointer.\n @param val The target JSON value.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @param new_val The value to be set, pass NULL to remove.\n @param doc Only used to create new values when needed.\n @return true if JSON pointer is valid and new value is set, false otherwise.\n @note The parent nodes will be created if they do not exist.\n    If the target value already exists, it will be replaced by the new value.\n */\nyyjson_api_inline bool yyjson_mut_ptr_setn(yyjson_mut_val *val,\n                                           const char *ptr, size_t len,\n                                           yyjson_mut_val *new_val,\n                                           yyjson_mut_doc *doc);\n\n/**\n Set value by a JSON pointer.\n @param val The target JSON value.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @param new_val The value to be set, pass NULL to remove.\n @param doc Only used to create new values when needed.\n @param create_parent Whether to create parent nodes if not exist.\n @param ctx A pointer to store the result context, or NULL if not needed.\n @param err A pointer to store the error information, or NULL if not needed.\n @return true if JSON pointer is valid and new value is set, false otherwise.\n @note If the target value already exists, it will be replaced by the new value.\n */\nyyjson_api_inline bool yyjson_mut_ptr_setx(yyjson_mut_val *val,\n                                           const char *ptr, size_t len,\n                                           yyjson_mut_val *new_val,\n                                           yyjson_mut_doc *doc,\n                                           bool create_parent,\n                                           yyjson_ptr_ctx *ctx,\n                                           yyjson_ptr_err *err);\n\n/**\n Replace value by a JSON pointer.\n @param doc The target JSON document.\n @param ptr The JSON pointer string (UTF-8 with null-terminator).\n @param new_val The new value to replace the old one.\n @return The old value that was replaced, or NULL if not found.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_ptr_replace(\n    yyjson_mut_doc *doc, const char *ptr, yyjson_mut_val *new_val);\n\n/**\n Replace value by a JSON pointer.\n @param doc The target JSON document.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @param new_val The new value to replace the old one.\n @return The old value that was replaced, or NULL if not found.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_ptr_replacen(\n    yyjson_mut_doc *doc, const char *ptr, size_t len, yyjson_mut_val *new_val);\n\n/**\n Replace value by a JSON pointer.\n @param doc The target JSON document.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @param new_val The new value to replace the old one.\n @param ctx A pointer to store the result context, or NULL if not needed.\n @param err A pointer to store the error information, or NULL if not needed.\n @return The old value that was replaced, or NULL if not found.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_ptr_replacex(\n    yyjson_mut_doc *doc, const char *ptr, size_t len, yyjson_mut_val *new_val,\n    yyjson_ptr_ctx *ctx, yyjson_ptr_err *err);\n\n/**\n Replace value by a JSON pointer.\n @param val The target JSON value.\n @param ptr The JSON pointer string (UTF-8 with null-terminator).\n @param new_val The new value to replace the old one.\n @return The old value that was replaced, or NULL if not found.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_ptr_replace(\n    yyjson_mut_val *val, const char *ptr, yyjson_mut_val *new_val);\n\n/**\n Replace value by a JSON pointer.\n @param val The target JSON value.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @param new_val The new value to replace the old one.\n @return The old value that was replaced, or NULL if not found.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_ptr_replacen(\n    yyjson_mut_val *val, const char *ptr, size_t len, yyjson_mut_val *new_val);\n\n/**\n Replace value by a JSON pointer.\n @param val The target JSON value.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @param new_val The new value to replace the old one.\n @param ctx A pointer to store the result context, or NULL if not needed.\n @param err A pointer to store the error information, or NULL if not needed.\n @return The old value that was replaced, or NULL if not found.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_ptr_replacex(\n    yyjson_mut_val *val, const char *ptr, size_t len, yyjson_mut_val *new_val,\n    yyjson_ptr_ctx *ctx, yyjson_ptr_err *err);\n\n/**\n Remove value by a JSON pointer.\n @param doc The target JSON document.\n @param ptr The JSON pointer string (UTF-8 with null-terminator).\n @return The removed value, or NULL on error.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_ptr_remove(\n    yyjson_mut_doc *doc, const char *ptr);\n\n/**\n Remove value by a JSON pointer.\n @param doc The target JSON document.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @return The removed value, or NULL on error.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_ptr_removen(\n    yyjson_mut_doc *doc, const char *ptr, size_t len);\n\n/**\n Remove value by a JSON pointer.\n @param doc The target JSON document.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @param ctx A pointer to store the result context, or NULL if not needed.\n @param err A pointer to store the error information, or NULL if not needed.\n @return The removed value, or NULL on error.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_ptr_removex(\n    yyjson_mut_doc *doc, const char *ptr, size_t len,\n    yyjson_ptr_ctx *ctx, yyjson_ptr_err *err);\n\n/**\n Remove value by a JSON pointer.\n @param val The target JSON value.\n @param ptr The JSON pointer string (UTF-8 with null-terminator).\n @return The removed value, or NULL on error.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_ptr_remove(yyjson_mut_val *val,\n                                                        const char *ptr);\n\n/**\n Remove value by a JSON pointer.\n @param val The target JSON value.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @return The removed value, or NULL on error.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_ptr_removen(yyjson_mut_val *val,\n                                                         const char *ptr,\n                                                         size_t len);\n\n/**\n Remove value by a JSON pointer.\n @param val The target JSON value.\n @param ptr The JSON pointer string (UTF-8, null-terminator is not required).\n @param len The length of `ptr` in bytes.\n @param ctx A pointer to store the result context, or NULL if not needed.\n @param err A pointer to store the error information, or NULL if not needed.\n @return The removed value, or NULL on error.\n */\nyyjson_api_inline yyjson_mut_val *yyjson_mut_ptr_removex(yyjson_mut_val *val,\n                                                         const char *ptr,\n                                                         size_t len,\n                                                         yyjson_ptr_ctx *ctx,\n                                                         yyjson_ptr_err *err);\n\n/**\n Append value by JSON pointer context.\n @param ctx The context from the `yyjson_mut_ptr_xxx()` calls.\n @param key New key if `ctx->ctn` is object, or NULL if `ctx->ctn` is array.\n @param val New value to be added.\n @return true on success or false on fail.\n */\nyyjson_api_inline bool yyjson_ptr_ctx_append(yyjson_ptr_ctx *ctx,\n                                             yyjson_mut_val *key,\n                                             yyjson_mut_val *val);\n\n/**\n Replace value by JSON pointer context.\n @param ctx The context from the `yyjson_mut_ptr_xxx()` calls.\n @param val New value to be replaced.\n @return true on success or false on fail.\n @note If success, the old value will be returned via `ctx->old`.\n */\nyyjson_api_inline bool yyjson_ptr_ctx_replace(yyjson_ptr_ctx *ctx,\n                                              yyjson_mut_val *val);\n\n/**\n Remove value by JSON pointer context.\n @param ctx The context from the `yyjson_mut_ptr_xxx()` calls.\n @return true on success or false on fail.\n @note If success, the old value will be returned via `ctx->old`.\n */\nyyjson_api_inline bool yyjson_ptr_ctx_remove(yyjson_ptr_ctx *ctx);\n\n\n\n/*==============================================================================\n * JSON Patch API (RFC 6902)\n * https://tools.ietf.org/html/rfc6902\n *============================================================================*/\n\n/** Result code for JSON patch. */\ntypedef uint32_t yyjson_patch_code;\n\n/** Success, no error. */\nstatic const yyjson_patch_code YYJSON_PATCH_SUCCESS = 0;\n\n/** Invalid parameter, such as NULL input or non-array patch. */\nstatic const yyjson_patch_code YYJSON_PATCH_ERROR_INVALID_PARAMETER = 1;\n\n/** Memory allocation failure occurs. */\nstatic const yyjson_patch_code YYJSON_PATCH_ERROR_MEMORY_ALLOCATION = 2;\n\n/** JSON patch operation is not object type. */\nstatic const yyjson_patch_code YYJSON_PATCH_ERROR_INVALID_OPERATION = 3;\n\n/** JSON patch operation is missing a required key. */\nstatic const yyjson_patch_code YYJSON_PATCH_ERROR_MISSING_KEY = 4;\n\n/** JSON patch operation member is invalid. */\nstatic const yyjson_patch_code YYJSON_PATCH_ERROR_INVALID_MEMBER = 5;\n\n/** JSON patch operation `test` not equal. */\nstatic const yyjson_patch_code YYJSON_PATCH_ERROR_EQUAL = 6;\n\n/** JSON patch operation failed on JSON pointer. */\nstatic const yyjson_patch_code YYJSON_PATCH_ERROR_POINTER = 7;\n\n/** Error information for JSON patch. */\ntypedef struct yyjson_patch_err {\n    /** Error code, see `yyjson_patch_code` for all possible values. */\n    yyjson_patch_code code;\n    /** Index of the error operation (0 if no error). */\n    size_t idx;\n    /** Error message, constant, no need to free (NULL if no error). */\n    const char *msg;\n    /** JSON pointer error if `code == YYJSON_PATCH_ERROR_POINTER`. */\n    yyjson_ptr_err ptr;\n} yyjson_patch_err;\n\n/**\n Creates and returns a patched JSON value (RFC 6902).\n The memory of the returned value is allocated by the `doc`.\n The `err` is used to receive error information, pass NULL if not needed.\n Returns NULL if the patch could not be applied.\n */\nyyjson_api yyjson_mut_val *yyjson_patch(yyjson_mut_doc *doc,\n                                        yyjson_val *orig,\n                                        yyjson_val *patch,\n                                        yyjson_patch_err *err);\n\n/**\n Creates and returns a patched JSON value (RFC 6902).\n The memory of the returned value is allocated by the `doc`.\n The `err` is used to receive error information, pass NULL if not needed.\n Returns NULL if the patch could not be applied.\n */\nyyjson_api yyjson_mut_val *yyjson_mut_patch(yyjson_mut_doc *doc,\n                                            yyjson_mut_val *orig,\n                                            yyjson_mut_val *patch,\n                                            yyjson_patch_err *err);\n\n\n\n/*==============================================================================\n * JSON Merge-Patch API (RFC 7386)\n * https://tools.ietf.org/html/rfc7386\n *============================================================================*/\n\n/**\n Creates and returns a merge-patched JSON value (RFC 7386).\n The memory of the returned value is allocated by the `doc`.\n Returns NULL if the patch could not be applied.\n\n @warning This function is recursive and may cause a stack overflow if the\n    object level is too deep.\n */\nyyjson_api yyjson_mut_val *yyjson_merge_patch(yyjson_mut_doc *doc,\n                                              yyjson_val *orig,\n                                              yyjson_val *patch);\n\n/**\n Creates and returns a merge-patched JSON value (RFC 7386).\n The memory of the returned value is allocated by the `doc`.\n Returns NULL if the patch could not be applied.\n\n @warning This function is recursive and may cause a stack overflow if the\n    object level is too deep.\n */\nyyjson_api yyjson_mut_val *yyjson_mut_merge_patch(yyjson_mut_doc *doc,\n                                                  yyjson_mut_val *orig,\n                                                  yyjson_mut_val *patch);\n\n\n\n/*==============================================================================\n * JSON Structure (Implementation)\n *============================================================================*/\n\n/** Payload of a JSON value (8 bytes). */\ntypedef union yyjson_val_uni {\n    uint64_t    u64;\n    int64_t     i64;\n    double      f64;\n    const char *str;\n    void       *ptr;\n    size_t      ofs;\n} yyjson_val_uni;\n\n/**\n Immutable JSON value, 16 bytes.\n */\nstruct yyjson_val {\n    uint64_t tag; /**< type, subtype and length */\n    yyjson_val_uni uni; /**< payload */\n};\n\nstruct yyjson_doc {\n    /** Root value of the document (nonnull). */\n    yyjson_val *root;\n    /** Allocator used by document (nonnull). */\n    yyjson_alc alc;\n    /** The total number of bytes read when parsing JSON (nonzero). */\n    size_t dat_read;\n    /** The total number of value read when parsing JSON (nonzero). */\n    size_t val_read;\n    /** The string pool used by JSON values (nullable). */\n    char *str_pool;\n};\n\n\n\n/*==============================================================================\n * Unsafe JSON Value API (Implementation)\n *============================================================================*/\n\n/*\n Whether the string does not need to be escaped for serialization.\n This function is used to optimize the writing speed of small constant strings.\n This function works only if the compiler can evaluate it at compile time.\n \n Clang supports it since v8.0,\n    earlier versions do not support constant_p(strlen) and return false.\n GCC supports it since at least v4.4,\n    earlier versions may compile it as run-time instructions.\n ICC supports it since at least v16,\n    earlier versions are uncertain.\n \n @param str The C string.\n @param len The returnd value from strlen(str).\n */\nyyjson_api_inline bool unsafe_yyjson_is_str_noesc(const char *str, size_t len) {\n#if YYJSON_HAS_CONSTANT_P && \\\n    (!YYJSON_IS_REAL_GCC || yyjson_gcc_available(4, 4, 0))\n    if (yyjson_constant_p(len) && len <= 32) {\n        /*\n         Same as the following loop:\n         \n         for (size_t i = 0; i < len; i++) {\n             char c = str[i];\n             if (c < ' ' || c > '~' || c == '\"' || c == '\\\\') return false;\n         }\n         \n         GCC evaluates it at compile time only if the string length is within 17\n         and -O3 (which turns on the -fpeel-loops flag) is used.\n         So the loop is unrolled for GCC.\n         */\n#       define yyjson_repeat32_incr(x) \\\n            x(0)  x(1)  x(2)  x(3)  x(4)  x(5)  x(6)  x(7)  \\\n            x(8)  x(9)  x(10) x(11) x(12) x(13) x(14) x(15) \\\n            x(16) x(17) x(18) x(19) x(20) x(21) x(22) x(23) \\\n            x(24) x(25) x(26) x(27) x(28) x(29) x(30) x(31)\n#       define yyjson_check_char_noesc(i) \\\n            if (i < len) { \\\n                char c = str[i]; \\\n                if (c < ' ' || c > '~' || c == '\"' || c == '\\\\') return false; }\n        yyjson_repeat32_incr(yyjson_check_char_noesc)\n#       undef yyjson_repeat32_incr\n#       undef yyjson_check_char_noesc\n        return true;\n    }\n#else\n    (void)str;\n    (void)len;\n#endif\n    return false;\n}\n\nyyjson_api_inline yyjson_type unsafe_yyjson_get_type(void *val) {\n    uint8_t tag = (uint8_t)((yyjson_val *)val)->tag;\n    return (yyjson_type)(tag & YYJSON_TYPE_MASK);\n}\n\nyyjson_api_inline yyjson_subtype unsafe_yyjson_get_subtype(void *val) {\n    uint8_t tag = (uint8_t)((yyjson_val *)val)->tag;\n    return (yyjson_subtype)(tag & YYJSON_SUBTYPE_MASK);\n}\n\nyyjson_api_inline uint8_t unsafe_yyjson_get_tag(void *val) {\n    uint8_t tag = (uint8_t)((yyjson_val *)val)->tag;\n    return (uint8_t)(tag & YYJSON_TAG_MASK);\n}\n\nyyjson_api_inline bool unsafe_yyjson_is_raw(void *val) {\n    return unsafe_yyjson_get_type(val) == YYJSON_TYPE_RAW;\n}\n\nyyjson_api_inline bool unsafe_yyjson_is_null(void *val) {\n    return unsafe_yyjson_get_type(val) == YYJSON_TYPE_NULL;\n}\n\nyyjson_api_inline bool unsafe_yyjson_is_bool(void *val) {\n    return unsafe_yyjson_get_type(val) == YYJSON_TYPE_BOOL;\n}\n\nyyjson_api_inline bool unsafe_yyjson_is_num(void *val) {\n    return unsafe_yyjson_get_type(val) == YYJSON_TYPE_NUM;\n}\n\nyyjson_api_inline bool unsafe_yyjson_is_str(void *val) {\n    return unsafe_yyjson_get_type(val) == YYJSON_TYPE_STR;\n}\n\nyyjson_api_inline bool unsafe_yyjson_is_arr(void *val) {\n    return unsafe_yyjson_get_type(val) == YYJSON_TYPE_ARR;\n}\n\nyyjson_api_inline bool unsafe_yyjson_is_obj(void *val) {\n    return unsafe_yyjson_get_type(val) == YYJSON_TYPE_OBJ;\n}\n\nyyjson_api_inline bool unsafe_yyjson_is_ctn(void *val) {\n    uint8_t mask = YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ;\n    return (unsafe_yyjson_get_tag(val) & mask) == mask;\n}\n\nyyjson_api_inline bool unsafe_yyjson_is_uint(void *val) {\n    const uint8_t patt = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_UINT;\n    return unsafe_yyjson_get_tag(val) == patt;\n}\n\nyyjson_api_inline bool unsafe_yyjson_is_sint(void *val) {\n    const uint8_t patt = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_SINT;\n    return unsafe_yyjson_get_tag(val) == patt;\n}\n\nyyjson_api_inline bool unsafe_yyjson_is_int(void *val) {\n    const uint8_t mask = YYJSON_TAG_MASK & (~YYJSON_SUBTYPE_SINT);\n    const uint8_t patt = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_UINT;\n    return (unsafe_yyjson_get_tag(val) & mask) == patt;\n}\n\nyyjson_api_inline bool unsafe_yyjson_is_real(void *val) {\n    const uint8_t patt = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL;\n    return unsafe_yyjson_get_tag(val) == patt;\n}\n\nyyjson_api_inline bool unsafe_yyjson_is_true(void *val) {\n    const uint8_t patt = YYJSON_TYPE_BOOL | YYJSON_SUBTYPE_TRUE;\n    return unsafe_yyjson_get_tag(val) == patt;\n}\n\nyyjson_api_inline bool unsafe_yyjson_is_false(void *val) {\n    const uint8_t patt = YYJSON_TYPE_BOOL | YYJSON_SUBTYPE_FALSE;\n    return unsafe_yyjson_get_tag(val) == patt;\n}\n\nyyjson_api_inline bool unsafe_yyjson_arr_is_flat(yyjson_val *val) {\n    size_t ofs = val->uni.ofs;\n    size_t len = (size_t)(val->tag >> YYJSON_TAG_BIT);\n    return len * sizeof(yyjson_val) + sizeof(yyjson_val) == ofs;\n}\n\nyyjson_api_inline const char *unsafe_yyjson_get_raw(void *val) {\n    return ((yyjson_val *)val)->uni.str;\n}\n\nyyjson_api_inline bool unsafe_yyjson_get_bool(void *val) {\n    uint8_t tag = unsafe_yyjson_get_tag(val);\n    return (bool)((tag & YYJSON_SUBTYPE_MASK) >> YYJSON_TYPE_BIT);\n}\n\nyyjson_api_inline uint64_t unsafe_yyjson_get_uint(void *val) {\n    return ((yyjson_val *)val)->uni.u64;\n}\n\nyyjson_api_inline int64_t unsafe_yyjson_get_sint(void *val) {\n    return ((yyjson_val *)val)->uni.i64;\n}\n\nyyjson_api_inline int unsafe_yyjson_get_int(void *val) {\n    return (int)((yyjson_val *)val)->uni.i64;\n}\n\nyyjson_api_inline double unsafe_yyjson_get_real(void *val) {\n    return ((yyjson_val *)val)->uni.f64;\n}\n\nyyjson_api_inline double unsafe_yyjson_get_num(void *val) {\n    uint8_t tag = unsafe_yyjson_get_tag(val);\n    if (tag == (YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL)) {\n        return ((yyjson_val *)val)->uni.f64;\n    } else if (tag == (YYJSON_TYPE_NUM | YYJSON_SUBTYPE_SINT)) {\n        return (double)((yyjson_val *)val)->uni.i64;\n    } else if (tag == (YYJSON_TYPE_NUM | YYJSON_SUBTYPE_UINT)) {\n#if YYJSON_U64_TO_F64_NO_IMPL\n        uint64_t msb = ((uint64_t)1) << 63;\n        uint64_t num = ((yyjson_val *)val)->uni.u64;\n        if ((num & msb) == 0) {\n            return (double)(int64_t)num;\n        } else {\n            return ((double)(int64_t)((num >> 1) | (num & 1))) * (double)2.0;\n        }\n#else\n        return (double)((yyjson_val *)val)->uni.u64;\n#endif\n    }\n    return 0.0;\n}\n\nyyjson_api_inline const char *unsafe_yyjson_get_str(void *val) {\n    return ((yyjson_val *)val)->uni.str;\n}\n\nyyjson_api_inline size_t unsafe_yyjson_get_len(void *val) {\n    return (size_t)(((yyjson_val *)val)->tag >> YYJSON_TAG_BIT);\n}\n\nyyjson_api_inline yyjson_val *unsafe_yyjson_get_first(yyjson_val *ctn) {\n    return ctn + 1;\n}\n\nyyjson_api_inline yyjson_val *unsafe_yyjson_get_next(yyjson_val *val) {\n    bool is_ctn = unsafe_yyjson_is_ctn(val);\n    size_t ctn_ofs = val->uni.ofs;\n    size_t ofs = (is_ctn ? ctn_ofs : sizeof(yyjson_val));\n    return (yyjson_val *)(void *)((uint8_t *)val + ofs);\n}\n\nyyjson_api_inline bool unsafe_yyjson_equals_strn(void *val, const char *str,\n                                                 size_t len) {\n    return unsafe_yyjson_get_len(val) == len &&\n           memcmp(((yyjson_val *)val)->uni.str, str, len) == 0;\n}\n\nyyjson_api_inline bool unsafe_yyjson_equals_str(void *val, const char *str) {\n    return unsafe_yyjson_equals_strn(val, str, strlen(str));\n}\n\nyyjson_api_inline void unsafe_yyjson_set_type(void *val, yyjson_type type,\n                                              yyjson_subtype subtype) {\n    uint8_t tag = (type | subtype);\n    uint64_t new_tag = ((yyjson_val *)val)->tag;\n    new_tag = (new_tag & (~(uint64_t)YYJSON_TAG_MASK)) | (uint64_t)tag;\n    ((yyjson_val *)val)->tag = new_tag;\n}\n\nyyjson_api_inline void unsafe_yyjson_set_len(void *val, size_t len) {\n    uint64_t tag = ((yyjson_val *)val)->tag & YYJSON_TAG_MASK;\n    tag |= (uint64_t)len << YYJSON_TAG_BIT;\n    ((yyjson_val *)val)->tag = tag;\n}\n\nyyjson_api_inline void unsafe_yyjson_inc_len(void *val) {\n    uint64_t tag = ((yyjson_val *)val)->tag;\n    tag += (uint64_t)(1 << YYJSON_TAG_BIT);\n    ((yyjson_val *)val)->tag = tag;\n}\n\nyyjson_api_inline void unsafe_yyjson_set_raw(void *val, const char *raw,\n                                             size_t len) {\n    unsafe_yyjson_set_type(val, YYJSON_TYPE_RAW, YYJSON_SUBTYPE_NONE);\n    unsafe_yyjson_set_len(val, len);\n    ((yyjson_val *)val)->uni.str = raw;\n}\n\nyyjson_api_inline void unsafe_yyjson_set_null(void *val) {\n    unsafe_yyjson_set_type(val, YYJSON_TYPE_NULL, YYJSON_SUBTYPE_NONE);\n    unsafe_yyjson_set_len(val, 0);\n}\n\nyyjson_api_inline void unsafe_yyjson_set_bool(void *val, bool num) {\n    yyjson_subtype subtype = num ? YYJSON_SUBTYPE_TRUE : YYJSON_SUBTYPE_FALSE;\n    unsafe_yyjson_set_type(val, YYJSON_TYPE_BOOL, subtype);\n    unsafe_yyjson_set_len(val, 0);\n}\n\nyyjson_api_inline void unsafe_yyjson_set_uint(void *val, uint64_t num) {\n    unsafe_yyjson_set_type(val, YYJSON_TYPE_NUM, YYJSON_SUBTYPE_UINT);\n    unsafe_yyjson_set_len(val, 0);\n    ((yyjson_val *)val)->uni.u64 = num;\n}\n\nyyjson_api_inline void unsafe_yyjson_set_sint(void *val, int64_t num) {\n    unsafe_yyjson_set_type(val, YYJSON_TYPE_NUM, YYJSON_SUBTYPE_SINT);\n    unsafe_yyjson_set_len(val, 0);\n    ((yyjson_val *)val)->uni.i64 = num;\n}\n\nyyjson_api_inline void unsafe_yyjson_set_real(void *val, double num) {\n    unsafe_yyjson_set_type(val, YYJSON_TYPE_NUM, YYJSON_SUBTYPE_REAL);\n    unsafe_yyjson_set_len(val, 0);\n    ((yyjson_val *)val)->uni.f64 = num;\n}\n\nyyjson_api_inline void unsafe_yyjson_set_str(void *val, const char *str) {\n    size_t len = strlen(str);\n    bool noesc = unsafe_yyjson_is_str_noesc(str, len);\n    yyjson_subtype sub = noesc ? YYJSON_SUBTYPE_NOESC : YYJSON_SUBTYPE_NONE;\n    unsafe_yyjson_set_type(val, YYJSON_TYPE_STR, sub);\n    unsafe_yyjson_set_len(val, len);\n    ((yyjson_val *)val)->uni.str = str;\n}\n\nyyjson_api_inline void unsafe_yyjson_set_strn(void *val, const char *str,\n                                              size_t len) {\n    unsafe_yyjson_set_type(val, YYJSON_TYPE_STR, YYJSON_SUBTYPE_NONE);\n    unsafe_yyjson_set_len(val, len);\n    ((yyjson_val *)val)->uni.str = str;\n}\n\nyyjson_api_inline void unsafe_yyjson_set_arr(void *val, size_t size) {\n    unsafe_yyjson_set_type(val, YYJSON_TYPE_ARR, YYJSON_SUBTYPE_NONE);\n    unsafe_yyjson_set_len(val, size);\n}\n\nyyjson_api_inline void unsafe_yyjson_set_obj(void *val, size_t size) {\n    unsafe_yyjson_set_type(val, YYJSON_TYPE_OBJ, YYJSON_SUBTYPE_NONE);\n    unsafe_yyjson_set_len(val, size);\n}\n\n\n\n/*==============================================================================\n * JSON Document API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline yyjson_val *yyjson_doc_get_root(yyjson_doc *doc) {\n    return doc ? doc->root : NULL;\n}\n\nyyjson_api_inline size_t yyjson_doc_get_read_size(yyjson_doc *doc) {\n    return doc ? doc->dat_read : 0;\n}\n\nyyjson_api_inline size_t yyjson_doc_get_val_count(yyjson_doc *doc) {\n    return doc ? doc->val_read : 0;\n}\n\nyyjson_api void yyjson_doc_free(yyjson_doc *doc) {\n    if (doc) {\n        yyjson_alc alc = doc->alc;\n        memset(&doc->alc, 0, sizeof(alc));\n        if (doc->str_pool) alc.free(alc.ctx, doc->str_pool);\n        alc.free(alc.ctx, doc);\n    }\n}\n\n\n\n/*==============================================================================\n * JSON Value Type API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline bool yyjson_is_raw(yyjson_val *val) {\n    return val ? unsafe_yyjson_is_raw(val) : false;\n}\n\nyyjson_api_inline bool yyjson_is_null(yyjson_val *val) {\n    return val ? unsafe_yyjson_is_null(val) : false;\n}\n\nyyjson_api_inline bool yyjson_is_true(yyjson_val *val) {\n    return val ? unsafe_yyjson_is_true(val) : false;\n}\n\nyyjson_api_inline bool yyjson_is_false(yyjson_val *val) {\n    return val ? unsafe_yyjson_is_false(val) : false;\n}\n\nyyjson_api_inline bool yyjson_is_bool(yyjson_val *val) {\n    return val ? unsafe_yyjson_is_bool(val) : false;\n}\n\nyyjson_api_inline bool yyjson_is_uint(yyjson_val *val) {\n    return val ? unsafe_yyjson_is_uint(val) : false;\n}\n\nyyjson_api_inline bool yyjson_is_sint(yyjson_val *val) {\n    return val ? unsafe_yyjson_is_sint(val) : false;\n}\n\nyyjson_api_inline bool yyjson_is_int(yyjson_val *val) {\n    return val ? unsafe_yyjson_is_int(val) : false;\n}\n\nyyjson_api_inline bool yyjson_is_real(yyjson_val *val) {\n    return val ? unsafe_yyjson_is_real(val) : false;\n}\n\nyyjson_api_inline bool yyjson_is_num(yyjson_val *val) {\n    return val ? unsafe_yyjson_is_num(val) : false;\n}\n\nyyjson_api_inline bool yyjson_is_str(yyjson_val *val) {\n    return val ? unsafe_yyjson_is_str(val) : false;\n}\n\nyyjson_api_inline bool yyjson_is_arr(yyjson_val *val) {\n    return val ? unsafe_yyjson_is_arr(val) : false;\n}\n\nyyjson_api_inline bool yyjson_is_obj(yyjson_val *val) {\n    return val ? unsafe_yyjson_is_obj(val) : false;\n}\n\nyyjson_api_inline bool yyjson_is_ctn(yyjson_val *val) {\n    return val ? unsafe_yyjson_is_ctn(val) : false;\n}\n\n\n\n/*==============================================================================\n * JSON Value Content API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline yyjson_type yyjson_get_type(yyjson_val *val) {\n    return val ? unsafe_yyjson_get_type(val) : YYJSON_TYPE_NONE;\n}\n\nyyjson_api_inline yyjson_subtype yyjson_get_subtype(yyjson_val *val) {\n    return val ? unsafe_yyjson_get_subtype(val) : YYJSON_SUBTYPE_NONE;\n}\n\nyyjson_api_inline uint8_t yyjson_get_tag(yyjson_val *val) {\n    return val ? unsafe_yyjson_get_tag(val) : 0;\n}\n\nyyjson_api_inline const char *yyjson_get_type_desc(yyjson_val *val) {\n    switch (yyjson_get_tag(val)) {\n        case YYJSON_TYPE_RAW  | YYJSON_SUBTYPE_NONE:  return \"raw\";\n        case YYJSON_TYPE_NULL | YYJSON_SUBTYPE_NONE:  return \"null\";\n        case YYJSON_TYPE_STR  | YYJSON_SUBTYPE_NONE:  return \"string\";\n        case YYJSON_TYPE_STR  | YYJSON_SUBTYPE_NOESC: return \"string\";\n        case YYJSON_TYPE_ARR  | YYJSON_SUBTYPE_NONE:  return \"array\";\n        case YYJSON_TYPE_OBJ  | YYJSON_SUBTYPE_NONE:  return \"object\";\n        case YYJSON_TYPE_BOOL | YYJSON_SUBTYPE_TRUE:  return \"true\";\n        case YYJSON_TYPE_BOOL | YYJSON_SUBTYPE_FALSE: return \"false\";\n        case YYJSON_TYPE_NUM  | YYJSON_SUBTYPE_UINT:  return \"uint\";\n        case YYJSON_TYPE_NUM  | YYJSON_SUBTYPE_SINT:  return \"sint\";\n        case YYJSON_TYPE_NUM  | YYJSON_SUBTYPE_REAL:  return \"real\";\n        default:                                      return \"unknown\";\n    }\n}\n\nyyjson_api_inline const char *yyjson_get_raw(yyjson_val *val) {\n    return yyjson_is_raw(val) ? unsafe_yyjson_get_raw(val) : NULL;\n}\n\nyyjson_api_inline bool yyjson_get_bool(yyjson_val *val) {\n    return yyjson_is_bool(val) ? unsafe_yyjson_get_bool(val) : false;\n}\n\nyyjson_api_inline uint64_t yyjson_get_uint(yyjson_val *val) {\n    return yyjson_is_int(val) ? unsafe_yyjson_get_uint(val) : 0;\n}\n\nyyjson_api_inline int64_t yyjson_get_sint(yyjson_val *val) {\n    return yyjson_is_int(val) ? unsafe_yyjson_get_sint(val) : 0;\n}\n\nyyjson_api_inline int yyjson_get_int(yyjson_val *val) {\n    return yyjson_is_int(val) ? unsafe_yyjson_get_int(val) : 0;\n}\n\nyyjson_api_inline double yyjson_get_real(yyjson_val *val) {\n    return yyjson_is_real(val) ? unsafe_yyjson_get_real(val) : 0.0;\n}\n\nyyjson_api_inline double yyjson_get_num(yyjson_val *val) {\n    return val ? unsafe_yyjson_get_num(val) : 0.0;\n}\n\nyyjson_api_inline const char *yyjson_get_str(yyjson_val *val) {\n    return yyjson_is_str(val) ? unsafe_yyjson_get_str(val) : NULL;\n}\n\nyyjson_api_inline size_t yyjson_get_len(yyjson_val *val) {\n    return val ? unsafe_yyjson_get_len(val) : 0;\n}\n\nyyjson_api_inline bool yyjson_equals_str(yyjson_val *val, const char *str) {\n    if (yyjson_likely(val && str)) {\n        return unsafe_yyjson_is_str(val) &&\n               unsafe_yyjson_equals_str(val, str);\n    }\n    return false;\n}\n\nyyjson_api_inline bool yyjson_equals_strn(yyjson_val *val, const char *str,\n                                          size_t len) {\n    if (yyjson_likely(val && str)) {\n        return unsafe_yyjson_is_str(val) &&\n               unsafe_yyjson_equals_strn(val, str, len);\n    }\n    return false;\n}\n\nyyjson_api bool unsafe_yyjson_equals(yyjson_val *lhs, yyjson_val *rhs);\n\nyyjson_api_inline bool yyjson_equals(yyjson_val *lhs, yyjson_val *rhs) {\n    if (yyjson_unlikely(!lhs || !rhs)) return false;\n    return unsafe_yyjson_equals(lhs, rhs);\n}\n\nyyjson_api_inline bool yyjson_set_raw(yyjson_val *val,\n                                      const char *raw, size_t len) {\n    if (yyjson_unlikely(!val || unsafe_yyjson_is_ctn(val))) return false;\n    unsafe_yyjson_set_raw(val, raw, len);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_set_null(yyjson_val *val) {\n    if (yyjson_unlikely(!val || unsafe_yyjson_is_ctn(val))) return false;\n    unsafe_yyjson_set_null(val);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_set_bool(yyjson_val *val, bool num) {\n    if (yyjson_unlikely(!val || unsafe_yyjson_is_ctn(val))) return false;\n    unsafe_yyjson_set_bool(val, num);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_set_uint(yyjson_val *val, uint64_t num) {\n    if (yyjson_unlikely(!val || unsafe_yyjson_is_ctn(val))) return false;\n    unsafe_yyjson_set_uint(val, num);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_set_sint(yyjson_val *val, int64_t num) {\n    if (yyjson_unlikely(!val || unsafe_yyjson_is_ctn(val))) return false;\n    unsafe_yyjson_set_sint(val, num);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_set_int(yyjson_val *val, int num) {\n    if (yyjson_unlikely(!val || unsafe_yyjson_is_ctn(val))) return false;\n    unsafe_yyjson_set_sint(val, (int64_t)num);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_set_real(yyjson_val *val, double num) {\n    if (yyjson_unlikely(!val || unsafe_yyjson_is_ctn(val))) return false;\n    unsafe_yyjson_set_real(val, num);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_set_str(yyjson_val *val, const char *str) {\n    if (yyjson_unlikely(!val || unsafe_yyjson_is_ctn(val))) return false;\n    if (yyjson_unlikely(!str)) return false;\n    unsafe_yyjson_set_str(val, str);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_set_strn(yyjson_val *val,\n                                       const char *str, size_t len) {\n    if (yyjson_unlikely(!val || unsafe_yyjson_is_ctn(val))) return false;\n    if (yyjson_unlikely(!str)) return false;\n    unsafe_yyjson_set_strn(val, str, len);\n    return true;\n}\n\n\n\n/*==============================================================================\n * JSON Array API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline size_t yyjson_arr_size(yyjson_val *arr) {\n    return yyjson_is_arr(arr) ? unsafe_yyjson_get_len(arr) : 0;\n}\n\nyyjson_api_inline yyjson_val *yyjson_arr_get(yyjson_val *arr, size_t idx) {\n    if (yyjson_likely(yyjson_is_arr(arr))) {\n        if (yyjson_likely(unsafe_yyjson_get_len(arr) > idx)) {\n            yyjson_val *val = unsafe_yyjson_get_first(arr);\n            if (unsafe_yyjson_arr_is_flat(arr)) {\n                return val + idx;\n            } else {\n                while (idx-- > 0) val = unsafe_yyjson_get_next(val);\n                return val;\n            }\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_val *yyjson_arr_get_first(yyjson_val *arr) {\n    if (yyjson_likely(yyjson_is_arr(arr))) {\n        if (yyjson_likely(unsafe_yyjson_get_len(arr) > 0)) {\n            return unsafe_yyjson_get_first(arr);\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_val *yyjson_arr_get_last(yyjson_val *arr) {\n    if (yyjson_likely(yyjson_is_arr(arr))) {\n        size_t len = unsafe_yyjson_get_len(arr);\n        if (yyjson_likely(len > 0)) {\n            yyjson_val *val = unsafe_yyjson_get_first(arr);\n            if (unsafe_yyjson_arr_is_flat(arr)) {\n                return val + (len - 1);\n            } else {\n                while (len-- > 1) val = unsafe_yyjson_get_next(val);\n                return val;\n            }\n        }\n    }\n    return NULL;\n}\n\n\n\n/*==============================================================================\n * JSON Array Iterator API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline bool yyjson_arr_iter_init(yyjson_val *arr,\n                                            yyjson_arr_iter *iter) {\n    if (yyjson_likely(yyjson_is_arr(arr) && iter)) {\n        iter->idx = 0;\n        iter->max = unsafe_yyjson_get_len(arr);\n        iter->cur = unsafe_yyjson_get_first(arr);\n        return true;\n    }\n    if (iter) memset(iter, 0, sizeof(yyjson_arr_iter));\n    return false;\n}\n\nyyjson_api_inline yyjson_arr_iter yyjson_arr_iter_with(yyjson_val *arr) {\n    yyjson_arr_iter iter;\n    yyjson_arr_iter_init(arr, &iter);\n    return iter;\n}\n\nyyjson_api_inline bool yyjson_arr_iter_has_next(yyjson_arr_iter *iter) {\n    return iter ? iter->idx < iter->max : false;\n}\n\nyyjson_api_inline yyjson_val *yyjson_arr_iter_next(yyjson_arr_iter *iter) {\n    yyjson_val *val;\n    if (iter && iter->idx < iter->max) {\n        val = iter->cur;\n        iter->cur = unsafe_yyjson_get_next(val);\n        iter->idx++;\n        return val;\n    }\n    return NULL;\n}\n\n\n\n/*==============================================================================\n * JSON Object API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline size_t yyjson_obj_size(yyjson_val *obj) {\n    return yyjson_is_obj(obj) ? unsafe_yyjson_get_len(obj) : 0;\n}\n\nyyjson_api_inline yyjson_val *yyjson_obj_get(yyjson_val *obj,\n                                             const char *key) {\n    return yyjson_obj_getn(obj, key, key ? strlen(key) : 0);\n}\n\nyyjson_api_inline yyjson_val *yyjson_obj_getn(yyjson_val *obj,\n                                              const char *_key,\n                                              size_t key_len) {\n    if (yyjson_likely(yyjson_is_obj(obj) && _key)) {\n        size_t len = unsafe_yyjson_get_len(obj);\n        yyjson_val *key = unsafe_yyjson_get_first(obj);\n        while (len-- > 0) {\n            if (unsafe_yyjson_equals_strn(key, _key, key_len)) return key + 1;\n            key = unsafe_yyjson_get_next(key + 1);\n        }\n    }\n    return NULL;\n}\n\n\n\n/*==============================================================================\n * JSON Object Iterator API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline bool yyjson_obj_iter_init(yyjson_val *obj,\n                                            yyjson_obj_iter *iter) {\n    if (yyjson_likely(yyjson_is_obj(obj) && iter)) {\n        iter->idx = 0;\n        iter->max = unsafe_yyjson_get_len(obj);\n        iter->cur = unsafe_yyjson_get_first(obj);\n        iter->obj = obj;\n        return true;\n    }\n    if (iter) memset(iter, 0, sizeof(yyjson_obj_iter));\n    return false;\n}\n\nyyjson_api_inline yyjson_obj_iter yyjson_obj_iter_with(yyjson_val *obj) {\n    yyjson_obj_iter iter;\n    yyjson_obj_iter_init(obj, &iter);\n    return iter;\n}\n\nyyjson_api_inline bool yyjson_obj_iter_has_next(yyjson_obj_iter *iter) {\n    return iter ? iter->idx < iter->max : false;\n}\n\nyyjson_api_inline yyjson_val *yyjson_obj_iter_next(yyjson_obj_iter *iter) {\n    if (iter && iter->idx < iter->max) {\n        yyjson_val *key = iter->cur;\n        iter->idx++;\n        iter->cur = unsafe_yyjson_get_next(key + 1);\n        return key;\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_val *yyjson_obj_iter_get_val(yyjson_val *key) {\n    return key ? key + 1 : NULL;\n}\n\nyyjson_api_inline yyjson_val *yyjson_obj_iter_get(yyjson_obj_iter *iter,\n                                                  const char *key) {\n    return yyjson_obj_iter_getn(iter, key, key ? strlen(key) : 0);\n}\n\nyyjson_api_inline yyjson_val *yyjson_obj_iter_getn(yyjson_obj_iter *iter,\n                                                   const char *key,\n                                                   size_t key_len) {\n    if (iter && key) {\n        size_t idx = iter->idx;\n        size_t max = iter->max;\n        yyjson_val *cur = iter->cur;\n        if (yyjson_unlikely(idx == max)) {\n            idx = 0;\n            cur = unsafe_yyjson_get_first(iter->obj);\n        }\n        while (idx++ < max) {\n            yyjson_val *next = unsafe_yyjson_get_next(cur + 1);\n            if (unsafe_yyjson_equals_strn(cur, key, key_len)) {\n                iter->idx = idx;\n                iter->cur = next;\n                return cur + 1;\n            }\n            cur = next;\n            if (idx == iter->max && iter->idx < iter->max) {\n                idx = 0;\n                max = iter->idx;\n                cur = unsafe_yyjson_get_first(iter->obj);\n            }\n        }\n    }\n    return NULL;\n}\n\n\n\n/*==============================================================================\n * Mutable JSON Structure (Implementation)\n *============================================================================*/\n\n/**\n Mutable JSON value, 24 bytes.\n The 'tag' and 'uni' field is same as immutable value.\n The 'next' field links all elements inside the container to be a cycle.\n */\nstruct yyjson_mut_val {\n    uint64_t tag; /**< type, subtype and length */\n    yyjson_val_uni uni; /**< payload */\n    yyjson_mut_val *next; /**< the next value in circular linked list */\n};\n\n/**\n A memory chunk in string memory pool.\n */\ntypedef struct yyjson_str_chunk {\n    struct yyjson_str_chunk *next; /* next chunk linked list */\n    size_t chunk_size; /* chunk size in bytes */\n    /* char str[]; flexible array member */\n} yyjson_str_chunk;\n\n/**\n A memory pool to hold all strings in a mutable document.\n */\ntypedef struct yyjson_str_pool {\n    char *cur; /* cursor inside current chunk */\n    char *end; /* the end of current chunk */\n    size_t chunk_size; /* chunk size in bytes while creating new chunk */\n    size_t chunk_size_max; /* maximum chunk size in bytes */\n    yyjson_str_chunk *chunks; /* a linked list of chunks, nullable */\n} yyjson_str_pool;\n\n/**\n A memory chunk in value memory pool.\n `sizeof(yyjson_val_chunk)` should not larger than `sizeof(yyjson_mut_val)`.\n */\ntypedef struct yyjson_val_chunk {\n    struct yyjson_val_chunk *next; /* next chunk linked list */\n    size_t chunk_size; /* chunk size in bytes */\n    /* char pad[sizeof(yyjson_mut_val) - sizeof(yyjson_val_chunk)]; padding */\n    /* yyjson_mut_val vals[]; flexible array member */\n} yyjson_val_chunk;\n\n/**\n A memory pool to hold all values in a mutable document.\n */\ntypedef struct yyjson_val_pool {\n    yyjson_mut_val *cur; /* cursor inside current chunk */\n    yyjson_mut_val *end; /* the end of current chunk */\n    size_t chunk_size; /* chunk size in bytes while creating new chunk */\n    size_t chunk_size_max; /* maximum chunk size in bytes */\n    yyjson_val_chunk *chunks; /* a linked list of chunks, nullable */\n} yyjson_val_pool;\n\nstruct yyjson_mut_doc {\n    yyjson_mut_val *root; /**< root value of the JSON document, nullable */\n    yyjson_alc alc; /**< a valid allocator, nonnull */\n    yyjson_str_pool str_pool; /**< string memory pool */\n    yyjson_val_pool val_pool; /**< value memory pool */\n};\n\n/* Ensures the capacity to at least equal to the specified byte length. */\nyyjson_api bool unsafe_yyjson_str_pool_grow(yyjson_str_pool *pool,\n                                            const yyjson_alc *alc,\n                                            size_t len);\n\n/* Ensures the capacity to at least equal to the specified value count. */\nyyjson_api bool unsafe_yyjson_val_pool_grow(yyjson_val_pool *pool,\n                                            const yyjson_alc *alc,\n                                            size_t count);\n\n/* Allocate memory for string. */\nyyjson_api_inline char *unsafe_yyjson_mut_str_alc(yyjson_mut_doc *doc,\n                                                  size_t len) {\n    char *mem;\n    const yyjson_alc *alc = &doc->alc;\n    yyjson_str_pool *pool = &doc->str_pool;\n    if (yyjson_unlikely((size_t)(pool->end - pool->cur) <= len)) {\n        if (yyjson_unlikely(!unsafe_yyjson_str_pool_grow(pool, alc, len + 1))) {\n            return NULL;\n        }\n    }\n    mem = pool->cur;\n    pool->cur = mem + len + 1;\n    return mem;\n}\n\nyyjson_api_inline char *unsafe_yyjson_mut_strncpy(yyjson_mut_doc *doc,\n                                                  const char *str, size_t len) {\n    char *mem = unsafe_yyjson_mut_str_alc(doc, len);\n    if (yyjson_unlikely(!mem)) return NULL;\n    memcpy((void *)mem, (const void *)str, len);\n    mem[len] = '\\0';\n    return mem;\n}\n\nyyjson_api_inline yyjson_mut_val *unsafe_yyjson_mut_val(yyjson_mut_doc *doc,\n                                                        size_t count) {\n    yyjson_mut_val *val;\n    yyjson_alc *alc = &doc->alc;\n    yyjson_val_pool *pool = &doc->val_pool;\n    if (yyjson_unlikely((size_t)(pool->end - pool->cur) < count)) {\n        if (yyjson_unlikely(!unsafe_yyjson_val_pool_grow(pool, alc, count))) {\n            return NULL;\n        }\n    }\n    val = pool->cur;\n    pool->cur += count;\n    return val;\n}\n\n\n\n/*==============================================================================\n * Mutable JSON Document API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_get_root(yyjson_mut_doc *doc) {\n    return doc ? doc->root : NULL;\n}\n\nyyjson_api_inline void yyjson_mut_doc_set_root(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *root) {\n    if (doc) doc->root = root;\n}\n\n\n\n/*==============================================================================\n * Mutable JSON Value Type API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline bool yyjson_mut_is_raw(yyjson_mut_val *val) {\n    return val ? unsafe_yyjson_is_raw(val) : false;\n}\n\nyyjson_api_inline bool yyjson_mut_is_null(yyjson_mut_val *val) {\n    return val ? unsafe_yyjson_is_null(val) : false;\n}\n\nyyjson_api_inline bool yyjson_mut_is_true(yyjson_mut_val *val) {\n    return val ? unsafe_yyjson_is_true(val) : false;\n}\n\nyyjson_api_inline bool yyjson_mut_is_false(yyjson_mut_val *val) {\n    return val ? unsafe_yyjson_is_false(val) : false;\n}\n\nyyjson_api_inline bool yyjson_mut_is_bool(yyjson_mut_val *val) {\n    return val ? unsafe_yyjson_is_bool(val) : false;\n}\n\nyyjson_api_inline bool yyjson_mut_is_uint(yyjson_mut_val *val) {\n    return val ? unsafe_yyjson_is_uint(val) : false;\n}\n\nyyjson_api_inline bool yyjson_mut_is_sint(yyjson_mut_val *val) {\n    return val ? unsafe_yyjson_is_sint(val) : false;\n}\n\nyyjson_api_inline bool yyjson_mut_is_int(yyjson_mut_val *val) {\n    return val ? unsafe_yyjson_is_int(val) : false;\n}\n\nyyjson_api_inline bool yyjson_mut_is_real(yyjson_mut_val *val) {\n    return val ? unsafe_yyjson_is_real(val) : false;\n}\n\nyyjson_api_inline bool yyjson_mut_is_num(yyjson_mut_val *val) {\n    return val ? unsafe_yyjson_is_num(val) : false;\n}\n\nyyjson_api_inline bool yyjson_mut_is_str(yyjson_mut_val *val) {\n    return val ? unsafe_yyjson_is_str(val) : false;\n}\n\nyyjson_api_inline bool yyjson_mut_is_arr(yyjson_mut_val *val) {\n    return val ? unsafe_yyjson_is_arr(val) : false;\n}\n\nyyjson_api_inline bool yyjson_mut_is_obj(yyjson_mut_val *val) {\n    return val ? unsafe_yyjson_is_obj(val) : false;\n}\n\nyyjson_api_inline bool yyjson_mut_is_ctn(yyjson_mut_val *val) {\n    return val ? unsafe_yyjson_is_ctn(val) : false;\n}\n\n\n\n/*==============================================================================\n * Mutable JSON Value Content API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline yyjson_type yyjson_mut_get_type(yyjson_mut_val *val) {\n    return yyjson_get_type((yyjson_val *)val);\n}\n\nyyjson_api_inline yyjson_subtype yyjson_mut_get_subtype(yyjson_mut_val *val) {\n    return yyjson_get_subtype((yyjson_val *)val);\n}\n\nyyjson_api_inline uint8_t yyjson_mut_get_tag(yyjson_mut_val *val) {\n    return yyjson_get_tag((yyjson_val *)val);\n}\n\nyyjson_api_inline const char *yyjson_mut_get_type_desc(yyjson_mut_val *val) {\n    return yyjson_get_type_desc((yyjson_val *)val);\n}\n\nyyjson_api_inline const char *yyjson_mut_get_raw(yyjson_mut_val *val) {\n    return yyjson_get_raw((yyjson_val *)val);\n}\n\nyyjson_api_inline bool yyjson_mut_get_bool(yyjson_mut_val *val) {\n    return yyjson_get_bool((yyjson_val *)val);\n}\n\nyyjson_api_inline uint64_t yyjson_mut_get_uint(yyjson_mut_val *val) {\n    return yyjson_get_uint((yyjson_val *)val);\n}\n\nyyjson_api_inline int64_t yyjson_mut_get_sint(yyjson_mut_val *val) {\n    return yyjson_get_sint((yyjson_val *)val);\n}\n\nyyjson_api_inline int yyjson_mut_get_int(yyjson_mut_val *val) {\n    return yyjson_get_int((yyjson_val *)val);\n}\n\nyyjson_api_inline double yyjson_mut_get_real(yyjson_mut_val *val) {\n    return yyjson_get_real((yyjson_val *)val);\n}\n\nyyjson_api_inline double yyjson_mut_get_num(yyjson_mut_val *val) {\n    return yyjson_get_num((yyjson_val *)val);\n}\n\nyyjson_api_inline const char *yyjson_mut_get_str(yyjson_mut_val *val) {\n    return yyjson_get_str((yyjson_val *)val);\n}\n\nyyjson_api_inline size_t yyjson_mut_get_len(yyjson_mut_val *val) {\n    return yyjson_get_len((yyjson_val *)val);\n}\n\nyyjson_api_inline bool yyjson_mut_equals_str(yyjson_mut_val *val,\n                                             const char *str) {\n    return yyjson_equals_str((yyjson_val *)val, str);\n}\n\nyyjson_api_inline bool yyjson_mut_equals_strn(yyjson_mut_val *val,\n                                              const char *str, size_t len) {\n    return yyjson_equals_strn((yyjson_val *)val, str, len);\n}\n\nyyjson_api bool unsafe_yyjson_mut_equals(yyjson_mut_val *lhs,\n                                         yyjson_mut_val *rhs);\n\nyyjson_api_inline bool yyjson_mut_equals(yyjson_mut_val *lhs,\n                                         yyjson_mut_val *rhs) {\n    if (yyjson_unlikely(!lhs || !rhs)) return false;\n    return unsafe_yyjson_mut_equals(lhs, rhs);\n}\n\nyyjson_api_inline bool yyjson_mut_set_raw(yyjson_mut_val *val,\n                                          const char *raw, size_t len) {\n    if (yyjson_unlikely(!val || !raw)) return false;\n    unsafe_yyjson_set_raw(val, raw, len);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_mut_set_null(yyjson_mut_val *val) {\n    if (yyjson_unlikely(!val)) return false;\n    unsafe_yyjson_set_null(val);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_mut_set_bool(yyjson_mut_val *val, bool num) {\n    if (yyjson_unlikely(!val)) return false;\n    unsafe_yyjson_set_bool(val, num);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_mut_set_uint(yyjson_mut_val *val, uint64_t num) {\n    if (yyjson_unlikely(!val)) return false;\n    unsafe_yyjson_set_uint(val, num);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_mut_set_sint(yyjson_mut_val *val, int64_t num) {\n    if (yyjson_unlikely(!val)) return false;\n    unsafe_yyjson_set_sint(val, num);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_mut_set_int(yyjson_mut_val *val, int num) {\n    if (yyjson_unlikely(!val)) return false;\n    unsafe_yyjson_set_sint(val, (int64_t)num);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_mut_set_real(yyjson_mut_val *val, double num) {\n    if (yyjson_unlikely(!val)) return false;\n    unsafe_yyjson_set_real(val, num);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_mut_set_str(yyjson_mut_val *val,\n                                          const char *str) {\n    if (yyjson_unlikely(!val || !str)) return false;\n    unsafe_yyjson_set_str(val, str);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_mut_set_strn(yyjson_mut_val *val,\n                                           const char *str, size_t len) {\n    if (yyjson_unlikely(!val || !str)) return false;\n    unsafe_yyjson_set_strn(val, str, len);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_mut_set_arr(yyjson_mut_val *val) {\n    if (yyjson_unlikely(!val)) return false;\n    unsafe_yyjson_set_arr(val, 0);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_mut_set_obj(yyjson_mut_val *val) {\n    if (yyjson_unlikely(!val)) return false;\n    unsafe_yyjson_set_obj(val, 0);\n    return true;\n}\n\n\n\n/*==============================================================================\n * Mutable JSON Value Creation API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_raw(yyjson_mut_doc *doc,\n                                                 const char *str) {\n    if (yyjson_likely(str)) return yyjson_mut_rawn(doc, str, strlen(str));\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_rawn(yyjson_mut_doc *doc,\n                                                  const char *str,\n                                                  size_t len) {\n    if (yyjson_likely(doc && str)) {\n        yyjson_mut_val *val = unsafe_yyjson_mut_val(doc, 1);\n        if (yyjson_likely(val)) {\n            val->tag = ((uint64_t)len << YYJSON_TAG_BIT) | YYJSON_TYPE_RAW;\n            val->uni.str = str;\n            return val;\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_rawcpy(yyjson_mut_doc *doc,\n                                                    const char *str) {\n    if (yyjson_likely(str)) return yyjson_mut_rawncpy(doc, str, strlen(str));\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_rawncpy(yyjson_mut_doc *doc,\n                                                     const char *str,\n                                                     size_t len) {\n    if (yyjson_likely(doc && str)) {\n        yyjson_mut_val *val = unsafe_yyjson_mut_val(doc, 1);\n        char *new_str = unsafe_yyjson_mut_strncpy(doc, str, len);\n        if (yyjson_likely(val && new_str)) {\n            val->tag = ((uint64_t)len << YYJSON_TAG_BIT) | YYJSON_TYPE_RAW;\n            val->uni.str = new_str;\n            return val;\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_null(yyjson_mut_doc *doc) {\n    if (yyjson_likely(doc)) {\n        yyjson_mut_val *val = unsafe_yyjson_mut_val(doc, 1);\n        if (yyjson_likely(val)) {\n            val->tag = YYJSON_TYPE_NULL | YYJSON_SUBTYPE_NONE;\n            return val;\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_true(yyjson_mut_doc *doc) {\n    if (yyjson_likely(doc)) {\n        yyjson_mut_val *val = unsafe_yyjson_mut_val(doc, 1);\n        if (yyjson_likely(val)) {\n            val->tag = YYJSON_TYPE_BOOL | YYJSON_SUBTYPE_TRUE;\n            return val;\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_false(yyjson_mut_doc *doc) {\n    if (yyjson_likely(doc)) {\n        yyjson_mut_val *val = unsafe_yyjson_mut_val(doc, 1);\n        if (yyjson_likely(val)) {\n            val->tag = YYJSON_TYPE_BOOL | YYJSON_SUBTYPE_FALSE;\n            return val;\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_bool(yyjson_mut_doc *doc,\n                                                  bool _val) {\n    if (yyjson_likely(doc)) {\n        yyjson_mut_val *val = unsafe_yyjson_mut_val(doc, 1);\n        if (yyjson_likely(val)) {\n            _val = !!_val;\n            val->tag = YYJSON_TYPE_BOOL | (uint8_t)((uint8_t)_val << 3);\n            return val;\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_uint(yyjson_mut_doc *doc,\n                                                  uint64_t num) {\n    if (yyjson_likely(doc)) {\n        yyjson_mut_val *val = unsafe_yyjson_mut_val(doc, 1);\n        if (yyjson_likely(val)) {\n            val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_UINT;\n            val->uni.u64 = num;\n            return val;\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_sint(yyjson_mut_doc *doc,\n                                                  int64_t num) {\n    if (yyjson_likely(doc)) {\n        yyjson_mut_val *val = unsafe_yyjson_mut_val(doc, 1);\n        if (yyjson_likely(val)) {\n            val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_SINT;\n            val->uni.i64 = num;\n            return val;\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_int(yyjson_mut_doc *doc,\n                                                 int64_t num) {\n    return yyjson_mut_sint(doc, num);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_real(yyjson_mut_doc *doc,\n                                                  double num) {\n    if (yyjson_likely(doc)) {\n        yyjson_mut_val *val = unsafe_yyjson_mut_val(doc, 1);\n        if (yyjson_likely(val)) {\n            val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL;\n            val->uni.f64 = num;\n            return val;\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_str(yyjson_mut_doc *doc,\n                                                 const char *str) {\n    if (yyjson_likely(doc && str)) {\n        size_t len = strlen(str);\n        bool noesc = unsafe_yyjson_is_str_noesc(str, len);\n        yyjson_subtype sub = noesc ? YYJSON_SUBTYPE_NOESC : YYJSON_SUBTYPE_NONE;\n        yyjson_mut_val *val = unsafe_yyjson_mut_val(doc, 1);\n        if (yyjson_likely(val)) {\n            val->tag = ((uint64_t)len << YYJSON_TAG_BIT) |\n                        (uint64_t)(YYJSON_TYPE_STR | sub);\n            val->uni.str = str;\n            return val;\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_strn(yyjson_mut_doc *doc,\n                                                  const char *str,\n                                                  size_t len) {\n    if (yyjson_likely(doc && str)) {\n        yyjson_mut_val *val = unsafe_yyjson_mut_val(doc, 1);\n        if (yyjson_likely(val)) {\n            val->tag = ((uint64_t)len << YYJSON_TAG_BIT) | YYJSON_TYPE_STR;\n            val->uni.str = str;\n            return val;\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_strcpy(yyjson_mut_doc *doc,\n                                                    const char *str) {\n    if (yyjson_likely(doc && str)) {\n        size_t len = strlen(str);\n        bool noesc = unsafe_yyjson_is_str_noesc(str, len);\n        yyjson_subtype sub = noesc ? YYJSON_SUBTYPE_NOESC : YYJSON_SUBTYPE_NONE;\n        yyjson_mut_val *val = unsafe_yyjson_mut_val(doc, 1);\n        char *new_str = unsafe_yyjson_mut_strncpy(doc, str, len);\n        if (yyjson_likely(val && new_str)) {\n            val->tag = ((uint64_t)len << YYJSON_TAG_BIT) |\n                        (uint64_t)(YYJSON_TYPE_STR | sub);\n            val->uni.str = new_str;\n            return val;\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_strncpy(yyjson_mut_doc *doc,\n                                                     const char *str,\n                                                     size_t len) {\n    if (yyjson_likely(doc && str)) {\n        yyjson_mut_val *val = unsafe_yyjson_mut_val(doc, 1);\n        char *new_str = unsafe_yyjson_mut_strncpy(doc, str, len);\n        if (yyjson_likely(val && new_str)) {\n            val->tag = ((uint64_t)len << YYJSON_TAG_BIT) | YYJSON_TYPE_STR;\n            val->uni.str = new_str;\n            return val;\n        }\n    }\n    return NULL;\n}\n\n\n\n/*==============================================================================\n * Mutable JSON Array API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline size_t yyjson_mut_arr_size(yyjson_mut_val *arr) {\n    return yyjson_mut_is_arr(arr) ? unsafe_yyjson_get_len(arr) : 0;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_get(yyjson_mut_val *arr,\n                                                     size_t idx) {\n    if (yyjson_likely(idx < yyjson_mut_arr_size(arr))) {\n        yyjson_mut_val *val = (yyjson_mut_val *)arr->uni.ptr;\n        while (idx-- > 0) val = val->next;\n        return val->next;\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_get_first(\n    yyjson_mut_val *arr) {\n    if (yyjson_likely(yyjson_mut_arr_size(arr) > 0)) {\n        return ((yyjson_mut_val *)arr->uni.ptr)->next;\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_get_last(\n    yyjson_mut_val *arr) {\n    if (yyjson_likely(yyjson_mut_arr_size(arr) > 0)) {\n        return ((yyjson_mut_val *)arr->uni.ptr);\n    }\n    return NULL;\n}\n\n\n\n/*==============================================================================\n * Mutable JSON Array Iterator API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline bool yyjson_mut_arr_iter_init(yyjson_mut_val *arr,\n                                                yyjson_mut_arr_iter *iter) {\n    if (yyjson_likely(yyjson_mut_is_arr(arr) && iter)) {\n        iter->idx = 0;\n        iter->max = unsafe_yyjson_get_len(arr);\n        iter->cur = iter->max ? (yyjson_mut_val *)arr->uni.ptr : NULL;\n        iter->pre = NULL;\n        iter->arr = arr;\n        return true;\n    }\n    if (iter) memset(iter, 0, sizeof(yyjson_mut_arr_iter));\n    return false;\n}\n\nyyjson_api_inline yyjson_mut_arr_iter yyjson_mut_arr_iter_with(\n    yyjson_mut_val *arr) {\n    yyjson_mut_arr_iter iter;\n    yyjson_mut_arr_iter_init(arr, &iter);\n    return iter;\n}\n\nyyjson_api_inline bool yyjson_mut_arr_iter_has_next(yyjson_mut_arr_iter *iter) {\n    return iter ? iter->idx < iter->max : false;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_iter_next(\n    yyjson_mut_arr_iter *iter) {\n    if (iter && iter->idx < iter->max) {\n        yyjson_mut_val *val = iter->cur;\n        iter->pre = val;\n        iter->cur = val->next;\n        iter->idx++;\n        return iter->cur;\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_iter_remove(\n    yyjson_mut_arr_iter *iter) {\n    if (yyjson_likely(iter && 0 < iter->idx && iter->idx <= iter->max)) {\n        yyjson_mut_val *prev = iter->pre;\n        yyjson_mut_val *cur = iter->cur;\n        yyjson_mut_val *next = cur->next;\n        if (yyjson_unlikely(iter->idx == iter->max)) iter->arr->uni.ptr = prev;\n        iter->idx--;\n        iter->max--;\n        unsafe_yyjson_set_len(iter->arr, iter->max);\n        prev->next = next;\n        iter->cur = next;\n        return cur;\n    }\n    return NULL;\n}\n\n\n\n/*==============================================================================\n * Mutable JSON Array Creation API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr(yyjson_mut_doc *doc) {\n    if (yyjson_likely(doc)) {\n        yyjson_mut_val *val = unsafe_yyjson_mut_val(doc, 1);\n        if (yyjson_likely(val)) {\n            val->tag = YYJSON_TYPE_ARR | YYJSON_SUBTYPE_NONE;\n            return val;\n        }\n    }\n    return NULL;\n}\n\n#define yyjson_mut_arr_with_func(func) \\\n    if (yyjson_likely(doc && ((0 < count && count < \\\n        (~(size_t)0) / sizeof(yyjson_mut_val) && vals) || count == 0))) { \\\n        yyjson_mut_val *arr = unsafe_yyjson_mut_val(doc, 1 + count); \\\n        if (yyjson_likely(arr)) { \\\n            arr->tag = ((uint64_t)count << YYJSON_TAG_BIT) | YYJSON_TYPE_ARR; \\\n            if (count > 0) { \\\n                size_t i; \\\n                for (i = 0; i < count; i++) { \\\n                    yyjson_mut_val *val = arr + i + 1; \\\n                    func \\\n                    val->next = val + 1; \\\n                } \\\n                arr[count].next = arr + 1; \\\n                arr->uni.ptr = arr + count; \\\n            } \\\n            return arr; \\\n        } \\\n    } \\\n    return NULL\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_bool(\n    yyjson_mut_doc *doc, const bool *vals, size_t count) {\n    yyjson_mut_arr_with_func({\n        bool _val = !!vals[i];\n        val->tag = YYJSON_TYPE_BOOL | (uint8_t)((uint8_t)_val << 3);\n    });\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_sint(\n    yyjson_mut_doc *doc, const int64_t *vals, size_t count) {\n    return yyjson_mut_arr_with_sint64(doc, vals, count);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_uint(\n    yyjson_mut_doc *doc, const uint64_t *vals, size_t count) {\n    return yyjson_mut_arr_with_uint64(doc, vals, count);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_real(\n    yyjson_mut_doc *doc, const double *vals, size_t count) {\n    return yyjson_mut_arr_with_double(doc, vals, count);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_sint8(\n    yyjson_mut_doc *doc, const int8_t *vals, size_t count) {\n    yyjson_mut_arr_with_func({\n        val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_SINT;\n        val->uni.i64 = (int64_t)vals[i];\n    });\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_sint16(\n    yyjson_mut_doc *doc, const int16_t *vals, size_t count) {\n    yyjson_mut_arr_with_func({\n        val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_SINT;\n        val->uni.i64 = vals[i];\n    });\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_sint32(\n    yyjson_mut_doc *doc, const int32_t *vals, size_t count) {\n    yyjson_mut_arr_with_func({\n        val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_SINT;\n        val->uni.i64 = vals[i];\n    });\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_sint64(\n    yyjson_mut_doc *doc, const int64_t *vals, size_t count) {\n    yyjson_mut_arr_with_func({\n        val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_SINT;\n        val->uni.i64 = vals[i];\n    });\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_uint8(\n    yyjson_mut_doc *doc, const uint8_t *vals, size_t count) {\n    yyjson_mut_arr_with_func({\n        val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_UINT;\n        val->uni.u64 = vals[i];\n    });\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_uint16(\n    yyjson_mut_doc *doc, const uint16_t *vals, size_t count) {\n    yyjson_mut_arr_with_func({\n        val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_UINT;\n        val->uni.u64 = vals[i];\n    });\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_uint32(\n    yyjson_mut_doc *doc, const uint32_t *vals, size_t count) {\n    yyjson_mut_arr_with_func({\n        val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_UINT;\n        val->uni.u64 = vals[i];\n    });\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_uint64(\n    yyjson_mut_doc *doc, const uint64_t *vals, size_t count) {\n    yyjson_mut_arr_with_func({\n        val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_UINT;\n        val->uni.u64 = vals[i];\n    });\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_float(\n    yyjson_mut_doc *doc, const float *vals, size_t count) {\n    yyjson_mut_arr_with_func({\n        val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL;\n        val->uni.f64 = (double)vals[i];\n    });\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_double(\n    yyjson_mut_doc *doc, const double *vals, size_t count) {\n    yyjson_mut_arr_with_func({\n        val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL;\n        val->uni.f64 = vals[i];\n    });\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_str(\n    yyjson_mut_doc *doc, const char **vals, size_t count) {\n    yyjson_mut_arr_with_func({\n        uint64_t len = (uint64_t)strlen(vals[i]);\n        val->tag = (len << YYJSON_TAG_BIT) | YYJSON_TYPE_STR;\n        val->uni.str = vals[i];\n        if (yyjson_unlikely(!val->uni.str)) return NULL;\n    });\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_strn(\n    yyjson_mut_doc *doc, const char **vals, const size_t *lens, size_t count) {\n    if (yyjson_unlikely(count > 0 && !lens)) return NULL;\n    yyjson_mut_arr_with_func({\n        val->tag = ((uint64_t)lens[i] << YYJSON_TAG_BIT) | YYJSON_TYPE_STR;\n        val->uni.str = vals[i];\n        if (yyjson_unlikely(!val->uni.str)) return NULL;\n    });\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_strcpy(\n    yyjson_mut_doc *doc, const char **vals, size_t count) {\n    size_t len;\n    const char *str;\n    yyjson_mut_arr_with_func({\n        str = vals[i];\n        if (!str) return NULL;\n        len = strlen(str);\n        val->tag = ((uint64_t)len << YYJSON_TAG_BIT) | YYJSON_TYPE_STR;\n        val->uni.str = unsafe_yyjson_mut_strncpy(doc, str, len);\n        if (yyjson_unlikely(!val->uni.str)) return NULL;\n    });\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_strncpy(\n    yyjson_mut_doc *doc, const char **vals, const size_t *lens, size_t count) {\n    size_t len;\n    const char *str;\n    if (yyjson_unlikely(count > 0 && !lens)) return NULL;\n    yyjson_mut_arr_with_func({\n        str = vals[i];\n        len = lens[i];\n        val->tag = ((uint64_t)len << YYJSON_TAG_BIT) | YYJSON_TYPE_STR;\n        val->uni.str = unsafe_yyjson_mut_strncpy(doc, str, len);\n        if (yyjson_unlikely(!val->uni.str)) return NULL;\n    });\n}\n\n#undef yyjson_mut_arr_with_func\n\n\n\n/*==============================================================================\n * Mutable JSON Array Modification API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline bool yyjson_mut_arr_insert(yyjson_mut_val *arr,\n                                             yyjson_mut_val *val, size_t idx) {\n    if (yyjson_likely(yyjson_mut_is_arr(arr) && val)) {\n        size_t len = unsafe_yyjson_get_len(arr);\n        if (yyjson_likely(idx <= len)) {\n            unsafe_yyjson_set_len(arr, len + 1);\n            if (len == 0) {\n                val->next = val;\n                arr->uni.ptr = val;\n            } else {\n                yyjson_mut_val *prev = ((yyjson_mut_val *)arr->uni.ptr);\n                yyjson_mut_val *next = prev->next;\n                if (idx == len) {\n                    prev->next = val;\n                    val->next = next;\n                    arr->uni.ptr = val;\n                } else {\n                    while (idx-- > 0) {\n                        prev = next;\n                        next = next->next;\n                    }\n                    prev->next = val;\n                    val->next = next;\n                }\n            }\n            return true;\n        }\n    }\n    return false;\n}\n\nyyjson_api_inline bool yyjson_mut_arr_append(yyjson_mut_val *arr,\n                                             yyjson_mut_val *val) {\n    if (yyjson_likely(yyjson_mut_is_arr(arr) && val)) {\n        size_t len = unsafe_yyjson_get_len(arr);\n        unsafe_yyjson_set_len(arr, len + 1);\n        if (len == 0) {\n            val->next = val;\n        } else {\n            yyjson_mut_val *prev = ((yyjson_mut_val *)arr->uni.ptr);\n            yyjson_mut_val *next = prev->next;\n            prev->next = val;\n            val->next = next;\n        }\n        arr->uni.ptr = val;\n        return true;\n    }\n    return false;\n}\n\nyyjson_api_inline bool yyjson_mut_arr_prepend(yyjson_mut_val *arr,\n                                              yyjson_mut_val *val) {\n    if (yyjson_likely(yyjson_mut_is_arr(arr) && val)) {\n        size_t len = unsafe_yyjson_get_len(arr);\n        unsafe_yyjson_set_len(arr, len + 1);\n        if (len == 0) {\n            val->next = val;\n            arr->uni.ptr = val;\n        } else {\n            yyjson_mut_val *prev = ((yyjson_mut_val *)arr->uni.ptr);\n            yyjson_mut_val *next = prev->next;\n            prev->next = val;\n            val->next = next;\n        }\n        return true;\n    }\n    return false;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_replace(yyjson_mut_val *arr,\n                                                         size_t idx,\n                                                         yyjson_mut_val *val) {\n    if (yyjson_likely(yyjson_mut_is_arr(arr) && val)) {\n        size_t len = unsafe_yyjson_get_len(arr);\n        if (yyjson_likely(idx < len)) {\n            if (yyjson_likely(len > 1)) {\n                yyjson_mut_val *prev = ((yyjson_mut_val *)arr->uni.ptr);\n                yyjson_mut_val *next = prev->next;\n                while (idx-- > 0) {\n                    prev = next;\n                    next = next->next;\n                }\n                prev->next = val;\n                val->next = next->next;\n                if ((void *)next == arr->uni.ptr) arr->uni.ptr = val;\n                return next;\n            } else {\n                yyjson_mut_val *prev = ((yyjson_mut_val *)arr->uni.ptr);\n                val->next = val;\n                arr->uni.ptr = val;\n                return prev;\n            }\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_remove(yyjson_mut_val *arr,\n                                                        size_t idx) {\n    if (yyjson_likely(yyjson_mut_is_arr(arr))) {\n        size_t len = unsafe_yyjson_get_len(arr);\n        if (yyjson_likely(idx < len)) {\n            unsafe_yyjson_set_len(arr, len - 1);\n            if (yyjson_likely(len > 1)) {\n                yyjson_mut_val *prev = ((yyjson_mut_val *)arr->uni.ptr);\n                yyjson_mut_val *next = prev->next;\n                while (idx-- > 0) {\n                    prev = next;\n                    next = next->next;\n                }\n                prev->next = next->next;\n                if ((void *)next == arr->uni.ptr) arr->uni.ptr = prev;\n                return next;\n            } else {\n                return ((yyjson_mut_val *)arr->uni.ptr);\n            }\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_remove_first(\n    yyjson_mut_val *arr) {\n    if (yyjson_likely(yyjson_mut_is_arr(arr))) {\n        size_t len = unsafe_yyjson_get_len(arr);\n        if (len > 1) {\n            yyjson_mut_val *prev = ((yyjson_mut_val *)arr->uni.ptr);\n            yyjson_mut_val *next = prev->next;\n            prev->next = next->next;\n            unsafe_yyjson_set_len(arr, len - 1);\n            return next;\n        } else if (len == 1) {\n            yyjson_mut_val *prev = ((yyjson_mut_val *)arr->uni.ptr);\n            unsafe_yyjson_set_len(arr, 0);\n            return prev;\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_remove_last(\n    yyjson_mut_val *arr) {\n    if (yyjson_likely(yyjson_mut_is_arr(arr))) {\n        size_t len = unsafe_yyjson_get_len(arr);\n        if (yyjson_likely(len > 1)) {\n            yyjson_mut_val *prev = ((yyjson_mut_val *)arr->uni.ptr);\n            yyjson_mut_val *next = prev->next;\n            unsafe_yyjson_set_len(arr, len - 1);\n            while (--len > 0) prev = prev->next;\n            prev->next = next;\n            next = (yyjson_mut_val *)arr->uni.ptr;\n            arr->uni.ptr = prev;\n            return next;\n        } else if (len == 1) {\n            yyjson_mut_val *prev = ((yyjson_mut_val *)arr->uni.ptr);\n            unsafe_yyjson_set_len(arr, 0);\n            return prev;\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline bool yyjson_mut_arr_remove_range(yyjson_mut_val *arr,\n                                                   size_t _idx, size_t _len) {\n    if (yyjson_likely(yyjson_mut_is_arr(arr))) {\n        yyjson_mut_val *prev, *next;\n        bool tail_removed;\n        size_t len = unsafe_yyjson_get_len(arr);\n        if (yyjson_unlikely(_idx + _len > len)) return false;\n        if (yyjson_unlikely(_len == 0)) return true;\n        unsafe_yyjson_set_len(arr, len - _len);\n        if (yyjson_unlikely(len == _len)) return true;\n        tail_removed = (_idx + _len == len);\n        prev = ((yyjson_mut_val *)arr->uni.ptr);\n        while (_idx-- > 0) prev = prev->next;\n        next = prev->next;\n        while (_len-- > 0) next = next->next;\n        prev->next = next;\n        if (yyjson_unlikely(tail_removed)) arr->uni.ptr = prev;\n        return true;\n    }\n    return false;\n}\n\nyyjson_api_inline bool yyjson_mut_arr_clear(yyjson_mut_val *arr) {\n    if (yyjson_likely(yyjson_mut_is_arr(arr))) {\n        unsafe_yyjson_set_len(arr, 0);\n        return true;\n    }\n    return false;\n}\n\nyyjson_api_inline bool yyjson_mut_arr_rotate(yyjson_mut_val *arr,\n                                             size_t idx) {\n    if (yyjson_likely(yyjson_mut_is_arr(arr) &&\n                      unsafe_yyjson_get_len(arr) > idx)) {\n        yyjson_mut_val *val = (yyjson_mut_val *)arr->uni.ptr;\n        while (idx-- > 0) val = val->next;\n        arr->uni.ptr = (void *)val;\n        return true;\n    }\n    return false;\n}\n\n\n\n/*==============================================================================\n * Mutable JSON Array Modification Convenience API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline bool yyjson_mut_arr_add_val(yyjson_mut_val *arr,\n                                              yyjson_mut_val *val) {\n    return yyjson_mut_arr_append(arr, val);\n}\n\nyyjson_api_inline bool yyjson_mut_arr_add_null(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *arr) {\n    if (yyjson_likely(doc && yyjson_mut_is_arr(arr))) {\n        yyjson_mut_val *val = yyjson_mut_null(doc);\n        return yyjson_mut_arr_append(arr, val);\n    }\n    return false;\n}\n\nyyjson_api_inline bool yyjson_mut_arr_add_true(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *arr) {\n    if (yyjson_likely(doc && yyjson_mut_is_arr(arr))) {\n        yyjson_mut_val *val = yyjson_mut_true(doc);\n        return yyjson_mut_arr_append(arr, val);\n    }\n    return false;\n}\n\nyyjson_api_inline bool yyjson_mut_arr_add_false(yyjson_mut_doc *doc,\n                                                yyjson_mut_val *arr) {\n    if (yyjson_likely(doc && yyjson_mut_is_arr(arr))) {\n        yyjson_mut_val *val = yyjson_mut_false(doc);\n        return yyjson_mut_arr_append(arr, val);\n    }\n    return false;\n}\n\nyyjson_api_inline bool yyjson_mut_arr_add_bool(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *arr,\n                                               bool _val) {\n    if (yyjson_likely(doc && yyjson_mut_is_arr(arr))) {\n        yyjson_mut_val *val = yyjson_mut_bool(doc, _val);\n        return yyjson_mut_arr_append(arr, val);\n    }\n    return false;\n}\n\nyyjson_api_inline bool yyjson_mut_arr_add_uint(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *arr,\n                                               uint64_t num) {\n    if (yyjson_likely(doc && yyjson_mut_is_arr(arr))) {\n        yyjson_mut_val *val = yyjson_mut_uint(doc, num);\n        return yyjson_mut_arr_append(arr, val);\n    }\n    return false;\n}\n\nyyjson_api_inline bool yyjson_mut_arr_add_sint(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *arr,\n                                               int64_t num) {\n    if (yyjson_likely(doc && yyjson_mut_is_arr(arr))) {\n        yyjson_mut_val *val = yyjson_mut_sint(doc, num);\n        return yyjson_mut_arr_append(arr, val);\n    }\n    return false;\n}\n\nyyjson_api_inline bool yyjson_mut_arr_add_int(yyjson_mut_doc *doc,\n                                              yyjson_mut_val *arr,\n                                              int64_t num) {\n    if (yyjson_likely(doc && yyjson_mut_is_arr(arr))) {\n        yyjson_mut_val *val = yyjson_mut_sint(doc, num);\n        return yyjson_mut_arr_append(arr, val);\n    }\n    return false;\n}\n\nyyjson_api_inline bool yyjson_mut_arr_add_real(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *arr,\n                                               double num) {\n    if (yyjson_likely(doc && yyjson_mut_is_arr(arr))) {\n        yyjson_mut_val *val = yyjson_mut_real(doc, num);\n        return yyjson_mut_arr_append(arr, val);\n    }\n    return false;\n}\n\nyyjson_api_inline bool yyjson_mut_arr_add_str(yyjson_mut_doc *doc,\n                                              yyjson_mut_val *arr,\n                                              const char *str) {\n    if (yyjson_likely(doc && yyjson_mut_is_arr(arr))) {\n        yyjson_mut_val *val = yyjson_mut_str(doc, str);\n        return yyjson_mut_arr_append(arr, val);\n    }\n    return false;\n}\n\nyyjson_api_inline bool yyjson_mut_arr_add_strn(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *arr,\n                                               const char *str, size_t len) {\n    if (yyjson_likely(doc && yyjson_mut_is_arr(arr))) {\n        yyjson_mut_val *val = yyjson_mut_strn(doc, str, len);\n        return yyjson_mut_arr_append(arr, val);\n    }\n    return false;\n}\n\nyyjson_api_inline bool yyjson_mut_arr_add_strcpy(yyjson_mut_doc *doc,\n                                                 yyjson_mut_val *arr,\n                                                 const char *str) {\n    if (yyjson_likely(doc && yyjson_mut_is_arr(arr))) {\n        yyjson_mut_val *val = yyjson_mut_strcpy(doc, str);\n        return yyjson_mut_arr_append(arr, val);\n    }\n    return false;\n}\n\nyyjson_api_inline bool yyjson_mut_arr_add_strncpy(yyjson_mut_doc *doc,\n                                                  yyjson_mut_val *arr,\n                                                  const char *str, size_t len) {\n    if (yyjson_likely(doc && yyjson_mut_is_arr(arr))) {\n        yyjson_mut_val *val = yyjson_mut_strncpy(doc, str, len);\n        return yyjson_mut_arr_append(arr, val);\n    }\n    return false;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_add_arr(yyjson_mut_doc *doc,\n                                                         yyjson_mut_val *arr) {\n    if (yyjson_likely(doc && yyjson_mut_is_arr(arr))) {\n        yyjson_mut_val *val = yyjson_mut_arr(doc);\n        return yyjson_mut_arr_append(arr, val) ? val : NULL;\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_arr_add_obj(yyjson_mut_doc *doc,\n                                                         yyjson_mut_val *arr) {\n    if (yyjson_likely(doc && yyjson_mut_is_arr(arr))) {\n        yyjson_mut_val *val = yyjson_mut_obj(doc);\n        return yyjson_mut_arr_append(arr, val) ? val : NULL;\n    }\n    return NULL;\n}\n\n\n\n/*==============================================================================\n * Mutable JSON Object API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline size_t yyjson_mut_obj_size(yyjson_mut_val *obj) {\n    return yyjson_mut_is_obj(obj) ? unsafe_yyjson_get_len(obj) : 0;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_get(yyjson_mut_val *obj,\n                                                     const char *key) {\n    return yyjson_mut_obj_getn(obj, key, key ? strlen(key) : 0);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_getn(yyjson_mut_val *obj,\n                                                      const char *_key,\n                                                      size_t key_len) {\n    size_t len = yyjson_mut_obj_size(obj);\n    if (yyjson_likely(len && _key)) {\n        yyjson_mut_val *key = ((yyjson_mut_val *)obj->uni.ptr)->next->next;\n        while (len-- > 0) {\n            if (unsafe_yyjson_equals_strn(key, _key, key_len)) return key->next;\n            key = key->next->next;\n        }\n    }\n    return NULL;\n}\n\n\n\n/*==============================================================================\n * Mutable JSON Object Iterator API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline bool yyjson_mut_obj_iter_init(yyjson_mut_val *obj,\n                                                yyjson_mut_obj_iter *iter) {\n    if (yyjson_likely(yyjson_mut_is_obj(obj) && iter)) {\n        iter->idx = 0;\n        iter->max = unsafe_yyjson_get_len(obj);\n        iter->cur = iter->max ? (yyjson_mut_val *)obj->uni.ptr : NULL;\n        iter->pre = NULL;\n        iter->obj = obj;\n        return true;\n    }\n    if (iter) memset(iter, 0, sizeof(yyjson_mut_obj_iter));\n    return false;\n}\n\nyyjson_api_inline yyjson_mut_obj_iter yyjson_mut_obj_iter_with(\n    yyjson_mut_val *obj) {\n    yyjson_mut_obj_iter iter;\n    yyjson_mut_obj_iter_init(obj, &iter);\n    return iter;\n}\n\nyyjson_api_inline bool yyjson_mut_obj_iter_has_next(yyjson_mut_obj_iter *iter) {\n    return iter ? iter->idx < iter->max : false;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_iter_next(\n    yyjson_mut_obj_iter *iter) {\n    if (iter && iter->idx < iter->max) {\n        yyjson_mut_val *key = iter->cur;\n        iter->pre = key;\n        iter->cur = key->next->next;\n        iter->idx++;\n        return iter->cur;\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_iter_get_val(\n    yyjson_mut_val *key) {\n    return key ? key->next : NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_iter_remove(\n    yyjson_mut_obj_iter *iter) {\n    if (yyjson_likely(iter && 0 < iter->idx && iter->idx <= iter->max)) {\n        yyjson_mut_val *prev = iter->pre;\n        yyjson_mut_val *cur = iter->cur;\n        yyjson_mut_val *next = cur->next->next;\n        if (yyjson_unlikely(iter->idx == iter->max)) iter->obj->uni.ptr = prev;\n        iter->idx--;\n        iter->max--;\n        unsafe_yyjson_set_len(iter->obj, iter->max);\n        prev->next->next = next;\n        iter->cur = prev;\n        return cur->next;\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_iter_get(\n    yyjson_mut_obj_iter *iter, const char *key) {\n    return yyjson_mut_obj_iter_getn(iter, key, key ? strlen(key) : 0);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_iter_getn(\n    yyjson_mut_obj_iter *iter, const char *key, size_t key_len) {\n    if (iter && key) {\n        size_t idx = 0;\n        size_t max = iter->max;\n        yyjson_mut_val *pre, *cur = iter->cur;\n        while (idx++ < max) {\n            pre = cur;\n            cur = cur->next->next;\n            if (unsafe_yyjson_equals_strn(cur, key, key_len)) {\n                iter->idx += idx;\n                if (iter->idx > max) iter->idx -= max + 1;\n                iter->pre = pre;\n                iter->cur = cur;\n                return cur->next;\n            }\n        }\n    }\n    return NULL;\n}\n\n\n\n/*==============================================================================\n * Mutable JSON Object Creation API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj(yyjson_mut_doc *doc) {\n    if (yyjson_likely(doc)) {\n        yyjson_mut_val *val = unsafe_yyjson_mut_val(doc, 1);\n        if (yyjson_likely(val)) {\n            val->tag = YYJSON_TYPE_OBJ | YYJSON_SUBTYPE_NONE;\n            return val;\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_with_str(yyjson_mut_doc *doc,\n                                                          const char **keys,\n                                                          const char **vals,\n                                                          size_t count) {\n    if (yyjson_likely(doc && ((count > 0 && keys && vals) || (count == 0)))) {\n        yyjson_mut_val *obj = unsafe_yyjson_mut_val(doc, 1 + count * 2);\n        if (yyjson_likely(obj)) {\n            obj->tag = ((uint64_t)count << YYJSON_TAG_BIT) | YYJSON_TYPE_OBJ;\n            if (count > 0) {\n                size_t i;\n                for (i = 0; i < count; i++) {\n                    yyjson_mut_val *key = obj + (i * 2 + 1);\n                    yyjson_mut_val *val = obj + (i * 2 + 2);\n                    uint64_t key_len = (uint64_t)strlen(keys[i]);\n                    uint64_t val_len = (uint64_t)strlen(vals[i]);\n                    key->tag = (key_len << YYJSON_TAG_BIT) | YYJSON_TYPE_STR;\n                    val->tag = (val_len << YYJSON_TAG_BIT) | YYJSON_TYPE_STR;\n                    key->uni.str = keys[i];\n                    val->uni.str = vals[i];\n                    key->next = val;\n                    val->next = val + 1;\n                }\n                obj[count * 2].next = obj + 1;\n                obj->uni.ptr = obj + (count * 2 - 1);\n            }\n            return obj;\n        }\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_with_kv(yyjson_mut_doc *doc,\n                                                         const char **pairs,\n                                                         size_t count) {\n    if (yyjson_likely(doc && ((count > 0 && pairs) || (count == 0)))) {\n        yyjson_mut_val *obj = unsafe_yyjson_mut_val(doc, 1 + count * 2);\n        if (yyjson_likely(obj)) {\n            obj->tag = ((uint64_t)count << YYJSON_TAG_BIT) | YYJSON_TYPE_OBJ;\n            if (count > 0) {\n                size_t i;\n                for (i = 0; i < count; i++) {\n                    yyjson_mut_val *key = obj + (i * 2 + 1);\n                    yyjson_mut_val *val = obj + (i * 2 + 2);\n                    const char *key_str = pairs[i * 2 + 0];\n                    const char *val_str = pairs[i * 2 + 1];\n                    uint64_t key_len = (uint64_t)strlen(key_str);\n                    uint64_t val_len = (uint64_t)strlen(val_str);\n                    key->tag = (key_len << YYJSON_TAG_BIT) | YYJSON_TYPE_STR;\n                    val->tag = (val_len << YYJSON_TAG_BIT) | YYJSON_TYPE_STR;\n                    key->uni.str = key_str;\n                    val->uni.str = val_str;\n                    key->next = val;\n                    val->next = val + 1;\n                }\n                obj[count * 2].next = obj + 1;\n                obj->uni.ptr = obj + (count * 2 - 1);\n            }\n            return obj;\n        }\n    }\n    return NULL;\n}\n\n\n\n/*==============================================================================\n * Mutable JSON Object Modification API (Implementation)\n *============================================================================*/\n\nyyjson_api_inline void unsafe_yyjson_mut_obj_add(yyjson_mut_val *obj,\n                                                 yyjson_mut_val *key,\n                                                 yyjson_mut_val *val,\n                                                 size_t len) {\n    if (yyjson_likely(len)) {\n        yyjson_mut_val *prev_val = ((yyjson_mut_val *)obj->uni.ptr)->next;\n        yyjson_mut_val *next_key = prev_val->next;\n        prev_val->next = key;\n        val->next = next_key;\n    } else {\n        val->next = key;\n    }\n    key->next = val;\n    obj->uni.ptr = (void *)key;\n    unsafe_yyjson_set_len(obj, len + 1);\n}\n\nyyjson_api_inline yyjson_mut_val *unsafe_yyjson_mut_obj_remove(\n    yyjson_mut_val *obj, const char *key, size_t key_len) {\n    size_t obj_len = unsafe_yyjson_get_len(obj);\n    if (obj_len) {\n        yyjson_mut_val *pre_key = (yyjson_mut_val *)obj->uni.ptr;\n        yyjson_mut_val *cur_key = pre_key->next->next;\n        yyjson_mut_val *removed_item = NULL;\n        size_t i;\n        for (i = 0; i < obj_len; i++) {\n            if (unsafe_yyjson_equals_strn(cur_key, key, key_len)) {\n                if (!removed_item) removed_item = cur_key->next;\n                cur_key = cur_key->next->next;\n                pre_key->next->next = cur_key;\n                if (i + 1 == obj_len) obj->uni.ptr = pre_key;\n                i--;\n                obj_len--;\n            } else {\n                pre_key = cur_key;\n                cur_key = cur_key->next->next;\n            }\n        }\n        unsafe_yyjson_set_len(obj, obj_len);\n        return removed_item;\n    } else {\n        return NULL;\n    }\n}\n\nyyjson_api_inline bool unsafe_yyjson_mut_obj_replace(yyjson_mut_val *obj,\n                                                     yyjson_mut_val *key,\n                                                     yyjson_mut_val *val) {\n    size_t key_len = unsafe_yyjson_get_len(key);\n    size_t obj_len = unsafe_yyjson_get_len(obj);\n    if (obj_len) {\n        yyjson_mut_val *pre_key = (yyjson_mut_val *)obj->uni.ptr;\n        yyjson_mut_val *cur_key = pre_key->next->next;\n        size_t i;\n        for (i = 0; i < obj_len; i++) {\n            if (unsafe_yyjson_equals_strn(cur_key, key->uni.str, key_len)) {\n                cur_key->next->tag = val->tag;\n                cur_key->next->uni.u64 = val->uni.u64;\n                return true;\n            } else {\n                cur_key = cur_key->next->next;\n            }\n        }\n    }\n    return false;\n}\n\nyyjson_api_inline void unsafe_yyjson_mut_obj_rotate(yyjson_mut_val *obj,\n                                                    size_t idx) {\n    yyjson_mut_val *key = (yyjson_mut_val *)obj->uni.ptr;\n    while (idx-- > 0) key = key->next->next;\n    obj->uni.ptr = (void *)key;\n}\n\nyyjson_api_inline bool yyjson_mut_obj_add(yyjson_mut_val *obj,\n                                          yyjson_mut_val *key,\n                                          yyjson_mut_val *val) {\n    if (yyjson_likely(yyjson_mut_is_obj(obj) &&\n                      yyjson_mut_is_str(key) && val)) {\n        unsafe_yyjson_mut_obj_add(obj, key, val, unsafe_yyjson_get_len(obj));\n        return true;\n    }\n    return false;\n}\n\nyyjson_api_inline bool yyjson_mut_obj_put(yyjson_mut_val *obj,\n                                          yyjson_mut_val *key,\n                                          yyjson_mut_val *val) {\n    bool replaced = false;\n    size_t key_len;\n    yyjson_mut_obj_iter iter;\n    yyjson_mut_val *cur_key;\n    if (yyjson_unlikely(!yyjson_mut_is_obj(obj) ||\n                        !yyjson_mut_is_str(key))) return false;\n    key_len = unsafe_yyjson_get_len(key);\n    yyjson_mut_obj_iter_init(obj, &iter);\n    while ((cur_key = yyjson_mut_obj_iter_next(&iter)) != 0) {\n        if (unsafe_yyjson_equals_strn(cur_key, key->uni.str, key_len)) {\n            if (!replaced && val) {\n                replaced = true;\n                val->next = cur_key->next->next;\n                cur_key->next = val;\n            } else {\n                yyjson_mut_obj_iter_remove(&iter);\n            }\n        }\n    }\n    if (!replaced && val) unsafe_yyjson_mut_obj_add(obj, key, val, iter.max);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_mut_obj_insert(yyjson_mut_val *obj,\n                                             yyjson_mut_val *key,\n                                             yyjson_mut_val *val,\n                                             size_t idx) {\n    if (yyjson_likely(yyjson_mut_is_obj(obj) &&\n                      yyjson_mut_is_str(key) && val)) {\n        size_t len = unsafe_yyjson_get_len(obj);\n        if (yyjson_likely(len >= idx)) {\n            if (len > idx) {\n                void *ptr = obj->uni.ptr;\n                unsafe_yyjson_mut_obj_rotate(obj, idx);\n                unsafe_yyjson_mut_obj_add(obj, key, val, len);\n                obj->uni.ptr = ptr;\n            } else {\n                unsafe_yyjson_mut_obj_add(obj, key, val, len);\n            }\n            return true;\n        }\n    }\n    return false;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_remove(yyjson_mut_val *obj,\n    yyjson_mut_val *key) {\n    if (yyjson_likely(yyjson_mut_is_obj(obj) && yyjson_mut_is_str(key))) {\n        return unsafe_yyjson_mut_obj_remove(obj, key->uni.str,\n                                            unsafe_yyjson_get_len(key));\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_remove_key(\n    yyjson_mut_val *obj, const char *key) {\n    if (yyjson_likely(yyjson_mut_is_obj(obj) && key)) {\n        size_t key_len = strlen(key);\n        return unsafe_yyjson_mut_obj_remove(obj, key, key_len);\n    }\n    return NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_remove_keyn(\n    yyjson_mut_val *obj, const char *key, size_t key_len) {\n    if (yyjson_likely(yyjson_mut_is_obj(obj) && key)) {\n        return unsafe_yyjson_mut_obj_remove(obj, key, key_len);\n    }\n    return NULL;\n}\n\nyyjson_api_inline bool yyjson_mut_obj_clear(yyjson_mut_val *obj) {\n    if (yyjson_likely(yyjson_mut_is_obj(obj))) {\n        unsafe_yyjson_set_len(obj, 0);\n        return true;\n    }\n    return false;\n}\n\nyyjson_api_inline bool yyjson_mut_obj_replace(yyjson_mut_val *obj,\n                                              yyjson_mut_val *key,\n                                              yyjson_mut_val *val) {\n    if (yyjson_likely(yyjson_mut_is_obj(obj) &&\n                      yyjson_mut_is_str(key) && val)) {\n        return unsafe_yyjson_mut_obj_replace(obj, key, val);\n    }\n    return false;\n}\n\nyyjson_api_inline bool yyjson_mut_obj_rotate(yyjson_mut_val *obj,\n                                             size_t idx) {\n    if (yyjson_likely(yyjson_mut_is_obj(obj) &&\n                      unsafe_yyjson_get_len(obj) > idx)) {\n        unsafe_yyjson_mut_obj_rotate(obj, idx);\n        return true;\n    }\n    return false;\n}\n\n\n\n/*==============================================================================\n * Mutable JSON Object Modification Convenience API (Implementation)\n *============================================================================*/\n\n#define yyjson_mut_obj_add_func(func) \\\n    if (yyjson_likely(doc && yyjson_mut_is_obj(obj) && _key)) { \\\n        yyjson_mut_val *key = unsafe_yyjson_mut_val(doc, 2); \\\n        if (yyjson_likely(key)) { \\\n            size_t len = unsafe_yyjson_get_len(obj); \\\n            yyjson_mut_val *val = key + 1; \\\n            size_t key_len = strlen(_key); \\\n            bool noesc = unsafe_yyjson_is_str_noesc(_key, key_len); \\\n            key->tag = YYJSON_TYPE_STR; \\\n            key->tag |= noesc ? YYJSON_SUBTYPE_NOESC : YYJSON_SUBTYPE_NONE; \\\n            key->tag |= (uint64_t)strlen(_key) << YYJSON_TAG_BIT; \\\n            key->uni.str = _key; \\\n            func \\\n            unsafe_yyjson_mut_obj_add(obj, key, val, len); \\\n            return true; \\\n        } \\\n    } \\\n    return false\n\nyyjson_api_inline bool yyjson_mut_obj_add_null(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *obj,\n                                               const char *_key) {\n    yyjson_mut_obj_add_func({\n        val->tag = YYJSON_TYPE_NULL | YYJSON_SUBTYPE_NONE;\n    });\n}\n\nyyjson_api_inline bool yyjson_mut_obj_add_true(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *obj,\n                                               const char *_key) {\n    yyjson_mut_obj_add_func({\n        val->tag = YYJSON_TYPE_BOOL | YYJSON_SUBTYPE_TRUE;\n    });\n}\n\nyyjson_api_inline bool yyjson_mut_obj_add_false(yyjson_mut_doc *doc,\n                                                yyjson_mut_val *obj,\n                                                const char *_key) {\n    yyjson_mut_obj_add_func({\n        val->tag = YYJSON_TYPE_BOOL | YYJSON_SUBTYPE_FALSE;\n    });\n}\n\nyyjson_api_inline bool yyjson_mut_obj_add_bool(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *obj,\n                                               const char *_key,\n                                               bool _val) {\n    yyjson_mut_obj_add_func({\n        _val = !!_val;\n        val->tag = YYJSON_TYPE_BOOL | (uint8_t)((uint8_t)(_val) << 3);\n    });\n}\n\nyyjson_api_inline bool yyjson_mut_obj_add_uint(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *obj,\n                                               const char *_key,\n                                               uint64_t _val) {\n    yyjson_mut_obj_add_func({\n        val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_UINT;\n        val->uni.u64 = _val;\n    });\n}\n\nyyjson_api_inline bool yyjson_mut_obj_add_sint(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *obj,\n                                               const char *_key,\n                                               int64_t _val) {\n    yyjson_mut_obj_add_func({\n        val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_SINT;\n        val->uni.i64 = _val;\n    });\n}\n\nyyjson_api_inline bool yyjson_mut_obj_add_int(yyjson_mut_doc *doc,\n                                              yyjson_mut_val *obj,\n                                              const char *_key,\n                                              int64_t _val) {\n    yyjson_mut_obj_add_func({\n        val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_SINT;\n        val->uni.i64 = _val;\n    });\n}\n\nyyjson_api_inline bool yyjson_mut_obj_add_real(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *obj,\n                                               const char *_key,\n                                               double _val) {\n    yyjson_mut_obj_add_func({\n        val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL;\n        val->uni.f64 = _val;\n    });\n}\n\nyyjson_api_inline bool yyjson_mut_obj_add_str(yyjson_mut_doc *doc,\n                                              yyjson_mut_val *obj,\n                                              const char *_key,\n                                              const char *_val) {\n    if (yyjson_unlikely(!_val)) return false;\n    yyjson_mut_obj_add_func({\n        size_t val_len = strlen(_val);\n        bool val_noesc = unsafe_yyjson_is_str_noesc(_val, val_len);\n        val->tag = ((uint64_t)strlen(_val) << YYJSON_TAG_BIT) | YYJSON_TYPE_STR;\n        val->tag |= val_noesc ? YYJSON_SUBTYPE_NOESC : YYJSON_SUBTYPE_NONE;\n        val->uni.str = _val;\n    });\n}\n\nyyjson_api_inline bool yyjson_mut_obj_add_strn(yyjson_mut_doc *doc,\n                                               yyjson_mut_val *obj,\n                                               const char *_key,\n                                               const char *_val,\n                                               size_t _len) {\n    if (yyjson_unlikely(!_val)) return false;\n    yyjson_mut_obj_add_func({\n        val->tag = ((uint64_t)_len << YYJSON_TAG_BIT) | YYJSON_TYPE_STR;\n        val->uni.str = _val;\n    });\n}\n\nyyjson_api_inline bool yyjson_mut_obj_add_strcpy(yyjson_mut_doc *doc,\n                                                 yyjson_mut_val *obj,\n                                                 const char *_key,\n                                                 const char *_val) {\n    if (yyjson_unlikely(!_val)) return false;\n    yyjson_mut_obj_add_func({\n        size_t _len = strlen(_val);\n        val->uni.str = unsafe_yyjson_mut_strncpy(doc, _val, _len);\n        if (yyjson_unlikely(!val->uni.str)) return false;\n        val->tag = ((uint64_t)_len << YYJSON_TAG_BIT) | YYJSON_TYPE_STR;\n    });\n}\n\nyyjson_api_inline bool yyjson_mut_obj_add_strncpy(yyjson_mut_doc *doc,\n                                                  yyjson_mut_val *obj,\n                                                  const char *_key,\n                                                  const char *_val,\n                                                  size_t _len) {\n    if (yyjson_unlikely(!_val)) return false;\n    yyjson_mut_obj_add_func({\n        val->uni.str = unsafe_yyjson_mut_strncpy(doc, _val, _len);\n        if (yyjson_unlikely(!val->uni.str)) return false;\n        val->tag = ((uint64_t)_len << YYJSON_TAG_BIT) | YYJSON_TYPE_STR;\n    });\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_add_arr(yyjson_mut_doc *doc,\n                                                         yyjson_mut_val *obj,\n                                                         const char *_key) {\n    yyjson_mut_val *key = yyjson_mut_str(doc, _key);\n    yyjson_mut_val *val = yyjson_mut_arr(doc);\n    return yyjson_mut_obj_add(obj, key, val) ? val : NULL;\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_add_obj(yyjson_mut_doc *doc,\n                                                         yyjson_mut_val *obj,\n                                                         const char *_key) {\n    yyjson_mut_val *key = yyjson_mut_str(doc, _key);\n    yyjson_mut_val *val = yyjson_mut_obj(doc);\n    return yyjson_mut_obj_add(obj, key, val) ? val : NULL;\n}\n\nyyjson_api_inline bool yyjson_mut_obj_add_val(yyjson_mut_doc *doc,\n                                              yyjson_mut_val *obj,\n                                              const char *_key,\n                                              yyjson_mut_val *_val) {\n    if (yyjson_unlikely(!_val)) return false;\n    yyjson_mut_obj_add_func({\n        val = _val;\n    });\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_remove_str(yyjson_mut_val *obj,\n                                                            const char *key) {\n    return yyjson_mut_obj_remove_strn(obj, key, key ? strlen(key) : 0);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_obj_remove_strn(\n    yyjson_mut_val *obj, const char *_key, size_t _len) {\n    if (yyjson_likely(yyjson_mut_is_obj(obj) && _key)) {\n        yyjson_mut_val *key;\n        yyjson_mut_obj_iter iter;\n        yyjson_mut_val *val_removed = NULL;\n        yyjson_mut_obj_iter_init(obj, &iter);\n        while ((key = yyjson_mut_obj_iter_next(&iter)) != NULL) {\n            if (unsafe_yyjson_equals_strn(key, _key, _len)) {\n                if (!val_removed) val_removed = key->next;\n                yyjson_mut_obj_iter_remove(&iter);\n            }\n        }\n        return val_removed;\n    }\n    return NULL;\n}\n\nyyjson_api_inline bool yyjson_mut_obj_rename_key(yyjson_mut_doc *doc,\n                                                 yyjson_mut_val *obj,\n                                                 const char *key,\n                                                 const char *new_key) {\n    if (!key || !new_key) return false;\n    return yyjson_mut_obj_rename_keyn(doc, obj, key, strlen(key),\n                                      new_key, strlen(new_key));\n}\n\nyyjson_api_inline bool yyjson_mut_obj_rename_keyn(yyjson_mut_doc *doc,\n                                                  yyjson_mut_val *obj,\n                                                  const char *key,\n                                                  size_t len,\n                                                  const char *new_key,\n                                                  size_t new_len) {\n    char *cpy_key = NULL;\n    yyjson_mut_val *old_key;\n    yyjson_mut_obj_iter iter;\n    if (!doc || !obj || !key || !new_key) return false;\n    yyjson_mut_obj_iter_init(obj, &iter);\n    while ((old_key = yyjson_mut_obj_iter_next(&iter))) {\n        if (unsafe_yyjson_equals_strn((void *)old_key, key, len)) {\n            if (!cpy_key) {\n                cpy_key = unsafe_yyjson_mut_strncpy(doc, new_key, new_len);\n                if (!cpy_key) return false;\n            }\n            yyjson_mut_set_strn(old_key, cpy_key, new_len);\n        }\n    }\n    return cpy_key != NULL;\n}\n\n\n\n/*==============================================================================\n * JSON Pointer API (Implementation)\n *============================================================================*/\n\n#define yyjson_ptr_set_err(_code, _msg) do { \\\n    if (err) { \\\n        err->code = YYJSON_PTR_ERR_##_code; \\\n        err->msg = _msg; \\\n        err->pos = 0; \\\n    } \\\n} while(false)\n\n/* require: val != NULL, *ptr == '/', len > 0 */\nyyjson_api yyjson_val *unsafe_yyjson_ptr_getx(yyjson_val *val,\n                                              const char *ptr, size_t len,\n                                              yyjson_ptr_err *err);\n\n/* require: val != NULL, *ptr == '/', len > 0 */\nyyjson_api yyjson_mut_val *unsafe_yyjson_mut_ptr_getx(yyjson_mut_val *val,\n                                                      const char *ptr,\n                                                      size_t len,\n                                                      yyjson_ptr_ctx *ctx,\n                                                      yyjson_ptr_err *err);\n\n/* require: val/new_val/doc != NULL, *ptr == '/', len > 0 */\nyyjson_api bool unsafe_yyjson_mut_ptr_putx(yyjson_mut_val *val,\n                                           const char *ptr, size_t len,\n                                           yyjson_mut_val *new_val,\n                                           yyjson_mut_doc *doc,\n                                           bool create_parent, bool insert_new,\n                                           yyjson_ptr_ctx *ctx,\n                                           yyjson_ptr_err *err);\n\n/* require: val/err != NULL, *ptr == '/', len > 0 */\nyyjson_api yyjson_mut_val *unsafe_yyjson_mut_ptr_replacex(\n    yyjson_mut_val *val, const char *ptr, size_t len, yyjson_mut_val *new_val,\n    yyjson_ptr_ctx *ctx, yyjson_ptr_err *err);\n\n/* require: val/err != NULL, *ptr == '/', len > 0 */\nyyjson_api yyjson_mut_val *unsafe_yyjson_mut_ptr_removex(yyjson_mut_val *val,\n                                                         const char *ptr,\n                                                         size_t len,\n                                                         yyjson_ptr_ctx *ctx,\n                                                         yyjson_ptr_err *err);\n\nyyjson_api_inline yyjson_val *yyjson_doc_ptr_get(yyjson_doc *doc,\n                                                 const char *ptr) {\n    if (yyjson_unlikely(!ptr)) return NULL;\n    return yyjson_doc_ptr_getn(doc, ptr, strlen(ptr));\n}\n\nyyjson_api_inline yyjson_val *yyjson_doc_ptr_getn(yyjson_doc *doc,\n                                                  const char *ptr, size_t len) {\n    return yyjson_doc_ptr_getx(doc, ptr, len, NULL);\n}\n\nyyjson_api_inline yyjson_val *yyjson_doc_ptr_getx(yyjson_doc *doc,\n                                                  const char *ptr, size_t len,\n                                                  yyjson_ptr_err *err) {\n    yyjson_ptr_set_err(NONE, NULL);\n    if (yyjson_unlikely(!doc || !ptr)) {\n        yyjson_ptr_set_err(PARAMETER, \"input parameter is NULL\");\n        return NULL;\n    }\n    if (yyjson_unlikely(!doc->root)) {\n        yyjson_ptr_set_err(NULL_ROOT, \"document's root is NULL\");\n        return NULL;\n    }\n    if (yyjson_unlikely(len == 0)) {\n        return doc->root;\n    }\n    if (yyjson_unlikely(*ptr != '/')) {\n        yyjson_ptr_set_err(SYNTAX, \"no prefix '/'\");\n        return NULL;\n    }\n    return unsafe_yyjson_ptr_getx(doc->root, ptr, len, err);\n}\n\nyyjson_api_inline yyjson_val *yyjson_ptr_get(yyjson_val *val,\n                                             const char *ptr) {\n    if (yyjson_unlikely(!ptr)) return NULL;\n    return yyjson_ptr_getn(val, ptr, strlen(ptr));\n}\n\nyyjson_api_inline yyjson_val *yyjson_ptr_getn(yyjson_val *val,\n                                              const char *ptr, size_t len) {\n    return yyjson_ptr_getx(val, ptr, len, NULL);\n}\n\nyyjson_api_inline yyjson_val *yyjson_ptr_getx(yyjson_val *val,\n                                              const char *ptr, size_t len,\n                                              yyjson_ptr_err *err) {\n    yyjson_ptr_set_err(NONE, NULL);\n    if (yyjson_unlikely(!val || !ptr)) {\n        yyjson_ptr_set_err(PARAMETER, \"input parameter is NULL\");\n        return NULL;\n    }\n    if (yyjson_unlikely(len == 0)) {\n        return val;\n    }\n    if (yyjson_unlikely(*ptr != '/')) {\n        yyjson_ptr_set_err(SYNTAX, \"no prefix '/'\");\n        return NULL;\n    }\n    return unsafe_yyjson_ptr_getx(val, ptr, len, err);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_ptr_get(yyjson_mut_doc *doc,\n                                                         const char *ptr) {\n    if (!ptr) return NULL;\n    return yyjson_mut_doc_ptr_getn(doc, ptr, strlen(ptr));\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_ptr_getn(yyjson_mut_doc *doc,\n                                                          const char *ptr,\n                                                          size_t len) {\n    return yyjson_mut_doc_ptr_getx(doc, ptr, len, NULL, NULL);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_ptr_getx(yyjson_mut_doc *doc,\n                                                          const char *ptr,\n                                                          size_t len,\n                                                          yyjson_ptr_ctx *ctx,\n                                                          yyjson_ptr_err *err) {\n    yyjson_ptr_set_err(NONE, NULL);\n    if (ctx) memset(ctx, 0, sizeof(*ctx));\n    \n    if (yyjson_unlikely(!doc || !ptr)) {\n        yyjson_ptr_set_err(PARAMETER, \"input parameter is NULL\");\n        return NULL;\n    }\n    if (yyjson_unlikely(!doc->root)) {\n        yyjson_ptr_set_err(NULL_ROOT, \"document's root is NULL\");\n        return NULL;\n    }\n    if (yyjson_unlikely(len == 0)) {\n        return doc->root;\n    }\n    if (yyjson_unlikely(*ptr != '/')) {\n        yyjson_ptr_set_err(SYNTAX, \"no prefix '/'\");\n        return NULL;\n    }\n    return unsafe_yyjson_mut_ptr_getx(doc->root, ptr, len, ctx, err);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_ptr_get(yyjson_mut_val *val,\n                                                     const char *ptr) {\n    if (!ptr) return NULL;\n    return yyjson_mut_ptr_getn(val, ptr, strlen(ptr));\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_ptr_getn(yyjson_mut_val *val,\n                                                      const char *ptr,\n                                                      size_t len) {\n    return yyjson_mut_ptr_getx(val, ptr, len, NULL, NULL);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_ptr_getx(yyjson_mut_val *val,\n                                                      const char *ptr,\n                                                      size_t len,\n                                                      yyjson_ptr_ctx *ctx,\n                                                      yyjson_ptr_err *err) {\n    yyjson_ptr_set_err(NONE, NULL);\n    if (ctx) memset(ctx, 0, sizeof(*ctx));\n    \n    if (yyjson_unlikely(!val || !ptr)) {\n        yyjson_ptr_set_err(PARAMETER, \"input parameter is NULL\");\n        return NULL;\n    }\n    if (yyjson_unlikely(len == 0)) {\n        return val;\n    }\n    if (yyjson_unlikely(*ptr != '/')) {\n        yyjson_ptr_set_err(SYNTAX, \"no prefix '/'\");\n        return NULL;\n    }\n    return unsafe_yyjson_mut_ptr_getx(val, ptr, len, ctx, err);\n}\n\nyyjson_api_inline bool yyjson_mut_doc_ptr_add(yyjson_mut_doc *doc,\n                                              const char *ptr,\n                                              yyjson_mut_val *new_val) {\n    if (yyjson_unlikely(!ptr)) return false;\n    return yyjson_mut_doc_ptr_addn(doc, ptr, strlen(ptr), new_val);\n}\n\nyyjson_api_inline bool yyjson_mut_doc_ptr_addn(yyjson_mut_doc *doc,\n                                               const char *ptr,\n                                               size_t len,\n                                               yyjson_mut_val *new_val) {\n    return yyjson_mut_doc_ptr_addx(doc, ptr, len, new_val, true, NULL, NULL);\n}\n\nyyjson_api_inline bool yyjson_mut_doc_ptr_addx(yyjson_mut_doc *doc,\n                                               const char *ptr, size_t len,\n                                               yyjson_mut_val *new_val,\n                                               bool create_parent,\n                                               yyjson_ptr_ctx *ctx,\n                                               yyjson_ptr_err *err) {\n    yyjson_ptr_set_err(NONE, NULL);\n    if (ctx) memset(ctx, 0, sizeof(*ctx));\n    \n    if (yyjson_unlikely(!doc || !ptr || !new_val)) {\n        yyjson_ptr_set_err(PARAMETER, \"input parameter is NULL\");\n        return false;\n    }\n    if (yyjson_unlikely(len == 0)) {\n        if (doc->root) {\n            yyjson_ptr_set_err(SET_ROOT, \"cannot set document's root\");\n            return false;\n        } else {\n            doc->root = new_val;\n            return true;\n        }\n    }\n    if (yyjson_unlikely(*ptr != '/')) {\n        yyjson_ptr_set_err(SYNTAX, \"no prefix '/'\");\n        return false;\n    }\n    if (yyjson_unlikely(!doc->root && !create_parent)) {\n        yyjson_ptr_set_err(NULL_ROOT, \"document's root is NULL\");\n        return false;\n    }\n    if (yyjson_unlikely(!doc->root)) {\n        yyjson_mut_val *root = yyjson_mut_obj(doc);\n        if (yyjson_unlikely(!root)) {\n            yyjson_ptr_set_err(MEMORY_ALLOCATION, \"failed to create value\");\n            return false;\n        }\n        if (unsafe_yyjson_mut_ptr_putx(root, ptr, len, new_val, doc,\n                                       create_parent, true, ctx, err)) {\n            doc->root = root;\n            return true;\n        }\n        return false;\n    }\n    return unsafe_yyjson_mut_ptr_putx(doc->root, ptr, len, new_val, doc,\n                                      create_parent, true, ctx, err);\n}\n\nyyjson_api_inline bool yyjson_mut_ptr_add(yyjson_mut_val *val,\n                                          const char *ptr,\n                                          yyjson_mut_val *new_val,\n                                          yyjson_mut_doc *doc) {\n    if (yyjson_unlikely(!ptr)) return false;\n    return yyjson_mut_ptr_addn(val, ptr, strlen(ptr), new_val, doc);\n}\n\nyyjson_api_inline bool yyjson_mut_ptr_addn(yyjson_mut_val *val,\n                                           const char *ptr, size_t len,\n                                           yyjson_mut_val *new_val,\n                                           yyjson_mut_doc *doc) {\n    return yyjson_mut_ptr_addx(val, ptr, len, new_val, doc, true, NULL, NULL);\n}\n\nyyjson_api_inline bool yyjson_mut_ptr_addx(yyjson_mut_val *val,\n                                           const char *ptr, size_t len,\n                                           yyjson_mut_val *new_val,\n                                           yyjson_mut_doc *doc,\n                                           bool create_parent,\n                                           yyjson_ptr_ctx *ctx,\n                                           yyjson_ptr_err *err) {\n    yyjson_ptr_set_err(NONE, NULL);\n    if (ctx) memset(ctx, 0, sizeof(*ctx));\n    \n    if (yyjson_unlikely(!val || !ptr || !new_val || !doc)) {\n        yyjson_ptr_set_err(PARAMETER, \"input parameter is NULL\");\n        return false;\n    }\n    if (yyjson_unlikely(len == 0)) {\n        yyjson_ptr_set_err(SET_ROOT, \"cannot set root\");\n        return false;\n    }\n    if (yyjson_unlikely(*ptr != '/')) {\n        yyjson_ptr_set_err(SYNTAX, \"no prefix '/'\");\n        return false;\n    }\n    return unsafe_yyjson_mut_ptr_putx(val, ptr, len, new_val,\n                                       doc, create_parent, true, ctx, err);\n}\n\nyyjson_api_inline bool yyjson_mut_doc_ptr_set(yyjson_mut_doc *doc,\n                                              const char *ptr,\n                                              yyjson_mut_val *new_val) {\n    if (yyjson_unlikely(!ptr)) return false;\n    return yyjson_mut_doc_ptr_setn(doc, ptr, strlen(ptr), new_val);\n}\n\nyyjson_api_inline bool yyjson_mut_doc_ptr_setn(yyjson_mut_doc *doc,\n                                               const char *ptr, size_t len,\n                                               yyjson_mut_val *new_val) {\n    return yyjson_mut_doc_ptr_setx(doc, ptr, len, new_val, true, NULL, NULL);\n}\n\nyyjson_api_inline bool yyjson_mut_doc_ptr_setx(yyjson_mut_doc *doc,\n                                               const char *ptr, size_t len,\n                                               yyjson_mut_val *new_val,\n                                               bool create_parent,\n                                               yyjson_ptr_ctx *ctx,\n                                               yyjson_ptr_err *err) {\n    yyjson_ptr_set_err(NONE, NULL);\n    if (ctx) memset(ctx, 0, sizeof(*ctx));\n    \n    if (yyjson_unlikely(!doc || !ptr)) {\n        yyjson_ptr_set_err(PARAMETER, \"input parameter is NULL\");\n        return false;\n    }\n    if (yyjson_unlikely(len == 0)) {\n        if (ctx) ctx->old = doc->root;\n        doc->root = new_val;\n        return true;\n    }\n    if (yyjson_unlikely(*ptr != '/')) {\n        yyjson_ptr_set_err(SYNTAX, \"no prefix '/'\");\n        return false;\n    }\n    if (!new_val) {\n        if (!doc->root) {\n            yyjson_ptr_set_err(RESOLVE, \"JSON pointer cannot be resolved\");\n            return false;\n        }\n        return !!unsafe_yyjson_mut_ptr_removex(doc->root, ptr, len, ctx, err);\n    }\n    if (yyjson_unlikely(!doc->root && !create_parent)) {\n        yyjson_ptr_set_err(NULL_ROOT, \"document's root is NULL\");\n        return false;\n    }\n    if (yyjson_unlikely(!doc->root)) {\n        yyjson_mut_val *root = yyjson_mut_obj(doc);\n        if (yyjson_unlikely(!root)) {\n            yyjson_ptr_set_err(MEMORY_ALLOCATION, \"failed to create value\");\n            return false;\n        }\n        if (unsafe_yyjson_mut_ptr_putx(root, ptr, len, new_val, doc,\n                                       create_parent, false, ctx, err)) {\n            doc->root = root;\n            return true;\n        }\n        return false;\n    }\n    return unsafe_yyjson_mut_ptr_putx(doc->root, ptr, len, new_val, doc,\n                                      create_parent, false, ctx, err);\n}\n\nyyjson_api_inline bool yyjson_mut_ptr_set(yyjson_mut_val *val,\n                                          const char *ptr,\n                                          yyjson_mut_val *new_val,\n                                          yyjson_mut_doc *doc) {\n    if (yyjson_unlikely(!ptr)) return false;\n    return yyjson_mut_ptr_setn(val, ptr, strlen(ptr), new_val, doc);\n}\n\nyyjson_api_inline bool yyjson_mut_ptr_setn(yyjson_mut_val *val,\n                                           const char *ptr, size_t len,\n                                           yyjson_mut_val *new_val,\n                                           yyjson_mut_doc *doc) {\n    return yyjson_mut_ptr_setx(val, ptr, len, new_val, doc, true, NULL, NULL);\n}\n\nyyjson_api_inline bool yyjson_mut_ptr_setx(yyjson_mut_val *val,\n                                           const char *ptr, size_t len,\n                                           yyjson_mut_val *new_val,\n                                           yyjson_mut_doc *doc,\n                                           bool create_parent,\n                                           yyjson_ptr_ctx *ctx,\n                                           yyjson_ptr_err *err) {\n    yyjson_ptr_set_err(NONE, NULL);\n    if (ctx) memset(ctx, 0, sizeof(*ctx));\n    \n    if (yyjson_unlikely(!val || !ptr || !doc)) {\n        yyjson_ptr_set_err(PARAMETER, \"input parameter is NULL\");\n        return false;\n    }\n    if (yyjson_unlikely(len == 0)) {\n        yyjson_ptr_set_err(SET_ROOT, \"cannot set root\");\n        return false;\n    }\n    if (yyjson_unlikely(*ptr != '/')) {\n        yyjson_ptr_set_err(SYNTAX, \"no prefix '/'\");\n        return false;\n    }\n    if (!new_val) {\n        return !!unsafe_yyjson_mut_ptr_removex(val, ptr, len, ctx, err);\n    }\n    return unsafe_yyjson_mut_ptr_putx(val, ptr, len, new_val, doc,\n                                      create_parent, false, ctx, err);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_ptr_replace(\n    yyjson_mut_doc *doc, const char *ptr, yyjson_mut_val *new_val) {\n    if (!ptr) return NULL;\n    return yyjson_mut_doc_ptr_replacen(doc, ptr, strlen(ptr), new_val);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_ptr_replacen(\n    yyjson_mut_doc *doc, const char *ptr, size_t len, yyjson_mut_val *new_val) {\n    return yyjson_mut_doc_ptr_replacex(doc, ptr, len, new_val, NULL, NULL);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_ptr_replacex(\n    yyjson_mut_doc *doc, const char *ptr, size_t len, yyjson_mut_val *new_val,\n    yyjson_ptr_ctx *ctx, yyjson_ptr_err *err) {\n    \n    yyjson_ptr_set_err(NONE, NULL);\n    if (ctx) memset(ctx, 0, sizeof(*ctx));\n    \n    if (yyjson_unlikely(!doc || !ptr || !new_val)) {\n        yyjson_ptr_set_err(PARAMETER, \"input parameter is NULL\");\n        return NULL;\n    }\n    if (yyjson_unlikely(len == 0)) {\n        yyjson_mut_val *root = doc->root;\n        if (yyjson_unlikely(!root)) {\n            yyjson_ptr_set_err(RESOLVE, \"JSON pointer cannot be resolved\");\n            return NULL;\n        }\n        if (ctx) ctx->old = root;\n        doc->root = new_val;\n        return root;\n    }\n    if (yyjson_unlikely(!doc->root)) {\n        yyjson_ptr_set_err(NULL_ROOT, \"document's root is NULL\");\n        return NULL;\n    }\n    if (yyjson_unlikely(*ptr != '/')) {\n        yyjson_ptr_set_err(SYNTAX, \"no prefix '/'\");\n        return NULL;\n    }\n    return unsafe_yyjson_mut_ptr_replacex(doc->root, ptr, len, new_val,\n                                          ctx, err);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_ptr_replace(\n    yyjson_mut_val *val, const char *ptr, yyjson_mut_val *new_val) {\n    if (!ptr) return NULL;\n    return yyjson_mut_ptr_replacen(val, ptr, strlen(ptr), new_val);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_ptr_replacen(\n    yyjson_mut_val *val, const char *ptr, size_t len, yyjson_mut_val *new_val) {\n    return yyjson_mut_ptr_replacex(val, ptr, len, new_val, NULL, NULL);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_ptr_replacex(\n    yyjson_mut_val *val, const char *ptr, size_t len, yyjson_mut_val *new_val,\n    yyjson_ptr_ctx *ctx, yyjson_ptr_err *err) {\n    \n    yyjson_ptr_set_err(NONE, NULL);\n    if (ctx) memset(ctx, 0, sizeof(*ctx));\n    \n    if (yyjson_unlikely(!val || !ptr || !new_val)) {\n        yyjson_ptr_set_err(PARAMETER, \"input parameter is NULL\");\n        return NULL;\n    }\n    if (yyjson_unlikely(len == 0)) {\n        yyjson_ptr_set_err(SET_ROOT, \"cannot set root\");\n        return NULL;\n    }\n    if (yyjson_unlikely(*ptr != '/')) {\n        yyjson_ptr_set_err(SYNTAX, \"no prefix '/'\");\n        return NULL;\n    }\n    return unsafe_yyjson_mut_ptr_replacex(val, ptr, len, new_val, ctx, err);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_ptr_remove(\n    yyjson_mut_doc *doc, const char *ptr) {\n    if (!ptr) return NULL;\n    return yyjson_mut_doc_ptr_removen(doc, ptr, strlen(ptr));\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_ptr_removen(\n    yyjson_mut_doc *doc, const char *ptr, size_t len) {\n    return yyjson_mut_doc_ptr_removex(doc, ptr, len, NULL, NULL);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_ptr_removex(\n    yyjson_mut_doc *doc, const char *ptr, size_t len,\n    yyjson_ptr_ctx *ctx, yyjson_ptr_err *err) {\n    \n    yyjson_ptr_set_err(NONE, NULL);\n    if (ctx) memset(ctx, 0, sizeof(*ctx));\n    \n    if (yyjson_unlikely(!doc || !ptr)) {\n        yyjson_ptr_set_err(PARAMETER, \"input parameter is NULL\");\n        return NULL;\n    }\n    if (yyjson_unlikely(!doc->root)) {\n        yyjson_ptr_set_err(NULL_ROOT, \"document's root is NULL\");\n        return NULL;\n    }\n    if (yyjson_unlikely(len == 0)) {\n        yyjson_mut_val *root = doc->root;\n        if (ctx) ctx->old = root;\n        doc->root = NULL;\n        return root;\n    }\n    if (yyjson_unlikely(*ptr != '/')) {\n        yyjson_ptr_set_err(SYNTAX, \"no prefix '/'\");\n        return NULL;\n    }\n    return unsafe_yyjson_mut_ptr_removex(doc->root, ptr, len, ctx, err);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_ptr_remove(yyjson_mut_val *val,\n                                                        const char *ptr) {\n    if (!ptr) return NULL;\n    return yyjson_mut_ptr_removen(val, ptr, strlen(ptr));\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_ptr_removen(yyjson_mut_val *val,\n                                                         const char *ptr,\n                                                         size_t len) {\n    return yyjson_mut_ptr_removex(val, ptr, len, NULL, NULL);\n}\n\nyyjson_api_inline yyjson_mut_val *yyjson_mut_ptr_removex(yyjson_mut_val *val,\n                                                         const char *ptr,\n                                                         size_t len,\n                                                         yyjson_ptr_ctx *ctx,\n                                                         yyjson_ptr_err *err) {\n    yyjson_ptr_set_err(NONE, NULL);\n    if (ctx) memset(ctx, 0, sizeof(*ctx));\n    \n    if (yyjson_unlikely(!val || !ptr)) {\n        yyjson_ptr_set_err(PARAMETER, \"input parameter is NULL\");\n        return NULL;\n    }\n    if (yyjson_unlikely(len == 0)) {\n        yyjson_ptr_set_err(SET_ROOT, \"cannot set root\");\n        return NULL;\n    }\n    if (yyjson_unlikely(*ptr != '/')) {\n        yyjson_ptr_set_err(SYNTAX, \"no prefix '/'\");\n        return NULL;\n    }\n    return unsafe_yyjson_mut_ptr_removex(val, ptr, len, ctx, err);\n}\n\nyyjson_api_inline bool yyjson_ptr_ctx_append(yyjson_ptr_ctx *ctx,\n                                             yyjson_mut_val *key,\n                                             yyjson_mut_val *val) {\n    yyjson_mut_val *ctn, *pre_key, *pre_val, *cur_key, *cur_val;\n    if (!ctx || !ctx->ctn || !val) return false;\n    ctn = ctx->ctn;\n    \n    if (yyjson_mut_is_obj(ctn)) {\n        if (!key) return false;\n        key->next = val;\n        pre_key = ctx->pre;\n        if (unsafe_yyjson_get_len(ctn) == 0) {\n            val->next = key;\n            ctn->uni.ptr = key;\n            ctx->pre = key;\n        } else if (!pre_key) {\n            pre_key = (yyjson_mut_val *)ctn->uni.ptr;\n            pre_val = pre_key->next;\n            val->next = pre_val->next;\n            pre_val->next = key;\n            ctn->uni.ptr = key;\n            ctx->pre = pre_key;\n        } else {\n            cur_key = pre_key->next->next;\n            cur_val = cur_key->next;\n            val->next = cur_val->next;\n            cur_val->next = key;\n            if (ctn->uni.ptr == cur_key) ctn->uni.ptr = key;\n            ctx->pre = cur_key;\n        }\n    } else {\n        pre_val = ctx->pre;\n        if (unsafe_yyjson_get_len(ctn) == 0) {\n            val->next = val;\n            ctn->uni.ptr = val;\n            ctx->pre = val;\n        } else if (!pre_val) {\n            pre_val = (yyjson_mut_val *)ctn->uni.ptr;\n            val->next = pre_val->next;\n            pre_val->next = val;\n            ctn->uni.ptr = val;\n            ctx->pre = pre_val;\n        } else {\n            cur_val = pre_val->next;\n            val->next = cur_val->next;\n            cur_val->next = val;\n            if (ctn->uni.ptr == cur_val) ctn->uni.ptr = val;\n            ctx->pre = cur_val;\n        }\n    }\n    unsafe_yyjson_inc_len(ctn);\n    return true;\n}\n\nyyjson_api_inline bool yyjson_ptr_ctx_replace(yyjson_ptr_ctx *ctx,\n                                              yyjson_mut_val *val) {\n    yyjson_mut_val *ctn, *pre_key, *cur_key, *pre_val, *cur_val;\n    if (!ctx || !ctx->ctn || !ctx->pre || !val) return false;\n    ctn = ctx->ctn;\n    if (yyjson_mut_is_obj(ctn)) {\n        pre_key = ctx->pre;\n        pre_val = pre_key->next;\n        cur_key = pre_val->next;\n        cur_val = cur_key->next;\n        /* replace current value */\n        cur_key->next = val;\n        val->next = cur_val->next;\n        ctx->old = cur_val;\n    } else {\n        pre_val = ctx->pre;\n        cur_val = pre_val->next;\n        /* replace current value */\n        if (pre_val != cur_val) {\n            val->next = cur_val->next;\n            pre_val->next = val;\n            if (ctn->uni.ptr == cur_val) ctn->uni.ptr = val;\n        } else {\n            val->next = val;\n            ctn->uni.ptr = val;\n            ctx->pre = val;\n        }\n        ctx->old = cur_val;\n    }\n    return true;\n}\n\nyyjson_api_inline bool yyjson_ptr_ctx_remove(yyjson_ptr_ctx *ctx) {\n    yyjson_mut_val *ctn, *pre_key, *pre_val, *cur_key, *cur_val;\n    size_t len;\n    if (!ctx || !ctx->ctn || !ctx->pre) return false;\n    ctn = ctx->ctn;\n    if (yyjson_mut_is_obj(ctn)) {\n        pre_key = ctx->pre;\n        pre_val = pre_key->next;\n        cur_key = pre_val->next;\n        cur_val = cur_key->next;\n        /* remove current key-value */\n        pre_val->next = cur_val->next;\n        if (ctn->uni.ptr == cur_key) ctn->uni.ptr = pre_key;\n        ctx->pre = NULL;\n        ctx->old = cur_val;\n    } else {\n        pre_val = ctx->pre;\n        cur_val = pre_val->next;\n        /* remove current key-value */\n        pre_val->next = cur_val->next;\n        if (ctn->uni.ptr == cur_val) ctn->uni.ptr = pre_val;\n        ctx->pre = NULL;\n        ctx->old = cur_val;\n    }\n    len = unsafe_yyjson_get_len(ctn) - 1;\n    if (len == 0) ctn->uni.ptr = NULL;\n    unsafe_yyjson_set_len(ctn, len);\n    return true;\n}\n\n#undef yyjson_ptr_set_err\n\n\n\n/*==============================================================================\n * JSON Value at Pointer API (Implementation)\n *============================================================================*/\n\n/**\n Set provided `value` if the JSON Pointer (RFC 6901) exists and is type bool.\n Returns true if value at `ptr` exists and is the correct type, otherwise false.\n */\nyyjson_api_inline bool yyjson_ptr_get_bool(\n    yyjson_val *root, const char *ptr, bool *value) {\n    yyjson_val *val = yyjson_ptr_get(root, ptr);\n    if (value && yyjson_is_bool(val)) {\n        *value = unsafe_yyjson_get_bool(val);\n        return true;\n    } else {\n        return false;\n    }\n}\n\n/**\n Set provided `value` if the JSON Pointer (RFC 6901) exists and is an integer\n that fits in `uint64_t`. Returns true if successful, otherwise false.\n */\nyyjson_api_inline bool yyjson_ptr_get_uint(\n    yyjson_val *root, const char *ptr, uint64_t *value) {\n    yyjson_val *val = yyjson_ptr_get(root, ptr);\n    if (value && val) {\n        uint64_t ret = val->uni.u64;\n        if (unsafe_yyjson_is_uint(val) ||\n            (unsafe_yyjson_is_sint(val) && !(ret >> 63))) {\n            *value = ret;\n            return true;\n        }\n    }\n    return false;\n}\n\n/**\n Set provided `value` if the JSON Pointer (RFC 6901) exists and is an integer\n that fits in `int64_t`. Returns true if successful, otherwise false.\n */\nyyjson_api_inline bool yyjson_ptr_get_sint(\n    yyjson_val *root, const char *ptr, int64_t *value) {\n    yyjson_val *val = yyjson_ptr_get(root, ptr);\n    if (value && val) {\n        int64_t ret = val->uni.i64;\n        if (unsafe_yyjson_is_sint(val) ||\n            (unsafe_yyjson_is_uint(val) && ret >= 0)) {\n            *value = ret;\n            return true;\n        }\n    }\n    return false;\n}\n\n/**\n Set provided `value` if the JSON Pointer (RFC 6901) exists and is type real.\n Returns true if value at `ptr` exists and is the correct type, otherwise false.\n */\nyyjson_api_inline bool yyjson_ptr_get_real(\n    yyjson_val *root, const char *ptr, double *value) {\n    yyjson_val *val = yyjson_ptr_get(root, ptr);\n    if (value && yyjson_is_real(val)) {\n        *value = unsafe_yyjson_get_real(val);\n        return true;\n    } else {\n        return false;\n    }\n}\n\n/**\n Set provided `value` if the JSON Pointer (RFC 6901) exists and is type sint,\n uint or real.\n Returns true if value at `ptr` exists and is the correct type, otherwise false.\n */\nyyjson_api_inline bool yyjson_ptr_get_num(\n    yyjson_val *root, const char *ptr, double *value) {\n    yyjson_val *val = yyjson_ptr_get(root, ptr);\n    if (value && yyjson_is_num(val)) {\n        *value = unsafe_yyjson_get_num(val);\n        return true;\n    } else {\n        return false;\n    }\n}\n\n/**\n Set provided `value` if the JSON Pointer (RFC 6901) exists and is type string.\n Returns true if value at `ptr` exists and is the correct type, otherwise false.\n */\nyyjson_api_inline bool yyjson_ptr_get_str(\n    yyjson_val *root, const char *ptr, const char **value) {\n    yyjson_val *val = yyjson_ptr_get(root, ptr);\n    if (value && yyjson_is_str(val)) {\n        *value = unsafe_yyjson_get_str(val);\n        return true;\n    } else {\n        return false;\n    }\n}\n\n\n\n/*==============================================================================\n * Deprecated\n *============================================================================*/\n\n/** @deprecated renamed to `yyjson_doc_ptr_get` */\nyyjson_deprecated(\"renamed to yyjson_doc_ptr_get\")\nyyjson_api_inline yyjson_val *yyjson_doc_get_pointer(yyjson_doc *doc,\n                                                     const char *ptr) {\n    return yyjson_doc_ptr_get(doc, ptr);\n}\n\n/** @deprecated renamed to `yyjson_doc_ptr_getn` */\nyyjson_deprecated(\"renamed to yyjson_doc_ptr_getn\")\nyyjson_api_inline yyjson_val *yyjson_doc_get_pointern(yyjson_doc *doc,\n                                                      const char *ptr,\n                                                      size_t len) {\n    return yyjson_doc_ptr_getn(doc, ptr, len);\n}\n\n/** @deprecated renamed to `yyjson_mut_doc_ptr_get` */\nyyjson_deprecated(\"renamed to yyjson_mut_doc_ptr_get\")\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_get_pointer(\n    yyjson_mut_doc *doc, const char *ptr) {\n    return yyjson_mut_doc_ptr_get(doc, ptr);\n}\n\n/** @deprecated renamed to `yyjson_mut_doc_ptr_getn` */\nyyjson_deprecated(\"renamed to yyjson_mut_doc_ptr_getn\")\nyyjson_api_inline yyjson_mut_val *yyjson_mut_doc_get_pointern(\n    yyjson_mut_doc *doc, const char *ptr, size_t len) {\n    return yyjson_mut_doc_ptr_getn(doc, ptr, len);\n}\n\n/** @deprecated renamed to `yyjson_ptr_get` */\nyyjson_deprecated(\"renamed to yyjson_ptr_get\")\nyyjson_api_inline yyjson_val *yyjson_get_pointer(yyjson_val *val,\n                                                 const char *ptr) {\n    return yyjson_ptr_get(val, ptr);\n}\n\n/** @deprecated renamed to `yyjson_ptr_getn` */\nyyjson_deprecated(\"renamed to yyjson_ptr_getn\")\nyyjson_api_inline yyjson_val *yyjson_get_pointern(yyjson_val *val,\n                                                  const char *ptr,\n                                                  size_t len) {\n    return yyjson_ptr_getn(val, ptr, len);\n}\n\n/** @deprecated renamed to `yyjson_mut_ptr_get` */\nyyjson_deprecated(\"renamed to yyjson_mut_ptr_get\")\nyyjson_api_inline yyjson_mut_val *yyjson_mut_get_pointer(yyjson_mut_val *val,\n                                                         const char *ptr) {\n    return yyjson_mut_ptr_get(val, ptr);\n}\n\n/** @deprecated renamed to `yyjson_mut_ptr_getn` */\nyyjson_deprecated(\"renamed to yyjson_mut_ptr_getn\")\nyyjson_api_inline yyjson_mut_val *yyjson_mut_get_pointern(yyjson_mut_val *val,\n                                                          const char *ptr,\n                                                          size_t len) {\n    return yyjson_mut_ptr_getn(val, ptr, len);\n}\n\n/** @deprecated renamed to `yyjson_mut_ptr_getn` */\nyyjson_deprecated(\"renamed to unsafe_yyjson_ptr_getn\")\nyyjson_api_inline yyjson_val *unsafe_yyjson_get_pointer(yyjson_val *val,\n                                                        const char *ptr,\n                                                        size_t len) {\n    yyjson_ptr_err err;\n    return unsafe_yyjson_ptr_getx(val, ptr, len, &err);\n}\n\n/** @deprecated renamed to `unsafe_yyjson_mut_ptr_getx` */\nyyjson_deprecated(\"renamed to unsafe_yyjson_mut_ptr_getx\")\nyyjson_api_inline yyjson_mut_val *unsafe_yyjson_mut_get_pointer(\n    yyjson_mut_val *val, const char *ptr, size_t len) {\n    yyjson_ptr_err err;\n    return unsafe_yyjson_mut_ptr_getx(val, ptr, len, NULL, &err);\n}\n\n\n\n/*==============================================================================\n * Compiler Hint End\n *============================================================================*/\n\n#if defined(__clang__)\n#   pragma clang diagnostic pop\n#elif defined(__GNUC__)\n#   if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)\n#   pragma GCC diagnostic pop\n#   endif\n#elif defined(_MSC_VER)\n#   pragma warning(pop)\n#endif /* warning suppress end */\n\n#ifdef __cplusplus\n}\n#endif /* extern \"C\" end */\n\n#endif /* YYJSON_H */\n"
  },
  {
    "path": "integration/client",
    "content": "#!/usr/bin/env python3\n# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2020-2023)\n\nimport asyncio\nimport sys\nimport time\n\nimport httpx\n\nport = sys.argv[1]\nurl = f\"http://127.0.0.1:{port}\"\n\ntimeout = httpx.Timeout(5.0)\nclient = httpx.AsyncClient(timeout=timeout)\n\nstop_time = time.time() + 5\n\nTEST_MESSAGE = \"http test running...\"\n\n\nasync def main():\n    sys.stdout.write(TEST_MESSAGE)\n    sys.stdout.flush()\n    count = 0\n    while time.time() < stop_time:\n        res = await client.get(url)\n        count += 1\n    sys.stdout.write(f\"\\r{TEST_MESSAGE} ok, {count} requests made\\n\")\n\n\nloop = asyncio.new_event_loop()\nasyncio.set_event_loop(loop)\nasyncio.run(main())\nloop.close()\n"
  },
  {
    "path": "integration/http",
    "content": "#!/usr/bin/env bash\n\nset -e\n\n_dir=\"$(dirname \"${BASH_SOURCE[0]}\")\"\n\nPYTHONPATH=${_dir} gunicorn --preload --bind localhost:8001 --workers 2 \"$@\" wsgi:app\n"
  },
  {
    "path": "integration/init",
    "content": "#!/usr/bin/env python3\n# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2023-2025)\n\nimport multiprocessing.pool\nimport sys\n\nimport orjson\n\nNUM_PROC = 16\n\nTEST_MESSAGE = \"parallel import of orjson running...\"\n\n\nclass Custom:\n    pass\n\n\ndef default(_):\n    return None\n\n\ndef func(_):\n    orjson.dumps(Custom(), option=orjson.OPT_SERIALIZE_NUMPY, default=default)\n    orjson.loads(b'{\"a\":1,\"b\":2,\"c\":3}')\n\n\ndef main():\n    sys.stdout.write(TEST_MESSAGE)\n    sys.stdout.flush()\n    with multiprocessing.pool.ThreadPool(processes=NUM_PROC) as pool:\n        pool.map(func, (i for i in range(NUM_PROC)))\n    sys.stdout.write(f\"\\r{TEST_MESSAGE} ok\\n\")\n    sys.stdout.flush()\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "integration/requirements.txt",
    "content": "flask;sys_platform!=\"win\"\ngunicorn;sys_platform!=\"win\"\nhttpx==0.28.1;sys_platform!=\"win\"\n"
  },
  {
    "path": "integration/run",
    "content": "#!/usr/bin/env bash\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2018-2023), Eric Jolibois (2022)\n\nset -eou pipefail\n\n_dir=\"$(dirname \"${BASH_SOURCE[0]}\")\"\n\nto_run=\"${@:-thread http init}\"\n\nexport PYTHONMALLOC=\"debug\"\n\nif [[ $to_run == *\"thread\"* ]]; then\n\t\"${_dir}\"/thread\nfi\n\nif [[ $to_run == *\"http\"* ]]; then\n\t\"${_dir}\"/http --daemon\n\tsleep 2\n\t\"${_dir}\"/client 8001\n\tset +e\n\tpkill -f 'wsgi:app' # pkill not present on all CI envs\n\tset -e\nfi\n\nif [[ $to_run == *\"typestubs\"* ]]; then\n\tpython \"${_dir}\"/typestubs.py\n\tmypy \"${_dir}\"/typestubs.py\nfi\n\nif [[ $to_run == *\"init\"* ]]; then\n\t\"${_dir}\"/init\nfi\n"
  },
  {
    "path": "integration/thread",
    "content": "#!/usr/bin/env python3\n# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2018-2025)\n\nimport sys\nimport traceback\nfrom concurrent.futures import ThreadPoolExecutor\nfrom operator import itemgetter\nfrom threading import get_ident\n\nimport orjson\n\nDATA = sorted(\n    [\n        {\n            \"id\": i,\n            \"name\": \"90as90ji0123ioj2390as90as90\",\n            \"body\": \"哈哈89asu89as😊89as9as90jas-😋0apjzxiojzx89hq23n\",\n            \"score\": 901290129.1,\n            \"bool\": True,\n            \"int\": 9832,\n            \"none\": None,\n        }\n        for i in range(10)\n    ],\n    key=itemgetter(\"id\"),\n)\n\n\nSTATUS = 0\n\nTEST_MESSAGE = \"thread test running...\"\n\nsys.stdout.write(TEST_MESSAGE)\nsys.stdout.flush()\n\n\ndef test_func(n):\n    try:\n        assert sorted(orjson.loads(orjson.dumps(DATA)), key=itemgetter(\"id\")) == DATA\n    except Exception:\n        traceback.print_exc()\n        print(f\"thread {get_ident()}: {n} dumps, loads ERROR\")\n\n\nwith ThreadPoolExecutor(max_workers=4) as executor:\n    executor.map(test_func, range(50000), chunksize=1000)\n    executor.shutdown(wait=True)\n\n\nif STATUS == 0:\n    sys.stdout.write(f\"\\r{TEST_MESSAGE} ok\\n\")\nelse:\n    sys.stdout.write(f\"\\r{TEST_MESSAGE} error\\n\")\n\n\nsys.exit(STATUS)\n"
  },
  {
    "path": "integration/typestubs.py",
    "content": "# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright Eric Jolibois (2022), ijl (2023)\n\nimport orjson\n\norjson.JSONDecodeError(msg=\"the_msg\", doc=\"the_doc\", pos=1)\n\norjson.dumps(orjson.Fragment(b\"{}\"))\n"
  },
  {
    "path": "integration/wsgi.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2018-2025)\n\nfrom datetime import datetime, timezone\nfrom uuid import uuid4\n\nfrom flask import Flask\n\nimport orjson\n\napp = Flask(__name__)\n\nNOW = datetime.now(timezone.utc)\n\n\n@app.route(\"/\")\ndef root():\n    data = {\n        \"uuid\": uuid4(),\n        \"updated_at\": NOW,\n        \"data\": [1, 2.2, None, True, False, orjson.Fragment(b\"{}\")],\n    }\n    payload = orjson.dumps(\n        data,\n        option=orjson.OPT_NAIVE_UTC | orjson.OPT_OMIT_MICROSECONDS,\n    )\n    return app.response_class(\n        response=payload,\n        status=200,\n        mimetype=\"application/json; charset=utf-8\",\n    )\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[project]\nname = \"orjson\"\nversion = \"3.11.7\"\nrepository = \"https://github.com/ijl/orjson\"\ndescription = \"Fast, correct Python JSON library supporting dataclasses, datetimes, and numpy\"\nrequires-python = \">=3.10\"\nclassifiers = [\n    \"Development Status :: 5 - Production/Stable\",\n    \"Intended Audience :: Developers\",\n    \"License :: OSI Approved :: Apache Software License\",\n    \"License :: OSI Approved :: MIT License\",\n    \"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)\",\n    \"Operating System :: MacOS\",\n    \"Operating System :: Microsoft :: Windows\",\n    \"Operating System :: POSIX :: Linux\",\n    \"Programming Language :: Python :: 3\",\n    \"Programming Language :: Python :: 3.10\",\n    \"Programming Language :: Python :: 3.11\",\n    \"Programming Language :: Python :: 3.12\",\n    \"Programming Language :: Python :: 3.13\",\n    \"Programming Language :: Python :: 3.14\",\n    \"Programming Language :: Python :: 3.15\",\n    \"Programming Language :: Python :: Implementation :: CPython\",\n    \"Programming Language :: Python\",\n    \"Programming Language :: Rust\",\n    \"Typing :: Typed\",\n]\nreadme = \"README.md\"\nlicense = \"MPL-2.0 AND (Apache-2.0 OR MIT)\"\n\n[project.urls]\nsource = \"https://github.com/ijl/orjson\"\ndocumentation = \"https://github.com/ijl/orjson\"\nchangelog = \"https://github.com/ijl/orjson/blob/master/CHANGELOG.md\"\n\n[build-system]\nbuild-backend = \"maturin\"\nrequires = [\"maturin>=1,<2\"]\n\n[tool.maturin]\npython-source = \"pysrc\"\ninclude = [\n    { format = \"sdist\", path = \".cargo/*\" },\n    { format = \"sdist\", path = \"build.rs\" },\n    { format = \"sdist\", path = \"Cargo.lock\" },\n    { format = \"sdist\", path = \"include/cargo/**/*\" },\n    { format = \"sdist\", path = \"include/yyjson/**/*\" },\n]\n\n[tool.ruff]\nline-length = 88\ntarget-version = \"py310\"\n\n[tool.ruff.lint]\nselect = [\n    \"A\",\n    \"ASYNC\",\n    \"B\",\n    \"COM\",\n    \"DTZ\",\n    \"E\",\n    \"EXE\",\n    \"F\",\n    \"FLY\",\n    \"I\",\n    \"ISC\",\n    \"PIE\",\n    \"PLC\",\n    \"PLE\",\n    \"PLR\",\n    \"PLW\",\n    \"RUF\",\n    \"TCH\",\n    \"TID\",\n    \"UP\",\n    \"W\",\n]\nignore = [\n    \"B005\", # Using `.strip()` with multi-character strings is misleading\n    \"DTZ001\", # `datetime.datetime()` called without a `tzinfo` argument\n    \"DTZ005\", # `datetime.datetime.now()` called without a `tz` argument\n    \"E402\", # Module level import not at top of file\n    \"E501\", # line too long\n    \"F601\", # Dictionary key literal ... repeated\n    \"PIE810\", # Call `startswith` once with a `tuple`\n    \"PLR2004\", # Magic value used in comparison\n    \"UP012\", # Unnecessary call to encode as UTF-8\n]\n\n[tool.pytest]\nminversion = \"9.0\"\nstrict = true\n\n[tool.ruff.lint.isort]\nknown-first-party = [\"orjson\"]\n\n[tool.mypy]\npython_version = \"3.10\"\n\n[[tool.mypy.overrides]]\nmodule = [\"dateutil\", \"pytz\"]\nignore_missing_imports = true\n"
  },
  {
    "path": "pysrc/orjson/__init__.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2023)\n\nfrom .orjson import *\nfrom .orjson import __version__\n\n__all__ = (\n    \"__version__\",\n    \"dumps\",\n    \"Fragment\",\n    \"JSONDecodeError\",\n    \"JSONEncodeError\",\n    \"loads\",\n    \"OPT_APPEND_NEWLINE\",\n    \"OPT_INDENT_2\",\n    \"OPT_NAIVE_UTC\",\n    \"OPT_NON_STR_KEYS\",\n    \"OPT_OMIT_MICROSECONDS\",\n    \"OPT_PASSTHROUGH_DATACLASS\",\n    \"OPT_PASSTHROUGH_DATETIME\",\n    \"OPT_PASSTHROUGH_SUBCLASS\",\n    \"OPT_SERIALIZE_DATACLASS\",\n    \"OPT_SERIALIZE_NUMPY\",\n    \"OPT_SERIALIZE_UUID\",\n    \"OPT_SORT_KEYS\",\n    \"OPT_STRICT_INTEGER\",\n    \"OPT_UTC_Z\",\n)\n"
  },
  {
    "path": "pysrc/orjson/__init__.pyi",
    "content": "# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2019-2026), Eric Jolibois (2022), Anders Kaseorg (2020)\n\nimport json\nfrom collections.abc import Callable\nfrom typing import Any\n\n__version__: str\n\ndef dumps(\n    __obj: Any,\n    default: Callable[[Any], Any] | None = ...,\n    option: int | None = ...,\n) -> bytes: ...\ndef loads(__obj: bytes | bytearray | memoryview | str) -> Any: ...\n\nclass JSONDecodeError(json.JSONDecodeError): ...\nclass JSONEncodeError(TypeError): ...\n\nclass Fragment(tuple):\n    contents: bytes | str\n\nOPT_APPEND_NEWLINE: int\nOPT_INDENT_2: int\nOPT_NAIVE_UTC: int\nOPT_NON_STR_KEYS: int\nOPT_OMIT_MICROSECONDS: int\nOPT_PASSTHROUGH_DATACLASS: int\nOPT_PASSTHROUGH_DATETIME: int\nOPT_PASSTHROUGH_SUBCLASS: int\nOPT_SERIALIZE_DATACLASS: int\nOPT_SERIALIZE_NUMPY: int\nOPT_SERIALIZE_UUID: int\nOPT_SORT_KEYS: int\nOPT_STRICT_INTEGER: int\nOPT_UTC_Z: int\n"
  },
  {
    "path": "pysrc/orjson/py.typed",
    "content": ""
  },
  {
    "path": "requirements-lint.txt",
    "content": "mypy==1.18.2\nruff>=0.14,<0.15\n"
  },
  {
    "path": "requirements.txt",
    "content": "-r bench/requirements.txt\n-r integration/requirements.txt\n-r requirements-lint.txt\n-r test/requirements.txt\nmaturin>=1.10,<2\n"
  },
  {
    "path": "script/blame-to-header",
    "content": "#!/usr/bin/env python3\n# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2026)\n\nimport asyncio\nimport datetime\nimport re\nimport subprocess\nfrom collections import defaultdict\nfrom pathlib import Path\n\nREPOSITORY = Path(__file__).parent.parent\n\nLICENSE_APACHE = \"(Apache-2.0 OR MIT)\"\nLICENSE_MPL2 = \"MPL-2.0\"\n\nSPACES = re.compile(r\"[ ]{2,}\")\n\nTO_INCLUDE = {\n    \".github/**/*.yaml\",\n    \"bench/*.py\",\n    \"bench/run\",\n    \"integration/*\",\n    \"pysrc/orjson/*\",\n    \"script/*\",\n    \"src/**/*.rs\",\n    \"test/**/*.py\",\n}\n\nTO_EXCLUDE = {\n    \"integration/http\",\n    \"script/cargo\",\n    \"script/debug\",\n    \"script/develop\",\n    \"script/install-fedora\",\n    \"script/lint\",\n    \"script/profile\",\n    \"script/pybench\",\n    \"script/pytest\",\n    \"script/valgrind\",\n    \"src/ffi/atomiculong.rs\",\n}\n\n\ndef aggregate_files() -> list[Path]:\n    files = []\n\n    files.append(REPOSITORY / Path(\"build.rs\"))\n\n    for pattern in TO_INCLUDE:\n        files.extend(REPOSITORY.glob(pattern))\n\n    files = {\n        each\n        for each in files\n        if not str(each).endswith((\"py.typed\", \"__pycache__\", \".txt\"))\n    }\n\n    for filename in TO_EXCLUDE:\n        files.remove(REPOSITORY / Path(filename))\n\n    return sorted(list(files))\n\n\nSKIP_FRAGMENTS = (\n    \"# Copyright\",\n    \"# SPDX\",\n    \"#!/usr\",\n    \"// Copyright\",\n    \"// SPDX\",\n)\n\n\ndef get_contributor_and_date(line: str) -> tuple[str, datetime.date] | None:\n    if not line or \"Not Committed Yet\" in line:\n        return None\n\n    end = line.index(\")\")\n    diff = line[end + 2 :]\n    diff = SPACES.sub(r\" \", diff)\n\n    # skip blank and ' };' etc\n    if len(diff) <= 3:\n        return None\n\n    # skip headers and imports\n    for fragment in SKIP_FRAGMENTS:\n        if diff.startswith(fragment):\n            return None\n\n    line = line[line.index(\"(\") + 1 : end]\n    line = SPACES.sub(r\" \", line)\n    segments = line.split(\" \")[0:-2]\n    contributor = \" \".join(segments[:-1])\n    date = datetime.date.fromtimestamp(int(segments[-1])).year\n    return (contributor, date)\n\n\ndef process_blame(filename: Path, blame: str) -> list[str, list[str]] | None:\n    file_license = \"(Apache-2.0 OR MIT)\"\n    contributors = defaultdict(list)\n    document = blame.split(\"\\n\")\n    for line in document:\n        ret = get_contributor_and_date(line)\n        if ret:\n            contributors[ret[0]].append(ret[1])\n\n    overall_earliest = 9999\n    overall_latest = 0\n    file_credit = []\n    for contributor, dates in contributors.items():\n        earliest = min(dates)\n        latest = max(dates)\n        overall_latest = max((latest, overall_latest))\n        overall_earliest = min((latest, overall_earliest))\n        num_lines = len(dates)\n        if earliest == latest:\n            file_credit.append((num_lines, f\"{contributor} ({earliest})\"))\n        else:\n            file_credit.append((num_lines, f\"{contributor} ({earliest}-{latest})\"))\n\n    if (len(contributors) == 1 and \"ijl\" in contributors) or overall_earliest == 2026:\n        file_license = LICENSE_MPL2\n\n    file_credit.sort(reverse=True)\n\n    return [file_license, file_credit]\n\n\nasync def handle_file(filename: str):\n    blame = await asyncio.create_subprocess_shell(\n        f\"git blame -C -C -C -M --date=raw {filename}\",\n        shell=True,\n        stdout=asyncio.subprocess.PIPE,\n        stderr=asyncio.subprocess.PIPE,\n    )\n\n    header = process_blame(filename, (await blame.stdout.read()).decode(\"utf-8\"))\n    if header is None:\n        print(f\"{filename.relative_to(REPOSITORY)} skipping\")\n        return\n    if not header[1] and str(filename).endswith(\"__init__.py\"):\n        return\n\n    if str(filename).endswith(\".rs\"):\n        prefix = \"//\"\n    else:\n        prefix = \"#\"\n\n    spdx = f\"{prefix} SPDX-License-Identifier: {header[0]}\"\n    credit = f\"{prefix} Copyright {', '.join(each[1] for each in header[1])}\"\n\n    contents = filename.read_bytes().decode(\"utf-8\").split(\"\\n\")\n    if contents[0].startswith(\"#!\"):\n        start_idx = 1\n    else:\n        start_idx = 0\n\n    if contents[start_idx].startswith(f\"{prefix} SPDX-License-Identifier\"):\n        contents[start_idx] = spdx\n    else:\n        contents.insert(start_idx, spdx)\n\n    if contents[start_idx + 1].startswith(f\"{prefix} Copyright\"):\n        contents[start_idx + 1] = credit\n    else:\n        contents.insert(start_idx + 1, credit)\n\n    # separate by blank line\n    first_line = start_idx + 2\n    while contents[first_line].startswith(prefix):\n        first_line += 1\n    if len(contents[first_line]) > 0:\n        contents.insert(first_line, \"\")\n\n    print(f\"{filename.relative_to(REPOSITORY)} {spdx}\")\n\n    filename.write_bytes(\"\\n\".join(contents).encode(\"utf-8\"))\n\n\nasync def main():\n    async with asyncio.TaskGroup() as tg:\n        for filename in aggregate_files():\n            tg.create_task(handle_file(filename))\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n"
  },
  {
    "path": "script/cargo",
    "content": "#!/usr/bin/env bash\n\nset -eou pipefail\n\nexport UNSAFE_PYO3_BUILD_FREE_THREADED=1\nexport UNSAFE_PYO3_SKIP_VERSION_CHECK=1\n\nRUSTFLAGS=\"-Z unstable-options -C panic=immediate-abort -Z panic_abort_tests\" cargo \"$@\" --target=\"${TARGET:-x86_64-unknown-linux-gnu}\"\n"
  },
  {
    "path": "script/check-pypi",
    "content": "#!/usr/bin/env python3\n# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2025)\n\nimport sys\nfrom pathlib import Path\n\nimport tomllib\n\ndist = sys.argv[1]\n\npyproject_doc = tomllib.loads(Path(\"pyproject.toml\").read_text(encoding=\"utf-8\"))\npyproject_version = pyproject_doc[\"project\"][\"version\"]\n\nprefix = f\"orjson-{pyproject_version}\"\n\nabis = (\n    \"cp310-cp310\",\n    \"cp311-cp311\",\n    \"cp312-cp312\",\n    \"cp313-cp313\",\n    \"cp314-cp314\",\n)\n\nper_abi_tags = (\n    \"macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2\",\n    \"manylinux_2_17_aarch64.manylinux2014_aarch64\",\n    \"manylinux_2_17_armv7l.manylinux2014_armv7l\",\n    \"manylinux_2_17_ppc64le.manylinux2014_ppc64le\",\n    \"manylinux_2_17_s390x.manylinux2014_s390x\",\n    \"manylinux_2_17_x86_64.manylinux2014_x86_64\",\n    \"manylinux_2_17_i686.manylinux2014_i686\",\n    \"musllinux_1_2_aarch64\",\n    \"musllinux_1_2_armv7l\",\n    \"musllinux_1_2_i686\",\n    \"musllinux_1_2_x86_64\",\n    \"win32\",\n    \"win_amd64\",\n)\n\nwheels_matrix = set()\n\n# orjson-3.10.15-cp310-cp310-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl\nfor abi in abis:\n    for tag in per_abi_tags:\n        wheels_matrix.add(f\"{prefix}-{abi}-{tag}.whl\")\n\nwheels_prerelease = set()\n\nwheels_unique = {\n    f\"{prefix}-cp311-cp311-macosx_15_0_arm64.whl\",\n    f\"{prefix}-cp311-cp311-win_arm64.whl\",\n    f\"{prefix}-cp312-cp312-macosx_15_0_arm64.whl\",\n    f\"{prefix}-cp312-cp312-win_arm64.whl\",\n    f\"{prefix}-cp313-cp313-macosx_15_0_arm64.whl\",\n    f\"{prefix}-cp313-cp313-win_arm64.whl\",\n    f\"{prefix}-cp314-cp314-macosx_15_0_arm64.whl\",\n    f\"{prefix}-cp314-cp314-win_arm64.whl\",\n}\n\nwheels_expected = wheels_matrix | wheels_unique | wheels_prerelease\n\nwheels_queued = set(\n    str(each).replace(f\"{dist}/\", \"\") for each in Path(dist).glob(\"*.whl\")\n)\n\nexit_code = 0\n\n# sdist\nsdist_path = Path(f\"{dist}/{prefix}.tar.gz\")\nif sdist_path.exists():\n    print(\"sdist present\\n\")\nelse:\n    exit_code = 1\n    print(f\"Missing sdist:\\n{sdist_path}\\n\")\n\n# whl\nif wheels_expected == wheels_queued:\n    print(f\"Wheels as expected, {len(wheels_queued)} total\\n\")\nelse:\n    exit_code = 1\n\n    missing = \"\\n\".join(sorted(wheels_expected - wheels_queued))\n    if missing:\n        print(f\"Missing wheels:\\n{missing}\\n\")\n\n    additional = \"\\n\".join(sorted(wheels_queued - wheels_expected))\n    if additional:\n        print(f\"Unexpected wheels:\\n{additional}\\n\")\n\nsys.exit(exit_code)\n"
  },
  {
    "path": "script/check-version",
    "content": "#!/usr/bin/env python3\n# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2025)\n\nfrom pathlib import Path\n\nimport tomllib\n\ncargo_doc = tomllib.loads(Path(\"Cargo.toml\").read_text(encoding=\"utf-8\"))\npyproject_doc = tomllib.loads(Path(\"pyproject.toml\").read_text(encoding=\"utf-8\"))\n\ncargo_version = cargo_doc[\"package\"][\"version\"]\npyproject_version = pyproject_doc[\"project\"][\"version\"]\n\nprint(f\"Cargo.toml version: {cargo_version}\")\nprint(f\"pyproject.toml version: {pyproject_version}\")\n\nassert cargo_version == pyproject_version\n"
  },
  {
    "path": "script/debug",
    "content": "#!/usr/bin/env bash\n\nset -eou pipefail\n\nrm -rf .cargo\nrm -f ${CARGO_TARGET_DIR}/wheels/*.whl\n\nexport UNSAFE_PYO3_BUILD_FREE_THREADED=1\nexport UNSAFE_PYO3_SKIP_VERSION_CHECK=1\n\nexport CC=\"${CC:-clang}\"\nexport LD=\"${LD:-lld}\"\nexport TARGET=\"${TARGET:-x86_64-unknown-linux-gnu}\"\nexport CARGO_TARGET_DIR=\"${CARGO_TARGET_DIR:-target}\"\n\nexport CFLAGS=\"-Os -fstrict-aliasing\"\n\nexport RUSTFLAGS=\"-C panic=unwind -C linker=${CC} -C link-arg=-fuse-ld=${LD}\"\n\nmaturin build --profile=dev --target=\"${TARGET}\"\n\nuv pip install ${CARGO_TARGET_DIR}/wheels/*.whl\n\npytest -v test\n\nmkdir .cargo\ncp ci/config.toml .cargo\n"
  },
  {
    "path": "script/develop",
    "content": "#!/bin/sh -e\n\nrm -f target/wheels/*\n\nexport UNSAFE_PYO3_BUILD_FREE_THREADED=1\nexport UNSAFE_PYO3_SKIP_VERSION_CHECK=1\n\nmkdir -p .cargo\ncp ci/config.toml .cargo/config.toml\n\nexport CC=\"${CC:-clang}\"\nexport LD=\"${LD:-lld}\"\nexport TARGET=\"${TARGET:-x86_64-unknown-linux-gnu}\"\nexport CARGO_TARGET_DIR=\"${CARGO_TARGET_DIR:-target}\"\nexport ORJSON_COMPATIBILITY=\"${ORJSON_COMPATIBILITY:-manylinux_2_17}\"\n\necho \"CC: ${CC}, LD: ${LD}, LD_LIBRARY_PATH: ${LD_LIBRARY_PATH}\"\n\nexport CFLAGS=\"-O2 -fstrict-aliasing -fno-plt -emit-llvm\"\nexport LDFLAGS=\"-fuse-ld=${LD} -Wl,-plugin-opt=also-emit-llvm -Wl,--as-needed -Wl,-zrelro,-znow\"\nexport RUSTFLAGS=\"-Z unstable-options -C panic=immediate-abort -C linker=${CC} -C link-arg=-fuse-ld=${LD} -C linker-plugin-lto -C link-arg=-Wl,-zrelro,-znow -Z mir-opt-level=4 -Z threads=8\"\n\nrm -f ${CARGO_TARGET_DIR}/wheels/*.whl\n\nmaturin build --target=\"${TARGET}\" --features=no_panic --compatibility=\"${ORJSON_COMPATIBILITY}\" \"$@\"\n\nuv pip install --link-mode=copy ${CARGO_TARGET_DIR}/wheels/*.whl\n"
  },
  {
    "path": "script/graph",
    "content": "#!/usr/bin/env python3\n# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2018-2025)\n\nimport collections\nimport io\nimport os\n\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nfrom tabulate import tabulate\n\nimport orjson\n\nLIBRARIES = (\"orjson\", \"json\")\n\n\ndef aggregate():\n    benchmarks_dir = os.path.join(\".benchmarks\", os.listdir(\".benchmarks\")[0])\n    res = collections.defaultdict(dict)\n    for filename in os.listdir(benchmarks_dir):\n        with open(os.path.join(benchmarks_dir, filename)) as fileh:\n            data = orjson.loads(fileh.read())\n\n        for each in data[\"benchmarks\"]:\n            res[each[\"group\"]][each[\"extra_info\"][\"lib\"]] = {\n                \"data\": [val * 1000 for val in each[\"stats\"][\"data\"]],\n                \"median\": each[\"stats\"][\"median\"] * 1000,\n                \"ops\": each[\"stats\"][\"ops\"],\n                \"correct\": each[\"extra_info\"][\"correct\"],\n            }\n    return res\n\n\ndef tab(obj):\n    buf = io.StringIO()\n    headers = (\n        \"Library\",\n        \"Median latency (milliseconds)\",\n        \"Operations per second\",\n        \"Relative (latency)\",\n    )\n\n    sns.set(rc={\"figure.facecolor\": (0, 0, 0, 0)})\n    sns.set_style(\"darkgrid\")\n\n    barplot_data = []\n    for group, val in sorted(obj.items(), reverse=True):\n        buf.write(\"\\n\" + \"#### \" + group + \"\\n\\n\")\n        table = []\n        for lib in LIBRARIES:\n            correct = val[lib][\"correct\"]\n            table.append(\n                [\n                    lib,\n                    val[lib][\"median\"] if correct else None,\n                    int(val[lib][\"ops\"]) if correct else None,\n                    0,\n                ],\n            )\n            barplot_data.append(\n                {\n                    \"operation\": \"deserialization\"\n                    if \"deserialization\" in group\n                    else \"serialization\",\n                    \"group\": group.strip(\"serialization\")\n                    .strip(\"deserialization\")\n                    .strip(),\n                    \"library\": lib,\n                    \"latency\": val[lib][\"median\"],\n                    \"operations\": int(val[lib][\"ops\"]) if correct else None,\n                },\n            )\n\n        orjson_baseline = table[0][1]\n        for each in table:\n            each[3] = (\n                \"%.1f\" % (each[1] / orjson_baseline)\n                if isinstance(each[1], float)\n                else None\n            )\n            if group.startswith(\"github\"):\n                each[1] = f\"{each[1]:.2f}\" if isinstance(each[1], float) else None\n            else:\n                each[1] = f\"{each[1]:.1f}\" if isinstance(each[1], float) else None\n\n        buf.write(tabulate(table, headers, tablefmt=\"github\") + \"\\n\")\n\n    for operation in (\"deserialization\", \"serialization\"):\n        per_op_data = list(\n            each for each in barplot_data if each[\"operation\"] == operation\n        )\n        if not per_op_data:\n            continue\n\n        max_y = 10 if operation == \"serialization\" else 5\n\n        json_baseline = {}\n        for each in per_op_data:\n            if each[\"group\"] == \"witter.json\":\n                each[\"group\"] = \"twitter.json\"\n            if each[\"library\"] == \"json\":\n                json_baseline[each[\"group\"]] = each[\"operations\"]\n\n        for each in per_op_data:\n            relative = each[\"operations\"] / json_baseline[each[\"group\"]]\n            each[\"relative\"] = min(max_y, relative)\n\n        p = pd.DataFrame.from_dict(per_op_data)\n        p.groupby(\"group\")\n\n        graph = sns.barplot(\n            p,\n            x=\"group\",\n            y=\"relative\",\n            orient=\"x\",\n            hue=\"library\",\n            errorbar=\"sd\",\n            legend=\"brief\",\n        )\n        graph.set_xlabel(\"Document\")\n        graph.set_ylabel(\"Operations/second relative to stdlib json\")\n\n        plt.title(operation)\n\n        # ensure Y range\n        plt.gca().set_yticks(\n            list(\n                {1, max_y}.union(\n                    set(int(y) for y in plt.gca().get_yticks() if int(y) <= max_y),\n                ),\n            ),\n        )\n\n        # print Y as percent\n        plt.gca().set_yticklabels([f\"{x}x\" for x in plt.gca().get_yticks()])\n\n        # reference for stdlib\n        plt.axhline(y=1, color=\"#999\", linestyle=\"dashed\")\n\n        plt.savefig(fname=f\"doc/{operation}\", dpi=300)\n        plt.close()\n\n    print(buf.getvalue())\n\n\ntab(aggregate())\n"
  },
  {
    "path": "script/install-fedora",
    "content": "#!/usr/bin/env bash\n\nset -eou pipefail\n\nexport VENV=\"${VENV:-.venv}\"\nexport CARGO_TARGET_DIR=\"${CARGO_TARGET_DIR:-target}\"\n\nrm /etc/yum.repos.d/fedora-cisco-openh264.repo || true\n\ndnf install --setopt=install_weak_deps=false -y rustup clang lld \"${PYTHON_PACKAGE}\" python3-uv\n\nrustup-init --default-toolchain \"${RUST_TOOLCHAIN}-${TARGET}\" --profile minimal --component rust-src -y\nsource \"${HOME}/.cargo/env\"\n\nmkdir -p .cargo\ncp ci/config.toml .cargo/config.toml\n\ncargo fetch --target=\"${TARGET}\" &\n\nrm -rf \"${VENV}\"\nuv venv --python \"${PYTHON}\" \"${VENV}\"\nsource \"${VENV}/bin/activate\"\n\nuv pip install --upgrade \"maturin>=1.10,<2\" -r test/requirements.txt -r integration/requirements.txt\n"
  },
  {
    "path": "script/lint",
    "content": "#!/usr/bin/env bash\n\nset -eou pipefail\n\nto_lint=\"./bench/*.py ./pysrc/orjson/__init__.pyi ./test/*.py script/pydataclass\nscript/pysort script/pynumpy script/pynonstr script/pycorrectness script/graph integration/init\nintegration/wsgi.py integration/typestubs.py integration/thread script/check-version\nscript/check-pypi\"\n\nruff format ${to_lint}\nruff check ${to_lint} --fix\nmypy --ignore-missing-imports --check-untyped-defs ./bench/*.py ./pysrc/orjson/__init__.pyi ./test/*.py\n"
  },
  {
    "path": "script/profile",
    "content": "#!/bin/sh -e\n\n# usage: ./profile data/citm_catalog.json.xz loads\n\nperf record -g --delay 250 ./bench/run_func \"$@\"\nperf report --percent-limit 0.1\n"
  },
  {
    "path": "script/pybench",
    "content": "#!/usr/bin/env bash\n\nset -eou pipefail\n\npytest \\\n    --verbose \\\n    --benchmark-min-time=1 \\\n    --benchmark-max-time=5 \\\n    --benchmark-disable-gc \\\n    --benchmark-autosave \\\n    --benchmark-save-data \\\n    --random-order \\\n    \"bench/benchmark_$1.py\"\n"
  },
  {
    "path": "script/pycorrectness",
    "content": "#!/usr/bin/env python3\n# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2019-2025)\n\nimport collections\nimport io\nimport json\nimport lzma\nimport os\nfrom pathlib import Path\n\nfrom tabulate import tabulate\n\nimport orjson\n\ndirname = os.path.join(os.path.dirname(__file__), \"..\", \"data\")\n\nLIBRARIES = [\"orjson\", \"json\"]\n\n\nLIBRARY_FUNC_MAP = {\n    \"orjson\": orjson.loads,\n    \"json\": json.loads,\n}\n\n\ndef read_fixture_bytes(filename, subdir=None):\n    if subdir is None:\n        parts = (dirname, filename)\n    else:\n        parts = (dirname, subdir, filename)\n    path = Path(*parts)\n    if path.suffix == \".xz\":\n        contents = lzma.decompress(path.read_bytes())\n    else:\n        contents = path.read_bytes()\n    return contents\n\n\nPARSING = {\n    filename: read_fixture_bytes(filename, \"parsing\")\n    for filename in os.listdir(\"data/parsing\")\n}\n\nJSONCHECKER = {\n    filename: read_fixture_bytes(filename, \"jsonchecker\")\n    for filename in os.listdir(\"data/jsonchecker\")\n}\n\n\nRESULTS = collections.defaultdict(dict)\n\n\ndef test_passed(libname, fixture):\n    passed = []\n    loads = LIBRARY_FUNC_MAP[libname]\n    try:\n        passed.append(loads(fixture) == orjson.loads(fixture))\n        passed.append(\n            loads(fixture.decode(\"utf-8\")) == orjson.loads(fixture.decode(\"utf-8\")),\n        )\n    except Exception:\n        passed.append(False)\n    return all(passed)\n\n\ndef test_failed(libname, fixture):\n    rejected_as_bytes = False\n    loads = LIBRARY_FUNC_MAP[libname]\n    try:\n        loads(fixture)\n    except Exception:\n        rejected_as_bytes = True\n\n    rejected_as_str = False\n    try:\n        loads(fixture.decode(\"utf-8\"))\n    except Exception:\n        rejected_as_str = True\n    return rejected_as_bytes and rejected_as_str\n\n\nMISTAKEN_PASSES = {key: 0 for key in LIBRARIES}\n\nMISTAKEN_FAILS = {key: 0 for key in LIBRARIES}\n\nPASS_WHITELIST = (\"fail01.json\", \"fail18.json\")\n\n\ndef should_pass(filename):\n    return (\n        filename.startswith(\"y_\")\n        or filename.startswith(\"pass\")\n        or filename in PASS_WHITELIST\n    )\n\n\ndef should_fail(filename):\n    return (\n        filename.startswith(\"n_\")\n        or filename.startswith(\"i_string\")\n        or filename.startswith(\"i_object\")\n        or filename.startswith(\"fail\")\n    ) and filename not in PASS_WHITELIST\n\n\nfor libname in LIBRARIES:\n    for fixture_set in (PARSING, JSONCHECKER):\n        for filename, fixture in fixture_set.items():\n            if should_pass(filename):\n                res = test_passed(libname, fixture)\n                RESULTS[filename][libname] = res\n                if not res:\n                    MISTAKEN_PASSES[libname] += 1\n\n            elif should_fail(filename):\n                res = test_failed(libname, fixture)\n                RESULTS[filename][libname] = res\n                if not res:\n                    MISTAKEN_FAILS[libname] += 1\n            elif filename.startswith(\"i_\"):\n                continue\n            else:\n                raise NotImplementedError\n\nFILENAMES = sorted(list(PARSING.keys()) + list(JSONCHECKER.keys()))\n\n\ntab_results = []\nfor filename in FILENAMES:\n    entry = [\n        filename,\n    ]\n    for libname in LIBRARIES:\n        try:\n            entry.append(\"ok\" if RESULTS[filename][libname] else \"fail\")\n        except KeyError:\n            continue\n    tab_results.append(entry)\n\nbuf = io.StringIO()\nbuf.write(tabulate(tab_results, [\"Fixture\", *LIBRARIES], tablefmt=\"github\"))\nbuf.write(\"\\n\")\nprint(buf.getvalue())\n\nfailure_results = [\n    [libname, MISTAKEN_FAILS[libname], MISTAKEN_PASSES[libname]]\n    for libname in LIBRARIES\n]\n\nbuf = io.StringIO()\nbuf.write(\n    tabulate(\n        failure_results,\n        [\n            \"Library\",\n            \"Invalid JSON documents not rejected\",\n            \"Valid JSON documents not deserialized\",\n        ],\n        tablefmt=\"github\",\n    ),\n)\nbuf.write(\"\\n\")\nprint(buf.getvalue())\n\nnum_results = len([each for each in tab_results if len(each) > 1])\n\nprint(f\"{num_results} documents tested\")\n"
  },
  {
    "path": "script/pydataclass",
    "content": "#!/usr/bin/env python3\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2019-2025), Aarni Koskela (2021)\n\nimport dataclasses\nimport io\nimport json\nimport os\nfrom timeit import timeit\n\nfrom tabulate import tabulate\n\nimport orjson\n\nif hasattr(os, \"sched_setaffinity\"):\n    os.sched_setaffinity(os.getpid(), {0, 1})\n\n\n@dataclasses.dataclass\nclass Member:\n    id: int\n    active: bool\n\n\n@dataclasses.dataclass\nclass Object:\n    id: int\n    name: str\n    members: list[Member]\n\n\nobjects_as_dataclass = [\n    Object(i, str(i) * 3, [Member(j, True) for j in range(10)])\n    for i in range(100000, 102000)\n]\n\nobjects_as_dict = [dataclasses.asdict(each) for each in objects_as_dataclass]\n\noutput_in_kib = len(orjson.dumps(objects_as_dict)) / 1024\n\nprint(f\"{output_in_kib:,.0f}KiB output (orjson)\")\n\n\ndef default(__obj):\n    if dataclasses.is_dataclass(__obj):\n        return dataclasses.asdict(__obj)\n\n\nheaders = (\"Library\", \"dict (ms)\", \"dataclass (ms)\", \"vs. orjson\")\n\nLIBRARIES = (\"orjson\", \"json\")\n\nITERATIONS = 100\n\n\ndef per_iter_latency(val):\n    if val is None:\n        return None\n    return (val * 1000) / ITERATIONS\n\n\ntable = []\nfor lib_name in LIBRARIES:\n    if lib_name == \"json\":\n        as_dict = timeit(\n            lambda: json.dumps(objects_as_dict).encode(\"utf-8\"),\n            number=ITERATIONS,\n        )\n        as_dataclass = timeit(\n            lambda: json.dumps(objects_as_dataclass, default=default).encode(\"utf-8\"),\n            number=ITERATIONS,\n        )\n    elif lib_name == \"orjson\":\n        as_dict = timeit(lambda: orjson.dumps(objects_as_dict), number=ITERATIONS)\n        as_dataclass = timeit(\n            lambda: orjson.dumps(\n                objects_as_dataclass,\n                None,\n                orjson.OPT_SERIALIZE_DATACLASS,\n            ),\n            number=ITERATIONS,\n        )\n        orjson_as_dataclass = per_iter_latency(as_dataclass)\n    else:\n        raise NotImplementedError\n\n    as_dict = per_iter_latency(as_dict)\n    as_dataclass = per_iter_latency(as_dataclass)\n\n    if lib_name == \"orjson\":\n        compared_to_orjson = 1\n    elif as_dataclass:\n        compared_to_orjson = int(as_dataclass / orjson_as_dataclass)\n    else:\n        compared_to_orjson = None\n\n    table.append(\n        (\n            lib_name,\n            f\"{as_dict:,.2f}\" if as_dict else \"\",\n            f\"{as_dataclass:,.2f}\" if as_dataclass else \"\",\n            f\"{compared_to_orjson:d}\" if compared_to_orjson else \"\",\n        ),\n    )\n\nbuf = io.StringIO()\nbuf.write(tabulate(table, headers, tablefmt=\"github\"))\nbuf.write(\"\\n\")\n\nprint(buf.getvalue())\n"
  },
  {
    "path": "script/pyindent",
    "content": "#!/usr/bin/env python3\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2019-2024), Aarni Koskela (2021)\n\nimport io\nimport json\nimport lzma\nimport os\nimport sys\nfrom pathlib import Path\nfrom timeit import timeit\n\nfrom tabulate import tabulate\n\nimport orjson\n\nif hasattr(os, \"sched_setaffinity\"):\n    os.sched_setaffinity(os.getpid(), {0, 1})\n\n\ndirname = os.path.join(os.path.dirname(__file__), \"..\", \"data\")\n\n\ndef read_fixture_obj(filename):\n    path = Path(dirname, filename)\n    if path.suffix == \".xz\":\n        contents = lzma.decompress(path.read_bytes())\n    else:\n        contents = path.read_bytes()\n    return orjson.loads(contents)\n\n\nfilename = sys.argv[1] if len(sys.argv) >= 1 else \"\"\n\ndata = read_fixture_obj(f\"{filename}.json.xz\")\n\nheaders = (\"Library\", \"compact (ms)\", \"pretty (ms)\", \"vs. orjson\")\n\nLIBRARIES = (\"orjson\", \"json\")\n\noutput_in_kib_compact = len(orjson.dumps(data)) / 1024\noutput_in_kib_pretty = len(orjson.dumps(data, option=orjson.OPT_INDENT_2)) / 1024\n\n# minimum 2s runtime for orjson compact\nITERATIONS = int(2 / (timeit(lambda: orjson.dumps(data), number=20) / 20))\n\nprint(\n    f\"{output_in_kib_compact:,.0f}KiB compact, {output_in_kib_pretty:,.0f}KiB pretty, {ITERATIONS} iterations\"\n)\n\n\ndef per_iter_latency(val):\n    if val is None:\n        return None\n    return (val * 1000) / ITERATIONS\n\n\ndef test_correctness(serialized):\n    return orjson.loads(serialized) == data\n\n\ntable = []\nfor lib_name in LIBRARIES:\n    print(f\"{lib_name}...\")\n    if lib_name == \"json\":\n        time_compact = timeit(\n            lambda: json.dumps(data).encode(\"utf-8\"),\n            number=ITERATIONS,\n        )\n        time_pretty = timeit(\n            lambda: json.dumps(data, indent=2).encode(\"utf-8\"),\n            number=ITERATIONS,\n        )\n        correct = test_correctness(json.dumps(data, indent=2).encode(\"utf-8\"))\n    elif lib_name == \"orjson\":\n        time_compact = timeit(lambda: orjson.dumps(data), number=ITERATIONS)\n        time_pretty = timeit(\n            lambda: orjson.dumps(data, None, orjson.OPT_INDENT_2),\n            number=ITERATIONS,\n        )\n        correct = test_correctness(orjson.dumps(data, None, orjson.OPT_INDENT_2))\n        orjson_time_pretty = per_iter_latency(time_pretty)\n    else:\n        raise NotImplementedError\n\n    time_compact = per_iter_latency(time_compact)\n    if not correct:\n        time_pretty = None\n    else:\n        time_pretty = per_iter_latency(time_pretty)\n\n    if lib_name == \"orjson\":\n        compared_to_orjson = 1\n    elif time_pretty:\n        compared_to_orjson = time_pretty / orjson_time_pretty\n    else:\n        compared_to_orjson = None\n\n    table.append(\n        (\n            lib_name,\n            f\"{time_compact:,.2f}\" if time_compact else \"\",\n            f\"{time_pretty:,.2f}\" if time_pretty else \"\",\n            f\"{compared_to_orjson:,.1f}\" if compared_to_orjson else \"\",\n        )\n    )\n\nbuf = io.StringIO()\nbuf.write(tabulate(table, headers, tablefmt=\"github\"))\nbuf.write(\"\\n\")\n\nprint(buf.getvalue())\n"
  },
  {
    "path": "script/pynonstr",
    "content": "#!/usr/bin/env python3\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2020-2025), Aarni Koskela (2021)\n\nimport datetime\nimport io\nimport json\nimport os\nimport random\nfrom time import mktime\nfrom timeit import timeit\n\nfrom tabulate import tabulate\n\nimport orjson\n\nif hasattr(os, \"sched_setaffinity\"):\n    os.sched_setaffinity(os.getpid(), {0, 1})\n\ndata_as_obj = []\nfor year in range(1920, 2020):\n    start = datetime.date(year, 1, 1)\n    array = [\n        (int(mktime((start + datetime.timedelta(days=i)).timetuple())), i + 1)\n        for i in range(365)\n    ]\n    array.append((\"other\", 0))\n    random.shuffle(array)\n    data_as_obj.append(dict(array))\n\ndata_as_str = orjson.loads(orjson.dumps(data_as_obj, option=orjson.OPT_NON_STR_KEYS))\n\nheaders = (\"Library\", \"str keys (ms)\", \"int keys (ms)\", \"int keys sorted (ms)\")\n\nLIBRARIES = (\"orjson\", \"json\")\n\nITERATIONS = 500\n\n\noutput_in_kib = len(orjson.dumps(data_as_str)) / 1024\n\nprint(f\"{output_in_kib:,.0f}KiB output (orjson)\")\n\n\ndef per_iter_latency(val):\n    if val is None:\n        return None\n    return (val * 1000) / ITERATIONS\n\n\ndef test_correctness(serialized):\n    return orjson.loads(serialized) == data_as_str\n\n\ntable = []\nfor lib_name in LIBRARIES:\n    print(f\"{lib_name}...\")\n    if lib_name == \"json\":\n        time_as_str = timeit(\n            lambda: json.dumps(data_as_str).encode(\"utf-8\"),\n            number=ITERATIONS,\n        )\n        time_as_obj = timeit(\n            lambda: json.dumps(data_as_obj).encode(\"utf-8\"),\n            number=ITERATIONS,\n        )\n        time_as_obj_sorted = (\n            None  # TypeError: '<' not supported between instances of 'str' and 'int'\n        )\n        correct = False\n    elif lib_name == \"orjson\":\n        time_as_str = timeit(\n            lambda: orjson.dumps(data_as_str, None, orjson.OPT_NON_STR_KEYS),\n            number=ITERATIONS,\n        )\n        time_as_obj = timeit(\n            lambda: orjson.dumps(data_as_obj, None, orjson.OPT_NON_STR_KEYS),\n            number=ITERATIONS,\n        )\n        time_as_obj_sorted = timeit(\n            lambda: orjson.dumps(\n                data_as_obj,\n                None,\n                orjson.OPT_NON_STR_KEYS | orjson.OPT_SORT_KEYS,\n            ),\n            number=ITERATIONS,\n        )\n        correct = test_correctness(\n            orjson.dumps(\n                data_as_obj,\n                None,\n                orjson.OPT_NON_STR_KEYS | orjson.OPT_SORT_KEYS,\n            ),\n        )\n    else:\n        raise NotImplementedError\n\n    time_as_str = per_iter_latency(time_as_str)\n    time_as_obj = per_iter_latency(time_as_obj)\n    if not correct:\n        time_as_obj_sorted = None\n    else:\n        time_as_obj_sorted = per_iter_latency(time_as_obj_sorted)\n\n    table.append(\n        (\n            lib_name,\n            f\"{time_as_str:,.2f}\" if time_as_str else \"\",\n            f\"{time_as_obj:,.2f}\" if time_as_obj else \"\",\n            f\"{time_as_obj_sorted:,.2f}\" if time_as_obj_sorted else \"\",\n        ),\n    )\n\nbuf = io.StringIO()\nbuf.write(tabulate(table, headers, tablefmt=\"github\"))\nbuf.write(\"\\n\")\n\nprint(buf.getvalue())\n"
  },
  {
    "path": "script/pynumpy",
    "content": "#!/usr/bin/env python3\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2020-2025), Nazar Kostetskyi (2022), Aarni Koskela (2021)\n\nimport gc\nimport io\nimport json\nimport os\nimport sys\nimport time\nfrom timeit import timeit\n\nimport numpy as np\nimport psutil\nfrom tabulate import tabulate\n\nimport orjson\n\nif hasattr(os, \"sched_setaffinity\"):\n    os.sched_setaffinity(os.getpid(), {0, 1})\n\n\nkind = sys.argv[1] if len(sys.argv) >= 1 else \"\"\n\n\nif kind == \"float16\":\n    dtype = np.float16\n    array = np.random.random(size=(50000, 100)).astype(dtype)\nelif kind == \"float32\":\n    dtype = np.float32\n    array = np.random.random(size=(50000, 100)).astype(dtype)\nelif kind == \"float64\":\n    dtype = np.float64\n    array = np.random.random(size=(50000, 100))\n    assert array.dtype == np.float64\nelif kind == \"bool\":\n    dtype = np.bool_\n    array = np.random.choice((True, False), size=(100000, 200))\nelif kind == \"int8\":\n    dtype = np.int8\n    array = np.random.randint(((2**7) - 1), size=(100000, 100), dtype=dtype)\nelif kind == \"int16\":\n    dtype = np.int16\n    array = np.random.randint(((2**15) - 1), size=(100000, 100), dtype=dtype)\nelif kind == \"int32\":\n    dtype = np.int32\n    array = np.random.randint(((2**31) - 1), size=(100000, 100), dtype=dtype)\nelif kind == \"uint8\":\n    dtype = np.uint8\n    array = np.random.randint(((2**8) - 1), size=(100000, 100), dtype=dtype)\nelif kind == \"uint16\":\n    dtype = np.uint16\n    array = np.random.randint(((2**16) - 1), size=(100000, 100), dtype=dtype)\nelif kind == \"uint32\":\n    dtype = np.uint32\n    array = np.random.randint(((2**31) - 1), size=(100000, 100), dtype=dtype)\nelse:\n    print(\n        \"usage: pynumpy (bool|int16|int32|float16|float32|float64|int8|uint8|uint16|uint32)\",\n    )\n    sys.exit(1)\nproc = psutil.Process()\n\n\ndef default(__obj):\n    if isinstance(__obj, np.ndarray):\n        return __obj.tolist()\n    raise TypeError\n\n\nheaders = (\"Library\", \"Latency (ms)\", \"RSS diff (MiB)\", \"vs. orjson\")\n\nLIBRARIES = (\"orjson\", \"json\")\n\nITERATIONS = 10\n\n\ndef orjson_dumps():\n    return orjson.dumps(array, option=orjson.OPT_SERIALIZE_NUMPY)\n\n\ndef json_dumps():\n    return json.dumps(array, default=default).encode(\"utf-8\")\n\n\noutput_in_mib = len(orjson_dumps()) / 1024 / 1024\n\nprint(f\"{output_in_mib:,.1f}MiB {kind} output (orjson)\")\n\ngc.collect()\nmem_before = proc.memory_full_info().rss / 1024 / 1024\n\n\ndef per_iter_latency(val):\n    if val is None:\n        return None\n    return (val * 1000) / ITERATIONS\n\n\ndef test_correctness(func):\n    return np.array_equal(array, np.array(orjson.loads(func()), dtype=dtype))\n\n\ntable = []\nfor lib_name in LIBRARIES:\n    gc.collect()\n\n    print(f\"{lib_name}...\")\n    func = locals()[f\"{lib_name}_dumps\"]\n    if func is None:\n        total_latency = None\n        latency = None\n        mem = None\n        correct = False\n    else:\n        total_latency = timeit(\n            func,\n            number=ITERATIONS,\n        )\n        latency = per_iter_latency(total_latency)\n        time.sleep(1)\n        mem = 0  # todo\n        correct = test_correctness(func)\n\n    if lib_name == \"orjson\":\n        compared_to_orjson = 1\n        orjson_latency = latency\n    elif latency:\n        compared_to_orjson = latency / orjson_latency\n    else:\n        compared_to_orjson = None\n\n    if not correct:\n        latency = None\n        mem = 0\n\n    mem_diff = mem - mem_before\n\n    table.append(\n        (\n            lib_name,\n            f\"{latency:,.0f}\" if latency else \"\",\n            f\"{mem_diff:,.0f}\" if mem else \"\",\n            f\"{compared_to_orjson:,.1f}\" if (latency and compared_to_orjson) else \"\",\n        ),\n    )\n\nbuf = io.StringIO()\nbuf.write(tabulate(table, headers, tablefmt=\"github\"))\nbuf.write(\"\\n\")\n\nprint(buf.getvalue())\n"
  },
  {
    "path": "script/pysort",
    "content": "#!/usr/bin/env python3\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2019-2024), Aarni Koskela (2021)\n\nimport io\nimport json\nimport lzma\nimport os\nfrom pathlib import Path\nfrom timeit import timeit\n\nfrom tabulate import tabulate\n\nimport orjson\n\nif hasattr(os, \"sched_setaffinity\"):\n    os.sched_setaffinity(os.getpid(), {0, 1})\n\n\ndirname = os.path.join(os.path.dirname(__file__), \"..\", \"data\")\n\n\ndef read_fixture_obj(filename):\n    path = Path(dirname, filename)\n    if path.suffix == \".xz\":\n        contents = lzma.decompress(path.read_bytes())\n    else:\n        contents = path.read_bytes()\n    return orjson.loads(contents)\n\n\ndata = read_fixture_obj(\"twitter.json.xz\")\n\nheaders = (\"Library\", \"unsorted (ms)\", \"sorted (ms)\", \"vs. orjson\")\n\nLIBRARIES = (\"orjson\", \"json\")\n\nITERATIONS = 500\n\n\ndef per_iter_latency(val):\n    if val is None:\n        return None\n    return (val * 1000) / ITERATIONS\n\n\ntable = []\nfor lib_name in LIBRARIES:\n    if lib_name == \"json\":\n        time_unsorted = timeit(\n            lambda: json.dumps(data).encode(\"utf-8\"),\n            number=ITERATIONS,\n        )\n        time_sorted = timeit(\n            lambda: json.dumps(data, sort_keys=True).encode(\"utf-8\"),\n            number=ITERATIONS,\n        )\n    elif lib_name == \"orjson\":\n        time_unsorted = timeit(lambda: orjson.dumps(data), number=ITERATIONS)\n        time_sorted = timeit(\n            lambda: orjson.dumps(data, None, orjson.OPT_SORT_KEYS),\n            number=ITERATIONS,\n        )\n        orjson_time_sorted = per_iter_latency(time_sorted)\n    else:\n        raise NotImplementedError\n\n    time_unsorted = per_iter_latency(time_unsorted)\n    time_sorted = per_iter_latency(time_sorted)\n\n    if lib_name == \"orjson\":\n        compared_to_orjson = 1\n    elif time_unsorted:\n        compared_to_orjson = time_sorted / orjson_time_sorted\n    else:\n        compared_to_orjson = None\n\n    table.append(\n        (\n            lib_name,\n            f\"{time_unsorted:,.2f}\" if time_unsorted else \"\",\n            f\"{time_sorted:,.2f}\" if time_sorted else \"\",\n            f\"{compared_to_orjson:,.1f}\" if compared_to_orjson else \"\",\n        ),\n    )\n\nbuf = io.StringIO()\nbuf.write(tabulate(table, headers, tablefmt=\"github\"))\nbuf.write(\"\\n\")\n\nprint(buf.getvalue())\n"
  },
  {
    "path": "script/pytest",
    "content": "#!/bin/sh -e\n\nPYTHONMALLOC=\"debug\" pytest -s test\n"
  },
  {
    "path": "script/valgrind",
    "content": "#!/usr/bin/env bash\n\nset -eou pipefail\n\nvalgrind \"$@\" pytest -v --ignore=test/test_memory.py test\n"
  },
  {
    "path": "src/alloc.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2025)\n\nuse crate::ffi::{PyMem_Free, PyMem_Malloc, PyMem_Realloc};\nuse core::alloc::{GlobalAlloc, Layout};\nuse core::ffi::c_void;\n\nstruct PyMemAllocator {}\n\n#[global_allocator]\nstatic ALLOCATOR: PyMemAllocator = PyMemAllocator {};\n\nunsafe impl Sync for PyMemAllocator {}\n\nunsafe impl GlobalAlloc for PyMemAllocator {\n    #[inline]\n    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {\n        unsafe { PyMem_Malloc(layout.size()).cast::<u8>() }\n    }\n\n    #[inline]\n    unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {\n        unsafe { PyMem_Free(ptr.cast::<c_void>()) }\n    }\n\n    #[inline]\n    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {\n        unsafe {\n            let len = layout.size();\n            let ptr = PyMem_Malloc(len).cast::<u8>();\n            core::ptr::write_bytes(ptr, 0, len);\n            ptr\n        }\n    }\n\n    #[inline]\n    unsafe fn realloc(&self, ptr: *mut u8, _layout: Layout, new_size: usize) -> *mut u8 {\n        unsafe { PyMem_Realloc(ptr.cast::<c_void>(), new_size).cast::<u8>() }\n    }\n}\n"
  },
  {
    "path": "src/deserialize/backend/ffi.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2022-2025)\n\n#[repr(C)]\npub(crate) struct yyjson_alc {\n    pub malloc: ::core::option::Option<\n        unsafe extern \"C\" fn(\n            ctx: *mut ::core::ffi::c_void,\n            size: usize,\n        ) -> *mut ::core::ffi::c_void,\n    >,\n    pub realloc: ::core::option::Option<\n        unsafe extern \"C\" fn(\n            ctx: *mut ::core::ffi::c_void,\n            ptr: *mut ::core::ffi::c_void,\n            size: usize,\n        ) -> *mut ::core::ffi::c_void,\n    >,\n    pub free: ::core::option::Option<\n        unsafe extern \"C\" fn(ctx: *mut ::core::ffi::c_void, ptr: *mut ::core::ffi::c_void),\n    >,\n    pub ctx: *mut ::core::ffi::c_void,\n}\n\npub(crate) type yyjson_read_code = u32;\npub(crate) const YYJSON_READ_SUCCESS: yyjson_read_code = 0;\n\n#[repr(C)]\npub(crate) struct yyjson_read_err {\n    pub code: yyjson_read_code,\n    pub msg: *const ::core::ffi::c_char,\n    pub pos: usize,\n}\n\n#[repr(C)]\npub(crate) union yyjson_val_uni {\n    pub u64_: u64,\n    pub i64_: i64,\n    pub f64_: f64,\n    pub str_: *const ::core::ffi::c_char,\n    pub ptr: *mut ::core::ffi::c_void,\n    pub ofs: usize,\n}\n\n#[repr(C)]\npub(crate) struct yyjson_val {\n    pub tag: u64,\n    pub uni: yyjson_val_uni,\n}\n\n#[repr(C)]\npub(crate) struct yyjson_doc {\n    pub root: *mut yyjson_val,\n    pub alc: yyjson_alc,\n    pub dat_read: usize,\n    pub val_read: usize,\n    pub str_pool: *mut ::core::ffi::c_char,\n}\n\nunsafe extern \"C\" {\n    pub fn yyjson_read_opts(\n        dat: *mut ::core::ffi::c_char,\n        len: usize,\n        alc: *const yyjson_alc,\n        err: *mut yyjson_read_err,\n    ) -> *mut yyjson_doc;\n\n    pub fn yyjson_alc_pool_init(\n        alc: *mut yyjson_alc,\n        buf: *mut ::core::ffi::c_void,\n        size: usize,\n    ) -> bool;\n}\n"
  },
  {
    "path": "src/deserialize/backend/mod.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2024-2025)\n\nmod ffi;\nmod yyjson;\n\npub(crate) use yyjson::deserialize;\n"
  },
  {
    "path": "src/deserialize/backend/yyjson.rs",
    "content": "// SPDX-License-Identifier: (Apache-2.0 OR MIT)\n// Copyright ijl (2022-2026), Anders Kaseorg (2023)\n\nuse super::ffi::{\n    YYJSON_READ_SUCCESS, yyjson_alc, yyjson_alc_pool_init, yyjson_doc, yyjson_read_err,\n    yyjson_read_opts, yyjson_val,\n};\nuse crate::deserialize::DeserializeError;\nuse crate::deserialize::pyobject::get_unicode_key;\nuse crate::ffi::{PyBoolRef, PyDictRef, PyFloatRef, PyIntRef, PyListRef, PyNoneRef, PyStrRef};\nuse core::ffi::c_char;\nuse core::ptr::{NonNull, null, null_mut};\nuse std::borrow::Cow;\n\nconst YYJSON_TAG_BIT: u8 = 8;\n\nconst YYJSON_VAL_SIZE: usize = core::mem::size_of::<yyjson_val>();\n\nconst TAG_ARRAY: u8 = 0b00000110;\nconst TAG_DOUBLE: u8 = 0b00010100;\nconst TAG_FALSE: u8 = 0b00000011;\nconst TAG_INT64: u8 = 0b00001100;\nconst TAG_NULL: u8 = 0b00000010;\nconst TAG_OBJECT: u8 = 0b00000111;\nconst TAG_STRING: u8 = 0b00000101;\nconst TAG_TRUE: u8 = 0b00001011;\nconst TAG_UINT64: u8 = 0b00000100;\n\nmacro_rules! is_yyjson_tag {\n    ($elem:expr, $tag:expr) => {\n        unsafe { (*$elem).tag as u8 == $tag }\n    };\n}\n\nfn yyjson_doc_get_root(doc: *mut yyjson_doc) -> *mut yyjson_val {\n    unsafe { (*doc).root }\n}\n\nfn unsafe_yyjson_get_len(val: *mut yyjson_val) -> usize {\n    unsafe { ((*val).tag >> YYJSON_TAG_BIT) as usize }\n}\n\nfn unsafe_yyjson_get_first(ctn: *mut yyjson_val) -> *mut yyjson_val {\n    unsafe { ctn.add(1) }\n}\n\nconst MINIMUM_BUFFER_CAPACITY: usize = 4096;\n\nfn buffer_capacity_to_allocate(len: usize) -> usize {\n    // The max memory size is (json_size / 2 * 16 * 1.5 + padding).\n    (((len / 2) * 24) + 256 + (MINIMUM_BUFFER_CAPACITY - 1)) & !(MINIMUM_BUFFER_CAPACITY - 1)\n}\n\nfn unsafe_yyjson_is_ctn(val: *mut yyjson_val) -> bool {\n    unsafe { (*val).tag as u8 & 0b00000110 == 0b00000110 }\n}\n\n#[allow(clippy::cast_ptr_alignment)]\nfn unsafe_yyjson_get_next_container(val: *mut yyjson_val) -> *mut yyjson_val {\n    unsafe { (val.cast::<u8>().add((*val).uni.ofs)).cast::<yyjson_val>() }\n}\n\n#[allow(clippy::cast_ptr_alignment)]\nfn unsafe_yyjson_get_next_non_container(val: *mut yyjson_val) -> *mut yyjson_val {\n    unsafe { (val.cast::<u8>().add(YYJSON_VAL_SIZE)).cast::<yyjson_val>() }\n}\n\npub(crate) fn deserialize(\n    data: &'static str,\n) -> Result<NonNull<crate::ffi::PyObject>, DeserializeError<'static>> {\n    assume!(!data.is_empty());\n    let buffer_capacity = buffer_capacity_to_allocate(data.len());\n    let buffer_ptr = ffi!(PyMem_Malloc(buffer_capacity));\n    if buffer_ptr.is_null() {\n        return Err(DeserializeError::from_yyjson(\n            Cow::Borrowed(\"Not enough memory to allocate buffer for parsing\"),\n            0,\n            data,\n        ));\n    }\n    let mut alloc = yyjson_alc {\n        malloc: None,\n        realloc: None,\n        free: None,\n        ctx: null_mut(),\n    };\n    unsafe {\n        yyjson_alc_pool_init(&raw mut alloc, buffer_ptr, buffer_capacity);\n    }\n\n    let mut err = yyjson_read_err {\n        code: YYJSON_READ_SUCCESS,\n        msg: null(),\n        pos: 0,\n    };\n\n    let doc = unsafe {\n        yyjson_read_opts(\n            data.as_ptr().cast::<c_char>().cast_mut(),\n            data.len(),\n            &raw const alloc,\n            &raw mut err,\n        )\n    };\n    if doc.is_null() {\n        ffi!(PyMem_Free(buffer_ptr));\n        let msg: Cow<str> = unsafe { core::ffi::CStr::from_ptr(err.msg).to_string_lossy() };\n        #[allow(clippy::cast_possible_wrap)]\n        let pos = err.pos as i64;\n        return Err(DeserializeError::from_yyjson(msg, pos, data));\n    }\n    let val = yyjson_doc_get_root(doc);\n    let pyval = {\n        if !unsafe_yyjson_is_ctn(val) {\n            cold_path!();\n            match ElementType::from_tag(val) {\n                ElementType::String => parse_yy_string(val),\n                ElementType::Uint64 => parse_yy_u64(val),\n                ElementType::Int64 => parse_yy_i64(val),\n                ElementType::Double => parse_yy_f64(val),\n                ElementType::Null => PyNoneRef::none().as_non_null_ptr(),\n                ElementType::True => PyBoolRef::pytrue().as_non_null_ptr(),\n                ElementType::False => PyBoolRef::pyfalse().as_non_null_ptr(),\n                ElementType::Array | ElementType::Object => unreachable_unchecked!(),\n            }\n        } else if is_yyjson_tag!(val, TAG_ARRAY) {\n            let pyval = PyListRef::with_capacity(unsafe_yyjson_get_len(val));\n            if unsafe_yyjson_get_len(val) > 0 {\n                populate_yy_array(pyval.clone(), val);\n            }\n            pyval.as_non_null_ptr()\n        } else {\n            let pyval = PyDictRef::with_capacity(unsafe_yyjson_get_len(val));\n            if unsafe_yyjson_get_len(val) > 0 {\n                populate_yy_object(pyval.clone(), val);\n            }\n            pyval.as_non_null_ptr()\n        }\n    };\n    ffi!(PyMem_Free(buffer_ptr));\n    Ok(pyval)\n}\n\nenum ElementType {\n    String,\n    Uint64,\n    Int64,\n    Double,\n    Null,\n    True,\n    False,\n    Array,\n    Object,\n}\n\nimpl ElementType {\n    fn from_tag(elem: *mut yyjson_val) -> Self {\n        match unsafe { (*elem).tag as u8 } {\n            TAG_STRING => Self::String,\n            TAG_UINT64 => Self::Uint64,\n            TAG_INT64 => Self::Int64,\n            TAG_DOUBLE => Self::Double,\n            TAG_NULL => Self::Null,\n            TAG_TRUE => Self::True,\n            TAG_FALSE => Self::False,\n            TAG_ARRAY => Self::Array,\n            TAG_OBJECT => Self::Object,\n            _ => unreachable_unchecked!(),\n        }\n    }\n}\n\n#[inline(always)]\nfn parse_yy_string(elem: *mut yyjson_val) -> NonNull<crate::ffi::PyObject> {\n    PyStrRef::from_str(str_from_slice!(\n        (*elem).uni.str_.cast::<u8>(),\n        unsafe_yyjson_get_len(elem)\n    ))\n    .as_non_null_ptr()\n}\n\n#[inline(always)]\nfn parse_yy_u64(elem: *mut yyjson_val) -> NonNull<crate::ffi::PyObject> {\n    PyIntRef::from_u64(unsafe { (*elem).uni.u64_ }).as_non_null_ptr()\n}\n\n#[inline(always)]\nfn parse_yy_i64(elem: *mut yyjson_val) -> NonNull<crate::ffi::PyObject> {\n    PyIntRef::from_i64(unsafe { (*elem).uni.i64_ }).as_non_null_ptr()\n}\n\n#[inline(always)]\nfn parse_yy_f64(elem: *mut yyjson_val) -> NonNull<crate::ffi::PyObject> {\n    PyFloatRef::from_f64(unsafe { (*elem).uni.f64_ }).as_non_null_ptr()\n}\n\n#[inline(never)]\nfn populate_yy_array(mut list: PyListRef, elem: *mut yyjson_val) {\n    unsafe {\n        let len = unsafe_yyjson_get_len(elem);\n        assume!(len >= 1);\n        let mut next = unsafe_yyjson_get_first(elem);\n\n        for idx in 0..len {\n            let val = next;\n            if unsafe_yyjson_is_ctn(val) {\n                cold_path!();\n                next = unsafe_yyjson_get_next_container(val);\n                if is_yyjson_tag!(val, TAG_ARRAY) {\n                    let pyval = PyListRef::with_capacity(unsafe_yyjson_get_len(val));\n                    list.set(idx, pyval.as_ptr());\n                    if unsafe_yyjson_get_len(val) > 0 {\n                        populate_yy_array(pyval.clone(), val);\n                    }\n                } else {\n                    let pyval = PyDictRef::with_capacity(unsafe_yyjson_get_len(val));\n                    list.set(idx, pyval.as_ptr());\n                    if unsafe_yyjson_get_len(val) > 0 {\n                        populate_yy_object(pyval.clone(), val);\n                    }\n                }\n            } else {\n                next = unsafe_yyjson_get_next_non_container(val);\n                let pyval = match ElementType::from_tag(val) {\n                    ElementType::String => parse_yy_string(val),\n                    ElementType::Uint64 => parse_yy_u64(val),\n                    ElementType::Int64 => parse_yy_i64(val),\n                    ElementType::Double => parse_yy_f64(val),\n                    ElementType::Null => PyNoneRef::none().as_non_null_ptr(),\n                    ElementType::True => PyBoolRef::pytrue().as_non_null_ptr(),\n                    ElementType::False => PyBoolRef::pyfalse().as_non_null_ptr(),\n                    ElementType::Array | ElementType::Object => unreachable_unchecked!(),\n                };\n                list.set(idx, pyval.as_ptr());\n            }\n        }\n    }\n}\n\n#[inline(never)]\nfn populate_yy_object(mut dict: PyDictRef, elem: *mut yyjson_val) {\n    unsafe {\n        let len = unsafe_yyjson_get_len(elem);\n        assume!(len >= 1);\n        let mut next_key = unsafe_yyjson_get_first(elem);\n        let mut next_val = next_key.add(1);\n        for _ in 0..len {\n            let val = next_val;\n            let pykey = {\n                let key_str = str_from_slice!(\n                    (*next_key).uni.str_.cast::<u8>(),\n                    unsafe_yyjson_get_len(next_key)\n                );\n                get_unicode_key(key_str)\n            };\n            if unsafe_yyjson_is_ctn(val) {\n                cold_path!();\n                next_key = unsafe_yyjson_get_next_container(val);\n                next_val = next_key.add(1);\n                if is_yyjson_tag!(val, TAG_ARRAY) {\n                    let pyval = PyListRef::with_capacity(unsafe_yyjson_get_len(val));\n                    dict.set(pykey, pyval.as_ptr());\n                    if unsafe_yyjson_get_len(val) > 0 {\n                        populate_yy_array(pyval, val);\n                    }\n                } else {\n                    let pyval = PyDictRef::with_capacity(unsafe_yyjson_get_len(val));\n                    dict.set(pykey, pyval.as_ptr());\n                    if unsafe_yyjson_get_len(val) > 0 {\n                        populate_yy_object(pyval.clone(), val);\n                    }\n                }\n            } else {\n                next_key = unsafe_yyjson_get_next_non_container(val);\n                next_val = next_key.add(1);\n                let pyval = match ElementType::from_tag(val) {\n                    ElementType::String => parse_yy_string(val),\n                    ElementType::Uint64 => parse_yy_u64(val),\n                    ElementType::Int64 => parse_yy_i64(val),\n                    ElementType::Double => parse_yy_f64(val),\n                    ElementType::Null => PyNoneRef::none().as_non_null_ptr(),\n                    ElementType::True => PyBoolRef::pytrue().as_non_null_ptr(),\n                    ElementType::False => PyBoolRef::pyfalse().as_non_null_ptr(),\n                    ElementType::Array | ElementType::Object => unreachable_unchecked!(),\n                };\n                dict.set(pykey, pyval.as_ptr());\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/deserialize/cache.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2019-2026)\n\nuse crate::ffi::{Py_DECREF, Py_INCREF, PyStrRef};\nuse associative_cache::{AssociativeCache, Capacity2048, HashDirectMapped, RoundRobinReplacement};\nuse core::cell::OnceCell;\n\n#[repr(transparent)]\npub(crate) struct CachedKey {\n    ptr: PyStrRef,\n}\n\nunsafe impl Send for CachedKey {}\nunsafe impl Sync for CachedKey {}\n\nimpl CachedKey {\n    pub const fn new(ptr: PyStrRef) -> CachedKey {\n        CachedKey { ptr: ptr }\n    }\n    pub fn get(&mut self) -> PyStrRef {\n        let ptr = self.ptr.as_ptr();\n        unsafe { Py_INCREF(ptr) };\n        self.ptr.clone()\n    }\n}\n\nimpl Drop for CachedKey {\n    fn drop(&mut self) {\n        unsafe { Py_DECREF(self.ptr.as_ptr().cast::<crate::ffi::PyObject>()) };\n    }\n}\n\npub(crate) type KeyMap =\n    AssociativeCache<u64, CachedKey, Capacity2048, HashDirectMapped, RoundRobinReplacement>;\n\npub(crate) static mut KEY_MAP: OnceCell<KeyMap> = OnceCell::new();\n"
  },
  {
    "path": "src/deserialize/deserializer.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2024-2026)\n\nuse super::DeserializeError;\nuse super::input::Utf8Buffer;\nuse crate::ffi::PyStrRef;\nuse core::ptr::NonNull;\n\n#[repr(transparent)]\npub struct Deserializer {\n    buffer: Utf8Buffer,\n}\n\nimpl Deserializer {\n    #[inline]\n    pub fn from_pyobject(\n        ptr: *mut crate::ffi::PyObject,\n    ) -> Result<Self, DeserializeError<'static>> {\n        let buffer = Utf8Buffer::from_pyobject(ptr)?;\n        debug_assert!(!buffer.as_str().is_empty());\n        Ok(Self { buffer: buffer })\n    }\n\n    #[inline]\n    pub fn deserialize(&self) -> Result<NonNull<crate::ffi::PyObject>, DeserializeError<'static>> {\n        if self.buffer.len() == 2 {\n            cold_path!();\n            match self.buffer.as_bytes() {\n                b\"[]\" => {\n                    return Ok(nonnull!(ffi!(PyList_New(0))));\n                }\n                b\"{}\" => {\n                    return Ok(nonnull!(unsafe { crate::ffi::PyDict_New(0) }));\n                }\n                b\"\\\"\\\"\" => {\n                    return Ok(PyStrRef::empty().as_non_null_ptr());\n                }\n                _ => {}\n            }\n        }\n        crate::deserialize::backend::deserialize(self.buffer.as_str())\n    }\n}\n\npub(crate) fn deserialize(\n    ptr: *mut crate::ffi::PyObject,\n) -> Result<NonNull<crate::ffi::PyObject>, DeserializeError<'static>> {\n    let deserializer = Deserializer::from_pyobject(ptr)?;\n    deserializer.deserialize()\n}\n"
  },
  {
    "path": "src/deserialize/error.rs",
    "content": "// SPDX-License-Identifier: (Apache-2.0 OR MIT)\n// Copyright ijl (2022-2026), Eric Jolibois (2021)\n\nuse std::borrow::Cow;\n\npub(crate) struct DeserializeError<'a> {\n    pub message: Cow<'a, str>,\n    pub data: Option<&'a str>,\n    pub pos: i64,\n}\n\nimpl<'a> DeserializeError<'a> {\n    #[cold]\n    pub fn invalid(message: Cow<'a, str>) -> Self {\n        DeserializeError {\n            message: message,\n            data: None,\n            pos: 0,\n        }\n    }\n\n    #[cold]\n    pub fn from_yyjson(message: Cow<'a, str>, pos: i64, data: &'a str) -> Self {\n        DeserializeError {\n            message: message,\n            data: Some(data),\n            pos: pos,\n        }\n    }\n\n    /// Return position of the error in the deserialized data\n    #[cold]\n    #[cfg_attr(feature = \"optimize\", optimize(size))]\n    pub fn pos(&self) -> i64 {\n        match self.data {\n            Some(as_str) => {\n                #[allow(clippy::cast_sign_loss)]\n                let pos = self.pos as usize;\n                #[allow(clippy::cast_possible_wrap)]\n                let res = as_str[0..pos].chars().count() as i64; // stmt_expr_attributes\n                res\n            }\n            None => 0,\n        }\n    }\n}\n"
  },
  {
    "path": "src/deserialize/input.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2026)\n\nuse crate::deserialize::DeserializeError;\n#[cfg(all(CPython, not(Py_GIL_DISABLED)))]\nuse crate::ffi::{PyByteArrayRef, PyMemoryViewRef};\nuse crate::ffi::{PyBytesRef, PyStrRef};\nuse crate::util::INVALID_STR;\nuse std::borrow::Cow;\n\n#[cfg(all(CPython, not(Py_GIL_DISABLED)))]\nconst INPUT_TYPE_MESSAGE: &str = \"Input must be bytes, bytearray, memoryview, or str\";\n\n#[cfg(all(CPython, Py_GIL_DISABLED))]\nconst INPUT_TYPE_MESSAGE: &str = \"Input must be bytes or str\";\n\n#[cfg(not(CPython))]\nconst INPUT_TYPE_MESSAGE: &str = \"Input must be bytes, bytearray, or str\";\n\n#[cfg_attr(not(Py_GIL_DISABLED), repr(transparent))]\npub struct Utf8Buffer {\n    buffer: &'static str,\n}\n\nimpl Utf8Buffer {\n    #[cfg(all(CPython, not(Py_GIL_DISABLED)))]\n    fn buffer_from_ptr(\n        ptr: *mut crate::ffi::PyObject,\n    ) -> Result<Option<&'static str>, DeserializeError<'static>> {\n        if let Ok(ob) = PyBytesRef::from_ptr(ptr) {\n            Ok(ob.as_str())\n        } else if let Ok(ob) = PyStrRef::from_ptr(ptr) {\n            Ok(ob.as_str())\n        } else if let Ok(ob) = PyByteArrayRef::from_ptr(ptr) {\n            Ok(ob.as_str())\n        } else if let Ok(ob) = PyMemoryViewRef::from_ptr(ptr) {\n            Ok(ob.as_str())\n        } else {\n            Err(DeserializeError::invalid(Cow::Borrowed(INPUT_TYPE_MESSAGE)))\n        }\n    }\n\n    #[cfg(any(not(CPython), Py_GIL_DISABLED))]\n    fn buffer_from_ptr(\n        ptr: *mut crate::ffi::PyObject,\n    ) -> Result<Option<&'static str>, DeserializeError<'static>> {\n        if let Ok(ob) = PyBytesRef::from_ptr(ptr) {\n            Ok(ob.as_str())\n        } else if let Ok(ob) = PyStrRef::from_ptr(ptr) {\n            Ok(ob.as_str())\n        } else {\n            Err(DeserializeError::invalid(Cow::Borrowed(INPUT_TYPE_MESSAGE)))\n        }\n    }\n\n    pub fn from_pyobject(\n        ptr: *mut crate::ffi::PyObject,\n    ) -> Result<Self, DeserializeError<'static>> {\n        debug_assert!(!ptr.is_null());\n        match Utf8Buffer::buffer_from_ptr(ptr) {\n            Ok(Some(as_str)) => {\n                if as_str.is_empty() {\n                    cold_path!();\n                    Err(DeserializeError::invalid(Cow::Borrowed(\n                        \"Input is a zero-length, empty document\",\n                    )))\n                } else {\n                    Ok(Self { buffer: as_str })\n                }\n            }\n            Ok(None) => {\n                cold_path!();\n                Err(DeserializeError::invalid(Cow::Borrowed(INVALID_STR)))\n            }\n            Err(_) => Err(DeserializeError::invalid(Cow::Borrowed(INPUT_TYPE_MESSAGE))),\n        }\n    }\n\n    pub fn as_str(&self) -> &'static str {\n        self.buffer\n    }\n\n    pub fn as_bytes(&self) -> &'static [u8] {\n        self.buffer.as_bytes()\n    }\n\n    pub fn len(&self) -> usize {\n        self.buffer.len()\n    }\n}\n"
  },
  {
    "path": "src/deserialize/mod.rs",
    "content": "// SPDX-License-Identifier: (Apache-2.0 OR MIT)\n// Copyright ijl (2020-2026), Eric Jolibois (2021)\n\nmod backend;\n#[cfg(not(Py_GIL_DISABLED))]\nmod cache;\nmod deserializer;\nmod error;\nmod input;\nmod pyobject;\n\n#[cfg(not(Py_GIL_DISABLED))]\npub(crate) use cache::{KEY_MAP, KeyMap};\npub(crate) use deserializer::deserialize;\npub(crate) use error::DeserializeError;\n"
  },
  {
    "path": "src/deserialize/pyobject.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2022-2026)\n\nuse crate::ffi::PyStrRef;\n\n#[cfg(all(CPython, not(Py_GIL_DISABLED)))]\n#[inline(always)]\npub(crate) fn get_unicode_key(key_str: &str) -> PyStrRef {\n    if key_str.len() > 64 {\n        cold_path!();\n        PyStrRef::from_str_with_hash(key_str)\n    } else {\n        assume!(key_str.len() <= 64);\n        let hash = xxhash_rust::xxh3::xxh3_64(key_str.as_bytes());\n        unsafe {\n            let entry = crate::deserialize::cache::KEY_MAP\n                .get_mut()\n                .unwrap_or_else(|| unreachable_unchecked!())\n                .entry(&hash)\n                .or_insert_with(\n                    || hash,\n                    || {\n                        crate::deserialize::cache::CachedKey::new(PyStrRef::from_str_with_hash(\n                            key_str,\n                        ))\n                    },\n                );\n            entry.get()\n        }\n    }\n}\n\n#[cfg(all(CPython, Py_GIL_DISABLED))]\n#[inline(always)]\npub(crate) fn get_unicode_key(key_str: &str) -> PyStrRef {\n    PyStrRef::from_str_with_hash(key_str)\n}\n\n#[cfg(not(CPython))]\n#[inline(always)]\npub(crate) fn get_unicode_key(key_str: &str) -> PyStrRef {\n    PyStrRef::from_str(key_str)\n}\n"
  },
  {
    "path": "src/exception.rs",
    "content": "// SPDX-License-Identifier: (Apache-2.0 OR MIT)\n// Copyright ijl (2020-2026), Jack Amadeo (2023)\n\nuse core::ptr::null_mut;\n\nuse crate::deserialize::DeserializeError;\nuse crate::ffi::{Py_DECREF, PyErr_SetObject, PyIntRef, PyObject, PyStrRef, PyTupleRef};\nuse crate::typeref::{JsonDecodeError, JsonEncodeError};\n\n#[cold]\n#[inline(never)]\n#[cfg_attr(feature = \"optimize\", optimize(size))]\npub(crate) fn raise_loads_exception(err: DeserializeError) -> *mut PyObject {\n    unsafe {\n        let err_pos = PyIntRef::from_i64(err.pos());\n        let err_msg = PyStrRef::from_str(&err.message);\n        let doc = match err.data {\n            Some(as_str) => PyStrRef::from_str(as_str),\n            None => PyStrRef::empty(),\n        };\n        let mut args = PyTupleRef::with_capacity(3);\n        args.set(0, err_msg.as_ptr());\n        args.set(1, doc.as_ptr());\n        args.set(2, err_pos.as_ptr());\n        PyErr_SetObject(JsonDecodeError, args.as_ptr());\n        Py_DECREF(args.as_ptr());\n    }\n    null_mut()\n}\n\n#[cold]\n#[inline(never)]\n#[cfg_attr(feature = \"optimize\", optimize(size))]\npub(crate) fn raise_dumps_exception_fixed(msg: &str) -> *mut PyObject {\n    unsafe {\n        let err_msg = PyStrRef::from_str(msg);\n        PyErr_SetObject(JsonEncodeError, err_msg.as_ptr());\n        Py_DECREF(err_msg.as_ptr());\n    }\n    null_mut()\n}\n\n#[cold]\n#[inline(never)]\n#[cfg_attr(feature = \"optimize\", optimize(size))]\n#[cfg(Py_3_12)]\npub(crate) fn raise_dumps_exception_dynamic(err: &str) -> *mut PyObject {\n    unsafe {\n        let cause_exc: *mut PyObject = crate::ffi::PyErr_GetRaisedException();\n\n        let err_msg = PyStrRef::from_str(err);\n        PyErr_SetObject(JsonEncodeError, err_msg.as_ptr());\n        Py_DECREF(err_msg.as_ptr());\n\n        if !cause_exc.is_null() {\n            let exc: *mut PyObject = crate::ffi::PyErr_GetRaisedException();\n            crate::ffi::PyException_SetCause(exc, cause_exc);\n            crate::ffi::PyErr_SetRaisedException(exc);\n        }\n    }\n    null_mut()\n}\n\n#[cold]\n#[inline(never)]\n#[cfg_attr(feature = \"optimize\", optimize(size))]\n#[cfg(not(Py_3_12))]\npub(crate) fn raise_dumps_exception_dynamic(err: &str) -> *mut PyObject {\n    unsafe {\n        let mut cause_tp: *mut PyObject = null_mut();\n        let mut cause_val: *mut PyObject = null_mut();\n        let mut cause_traceback: *mut PyObject = null_mut();\n        crate::ffi::PyErr_Fetch(&mut cause_tp, &mut cause_val, &mut cause_traceback);\n\n        let err_msg = PyStrRef::from_str(err);\n        PyErr_SetObject(JsonEncodeError, err_msg.as_ptr());\n        Py_DECREF(err_msg.as_ptr());\n\n        let mut tp: *mut PyObject = null_mut();\n        let mut val: *mut PyObject = null_mut();\n        let mut traceback: *mut PyObject = null_mut();\n        crate::ffi::PyErr_Fetch(&mut tp, &mut val, &mut traceback);\n        crate::ffi::PyErr_NormalizeException(&mut tp, &mut val, &mut traceback);\n\n        if !cause_tp.is_null() {\n            crate::ffi::PyErr_NormalizeException(\n                &mut cause_tp,\n                &mut cause_val,\n                &mut cause_traceback,\n            );\n            crate::ffi::PyException_SetCause(val, cause_val);\n            Py_DECREF(cause_tp);\n        }\n        if !cause_traceback.is_null() {\n            Py_DECREF(cause_traceback);\n        }\n\n        crate::ffi::PyErr_Restore(tp, val, traceback);\n    }\n    null_mut()\n}\n"
  },
  {
    "path": "src/ffi/atomiculong.rs",
    "content": "// SPDX-License-Identifier: (Apache-2.0 OR MIT)\n// pyo3-ffi/src/impl_/mod.rs at 0.27.1\n\nmod atomic_c_ulong {\n    pub struct GetAtomicCULong<const WIDTH: usize>();\n\n    pub trait AtomicCULongType {\n        type Type;\n    }\n    impl AtomicCULongType for GetAtomicCULong<32> {\n        type Type = core::sync::atomic::AtomicU32;\n    }\n    impl AtomicCULongType for GetAtomicCULong<64> {\n        type Type = core::sync::atomic::AtomicU64;\n    }\n\n    pub type TYPE =\n        <GetAtomicCULong<{ core::mem::size_of::<core::ffi::c_ulong>() * 8 }> as AtomicCULongType>::Type;\n}\n\npub type AtomicCULong = atomic_c_ulong::TYPE;\n"
  },
  {
    "path": "src/ffi/buffer.rs",
    "content": "// SPDX-License-Identifier: (Apache-2.0 OR MIT)\n// Copyright ijl (2021-2026), Baul (2020)\n\nuse crate::ffi::{Py_buffer, Py_hash_t, Py_ssize_t, PyObject, PyVarObject};\nuse core::ffi::c_int;\n\n#[repr(C)]\npub(crate) struct _PyManagedBufferObject {\n    pub ob_base: *mut PyObject,\n    pub flags: c_int,\n    pub exports: Py_ssize_t,\n    pub master: *mut Py_buffer,\n}\n\n#[repr(C)]\npub(crate) struct PyMemoryViewObject {\n    pub ob_base: PyVarObject,\n    pub mbuf: *mut _PyManagedBufferObject,\n    pub hash: Py_hash_t,\n    pub flags: c_int,\n    pub exports: Py_ssize_t,\n    pub view: Py_buffer,\n    pub weakreflist: *mut PyObject,\n    pub ob_array: [Py_ssize_t; 1],\n}\n\n#[allow(non_snake_case)]\n#[inline(always)]\npub(crate) unsafe fn PyMemoryView_GET_BUFFER(op: *mut PyObject) -> *const Py_buffer {\n    unsafe { &raw const (*op.cast::<PyMemoryViewObject>()).view }\n}\n"
  },
  {
    "path": "src/ffi/bytes.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2022-2026)\n\nuse crate::ffi::{Py_ssize_t, PyObject};\nuse core::ffi::c_char;\n\npub(crate) use pyo3_ffi::PyBytesObject;\n\n#[cfg(CPython)]\n#[allow(non_snake_case)]\n#[inline(always)]\npub(crate) unsafe fn PyBytes_AS_STRING(op: *mut PyObject) -> *const c_char {\n    unsafe { (&raw const (*op.cast::<crate::ffi::PyBytesObject>()).ob_sval).cast::<c_char>() }\n}\n\n#[cfg(not(CPython))]\n#[allow(non_snake_case)]\n#[inline(always)]\npub(crate) unsafe fn PyBytes_AS_STRING(op: *mut PyObject) -> *const c_char {\n    unsafe { pyo3_ffi::PyBytes_AsString(op) }\n}\n\n#[allow(non_snake_case)]\n#[inline(always)]\npub(crate) unsafe fn PyBytes_GET_SIZE(op: *mut PyObject) -> Py_ssize_t {\n    unsafe { super::compat::Py_SIZE(op) }\n}\n"
  },
  {
    "path": "src/ffi/compat.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2024-2026)\n\n#[cfg(Py_GIL_DISABLED)]\n#[allow(non_upper_case_globals)]\npub(crate) const _Py_IMMORTAL_REFCNT_LOCAL: u32 = u32::MAX;\n\n#[cfg(all(Py_3_14, target_pointer_width = \"32\"))]\n#[allow(non_upper_case_globals)]\npub(crate) const _Py_IMMORTAL_MINIMUM_REFCNT: pyo3_ffi::Py_ssize_t =\n    ((1 as core::ffi::c_long) << (30 as core::ffi::c_long)) as pyo3_ffi::Py_ssize_t;\n\n#[cfg(all(Py_3_12, not(Py_3_14)))]\n#[allow(non_upper_case_globals)]\npub(crate) const _Py_IMMORTAL_REFCNT: pyo3_ffi::Py_ssize_t = {\n    if cfg!(target_pointer_width = \"64\") {\n        core::ffi::c_uint::MAX as pyo3_ffi::Py_ssize_t\n    } else {\n        // for 32-bit systems, use the lower 30 bits (see comment in CPython's object.h)\n        (core::ffi::c_uint::MAX >> 2) as pyo3_ffi::Py_ssize_t\n    }\n};\n#[cfg(all(Py_3_12, not(Py_GIL_DISABLED)))]\n#[inline(always)]\n#[allow(non_snake_case)]\npub(crate) unsafe fn _Py_IsImmortal(op: *mut pyo3_ffi::PyObject) -> core::ffi::c_int {\n    unsafe {\n        #[cfg(all(target_pointer_width = \"64\", not(Py_GIL_DISABLED)))]\n        {\n            (((*op).ob_refcnt.ob_refcnt as pyo3_ffi::PY_INT32_T) < 0) as core::ffi::c_int\n        }\n\n        #[cfg(all(target_pointer_width = \"32\", not(Py_GIL_DISABLED)))]\n        {\n            #[cfg(not(Py_3_14))]\n            {\n                ((*op).ob_refcnt.ob_refcnt == _Py_IMMORTAL_REFCNT) as core::ffi::c_int\n            }\n\n            #[cfg(Py_3_14)]\n            {\n                ((*op).ob_refcnt.ob_refcnt >= _Py_IMMORTAL_MINIMUM_REFCNT) as core::ffi::c_int\n            }\n        }\n\n        #[cfg(Py_GIL_DISABLED)]\n        {\n            ((*op)\n                .ob_ref_local\n                .load(core::sync::atomic::Ordering::Relaxed)\n                == _Py_IMMORTAL_REFCNT_LOCAL) as core::ffi::c_int\n        }\n    }\n}\n\n#[cfg(CPython)]\n#[inline(always)]\n#[allow(non_snake_case)]\npub(crate) unsafe fn PyDict_New(len: isize) -> *mut pyo3_ffi::PyObject {\n    unsafe {\n        if len > 8 {\n            _PyDict_NewPresized(len)\n        } else {\n            pyo3_ffi::PyDict_New()\n        }\n    }\n}\n\n#[cfg(not(CPython))]\n#[inline(always)]\n#[allow(non_snake_case)]\npub(crate) unsafe fn PyDict_New(_len: isize) -> *mut pyo3_ffi::PyObject {\n    unsafe { pyo3_ffi::PyDict_New() }\n}\n\n#[cfg(all(CPython, Py_3_14))]\n#[inline(always)]\n#[allow(non_snake_case)]\npub(crate) unsafe fn Py_HashBuffer(\n    ptr: *const core::ffi::c_void,\n    len: pyo3_ffi::Py_ssize_t,\n) -> pyo3_ffi::Py_hash_t {\n    unsafe { pyo3_ffi::Py_HashBuffer(ptr, len) }\n}\n\n#[cfg(all(CPython, not(Py_3_14)))]\n#[inline(always)]\n#[allow(non_snake_case)]\npub(crate) unsafe fn Py_HashBuffer(\n    ptr: *const core::ffi::c_void,\n    len: pyo3_ffi::Py_ssize_t,\n) -> pyo3_ffi::Py_hash_t {\n    unsafe { pyo3_ffi::_Py_HashBytes(ptr, len) }\n}\n\n#[cfg(not(Py_3_13))]\n#[inline(always)]\n#[allow(non_snake_case)]\npub(crate) unsafe fn PyLong_AsByteArray(\n    v: *mut pyo3_ffi::PyLongObject,\n    bytes: *mut core::ffi::c_uchar,\n    n: pyo3_ffi::Py_ssize_t,\n    little_endian: core::ffi::c_int,\n    is_signed: core::ffi::c_int,\n) -> core::ffi::c_int {\n    unsafe { _PyLong_AsByteArray(v, bytes, n, little_endian, is_signed) }\n}\n\n#[cfg(Py_3_13)]\n#[inline(always)]\n#[allow(non_snake_case)]\npub(crate) unsafe fn PyLong_AsByteArray(\n    v: *mut pyo3_ffi::PyLongObject,\n    bytes: *mut core::ffi::c_uchar,\n    n: pyo3_ffi::Py_ssize_t,\n    little_endian: core::ffi::c_int,\n    is_signed: core::ffi::c_int,\n) -> core::ffi::c_int {\n    unsafe { _PyLong_AsByteArray(v, bytes, n, little_endian, is_signed, 0) }\n}\n\n#[cfg(CPython)]\n#[inline(always)]\n#[allow(non_snake_case)]\npub(crate) unsafe fn Py_SIZE(op: *mut pyo3_ffi::PyObject) -> pyo3_ffi::Py_ssize_t {\n    unsafe { (*op.cast::<pyo3_ffi::PyVarObject>()).ob_size }\n}\n\n#[cfg(not(CPython))]\n#[inline(always)]\n#[allow(non_snake_case)]\npub(crate) unsafe fn Py_SIZE(op: *mut pyo3_ffi::PyObject) -> pyo3_ffi::Py_ssize_t {\n    unsafe { pyo3_ffi::Py_SIZE(op) }\n}\n\n#[allow(unused)]\n#[cfg(any(CPython, PyPy))]\n#[inline(always)]\n#[allow(non_snake_case)]\npub(crate) unsafe fn Py_SET_SIZE(op: *mut pyo3_ffi::PyVarObject, size: pyo3_ffi::Py_ssize_t) {\n    unsafe { (*op).ob_size = size }\n}\n\n#[allow(unused)]\n#[cfg(GraalPy)]\n#[inline(always)]\n#[allow(non_snake_case)]\npub(crate) unsafe fn Py_SET_SIZE(op: *mut pyo3_ffi::PyVarObject, size: pyo3_ffi::Py_ssize_t) {\n    unsafe { (*op)._ob_size_graalpy = size }\n}\n\n#[cfg(CPython)]\n#[inline(always)]\n#[allow(non_snake_case)]\npub(crate) unsafe fn PyTuple_GET_ITEM(\n    op: *mut pyo3_ffi::PyObject,\n    i: pyo3_ffi::Py_ssize_t,\n) -> *mut pyo3_ffi::PyObject {\n    unsafe {\n        *(*op.cast::<pyo3_ffi::PyTupleObject>())\n            .ob_item\n            .as_ptr()\n            .offset(i)\n    }\n}\n\n#[cfg(not(CPython))]\n#[inline(always)]\n#[allow(non_snake_case)]\npub(crate) unsafe fn PyTuple_GET_ITEM(\n    op: *mut pyo3_ffi::PyObject,\n    i: pyo3_ffi::Py_ssize_t,\n) -> *mut pyo3_ffi::PyObject {\n    unsafe { pyo3_ffi::PyTuple_GetItem(op, i) }\n}\n\n#[cfg(CPython)]\n#[inline(always)]\n#[allow(non_snake_case)]\npub(crate) unsafe fn PyTuple_SET_ITEM(\n    op: *mut pyo3_ffi::PyObject,\n    i: pyo3_ffi::Py_ssize_t,\n    v: *mut pyo3_ffi::PyObject,\n) {\n    unsafe {\n        *(*(op.cast::<pyo3_ffi::PyTupleObject>()))\n            .ob_item\n            .as_mut_ptr()\n            .offset(i) = v;\n    }\n}\n\n#[cfg(not(CPython))]\n#[inline(always)]\n#[allow(non_snake_case)]\npub(crate) unsafe fn PyTuple_SET_ITEM(\n    op: *mut pyo3_ffi::PyObject,\n    i: pyo3_ffi::Py_ssize_t,\n    v: *mut pyo3_ffi::PyObject,\n) {\n    unsafe {\n        pyo3_ffi::PyTuple_SetItem(op, i, v);\n    }\n}\n\nunsafe extern \"C\" {\n\n    #[cfg(CPython)]\n    pub fn _PyBytes_Resize(\n        pv: *mut *mut pyo3_ffi::PyObject,\n        newsize: pyo3_ffi::Py_ssize_t,\n    ) -> core::ffi::c_int;\n\n    #[cfg(CPython)]\n    pub fn _PyDict_Next(\n        mp: *mut pyo3_ffi::PyObject,\n        pos: *mut pyo3_ffi::Py_ssize_t,\n        key: *mut *mut pyo3_ffi::PyObject,\n        value: *mut *mut pyo3_ffi::PyObject,\n        hash: *mut pyo3_ffi::Py_hash_t,\n    ) -> core::ffi::c_int;\n\n    #[cfg(CPython)]\n    pub fn _PyDict_NewPresized(minused: pyo3_ffi::Py_ssize_t) -> *mut pyo3_ffi::PyObject;\n\n    #[cfg(CPython)]\n    pub fn _PyDict_Contains_KnownHash(\n        op: *mut pyo3_ffi::PyObject,\n        key: *mut pyo3_ffi::PyObject,\n        hash: pyo3_ffi::Py_hash_t,\n    ) -> core::ffi::c_int;\n\n    #[cfg(all(CPython, not(Py_3_13)))]\n    pub(crate) fn _PyDict_SetItem_KnownHash(\n        mp: *mut pyo3_ffi::PyObject,\n        name: *mut pyo3_ffi::PyObject,\n        value: *mut pyo3_ffi::PyObject,\n        hash: pyo3_ffi::Py_hash_t,\n    ) -> core::ffi::c_int;\n\n    #[cfg(all(CPython, Py_3_13))]\n    pub(crate) fn _PyDict_SetItem_KnownHash_LockHeld(\n        mp: *mut pyo3_ffi::PyDictObject,\n        name: *mut pyo3_ffi::PyObject,\n        value: *mut pyo3_ffi::PyObject,\n        hash: pyo3_ffi::Py_hash_t,\n    ) -> core::ffi::c_int;\n\n    #[cfg(Py_3_13)]\n    #[cfg_attr(PyPy, link_name = \"_PyPyLong_AsByteArrayO\")]\n    pub(crate) fn _PyLong_AsByteArray(\n        v: *mut pyo3_ffi::PyLongObject,\n        bytes: *mut core::ffi::c_uchar,\n        n: pyo3_ffi::Py_ssize_t,\n        little_endian: core::ffi::c_int,\n        is_signed: core::ffi::c_int,\n        with_exceptions: core::ffi::c_int,\n    ) -> core::ffi::c_int;\n\n    #[cfg(not(Py_3_13))]\n    #[cfg_attr(PyPy, link_name = \"_PyPyLong_AsByteArrayO\")]\n    pub(crate) fn _PyLong_AsByteArray(\n        v: *mut pyo3_ffi::PyLongObject,\n        bytes: *mut core::ffi::c_uchar,\n        n: pyo3_ffi::Py_ssize_t,\n        little_endian: core::ffi::c_int,\n        is_signed: core::ffi::c_int,\n    ) -> core::ffi::c_int;\n}\n"
  },
  {
    "path": "src/ffi/fragment.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2020-2026)\n\nuse core::ffi::c_char;\n\nuse crate::ffi::{\n    Py_DECREF, Py_INCREF, Py_TPFLAGS_DEFAULT, PyErr_SetObject, PyExc_TypeError, PyObject,\n    PyTupleRef, PyType_Ready, PyType_Type, PyTypeObject, PyUnicode_FromStringAndSize, PyVarObject,\n};\nuse core::ptr::null_mut;\n\n#[cfg(Py_GIL_DISABLED)]\nuse super::atomiculong::AtomicCULong;\n#[cfg(Py_GIL_DISABLED)]\nuse core::sync::atomic::{AtomicIsize, AtomicU32};\n\n#[cfg(Py_GIL_DISABLED)]\nmacro_rules! pymutex_new {\n    () => {\n        unsafe { core::mem::zeroed() }\n    };\n}\n\n#[repr(C)]\npub(crate) struct Fragment {\n    #[cfg(Py_GIL_DISABLED)]\n    pub ob_tid: usize,\n    #[cfg(all(Py_GIL_DISABLED, Py_3_14))]\n    pub ob_flags: u16,\n    #[cfg(all(Py_GIL_DISABLED, not(Py_3_14)))]\n    pub _padding: u16,\n    #[cfg(Py_GIL_DISABLED)]\n    pub ob_mutex: pyo3_ffi::PyMutex,\n    #[cfg(Py_GIL_DISABLED)]\n    pub ob_gc_bits: u8,\n    #[cfg(Py_GIL_DISABLED)]\n    pub ob_ref_local: AtomicU32,\n    #[cfg(Py_GIL_DISABLED)]\n    pub ob_ref_shared: AtomicIsize,\n    #[cfg(not(Py_GIL_DISABLED))]\n    pub ob_refcnt: pyo3_ffi::Py_ssize_t,\n    #[cfg(PyPy)]\n    pub ob_pypy_link: pyo3_ffi::Py_ssize_t,\n    pub ob_type: *mut pyo3_ffi::PyTypeObject,\n    pub contents: *mut pyo3_ffi::PyObject,\n}\n\n#[cold]\n#[inline(never)]\n#[cfg_attr(feature = \"optimize\", optimize(size))]\nfn raise_args_exception() {\n    unsafe {\n        let msg = \"orjson.Fragment() takes exactly 1 positional argument\";\n        let err_msg =\n            PyUnicode_FromStringAndSize(msg.as_ptr().cast::<c_char>(), msg.len().cast_signed());\n        PyErr_SetObject(PyExc_TypeError, err_msg);\n        Py_DECREF(err_msg);\n    };\n}\n\n#[unsafe(no_mangle)]\n#[cold]\n#[cfg_attr(feature = \"optimize\", optimize(size))]\npub(crate) unsafe extern \"C\" fn orjson_fragment_tp_new(\n    _subtype: *mut PyTypeObject,\n    args: *mut PyObject,\n    kwds: *mut PyObject,\n) -> *mut PyObject {\n    unsafe {\n        let argsob = PyTupleRef::from_ptr_unchecked(args);\n        if argsob.len() != 1 || !kwds.is_null() {\n            raise_args_exception();\n            null_mut()\n        } else {\n            let contents = argsob.get(0);\n            Py_INCREF(contents);\n            let obj = Box::new(Fragment {\n                #[cfg(Py_GIL_DISABLED)]\n                ob_tid: 0,\n                #[cfg(all(Py_GIL_DISABLED, Py_3_14))]\n                ob_flags: 0,\n                #[cfg(all(Py_GIL_DISABLED, not(Py_3_14)))]\n                _padding: 0,\n                #[cfg(Py_GIL_DISABLED)]\n                ob_mutex: pymutex_new!(),\n                #[cfg(Py_GIL_DISABLED)]\n                ob_gc_bits: 0,\n                #[cfg(Py_GIL_DISABLED)]\n                ob_ref_local: AtomicU32::new(0),\n                #[cfg(Py_GIL_DISABLED)]\n                ob_ref_shared: AtomicIsize::new(0),\n                #[cfg(not(Py_GIL_DISABLED))]\n                ob_refcnt: 1,\n                #[cfg(PyPy)]\n                ob_pypy_link: 0,\n                ob_type: crate::typeref::FRAGMENT_TYPE,\n                contents: contents,\n            });\n            Box::into_raw(obj).cast::<PyObject>()\n        }\n    }\n}\n\n#[unsafe(no_mangle)]\n#[cold]\n#[cfg_attr(feature = \"optimize\", optimize(size))]\npub(crate) unsafe extern \"C\" fn orjson_fragment_dealloc(object: *mut PyObject) {\n    unsafe {\n        Py_DECREF((*object.cast::<Fragment>()).contents);\n        crate::ffi::PyMem_Free(object.cast::<core::ffi::c_void>());\n    }\n}\n\n#[unsafe(no_mangle)]\n#[cold]\n#[cfg_attr(feature = \"optimize\", optimize(size))]\npub(crate) unsafe extern \"C\" fn orjson_fragmenttype_new() -> *mut PyTypeObject {\n    unsafe {\n        #[cfg(Py_GIL_DISABLED)]\n        let tp_flags: AtomicCULong =\n            AtomicCULong::new(Py_TPFLAGS_DEFAULT | pyo3_ffi::Py_TPFLAGS_IMMUTABLETYPE);\n        #[cfg(not(Py_GIL_DISABLED))]\n        let tp_flags: core::ffi::c_ulong = Py_TPFLAGS_DEFAULT | pyo3_ffi::Py_TPFLAGS_IMMUTABLETYPE;\n        let ob = Box::new(PyTypeObject {\n            ob_base: PyVarObject {\n                ob_base: PyObject {\n                    #[cfg(Py_GIL_DISABLED)]\n                    ob_tid: 0,\n                    #[cfg(all(Py_GIL_DISABLED, Py_3_14))]\n                    ob_flags: 0,\n                    #[cfg(all(Py_GIL_DISABLED, not(Py_3_14)))]\n                    _padding: 0,\n                    #[cfg(Py_GIL_DISABLED)]\n                    ob_mutex: pymutex_new!(),\n                    #[cfg(Py_GIL_DISABLED)]\n                    ob_gc_bits: 0,\n                    #[cfg(Py_GIL_DISABLED)]\n                    ob_ref_local: AtomicU32::new(crate::ffi::compat::_Py_IMMORTAL_REFCNT_LOCAL),\n                    #[cfg(Py_GIL_DISABLED)]\n                    ob_ref_shared: AtomicIsize::new(0),\n                    #[cfg(all(Py_3_12, not(Py_GIL_DISABLED)))]\n                    ob_refcnt: pyo3_ffi::PyObjectObRefcnt { ob_refcnt: 0 },\n                    #[cfg(not(Py_3_12))]\n                    ob_refcnt: 0,\n                    #[cfg(PyPy)]\n                    ob_pypy_link: 0,\n                    ob_type: &raw mut PyType_Type,\n                },\n                #[cfg(not(GraalPy))]\n                ob_size: 0,\n                #[cfg(GraalPy)]\n                _ob_size_graalpy: 0,\n            },\n            tp_name: c\"orjson.Fragment\".as_ptr(),\n            tp_basicsize: core::mem::size_of::<Fragment>().cast_signed(),\n            tp_itemsize: 0,\n            tp_dealloc: Some(orjson_fragment_dealloc),\n            tp_init: None,\n            tp_new: Some(orjson_fragment_tp_new),\n            tp_flags: tp_flags,\n            // ...\n            tp_bases: null_mut(),\n            tp_cache: null_mut(),\n            tp_del: None,\n            tp_finalize: None,\n            tp_free: None,\n            tp_is_gc: None,\n            tp_mro: null_mut(),\n            tp_subclasses: null_mut(),\n            tp_vectorcall: None,\n            tp_version_tag: 0,\n            tp_weaklist: null_mut(),\n            tp_vectorcall_offset: 0,\n            tp_getattr: None,\n            tp_setattr: None,\n            tp_as_async: null_mut(),\n            tp_repr: None,\n            tp_as_number: null_mut(),\n            tp_as_sequence: null_mut(),\n            tp_as_mapping: null_mut(),\n            tp_hash: None,\n            tp_call: None,\n            tp_str: None,\n            tp_getattro: None,\n            tp_setattro: None,\n            tp_as_buffer: null_mut(),\n            tp_doc: core::ptr::null_mut(),\n            tp_traverse: None,\n            tp_clear: None,\n            tp_richcompare: None,\n            tp_weaklistoffset: 0,\n            tp_iter: None,\n            tp_iternext: None,\n            tp_methods: null_mut(),\n            tp_members: null_mut(),\n            tp_getset: null_mut(),\n            tp_base: null_mut(),\n            tp_dict: null_mut(),\n            tp_descr_get: None,\n            tp_descr_set: None,\n            tp_dictoffset: 0,\n            tp_alloc: None,\n            #[cfg(Py_3_12)]\n            tp_watched: 0,\n        });\n        let ob_ptr = Box::into_raw(ob);\n        PyType_Ready(ob_ptr);\n        ob_ptr\n    }\n}\n"
  },
  {
    "path": "src/ffi/mod.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2022-2026)\n\n#[cfg(Py_GIL_DISABLED)]\nmod atomiculong;\n#[cfg(all(CPython, not(Py_GIL_DISABLED)))]\nmod buffer;\nmod bytes;\npub(crate) mod compat;\nmod fragment;\nmod pyboolref;\n#[cfg(all(CPython, not(Py_GIL_DISABLED)))]\nmod pybytearrayref;\nmod pybytesref;\nmod pydictref;\nmod pyfloatref;\nmod pyfragmentref;\nmod pyintref;\nmod pylistref;\n#[cfg(all(CPython, not(Py_GIL_DISABLED)))]\nmod pymemoryview;\nmod pynoneref;\nmod pystrref;\nmod pytupleref;\nmod pyuuidref;\nmod utf8;\n\npub(crate) use compat::*;\n\n#[allow(unused_imports)]\npub(crate) use {\n    bytes::{PyBytes_AS_STRING, PyBytes_GET_SIZE, PyBytesObject},\n    fragment::{Fragment, orjson_fragmenttype_new},\n    pyboolref::PyBoolRef,\n    pybytesref::{PyBytesRef, PyBytesRefError},\n    pydictref::PyDictRef,\n    pyfloatref::PyFloatRef,\n    pyfragmentref::{PyFragmentRef, PyFragmentRefError},\n    pyintref::{PyIntError, PyIntKind, PyIntRef},\n    pylistref::PyListRef,\n    pynoneref::PyNoneRef,\n    pystrref::{PyStrRef, PyStrSubclassRef, set_str_create_fn},\n    pytupleref::PyTupleRef,\n    pyuuidref::PyUuidRef,\n};\n\n#[allow(unused_imports)]\n#[cfg(all(CPython, not(Py_GIL_DISABLED)))]\npub(crate) use {\n    pybytearrayref::{PyByteArrayRef, PyByteArrayRefError},\n    pymemoryview::{PyMemoryViewRef, PyMemoryViewRefError},\n};\n\n#[allow(unused_imports)]\npub(crate) use pyo3_ffi::{\n    METH_FASTCALL, METH_KEYWORDS, METH_O, Py_DECREF, Py_False, Py_INCREF, Py_None, Py_REFCNT,\n    Py_TPFLAGS_DEFAULT, Py_TPFLAGS_DICT_SUBCLASS, Py_TPFLAGS_LIST_SUBCLASS,\n    Py_TPFLAGS_LONG_SUBCLASS, Py_TPFLAGS_TUPLE_SUBCLASS, Py_TPFLAGS_UNICODE_SUBCLASS, Py_TYPE,\n    Py_True, Py_XDECREF, Py_buffer, Py_hash_t, Py_intptr_t, Py_mod_exec, Py_ssize_t, PyASCIIObject,\n    PyBool_Type, PyBuffer_IsContiguous, PyByteArray_AsString, PyByteArray_Size, PyByteArray_Type,\n    PyBytes_FromStringAndSize, PyBytes_Type, PyCFunction_NewEx, PyCapsule_Import,\n    PyCompactUnicodeObject, PyDateTime_CAPI, PyDateTime_DATE_GET_HOUR,\n    PyDateTime_DATE_GET_MICROSECOND, PyDateTime_DATE_GET_MINUTE, PyDateTime_DATE_GET_SECOND,\n    PyDateTime_DATE_GET_TZINFO, PyDateTime_DELTA_GET_DAYS, PyDateTime_DELTA_GET_SECONDS,\n    PyDateTime_DateTime, PyDateTime_GET_DAY, PyDateTime_GET_MONTH, PyDateTime_GET_YEAR,\n    PyDateTime_IMPORT, PyDateTime_TIME_GET_HOUR, PyDateTime_TIME_GET_MICROSECOND,\n    PyDateTime_TIME_GET_MINUTE, PyDateTime_TIME_GET_SECOND, PyDateTime_Time, PyDict_Contains,\n    PyDict_Next, PyDict_SetItem, PyDict_Type, PyDictObject, PyErr_Clear, PyErr_NewException,\n    PyErr_Occurred, PyErr_SetObject, PyExc_TypeError, PyException_SetCause, PyFloat_AS_DOUBLE,\n    PyFloat_FromDouble, PyFloat_Type, PyImport_ImportModule, PyList_GET_ITEM, PyList_New,\n    PyList_SET_ITEM, PyList_Type, PyListObject, PyLong_AsLong, PyLong_AsLongLong,\n    PyLong_AsUnsignedLongLong, PyLong_FromLongLong, PyLong_FromUnsignedLongLong, PyLong_Type,\n    PyLongObject, PyMapping_GetItemString, PyMem_Free, PyMem_Malloc, PyMem_Realloc,\n    PyMemoryView_Type, PyMethodDef, PyMethodDefPointer, PyModule_AddIntConstant,\n    PyModule_AddObject, PyModuleDef, PyModuleDef_HEAD_INIT, PyModuleDef_Init, PyModuleDef_Slot,\n    PyObject, PyObject_CallFunctionObjArgs, PyObject_CallMethodObjArgs, PyObject_GenericGetDict,\n    PyObject_GetAttr, PyObject_HasAttr, PyObject_Hash, PyObject_Vectorcall, PyTuple_New,\n    PyTuple_Type, PyTupleObject, PyType_Ready, PyType_Type, PyTypeObject, PyUnicode_AsUTF8AndSize,\n    PyUnicode_FromStringAndSize, PyUnicode_InternFromString, PyUnicode_New, PyUnicode_Type,\n    PyVarObject, PyVectorcall_NARGS,\n};\n\n#[allow(unused_imports, deprecated)]\npub(crate) use pyo3_ffi::PyErr_Restore;\n\n#[cfg(CPython)]\npub(crate) use pyo3_ffi::{PyObject_CallMethodNoArgs, PyObject_CallMethodOneArg};\n\n#[cfg(all(CPython, not(Py_GIL_DISABLED)))]\npub(crate) use buffer::PyMemoryView_GET_BUFFER;\n\n#[cfg(not(feature = \"inline_str\"))]\npub(crate) use pyo3_ffi::{PyUnicode_DATA, PyUnicode_KIND};\n\n#[cfg(Py_3_12)]\n#[allow(unused_imports)]\npub(crate) use pyo3_ffi::{\n    Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED, Py_mod_multiple_interpreters,\n    PyErr_GetRaisedException, PyErr_SetRaisedException, PyType_GetDict,\n};\n\n#[cfg(not(Py_3_12))]\n#[allow(unused_imports)]\npub(crate) use pyo3_ffi::{PyErr_Fetch, PyErr_NormalizeException};\n\n#[cfg(not(Py_3_13))]\n#[allow(unused_imports)]\npub(crate) use pyo3_ffi::PyModule_AddObjectRef;\n\n#[cfg(Py_3_13)]\n#[allow(unused_imports)]\npub(crate) use pyo3_ffi::PyModule_Add;\n\n#[cfg(Py_3_13)]\n#[allow(unused_imports)]\npub(crate) use pyo3_ffi::{Py_MOD_GIL_USED, Py_mod_gil};\n"
  },
  {
    "path": "src/ffi/pyboolref.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2026)\n\n#[derive(Clone)]\n#[repr(transparent)]\npub(crate) struct PyBoolRef {\n    ptr: core::ptr::NonNull<pyo3_ffi::PyObject>,\n}\n\nunsafe impl Send for PyBoolRef {}\nunsafe impl Sync for PyBoolRef {}\n\nimpl PartialEq for PyBoolRef {\n    fn eq(&self, other: &Self) -> bool {\n        self.ptr == other.ptr\n    }\n}\n\nimpl PyBoolRef {\n    #[inline]\n    pub(crate) unsafe fn from_ptr_unchecked(ptr: *mut pyo3_ffi::PyObject) -> Self {\n        unsafe {\n            debug_assert!(!ptr.is_null());\n            debug_assert!(ob_type!(ptr) == crate::typeref::BOOL_TYPE);\n            Self {\n                ptr: core::ptr::NonNull::new_unchecked(ptr),\n            }\n        }\n    }\n\n    #[inline]\n    #[allow(unused)]\n    pub const fn as_ptr(&self) -> *mut pyo3_ffi::PyObject {\n        self.ptr.as_ptr()\n    }\n\n    #[inline]\n    #[allow(unused)]\n    pub const fn as_non_null_ptr(&self) -> core::ptr::NonNull<pyo3_ffi::PyObject> {\n        self.ptr\n    }\n\n    #[inline]\n    pub fn pytrue() -> Self {\n        Self {\n            ptr: unsafe { core::ptr::NonNull::new_unchecked(use_immortal!(crate::typeref::TRUE)) },\n        }\n    }\n\n    #[inline]\n    pub fn pyfalse() -> Self {\n        Self {\n            ptr: unsafe { core::ptr::NonNull::new_unchecked(use_immortal!(crate::typeref::FALSE)) },\n        }\n    }\n}\n"
  },
  {
    "path": "src/ffi/pybytearrayref.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2026)\n\npub(crate) enum PyByteArrayRefError {\n    NotType,\n}\n\n#[derive(Clone)]\n#[repr(transparent)]\npub(crate) struct PyByteArrayRef {\n    ptr: core::ptr::NonNull<pyo3_ffi::PyObject>,\n}\n\nunsafe impl Send for PyByteArrayRef {}\nunsafe impl Sync for PyByteArrayRef {}\n\nimpl PartialEq for PyByteArrayRef {\n    fn eq(&self, other: &Self) -> bool {\n        self.ptr == other.ptr\n    }\n}\n\nimpl PyByteArrayRef {\n    #[inline]\n    pub fn from_ptr(ptr: *mut pyo3_ffi::PyObject) -> Result<Self, PyByteArrayRefError> {\n        unsafe {\n            debug_assert!(!ptr.is_null());\n            if ob_type!(ptr) == &raw mut crate::ffi::PyByteArray_Type {\n                Ok(Self {\n                    ptr: core::ptr::NonNull::new_unchecked(ptr),\n                })\n            } else {\n                Err(PyByteArrayRefError::NotType)\n            }\n        }\n    }\n\n    #[inline]\n    pub fn as_ptr(&self) -> *mut pyo3_ffi::PyObject {\n        self.ptr.as_ptr()\n    }\n\n    #[allow(unused)]\n    #[inline]\n    pub fn as_non_null_ptr(&self) -> core::ptr::NonNull<pyo3_ffi::PyObject> {\n        self.ptr\n    }\n\n    #[inline]\n    pub fn as_bytes(&self) -> &'static [u8] {\n        unsafe {\n            core::slice::from_raw_parts(\n                crate::ffi::PyByteArray_AsString(self.as_ptr())\n                    .cast::<u8>()\n                    .cast_const(),\n                crate::util::isize_to_usize(crate::ffi::PyByteArray_Size(self.as_ptr())),\n            )\n        }\n    }\n\n    #[inline]\n    pub fn as_str(&self) -> Option<&'static str> {\n        let buffer = self.as_bytes();\n        if !crate::ffi::utf8::is_valid_utf8(buffer) {\n            cold_path!();\n            None\n        } else {\n            unsafe { Some(core::str::from_utf8_unchecked(buffer)) }\n        }\n    }\n}\n"
  },
  {
    "path": "src/ffi/pybytesref.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2026)\n\npub(crate) enum PyBytesRefError {\n    NotType,\n}\n\n#[derive(Clone)]\n#[repr(transparent)]\npub(crate) struct PyBytesRef {\n    ptr: core::ptr::NonNull<pyo3_ffi::PyObject>,\n}\n\nunsafe impl Send for PyBytesRef {}\nunsafe impl Sync for PyBytesRef {}\n\nimpl PartialEq for PyBytesRef {\n    fn eq(&self, other: &Self) -> bool {\n        self.ptr == other.ptr\n    }\n}\n\nimpl PyBytesRef {\n    #[inline]\n    pub fn from_ptr(ptr: *mut pyo3_ffi::PyObject) -> Result<Self, PyBytesRefError> {\n        unsafe {\n            debug_assert!(!ptr.is_null());\n            if ob_type!(ptr) == crate::typeref::BYTES_TYPE {\n                Ok(Self {\n                    ptr: core::ptr::NonNull::new_unchecked(ptr),\n                })\n            } else {\n                Err(PyBytesRefError::NotType)\n            }\n        }\n    }\n\n    #[inline]\n    pub fn as_ptr(&self) -> *mut pyo3_ffi::PyObject {\n        self.ptr.as_ptr()\n    }\n\n    #[allow(unused)]\n    #[inline]\n    pub fn as_non_null_ptr(&self) -> core::ptr::NonNull<pyo3_ffi::PyObject> {\n        self.ptr\n    }\n\n    #[inline]\n    pub fn as_bytes(&self) -> &'static [u8] {\n        unsafe {\n            core::slice::from_raw_parts(\n                crate::ffi::PyBytes_AS_STRING(self.as_ptr()).cast::<u8>(),\n                crate::util::isize_to_usize(crate::ffi::PyBytes_GET_SIZE(self.as_ptr())),\n            )\n        }\n    }\n\n    #[inline]\n    pub fn as_str(&self) -> Option<&'static str> {\n        let buffer = self.as_bytes();\n        if !crate::ffi::utf8::is_valid_utf8(buffer) {\n            cold_path!();\n            None\n        } else {\n            unsafe { Some(core::str::from_utf8_unchecked(buffer)) }\n        }\n    }\n}\n"
  },
  {
    "path": "src/ffi/pydictref.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2025-2026)\n\n#[allow(unused)]\nuse super::Py_TPFLAGS_DICT_SUBCLASS;\n\n#[derive(Clone)]\n#[repr(transparent)]\npub(crate) struct PyDictRef {\n    ptr: core::ptr::NonNull<pyo3_ffi::PyObject>,\n}\n\nunsafe impl Send for PyDictRef {}\nunsafe impl Sync for PyDictRef {}\n\nimpl PartialEq for PyDictRef {\n    fn eq(&self, other: &Self) -> bool {\n        self.ptr == other.ptr\n    }\n}\n\nimpl PyDictRef {\n    #[cfg(CPython)]\n    #[inline]\n    pub fn with_capacity(cap: usize) -> Self {\n        unsafe {\n            let ptr = crate::ffi::PyDict_New(crate::util::usize_to_isize(cap));\n            debug_assert!(!ptr.is_null());\n            Self { ptr: nonnull!(ptr) }\n        }\n    }\n\n    #[cfg(not(CPython))]\n    #[allow(unused)]\n    #[inline]\n    pub fn with_capacity(_cap: usize) -> Self {\n        Self::new()\n    }\n\n    #[allow(unused)]\n    #[inline]\n    pub fn new() -> Self {\n        unsafe {\n            let ptr = crate::ffi::PyDict_New(0);\n            debug_assert!(!ptr.is_null());\n            Self { ptr: nonnull!(ptr) }\n        }\n    }\n\n    #[inline]\n    pub(crate) unsafe fn from_ptr_unchecked(ptr: *mut pyo3_ffi::PyObject) -> Self {\n        unsafe {\n            debug_assert!(!ptr.is_null());\n            debug_assert!(\n                ob_type!(ptr) == crate::typeref::DICT_TYPE\n                    || is_subclass_by_flag!(tp_flags!(ob_type!(ptr)), Py_TPFLAGS_DICT_SUBCLASS)\n            );\n            Self {\n                ptr: core::ptr::NonNull::new_unchecked(ptr),\n            }\n        }\n    }\n\n    #[inline]\n    #[allow(unused)]\n    pub fn as_ptr(&self) -> *mut pyo3_ffi::PyObject {\n        self.ptr.as_ptr()\n    }\n\n    #[inline]\n    #[allow(unused)]\n    pub fn as_non_null_ptr(&self) -> core::ptr::NonNull<pyo3_ffi::PyObject> {\n        self.ptr\n    }\n\n    #[inline]\n    pub fn len(&self) -> usize {\n        unsafe { crate::util::isize_to_usize(super::Py_SIZE(self.as_ptr())) }\n    }\n\n    #[cfg(CPython)]\n    #[inline]\n    pub fn set(&mut self, key: crate::ffi::PyStrRef, value: *mut crate::ffi::PyObject) {\n        debug_assert!(ffi!(Py_REFCNT(self.as_ptr())) == 1);\n        debug_assert!(key.hash() != -1);\n        #[cfg(not(Py_3_13))]\n        unsafe {\n            let _ = crate::ffi::_PyDict_SetItem_KnownHash(\n                self.as_ptr(),\n                key.as_ptr(),\n                value,\n                key.hash(),\n            );\n        }\n        #[cfg(Py_3_13)]\n        unsafe {\n            let _ = crate::ffi::_PyDict_SetItem_KnownHash_LockHeld(\n                self.as_ptr().cast::<crate::ffi::PyDictObject>(),\n                key.as_ptr(),\n                value,\n                key.hash(),\n            );\n        }\n        #[cfg(not(Py_GIL_DISABLED))]\n        reverse_pydict_incref!(key.as_ptr());\n        reverse_pydict_incref!(value);\n    }\n\n    #[cfg(not(CPython))]\n    #[inline]\n    pub fn set(&mut self, key: crate::ffi::PyStrRef, value: *mut crate::ffi::PyObject) {\n        unsafe {\n            let _ = crate::ffi::PyDict_SetItem(self.as_ptr(), key.as_ptr(), value);\n        }\n        #[cfg(not(Py_GIL_DISABLED))]\n        reverse_pydict_incref!(key.as_ptr());\n        reverse_pydict_incref!(value);\n    }\n}\n"
  },
  {
    "path": "src/ffi/pyfloatref.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2026)\n\n#[derive(Clone)]\n#[repr(transparent)]\npub(crate) struct PyFloatRef {\n    ptr: core::ptr::NonNull<pyo3_ffi::PyObject>,\n}\n\nunsafe impl Send for PyFloatRef {}\nunsafe impl Sync for PyFloatRef {}\n\nimpl PartialEq for PyFloatRef {\n    fn eq(&self, other: &Self) -> bool {\n        self.ptr == other.ptr\n    }\n}\n\nimpl PyFloatRef {\n    #[inline]\n    pub(crate) unsafe fn from_ptr_unchecked(ptr: *mut pyo3_ffi::PyObject) -> Self {\n        unsafe {\n            debug_assert!(!ptr.is_null());\n            debug_assert!(ob_type!(ptr) == crate::typeref::FLOAT_TYPE);\n            Self {\n                ptr: core::ptr::NonNull::new_unchecked(ptr),\n            }\n        }\n    }\n\n    #[inline]\n    pub fn as_non_null_ptr(&self) -> core::ptr::NonNull<pyo3_ffi::PyObject> {\n        self.ptr\n    }\n\n    #[inline]\n    pub fn value(&self) -> f64 {\n        unsafe { super::PyFloat_AS_DOUBLE(self.ptr.as_ptr()) }\n    }\n\n    #[inline]\n    pub fn from_f64(value: f64) -> Self {\n        unsafe {\n            let ptr = super::PyFloat_FromDouble(value);\n            Self::from_ptr_unchecked(ptr)\n        }\n    }\n}\n"
  },
  {
    "path": "src/ffi/pyfragmentref.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2026)\n\nuse crate::ffi::{Fragment, PyBytesRef, PyStrRef};\n\npub(crate) enum PyFragmentRefError {\n    InvalidStr,\n    InvalidFragment,\n}\n\n#[repr(transparent)]\npub(crate) struct PyFragmentRef {\n    ptr: core::ptr::NonNull<pyo3_ffi::PyObject>,\n}\n\nunsafe impl Send for PyFragmentRef {}\nunsafe impl Sync for PyFragmentRef {}\n\nimpl PartialEq for PyFragmentRef {\n    fn eq(&self, other: &Self) -> bool {\n        self.ptr == other.ptr\n    }\n}\n\nimpl PyFragmentRef {\n    #[inline]\n    pub(crate) unsafe fn from_ptr_unchecked(ptr: *mut pyo3_ffi::PyObject) -> Self {\n        unsafe {\n            debug_assert!(!ptr.is_null());\n            debug_assert!(ob_type!(ptr) == crate::typeref::FRAGMENT_TYPE);\n            Self {\n                ptr: core::ptr::NonNull::new_unchecked(ptr),\n            }\n        }\n    }\n\n    #[inline]\n    #[allow(unused)]\n    pub fn as_ptr(&self) -> *mut pyo3_ffi::PyObject {\n        self.ptr.as_ptr()\n    }\n\n    #[inline]\n    #[allow(unused)]\n    pub fn as_non_null_ptr(&self) -> core::ptr::NonNull<pyo3_ffi::PyObject> {\n        self.ptr\n    }\n\n    #[cold]\n    pub fn value(&self) -> Result<&[u8], PyFragmentRefError> {\n        let buffer: &[u8];\n        unsafe {\n            let contents: *mut pyo3_ffi::PyObject =\n                (*self.ptr.as_ptr().cast::<Fragment>()).contents;\n            if let Ok(ob) = PyBytesRef::from_ptr(contents) {\n                buffer = ob.as_bytes();\n            } else if let Ok(ob) = PyStrRef::from_ptr(contents) {\n                match ob.as_str() {\n                    Some(ob) => buffer = ob.as_bytes(),\n                    None => return Err(PyFragmentRefError::InvalidStr),\n                }\n            } else {\n                return Err(PyFragmentRefError::InvalidFragment);\n            }\n            Ok(buffer)\n        }\n    }\n}\n"
  },
  {
    "path": "src/ffi/pyintref.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2023-2026)\n\n#[allow(unused)]\nuse super::Py_TPFLAGS_LONG_SUBCLASS;\nuse super::{PyLong_FromLongLong, PyLong_FromUnsignedLongLong, PyObject};\nuse crate::opt::{MAX_OPT, Opt};\n\n// longintrepr.h, _longobject, _PyLongValue\n\n#[allow(dead_code)]\n#[cfg(Py_3_12)]\n#[allow(non_upper_case_globals)]\nconst SIGN_MASK: usize = 3;\n\n#[cfg(all(Py_3_12, feature = \"inline_int\"))]\n#[allow(non_upper_case_globals)]\nconst NON_SIZE_BITS: usize = 3;\n\n#[cfg(Py_3_12)]\n#[repr(C)]\npub(crate) struct _PyLongValue {\n    pub lv_tag: usize,\n    pub ob_digit: u32,\n}\n\n#[cfg(all(Py_3_12, feature = \"inline_int\"))]\n#[repr(C)]\npub(crate) struct PyLongObject {\n    pub ob_base: super::PyObject,\n    pub long_value: _PyLongValue,\n}\n\n#[allow(dead_code)]\n#[cfg(all(not(Py_3_12), feature = \"inline_int\"))]\n#[repr(C)]\npub(crate) struct PyLongObject {\n    pub ob_base: super::PyVarObject,\n    pub ob_digit: u32,\n}\n\npub(crate) enum PyIntError {\n    NotType,\n    #[cfg(not(feature = \"inline_int\"))]\n    NotSigned,\n    Exceeds64Bit,\n}\n\npub(crate) enum PyIntOptConversionError {\n    InvalidRange,\n}\n\n#[allow(unused)]\n#[derive(PartialEq)]\npub(crate) enum PyIntKind {\n    U32,\n    I32,\n    U64,\n    I64,\n}\n\n#[derive(Clone)]\n#[repr(transparent)]\npub(crate) struct PyIntRef {\n    ptr: core::ptr::NonNull<PyObject>,\n}\n\nunsafe impl Send for PyIntRef {}\nunsafe impl Sync for PyIntRef {}\n\nimpl PartialEq for PyIntRef {\n    fn eq(&self, other: &Self) -> bool {\n        self.ptr == other.ptr\n    }\n}\n\nimpl PyIntRef {\n    #[inline]\n    pub fn from_ptr(ptr: *mut pyo3_ffi::PyObject) -> Result<Self, PyIntError> {\n        unsafe {\n            debug_assert!(!ptr.is_null());\n            if ob_type!(ptr) == crate::typeref::INT_TYPE {\n                Ok(Self {\n                    ptr: core::ptr::NonNull::new_unchecked(ptr),\n                })\n            } else {\n                Err(PyIntError::NotType)\n            }\n        }\n    }\n    #[inline]\n    pub unsafe fn from_ptr_unchecked(ptr: *mut PyObject) -> Self {\n        unsafe {\n            debug_assert!(!ptr.is_null());\n            debug_assert!(\n                ob_type!(ptr) == crate::typeref::INT_TYPE\n                    || is_subclass_by_flag!(tp_flags!(ob_type!(ptr)), Py_TPFLAGS_LONG_SUBCLASS)\n            );\n            Self {\n                ptr: core::ptr::NonNull::new_unchecked(ptr),\n            }\n        }\n    }\n\n    #[inline]\n    pub fn as_ptr(&self) -> *mut PyObject {\n        self.ptr.as_ptr()\n    }\n\n    #[inline]\n    pub fn as_non_null_ptr(&self) -> core::ptr::NonNull<PyObject> {\n        self.ptr\n    }\n\n    #[cfg(feature = \"inline_int\")]\n    #[inline]\n    pub fn kind(&self) -> PyIntKind {\n        match (self.is_signed(), self.fits_in_i32()) {\n            (true, true) => PyIntKind::I32,\n            (true, false) => PyIntKind::I64,\n            (false, true) => PyIntKind::U32,\n            (false, false) => PyIntKind::U64,\n        }\n    }\n\n    #[cfg(all(Py_3_12, feature = \"inline_int\"))]\n    #[inline]\n    pub fn is_signed(&self) -> bool {\n        unsafe { (*self.as_ptr().cast::<PyLongObject>()).long_value.lv_tag & SIGN_MASK != 0 }\n    }\n\n    #[cfg(all(not(Py_3_12), feature = \"inline_int\"))]\n    #[inline]\n    pub fn is_signed(&self) -> bool {\n        unsafe { (*self.as_ptr().cast::<super::PyVarObject>()).ob_size < 0 }\n    }\n\n    #[cfg(all(Py_3_12, feature = \"inline_int\"))]\n    #[inline]\n    pub fn fits_in_i32(&self) -> bool {\n        unsafe { (*self.as_ptr().cast::<PyLongObject>()).long_value.lv_tag < (2 << NON_SIZE_BITS) }\n    }\n\n    #[cfg(all(not(Py_3_12), feature = \"inline_int\"))]\n    #[inline]\n    pub fn fits_in_i32(&self) -> bool {\n        unsafe { isize::abs(super::Py_SIZE(self.as_ptr())) == 1 }\n    }\n\n    #[cfg(all(Py_3_12, feature = \"inline_int\"))]\n    #[inline]\n    fn get_inline_value(&self) -> u32 {\n        unsafe { (*self.as_ptr().cast::<PyLongObject>()).long_value.ob_digit }\n    }\n\n    #[cfg(all(not(Py_3_12), feature = \"inline_int\"))]\n    #[inline]\n    fn get_inline_value(&self) -> u32 {\n        unsafe { (*self.as_ptr().cast::<PyLongObject>()).ob_digit }\n    }\n\n    #[cfg(feature = \"inline_int\")]\n    #[inline]\n    pub unsafe fn as_u32(&self) -> u32 {\n        debug_assert!(self.kind() == PyIntKind::U32);\n        self.get_inline_value()\n    }\n\n    #[cfg(feature = \"inline_int\")]\n    #[inline]\n    pub unsafe fn as_i32(&self) -> i32 {\n        debug_assert!(self.kind() == PyIntKind::I32);\n        -(self.get_inline_value().cast_signed())\n    }\n\n    #[cfg(feature = \"inline_int\")]\n    #[inline]\n    fn get_64bit_value(&self) -> Result<[u8; 8], PyIntError> {\n        unsafe {\n            let mut buffer: [u8; 8] = [0; 8];\n            let ret = crate::ffi::PyLong_AsByteArray(\n                self.as_ptr().cast::<pyo3_ffi::PyLongObject>(),\n                buffer.as_mut_ptr().cast::<core::ffi::c_uchar>(),\n                8,\n                1,\n                i32::from(self.is_signed()),\n            );\n            if ret == -1 {\n                cold_path!();\n                #[cfg(not(Py_3_13))]\n                ffi!(PyErr_Clear());\n                Err(PyIntError::Exceeds64Bit)\n            } else {\n                Ok(buffer)\n            }\n        }\n    }\n\n    #[cfg(feature = \"inline_int\")]\n    #[inline]\n    pub unsafe fn as_i64(&self) -> Result<i64, PyIntError> {\n        debug_assert!(self.kind() == PyIntKind::I64);\n        let val = self.get_64bit_value()?;\n        #[allow(unnecessary_transmutes)]\n        unsafe {\n            Ok(core::mem::transmute::<[u8; 8], i64>(val))\n        }\n    }\n\n    #[cfg(feature = \"inline_int\")]\n    #[inline]\n    pub unsafe fn as_u64(&self) -> Result<u64, PyIntError> {\n        debug_assert!(self.kind() == PyIntKind::U64);\n        let val = self.get_64bit_value()?;\n        #[allow(unnecessary_transmutes)]\n        unsafe {\n            Ok(core::mem::transmute::<[u8; 8], u64>(val))\n        }\n    }\n\n    #[cfg(not(feature = \"inline_int\"))]\n    #[inline]\n    pub unsafe fn as_i64(&self) -> Result<i64, PyIntError> {\n        let ival = ffi!(PyLong_AsLongLong(self.as_ptr()));\n        if ival == -1 && !ffi!(PyErr_Occurred()).is_null() {\n            cold_path!();\n            ffi!(PyErr_Clear());\n            Err(PyIntError::NotSigned)\n        } else {\n            Ok(ival)\n        }\n    }\n\n    #[cfg(not(feature = \"inline_int\"))]\n    #[inline]\n    pub unsafe fn as_u64(&self) -> Result<u64, PyIntError> {\n        let uval = ffi!(PyLong_AsUnsignedLongLong(self.as_ptr()));\n        if uval == u64::MAX && !ffi!(PyErr_Occurred()).is_null() {\n            cold_path!();\n            Err(PyIntError::Exceeds64Bit)\n        } else {\n            Ok(uval)\n        }\n    }\n\n    #[cfg(feature = \"inline_int\")]\n    pub fn as_opt(&self) -> Result<Opt, PyIntOptConversionError> {\n        let val = self.get_inline_value();\n        if val == 0 {\n            Ok(val as Opt)\n        } else {\n            match self.kind() {\n                PyIntKind::U32 => {\n                    if !(0..=MAX_OPT as u32).contains(&val) {\n                        Err(PyIntOptConversionError::InvalidRange)\n                    } else {\n                        Ok(val as Opt)\n                    }\n                }\n                _ => Err(PyIntOptConversionError::InvalidRange),\n            }\n        }\n    }\n\n    #[cfg(not(feature = \"inline_int\"))]\n    pub fn as_opt(&self) -> Result<Opt, PyIntOptConversionError> {\n        match unsafe { self.as_u64() } {\n            Ok(val) => {\n                if !(0..=MAX_OPT as u64).contains(&val) {\n                    Err(PyIntOptConversionError::InvalidRange)\n                } else {\n                    Ok(val as Opt)\n                }\n            }\n            Err(_) => Err(PyIntOptConversionError::InvalidRange),\n        }\n    }\n\n    #[inline]\n    pub fn from_i64(value: i64) -> Self {\n        unsafe {\n            let ptr = PyLong_FromLongLong(value);\n            debug_assert!(!ptr.is_null());\n            Self::from_ptr_unchecked(ptr)\n        }\n    }\n\n    #[inline]\n    pub fn from_u64(value: u64) -> Self {\n        unsafe {\n            let ptr = PyLong_FromUnsignedLongLong(value);\n            debug_assert!(!ptr.is_null());\n            Self::from_ptr_unchecked(ptr)\n        }\n    }\n}\n"
  },
  {
    "path": "src/ffi/pylistref.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2026)\n\n#[derive(Clone)]\n#[repr(transparent)]\npub(crate) struct PyListRef {\n    ptr: core::ptr::NonNull<pyo3_ffi::PyObject>,\n}\n\nunsafe impl Send for PyListRef {}\nunsafe impl Sync for PyListRef {}\n\nimpl PartialEq for PyListRef {\n    fn eq(&self, other: &Self) -> bool {\n        self.ptr == other.ptr\n    }\n}\n\nimpl PyListRef {\n    #[inline]\n    pub unsafe fn from_ptr_unchecked(ptr: *mut pyo3_ffi::PyObject) -> Self {\n        unsafe {\n            debug_assert!(!ptr.is_null());\n            debug_assert!(\n                is_type!(ob_type!(ptr), crate::typeref::LIST_TYPE)\n                    || is_subclass_by_flag!(tp_flags!(ob_type!(ptr)), Py_TPFLAGS_LIST_SUBCLASS)\n            );\n            Self {\n                ptr: core::ptr::NonNull::new_unchecked(ptr),\n            }\n        }\n    }\n\n    #[inline]\n    pub fn with_capacity(cap: usize) -> Self {\n        unsafe {\n            let list = super::PyList_New(crate::util::usize_to_isize(cap));\n            debug_assert!(!list.is_null());\n            Self {\n                ptr: nonnull!(list),\n            }\n        }\n    }\n\n    #[inline]\n    #[allow(unused)]\n    pub fn as_ptr(&self) -> *mut pyo3_ffi::PyObject {\n        self.ptr.as_ptr()\n    }\n\n    #[inline]\n    #[allow(unused)]\n    pub fn as_non_null_ptr(&self) -> core::ptr::NonNull<pyo3_ffi::PyObject> {\n        self.ptr\n    }\n\n    #[cfg(CPython)]\n    #[inline]\n    pub fn data_ptr(&self) -> *const *mut pyo3_ffi::PyObject {\n        unsafe { (*self.ptr.as_ptr().cast::<pyo3_ffi::PyListObject>()).ob_item }\n    }\n\n    #[cfg(CPython)]\n    #[inline]\n    pub fn get(&mut self, i: usize) -> *mut pyo3_ffi::PyObject {\n        unsafe { *((self.data_ptr()).add(i)) }\n    }\n\n    #[cfg(not(CPython))]\n    #[inline]\n    pub fn get(&mut self, i: usize) -> *mut pyo3_ffi::PyObject {\n        unsafe { pyo3_ffi::PyList_GetItem(self.ptr.as_ptr(), crate::util::usize_to_isize(i)) }\n    }\n\n    #[cfg(CPython)]\n    #[inline]\n    pub fn set(&mut self, i: usize, val: *mut pyo3_ffi::PyObject) {\n        unsafe {\n            core::ptr::write(self.data_ptr().cast_mut().add(i), val);\n        }\n    }\n\n    #[cfg(not(CPython))]\n    pub fn set(&mut self, i: usize, val: *mut pyo3_ffi::PyObject) {\n        unsafe { pyo3_ffi::PyList_SetItem(self.ptr.as_ptr(), crate::util::usize_to_isize(i), val) };\n    }\n\n    #[inline]\n    pub fn len(&self) -> usize {\n        unsafe { crate::util::isize_to_usize(super::Py_SIZE(self.ptr.as_ptr())) }\n    }\n}\n"
  },
  {
    "path": "src/ffi/pymemoryview.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2024-2026)\n\n#[allow(clippy::enum_variant_names)]\n#[allow(unused)]\npub(crate) enum PyMemoryViewRefError {\n    NotType,\n    NotCContiguous,\n    NotSupported,\n}\n\n#[derive(Clone)]\n#[repr(transparent)]\npub(crate) struct PyMemoryViewRef {\n    ptr: core::ptr::NonNull<pyo3_ffi::PyObject>,\n}\n\nunsafe impl Send for PyMemoryViewRef {}\nunsafe impl Sync for PyMemoryViewRef {}\n\nimpl PartialEq for PyMemoryViewRef {\n    fn eq(&self, other: &Self) -> bool {\n        self.ptr == other.ptr\n    }\n}\n\nimpl PyMemoryViewRef {\n    #[cfg(CPython)]\n    #[inline]\n    pub fn from_ptr(ptr: *mut pyo3_ffi::PyObject) -> Result<Self, PyMemoryViewRefError> {\n        unsafe {\n            debug_assert!(!ptr.is_null());\n            if ob_type!(ptr) == &raw mut crate::ffi::PyMemoryView_Type {\n                let membuf = unsafe { crate::ffi::PyMemoryView_GET_BUFFER(ptr) };\n                #[allow(clippy::cast_possible_wrap)]\n                if unsafe {\n                    crate::ffi::PyBuffer_IsContiguous(membuf, b'C' as core::ffi::c_char) == 0\n                } {\n                    return Err(PyMemoryViewRefError::NotCContiguous);\n                }\n                Ok(Self {\n                    ptr: core::ptr::NonNull::new_unchecked(ptr),\n                })\n            } else {\n                Err(PyMemoryViewRefError::NotType)\n            }\n        }\n    }\n\n    #[cfg(not(CPython))]\n    #[inline]\n    pub fn from_ptr(ptr: *mut pyo3_ffi::PyObject) -> Result<Self, PyMemoryViewRefError> {\n        unsafe {\n            debug_assert!(!ptr.is_null());\n            if ob_type!(ptr) == &raw mut crate::ffi::PyMemoryView_Type {\n                Err(PyMemoryViewRefError::NotSupported)\n            } else {\n                Err(PyMemoryViewRefError::NotType)\n            }\n        }\n    }\n\n    #[allow(unused)]\n    #[inline]\n    pub fn as_ptr(&self) -> *mut pyo3_ffi::PyObject {\n        self.ptr.as_ptr()\n    }\n\n    #[allow(unused)]\n    #[inline]\n    pub fn as_non_null_ptr(&self) -> core::ptr::NonNull<pyo3_ffi::PyObject> {\n        self.ptr\n    }\n\n    #[cfg(CPython)]\n    #[inline]\n    pub fn as_bytes(&self) -> &'static [u8] {\n        unsafe {\n            let membuf = crate::ffi::PyMemoryView_GET_BUFFER(self.as_ptr());\n            core::slice::from_raw_parts(\n                (*membuf).buf.cast::<u8>().cast_const(),\n                crate::util::isize_to_usize((*membuf).len),\n            )\n        }\n    }\n\n    #[cfg(CPython)]\n    #[inline]\n    pub fn as_str(&self) -> Option<&'static str> {\n        let buffer = self.as_bytes();\n        if !crate::ffi::utf8::is_valid_utf8(buffer) {\n            cold_path!();\n            None\n        } else {\n            unsafe { Some(core::str::from_utf8_unchecked(buffer)) }\n        }\n    }\n\n    #[cfg(not(CPython))]\n    #[inline]\n    pub fn as_str(&self) -> Option<&'static str> {\n        None\n    }\n}\n"
  },
  {
    "path": "src/ffi/pynoneref.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2026)\n\n#[derive(Clone)]\n#[repr(transparent)]\npub(crate) struct PyNoneRef {\n    ptr: core::ptr::NonNull<pyo3_ffi::PyObject>,\n}\n\nunsafe impl Send for PyNoneRef {}\nunsafe impl Sync for PyNoneRef {}\n\nimpl PartialEq for PyNoneRef {\n    fn eq(&self, other: &Self) -> bool {\n        self.ptr == other.ptr\n    }\n}\n\nimpl PyNoneRef {\n    #[inline]\n    #[allow(unused)]\n    pub(crate) unsafe fn from_ptr_unchecked(ptr: *mut pyo3_ffi::PyObject) -> Self {\n        unsafe {\n            debug_assert!(!ptr.is_null());\n            debug_assert!(ob_type!(ptr) == crate::typeref::NONE_TYPE);\n            Self {\n                ptr: core::ptr::NonNull::new_unchecked(ptr),\n            }\n        }\n    }\n\n    #[inline]\n    #[allow(unused)]\n    pub fn as_ptr(&self) -> *mut pyo3_ffi::PyObject {\n        self.ptr.as_ptr()\n    }\n\n    #[inline]\n    #[allow(unused)]\n    pub fn as_non_null_ptr(&self) -> core::ptr::NonNull<pyo3_ffi::PyObject> {\n        self.ptr\n    }\n\n    #[inline]\n    pub fn none() -> Self {\n        Self {\n            ptr: unsafe { core::ptr::NonNull::new_unchecked(use_immortal!(crate::typeref::NONE)) },\n        }\n    }\n}\n"
  },
  {
    "path": "src/ffi/pystrref/avx512.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2024-2026)\n\nuse super::pyunicode_new::*;\n\nuse core::arch::x86_64::{\n    _mm512_and_si512, _mm512_cmpgt_epu8_mask, _mm512_cmpneq_epi8_mask, _mm512_loadu_epi8,\n    _mm512_mask_cmpneq_epi8_mask, _mm512_maskz_loadu_epi8, _mm512_max_epu8, _mm512_set1_epi8,\n};\n\n#[inline(never)]\n#[target_feature(enable = \"avx512f,avx512bw,avx512vl,bmi2\")]\npub(crate) unsafe fn create_str_impl_avx512vl(buf: &str) -> *mut crate::ffi::PyObject {\n    unsafe {\n        const STRIDE: usize = 64;\n\n        let buf_ptr = buf.as_bytes().as_ptr().cast::<i8>();\n        let buf_len = buf.len();\n\n        assume!(buf_len > 0);\n\n        let num_loops = buf_len / STRIDE;\n        let remainder = buf_len % STRIDE;\n\n        let remainder_mask: u64 = !(u64::MAX << remainder);\n        let mut str_vec = _mm512_maskz_loadu_epi8(remainder_mask, buf_ptr);\n        let sptr = buf_ptr.add(remainder);\n\n        for i in 0..num_loops {\n            str_vec = _mm512_max_epu8(\n                str_vec,\n                _mm512_loadu_epi8(sptr.add(STRIDE * i).cast::<i8>()),\n            );\n        }\n\n        #[allow(overflowing_literals)]\n        let vec_128 = _mm512_set1_epi8(0b10000000i8);\n        if _mm512_cmpgt_epu8_mask(str_vec, vec_128) == 0 {\n            pyunicode_ascii(buf.as_bytes().as_ptr(), buf_len)\n        } else {\n            #[allow(overflowing_literals)]\n            let is_four = _mm512_cmpgt_epu8_mask(str_vec, _mm512_set1_epi8(239i8)) != 0;\n            #[allow(overflowing_literals)]\n            let is_not_latin = _mm512_cmpgt_epu8_mask(str_vec, _mm512_set1_epi8(195i8)) != 0;\n            #[allow(overflowing_literals)]\n            let multibyte = _mm512_set1_epi8(0b11000000i8);\n\n            let mut num_chars = _mm512_mask_cmpneq_epi8_mask(\n                remainder_mask,\n                _mm512_and_si512(_mm512_maskz_loadu_epi8(remainder_mask, buf_ptr), multibyte),\n                vec_128,\n            )\n            .count_ones() as usize;\n\n            for i in 0..num_loops {\n                num_chars += _mm512_cmpneq_epi8_mask(\n                    _mm512_and_si512(\n                        _mm512_loadu_epi8(sptr.add(STRIDE * i).cast::<i8>()),\n                        multibyte,\n                    ),\n                    vec_128,\n                )\n                .count_ones() as usize;\n            }\n\n            if is_four {\n                pyunicode_fourbyte(buf, num_chars)\n            } else if is_not_latin {\n                pyunicode_twobyte(buf, num_chars)\n            } else {\n                pyunicode_onebyte(buf, num_chars)\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/ffi/pystrref/mod.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2026)\n\n#[cfg(feature = \"avx512\")]\n#[cfg(CPython)]\nmod avx512;\nmod object;\n#[cfg(CPython)]\nmod pyunicode_new;\n#[cfg(CPython)]\nmod scalar;\n\npub(crate) use object::{PyStrRef, PyStrSubclassRef, set_str_create_fn};\n"
  },
  {
    "path": "src/ffi/pystrref/object.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2025-2026)\n\n#[allow(unused)]\nuse crate::ffi::{Py_HashBuffer, Py_ssize_t, PyASCIIObject, PyCompactUnicodeObject, PyObject};\n#[cfg(all(CPython, not(feature = \"inline_str\")))]\nuse crate::ffi::{PyUnicode_DATA, PyUnicode_KIND};\nuse crate::typeref::{EMPTY_UNICODE, STR_TYPE};\nuse core::ptr::NonNull;\n\nfn to_str_via_ffi(op: *mut PyObject) -> Option<&'static str> {\n    let mut str_size: Py_ssize_t = 0;\n    let ptr = ffi!(PyUnicode_AsUTF8AndSize(op, &raw mut str_size)).cast::<u8>();\n    if ptr.is_null() {\n        cold_path!();\n        None\n    } else {\n        #[allow(clippy::cast_sign_loss)]\n        let str_usize = str_size as usize;\n        Some(str_from_slice!(ptr, str_usize))\n    }\n}\n\n#[cfg(all(CPython, feature = \"avx512\"))]\npub type StrDeserializer = unsafe fn(&str) -> *mut PyObject;\n\n#[cfg(all(CPython, feature = \"avx512\"))]\nstatic mut STR_CREATE_FN: StrDeserializer = super::scalar::str_impl_kind_scalar;\n\npub fn set_str_create_fn() {\n    unsafe {\n        #[cfg(all(CPython, feature = \"avx512\"))]\n        if std::is_x86_feature_detected!(\"avx512vl\") {\n            STR_CREATE_FN = super::avx512::create_str_impl_avx512vl;\n        }\n    }\n}\n\n#[cfg(all(feature = \"inline_str\", Py_3_14, Py_GIL_DISABLED))]\nconst STATE_KIND_SHIFT: usize = 8;\n\n#[cfg(all(feature = \"inline_str\", not(all(Py_3_14, Py_GIL_DISABLED))))]\nconst STATE_KIND_SHIFT: usize = 2;\n\n#[cfg(feature = \"inline_str\")]\nconst STATE_KIND_MASK: u32 = 7 << STATE_KIND_SHIFT;\n\n#[cfg(feature = \"inline_str\")]\nconst STATE_COMPACT_ASCII: u32 =\n    1 << STATE_KIND_SHIFT | 1 << (STATE_KIND_SHIFT + 3) | 1 << (STATE_KIND_SHIFT + 4);\n\npub(crate) enum PyStrRefError {\n    NotStrType,\n}\n\n#[derive(Clone)]\n#[repr(transparent)]\npub(crate) struct PyStrRef {\n    ptr: core::ptr::NonNull<pyo3_ffi::PyObject>,\n}\n\nunsafe impl Send for PyStrRef {}\nunsafe impl Sync for PyStrRef {}\n\nimpl PartialEq for PyStrRef {\n    fn eq(&self, other: &Self) -> bool {\n        self.ptr == other.ptr\n    }\n}\n\nimpl PyStrRef {\n    #[inline]\n    pub fn from_ptr(ptr: *mut pyo3_ffi::PyObject) -> Result<Self, PyStrRefError> {\n        unsafe {\n            debug_assert!(!ptr.is_null());\n            if ob_type!(ptr) == crate::typeref::STR_TYPE {\n                Ok(Self {\n                    ptr: core::ptr::NonNull::new_unchecked(ptr),\n                })\n            } else {\n                cold_path!();\n                Err(PyStrRefError::NotStrType)\n            }\n        }\n    }\n\n    #[inline]\n    pub unsafe fn from_ptr_unchecked(ptr: *mut pyo3_ffi::PyObject) -> Self {\n        unsafe {\n            debug_assert!(!ptr.is_null());\n            debug_assert!(ob_type!(ptr) == crate::typeref::STR_TYPE);\n            Self {\n                ptr: core::ptr::NonNull::new_unchecked(ptr),\n            }\n        }\n    }\n\n    #[inline]\n    pub fn empty() -> Self {\n        unsafe {\n            Self {\n                ptr: nonnull!(use_immortal!(EMPTY_UNICODE)),\n            }\n        }\n    }\n\n    #[inline]\n    pub fn as_ptr(&self) -> *mut pyo3_ffi::PyObject {\n        self.ptr.as_ptr()\n    }\n\n    pub fn as_non_null_ptr(&self) -> NonNull<PyObject> {\n        nonnull!(self.as_ptr())\n    }\n\n    #[cfg(CPython)]\n    #[inline(always)]\n    pub fn from_str_with_hash(buf: &str) -> Self {\n        let mut obj = PyStrRef::from_str(buf);\n        obj.set_hash();\n        obj\n    }\n\n    #[cfg(CPython)]\n    #[inline(always)]\n    pub fn from_str(buf: &str) -> Self {\n        if buf.is_empty() {\n            cold_path!();\n            return Self::empty();\n        }\n        #[cfg(not(feature = \"avx512\"))]\n        let str_ptr = unsafe { super::scalar::str_impl_kind_scalar(buf) };\n        #[cfg(feature = \"avx512\")]\n        let str_ptr = unsafe { STR_CREATE_FN(buf) };\n        debug_assert!(!str_ptr.is_null());\n        Self {\n            ptr: nonnull!(str_ptr),\n        }\n    }\n\n    #[cfg(not(CPython))]\n    #[inline(always)]\n    pub fn from_str(buf: &str) -> Self {\n        if buf.is_empty() {\n            cold_path!();\n            return Self::empty();\n        }\n        let str_ptr = unsafe {\n            crate::ffi::PyUnicode_FromStringAndSize(\n                buf.as_ptr().cast::<core::ffi::c_char>(),\n                crate::util::usize_to_isize(buf.len()),\n            )\n        };\n        debug_assert!(!str_ptr.is_null());\n        Self {\n            ptr: nonnull!(str_ptr),\n        }\n    }\n\n    #[cfg(CPython)]\n    #[allow(unused)]\n    pub fn hash(&self) -> crate::ffi::Py_hash_t {\n        unsafe {\n            debug_assert!((*self.as_ptr().cast::<PyASCIIObject>()).hash != -1);\n            (*self.as_ptr().cast::<PyASCIIObject>()).hash\n        }\n    }\n\n    #[cfg(feature = \"inline_str\")]\n    fn set_hash(&mut self) {\n        unsafe {\n            let ptr = self.as_ptr().cast::<PyASCIIObject>();\n            let data_ptr: *mut core::ffi::c_void =\n                if (*ptr).state & STATE_COMPACT_ASCII == STATE_COMPACT_ASCII {\n                    ptr.offset(1).cast::<core::ffi::c_void>()\n                } else {\n                    ptr.cast::<PyCompactUnicodeObject>()\n                        .offset(1)\n                        .cast::<core::ffi::c_void>()\n                };\n            #[allow(clippy::cast_possible_wrap)]\n            let num_bytes =\n                (*ptr).length * (((*ptr).state & STATE_KIND_MASK) >> STATE_KIND_SHIFT) as isize;\n            let hash = Py_HashBuffer(data_ptr, num_bytes);\n            (*ptr).hash = hash;\n            debug_assert!((*ptr).hash != -1);\n        }\n    }\n\n    #[cfg(not(feature = \"inline_str\"))]\n    fn set_hash(&mut self) {\n        unsafe {\n            let data_ptr = PyUnicode_DATA(self.as_ptr());\n            #[allow(clippy::cast_possible_wrap)]\n            let num_bytes = PyUnicode_KIND(self.as_ptr()) as isize * ffi!(Py_SIZE(self.as_ptr()));\n            let hash = Py_HashBuffer(data_ptr, num_bytes);\n            (*self.as_ptr().cast::<PyASCIIObject>()).hash = hash;\n            debug_assert!(self.hash() != -1);\n        }\n    }\n\n    #[inline(always)]\n    #[cfg(feature = \"inline_str\")]\n    pub fn as_str(&self) -> Option<&'static str> {\n        unsafe {\n            let op = self.as_ptr();\n            if (*op.cast::<PyASCIIObject>()).state & STATE_COMPACT_ASCII == STATE_COMPACT_ASCII {\n                let ptr = op.cast::<PyASCIIObject>().offset(1).cast::<u8>();\n                let len = crate::util::isize_to_usize((*op.cast::<PyASCIIObject>()).length);\n                Some(str_from_slice!(ptr, len))\n            } else if (*op.cast::<PyASCIIObject>()).state & STATE_COMPACT_ASCII == 0 {\n                cold_path!();\n                to_str_via_ffi(op)\n            } else if (*op.cast::<PyCompactUnicodeObject>()).utf8_length != 0 {\n                let ptr = ((*op.cast::<PyCompactUnicodeObject>()).utf8).cast::<u8>();\n                let len =\n                    crate::util::isize_to_usize((*op.cast::<PyCompactUnicodeObject>()).utf8_length);\n                Some(str_from_slice!(ptr, len))\n            } else {\n                to_str_via_ffi(op)\n            }\n        }\n    }\n\n    #[inline(always)]\n    #[cfg(not(feature = \"inline_str\"))]\n    pub fn as_str(&self) -> Option<&'static str> {\n        to_str_via_ffi(self.as_ptr())\n    }\n}\n\n#[repr(transparent)]\npub(crate) struct PyStrSubclassRef {\n    ptr: NonNull<PyObject>,\n}\n\nimpl PyStrSubclassRef {\n    pub unsafe fn from_ptr_unchecked(ptr: *mut PyObject) -> PyStrSubclassRef {\n        let ob_type = ob_type!(ptr);\n        let tp_flags = tp_flags!(ob_type);\n        debug_assert!(!ptr.is_null());\n        debug_assert!(!is_class_by_type!(ob_type, STR_TYPE));\n        debug_assert!(is_subclass_by_flag!(tp_flags, Py_TPFLAGS_UNICODE_SUBCLASS));\n        PyStrSubclassRef { ptr: nonnull!(ptr) }\n    }\n\n    #[inline]\n    pub fn as_ptr(&self) -> *mut pyo3_ffi::PyObject {\n        self.ptr.as_ptr()\n    }\n\n    #[inline(always)]\n    pub fn as_str(&self) -> Option<&'static str> {\n        to_str_via_ffi(self.as_ptr())\n    }\n}\n"
  },
  {
    "path": "src/ffi/pystrref/pyunicode_new.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2023-2026)\n\nuse crate::ffi::{PyASCIIObject, PyCompactUnicodeObject, PyObject, PyUnicode_New};\nuse crate::util::usize_to_isize;\n\nmacro_rules! validate_str {\n    ($ptr:expr) => {\n        #[cfg(CPython)]\n        unsafe {\n            debug_assert!(pyo3_ffi::_PyUnicode_CheckConsistency($ptr.cast::<PyObject>(), 1) == 1)\n        };\n    };\n}\n\n#[inline(never)]\npub(crate) fn pyunicode_ascii(buf: *const u8, num_chars: usize) -> *mut PyObject {\n    unsafe {\n        let ptr = PyUnicode_New(usize_to_isize(num_chars), 127);\n        let data_ptr = ptr.cast::<PyASCIIObject>().offset(1).cast::<u8>();\n        core::ptr::copy_nonoverlapping(buf, data_ptr, num_chars);\n        core::ptr::write(data_ptr.add(num_chars), 0);\n        validate_str!(ptr);\n        ptr.cast::<PyObject>()\n    }\n}\n\n#[cold]\n#[inline(never)]\npub(crate) fn pyunicode_onebyte(buf: &str, num_chars: usize) -> *mut PyObject {\n    unsafe {\n        let ptr = PyUnicode_New(usize_to_isize(num_chars), 255);\n        let mut data_ptr = ptr.cast::<PyCompactUnicodeObject>().offset(1).cast::<u8>();\n        for each in buf.chars().fuse() {\n            core::ptr::write(data_ptr, each as u8);\n            data_ptr = data_ptr.offset(1);\n        }\n        core::ptr::write(data_ptr, 0);\n        validate_str!(ptr);\n        ptr.cast::<PyObject>()\n    }\n}\n\n#[inline(never)]\npub(crate) fn pyunicode_twobyte(buf: &str, num_chars: usize) -> *mut PyObject {\n    unsafe {\n        let ptr = PyUnicode_New(usize_to_isize(num_chars), 65535);\n        let mut data_ptr = ptr.cast::<PyCompactUnicodeObject>().offset(1).cast::<u16>();\n        for each in buf.chars().fuse() {\n            core::ptr::write(data_ptr, each as u16);\n            data_ptr = data_ptr.offset(1);\n        }\n        core::ptr::write(data_ptr, 0);\n        validate_str!(ptr);\n        ptr.cast::<PyObject>()\n    }\n}\n\n#[inline(never)]\npub(crate) fn pyunicode_fourbyte(buf: &str, num_chars: usize) -> *mut PyObject {\n    unsafe {\n        let ptr = PyUnicode_New(usize_to_isize(num_chars), 1114111);\n        let mut data_ptr = ptr.cast::<PyCompactUnicodeObject>().offset(1).cast::<u32>();\n        for each in buf.chars().fuse() {\n            core::ptr::write(data_ptr, each as u32);\n            data_ptr = data_ptr.offset(1);\n        }\n        core::ptr::write(data_ptr, 0);\n        validate_str!(ptr);\n        ptr.cast::<PyObject>()\n    }\n}\n"
  },
  {
    "path": "src/ffi/pystrref/scalar.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2024-2026)\n\nuse super::pyunicode_new::{\n    pyunicode_ascii, pyunicode_fourbyte, pyunicode_onebyte, pyunicode_twobyte,\n};\n\n#[inline(never)]\npub(crate) unsafe fn str_impl_kind_scalar(buf: &str) -> *mut crate::ffi::PyObject {\n    let num_chars = bytecount::num_chars(buf.as_bytes());\n    if buf.len() == num_chars {\n        return pyunicode_ascii(buf.as_ptr(), num_chars);\n    }\n    unsafe {\n        let len = buf.len();\n        assume!(len > 0);\n\n        if *(buf.as_bytes().as_ptr()) > 239 {\n            cold_path!();\n            return pyunicode_fourbyte(buf, num_chars);\n        }\n\n        let sptr = buf.as_bytes().as_ptr();\n\n        let mut is_four = false;\n        let mut not_latin = false;\n        for i in 0..len {\n            is_four |= *sptr.add(i) > 239;\n            not_latin |= *sptr.add(i) > 195;\n        }\n        if is_four {\n            pyunicode_fourbyte(buf, num_chars)\n        } else if not_latin {\n            pyunicode_twobyte(buf, num_chars)\n        } else {\n            pyunicode_onebyte(buf, num_chars)\n        }\n    }\n}\n"
  },
  {
    "path": "src/ffi/pytupleref.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2026)\n\n#[derive(Clone)]\n#[repr(transparent)]\npub(crate) struct PyTupleRef {\n    ptr: core::ptr::NonNull<pyo3_ffi::PyObject>,\n}\n\nunsafe impl Send for PyTupleRef {}\nunsafe impl Sync for PyTupleRef {}\n\nimpl PartialEq for PyTupleRef {\n    fn eq(&self, other: &Self) -> bool {\n        self.ptr == other.ptr\n    }\n}\n\nimpl PyTupleRef {\n    #[inline]\n    pub fn with_capacity(cap: usize) -> Self {\n        unsafe {\n            let ptr = crate::ffi::PyTuple_New(crate::util::usize_to_isize(cap));\n            debug_assert!(!ptr.is_null());\n            Self { ptr: nonnull!(ptr) }\n        }\n    }\n\n    #[inline]\n    pub unsafe fn from_ptr_unchecked(ptr: *mut pyo3_ffi::PyObject) -> Self {\n        unsafe {\n            debug_assert!(!ptr.is_null());\n            debug_assert!(\n                is_type!(ob_type!(ptr), crate::typeref::TUPLE_TYPE)\n                    || is_subclass_by_flag!(tp_flags!(ob_type!(ptr)), Py_TPFLAGS_TUPLE_SUBCLASS)\n            );\n            Self {\n                ptr: core::ptr::NonNull::new_unchecked(ptr),\n            }\n        }\n    }\n\n    #[inline]\n    #[allow(unused)]\n    pub fn as_ptr(&self) -> *mut pyo3_ffi::PyObject {\n        self.ptr.as_ptr()\n    }\n\n    #[inline]\n    #[allow(unused)]\n    pub fn as_non_null_ptr(&self) -> core::ptr::NonNull<pyo3_ffi::PyObject> {\n        self.ptr\n    }\n\n    pub fn get(&self, i: usize) -> *mut pyo3_ffi::PyObject {\n        unsafe { crate::ffi::PyTuple_GET_ITEM(self.ptr.as_ptr(), crate::util::usize_to_isize(i)) }\n    }\n\n    #[inline]\n    pub fn set(&mut self, i: usize, val: *mut pyo3_ffi::PyObject) {\n        unsafe {\n            crate::ffi::PyTuple_SET_ITEM(self.as_ptr(), crate::util::usize_to_isize(i), val);\n        }\n    }\n\n    #[inline]\n    pub fn len(&self) -> usize {\n        unsafe { crate::util::isize_to_usize(super::Py_SIZE(self.ptr.as_ptr())) }\n    }\n}\n"
  },
  {
    "path": "src/ffi/pyuuidref.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2026)\n\nuse core::ffi::c_uchar;\n\n#[derive(Clone)]\n#[repr(transparent)]\npub(crate) struct PyUuidRef {\n    ptr: core::ptr::NonNull<pyo3_ffi::PyObject>,\n}\n\nunsafe impl Send for PyUuidRef {}\nunsafe impl Sync for PyUuidRef {}\n\nimpl PartialEq for PyUuidRef {\n    fn eq(&self, other: &Self) -> bool {\n        self.ptr == other.ptr\n    }\n}\n\nimpl PyUuidRef {\n    #[inline]\n    pub(crate) unsafe fn from_ptr_unchecked(ptr: *mut pyo3_ffi::PyObject) -> Self {\n        unsafe {\n            debug_assert!(!ptr.is_null());\n            debug_assert!(ob_type!(ptr) == crate::typeref::UUID_TYPE);\n            Self {\n                ptr: core::ptr::NonNull::new_unchecked(ptr),\n            }\n        }\n    }\n\n    #[inline(never)]\n    pub(crate) fn value(&self) -> u128 {\n        unsafe {\n            {\n                // test_uuid_immutable, test_uuid_int\n                let py_int =\n                    crate::ffi::PyObject_GetAttr(self.ptr.as_ptr(), crate::typeref::INT_ATTR_STR);\n                ffi!(Py_DECREF(py_int));\n                let mut buffer: [c_uchar; 16] = [0; 16];\n                unsafe {\n                    // test_uuid_overflow\n                    crate::ffi::PyLong_AsByteArray(\n                        py_int.cast::<crate::ffi::PyLongObject>(),\n                        buffer.as_mut_ptr(),\n                        16,\n                        1, // little_endian\n                        0, // is_signed\n                    );\n                };\n                u128::from_le_bytes(buffer)\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/ffi/utf8.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2021-2026)\n\n#[cfg(all(target_arch = \"x86_64\", not(target_feature = \"avx2\")))]\npub(crate) fn is_valid_utf8(buf: &[u8]) -> bool {\n    if std::is_x86_feature_detected!(\"avx2\") {\n        unsafe { simdutf8::basic::imp::x86::avx2::validate_utf8(buf).is_ok() }\n    } else {\n        encoding_rs::Encoding::utf8_valid_up_to(buf) == buf.len()\n    }\n}\n\n#[cfg(all(target_arch = \"x86_64\", target_feature = \"avx2\"))]\npub(crate) fn is_valid_utf8(buf: &[u8]) -> bool {\n    simdutf8::basic::from_utf8(buf).is_ok()\n}\n\n#[cfg(target_arch = \"aarch64\")]\npub(crate) fn is_valid_utf8(buf: &[u8]) -> bool {\n    unsafe { simdutf8::basic::imp::aarch64::neon::validate_utf8(buf).is_ok() }\n}\n\n#[cfg(not(any(target_arch = \"x86_64\", target_arch = \"aarch64\")))]\npub(crate) fn is_valid_utf8(buf: &[u8]) -> bool {\n    std::str::from_utf8(buf).is_ok()\n}\n"
  },
  {
    "path": "src/lib.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2018-2026)\n\n#![cfg_attr(feature = \"optimize\", feature(optimize_attribute))]\n#![cfg_attr(feature = \"generic_simd\", feature(portable_simd))]\n#![cfg_attr(feature = \"cold_path\", feature(cold_path))]\n#![allow(non_camel_case_types)]\n#![allow(static_mut_refs)]\n#![allow(unused_unsafe)]\n#![warn(clippy::correctness)]\n#![warn(clippy::suspicious)]\n#![warn(clippy::complexity)]\n#![warn(clippy::perf)]\n#![warn(clippy::style)]\n#![allow(clippy::inline_always)]\n#![allow(clippy::explicit_iter_loop)]\n#![allow(clippy::redundant_field_names)]\n#![allow(clippy::upper_case_acronyms)]\n#![allow(clippy::zero_prefixed_literal)]\n#![warn(clippy::borrow_as_ptr)]\n#![warn(clippy::cast_possible_wrap)]\n#![warn(clippy::cast_ptr_alignment)]\n#![warn(clippy::cast_sign_loss)]\n#![warn(clippy::elidable_lifetime_names)]\n#![warn(clippy::ptr_arg)]\n#![warn(clippy::ptr_as_ptr)]\n#![warn(clippy::ptr_cast_constness)]\n#![warn(clippy::ptr_eq)]\n#![warn(clippy::redundant_allocation)]\n#![warn(clippy::redundant_clone)]\n#![warn(clippy::redundant_locals)]\n#![warn(clippy::redundant_slicing)]\n#![warn(clippy::semicolon_inside_block)]\n#![warn(clippy::size_of_ref)]\n#![warn(clippy::std_instead_of_core)]\n#![warn(clippy::trivially_copy_pass_by_ref)]\n#![warn(clippy::unnecessary_semicolon)]\n#![warn(clippy::unnecessary_wraps)]\n#![warn(clippy::zero_ptr)]\n\n#[cfg(feature = \"unwind\")]\nextern crate unwinding;\n\n#[macro_use]\nmod util;\n\nmod alloc;\nmod deserialize;\nmod exception;\nmod ffi;\nmod opt;\nmod serialize;\nmod typeref;\n\nuse core::ffi::{c_char, c_int, c_void};\nuse core::ptr::{NonNull, null, null_mut};\n\nuse crate::deserialize::deserialize;\nuse crate::exception::{\n    raise_dumps_exception_dynamic, raise_dumps_exception_fixed, raise_loads_exception,\n};\nuse crate::ffi::{\n    METH_KEYWORDS, METH_O, Py_SIZE, Py_ssize_t, PyCFunction_NewEx, PyIntRef, PyMethodDef,\n    PyMethodDefPointer, PyModuleDef, PyModuleDef_HEAD_INIT, PyModuleDef_Slot, PyNoneRef, PyObject,\n    PyTupleRef, PyUnicode_FromStringAndSize, PyUnicode_InternFromString, PyVectorcall_NARGS,\n};\nuse crate::serialize::serialize;\nuse crate::util::{isize_to_usize, usize_to_isize};\n\n#[cfg(Py_3_13)]\nmacro_rules! add {\n    ($mptr:expr, $name:expr, $obj:expr) => {\n        crate::ffi::PyModule_Add($mptr, $name.as_ptr(), $obj);\n    };\n}\n\n#[cfg(not(Py_3_13))]\nmacro_rules! add {\n    ($mptr:expr, $name:expr, $obj:expr) => {\n        crate::ffi::PyModule_AddObjectRef($mptr, $name.as_ptr(), $obj);\n    };\n}\n\nmacro_rules! opt {\n    ($mptr:expr, $name:expr, $opt:expr) => {\n        #[cfg(all(not(target_os = \"windows\"), target_pointer_width = \"64\"))]\n        crate::ffi::PyModule_AddIntConstant($mptr, $name.as_ptr(), i64::from($opt));\n        #[cfg(all(not(target_os = \"windows\"), target_pointer_width = \"32\"))]\n        crate::ffi::PyModule_AddIntConstant($mptr, $name.as_ptr(), $opt as i32);\n        #[cfg(target_os = \"windows\")]\n        crate::ffi::PyModule_AddIntConstant($mptr, $name.as_ptr(), $opt as i32);\n    };\n}\n\n#[allow(non_snake_case)]\n#[unsafe(no_mangle)]\n#[cold]\n#[cfg_attr(feature = \"optimize\", optimize(size))]\npub(crate) unsafe extern \"C\" fn orjson_init_exec(mptr: *mut PyObject) -> c_int {\n    unsafe {\n        typeref::init_typerefs();\n\n        {\n            let version = env!(\"CARGO_PKG_VERSION\");\n            let pyversion = PyUnicode_FromStringAndSize(\n                version.as_ptr().cast::<c_char>(),\n                usize_to_isize(version.len()),\n            );\n            add!(mptr, c\"__version__\", pyversion);\n        }\n\n        {\n            let dumps_doc = c\"dumps(obj, /, default=None, option=None)\\n--\\n\\nSerialize Python objects to JSON.\";\n\n            let wrapped_dumps = Box::new(PyMethodDef {\n                ml_name: c\"dumps\".as_ptr(),\n                ml_meth: PyMethodDefPointer {\n                    PyCFunctionFastWithKeywords: dumps,\n                },\n                ml_flags: crate::ffi::METH_FASTCALL | METH_KEYWORDS,\n                ml_doc: dumps_doc.as_ptr(),\n            });\n\n            let func = PyCFunction_NewEx(\n                Box::into_raw(wrapped_dumps),\n                null_mut(),\n                PyUnicode_InternFromString(c\"orjson\".as_ptr()),\n            );\n            add!(mptr, c\"dumps\", func);\n        }\n\n        {\n            let loads_doc = c\"loads(obj, /)\\n--\\n\\nDeserialize JSON to Python objects.\";\n\n            let wrapped_loads = Box::new(PyMethodDef {\n                ml_name: c\"loads\".as_ptr(),\n                ml_meth: PyMethodDefPointer { PyCFunction: loads },\n                ml_flags: METH_O,\n                ml_doc: loads_doc.as_ptr(),\n            });\n            let func = PyCFunction_NewEx(\n                Box::into_raw(wrapped_loads),\n                null_mut(),\n                PyUnicode_InternFromString(c\"orjson\".as_ptr()),\n            );\n            add!(mptr, c\"loads\", func);\n        }\n\n        add!(mptr, c\"Fragment\", typeref::FRAGMENT_TYPE.cast::<PyObject>());\n\n        opt!(mptr, c\"OPT_APPEND_NEWLINE\", opt::APPEND_NEWLINE);\n        opt!(mptr, c\"OPT_INDENT_2\", opt::INDENT_2);\n        opt!(mptr, c\"OPT_NAIVE_UTC\", opt::NAIVE_UTC);\n        opt!(mptr, c\"OPT_NON_STR_KEYS\", opt::NON_STR_KEYS);\n        opt!(mptr, c\"OPT_OMIT_MICROSECONDS\", opt::OMIT_MICROSECONDS);\n        opt!(\n            mptr,\n            c\"OPT_PASSTHROUGH_DATACLASS\",\n            opt::PASSTHROUGH_DATACLASS\n        );\n        opt!(mptr, c\"OPT_PASSTHROUGH_DATETIME\", opt::PASSTHROUGH_DATETIME);\n        opt!(mptr, c\"OPT_PASSTHROUGH_SUBCLASS\", opt::PASSTHROUGH_SUBCLASS);\n        opt!(mptr, c\"OPT_SERIALIZE_DATACLASS\", opt::SERIALIZE_DATACLASS);\n        opt!(mptr, c\"OPT_SERIALIZE_NUMPY\", opt::SERIALIZE_NUMPY);\n        opt!(mptr, c\"OPT_SERIALIZE_UUID\", opt::SERIALIZE_UUID);\n        opt!(mptr, c\"OPT_SORT_KEYS\", opt::SORT_KEYS);\n        opt!(mptr, c\"OPT_STRICT_INTEGER\", opt::STRICT_INTEGER);\n        opt!(mptr, c\"OPT_UTC_Z\", opt::UTC_Z);\n\n        add!(mptr, c\"JSONDecodeError\", typeref::JsonDecodeError);\n        add!(mptr, c\"JSONEncodeError\", typeref::JsonEncodeError);\n\n        0\n    }\n}\n\n#[allow(non_snake_case)]\n#[unsafe(no_mangle)]\n#[cold]\n#[cfg_attr(feature = \"optimize\", optimize(size))]\npub(crate) unsafe extern \"C\" fn PyInit_orjson() -> *mut PyModuleDef {\n    #[cfg(not(Py_3_12))]\n    const PYMODULEDEF_LEN: usize = 2;\n    #[cfg(all(Py_3_12, not(Py_3_13)))]\n    const PYMODULEDEF_LEN: usize = 3;\n    #[cfg(Py_3_13)]\n    const PYMODULEDEF_LEN: usize = 4;\n    unsafe {\n        let mod_slots: Box<[PyModuleDef_Slot; PYMODULEDEF_LEN]> = Box::new([\n            PyModuleDef_Slot {\n                slot: crate::ffi::Py_mod_exec,\n                #[allow(clippy::fn_to_numeric_cast_any, clippy::as_conversions)]\n                value: orjson_init_exec as *mut c_void,\n            },\n            #[cfg(Py_3_12)]\n            PyModuleDef_Slot {\n                slot: crate::ffi::Py_mod_multiple_interpreters,\n                value: crate::ffi::Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED,\n            },\n            #[cfg(Py_3_13)]\n            PyModuleDef_Slot {\n                slot: crate::ffi::Py_mod_gil,\n                value: crate::ffi::Py_MOD_GIL_USED,\n            },\n            PyModuleDef_Slot {\n                slot: 0,\n                value: null_mut(),\n            },\n        ]);\n\n        let init = Box::new(PyModuleDef {\n            m_base: PyModuleDef_HEAD_INIT,\n            m_name: c\"orjson\".as_ptr(),\n            m_doc: null(),\n            m_size: 0,\n            m_methods: null_mut(),\n            m_slots: Box::into_raw(mod_slots).cast::<PyModuleDef_Slot>(),\n            m_traverse: None,\n            m_clear: None,\n            m_free: None,\n        });\n        let init_ptr = Box::into_raw(init);\n        ffi!(PyModuleDef_Init(init_ptr));\n        init_ptr\n    }\n}\n\n#[unsafe(no_mangle)]\npub(crate) unsafe extern \"C\" fn loads(_self: *mut PyObject, obj: *mut PyObject) -> *mut PyObject {\n    deserialize(obj).map_or_else(raise_loads_exception, NonNull::as_ptr)\n}\n\n#[cfg(CPython)]\nmacro_rules! matches_kwarg {\n    ($val:expr, $ref:expr) => {\n        unsafe { core::ptr::eq($val, $ref) }\n    };\n}\n\n#[cfg(not(CPython))]\nmacro_rules! matches_kwarg {\n    ($val:expr, $ref:expr) => {\n        unsafe { crate::ffi::PyObject_Hash($val) == crate::ffi::PyObject_Hash($ref) }\n    };\n}\n\n#[unsafe(no_mangle)]\npub(crate) unsafe extern \"C\" fn dumps(\n    _self: *mut PyObject,\n    args: *const *mut PyObject,\n    nargs: Py_ssize_t,\n    kwnames: *mut PyObject,\n) -> *mut PyObject {\n    unsafe {\n        let mut default: Option<NonNull<PyObject>> = None;\n        let mut optsptr: Option<NonNull<PyObject>> = None;\n\n        let num_args = PyVectorcall_NARGS(isize_to_usize(nargs));\n        if num_args == 0 {\n            cold_path!();\n            return raise_dumps_exception_fixed(\n                \"dumps() missing 1 required positional argument: 'obj'\",\n            );\n        }\n        if num_args & 2 == 2 {\n            default = Some(NonNull::new_unchecked(*args.offset(1)));\n        }\n        if num_args & 3 == 3 {\n            optsptr = Some(NonNull::new_unchecked(*args.offset(2)));\n        }\n        if !kwnames.is_null() {\n            cold_path!();\n            let kwob = PyTupleRef::from_ptr_unchecked(kwnames);\n            for i in 0..=Py_SIZE(kwnames).saturating_sub(1) {\n                let arg = kwob.get(i.cast_unsigned());\n                if matches_kwarg!(arg, typeref::OPTION) {\n                    if num_args & 3 == 3 {\n                        cold_path!();\n                        return raise_dumps_exception_fixed(\n                            \"dumps() got multiple values for argument: 'option'\",\n                        );\n                    }\n                    optsptr = Some(NonNull::new_unchecked(*args.offset(num_args + i)));\n                } else if matches_kwarg!(arg, typeref::DEFAULT) {\n                    if num_args & 2 == 2 {\n                        cold_path!();\n                        return raise_dumps_exception_fixed(\n                            \"dumps() got multiple values for argument: 'default'\",\n                        );\n                    }\n                    default = Some(NonNull::new_unchecked(*args.offset(num_args + i)));\n                } else {\n                    return raise_dumps_exception_fixed(\n                        \"dumps() got an unexpected keyword argument\",\n                    );\n                }\n            }\n        }\n\n        let mut opts = 0 as opt::Opt;\n        if let Some(tmp) = optsptr {\n            cold_path!();\n            match PyIntRef::from_ptr(tmp.as_ptr()) {\n                Ok(val) => match val.as_opt() {\n                    Ok(opt) => {\n                        opts = opt;\n                    }\n                    Err(_) => {\n                        return raise_dumps_exception_fixed(\"Invalid opts\");\n                    }\n                },\n                Err(_) => {\n                    if !core::ptr::eq(tmp.as_ptr(), PyNoneRef::none().as_ptr()) {\n                        cold_path!();\n                        return raise_dumps_exception_fixed(\"Invalid opts\");\n                    }\n                }\n            }\n        }\n\n        serialize(*args, default, opts).map_or_else(\n            |err| raise_dumps_exception_dynamic(err.as_str()),\n            NonNull::as_ptr,\n        )\n    }\n}\n"
  },
  {
    "path": "src/opt.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2020-2025)\n\npub(crate) type Opt = u32;\n\npub(crate) const INDENT_2: Opt = 1;\npub(crate) const NAIVE_UTC: Opt = 1 << 1;\npub(crate) const NON_STR_KEYS: Opt = 1 << 2;\npub(crate) const OMIT_MICROSECONDS: Opt = 1 << 3;\npub(crate) const SERIALIZE_NUMPY: Opt = 1 << 4;\npub(crate) const SORT_KEYS: Opt = 1 << 5;\npub(crate) const STRICT_INTEGER: Opt = 1 << 6;\npub(crate) const UTC_Z: Opt = 1 << 7;\npub(crate) const PASSTHROUGH_SUBCLASS: Opt = 1 << 8;\npub(crate) const PASSTHROUGH_DATETIME: Opt = 1 << 9;\npub(crate) const APPEND_NEWLINE: Opt = 1 << 10;\npub(crate) const PASSTHROUGH_DATACLASS: Opt = 1 << 11;\n\n// deprecated\npub(crate) const SERIALIZE_DATACLASS: Opt = 0;\npub(crate) const SERIALIZE_UUID: Opt = 0;\n\npub(crate) const SORT_OR_NON_STR_KEYS: Opt = SORT_KEYS | NON_STR_KEYS;\n\npub(crate) const NOT_PASSTHROUGH: Opt =\n    !(PASSTHROUGH_DATETIME | PASSTHROUGH_DATACLASS | PASSTHROUGH_SUBCLASS);\n\n#[allow(clippy::cast_possible_wrap)]\npub(crate) const MAX_OPT: i32 = (APPEND_NEWLINE\n    | INDENT_2\n    | NAIVE_UTC\n    | NON_STR_KEYS\n    | OMIT_MICROSECONDS\n    | PASSTHROUGH_DATETIME\n    | PASSTHROUGH_DATACLASS\n    | PASSTHROUGH_SUBCLASS\n    | SERIALIZE_DATACLASS\n    | SERIALIZE_NUMPY\n    | SERIALIZE_UUID\n    | SORT_KEYS\n    | STRICT_INTEGER\n    | UTC_Z) as i32;\n"
  },
  {
    "path": "src/serialize/buffer.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2024-2025)\n\nuse bytes::{BufMut, buf::UninitSlice};\nuse core::mem::MaybeUninit;\n\nconst BUFFER_LENGTH: usize = 64 - core::mem::size_of::<usize>();\n\n/// For use to serialize fixed-size UUIDs and DateTime.\n#[repr(align(64))]\npub(crate) struct SmallFixedBuffer {\n    idx: usize,\n    bytes: [MaybeUninit<u8>; BUFFER_LENGTH],\n}\n\nimpl SmallFixedBuffer {\n    #[inline]\n    pub fn new() -> Self {\n        Self {\n            idx: 0,\n            bytes: [MaybeUninit::<u8>::uninit(); BUFFER_LENGTH],\n        }\n    }\n\n    #[inline]\n    pub fn as_ptr(&self) -> *const u8 {\n        (&raw const self.bytes).cast::<u8>()\n    }\n\n    #[inline]\n    pub fn len(&self) -> usize {\n        self.idx\n    }\n}\n\nunsafe impl BufMut for SmallFixedBuffer {\n    #[inline]\n    unsafe fn advance_mut(&mut self, cnt: usize) {\n        self.idx += cnt;\n    }\n\n    #[inline]\n    fn chunk_mut(&mut self) -> &mut UninitSlice {\n        UninitSlice::uninit(&mut self.bytes)\n    }\n\n    #[inline]\n    fn remaining_mut(&self) -> usize {\n        BUFFER_LENGTH - self.idx\n    }\n\n    #[inline]\n    fn put_u8(&mut self, value: u8) {\n        debug_assert!(self.remaining_mut() > 1);\n        unsafe {\n            core::ptr::write((&raw mut self.bytes).cast::<u8>().add(self.idx), value);\n            self.advance_mut(1);\n        };\n    }\n\n    #[inline]\n    fn put_slice(&mut self, src: &[u8]) {\n        debug_assert!(self.remaining_mut() > src.len());\n        unsafe {\n            core::ptr::copy_nonoverlapping(\n                src.as_ptr(),\n                (&raw mut self.bytes).cast::<u8>().add(self.idx),\n                src.len(),\n            );\n            self.advance_mut(src.len());\n        }\n    }\n}\n"
  },
  {
    "path": "src/serialize/error.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2021-2025)\n\nuse core::ffi::CStr;\nuse core::ptr::NonNull;\n\npub(crate) enum SerializeError {\n    DatetimeLibraryUnsupported,\n    DefaultRecursionLimit,\n    Integer53Bits,\n    Integer64Bits,\n    InvalidStr,\n    InvalidFragment,\n    KeyMustBeStr,\n    RecursionLimit,\n    TimeHasTzinfo,\n    DictIntegerKey64Bit,\n    DictKeyInvalidType,\n    NumpyMalformed,\n    NumpyNotCContiguous,\n    NumpyNotNativeEndian,\n    NumpyUnsupportedDatatype,\n    UnsupportedType(NonNull<crate::ffi::PyObject>),\n}\n\nimpl core::fmt::Display for SerializeError {\n    #[cold]\n    #[cfg_attr(feature = \"optimize\", optimize(size))]\n    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {\n        match *self {\n            SerializeError::DatetimeLibraryUnsupported => write!(\n                f,\n                \"datetime's timezone library is not supported: use datetime.timezone.utc, pendulum, pytz, or dateutil\"\n            ),\n            SerializeError::DefaultRecursionLimit => {\n                write!(f, \"default serializer exceeds recursion limit\")\n            }\n            SerializeError::Integer53Bits => write!(f, \"Integer exceeds 53-bit range\"),\n            SerializeError::Integer64Bits => write!(f, \"Integer exceeds 64-bit range\"),\n            SerializeError::InvalidStr => write!(f, \"{}\", crate::util::INVALID_STR),\n            SerializeError::InvalidFragment => {\n                write!(f, \"orjson.Fragment's content is not of type bytes or str\")\n            }\n            SerializeError::KeyMustBeStr => write!(f, \"Dict key must be str\"),\n            SerializeError::RecursionLimit => write!(f, \"Recursion limit reached\"),\n            SerializeError::TimeHasTzinfo => write!(f, \"datetime.time must not have tzinfo set\"),\n            SerializeError::DictIntegerKey64Bit => {\n                write!(f, \"Dict integer key must be within 64-bit range\")\n            }\n            SerializeError::DictKeyInvalidType => {\n                write!(f, \"Dict key must a type serializable with OPT_NON_STR_KEYS\")\n            }\n            SerializeError::NumpyMalformed => write!(f, \"numpy array is malformed\"),\n            SerializeError::NumpyNotCContiguous => write!(\n                f,\n                \"numpy array is not C contiguous; use ndarray.tolist() in default\"\n            ),\n            SerializeError::NumpyNotNativeEndian => {\n                write!(f, \"numpy array is not native-endianness\")\n            }\n            SerializeError::NumpyUnsupportedDatatype => {\n                write!(f, \"unsupported datatype in numpy array\")\n            }\n            SerializeError::UnsupportedType(ptr) => {\n                let name =\n                    unsafe { CStr::from_ptr((*ob_type!(ptr.as_ptr())).tp_name).to_string_lossy() };\n                write!(f, \"Type is not JSON serializable: {name}\")\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/serialize/mod.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2021-2025)\n\nmod buffer;\nmod error;\nmod obtype;\nmod per_type;\nmod serializer;\nmod state;\npub(crate) mod writer;\n\npub(crate) use serializer::serialize;\n"
  },
  {
    "path": "src/serialize/obtype.rs",
    "content": "// SPDX-License-Identifier: (Apache-2.0 OR MIT)\n// Copyright ijl (2020-2025), Aviram Hassan (2020)\n\nuse crate::opt::{\n    Opt, PASSTHROUGH_DATACLASS, PASSTHROUGH_DATETIME, PASSTHROUGH_SUBCLASS, SERIALIZE_NUMPY,\n};\nuse crate::serialize::per_type::{is_numpy_array, is_numpy_scalar};\nuse crate::typeref::{\n    BOOL_TYPE, DATACLASS_FIELDS_STR, DATE_TYPE, DATETIME_TYPE, DICT_TYPE, ENUM_TYPE, FLOAT_TYPE,\n    FRAGMENT_TYPE, INT_TYPE, LIST_TYPE, NONE_TYPE, STR_TYPE, TIME_TYPE, TUPLE_TYPE, UUID_TYPE,\n};\n\n#[repr(u32)]\npub(crate) enum ObType {\n    Str,\n    Int,\n    Bool,\n    None,\n    Float,\n    List,\n    Dict,\n    Datetime,\n    Date,\n    Time,\n    Tuple,\n    Uuid,\n    Dataclass,\n    NumpyScalar,\n    NumpyArray,\n    Enum,\n    StrSubclass,\n    Fragment,\n    Unknown,\n}\n\npub(crate) fn pyobject_to_obtype(obj: *mut crate::ffi::PyObject, opts: Opt) -> ObType {\n    let ob_type = ob_type!(obj);\n    if is_class_by_type!(ob_type, STR_TYPE) {\n        ObType::Str\n    } else if is_class_by_type!(ob_type, INT_TYPE) {\n        ObType::Int\n    } else if is_class_by_type!(ob_type, BOOL_TYPE) {\n        ObType::Bool\n    } else if is_class_by_type!(ob_type, NONE_TYPE) {\n        ObType::None\n    } else if is_class_by_type!(ob_type, FLOAT_TYPE) {\n        ObType::Float\n    } else if is_class_by_type!(ob_type, LIST_TYPE) {\n        ObType::List\n    } else if is_class_by_type!(ob_type, DICT_TYPE) {\n        ObType::Dict\n    } else if is_class_by_type!(ob_type, DATETIME_TYPE) && opt_disabled!(opts, PASSTHROUGH_DATETIME)\n    {\n        ObType::Datetime\n    } else {\n        pyobject_to_obtype_unlikely(ob_type, opts)\n    }\n}\n\n#[cfg_attr(feature = \"optimize\", optimize(size))]\n#[inline(never)]\npub(crate) fn pyobject_to_obtype_unlikely(\n    ob_type: *mut crate::ffi::PyTypeObject,\n    opts: Opt,\n) -> ObType {\n    if is_class_by_type!(ob_type, UUID_TYPE) {\n        return ObType::Uuid;\n    } else if is_class_by_type!(ob_type, TUPLE_TYPE) {\n        return ObType::Tuple;\n    } else if is_class_by_type!(ob_type, FRAGMENT_TYPE) {\n        return ObType::Fragment;\n    }\n\n    if opt_disabled!(opts, PASSTHROUGH_DATETIME) {\n        if is_class_by_type!(ob_type, DATE_TYPE) {\n            return ObType::Date;\n        } else if is_class_by_type!(ob_type, TIME_TYPE) {\n            return ObType::Time;\n        }\n    }\n\n    let tp_flags = tp_flags!(ob_type);\n\n    if opt_disabled!(opts, PASSTHROUGH_SUBCLASS) {\n        if is_subclass_by_flag!(tp_flags, Py_TPFLAGS_UNICODE_SUBCLASS) {\n            return ObType::StrSubclass;\n        } else if is_subclass_by_flag!(tp_flags, Py_TPFLAGS_LONG_SUBCLASS) {\n            return ObType::Int;\n        } else if is_subclass_by_flag!(tp_flags, Py_TPFLAGS_LIST_SUBCLASS) {\n            return ObType::List;\n        } else if is_subclass_by_flag!(tp_flags, Py_TPFLAGS_DICT_SUBCLASS) {\n            return ObType::Dict;\n        }\n    }\n\n    if is_subclass_by_type!(ob_type, ENUM_TYPE) {\n        return ObType::Enum;\n    }\n\n    if opt_disabled!(opts, PASSTHROUGH_DATACLASS) && pydict_contains!(ob_type, DATACLASS_FIELDS_STR)\n    {\n        return ObType::Dataclass;\n    }\n\n    if opt_enabled!(opts, SERIALIZE_NUMPY) {\n        cold_path!();\n        if is_numpy_scalar(ob_type) {\n            return ObType::NumpyScalar;\n        } else if is_numpy_array(ob_type) {\n            return ObType::NumpyArray;\n        }\n    }\n\n    ObType::Unknown\n}\n"
  },
  {
    "path": "src/serialize/per_type/dataclass.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2018-2026)\n\nuse crate::ffi::PyStrRef;\nuse crate::serialize::error::SerializeError;\nuse crate::serialize::per_type::dict::ZeroDictSerializer;\nuse crate::serialize::serializer::PyObjectSerializer;\nuse crate::serialize::state::SerializerState;\nuse crate::typeref::{\n    DATACLASS_FIELDS_STR, DICT_STR, FIELD_TYPE, FIELD_TYPE_STR, SLOTS_STR, STR_TYPE,\n};\nuse crate::util::isize_to_usize;\n\nuse serde::ser::{Serialize, SerializeMap, Serializer};\n\nuse core::ptr::NonNull;\n\n#[repr(transparent)]\npub(crate) struct DataclassGenericSerializer<'a> {\n    previous: &'a PyObjectSerializer,\n}\n\nimpl<'a> DataclassGenericSerializer<'a> {\n    pub fn new(previous: &'a PyObjectSerializer) -> Self {\n        Self { previous: previous }\n    }\n}\n\nimpl Serialize for DataclassGenericSerializer<'_> {\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        if self.previous.state.recursion_limit() {\n            err!(SerializeError::RecursionLimit)\n        }\n        let dict = ffi!(PyObject_GetAttr(self.previous.ptr, DICT_STR));\n        let ob_type = ob_type!(self.previous.ptr);\n        if dict.is_null() {\n            cold_path!();\n            ffi!(PyErr_Clear());\n            DataclassFallbackSerializer::new(\n                self.previous.ptr,\n                self.previous.state,\n                self.previous.default,\n            )\n            .serialize(serializer)\n        } else if pydict_contains!(ob_type, SLOTS_STR) {\n            let ret = DataclassFallbackSerializer::new(\n                self.previous.ptr,\n                self.previous.state,\n                self.previous.default,\n            )\n            .serialize(serializer);\n            ffi!(Py_DECREF(dict));\n            ret\n        } else {\n            let ret =\n                DataclassFastSerializer::new(dict, self.previous.state, self.previous.default)\n                    .serialize(serializer);\n            ffi!(Py_DECREF(dict));\n            ret\n        }\n    }\n}\n\npub(crate) struct DataclassFastSerializer {\n    ptr: *mut crate::ffi::PyObject,\n    state: SerializerState,\n    default: Option<NonNull<crate::ffi::PyObject>>,\n}\n\nimpl DataclassFastSerializer {\n    pub fn new(\n        ptr: *mut crate::ffi::PyObject,\n        state: SerializerState,\n        default: Option<NonNull<crate::ffi::PyObject>>,\n    ) -> Self {\n        DataclassFastSerializer {\n            ptr: ptr,\n            state: state.copy_for_recursive_call(),\n            default: default,\n        }\n    }\n}\n\nimpl Serialize for DataclassFastSerializer {\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let len = isize_to_usize(ffi!(Py_SIZE(self.ptr)));\n        if len == 0 {\n            cold_path!();\n            return ZeroDictSerializer::new().serialize(serializer);\n        }\n        let mut map = serializer.serialize_map(None).unwrap();\n\n        let mut pos = 0;\n        let mut next_key: *mut crate::ffi::PyObject = core::ptr::null_mut();\n        let mut next_value: *mut crate::ffi::PyObject = core::ptr::null_mut();\n\n        pydict_next!(\n            self.ptr,\n            &raw mut pos,\n            &raw mut next_key,\n            &raw mut next_value\n        );\n\n        for _ in 0..len {\n            let key = next_key;\n            let value = next_value;\n\n            pydict_next!(\n                self.ptr,\n                &raw mut pos,\n                &raw mut next_key,\n                &raw mut next_value\n            );\n\n            let key_as_str = {\n                let key_ob_type = ob_type!(key);\n                if !is_class_by_type!(key_ob_type, STR_TYPE) {\n                    cold_path!();\n                    err!(SerializeError::KeyMustBeStr)\n                }\n                match unsafe { PyStrRef::from_ptr_unchecked(key).as_str() } {\n                    Some(uni) => uni,\n                    None => err!(SerializeError::InvalidStr),\n                }\n            };\n            if key_as_str.as_bytes()[0] == b'_' {\n                cold_path!();\n                continue;\n            }\n            let pyvalue = PyObjectSerializer::new(value, self.state, self.default);\n            map.serialize_key(key_as_str).unwrap();\n            map.serialize_value(&pyvalue)?;\n        }\n        map.end()\n    }\n}\n\npub(crate) struct DataclassFallbackSerializer {\n    ptr: *mut crate::ffi::PyObject,\n    state: SerializerState,\n    default: Option<NonNull<crate::ffi::PyObject>>,\n}\n\nimpl DataclassFallbackSerializer {\n    pub fn new(\n        ptr: *mut crate::ffi::PyObject,\n        state: SerializerState,\n        default: Option<NonNull<crate::ffi::PyObject>>,\n    ) -> Self {\n        DataclassFallbackSerializer {\n            ptr: ptr,\n            state: state.copy_for_recursive_call(),\n            default: default,\n        }\n    }\n}\n\nimpl Serialize for DataclassFallbackSerializer {\n    #[cold]\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let fields = ffi!(PyObject_GetAttr(self.ptr, DATACLASS_FIELDS_STR));\n        debug_assert!(ffi!(Py_REFCNT(fields)) >= 2);\n        ffi!(Py_DECREF(fields));\n        let len = isize_to_usize(ffi!(Py_SIZE(fields)));\n        if len == 0 {\n            cold_path!();\n            return ZeroDictSerializer::new().serialize(serializer);\n        }\n        let mut map = serializer.serialize_map(None).unwrap();\n\n        let mut pos = 0;\n        let mut next_key: *mut crate::ffi::PyObject = core::ptr::null_mut();\n        let mut next_value: *mut crate::ffi::PyObject = core::ptr::null_mut();\n\n        pydict_next!(fields, &raw mut pos, &raw mut next_key, &raw mut next_value);\n\n        for _ in 0..len {\n            let attr = next_key;\n            let field = next_value;\n\n            pydict_next!(fields, &raw mut pos, &raw mut next_key, &raw mut next_value);\n\n            let field_type = ffi!(PyObject_GetAttr(field, FIELD_TYPE_STR));\n            debug_assert!(ffi!(Py_REFCNT(field_type)) >= 2);\n            ffi!(Py_DECREF(field_type));\n            if unsafe { !core::ptr::eq(field_type.cast::<crate::ffi::PyTypeObject>(), FIELD_TYPE) }\n            {\n                continue;\n            }\n\n            let key_as_str = match unsafe { PyStrRef::from_ptr_unchecked(attr).as_str() } {\n                Some(uni) => uni,\n                None => err!(SerializeError::InvalidStr),\n            };\n            if key_as_str.as_bytes()[0] == b'_' {\n                cold_path!();\n                continue;\n            }\n\n            let value = ffi!(PyObject_GetAttr(self.ptr, attr));\n            debug_assert!(ffi!(Py_REFCNT(value)) >= 2);\n            ffi!(Py_DECREF(value));\n            let pyvalue = PyObjectSerializer::new(value, self.state, self.default);\n\n            map.serialize_key(key_as_str).unwrap();\n            map.serialize_value(&pyvalue)?;\n        }\n        map.end()\n    }\n}\n"
  },
  {
    "path": "src/serialize/per_type/datetime.rs",
    "content": "// SPDX-License-Identifier: (Apache-2.0 OR MIT)\n// Copyright ijl (2018-2026), Ben Sully (2021)\n\nuse crate::opt::{OMIT_MICROSECONDS, Opt};\nuse crate::serialize::buffer::SmallFixedBuffer;\nuse crate::serialize::error::SerializeError;\nuse crate::serialize::per_type::datetimelike::{DateTimeError, DateTimeLike, Offset};\nuse crate::typeref::{\n    CONVERT_METHOD_STR, DST_STR, NORMALIZE_METHOD_STR, UTCOFFSET_METHOD_STR, ZONEINFO_TYPE,\n};\nuse serde::ser::{Serialize, Serializer};\n\nmacro_rules! write_double_digit {\n    ($buf:ident, $value:ident) => {\n        if $value < 10 {\n            $buf.put_u8(b'0');\n        }\n        $buf.put_slice(itoa::Buffer::new().format($value).as_bytes());\n    };\n}\n\nmacro_rules! write_microsecond {\n    ($buf:ident, $microsecond:ident) => {\n        if $microsecond != 0 {\n            let mut buf = itoa::Buffer::new();\n            let formatted = buf.format($microsecond);\n            $buf.put_slice(&[b'.', b'0', b'0', b'0', b'0', b'0', b'0'][..(7 - formatted.len())]);\n            $buf.put_slice(formatted.as_bytes());\n        }\n    };\n}\n\n#[repr(transparent)]\npub(crate) struct Date {\n    ptr: *mut crate::ffi::PyObject,\n}\n\nimpl Date {\n    pub fn new(ptr: *mut crate::ffi::PyObject) -> Self {\n        Date { ptr: ptr }\n    }\n\n    #[inline(never)]\n    pub fn write_buf<B>(&self, buf: &mut B)\n    where\n        B: bytes::BufMut,\n    {\n        {\n            let year = ffi!(PyDateTime_GET_YEAR(self.ptr));\n            let mut yearbuf = itoa::Buffer::new();\n            let formatted = yearbuf.format(year);\n            if year < 1000 {\n                cold_path!();\n                // date-fullyear   = 4DIGIT\n                buf.put_slice(&[b'0', b'0', b'0', b'0'][..(4 - formatted.len())]);\n            }\n            buf.put_slice(formatted.as_bytes());\n        }\n        buf.put_u8(b'-');\n        {\n            let val_py = ffi!(PyDateTime_GET_MONTH(self.ptr));\n            debug_assert!(val_py >= 0);\n            let val = val_py.cast_unsigned();\n            write_double_digit!(buf, val);\n        }\n        buf.put_u8(b'-');\n        {\n            let val_py = ffi!(PyDateTime_GET_DAY(self.ptr));\n            debug_assert!(val_py >= 0);\n            let val = val_py.cast_unsigned();\n            write_double_digit!(buf, val);\n        }\n    }\n}\nimpl Serialize for Date {\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut buf = SmallFixedBuffer::new();\n        self.write_buf(&mut buf);\n        serializer.serialize_unit_struct(str_from_slice!(buf.as_ptr(), buf.len()))\n    }\n}\n\npub(crate) enum TimeError {\n    HasTimezone,\n}\n\npub(crate) struct Time {\n    ptr: *mut crate::ffi::PyObject,\n    opts: Opt,\n}\n\nimpl Time {\n    pub fn new(ptr: *mut crate::ffi::PyObject, opts: Opt) -> Self {\n        Time {\n            ptr: ptr,\n            opts: opts,\n        }\n    }\n\n    #[inline(never)]\n    pub fn write_buf<B>(&self, buf: &mut B) -> Result<(), TimeError>\n    where\n        B: bytes::BufMut,\n    {\n        if unsafe { (*self.ptr.cast::<crate::ffi::PyDateTime_Time>()).hastzinfo == 1 } {\n            return Err(TimeError::HasTimezone);\n        }\n        let hour = ffi!(PyDateTime_TIME_GET_HOUR(self.ptr)).cast_unsigned();\n        write_double_digit!(buf, hour);\n        buf.put_u8(b':');\n        let minute = ffi!(PyDateTime_TIME_GET_MINUTE(self.ptr)).cast_unsigned();\n        write_double_digit!(buf, minute);\n        buf.put_u8(b':');\n        let second = ffi!(PyDateTime_TIME_GET_SECOND(self.ptr)).cast_unsigned();\n        write_double_digit!(buf, second);\n        if opt_disabled!(self.opts, OMIT_MICROSECONDS) {\n            let microsecond = ffi!(PyDateTime_TIME_GET_MICROSECOND(self.ptr)).cast_unsigned();\n            write_microsecond!(buf, microsecond);\n        }\n        Ok(())\n    }\n}\n\nimpl Serialize for Time {\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut buf = SmallFixedBuffer::new();\n        if self.write_buf(&mut buf).is_err() {\n            err!(SerializeError::DatetimeLibraryUnsupported)\n        }\n        serializer.serialize_unit_struct(str_from_slice!(buf.as_ptr(), buf.len()))\n    }\n}\n\npub(crate) struct DateTime {\n    ptr: *mut crate::ffi::PyObject,\n    opts: Opt,\n}\n\nimpl DateTime {\n    pub fn new(ptr: *mut crate::ffi::PyObject, opts: Opt) -> Self {\n        DateTime {\n            ptr: ptr,\n            opts: opts,\n        }\n    }\n}\n\nmacro_rules! pydatetime_get {\n    ($fn: ident, $pyfn: ident, $ty: ident) => {\n        fn $fn(&self) -> $ty {\n            let ret = ffi!($pyfn(self.ptr));\n            debug_assert!(ret >= 0);\n            #[allow(clippy::cast_sign_loss)]\n            let ret2 = ret as $ty; // stmt_expr_attributes\n            ret2\n        }\n    };\n}\n\nimpl DateTimeLike for DateTime {\n    pydatetime_get!(year, PyDateTime_GET_YEAR, i32);\n    pydatetime_get!(month, PyDateTime_GET_MONTH, u8);\n    pydatetime_get!(day, PyDateTime_GET_DAY, u8);\n    pydatetime_get!(hour, PyDateTime_DATE_GET_HOUR, u8);\n    pydatetime_get!(minute, PyDateTime_DATE_GET_MINUTE, u8);\n    pydatetime_get!(second, PyDateTime_DATE_GET_SECOND, u8);\n    pydatetime_get!(microsecond, PyDateTime_DATE_GET_MICROSECOND, u32);\n\n    fn nanosecond(&self) -> u32 {\n        self.microsecond() * 1_000\n    }\n\n    fn has_tz(&self) -> bool {\n        unsafe { (*(self.ptr.cast::<crate::ffi::PyDateTime_DateTime>())).hastzinfo == 1 }\n    }\n\n    #[inline(never)]\n    fn slow_offset(&self) -> Result<Offset, DateTimeError> {\n        let tzinfo = ffi!(PyDateTime_DATE_GET_TZINFO(self.ptr));\n        if ffi!(PyObject_HasAttr(tzinfo, CONVERT_METHOD_STR)) == 1 {\n            // pendulum\n            let py_offset = call_method!(self.ptr, UTCOFFSET_METHOD_STR);\n            let offset = Offset {\n                second: ffi!(PyDateTime_DELTA_GET_SECONDS(py_offset)),\n                day: ffi!(PyDateTime_DELTA_GET_DAYS(py_offset)),\n            };\n            ffi!(Py_DECREF(py_offset));\n            Ok(offset)\n        } else if ffi!(PyObject_HasAttr(tzinfo, NORMALIZE_METHOD_STR)) == 1 {\n            // pytz\n            let method_ptr = call_method!(tzinfo, NORMALIZE_METHOD_STR, self.ptr);\n            let py_offset = call_method!(method_ptr, UTCOFFSET_METHOD_STR);\n            ffi!(Py_DECREF(method_ptr));\n            let offset = Offset {\n                second: ffi!(PyDateTime_DELTA_GET_SECONDS(py_offset)),\n                day: ffi!(PyDateTime_DELTA_GET_DAYS(py_offset)),\n            };\n            ffi!(Py_DECREF(py_offset));\n            Ok(offset)\n        } else if ffi!(PyObject_HasAttr(tzinfo, DST_STR)) == 1 {\n            // dateutil/arrow, datetime.timezone.utc\n            let py_offset = call_method!(tzinfo, UTCOFFSET_METHOD_STR, self.ptr);\n            let offset = Offset {\n                second: ffi!(PyDateTime_DELTA_GET_SECONDS(py_offset)),\n                day: ffi!(PyDateTime_DELTA_GET_DAYS(py_offset)),\n            };\n            ffi!(Py_DECREF(py_offset));\n            Ok(offset)\n        } else {\n            Err(DateTimeError::LibraryUnsupported)\n        }\n    }\n\n    #[inline]\n    fn offset(&self) -> Result<Offset, DateTimeError> {\n        if !self.has_tz() {\n            Ok(Offset::default())\n        } else {\n            let tzinfo = ffi!(PyDateTime_DATE_GET_TZINFO(self.ptr));\n            if unsafe { core::ptr::eq(ob_type!(tzinfo), ZONEINFO_TYPE) } {\n                // zoneinfo\n                let py_offset = call_method!(tzinfo, UTCOFFSET_METHOD_STR, self.ptr);\n                let offset = Offset {\n                    second: ffi!(PyDateTime_DELTA_GET_SECONDS(py_offset)),\n                    day: ffi!(PyDateTime_DELTA_GET_DAYS(py_offset)),\n                };\n                ffi!(Py_DECREF(py_offset));\n                Ok(offset)\n            } else {\n                self.slow_offset()\n            }\n        }\n    }\n}\n\nimpl Serialize for DateTime {\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut buf = SmallFixedBuffer::new();\n        if self.write_buf(&mut buf, self.opts).is_err() {\n            err!(SerializeError::DatetimeLibraryUnsupported)\n        }\n        serializer.serialize_unit_struct(str_from_slice!(buf.as_ptr(), buf.len()))\n    }\n}\n"
  },
  {
    "path": "src/serialize/per_type/datetimelike.rs",
    "content": "// SPDX-License-Identifier: (Apache-2.0 OR MIT)\n// Copyright ijl (2020-2025), Ben Sully (2021)\n\nuse crate::opt::{NAIVE_UTC, OMIT_MICROSECONDS, Opt, UTC_Z};\n\npub(crate) enum DateTimeError {\n    LibraryUnsupported,\n}\n\nmacro_rules! write_double_digit {\n    ($buf:ident, $value:expr) => {\n        if $value < 10 {\n            $buf.put_u8(b'0');\n        }\n        $buf.put_slice(itoa::Buffer::new().format($value).as_bytes());\n    };\n}\n\nmacro_rules! write_triple_digit {\n    ($buf:ident, $value:expr) => {\n        if $value < 100 {\n            $buf.put_u8(b'0');\n        }\n        if $value < 10 {\n            $buf.put_u8(b'0');\n        }\n        $buf.put_slice(itoa::Buffer::new().format($value).as_bytes());\n    };\n}\n\n#[derive(Default)]\npub(crate) struct Offset {\n    pub day: i32,\n    pub second: i32,\n}\n\n/// Trait providing a method to write a datetime-like object to a buffer in an RFC3339-compatible format.\n///\n/// The provided `write_buf` method does not allocate, and is faster\n/// than writing to a heap-allocated string.\npub(crate) trait DateTimeLike {\n    /// Returns the year component of the datetime.\n    fn year(&self) -> i32;\n    /// Returns the month component of the datetime.\n    fn month(&self) -> u8;\n    /// Returns the day component of the datetime.\n    fn day(&self) -> u8;\n    /// Returns the hour component of the datetime.\n    fn hour(&self) -> u8;\n    /// Returns the minute component of the datetime.\n    fn minute(&self) -> u8;\n    /// Returns the second component of the datetime.\n    fn second(&self) -> u8;\n    /// Returns the number of microseconds since the whole non-leap second.\n    fn microsecond(&self) -> u32;\n    /// Returns the number of nanoseconds since the whole non-leap second.\n    fn nanosecond(&self) -> u32;\n\n    /// Is the object time-zone aware?\n    fn has_tz(&self) -> bool;\n\n    //// Non-zoneinfo implementation of offset()\n    fn slow_offset(&self) -> Result<Offset, DateTimeError>;\n\n    /// The offset of the timezone.\n    fn offset(&self) -> Result<Offset, DateTimeError>;\n\n    /// Write `self` to a buffer in RFC3339 format, using `opts` to\n    /// customise if desired.\n    #[inline(never)]\n    fn write_buf<B>(&self, buf: &mut B, opts: Opt) -> Result<(), DateTimeError>\n    where\n        B: bytes::BufMut,\n    {\n        {\n            let year = self.year();\n            let mut yearbuf = itoa::Buffer::new();\n            let formatted = yearbuf.format(year);\n            if year < 1000 {\n                cold_path!();\n                // date-fullyear   = 4DIGIT\n                buf.put_slice(&[b'0', b'0', b'0', b'0'][..(4 - formatted.len())]);\n            }\n            buf.put_slice(formatted.as_bytes());\n        }\n        buf.put_u8(b'-');\n        write_double_digit!(buf, self.month());\n        buf.put_u8(b'-');\n        write_double_digit!(buf, self.day());\n        buf.put_u8(b'T');\n        write_double_digit!(buf, self.hour());\n        buf.put_u8(b':');\n        write_double_digit!(buf, self.minute());\n        buf.put_u8(b':');\n        write_double_digit!(buf, self.second());\n        if opt_disabled!(opts, OMIT_MICROSECONDS) {\n            let microsecond = self.microsecond();\n            if microsecond != 0 {\n                buf.put_u8(b'.');\n                write_triple_digit!(buf, microsecond / 1_000);\n                write_triple_digit!(buf, microsecond % 1_000);\n                // Don't support writing nanoseconds for now.\n                // If requested, something like the following should work,\n                // and `SmallFixedBuffer` needs at least length 35.\n                // let nanosecond = self.nanosecond();\n                // if nanosecond % 1_000 != 0 {\n                //     write_triple_digit!(buf, nanosecond % 1_000);\n                // }\n            }\n        }\n        if self.has_tz() || opt_enabled!(opts, NAIVE_UTC) {\n            let offset = self.offset()?;\n            let mut offset_second = offset.second;\n            if offset_second == 0 {\n                if opt_enabled!(opts, UTC_Z) {\n                    buf.put_u8(b'Z');\n                } else {\n                    buf.put_slice(b\"+00:00\");\n                }\n            } else {\n                // This branch is only really hit by the Python datetime implementation,\n                // since numpy datetimes are all converted to UTC.\n                if offset.day == -1 {\n                    // datetime.timedelta(days=-1, seconds=68400) -> -05:00\n                    buf.put_u8(b'-');\n                    offset_second = 86400 - offset_second;\n                } else {\n                    // datetime.timedelta(seconds=37800) -> +10:30\n                    buf.put_u8(b'+');\n                }\n                let offset_minute = offset_second / 60;\n                let offset_hour = offset_minute / 60;\n                write_double_digit!(buf, offset_hour);\n                buf.put_u8(b':');\n                let mut offset_minute_print = offset_minute % 60;\n                // https://tools.ietf.org/html/rfc3339#section-5.8\n                // \"exactly 19 minutes and 32.13 seconds ahead of UTC\"\n                // \"closest representable UTC offset\"\n                //  \"+20:00\"\n                let offset_excess_second =\n                    offset_second - (offset_minute_print * 60 + offset_hour * 3600);\n                if offset_excess_second >= 30 {\n                    offset_minute_print += 1;\n                }\n                write_double_digit!(buf, offset_minute_print);\n            }\n        }\n        Ok(())\n    }\n}\n"
  },
  {
    "path": "src/serialize/per_type/default.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2018-2026)\n\nuse crate::serialize::error::SerializeError;\nuse crate::serialize::serializer::PyObjectSerializer;\n\nuse serde::ser::{Serialize, Serializer};\n\n#[repr(transparent)]\npub(crate) struct DefaultSerializer<'a> {\n    previous: &'a PyObjectSerializer,\n}\n\nimpl<'a> DefaultSerializer<'a> {\n    pub fn new(previous: &'a PyObjectSerializer) -> Self {\n        Self { previous: previous }\n    }\n}\n\nimpl Serialize for DefaultSerializer<'_> {\n    #[cold]\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        match self.previous.default {\n            Some(callable) => {\n                if self.previous.state.default_calls_limit() {\n                    cold_path!();\n                    err!(SerializeError::DefaultRecursionLimit)\n                }\n                let nargs = ffi!(PyVectorcall_NARGS(1)).cast_unsigned() as usize;\n                let default_obj = unsafe {\n                    crate::ffi::PyObject_Vectorcall(\n                        callable.as_ptr(),\n                        &raw const self.previous.ptr,\n                        nargs,\n                        core::ptr::null_mut(),\n                    )\n                };\n                if default_obj.is_null() {\n                    err!(SerializeError::UnsupportedType(nonnull!(self.previous.ptr)))\n                } else {\n                    let res = PyObjectSerializer::new(\n                        default_obj,\n                        self.previous.state.copy_for_default_call(),\n                        self.previous.default,\n                    )\n                    .serialize(serializer);\n                    ffi!(Py_DECREF(default_obj));\n                    res\n                }\n            }\n            None => err!(SerializeError::UnsupportedType(nonnull!(self.previous.ptr))),\n        }\n    }\n}\n"
  },
  {
    "path": "src/serialize/per_type/dict.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2018-2026)\n\nuse crate::ffi::{\n    PyBoolRef, PyDictRef, PyFloatRef, PyFragmentRef, PyIntRef, PyListRef, PyStrRef,\n    PyStrSubclassRef, PyUuidRef,\n};\nuse crate::opt::{NON_STR_KEYS, NOT_PASSTHROUGH, SORT_KEYS, SORT_OR_NON_STR_KEYS};\nuse crate::serialize::buffer::SmallFixedBuffer;\nuse crate::serialize::error::SerializeError;\nuse crate::serialize::obtype::{ObType, pyobject_to_obtype};\nuse crate::serialize::per_type::datetimelike::DateTimeLike;\nuse crate::serialize::per_type::{\n    BoolSerializer, DataclassGenericSerializer, Date, DateTime, DefaultSerializer, EnumSerializer,\n    FloatSerializer, FragmentSerializer, IntSerializer, ListTupleSerializer, NoneSerializer,\n    NumpyScalar, NumpySerializer, StrSerializer, StrSubclassSerializer, Time, UUID,\n    ZeroListSerializer,\n};\nuse crate::serialize::serializer::PyObjectSerializer;\nuse crate::serialize::state::SerializerState;\nuse crate::typeref::{STR_TYPE, TRUE, VALUE_STR};\nuse core::ptr::NonNull;\nuse serde::ser::{Serialize, SerializeMap, Serializer};\nuse smallvec::SmallVec;\n\npub(crate) struct ZeroDictSerializer;\n\nimpl ZeroDictSerializer {\n    pub const fn new() -> Self {\n        Self {}\n    }\n}\n\nimpl Serialize for ZeroDictSerializer {\n    #[inline(always)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_bytes(b\"{}\")\n    }\n}\n\npub(crate) struct DictGenericSerializer {\n    dict: PyDictRef,\n    state: SerializerState,\n    #[allow(dead_code)]\n    default: Option<NonNull<crate::ffi::PyObject>>,\n}\n\nimpl DictGenericSerializer {\n    pub fn new(\n        dict: PyDictRef,\n        state: SerializerState,\n        default: Option<NonNull<crate::ffi::PyObject>>,\n    ) -> Self {\n        DictGenericSerializer {\n            dict: dict,\n            state: state.copy_for_recursive_call(),\n            default: default,\n        }\n    }\n}\n\nimpl Serialize for DictGenericSerializer {\n    #[inline(always)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        if self.state.recursion_limit() {\n            cold_path!();\n            err!(SerializeError::RecursionLimit)\n        }\n\n        if self.dict.len() == 0 {\n            cold_path!();\n            ZeroDictSerializer::new().serialize(serializer)\n        } else if opt_disabled!(self.state.opts(), SORT_OR_NON_STR_KEYS) {\n            unsafe {\n                (*(core::ptr::from_ref::<DictGenericSerializer>(self)).cast::<Dict>())\n                    .serialize(serializer)\n            }\n        } else if opt_enabled!(self.state.opts(), NON_STR_KEYS) {\n            unsafe {\n                (*(core::ptr::from_ref::<DictGenericSerializer>(self)).cast::<DictNonStrKey>())\n                    .serialize(serializer)\n            }\n        } else {\n            unsafe {\n                (*(core::ptr::from_ref::<DictGenericSerializer>(self)).cast::<DictSortedKey>())\n                    .serialize(serializer)\n            }\n        }\n    }\n}\n\nmacro_rules! impl_serialize_entry {\n    ($map:expr, $self:expr, $key:expr, $value:expr) => {\n        match pyobject_to_obtype($value, $self.state.opts()) {\n            ObType::Str => {\n                $map.serialize_key($key).unwrap();\n                $map.serialize_value(&StrSerializer::new(unsafe {\n                    PyStrRef::from_ptr_unchecked($value)\n                }))?;\n            }\n            ObType::StrSubclass => {\n                $map.serialize_key($key).unwrap();\n                $map.serialize_value(&StrSubclassSerializer::new(unsafe {\n                    PyStrSubclassRef::from_ptr_unchecked($value)\n                }))?;\n            }\n            ObType::Int => {\n                $map.serialize_key($key).unwrap();\n                $map.serialize_value(&IntSerializer::new(\n                    unsafe { PyIntRef::from_ptr_unchecked($value) },\n                    $self.state.opts(),\n                ))?;\n            }\n            ObType::None => {\n                $map.serialize_key($key).unwrap();\n                $map.serialize_value(&NoneSerializer::new()).unwrap();\n            }\n            ObType::Float => {\n                $map.serialize_key($key).unwrap();\n                $map.serialize_value(&FloatSerializer::new(unsafe {\n                    PyFloatRef::from_ptr_unchecked($value)\n                }))?;\n            }\n            ObType::Bool => {\n                $map.serialize_key($key).unwrap();\n                $map.serialize_value(&BoolSerializer::new(unsafe {\n                    PyBoolRef::from_ptr_unchecked($value)\n                }))\n                .unwrap();\n            }\n            ObType::Datetime => {\n                $map.serialize_key($key).unwrap();\n                $map.serialize_value(&DateTime::new($value, $self.state.opts()))?;\n            }\n            ObType::Date => {\n                $map.serialize_key($key).unwrap();\n                $map.serialize_value(&Date::new($value))?;\n            }\n            ObType::Time => {\n                $map.serialize_key($key).unwrap();\n                $map.serialize_value(&Time::new($value, $self.state.opts()))?;\n            }\n            ObType::Uuid => {\n                $map.serialize_key($key).unwrap();\n                $map.serialize_value(&UUID::new(unsafe { PyUuidRef::from_ptr_unchecked($value) }))\n                    .unwrap();\n            }\n            ObType::Dict => {\n                let pyvalue = DictGenericSerializer::new(\n                    unsafe { PyDictRef::from_ptr_unchecked($value) },\n                    $self.state,\n                    $self.default,\n                );\n                $map.serialize_key($key).unwrap();\n                $map.serialize_value(&pyvalue)?;\n            }\n            ObType::List => {\n                if ffi!(Py_SIZE($value)) == 0 {\n                    $map.serialize_key($key).unwrap();\n                    $map.serialize_value(&ZeroListSerializer::new()).unwrap();\n                } else {\n                    let pyvalue = ListTupleSerializer::from_list(\n                        unsafe { PyListRef::from_ptr_unchecked($value) },\n                        $self.state,\n                        $self.default,\n                    );\n                    $map.serialize_key($key).unwrap();\n                    $map.serialize_value(&pyvalue)?;\n                }\n            }\n            ObType::Tuple => {\n                if ffi!(Py_SIZE($value)) == 0 {\n                    $map.serialize_key($key).unwrap();\n                    $map.serialize_value(&ZeroListSerializer::new()).unwrap();\n                } else {\n                    let pyvalue =\n                        ListTupleSerializer::from_tuple($value, $self.state, $self.default);\n                    $map.serialize_key($key).unwrap();\n                    $map.serialize_value(&pyvalue)?;\n                }\n            }\n            ObType::Dataclass => {\n                $map.serialize_key($key).unwrap();\n                $map.serialize_value(&DataclassGenericSerializer::new(&PyObjectSerializer::new(\n                    $value,\n                    $self.state,\n                    $self.default,\n                )))?;\n            }\n            ObType::Enum => {\n                $map.serialize_key($key).unwrap();\n                $map.serialize_value(&EnumSerializer::new(&PyObjectSerializer::new(\n                    $value,\n                    $self.state,\n                    $self.default,\n                )))?;\n            }\n            ObType::NumpyArray => {\n                $map.serialize_key($key).unwrap();\n                $map.serialize_value(&NumpySerializer::new(&PyObjectSerializer::new(\n                    $value,\n                    $self.state,\n                    $self.default,\n                )))?;\n            }\n            ObType::NumpyScalar => {\n                $map.serialize_key($key).unwrap();\n                $map.serialize_value(&NumpyScalar::new($value, $self.state.opts()))?;\n            }\n            ObType::Fragment => {\n                $map.serialize_key($key).unwrap();\n                $map.serialize_value(&FragmentSerializer::new(unsafe {\n                    PyFragmentRef::from_ptr_unchecked($value)\n                }))?;\n            }\n            ObType::Unknown => {\n                $map.serialize_key($key).unwrap();\n                $map.serialize_value(&DefaultSerializer::new(&PyObjectSerializer::new(\n                    $value,\n                    $self.state,\n                    $self.default,\n                )))?;\n            }\n        }\n    };\n}\n\npub(crate) struct Dict {\n    dict: PyDictRef,\n    state: SerializerState,\n    default: Option<NonNull<crate::ffi::PyObject>>,\n}\n\nimpl Serialize for Dict {\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut pos = 0;\n        let mut next_key: *mut crate::ffi::PyObject = core::ptr::null_mut();\n        let mut next_value: *mut crate::ffi::PyObject = core::ptr::null_mut();\n\n        pydict_next!(\n            self.dict.as_ptr(),\n            &raw mut pos,\n            &raw mut next_key,\n            &raw mut next_value\n        );\n\n        let mut map = serializer.serialize_map(None).unwrap();\n\n        let len = self.dict.len();\n        assume!(len > 0);\n\n        for _ in 0..len {\n            let key = next_key;\n            let value = next_value;\n\n            pydict_next!(\n                self.dict.as_ptr(),\n                &raw mut pos,\n                &raw mut next_key,\n                &raw mut next_value\n            );\n\n            // key\n            let uni = PyStrRef::from_ptr(key)\n                .map_err(|_| serde::ser::Error::custom(SerializeError::KeyMustBeStr))?\n                .as_str();\n            if uni.is_none() {\n                cold_path!();\n                err!(SerializeError::InvalidStr);\n            }\n\n            // value\n            impl_serialize_entry!(map, self, uni.unwrap(), value);\n        }\n\n        map.end()\n    }\n}\n\npub(crate) struct DictSortedKey {\n    dict: PyDictRef,\n    state: SerializerState,\n    default: Option<NonNull<crate::ffi::PyObject>>,\n}\n\nimpl Serialize for DictSortedKey {\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut pos = 0;\n        let mut next_key: *mut crate::ffi::PyObject = core::ptr::null_mut();\n        let mut next_value: *mut crate::ffi::PyObject = core::ptr::null_mut();\n\n        pydict_next!(\n            self.dict.as_ptr(),\n            &raw mut pos,\n            &raw mut next_key,\n            &raw mut next_value\n        );\n\n        let len = self.dict.len();\n        assume!(len > 0);\n\n        let mut items: SmallVec<[(&str, *mut crate::ffi::PyObject); 8]> =\n            SmallVec::with_capacity(len);\n\n        for _ in 0..len {\n            let key = next_key;\n            let value = next_value;\n\n            pydict_next!(\n                self.dict.as_ptr(),\n                &raw mut pos,\n                &raw mut next_key,\n                &raw mut next_value\n            );\n\n            if unsafe { !core::ptr::eq(ob_type!(key), STR_TYPE) } {\n                err!(SerializeError::KeyMustBeStr)\n            }\n            let pystr = unsafe { PyStrRef::from_ptr_unchecked(key) };\n            let uni = pystr.as_str();\n            if uni.is_none() {\n                err!(SerializeError::InvalidStr)\n            }\n            let key_as_str = uni.unwrap();\n\n            items.push((key_as_str, value));\n        }\n\n        sort_dict_items(&mut items);\n\n        let mut map = serializer.serialize_map(None).unwrap();\n        for (key, val) in items.iter() {\n            let pyvalue = PyObjectSerializer::new(*val, self.state, self.default);\n            map.serialize_key(key).unwrap();\n            map.serialize_value(&pyvalue)?;\n        }\n        map.end()\n    }\n}\n#[cold]\n#[inline(never)]\nfn non_str_str(key: PyStrRef) -> Result<String, SerializeError> {\n    // because of ObType::Enum\n    match key.as_str() {\n        Some(uni) => Ok(String::from(uni)),\n        None => {\n            cold_path!();\n            Err(SerializeError::InvalidStr)\n        }\n    }\n}\n\n#[cold]\n#[inline(never)]\nfn non_str_str_subclass(key: PyStrSubclassRef) -> Result<String, SerializeError> {\n    match key.as_str() {\n        Some(uni) => Ok(String::from(uni)),\n        None => {\n            cold_path!();\n            Err(SerializeError::InvalidStr)\n        }\n    }\n}\n\n#[allow(clippy::unnecessary_wraps)]\n#[inline(never)]\nfn non_str_date(key: *mut crate::ffi::PyObject) -> Result<String, SerializeError> {\n    let mut buf = SmallFixedBuffer::new();\n    Date::new(key).write_buf(&mut buf);\n    let key_as_str = str_from_slice!(buf.as_ptr(), buf.len());\n    Ok(String::from(key_as_str))\n}\n\n#[inline(never)]\nfn non_str_datetime(\n    key: *mut crate::ffi::PyObject,\n    opts: crate::opt::Opt,\n) -> Result<String, SerializeError> {\n    let mut buf = SmallFixedBuffer::new();\n    let dt = DateTime::new(key, opts);\n    if dt.write_buf(&mut buf, opts).is_err() {\n        return Err(SerializeError::DatetimeLibraryUnsupported);\n    }\n    let key_as_str = str_from_slice!(buf.as_ptr(), buf.len());\n    Ok(String::from(key_as_str))\n}\n\n#[cold]\n#[inline(never)]\nfn non_str_time(\n    key: *mut crate::ffi::PyObject,\n    opts: crate::opt::Opt,\n) -> Result<String, SerializeError> {\n    let mut buf = SmallFixedBuffer::new();\n    let time = Time::new(key, opts);\n    if time.write_buf(&mut buf).is_err() {\n        return Err(SerializeError::TimeHasTzinfo);\n    }\n    let key_as_str = str_from_slice!(buf.as_ptr(), buf.len());\n    Ok(String::from(key_as_str))\n}\n\n#[allow(clippy::unnecessary_wraps)]\n#[inline(never)]\nfn non_str_uuid(key: PyUuidRef) -> Result<String, SerializeError> {\n    let mut buf = SmallFixedBuffer::new();\n    UUID::new(key).write_buf(&mut buf);\n    let key_as_str = str_from_slice!(buf.as_ptr(), buf.len());\n    Ok(String::from(key_as_str))\n}\n\n#[allow(clippy::unnecessary_wraps)]\n#[cold]\n#[inline(never)]\nfn non_str_float(key: *mut crate::ffi::PyObject) -> Result<String, SerializeError> {\n    let val = ffi!(PyFloat_AS_DOUBLE(key));\n    if !val.is_finite() {\n        Ok(String::from(\"null\"))\n    } else {\n        Ok(String::from(zmij::Buffer::new().format_finite(val)))\n    }\n}\n\n#[allow(clippy::unnecessary_wraps)]\n#[inline(never)]\nfn non_str_int(key: *mut crate::ffi::PyObject) -> Result<String, SerializeError> {\n    let ival = ffi!(PyLong_AsLongLong(key));\n    if ival == -1 && !ffi!(PyErr_Occurred()).is_null() {\n        cold_path!();\n        ffi!(PyErr_Clear());\n        let uval = ffi!(PyLong_AsUnsignedLongLong(key));\n        if uval == u64::MAX && !ffi!(PyErr_Occurred()).is_null() {\n            return Err(SerializeError::DictIntegerKey64Bit);\n        }\n        Ok(String::from(itoa::Buffer::new().format(uval)))\n    } else {\n        Ok(String::from(itoa::Buffer::new().format(ival)))\n    }\n}\n\n#[inline(never)]\nfn sort_dict_items(items: &mut SmallVec<[(&str, *mut crate::ffi::PyObject); 8]>) {\n    items.sort_unstable_by(|a, b| a.0.cmp(b.0));\n}\n\npub(crate) struct DictNonStrKey {\n    dict: PyDictRef,\n    state: SerializerState,\n    default: Option<NonNull<crate::ffi::PyObject>>,\n}\n\nimpl DictNonStrKey {\n    fn pyobject_to_string(\n        key: *mut crate::ffi::PyObject,\n        opts: crate::opt::Opt,\n    ) -> Result<String, SerializeError> {\n        unsafe {\n            match pyobject_to_obtype(key, opts) {\n                ObType::None => Ok(String::from(\"null\")),\n                ObType::Bool => {\n                    if unsafe { core::ptr::eq(key, TRUE) } {\n                        Ok(String::from(\"true\"))\n                    } else {\n                        Ok(String::from(\"false\"))\n                    }\n                }\n                ObType::Int => non_str_int(key),\n                ObType::Float => non_str_float(key),\n                ObType::Datetime => non_str_datetime(key, opts),\n                ObType::Date => non_str_date(key),\n                ObType::Time => non_str_time(key, opts),\n                ObType::Uuid => non_str_uuid(PyUuidRef::from_ptr_unchecked(key)),\n                ObType::Enum => {\n                    let value = ffi!(PyObject_GetAttr(key, VALUE_STR));\n                    debug_assert!(ffi!(Py_REFCNT(value)) >= 2);\n                    let ret = Self::pyobject_to_string(value, opts);\n                    ffi!(Py_DECREF(value));\n                    ret\n                }\n                ObType::Str => non_str_str(PyStrRef::from_ptr_unchecked(key)),\n                ObType::StrSubclass => {\n                    non_str_str_subclass(PyStrSubclassRef::from_ptr_unchecked(key))\n                }\n                ObType::Tuple\n                | ObType::NumpyScalar\n                | ObType::NumpyArray\n                | ObType::Dict\n                | ObType::List\n                | ObType::Dataclass\n                | ObType::Fragment\n                | ObType::Unknown => Err(SerializeError::DictKeyInvalidType),\n            }\n        }\n    }\n}\n\nimpl Serialize for DictNonStrKey {\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut pos = 0;\n        let mut next_key: *mut crate::ffi::PyObject = core::ptr::null_mut();\n        let mut next_value: *mut crate::ffi::PyObject = core::ptr::null_mut();\n\n        pydict_next!(\n            self.dict.as_ptr(),\n            &raw mut pos,\n            &raw mut next_key,\n            &raw mut next_value\n        );\n\n        let opts = self.state.opts() & NOT_PASSTHROUGH;\n\n        let len = self.dict.len();\n        assume!(len > 0);\n\n        let mut items: SmallVec<[(String, *mut crate::ffi::PyObject); 8]> =\n            SmallVec::with_capacity(len);\n\n        for _ in 0..len {\n            let key = next_key;\n            let value = next_value;\n\n            pydict_next!(\n                self.dict.as_ptr(),\n                &raw mut pos,\n                &raw mut next_key,\n                &raw mut next_value\n            );\n\n            match PyStrRef::from_ptr(key) {\n                Ok(pystr) => match pystr.as_str() {\n                    Some(uni) => {\n                        items.push((String::from(uni), value));\n                    }\n                    None => err!(SerializeError::InvalidStr),\n                },\n                Err(_) => match Self::pyobject_to_string(key, opts) {\n                    Ok(key_as_str) => items.push((key_as_str, value)),\n                    Err(err) => err!(err),\n                },\n            }\n        }\n\n        let mut items_as_str: SmallVec<[(&str, *mut crate::ffi::PyObject); 8]> =\n            SmallVec::with_capacity(len);\n        items\n            .iter()\n            .for_each(|(key, val)| items_as_str.push(((*key).as_str(), *val)));\n\n        if opt_enabled!(opts, SORT_KEYS) {\n            sort_dict_items(&mut items_as_str);\n        }\n\n        let mut map = serializer.serialize_map(None).unwrap();\n        for (key, val) in items_as_str.iter() {\n            let pyvalue = PyObjectSerializer::new(*val, self.state, self.default);\n            map.serialize_key(key).unwrap();\n            map.serialize_value(&pyvalue)?;\n        }\n        map.end()\n    }\n}\n"
  },
  {
    "path": "src/serialize/per_type/float.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2018-2026)\n\nuse crate::ffi::PyFloatRef;\nuse serde::ser::{Serialize, Serializer};\n\n#[repr(transparent)]\npub(crate) struct FloatSerializer {\n    ob: PyFloatRef,\n}\n\nimpl FloatSerializer {\n    pub fn new(ptr: PyFloatRef) -> Self {\n        FloatSerializer { ob: ptr }\n    }\n}\n\nimpl Serialize for FloatSerializer {\n    #[inline(always)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_f64(self.ob.value())\n    }\n}\n"
  },
  {
    "path": "src/serialize/per_type/fragment.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2018-2026)\n\nuse crate::ffi::{PyFragmentRef, PyFragmentRefError};\nuse crate::serialize::error::SerializeError;\n\nuse serde::ser::{Serialize, Serializer};\n\n#[repr(transparent)]\npub(crate) struct FragmentSerializer {\n    ob: PyFragmentRef,\n}\n\nimpl FragmentSerializer {\n    pub fn new(ob: PyFragmentRef) -> Self {\n        FragmentSerializer { ob: ob }\n    }\n}\n\nimpl Serialize for FragmentSerializer {\n    #[cold]\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        match self.ob.value() {\n            Ok(buffer) => serializer.serialize_bytes(buffer),\n            Err(PyFragmentRefError::InvalidStr) => err!(SerializeError::InvalidStr),\n            Err(PyFragmentRefError::InvalidFragment) => err!(SerializeError::InvalidFragment),\n        }\n    }\n}\n"
  },
  {
    "path": "src/serialize/per_type/int.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2018-2026)\n\nuse crate::ffi::PyIntRef;\nuse crate::opt::{Opt, STRICT_INTEGER};\nuse crate::serialize::error::SerializeError;\nuse serde::ser::{Serialize, Serializer};\n\n// https://tools.ietf.org/html/rfc7159#section-6\n// \"[-(2**53)+1, (2**53)-1]\"\nconst STRICT_INT_MIN: i64 = -9007199254740991;\nconst STRICT_INT_MAX: i64 = 9007199254740991;\n\npub(crate) struct IntSerializer {\n    ob: PyIntRef,\n    opts: Opt,\n}\n\nimpl IntSerializer {\n    pub fn new(ob: PyIntRef, opts: Opt) -> Self {\n        IntSerializer { ob: ob, opts: opts }\n    }\n}\n\nimpl Serialize for IntSerializer {\n    #[inline(always)]\n    #[cfg(feature = \"inline_int\")]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        unsafe {\n            match self.ob.kind() {\n                crate::ffi::PyIntKind::I32 => serializer.serialize_i32(self.ob.as_i32()),\n                crate::ffi::PyIntKind::U32 => serializer.serialize_u32(self.ob.as_u32()),\n                crate::ffi::PyIntKind::I64 => {\n                    let value = self\n                        .ob\n                        .as_i64()\n                        .map_err(|_| serde::ser::Error::custom(SerializeError::Integer64Bits))?;\n                    if opt_enabled!(self.opts, STRICT_INTEGER)\n                        && !(STRICT_INT_MIN..=STRICT_INT_MAX).contains(&value)\n                    {\n                        cold_path!();\n                        err!(SerializeError::Integer53Bits);\n                    }\n                    serializer.serialize_i64(value)\n                }\n                crate::ffi::PyIntKind::U64 => {\n                    let value = self\n                        .ob\n                        .as_u64()\n                        .map_err(|_| serde::ser::Error::custom(SerializeError::Integer64Bits))?;\n                    if opt_enabled!(self.opts, STRICT_INTEGER) && value > STRICT_INT_MAX as u64 {\n                        cold_path!();\n                        err!(SerializeError::Integer53Bits);\n                    }\n                    serializer.serialize_u64(value)\n                }\n            }\n        }\n    }\n\n    #[inline(always)]\n    #[cfg(not(feature = \"inline_int\"))]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        unsafe {\n            match self.ob.as_i64() {\n                Ok(value) => {\n                    if opt_enabled!(self.opts, STRICT_INTEGER)\n                        && !(STRICT_INT_MIN..=STRICT_INT_MAX).contains(&value)\n                    {\n                        cold_path!();\n                        err!(SerializeError::Integer53Bits);\n                    }\n                    serializer.serialize_i64(value)\n                }\n                Err(_) => match self.ob.as_u64() {\n                    Ok(value) => {\n                        if opt_enabled!(self.opts, STRICT_INTEGER) && value > STRICT_INT_MAX as u64\n                        {\n                            cold_path!();\n                            err!(SerializeError::Integer53Bits);\n                        }\n                        serializer.serialize_u64(value)\n                    }\n                    Err(_) => err!(SerializeError::Integer64Bits),\n                },\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/serialize/per_type/list.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2018-2026)\n\nuse crate::ffi::{\n    PyBoolRef, PyDictRef, PyFloatRef, PyFragmentRef, PyIntRef, PyListRef, PyStrRef,\n    PyStrSubclassRef, PyUuidRef,\n};\nuse crate::serialize::error::SerializeError;\nuse crate::serialize::obtype::{ObType, pyobject_to_obtype};\nuse crate::serialize::per_type::{\n    BoolSerializer, DataclassGenericSerializer, Date, DateTime, DefaultSerializer,\n    DictGenericSerializer, EnumSerializer, FloatSerializer, FragmentSerializer, IntSerializer,\n    NoneSerializer, NumpyScalar, NumpySerializer, StrSerializer, StrSubclassSerializer, Time, UUID,\n};\nuse crate::serialize::serializer::PyObjectSerializer;\nuse crate::serialize::state::SerializerState;\nuse crate::typeref::TUPLE_TYPE;\nuse crate::util::isize_to_usize;\n\nuse core::ptr::NonNull;\nuse serde::ser::{Serialize, SerializeSeq, Serializer};\n\npub(crate) struct ZeroListSerializer;\n\nimpl ZeroListSerializer {\n    pub const fn new() -> Self {\n        Self {}\n    }\n}\n\nimpl Serialize for ZeroListSerializer {\n    #[inline(always)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_bytes(b\"[]\")\n    }\n}\n\npub(crate) struct ListTupleSerializer {\n    data_ptr: *const *mut crate::ffi::PyObject,\n    state: SerializerState,\n    default: Option<NonNull<crate::ffi::PyObject>>,\n    len: usize,\n}\n\nimpl ListTupleSerializer {\n    pub fn from_list(\n        ob: PyListRef,\n        state: SerializerState,\n        default: Option<NonNull<crate::ffi::PyObject>>,\n    ) -> Self {\n        Self {\n            data_ptr: ob.data_ptr(),\n            len: ob.len(),\n            state: state.copy_for_recursive_call(),\n            default: default,\n        }\n    }\n\n    pub fn from_tuple(\n        ptr: *mut crate::ffi::PyObject,\n        state: SerializerState,\n        default: Option<NonNull<crate::ffi::PyObject>>,\n    ) -> Self {\n        debug_assert!(\n            is_type!(ob_type!(ptr), TUPLE_TYPE)\n                || is_subclass_by_flag!(tp_flags!(ob_type!(ptr)), Py_TPFLAGS_TUPLE_SUBCLASS)\n        );\n        let data_ptr = unsafe { (*ptr.cast::<crate::ffi::PyTupleObject>()).ob_item.as_ptr() };\n        let len = isize_to_usize(ffi!(Py_SIZE(ptr)));\n        Self {\n            data_ptr: data_ptr,\n            len: len,\n            state: state.copy_for_recursive_call(),\n            default: default,\n        }\n    }\n}\n\nimpl Serialize for ListTupleSerializer {\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        if self.state.recursion_limit() {\n            cold_path!();\n            err!(SerializeError::RecursionLimit)\n        }\n        debug_assert!(self.len >= 1);\n        let mut seq = serializer.serialize_seq(None).unwrap();\n        for idx in 0..self.len {\n            let value = unsafe { *((self.data_ptr).add(idx)) };\n            match pyobject_to_obtype(value, self.state.opts()) {\n                ObType::Str => {\n                    seq.serialize_element(&StrSerializer::new(unsafe {\n                        PyStrRef::from_ptr_unchecked(value)\n                    }))?;\n                }\n                ObType::StrSubclass => {\n                    seq.serialize_element(&StrSubclassSerializer::new(unsafe {\n                        PyStrSubclassRef::from_ptr_unchecked(value)\n                    }))?;\n                }\n                ObType::Int => {\n                    seq.serialize_element(&IntSerializer::new(\n                        unsafe { PyIntRef::from_ptr_unchecked(value) },\n                        self.state.opts(),\n                    ))?;\n                }\n                ObType::None => {\n                    seq.serialize_element(&NoneSerializer::new()).unwrap();\n                }\n                ObType::Float => {\n                    seq.serialize_element(&FloatSerializer::new(unsafe {\n                        PyFloatRef::from_ptr_unchecked(value)\n                    }))?;\n                }\n                ObType::Bool => {\n                    seq.serialize_element(&BoolSerializer::new(unsafe {\n                        PyBoolRef::from_ptr_unchecked(value)\n                    }))\n                    .unwrap();\n                }\n                ObType::Datetime => {\n                    seq.serialize_element(&DateTime::new(value, self.state.opts()))?;\n                }\n                ObType::Date => {\n                    seq.serialize_element(&Date::new(value))?;\n                }\n                ObType::Time => {\n                    seq.serialize_element(&Time::new(value, self.state.opts()))?;\n                }\n                ObType::Uuid => {\n                    seq.serialize_element(&UUID::new(unsafe {\n                        PyUuidRef::from_ptr_unchecked(value)\n                    }))\n                    .unwrap();\n                }\n                ObType::Dict => {\n                    let pyvalue = DictGenericSerializer::new(\n                        unsafe { PyDictRef::from_ptr_unchecked(value) },\n                        self.state,\n                        self.default,\n                    );\n                    seq.serialize_element(&pyvalue)?;\n                }\n                ObType::List => {\n                    if ffi!(Py_SIZE(value)) == 0 {\n                        seq.serialize_element(&ZeroListSerializer::new()).unwrap();\n                    } else {\n                        let pyvalue = ListTupleSerializer::from_list(\n                            unsafe { PyListRef::from_ptr_unchecked(value) },\n                            self.state,\n                            self.default,\n                        );\n                        seq.serialize_element(&pyvalue)?;\n                    }\n                }\n                ObType::Tuple => {\n                    if ffi!(Py_SIZE(value)) == 0 {\n                        seq.serialize_element(&ZeroListSerializer::new()).unwrap();\n                    } else {\n                        let pyvalue =\n                            ListTupleSerializer::from_tuple(value, self.state, self.default);\n                        seq.serialize_element(&pyvalue)?;\n                    }\n                }\n                ObType::Dataclass => {\n                    seq.serialize_element(&DataclassGenericSerializer::new(\n                        &PyObjectSerializer::new(value, self.state, self.default),\n                    ))?;\n                }\n                ObType::Enum => {\n                    seq.serialize_element(&EnumSerializer::new(&PyObjectSerializer::new(\n                        value,\n                        self.state,\n                        self.default,\n                    )))?;\n                }\n                ObType::NumpyArray => {\n                    seq.serialize_element(&NumpySerializer::new(&PyObjectSerializer::new(\n                        value,\n                        self.state,\n                        self.default,\n                    )))?;\n                }\n                ObType::NumpyScalar => {\n                    seq.serialize_element(&NumpyScalar::new(value, self.state.opts()))?;\n                }\n                ObType::Fragment => {\n                    seq.serialize_element(&FragmentSerializer::new(unsafe {\n                        PyFragmentRef::from_ptr_unchecked(value)\n                    }))?;\n                }\n                ObType::Unknown => {\n                    seq.serialize_element(&DefaultSerializer::new(&PyObjectSerializer::new(\n                        value,\n                        self.state,\n                        self.default,\n                    )))?;\n                }\n            }\n        }\n        seq.end()\n    }\n}\n"
  },
  {
    "path": "src/serialize/per_type/mod.rs",
    "content": "// SPDX-License-Identifier: (Apache-2.0 OR MIT)\n// Copyright ijl (2020-2025), Ben Sully (2021)\n\nmod dataclass;\nmod datetime;\nmod pybool;\n#[macro_use]\nmod datetimelike;\nmod default;\nmod dict;\nmod float;\nmod fragment;\nmod int;\nmod list;\nmod none;\nmod numpy;\nmod pyenum;\nmod unicode;\nmod uuid;\n\npub(crate) use dataclass::DataclassGenericSerializer;\npub(crate) use datetime::{Date, DateTime, Time};\npub(crate) use datetimelike::{DateTimeError, DateTimeLike, Offset};\npub(crate) use default::DefaultSerializer;\npub(crate) use dict::DictGenericSerializer;\npub(crate) use float::FloatSerializer;\npub(crate) use fragment::FragmentSerializer;\npub(crate) use int::IntSerializer;\npub(crate) use list::{ListTupleSerializer, ZeroListSerializer};\npub(crate) use none::NoneSerializer;\npub(crate) use numpy::{NumpyScalar, NumpySerializer, is_numpy_array, is_numpy_scalar};\npub(crate) use pybool::BoolSerializer;\npub(crate) use pyenum::EnumSerializer;\npub(crate) use unicode::{StrSerializer, StrSubclassSerializer};\npub(crate) use uuid::UUID;\n"
  },
  {
    "path": "src/serialize/per_type/none.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2018-2025)\n\nuse serde::ser::{Serialize, Serializer};\n\npub(crate) struct NoneSerializer;\n\nimpl NoneSerializer {\n    pub const fn new() -> Self {\n        Self {}\n    }\n}\n\nimpl Serialize for NoneSerializer {\n    #[inline]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_unit()\n    }\n}\n"
  },
  {
    "path": "src/serialize/per_type/numpy.rs",
    "content": "// SPDX-License-Identifier: (Apache-2.0 OR MIT)\n// Copyright ijl (2018-2026), Ben Sully (2021), Nazar Kostetskyi (2022), Aviram Hassan (2020-2021)\n\nuse crate::ffi::{\n    Py_intptr_t, Py_ssize_t, PyListRef, PyObject, PyStrRef, PyTupleRef, PyTypeObject,\n};\nuse crate::opt::Opt;\nuse crate::serialize::buffer::SmallFixedBuffer;\nuse crate::serialize::error::SerializeError;\nuse crate::serialize::per_type::{\n    DateTimeError, DateTimeLike, DefaultSerializer, Offset, ZeroListSerializer,\n};\nuse crate::serialize::serializer::PyObjectSerializer;\nuse crate::typeref::{ARRAY_STRUCT_STR, DESCR_STR, DTYPE_STR, NUMPY_TYPES, load_numpy_types};\nuse crate::util::isize_to_usize;\nuse core::ffi::{c_char, c_int, c_void};\nuse jiff::Timestamp;\nuse jiff::civil::DateTime;\nuse serde::ser::{self, Serialize, SerializeSeq, Serializer};\nuse std::fmt;\n\n#[repr(transparent)]\npub(crate) struct NumpySerializer<'a> {\n    previous: &'a PyObjectSerializer,\n}\n\nimpl<'a> NumpySerializer<'a> {\n    pub fn new(previous: &'a PyObjectSerializer) -> Self {\n        Self { previous: previous }\n    }\n}\n\nimpl Serialize for NumpySerializer<'_> {\n    #[cold]\n    #[inline(never)]\n    #[cfg_attr(feature = \"optimize\", optimize(size))]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        match NumpyArray::new(self.previous.ptr, self.previous.state.opts()) {\n            Ok(val) => val.serialize(serializer),\n            Err(PyArrayError::Malformed) => err!(SerializeError::NumpyMalformed),\n            Err(PyArrayError::NotContiguous | PyArrayError::UnsupportedDataType)\n                if self.previous.default.is_some() =>\n            {\n                DefaultSerializer::new(self.previous).serialize(serializer)\n            }\n            Err(PyArrayError::NotContiguous) => {\n                err!(SerializeError::NumpyNotCContiguous)\n            }\n            Err(PyArrayError::NotNativeEndian) => {\n                err!(SerializeError::NumpyNotNativeEndian)\n            }\n            Err(PyArrayError::UnsupportedDataType) => {\n                err!(SerializeError::NumpyUnsupportedDatatype)\n            }\n        }\n    }\n}\n\nmacro_rules! slice {\n    ($ptr:expr, $size:expr) => {\n        unsafe { core::slice::from_raw_parts($ptr, $size) }\n    };\n}\n\n#[cold]\npub(crate) fn is_numpy_scalar(ob_type: *mut PyTypeObject) -> bool {\n    let numpy_types = unsafe { NUMPY_TYPES.get_or_init(load_numpy_types) };\n    if numpy_types.is_none() {\n        false\n    } else {\n        let scalar_types = unsafe { numpy_types.unwrap().as_ref() };\n        core::ptr::eq(ob_type, scalar_types.float64)\n            || core::ptr::eq(ob_type, scalar_types.float32)\n            || core::ptr::eq(ob_type, scalar_types.float16)\n            || core::ptr::eq(ob_type, scalar_types.int64)\n            || core::ptr::eq(ob_type, scalar_types.int16)\n            || core::ptr::eq(ob_type, scalar_types.int32)\n            || core::ptr::eq(ob_type, scalar_types.int8)\n            || core::ptr::eq(ob_type, scalar_types.uint64)\n            || core::ptr::eq(ob_type, scalar_types.uint32)\n            || core::ptr::eq(ob_type, scalar_types.uint8)\n            || core::ptr::eq(ob_type, scalar_types.uint16)\n            || core::ptr::eq(ob_type, scalar_types.bool_)\n            || core::ptr::eq(ob_type, scalar_types.datetime64)\n    }\n}\n\n#[cold]\npub(crate) fn is_numpy_array(ob_type: *mut PyTypeObject) -> bool {\n    let numpy_types = unsafe { NUMPY_TYPES.get_or_init(load_numpy_types) };\n    if numpy_types.is_none() {\n        false\n    } else {\n        let scalar_types = unsafe { numpy_types.unwrap().as_ref() };\n        unsafe { core::ptr::eq(ob_type, scalar_types.array) }\n    }\n}\n\n#[repr(C)]\npub(crate) struct PyCapsule {\n    pub ob_refcnt: Py_ssize_t,\n    pub ob_type: *mut PyTypeObject,\n    pub pointer: *mut c_void,\n    pub name: *const c_char,\n    pub context: *mut c_void,\n    pub destructor: *mut c_void, // should be typedef void (*PyCapsule_Destructor)(PyObject *);\n}\n\n// https://docs.scipy.org/doc/numpy/reference/arrays.interface.html#c.__array_struct__\n\nconst NPY_ARRAY_C_CONTIGUOUS: c_int = 0x1;\nconst NPY_ARRAY_NOTSWAPPED: c_int = 0x200;\n\n#[repr(C)]\npub(crate) struct PyArrayInterface {\n    pub two: c_int,\n    pub nd: c_int,\n    pub typekind: c_char,\n    pub itemsize: c_int,\n    pub flags: c_int,\n    pub shape: *mut Py_intptr_t,\n    pub strides: *mut Py_intptr_t,\n    pub data: *mut c_void,\n    pub descr: *mut PyObject,\n}\n\n#[derive(Clone, Copy)]\npub(crate) enum ItemType {\n    BOOL,\n    DATETIME64(NumpyDatetimeUnit),\n    F16,\n    F32,\n    F64,\n    I8,\n    I16,\n    I32,\n    I64,\n    U8,\n    U16,\n    U32,\n    U64,\n}\n\nimpl ItemType {\n    fn find(array: *mut PyArrayInterface, ptr: *mut PyObject) -> Option<ItemType> {\n        match unsafe { ((*array).typekind, (*array).itemsize) } {\n            (098, 1) => Some(ItemType::BOOL),\n            (077, 8) => {\n                let unit = NumpyDatetimeUnit::from_pyobject(ptr);\n                Some(ItemType::DATETIME64(unit))\n            }\n            (102, 2) => Some(ItemType::F16),\n            (102, 4) => Some(ItemType::F32),\n            (102, 8) => Some(ItemType::F64),\n            (105, 1) => Some(ItemType::I8),\n            (105, 2) => Some(ItemType::I16),\n            (105, 4) => Some(ItemType::I32),\n            (105, 8) => Some(ItemType::I64),\n            (117, 1) => Some(ItemType::U8),\n            (117, 2) => Some(ItemType::U16),\n            (117, 4) => Some(ItemType::U32),\n            (117, 8) => Some(ItemType::U64),\n            _ => None,\n        }\n    }\n}\n\npub(crate) enum PyArrayError {\n    Malformed,\n    NotContiguous,\n    NotNativeEndian,\n    UnsupportedDataType,\n}\n\n// >>> arr = numpy.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], numpy.int32)\n// >>> arr.ndim\n// 3\n// >>> arr.shape\n// (2, 2, 2)\n// >>> arr.strides\n// (16, 8, 4)\npub(crate) struct NumpyArray {\n    array: *mut PyArrayInterface,\n    position: Vec<isize>,\n    children: Vec<NumpyArray>,\n    depth: usize,\n    capsule: *mut PyCapsule,\n    kind: ItemType,\n    opts: Opt,\n}\n\nimpl NumpyArray {\n    #[cold]\n    #[inline(never)]\n    #[cfg_attr(feature = \"optimize\", optimize(size))]\n    pub fn new(ptr: *mut PyObject, opts: Opt) -> Result<Self, PyArrayError> {\n        let capsule = ffi!(PyObject_GetAttr(ptr, ARRAY_STRUCT_STR));\n        debug_assert!(!capsule.is_null());\n        let array = unsafe {\n            (*capsule.cast::<PyCapsule>())\n                .pointer\n                .cast::<PyArrayInterface>()\n        };\n        debug_assert!(!array.is_null());\n        if unsafe { (*array).two != 2 } {\n            ffi!(Py_DECREF(capsule));\n            Err(PyArrayError::Malformed)\n        } else if unsafe { (*array).flags } & NPY_ARRAY_C_CONTIGUOUS != NPY_ARRAY_C_CONTIGUOUS {\n            ffi!(Py_DECREF(capsule));\n            Err(PyArrayError::NotContiguous)\n        } else if unsafe { (*array).flags } & NPY_ARRAY_NOTSWAPPED != NPY_ARRAY_NOTSWAPPED {\n            ffi!(Py_DECREF(capsule));\n            Err(PyArrayError::NotNativeEndian)\n        } else {\n            debug_assert!(unsafe { (*array).nd >= 0 });\n            let num_dimensions = unsafe { (*array).nd.cast_unsigned() as usize };\n            if num_dimensions == 0 {\n                ffi!(Py_DECREF(capsule));\n                return Err(PyArrayError::UnsupportedDataType);\n            }\n            match ItemType::find(array, ptr) {\n                None => {\n                    ffi!(Py_DECREF(capsule));\n                    Err(PyArrayError::UnsupportedDataType)\n                }\n                Some(kind) => {\n                    let mut pyarray = NumpyArray {\n                        array: array,\n                        position: vec![0; num_dimensions],\n                        children: Vec::with_capacity(num_dimensions),\n                        depth: 0,\n                        capsule: capsule.cast::<PyCapsule>(),\n                        kind: kind,\n                        opts,\n                    };\n                    if pyarray.dimensions() > 1 {\n                        pyarray.build();\n                    }\n                    Ok(pyarray)\n                }\n            }\n        }\n    }\n\n    #[cfg_attr(feature = \"optimize\", optimize(size))]\n    fn child_from_parent(&self, position: Vec<isize>, num_children: usize) -> Self {\n        let mut arr = NumpyArray {\n            array: self.array,\n            position: position,\n            children: Vec::with_capacity(num_children),\n            depth: self.depth + 1,\n            capsule: self.capsule,\n            kind: self.kind,\n            opts: self.opts,\n        };\n        arr.build();\n        arr\n    }\n\n    #[cfg_attr(feature = \"optimize\", optimize(size))]\n    fn build(&mut self) {\n        if self.depth < self.dimensions() - 1 {\n            for i in 0..self.shape()[self.depth] {\n                let mut position: Vec<isize> = self.position.clone();\n                position[self.depth] = i;\n                let num_children: usize = if self.depth < self.dimensions() - 2 {\n                    isize_to_usize(self.shape()[self.depth + 1])\n                } else {\n                    0\n                };\n                self.children\n                    .push(self.child_from_parent(position, num_children));\n            }\n        }\n    }\n\n    #[inline(always)]\n    fn data(&self) -> *const c_void {\n        let offset = self\n            .strides()\n            .iter()\n            .zip(self.position.iter().copied())\n            .take(self.depth)\n            .map(|(a, b)| a * b)\n            .sum::<isize>();\n        unsafe { (*self.array).data.offset(offset) }\n    }\n\n    fn num_items(&self) -> usize {\n        isize_to_usize(self.shape()[self.shape().len() - 1])\n    }\n\n    fn dimensions(&self) -> usize {\n        unsafe { (*self.array).nd.cast_unsigned() as usize }\n    }\n\n    fn shape(&self) -> &[isize] {\n        slice!((*self.array).shape.cast_const(), self.dimensions())\n    }\n\n    fn strides(&self) -> &[isize] {\n        slice!((*self.array).strides.cast_const(), self.dimensions())\n    }\n}\n\nimpl Drop for NumpyArray {\n    fn drop(&mut self) {\n        if self.depth == 0 {\n            ffi!(Py_DECREF(self.array.cast::<PyObject>()));\n            ffi!(Py_DECREF(self.capsule.cast::<PyObject>()));\n        }\n    }\n}\n\nimpl Serialize for NumpyArray {\n    #[cold]\n    #[inline(never)]\n    #[cfg_attr(feature = \"optimize\", optimize(size))]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        if !(self.depth >= self.dimensions() || self.shape()[self.depth] != 0) {\n            cold_path!();\n            ZeroListSerializer::new().serialize(serializer)\n        } else if !self.children.is_empty() {\n            cold_path!();\n            let mut seq = serializer.serialize_seq(None).unwrap();\n            for child in &self.children {\n                seq.serialize_element(child).unwrap();\n            }\n            seq.end()\n        } else {\n            match self.kind {\n                ItemType::F64 => {\n                    NumpyF64Array::new(slice!(self.data().cast::<f64>(), self.num_items()))\n                        .serialize(serializer)\n                }\n                ItemType::F32 => {\n                    NumpyF32Array::new(slice!(self.data().cast::<f32>(), self.num_items()))\n                        .serialize(serializer)\n                }\n                ItemType::F16 => {\n                    NumpyF16Array::new(slice!(self.data().cast::<u16>(), self.num_items()))\n                        .serialize(serializer)\n                }\n                ItemType::U64 => {\n                    NumpyU64Array::new(slice!(self.data().cast::<u64>(), self.num_items()))\n                        .serialize(serializer)\n                }\n                ItemType::U32 => {\n                    NumpyU32Array::new(slice!(self.data().cast::<u32>(), self.num_items()))\n                        .serialize(serializer)\n                }\n                ItemType::U16 => {\n                    NumpyU16Array::new(slice!(self.data().cast::<u16>(), self.num_items()))\n                        .serialize(serializer)\n                }\n                ItemType::U8 => {\n                    NumpyU8Array::new(slice!(self.data().cast::<u8>(), self.num_items()))\n                        .serialize(serializer)\n                }\n                ItemType::I64 => {\n                    NumpyI64Array::new(slice!(self.data().cast::<i64>(), self.num_items()))\n                        .serialize(serializer)\n                }\n                ItemType::I32 => {\n                    NumpyI32Array::new(slice!(self.data().cast::<i32>(), self.num_items()))\n                        .serialize(serializer)\n                }\n                ItemType::I16 => {\n                    NumpyI16Array::new(slice!(self.data().cast::<i16>(), self.num_items()))\n                        .serialize(serializer)\n                }\n                ItemType::I8 => {\n                    NumpyI8Array::new(slice!(self.data().cast::<i8>(), self.num_items()))\n                        .serialize(serializer)\n                }\n                ItemType::BOOL => {\n                    NumpyBoolArray::new(slice!(self.data().cast::<u8>(), self.num_items()))\n                        .serialize(serializer)\n                }\n                ItemType::DATETIME64(unit) => NumpyDatetime64Array::new(\n                    slice!(self.data().cast::<i64>(), self.num_items()),\n                    unit,\n                    self.opts,\n                )\n                .serialize(serializer),\n            }\n        }\n    }\n}\n\n#[repr(transparent)]\nstruct NumpyF64Array<'a> {\n    data: &'a [f64],\n}\n\nimpl<'a> NumpyF64Array<'a> {\n    fn new(data: &'a [f64]) -> Self {\n        Self { data }\n    }\n}\n\nimpl Serialize for NumpyF64Array<'_> {\n    #[cold]\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut seq = serializer.serialize_seq(None).unwrap();\n        for &each in self.data.iter() {\n            seq.serialize_element(&DataTypeF64 { obj: each }).unwrap();\n        }\n        seq.end()\n    }\n}\n\n#[repr(transparent)]\npub(crate) struct DataTypeF64 {\n    obj: f64,\n}\n\nimpl Serialize for DataTypeF64 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_f64(self.obj)\n    }\n}\n\n#[repr(transparent)]\nstruct NumpyF32Array<'a> {\n    data: &'a [f32],\n}\n\nimpl<'a> NumpyF32Array<'a> {\n    fn new(data: &'a [f32]) -> Self {\n        Self { data }\n    }\n}\n\nimpl Serialize for NumpyF32Array<'_> {\n    #[cold]\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut seq = serializer.serialize_seq(None).unwrap();\n        for &each in self.data.iter() {\n            seq.serialize_element(&DataTypeF32 { obj: each }).unwrap();\n        }\n        seq.end()\n    }\n}\n\n#[repr(transparent)]\nstruct DataTypeF32 {\n    obj: f32,\n}\n\nimpl Serialize for DataTypeF32 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_f32(self.obj)\n    }\n}\n\n#[repr(transparent)]\nstruct NumpyF16Array<'a> {\n    data: &'a [u16],\n}\n\nimpl<'a> NumpyF16Array<'a> {\n    fn new(data: &'a [u16]) -> Self {\n        Self { data }\n    }\n}\n\nimpl Serialize for NumpyF16Array<'_> {\n    #[cold]\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut seq = serializer.serialize_seq(None).unwrap();\n        for &each in self.data.iter() {\n            seq.serialize_element(&DataTypeF16 { obj: each }).unwrap();\n        }\n        seq.end()\n    }\n}\n\n#[repr(transparent)]\nstruct DataTypeF16 {\n    obj: u16,\n}\n\nimpl Serialize for DataTypeF16 {\n    #[cold]\n    #[cfg_attr(feature = \"optimize\", optimize(size))]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let as_f16 = half::f16::from_bits(self.obj);\n        serializer.serialize_f32(as_f16.to_f32())\n    }\n}\n\n#[repr(transparent)]\nstruct NumpyU64Array<'a> {\n    data: &'a [u64],\n}\n\nimpl<'a> NumpyU64Array<'a> {\n    fn new(data: &'a [u64]) -> Self {\n        Self { data }\n    }\n}\n\nimpl Serialize for NumpyU64Array<'_> {\n    #[cold]\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut seq = serializer.serialize_seq(None).unwrap();\n        for &each in self.data.iter() {\n            seq.serialize_element(&DataTypeU64 { obj: each }).unwrap();\n        }\n        seq.end()\n    }\n}\n\n#[repr(transparent)]\npub(crate) struct DataTypeU64 {\n    obj: u64,\n}\n\nimpl Serialize for DataTypeU64 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_u64(self.obj)\n    }\n}\n\n#[repr(transparent)]\nstruct NumpyU32Array<'a> {\n    data: &'a [u32],\n}\n\nimpl<'a> NumpyU32Array<'a> {\n    fn new(data: &'a [u32]) -> Self {\n        Self { data }\n    }\n}\n\nimpl Serialize for NumpyU32Array<'_> {\n    #[cold]\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut seq = serializer.serialize_seq(None).unwrap();\n        for &each in self.data.iter() {\n            seq.serialize_element(&DataTypeU32 { obj: each }).unwrap();\n        }\n        seq.end()\n    }\n}\n\n#[repr(transparent)]\npub(crate) struct DataTypeU32 {\n    obj: u32,\n}\n\nimpl Serialize for DataTypeU32 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_u32(self.obj)\n    }\n}\n\n#[repr(transparent)]\nstruct NumpyU16Array<'a> {\n    data: &'a [u16],\n}\n\nimpl<'a> NumpyU16Array<'a> {\n    fn new(data: &'a [u16]) -> Self {\n        Self { data }\n    }\n}\n\nimpl Serialize for NumpyU16Array<'_> {\n    #[cold]\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut seq = serializer.serialize_seq(None).unwrap();\n        for &each in self.data.iter() {\n            seq.serialize_element(&DataTypeU16 { obj: each }).unwrap();\n        }\n        seq.end()\n    }\n}\n\n#[repr(transparent)]\npub(crate) struct DataTypeU16 {\n    obj: u16,\n}\n\nimpl Serialize for DataTypeU16 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_u32(u32::from(self.obj))\n    }\n}\n\n#[repr(transparent)]\nstruct NumpyI64Array<'a> {\n    data: &'a [i64],\n}\n\nimpl<'a> NumpyI64Array<'a> {\n    fn new(data: &'a [i64]) -> Self {\n        Self { data }\n    }\n}\n\nimpl Serialize for NumpyI64Array<'_> {\n    #[cold]\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut seq = serializer.serialize_seq(None).unwrap();\n        for &each in self.data.iter() {\n            seq.serialize_element(&DataTypeI64 { obj: each }).unwrap();\n        }\n        seq.end()\n    }\n}\n\n#[repr(transparent)]\npub(crate) struct DataTypeI64 {\n    obj: i64,\n}\n\nimpl Serialize for DataTypeI64 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_i64(self.obj)\n    }\n}\n\n#[repr(transparent)]\nstruct NumpyI32Array<'a> {\n    data: &'a [i32],\n}\n\nimpl<'a> NumpyI32Array<'a> {\n    fn new(data: &'a [i32]) -> Self {\n        Self { data }\n    }\n}\n\nimpl Serialize for NumpyI32Array<'_> {\n    #[cold]\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut seq = serializer.serialize_seq(None).unwrap();\n        for &each in self.data.iter() {\n            seq.serialize_element(&DataTypeI32 { obj: each }).unwrap();\n        }\n        seq.end()\n    }\n}\n\n#[repr(transparent)]\npub(crate) struct DataTypeI32 {\n    obj: i32,\n}\n\nimpl Serialize for DataTypeI32 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_i32(self.obj)\n    }\n}\n\n#[repr(transparent)]\nstruct NumpyI16Array<'a> {\n    data: &'a [i16],\n}\n\nimpl<'a> NumpyI16Array<'a> {\n    fn new(data: &'a [i16]) -> Self {\n        Self { data }\n    }\n}\n\nimpl Serialize for NumpyI16Array<'_> {\n    #[cold]\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut seq = serializer.serialize_seq(None).unwrap();\n        for &each in self.data.iter() {\n            seq.serialize_element(&DataTypeI16 { obj: each }).unwrap();\n        }\n        seq.end()\n    }\n}\n\n#[repr(transparent)]\npub(crate) struct DataTypeI16 {\n    obj: i16,\n}\n\nimpl Serialize for DataTypeI16 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_i32(i32::from(self.obj))\n    }\n}\n\n#[repr(transparent)]\nstruct NumpyI8Array<'a> {\n    data: &'a [i8],\n}\n\nimpl<'a> NumpyI8Array<'a> {\n    fn new(data: &'a [i8]) -> Self {\n        Self { data }\n    }\n}\n\nimpl Serialize for NumpyI8Array<'_> {\n    #[cold]\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut seq = serializer.serialize_seq(None).unwrap();\n        for &each in self.data.iter() {\n            seq.serialize_element(&DataTypeI8 { obj: each }).unwrap();\n        }\n        seq.end()\n    }\n}\n\n#[repr(transparent)]\npub(crate) struct DataTypeI8 {\n    obj: i8,\n}\n\nimpl Serialize for DataTypeI8 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_i32(i32::from(self.obj))\n    }\n}\n\n#[repr(transparent)]\nstruct NumpyU8Array<'a> {\n    data: &'a [u8],\n}\n\nimpl<'a> NumpyU8Array<'a> {\n    fn new(data: &'a [u8]) -> Self {\n        Self { data }\n    }\n}\n\nimpl Serialize for NumpyU8Array<'_> {\n    #[cold]\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut seq = serializer.serialize_seq(None).unwrap();\n        for &each in self.data.iter() {\n            seq.serialize_element(&DataTypeU8 { obj: each }).unwrap();\n        }\n        seq.end()\n    }\n}\n\n#[repr(transparent)]\npub(crate) struct DataTypeU8 {\n    obj: u8,\n}\n\nimpl Serialize for DataTypeU8 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_u32(u32::from(self.obj))\n    }\n}\n\n#[repr(transparent)]\nstruct NumpyBoolArray<'a> {\n    data: &'a [u8],\n}\n\nimpl<'a> NumpyBoolArray<'a> {\n    fn new(data: &'a [u8]) -> Self {\n        Self { data }\n    }\n}\n\nimpl Serialize for NumpyBoolArray<'_> {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut seq = serializer.serialize_seq(None).unwrap();\n        for &each in self.data.iter() {\n            seq.serialize_element(&DataTypeBool { obj: each }).unwrap();\n        }\n        seq.end()\n    }\n}\n\n#[repr(transparent)]\npub(crate) struct DataTypeBool {\n    obj: u8,\n}\n\nimpl Serialize for DataTypeBool {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_bool(self.obj == 1)\n    }\n}\n\npub(crate) struct NumpyScalar {\n    ptr: *mut PyObject,\n    opts: Opt,\n}\n\nimpl NumpyScalar {\n    pub fn new(ptr: *mut PyObject, opts: Opt) -> Self {\n        NumpyScalar { ptr, opts }\n    }\n}\n\nimpl Serialize for NumpyScalar {\n    #[cold]\n    #[inline(never)]\n    #[cfg_attr(feature = \"optimize\", optimize(size))]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        unsafe {\n            let ob_type = ob_type!(self.ptr);\n            let scalar_types =\n                unsafe { NUMPY_TYPES.get_or_init(load_numpy_types).unwrap().as_ref() };\n            if core::ptr::eq(ob_type, scalar_types.float64) {\n                (*(self.ptr.cast::<NumpyFloat64>())).serialize(serializer)\n            } else if core::ptr::eq(ob_type, scalar_types.float32) {\n                (*(self.ptr.cast::<NumpyFloat32>())).serialize(serializer)\n            } else if core::ptr::eq(ob_type, scalar_types.float16) {\n                (*(self.ptr.cast::<NumpyFloat16>())).serialize(serializer)\n            } else if core::ptr::eq(ob_type, scalar_types.int64) {\n                (*(self.ptr.cast::<NumpyInt64>())).serialize(serializer)\n            } else if core::ptr::eq(ob_type, scalar_types.int32) {\n                (*(self.ptr.cast::<NumpyInt32>())).serialize(serializer)\n            } else if core::ptr::eq(ob_type, scalar_types.int16) {\n                (*(self.ptr.cast::<NumpyInt16>())).serialize(serializer)\n            } else if core::ptr::eq(ob_type, scalar_types.int8) {\n                (*(self.ptr.cast::<NumpyInt8>())).serialize(serializer)\n            } else if core::ptr::eq(ob_type, scalar_types.uint64) {\n                (*(self.ptr.cast::<NumpyUint64>())).serialize(serializer)\n            } else if core::ptr::eq(ob_type, scalar_types.uint32) {\n                (*(self.ptr.cast::<NumpyUint32>())).serialize(serializer)\n            } else if core::ptr::eq(ob_type, scalar_types.uint16) {\n                (*(self.ptr.cast::<NumpyUint16>())).serialize(serializer)\n            } else if core::ptr::eq(ob_type, scalar_types.uint8) {\n                (*(self.ptr.cast::<NumpyUint8>())).serialize(serializer)\n            } else if core::ptr::eq(ob_type, scalar_types.bool_) {\n                (*(self.ptr.cast::<NumpyBool>())).serialize(serializer)\n            } else if core::ptr::eq(ob_type, scalar_types.datetime64) {\n                let unit = NumpyDatetimeUnit::from_pyobject(self.ptr);\n                let obj = &*self.ptr.cast::<NumpyDatetime64>();\n                let dt = unit\n                    .datetime(obj.value, self.opts)\n                    .map_err(NumpyDateTimeError::into_serde_err)?;\n                dt.serialize(serializer)\n            } else {\n                unreachable!()\n            }\n        }\n    }\n}\n\n#[repr(C)]\npub(crate) struct NumpyInt8 {\n    ob_refcnt: Py_ssize_t,\n    ob_type: *mut PyTypeObject,\n    value: i8,\n}\n\nimpl Serialize for NumpyInt8 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_i32(i32::from(self.value))\n    }\n}\n\n#[repr(C)]\npub(crate) struct NumpyInt16 {\n    pub ob_refcnt: Py_ssize_t,\n    pub ob_type: *mut PyTypeObject,\n    pub value: i16,\n}\n\nimpl Serialize for NumpyInt16 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_i32(i32::from(self.value))\n    }\n}\n\n#[repr(C)]\npub(crate) struct NumpyInt32 {\n    ob_refcnt: Py_ssize_t,\n    ob_type: *mut PyTypeObject,\n    value: i32,\n}\n\nimpl Serialize for NumpyInt32 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_i32(self.value)\n    }\n}\n\n#[repr(C)]\npub(crate) struct NumpyInt64 {\n    ob_refcnt: Py_ssize_t,\n    ob_type: *mut PyTypeObject,\n    value: i64,\n}\n\nimpl Serialize for NumpyInt64 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_i64(self.value)\n    }\n}\n\n#[repr(C)]\npub(crate) struct NumpyUint8 {\n    ob_refcnt: Py_ssize_t,\n    ob_type: *mut PyTypeObject,\n    value: u8,\n}\n\nimpl Serialize for NumpyUint8 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_u32(u32::from(self.value))\n    }\n}\n\n#[repr(C)]\npub(crate) struct NumpyUint16 {\n    pub ob_refcnt: Py_ssize_t,\n    pub ob_type: *mut PyTypeObject,\n    pub value: u16,\n}\n\nimpl Serialize for NumpyUint16 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_u32(u32::from(self.value))\n    }\n}\n\n#[repr(C)]\npub(crate) struct NumpyUint32 {\n    ob_refcnt: Py_ssize_t,\n    ob_type: *mut PyTypeObject,\n    value: u32,\n}\n\nimpl Serialize for NumpyUint32 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_u32(self.value)\n    }\n}\n\n#[repr(C)]\npub(crate) struct NumpyUint64 {\n    ob_refcnt: Py_ssize_t,\n    ob_type: *mut PyTypeObject,\n    value: u64,\n}\n\nimpl Serialize for NumpyUint64 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_u64(self.value)\n    }\n}\n\n#[repr(C)]\npub(crate) struct NumpyFloat16 {\n    ob_refcnt: Py_ssize_t,\n    ob_type: *mut PyTypeObject,\n    value: u16,\n}\n\nimpl Serialize for NumpyFloat16 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let as_f16 = half::f16::from_bits(self.value);\n        serializer.serialize_f32(as_f16.to_f32())\n    }\n}\n\n#[repr(C)]\npub(crate) struct NumpyFloat32 {\n    ob_refcnt: Py_ssize_t,\n    ob_type: *mut PyTypeObject,\n    value: f32,\n}\n\nimpl Serialize for NumpyFloat32 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_f32(self.value)\n    }\n}\n\n#[repr(C)]\npub(crate) struct NumpyFloat64 {\n    ob_refcnt: Py_ssize_t,\n    ob_type: *mut PyTypeObject,\n    value: f64,\n}\n\nimpl Serialize for NumpyFloat64 {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_f64(self.value)\n    }\n}\n\n#[repr(C)]\npub(crate) struct NumpyBool {\n    ob_refcnt: Py_ssize_t,\n    ob_type: *mut PyTypeObject,\n    value: bool,\n}\n\nimpl Serialize for NumpyBool {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_bool(self.value)\n    }\n}\n\n/// This mimicks the units supported by numpy's datetime64 type.\n///\n/// See\n/// https://github.com/numpy/numpy/blob/fc8e3bbe419748ac5c6b7f3d0845e4bafa74644b/numpy/core/include/numpy/ndarraytypes.h#L268-L282.\n#[derive(Clone, Copy)]\npub(crate) enum NumpyDatetimeUnit {\n    NaT,\n    Years,\n    Months,\n    Weeks,\n    Days,\n    Hours,\n    Minutes,\n    Seconds,\n    Milliseconds,\n    Microseconds,\n    Nanoseconds,\n    Picoseconds,\n    Femtoseconds,\n    Attoseconds,\n    Generic,\n}\n\nimpl fmt::Display for NumpyDatetimeUnit {\n    #[cold]\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        let unit = match self {\n            Self::NaT => \"NaT\",\n            Self::Years => \"years\",\n            Self::Months => \"months\",\n            Self::Weeks => \"weeks\",\n            Self::Days => \"days\",\n            Self::Hours => \"hours\",\n            Self::Minutes => \"minutes\",\n            Self::Seconds => \"seconds\",\n            Self::Milliseconds => \"milliseconds\",\n            Self::Microseconds => \"microseconds\",\n            Self::Nanoseconds => \"nanoseconds\",\n            Self::Picoseconds => \"picoseconds\",\n            Self::Femtoseconds => \"femtoseconds\",\n            Self::Attoseconds => \"attoseconds\",\n            Self::Generic => \"generic\",\n        };\n        write!(f, \"{unit}\")\n    }\n}\n\n#[derive(Clone, Copy)]\nenum NumpyDateTimeError {\n    UnsupportedUnit(NumpyDatetimeUnit),\n    Unrepresentable { unit: NumpyDatetimeUnit, val: i64 },\n}\n\nimpl NumpyDateTimeError {\n    #[cold]\n    fn into_serde_err<T: ser::Error>(self) -> T {\n        let err = match self {\n            Self::UnsupportedUnit(unit) => format!(\"unsupported numpy.datetime64 unit: {unit}\"),\n            Self::Unrepresentable { unit, val } => {\n                format!(\"unrepresentable numpy.datetime64: {val} {unit}\")\n            }\n        };\n        ser::Error::custom(err)\n    }\n}\n\nmacro_rules! to_jiff_datetime {\n    ($timestamp:expr, $self:expr, $val:expr) => {\n        Ok(\n            ($timestamp.map_err(|_| NumpyDateTimeError::Unrepresentable {\n                unit: $self,\n                val: $val,\n            })?)\n            .to_zoned(jiff::tz::TimeZone::UTC)\n            .datetime(),\n        )\n    };\n}\n\nimpl NumpyDatetimeUnit {\n    /// Create a `NumpyDatetimeUnit` from a pointer to a Python object holding a\n    /// numpy array.\n    ///\n    /// This function must only be called with pointers to numpy arrays.\n    ///\n    /// We need to look inside the `obj.dtype.descr` attribute of the Python\n    /// object rather than using the `descr` field of the `__array_struct__`\n    /// because that field isn't populated for datetime64 arrays; see\n    /// https://github.com/numpy/numpy/issues/5350.\n    #[cold]\n    #[cfg_attr(feature = \"optimize\", optimize(size))]\n    fn from_pyobject(ptr: *mut PyObject) -> Self {\n        let dtype = ffi!(PyObject_GetAttr(ptr, DTYPE_STR));\n        let descr = ffi!(PyObject_GetAttr(dtype, DESCR_STR));\n        let el0 = unsafe { PyListRef::from_ptr_unchecked(descr).get(0) };\n        let descr_str = unsafe { PyTupleRef::from_ptr_unchecked(el0).get(1) };\n        match PyStrRef::from_ptr(descr_str) {\n            Ok(uni) => {\n                match uni.as_str() {\n                    Some(as_str) => {\n                        if as_str.len() < 5 {\n                            return Self::NaT;\n                        }\n                        // unit descriptions are found at\n                        // https://github.com/numpy/numpy/blob/b235f9e701e14ed6f6f6dcba885f7986a833743f/numpy/core/src/multiarray/datetime.c#L79-L96.\n                        let ret = match &as_str[4..as_str.len() - 1] {\n                            \"Y\" => Self::Years,\n                            \"M\" => Self::Months,\n                            \"W\" => Self::Weeks,\n                            \"D\" => Self::Days,\n                            \"h\" => Self::Hours,\n                            \"m\" => Self::Minutes,\n                            \"s\" => Self::Seconds,\n                            \"ms\" => Self::Milliseconds,\n                            \"us\" => Self::Microseconds,\n                            \"ns\" => Self::Nanoseconds,\n                            \"ps\" => Self::Picoseconds,\n                            \"fs\" => Self::Femtoseconds,\n                            \"as\" => Self::Attoseconds,\n                            \"generic\" => Self::Generic,\n                            _ => unreachable!(),\n                        };\n                        ffi!(Py_DECREF(dtype));\n                        ffi!(Py_DECREF(descr));\n                        ret\n                    }\n                    None => Self::NaT,\n                }\n            }\n            Err(_) => Self::NaT,\n        }\n    }\n\n    /// Return a `NumpyDatetime64Repr` for a value in array with this unit.\n    ///\n    /// Returns an `Err(NumpyDateTimeError)` if the value is invalid for this unit.\n    #[cold]\n    #[cfg_attr(feature = \"optimize\", optimize(size))]\n    fn datetime(self, val: i64, opts: Opt) -> Result<NumpyDatetime64Repr, NumpyDateTimeError> {\n        match self {\n            Self::Years => Ok(DateTime::new(\n                (val + 1970)\n                    .try_into()\n                    .map_err(|_| NumpyDateTimeError::Unrepresentable { unit: self, val })?,\n                1,\n                1,\n                0,\n                0,\n                0,\n                0,\n            )\n            .unwrap()),\n            Self::Months => Ok(DateTime::new(\n                (val / 12 + 1970)\n                    .try_into()\n                    .map_err(|_| NumpyDateTimeError::Unrepresentable { unit: self, val })?,\n                (val % 12 + 1)\n                    .try_into()\n                    .map_err(|_| NumpyDateTimeError::Unrepresentable { unit: self, val })?,\n                1,\n                0,\n                0,\n                0,\n                0,\n            )\n            .unwrap()),\n            Self::Weeks => {\n                to_jiff_datetime!(Timestamp::from_second(val * 7 * 24 * 60 * 60), self, val)\n            }\n            Self::Days => to_jiff_datetime!(Timestamp::from_second(val * 24 * 60 * 60), self, val),\n            Self::Hours => to_jiff_datetime!(Timestamp::from_second(val * 60 * 60), self, val),\n            Self::Minutes => to_jiff_datetime!(Timestamp::from_second(val * 60), self, val),\n            Self::Seconds => to_jiff_datetime!(Timestamp::from_second(val), self, val),\n            Self::Milliseconds => to_jiff_datetime!(Timestamp::from_millisecond(val), self, val),\n            Self::Microseconds => to_jiff_datetime!(Timestamp::from_microsecond(val), self, val),\n            Self::Nanoseconds => {\n                to_jiff_datetime!(Timestamp::from_nanosecond(i128::from(val)), self, val)\n            }\n            _ => Err(NumpyDateTimeError::UnsupportedUnit(self)),\n        }\n        .map(|dt| NumpyDatetime64Repr { dt, opts })\n    }\n}\n\nstruct NumpyDatetime64Array<'a> {\n    data: &'a [i64],\n    unit: NumpyDatetimeUnit,\n    opts: Opt,\n}\n\nimpl<'a> NumpyDatetime64Array<'a> {\n    fn new(data: &'a [i64], unit: NumpyDatetimeUnit, opts: Opt) -> Self {\n        Self { data, unit, opts }\n    }\n}\n\nimpl Serialize for NumpyDatetime64Array<'_> {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut seq = serializer.serialize_seq(None).unwrap();\n        for &each in self.data.iter() {\n            let dt = self\n                .unit\n                .datetime(each, self.opts)\n                .map_err(NumpyDateTimeError::into_serde_err)?;\n            seq.serialize_element(&dt).unwrap();\n        }\n        seq.end()\n    }\n}\n\n#[repr(C)]\npub(crate) struct NumpyDatetime64 {\n    ob_refcnt: Py_ssize_t,\n    ob_type: *mut PyTypeObject,\n    value: i64,\n}\n\nmacro_rules! forward_inner {\n    ($meth: ident, $ty: ident) => {\n        fn $meth(&self) -> $ty {\n            debug_assert!(self.dt.$meth() >= 0);\n            #[allow(clippy::cast_sign_loss)]\n            let ret = self.dt.$meth() as $ty; // stmt_expr_attributes\n            ret\n        }\n    };\n}\n\nstruct NumpyDatetime64Repr {\n    dt: DateTime,\n    opts: Opt,\n}\n\nimpl DateTimeLike for NumpyDatetime64Repr {\n    forward_inner!(year, i32);\n    forward_inner!(month, u8);\n    forward_inner!(day, u8);\n    forward_inner!(hour, u8);\n    forward_inner!(minute, u8);\n    forward_inner!(second, u8);\n\n    fn nanosecond(&self) -> u32 {\n        debug_assert!(self.dt.subsec_nanosecond() >= 0);\n        self.dt.subsec_nanosecond().cast_unsigned()\n    }\n\n    fn microsecond(&self) -> u32 {\n        self.nanosecond() / 1_000\n    }\n\n    fn has_tz(&self) -> bool {\n        false\n    }\n\n    fn slow_offset(&self) -> Result<Offset, DateTimeError> {\n        unreachable!()\n    }\n\n    fn offset(&self) -> Result<Offset, DateTimeError> {\n        Ok(Offset::default())\n    }\n}\n\nimpl Serialize for NumpyDatetime64Repr {\n    #[cold]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut buf = SmallFixedBuffer::new();\n        let _ = self.write_buf(&mut buf, self.opts);\n        serializer.collect_str(str_from_slice!(buf.as_ptr(), buf.len()))\n    }\n}\n"
  },
  {
    "path": "src/serialize/per_type/pybool.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2018-2026)\n\nuse crate::ffi::PyBoolRef;\nuse serde::ser::{Serialize, Serializer};\n\n#[repr(transparent)]\npub(crate) struct BoolSerializer {\n    ob: PyBoolRef,\n}\n\nimpl BoolSerializer {\n    pub fn new(ob: PyBoolRef) -> Self {\n        BoolSerializer { ob: ob }\n    }\n}\n\nimpl Serialize for BoolSerializer {\n    #[inline]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        serializer.serialize_bool(unsafe { core::ptr::eq(self.ob.as_ptr(), crate::typeref::TRUE) })\n    }\n}\n"
  },
  {
    "path": "src/serialize/per_type/pyenum.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2018-2025)\n\nuse crate::serialize::serializer::PyObjectSerializer;\nuse crate::typeref::VALUE_STR;\nuse serde::ser::{Serialize, Serializer};\n\n#[repr(transparent)]\npub(crate) struct EnumSerializer<'a> {\n    previous: &'a PyObjectSerializer,\n}\n\nimpl<'a> EnumSerializer<'a> {\n    pub fn new(previous: &'a PyObjectSerializer) -> Self {\n        Self { previous: previous }\n    }\n}\n\nimpl Serialize for EnumSerializer<'_> {\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let value = ffi!(PyObject_GetAttr(self.previous.ptr, VALUE_STR));\n        debug_assert!(ffi!(Py_REFCNT(value)) >= 2);\n        let ret = PyObjectSerializer::new(value, self.previous.state, self.previous.default)\n            .serialize(serializer);\n        ffi!(Py_DECREF(value));\n        ret\n    }\n}\n"
  },
  {
    "path": "src/serialize/per_type/unicode.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2018-2026)\n\nuse crate::ffi::{PyStrRef, PyStrSubclassRef};\nuse crate::serialize::error::SerializeError;\n\nuse serde::ser::{Serialize, Serializer};\n\n#[repr(transparent)]\npub(crate) struct StrSerializer {\n    ob: PyStrRef,\n}\n\nimpl StrSerializer {\n    pub fn new(ptr: PyStrRef) -> Self {\n        StrSerializer { ob: ptr }\n    }\n}\n\nimpl Serialize for StrSerializer {\n    #[inline(always)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        match self.ob.clone().as_str() {\n            Some(uni) => serializer.serialize_str(uni),\n            None => {\n                cold_path!();\n                err!(SerializeError::InvalidStr)\n            }\n        }\n    }\n}\n\n#[repr(transparent)]\npub(crate) struct StrSubclassSerializer {\n    ob: PyStrSubclassRef,\n}\n\nimpl StrSubclassSerializer {\n    pub fn new(ptr: PyStrSubclassRef) -> Self {\n        StrSubclassSerializer { ob: ptr }\n    }\n}\n\nimpl Serialize for StrSubclassSerializer {\n    #[inline(never)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        match self.ob.as_str() {\n            Some(uni) => serializer.serialize_str(uni),\n            None => {\n                cold_path!();\n                err!(SerializeError::InvalidStr)\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/serialize/per_type/uuid.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2018-2026)\n\nuse crate::ffi::PyUuidRef;\nuse crate::serialize::buffer::SmallFixedBuffer;\nuse serde::ser::{Serialize, Serializer};\n\n#[repr(transparent)]\npub(crate) struct UUID {\n    ob: PyUuidRef,\n}\n\nimpl UUID {\n    pub fn new(ptr: PyUuidRef) -> Self {\n        UUID { ob: ptr }\n    }\n\n    #[inline(never)]\n    pub fn write_buf<B>(&self, buf: &mut B)\n    where\n        B: bytes::BufMut,\n    {\n        unsafe {\n            let buffer_length: usize = 40;\n            debug_assert!(buf.remaining_mut() >= buffer_length);\n            let len = uuid::Uuid::from_u128(self.ob.value())\n                .hyphenated()\n                .encode_lower(core::slice::from_raw_parts_mut(\n                    buf.chunk_mut().as_mut_ptr(),\n                    buffer_length,\n                ))\n                .len();\n            buf.advance_mut(len);\n        }\n    }\n}\nimpl Serialize for UUID {\n    #[inline(always)]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let mut buf = SmallFixedBuffer::new();\n        self.write_buf(&mut buf);\n        serializer.serialize_unit_struct(str_from_slice!(buf.as_ptr(), buf.len()))\n    }\n}\n"
  },
  {
    "path": "src/serialize/serializer.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2018-2026)\n\nuse crate::ffi::{\n    PyBoolRef, PyDictRef, PyFloatRef, PyFragmentRef, PyIntRef, PyListRef, PyStrRef,\n    PyStrSubclassRef, PyUuidRef,\n};\nuse crate::opt::{APPEND_NEWLINE, INDENT_2, Opt};\nuse crate::serialize::obtype::{ObType, pyobject_to_obtype};\nuse crate::serialize::per_type::{\n    BoolSerializer, DataclassGenericSerializer, Date, DateTime, DefaultSerializer,\n    DictGenericSerializer, EnumSerializer, FloatSerializer, FragmentSerializer, IntSerializer,\n    ListTupleSerializer, NoneSerializer, NumpyScalar, NumpySerializer, StrSerializer,\n    StrSubclassSerializer, Time, UUID, ZeroListSerializer,\n};\nuse crate::serialize::state::SerializerState;\nuse crate::serialize::writer::{BytesWriter, to_writer, to_writer_pretty};\nuse core::ptr::NonNull;\nuse serde::ser::{Serialize, Serializer};\n\npub(crate) fn serialize(\n    ptr: *mut crate::ffi::PyObject,\n    default: Option<NonNull<crate::ffi::PyObject>>,\n    opts: Opt,\n) -> Result<NonNull<crate::ffi::PyObject>, String> {\n    let mut buf = BytesWriter::default();\n    let obj = PyObjectSerializer::new(ptr, SerializerState::new(opts), default);\n    let res = if opt_disabled!(opts, INDENT_2) {\n        to_writer(&mut buf, &obj)\n    } else {\n        to_writer_pretty(&mut buf, &obj)\n    };\n    match res {\n        Ok(()) => Ok(buf.finish(opt_enabled!(opts, APPEND_NEWLINE))),\n        Err(err) => {\n            buf.abort();\n            Err(err.to_string())\n        }\n    }\n}\n\npub(crate) struct PyObjectSerializer {\n    pub ptr: *mut crate::ffi::PyObject,\n    pub state: SerializerState,\n    pub default: Option<NonNull<crate::ffi::PyObject>>,\n}\n\nimpl PyObjectSerializer {\n    pub fn new(\n        ptr: *mut crate::ffi::PyObject,\n        state: SerializerState,\n        default: Option<NonNull<crate::ffi::PyObject>>,\n    ) -> Self {\n        PyObjectSerializer {\n            ptr: ptr,\n            state: state,\n            default: default,\n        }\n    }\n}\n\nimpl Serialize for PyObjectSerializer {\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        unsafe {\n            match pyobject_to_obtype(self.ptr, self.state.opts()) {\n                ObType::Str => {\n                    StrSerializer::new(PyStrRef::from_ptr_unchecked(self.ptr)).serialize(serializer)\n                }\n                ObType::StrSubclass => {\n                    StrSubclassSerializer::new(PyStrSubclassRef::from_ptr_unchecked(self.ptr))\n                        .serialize(serializer)\n                }\n                ObType::Int => IntSerializer::new(\n                    unsafe { PyIntRef::from_ptr_unchecked(self.ptr) },\n                    self.state.opts(),\n                )\n                .serialize(serializer),\n                ObType::None => NoneSerializer::new().serialize(serializer),\n                ObType::Float => FloatSerializer::new(PyFloatRef::from_ptr_unchecked(self.ptr))\n                    .serialize(serializer),\n                ObType::Bool => {\n                    BoolSerializer::new(unsafe { PyBoolRef::from_ptr_unchecked(self.ptr) })\n                        .serialize(serializer)\n                }\n                ObType::Datetime => {\n                    DateTime::new(self.ptr, self.state.opts()).serialize(serializer)\n                }\n                ObType::Date => Date::new(self.ptr).serialize(serializer),\n                ObType::Time => Time::new(self.ptr, self.state.opts()).serialize(serializer),\n                ObType::Uuid => {\n                    UUID::new(PyUuidRef::from_ptr_unchecked(self.ptr)).serialize(serializer)\n                }\n                ObType::Dict => DictGenericSerializer::new(\n                    PyDictRef::from_ptr_unchecked(self.ptr),\n                    self.state,\n                    self.default,\n                )\n                .serialize(serializer),\n                ObType::List => {\n                    if ffi!(Py_SIZE(self.ptr)) == 0 {\n                        ZeroListSerializer::new().serialize(serializer)\n                    } else {\n                        ListTupleSerializer::from_list(\n                            PyListRef::from_ptr_unchecked(self.ptr),\n                            self.state,\n                            self.default,\n                        )\n                        .serialize(serializer)\n                    }\n                }\n                ObType::Tuple => {\n                    if ffi!(Py_SIZE(self.ptr)) == 0 {\n                        ZeroListSerializer::new().serialize(serializer)\n                    } else {\n                        ListTupleSerializer::from_tuple(self.ptr, self.state, self.default)\n                            .serialize(serializer)\n                    }\n                }\n                ObType::Dataclass => DataclassGenericSerializer::new(self).serialize(serializer),\n                ObType::Enum => EnumSerializer::new(self).serialize(serializer),\n                ObType::NumpyArray => NumpySerializer::new(self).serialize(serializer),\n                ObType::NumpyScalar => {\n                    NumpyScalar::new(self.ptr, self.state.opts()).serialize(serializer)\n                }\n                ObType::Fragment => {\n                    FragmentSerializer::new(unsafe { PyFragmentRef::from_ptr_unchecked(self.ptr) })\n                        .serialize(serializer)\n                }\n                ObType::Unknown => DefaultSerializer::new(self).serialize(serializer),\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/serialize/state.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2024-2025)\n\nuse crate::opt::Opt;\n\nconst RECURSION_SHIFT: usize = 24;\nconst RECURSION_MASK: u32 = 255 << RECURSION_SHIFT;\n\nconst DEFAULT_SHIFT: usize = 16;\nconst DEFAULT_MASK: u32 = 255 << DEFAULT_SHIFT;\n\n#[repr(transparent)]\n#[derive(Copy, Clone)]\npub(crate) struct SerializerState {\n    // recursion: u8,\n    // default_calls: u8,\n    // opts: u16,\n    state: u32,\n}\n\nimpl SerializerState {\n    #[inline(always)]\n    pub fn new(opts: Opt) -> Self {\n        debug_assert!(opts < u32::from(u16::MAX));\n        Self { state: opts }\n    }\n\n    #[inline(always)]\n    pub fn opts(self) -> u32 {\n        self.state\n    }\n\n    #[inline(always)]\n    pub fn recursion_limit(self) -> bool {\n        self.state & RECURSION_MASK == RECURSION_MASK\n    }\n\n    #[inline(always)]\n    pub fn default_calls_limit(self) -> bool {\n        self.state & DEFAULT_MASK == DEFAULT_MASK\n    }\n\n    #[inline(always)]\n    pub fn copy_for_recursive_call(self) -> Self {\n        let opt = self.state & !RECURSION_MASK;\n        let recursion = (((self.state & RECURSION_MASK) >> RECURSION_SHIFT) + 1) << RECURSION_SHIFT;\n        Self {\n            state: opt | recursion,\n        }\n    }\n\n    #[inline(always)]\n    pub fn copy_for_default_call(self) -> Self {\n        let opt = self.state & !DEFAULT_MASK;\n        let default_calls = (((self.state & DEFAULT_MASK) >> DEFAULT_SHIFT) + 1) << DEFAULT_SHIFT;\n        Self {\n            state: opt | default_calls,\n        }\n    }\n}\n"
  },
  {
    "path": "src/serialize/writer/byteswriter.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2020-2025)\n\nuse crate::ffi::{PyBytes_FromStringAndSize, PyObject};\nuse crate::util::usize_to_isize;\nuse bytes::{BufMut, buf::UninitSlice};\nuse core::mem::MaybeUninit;\nuse core::ptr::NonNull;\n\n#[cfg(CPython)]\nconst BUFFER_LENGTH: usize = 1024;\n\n#[cfg(not(CPython))]\nconst BUFFER_LENGTH: usize = 4096;\n\npub(crate) struct BytesWriter {\n    cap: usize,\n    len: usize,\n    #[cfg(CPython)]\n    bytes: *mut crate::ffi::PyBytesObject,\n    #[cfg(not(CPython))]\n    bytes: *mut u8,\n}\n\nimpl BytesWriter {\n    #[inline]\n    pub fn default() -> Self {\n        BytesWriter {\n            cap: BUFFER_LENGTH,\n            len: 0,\n            #[cfg(CPython)]\n            bytes: unsafe {\n                PyBytes_FromStringAndSize(core::ptr::null_mut(), usize_to_isize(BUFFER_LENGTH))\n                    .cast::<crate::ffi::PyBytesObject>()\n            },\n            #[cfg(not(CPython))]\n            bytes: unsafe { crate::ffi::PyMem_Malloc(BUFFER_LENGTH).cast::<u8>() },\n        }\n    }\n\n    #[cfg(CPython)]\n    pub fn abort(&mut self) {\n        ffi!(Py_DECREF(self.bytes.cast::<PyObject>()));\n    }\n\n    #[cfg(not(CPython))]\n    pub fn abort(&mut self) {\n        unsafe {\n            crate::ffi::PyMem_Free(self.bytes.cast::<core::ffi::c_void>());\n        }\n    }\n\n    fn append_and_terminate(&mut self, append: bool) {\n        unsafe {\n            if append {\n                core::ptr::write(self.buffer_ptr(), b'\\n');\n                self.len += 1;\n            }\n            #[cfg(CPython)]\n            core::ptr::write(self.buffer_ptr(), 0);\n        }\n    }\n\n    #[cfg(CPython)]\n    #[inline]\n    pub fn finish(&mut self, append: bool) -> NonNull<PyObject> {\n        unsafe {\n            self.append_and_terminate(append);\n            crate::ffi::Py_SET_SIZE(\n                self.bytes.cast::<crate::ffi::PyVarObject>(),\n                usize_to_isize(self.len),\n            );\n            self.resize(self.len);\n            NonNull::new_unchecked(self.bytes.cast::<PyObject>())\n        }\n    }\n\n    #[cfg(not(CPython))]\n    #[inline]\n    pub fn finish(&mut self, append: bool) -> NonNull<PyObject> {\n        unsafe {\n            self.append_and_terminate(append);\n            let bytes = PyBytes_FromStringAndSize(\n                self.bytes.cast::<i8>().cast_const(),\n                usize_to_isize(self.len),\n            );\n            debug_assert!(!bytes.is_null());\n            crate::ffi::PyMem_Free(self.bytes.cast::<core::ffi::c_void>());\n            nonnull!(bytes)\n        }\n    }\n\n    #[cfg(CPython)]\n    #[inline]\n    fn buffer_ptr(&self) -> *mut u8 {\n        unsafe { (&raw mut (*self.bytes).ob_sval).cast::<u8>().add(self.len) }\n    }\n\n    #[cfg(not(CPython))]\n    #[inline]\n    fn buffer_ptr(&self) -> *mut u8 {\n        debug_assert!(!self.bytes.is_null());\n        unsafe { self.bytes.add(self.len) }\n    }\n\n    #[cfg(CPython)]\n    #[inline]\n    pub fn resize(&mut self, len: usize) {\n        self.cap = len;\n        unsafe {\n            crate::ffi::_PyBytes_Resize(\n                (&raw mut self.bytes).cast::<*mut PyObject>(),\n                usize_to_isize(len),\n            );\n        }\n    }\n\n    #[cfg(not(CPython))]\n    #[inline]\n    pub fn resize(&mut self, len: usize) {\n        self.cap = len;\n        unsafe {\n            self.bytes =\n                crate::ffi::PyMem_Realloc(self.bytes.cast::<core::ffi::c_void>(), len).cast::<u8>();\n            debug_assert!(!self.bytes.is_null());\n        }\n    }\n\n    #[cold]\n    #[inline(never)]\n    fn grow(&mut self, len: usize) {\n        let mut cap = self.cap;\n        while len >= cap {\n            cap *= 2;\n        }\n        self.resize(cap);\n    }\n}\n\nunsafe impl BufMut for BytesWriter {\n    #[inline]\n    unsafe fn advance_mut(&mut self, cnt: usize) {\n        self.len += cnt;\n    }\n\n    #[inline]\n    fn chunk_mut(&mut self) -> &mut UninitSlice {\n        unsafe {\n            UninitSlice::uninit(core::slice::from_raw_parts_mut(\n                self.buffer_ptr().cast::<MaybeUninit<u8>>(),\n                self.remaining_mut(),\n            ))\n        }\n    }\n\n    #[inline]\n    fn remaining_mut(&self) -> usize {\n        self.cap - self.len\n    }\n\n    #[inline]\n    fn put_u8(&mut self, value: u8) {\n        debug_assert!(self.remaining_mut() > 1);\n        unsafe {\n            core::ptr::write(self.buffer_ptr(), value);\n            self.advance_mut(1);\n        }\n    }\n\n    #[inline]\n    fn put_bytes(&mut self, val: u8, cnt: usize) {\n        debug_assert!(self.remaining_mut() > cnt);\n        unsafe {\n            core::ptr::write_bytes(self.buffer_ptr(), val, cnt);\n            self.advance_mut(cnt);\n        };\n    }\n\n    #[inline]\n    fn put_slice(&mut self, src: &[u8]) {\n        debug_assert!(self.remaining_mut() > src.len());\n        unsafe {\n            core::ptr::copy_nonoverlapping(src.as_ptr(), self.buffer_ptr(), src.len());\n            self.advance_mut(src.len());\n        }\n    }\n}\n\n// hack based on saethlin's research and patch in https://github.com/serde-rs/json/issues/766\npub(crate) trait WriteExt {\n    #[inline]\n    fn as_mut_buffer_ptr(&mut self) -> *mut u8 {\n        core::ptr::null_mut()\n    }\n\n    #[inline]\n    fn reserve(&mut self, len: usize) {\n        let _ = len;\n    }\n}\n\nimpl WriteExt for &mut BytesWriter {\n    #[inline(always)]\n    fn as_mut_buffer_ptr(&mut self) -> *mut u8 {\n        self.buffer_ptr()\n    }\n\n    #[inline(always)]\n    fn reserve(&mut self, len: usize) {\n        let end_length = self.len + len;\n        if end_length >= self.cap {\n            cold_path!();\n            self.grow(end_length);\n        }\n    }\n}\n"
  },
  {
    "path": "src/serialize/writer/formatter.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2022-2026)\n// This is an adaptation of `src/value/ser.rs` from serde-json.\n\nuse super::{\n    write_float32, write_float64, write_integer_i32, write_integer_i64, write_integer_u32,\n    write_integer_u64,\n};\nuse crate::serialize::writer::WriteExt;\nuse std::io;\n\nmacro_rules! debug_assert_has_capacity {\n    ($writer:expr) => {\n        debug_assert!($writer.remaining_mut() > 4)\n    };\n}\n\npub(crate) trait Formatter {\n    #[inline]\n    fn write_null<W>(&mut self, writer: &mut W) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        unsafe {\n            reserve_minimum!(writer);\n            writer.put_slice(b\"null\");\n            Ok(())\n        }\n    }\n\n    #[inline]\n    fn write_bool<W>(&mut self, writer: &mut W, value: bool) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        reserve_minimum!(writer);\n        unsafe {\n            writer.put_slice(if value { b\"true\" } else { b\"false\" });\n        }\n        Ok(())\n    }\n\n    #[inline]\n    fn write_i32<W>(&mut self, writer: &mut W, value: i32) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        unsafe {\n            reserve_minimum!(writer);\n            write_integer_i32(writer, value);\n        }\n        Ok(())\n    }\n\n    #[inline]\n    fn write_i64<W>(&mut self, writer: &mut W, value: i64) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        unsafe {\n            reserve_minimum!(writer);\n            write_integer_i64(writer, value);\n        }\n        Ok(())\n    }\n\n    #[inline]\n    fn write_u32<W>(&mut self, writer: &mut W, value: u32) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        unsafe {\n            reserve_minimum!(writer);\n            write_integer_u32(writer, value);\n        }\n        Ok(())\n    }\n\n    #[inline]\n    fn write_u64<W>(&mut self, writer: &mut W, value: u64) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        unsafe {\n            reserve_minimum!(writer);\n            write_integer_u64(writer, value);\n        }\n        Ok(())\n    }\n\n    #[inline]\n    fn write_f32<W>(&mut self, writer: &mut W, value: f32) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        unsafe {\n            reserve_minimum!(writer);\n            write_float32(writer, value);\n        }\n        Ok(())\n    }\n\n    #[inline]\n    fn write_f64<W>(&mut self, writer: &mut W, value: f64) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        unsafe {\n            reserve_minimum!(writer);\n            write_float64(writer, value);\n        }\n        Ok(())\n    }\n\n    #[inline]\n    fn begin_array<W>(&mut self, writer: &mut W) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        reserve_minimum!(writer);\n        unsafe {\n            writer.put_u8(b'[');\n        }\n        Ok(())\n    }\n\n    #[inline]\n    fn end_array<W>(&mut self, writer: &mut W) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        debug_assert_has_capacity!(writer);\n        unsafe {\n            writer.put_u8(b']');\n        }\n        Ok(())\n    }\n\n    #[inline]\n    fn begin_array_value<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        debug_assert_has_capacity!(writer);\n        if !first {\n            unsafe { writer.put_u8(b',') }\n        }\n        Ok(())\n    }\n\n    #[inline]\n    fn end_array_value<W>(&mut self, _writer: &mut W) -> io::Result<()>\n    where\n        W: ?Sized,\n    {\n        Ok(())\n    }\n\n    #[inline]\n    fn begin_object<W>(&mut self, writer: &mut W) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        reserve_minimum!(writer);\n        unsafe {\n            writer.put_u8(b'{');\n        }\n        Ok(())\n    }\n\n    #[inline]\n    fn end_object<W>(&mut self, writer: &mut W) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        reserve_minimum!(writer);\n        unsafe {\n            writer.put_u8(b'}');\n        }\n        Ok(())\n    }\n\n    #[inline]\n    fn begin_object_key<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        debug_assert_has_capacity!(writer);\n        if !first {\n            unsafe {\n                writer.put_u8(b',');\n            }\n        }\n        Ok(())\n    }\n\n    #[inline]\n    fn end_object_key<W>(&mut self, _writer: &mut W) -> io::Result<()>\n    where\n        W: ?Sized,\n    {\n        Ok(())\n    }\n\n    #[inline]\n    fn begin_object_value<W>(&mut self, writer: &mut W) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        debug_assert_has_capacity!(writer);\n        unsafe {\n            writer.put_u8(b':');\n        }\n        Ok(())\n    }\n\n    #[inline]\n    fn end_object_value<W>(&mut self, _writer: &mut W) -> io::Result<()>\n    where\n        W: ?Sized,\n    {\n        Ok(())\n    }\n}\n\npub(crate) struct CompactFormatter;\n\nimpl Formatter for CompactFormatter {}\n\npub(crate) struct PrettyFormatter {\n    current_indent: usize,\n    has_value: bool,\n}\n\nimpl PrettyFormatter {\n    #[allow(clippy::new_without_default)]\n    pub const fn new() -> Self {\n        PrettyFormatter {\n            current_indent: 0,\n            has_value: false,\n        }\n    }\n}\n\nimpl Formatter for PrettyFormatter {\n    #[inline]\n    fn begin_array<W>(&mut self, writer: &mut W) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        self.current_indent += 1;\n        self.has_value = false;\n        reserve_minimum!(writer);\n        unsafe {\n            writer.put_u8(b'[');\n        }\n        Ok(())\n    }\n\n    #[inline]\n    fn end_array<W>(&mut self, writer: &mut W) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        self.current_indent -= 1;\n        let num_spaces = self.current_indent * 2;\n        reserve_pretty!(writer, num_spaces);\n\n        unsafe {\n            if self.has_value {\n                writer.put_u8(b'\\n');\n                writer.put_bytes(b' ', num_spaces);\n            }\n            writer.put_u8(b']');\n            Ok(())\n        }\n    }\n\n    #[inline]\n    fn begin_array_value<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        let num_spaces = self.current_indent * 2;\n        reserve_pretty!(writer, num_spaces);\n\n        unsafe {\n            writer.put_slice(if first { b\"\\n\" } else { b\",\\n\" });\n            writer.put_bytes(b' ', num_spaces);\n        };\n        Ok(())\n    }\n\n    #[inline]\n    fn end_array_value<W>(&mut self, _writer: &mut W) -> io::Result<()>\n    where\n        W: ?Sized,\n    {\n        self.has_value = true;\n        Ok(())\n    }\n\n    #[inline]\n    fn begin_object<W>(&mut self, writer: &mut W) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        self.current_indent += 1;\n        self.has_value = false;\n\n        reserve_minimum!(writer);\n        unsafe {\n            writer.put_u8(b'{');\n        }\n        Ok(())\n    }\n\n    #[inline]\n    fn end_object<W>(&mut self, writer: &mut W) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        self.current_indent -= 1;\n        let num_spaces = self.current_indent * 2;\n        reserve_pretty!(writer, num_spaces);\n\n        unsafe {\n            if self.has_value {\n                writer.put_u8(b'\\n');\n                writer.put_bytes(b' ', num_spaces);\n            }\n\n            writer.put_u8(b'}');\n            Ok(())\n        }\n    }\n\n    #[inline]\n    fn begin_object_key<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        let num_spaces = self.current_indent * 2;\n        reserve_pretty!(writer, num_spaces);\n        unsafe {\n            writer.put_slice(if first { b\"\\n\" } else { b\",\\n\" });\n            writer.put_bytes(b' ', num_spaces);\n        }\n        Ok(())\n    }\n\n    #[inline]\n    fn begin_object_value<W>(&mut self, writer: &mut W) -> io::Result<()>\n    where\n        W: ?Sized + WriteExt + bytes::BufMut,\n    {\n        reserve_minimum!(writer);\n        unsafe {\n            writer.put_slice(b\": \");\n        }\n        Ok(())\n    }\n\n    #[inline]\n    fn end_object_value<W>(&mut self, _writer: &mut W) -> io::Result<()>\n    where\n        W: ?Sized,\n    {\n        self.has_value = true;\n        Ok(())\n    }\n}\n"
  },
  {
    "path": "src/serialize/writer/json.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2022-2025)\n// This is an adaptation of `src/value/ser.rs` from serde-json.\n\nuse crate::serialize::writer::WriteExt;\nuse crate::serialize::writer::formatter::{CompactFormatter, Formatter, PrettyFormatter};\nuse serde::ser::{self, Impossible, Serialize};\nuse serde_json::error::{Error, Result};\n\npub(crate) struct Serializer<W, F = CompactFormatter> {\n    writer: W,\n    formatter: F,\n}\n\nimpl<W> Serializer<W>\nwhere\n    W: WriteExt + bytes::BufMut,\n{\n    #[inline]\n    pub fn new(writer: W) -> Self {\n        Serializer::with_formatter(writer, CompactFormatter)\n    }\n}\n\nimpl<W> Serializer<W, PrettyFormatter>\nwhere\n    W: WriteExt + bytes::BufMut,\n{\n    #[inline]\n    pub fn pretty(writer: W) -> Self {\n        Serializer::with_formatter(writer, PrettyFormatter::new())\n    }\n}\n\nimpl<W, F> Serializer<W, F>\nwhere\n    W: WriteExt + bytes::BufMut,\n    F: Formatter,\n{\n    #[inline]\n    pub fn with_formatter(writer: W, formatter: F) -> Self {\n        Serializer { writer, formatter }\n    }\n}\n\nimpl<'a, W, F> ser::Serializer for &'a mut Serializer<W, F>\nwhere\n    W: WriteExt + bytes::BufMut,\n    F: Formatter,\n{\n    type Ok = ();\n    type Error = Error;\n\n    type SerializeSeq = Compound<'a, W, F>;\n    type SerializeTuple = Impossible<(), Error>;\n    type SerializeTupleStruct = Impossible<(), Error>;\n    type SerializeTupleVariant = Impossible<(), Error>;\n    type SerializeMap = Compound<'a, W, F>;\n    type SerializeStruct = Impossible<(), Error>;\n    type SerializeStructVariant = Impossible<(), Error>;\n\n    #[inline]\n    fn serialize_bool(self, value: bool) -> Result<()> {\n        self.formatter\n            .write_bool(&mut self.writer, value)\n            .map_err(Error::io)\n    }\n\n    fn serialize_i8(self, _value: i8) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_i16(self, _value: i16) -> Result<()> {\n        unreachable!();\n    }\n\n    #[inline]\n    fn serialize_i32(self, value: i32) -> Result<()> {\n        self.formatter\n            .write_i32(&mut self.writer, value)\n            .map_err(Error::io)\n    }\n\n    #[inline]\n    fn serialize_i64(self, value: i64) -> Result<()> {\n        self.formatter\n            .write_i64(&mut self.writer, value)\n            .map_err(Error::io)\n    }\n\n    fn serialize_i128(self, _value: i128) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_u8(self, _value: u8) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_u16(self, _value: u16) -> Result<()> {\n        unreachable!();\n    }\n\n    #[inline]\n    fn serialize_u32(self, value: u32) -> Result<()> {\n        self.formatter\n            .write_u32(&mut self.writer, value)\n            .map_err(Error::io)\n    }\n\n    #[inline]\n    fn serialize_u64(self, value: u64) -> Result<()> {\n        self.formatter\n            .write_u64(&mut self.writer, value)\n            .map_err(Error::io)\n    }\n\n    fn serialize_u128(self, _value: u128) -> Result<()> {\n        unreachable!();\n    }\n\n    #[inline]\n    fn serialize_f32(self, value: f32) -> Result<()> {\n        if value.is_infinite() || value.is_nan() {\n            cold_path!();\n            self.serialize_unit()\n        } else {\n            self.formatter\n                .write_f32(&mut self.writer, value)\n                .map_err(Error::io)\n        }\n    }\n    #[inline]\n    fn serialize_f64(self, value: f64) -> Result<()> {\n        if value.is_infinite() || value.is_nan() {\n            cold_path!();\n            self.serialize_unit()\n        } else {\n            self.formatter\n                .write_f64(&mut self.writer, value)\n                .map_err(Error::io)\n        }\n    }\n\n    fn serialize_char(self, _value: char) -> Result<()> {\n        unreachable!();\n    }\n\n    #[inline(always)]\n    fn serialize_str(self, value: &str) -> Result<()> {\n        format_escaped_str(&mut self.writer, value);\n        Ok(())\n    }\n\n    #[inline(always)]\n    fn serialize_bytes(self, value: &[u8]) -> Result<()> {\n        self.writer.reserve(value.len() + 32);\n        unsafe {\n            self.writer.put_slice(value);\n        }\n        Ok(())\n    }\n\n    #[inline]\n    fn serialize_unit(self) -> Result<()> {\n        self.formatter\n            .write_null(&mut self.writer)\n            .map_err(Error::io)\n    }\n\n    #[inline(always)]\n    fn serialize_unit_struct(self, name: &'static str) -> Result<()> {\n        debug_assert!(name.len() <= 36);\n        reserve_minimum!(self.writer);\n        unsafe {\n            self.writer.put_u8(b'\"');\n            self.writer.put_slice(name.as_bytes());\n            self.writer.put_u8(b'\"');\n        }\n        Ok(())\n    }\n\n    fn serialize_unit_variant(\n        self,\n        _name: &'static str,\n        _variant_index: u32,\n        _variant: &'static str,\n    ) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_newtype_struct<T>(self, _name: &'static str, _value: &T) -> Result<()>\n    where\n        T: ?Sized + Serialize,\n    {\n        unreachable!();\n    }\n\n    fn serialize_newtype_variant<T>(\n        self,\n        _name: &'static str,\n        _variant_index: u32,\n        _variant: &'static str,\n        _value: &T,\n    ) -> Result<()>\n    where\n        T: ?Sized + Serialize,\n    {\n        unreachable!();\n    }\n\n    #[inline]\n    fn serialize_none(self) -> Result<()> {\n        self.serialize_unit()\n    }\n\n    #[inline]\n    fn serialize_some<T>(self, value: &T) -> Result<()>\n    where\n        T: ?Sized + Serialize,\n    {\n        value.serialize(self)\n    }\n\n    #[inline(always)]\n    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {\n        self.formatter\n            .begin_array(&mut self.writer)\n            .map_err(Error::io)?;\n        Ok(Compound {\n            ser: self,\n            state: State::First,\n        })\n    }\n\n    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {\n        unreachable!();\n    }\n\n    fn serialize_tuple_struct(\n        self,\n        _name: &'static str,\n        _len: usize,\n    ) -> Result<Self::SerializeTupleStruct> {\n        unreachable!();\n    }\n\n    fn serialize_tuple_variant(\n        self,\n        _name: &'static str,\n        _variant_index: u32,\n        _variant: &'static str,\n        _len: usize,\n    ) -> Result<Self::SerializeTupleVariant> {\n        unreachable!();\n    }\n\n    #[inline(always)]\n    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {\n        self.formatter\n            .begin_object(&mut self.writer)\n            .map_err(Error::io)?;\n        Ok(Compound {\n            ser: self,\n            state: State::First,\n        })\n    }\n\n    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {\n        unreachable!();\n    }\n\n    fn serialize_struct_variant(\n        self,\n        _name: &'static str,\n        _variant_index: u32,\n        _variant: &'static str,\n        _len: usize,\n    ) -> Result<Self::SerializeStructVariant> {\n        unreachable!();\n    }\n}\n\n#[derive(Eq, PartialEq)]\npub(crate) enum State {\n    First,\n    Rest,\n}\n\npub(crate) struct Compound<'a, W: 'a, F: 'a> {\n    ser: &'a mut Serializer<W, F>,\n    state: State,\n}\n\nimpl<W, F> ser::SerializeSeq for Compound<'_, W, F>\nwhere\n    W: WriteExt + bytes::BufMut,\n    F: Formatter,\n{\n    type Ok = ();\n    type Error = Error;\n\n    #[inline]\n    fn serialize_element<T>(&mut self, value: &T) -> Result<()>\n    where\n        T: ?Sized + Serialize,\n    {\n        self.ser\n            .formatter\n            .begin_array_value(&mut self.ser.writer, self.state == State::First)\n            .unwrap();\n        self.state = State::Rest;\n        value.serialize(&mut *self.ser)?;\n        self.ser\n            .formatter\n            .end_array_value(&mut self.ser.writer)\n            .map_err(Error::io)\n            .unwrap();\n        Ok(())\n    }\n\n    #[inline]\n    fn end(self) -> Result<()> {\n        self.ser.formatter.end_array(&mut self.ser.writer).unwrap();\n        Ok(())\n    }\n}\n\nimpl<W, F> ser::SerializeMap for Compound<'_, W, F>\nwhere\n    W: WriteExt + bytes::BufMut,\n    F: Formatter,\n{\n    type Ok = ();\n    type Error = Error;\n\n    fn serialize_entry<K, V>(&mut self, _key: &K, _value: &V) -> Result<()>\n    where\n        K: ?Sized + Serialize,\n        V: ?Sized + Serialize,\n    {\n        unreachable!()\n    }\n\n    #[inline]\n    fn serialize_key<T>(&mut self, key: &T) -> Result<()>\n    where\n        T: ?Sized + Serialize,\n    {\n        self.ser\n            .formatter\n            .begin_object_key(&mut self.ser.writer, self.state == State::First)\n            .unwrap();\n        self.state = State::Rest;\n\n        key.serialize(MapKeySerializer { ser: self.ser })?;\n\n        self.ser\n            .formatter\n            .end_object_key(&mut self.ser.writer)\n            .unwrap();\n        Ok(())\n    }\n\n    #[inline]\n    fn serialize_value<T>(&mut self, value: &T) -> Result<()>\n    where\n        T: ?Sized + Serialize,\n    {\n        self.ser\n            .formatter\n            .begin_object_value(&mut self.ser.writer)\n            .unwrap();\n        value.serialize(&mut *self.ser)?;\n        self.ser\n            .formatter\n            .end_object_value(&mut self.ser.writer)\n            .unwrap();\n        Ok(())\n    }\n\n    #[inline]\n    fn end(self) -> Result<()> {\n        self.ser.formatter.end_object(&mut self.ser.writer).unwrap();\n        Ok(())\n    }\n}\n\n#[repr(transparent)]\nstruct MapKeySerializer<'a, W: 'a, F: 'a> {\n    ser: &'a mut Serializer<W, F>,\n}\n\nimpl<W, F> ser::Serializer for MapKeySerializer<'_, W, F>\nwhere\n    W: WriteExt + bytes::BufMut,\n    F: Formatter,\n{\n    type Ok = ();\n    type Error = Error;\n    type SerializeSeq = Impossible<(), Error>;\n    type SerializeTuple = Impossible<(), Error>;\n    type SerializeTupleStruct = Impossible<(), Error>;\n    type SerializeTupleVariant = Impossible<(), Error>;\n    type SerializeMap = Impossible<(), Error>;\n    type SerializeStruct = Impossible<(), Error>;\n    type SerializeStructVariant = Impossible<(), Error>;\n\n    #[inline(always)]\n    fn serialize_str(self, value: &str) -> Result<()> {\n        self.ser.serialize_str(value)\n    }\n\n    fn serialize_unit_variant(\n        self,\n        _name: &'static str,\n        _variant_index: u32,\n        _variant: &'static str,\n    ) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_newtype_struct<T>(self, _name: &'static str, _value: &T) -> Result<()>\n    where\n        T: ?Sized + Serialize,\n    {\n        unreachable!();\n    }\n    fn serialize_bool(self, _value: bool) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_i8(self, _value: i8) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_i16(self, _value: i16) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_i32(self, _value: i32) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_i64(self, _value: i64) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_i128(self, _value: i128) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_u8(self, _value: u8) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_u16(self, _value: u16) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_u32(self, _value: u32) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_u64(self, _value: u64) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_u128(self, _value: u128) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_f32(self, _value: f32) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_f64(self, _value: f64) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_char(self, _value: char) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_bytes(self, _value: &[u8]) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_unit(self) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_newtype_variant<T>(\n        self,\n        _name: &'static str,\n        _variant_index: u32,\n        _variant: &'static str,\n        _value: &T,\n    ) -> Result<()>\n    where\n        T: ?Sized + Serialize,\n    {\n        unreachable!();\n    }\n\n    fn serialize_none(self) -> Result<()> {\n        unreachable!();\n    }\n\n    fn serialize_some<T>(self, _value: &T) -> Result<()>\n    where\n        T: ?Sized + Serialize,\n    {\n        unreachable!();\n    }\n\n    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {\n        unreachable!();\n    }\n\n    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {\n        unreachable!();\n    }\n\n    fn serialize_tuple_struct(\n        self,\n        _name: &'static str,\n        _len: usize,\n    ) -> Result<Self::SerializeTupleStruct> {\n        unreachable!();\n    }\n\n    fn serialize_tuple_variant(\n        self,\n        _name: &'static str,\n        _variant_index: u32,\n        _variant: &'static str,\n        _len: usize,\n    ) -> Result<Self::SerializeTupleVariant> {\n        unreachable!();\n    }\n\n    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {\n        unreachable!();\n    }\n\n    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {\n        unreachable!();\n    }\n\n    fn serialize_struct_variant(\n        self,\n        _name: &'static str,\n        _variant_index: u32,\n        _variant: &'static str,\n        _len: usize,\n    ) -> Result<Self::SerializeStructVariant> {\n        unreachable!();\n    }\n}\n\nmacro_rules! reserve_str {\n    ($writer:expr, $value:expr) => {\n        $writer.reserve($value.len() * 8 + 32);\n    };\n}\n\n#[cfg(all(target_arch = \"x86_64\", feature = \"avx512\"))]\ntype StrFormatter = unsafe fn(*mut u8, *const u8, usize) -> usize;\n\n#[cfg(all(target_arch = \"x86_64\", feature = \"avx512\"))]\nstatic mut STR_FORMATTER_FN: StrFormatter =\n    crate::serialize::writer::str::format_escaped_str_impl_sse2_128;\n\npub(crate) fn set_str_formatter_fn() {\n    unsafe {\n        #[cfg(all(target_arch = \"x86_64\", feature = \"avx512\"))]\n        if std::is_x86_feature_detected!(\"avx512vl\") {\n            STR_FORMATTER_FN = crate::serialize::writer::str::format_escaped_str_impl_512vl;\n        }\n    }\n}\n\n#[cfg(all(target_arch = \"x86_64\", not(feature = \"avx512\")))]\n#[inline(always)]\nfn format_escaped_str<W>(writer: &mut W, value: &str)\nwhere\n    W: ?Sized + WriteExt + bytes::BufMut,\n{\n    unsafe {\n        reserve_str!(writer, value);\n\n        let written = crate::serialize::writer::str::format_escaped_str_impl_sse2_128(\n            writer.as_mut_buffer_ptr(),\n            value.as_bytes().as_ptr(),\n            value.len(),\n        );\n\n        writer.advance_mut(written);\n    }\n}\n\n#[cfg(all(target_arch = \"x86_64\", feature = \"avx512\"))]\n#[inline(always)]\nfn format_escaped_str<W>(writer: &mut W, value: &str)\nwhere\n    W: ?Sized + WriteExt + bytes::BufMut,\n{\n    unsafe {\n        reserve_str!(writer, value);\n\n        let written = STR_FORMATTER_FN(\n            writer.as_mut_buffer_ptr(),\n            value.as_bytes().as_ptr(),\n            value.len(),\n        );\n\n        writer.advance_mut(written);\n    }\n}\n\n#[cfg(all(\n    not(target_arch = \"x86_64\"),\n    not(feature = \"avx512\"),\n    feature = \"generic_simd\"\n))]\n#[inline(always)]\nfn format_escaped_str<W>(writer: &mut W, value: &str)\nwhere\n    W: ?Sized + WriteExt + bytes::BufMut,\n{\n    unsafe {\n        reserve_str!(writer, value);\n\n        let written = crate::serialize::writer::str::format_escaped_str_impl_generic_128(\n            writer.as_mut_buffer_ptr(),\n            value.as_bytes().as_ptr(),\n            value.len(),\n        );\n\n        writer.advance_mut(written);\n    }\n}\n\n#[cfg(all(not(target_arch = \"x86_64\"), not(feature = \"generic_simd\")))]\n#[inline(always)]\nfn format_escaped_str<W>(writer: &mut W, value: &str)\nwhere\n    W: ?Sized + WriteExt + bytes::BufMut,\n{\n    unsafe {\n        reserve_str!(writer, value);\n\n        let written = crate::serialize::writer::str::format_escaped_str_scalar(\n            writer.as_mut_buffer_ptr(),\n            value.as_bytes().as_ptr(),\n            value.len(),\n        );\n\n        writer.advance_mut(written);\n    }\n}\n\n#[inline]\npub(crate) fn to_writer<W, T>(writer: W, value: &T) -> Result<()>\nwhere\n    W: WriteExt + bytes::BufMut,\n    T: ?Sized + Serialize,\n{\n    let mut ser = Serializer::new(writer);\n    value.serialize(&mut ser)\n}\n\n#[inline]\npub(crate) fn to_writer_pretty<W, T>(writer: W, value: &T) -> Result<()>\nwhere\n    W: WriteExt + bytes::BufMut,\n    T: ?Sized + Serialize,\n{\n    let mut ser = Serializer::pretty(writer);\n    value.serialize(&mut ser)\n}\n"
  },
  {
    "path": "src/serialize/writer/mod.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2024-2026)\n\nmod byteswriter;\nmod formatter;\nmod json;\nmod num;\nmod str;\n\npub(crate) use byteswriter::{BytesWriter, WriteExt};\npub(crate) use json::{set_str_formatter_fn, to_writer, to_writer_pretty};\npub(crate) use num::{\n    write_float32, write_float64, write_integer_i32, write_integer_i64, write_integer_u32,\n    write_integer_u64,\n};\n"
  },
  {
    "path": "src/serialize/writer/num.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2026)\n\nuse crate::serialize::writer::WriteExt;\nuse bytes::BufMut;\n\n#[inline]\npub(crate) fn write_integer_u32<B>(buf: &mut B, val: u32)\nwhere\n    B: ?Sized + WriteExt + BufMut,\n{\n    write_integer(buf, val)\n}\n\n#[inline]\npub(crate) fn write_integer_i32<B>(buf: &mut B, val: i32)\nwhere\n    B: ?Sized + WriteExt + BufMut,\n{\n    write_integer(buf, val)\n}\n\n#[inline]\npub(crate) fn write_integer_u64<B>(buf: &mut B, val: u64)\nwhere\n    B: ?Sized + WriteExt + BufMut,\n{\n    write_integer(buf, val)\n}\n\n#[inline]\npub(crate) fn write_integer_i64<B>(buf: &mut B, val: i64)\nwhere\n    B: ?Sized + WriteExt + BufMut,\n{\n    write_integer(buf, val)\n}\n\n#[inline]\nfn write_integer<B, V: itoap::Integer>(buf: &mut B, val: V)\nwhere\n    B: ?Sized + WriteExt + BufMut,\n{\n    unsafe {\n        debug_assert!(buf.remaining_mut() >= 20);\n        let len = itoap::write_to_ptr(buf.as_mut_buffer_ptr(), val);\n        buf.advance_mut(len);\n    }\n}\n\n#[inline]\npub(crate) fn write_float32<B>(buf: &mut B, val: f32)\nwhere\n    B: ?Sized + WriteExt + BufMut,\n{\n    if val.is_infinite() || val.is_nan() {\n        cold_path!();\n        buf.put_slice(b\"null\");\n    } else {\n        write_finite_float(buf, val)\n    }\n}\n\n#[inline]\npub(crate) fn write_float64<B>(buf: &mut B, val: f64)\nwhere\n    B: ?Sized + WriteExt + BufMut,\n{\n    if val.is_infinite() || val.is_nan() {\n        cold_path!();\n        buf.put_slice(b\"null\");\n    } else {\n        write_finite_float(buf, val)\n    }\n}\n\nfn write_finite_float<B, F: zmij::Float>(buf: &mut B, val: F)\nwhere\n    B: ?Sized + WriteExt + BufMut,\n{\n    unsafe {\n        debug_assert!(buf.remaining_mut() >= 40);\n        let buffer =\n            unsafe { core::mem::transmute::<*mut u8, &mut zmij::Buffer>(buf.as_mut_buffer_ptr()) };\n        let res = buffer.format_finite(val);\n        buf.advance_mut(res.len());\n    }\n}\n"
  },
  {
    "path": "src/serialize/writer/str/avx512.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2024-2025)\n\nuse core::arch::x86_64::{\n    _mm256_cmpeq_epu8_mask, _mm256_cmplt_epu8_mask, _mm256_loadu_epi8, _mm256_maskz_loadu_epi8,\n    _mm256_set1_epi8, _mm256_storeu_epi8,\n};\n\n#[inline(never)]\n#[target_feature(enable = \"avx512f,avx512bw,avx512vl,bmi2\")]\npub(crate) unsafe fn format_escaped_str_impl_512vl(\n    odst: *mut u8,\n    value_ptr: *const u8,\n    value_len: usize,\n) -> usize {\n    unsafe {\n        const STRIDE: usize = 32;\n\n        let mut dst = odst;\n        let mut src = value_ptr;\n        let mut nb: usize = value_len;\n\n        let blash = _mm256_set1_epi8(0b01011100i8);\n        let quote = _mm256_set1_epi8(0b00100010i8);\n        let x20 = _mm256_set1_epi8(0b00100000i8);\n\n        core::ptr::write(dst, b'\"');\n        dst = dst.add(1);\n\n        while nb >= STRIDE {\n            let str_vec = _mm256_loadu_epi8(src.cast::<i8>());\n\n            _mm256_storeu_epi8(dst.cast::<i8>(), str_vec);\n\n            let mask = _mm256_cmpeq_epu8_mask(str_vec, blash)\n                | _mm256_cmpeq_epu8_mask(str_vec, quote)\n                | _mm256_cmplt_epu8_mask(str_vec, x20);\n\n            if mask != 0 {\n                let cn = mask.trailing_zeros() as usize;\n                src = src.add(cn);\n                dst = dst.add(cn);\n                nb -= cn;\n                nb -= 1;\n\n                write_escape!(*(src), dst);\n                src = src.add(1);\n            } else {\n                nb -= STRIDE;\n                dst = dst.add(STRIDE);\n                src = src.add(STRIDE);\n            }\n        }\n\n        loop {\n            let remainder_mask = !(u32::MAX << nb);\n            let str_vec = _mm256_maskz_loadu_epi8(remainder_mask, src.cast::<i8>());\n\n            _mm256_storeu_epi8(dst.cast::<i8>(), str_vec);\n\n            let mask = (_mm256_cmpeq_epu8_mask(str_vec, blash)\n                | _mm256_cmpeq_epu8_mask(str_vec, quote)\n                | _mm256_cmplt_epu8_mask(str_vec, x20))\n                & remainder_mask;\n\n            if mask != 0 {\n                let cn = mask.trailing_zeros() as usize;\n                src = src.add(cn);\n                dst = dst.add(cn);\n                nb -= cn;\n                nb -= 1;\n\n                write_escape!(*(src), dst);\n                src = src.add(1);\n            } else {\n                dst = dst.add(nb);\n                break;\n            }\n        }\n\n        core::ptr::write(dst, b'\"');\n        dst = dst.add(1);\n\n        dst as usize - odst as usize\n    }\n}\n"
  },
  {
    "path": "src/serialize/writer/str/escape.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2024-2026)\n// the constants and SIMD approach are adapted from cloudwego's sonic-rs\n\n#[cfg(feature = \"inline_int\")]\nmacro_rules! write_escape {\n    ($byte:expr, $dst:expr) => {\n        debug_assert!($byte < 96);\n        #[allow(unnecessary_transmutes)]\n        let escape = core::mem::transmute::<[u8; 8], u64>(\n            *crate::serialize::writer::str::escape::QUOTE_TAB.get_unchecked($byte as usize),\n        );\n        #[allow(clippy::cast_ptr_alignment)]\n        let _dst = $dst.cast::<u64>(); // stmt_expr_attributes\n        core::ptr::write(_dst, escape);\n        $dst = $dst.add((escape as usize) >> 56);\n    };\n}\n\n#[cfg(not(feature = \"inline_int\"))]\nmacro_rules! write_escape {\n    ($byte:expr, $dst:expr) => {\n        debug_assert!($byte < 96);\n        let escape = crate::serialize::writer::str::escape::QUOTE_TAB.get_unchecked($byte as usize);\n        core::ptr::copy_nonoverlapping(escape.as_ptr(), $dst, 8);\n        $dst = $dst.add(((*escape.as_ptr().add(7)) as usize));\n    };\n}\n\npub(crate) const NEED_ESCAPED: [u8; 256] = [\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n    0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n];\n\npub(crate) const QUOTE_TAB: [[u8; 8]; 96] = [\n    [b'\\\\', b'u', b'0', b'0', b'0', b'0', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'0', b'1', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'0', b'2', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'0', b'3', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'0', b'4', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'0', b'5', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'0', b'6', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'0', b'7', 0, 6],\n    [b'\\\\', b'b', b'0', b'0', b'0', b'0', 0, 2],\n    [b'\\\\', b't', b'0', b'0', b'0', b'0', 0, 2],\n    [b'\\\\', b'n', b'0', b'0', b'0', b'0', 0, 2],\n    [b'\\\\', b'u', b'0', b'0', b'0', b'b', 0, 6],\n    [b'\\\\', b'f', b'0', b'0', b'0', b'0', 0, 2],\n    [b'\\\\', b'r', b'0', b'0', b'0', b'0', 0, 2],\n    [b'\\\\', b'u', b'0', b'0', b'0', b'e', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'0', b'f', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'1', b'0', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'1', b'1', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'1', b'2', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'1', b'3', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'1', b'4', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'1', b'5', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'1', b'6', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'1', b'7', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'1', b'8', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'1', b'9', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'1', b'a', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'1', b'b', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'1', b'c', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'1', b'd', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'1', b'e', 0, 6],\n    [b'\\\\', b'u', b'0', b'0', b'1', b'f', 0, 6],\n    [0; 8],\n    [0; 8],\n    [b'\\\\', b'\"', 0, 0, 0, 0, 0, 2],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n    [b'\\\\', b'\\\\', 0, 0, 0, 0, 0, 2],\n    [0; 8],\n    [0; 8],\n    [0; 8],\n];\n"
  },
  {
    "path": "src/serialize/writer/str/generic.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2024-2025)\n\nuse core::simd::cmp::{SimdPartialEq, SimdPartialOrd};\nuse core::simd::u8x16;\n\n#[inline(never)]\n#[cfg_attr(target_arch = \"aarch64\", target_feature(enable = \"neon\"))]\npub(crate) unsafe fn format_escaped_str_impl_generic_128(\n    odst: *mut u8,\n    value_ptr: *const u8,\n    value_len: usize,\n) -> usize {\n    unsafe {\n        const STRIDE: usize = 16;\n\n        let mut dst = odst;\n        let mut src = value_ptr;\n\n        core::ptr::write(dst, b'\"');\n        dst = dst.add(1);\n\n        if value_len < STRIDE {\n            impl_format_scalar!(dst, src, value_len);\n        } else {\n            let blash = u8x16::splat(b'\\\\');\n            let quote = u8x16::splat(b'\"');\n            let x20 = u8x16::splat(32);\n\n            let last_stride_src = src.add(value_len).sub(STRIDE);\n            let mut nb: usize = value_len;\n\n            {\n                while nb >= STRIDE {\n                    let v = u8x16::from_slice(core::slice::from_raw_parts(src, STRIDE));\n                    let mask =\n                        (v.simd_eq(blash) | v.simd_eq(quote) | v.simd_lt(x20)).to_bitmask() as u32;\n                    v.copy_to_slice(core::slice::from_raw_parts_mut(dst, STRIDE));\n\n                    if mask != 0 {\n                        let cn = mask.trailing_zeros() as usize;\n                        nb -= cn;\n                        dst = dst.add(cn);\n                        src = src.add(cn);\n                        nb -= 1;\n                        write_escape!(*(src), dst);\n                        src = src.add(1);\n                    } else {\n                        nb -= STRIDE;\n                        dst = dst.add(STRIDE);\n                        src = src.add(STRIDE);\n                    }\n                }\n            }\n\n            let mut scratch: [u8; 32] = [b'a'; 32];\n            let mut v = u8x16::from_slice(core::slice::from_raw_parts(last_stride_src, STRIDE));\n            v.copy_to_slice(core::slice::from_raw_parts_mut(\n                scratch.as_mut_ptr(),\n                STRIDE,\n            ));\n\n            let mut scratch_ptr = scratch.as_mut_ptr().add(16 - nb);\n            v = u8x16::from_slice(core::slice::from_raw_parts(scratch_ptr, STRIDE));\n            let mut mask =\n                (v.simd_eq(blash) | v.simd_eq(quote) | v.simd_lt(x20)).to_bitmask() as u32;\n\n            loop {\n                v.copy_to_slice(core::slice::from_raw_parts_mut(dst, STRIDE));\n                if mask != 0 {\n                    let cn = mask.trailing_zeros() as usize;\n                    nb -= cn;\n                    dst = dst.add(cn);\n                    scratch_ptr = scratch_ptr.add(cn);\n                    nb -= 1;\n                    mask >>= cn + 1;\n                    write_escape!(*(scratch_ptr), dst);\n                    scratch_ptr = scratch_ptr.add(1);\n                    v = u8x16::from_slice(core::slice::from_raw_parts(scratch_ptr, STRIDE));\n                } else {\n                    dst = dst.add(nb);\n                    break;\n                }\n            }\n        }\n\n        core::ptr::write(dst, b'\"');\n        dst = dst.add(1);\n\n        dst as usize - odst as usize\n    }\n}\n"
  },
  {
    "path": "src/serialize/writer/str/mod.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2024-2025)\n\n#[macro_use]\nmod escape;\n#[macro_use]\nmod scalar;\n\n#[cfg(all(feature = \"generic_simd\", not(target_arch = \"x86_64\")))]\nmod generic;\n\n#[cfg(target_arch = \"x86_64\")]\nmod sse2;\n\n#[cfg(all(target_arch = \"x86_64\", feature = \"avx512\"))]\nmod avx512;\n\n#[cfg(all(not(target_arch = \"x86_64\"), not(feature = \"generic_simd\")))]\npub(crate) use scalar::format_escaped_str_scalar;\n\n#[cfg(all(target_arch = \"x86_64\", feature = \"avx512\"))]\npub(crate) use avx512::format_escaped_str_impl_512vl;\n\n#[allow(unused_imports)]\n#[cfg(target_arch = \"x86_64\")]\npub(crate) use sse2::format_escaped_str_impl_sse2_128;\n\n#[cfg(all(feature = \"generic_simd\", not(target_arch = \"x86_64\")))]\npub(crate) use generic::format_escaped_str_impl_generic_128;\n"
  },
  {
    "path": "src/serialize/writer/str/scalar.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2024-2025)\n\nmacro_rules! impl_format_scalar {\n    ($dst:expr, $src:expr, $value_len:expr) => {\n        unsafe {\n            for _ in 0..$value_len {\n                core::ptr::write($dst, *($src));\n                $src = $src.add(1);\n                $dst = $dst.add(1);\n                if *super::escape::NEED_ESCAPED.get_unchecked(*($src.sub(1)) as usize) != 0 {\n                    $dst = $dst.sub(1);\n                    write_escape!(*($src.sub(1)), $dst);\n                }\n            }\n        }\n    };\n}\n\n#[inline(never)]\n#[cfg(all(not(target_arch = \"x86_64\"), not(feature = \"generic_simd\")))]\npub(crate) unsafe fn format_escaped_str_scalar(\n    odst: *mut u8,\n    value_ptr: *const u8,\n    value_len: usize,\n) -> usize {\n    unsafe {\n        let mut dst = odst;\n        let mut src = value_ptr;\n\n        core::ptr::write(dst, b'\"');\n        dst = dst.add(1);\n\n        impl_format_scalar!(dst, src, value_len);\n\n        core::ptr::write(dst, b'\"');\n        dst = dst.add(1);\n\n        dst as usize - odst as usize\n    }\n}\n"
  },
  {
    "path": "src/serialize/writer/str/sse2.rs",
    "content": "// SPDX-License-Identifier: MPL-2.0\n// Copyright ijl (2024-2025)\n\nuse core::arch::x86_64::{\n    __m128i, _mm_cmpeq_epi8, _mm_loadu_si128, _mm_movemask_epi8, _mm_or_si128, _mm_set1_epi8,\n    _mm_setzero_si128, _mm_storeu_si128, _mm_subs_epu8,\n};\n\n#[allow(dead_code)]\n#[expect(clippy::cast_ptr_alignment)]\n#[inline(never)]\npub(crate) unsafe fn format_escaped_str_impl_sse2_128(\n    odst: *mut u8,\n    value_ptr: *const u8,\n    value_len: usize,\n) -> usize {\n    unsafe {\n        const STRIDE: usize = 16;\n\n        let mut dst = odst;\n        let mut src = value_ptr;\n\n        core::ptr::write(dst, b'\"');\n        dst = dst.add(1);\n\n        if value_len < STRIDE {\n            impl_format_scalar!(dst, src, value_len);\n        } else {\n            let blash = _mm_set1_epi8(0b01011100i8);\n            let quote = _mm_set1_epi8(0b00100010i8);\n            let x20 = _mm_set1_epi8(0b00011111i8);\n            let v0 = _mm_setzero_si128();\n\n            let last_stride_src = src.add(value_len).sub(STRIDE);\n            let mut nb: usize = value_len;\n\n            unsafe {\n                while nb >= STRIDE {\n                    let str_vec = _mm_loadu_si128(src.cast::<__m128i>());\n\n                    let mask = _mm_movemask_epi8(_mm_or_si128(\n                        _mm_or_si128(\n                            _mm_cmpeq_epi8(str_vec, blash),\n                            _mm_cmpeq_epi8(str_vec, quote),\n                        ),\n                        _mm_cmpeq_epi8(_mm_subs_epu8(str_vec, x20), v0),\n                    ));\n\n                    _mm_storeu_si128(dst.cast::<__m128i>(), str_vec);\n\n                    if mask != 0 {\n                        let cn = mask.trailing_zeros() as usize;\n                        nb -= cn;\n                        dst = dst.add(cn);\n                        src = src.add(cn);\n                        nb -= 1;\n                        write_escape!(*(src), dst);\n                        src = src.add(1);\n                    } else {\n                        nb -= STRIDE;\n                        dst = dst.add(STRIDE);\n                        src = src.add(STRIDE);\n                    }\n                }\n\n                let mut scratch: [u8; 32] = [b'a'; 32];\n                let mut str_vec = _mm_loadu_si128(last_stride_src.cast::<__m128i>());\n                _mm_storeu_si128(scratch.as_mut_ptr().cast::<__m128i>(), str_vec);\n\n                let mut scratch_ptr = scratch.as_mut_ptr().add(16 - nb);\n                str_vec = _mm_loadu_si128(scratch_ptr as *const __m128i);\n\n                let mut mask = _mm_movemask_epi8(_mm_or_si128(\n                    _mm_or_si128(\n                        _mm_cmpeq_epi8(str_vec, blash),\n                        _mm_cmpeq_epi8(str_vec, quote),\n                    ),\n                    _mm_cmpeq_epi8(_mm_subs_epu8(str_vec, x20), v0),\n                ));\n\n                loop {\n                    _mm_storeu_si128(dst.cast::<__m128i>(), str_vec);\n\n                    if mask != 0 {\n                        let cn = mask.trailing_zeros() as usize;\n                        nb -= cn;\n                        dst = dst.add(cn);\n                        scratch_ptr = scratch_ptr.add(cn);\n                        nb -= 1;\n                        mask >>= cn + 1;\n                        write_escape!(*(scratch_ptr), dst);\n                        scratch_ptr = scratch_ptr.add(1);\n                        str_vec = _mm_loadu_si128(scratch_ptr as *const __m128i);\n                    } else {\n                        dst = dst.add(nb);\n                        break;\n                    }\n                }\n            }\n        }\n\n        core::ptr::write(dst, b'\"');\n        dst = dst.add(1);\n\n        dst as usize - odst as usize\n    }\n}\n"
  },
  {
    "path": "src/typeref.rs",
    "content": "// SPDX-License-Identifier: (Apache-2.0 OR MIT)\n// Copyright ijl (2020-2026), Aviram Hassan (2020-2021), Nazar Kostetskyi (2022), Ben Sully (2021)\n\nuse core::ffi::CStr;\nuse core::ptr::{NonNull, null_mut};\nuse once_cell::race::OnceBox;\nuse std::sync::OnceLock;\n\nuse crate::ffi::{\n    Py_DECREF, Py_False, Py_INCREF, Py_None, Py_True, Py_XDECREF, PyBool_Type, PyBytes_Type,\n    PyDict_Type, PyErr_Clear, PyErr_NewException, PyExc_TypeError, PyFloat_Type,\n    PyImport_ImportModule, PyList_Type, PyLong_Type, PyMapping_GetItemString, PyObject,\n    PyObject_GenericGetDict, PyTuple_Type, PyTypeObject, PyUnicode_InternFromString, PyUnicode_New,\n    PyUnicode_Type, orjson_fragmenttype_new,\n};\n\npub(crate) static mut DEFAULT: *mut PyObject = null_mut();\npub(crate) static mut OPTION: *mut PyObject = null_mut();\n\npub(crate) static mut NONE: *mut PyObject = null_mut();\npub(crate) static mut TRUE: *mut PyObject = null_mut();\npub(crate) static mut FALSE: *mut PyObject = null_mut();\npub(crate) static mut EMPTY_UNICODE: *mut PyObject = null_mut();\n\npub(crate) static mut BYTES_TYPE: *mut PyTypeObject = null_mut();\npub(crate) static mut STR_TYPE: *mut PyTypeObject = null_mut();\npub(crate) static mut INT_TYPE: *mut PyTypeObject = null_mut();\npub(crate) static mut BOOL_TYPE: *mut PyTypeObject = null_mut();\npub(crate) static mut NONE_TYPE: *mut PyTypeObject = null_mut();\npub(crate) static mut FLOAT_TYPE: *mut PyTypeObject = null_mut();\npub(crate) static mut LIST_TYPE: *mut PyTypeObject = null_mut();\npub(crate) static mut DICT_TYPE: *mut PyTypeObject = null_mut();\npub(crate) static mut DATETIME_TYPE: *mut PyTypeObject = null_mut();\npub(crate) static mut DATE_TYPE: *mut PyTypeObject = null_mut();\npub(crate) static mut TIME_TYPE: *mut PyTypeObject = null_mut();\npub(crate) static mut TUPLE_TYPE: *mut PyTypeObject = null_mut();\npub(crate) static mut UUID_TYPE: *mut PyTypeObject = null_mut();\npub(crate) static mut ENUM_TYPE: *mut PyTypeObject = null_mut();\npub(crate) static mut FIELD_TYPE: *mut PyTypeObject = null_mut();\npub(crate) static mut FRAGMENT_TYPE: *mut PyTypeObject = null_mut();\n\npub(crate) static mut ZONEINFO_TYPE: *mut PyTypeObject = null_mut();\n\npub(crate) static mut UTCOFFSET_METHOD_STR: *mut PyObject = null_mut();\npub(crate) static mut NORMALIZE_METHOD_STR: *mut PyObject = null_mut();\npub(crate) static mut CONVERT_METHOD_STR: *mut PyObject = null_mut();\npub(crate) static mut DST_STR: *mut PyObject = null_mut();\n\npub(crate) static mut DICT_STR: *mut PyObject = null_mut();\npub(crate) static mut DATACLASS_FIELDS_STR: *mut PyObject = null_mut();\npub(crate) static mut SLOTS_STR: *mut PyObject = null_mut();\npub(crate) static mut FIELD_TYPE_STR: *mut PyObject = null_mut();\npub(crate) static mut ARRAY_STRUCT_STR: *mut PyObject = null_mut();\npub(crate) static mut DTYPE_STR: *mut PyObject = null_mut();\npub(crate) static mut DESCR_STR: *mut PyObject = null_mut();\npub(crate) static mut VALUE_STR: *mut PyObject = null_mut();\npub(crate) static mut INT_ATTR_STR: *mut PyObject = null_mut();\n\n#[allow(non_upper_case_globals)]\npub(crate) static mut JsonEncodeError: *mut PyObject = null_mut();\n#[allow(non_upper_case_globals)]\npub(crate) static mut JsonDecodeError: *mut PyObject = null_mut();\n\nunsafe fn look_up_type_object(module_name: &CStr, member_name: &CStr) -> *mut PyTypeObject {\n    unsafe {\n        let module = PyImport_ImportModule(module_name.as_ptr());\n        let module_dict = PyObject_GenericGetDict(module, null_mut());\n        let ptr = PyMapping_GetItemString(module_dict, member_name.as_ptr()).cast::<PyTypeObject>();\n        Py_DECREF(module_dict);\n        Py_DECREF(module);\n        ptr\n    }\n}\n\n#[cfg(not(PyPy))]\nunsafe fn look_up_datetime() {\n    unsafe {\n        crate::ffi::PyDateTime_IMPORT();\n        let datetime_capsule = crate::ffi::PyCapsule_Import(c\"datetime.datetime_CAPI\".as_ptr(), 1)\n            .cast::<crate::ffi::PyDateTime_CAPI>();\n        debug_assert!(!datetime_capsule.is_null());\n\n        DATETIME_TYPE = (*datetime_capsule).DateTimeType;\n        DATE_TYPE = (*datetime_capsule).DateType;\n        TIME_TYPE = (*datetime_capsule).TimeType;\n        ZONEINFO_TYPE = (*datetime_capsule).TZInfoType;\n    }\n}\n\n#[cfg(PyPy)]\nunsafe fn look_up_datetime() {\n    unsafe {\n        DATETIME_TYPE = look_up_type_object(c\"datetime\", c\"datetime\");\n        DATE_TYPE = look_up_type_object(c\"datetime\", c\"date\");\n        TIME_TYPE = look_up_type_object(c\"datetime\", c\"time\");\n        ZONEINFO_TYPE = look_up_type_object(c\"zoneinfo\", c\"ZoneInfo\");\n    }\n}\n\nstatic INIT: OnceLock<bool> = OnceLock::new();\n\npub(crate) fn init_typerefs() {\n    INIT.get_or_init(_init_typerefs_impl);\n}\n\n#[cold]\n#[cfg_attr(feature = \"optimize\", optimize(size))]\nfn _init_typerefs_impl() -> bool {\n    unsafe {\n        debug_assert!(crate::opt::MAX_OPT < i32::from(u16::MAX));\n\n        #[cfg(not(Py_GIL_DISABLED))]\n        assert!(\n            crate::deserialize::KEY_MAP\n                .set(crate::deserialize::KeyMap::default())\n                .is_ok()\n        );\n\n        crate::serialize::writer::set_str_formatter_fn();\n        crate::ffi::set_str_create_fn();\n\n        NONE = Py_None();\n        TRUE = Py_True();\n        FALSE = Py_False();\n        EMPTY_UNICODE = PyUnicode_New(0, 255);\n\n        STR_TYPE = &raw mut PyUnicode_Type;\n        BYTES_TYPE = &raw mut PyBytes_Type;\n        DICT_TYPE = &raw mut PyDict_Type;\n        LIST_TYPE = &raw mut PyList_Type;\n        TUPLE_TYPE = &raw mut PyTuple_Type;\n        NONE_TYPE = ob_type!(NONE);\n        BOOL_TYPE = &raw mut PyBool_Type;\n        INT_TYPE = &raw mut PyLong_Type;\n        FLOAT_TYPE = &raw mut PyFloat_Type;\n\n        look_up_datetime();\n\n        UUID_TYPE = look_up_type_object(c\"uuid\", c\"UUID\");\n        ENUM_TYPE = look_up_type_object(c\"enum\", c\"EnumMeta\");\n        FIELD_TYPE = look_up_type_object(c\"dataclasses\", c\"_FIELD\");\n\n        FRAGMENT_TYPE = orjson_fragmenttype_new();\n\n        INT_ATTR_STR = PyUnicode_InternFromString(c\"int\".as_ptr());\n        UTCOFFSET_METHOD_STR = PyUnicode_InternFromString(c\"utcoffset\".as_ptr());\n        NORMALIZE_METHOD_STR = PyUnicode_InternFromString(c\"normalize\".as_ptr());\n        CONVERT_METHOD_STR = PyUnicode_InternFromString(c\"convert\".as_ptr());\n        DST_STR = PyUnicode_InternFromString(c\"dst\".as_ptr());\n        DICT_STR = PyUnicode_InternFromString(c\"__dict__\".as_ptr());\n        DATACLASS_FIELDS_STR = PyUnicode_InternFromString(c\"__dataclass_fields__\".as_ptr());\n        SLOTS_STR = PyUnicode_InternFromString(c\"__slots__\".as_ptr());\n        FIELD_TYPE_STR = PyUnicode_InternFromString(c\"_field_type\".as_ptr());\n        ARRAY_STRUCT_STR = PyUnicode_InternFromString(c\"__array_struct__\".as_ptr());\n        DTYPE_STR = PyUnicode_InternFromString(c\"dtype\".as_ptr());\n        DESCR_STR = PyUnicode_InternFromString(c\"descr\".as_ptr());\n        VALUE_STR = PyUnicode_InternFromString(c\"value\".as_ptr());\n        DEFAULT = PyUnicode_InternFromString(c\"default\".as_ptr());\n        OPTION = PyUnicode_InternFromString(c\"option\".as_ptr());\n\n        JsonEncodeError = PyExc_TypeError;\n        Py_INCREF(JsonEncodeError);\n        let json_jsondecodeerror =\n            look_up_type_object(c\"json\", c\"JSONDecodeError\").cast::<PyObject>();\n        debug_assert!(!json_jsondecodeerror.is_null());\n        JsonDecodeError = PyErr_NewException(\n            c\"orjson.JSONDecodeError\".as_ptr(),\n            json_jsondecodeerror,\n            null_mut(),\n        );\n        debug_assert!(!JsonDecodeError.is_null());\n        Py_XDECREF(json_jsondecodeerror);\n    };\n    true\n}\n\npub(crate) struct NumpyTypes {\n    pub array: *mut PyTypeObject,\n    pub float64: *mut PyTypeObject,\n    pub float32: *mut PyTypeObject,\n    pub float16: *mut PyTypeObject,\n    pub int64: *mut PyTypeObject,\n    pub int32: *mut PyTypeObject,\n    pub int16: *mut PyTypeObject,\n    pub int8: *mut PyTypeObject,\n    pub uint64: *mut PyTypeObject,\n    pub uint32: *mut PyTypeObject,\n    pub uint16: *mut PyTypeObject,\n    pub uint8: *mut PyTypeObject,\n    pub bool_: *mut PyTypeObject,\n    pub datetime64: *mut PyTypeObject,\n}\n\npub(crate) static mut NUMPY_TYPES: OnceBox<Option<NonNull<NumpyTypes>>> = OnceBox::new();\n\nunsafe fn look_up_numpy_type(\n    numpy_module_dict: *mut PyObject,\n    np_type: &CStr,\n) -> *mut PyTypeObject {\n    unsafe {\n        let ptr = PyMapping_GetItemString(numpy_module_dict, np_type.as_ptr());\n        Py_XDECREF(ptr);\n        ptr.cast::<PyTypeObject>()\n    }\n}\n\n#[cold]\n#[cfg_attr(feature = \"optimize\", optimize(size))]\npub(crate) fn load_numpy_types() -> Box<Option<NonNull<NumpyTypes>>> {\n    unsafe {\n        let numpy = PyImport_ImportModule(c\"numpy\".as_ptr());\n        if numpy.is_null() {\n            PyErr_Clear();\n            return Box::new(None);\n        }\n        let numpy_module_dict = PyObject_GenericGetDict(numpy, null_mut());\n        let types = Box::new(NumpyTypes {\n            array: look_up_numpy_type(numpy_module_dict, c\"ndarray\"),\n            float16: look_up_numpy_type(numpy_module_dict, c\"half\"),\n            float32: look_up_numpy_type(numpy_module_dict, c\"float32\"),\n            float64: look_up_numpy_type(numpy_module_dict, c\"float64\"),\n            int8: look_up_numpy_type(numpy_module_dict, c\"int8\"),\n            int16: look_up_numpy_type(numpy_module_dict, c\"int16\"),\n            int32: look_up_numpy_type(numpy_module_dict, c\"int32\"),\n            int64: look_up_numpy_type(numpy_module_dict, c\"int64\"),\n            uint16: look_up_numpy_type(numpy_module_dict, c\"uint16\"),\n            uint32: look_up_numpy_type(numpy_module_dict, c\"uint32\"),\n            uint64: look_up_numpy_type(numpy_module_dict, c\"uint64\"),\n            uint8: look_up_numpy_type(numpy_module_dict, c\"uint8\"),\n            bool_: look_up_numpy_type(numpy_module_dict, c\"bool_\"),\n            datetime64: look_up_numpy_type(numpy_module_dict, c\"datetime64\"),\n        });\n        Py_XDECREF(numpy_module_dict);\n        Py_XDECREF(numpy);\n        Box::new(Some(nonnull!(Box::<NumpyTypes>::into_raw(types))))\n    }\n}\n"
  },
  {
    "path": "src/util.rs",
    "content": "// SPDX-License-Identifier: (Apache-2.0 OR MIT)\n// Copyright ijl (2019-2026), Marc Mueller (2023)\n\npub(crate) const INVALID_STR: &str = \"str is not valid UTF-8: surrogates not allowed\";\n\nmacro_rules! is_type {\n    ($obj_ptr:expr, $type_ptr:expr) => {\n        unsafe { $obj_ptr == $type_ptr }\n    };\n}\n\n#[cfg(CPython)]\nmacro_rules! ob_type {\n    ($obj:expr) => {\n        unsafe { (*$obj).ob_type }\n    };\n}\n\n#[cfg(not(CPython))]\nmacro_rules! ob_type {\n    ($obj:expr) => {\n        unsafe { crate::ffi::Py_TYPE($obj) }\n    };\n}\n\nmacro_rules! is_class_by_type {\n    ($ob_type:expr, $type_ptr:ident) => {\n        unsafe { $ob_type == $type_ptr }\n    };\n}\n\n#[cfg(not(Py_GIL_DISABLED))]\nmacro_rules! tp_flags {\n    ($ob_type:expr) => {\n        unsafe { (*$ob_type).tp_flags }\n    };\n}\n\n#[cfg(Py_GIL_DISABLED)]\nmacro_rules! tp_flags {\n    ($ob_type:expr) => {\n        unsafe {\n            (*$ob_type)\n                .tp_flags\n                .load(core::sync::atomic::Ordering::Relaxed)\n        }\n    };\n}\n\nmacro_rules! is_subclass_by_flag {\n    ($tp_flags:expr, $flag:ident) => {\n        unsafe { (($tp_flags & crate::ffi::$flag) != 0) }\n    };\n}\n\nmacro_rules! is_subclass_by_type {\n    ($ob_type:expr, $type:ident) => {\n        unsafe {\n            (*($ob_type.cast::<crate::ffi::PyTypeObject>()))\n                .ob_base\n                .ob_base\n                .ob_type\n                == $type\n        }\n    };\n}\n\nmacro_rules! err {\n    ($msg:expr) => {\n        return Err(serde::ser::Error::custom($msg))\n    };\n}\n\nmacro_rules! opt_enabled {\n    ($var:expr, $flag:expr) => {\n        $var & $flag != 0\n    };\n}\n\nmacro_rules! opt_disabled {\n    ($var:expr, $flag:expr) => {\n        $var & $flag == 0\n    };\n}\n\nmacro_rules! cold_path {\n    () => {\n        #[cfg(feature = \"cold_path\")]\n        core::hint::cold_path();\n    };\n}\n\nmacro_rules! nonnull {\n    ($exp:expr) => {\n        unsafe { core::ptr::NonNull::new_unchecked($exp) }\n    };\n}\n\nmacro_rules! str_from_slice {\n    ($ptr:expr, $size:expr) => {\n        unsafe { core::str::from_utf8_unchecked(core::slice::from_raw_parts($ptr, $size as usize)) }\n    };\n}\n\n#[cfg(all(Py_3_12, not(Py_GIL_DISABLED)))]\nmacro_rules! reverse_pydict_incref {\n    ($op:expr) => {\n        unsafe {\n            if crate::ffi::_Py_IsImmortal($op) == 0 {\n                debug_assert!(ffi!(Py_REFCNT($op)) >= 2);\n                (*$op).ob_refcnt.ob_refcnt -= 1;\n            }\n        }\n    };\n}\n\n#[cfg(Py_GIL_DISABLED)]\nmacro_rules! reverse_pydict_incref {\n    ($op:expr) => {\n        debug_assert!(ffi!(Py_REFCNT($op)) >= 2);\n        ffi!(Py_DECREF($op))\n    };\n}\n\n#[cfg(not(Py_3_12))]\nmacro_rules! reverse_pydict_incref {\n    ($op:expr) => {\n        unsafe {\n            debug_assert!(ffi!(Py_REFCNT($op)) >= 2);\n            (*$op).ob_refcnt -= 1;\n        }\n    };\n}\n\nmacro_rules! ffi {\n    ($fn:ident()) => {\n        unsafe { crate::ffi::$fn() }\n    };\n\n    ($fn:ident($obj1:expr)) => {\n        unsafe { crate::ffi::$fn($obj1) }\n    };\n\n    ($fn:ident($obj1:expr, $obj2:expr)) => {\n        unsafe { crate::ffi::$fn($obj1, $obj2) }\n    };\n\n    ($fn:ident($obj1:expr, $obj2:expr, $obj3:expr)) => {\n        unsafe { crate::ffi::$fn($obj1, $obj2, $obj3) }\n    };\n\n    ($fn:ident($obj1:expr, $obj2:expr, $obj3:expr, $obj4:expr)) => {\n        unsafe { crate::ffi::$fn($obj1, $obj2, $obj3, $obj4) }\n    };\n}\n\n#[cfg(CPython)]\nmacro_rules! call_method {\n    ($obj1:expr, $obj2:expr) => {\n        unsafe { crate::ffi::PyObject_CallMethodNoArgs($obj1, $obj2) }\n    };\n    ($obj1:expr, $obj2:expr, $obj3:expr) => {\n        unsafe { crate::ffi::PyObject_CallMethodOneArg($obj1, $obj2, $obj3) }\n    };\n}\n\n#[cfg(not(CPython))]\nmacro_rules! call_method {\n    ($obj1:expr, $obj2:expr) => {\n        unsafe { crate::ffi::PyObject_CallMethodObjArgs($obj1, $obj2) }\n    };\n    ($obj1:expr, $obj2:expr, $obj3:expr) => {\n        unsafe { crate::ffi::PyObject_CallMethodObjArgs($obj1, $obj2, $obj3) }\n    };\n}\n\n#[cfg(all(CPython, Py_3_13))]\nmacro_rules! pydict_contains {\n    ($obj1:expr, $obj2:expr) => {\n        unsafe { crate::ffi::PyDict_Contains(crate::ffi::PyType_GetDict($obj1), $obj2) == 1 }\n    };\n}\n\n#[cfg(all(CPython, Py_3_12, not(Py_3_13)))]\nmacro_rules! pydict_contains {\n    ($obj1:expr, $obj2:expr) => {\n        unsafe {\n            debug_assert!((*$obj2.cast::<crate::ffi::PyASCIIObject>()).hash != -1);\n            crate::ffi::_PyDict_Contains_KnownHash(\n                crate::ffi::PyType_GetDict($obj1),\n                $obj2,\n                (*$obj2.cast::<crate::ffi::PyASCIIObject>()).hash,\n            ) == 1\n        }\n    };\n}\n\n#[cfg(all(CPython, not(Py_3_12)))]\nmacro_rules! pydict_contains {\n    ($obj1:expr, $obj2:expr) => {\n        unsafe {\n            debug_assert!((*$obj2.cast::<crate::ffi::PyASCIIObject>()).hash != -1);\n            crate::ffi::_PyDict_Contains_KnownHash(\n                (*$obj1).tp_dict,\n                $obj2,\n                (*$obj2.cast::<crate::ffi::PyASCIIObject>()).hash,\n            ) == 1\n        }\n    };\n}\n\n#[cfg(not(CPython))]\nmacro_rules! pydict_contains {\n    ($obj1:expr, $obj2:expr) => {\n        unsafe { crate::ffi::PyDict_Contains((*$obj1).tp_dict, $obj2) == 1 }\n    };\n}\n\n#[cfg(Py_3_12)]\nmacro_rules! use_immortal {\n    ($op:expr) => {\n        unsafe { $op }\n    };\n}\n\n#[cfg(not(Py_3_12))]\nmacro_rules! use_immortal {\n    ($op:expr) => {\n        unsafe {\n            ffi!(Py_INCREF($op));\n            $op\n        }\n    };\n}\n\n#[cfg(all(CPython, not(Py_3_13)))]\nmacro_rules! pydict_next {\n    ($obj1:expr, $obj2:expr, $obj3:expr, $obj4:expr) => {\n        unsafe { crate::ffi::_PyDict_Next($obj1, $obj2, $obj3, $obj4, core::ptr::null_mut()) }\n    };\n}\n\n#[cfg(all(CPython, Py_3_13))]\nmacro_rules! pydict_next {\n    ($obj1:expr, $obj2:expr, $obj3:expr, $obj4:expr) => {\n        unsafe { crate::ffi::PyDict_Next($obj1, $obj2, $obj3, $obj4) }\n    };\n}\n\n#[cfg(not(CPython))]\nmacro_rules! pydict_next {\n    ($obj1:expr, $obj2:expr, $obj3:expr, $obj4:expr) => {\n        unsafe { crate::ffi::PyDict_Next($obj1, $obj2, $obj3, $obj4) }\n    };\n}\n\nmacro_rules! reserve_minimum {\n    ($writer:expr) => {\n        $writer.reserve(128);\n    };\n}\n\nmacro_rules! reserve_pretty {\n    ($writer:expr, $val:expr) => {\n        $writer.reserve($val + 32);\n    };\n}\n\nmacro_rules! assume {\n    ($expr:expr) => {\n        debug_assert!($expr);\n        unsafe {\n            core::hint::assert_unchecked($expr);\n        };\n    };\n}\n\nmacro_rules! unreachable_unchecked {\n    () => {\n        unsafe { core::hint::unreachable_unchecked() }\n    };\n}\n\n#[inline(always)]\n#[allow(clippy::cast_possible_wrap)]\npub(crate) fn usize_to_isize(val: usize) -> isize {\n    debug_assert!(val < (isize::MAX as usize));\n    val as isize\n}\n\n#[inline(always)]\npub(crate) fn isize_to_usize(val: isize) -> usize {\n    debug_assert!(val >= 0);\n    val.cast_unsigned()\n}\n"
  },
  {
    "path": "test/__init__.py",
    "content": ""
  },
  {
    "path": "test/requirements.txt",
    "content": "faker\nnumpy;(platform_machine==\"x86_64\" or (platform_machine==\"aarch64\" and sys_platform == \"linux\")) and python_version<\"3.15\" and implementation_name==\"cpython\"\npendulum;sys_platform==\"linux\" and platform_machine==\"x86_64\" and python_version<\"3.15\" and implementation_name==\"cpython\"\npsutil;(sys_platform==\"linux\" or sys_platform == \"macos\") and platform_machine==\"x86_64\" and python_version<\"3.14\" and implementation_name==\"cpython\"\npytest\npython-dateutil >=2,<3;python_version<\"3.15\" and implementation_name==\"cpython\"\npytz\n"
  },
  {
    "path": "test/test_api.py",
    "content": "# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2018-2025), hauntsaninja (2020)\n\nimport datetime\nimport inspect\nimport json\nimport re\n\nimport pytest\n\nimport orjson\n\nSIMPLE_TYPES = (1, 1.0, -1, None, \"str\", True, False)\n\nLOADS_RECURSION_LIMIT = 1024\n\n\ndef default(obj):\n    return str(obj)\n\n\nclass TestApi:\n    def test_loads_trailing(self):\n        \"\"\"\n        loads() handles trailing whitespace\n        \"\"\"\n        assert orjson.loads(\"{}\\n\\t \") == {}\n\n    def test_loads_trailing_invalid(self):\n        \"\"\"\n        loads() handles trailing invalid\n        \"\"\"\n        pytest.raises(orjson.JSONDecodeError, orjson.loads, \"{}\\n\\t a\")\n\n    def test_simple_json(self):\n        \"\"\"\n        dumps() equivalent to json on simple types\n        \"\"\"\n        for obj in SIMPLE_TYPES:\n            assert orjson.dumps(obj) == json.dumps(obj).encode(\"utf-8\")\n\n    def test_simple_round_trip(self):\n        \"\"\"\n        dumps(), loads() round trip on simple types\n        \"\"\"\n        for obj in SIMPLE_TYPES:\n            assert orjson.loads(orjson.dumps(obj)) == obj\n\n    def test_loads_type(self):\n        \"\"\"\n        loads() invalid type\n        \"\"\"\n        for val in (1, 3.14, [], {}, None):  # type: ignore\n            pytest.raises(orjson.JSONDecodeError, orjson.loads, val)\n\n    def test_loads_recursion_partial(self):\n        \"\"\"\n        loads() recursion limit partial\n        \"\"\"\n        pytest.raises(orjson.JSONDecodeError, orjson.loads, \"[\" * (1024 * 1024))\n\n    def test_loads_recursion_valid_limit_array(self):\n        \"\"\"\n        loads() recursion limit at limit array\n        \"\"\"\n        n = LOADS_RECURSION_LIMIT + 1\n        value = b\"[\" * n + b\"]\" * n\n        pytest.raises(orjson.JSONDecodeError, orjson.loads, value)\n\n    def test_loads_recursion_valid_limit_object(self):\n        \"\"\"\n        loads() recursion limit at limit object\n        \"\"\"\n        n = LOADS_RECURSION_LIMIT\n        value = b'{\"key\":' * n + b'{\"key\":true}' + b\"}\" * n\n        pytest.raises(orjson.JSONDecodeError, orjson.loads, value)\n\n    def test_loads_recursion_valid_limit_mixed(self):\n        \"\"\"\n        loads() recursion limit at limit mixed\n        \"\"\"\n        n = LOADS_RECURSION_LIMIT\n        value = b\"\".join((b\"[\", b'{\"key\":' * n, b'{\"key\":true}' + b\"}\" * n, b\"]\"))\n        pytest.raises(orjson.JSONDecodeError, orjson.loads, value)\n\n    def test_loads_recursion_valid_excessive_array(self):\n        \"\"\"\n        loads() recursion limit excessively high value\n        \"\"\"\n        n = 10000000\n        value = b\"[\" * n + b\"]\" * n\n        pytest.raises(orjson.JSONDecodeError, orjson.loads, value)\n\n    def test_loads_recursion_valid_limit_array_pretty(self):\n        \"\"\"\n        loads() recursion limit at limit array pretty\n        \"\"\"\n        n = LOADS_RECURSION_LIMIT + 1\n        value = b\"[\\n  \" * n + b\"]\" * n\n        pytest.raises(orjson.JSONDecodeError, orjson.loads, value)\n\n    def test_loads_recursion_valid_limit_object_pretty(self):\n        \"\"\"\n        loads() recursion limit at limit object pretty\n        \"\"\"\n        n = LOADS_RECURSION_LIMIT\n        value = b'{\\n  \"key\":' * n + b'{\"key\":true}' + b\"}\" * n\n        pytest.raises(orjson.JSONDecodeError, orjson.loads, value)\n\n    def test_loads_recursion_valid_limit_mixed_pretty(self):\n        \"\"\"\n        loads() recursion limit at limit mixed pretty\n        \"\"\"\n        n = LOADS_RECURSION_LIMIT\n        value = b'[\\n  {\"key\":' * n + b'{\"key\":true}' + b\"}\" * n + b\"]\"\n        pytest.raises(orjson.JSONDecodeError, orjson.loads, value)\n\n    def test_loads_recursion_valid_excessive_array_pretty(self):\n        \"\"\"\n        loads() recursion limit excessively high value pretty\n        \"\"\"\n        n = 10000000\n        value = b\"[\\n  \" * n + b\"]\" * n\n        pytest.raises(orjson.JSONDecodeError, orjson.loads, value)\n\n    def test_version(self):\n        \"\"\"\n        __version__\n        \"\"\"\n        assert re.match(r\"^\\d+\\.\\d+(\\.\\d+)?$\", orjson.__version__)\n\n    def test_valueerror(self):\n        \"\"\"\n        orjson.JSONDecodeError is a subclass of ValueError\n        \"\"\"\n        pytest.raises(orjson.JSONDecodeError, orjson.loads, \"{\")\n        pytest.raises(ValueError, orjson.loads, \"{\")\n\n    def test_optional_none(self):\n        \"\"\"\n        dumps() option, default None\n        \"\"\"\n        assert orjson.dumps([], option=None) == b\"[]\"\n        assert orjson.dumps([], default=None) == b\"[]\"\n        assert orjson.dumps([], option=None, default=None) == b\"[]\"\n        assert orjson.dumps([], None, None) == b\"[]\"\n\n    def test_option_not_int(self):\n        \"\"\"\n        dumps() option not int or None\n        \"\"\"\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(True, option=True)\n\n    def test_option_invalid_int(self):\n        \"\"\"\n        dumps() option invalid 64-bit number\n        \"\"\"\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(True, option=9223372036854775809)\n\n    def test_option_range_low(self):\n        \"\"\"\n        dumps() option out of range low\n        \"\"\"\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(True, option=-1)\n\n    def test_option_range_high(self):\n        \"\"\"\n        dumps() option out of range high\n        \"\"\"\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(True, option=1 << 12)\n\n    def test_opts_multiple(self):\n        \"\"\"\n        dumps() multiple option\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [1, datetime.datetime(2000, 1, 1, 2, 3, 4)],\n                option=orjson.OPT_STRICT_INTEGER | orjson.OPT_NAIVE_UTC,\n            )\n            == b'[1,\"2000-01-01T02:03:04+00:00\"]'\n        )\n\n    def test_default_positional(self):\n        \"\"\"\n        dumps() positional arg\n        \"\"\"\n        with pytest.raises(TypeError):\n            orjson.dumps(__obj={})  # type: ignore\n        with pytest.raises(TypeError):\n            orjson.dumps(zxc={})  # type: ignore\n\n    def test_default_unknown_kwarg(self):\n        \"\"\"\n        dumps() unknown kwarg\n        \"\"\"\n        with pytest.raises(TypeError):\n            orjson.dumps({}, zxc=default)  # type: ignore\n\n    def test_default_empty_kwarg(self):\n        \"\"\"\n        dumps() empty kwarg\n        \"\"\"\n        assert orjson.dumps(None) == b\"null\"\n\n    def test_default_twice(self):\n        \"\"\"\n        dumps() default twice\n        \"\"\"\n        with pytest.raises(TypeError):\n            orjson.dumps({}, default, default=default)  # type: ignore\n\n    def test_option_twice(self):\n        \"\"\"\n        dumps() option twice\n        \"\"\"\n        with pytest.raises(TypeError):\n            orjson.dumps({}, None, orjson.OPT_NAIVE_UTC, option=orjson.OPT_NAIVE_UTC)  # type: ignore\n\n    def test_option_mixed(self):\n        \"\"\"\n        dumps() option one arg, one kwarg\n        \"\"\"\n\n        class Custom:\n            def __str__(self):\n                return \"zxc\"\n\n        assert (\n            orjson.dumps(\n                [Custom(), datetime.datetime(2000, 1, 1, 2, 3, 4)],\n                default,\n                option=orjson.OPT_NAIVE_UTC,\n            )\n            == b'[\"zxc\",\"2000-01-01T02:03:04+00:00\"]'\n        )\n\n    def test_dumps_signature(self):\n        \"\"\"\n        dumps() valid __text_signature__\n        \"\"\"\n        assert (\n            str(inspect.signature(orjson.dumps))\n            == \"(obj, /, default=None, option=None)\"\n        )\n        inspect.signature(orjson.dumps).bind(\"str\")\n        inspect.signature(orjson.dumps).bind(\"str\", default=default, option=1)\n        inspect.signature(orjson.dumps).bind(\"str\", default=None, option=None)\n\n    def test_loads_signature(self):\n        \"\"\"\n        loads() valid __text_signature__\n        \"\"\"\n        assert str(inspect.signature(orjson.loads)), \"(obj == /)\"\n        inspect.signature(orjson.loads).bind(\"[]\")\n\n    def test_dumps_module_str(self):\n        \"\"\"\n        orjson.dumps.__module__ is a str\n        \"\"\"\n        assert orjson.dumps.__module__ == \"orjson\"\n\n    def test_loads_module_str(self):\n        \"\"\"\n        orjson.loads.__module__ is a str\n        \"\"\"\n        assert orjson.loads.__module__ == \"orjson\"\n\n    def test_bytes_buffer(self):\n        \"\"\"\n        dumps() trigger buffer growing where length is greater than growth\n        \"\"\"\n        a = \"a\" * 900\n        b = \"b\" * 4096\n        c = \"c\" * 4096 * 4096\n        assert orjson.dumps([a, b, c]) == f'[\"{a}\",\"{b}\",\"{c}\"]'.encode(\"utf-8\")\n\n    def test_bytes_null_terminated(self):\n        \"\"\"\n        dumps() PyBytesObject buffer is null-terminated\n        \"\"\"\n        # would raise ValueError: invalid literal for int() with base 10: b'1596728892'\n        int(orjson.dumps(1596728892))\n"
  },
  {
    "path": "test/test_append_newline.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2020-2025)\n\nimport orjson\n\nfrom .util import needs_data, read_fixture_obj\n\n\nclass TestAppendNewline:\n    def test_dumps_newline(self):\n        \"\"\"\n        dumps() OPT_APPEND_NEWLINE\n        \"\"\"\n        assert orjson.dumps([], option=orjson.OPT_APPEND_NEWLINE) == b\"[]\\n\"\n\n    @needs_data\n    def test_twitter_newline(self):\n        \"\"\"\n        loads(),dumps() twitter.json OPT_APPEND_NEWLINE\n        \"\"\"\n        val = read_fixture_obj(\"twitter.json.xz\")\n        assert orjson.loads(orjson.dumps(val, option=orjson.OPT_APPEND_NEWLINE)) == val\n\n    @needs_data\n    def test_canada(self):\n        \"\"\"\n        loads(), dumps() canada.json OPT_APPEND_NEWLINE\n        \"\"\"\n        val = read_fixture_obj(\"canada.json.xz\")\n        assert orjson.loads(orjson.dumps(val, option=orjson.OPT_APPEND_NEWLINE)) == val\n\n    @needs_data\n    def test_citm_catalog_newline(self):\n        \"\"\"\n        loads(), dumps() citm_catalog.json OPT_APPEND_NEWLINE\n        \"\"\"\n        val = read_fixture_obj(\"citm_catalog.json.xz\")\n        assert orjson.loads(orjson.dumps(val, option=orjson.OPT_APPEND_NEWLINE)) == val\n\n    @needs_data\n    def test_github_newline(self):\n        \"\"\"\n        loads(), dumps() github.json OPT_APPEND_NEWLINE\n        \"\"\"\n        val = read_fixture_obj(\"github.json.xz\")\n        assert orjson.loads(orjson.dumps(val, option=orjson.OPT_APPEND_NEWLINE)) == val\n"
  },
  {
    "path": "test/test_buffer.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2025)\n\nimport os\n\nimport pytest\n\nimport orjson\n\nORJSON_RUNNER_MEMORY_GIB = os.getenv(\"ORJSON_RUNNER_MEMORY_GIB\", \"\")\n\n\n@pytest.mark.skipif(\n    not ORJSON_RUNNER_MEMORY_GIB,\n    reason=\"ORJSON_RUNNER_MEMORY_GIB not defined\",\n)\ndef test_memory_loads():\n    buffer_factor = 12\n    segment = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n    size = (\n        (int(ORJSON_RUNNER_MEMORY_GIB) * 1024 * 1024 * 1024)\n        // buffer_factor\n        // len(segment)\n    )\n    doc = \"\".join(segment for _ in range(size))\n    with pytest.raises(orjson.JSONDecodeError) as exc_info:\n        _ = orjson.loads(doc)\n    assert (\n        str(exc_info.value)\n        == \"Not enough memory to allocate buffer for parsing: line 1 column 1 (char 0)\"\n    )\n"
  },
  {
    "path": "test/test_canonical.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2019-2022)\n\nimport orjson\n\n\nclass TestCanonicalTests:\n    def test_dumps_ctrl_escape(self):\n        \"\"\"\n        dumps() ctrl characters\n        \"\"\"\n        assert orjson.dumps(\"text\\u0003\\r\\n\") == b'\"text\\\\u0003\\\\r\\\\n\"'\n\n    def test_dumps_escape_quote_backslash(self):\n        \"\"\"\n        dumps() quote, backslash escape\n        \"\"\"\n        assert orjson.dumps(r'\"\\ test') == b'\"\\\\\"\\\\\\\\ test\"'\n\n    def test_dumps_escape_line_separator(self):\n        \"\"\"\n        dumps() U+2028, U+2029 escape\n        \"\"\"\n        assert (\n            orjson.dumps({\"spaces\": \"\\u2028 \\u2029\"})\n            == b'{\"spaces\":\"\\xe2\\x80\\xa8 \\xe2\\x80\\xa9\"}'\n        )\n"
  },
  {
    "path": "test/test_circular.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2019-2023)\n\nimport pytest\n\nimport orjson\n\n\nclass TestCircular:\n    def test_circular_dict(self):\n        \"\"\"\n        dumps() circular reference dict\n        \"\"\"\n        obj = {}  # type: ignore\n        obj[\"obj\"] = obj\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(obj)\n\n    def test_circular_dict_sort_keys(self):\n        \"\"\"\n        dumps() circular reference dict OPT_SORT_KEYS\n        \"\"\"\n        obj = {}  # type: ignore\n        obj[\"obj\"] = obj\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(obj, option=orjson.OPT_SORT_KEYS)\n\n    def test_circular_dict_non_str_keys(self):\n        \"\"\"\n        dumps() circular reference dict OPT_NON_STR_KEYS\n        \"\"\"\n        obj = {}  # type: ignore\n        obj[\"obj\"] = obj\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(obj, option=orjson.OPT_NON_STR_KEYS)\n\n    def test_circular_list(self):\n        \"\"\"\n        dumps() circular reference list\n        \"\"\"\n        obj = []  # type: ignore\n        obj.append(obj)  # type: ignore\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(obj)\n\n    def test_circular_nested(self):\n        \"\"\"\n        dumps() circular reference nested dict, list\n        \"\"\"\n        obj = {}  # type: ignore\n        obj[\"list\"] = [{\"obj\": obj}]\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(obj)\n\n    def test_circular_nested_sort_keys(self):\n        \"\"\"\n        dumps() circular reference nested dict, list OPT_SORT_KEYS\n        \"\"\"\n        obj = {}  # type: ignore\n        obj[\"list\"] = [{\"obj\": obj}]\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(obj, option=orjson.OPT_SORT_KEYS)\n\n    def test_circular_nested_non_str_keys(self):\n        \"\"\"\n        dumps() circular reference nested dict, list OPT_NON_STR_KEYS\n        \"\"\"\n        obj = {}  # type: ignore\n        obj[\"list\"] = [{\"obj\": obj}]\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(obj, option=orjson.OPT_NON_STR_KEYS)\n"
  },
  {
    "path": "test/test_dataclass.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2019-2026)\n\nimport abc\nimport uuid\nfrom dataclasses import InitVar, asdict, dataclass, field\nfrom enum import Enum\nfrom typing import ClassVar, Optional\n\nimport pytest\n\nimport orjson\n\n\nclass AnEnum(Enum):\n    ONE = 1\n    TWO = 2\n\n\n@dataclass\nclass EmptyDataclass:\n    pass\n\n\n@dataclass\nclass EmptyDataclassSlots:\n    __slots__ = ()\n\n\n@dataclass\nclass Dataclass1:\n    name: str\n    number: int\n    sub: Optional[\"Dataclass1\"]\n\n\n@dataclass\nclass Dataclass2:\n    name: str | None = field(default=\"?\")\n\n\n@dataclass\nclass Dataclass3:\n    a: str\n    b: int\n    c: dict\n    d: bool\n    e: float\n    f: list\n    g: tuple\n\n\n@dataclass\nclass Dataclass4:\n    a: str = field()\n    b: int = field(metadata={\"unrelated\": False})\n    c: float = 1.1\n\n\n@dataclass\nclass Datasubclass(Dataclass1):\n    additional: bool\n\n\n@dataclass\nclass Slotsdataclass:\n    __slots__ = (\"_c\", \"a\", \"b\", \"d\")\n    a: str\n    b: int\n    _c: str\n    d: InitVar[str]\n    cls_var: ClassVar[str] = \"cls\"\n\n\n@dataclass\nclass Defaultdataclass:\n    a: uuid.UUID\n    b: AnEnum\n\n\n@dataclass\nclass UnsortedDataclass:\n    c: int\n    b: int\n    a: int\n    d: dict | None\n\n\n@dataclass\nclass InitDataclass:\n    a: InitVar[str]\n    b: InitVar[str]\n    cls_var: ClassVar[str] = \"cls\"\n    ab: str = \"\"\n\n    def __post_init__(self, a: str, b: str):\n        self._other = 1\n        self.ab = f\"{a} {b}\"\n\n\nclass AbstractBase(abc.ABC):\n    @abc.abstractmethod\n    def key(self):\n        raise NotImplementedError\n\n\n@dataclass(frozen=True)\nclass ConcreteAbc(AbstractBase):\n    __slots__ = (\"attr\",)\n\n    attr: float\n\n    def key(self):\n        return \"dkjf\"\n\n\nclass TestDataclass:\n    def test_dataclass(self):\n        \"\"\"\n        dumps() dataclass\n        \"\"\"\n        obj = Dataclass1(\"a\", 1, None)\n        assert orjson.dumps(obj) == b'{\"name\":\"a\",\"number\":1,\"sub\":null}'\n\n    def test_dataclass_recursive(self):\n        \"\"\"\n        dumps() dataclass recursive\n        \"\"\"\n        obj = Dataclass1(\"a\", 1, Dataclass1(\"b\", 2, None))\n        assert (\n            orjson.dumps(obj)\n            == b'{\"name\":\"a\",\"number\":1,\"sub\":{\"name\":\"b\",\"number\":2,\"sub\":null}}'\n        )\n\n    def test_dataclass_circular(self):\n        \"\"\"\n        dumps() dataclass circular\n        \"\"\"\n        obj1 = Dataclass1(\"a\", 1, None)\n        obj2 = Dataclass1(\"b\", 2, obj1)\n        obj1.sub = obj2\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(obj1)\n\n    def test_dataclass_empty(self):\n        \"\"\"\n        dumps() no attributes\n        \"\"\"\n        assert orjson.dumps(EmptyDataclass()) == b\"{}\"\n\n    def test_dataclass_empty_slots(self):\n        \"\"\"\n        dumps() no attributes slots\n        \"\"\"\n        assert orjson.dumps(EmptyDataclassSlots()) == b\"{}\"\n\n    def test_dataclass_default_arg(self):\n        \"\"\"\n        dumps() dataclass default arg\n        \"\"\"\n        obj = Dataclass2()\n        assert orjson.dumps(obj) == b'{\"name\":\"?\"}'\n\n    def test_dataclass_types(self):\n        \"\"\"\n        dumps() dataclass types\n        \"\"\"\n        obj = Dataclass3(\"a\", 1, {\"a\": \"b\"}, True, 1.1, [1, 2], (3, 4))\n        assert (\n            orjson.dumps(obj)\n            == b'{\"a\":\"a\",\"b\":1,\"c\":{\"a\":\"b\"},\"d\":true,\"e\":1.1,\"f\":[1,2],\"g\":[3,4]}'\n        )\n\n    def test_dataclass_metadata(self):\n        \"\"\"\n        dumps() dataclass metadata\n        \"\"\"\n        obj = Dataclass4(\"a\", 1, 2.1)\n        assert orjson.dumps(obj) == b'{\"a\":\"a\",\"b\":1,\"c\":2.1}'\n\n    def test_dataclass_classvar(self):\n        \"\"\"\n        dumps() dataclass class variable\n        \"\"\"\n        obj = Dataclass4(\"a\", 1)\n        assert orjson.dumps(obj) == b'{\"a\":\"a\",\"b\":1,\"c\":1.1}'\n\n    def test_dataclass_subclass(self):\n        \"\"\"\n        dumps() dataclass subclass\n        \"\"\"\n        obj = Datasubclass(\"a\", 1, None, False)\n        assert (\n            orjson.dumps(obj)\n            == b'{\"name\":\"a\",\"number\":1,\"sub\":null,\"additional\":false}'\n        )\n\n    def test_dataclass_slots(self):\n        \"\"\"\n        dumps() dataclass with __slots__ does not include under attributes, InitVar, or ClassVar\n        \"\"\"\n        obj = Slotsdataclass(\"a\", 1, \"c\", \"d\")\n        assert \"__dict__\" not in dir(obj)\n        assert orjson.dumps(obj) == b'{\"a\":\"a\",\"b\":1}'\n\n    def test_dataclass_default(self):\n        \"\"\"\n        dumps() dataclass with default\n        \"\"\"\n\n        def default(__obj):\n            if isinstance(__obj, uuid.UUID):\n                return str(__obj)\n            elif isinstance(__obj, Enum):\n                return __obj.value\n\n        obj = Defaultdataclass(\n            uuid.UUID(\"808989c0-00d5-48a8-b5c4-c804bf9032f2\"),\n            AnEnum.ONE,\n        )\n        assert (\n            orjson.dumps(obj, default=default)\n            == b'{\"a\":\"808989c0-00d5-48a8-b5c4-c804bf9032f2\",\"b\":1}'\n        )\n\n    def test_dataclass_sort(self):\n        \"\"\"\n        OPT_SORT_KEYS has no effect on dataclasses\n        \"\"\"\n        obj = UnsortedDataclass(1, 2, 3, None)\n        assert (\n            orjson.dumps(obj, option=orjson.OPT_SORT_KEYS)\n            == b'{\"c\":1,\"b\":2,\"a\":3,\"d\":null}'\n        )\n\n    def test_dataclass_sort_sub(self):\n        \"\"\"\n        dataclass fast path does not prevent OPT_SORT_KEYS from cascading\n        \"\"\"\n        obj = UnsortedDataclass(1, 2, 3, {\"f\": 2, \"e\": 1})\n        assert (\n            orjson.dumps(obj, option=orjson.OPT_SORT_KEYS)\n            == b'{\"c\":1,\"b\":2,\"a\":3,\"d\":{\"e\":1,\"f\":2}}'\n        )\n\n    def test_dataclass_under(self):\n        \"\"\"\n        dumps() does not include under attributes, InitVar, or ClassVar\n        \"\"\"\n        obj = InitDataclass(\"zxc\", \"vbn\")\n        assert orjson.dumps(obj) == b'{\"ab\":\"zxc vbn\"}'\n\n    def test_dataclass_option(self):\n        \"\"\"\n        dumps() accepts deprecated OPT_SERIALIZE_DATACLASS\n        \"\"\"\n        obj = Dataclass1(\"a\", 1, None)\n        assert (\n            orjson.dumps(obj, option=orjson.OPT_SERIALIZE_DATACLASS)\n            == b'{\"name\":\"a\",\"number\":1,\"sub\":null}'\n        )\n\n\nclass TestDataclassPassthrough:\n    def test_dataclass_passthrough_raise(self):\n        \"\"\"\n        dumps() dataclass passes to default with OPT_PASSTHROUGH_DATACLASS\n        \"\"\"\n        obj = Dataclass1(\"a\", 1, None)\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(obj, option=orjson.OPT_PASSTHROUGH_DATACLASS)\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(\n                InitDataclass(\"zxc\", \"vbn\"),\n                option=orjson.OPT_PASSTHROUGH_DATACLASS,\n            )\n\n    def test_dataclass_passthrough_default(self):\n        \"\"\"\n        dumps() dataclass passes to default with OPT_PASSTHROUGH_DATACLASS\n        \"\"\"\n        obj = Dataclass1(\"a\", 1, None)\n        assert (\n            orjson.dumps(obj, option=orjson.OPT_PASSTHROUGH_DATACLASS, default=asdict)\n            == b'{\"name\":\"a\",\"number\":1,\"sub\":null}'\n        )\n\n        def default(obj):\n            if isinstance(obj, Dataclass1):\n                return {\"name\": obj.name, \"number\": obj.number}\n            raise TypeError\n\n        assert (\n            orjson.dumps(obj, option=orjson.OPT_PASSTHROUGH_DATACLASS, default=default)\n            == b'{\"name\":\"a\",\"number\":1}'\n        )\n\n\nclass TestAbstractDataclass:\n    def test_dataclass_abc(self):\n        obj = ConcreteAbc(1.0)\n        assert orjson.dumps(obj) == b'{\"attr\":1.0}'\n"
  },
  {
    "path": "test/test_datetime.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2019-2025)\n\nimport datetime\n\nimport pytest\n\nimport orjson\n\ntry:\n    import zoneinfo\n\n    _ = zoneinfo.ZoneInfo(\"Europe/Amsterdam\")\nexcept Exception:  # ImportError,ZoneInfoNotFoundError\n    zoneinfo = None  # type: ignore\n\ntry:\n    import pytz\nexcept ImportError:\n    pytz = None  # type: ignore\n\ntry:\n    import pendulum\nexcept ImportError:\n    pendulum = None  # type: ignore\n\ntry:\n    from dateutil import tz\nexcept ImportError:\n    tz = None  # type: ignore\n\n\nAMSTERDAM_1937_DATETIMES = (\n    b'[\"1937-01-01T12:00:27.000087+00:20\"]',  # tzinfo<2022b and an example in RFC 3339\n    b'[\"1937-01-01T12:00:27.000087+00:00\"]',  # tzinfo>=2022b\n)\n\nAMSTERDAM_1937_DATETIMES_WITH_Z = (\n    b'[\"1937-01-01T12:00:27.000087+00:20\"]',\n    b'[\"1937-01-01T12:00:27.000087Z\"]',\n)\n\n\nclass TestDatetime:\n    def test_datetime_naive(self):\n        \"\"\"\n        datetime.datetime naive prints without offset\n        \"\"\"\n        assert (\n            orjson.dumps([datetime.datetime(2000, 1, 1, 2, 3, 4, 123)])\n            == b'[\"2000-01-01T02:03:04.000123\"]'\n        )\n\n    def test_datetime_naive_utc(self):\n        \"\"\"\n        datetime.datetime naive with opt assumes UTC\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [datetime.datetime(2000, 1, 1, 2, 3, 4, 123)],\n                option=orjson.OPT_NAIVE_UTC,\n            )\n            == b'[\"2000-01-01T02:03:04.000123+00:00\"]'\n        )\n\n    def test_datetime_min(self):\n        \"\"\"\n        datetime.datetime min range\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [datetime.datetime(datetime.MINYEAR, 1, 1, 0, 0, 0, 0)],\n                option=orjson.OPT_NAIVE_UTC,\n            )\n            == b'[\"0001-01-01T00:00:00+00:00\"]'\n        )\n\n    def test_datetime_max(self):\n        \"\"\"\n        datetime.datetime max range\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [datetime.datetime(datetime.MAXYEAR, 12, 31, 23, 59, 50, 999999)],\n                option=orjson.OPT_NAIVE_UTC,\n            )\n            == b'[\"9999-12-31T23:59:50.999999+00:00\"]'\n        )\n\n    def test_datetime_three_digits(self):\n        \"\"\"\n        datetime.datetime three digit year\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [datetime.datetime(312, 1, 1)],\n                option=orjson.OPT_NAIVE_UTC,\n            )\n            == b'[\"0312-01-01T00:00:00+00:00\"]'\n        )\n\n    def test_datetime_two_digits(self):\n        \"\"\"\n        datetime.datetime two digit year\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [datetime.datetime(46, 1, 1)],\n                option=orjson.OPT_NAIVE_UTC,\n            )\n            == b'[\"0046-01-01T00:00:00+00:00\"]'\n        )\n\n    @pytest.mark.skipif(tz is None, reason=\"dateutil optional\")\n    def test_datetime_tz_assume(self):\n        \"\"\"\n        datetime.datetime tz with assume UTC uses tz\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        2018,\n                        1,\n                        1,\n                        2,\n                        3,\n                        4,\n                        0,\n                        tzinfo=tz.gettz(\"Asia/Shanghai\"),\n                    ),\n                ],\n                option=orjson.OPT_NAIVE_UTC,\n            )\n            == b'[\"2018-01-01T02:03:04+08:00\"]'\n        )\n\n    def test_datetime_timezone_utc(self):\n        \"\"\"\n        datetime.datetime.utc\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        2018,\n                        6,\n                        1,\n                        2,\n                        3,\n                        4,\n                        0,\n                        tzinfo=datetime.timezone.utc,\n                    ),\n                ],\n            )\n            == b'[\"2018-06-01T02:03:04+00:00\"]'\n        )\n\n    @pytest.mark.skipif(pytz is None, reason=\"pytz optional\")\n    def test_datetime_pytz_utc(self):\n        \"\"\"\n        pytz.UTC\n        \"\"\"\n        assert (\n            orjson.dumps([datetime.datetime(2018, 6, 1, 2, 3, 4, 0, tzinfo=pytz.UTC)])\n            == b'[\"2018-06-01T02:03:04+00:00\"]'\n        )\n\n    @pytest.mark.skipif(zoneinfo is None, reason=\"zoneinfo not available\")\n    def test_datetime_zoneinfo_utc(self):\n        \"\"\"\n        zoneinfo.ZoneInfo(\"UTC\")\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        2018,\n                        6,\n                        1,\n                        2,\n                        3,\n                        4,\n                        0,\n                        tzinfo=zoneinfo.ZoneInfo(\"UTC\"),\n                    ),\n                ],\n            )\n            == b'[\"2018-06-01T02:03:04+00:00\"]'\n        )\n\n    @pytest.mark.skipif(zoneinfo is None, reason=\"zoneinfo not available\")\n    def test_datetime_zoneinfo_positive(self):\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        2018,\n                        1,\n                        1,\n                        2,\n                        3,\n                        4,\n                        0,\n                        tzinfo=zoneinfo.ZoneInfo(\"Asia/Shanghai\"),\n                    ),\n                ],\n            )\n            == b'[\"2018-01-01T02:03:04+08:00\"]'\n        )\n\n    @pytest.mark.skipif(zoneinfo is None, reason=\"zoneinfo not available\")\n    def test_datetime_zoneinfo_negative(self):\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        2018,\n                        6,\n                        1,\n                        2,\n                        3,\n                        4,\n                        0,\n                        tzinfo=zoneinfo.ZoneInfo(\"America/New_York\"),\n                    ),\n                ],\n            )\n            == b'[\"2018-06-01T02:03:04-04:00\"]'\n        )\n\n    @pytest.mark.skipif(pendulum is None, reason=\"pendulum not installed\")\n    def test_datetime_pendulum_utc(self):\n        \"\"\"\n        datetime.datetime UTC\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [datetime.datetime(2018, 6, 1, 2, 3, 4, 0, tzinfo=pendulum.UTC)],\n            )\n            == b'[\"2018-06-01T02:03:04+00:00\"]'\n        )\n\n    @pytest.mark.skipif(tz is None, reason=\"dateutil optional\")\n    def test_datetime_arrow_positive(self):\n        \"\"\"\n        datetime.datetime positive UTC\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        2018,\n                        1,\n                        1,\n                        2,\n                        3,\n                        4,\n                        0,\n                        tzinfo=tz.gettz(\"Asia/Shanghai\"),\n                    ),\n                ],\n            )\n            == b'[\"2018-01-01T02:03:04+08:00\"]'\n        )\n\n    @pytest.mark.skipif(pytz is None, reason=\"pytz optional\")\n    def test_datetime_pytz_positive(self):\n        \"\"\"\n        datetime.datetime positive UTC\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        2018,\n                        1,\n                        1,\n                        2,\n                        3,\n                        4,\n                        0,\n                        tzinfo=pytz.timezone(\"Asia/Shanghai\"),\n                    ),\n                ],\n            )\n            == b'[\"2018-01-01T02:03:04+08:00\"]'\n        )\n\n    @pytest.mark.skipif(pendulum is None, reason=\"pendulum not installed\")\n    def test_datetime_pendulum_positive(self):\n        \"\"\"\n        datetime.datetime positive UTC\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        2018,\n                        1,\n                        1,\n                        2,\n                        3,\n                        4,\n                        0,\n                        tzinfo=pendulum.timezone(\"Asia/Shanghai\"),  # type: ignore\n                    ),\n                ],\n            )\n            == b'[\"2018-01-01T02:03:04+08:00\"]'\n        )\n\n    @pytest.mark.skipif(pytz is None, reason=\"pytz optional\")\n    def test_datetime_pytz_negative_dst(self):\n        \"\"\"\n        datetime.datetime negative UTC DST\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        2018,\n                        6,\n                        1,\n                        2,\n                        3,\n                        4,\n                        0,\n                        tzinfo=pytz.timezone(\"America/New_York\"),\n                    ),\n                ],\n            )\n            == b'[\"2018-06-01T02:03:04-04:00\"]'\n        )\n\n    @pytest.mark.skipif(pendulum is None, reason=\"pendulum not installed\")\n    def test_datetime_pendulum_negative_dst(self):\n        \"\"\"\n        datetime.datetime negative UTC DST\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        2018,\n                        6,\n                        1,\n                        2,\n                        3,\n                        4,\n                        0,\n                        tzinfo=pendulum.timezone(\"America/New_York\"),  # type: ignore\n                    ),\n                ],\n            )\n            == b'[\"2018-06-01T02:03:04-04:00\"]'\n        )\n\n    @pytest.mark.skipif(zoneinfo is None, reason=\"zoneinfo not available\")\n    def test_datetime_zoneinfo_negative_non_dst(self):\n        \"\"\"\n        datetime.datetime negative UTC non-DST\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        2018,\n                        12,\n                        1,\n                        2,\n                        3,\n                        4,\n                        0,\n                        tzinfo=zoneinfo.ZoneInfo(\"America/New_York\"),\n                    ),\n                ],\n            )\n            == b'[\"2018-12-01T02:03:04-05:00\"]'\n        )\n\n    @pytest.mark.skipif(pytz is None, reason=\"pytz optional\")\n    def test_datetime_pytz_negative_non_dst(self):\n        \"\"\"\n        datetime.datetime negative UTC non-DST\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        2018,\n                        12,\n                        1,\n                        2,\n                        3,\n                        4,\n                        0,\n                        tzinfo=pytz.timezone(\"America/New_York\"),\n                    ),\n                ],\n            )\n            == b'[\"2018-12-01T02:03:04-05:00\"]'\n        )\n\n    @pytest.mark.skipif(pendulum is None, reason=\"pendulum not installed\")\n    def test_datetime_pendulum_negative_non_dst(self):\n        \"\"\"\n        datetime.datetime negative UTC non-DST\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        2018,\n                        12,\n                        1,\n                        2,\n                        3,\n                        4,\n                        0,\n                        tzinfo=pendulum.timezone(\"America/New_York\"),  # type: ignore\n                    ),\n                ],\n            )\n            == b'[\"2018-12-01T02:03:04-05:00\"]'\n        )\n\n    @pytest.mark.skipif(zoneinfo is None, reason=\"zoneinfo not available\")\n    def test_datetime_zoneinfo_partial_hour(self):\n        \"\"\"\n        datetime.datetime UTC offset partial hour\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        2018,\n                        12,\n                        1,\n                        2,\n                        3,\n                        4,\n                        0,\n                        tzinfo=zoneinfo.ZoneInfo(\"Australia/Adelaide\"),\n                    ),\n                ],\n            )\n            == b'[\"2018-12-01T02:03:04+10:30\"]'\n        )\n\n    @pytest.mark.skipif(pytz is None, reason=\"pytz optional\")\n    def test_datetime_pytz_partial_hour(self):\n        \"\"\"\n        datetime.datetime UTC offset partial hour\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        2018,\n                        12,\n                        1,\n                        2,\n                        3,\n                        4,\n                        0,\n                        tzinfo=pytz.timezone(\"Australia/Adelaide\"),\n                    ),\n                ],\n            )\n            == b'[\"2018-12-01T02:03:04+10:30\"]'\n        )\n\n    @pytest.mark.skipif(pendulum is None, reason=\"pendulum not installed\")\n    def test_datetime_pendulum_partial_hour(self):\n        \"\"\"\n        datetime.datetime UTC offset partial hour\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        2018,\n                        12,\n                        1,\n                        2,\n                        3,\n                        4,\n                        0,\n                        tzinfo=pendulum.timezone(\"Australia/Adelaide\"),  # type: ignore\n                    ),\n                ],\n            )\n            == b'[\"2018-12-01T02:03:04+10:30\"]'\n        )\n\n    @pytest.mark.skipif(pendulum is None, reason=\"pendulum not installed\")\n    def test_datetime_partial_second_pendulum_supported(self):\n        \"\"\"\n        datetime.datetime UTC offset round seconds\n\n        https://tools.ietf.org/html/rfc3339#section-5.8\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        1937,\n                        1,\n                        1,\n                        12,\n                        0,\n                        27,\n                        87,\n                        tzinfo=pendulum.timezone(\"Europe/Amsterdam\"),  # type: ignore\n                    ),\n                ],\n            )\n            in AMSTERDAM_1937_DATETIMES\n        )\n\n    @pytest.mark.skipif(zoneinfo is None, reason=\"zoneinfo not available\")\n    def test_datetime_partial_second_zoneinfo(self):\n        \"\"\"\n        datetime.datetime UTC offset round seconds\n\n        https://tools.ietf.org/html/rfc3339#section-5.8\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        1937,\n                        1,\n                        1,\n                        12,\n                        0,\n                        27,\n                        87,\n                        tzinfo=zoneinfo.ZoneInfo(\"Europe/Amsterdam\"),\n                    ),\n                ],\n            )\n            in AMSTERDAM_1937_DATETIMES\n        )\n\n    @pytest.mark.skipif(pytz is None, reason=\"pytz optional\")\n    def test_datetime_partial_second_pytz(self):\n        \"\"\"\n        datetime.datetime UTC offset round seconds\n\n        https://tools.ietf.org/html/rfc3339#section-5.8\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        1937,\n                        1,\n                        1,\n                        12,\n                        0,\n                        27,\n                        87,\n                        tzinfo=pytz.timezone(\"Europe/Amsterdam\"),\n                    ),\n                ],\n            )\n            in AMSTERDAM_1937_DATETIMES\n        )\n\n    @pytest.mark.skipif(tz is None, reason=\"dateutil optional\")\n    def test_datetime_partial_second_dateutil(self):\n        \"\"\"\n        datetime.datetime UTC offset round seconds\n\n        https://tools.ietf.org/html/rfc3339#section-5.8\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        1937,\n                        1,\n                        1,\n                        12,\n                        0,\n                        27,\n                        87,\n                        tzinfo=tz.gettz(\"Europe/Amsterdam\"),\n                    ),\n                ],\n            )\n            in AMSTERDAM_1937_DATETIMES\n        )\n\n    def test_datetime_microsecond_max(self):\n        \"\"\"\n        datetime.datetime microsecond max\n        \"\"\"\n        assert (\n            orjson.dumps(datetime.datetime(2000, 1, 1, 0, 0, 0, 999999))\n            == b'\"2000-01-01T00:00:00.999999\"'\n        )\n\n    def test_datetime_microsecond_min(self):\n        \"\"\"\n        datetime.datetime microsecond min\n        \"\"\"\n        assert (\n            orjson.dumps(datetime.datetime(2000, 1, 1, 0, 0, 0, 1))\n            == b'\"2000-01-01T00:00:00.000001\"'\n        )\n\n    def test_datetime_omit_microseconds(self):\n        \"\"\"\n        datetime.datetime OPT_OMIT_MICROSECONDS\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [datetime.datetime(2000, 1, 1, 2, 3, 4, 123)],\n                option=orjson.OPT_OMIT_MICROSECONDS,\n            )\n            == b'[\"2000-01-01T02:03:04\"]'\n        )\n\n    def test_datetime_omit_microseconds_naive(self):\n        \"\"\"\n        datetime.datetime naive OPT_OMIT_MICROSECONDS\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [datetime.datetime(2000, 1, 1, 2, 3, 4, 123)],\n                option=orjson.OPT_NAIVE_UTC | orjson.OPT_OMIT_MICROSECONDS,\n            )\n            == b'[\"2000-01-01T02:03:04+00:00\"]'\n        )\n\n    def test_time_omit_microseconds(self):\n        \"\"\"\n        datetime.time OPT_OMIT_MICROSECONDS\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [datetime.time(2, 3, 4, 123)],\n                option=orjson.OPT_OMIT_MICROSECONDS,\n            )\n            == b'[\"02:03:04\"]'\n        )\n\n    def test_datetime_utc_z_naive_omit(self):\n        \"\"\"\n        datetime.datetime naive OPT_UTC_Z\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [datetime.datetime(2000, 1, 1, 2, 3, 4, 123)],\n                option=orjson.OPT_NAIVE_UTC\n                | orjson.OPT_UTC_Z\n                | orjson.OPT_OMIT_MICROSECONDS,\n            )\n            == b'[\"2000-01-01T02:03:04Z\"]'\n        )\n\n    def test_datetime_utc_z_naive(self):\n        \"\"\"\n        datetime.datetime naive OPT_UTC_Z\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [datetime.datetime(2000, 1, 1, 2, 3, 4, 123)],\n                option=orjson.OPT_NAIVE_UTC | orjson.OPT_UTC_Z,\n            )\n            == b'[\"2000-01-01T02:03:04.000123Z\"]'\n        )\n\n    def test_datetime_utc_z_without_tz(self):\n        \"\"\"\n        datetime.datetime naive OPT_UTC_Z\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [datetime.datetime(2000, 1, 1, 2, 3, 4, 123)],\n                option=orjson.OPT_UTC_Z,\n            )\n            == b'[\"2000-01-01T02:03:04.000123\"]'\n        )\n\n    @pytest.mark.skipif(tz is None, reason=\"dateutil optional\")\n    def test_datetime_utc_z_with_tz(self):\n        \"\"\"\n        datetime.datetime naive OPT_UTC_Z\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        2000,\n                        1,\n                        1,\n                        0,\n                        0,\n                        0,\n                        1,\n                        tzinfo=datetime.timezone.utc,\n                    ),\n                ],\n                option=orjson.OPT_UTC_Z,\n            )\n            == b'[\"2000-01-01T00:00:00.000001Z\"]'\n        )\n        assert (\n            orjson.dumps(\n                [\n                    datetime.datetime(\n                        1937,\n                        1,\n                        1,\n                        12,\n                        0,\n                        27,\n                        87,\n                        tzinfo=tz.gettz(\"Europe/Amsterdam\"),\n                    ),\n                ],\n                option=orjson.OPT_UTC_Z,\n            )\n            in AMSTERDAM_1937_DATETIMES_WITH_Z\n        )\n\n    @pytest.mark.skipif(pendulum is None, reason=\"pendulum not installed\")\n    def test_datetime_roundtrip(self):\n        \"\"\"\n        datetime.datetime parsed by pendulum\n        \"\"\"\n        obj = datetime.datetime(2000, 1, 1, 0, 0, 0, 1, tzinfo=datetime.timezone.utc)\n        serialized = orjson.dumps(obj).decode(\"utf-8\").replace('\"', \"\")\n        parsed = pendulum.parse(serialized)\n        for attr in (\"year\", \"month\", \"day\", \"hour\", \"minute\", \"second\", \"microsecond\"):\n            assert getattr(obj, attr) == getattr(parsed, attr)\n\n\nclass TestDate:\n    def test_date(self):\n        \"\"\"\n        datetime.date\n        \"\"\"\n        assert orjson.dumps([datetime.date(2000, 1, 13)]) == b'[\"2000-01-13\"]'\n\n    def test_date_min(self):\n        \"\"\"\n        datetime.date MINYEAR\n        \"\"\"\n        assert (\n            orjson.dumps([datetime.date(datetime.MINYEAR, 1, 1)]) == b'[\"0001-01-01\"]'\n        )\n\n    def test_date_max(self):\n        \"\"\"\n        datetime.date MAXYEAR\n        \"\"\"\n        assert (\n            orjson.dumps([datetime.date(datetime.MAXYEAR, 12, 31)]) == b'[\"9999-12-31\"]'\n        )\n\n    def test_date_three_digits(self):\n        \"\"\"\n        datetime.date three digit year\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [datetime.date(312, 1, 1)],\n            )\n            == b'[\"0312-01-01\"]'\n        )\n\n    def test_date_two_digits(self):\n        \"\"\"\n        datetime.date two digit year\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [datetime.date(46, 1, 1)],\n            )\n            == b'[\"0046-01-01\"]'\n        )\n\n\nclass TestTime:\n    def test_time(self):\n        \"\"\"\n        datetime.time\n        \"\"\"\n        assert orjson.dumps([datetime.time(12, 15, 59, 111)]) == b'[\"12:15:59.000111\"]'\n        assert orjson.dumps([datetime.time(12, 15, 59)]) == b'[\"12:15:59\"]'\n\n    @pytest.mark.skipif(zoneinfo is None, reason=\"zoneinfo not available\")\n    def test_time_tz(self):\n        \"\"\"\n        datetime.time with tzinfo error\n        \"\"\"\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(\n                [\n                    datetime.time(\n                        12,\n                        15,\n                        59,\n                        111,\n                        tzinfo=zoneinfo.ZoneInfo(\"Asia/Shanghai\"),\n                    ),\n                ],\n            )\n\n    def test_time_microsecond_max(self):\n        \"\"\"\n        datetime.time microsecond max\n        \"\"\"\n        assert orjson.dumps(datetime.time(0, 0, 0, 999999)) == b'\"00:00:00.999999\"'\n\n    def test_time_microsecond_min(self):\n        \"\"\"\n        datetime.time microsecond min\n        \"\"\"\n        assert orjson.dumps(datetime.time(0, 0, 0, 1)) == b'\"00:00:00.000001\"'\n\n\nclass TestDateclassPassthrough:\n    def test_passthrough_datetime(self):\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(\n                datetime.datetime(1970, 1, 1),\n                option=orjson.OPT_PASSTHROUGH_DATETIME,\n            )\n\n    def test_passthrough_date(self):\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(\n                datetime.date(1970, 1, 1),\n                option=orjson.OPT_PASSTHROUGH_DATETIME,\n            )\n\n    def test_passthrough_time(self):\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(\n                datetime.time(12, 0, 0),\n                option=orjson.OPT_PASSTHROUGH_DATETIME,\n            )\n\n    def test_passthrough_datetime_default(self):\n        def default(obj):\n            return obj.strftime(\"%a, %d %b %Y %H:%M:%S GMT\")\n\n        assert (\n            orjson.dumps(\n                datetime.datetime(1970, 1, 1),\n                option=orjson.OPT_PASSTHROUGH_DATETIME,\n                default=default,\n            )\n            == b'\"Thu, 01 Jan 1970 00:00:00 GMT\"'\n        )\n"
  },
  {
    "path": "test/test_default.py",
    "content": "# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2019-2025), Rami Chowdhury (2020), Marc Mueller (2023), Jack Amadeo (2023)\n\nimport datetime\nimport sys\nimport uuid\n\nimport pytest\n\nimport orjson\n\nfrom .util import SUPPORTS_GETREFCOUNT, numpy\n\n\nclass Custom:\n    def __init__(self):\n        self.name = uuid.uuid4().hex\n\n    def __str__(self):\n        return f\"{self.__class__.__name__}({self.name})\"\n\n\nclass Recursive:\n    def __init__(self, cur):\n        self.cur = cur\n\n\ndef default_recursive(obj):\n    if obj.cur != 0:\n        obj.cur -= 1\n        return obj\n    return obj.cur\n\n\ndef default_raises(obj):\n    raise TypeError\n\n\nclass TestType:\n    def test_default_not_callable(self):\n        \"\"\"\n        dumps() default not callable\n        \"\"\"\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(Custom(), default=NotImplementedError)\n\n        ran = False\n        try:\n            orjson.dumps(Custom(), default=NotImplementedError)\n        except Exception as err:\n            assert isinstance(err, orjson.JSONEncodeError)\n            assert str(err) == \"default serializer exceeds recursion limit\"\n            ran = True\n        assert ran\n\n    def test_default_func(self):\n        \"\"\"\n        dumps() default function\n        \"\"\"\n        ref = Custom()\n\n        def default(obj):\n            return str(obj)\n\n        assert orjson.dumps(ref, default=default) == b'\"%s\"' % str(ref).encode(\"utf-8\")\n\n    def test_default_func_none(self):\n        \"\"\"\n        dumps() default function None ok\n        \"\"\"\n        assert orjson.dumps(Custom(), default=lambda x: None) == b\"null\"\n\n    def test_default_func_empty(self):\n        \"\"\"\n        dumps() default function no explicit return\n        \"\"\"\n        ref = Custom()\n\n        def default(obj):\n            if isinstance(obj, set):\n                return list(obj)\n\n        assert orjson.dumps(ref, default=default) == b\"null\"\n        assert orjson.dumps({ref}, default=default) == b\"[null]\"\n\n    def test_default_func_exc(self):\n        \"\"\"\n        dumps() default function raises exception\n        \"\"\"\n\n        def default(obj):\n            raise NotImplementedError\n\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(Custom(), default=default)\n\n        ran = False\n        try:\n            orjson.dumps(Custom(), default=default)\n        except Exception as err:\n            assert isinstance(err, orjson.JSONEncodeError)\n            assert str(err) == \"Type is not JSON serializable: Custom\"\n            ran = True\n        assert ran\n\n    def test_default_exception_type(self):\n        \"\"\"\n        dumps() TypeError in default() raises orjson.JSONEncodeError\n        \"\"\"\n        ref = Custom()\n\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(ref, default=default_raises)\n\n    def test_default_vectorcall_str(self):\n        \"\"\"\n        dumps() default function vectorcall str\n        \"\"\"\n\n        class SubStr(str):\n            pass\n\n        obj = SubStr(\"saasa\")\n        ref = b'\"%s\"' % str(obj).encode(\"utf-8\")\n        assert (\n            orjson.dumps(obj, option=orjson.OPT_PASSTHROUGH_SUBCLASS, default=str)\n            == ref\n        )\n\n    def test_default_vectorcall_list(self):\n        \"\"\"\n        dumps() default function vectorcall list\n        \"\"\"\n        obj = {1, 2}\n        ref = b\"[1,2]\"\n        assert orjson.dumps(obj, default=list) == ref\n\n    def test_default_func_nested_str(self):\n        \"\"\"\n        dumps() default function nested str\n        \"\"\"\n        ref = Custom()\n\n        def default(obj):\n            return str(obj)\n\n        assert orjson.dumps({\"a\": ref}, default=default) == b'{\"a\":\"%s\"}' % str(\n            ref,\n        ).encode(\"utf-8\")\n\n    def test_default_func_list(self):\n        \"\"\"\n        dumps() default function nested list\n        \"\"\"\n        ref = Custom()\n\n        def default(obj):\n            if isinstance(obj, Custom):\n                return [str(obj)]\n\n        assert orjson.dumps({\"a\": ref}, default=default) == b'{\"a\":[\"%s\"]}' % str(\n            ref,\n        ).encode(\"utf-8\")\n\n    def test_default_func_nested_list(self):\n        \"\"\"\n        dumps() default function list\n        \"\"\"\n        ref = Custom()\n\n        def default(obj):\n            return str(obj)\n\n        assert orjson.dumps([ref] * 100, default=default) == b\"[%s]\" % b\",\".join(\n            b'\"%s\"' % str(ref).encode(\"utf-8\") for _ in range(100)\n        )\n\n    def test_default_func_bytes(self):\n        \"\"\"\n        dumps() default function errors on non-str\n        \"\"\"\n        ref = Custom()\n\n        def default(obj):\n            return bytes(obj)\n\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(ref, default=default)\n\n        ran = False\n        try:\n            orjson.dumps(ref, default=default)\n        except Exception as err:\n            assert isinstance(err, orjson.JSONEncodeError)\n            assert str(err) == \"Type is not JSON serializable: Custom\"\n            ran = True\n        assert ran\n\n    def test_default_func_invalid_str(self):\n        \"\"\"\n        dumps() default function errors on invalid str\n        \"\"\"\n        ref = Custom()\n\n        def default(obj):\n            return \"\\ud800\"\n\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(ref, default=default)\n\n    def test_default_lambda_ok(self):\n        \"\"\"\n        dumps() default lambda\n        \"\"\"\n        ref = Custom()\n        assert orjson.dumps(ref, default=lambda x: str(x)) == b'\"%s\"' % str(ref).encode(\n            \"utf-8\",\n        )\n\n    def test_default_callable_ok(self):\n        \"\"\"\n        dumps() default callable\n        \"\"\"\n\n        class CustomSerializer:\n            def __init__(self):\n                self._cache = {}\n\n            def __call__(self, obj):\n                if obj not in self._cache:\n                    self._cache[obj] = str(obj)\n                return self._cache[obj]\n\n        ref_obj = Custom()\n        ref_bytes = b'\"%s\"' % str(ref_obj).encode(\"utf-8\")\n        for obj in [ref_obj] * 100:\n            assert orjson.dumps(obj, default=CustomSerializer()) == ref_bytes\n\n    def test_default_recursion(self):\n        \"\"\"\n        dumps() default recursion limit\n        \"\"\"\n        assert orjson.dumps(Recursive(254), default=default_recursive) == b\"0\"\n\n    def test_default_recursion_reset(self):\n        \"\"\"\n        dumps() default recursion limit reset\n        \"\"\"\n        assert (\n            orjson.dumps(\n                [Recursive(254), {\"a\": \"b\"}, Recursive(254), Recursive(254)],\n                default=default_recursive,\n            )\n            == b'[0,{\"a\":\"b\"},0,0]'\n        )\n\n    def test_default_recursion_infinite(self):\n        \"\"\"\n        dumps() default infinite recursion\n        \"\"\"\n        ref = Custom()\n\n        def default(obj):\n            return obj\n\n        if SUPPORTS_GETREFCOUNT:\n            refcount = sys.getrefcount(ref)\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(ref, default=default)\n        if SUPPORTS_GETREFCOUNT:\n            assert sys.getrefcount(ref) == refcount\n\n    def test_reference_cleanup_default_custom_pass(self):\n        ref = Custom()\n\n        def default(obj):\n            if isinstance(ref, Custom):\n                return str(ref)\n            raise TypeError\n\n        if SUPPORTS_GETREFCOUNT:\n            refcount = sys.getrefcount(ref)\n        orjson.dumps(ref, default=default)\n        if SUPPORTS_GETREFCOUNT:\n            assert sys.getrefcount(ref) == refcount\n\n    def test_reference_cleanup_default_custom_error(self):\n        \"\"\"\n        references to encoded objects are cleaned up\n        \"\"\"\n        ref = Custom()\n\n        def default(obj):\n            raise TypeError\n\n        if SUPPORTS_GETREFCOUNT:\n            refcount = sys.getrefcount(ref)\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(ref, default=default)\n        if SUPPORTS_GETREFCOUNT:\n            assert sys.getrefcount(ref) == refcount\n\n    def test_reference_cleanup_default_subclass(self):\n        ref = datetime.datetime(1970, 1, 1, 0, 0, 0)\n\n        def default(obj):\n            if isinstance(ref, datetime.datetime):\n                return repr(ref)\n            raise TypeError\n\n        if SUPPORTS_GETREFCOUNT:\n            refcount = sys.getrefcount(ref)\n        orjson.dumps(ref, option=orjson.OPT_PASSTHROUGH_DATETIME, default=default)\n        if SUPPORTS_GETREFCOUNT:\n            assert sys.getrefcount(ref) == refcount\n\n    def test_reference_cleanup_default_subclass_lambda(self):\n        ref = uuid.uuid4()\n\n        if SUPPORTS_GETREFCOUNT:\n            refcount = sys.getrefcount(ref)\n        orjson.dumps(\n            ref,\n            option=orjson.OPT_PASSTHROUGH_DATETIME,\n            default=lambda val: str(val),\n        )\n        if SUPPORTS_GETREFCOUNT:\n            assert sys.getrefcount(ref) == refcount\n\n    @pytest.mark.skipif(numpy is None, reason=\"numpy is not installed\")\n    def test_default_numpy(self):\n        ref = numpy.array([\"\"] * 100)  # type: ignore\n        if SUPPORTS_GETREFCOUNT:\n            refcount = sys.getrefcount(ref)\n        orjson.dumps(\n            ref,\n            option=orjson.OPT_SERIALIZE_NUMPY,\n            default=lambda val: val.tolist(),\n        )\n        if SUPPORTS_GETREFCOUNT:\n            assert sys.getrefcount(ref) == refcount\n\n    def test_default_set(self):\n        \"\"\"\n        dumps() default function with set\n        \"\"\"\n\n        def default(obj):\n            if isinstance(obj, set):\n                return list(obj)\n            raise TypeError\n\n        assert orjson.dumps({1, 2}, default=default) == b\"[1,2]\"\n"
  },
  {
    "path": "test/test_dict.py",
    "content": "# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2018-2025), J. Nick Koston (2022), Anders Kaseorg (2022)\n\nimport pytest\n\nimport orjson\n\n\nclass TestDict:\n    def test_dict(self):\n        \"\"\"\n        dict\n        \"\"\"\n        obj = {\"key\": \"value\"}\n        ref = '{\"key\":\"value\"}'\n        assert orjson.dumps(obj) == ref.encode(\"utf-8\")\n        assert orjson.loads(ref) == obj\n\n    def test_dict_duplicate_loads(self):\n        assert orjson.loads(b'{\"1\":true,\"1\":false}') == {\"1\": False}\n\n    def test_dict_empty(self):\n        obj = [{\"key\": [{}] * 4096}] * 4096  # type:ignore\n        assert orjson.loads(orjson.dumps(obj)) == obj\n\n    def test_dict_large_dict(self):\n        \"\"\"\n        dict with >512 keys\n        \"\"\"\n        obj = {f\"key_{idx}\": [{}, {\"a\": [{}, {}, {}]}, {}] for idx in range(513)}  # type: ignore\n        assert len(obj) == 513\n        assert orjson.loads(orjson.dumps(obj)) == obj\n\n    def test_dict_large_4096(self):\n        \"\"\"\n        dict with >4096 keys\n        \"\"\"\n        obj = {f\"key_{idx}\": f\"value_{idx}\" for idx in range(4097)}\n        assert len(obj) == 4097\n        assert orjson.loads(orjson.dumps(obj)) == obj\n\n    def test_dict_large_65536(self):\n        \"\"\"\n        dict with >65536 keys\n        \"\"\"\n        obj = {f\"key_{idx}\": f\"value_{idx}\" for idx in range(65537)}\n        assert len(obj) == 65537\n        assert orjson.loads(orjson.dumps(obj)) == obj\n\n    def test_dict_large_keys(self):\n        \"\"\"\n        dict with keys too large to cache\n        \"\"\"\n        obj = {\n            \"keeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeey\": \"value\",\n        }\n        ref = '{\"keeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeey\":\"value\"}'\n        assert orjson.dumps(obj) == ref.encode(\"utf-8\")\n        assert orjson.loads(ref) == obj\n\n    def test_dict_unicode(self):\n        \"\"\"\n        dict unicode keys\n        \"\"\"\n        obj = {\"🐈\": \"value\"}\n        ref = b'{\"\\xf0\\x9f\\x90\\x88\":\"value\"}'\n        assert orjson.dumps(obj) == ref\n        assert orjson.loads(ref) == obj\n        assert orjson.loads(ref)[\"🐈\"] == \"value\"\n\n    def test_dict_invalid_key_dumps(self):\n        \"\"\"\n        dict invalid key dumps()\n        \"\"\"\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps({1: \"value\"})\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps({b\"key\": \"value\"})\n\n    def test_dict_invalid_key_loads(self):\n        \"\"\"\n        dict invalid key loads()\n        \"\"\"\n        with pytest.raises(orjson.JSONDecodeError):\n            orjson.loads('{1:\"value\"}')\n        with pytest.raises(orjson.JSONDecodeError):\n            orjson.loads('{{\"a\":true}:true}')\n\n    def test_dict_similar_keys(self):\n        \"\"\"\n        loads() similar keys\n\n        This was a regression in 3.4.2 caused by using\n        the implementation in wy instead of wyhash.\n        \"\"\"\n        assert orjson.loads(\n            '{\"cf_status_firefox67\": \"---\", \"cf_status_firefox57\": \"verified\"}',\n        ) == {\"cf_status_firefox57\": \"verified\", \"cf_status_firefox67\": \"---\"}\n\n    def test_dict_pop_replace_first(self):\n        \"Test pop and replace a first key in a dict with other keys.\"\n        data = {\"id\": \"any\", \"other\": \"any\"}\n        data.pop(\"id\")\n        assert orjson.dumps(data) == b'{\"other\":\"any\"}'\n        data[\"id\"] = \"new\"\n        assert orjson.dumps(data) == b'{\"other\":\"any\",\"id\":\"new\"}'\n\n    def test_dict_pop_replace_last(self):\n        \"Test pop and replace a last key in a dict with other keys.\"\n        data = {\"other\": \"any\", \"id\": \"any\"}\n        data.pop(\"id\")\n        assert orjson.dumps(data) == b'{\"other\":\"any\"}'\n        data[\"id\"] = \"new\"\n        assert orjson.dumps(data) == b'{\"other\":\"any\",\"id\":\"new\"}'\n\n    def test_dict_pop(self):\n        \"Test pop and replace a key in a dict with no other keys.\"\n        data = {\"id\": \"any\"}\n        data.pop(\"id\")\n        assert orjson.dumps(data) == b\"{}\"\n        data[\"id\"] = \"new\"\n        assert orjson.dumps(data) == b'{\"id\":\"new\"}'\n\n    def test_in_place(self):\n        \"Mutate dict in-place\"\n        data = {\"id\": \"any\", \"static\": \"msg\"}\n        data[\"id\"] = \"new\"\n        assert orjson.dumps(data) == b'{\"id\":\"new\",\"static\":\"msg\"}'\n\n    def test_dict_0xff(self):\n        \"dk_size <= 0xff\"\n        data = {str(idx): idx for idx in range(0xFF)}\n        data.pop(\"112\")\n        data[\"112\"] = 1\n        data[\"113\"] = 2\n        assert orjson.loads(orjson.dumps(data)) == data\n\n    def test_dict_0xff_repeated(self):\n        \"dk_size <= 0xff repeated\"\n        for _ in range(100):\n            data = {str(idx): idx for idx in range(0xFF)}\n            data.pop(\"112\")\n            data[\"112\"] = 1\n            data[\"113\"] = 2\n            assert orjson.loads(orjson.dumps(data)) == data\n\n    def test_dict_0xffff(self):\n        \"dk_size <= 0xffff\"\n        data = {str(idx): idx for idx in range(0xFFFF)}\n        data.pop(\"112\")\n        data[\"112\"] = 1\n        data[\"113\"] = 2\n        assert orjson.loads(orjson.dumps(data)) == data\n\n    def test_dict_0xffff_repeated(self):\n        \"dk_size <= 0xffff repeated\"\n        for _ in range(100):\n            data = {str(idx): idx for idx in range(0xFFFF)}\n            data.pop(\"112\")\n            data[\"112\"] = 1\n            data[\"113\"] = 2\n            assert orjson.loads(orjson.dumps(data)) == data\n\n    def test_dict_dict(self):\n        class C:\n            def __init__(self):\n                self.a = 0\n                self.b = 1\n\n        assert orjson.dumps(C().__dict__) == b'{\"a\":0,\"b\":1}'\n"
  },
  {
    "path": "test/test_enum.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2020-2025)\n\nimport datetime\nimport enum\n\nimport pytest\n\nimport orjson\n\n\nclass StrEnum(str, enum.Enum):\n    AAA = \"aaa\"\n\n\nclass IntEnum(int, enum.Enum):\n    ONE = 1\n\n\nclass IntEnumEnum(enum.IntEnum):\n    ONE = 1\n\n\nclass IntFlagEnum(enum.IntFlag):\n    ONE = 1\n\n\nclass FlagEnum(enum.Flag):\n    ONE = 1\n\n\nclass AutoEnum(enum.auto):\n    A = \"a\"\n\n\nclass FloatEnum(float, enum.Enum):\n    ONE = 1.1\n\n\nclass Custom:\n    def __init__(self, val):\n        self.val = val\n\n\ndef default(obj):\n    if isinstance(obj, Custom):\n        return obj.val\n    raise TypeError\n\n\nclass UnspecifiedEnum(enum.Enum):\n    A = \"a\"\n    B = 1\n    C = FloatEnum.ONE\n    D = {\"d\": IntEnum.ONE}  # noqa: RUF012\n    E = Custom(\"c\")\n    F = datetime.datetime(1970, 1, 1)\n\n\nclass TestEnum:\n    def test_cannot_subclass(self):\n        \"\"\"\n        enum.Enum cannot be subclassed\n\n        obj->ob_type->ob_base will always be enum.EnumMeta\n        \"\"\"\n        with pytest.raises(TypeError):\n\n            class Subclass(StrEnum):  # type: ignore\n                B = \"b\"\n\n    def test_arbitrary_enum(self):\n        assert orjson.dumps(UnspecifiedEnum.A) == b'\"a\"'\n        assert orjson.dumps(UnspecifiedEnum.B) == b\"1\"\n        assert orjson.dumps(UnspecifiedEnum.C) == b\"1.1\"\n        assert orjson.dumps(UnspecifiedEnum.D) == b'{\"d\":1}'\n\n    def test_custom_enum(self):\n        assert orjson.dumps(UnspecifiedEnum.E, default=default) == b'\"c\"'\n\n    def test_enum_options(self):\n        assert (\n            orjson.dumps(UnspecifiedEnum.F, option=orjson.OPT_NAIVE_UTC)\n            == b'\"1970-01-01T00:00:00+00:00\"'\n        )\n\n    def test_int_enum(self):\n        assert orjson.dumps(IntEnum.ONE) == b\"1\"\n\n    def test_intenum_enum(self):\n        assert orjson.dumps(IntEnumEnum.ONE) == b\"1\"\n\n    def test_intflag_enum(self):\n        assert orjson.dumps(IntFlagEnum.ONE) == b\"1\"\n\n    def test_flag_enum(self):\n        assert orjson.dumps(FlagEnum.ONE) == b\"1\"\n\n    def test_auto_enum(self):\n        assert orjson.dumps(AutoEnum.A) == b'\"a\"'\n\n    def test_float_enum(self):\n        assert orjson.dumps(FloatEnum.ONE) == b\"1.1\"\n\n    def test_str_enum(self):\n        assert orjson.dumps(StrEnum.AAA) == b'\"aaa\"'\n\n    def test_bool_enum(self):\n        with pytest.raises(TypeError):\n\n            class BoolEnum(bool, enum.Enum):  # type: ignore\n                TRUE = True\n\n    def test_non_str_keys_enum(self):\n        assert (\n            orjson.dumps({StrEnum.AAA: 1}, option=orjson.OPT_NON_STR_KEYS)\n            == b'{\"aaa\":1}'\n        )\n        assert (\n            orjson.dumps({IntEnum.ONE: 1}, option=orjson.OPT_NON_STR_KEYS) == b'{\"1\":1}'\n        )\n"
  },
  {
    "path": "test/test_error.py",
    "content": "# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2021-2025), Eric Jolibois (2021), o.ermakov (2023)\n\nimport json\n\nimport pytest\n\nimport orjson\n\nfrom .util import needs_data, read_fixture_str\n\nASCII_TEST = b\"\"\"\\\n{\n  \"a\": \"qwe\",\n  \"b\": \"qweqwe\",\n  \"c\": \"qweq\",\n  \"d: \"qwe\"\n}\n\"\"\"\n\nMULTILINE_EMOJI = \"\"\"[\n    \"😊\",\n    \"a\"\n\"\"\"\n\n\nclass TestJsonDecodeError:\n    def _get_error_infos(self, json_decode_error_exc_info):\n        return {\n            k: v\n            for k, v in json_decode_error_exc_info.value.__dict__.items()\n            if k in (\"pos\", \"lineno\", \"colno\")\n        }\n\n    def _test(self, data, expected_err_infos):\n        with pytest.raises(json.decoder.JSONDecodeError) as json_exc_info:\n            json.loads(data)\n\n        with pytest.raises(json.decoder.JSONDecodeError) as orjson_exc_info:\n            orjson.loads(data)\n\n        assert (\n            self._get_error_infos(json_exc_info)\n            == self._get_error_infos(orjson_exc_info)\n            == expected_err_infos\n        )\n\n    def test_empty(self):\n        with pytest.raises(orjson.JSONDecodeError) as json_exc_info:\n            orjson.loads(\"\")\n        assert str(json_exc_info.value).startswith(\n            \"Input is a zero-length, empty document:\",\n        )\n\n    def test_ascii(self):\n        self._test(\n            ASCII_TEST,\n            {\"pos\": 55, \"lineno\": 5, \"colno\": 8},\n        )\n\n    def test_latin1(self):\n        self._test(\n            \"\"\"[\"üýþÿ\", \"a\" \"\"\",\n            {\"pos\": 13, \"lineno\": 1, \"colno\": 14},\n        )\n\n    def test_two_byte_str(self):\n        self._test(\n            \"\"\"[\"東京\", \"a\" \"\"\",\n            {\"pos\": 11, \"lineno\": 1, \"colno\": 12},\n        )\n\n    def test_two_byte_bytes(self):\n        self._test(\n            b'[\"\\xe6\\x9d\\xb1\\xe4\\xba\\xac\", \"a\" ',\n            {\"pos\": 11, \"lineno\": 1, \"colno\": 12},\n        )\n\n    def test_four_byte(self):\n        self._test(\n            MULTILINE_EMOJI,\n            {\"pos\": 19, \"lineno\": 4, \"colno\": 1},\n        )\n\n    @needs_data\n    def test_tab(self):\n        data = read_fixture_str(\"fail26.json\", \"jsonchecker\")\n        with pytest.raises(json.decoder.JSONDecodeError) as json_exc_info:\n            json.loads(data)\n\n        assert self._get_error_infos(json_exc_info) == {\n            \"pos\": 5,\n            \"lineno\": 1,\n            \"colno\": 6,\n        }\n\n        with pytest.raises(json.decoder.JSONDecodeError) as json_exc_info:\n            orjson.loads(data)\n\n        assert self._get_error_infos(json_exc_info) == {\n            \"pos\": 6,\n            \"lineno\": 1,\n            \"colno\": 7,\n        }\n\n\nclass Custom:\n    pass\n\n\nclass CustomException(Exception):\n    pass\n\n\ndef default_typeerror(obj):\n    raise TypeError\n\n\ndef default_notimplementederror(obj):\n    raise NotImplementedError\n\n\ndef default_systemerror(obj):\n    raise SystemError\n\n\ndef default_importerror(obj):\n    import doesnotexist  # noqa: PLC0415\n\n    assert doesnotexist\n\n\nCUSTOM_ERROR_MESSAGE = \"zxc\"\n\n\ndef default_customerror(obj):\n    raise CustomException(CUSTOM_ERROR_MESSAGE)\n\n\nclass TestJsonEncodeError:\n    def test_dumps_arg(self):\n        with pytest.raises(orjson.JSONEncodeError) as exc_info:\n            orjson.dumps()  # type: ignore\n        assert exc_info.type == orjson.JSONEncodeError\n        assert (\n            str(exc_info.value)\n            == \"dumps() missing 1 required positional argument: 'obj'\"\n        )\n        assert exc_info.value.__cause__ is None\n\n    def test_dumps_chain_none(self):\n        with pytest.raises(orjson.JSONEncodeError) as exc_info:\n            orjson.dumps(Custom())\n        assert exc_info.type == orjson.JSONEncodeError\n        assert str(exc_info.value) == \"Type is not JSON serializable: Custom\"\n        assert exc_info.value.__cause__ is None\n\n    def test_dumps_chain_u64(self):\n        with pytest.raises(orjson.JSONEncodeError) as exc_info:\n            orjson.dumps([18446744073709551615, Custom()])\n        assert exc_info.type == orjson.JSONEncodeError\n        assert exc_info.value.__cause__ is None\n\n    def test_dumps_chain_default_typeerror(self):\n        with pytest.raises(orjson.JSONEncodeError) as exc_info:\n            orjson.dumps(Custom(), default=default_typeerror)\n        assert exc_info.type == orjson.JSONEncodeError\n        assert isinstance(exc_info.value.__cause__, TypeError)\n\n    def test_dumps_chain_default_systemerror(self):\n        with pytest.raises(orjson.JSONEncodeError) as exc_info:\n            orjson.dumps(Custom(), default=default_systemerror)\n        assert exc_info.type == orjson.JSONEncodeError\n        assert isinstance(exc_info.value.__cause__, SystemError)\n\n    def test_dumps_chain_default_importerror(self):\n        with pytest.raises(orjson.JSONEncodeError) as exc_info:\n            orjson.dumps(Custom(), default=default_importerror)\n        assert exc_info.type == orjson.JSONEncodeError\n        assert isinstance(exc_info.value.__cause__, ImportError)\n\n    def test_dumps_chain_default_customerror(self):\n        with pytest.raises(orjson.JSONEncodeError) as exc_info:\n            orjson.dumps(Custom(), default=default_customerror)\n        assert exc_info.type == orjson.JSONEncodeError\n        assert isinstance(exc_info.value.__cause__, CustomException)\n        assert str(exc_info.value.__cause__) == CUSTOM_ERROR_MESSAGE\n\n    def test_dumps_normalize_exception(self):\n        with pytest.raises(orjson.JSONEncodeError) as exc_info:\n            orjson.dumps(10**60)\n        assert exc_info.type == orjson.JSONEncodeError\n"
  },
  {
    "path": "test/test_escape.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2025)\n\nimport orjson\n\n\ndef test_issue565():\n    assert (\n        orjson.dumps(\"\\n\\r\\u000b\\f\\u001c\\u001d\\u001e\")\n        == b'\"\\\\n\\\\r\\\\u000b\\\\f\\\\u001c\\\\u001d\\\\u001e\"'\n    )\n\n\ndef test_0x00():\n    assert orjson.dumps(\"\\u0000\") == b'\"\\\\u0000\"'\n\n\ndef test_0x01():\n    assert orjson.dumps(\"\\u0001\") == b'\"\\\\u0001\"'\n\n\ndef test_0x02():\n    assert orjson.dumps(\"\\u0002\") == b'\"\\\\u0002\"'\n\n\ndef test_0x03():\n    assert orjson.dumps(\"\\u0003\") == b'\"\\\\u0003\"'\n\n\ndef test_0x04():\n    assert orjson.dumps(\"\\u0004\") == b'\"\\\\u0004\"'\n\n\ndef test_0x05():\n    assert orjson.dumps(\"\\u0005\") == b'\"\\\\u0005\"'\n\n\ndef test_0x06():\n    assert orjson.dumps(\"\\u0006\") == b'\"\\\\u0006\"'\n\n\ndef test_0x07():\n    assert orjson.dumps(\"\\u0007\") == b'\"\\\\u0007\"'\n\n\ndef test_0x08():\n    assert orjson.dumps(\"\\u0008\") == b'\"\\\\b\"'\n\n\ndef test_0x09():\n    assert orjson.dumps(\"\\u0009\") == b'\"\\\\t\"'\n\n\ndef test_0x0a():\n    assert orjson.dumps(\"\\u000a\") == b'\"\\\\n\"'\n\n\ndef test_0x0b():\n    assert orjson.dumps(\"\\u000b\") == b'\"\\\\u000b\"'\n\n\ndef test_0x0c():\n    assert orjson.dumps(\"\\u000c\") == b'\"\\\\f\"'\n\n\ndef test_0x0d():\n    assert orjson.dumps(\"\\u000d\") == b'\"\\\\r\"'\n\n\ndef test_0x0e():\n    assert orjson.dumps(\"\\u000e\") == b'\"\\\\u000e\"'\n\n\ndef test_0x0f():\n    assert orjson.dumps(\"\\u000f\") == b'\"\\\\u000f\"'\n\n\ndef test_0x10():\n    assert orjson.dumps(\"\\u0010\") == b'\"\\\\u0010\"'\n\n\ndef test_0x11():\n    assert orjson.dumps(\"\\u0011\") == b'\"\\\\u0011\"'\n\n\ndef test_0x12():\n    assert orjson.dumps(\"\\u0012\") == b'\"\\\\u0012\"'\n\n\ndef test_0x13():\n    assert orjson.dumps(\"\\u0013\") == b'\"\\\\u0013\"'\n\n\ndef test_0x14():\n    assert orjson.dumps(\"\\u0014\") == b'\"\\\\u0014\"'\n\n\ndef test_0x15():\n    assert orjson.dumps(\"\\u0015\") == b'\"\\\\u0015\"'\n\n\ndef test_0x16():\n    assert orjson.dumps(\"\\u0016\") == b'\"\\\\u0016\"'\n\n\ndef test_0x17():\n    assert orjson.dumps(\"\\u0017\") == b'\"\\\\u0017\"'\n\n\ndef test_0x18():\n    assert orjson.dumps(\"\\u0018\") == b'\"\\\\u0018\"'\n\n\ndef test_0x19():\n    assert orjson.dumps(\"\\u0019\") == b'\"\\\\u0019\"'\n\n\ndef test_0x1a():\n    assert orjson.dumps(\"\\u001a\") == b'\"\\\\u001a\"'\n\n\ndef test_backslash():\n    assert orjson.dumps(\"\\\\\") == b'\"\\\\\\\\\"'\n\n\ndef test_quote():\n    assert orjson.dumps('\"') == b'\"\\\\\"\"'\n"
  },
  {
    "path": "test/test_fake.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2023-2025)\n\nimport random\n\nimport pytest\n\nimport orjson\n\ntry:\n    from faker import Faker\nexcept ImportError:\n    Faker = None  # type: ignore\n\nNUM_LOOPS = 10\nNUM_SHUFFLES = 10\nNUM_ENTRIES = 250\n\nFAKER_LOCALES = [\n    \"ar_AA\",\n    \"fi_FI\",\n    \"fil_PH\",\n    \"he_IL\",\n    \"ja_JP\",\n    \"th_TH\",\n    \"tr_TR\",\n    \"uk_UA\",\n    \"vi_VN\",\n]\n\n\nclass TestFaker:\n    @pytest.mark.skipif(Faker is None, reason=\"faker not available\")\n    def test_faker(self):\n        fake = Faker(FAKER_LOCALES)\n        profile_keys = list(\n            set(fake.profile().keys()) - {\"birthdate\", \"current_location\"},\n        )\n        for _ in range(NUM_LOOPS):\n            data = [\n                {\n                    \"person\": fake.profile(profile_keys),\n                    \"emoji\": fake.emoji(),\n                    \"text\": fake.paragraphs(),\n                }\n                for _ in range(NUM_ENTRIES)\n            ]\n            for _ in range(NUM_SHUFFLES):\n                random.shuffle(data)\n                output = orjson.dumps(data)\n                assert orjson.loads(output) == data\n"
  },
  {
    "path": "test/test_fixture.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2018-2025)\n\nimport pytest\n\nimport orjson\n\nfrom .util import needs_data, read_fixture_bytes, read_fixture_str\n\n\n@needs_data\nclass TestFixture:\n    def test_twitter(self):\n        \"\"\"\n        loads(),dumps() twitter.json\n        \"\"\"\n        val = read_fixture_str(\"twitter.json.xz\")\n        read = orjson.loads(val)\n        assert orjson.loads(orjson.dumps(read)) == read\n\n    @needs_data\n    def test_canada(self):\n        \"\"\"\n        loads(), dumps() canada.json\n        \"\"\"\n        val = read_fixture_str(\"canada.json.xz\")\n        read = orjson.loads(val)\n        assert orjson.loads(orjson.dumps(read)) == read\n\n    def test_citm_catalog(self):\n        \"\"\"\n        loads(), dumps() citm_catalog.json\n        \"\"\"\n        val = read_fixture_str(\"citm_catalog.json.xz\")\n        read = orjson.loads(val)\n        assert orjson.loads(orjson.dumps(read)) == read\n\n    def test_github(self):\n        \"\"\"\n        loads(), dumps() github.json\n        \"\"\"\n        val = read_fixture_str(\"github.json.xz\")\n        read = orjson.loads(val)\n        assert orjson.loads(orjson.dumps(read)) == read\n\n    def test_blns(self):\n        \"\"\"\n        loads() blns.json JSONDecodeError\n\n        https://github.com/minimaxir/big-list-of-naughty-strings\n        \"\"\"\n        val = read_fixture_bytes(\"blns.txt.xz\")\n        for line in val.split(b\"\\n\"):\n            if line and not line.startswith(b\"#\"):\n                with pytest.raises(orjson.JSONDecodeError):\n                    _ = orjson.loads(b'\"' + val + b'\"')\n"
  },
  {
    "path": "test/test_fragment.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2023-2025)\n\nimport pytest\n\nimport orjson\n\ntry:\n    import pandas as pd\nexcept ImportError:\n    pd = None  # type: ignore\n\nfrom .util import needs_data, read_fixture_bytes\n\n\nclass TestFragment:\n    def test_fragment_fragment_eq(self):\n        assert orjson.Fragment(b\"{}\") != orjson.Fragment(b\"{}\")\n\n    def test_fragment_fragment_not_mut(self):\n        fragment = orjson.Fragment(b\"{}\")\n        with pytest.raises(AttributeError):\n            fragment.contents = b\"[]\"\n        assert orjson.dumps(fragment) == b\"{}\"\n\n    def test_fragment_repr(self):\n        assert repr(orjson.Fragment(b\"{}\")).startswith(\"<orjson.Fragment object at \")\n\n    def test_fragment_fragment_bytes(self):\n        assert orjson.dumps(orjson.Fragment(b\"{}\")) == b\"{}\"\n        assert orjson.dumps(orjson.Fragment(b\"[]\")) == b\"[]\"\n        assert orjson.dumps([orjson.Fragment(b\"{}\")]) == b\"[{}]\"\n        assert orjson.dumps([orjson.Fragment(b'{}\"a\\\\')]) == b'[{}\"a\\\\]'\n\n    def test_fragment_fragment_str(self):\n        assert orjson.dumps(orjson.Fragment(\"{}\")) == b\"{}\"\n        assert orjson.dumps(orjson.Fragment(\"[]\")) == b\"[]\"\n        assert orjson.dumps([orjson.Fragment(\"{}\")]) == b\"[{}]\"\n        assert orjson.dumps([orjson.Fragment('{}\"a\\\\')]) == b'[{}\"a\\\\]'\n\n    def test_fragment_fragment_str_empty(self):\n        assert orjson.dumps(orjson.Fragment(\"\")) == b\"\"\n\n    def test_fragment_fragment_str_str(self):\n        assert orjson.dumps(orjson.Fragment('\"str\"')) == b'\"str\"'\n\n    def test_fragment_fragment_str_emoji(self):\n        assert orjson.dumps(orjson.Fragment('\"🐈\"')) == b'\"\\xf0\\x9f\\x90\\x88\"'\n\n    def test_fragment_fragment_str_array(self):\n        n = 8096\n        obj = [orjson.Fragment('\"🐈\"')] * n\n        ref = b\"[\" + b\",\".join(b'\"\\xf0\\x9f\\x90\\x88\"' for _ in range(n)) + b\"]\"\n        assert orjson.dumps(obj) == ref\n\n    def test_fragment_fragment_str_invalid(self):\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(orjson.Fragment(\"\\ud800\"))  # type: ignore\n\n    def test_fragment_fragment_bytes_invalid(self):\n        assert orjson.dumps(orjson.Fragment(b\"\\\\ud800\")) == b\"\\\\ud800\"\n\n    def test_fragment_fragment_none(self):\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps([orjson.Fragment(None)])  # type: ignore\n\n    def test_fragment_fragment_args_zero(self):\n        with pytest.raises(TypeError):\n            orjson.dumps(orjson.Fragment())\n\n    def test_fragment_fragment_args_two(self):\n        with pytest.raises(TypeError):\n            orjson.dumps(orjson.Fragment(b\"{}\", None))  # type: ignore\n\n    def test_fragment_fragment_keywords(self):\n        with pytest.raises(TypeError):\n            orjson.dumps(orjson.Fragment(contents=b\"{}\"))  # type: ignore\n\n    def test_fragment_fragment_arg_and_keywords(self):\n        with pytest.raises(TypeError):\n            orjson.dumps(orjson.Fragment(b\"{}\", contents=b\"{}\"))  # type: ignore\n\n\n@pytest.mark.skipif(pd is None, reason=\"pandas is not installed\")\nclass TestFragmentPandas:\n    def test_fragment_pandas(self):\n        \"\"\"\n        Fragment pandas.DataFrame.to_json()\n        \"\"\"\n\n        def default(value):\n            if isinstance(value, pd.DataFrame):\n                return orjson.Fragment(value.to_json(orient=\"records\"))\n            raise TypeError\n\n        val = pd.DataFrame({\"foo\": [1, 2, 3], \"bar\": [4, 5, 6]})\n        assert (\n            orjson.dumps({\"data\": val}, default=default)\n            == b'{\"data\":[{\"foo\":1,\"bar\":4},{\"foo\":2,\"bar\":5},{\"foo\":3,\"bar\":6}]}'\n        )\n\n\n@needs_data\nclass TestFragmentParsing:\n    def _run_test(self, filename: str):\n        data = read_fixture_bytes(filename, \"parsing\")\n        orjson.dumps(orjson.Fragment(data))\n\n    def test_fragment_y_array_arraysWithSpace(self):\n        self._run_test(\"y_array_arraysWithSpaces.json\")\n\n    def test_fragment_y_array_empty_string(self):\n        self._run_test(\"y_array_empty-string.json\")\n\n    def test_fragment_y_array_empty(self):\n        self._run_test(\"y_array_empty.json\")\n\n    def test_fragment_y_array_ending_with_newline(self):\n        self._run_test(\"y_array_ending_with_newline.json\")\n\n    def test_fragment_y_array_false(self):\n        self._run_test(\"y_array_false.json\")\n\n    def test_fragment_y_array_heterogeneou(self):\n        self._run_test(\"y_array_heterogeneous.json\")\n\n    def test_fragment_y_array_null(self):\n        self._run_test(\"y_array_null.json\")\n\n    def test_fragment_y_array_with_1_and_newline(self):\n        self._run_test(\"y_array_with_1_and_newline.json\")\n\n    def test_fragment_y_array_with_leading_space(self):\n        self._run_test(\"y_array_with_leading_space.json\")\n\n    def test_fragment_y_array_with_several_null(self):\n        self._run_test(\"y_array_with_several_null.json\")\n\n    def test_fragment_y_array_with_trailing_space(self):\n        self._run_test(\"y_array_with_trailing_space.json\")\n\n    def test_fragment_y_number(self):\n        self._run_test(\"y_number.json\")\n\n    def test_fragment_y_number_0e_1(self):\n        self._run_test(\"y_number_0e+1.json\")\n\n    def test_fragment_y_number_0e1(self):\n        self._run_test(\"y_number_0e1.json\")\n\n    def test_fragment_y_number_after_space(self):\n        self._run_test(\"y_number_after_space.json\")\n\n    def test_fragment_y_number_double_close_to_zer(self):\n        self._run_test(\"y_number_double_close_to_zero.json\")\n\n    def test_fragment_y_number_int_with_exp(self):\n        self._run_test(\"y_number_int_with_exp.json\")\n\n    def test_fragment_y_number_minus_zer(self):\n        self._run_test(\"y_number_minus_zero.json\")\n\n    def test_fragment_y_number_negative_int(self):\n        self._run_test(\"y_number_negative_int.json\")\n\n    def test_fragment_y_number_negative_one(self):\n        self._run_test(\"y_number_negative_one.json\")\n\n    def test_fragment_y_number_negative_zer(self):\n        self._run_test(\"y_number_negative_zero.json\")\n\n    def test_fragment_y_number_real_capital_e(self):\n        self._run_test(\"y_number_real_capital_e.json\")\n\n    def test_fragment_y_number_real_capital_e_neg_exp(self):\n        self._run_test(\"y_number_real_capital_e_neg_exp.json\")\n\n    def test_fragment_y_number_real_capital_e_pos_exp(self):\n        self._run_test(\"y_number_real_capital_e_pos_exp.json\")\n\n    def test_fragment_y_number_real_exponent(self):\n        self._run_test(\"y_number_real_exponent.json\")\n\n    def test_fragment_y_number_real_fraction_exponent(self):\n        self._run_test(\"y_number_real_fraction_exponent.json\")\n\n    def test_fragment_y_number_real_neg_exp(self):\n        self._run_test(\"y_number_real_neg_exp.json\")\n\n    def test_fragment_y_number_real_pos_exponent(self):\n        self._run_test(\"y_number_real_pos_exponent.json\")\n\n    def test_fragment_y_number_simple_int(self):\n        self._run_test(\"y_number_simple_int.json\")\n\n    def test_fragment_y_number_simple_real(self):\n        self._run_test(\"y_number_simple_real.json\")\n\n    def test_fragment_y_object(self):\n        self._run_test(\"y_object.json\")\n\n    def test_fragment_y_object_basic(self):\n        self._run_test(\"y_object_basic.json\")\n\n    def test_fragment_y_object_duplicated_key(self):\n        self._run_test(\"y_object_duplicated_key.json\")\n\n    def test_fragment_y_object_duplicated_key_and_value(self):\n        self._run_test(\"y_object_duplicated_key_and_value.json\")\n\n    def test_fragment_y_object_empty(self):\n        self._run_test(\"y_object_empty.json\")\n\n    def test_fragment_y_object_empty_key(self):\n        self._run_test(\"y_object_empty_key.json\")\n\n    def test_fragment_y_object_escaped_null_in_key(self):\n        self._run_test(\"y_object_escaped_null_in_key.json\")\n\n    def test_fragment_y_object_extreme_number(self):\n        self._run_test(\"y_object_extreme_numbers.json\")\n\n    def test_fragment_y_object_long_string(self):\n        self._run_test(\"y_object_long_strings.json\")\n\n    def test_fragment_y_object_simple(self):\n        self._run_test(\"y_object_simple.json\")\n\n    def test_fragment_y_object_string_unicode(self):\n        self._run_test(\"y_object_string_unicode.json\")\n\n    def test_fragment_y_object_with_newline(self):\n        self._run_test(\"y_object_with_newlines.json\")\n\n    def test_fragment_y_string_1_2_3_bytes_UTF_8_sequence(self):\n        self._run_test(\"y_string_1_2_3_bytes_UTF-8_sequences.json\")\n\n    def test_fragment_y_string_accepted_surrogate_pair(self):\n        self._run_test(\"y_string_accepted_surrogate_pair.json\")\n\n    def test_fragment_y_string_accepted_surrogate_pairs(self):\n        self._run_test(\"y_string_accepted_surrogate_pairs.json\")\n\n    def test_fragment_y_string_allowed_escape(self):\n        self._run_test(\"y_string_allowed_escapes.json\")\n\n    def test_fragment_y_string_backslash_and_u_escaped_zer(self):\n        self._run_test(\"y_string_backslash_and_u_escaped_zero.json\")\n\n    def test_fragment_y_string_backslash_doublequote(self):\n        self._run_test(\"y_string_backslash_doublequotes.json\")\n\n    def test_fragment_y_string_comment(self):\n        self._run_test(\"y_string_comments.json\")\n\n    def test_fragment_y_string_double_escape_a(self):\n        self._run_test(\"y_string_double_escape_a.json\")\n\n    def test_fragment_y_string_double_escape_(self):\n        self._run_test(\"y_string_double_escape_n.json\")\n\n    def test_fragment_y_string_escaped_control_character(self):\n        self._run_test(\"y_string_escaped_control_character.json\")\n\n    def test_fragment_y_string_escaped_noncharacter(self):\n        self._run_test(\"y_string_escaped_noncharacter.json\")\n\n    def test_fragment_y_string_in_array(self):\n        self._run_test(\"y_string_in_array.json\")\n\n    def test_fragment_y_string_in_array_with_leading_space(self):\n        self._run_test(\"y_string_in_array_with_leading_space.json\")\n\n    def test_fragment_y_string_last_surrogates_1_and_2(self):\n        self._run_test(\"y_string_last_surrogates_1_and_2.json\")\n\n    def test_fragment_y_string_nbsp_uescaped(self):\n        self._run_test(\"y_string_nbsp_uescaped.json\")\n\n    def test_fragment_y_string_nonCharacterInUTF_8_U_10FFFF(self):\n        self._run_test(\"y_string_nonCharacterInUTF-8_U+10FFFF.json\")\n\n    def test_fragment_y_string_nonCharacterInUTF_8_U_FFFF(self):\n        self._run_test(\"y_string_nonCharacterInUTF-8_U+FFFF.json\")\n\n    def test_fragment_y_string_null_escape(self):\n        self._run_test(\"y_string_null_escape.json\")\n\n    def test_fragment_y_string_one_byte_utf_8(self):\n        self._run_test(\"y_string_one-byte-utf-8.json\")\n\n    def test_fragment_y_string_pi(self):\n        self._run_test(\"y_string_pi.json\")\n\n    def test_fragment_y_string_reservedCharacterInUTF_8_U_1BFFF(self):\n        self._run_test(\"y_string_reservedCharacterInUTF-8_U+1BFFF.json\")\n\n    def test_fragment_y_string_simple_ascii(self):\n        self._run_test(\"y_string_simple_ascii.json\")\n\n    def test_fragment_y_string_space(self):\n        self._run_test(\"y_string_space.json\")\n\n    def test_fragment_y_string_surrogates_U_1D11E_MUSICAL_SYMBOL_G_CLEF(self):\n        self._run_test(\"y_string_surrogates_U+1D11E_MUSICAL_SYMBOL_G_CLEF.json\")\n\n    def test_fragment_y_string_three_byte_utf_8(self):\n        self._run_test(\"y_string_three-byte-utf-8.json\")\n\n    def test_fragment_y_string_two_byte_utf_8(self):\n        self._run_test(\"y_string_two-byte-utf-8.json\")\n\n    def test_fragment_y_string_u_2028_line_sep(self):\n        self._run_test(\"y_string_u+2028_line_sep.json\")\n\n    def test_fragment_y_string_u_2029_par_sep(self):\n        self._run_test(\"y_string_u+2029_par_sep.json\")\n\n    def test_fragment_y_string_uEscape(self):\n        self._run_test(\"y_string_uEscape.json\")\n\n    def test_fragment_y_string_uescaped_newline(self):\n        self._run_test(\"y_string_uescaped_newline.json\")\n\n    def test_fragment_y_string_unescaped_char_delete(self):\n        self._run_test(\"y_string_unescaped_char_delete.json\")\n\n    def test_fragment_y_string_unicode(self):\n        self._run_test(\"y_string_unicode.json\")\n\n    def test_fragment_y_string_unicodeEscapedBackslash(self):\n        self._run_test(\"y_string_unicodeEscapedBackslash.json\")\n\n    def test_fragment_y_string_unicode_2(self):\n        self._run_test(\"y_string_unicode_2.json\")\n\n    def test_fragment_y_string_unicode_U_10FFFE_nonchar(self):\n        self._run_test(\"y_string_unicode_U+10FFFE_nonchar.json\")\n\n    def test_fragment_y_string_unicode_U_1FFFE_nonchar(self):\n        self._run_test(\"y_string_unicode_U+1FFFE_nonchar.json\")\n\n    def test_fragment_y_string_unicode_U_200B_ZERO_WIDTH_SPACE(self):\n        self._run_test(\"y_string_unicode_U+200B_ZERO_WIDTH_SPACE.json\")\n\n    def test_fragment_y_string_unicode_U_2064_invisible_plu(self):\n        self._run_test(\"y_string_unicode_U+2064_invisible_plus.json\")\n\n    def test_fragment_y_string_unicode_U_FDD0_nonchar(self):\n        self._run_test(\"y_string_unicode_U+FDD0_nonchar.json\")\n\n    def test_fragment_y_string_unicode_U_FFFE_nonchar(self):\n        self._run_test(\"y_string_unicode_U+FFFE_nonchar.json\")\n\n    def test_fragment_y_string_unicode_escaped_double_quote(self):\n        self._run_test(\"y_string_unicode_escaped_double_quote.json\")\n\n    def test_fragment_y_string_utf8(self):\n        self._run_test(\"y_string_utf8.json\")\n\n    def test_fragment_y_string_with_del_character(self):\n        self._run_test(\"y_string_with_del_character.json\")\n\n    def test_fragment_y_structure_lonely_false(self):\n        self._run_test(\"y_structure_lonely_false.json\")\n\n    def test_fragment_y_structure_lonely_int(self):\n        self._run_test(\"y_structure_lonely_int.json\")\n\n    def test_fragment_y_structure_lonely_negative_real(self):\n        self._run_test(\"y_structure_lonely_negative_real.json\")\n\n    def test_fragment_y_structure_lonely_null(self):\n        self._run_test(\"y_structure_lonely_null.json\")\n\n    def test_fragment_y_structure_lonely_string(self):\n        self._run_test(\"y_structure_lonely_string.json\")\n\n    def test_fragment_y_structure_lonely_true(self):\n        self._run_test(\"y_structure_lonely_true.json\")\n\n    def test_fragment_y_structure_string_empty(self):\n        self._run_test(\"y_structure_string_empty.json\")\n\n    def test_fragment_y_structure_trailing_newline(self):\n        self._run_test(\"y_structure_trailing_newline.json\")\n\n    def test_fragment_y_structure_true_in_array(self):\n        self._run_test(\"y_structure_true_in_array.json\")\n\n    def test_fragment_y_structure_whitespace_array(self):\n        self._run_test(\"y_structure_whitespace_array.json\")\n\n    def test_fragment_n_array_1_true_without_comma(self):\n        self._run_test(\"n_array_1_true_without_comma.json\")\n\n    def test_fragment_n_array_a_invalid_utf8(self):\n        self._run_test(\"n_array_a_invalid_utf8.json\")\n\n    def test_fragment_n_array_colon_instead_of_comma(self):\n        self._run_test(\"n_array_colon_instead_of_comma.json\")\n\n    def test_fragment_n_array_comma_after_close(self):\n        self._run_test(\"n_array_comma_after_close.json\")\n\n    def test_fragment_n_array_comma_and_number(self):\n        self._run_test(\"n_array_comma_and_number.json\")\n\n    def test_fragment_n_array_double_comma(self):\n        self._run_test(\"n_array_double_comma.json\")\n\n    def test_fragment_n_array_double_extra_comma(self):\n        self._run_test(\"n_array_double_extra_comma.json\")\n\n    def test_fragment_n_array_extra_close(self):\n        self._run_test(\"n_array_extra_close.json\")\n\n    def test_fragment_n_array_extra_comma(self):\n        self._run_test(\"n_array_extra_comma.json\")\n\n    def test_fragment_n_array_incomplete(self):\n        self._run_test(\"n_array_incomplete.json\")\n\n    def test_fragment_n_array_incomplete_invalid_value(self):\n        self._run_test(\"n_array_incomplete_invalid_value.json\")\n\n    def test_fragment_n_array_inner_array_no_comma(self):\n        self._run_test(\"n_array_inner_array_no_comma.json\")\n\n    def test_fragment_n_array_invalid_utf8(self):\n        self._run_test(\"n_array_invalid_utf8.json\")\n\n    def test_fragment_n_array_items_separated_by_semicol(self):\n        self._run_test(\"n_array_items_separated_by_semicolon.json\")\n\n    def test_fragment_n_array_just_comma(self):\n        self._run_test(\"n_array_just_comma.json\")\n\n    def test_fragment_n_array_just_minu(self):\n        self._run_test(\"n_array_just_minus.json\")\n\n    def test_fragment_n_array_missing_value(self):\n        self._run_test(\"n_array_missing_value.json\")\n\n    def test_fragment_n_array_newlines_unclosed(self):\n        self._run_test(\"n_array_newlines_unclosed.json\")\n\n    def test_fragment_n_array_number_and_comma(self):\n        self._run_test(\"n_array_number_and_comma.json\")\n\n    def test_fragment_n_array_number_and_several_comma(self):\n        self._run_test(\"n_array_number_and_several_commas.json\")\n\n    def test_fragment_n_array_spaces_vertical_tab_formfeed(self):\n        self._run_test(\"n_array_spaces_vertical_tab_formfeed.json\")\n\n    def test_fragment_n_array_star_inside(self):\n        self._run_test(\"n_array_star_inside.json\")\n\n    def test_fragment_n_array_unclosed(self):\n        self._run_test(\"n_array_unclosed.json\")\n\n    def test_fragment_n_array_unclosed_trailing_comma(self):\n        self._run_test(\"n_array_unclosed_trailing_comma.json\")\n\n    def test_fragment_n_array_unclosed_with_new_line(self):\n        self._run_test(\"n_array_unclosed_with_new_lines.json\")\n\n    def test_fragment_n_array_unclosed_with_object_inside(self):\n        self._run_test(\"n_array_unclosed_with_object_inside.json\")\n\n    def test_fragment_n_incomplete_false(self):\n        self._run_test(\"n_incomplete_false.json\")\n\n    def test_fragment_n_incomplete_null(self):\n        self._run_test(\"n_incomplete_null.json\")\n\n    def test_fragment_n_incomplete_true(self):\n        self._run_test(\"n_incomplete_true.json\")\n\n    def test_fragment_n_multidigit_number_then_00(self):\n        self._run_test(\"n_multidigit_number_then_00.json\")\n\n    def test_fragment_n_number__(self):\n        self._run_test(\"n_number_++.json\")\n\n    def test_fragment_n_number_1(self):\n        self._run_test(\"n_number_+1.json\")\n\n    def test_fragment_n_number_Inf(self):\n        self._run_test(\"n_number_+Inf.json\")\n\n    def test_fragment_n_number_01(self):\n        self._run_test(\"n_number_-01.json\")\n\n    def test_fragment_n_number_1_0(self):\n        self._run_test(\"n_number_-1.0..json\")\n\n    def test_fragment_n_number_2(self):\n        self._run_test(\"n_number_-2..json\")\n\n    def test_fragment_n_number_negative_NaN(self):\n        self._run_test(\"n_number_-NaN.json\")\n\n    def test_fragment_n_number_negative_1(self):\n        self._run_test(\"n_number_.-1.json\")\n\n    def test_fragment_n_number_2e_3(self):\n        self._run_test(\"n_number_.2e-3.json\")\n\n    def test_fragment_n_number_0_1_2(self):\n        self._run_test(\"n_number_0.1.2.json\")\n\n    def test_fragment_n_number_0_3e_(self):\n        self._run_test(\"n_number_0.3e+.json\")\n\n    def test_fragment_n_number_0_3e(self):\n        self._run_test(\"n_number_0.3e.json\")\n\n    def test_fragment_n_number_0_e1(self):\n        self._run_test(\"n_number_0.e1.json\")\n\n    def test_fragment_n_number_0_capital_E_(self):\n        self._run_test(\"n_number_0_capital_E+.json\")\n\n    def test_fragment_n_number_0_capital_E(self):\n        self._run_test(\"n_number_0_capital_E.json\")\n\n    def test_fragment_n_number_0e_(self):\n        self._run_test(\"n_number_0e+.json\")\n\n    def test_fragment_n_number_0e(self):\n        self._run_test(\"n_number_0e.json\")\n\n    def test_fragment_n_number_1_0e_(self):\n        self._run_test(\"n_number_1.0e+.json\")\n\n    def test_fragment_n_number_1_0e_2(self):\n        self._run_test(\"n_number_1.0e-.json\")\n\n    def test_fragment_n_number_1_0e(self):\n        self._run_test(\"n_number_1.0e.json\")\n\n    def test_fragment_n_number_1_000(self):\n        self._run_test(\"n_number_1_000.json\")\n\n    def test_fragment_n_number_1eE2(self):\n        self._run_test(\"n_number_1eE2.json\")\n\n    def test_fragment_n_number_2_e_3(self):\n        self._run_test(\"n_number_2.e+3.json\")\n\n    def test_fragment_n_number_2_e_3_2(self):\n        self._run_test(\"n_number_2.e-3.json\")\n\n    def test_fragment_n_number_2_e3_3(self):\n        self._run_test(\"n_number_2.e3.json\")\n\n    def test_fragment_n_number_9_e_(self):\n        self._run_test(\"n_number_9.e+.json\")\n\n    def test_fragment_n_number_negative_Inf(self):\n        self._run_test(\"n_number_Inf.json\")\n\n    def test_fragment_n_number_NaN(self):\n        self._run_test(\"n_number_NaN.json\")\n\n    def test_fragment_n_number_U_FF11_fullwidth_digit_one(self):\n        self._run_test(\"n_number_U+FF11_fullwidth_digit_one.json\")\n\n    def test_fragment_n_number_expressi(self):\n        self._run_test(\"n_number_expression.json\")\n\n    def test_fragment_n_number_hex_1_digit(self):\n        self._run_test(\"n_number_hex_1_digit.json\")\n\n    def test_fragment_n_number_hex_2_digit(self):\n        self._run_test(\"n_number_hex_2_digits.json\")\n\n    def test_fragment_n_number_infinity(self):\n        self._run_test(\"n_number_infinity.json\")\n\n    def test_fragment_n_number_invalid_(self):\n        self._run_test(\"n_number_invalid+-.json\")\n\n    def test_fragment_n_number_invalid_negative_real(self):\n        self._run_test(\"n_number_invalid-negative-real.json\")\n\n    def test_fragment_n_number_invalid_utf_8_in_bigger_int(self):\n        self._run_test(\"n_number_invalid-utf-8-in-bigger-int.json\")\n\n    def test_fragment_n_number_invalid_utf_8_in_exponent(self):\n        self._run_test(\"n_number_invalid-utf-8-in-exponent.json\")\n\n    def test_fragment_n_number_invalid_utf_8_in_int(self):\n        self._run_test(\"n_number_invalid-utf-8-in-int.json\")\n\n    def test_fragment_n_number_minus_infinity(self):\n        self._run_test(\"n_number_minus_infinity.json\")\n\n    def test_fragment_n_number_minus_sign_with_trailing_garbage(self):\n        self._run_test(\"n_number_minus_sign_with_trailing_garbage.json\")\n\n    def test_fragment_n_number_minus_space_1(self):\n        self._run_test(\"n_number_minus_space_1.json\")\n\n    def test_fragment_n_number_neg_int_starting_with_zer(self):\n        self._run_test(\"n_number_neg_int_starting_with_zero.json\")\n\n    def test_fragment_n_number_neg_real_without_int_part(self):\n        self._run_test(\"n_number_neg_real_without_int_part.json\")\n\n    def test_fragment_n_number_neg_with_garbage_at_end(self):\n        self._run_test(\"n_number_neg_with_garbage_at_end.json\")\n\n    def test_fragment_n_number_real_garbage_after_e(self):\n        self._run_test(\"n_number_real_garbage_after_e.json\")\n\n    def test_fragment_n_number_real_with_invalid_utf8_after_e(self):\n        self._run_test(\"n_number_real_with_invalid_utf8_after_e.json\")\n\n    def test_fragment_n_number_real_without_fractional_part(self):\n        self._run_test(\"n_number_real_without_fractional_part.json\")\n\n    def test_fragment_n_number_starting_with_dot(self):\n        self._run_test(\"n_number_starting_with_dot.json\")\n\n    def test_fragment_n_number_with_alpha(self):\n        self._run_test(\"n_number_with_alpha.json\")\n\n    def test_fragment_n_number_with_alpha_char(self):\n        self._run_test(\"n_number_with_alpha_char.json\")\n\n    def test_fragment_n_number_with_leading_zer(self):\n        self._run_test(\"n_number_with_leading_zero.json\")\n\n    def test_fragment_n_object_bad_value(self):\n        self._run_test(\"n_object_bad_value.json\")\n\n    def test_fragment_n_object_bracket_key(self):\n        self._run_test(\"n_object_bracket_key.json\")\n\n    def test_fragment_n_object_comma_instead_of_col(self):\n        self._run_test(\"n_object_comma_instead_of_colon.json\")\n\n    def test_fragment_n_object_double_col(self):\n        self._run_test(\"n_object_double_colon.json\")\n\n    def test_fragment_n_object_emoji(self):\n        self._run_test(\"n_object_emoji.json\")\n\n    def test_fragment_n_object_garbage_at_end(self):\n        self._run_test(\"n_object_garbage_at_end.json\")\n\n    def test_fragment_n_object_key_with_single_quote(self):\n        self._run_test(\"n_object_key_with_single_quotes.json\")\n\n    def test_fragment_n_object_lone_continuation_byte_in_key_and_trailing_comma(self):\n        self._run_test(\"n_object_lone_continuation_byte_in_key_and_trailing_comma.json\")\n\n    def test_fragment_n_object_missing_col(self):\n        self._run_test(\"n_object_missing_colon.json\")\n\n    def test_fragment_n_object_missing_key(self):\n        self._run_test(\"n_object_missing_key.json\")\n\n    def test_fragment_n_object_missing_semicol(self):\n        self._run_test(\"n_object_missing_semicolon.json\")\n\n    def test_fragment_n_object_missing_value(self):\n        self._run_test(\"n_object_missing_value.json\")\n\n    def test_fragment_n_object_no_col(self):\n        self._run_test(\"n_object_no-colon.json\")\n\n    def test_fragment_n_object_non_string_key(self):\n        self._run_test(\"n_object_non_string_key.json\")\n\n    def test_fragment_n_object_non_string_key_but_huge_number_instead(self):\n        self._run_test(\"n_object_non_string_key_but_huge_number_instead.json\")\n\n    def test_fragment_n_object_repeated_null_null(self):\n        self._run_test(\"n_object_repeated_null_null.json\")\n\n    def test_fragment_n_object_several_trailing_comma(self):\n        self._run_test(\"n_object_several_trailing_commas.json\")\n\n    def test_fragment_n_object_single_quote(self):\n        self._run_test(\"n_object_single_quote.json\")\n\n    def test_fragment_n_object_trailing_comma(self):\n        self._run_test(\"n_object_trailing_comma.json\")\n\n    def test_fragment_n_object_trailing_comment(self):\n        self._run_test(\"n_object_trailing_comment.json\")\n\n    def test_fragment_n_object_trailing_comment_ope(self):\n        self._run_test(\"n_object_trailing_comment_open.json\")\n\n    def test_fragment_n_object_trailing_comment_slash_ope(self):\n        self._run_test(\"n_object_trailing_comment_slash_open.json\")\n\n    def test_fragment_n_object_trailing_comment_slash_open_incomplete(self):\n        self._run_test(\"n_object_trailing_comment_slash_open_incomplete.json\")\n\n    def test_fragment_n_object_two_commas_in_a_row(self):\n        self._run_test(\"n_object_two_commas_in_a_row.json\")\n\n    def test_fragment_n_object_unquoted_key(self):\n        self._run_test(\"n_object_unquoted_key.json\")\n\n    def test_fragment_n_object_unterminated_value(self):\n        self._run_test(\"n_object_unterminated-value.json\")\n\n    def test_fragment_n_object_with_single_string(self):\n        self._run_test(\"n_object_with_single_string.json\")\n\n    def test_fragment_n_object_with_trailing_garbage(self):\n        self._run_test(\"n_object_with_trailing_garbage.json\")\n\n    def test_fragment_n_single_space(self):\n        self._run_test(\"n_single_space.json\")\n\n    def test_fragment_n_string_1_surrogate_then_escape(self):\n        self._run_test(\"n_string_1_surrogate_then_escape.json\")\n\n    def test_fragment_n_string_1_surrogate_then_escape_u(self):\n        self._run_test(\"n_string_1_surrogate_then_escape_u.json\")\n\n    def test_fragment_n_string_1_surrogate_then_escape_u1(self):\n        self._run_test(\"n_string_1_surrogate_then_escape_u1.json\")\n\n    def test_fragment_n_string_1_surrogate_then_escape_u1x(self):\n        self._run_test(\"n_string_1_surrogate_then_escape_u1x.json\")\n\n    def test_fragment_n_string_accentuated_char_no_quote(self):\n        self._run_test(\"n_string_accentuated_char_no_quotes.json\")\n\n    def test_fragment_n_string_backslash_00(self):\n        self._run_test(\"n_string_backslash_00.json\")\n\n    def test_fragment_n_string_escape_x(self):\n        self._run_test(\"n_string_escape_x.json\")\n\n    def test_fragment_n_string_escaped_backslash_bad(self):\n        self._run_test(\"n_string_escaped_backslash_bad.json\")\n\n    def test_fragment_n_string_escaped_ctrl_char_tab(self):\n        self._run_test(\"n_string_escaped_ctrl_char_tab.json\")\n\n    def test_fragment_n_string_escaped_emoji(self):\n        self._run_test(\"n_string_escaped_emoji.json\")\n\n    def test_fragment_n_string_incomplete_escape(self):\n        self._run_test(\"n_string_incomplete_escape.json\")\n\n    def test_fragment_n_string_incomplete_escaped_character(self):\n        self._run_test(\"n_string_incomplete_escaped_character.json\")\n\n    def test_fragment_n_string_incomplete_surrogate(self):\n        self._run_test(\"n_string_incomplete_surrogate.json\")\n\n    def test_fragment_n_string_incomplete_surrogate_escape_invalid(self):\n        self._run_test(\"n_string_incomplete_surrogate_escape_invalid.json\")\n\n    def test_fragment_n_string_invalid_utf_8_in_escape(self):\n        self._run_test(\"n_string_invalid-utf-8-in-escape.json\")\n\n    def test_fragment_n_string_invalid_backslash_esc(self):\n        self._run_test(\"n_string_invalid_backslash_esc.json\")\n\n    def test_fragment_n_string_invalid_unicode_escape(self):\n        self._run_test(\"n_string_invalid_unicode_escape.json\")\n\n    def test_fragment_n_string_invalid_utf8_after_escape(self):\n        self._run_test(\"n_string_invalid_utf8_after_escape.json\")\n\n    def test_fragment_n_string_leading_uescaped_thinspace(self):\n        self._run_test(\"n_string_leading_uescaped_thinspace.json\")\n\n    def test_fragment_n_string_no_quotes_with_bad_escape(self):\n        self._run_test(\"n_string_no_quotes_with_bad_escape.json\")\n\n    def test_fragment_n_string_single_doublequote(self):\n        self._run_test(\"n_string_single_doublequote.json\")\n\n    def test_fragment_n_string_single_quote(self):\n        self._run_test(\"n_string_single_quote.json\")\n\n    def test_fragment_n_string_single_string_no_double_quote(self):\n        self._run_test(\"n_string_single_string_no_double_quotes.json\")\n\n    def test_fragment_n_string_start_escape_unclosed(self):\n        self._run_test(\"n_string_start_escape_unclosed.json\")\n\n    def test_fragment_n_string_unescaped_crtl_char(self):\n        self._run_test(\"n_string_unescaped_crtl_char.json\")\n\n    def test_fragment_n_string_unescaped_newline(self):\n        self._run_test(\"n_string_unescaped_newline.json\")\n\n    def test_fragment_n_string_unescaped_tab(self):\n        self._run_test(\"n_string_unescaped_tab.json\")\n\n    def test_fragment_n_string_unicode_CapitalU(self):\n        self._run_test(\"n_string_unicode_CapitalU.json\")\n\n    def test_fragment_n_string_with_trailing_garbage(self):\n        self._run_test(\"n_string_with_trailing_garbage.json\")\n\n    def test_fragment_n_structure_100000_opening_array(self):\n        self._run_test(\"n_structure_100000_opening_arrays.json.xz\")\n\n    def test_fragment_n_structure_U_2060_word_joined(self):\n        self._run_test(\"n_structure_U+2060_word_joined.json\")\n\n    def test_fragment_n_structure_UTF8_BOM_no_data(self):\n        self._run_test(\"n_structure_UTF8_BOM_no_data.json\")\n\n    def test_fragment_n_structure_angle_bracket_(self):\n        self._run_test(\"n_structure_angle_bracket_..json\")\n\n    def test_fragment_n_structure_angle_bracket_null(self):\n        self._run_test(\"n_structure_angle_bracket_null.json\")\n\n    def test_fragment_n_structure_array_trailing_garbage(self):\n        self._run_test(\"n_structure_array_trailing_garbage.json\")\n\n    def test_fragment_n_structure_array_with_extra_array_close(self):\n        self._run_test(\"n_structure_array_with_extra_array_close.json\")\n\n    def test_fragment_n_structure_array_with_unclosed_string(self):\n        self._run_test(\"n_structure_array_with_unclosed_string.json\")\n\n    def test_fragment_n_structure_ascii_unicode_identifier(self):\n        self._run_test(\"n_structure_ascii-unicode-identifier.json\")\n\n    def test_fragment_n_structure_capitalized_True(self):\n        self._run_test(\"n_structure_capitalized_True.json\")\n\n    def test_fragment_n_structure_close_unopened_array(self):\n        self._run_test(\"n_structure_close_unopened_array.json\")\n\n    def test_fragment_n_structure_comma_instead_of_closing_brace(self):\n        self._run_test(\"n_structure_comma_instead_of_closing_brace.json\")\n\n    def test_fragment_n_structure_double_array(self):\n        self._run_test(\"n_structure_double_array.json\")\n\n    def test_fragment_n_structure_end_array(self):\n        self._run_test(\"n_structure_end_array.json\")\n\n    def test_fragment_n_structure_incomplete_UTF8_BOM(self):\n        self._run_test(\"n_structure_incomplete_UTF8_BOM.json\")\n\n    def test_fragment_n_structure_lone_invalid_utf_8(self):\n        self._run_test(\"n_structure_lone-invalid-utf-8.json\")\n\n    def test_fragment_n_structure_lone_open_bracket(self):\n        self._run_test(\"n_structure_lone-open-bracket.json\")\n\n    def test_fragment_n_structure_no_data(self):\n        self._run_test(\"n_structure_no_data.json\")\n\n    def test_fragment_n_structure_null_byte_outside_string(self):\n        self._run_test(\"n_structure_null-byte-outside-string.json\")\n\n    def test_fragment_n_structure_number_with_trailing_garbage(self):\n        self._run_test(\"n_structure_number_with_trailing_garbage.json\")\n\n    def test_fragment_n_structure_object_followed_by_closing_object(self):\n        self._run_test(\"n_structure_object_followed_by_closing_object.json\")\n\n    def test_fragment_n_structure_object_unclosed_no_value(self):\n        self._run_test(\"n_structure_object_unclosed_no_value.json\")\n\n    def test_fragment_n_structure_object_with_comment(self):\n        self._run_test(\"n_structure_object_with_comment.json\")\n\n    def test_fragment_n_structure_object_with_trailing_garbage(self):\n        self._run_test(\"n_structure_object_with_trailing_garbage.json\")\n\n    def test_fragment_n_structure_open_array_apostrophe(self):\n        self._run_test(\"n_structure_open_array_apostrophe.json\")\n\n    def test_fragment_n_structure_open_array_comma(self):\n        self._run_test(\"n_structure_open_array_comma.json\")\n\n    def test_fragment_n_structure_open_array_object(self):\n        self._run_test(\"n_structure_open_array_object.json.xz\")\n\n    def test_fragment_n_structure_open_array_open_object(self):\n        self._run_test(\"n_structure_open_array_open_object.json\")\n\n    def test_fragment_n_structure_open_array_open_string(self):\n        self._run_test(\"n_structure_open_array_open_string.json\")\n\n    def test_fragment_n_structure_open_array_string(self):\n        self._run_test(\"n_structure_open_array_string.json\")\n\n    def test_fragment_n_structure_open_object(self):\n        self._run_test(\"n_structure_open_object.json\")\n\n    def test_fragment_n_structure_open_object_close_array(self):\n        self._run_test(\"n_structure_open_object_close_array.json\")\n\n    def test_fragment_n_structure_open_object_comma(self):\n        self._run_test(\"n_structure_open_object_comma.json\")\n\n    def test_fragment_n_structure_open_object_open_array(self):\n        self._run_test(\"n_structure_open_object_open_array.json\")\n\n    def test_fragment_n_structure_open_object_open_string(self):\n        self._run_test(\"n_structure_open_object_open_string.json\")\n\n    def test_fragment_n_structure_open_object_string_with_apostrophe(self):\n        self._run_test(\"n_structure_open_object_string_with_apostrophes.json\")\n\n    def test_fragment_n_structure_open_ope(self):\n        self._run_test(\"n_structure_open_open.json\")\n\n    def test_fragment_n_structure_single_eacute(self):\n        self._run_test(\"n_structure_single_eacute.json\")\n\n    def test_fragment_n_structure_single_star(self):\n        self._run_test(\"n_structure_single_star.json\")\n\n    def test_fragment_n_structure_trailing_(self):\n        self._run_test(\"n_structure_trailing_#.json\")\n\n    def test_fragment_n_structure_uescaped_LF_before_string(self):\n        self._run_test(\"n_structure_uescaped_LF_before_string.json\")\n\n    def test_fragment_n_structure_unclosed_array(self):\n        self._run_test(\"n_structure_unclosed_array.json\")\n\n    def test_fragment_n_structure_unclosed_array_partial_null(self):\n        self._run_test(\"n_structure_unclosed_array_partial_null.json\")\n\n    def test_fragment_n_structure_unclosed_array_unfinished_false(self):\n        self._run_test(\"n_structure_unclosed_array_unfinished_false.json\")\n\n    def test_fragment_n_structure_unclosed_array_unfinished_true(self):\n        self._run_test(\"n_structure_unclosed_array_unfinished_true.json\")\n\n    def test_fragment_n_structure_unclosed_object(self):\n        self._run_test(\"n_structure_unclosed_object.json\")\n\n    def test_fragment_n_structure_unicode_identifier(self):\n        self._run_test(\"n_structure_unicode-identifier.json\")\n\n    def test_fragment_n_structure_whitespace_U_2060_word_joiner(self):\n        self._run_test(\"n_structure_whitespace_U+2060_word_joiner.json\")\n\n    def test_fragment_n_structure_whitespace_formfeed(self):\n        self._run_test(\"n_structure_whitespace_formfeed.json\")\n\n    def test_fragment_i_number_double_huge_neg_exp(self):\n        self._run_test(\"i_number_double_huge_neg_exp.json\")\n\n    def test_fragment_i_number_huge_exp(self):\n        self._run_test(\"i_number_huge_exp.json\")\n\n    def test_fragment_i_number_neg_int_huge_exp(self):\n        self._run_test(\"i_number_neg_int_huge_exp.json\")\n\n    def test_fragment_i_number_pos_double_huge_exp(self):\n        self._run_test(\"i_number_pos_double_huge_exp.json\")\n\n    def test_fragment_i_number_real_neg_overflow(self):\n        self._run_test(\"i_number_real_neg_overflow.json\")\n\n    def test_fragment_i_number_real_pos_overflow(self):\n        self._run_test(\"i_number_real_pos_overflow.json\")\n\n    def test_fragment_i_number_real_underflow(self):\n        self._run_test(\"i_number_real_underflow.json\")\n\n    def test_fragment_i_number_too_big_neg_int(self):\n        self._run_test(\"i_number_too_big_neg_int.json\")\n\n    def test_fragment_i_number_too_big_pos_int(self):\n        self._run_test(\"i_number_too_big_pos_int.json\")\n\n    def test_fragment_i_number_very_big_negative_int(self):\n        self._run_test(\"i_number_very_big_negative_int.json\")\n\n    def test_fragment_i_object_key_lone_2nd_surrogate(self):\n        self._run_test(\"i_object_key_lone_2nd_surrogate.json\")\n\n    def test_fragment_i_string_1st_surrogate_but_2nd_missing(self):\n        self._run_test(\"i_string_1st_surrogate_but_2nd_missing.json\")\n\n    def test_fragment_i_string_1st_valid_surrogate_2nd_invalid(self):\n        self._run_test(\"i_string_1st_valid_surrogate_2nd_invalid.json\")\n\n    def test_fragment_i_string_UTF_16LE_with_BOM(self):\n        self._run_test(\"i_string_UTF-16LE_with_BOM.json\")\n\n    def test_fragment_i_string_UTF_8_invalid_sequence(self):\n        self._run_test(\"i_string_UTF-8_invalid_sequence.json\")\n\n    def test_fragment_i_string_UTF8_surrogate_U_D800(self):\n        self._run_test(\"i_string_UTF8_surrogate_U+D800.json\")\n\n    def test_fragment_i_string_incomplete_surrogate_and_escape_valid(self):\n        self._run_test(\"i_string_incomplete_surrogate_and_escape_valid.json\")\n\n    def test_fragment_i_string_incomplete_surrogate_pair(self):\n        self._run_test(\"i_string_incomplete_surrogate_pair.json\")\n\n    def test_fragment_i_string_incomplete_surrogates_escape_valid(self):\n        self._run_test(\"i_string_incomplete_surrogates_escape_valid.json\")\n\n    def test_fragment_i_string_invalid_lonely_surrogate(self):\n        self._run_test(\"i_string_invalid_lonely_surrogate.json\")\n\n    def test_fragment_i_string_invalid_surrogate(self):\n        self._run_test(\"i_string_invalid_surrogate.json\")\n\n    def test_fragment_i_string_invalid_utf_8(self):\n        self._run_test(\"i_string_invalid_utf-8.json\")\n\n    def test_fragment_i_string_inverted_surrogates_U_1D11E(self):\n        self._run_test(\"i_string_inverted_surrogates_U+1D11E.json\")\n\n    def test_fragment_i_string_iso_latin_1(self):\n        self._run_test(\"i_string_iso_latin_1.json\")\n\n    def test_fragment_i_string_lone_second_surrogate(self):\n        self._run_test(\"i_string_lone_second_surrogate.json\")\n\n    def test_fragment_i_string_lone_utf8_continuation_byte(self):\n        self._run_test(\"i_string_lone_utf8_continuation_byte.json\")\n\n    def test_fragment_i_string_not_in_unicode_range(self):\n        self._run_test(\"i_string_not_in_unicode_range.json\")\n\n    def test_fragment_i_string_overlong_sequence_2_byte(self):\n        self._run_test(\"i_string_overlong_sequence_2_bytes.json\")\n\n    def test_fragment_i_string_overlong_sequence_6_byte(self):\n        self._run_test(\"i_string_overlong_sequence_6_bytes.json\")\n\n    def test_fragment_i_string_overlong_sequence_6_bytes_null(self):\n        self._run_test(\"i_string_overlong_sequence_6_bytes_null.json\")\n\n    def test_fragment_i_string_truncated_utf_8(self):\n        self._run_test(\"i_string_truncated-utf-8.json\")\n\n    def test_fragment_i_string_utf16BE_no_BOM(self):\n        self._run_test(\"i_string_utf16BE_no_BOM.json\")\n\n    def test_fragment_i_string_utf16LE_no_BOM(self):\n        self._run_test(\"i_string_utf16LE_no_BOM.json\")\n\n    def test_fragment_i_structure_500_nested_array(self):\n        self._run_test(\"i_structure_500_nested_arrays.json.xz\")\n\n    def test_fragment_i_structure_UTF_8_BOM_empty_object(self):\n        self._run_test(\"i_structure_UTF-8_BOM_empty_object.json\")\n"
  },
  {
    "path": "test/test_indent.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2020-2025)\n\nimport datetime\nimport json\n\nimport orjson\n\nfrom .util import needs_data, read_fixture_obj\n\n\n@needs_data\nclass TestIndentedOutput:\n    def test_equivalent(self):\n        \"\"\"\n        OPT_INDENT_2 is equivalent to indent=2\n        \"\"\"\n        obj = {\"a\": \"b\", \"c\": {\"d\": True}, \"e\": [1, 2]}\n        assert orjson.dumps(obj, option=orjson.OPT_INDENT_2) == json.dumps(\n            obj,\n            indent=2,\n        ).encode(\"utf-8\")\n\n    def test_sort(self):\n        obj = {\"b\": 1, \"a\": 2}\n        assert (\n            orjson.dumps(obj, option=orjson.OPT_INDENT_2 | orjson.OPT_SORT_KEYS)\n            == b'{\\n  \"a\": 2,\\n  \"b\": 1\\n}'\n        )\n\n    def test_non_str(self):\n        obj = {1: 1, \"a\": 2}\n        assert (\n            orjson.dumps(obj, option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS)\n            == b'{\\n  \"1\": 1,\\n  \"a\": 2\\n}'\n        )\n\n    def test_options(self):\n        obj = {\n            1: 1,\n            \"b\": True,\n            \"a\": datetime.datetime(1970, 1, 1),\n        }\n        assert (\n            orjson.dumps(\n                obj,\n                option=orjson.OPT_INDENT_2\n                | orjson.OPT_SORT_KEYS\n                | orjson.OPT_NON_STR_KEYS\n                | orjson.OPT_NAIVE_UTC,\n            )\n            == b'{\\n  \"1\": 1,\\n  \"a\": \"1970-01-01T00:00:00+00:00\",\\n  \"b\": true\\n}'\n        )\n\n    def test_empty(self):\n        obj = [{}, [[[]]], {\"key\": []}]\n        ref = b'[\\n  {},\\n  [\\n    [\\n      []\\n    ]\\n  ],\\n  {\\n    \"key\": []\\n  }\\n]'\n        assert orjson.dumps(obj, option=orjson.OPT_INDENT_2) == ref\n\n    def test_list_max(self):\n        fixture = b\"\".join(\n            (b\"\".join(b\"[\" for _ in range(254)), b\"\".join(b\"]\" for _ in range(254))),\n        )\n        obj = orjson.loads(fixture)\n        serialized = orjson.dumps(\n            obj,\n            option=orjson.OPT_INDENT_2,\n        )\n        assert orjson.loads(serialized) == obj\n\n    def test_dict_max(self):\n        fixture = {\"key\": None}\n        target = fixture\n        for _ in range(253):\n            target[\"key\"] = {\"key\": None}  # type:ignore\n            target = target[\"key\"]  # type: ignore\n\n        serialized = orjson.dumps(\n            fixture,\n            option=orjson.OPT_INDENT_2,\n        )\n        assert orjson.loads(serialized) == fixture\n\n    def test_twitter_pretty(self):\n        \"\"\"\n        twitter.json pretty\n        \"\"\"\n        obj = read_fixture_obj(\"twitter.json.xz\")\n        assert orjson.dumps(obj, option=orjson.OPT_INDENT_2) == json.dumps(\n            obj,\n            indent=2,\n            ensure_ascii=False,\n        ).encode(\"utf-8\")\n\n    def test_github_pretty(self):\n        \"\"\"\n        github.json pretty\n        \"\"\"\n        obj = read_fixture_obj(\"github.json.xz\")\n        assert orjson.dumps(obj, option=orjson.OPT_INDENT_2) == json.dumps(\n            obj,\n            indent=2,\n            ensure_ascii=False,\n        ).encode(\"utf-8\")\n\n    def test_canada_pretty(self):\n        \"\"\"\n        canada.json pretty\n        \"\"\"\n        obj = read_fixture_obj(\"canada.json.xz\")\n        assert orjson.dumps(obj, option=orjson.OPT_INDENT_2) == json.dumps(\n            obj,\n            indent=2,\n            ensure_ascii=False,\n        ).encode(\"utf-8\")\n\n    def test_citm_catalog_pretty(self):\n        \"\"\"\n        citm_catalog.json pretty\n        \"\"\"\n        obj = read_fixture_obj(\"citm_catalog.json.xz\")\n        assert orjson.dumps(obj, option=orjson.OPT_INDENT_2) == json.dumps(\n            obj,\n            indent=2,\n            ensure_ascii=False,\n        ).encode(\"utf-8\")\n"
  },
  {
    "path": "test/test_issue221.py",
    "content": "# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2022-2025), Aarni Koskela (2022)\n\nimport pytest\n\nimport orjson\n\n\n@pytest.mark.parametrize(\n    \"val\",\n    [\n        b'\"\\xc8\\x93',\n        b'\"\\xc8',\n    ],\n)\ndef test_invalid(val):\n    with pytest.raises(orjson.JSONDecodeError):\n        orjson.loads(val)\n"
  },
  {
    "path": "test/test_issue331.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2023-2025)\n\nimport datetime\n\nimport orjson\n\nfrom .util import needs_data, read_fixture_bytes\n\nFIXTURE_ISSUE_335 = {\n    \"pfkrpavmb\": \"maxyjzmvacdwjfiifmzwbztjmnqdsjesykpf\",\n    \"obtsdcnmi\": \"psyucdnwjr\",\n    \"ghsccsccdwep\": 1673954411550,\n    \"vyqvkq\": \"ilfcrjas\",\n    \"drfobem\": {\n        \"mzqwuvwsglxx\": 1673954411550,\n        \"oup\": \"mmimyli\",\n        \"pxfepg\": {\n            \"pnqjr\": \"ylttscz\",\n            \"rahfmy\": \"xrcsutu\",\n            \"rccgrkom\": \"fbt\",\n            \"xulnoryigkhtoybq\": \"hubxdjrnaq\",\n            \"vdwriwvlgu\": datetime.datetime(\n                2023,\n                1,\n                15,\n                15,\n                23,\n                38,\n                686000,\n                tzinfo=datetime.timezone.utc,\n            ),\n            \"fhmjsszqmxwfruiq\": \"fzghfrbjxqccf\",\n            \"dyiurstuzhu\": None,\n            \"tdovgfimofmclc\": datetime.datetime(\n                2023,\n                1,\n                15,\n                15,\n                23,\n                38,\n                686000,\n                tzinfo=datetime.timezone.utc,\n            ),\n            \"iyxkgbwxdlrdc\": datetime.datetime(\n                2023,\n                1,\n                17,\n                11,\n                19,\n                55,\n                761000,\n                tzinfo=datetime.timezone.utc,\n            ),\n            \"jnjtckehsrtwhgzuhksmclk\": [\"tlejijcpbjzygepptbxgrugcbufncyupnivbljzhxe\"],\n            \"zewoojzsiykjf\": datetime.datetime(\n                2023,\n                1,\n                17,\n                11,\n                17,\n                46,\n                140960,\n                tzinfo=datetime.timezone.utc,\n            ),\n            \"muzabbfnxptvqwzbeilkz\": False,\n            \"wdiuepootdqyniogblxgwkgcqezutcesb\": None,\n            \"lzkthufcerqnxdypdts\": datetime.datetime(\n                2023,\n                1,\n                17,\n                11,\n                19,\n                56,\n                73000,\n                tzinfo=datetime.timezone.utc,\n            ),\n            \"epukgzafaubmn\": 50000.0,\n            \"cdpeessdedncodoajdqsos\": 50000.0,\n            \"adxucexfjgfwxo\": \"jwuoomwdrfklgt\",\n            \"sotxdizdpuunbssidop\": None,\n            \"lxmgvysiltbzfkjne\": None,\n            \"wyeaarjbilfmjbfzjuzv\": None,\n            \"cwlcgx\": -1272.22,\n            \"oniptvyaub\": -1275.75,\n            \"hqsfeelokxlwnha\": datetime.datetime(\n                2023,\n                1,\n                17,\n                11,\n                19,\n                55,\n                886000,\n                tzinfo=datetime.timezone.utc,\n            ),\n            \"nuidlcyrxcrkyytgrnmc\": -733.5,\n            \"wmofdeftonjcdnkg\": -737.03,\n            \"bnsttxjfxxgxphfiguqew\": datetime.datetime(\n                2023,\n                1,\n                17,\n                11,\n                19,\n                55,\n                886000,\n                tzinfo=datetime.timezone.utc,\n            ),\n            \"audhoqqxjliwnsqttwsadmwwv\": -737.03,\n            \"badwwjzugwtdkbsamckoljfrrumtrt\": datetime.datetime(\n                2023,\n                1,\n                17,\n                11,\n                19,\n                55,\n                886000,\n                tzinfo=datetime.timezone.utc,\n            ),\n            \"zlbggbbjgsugkgkqjycxwdx\": -1241.28,\n            \"fxueeffryeafcxtkfzdmlmgu\": -538.72,\n            \"yjmapfqummrsyujkosmixumjgfkwd\": datetime.datetime(\n                2023,\n                1,\n                16,\n                22,\n                59,\n                59,\n                999999,\n                tzinfo=datetime.timezone.utc,\n            ),\n            \"qepdxlodjetleseyminybdvitcgd\": None,\n            \"ltokvpltajwbn\": datetime.date(2023, 1, 17),\n            \"ifzhionnrpeoorsupiniwbljek\": datetime.datetime(\n                2023,\n                1,\n                17,\n                11,\n                19,\n                49,\n                113000,\n                tzinfo=datetime.timezone.utc,\n            ),\n            \"ljmmehacdawrlbhlhthm\": -1241.28,\n            \"jnwffrtloedorwctsclshnpwjq\": -702.56,\n            \"yhgssmtrmrcqhsdaekvoxyv\": None,\n            \"nfzljididdzkofkrjfxdloygjxfhhoe\": None,\n            \"mpctjlifbrgugaugiijj\": None,\n            \"ckknohnsefzknbvnmwzlxlajsckl\": None,\n            \"rfehqmeeslkcfbptrrghvivcrx\": None,\n            \"nqeovbshknctkgkcytzbhfuvpcyamfrafi\": None,\n            \"lptomdhvkvjnegsanzshqecas\": 0,\n            \"vkbijuitbghlywkeojjf\": None,\n            \"hzzmtggbqdglch\": \"xgehztikx\",\n            \"yhmplqyhbndcfdafjvvr\": False,\n            \"oucaxvjhjapayexuqwvnnls\": None,\n            \"xbnagbhttfloffstxyr\": 1673954411.5502248,\n            \"eiqrshvbjmlyzqle\": {\n                \"dkayiglkkhfrvbliqy\": [\"ohjuifj\"],\n                \"grqcjzqdiaslqaxhcqg\": [\"fuuxwsu\"],\n            },\n            \"uflenvgkk\": {\n                \"ehycwsz\": {\n                    \"jeikui\": \"noxawd\",\n                    \"gkrefq\": \"hfonlfp\",\n                    \"xkxs\": \"jzt\",\n                    \"ztpmv\": \"mpscuot\",\n                    \"zagmfzmgh\": \"pdculhh\",\n                    \"jgzsrpukwqoln\": 100000.0,\n                    \"vlqzkxbwc\": datetime.datetime(\n                        2023,\n                        1,\n                        17,\n                        11,\n                        19,\n                        50,\n                        867000,\n                        tzinfo=datetime.timezone.utc,\n                    ),\n                    \"cchovdmelbchcgvtg\": -30.94,\n                    \"xvznnjfpwtdujqrh\": 0.92059,\n                    \"tmsqwiiopyhlcovcxhojuzzyac\": 1.0862009,\n                    \"tfzkaimjrpsbeswnrxeo\": 0.0,\n                    \"isqjxmjupeiboufeaavkdj\": -9.76,\n                    \"ywjqjiasfuifyqmz\": 0.0,\n                    \"uvtlmdrk\": 0.92028,\n                    \"dquzguej\": None,\n                    \"guudreveynvhvhihegoybqrmejkj\": datetime.datetime(\n                        2023,\n                        1,\n                        17,\n                        11,\n                        19,\n                        56,\n                        73000,\n                        tzinfo=datetime.timezone.utc,\n                    ),\n                    \"agvnijfztpbpatej\": \"zym\",\n                    \"mqsozcvnuvueixszfz\": [\n                        {\n                            \"oepzcayabl\": \"givcnhztbdmili\",\n                            \"rhhaorqbiziqvyhglecqw\": True,\n                            \"paxvrmateisxfqs\": 1.0862009,\n                            \"bydrnmhvj\": {\n                                \"kwqlickvqv\": \"beinfgmofalgytujorwxqfvlxtbeujmqwrdqzkfpul\",\n                                \"cxdikf\": \"dfpbnpe\",\n                                \"dnnhiy\": \"reeenz\",\n                                \"tx\": datetime.datetime(\n                                    2023,\n                                    1,\n                                    17,\n                                    11,\n                                    19,\n                                    56,\n                                    73000,\n                                    tzinfo=datetime.timezone.utc,\n                                ),\n                                \"tck\": datetime.date(2023, 1, 17),\n                                \"nvt\": 0.92064,\n                                \"enc\": 0.92059,\n                                \"icginezbybhcs\": 1673954396073,\n                                \"gfamgxmknxirghgmtxl\": 1673954411.5492423,\n                            },\n                        },\n                    ],\n                    \"dqiabsyky\": {\n                        \"hxzdtwunrr\": \"fozhshbmijhujcznqykxtlaxfbtdpzvwvjtyuqzlyw\",\n                        \"tmpscl\": \"tbivvoa\",\n                        \"vjjjvl\": \"arukeb\",\n                        \"fm\": datetime.datetime(\n                            2023,\n                            1,\n                            17,\n                            11,\n                            19,\n                            56,\n                            73000,\n                            tzinfo=datetime.timezone.utc,\n                        ),\n                        \"rjq\": datetime.date(2023, 1, 17),\n                        \"oax\": 0.92064,\n                        \"gdv\": 0.92059,\n                        \"vousomtllbpsh\": 1673954396073,\n                        \"pgiblyqswxvwkpmpyay\": 1673954411.5492423,\n                    },\n                    \"gebil\": [\n                        {\n                            \"bzrjh\": 0.92065,\n                            \"izmljcvqinm\": 3.25,\n                            \"legczrbxlrmcep\": None,\n                        },\n                    ],\n                    \"eqg\": [\n                        {\n                            \"yngp\": \"kako\",\n                            \"udntq\": {\n                                \"wzygahsmwd\": \"hplammnltegchpaorxaremhymtqtxdpfzzoyouimnw\",\n                                \"iofcbwwgu\": datetime.datetime(\n                                    2023,\n                                    1,\n                                    17,\n                                    11,\n                                    19,\n                                    50,\n                                    867000,\n                                    tzinfo=datetime.timezone.utc,\n                                ),\n                                \"nengib\": \"zpyilz\",\n                                \"sorpcw\": \"ixhzipg\",\n                                \"kruw\": \"taq\",\n                                \"vaqaj\": \"kravspj\",\n                                \"omkjhzkxp\": \"watatag\",\n                                \"ckwtjcqkjxmdn\": 100000.0,\n                                \"kpjtgiuhfqx\": 3.25,\n                                \"upkgqboyyg\": 0.92065,\n                                \"gkshzyqtpmolnybr\": 0.92065,\n                                \"oeiueaildnobcyzzpqwjwivkgj\": 1.0861891,\n                                \"hiheqtjxyjnweryve\": 0.0,\n                                \"wntcyohtaeylkylp\": 0.0,\n                                \"jmebuufukzzymohzynpxzp\": -9.76,\n                                \"rblubytyjuvbeurwrqmz\": 0.0,\n                                \"xpscrgcnratymu\": None,\n                            },\n                        },\n                    ],\n                    \"kpmgmiqgmswzebawzciss\": -0.7,\n                    \"ktggnjdemtfxhnultritqokgbjucktdiooic\": 0.92058,\n                    \"oawdfonaymcwwvmszhdlemjcnb\": datetime.datetime(\n                        2023,\n                        1,\n                        17,\n                        11,\n                        19,\n                        55,\n                        886000,\n                        tzinfo=datetime.timezone.utc,\n                    ),\n                    \"bwfkzqjqqjdgbfbbjwoxhweihipy\": \"lzvn\",\n                    \"feslxjpurrukajwellwjqww\": 0.0,\n                    \"ptuysyuuhwkfqlugjlxkohwanzijtzknupfikp\": None,\n                    \"gquuleqhpsbyiluhijdddreenggl\": datetime.datetime(\n                        2023,\n                        1,\n                        17,\n                        11,\n                        19,\n                        50,\n                        867000,\n                        tzinfo=datetime.timezone.utc,\n                    ),\n                    \"auhxrvhvvtszkkkpyhbhvpjlypjoyz\": \"vqdxfdvgxqcu\",\n                },\n            },\n        },\n        \"qbov\": \"vylhkevwf\",\n        \"uidiyv\": {\n            \"qkyoj\": {\n                \"cclzxqbosqmj\": 1673954395761,\n                \"rzijfrywwwcr\": 1,\n                \"toujesmzk\": \"afnu\",\n                \"aqmpunnlt\": \"nyreokscjljpfcrrstxgvwddphymgzkvuolbigqhla\",\n                \"ofrjrk\": \"rlffwrw\",\n                \"legyfjl\": {\n                    \"byalenyqro\": \"tbzhyxo\",\n                    \"qxrtujt\": 0.92028,\n                    \"onmhbvy\": 0,\n                    \"cbhmp\": \"vqrkzbg\",\n                },\n            },\n        },\n    },\n}\n\n\n@needs_data\ndef test_issue331_1_pretty():\n    as_bytes = read_fixture_bytes(\"issue331_1.json.xz\")\n    as_obj = orjson.loads(as_bytes)\n    for _ in range(1000):\n        assert orjson.loads(orjson.dumps(as_obj, option=orjson.OPT_INDENT_2)) == as_obj\n\n\n@needs_data\ndef test_issue331_1_compact():\n    as_bytes = read_fixture_bytes(\"issue331_1.json.xz\")\n    as_obj = orjson.loads(as_bytes)\n    for _ in range(1000):\n        assert orjson.loads(orjson.dumps(as_obj)) == as_obj\n\n\n@needs_data\ndef test_issue331_2_pretty():\n    as_bytes = read_fixture_bytes(\"issue331_2.json.xz\")\n    as_obj = orjson.loads(as_bytes)\n    for _ in range(1000):\n        assert orjson.loads(orjson.dumps(as_obj, option=orjson.OPT_INDENT_2)) == as_obj\n\n\n@needs_data\ndef test_issue331_2_compact():\n    as_bytes = read_fixture_bytes(\"issue331_2.json.xz\")\n    as_obj = orjson.loads(as_bytes)\n    for _ in range(1000):\n        assert orjson.loads(orjson.dumps(as_obj)) == as_obj\n\n\ndef test_issue335_compact():\n    for _ in range(1000):\n        assert orjson.dumps(FIXTURE_ISSUE_335)\n\n\ndef test_issue335_pretty():\n    for _ in range(1000):\n        assert orjson.dumps(FIXTURE_ISSUE_335, option=orjson.OPT_INDENT_2)\n"
  },
  {
    "path": "test/test_jsonchecker.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2018-2026)\n# Test files from http://json.org/JSON_checker/\n\nimport pytest\n\nimport orjson\n\nfrom .util import needs_data, read_fixture_str\n\nPATTERN_1 = '[\"JSON Test Pattern pass1\",{\"object with 1 member\":[\"array with 1 element\"]},{},[],-42,true,false,null,{\"integer\":1234567890,\"real\":-9876.54321,\"e\":1.23456789e-13,\"E\":1.23456789e+34,\"\":2.3456789012e+76,\"zero\":0,\"one\":1,\"space\":\" \",\"quote\":\"\\\\\"\",\"backslash\":\"\\\\\\\\\",\"controls\":\"\\\\b\\\\f\\\\n\\\\r\\\\t\",\"slash\":\"/ & /\",\"alpha\":\"abcdefghijklmnopqrstuvwyz\",\"ALPHA\":\"ABCDEFGHIJKLMNOPQRSTUVWYZ\",\"digit\":\"0123456789\",\"0123456789\":\"digit\",\"special\":\"`1~!@#$%^&*()_+-={\\':[,]}|;.</>?\",\"hex\":\"ģ䕧覫췯ꯍ\\uef4a\",\"true\":true,\"false\":false,\"null\":null,\"array\":[],\"object\":{},\"address\":\"50 St. James Street\",\"url\":\"http://www.JSON.org/\",\"comment\":\"// /* <!-- --\",\"# -- --> */\":\" \",\" s p a c e d \":[1,2,3,4,5,6,7],\"compact\":[1,2,3,4,5,6,7],\"jsontext\":\"{\\\\\"object with 1 member\\\\\":[\\\\\"array with 1 element\\\\\"]}\",\"quotes\":\"&#34; \\\\\" %22 0x22 034 &#x22;\",\"/\\\\\\\\\\\\\"쫾몾ꮘﳞ볚\\uef4a\\\\b\\\\f\\\\n\\\\r\\\\t`1~!@#$%^&*()_+-=[]{}|;:\\',./<>?\":\"A key can be any string\"},0.5,98.6,99.44,1066,10.0,1.0,0.1,1.0,2.0,2.0,\"rosebud\"]'.encode()\n\n\n@needs_data\nclass TestJsonChecker:\n    def _run_fail_json(self, filename, exc=orjson.JSONDecodeError):\n        data = read_fixture_str(filename, \"jsonchecker\")\n        pytest.raises(exc, orjson.loads, data)\n\n    def _run_pass_json(self, filename, match=\"\"):\n        data = read_fixture_str(filename, \"jsonchecker\")\n        assert orjson.dumps(orjson.loads(data)) == match\n\n    def test_fail01(self):\n        \"\"\"\n        fail01.json\n        \"\"\"\n        self._run_pass_json(\n            \"fail01.json\",\n            b'\"A JSON payload should be an object or array, not a string.\"',\n        )\n\n    def test_fail02(self):\n        \"\"\"\n        fail02.json\n        \"\"\"\n        self._run_fail_json(\"fail02.json\", orjson.JSONDecodeError)  # EOF\n\n    def test_fail03(self):\n        \"\"\"\n        fail03.json\n        \"\"\"\n        self._run_fail_json(\"fail03.json\")\n\n    def test_fail04(self):\n        \"\"\"\n        fail04.json\n        \"\"\"\n        self._run_fail_json(\"fail04.json\")\n\n    def test_fail05(self):\n        \"\"\"\n        fail05.json\n        \"\"\"\n        self._run_fail_json(\"fail05.json\")\n\n    def test_fail06(self):\n        \"\"\"\n        fail06.json\n        \"\"\"\n        self._run_fail_json(\"fail06.json\")\n\n    def test_fail07(self):\n        \"\"\"\n        fail07.json\n        \"\"\"\n        self._run_fail_json(\"fail07.json\")\n\n    def test_fail08(self):\n        \"\"\"\n        fail08.json\n        \"\"\"\n        self._run_fail_json(\"fail08.json\")\n\n    def test_fail09(self):\n        \"\"\"\n        fail09.json\n        \"\"\"\n        self._run_fail_json(\"fail09.json\")\n\n    def test_fail10(self):\n        \"\"\"\n        fail10.json\n        \"\"\"\n        self._run_fail_json(\"fail10.json\")\n\n    def test_fail11(self):\n        \"\"\"\n        fail11.json\n        \"\"\"\n        self._run_fail_json(\"fail11.json\")\n\n    def test_fail12(self):\n        \"\"\"\n        fail12.json\n        \"\"\"\n        self._run_fail_json(\"fail12.json\")\n\n    def test_fail13(self):\n        \"\"\"\n        fail13.json\n        \"\"\"\n        self._run_fail_json(\"fail13.json\")\n\n    def test_fail14(self):\n        \"\"\"\n        fail14.json\n        \"\"\"\n        self._run_fail_json(\"fail14.json\")\n\n    def test_fail15(self):\n        \"\"\"\n        fail15.json\n        \"\"\"\n        self._run_fail_json(\"fail15.json\")\n\n    def test_fail16(self):\n        \"\"\"\n        fail16.json\n        \"\"\"\n        self._run_fail_json(\"fail16.json\")\n\n    def test_fail17(self):\n        \"\"\"\n        fail17.json\n        \"\"\"\n        self._run_fail_json(\"fail17.json\")\n\n    def test_fail18(self):\n        \"\"\"\n        fail18.json\n        \"\"\"\n        self._run_pass_json(\n            \"fail18.json\",\n            b'[[[[[[[[[[[[[[[[[[[[\"Too deep\"]]]]]]]]]]]]]]]]]]]]',\n        )\n\n    def test_fail19(self):\n        \"\"\"\n        fail19.json\n        \"\"\"\n        self._run_fail_json(\"fail19.json\")\n\n    def test_fail20(self):\n        \"\"\"\n        fail20.json\n        \"\"\"\n        self._run_fail_json(\"fail20.json\")\n\n    def test_fail21(self):\n        \"\"\"\n        fail21.json\n        \"\"\"\n        self._run_fail_json(\"fail21.json\")\n\n    def test_fail22(self):\n        \"\"\"\n        fail22.json\n        \"\"\"\n        self._run_fail_json(\"fail22.json\")\n\n    def test_fail23(self):\n        \"\"\"\n        fail23.json\n        \"\"\"\n        self._run_fail_json(\"fail23.json\")\n\n    def test_fail24(self):\n        \"\"\"\n        fail24.json\n        \"\"\"\n        self._run_fail_json(\"fail24.json\")\n\n    def test_fail25(self):\n        \"\"\"\n        fail25.json\n        \"\"\"\n        self._run_fail_json(\"fail25.json\")\n\n    def test_fail26(self):\n        \"\"\"\n        fail26.json\n        \"\"\"\n        self._run_fail_json(\"fail26.json\")\n\n    def test_fail27(self):\n        \"\"\"\n        fail27.json\n        \"\"\"\n        self._run_fail_json(\"fail27.json\")\n\n    def test_fail28(self):\n        \"\"\"\n        fail28.json\n        \"\"\"\n        self._run_fail_json(\"fail28.json\")\n\n    def test_fail29(self):\n        \"\"\"\n        fail29.json\n        \"\"\"\n        self._run_fail_json(\"fail29.json\")\n\n    def test_fail30(self):\n        \"\"\"\n        fail30.json\n        \"\"\"\n        self._run_fail_json(\"fail30.json\")\n\n    def test_fail31(self):\n        \"\"\"\n        fail31.json\n        \"\"\"\n        self._run_fail_json(\"fail31.json\")\n\n    def test_fail32(self):\n        \"\"\"\n        fail32.json\n        \"\"\"\n        self._run_fail_json(\"fail32.json\", orjson.JSONDecodeError)  # EOF\n\n    def test_fail33(self):\n        \"\"\"\n        fail33.json\n        \"\"\"\n        self._run_fail_json(\"fail33.json\")\n\n    def test_pass01(self):\n        \"\"\"\n        pass01.json\n        \"\"\"\n        self._run_pass_json(\"pass01.json\", PATTERN_1)\n\n    def test_pass02(self):\n        \"\"\"\n        pass02.json\n        \"\"\"\n        self._run_pass_json(\n            \"pass02.json\",\n            b'[[[[[[[[[[[[[[[[[[[\"Not too deep\"]]]]]]]]]]]]]]]]]]]',\n        )\n\n    def test_pass03(self):\n        \"\"\"\n        pass03.json\n        \"\"\"\n        self._run_pass_json(\n            \"pass03.json\",\n            b'{\"JSON Test Pattern pass3\":{\"The outermost value\":\"must be '\n            b'an object or array.\",\"In this test\":\"It is an object.\"}}',\n        )\n"
  },
  {
    "path": "test/test_memory.py",
    "content": "# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2019-2026), Rami Chowdhury (2020)\n\nimport dataclasses\nimport datetime\nimport gc\nimport random\n\nfrom .util import SUPPORTS_MEMORYVIEW, numpy, pandas\n\ntry:\n    import pytz\nexcept ImportError:\n    pytz = None  # type: ignore\n\ntry:\n    import psutil\nexcept ImportError:\n    psutil = None  # type: ignore\n\nimport pytest\n\nimport orjson\n\nfrom .util import IS_FREETHREADING\n\nFIXTURE = '{\"a\":[81891289, 8919812.190129012], \"b\": false, \"c\": null, \"d\": \"東京\"}'\n\n\ndef default(obj):\n    return str(obj)\n\n\n@dataclasses.dataclass\nclass Member:\n    id: int\n    active: bool\n\n\n@dataclasses.dataclass\nclass Object:\n    id: int\n    updated_at: datetime.datetime\n    name: str\n    members: list[Member]\n\n\nDATACLASS_FIXTURE = [\n    Object(\n        i,\n        datetime.datetime.now(datetime.timezone.utc)\n        + datetime.timedelta(seconds=random.randint(0, 10000)),\n        str(i) * 3,\n        [Member(j, True) for j in range(10)],\n    )\n    for i in range(100000, 101000)\n]\n\nMAX_INCREASE = 4194304  # 4MiB\n\nif IS_FREETHREADING:\n    MAX_INCREASE *= 4\n\n\nclass Unsupported:\n    pass\n\n\nclass TestMemory:\n    @pytest.mark.skipif(psutil is None, reason=\"psutil not installed\")\n    def test_memory_loads(self):\n        \"\"\"\n        loads() memory leak\n        \"\"\"\n        proc = psutil.Process()\n        gc.collect()\n        val = orjson.loads(FIXTURE)\n        assert val\n        mem = proc.memory_info().rss\n        for _ in range(10000):\n            val = orjson.loads(FIXTURE)\n            assert val\n        gc.collect()\n        assert proc.memory_info().rss <= mem + MAX_INCREASE\n\n    @pytest.mark.skipif(psutil is None, reason=\"psutil not installed\")\n    @pytest.mark.skipif(SUPPORTS_MEMORYVIEW is False, reason=\"memoryview\")\n    def test_memory_loads_memoryview(self):\n        \"\"\"\n        loads() memory leak using memoryview\n        \"\"\"\n        proc = psutil.Process()\n        gc.collect()\n        fixture = FIXTURE.encode(\"utf-8\")\n        val = orjson.loads(fixture)\n        assert val\n        mem = proc.memory_info().rss\n        for _ in range(10000):\n            val = orjson.loads(memoryview(fixture))\n            assert val\n        gc.collect()\n        assert proc.memory_info().rss <= mem + MAX_INCREASE\n\n    @pytest.mark.skipif(psutil is None, reason=\"psutil not installed\")\n    def test_memory_dumps(self):\n        \"\"\"\n        dumps() memory leak\n        \"\"\"\n        proc = psutil.Process()\n        gc.collect()\n        fixture = orjson.loads(FIXTURE)\n        val = orjson.dumps(fixture)\n        assert val\n        mem = proc.memory_info().rss\n        for _ in range(10000):\n            val = orjson.dumps(fixture)\n            assert val\n        gc.collect()\n        assert proc.memory_info().rss <= mem + MAX_INCREASE\n        assert proc.memory_info().rss <= mem + MAX_INCREASE\n\n    @pytest.mark.skipif(psutil is None, reason=\"psutil not installed\")\n    def test_memory_loads_exc(self):\n        \"\"\"\n        loads() memory leak exception without a GC pause\n        \"\"\"\n        proc = psutil.Process()\n        gc.disable()\n        mem = proc.memory_info().rss\n        n = 10000\n        i = 0\n        for _ in range(n):\n            try:\n                orjson.loads(\"\")\n            except orjson.JSONDecodeError:\n                i += 1\n        assert n == i\n        assert proc.memory_info().rss <= mem + MAX_INCREASE\n        gc.enable()\n\n    @pytest.mark.skipif(psutil is None, reason=\"psutil not installed\")\n    def test_memory_dumps_exc(self):\n        \"\"\"\n        dumps() memory leak exception without a GC pause\n        \"\"\"\n        proc = psutil.Process()\n        gc.disable()\n        data = Unsupported()\n        mem = proc.memory_info().rss\n        n = 10000\n        i = 0\n        for _ in range(n):\n            try:\n                orjson.dumps(data)\n            except orjson.JSONEncodeError:\n                i += 1\n        assert n == i\n        assert proc.memory_info().rss <= mem + MAX_INCREASE\n        gc.enable()\n\n    @pytest.mark.skipif(psutil is None, reason=\"psutil not installed\")\n    def test_memory_dumps_default(self):\n        \"\"\"\n        dumps() default memory leak\n        \"\"\"\n        proc = psutil.Process()\n        gc.collect()\n        fixture = orjson.loads(FIXTURE)\n\n        class Custom:\n            def __init__(self, name):\n                self.name = name\n\n            def __str__(self):\n                return f\"{self.__class__.__name__}({self.name})\"\n\n        fixture[\"custom\"] = Custom(\"orjson\")\n        val = orjson.dumps(fixture, default=default)\n        mem = proc.memory_info().rss\n        for _ in range(10000):\n            val = orjson.dumps(fixture, default=default)\n            assert val\n        gc.collect()\n        assert proc.memory_info().rss <= mem + MAX_INCREASE\n\n    @pytest.mark.skipif(psutil is None, reason=\"psutil not installed\")\n    def test_memory_dumps_dataclass(self):\n        \"\"\"\n        dumps() dataclass memory leak\n        \"\"\"\n        proc = psutil.Process()\n        gc.collect()\n        val = orjson.dumps(DATACLASS_FIXTURE)\n        assert val\n        mem = proc.memory_info().rss\n        for _ in range(100):\n            val = orjson.dumps(DATACLASS_FIXTURE)\n            assert val\n        assert val\n        gc.collect()\n        assert proc.memory_info().rss <= mem + MAX_INCREASE\n\n    @pytest.mark.skipif(\n        psutil is None or pytz is None,\n        reason=\"psutil not installed\",\n    )\n    def test_memory_dumps_pytz_tzinfo(self):\n        \"\"\"\n        dumps() pytz tzinfo memory leak\n        \"\"\"\n        proc = psutil.Process()\n        gc.collect()\n        dt = datetime.datetime.now()\n        val = orjson.dumps(pytz.UTC.localize(dt))\n        assert val\n        mem = proc.memory_info().rss\n        for _ in range(50000):\n            val = orjson.dumps(pytz.UTC.localize(dt))\n            assert val\n        assert val\n        gc.collect()\n        assert proc.memory_info().rss <= mem + MAX_INCREASE\n\n    @pytest.mark.skipif(psutil is None, reason=\"psutil not installed\")\n    def test_memory_loads_keys(self):\n        \"\"\"\n        loads() memory leak with number of keys causing cache eviction\n        \"\"\"\n        proc = psutil.Process()\n        gc.collect()\n        fixture = {f\"key_{idx}\": \"value\" for idx in range(1024)}\n        assert len(fixture) == 1024\n        val = orjson.dumps(fixture)\n        loaded = orjson.loads(val)\n        assert loaded\n        mem = proc.memory_info().rss\n        for _ in range(100):\n            loaded = orjson.loads(val)\n            assert loaded\n        gc.collect()\n        assert proc.memory_info().rss <= mem + MAX_INCREASE\n\n    @pytest.mark.skipif(psutil is None, reason=\"psutil not installed\")\n    @pytest.mark.skipif(numpy is None, reason=\"numpy is not installed\")\n    def test_memory_dumps_numpy(self):\n        \"\"\"\n        dumps() numpy memory leak\n        \"\"\"\n        proc = psutil.Process()\n        gc.collect()\n        fixture = numpy.random.rand(4, 4, 4)  # type: ignore\n        val = orjson.dumps(fixture, option=orjson.OPT_SERIALIZE_NUMPY)\n        assert val\n        mem = proc.memory_info().rss\n        for _ in range(100):\n            val = orjson.dumps(fixture, option=orjson.OPT_SERIALIZE_NUMPY)\n            assert val\n        assert val\n        gc.collect()\n        assert proc.memory_info().rss <= mem + MAX_INCREASE\n\n    @pytest.mark.skipif(psutil is None, reason=\"psutil not installed\")\n    @pytest.mark.skipif(pandas is None, reason=\"pandas is not installed\")\n    def test_memory_dumps_pandas(self):\n        \"\"\"\n        dumps() pandas memory leak\n        \"\"\"\n        proc = psutil.Process()\n        gc.collect()\n        numpy.random.rand(4, 4, 4)  # type: ignore\n        df = pandas.Series(numpy.random.rand(4, 4, 4).tolist())  # type: ignore\n        val = df.map(orjson.dumps)\n        assert not val.empty\n        mem = proc.memory_info().rss\n        for _ in range(100):\n            val = df.map(orjson.dumps)\n            assert not val.empty\n        gc.collect()\n        assert proc.memory_info().rss <= mem + MAX_INCREASE\n\n    @pytest.mark.skipif(psutil is None, reason=\"psutil not installed\")\n    def test_memory_dumps_fragment(self):\n        \"\"\"\n        dumps() Fragment memory leak\n        \"\"\"\n        proc = psutil.Process()\n        gc.collect()\n        orjson.dumps(orjson.Fragment(str(0)))\n        mem = proc.memory_info().rss\n        for i in range(10000):\n            orjson.dumps(orjson.Fragment(str(i)))\n        gc.collect()\n        assert proc.memory_info().rss <= mem + MAX_INCREASE\n"
  },
  {
    "path": "test/test_non_str_keys.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2020-2025)\n\nimport dataclasses\nimport datetime\nimport uuid\n\nimport pytest\n\nimport orjson\n\ntry:\n    import pytz\nexcept ImportError:\n    pytz = None  # type: ignore\n\nfrom .util import numpy\n\n\nclass SubStr(str):\n    pass\n\n\nclass TestNonStrKeyTests:\n    def test_dict_keys_duplicate(self):\n        \"\"\"\n        OPT_NON_STR_KEYS serializes duplicate keys\n        \"\"\"\n        assert (\n            orjson.dumps({\"1\": True, 1: False}, option=orjson.OPT_NON_STR_KEYS)\n            == b'{\"1\":true,\"1\":false}'\n        )\n\n    def test_dict_keys_int(self):\n        assert (\n            orjson.dumps({1: True, 2: False}, option=orjson.OPT_NON_STR_KEYS)\n            == b'{\"1\":true,\"2\":false}'\n        )\n\n    def test_dict_keys_substr(self):\n        assert (\n            orjson.dumps({SubStr(\"aaa\"): True}, option=orjson.OPT_NON_STR_KEYS)\n            == b'{\"aaa\":true}'\n        )\n\n    def test_dict_keys_substr_passthrough(self):\n        \"\"\"\n        OPT_PASSTHROUGH_SUBCLASS does not affect OPT_NON_STR_KEYS\n        \"\"\"\n        assert (\n            orjson.dumps(\n                {SubStr(\"aaa\"): True},\n                option=orjson.OPT_NON_STR_KEYS | orjson.OPT_PASSTHROUGH_SUBCLASS,\n            )\n            == b'{\"aaa\":true}'\n        )\n\n    def test_dict_keys_substr_invalid(self):\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps({SubStr(\"\\ud800\"): True}, option=orjson.OPT_NON_STR_KEYS)\n\n    def test_dict_keys_strict(self):\n        \"\"\"\n        OPT_NON_STR_KEYS does not respect OPT_STRICT_INTEGER\n        \"\"\"\n        assert (\n            orjson.dumps(\n                {9223372036854775807: True},\n                option=orjson.OPT_NON_STR_KEYS | orjson.OPT_STRICT_INTEGER,\n            )\n            == b'{\"9223372036854775807\":true}'\n        )\n\n    def test_dict_keys_int_range_valid_i64(self):\n        \"\"\"\n        OPT_NON_STR_KEYS has a i64 range for int, valid\n        \"\"\"\n        assert (\n            orjson.dumps(\n                {9223372036854775807: True},\n                option=orjson.OPT_NON_STR_KEYS | orjson.OPT_STRICT_INTEGER,\n            )\n            == b'{\"9223372036854775807\":true}'\n        )\n        assert (\n            orjson.dumps(\n                {-9223372036854775807: True},\n                option=orjson.OPT_NON_STR_KEYS | orjson.OPT_STRICT_INTEGER,\n            )\n            == b'{\"-9223372036854775807\":true}'\n        )\n        assert (\n            orjson.dumps(\n                {9223372036854775809: True},\n                option=orjson.OPT_NON_STR_KEYS | orjson.OPT_STRICT_INTEGER,\n            )\n            == b'{\"9223372036854775809\":true}'\n        )\n\n    def test_dict_keys_int_range_valid_u64(self):\n        \"\"\"\n        OPT_NON_STR_KEYS has a u64 range for int, valid\n        \"\"\"\n        assert (\n            orjson.dumps(\n                {0: True},\n                option=orjson.OPT_NON_STR_KEYS | orjson.OPT_STRICT_INTEGER,\n            )\n            == b'{\"0\":true}'\n        )\n        assert (\n            orjson.dumps(\n                {18446744073709551615: True},\n                option=orjson.OPT_NON_STR_KEYS | orjson.OPT_STRICT_INTEGER,\n            )\n            == b'{\"18446744073709551615\":true}'\n        )\n\n    def test_dict_keys_int_range_invalid(self):\n        \"\"\"\n        OPT_NON_STR_KEYS has a range of i64::MIN to u64::MAX\n        \"\"\"\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps({-9223372036854775809: True}, option=orjson.OPT_NON_STR_KEYS)\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps({18446744073709551616: True}, option=orjson.OPT_NON_STR_KEYS)\n\n    def test_dict_keys_float(self):\n        assert (\n            orjson.dumps({1.1: True, 2.2: False}, option=orjson.OPT_NON_STR_KEYS)\n            == b'{\"1.1\":true,\"2.2\":false}'\n        )\n\n    def test_dict_keys_inf(self):\n        assert (\n            orjson.dumps({float(\"Infinity\"): True}, option=orjson.OPT_NON_STR_KEYS)\n            == b'{\"null\":true}'\n        )\n        assert (\n            orjson.dumps({float(\"-Infinity\"): True}, option=orjson.OPT_NON_STR_KEYS)\n            == b'{\"null\":true}'\n        )\n\n    def test_dict_keys_nan(self):\n        assert (\n            orjson.dumps({float(\"NaN\"): True}, option=orjson.OPT_NON_STR_KEYS)\n            == b'{\"null\":true}'\n        )\n\n    def test_dict_keys_bool(self):\n        assert (\n            orjson.dumps({True: True, False: False}, option=orjson.OPT_NON_STR_KEYS)\n            == b'{\"true\":true,\"false\":false}'\n        )\n\n    def test_dict_keys_datetime(self):\n        assert (\n            orjson.dumps(\n                {datetime.datetime(2000, 1, 1, 2, 3, 4, 123): True},\n                option=orjson.OPT_NON_STR_KEYS,\n            )\n            == b'{\"2000-01-01T02:03:04.000123\":true}'\n        )\n\n    def test_dict_keys_datetime_opt(self):\n        assert (\n            orjson.dumps(\n                {datetime.datetime(2000, 1, 1, 2, 3, 4, 123): True},\n                option=orjson.OPT_NON_STR_KEYS\n                | orjson.OPT_OMIT_MICROSECONDS\n                | orjson.OPT_NAIVE_UTC\n                | orjson.OPT_UTC_Z,\n            )\n            == b'{\"2000-01-01T02:03:04Z\":true}'\n        )\n\n    def test_dict_keys_datetime_passthrough(self):\n        \"\"\"\n        OPT_PASSTHROUGH_DATETIME does not affect OPT_NON_STR_KEYS\n        \"\"\"\n        assert (\n            orjson.dumps(\n                {datetime.datetime(2000, 1, 1, 2, 3, 4, 123): True},\n                option=orjson.OPT_NON_STR_KEYS | orjson.OPT_PASSTHROUGH_DATETIME,\n            )\n            == b'{\"2000-01-01T02:03:04.000123\":true}'\n        )\n\n    def test_dict_keys_uuid(self):\n        \"\"\"\n        OPT_NON_STR_KEYS always serializes UUID as keys\n        \"\"\"\n        assert (\n            orjson.dumps(\n                {uuid.UUID(\"7202d115-7ff3-4c81-a7c1-2a1f067b1ece\"): True},\n                option=orjson.OPT_NON_STR_KEYS,\n            )\n            == b'{\"7202d115-7ff3-4c81-a7c1-2a1f067b1ece\":true}'\n        )\n\n    def test_dict_keys_date(self):\n        assert (\n            orjson.dumps(\n                {datetime.date(1970, 1, 1): True},\n                option=orjson.OPT_NON_STR_KEYS,\n            )\n            == b'{\"1970-01-01\":true}'\n        )\n\n    def test_dict_keys_time(self):\n        assert (\n            orjson.dumps(\n                {datetime.time(12, 15, 59, 111): True},\n                option=orjson.OPT_NON_STR_KEYS,\n            )\n            == b'{\"12:15:59.000111\":true}'\n        )\n\n    def test_dict_non_str_and_sort_keys(self):\n        assert (\n            orjson.dumps(\n                {\n                    \"other\": 1,\n                    datetime.date(1970, 1, 5): 2,\n                    datetime.date(1970, 1, 3): 3,\n                },\n                option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SORT_KEYS,\n            )\n            == b'{\"1970-01-03\":3,\"1970-01-05\":2,\"other\":1}'\n        )\n\n    @pytest.mark.skipif(pytz is None, reason=\"pytz optional\")\n    def test_dict_keys_time_err(self):\n        \"\"\"\n        OPT_NON_STR_KEYS propagates errors in types\n        \"\"\"\n        val = datetime.time(12, 15, 59, 111, tzinfo=pytz.timezone(\"Asia/Shanghai\"))\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps({val: True}, option=orjson.OPT_NON_STR_KEYS)\n\n    def test_dict_keys_str(self):\n        assert (\n            orjson.dumps({\"1\": True}, option=orjson.OPT_NON_STR_KEYS) == b'{\"1\":true}'\n        )\n\n    def test_dict_keys_type(self):\n        class Obj:\n            a: str\n\n        val = Obj()\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps({val: True}, option=orjson.OPT_NON_STR_KEYS)\n\n    @pytest.mark.skipif(numpy is None, reason=\"numpy is not installed\")\n    def test_dict_keys_array(self):\n        with pytest.raises(TypeError):\n            _ = {numpy.array([1, 2]): True}  # type: ignore\n\n    def test_dict_keys_dataclass(self):\n        @dataclasses.dataclass\n        class Dataclass:\n            a: str\n\n        with pytest.raises(TypeError):\n            _ = {Dataclass(\"a\"): True}\n\n    def test_dict_keys_dataclass_hash(self):\n        @dataclasses.dataclass\n        class Dataclass:\n            a: str\n\n            def __hash__(self):\n                return 1\n\n        obj = {Dataclass(\"a\"): True}\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(obj, option=orjson.OPT_NON_STR_KEYS)\n\n    def test_dict_keys_list(self):\n        with pytest.raises(TypeError):\n            _ = {[]: True}\n\n    def test_dict_keys_dict(self):\n        with pytest.raises(TypeError):\n            _ = {{}: True}\n\n    def test_dict_keys_tuple(self):\n        obj = {(): True}\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(obj, option=orjson.OPT_NON_STR_KEYS)\n\n    def test_dict_keys_unknown(self):\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps({frozenset(): True}, option=orjson.OPT_NON_STR_KEYS)\n\n    def test_dict_keys_no_str_call(self):\n        class Obj:\n            a: str\n\n            def __str__(self):\n                return \"Obj\"\n\n        val = Obj()\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps({val: True}, option=orjson.OPT_NON_STR_KEYS)\n"
  },
  {
    "path": "test/test_numpy.py",
    "content": "# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2020-2026), Ben Sully (2021), Nazar Kostetskyi (2022), Aviram Hassan (2020-2021), Marco Ribeiro (2020), Eric Jolibois (2021)\n# mypy: ignore-errors\n\nimport sys\n\nimport pytest\n\nimport orjson\n\nfrom .util import numpy\n\n\ndef numpy_default(obj):\n    if isinstance(obj, numpy.ndarray):\n        return obj.tolist()\n    raise TypeError\n\n\n@pytest.mark.skipif(numpy is None, reason=\"numpy is not installed\")\nclass TestNumpy:\n    def test_numpy_array_d1_uintp(self):\n        low = numpy.iinfo(numpy.uintp).min\n        high = numpy.iinfo(numpy.uintp).max\n        assert orjson.dumps(\n            numpy.array([low, high], numpy.uintp),\n            option=orjson.OPT_SERIALIZE_NUMPY,\n        ) == f\"[{low},{high}]\".encode(\"ascii\")\n\n    def test_numpy_array_d1_intp(self):\n        low = numpy.iinfo(numpy.intp).min\n        high = numpy.iinfo(numpy.intp).max\n        assert orjson.dumps(\n            numpy.array([low, high], numpy.intp),\n            option=orjson.OPT_SERIALIZE_NUMPY,\n        ) == f\"[{low},{high}]\".encode(\"ascii\")\n\n    def test_numpy_array_d1_i64(self):\n        assert (\n            orjson.dumps(\n                numpy.array([-9223372036854775807, 9223372036854775807], numpy.int64),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[-9223372036854775807,9223372036854775807]\"\n        )\n\n    def test_numpy_array_d1_u64(self):\n        assert (\n            orjson.dumps(\n                numpy.array([0, 18446744073709551615], numpy.uint64),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[0,18446744073709551615]\"\n        )\n\n    def test_numpy_array_d1_i8(self):\n        assert (\n            orjson.dumps(\n                numpy.array([-128, 127], numpy.int8),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[-128,127]\"\n        )\n\n    def test_numpy_array_d1_u8(self):\n        assert (\n            orjson.dumps(\n                numpy.array([0, 255], numpy.uint8),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[0,255]\"\n        )\n\n    def test_numpy_array_d1_i32(self):\n        assert (\n            orjson.dumps(\n                numpy.array([-2147483647, 2147483647], numpy.int32),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[-2147483647,2147483647]\"\n        )\n\n    def test_numpy_array_d1_i16(self):\n        assert (\n            orjson.dumps(\n                numpy.array([-32768, 32767], numpy.int16),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[-32768,32767]\"\n        )\n\n    def test_numpy_array_d1_u16(self):\n        assert (\n            orjson.dumps(\n                numpy.array([0, 65535], numpy.uint16),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[0,65535]\"\n        )\n\n    def test_numpy_array_d1_u32(self):\n        assert (\n            orjson.dumps(\n                numpy.array([0, 4294967295], numpy.uint32),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[0,4294967295]\"\n        )\n\n    def test_numpy_array_d1_f32(self):\n        assert (\n            orjson.dumps(\n                numpy.array([1.0, 3.4028235e38], numpy.float32),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[1.0,3.4028235e+38]\"\n        )\n\n    def test_numpy_array_d1_f16(self):\n        assert (\n            orjson.dumps(\n                numpy.array([-1.0, 0.0009765625, 1.0, 65504.0], numpy.float16),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[-1.0,0.0009765625,1.0,65504.0]\"\n        )\n\n    def test_numpy_array_f16_roundtrip(self):\n        ref = [\n            -1.0,\n            -2.0,\n            0.000000059604645,\n            0.000060975552,\n            0.00006103515625,\n            0.0009765625,\n            0.33325195,\n            0.99951172,\n            1.0,\n            1.00097656,\n            65504.0,\n        ]\n        obj = numpy.array(ref, numpy.float16)  # type: ignore\n        serialized = orjson.dumps(\n            obj,\n            option=orjson.OPT_SERIALIZE_NUMPY,\n        )\n        deserialized = numpy.array(orjson.loads(serialized), numpy.float16)  # type: ignore\n        assert numpy.array_equal(obj, deserialized)\n\n    def test_numpy_array_f16_edge(self):\n        assert (\n            orjson.dumps(\n                numpy.array(\n                    [\n                        numpy.inf,\n                        -numpy.inf,\n                        numpy.nan,\n                        -0.0,\n                        0.0,\n                        numpy.pi,\n                    ],\n                    numpy.float16,\n                ),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[null,null,null,-0.0,0.0,3.140625]\"\n        )\n\n    def test_numpy_array_f32_edge(self):\n        assert (\n            orjson.dumps(\n                numpy.array(\n                    [\n                        numpy.inf,\n                        -numpy.inf,\n                        numpy.nan,\n                        -0.0,\n                        0.0,\n                        numpy.pi,\n                    ],\n                    numpy.float32,\n                ),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[null,null,null,-0.0,0.0,3.1415927]\"\n        )\n\n    def test_numpy_array_f64_edge(self):\n        assert (\n            orjson.dumps(\n                numpy.array(\n                    [\n                        numpy.inf,\n                        -numpy.inf,\n                        numpy.nan,\n                        -0.0,\n                        0.0,\n                        numpy.pi,\n                    ],\n                    numpy.float64,\n                ),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[null,null,null,-0.0,0.0,3.141592653589793]\"\n        )\n\n    def test_numpy_array_d1_f64(self):\n        assert (\n            orjson.dumps(\n                numpy.array([1.0, 1.7976931348623157e308], numpy.float64),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[1.0,1.7976931348623157e+308]\"\n        )\n\n    def test_numpy_array_d1_bool(self):\n        assert (\n            orjson.dumps(\n                numpy.array([True, False, False, True]),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[true,false,false,true]\"\n        )\n\n    def test_numpy_array_d1_datetime64_years(self):\n        assert (\n            orjson.dumps(\n                numpy.array(\n                    [\n                        numpy.datetime64(\"1\"),\n                        numpy.datetime64(\"970\"),\n                        numpy.datetime64(\"1920\"),\n                        numpy.datetime64(\"1971\"),\n                        numpy.datetime64(\"2021\"),\n                        numpy.datetime64(\"2022\"),\n                        numpy.datetime64(\"2023\"),\n                        numpy.datetime64(\"9999\"),\n                    ],\n                ),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b'[\"0001-01-01T00:00:00\",\"0970-01-01T00:00:00\",\"1920-01-01T00:00:00\",\"1971-01-01T00:00:00\",\"2021-01-01T00:00:00\",\"2022-01-01T00:00:00\",\"2023-01-01T00:00:00\",\"9999-01-01T00:00:00\"]'\n        )\n\n    def test_numpy_array_d1_datetime64_months(self):\n        assert (\n            orjson.dumps(\n                numpy.array(\n                    [\n                        numpy.datetime64(\"2021-01\"),\n                        numpy.datetime64(\"2022-01\"),\n                        numpy.datetime64(\"2023-01\"),\n                    ],\n                ),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b'[\"2021-01-01T00:00:00\",\"2022-01-01T00:00:00\",\"2023-01-01T00:00:00\"]'\n        )\n\n    def test_numpy_array_d1_datetime64_days(self):\n        assert (\n            orjson.dumps(\n                numpy.array(\n                    [\n                        numpy.datetime64(\"2021-01-01\"),\n                        numpy.datetime64(\"2021-01-01\"),\n                        numpy.datetime64(\"2021-01-01\"),\n                    ],\n                ),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b'[\"2021-01-01T00:00:00\",\"2021-01-01T00:00:00\",\"2021-01-01T00:00:00\"]'\n        )\n\n    def test_numpy_array_d1_datetime64_hours(self):\n        assert (\n            orjson.dumps(\n                numpy.array(\n                    [\n                        numpy.datetime64(\"2021-01-01T00\"),\n                        numpy.datetime64(\"2021-01-01T01\"),\n                        numpy.datetime64(\"2021-01-01T02\"),\n                    ],\n                ),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b'[\"2021-01-01T00:00:00\",\"2021-01-01T01:00:00\",\"2021-01-01T02:00:00\"]'\n        )\n\n    def test_numpy_array_d1_datetime64_minutes(self):\n        assert (\n            orjson.dumps(\n                numpy.array(\n                    [\n                        numpy.datetime64(\"2021-01-01T00:00\"),\n                        numpy.datetime64(\"2021-01-01T00:01\"),\n                        numpy.datetime64(\"2021-01-01T00:02\"),\n                    ],\n                ),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b'[\"2021-01-01T00:00:00\",\"2021-01-01T00:01:00\",\"2021-01-01T00:02:00\"]'\n        )\n\n    def test_numpy_array_d1_datetime64_seconds(self):\n        assert (\n            orjson.dumps(\n                numpy.array(\n                    [\n                        numpy.datetime64(\"2021-01-01T00:00:00\"),\n                        numpy.datetime64(\"2021-01-01T00:00:01\"),\n                        numpy.datetime64(\"2021-01-01T00:00:02\"),\n                    ],\n                ),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b'[\"2021-01-01T00:00:00\",\"2021-01-01T00:00:01\",\"2021-01-01T00:00:02\"]'\n        )\n\n    def test_numpy_array_d1_datetime64_milliseconds(self):\n        assert (\n            orjson.dumps(\n                numpy.array(\n                    [\n                        numpy.datetime64(\"2021-01-01T00:00:00\"),\n                        numpy.datetime64(\"2021-01-01T00:00:00.172\"),\n                        numpy.datetime64(\"2021-01-01T00:00:00.567\"),\n                    ],\n                ),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b'[\"2021-01-01T00:00:00\",\"2021-01-01T00:00:00.172000\",\"2021-01-01T00:00:00.567000\"]'\n        )\n\n    def test_numpy_array_d1_datetime64_microseconds(self):\n        assert (\n            orjson.dumps(\n                numpy.array(\n                    [\n                        numpy.datetime64(\"2021-01-01T00:00:00\"),\n                        numpy.datetime64(\"2021-01-01T00:00:00.172\"),\n                        numpy.datetime64(\"2021-01-01T00:00:00.567891\"),\n                    ],\n                ),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b'[\"2021-01-01T00:00:00\",\"2021-01-01T00:00:00.172000\",\"2021-01-01T00:00:00.567891\"]'\n        )\n\n    def test_numpy_array_d1_datetime64_nanoseconds(self):\n        assert (\n            orjson.dumps(\n                numpy.array(\n                    [\n                        numpy.datetime64(\"2021-01-01T00:00:00\"),\n                        numpy.datetime64(\"2021-01-01T00:00:00.172\"),\n                        numpy.datetime64(\"2021-01-01T00:00:00.567891234\"),\n                    ],\n                ),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b'[\"2021-01-01T00:00:00\",\"2021-01-01T00:00:00.172000\",\"2021-01-01T00:00:00.567891\"]'\n        )\n\n    def test_numpy_array_d1_datetime64_picoseconds(self):\n        try:\n            orjson.dumps(\n                numpy.array(\n                    [\n                        numpy.datetime64(\"2021-01-01T00:00:00\"),\n                        numpy.datetime64(\"2021-01-01T00:00:00.172\"),\n                        numpy.datetime64(\"2021-01-01T00:00:00.567891234567\"),\n                    ],\n                ),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            raise AssertionError()\n        except TypeError as exc:\n            assert str(exc) == \"unsupported numpy.datetime64 unit: picoseconds\"\n\n    def test_numpy_array_d2_i64(self):\n        assert (\n            orjson.dumps(\n                numpy.array([[1, 2, 3], [4, 5, 6]], numpy.int64),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[[1,2,3],[4,5,6]]\"\n        )\n\n    def test_numpy_array_d2_f64(self):\n        assert (\n            orjson.dumps(\n                numpy.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], numpy.float64),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[[1.0,2.0,3.0],[4.0,5.0,6.0]]\"\n        )\n\n    def test_numpy_array_d3_i8(self):\n        assert (\n            orjson.dumps(\n                numpy.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], numpy.int8),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[[[1,2],[3,4]],[[5,6],[7,8]]]\"\n        )\n\n    def test_numpy_array_d3_u8(self):\n        assert (\n            orjson.dumps(\n                numpy.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], numpy.uint8),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[[[1,2],[3,4]],[[5,6],[7,8]]]\"\n        )\n\n    def test_numpy_array_d3_i32(self):\n        assert (\n            orjson.dumps(\n                numpy.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], numpy.int32),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[[[1,2],[3,4]],[[5,6],[7,8]]]\"\n        )\n\n    def test_numpy_array_d3_i64(self):\n        assert (\n            orjson.dumps(\n                numpy.array([[[1, 2], [3, 4], [5, 6], [7, 8]]], numpy.int64),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[[[1,2],[3,4],[5,6],[7,8]]]\"\n        )\n\n    def test_numpy_array_d3_f64(self):\n        assert (\n            orjson.dumps(\n                numpy.array(\n                    [[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]]],\n                    numpy.float64,\n                ),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"[[[1.0,2.0],[3.0,4.0]],[[5.0,6.0],[7.0,8.0]]]\"\n        )\n\n    def test_numpy_array_fortran(self):\n        array = numpy.array([[1, 2], [3, 4]], order=\"F\")\n        assert array.flags[\"F_CONTIGUOUS\"] is True\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(array, option=orjson.OPT_SERIALIZE_NUMPY)\n        assert orjson.dumps(\n            array,\n            default=numpy_default,\n            option=orjson.OPT_SERIALIZE_NUMPY,\n        ) == orjson.dumps(array.tolist())\n\n    def test_numpy_array_non_contiguous_message(self):\n        array = numpy.array([[1, 2], [3, 4]], order=\"F\")\n        assert array.flags[\"F_CONTIGUOUS\"] is True\n        try:\n            orjson.dumps(array, option=orjson.OPT_SERIALIZE_NUMPY)\n            raise AssertionError()\n        except TypeError as exc:\n            assert (\n                str(exc)\n                == \"numpy array is not C contiguous; use ndarray.tolist() in default\"\n            )\n\n    def test_numpy_array_unsupported_dtype(self):\n        array = numpy.array([[1, 2], [3, 4]], numpy.csingle)  # type: ignore\n        with pytest.raises(orjson.JSONEncodeError) as cm:\n            orjson.dumps(array, option=orjson.OPT_SERIALIZE_NUMPY)\n        assert \"unsupported datatype in numpy array\" in str(cm)\n\n    def test_numpy_array_d1(self):\n        array = numpy.array([1])\n        assert (\n            orjson.loads(\n                orjson.dumps(\n                    array,\n                    option=orjson.OPT_SERIALIZE_NUMPY,\n                ),\n            )\n            == array.tolist()\n        )\n\n    def test_numpy_array_d2(self):\n        array = numpy.array([[1]])\n        assert (\n            orjson.loads(\n                orjson.dumps(\n                    array,\n                    option=orjson.OPT_SERIALIZE_NUMPY,\n                ),\n            )\n            == array.tolist()\n        )\n\n    def test_numpy_array_d3(self):\n        array = numpy.array([[[1]]])\n        assert (\n            orjson.loads(\n                orjson.dumps(\n                    array,\n                    option=orjson.OPT_SERIALIZE_NUMPY,\n                ),\n            )\n            == array.tolist()\n        )\n\n    def test_numpy_array_d4(self):\n        array = numpy.array([[[[1]]]])\n        assert (\n            orjson.loads(\n                orjson.dumps(\n                    array,\n                    option=orjson.OPT_SERIALIZE_NUMPY,\n                ),\n            )\n            == array.tolist()\n        )\n\n    def test_numpy_array_4_stride(self):\n        array = numpy.random.rand(4, 4, 4, 4)\n        assert (\n            orjson.loads(\n                orjson.dumps(\n                    array,\n                    option=orjson.OPT_SERIALIZE_NUMPY,\n                ),\n            )\n            == array.tolist()\n        )\n\n    def test_numpy_array_dimension_zero(self):\n        array = numpy.array(0)\n        assert array.ndim == 0\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(array, option=orjson.OPT_SERIALIZE_NUMPY)\n\n        array = numpy.empty((0, 4, 2))\n        assert (\n            orjson.loads(\n                orjson.dumps(\n                    array,\n                    option=orjson.OPT_SERIALIZE_NUMPY,\n                ),\n            )\n            == array.tolist()\n        )\n\n        array = numpy.empty((4, 0, 2))\n        assert (\n            orjson.loads(\n                orjson.dumps(\n                    array,\n                    option=orjson.OPT_SERIALIZE_NUMPY,\n                ),\n            )\n            == array.tolist()\n        )\n\n        array = numpy.empty((2, 4, 0))\n        assert (\n            orjson.loads(\n                orjson.dumps(\n                    array,\n                    option=orjson.OPT_SERIALIZE_NUMPY,\n                ),\n            )\n            == array.tolist()\n        )\n\n    def test_numpy_array_dimension_max(self):\n        array = numpy.random.rand(\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n            1,\n        )\n        assert array.ndim == 32\n        assert (\n            orjson.loads(\n                orjson.dumps(\n                    array,\n                    option=orjson.OPT_SERIALIZE_NUMPY,\n                ),\n            )\n            == array.tolist()\n        )\n\n    def test_numpy_scalar_int8(self):\n        assert orjson.dumps(numpy.int8(0), option=orjson.OPT_SERIALIZE_NUMPY) == b\"0\"\n        assert (\n            orjson.dumps(numpy.int8(127), option=orjson.OPT_SERIALIZE_NUMPY) == b\"127\"\n        )\n        assert (\n            orjson.dumps(numpy.int8(-128), option=orjson.OPT_SERIALIZE_NUMPY) == b\"-128\"\n        )\n\n    def test_numpy_scalar_int16(self):\n        assert orjson.dumps(numpy.int16(0), option=orjson.OPT_SERIALIZE_NUMPY) == b\"0\"\n        assert (\n            orjson.dumps(numpy.int16(32767), option=orjson.OPT_SERIALIZE_NUMPY)\n            == b\"32767\"\n        )\n        assert (\n            orjson.dumps(numpy.int16(-32768), option=orjson.OPT_SERIALIZE_NUMPY)\n            == b\"-32768\"\n        )\n\n    def test_numpy_scalar_int32(self):\n        assert orjson.dumps(numpy.int32(1), option=orjson.OPT_SERIALIZE_NUMPY) == b\"1\"\n        assert (\n            orjson.dumps(numpy.int32(2147483647), option=orjson.OPT_SERIALIZE_NUMPY)\n            == b\"2147483647\"\n        )\n        assert (\n            orjson.dumps(numpy.int32(-2147483648), option=orjson.OPT_SERIALIZE_NUMPY)\n            == b\"-2147483648\"\n        )\n\n    def test_numpy_scalar_int64(self):\n        assert (\n            orjson.dumps(\n                numpy.int64(-9223372036854775808),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"-9223372036854775808\"\n        )\n        assert (\n            orjson.dumps(\n                numpy.int64(9223372036854775807),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"9223372036854775807\"\n        )\n\n    def test_numpy_scalar_uint8(self):\n        assert orjson.dumps(numpy.uint8(0), option=orjson.OPT_SERIALIZE_NUMPY) == b\"0\"\n        assert (\n            orjson.dumps(numpy.uint8(255), option=orjson.OPT_SERIALIZE_NUMPY) == b\"255\"\n        )\n\n    def test_numpy_scalar_uint16(self):\n        assert orjson.dumps(numpy.uint16(0), option=orjson.OPT_SERIALIZE_NUMPY) == b\"0\"\n        assert (\n            orjson.dumps(numpy.uint16(65535), option=orjson.OPT_SERIALIZE_NUMPY)\n            == b\"65535\"\n        )\n\n    def test_numpy_scalar_uint32(self):\n        assert orjson.dumps(numpy.uint32(0), option=orjson.OPT_SERIALIZE_NUMPY) == b\"0\"\n        assert (\n            orjson.dumps(numpy.uint32(4294967295), option=orjson.OPT_SERIALIZE_NUMPY)\n            == b\"4294967295\"\n        )\n\n    def test_numpy_scalar_uint64(self):\n        assert orjson.dumps(numpy.uint64(0), option=orjson.OPT_SERIALIZE_NUMPY) == b\"0\"\n        assert (\n            orjson.dumps(\n                numpy.uint64(18446744073709551615),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b\"18446744073709551615\"\n        )\n\n    def test_numpy_scalar_float16(self):\n        assert (\n            orjson.dumps(numpy.float16(1.0), option=orjson.OPT_SERIALIZE_NUMPY)\n            == b\"1.0\"\n        )\n\n    def test_numpy_scalar_float32(self):\n        assert (\n            orjson.dumps(numpy.float32(1.0), option=orjson.OPT_SERIALIZE_NUMPY)\n            == b\"1.0\"\n        )\n\n    def test_numpy_scalar_float64(self):\n        assert (\n            orjson.dumps(numpy.float64(123.123), option=orjson.OPT_SERIALIZE_NUMPY)\n            == b\"123.123\"\n        )\n\n    def test_numpy_bool(self):\n        assert (\n            orjson.dumps(\n                {\"a\": numpy.bool_(True), \"b\": numpy.bool_(False)},\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b'{\"a\":true,\"b\":false}'\n        )\n\n    def test_numpy_datetime_year(self):\n        assert (\n            orjson.dumps(numpy.datetime64(\"2021\"), option=orjson.OPT_SERIALIZE_NUMPY)\n            == b'\"2021-01-01T00:00:00\"'\n        )\n\n    def test_numpy_datetime_month(self):\n        assert (\n            orjson.dumps(numpy.datetime64(\"2021-01\"), option=orjson.OPT_SERIALIZE_NUMPY)\n            == b'\"2021-01-01T00:00:00\"'\n        )\n\n    def test_numpy_datetime_day(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01\"),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b'\"2021-01-01T00:00:00\"'\n        )\n\n    def test_numpy_datetime_hour(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00\"),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b'\"2021-01-01T00:00:00\"'\n        )\n\n    def test_numpy_datetime_minute(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00\"),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b'\"2021-01-01T00:00:00\"'\n        )\n\n    def test_numpy_datetime_second(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00:00\"),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b'\"2021-01-01T00:00:00\"'\n        )\n\n    def test_numpy_datetime_milli(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00:00.172\"),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b'\"2021-01-01T00:00:00.172000\"'\n        )\n\n    def test_numpy_datetime_micro(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00:00.172576\"),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b'\"2021-01-01T00:00:00.172576\"'\n        )\n\n    def test_numpy_datetime_nano(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00:00.172576789\"),\n                option=orjson.OPT_SERIALIZE_NUMPY,\n            )\n            == b'\"2021-01-01T00:00:00.172576\"'\n        )\n\n    def test_numpy_datetime_naive_utc_year(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021\"),\n                option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NAIVE_UTC,\n            )\n            == b'\"2021-01-01T00:00:00+00:00\"'\n        )\n\n    def test_numpy_datetime_naive_utc_month(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01\"),\n                option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NAIVE_UTC,\n            )\n            == b'\"2021-01-01T00:00:00+00:00\"'\n        )\n\n    def test_numpy_datetime_naive_utc_day(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01\"),\n                option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NAIVE_UTC,\n            )\n            == b'\"2021-01-01T00:00:00+00:00\"'\n        )\n\n    def test_numpy_datetime_naive_utc_hour(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00\"),\n                option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NAIVE_UTC,\n            )\n            == b'\"2021-01-01T00:00:00+00:00\"'\n        )\n\n    def test_numpy_datetime_naive_utc_minute(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00\"),\n                option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NAIVE_UTC,\n            )\n            == b'\"2021-01-01T00:00:00+00:00\"'\n        )\n\n    def test_numpy_datetime_naive_utc_second(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00:00\"),\n                option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NAIVE_UTC,\n            )\n            == b'\"2021-01-01T00:00:00+00:00\"'\n        )\n\n    def test_numpy_datetime_naive_utc_milli(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00:00.172\"),\n                option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NAIVE_UTC,\n            )\n            == b'\"2021-01-01T00:00:00.172000+00:00\"'\n        )\n\n    def test_numpy_datetime_naive_utc_micro(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00:00.172576\"),\n                option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NAIVE_UTC,\n            )\n            == b'\"2021-01-01T00:00:00.172576+00:00\"'\n        )\n\n    def test_numpy_datetime_naive_utc_nano(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00:00.172576789\"),\n                option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NAIVE_UTC,\n            )\n            == b'\"2021-01-01T00:00:00.172576+00:00\"'\n        )\n\n    def test_numpy_datetime_naive_utc_utc_z_year(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021\"),\n                option=orjson.OPT_SERIALIZE_NUMPY\n                | orjson.OPT_NAIVE_UTC\n                | orjson.OPT_UTC_Z,\n            )\n            == b'\"2021-01-01T00:00:00Z\"'\n        )\n\n    def test_numpy_datetime_naive_utc_utc_z_month(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01\"),\n                option=orjson.OPT_SERIALIZE_NUMPY\n                | orjson.OPT_NAIVE_UTC\n                | orjson.OPT_UTC_Z,\n            )\n            == b'\"2021-01-01T00:00:00Z\"'\n        )\n\n    def test_numpy_datetime_naive_utc_utc_z_day(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01\"),\n                option=orjson.OPT_SERIALIZE_NUMPY\n                | orjson.OPT_NAIVE_UTC\n                | orjson.OPT_UTC_Z,\n            )\n            == b'\"2021-01-01T00:00:00Z\"'\n        )\n\n    def test_numpy_datetime_naive_utc_utc_z_hour(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00\"),\n                option=orjson.OPT_SERIALIZE_NUMPY\n                | orjson.OPT_NAIVE_UTC\n                | orjson.OPT_UTC_Z,\n            )\n            == b'\"2021-01-01T00:00:00Z\"'\n        )\n\n    def test_numpy_datetime_naive_utc_utc_z_minute(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00\"),\n                option=orjson.OPT_SERIALIZE_NUMPY\n                | orjson.OPT_NAIVE_UTC\n                | orjson.OPT_UTC_Z,\n            )\n            == b'\"2021-01-01T00:00:00Z\"'\n        )\n\n    def test_numpy_datetime_naive_utc_utc_z_second(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00:00\"),\n                option=orjson.OPT_SERIALIZE_NUMPY\n                | orjson.OPT_NAIVE_UTC\n                | orjson.OPT_UTC_Z,\n            )\n            == b'\"2021-01-01T00:00:00Z\"'\n        )\n\n    def test_numpy_datetime_naive_utc_utc_z_milli(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00:00.172\"),\n                option=orjson.OPT_SERIALIZE_NUMPY\n                | orjson.OPT_NAIVE_UTC\n                | orjson.OPT_UTC_Z,\n            )\n            == b'\"2021-01-01T00:00:00.172000Z\"'\n        )\n\n    def test_numpy_datetime_naive_utc_utc_z_micro(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00:00.172576\"),\n                option=orjson.OPT_SERIALIZE_NUMPY\n                | orjson.OPT_NAIVE_UTC\n                | orjson.OPT_UTC_Z,\n            )\n            == b'\"2021-01-01T00:00:00.172576Z\"'\n        )\n\n    def test_numpy_datetime_naive_utc_utc_z_nano(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00:00.172576789\"),\n                option=orjson.OPT_SERIALIZE_NUMPY\n                | orjson.OPT_NAIVE_UTC\n                | orjson.OPT_UTC_Z,\n            )\n            == b'\"2021-01-01T00:00:00.172576Z\"'\n        )\n\n    def test_numpy_datetime_omit_microseconds_year(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021\"),\n                option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_OMIT_MICROSECONDS,\n            )\n            == b'\"2021-01-01T00:00:00\"'\n        )\n\n    def test_numpy_datetime_omit_microseconds_month(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01\"),\n                option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_OMIT_MICROSECONDS,\n            )\n            == b'\"2021-01-01T00:00:00\"'\n        )\n\n    def test_numpy_datetime_omit_microseconds_day(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01\"),\n                option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_OMIT_MICROSECONDS,\n            )\n            == b'\"2021-01-01T00:00:00\"'\n        )\n\n    def test_numpy_datetime_omit_microseconds_hour(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00\"),\n                option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_OMIT_MICROSECONDS,\n            )\n            == b'\"2021-01-01T00:00:00\"'\n        )\n\n    def test_numpy_datetime_omit_microseconds_minute(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00\"),\n                option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_OMIT_MICROSECONDS,\n            )\n            == b'\"2021-01-01T00:00:00\"'\n        )\n\n    def test_numpy_datetime_omit_microseconds_second(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00:00\"),\n                option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_OMIT_MICROSECONDS,\n            )\n            == b'\"2021-01-01T00:00:00\"'\n        )\n\n    def test_numpy_datetime_omit_microseconds_milli(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00:00.172\"),\n                option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_OMIT_MICROSECONDS,\n            )\n            == b'\"2021-01-01T00:00:00\"'\n        )\n\n    def test_numpy_datetime_omit_microseconds_micro(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00:00.172576\"),\n                option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_OMIT_MICROSECONDS,\n            )\n            == b'\"2021-01-01T00:00:00\"'\n        )\n\n    def test_numpy_datetime_omit_microseconds_nano(self):\n        assert (\n            orjson.dumps(\n                numpy.datetime64(\"2021-01-01T00:00:00.172576789\"),\n                option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_OMIT_MICROSECONDS,\n            )\n            == b'\"2021-01-01T00:00:00\"'\n        )\n\n    def test_numpy_datetime_nat(self):\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(numpy.datetime64(\"NaT\"), option=orjson.OPT_SERIALIZE_NUMPY)\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps([numpy.datetime64(\"NaT\")], option=orjson.OPT_SERIALIZE_NUMPY)\n\n    def test_numpy_repeated(self):\n        data = numpy.array([[[1, 2], [3, 4], [5, 6], [7, 8]]], numpy.int64)  # type: ignore\n        for _ in range(3):\n            assert (\n                orjson.dumps(\n                    data,\n                    option=orjson.OPT_SERIALIZE_NUMPY,\n                )\n                == b\"[[[1,2],[3,4],[5,6],[7,8]]]\"\n            )\n\n\n@pytest.mark.skipif(numpy is None, reason=\"numpy is not installed\")\nclass TestNumpyEquivalence:\n    def _test(self, obj):\n        assert orjson.dumps(obj, option=orjson.OPT_SERIALIZE_NUMPY) == orjson.dumps(\n            obj.tolist(),\n        )\n\n    def test_numpy_uint8(self):\n        self._test(numpy.array([0, 255], numpy.uint8))\n\n    def test_numpy_uint16(self):\n        self._test(numpy.array([0, 65535], numpy.uint16))\n\n    def test_numpy_uint32(self):\n        self._test(numpy.array([0, 4294967295], numpy.uint32))\n\n    def test_numpy_uint64(self):\n        self._test(numpy.array([0, 18446744073709551615], numpy.uint64))\n\n    def test_numpy_int8(self):\n        self._test(numpy.array([-128, 127], numpy.int8))\n\n    def test_numpy_int16(self):\n        self._test(numpy.array([-32768, 32767], numpy.int16))\n\n    def test_numpy_int32(self):\n        self._test(numpy.array([-2147483647, 2147483647], numpy.int32))\n\n    def test_numpy_int64(self):\n        self._test(\n            numpy.array([-9223372036854775807, 9223372036854775807], numpy.int64),\n        )\n\n    @pytest.mark.skip(reason=\"tolist() conversion results in 3.4028234663852886e38\")\n    def test_numpy_float32(self):\n        self._test(\n            numpy.array(\n                [\n                    -340282346638528859811704183484516925440.0000000000000000,\n                    340282346638528859811704183484516925440.0000000000000000,\n                ],\n                numpy.float32,\n            ),\n        )\n        self._test(numpy.array([-3.4028235e38, 3.4028235e38], numpy.float32))\n\n    def test_numpy_float64(self):\n        self._test(\n            numpy.array(\n                [-1.7976931348623157e308, 1.7976931348623157e308],\n                numpy.float64,\n            ),\n        )\n\n\n@pytest.mark.skipif(numpy is None, reason=\"numpy is not installed\")\nclass NumpyEndianness:\n    def test_numpy_array_dimension_zero(self):\n        wrong_endianness = \">\" if sys.byteorder == \"little\" else \"<\"\n        array = numpy.array([0, 1, 0.4, 5.7], dtype=f\"{wrong_endianness}f8\")\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(array, option=orjson.OPT_SERIALIZE_NUMPY)\n"
  },
  {
    "path": "test/test_parsing.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2018-2026)\n\nimport pytest\n\nimport orjson\n\nfrom .util import (\n    SUPPORTS_BYTEARRAY,\n    SUPPORTS_MEMORYVIEW,\n    needs_data,\n    read_fixture_bytes,\n)\n\n\n@needs_data\nclass TestJSONTestSuiteParsing:\n    def _run_fail_json(self, filename, exc=orjson.JSONDecodeError):\n        data = read_fixture_bytes(filename, \"parsing\")\n        with pytest.raises(exc):\n            orjson.loads(data)\n        if SUPPORTS_BYTEARRAY:\n            with pytest.raises(exc):\n                orjson.loads(bytearray(data))\n        if SUPPORTS_MEMORYVIEW:\n            with pytest.raises(exc):\n                orjson.loads(memoryview(data))\n        try:\n            decoded = data.decode(\"utf-8\")\n        except UnicodeDecodeError:\n            pass\n        else:\n            with pytest.raises(exc):\n                orjson.loads(decoded)\n\n    def _run_pass_json(self, filename, match=\"\"):\n        data = read_fixture_bytes(filename, \"parsing\")\n        orjson.loads(data)\n        if SUPPORTS_BYTEARRAY:\n            orjson.loads(bytearray(data))\n        if SUPPORTS_MEMORYVIEW:\n            orjson.loads(memoryview(data))\n        orjson.loads(data.decode(\"utf-8\"))\n\n    def test_y_array_arraysWithSpace(self):\n        \"\"\"\n        y_array_arraysWithSpaces.json\n        \"\"\"\n        self._run_pass_json(\"y_array_arraysWithSpaces.json\")\n\n    def test_y_array_empty_string(self):\n        \"\"\"\n        y_array_empty-string.json\n        \"\"\"\n        self._run_pass_json(\"y_array_empty-string.json\")\n\n    def test_y_array_empty(self):\n        \"\"\"\n        y_array_empty.json\n        \"\"\"\n        self._run_pass_json(\"y_array_empty.json\")\n\n    def test_y_array_ending_with_newline(self):\n        \"\"\"\n        y_array_ending_with_newline.json\n        \"\"\"\n        self._run_pass_json(\"y_array_ending_with_newline.json\")\n\n    def test_y_array_false(self):\n        \"\"\"\n        y_array_false.json\n        \"\"\"\n        self._run_pass_json(\"y_array_false.json\")\n\n    def test_y_array_heterogeneou(self):\n        \"\"\"\n        y_array_heterogeneous.json\n        \"\"\"\n        self._run_pass_json(\"y_array_heterogeneous.json\")\n\n    def test_y_array_null(self):\n        \"\"\"\n        y_array_null.json\n        \"\"\"\n        self._run_pass_json(\"y_array_null.json\")\n\n    def test_y_array_with_1_and_newline(self):\n        \"\"\"\n        y_array_with_1_and_newline.json\n        \"\"\"\n        self._run_pass_json(\"y_array_with_1_and_newline.json\")\n\n    def test_y_array_with_leading_space(self):\n        \"\"\"\n        y_array_with_leading_space.json\n        \"\"\"\n        self._run_pass_json(\"y_array_with_leading_space.json\")\n\n    def test_y_array_with_several_null(self):\n        \"\"\"\n        y_array_with_several_null.json\n        \"\"\"\n        self._run_pass_json(\"y_array_with_several_null.json\")\n\n    def test_y_array_with_trailing_space(self):\n        \"\"\"\n        y_array_with_trailing_space.json\n        \"\"\"\n        self._run_pass_json(\"y_array_with_trailing_space.json\")\n\n    def test_y_number(self):\n        \"\"\"\n        y_number.json\n        \"\"\"\n        self._run_pass_json(\"y_number.json\")\n\n    def test_y_number_0e_1(self):\n        \"\"\"\n        y_number_0e+1.json\n        \"\"\"\n        self._run_pass_json(\"y_number_0e+1.json\")\n\n    def test_y_number_0e1(self):\n        \"\"\"\n        y_number_0e1.json\n        \"\"\"\n        self._run_pass_json(\"y_number_0e1.json\")\n\n    def test_y_number_after_space(self):\n        \"\"\"\n        y_number_after_space.json\n        \"\"\"\n        self._run_pass_json(\"y_number_after_space.json\")\n\n    def test_y_number_double_close_to_zer(self):\n        \"\"\"\n        y_number_double_close_to_zero.json\n        \"\"\"\n        self._run_pass_json(\"y_number_double_close_to_zero.json\")\n\n    def test_y_number_int_with_exp(self):\n        \"\"\"\n        y_number_int_with_exp.json\n        \"\"\"\n        self._run_pass_json(\"y_number_int_with_exp.json\")\n\n    def test_y_number_minus_zer(self):\n        \"\"\"\n        y_number_minus_zero.json\n        \"\"\"\n        self._run_pass_json(\"y_number_minus_zero.json\")\n\n    def test_y_number_negative_int(self):\n        \"\"\"\n        y_number_negative_int.json\n        \"\"\"\n        self._run_pass_json(\"y_number_negative_int.json\")\n\n    def test_y_number_negative_one(self):\n        \"\"\"\n        y_number_negative_one.json\n        \"\"\"\n        self._run_pass_json(\"y_number_negative_one.json\")\n\n    def test_y_number_negative_zer(self):\n        \"\"\"\n        y_number_negative_zero.json\n        \"\"\"\n        self._run_pass_json(\"y_number_negative_zero.json\")\n\n    def test_y_number_real_capital_e(self):\n        \"\"\"\n        y_number_real_capital_e.json\n        \"\"\"\n        self._run_pass_json(\"y_number_real_capital_e.json\")\n\n    def test_y_number_real_capital_e_neg_exp(self):\n        \"\"\"\n        y_number_real_capital_e_neg_exp.json\n        \"\"\"\n        self._run_pass_json(\"y_number_real_capital_e_neg_exp.json\")\n\n    def test_y_number_real_capital_e_pos_exp(self):\n        \"\"\"\n        y_number_real_capital_e_pos_exp.json\n        \"\"\"\n        self._run_pass_json(\"y_number_real_capital_e_pos_exp.json\")\n\n    def test_y_number_real_exponent(self):\n        \"\"\"\n        y_number_real_exponent.json\n        \"\"\"\n        self._run_pass_json(\"y_number_real_exponent.json\")\n\n    def test_y_number_real_fraction_exponent(self):\n        \"\"\"\n        y_number_real_fraction_exponent.json\n        \"\"\"\n        self._run_pass_json(\"y_number_real_fraction_exponent.json\")\n\n    def test_y_number_real_neg_exp(self):\n        \"\"\"\n        y_number_real_neg_exp.json\n        \"\"\"\n        self._run_pass_json(\"y_number_real_neg_exp.json\")\n\n    def test_y_number_real_pos_exponent(self):\n        \"\"\"\n        y_number_real_pos_exponent.json\n        \"\"\"\n        self._run_pass_json(\"y_number_real_pos_exponent.json\")\n\n    def test_y_number_simple_int(self):\n        \"\"\"\n        y_number_simple_int.json\n        \"\"\"\n        self._run_pass_json(\"y_number_simple_int.json\")\n\n    def test_y_number_simple_real(self):\n        \"\"\"\n        y_number_simple_real.json\n        \"\"\"\n        self._run_pass_json(\"y_number_simple_real.json\")\n\n    def test_y_object(self):\n        \"\"\"\n        y_object.json\n        \"\"\"\n        self._run_pass_json(\"y_object.json\")\n\n    def test_y_object_basic(self):\n        \"\"\"\n        y_object_basic.json\n        \"\"\"\n        self._run_pass_json(\"y_object_basic.json\")\n\n    def test_y_object_duplicated_key(self):\n        \"\"\"\n        y_object_duplicated_key.json\n        \"\"\"\n        self._run_pass_json(\"y_object_duplicated_key.json\")\n\n    def test_y_object_duplicated_key_and_value(self):\n        \"\"\"\n        y_object_duplicated_key_and_value.json\n        \"\"\"\n        self._run_pass_json(\"y_object_duplicated_key_and_value.json\")\n\n    def test_y_object_empty(self):\n        \"\"\"\n        y_object_empty.json\n        \"\"\"\n        self._run_pass_json(\"y_object_empty.json\")\n\n    def test_y_object_empty_key(self):\n        \"\"\"\n        y_object_empty_key.json\n        \"\"\"\n        self._run_pass_json(\"y_object_empty_key.json\")\n\n    def test_y_object_escaped_null_in_key(self):\n        \"\"\"\n        y_object_escaped_null_in_key.json\n        \"\"\"\n        self._run_pass_json(\"y_object_escaped_null_in_key.json\")\n\n    def test_y_object_extreme_number(self):\n        \"\"\"\n        y_object_extreme_numbers.json\n        \"\"\"\n        self._run_pass_json(\"y_object_extreme_numbers.json\")\n\n    def test_y_object_long_string(self):\n        \"\"\"\n        y_object_long_strings.json\n        \"\"\"\n        self._run_pass_json(\"y_object_long_strings.json\")\n\n    def test_y_object_simple(self):\n        \"\"\"\n        y_object_simple.json\n        \"\"\"\n        self._run_pass_json(\"y_object_simple.json\")\n\n    def test_y_object_string_unicode(self):\n        \"\"\"\n        y_object_string_unicode.json\n        \"\"\"\n        self._run_pass_json(\"y_object_string_unicode.json\")\n\n    def test_y_object_with_newline(self):\n        \"\"\"\n        y_object_with_newlines.json\n        \"\"\"\n        self._run_pass_json(\"y_object_with_newlines.json\")\n\n    def test_y_string_1_2_3_bytes_UTF_8_sequence(self):\n        \"\"\"\n        y_string_1_2_3_bytes_UTF-8_sequences.json\n        \"\"\"\n        self._run_pass_json(\"y_string_1_2_3_bytes_UTF-8_sequences.json\")\n\n    def test_y_string_accepted_surrogate_pair(self):\n        \"\"\"\n        y_string_accepted_surrogate_pair.json\n        \"\"\"\n        self._run_pass_json(\"y_string_accepted_surrogate_pair.json\")\n\n    def test_y_string_accepted_surrogate_pairs(self):\n        \"\"\"\n        y_string_accepted_surrogate_pairs.json\n        \"\"\"\n        self._run_pass_json(\"y_string_accepted_surrogate_pairs.json\")\n\n    def test_y_string_allowed_escape(self):\n        \"\"\"\n        y_string_allowed_escapes.json\n        \"\"\"\n        self._run_pass_json(\"y_string_allowed_escapes.json\")\n\n    def test_y_string_backslash_and_u_escaped_zer(self):\n        \"\"\"\n        y_string_backslash_and_u_escaped_zero.json\n        \"\"\"\n        self._run_pass_json(\"y_string_backslash_and_u_escaped_zero.json\")\n\n    def test_y_string_backslash_doublequote(self):\n        \"\"\"\n        y_string_backslash_doublequotes.json\n        \"\"\"\n        self._run_pass_json(\"y_string_backslash_doublequotes.json\")\n\n    def test_y_string_comment(self):\n        \"\"\"\n        y_string_comments.json\n        \"\"\"\n        self._run_pass_json(\"y_string_comments.json\")\n\n    def test_y_string_double_escape_a(self):\n        \"\"\"\n        y_string_double_escape_a.json\n        \"\"\"\n        self._run_pass_json(\"y_string_double_escape_a.json\")\n\n    def test_y_string_double_escape_(self):\n        \"\"\"\n        y_string_double_escape_n.json\n        \"\"\"\n        self._run_pass_json(\"y_string_double_escape_n.json\")\n\n    def test_y_string_escaped_control_character(self):\n        \"\"\"\n        y_string_escaped_control_character.json\n        \"\"\"\n        self._run_pass_json(\"y_string_escaped_control_character.json\")\n\n    def test_y_string_escaped_noncharacter(self):\n        \"\"\"\n        y_string_escaped_noncharacter.json\n        \"\"\"\n        self._run_pass_json(\"y_string_escaped_noncharacter.json\")\n\n    def test_y_string_in_array(self):\n        \"\"\"\n        y_string_in_array.json\n        \"\"\"\n        self._run_pass_json(\"y_string_in_array.json\")\n\n    def test_y_string_in_array_with_leading_space(self):\n        \"\"\"\n        y_string_in_array_with_leading_space.json\n        \"\"\"\n        self._run_pass_json(\"y_string_in_array_with_leading_space.json\")\n\n    def test_y_string_last_surrogates_1_and_2(self):\n        \"\"\"\n        y_string_last_surrogates_1_and_2.json\n        \"\"\"\n        self._run_pass_json(\"y_string_last_surrogates_1_and_2.json\")\n\n    def test_y_string_nbsp_uescaped(self):\n        \"\"\"\n        y_string_nbsp_uescaped.json\n        \"\"\"\n        self._run_pass_json(\"y_string_nbsp_uescaped.json\")\n\n    def test_y_string_nonCharacterInUTF_8_U_10FFFF(self):\n        \"\"\"\n        y_string_nonCharacterInUTF-8_U+10FFFF.json\n        \"\"\"\n        self._run_pass_json(\"y_string_nonCharacterInUTF-8_U+10FFFF.json\")\n\n    def test_y_string_nonCharacterInUTF_8_U_FFFF(self):\n        \"\"\"\n        y_string_nonCharacterInUTF-8_U+FFFF.json\n        \"\"\"\n        self._run_pass_json(\"y_string_nonCharacterInUTF-8_U+FFFF.json\")\n\n    def test_y_string_null_escape(self):\n        \"\"\"\n        y_string_null_escape.json\n        \"\"\"\n        self._run_pass_json(\"y_string_null_escape.json\")\n\n    def test_y_string_one_byte_utf_8(self):\n        \"\"\"\n        y_string_one-byte-utf-8.json\n        \"\"\"\n        self._run_pass_json(\"y_string_one-byte-utf-8.json\")\n\n    def test_y_string_pi(self):\n        \"\"\"\n        y_string_pi.json\n        \"\"\"\n        self._run_pass_json(\"y_string_pi.json\")\n\n    def test_y_string_reservedCharacterInUTF_8_U_1BFFF(self):\n        \"\"\"\n        y_string_reservedCharacterInUTF-8_U+1BFFF.json\n        \"\"\"\n        self._run_pass_json(\"y_string_reservedCharacterInUTF-8_U+1BFFF.json\")\n\n    def test_y_string_simple_ascii(self):\n        \"\"\"\n        y_string_simple_ascii.json\n        \"\"\"\n        self._run_pass_json(\"y_string_simple_ascii.json\")\n\n    def test_y_string_space(self):\n        \"\"\"\n        y_string_space.json\n        \"\"\"\n        self._run_pass_json(\"y_string_space.json\")\n\n    def test_y_string_surrogates_U_1D11E_MUSICAL_SYMBOL_G_CLEF(self):\n        \"\"\"\n        y_string_surrogates_U+1D11E_MUSICAL_SYMBOL_G_CLEF.json\n        \"\"\"\n        self._run_pass_json(\"y_string_surrogates_U+1D11E_MUSICAL_SYMBOL_G_CLEF.json\")\n\n    def test_y_string_three_byte_utf_8(self):\n        \"\"\"\n        y_string_three-byte-utf-8.json\n        \"\"\"\n        self._run_pass_json(\"y_string_three-byte-utf-8.json\")\n\n    def test_y_string_two_byte_utf_8(self):\n        \"\"\"\n        y_string_two-byte-utf-8.json\n        \"\"\"\n        self._run_pass_json(\"y_string_two-byte-utf-8.json\")\n\n    def test_y_string_u_2028_line_sep(self):\n        \"\"\"\n        y_string_u+2028_line_sep.json\n        \"\"\"\n        self._run_pass_json(\"y_string_u+2028_line_sep.json\")\n\n    def test_y_string_u_2029_par_sep(self):\n        \"\"\"\n        y_string_u+2029_par_sep.json\n        \"\"\"\n        self._run_pass_json(\"y_string_u+2029_par_sep.json\")\n\n    def test_y_string_uEscape(self):\n        \"\"\"\n        y_string_uEscape.json\n        \"\"\"\n        self._run_pass_json(\"y_string_uEscape.json\")\n\n    def test_y_string_uescaped_newline(self):\n        \"\"\"\n        y_string_uescaped_newline.json\n        \"\"\"\n        self._run_pass_json(\"y_string_uescaped_newline.json\")\n\n    def test_y_string_unescaped_char_delete(self):\n        \"\"\"\n        y_string_unescaped_char_delete.json\n        \"\"\"\n        self._run_pass_json(\"y_string_unescaped_char_delete.json\")\n\n    def test_y_string_unicode(self):\n        \"\"\"\n        y_string_unicode.json\n        \"\"\"\n        self._run_pass_json(\"y_string_unicode.json\")\n\n    def test_y_string_unicodeEscapedBackslash(self):\n        \"\"\"\n        y_string_unicodeEscapedBackslash.json\n        \"\"\"\n        self._run_pass_json(\"y_string_unicodeEscapedBackslash.json\")\n\n    def test_y_string_unicode_2(self):\n        \"\"\"\n        y_string_unicode_2.json\n        \"\"\"\n        self._run_pass_json(\"y_string_unicode_2.json\")\n\n    def test_y_string_unicode_U_10FFFE_nonchar(self):\n        \"\"\"\n        y_string_unicode_U+10FFFE_nonchar.json\n        \"\"\"\n        self._run_pass_json(\"y_string_unicode_U+10FFFE_nonchar.json\")\n\n    def test_y_string_unicode_U_1FFFE_nonchar(self):\n        \"\"\"\n        y_string_unicode_U+1FFFE_nonchar.json\n        \"\"\"\n        self._run_pass_json(\"y_string_unicode_U+1FFFE_nonchar.json\")\n\n    def test_y_string_unicode_U_200B_ZERO_WIDTH_SPACE(self):\n        \"\"\"\n        y_string_unicode_U+200B_ZERO_WIDTH_SPACE.json\n        \"\"\"\n        self._run_pass_json(\"y_string_unicode_U+200B_ZERO_WIDTH_SPACE.json\")\n\n    def test_y_string_unicode_U_2064_invisible_plu(self):\n        \"\"\"\n        y_string_unicode_U+2064_invisible_plus.json\n        \"\"\"\n        self._run_pass_json(\"y_string_unicode_U+2064_invisible_plus.json\")\n\n    def test_y_string_unicode_U_FDD0_nonchar(self):\n        \"\"\"\n        y_string_unicode_U+FDD0_nonchar.json\n        \"\"\"\n        self._run_pass_json(\"y_string_unicode_U+FDD0_nonchar.json\")\n\n    def test_y_string_unicode_U_FFFE_nonchar(self):\n        \"\"\"\n        y_string_unicode_U+FFFE_nonchar.json\n        \"\"\"\n        self._run_pass_json(\"y_string_unicode_U+FFFE_nonchar.json\")\n\n    def test_y_string_unicode_escaped_double_quote(self):\n        \"\"\"\n        y_string_unicode_escaped_double_quote.json\n        \"\"\"\n        self._run_pass_json(\"y_string_unicode_escaped_double_quote.json\")\n\n    def test_y_string_utf8(self):\n        \"\"\"\n        y_string_utf8.json\n        \"\"\"\n        self._run_pass_json(\"y_string_utf8.json\")\n\n    def test_y_string_with_del_character(self):\n        \"\"\"\n        y_string_with_del_character.json\n        \"\"\"\n        self._run_pass_json(\"y_string_with_del_character.json\")\n\n    def test_y_structure_lonely_false(self):\n        \"\"\"\n        y_structure_lonely_false.json\n        \"\"\"\n        self._run_pass_json(\"y_structure_lonely_false.json\")\n\n    def test_y_structure_lonely_int(self):\n        \"\"\"\n        y_structure_lonely_int.json\n        \"\"\"\n        self._run_pass_json(\"y_structure_lonely_int.json\")\n\n    def test_y_structure_lonely_negative_real(self):\n        \"\"\"\n        y_structure_lonely_negative_real.json\n        \"\"\"\n        self._run_pass_json(\"y_structure_lonely_negative_real.json\")\n\n    def test_y_structure_lonely_null(self):\n        \"\"\"\n        y_structure_lonely_null.json\n        \"\"\"\n        self._run_pass_json(\"y_structure_lonely_null.json\")\n\n    def test_y_structure_lonely_string(self):\n        \"\"\"\n        y_structure_lonely_string.json\n        \"\"\"\n        self._run_pass_json(\"y_structure_lonely_string.json\")\n\n    def test_y_structure_lonely_true(self):\n        \"\"\"\n        y_structure_lonely_true.json\n        \"\"\"\n        self._run_pass_json(\"y_structure_lonely_true.json\")\n\n    def test_y_structure_string_empty(self):\n        \"\"\"\n        y_structure_string_empty.json\n        \"\"\"\n        self._run_pass_json(\"y_structure_string_empty.json\")\n\n    def test_y_structure_trailing_newline(self):\n        \"\"\"\n        y_structure_trailing_newline.json\n        \"\"\"\n        self._run_pass_json(\"y_structure_trailing_newline.json\")\n\n    def test_y_structure_true_in_array(self):\n        \"\"\"\n        y_structure_true_in_array.json\n        \"\"\"\n        self._run_pass_json(\"y_structure_true_in_array.json\")\n\n    def test_y_structure_whitespace_array(self):\n        \"\"\"\n        y_structure_whitespace_array.json\n        \"\"\"\n        self._run_pass_json(\"y_structure_whitespace_array.json\")\n\n    def test_n_array_1_true_without_comma(self):\n        \"\"\"\n        n_array_1_true_without_comma.json\n        \"\"\"\n        self._run_fail_json(\"n_array_1_true_without_comma.json\")\n\n    def test_n_array_a_invalid_utf8(self):\n        \"\"\"\n        n_array_a_invalid_utf8.json\n        \"\"\"\n        self._run_fail_json(\"n_array_a_invalid_utf8.json\")\n\n    def test_n_array_colon_instead_of_comma(self):\n        \"\"\"\n        n_array_colon_instead_of_comma.json\n        \"\"\"\n        self._run_fail_json(\"n_array_colon_instead_of_comma.json\")\n\n    def test_n_array_comma_after_close(self):\n        \"\"\"\n        n_array_comma_after_close.json\n        \"\"\"\n        self._run_fail_json(\"n_array_comma_after_close.json\")\n\n    def test_n_array_comma_and_number(self):\n        \"\"\"\n        n_array_comma_and_number.json\n        \"\"\"\n        self._run_fail_json(\"n_array_comma_and_number.json\")\n\n    def test_n_array_double_comma(self):\n        \"\"\"\n        n_array_double_comma.json\n        \"\"\"\n        self._run_fail_json(\"n_array_double_comma.json\")\n\n    def test_n_array_double_extra_comma(self):\n        \"\"\"\n        n_array_double_extra_comma.json\n        \"\"\"\n        self._run_fail_json(\"n_array_double_extra_comma.json\")\n\n    def test_n_array_extra_close(self):\n        \"\"\"\n        n_array_extra_close.json\n        \"\"\"\n        self._run_fail_json(\"n_array_extra_close.json\")\n\n    def test_n_array_extra_comma(self):\n        \"\"\"\n        n_array_extra_comma.json\n        \"\"\"\n        self._run_fail_json(\"n_array_extra_comma.json\")\n\n    def test_n_array_incomplete(self):\n        \"\"\"\n        n_array_incomplete.json\n        \"\"\"\n        self._run_fail_json(\"n_array_incomplete.json\")\n\n    def test_n_array_incomplete_invalid_value(self):\n        \"\"\"\n        n_array_incomplete_invalid_value.json\n        \"\"\"\n        self._run_fail_json(\"n_array_incomplete_invalid_value.json\")\n\n    def test_n_array_inner_array_no_comma(self):\n        \"\"\"\n        n_array_inner_array_no_comma.json\n        \"\"\"\n        self._run_fail_json(\"n_array_inner_array_no_comma.json\")\n\n    def test_n_array_invalid_utf8(self):\n        \"\"\"\n        n_array_invalid_utf8.json\n        \"\"\"\n        self._run_fail_json(\"n_array_invalid_utf8.json\")\n\n    def test_n_array_items_separated_by_semicol(self):\n        \"\"\"\n        n_array_items_separated_by_semicolon.json\n        \"\"\"\n        self._run_fail_json(\"n_array_items_separated_by_semicolon.json\")\n\n    def test_n_array_just_comma(self):\n        \"\"\"\n        n_array_just_comma.json\n        \"\"\"\n        self._run_fail_json(\"n_array_just_comma.json\")\n\n    def test_n_array_just_minu(self):\n        \"\"\"\n        n_array_just_minus.json\n        \"\"\"\n        self._run_fail_json(\"n_array_just_minus.json\")\n\n    def test_n_array_missing_value(self):\n        \"\"\"\n        n_array_missing_value.json\n        \"\"\"\n        self._run_fail_json(\"n_array_missing_value.json\")\n\n    def test_n_array_newlines_unclosed(self):\n        \"\"\"\n        n_array_newlines_unclosed.json\n        \"\"\"\n        self._run_fail_json(\"n_array_newlines_unclosed.json\")\n\n    def test_n_array_number_and_comma(self):\n        \"\"\"\n        n_array_number_and_comma.json\n        \"\"\"\n        self._run_fail_json(\"n_array_number_and_comma.json\")\n\n    def test_n_array_number_and_several_comma(self):\n        \"\"\"\n        n_array_number_and_several_commas.json\n        \"\"\"\n        self._run_fail_json(\"n_array_number_and_several_commas.json\")\n\n    def test_n_array_spaces_vertical_tab_formfeed(self):\n        \"\"\"\n        n_array_spaces_vertical_tab_formfeed.json\n        \"\"\"\n        self._run_fail_json(\"n_array_spaces_vertical_tab_formfeed.json\")\n\n    def test_n_array_star_inside(self):\n        \"\"\"\n        n_array_star_inside.json\n        \"\"\"\n        self._run_fail_json(\"n_array_star_inside.json\")\n\n    def test_n_array_unclosed(self):\n        \"\"\"\n        n_array_unclosed.json\n        \"\"\"\n        self._run_fail_json(\"n_array_unclosed.json\")\n\n    def test_n_array_unclosed_trailing_comma(self):\n        \"\"\"\n        n_array_unclosed_trailing_comma.json\n        \"\"\"\n        self._run_fail_json(\"n_array_unclosed_trailing_comma.json\")\n\n    def test_n_array_unclosed_with_new_line(self):\n        \"\"\"\n        n_array_unclosed_with_new_lines.json\n        \"\"\"\n        self._run_fail_json(\"n_array_unclosed_with_new_lines.json\")\n\n    def test_n_array_unclosed_with_object_inside(self):\n        \"\"\"\n        n_array_unclosed_with_object_inside.json\n        \"\"\"\n        self._run_fail_json(\"n_array_unclosed_with_object_inside.json\")\n\n    def test_n_incomplete_false(self):\n        \"\"\"\n        n_incomplete_false.json\n        \"\"\"\n        self._run_fail_json(\"n_incomplete_false.json\")\n\n    def test_n_incomplete_null(self):\n        \"\"\"\n        n_incomplete_null.json\n        \"\"\"\n        self._run_fail_json(\"n_incomplete_null.json\")\n\n    def test_n_incomplete_true(self):\n        \"\"\"\n        n_incomplete_true.json\n        \"\"\"\n        self._run_fail_json(\"n_incomplete_true.json\")\n\n    def test_n_multidigit_number_then_00(self):\n        \"\"\"\n        n_multidigit_number_then_00.json\n        \"\"\"\n        self._run_fail_json(\"n_multidigit_number_then_00.json\")\n\n    def test_n_number__(self):\n        \"\"\"\n        n_number_++.json\n        \"\"\"\n        self._run_fail_json(\"n_number_++.json\")\n\n    def test_n_number_1(self):\n        \"\"\"\n        n_number_+1.json\n        \"\"\"\n        self._run_fail_json(\"n_number_+1.json\")\n\n    def test_n_number_Inf(self):\n        \"\"\"\n        n_number_+Inf.json\n        \"\"\"\n        self._run_fail_json(\"n_number_+Inf.json\")\n\n    def test_n_number_01(self):\n        \"\"\"\n        n_number_-01.json\n        \"\"\"\n        self._run_fail_json(\"n_number_-01.json\")\n\n    def test_n_number_1_0(self):\n        \"\"\"\n        n_number_-1.0..json\n        \"\"\"\n        self._run_fail_json(\"n_number_-1.0..json\")\n\n    def test_n_number_2(self):\n        \"\"\"\n        n_number_-2..json\n        \"\"\"\n        self._run_fail_json(\"n_number_-2..json\")\n\n    def test_n_number_negative_NaN(self):\n        \"\"\"\n        n_number_-NaN.json\n        \"\"\"\n        self._run_fail_json(\"n_number_-NaN.json\")\n\n    def test_n_number_negative_1(self):\n        \"\"\"\n        n_number_.-1.json\n        \"\"\"\n        self._run_fail_json(\"n_number_.-1.json\")\n\n    def test_n_number_2e_3(self):\n        \"\"\"\n        n_number_.2e-3.json\n        \"\"\"\n        self._run_fail_json(\"n_number_.2e-3.json\")\n\n    def test_n_number_0_1_2(self):\n        \"\"\"\n        n_number_0.1.2.json\n        \"\"\"\n        self._run_fail_json(\"n_number_0.1.2.json\")\n\n    def test_n_number_0_3e_(self):\n        \"\"\"\n        n_number_0.3e+.json\n        \"\"\"\n        self._run_fail_json(\"n_number_0.3e+.json\")\n\n    def test_n_number_0_3e(self):\n        \"\"\"\n        n_number_0.3e.json\n        \"\"\"\n        self._run_fail_json(\"n_number_0.3e.json\")\n\n    def test_n_number_0_e1(self):\n        \"\"\"\n        n_number_0.e1.json\n        \"\"\"\n        self._run_fail_json(\"n_number_0.e1.json\")\n\n    def test_n_number_0_capital_E_(self):\n        \"\"\"\n        n_number_0_capital_E+.json\n        \"\"\"\n        self._run_fail_json(\"n_number_0_capital_E+.json\")\n\n    def test_n_number_0_capital_E(self):\n        \"\"\"\n        n_number_0_capital_E.json\n        \"\"\"\n        self._run_fail_json(\"n_number_0_capital_E.json\")\n\n    def test_n_number_0e_(self):\n        \"\"\"\n        n_number_0e+.json\n        \"\"\"\n        self._run_fail_json(\"n_number_0e+.json\")\n\n    def test_n_number_0e(self):\n        \"\"\"\n        n_number_0e.json\n        \"\"\"\n        self._run_fail_json(\"n_number_0e.json\")\n\n    def test_n_number_1_0e_(self):\n        \"\"\"\n        n_number_1.0e+.json\n        \"\"\"\n        self._run_fail_json(\"n_number_1.0e+.json\")\n\n    def test_n_number_1_0e_2(self):\n        \"\"\"\n        n_number_1.0e-.json\n        \"\"\"\n        self._run_fail_json(\"n_number_1.0e-.json\")\n\n    def test_n_number_1_0e(self):\n        \"\"\"\n        n_number_1.0e.json\n        \"\"\"\n        self._run_fail_json(\"n_number_1.0e.json\")\n\n    def test_n_number_1_000(self):\n        \"\"\"\n        n_number_1_000.json\n        \"\"\"\n        self._run_fail_json(\"n_number_1_000.json\")\n\n    def test_n_number_1eE2(self):\n        \"\"\"\n        n_number_1eE2.json\n        \"\"\"\n        self._run_fail_json(\"n_number_1eE2.json\")\n\n    def test_n_number_2_e_3(self):\n        \"\"\"\n        n_number_2.e+3.json\n        \"\"\"\n        self._run_fail_json(\"n_number_2.e+3.json\")\n\n    def test_n_number_2_e_3_2(self):\n        \"\"\"\n        n_number_2.e-3.json\n        \"\"\"\n        self._run_fail_json(\"n_number_2.e-3.json\")\n\n    def test_n_number_2_e3_3(self):\n        \"\"\"\n        n_number_2.e3.json\n        \"\"\"\n        self._run_fail_json(\"n_number_2.e3.json\")\n\n    def test_n_number_9_e_(self):\n        \"\"\"\n        n_number_9.e+.json\n        \"\"\"\n        self._run_fail_json(\"n_number_9.e+.json\")\n\n    def test_n_number_negative_Inf(self):\n        \"\"\"\n        n_number_Inf.json\n        \"\"\"\n        self._run_fail_json(\"n_number_Inf.json\")\n\n    def test_n_number_NaN(self):\n        \"\"\"\n        n_number_NaN.json\n        \"\"\"\n        self._run_fail_json(\"n_number_NaN.json\")\n\n    def test_n_number_U_FF11_fullwidth_digit_one(self):\n        \"\"\"\n        n_number_U+FF11_fullwidth_digit_one.json\n        \"\"\"\n        self._run_fail_json(\"n_number_U+FF11_fullwidth_digit_one.json\")\n\n    def test_n_number_expressi(self):\n        \"\"\"\n        n_number_expression.json\n        \"\"\"\n        self._run_fail_json(\"n_number_expression.json\")\n\n    def test_n_number_hex_1_digit(self):\n        \"\"\"\n        n_number_hex_1_digit.json\n        \"\"\"\n        self._run_fail_json(\"n_number_hex_1_digit.json\")\n\n    def test_n_number_hex_2_digit(self):\n        \"\"\"\n        n_number_hex_2_digits.json\n        \"\"\"\n        self._run_fail_json(\"n_number_hex_2_digits.json\")\n\n    def test_n_number_infinity(self):\n        \"\"\"\n        n_number_infinity.json\n        \"\"\"\n        self._run_fail_json(\"n_number_infinity.json\")\n\n    def test_n_number_invalid_(self):\n        \"\"\"\n        n_number_invalid+-.json\n        \"\"\"\n        self._run_fail_json(\"n_number_invalid+-.json\")\n\n    def test_n_number_invalid_negative_real(self):\n        \"\"\"\n        n_number_invalid-negative-real.json\n        \"\"\"\n        self._run_fail_json(\"n_number_invalid-negative-real.json\")\n\n    def test_n_number_invalid_utf_8_in_bigger_int(self):\n        \"\"\"\n        n_number_invalid-utf-8-in-bigger-int.json\n        \"\"\"\n        self._run_fail_json(\"n_number_invalid-utf-8-in-bigger-int.json\")\n\n    def test_n_number_invalid_utf_8_in_exponent(self):\n        \"\"\"\n        n_number_invalid-utf-8-in-exponent.json\n        \"\"\"\n        self._run_fail_json(\"n_number_invalid-utf-8-in-exponent.json\")\n\n    def test_n_number_invalid_utf_8_in_int(self):\n        \"\"\"\n        n_number_invalid-utf-8-in-int.json\n        \"\"\"\n        self._run_fail_json(\"n_number_invalid-utf-8-in-int.json\")\n\n    def test_n_number_minus_infinity(self):\n        \"\"\"\n        n_number_minus_infinity.json\n        \"\"\"\n        self._run_fail_json(\"n_number_minus_infinity.json\")\n\n    def test_n_number_minus_sign_with_trailing_garbage(self):\n        \"\"\"\n        n_number_minus_sign_with_trailing_garbage.json\n        \"\"\"\n        self._run_fail_json(\"n_number_minus_sign_with_trailing_garbage.json\")\n\n    def test_n_number_minus_space_1(self):\n        \"\"\"\n        n_number_minus_space_1.json\n        \"\"\"\n        self._run_fail_json(\"n_number_minus_space_1.json\")\n\n    def test_n_number_neg_int_starting_with_zer(self):\n        \"\"\"\n        n_number_neg_int_starting_with_zero.json\n        \"\"\"\n        self._run_fail_json(\"n_number_neg_int_starting_with_zero.json\")\n\n    def test_n_number_neg_real_without_int_part(self):\n        \"\"\"\n        n_number_neg_real_without_int_part.json\n        \"\"\"\n        self._run_fail_json(\"n_number_neg_real_without_int_part.json\")\n\n    def test_n_number_neg_with_garbage_at_end(self):\n        \"\"\"\n        n_number_neg_with_garbage_at_end.json\n        \"\"\"\n        self._run_fail_json(\"n_number_neg_with_garbage_at_end.json\")\n\n    def test_n_number_real_garbage_after_e(self):\n        \"\"\"\n        n_number_real_garbage_after_e.json\n        \"\"\"\n        self._run_fail_json(\"n_number_real_garbage_after_e.json\")\n\n    def test_n_number_real_with_invalid_utf8_after_e(self):\n        \"\"\"\n        n_number_real_with_invalid_utf8_after_e.json\n        \"\"\"\n        self._run_fail_json(\"n_number_real_with_invalid_utf8_after_e.json\")\n\n    def test_n_number_real_without_fractional_part(self):\n        \"\"\"\n        n_number_real_without_fractional_part.json\n        \"\"\"\n        self._run_fail_json(\"n_number_real_without_fractional_part.json\")\n\n    def test_n_number_starting_with_dot(self):\n        \"\"\"\n        n_number_starting_with_dot.json\n        \"\"\"\n        self._run_fail_json(\"n_number_starting_with_dot.json\")\n\n    def test_n_number_with_alpha(self):\n        \"\"\"\n        n_number_with_alpha.json\n        \"\"\"\n        self._run_fail_json(\"n_number_with_alpha.json\")\n\n    def test_n_number_with_alpha_char(self):\n        \"\"\"\n        n_number_with_alpha_char.json\n        \"\"\"\n        self._run_fail_json(\"n_number_with_alpha_char.json\")\n\n    def test_n_number_with_leading_zer(self):\n        \"\"\"\n        n_number_with_leading_zero.json\n        \"\"\"\n        self._run_fail_json(\"n_number_with_leading_zero.json\")\n\n    def test_n_object_bad_value(self):\n        \"\"\"\n        n_object_bad_value.json\n        \"\"\"\n        self._run_fail_json(\"n_object_bad_value.json\")\n\n    def test_n_object_bracket_key(self):\n        \"\"\"\n        n_object_bracket_key.json\n        \"\"\"\n        self._run_fail_json(\"n_object_bracket_key.json\")\n\n    def test_n_object_comma_instead_of_col(self):\n        \"\"\"\n        n_object_comma_instead_of_colon.json\n        \"\"\"\n        self._run_fail_json(\"n_object_comma_instead_of_colon.json\")\n\n    def test_n_object_double_col(self):\n        \"\"\"\n        n_object_double_colon.json\n        \"\"\"\n        self._run_fail_json(\"n_object_double_colon.json\")\n\n    def test_n_object_emoji(self):\n        \"\"\"\n        n_object_emoji.json\n        \"\"\"\n        self._run_fail_json(\"n_object_emoji.json\")\n\n    def test_n_object_garbage_at_end(self):\n        \"\"\"\n        n_object_garbage_at_end.json\n        \"\"\"\n        self._run_fail_json(\"n_object_garbage_at_end.json\")\n\n    def test_n_object_key_with_single_quote(self):\n        \"\"\"\n        n_object_key_with_single_quotes.json\n        \"\"\"\n        self._run_fail_json(\"n_object_key_with_single_quotes.json\")\n\n    def test_n_object_lone_continuation_byte_in_key_and_trailing_comma(self):\n        \"\"\"\n        n_object_lone_continuation_byte_in_key_and_trailing_comma.json\n        \"\"\"\n        self._run_fail_json(\n            \"n_object_lone_continuation_byte_in_key_and_trailing_comma.json\",\n        )\n\n    def test_n_object_missing_col(self):\n        \"\"\"\n        n_object_missing_colon.json\n        \"\"\"\n        self._run_fail_json(\"n_object_missing_colon.json\")\n\n    def test_n_object_missing_key(self):\n        \"\"\"\n        n_object_missing_key.json\n        \"\"\"\n        self._run_fail_json(\"n_object_missing_key.json\")\n\n    def test_n_object_missing_semicol(self):\n        \"\"\"\n        n_object_missing_semicolon.json\n        \"\"\"\n        self._run_fail_json(\"n_object_missing_semicolon.json\")\n\n    def test_n_object_missing_value(self):\n        \"\"\"\n        n_object_missing_value.json\n        \"\"\"\n        self._run_fail_json(\"n_object_missing_value.json\")\n\n    def test_n_object_no_col(self):\n        \"\"\"\n        n_object_no-colon.json\n        \"\"\"\n        self._run_fail_json(\"n_object_no-colon.json\")\n\n    def test_n_object_non_string_key(self):\n        \"\"\"\n        n_object_non_string_key.json\n        \"\"\"\n        self._run_fail_json(\"n_object_non_string_key.json\")\n\n    def test_n_object_non_string_key_but_huge_number_instead(self):\n        \"\"\"\n        n_object_non_string_key_but_huge_number_instead.json\n        \"\"\"\n        self._run_fail_json(\"n_object_non_string_key_but_huge_number_instead.json\")\n\n    def test_n_object_repeated_null_null(self):\n        \"\"\"\n        n_object_repeated_null_null.json\n        \"\"\"\n        self._run_fail_json(\"n_object_repeated_null_null.json\")\n\n    def test_n_object_several_trailing_comma(self):\n        \"\"\"\n        n_object_several_trailing_commas.json\n        \"\"\"\n        self._run_fail_json(\"n_object_several_trailing_commas.json\")\n\n    def test_n_object_single_quote(self):\n        \"\"\"\n        n_object_single_quote.json\n        \"\"\"\n        self._run_fail_json(\"n_object_single_quote.json\")\n\n    def test_n_object_trailing_comma(self):\n        \"\"\"\n        n_object_trailing_comma.json\n        \"\"\"\n        self._run_fail_json(\"n_object_trailing_comma.json\")\n\n    def test_n_object_trailing_comment(self):\n        \"\"\"\n        n_object_trailing_comment.json\n        \"\"\"\n        self._run_fail_json(\"n_object_trailing_comment.json\")\n\n    def test_n_object_trailing_comment_ope(self):\n        \"\"\"\n        n_object_trailing_comment_open.json\n        \"\"\"\n        self._run_fail_json(\"n_object_trailing_comment_open.json\")\n\n    def test_n_object_trailing_comment_slash_ope(self):\n        \"\"\"\n        n_object_trailing_comment_slash_open.json\n        \"\"\"\n        self._run_fail_json(\"n_object_trailing_comment_slash_open.json\")\n\n    def test_n_object_trailing_comment_slash_open_incomplete(self):\n        \"\"\"\n        n_object_trailing_comment_slash_open_incomplete.json\n        \"\"\"\n        self._run_fail_json(\"n_object_trailing_comment_slash_open_incomplete.json\")\n\n    def test_n_object_two_commas_in_a_row(self):\n        \"\"\"\n        n_object_two_commas_in_a_row.json\n        \"\"\"\n        self._run_fail_json(\"n_object_two_commas_in_a_row.json\")\n\n    def test_n_object_unquoted_key(self):\n        \"\"\"\n        n_object_unquoted_key.json\n        \"\"\"\n        self._run_fail_json(\"n_object_unquoted_key.json\")\n\n    def test_n_object_unterminated_value(self):\n        \"\"\"\n        n_object_unterminated-value.json\n        \"\"\"\n        self._run_fail_json(\"n_object_unterminated-value.json\")\n\n    def test_n_object_with_single_string(self):\n        \"\"\"\n        n_object_with_single_string.json\n        \"\"\"\n        self._run_fail_json(\"n_object_with_single_string.json\")\n\n    def test_n_object_with_trailing_garbage(self):\n        \"\"\"\n        n_object_with_trailing_garbage.json\n        \"\"\"\n        self._run_fail_json(\"n_object_with_trailing_garbage.json\")\n\n    def test_n_single_space(self):\n        \"\"\"\n        n_single_space.json\n        \"\"\"\n        self._run_fail_json(\"n_single_space.json\")\n\n    def test_n_string_1_surrogate_then_escape(self):\n        \"\"\"\n        n_string_1_surrogate_then_escape.json\n        \"\"\"\n        self._run_fail_json(\"n_string_1_surrogate_then_escape.json\")\n\n    def test_n_string_1_surrogate_then_escape_u(self):\n        \"\"\"\n        n_string_1_surrogate_then_escape_u.json\n        \"\"\"\n        self._run_fail_json(\"n_string_1_surrogate_then_escape_u.json\")\n\n    def test_n_string_1_surrogate_then_escape_u1(self):\n        \"\"\"\n        n_string_1_surrogate_then_escape_u1.json\n        \"\"\"\n        self._run_fail_json(\"n_string_1_surrogate_then_escape_u1.json\")\n\n    def test_n_string_1_surrogate_then_escape_u1x(self):\n        \"\"\"\n        n_string_1_surrogate_then_escape_u1x.json\n        \"\"\"\n        self._run_fail_json(\"n_string_1_surrogate_then_escape_u1x.json\")\n\n    def test_n_string_accentuated_char_no_quote(self):\n        \"\"\"\n        n_string_accentuated_char_no_quotes.json\n        \"\"\"\n        self._run_fail_json(\"n_string_accentuated_char_no_quotes.json\")\n\n    def test_n_string_backslash_00(self):\n        \"\"\"\n        n_string_backslash_00.json\n        \"\"\"\n        self._run_fail_json(\"n_string_backslash_00.json\")\n\n    def test_n_string_escape_x(self):\n        \"\"\"\n        n_string_escape_x.json\n        \"\"\"\n        self._run_fail_json(\"n_string_escape_x.json\")\n\n    def test_n_string_escaped_backslash_bad(self):\n        \"\"\"\n        n_string_escaped_backslash_bad.json\n        \"\"\"\n        self._run_fail_json(\"n_string_escaped_backslash_bad.json\")\n\n    def test_n_string_escaped_ctrl_char_tab(self):\n        \"\"\"\n        n_string_escaped_ctrl_char_tab.json\n        \"\"\"\n        self._run_fail_json(\"n_string_escaped_ctrl_char_tab.json\")\n\n    def test_n_string_escaped_emoji(self):\n        \"\"\"\n        n_string_escaped_emoji.json\n        \"\"\"\n        self._run_fail_json(\"n_string_escaped_emoji.json\")\n\n    def test_n_string_incomplete_escape(self):\n        \"\"\"\n        n_string_incomplete_escape.json\n        \"\"\"\n        self._run_fail_json(\"n_string_incomplete_escape.json\")\n\n    def test_n_string_incomplete_escaped_character(self):\n        \"\"\"\n        n_string_incomplete_escaped_character.json\n        \"\"\"\n        self._run_fail_json(\"n_string_incomplete_escaped_character.json\")\n\n    def test_n_string_incomplete_surrogate(self):\n        \"\"\"\n        n_string_incomplete_surrogate.json\n        \"\"\"\n        self._run_fail_json(\"n_string_incomplete_surrogate.json\")\n\n    def test_n_string_incomplete_surrogate_escape_invalid(self):\n        \"\"\"\n        n_string_incomplete_surrogate_escape_invalid.json\n        \"\"\"\n        self._run_fail_json(\"n_string_incomplete_surrogate_escape_invalid.json\")\n\n    def test_n_string_invalid_utf_8_in_escape(self):\n        \"\"\"\n        n_string_invalid-utf-8-in-escape.json\n        \"\"\"\n        self._run_fail_json(\"n_string_invalid-utf-8-in-escape.json\")\n\n    def test_n_string_invalid_backslash_esc(self):\n        \"\"\"\n        n_string_invalid_backslash_esc.json\n        \"\"\"\n        self._run_fail_json(\"n_string_invalid_backslash_esc.json\")\n\n    def test_n_string_invalid_unicode_escape(self):\n        \"\"\"\n        n_string_invalid_unicode_escape.json\n        \"\"\"\n        self._run_fail_json(\"n_string_invalid_unicode_escape.json\")\n\n    def test_n_string_invalid_utf8_after_escape(self):\n        \"\"\"\n        n_string_invalid_utf8_after_escape.json\n        \"\"\"\n        self._run_fail_json(\"n_string_invalid_utf8_after_escape.json\")\n\n    def test_n_string_leading_uescaped_thinspace(self):\n        \"\"\"\n        n_string_leading_uescaped_thinspace.json\n        \"\"\"\n        self._run_fail_json(\"n_string_leading_uescaped_thinspace.json\")\n\n    def test_n_string_no_quotes_with_bad_escape(self):\n        \"\"\"\n        n_string_no_quotes_with_bad_escape.json\n        \"\"\"\n        self._run_fail_json(\"n_string_no_quotes_with_bad_escape.json\")\n\n    def test_n_string_single_doublequote(self):\n        \"\"\"\n        n_string_single_doublequote.json\n        \"\"\"\n        self._run_fail_json(\"n_string_single_doublequote.json\")\n\n    def test_n_string_single_quote(self):\n        \"\"\"\n        n_string_single_quote.json\n        \"\"\"\n        self._run_fail_json(\"n_string_single_quote.json\")\n\n    def test_n_string_single_string_no_double_quote(self):\n        \"\"\"\n        n_string_single_string_no_double_quotes.json\n        \"\"\"\n        self._run_fail_json(\"n_string_single_string_no_double_quotes.json\")\n\n    def test_n_string_start_escape_unclosed(self):\n        \"\"\"\n        n_string_start_escape_unclosed.json\n        \"\"\"\n        self._run_fail_json(\"n_string_start_escape_unclosed.json\")\n\n    def test_n_string_unescaped_crtl_char(self):\n        \"\"\"\n        n_string_unescaped_crtl_char.json\n        \"\"\"\n        self._run_fail_json(\"n_string_unescaped_crtl_char.json\")\n\n    def test_n_string_unescaped_newline(self):\n        \"\"\"\n        n_string_unescaped_newline.json\n        \"\"\"\n        self._run_fail_json(\"n_string_unescaped_newline.json\")\n\n    def test_n_string_unescaped_tab(self):\n        \"\"\"\n        n_string_unescaped_tab.json\n        \"\"\"\n        self._run_fail_json(\"n_string_unescaped_tab.json\")\n\n    def test_n_string_unicode_CapitalU(self):\n        \"\"\"\n        n_string_unicode_CapitalU.json\n        \"\"\"\n        self._run_fail_json(\"n_string_unicode_CapitalU.json\")\n\n    def test_n_string_with_trailing_garbage(self):\n        \"\"\"\n        n_string_with_trailing_garbage.json\n        \"\"\"\n        self._run_fail_json(\"n_string_with_trailing_garbage.json\")\n\n    def test_n_structure_100000_opening_array(self):\n        \"\"\"\n        n_structure_100000_opening_arrays.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_100000_opening_arrays.json.xz\")\n\n    def test_n_structure_U_2060_word_joined(self):\n        \"\"\"\n        n_structure_U+2060_word_joined.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_U+2060_word_joined.json\")\n\n    def test_n_structure_UTF8_BOM_no_data(self):\n        \"\"\"\n        n_structure_UTF8_BOM_no_data.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_UTF8_BOM_no_data.json\")\n\n    def test_n_structure_angle_bracket_(self):\n        \"\"\"\n        n_structure_angle_bracket_..json\n        \"\"\"\n        self._run_fail_json(\"n_structure_angle_bracket_..json\")\n\n    def test_n_structure_angle_bracket_null(self):\n        \"\"\"\n        n_structure_angle_bracket_null.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_angle_bracket_null.json\")\n\n    def test_n_structure_array_trailing_garbage(self):\n        \"\"\"\n        n_structure_array_trailing_garbage.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_array_trailing_garbage.json\")\n\n    def test_n_structure_array_with_extra_array_close(self):\n        \"\"\"\n        n_structure_array_with_extra_array_close.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_array_with_extra_array_close.json\")\n\n    def test_n_structure_array_with_unclosed_string(self):\n        \"\"\"\n        n_structure_array_with_unclosed_string.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_array_with_unclosed_string.json\")\n\n    def test_n_structure_ascii_unicode_identifier(self):\n        \"\"\"\n        n_structure_ascii-unicode-identifier.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_ascii-unicode-identifier.json\")\n\n    def test_n_structure_capitalized_True(self):\n        \"\"\"\n        n_structure_capitalized_True.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_capitalized_True.json\")\n\n    def test_n_structure_close_unopened_array(self):\n        \"\"\"\n        n_structure_close_unopened_array.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_close_unopened_array.json\")\n\n    def test_n_structure_comma_instead_of_closing_brace(self):\n        \"\"\"\n        n_structure_comma_instead_of_closing_brace.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_comma_instead_of_closing_brace.json\")\n\n    def test_n_structure_double_array(self):\n        \"\"\"\n        n_structure_double_array.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_double_array.json\")\n\n    def test_n_structure_end_array(self):\n        \"\"\"\n        n_structure_end_array.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_end_array.json\")\n\n    def test_n_structure_incomplete_UTF8_BOM(self):\n        \"\"\"\n        n_structure_incomplete_UTF8_BOM.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_incomplete_UTF8_BOM.json\")\n\n    def test_n_structure_lone_invalid_utf_8(self):\n        \"\"\"\n        n_structure_lone-invalid-utf-8.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_lone-invalid-utf-8.json\")\n\n    def test_n_structure_lone_open_bracket(self):\n        \"\"\"\n        n_structure_lone-open-bracket.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_lone-open-bracket.json\")\n\n    def test_n_structure_no_data(self):\n        \"\"\"\n        n_structure_no_data.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_no_data.json\")\n\n    def test_n_structure_null_byte_outside_string(self):\n        \"\"\"\n        n_structure_null-byte-outside-string.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_null-byte-outside-string.json\")\n\n    def test_n_structure_number_with_trailing_garbage(self):\n        \"\"\"\n        n_structure_number_with_trailing_garbage.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_number_with_trailing_garbage.json\")\n\n    def test_n_structure_object_followed_by_closing_object(self):\n        \"\"\"\n        n_structure_object_followed_by_closing_object.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_object_followed_by_closing_object.json\")\n\n    def test_n_structure_object_unclosed_no_value(self):\n        \"\"\"\n        n_structure_object_unclosed_no_value.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_object_unclosed_no_value.json\")\n\n    def test_n_structure_object_with_comment(self):\n        \"\"\"\n        n_structure_object_with_comment.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_object_with_comment.json\")\n\n    def test_n_structure_object_with_trailing_garbage(self):\n        \"\"\"\n        n_structure_object_with_trailing_garbage.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_object_with_trailing_garbage.json\")\n\n    def test_n_structure_open_array_apostrophe(self):\n        \"\"\"\n        n_structure_open_array_apostrophe.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_open_array_apostrophe.json\")\n\n    def test_n_structure_open_array_comma(self):\n        \"\"\"\n        n_structure_open_array_comma.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_open_array_comma.json\")\n\n    def test_n_structure_open_array_object(self):\n        \"\"\"\n        n_structure_open_array_object.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_open_array_object.json.xz\")\n\n    def test_n_structure_open_array_open_object(self):\n        \"\"\"\n        n_structure_open_array_open_object.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_open_array_open_object.json\")\n\n    def test_n_structure_open_array_open_string(self):\n        \"\"\"\n        n_structure_open_array_open_string.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_open_array_open_string.json\")\n\n    def test_n_structure_open_array_string(self):\n        \"\"\"\n        n_structure_open_array_string.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_open_array_string.json\")\n\n    def test_n_structure_open_object(self):\n        \"\"\"\n        n_structure_open_object.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_open_object.json\")\n\n    def test_n_structure_open_object_close_array(self):\n        \"\"\"\n        n_structure_open_object_close_array.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_open_object_close_array.json\")\n\n    def test_n_structure_open_object_comma(self):\n        \"\"\"\n        n_structure_open_object_comma.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_open_object_comma.json\")\n\n    def test_n_structure_open_object_open_array(self):\n        \"\"\"\n        n_structure_open_object_open_array.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_open_object_open_array.json\")\n\n    def test_n_structure_open_object_open_string(self):\n        \"\"\"\n        n_structure_open_object_open_string.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_open_object_open_string.json\")\n\n    def test_n_structure_open_object_string_with_apostrophe(self):\n        \"\"\"\n        n_structure_open_object_string_with_apostrophes.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_open_object_string_with_apostrophes.json\")\n\n    def test_n_structure_open_ope(self):\n        \"\"\"\n        n_structure_open_open.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_open_open.json\")\n\n    def test_n_structure_single_eacute(self):\n        \"\"\"\n        n_structure_single_eacute.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_single_eacute.json\")\n\n    def test_n_structure_single_star(self):\n        \"\"\"\n        n_structure_single_star.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_single_star.json\")\n\n    def test_n_structure_trailing_(self):\n        \"\"\"\n        n_structure_trailing_#.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_trailing_#.json\")\n\n    def test_n_structure_uescaped_LF_before_string(self):\n        \"\"\"\n        n_structure_uescaped_LF_before_string.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_uescaped_LF_before_string.json\")\n\n    def test_n_structure_unclosed_array(self):\n        \"\"\"\n        n_structure_unclosed_array.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_unclosed_array.json\")\n\n    def test_n_structure_unclosed_array_partial_null(self):\n        \"\"\"\n        n_structure_unclosed_array_partial_null.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_unclosed_array_partial_null.json\")\n\n    def test_n_structure_unclosed_array_unfinished_false(self):\n        \"\"\"\n        n_structure_unclosed_array_unfinished_false.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_unclosed_array_unfinished_false.json\")\n\n    def test_n_structure_unclosed_array_unfinished_true(self):\n        \"\"\"\n        n_structure_unclosed_array_unfinished_true.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_unclosed_array_unfinished_true.json\")\n\n    def test_n_structure_unclosed_object(self):\n        \"\"\"\n        n_structure_unclosed_object.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_unclosed_object.json\")\n\n    def test_n_structure_unicode_identifier(self):\n        \"\"\"\n        n_structure_unicode-identifier.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_unicode-identifier.json\")\n\n    def test_n_structure_whitespace_U_2060_word_joiner(self):\n        \"\"\"\n        n_structure_whitespace_U+2060_word_joiner.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_whitespace_U+2060_word_joiner.json\")\n\n    def test_n_structure_whitespace_formfeed(self):\n        \"\"\"\n        n_structure_whitespace_formfeed.json\n        \"\"\"\n        self._run_fail_json(\"n_structure_whitespace_formfeed.json\")\n\n    def test_i_number_double_huge_neg_exp(self):\n        \"\"\"\n        i_number_double_huge_neg_exp.json\n        \"\"\"\n        self._run_pass_json(\"i_number_double_huge_neg_exp.json\")\n\n    def test_i_number_huge_exp(self):\n        \"\"\"\n        i_number_huge_exp.json\n        \"\"\"\n        self._run_fail_json(\"i_number_huge_exp.json\")\n\n    def test_i_number_neg_int_huge_exp(self):\n        \"\"\"\n        i_number_neg_int_huge_exp.json\n        \"\"\"\n        self._run_fail_json(\"i_number_neg_int_huge_exp.json\")\n\n    def test_i_number_pos_double_huge_exp(self):\n        \"\"\"\n        i_number_pos_double_huge_exp.json\n        \"\"\"\n        self._run_fail_json(\"i_number_pos_double_huge_exp.json\")\n\n    def test_i_number_real_neg_overflow(self):\n        \"\"\"\n        i_number_real_neg_overflow.json\n        \"\"\"\n        self._run_fail_json(\"i_number_real_neg_overflow.json\")\n\n    def test_i_number_real_pos_overflow(self):\n        \"\"\"\n        i_number_real_pos_overflow.json\n        \"\"\"\n        self._run_fail_json(\"i_number_real_pos_overflow.json\")\n\n    def test_i_number_real_underflow(self):\n        \"\"\"\n        i_number_real_underflow.json\n        \"\"\"\n        self._run_pass_json(\"i_number_real_underflow.json\")\n\n    def test_i_number_too_big_neg_int(self):\n        \"\"\"\n        i_number_too_big_neg_int.json\n        \"\"\"\n        self._run_pass_json(\"i_number_too_big_neg_int.json\")\n\n    def test_i_number_too_big_pos_int(self):\n        \"\"\"\n        i_number_too_big_pos_int.json\n        \"\"\"\n        self._run_pass_json(\"i_number_too_big_pos_int.json\")\n\n    def test_i_number_very_big_negative_int(self):\n        \"\"\"\n        i_number_very_big_negative_int.json\n        \"\"\"\n        self._run_pass_json(\"i_number_very_big_negative_int.json\")\n\n    def test_i_object_key_lone_2nd_surrogate(self):\n        \"\"\"\n        i_object_key_lone_2nd_surrogate.json\n        \"\"\"\n        self._run_fail_json(\"i_object_key_lone_2nd_surrogate.json\")\n\n    def test_i_string_1st_surrogate_but_2nd_missing(self):\n        \"\"\"\n        i_string_1st_surrogate_but_2nd_missing.json\n        \"\"\"\n        self._run_fail_json(\"i_string_1st_surrogate_but_2nd_missing.json\")\n\n    def test_i_string_1st_valid_surrogate_2nd_invalid(self):\n        \"\"\"\n        i_string_1st_valid_surrogate_2nd_invalid.json\n        \"\"\"\n        self._run_fail_json(\"i_string_1st_valid_surrogate_2nd_invalid.json\")\n\n    def test_i_string_UTF_16LE_with_BOM(self):\n        \"\"\"\n        i_string_UTF-16LE_with_BOM.json\n        \"\"\"\n        self._run_fail_json(\"i_string_UTF-16LE_with_BOM.json\")\n\n    def test_i_string_UTF_8_invalid_sequence(self):\n        \"\"\"\n        i_string_UTF-8_invalid_sequence.json\n        \"\"\"\n        self._run_fail_json(\"i_string_UTF-8_invalid_sequence.json\")\n\n    def test_i_string_UTF8_surrogate_U_D800(self):\n        \"\"\"\n        i_string_UTF8_surrogate_U+D800.json\n        \"\"\"\n        self._run_fail_json(\"i_string_UTF8_surrogate_U+D800.json\")\n\n    def test_i_string_incomplete_surrogate_and_escape_valid(self):\n        \"\"\"\n        i_string_incomplete_surrogate_and_escape_valid.json\n        \"\"\"\n        self._run_fail_json(\"i_string_incomplete_surrogate_and_escape_valid.json\")\n\n    def test_i_string_incomplete_surrogate_pair(self):\n        \"\"\"\n        i_string_incomplete_surrogate_pair.json\n        \"\"\"\n        self._run_fail_json(\"i_string_incomplete_surrogate_pair.json\")\n\n    def test_i_string_incomplete_surrogates_escape_valid(self):\n        \"\"\"\n        i_string_incomplete_surrogates_escape_valid.json\n        \"\"\"\n        self._run_fail_json(\"i_string_incomplete_surrogates_escape_valid.json\")\n\n    def test_i_string_invalid_lonely_surrogate(self):\n        \"\"\"\n        i_string_invalid_lonely_surrogate.json\n        \"\"\"\n        self._run_fail_json(\"i_string_invalid_lonely_surrogate.json\")\n\n    def test_i_string_invalid_surrogate(self):\n        \"\"\"\n        i_string_invalid_surrogate.json\n        \"\"\"\n        self._run_fail_json(\"i_string_invalid_surrogate.json\")\n\n    def test_i_string_invalid_utf_8(self):\n        \"\"\"\n        i_string_invalid_utf-8.json\n        \"\"\"\n        self._run_fail_json(\"i_string_invalid_utf-8.json\")\n\n    def test_i_string_inverted_surrogates_U_1D11E(self):\n        \"\"\"\n        i_string_inverted_surrogates_U+1D11E.json\n        \"\"\"\n        self._run_fail_json(\"i_string_inverted_surrogates_U+1D11E.json\")\n\n    def test_i_string_iso_latin_1(self):\n        \"\"\"\n        i_string_iso_latin_1.json\n        \"\"\"\n        self._run_fail_json(\"i_string_iso_latin_1.json\")\n\n    def test_i_string_lone_second_surrogate(self):\n        \"\"\"\n        i_string_lone_second_surrogate.json\n        \"\"\"\n        self._run_fail_json(\"i_string_lone_second_surrogate.json\")\n\n    def test_i_string_lone_utf8_continuation_byte(self):\n        \"\"\"\n        i_string_lone_utf8_continuation_byte.json\n        \"\"\"\n        self._run_fail_json(\"i_string_lone_utf8_continuation_byte.json\")\n\n    def test_i_string_not_in_unicode_range(self):\n        \"\"\"\n        i_string_not_in_unicode_range.json\n        \"\"\"\n        self._run_fail_json(\"i_string_not_in_unicode_range.json\")\n\n    def test_i_string_overlong_sequence_2_byte(self):\n        \"\"\"\n        i_string_overlong_sequence_2_bytes.json\n        \"\"\"\n        self._run_fail_json(\"i_string_overlong_sequence_2_bytes.json\")\n\n    def test_i_string_overlong_sequence_6_byte(self):\n        \"\"\"\n        i_string_overlong_sequence_6_bytes.json\n        \"\"\"\n        self._run_fail_json(\"i_string_overlong_sequence_6_bytes.json\")\n\n    def test_i_string_overlong_sequence_6_bytes_null(self):\n        \"\"\"\n        i_string_overlong_sequence_6_bytes_null.json\n        \"\"\"\n        self._run_fail_json(\"i_string_overlong_sequence_6_bytes_null.json\")\n\n    def test_i_string_truncated_utf_8(self):\n        \"\"\"\n        i_string_truncated-utf-8.json\n        \"\"\"\n        self._run_fail_json(\"i_string_truncated-utf-8.json\")\n\n    def test_i_string_utf16BE_no_BOM(self):\n        \"\"\"\n        i_string_utf16BE_no_BOM.json\n        \"\"\"\n        self._run_fail_json(\"i_string_utf16BE_no_BOM.json\")\n\n    def test_i_string_utf16LE_no_BOM(self):\n        \"\"\"\n        i_string_utf16LE_no_BOM.json\n        \"\"\"\n        self._run_fail_json(\"i_string_utf16LE_no_BOM.json\")\n\n    def test_i_structure_500_nested_array(self):\n        \"\"\"\n        i_structure_500_nested_arrays.json\n        \"\"\"\n        try:\n            self._run_pass_json(\"i_structure_500_nested_arrays.json.xz\")\n        except orjson.JSONDecodeError:\n            # fails on serde, passes on yyjson\n            pass\n\n    def test_i_structure_UTF_8_BOM_empty_object(self):\n        \"\"\"\n        i_structure_UTF-8_BOM_empty_object.json\n        \"\"\"\n        self._run_fail_json(\"i_structure_UTF-8_BOM_empty_object.json\")\n"
  },
  {
    "path": "test/test_recursion.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2026)\n\n\nimport pytest\n\nimport orjson\n\n\ndef make_recursive_list_dict(limit: int, envelope_key: str, recurse_key: str):\n    i = 0\n    root = [{envelope_key: i, recurse_key: []}]\n    i += 1\n    while i < limit:\n        sub = [{envelope_key: i, recurse_key: []}]\n        sub[0][recurse_key] = root\n        root = sub\n        i += 1\n    return root\n\n\nclass TestSerializeRecursion:\n    @pytest.mark.parametrize(\"i\", range(1, 127))\n    def test_dumps_recursion_valid_long(self, i):\n        root = make_recursive_list_dict(i, \"🐈\" * 512, \"b\" * 1024)\n        orjson.dumps(root)\n\n    @pytest.mark.parametrize(\"i\", range(1, 127))\n    def test_dumps_recursion_valid_short_1(self, i):\n        root = make_recursive_list_dict(i, \"a\", \"\")\n        orjson.dumps(root)\n\n    @pytest.mark.parametrize(\"i\", range(1, 127))\n    def test_dumps_recursion_valid_short_2(self, i):\n        root = make_recursive_list_dict(i, \"level\", \"next\")\n        orjson.dumps(root)\n\n    def test_dumps_recursion_limit(self):\n        root = make_recursive_list_dict(128, \"level\", \"next\")\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(root)\n"
  },
  {
    "path": "test/test_reentrant.py",
    "content": "# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright Anders Kaseorg (2023)\n\nimport orjson\n\n\nclass C:\n    c: \"C\"\n\n    def __del__(self):\n        orjson.loads('\"' + \"a\" * 10000 + '\"')\n\n\ndef test_reentrant():\n    c = C()\n    c.c = c\n    del c\n\n    orjson.loads(\"[\" + \"[],\" * 1000 + \"[]]\")\n"
  },
  {
    "path": "test/test_roundtrip.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2018-2026)\n\nimport orjson\n\nfrom .util import needs_data, read_fixture_str\n\n\n@needs_data\nclass TestJsonChecker:\n    def _run_roundtrip_json(self, filename, byte_exact=True):\n        data = read_fixture_str(filename, \"roundtrip\")\n        if byte_exact:\n            assert orjson.dumps(orjson.loads(data)) == data.encode(\"utf-8\")\n        else:\n            assert orjson.loads(orjson.dumps(orjson.loads(data))) == orjson.loads(data)\n\n    def test_roundtrip001(self):\n        \"\"\"\n        roundtrip001.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip01.json\")\n\n    def test_roundtrip002(self):\n        \"\"\"\n        roundtrip002.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip02.json\")\n\n    def test_roundtrip003(self):\n        \"\"\"\n        roundtrip003.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip03.json\")\n\n    def test_roundtrip004(self):\n        \"\"\"\n        roundtrip004.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip04.json\")\n\n    def test_roundtrip005(self):\n        \"\"\"\n        roundtrip005.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip05.json\")\n\n    def test_roundtrip006(self):\n        \"\"\"\n        roundtrip006.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip06.json\")\n\n    def test_roundtrip007(self):\n        \"\"\"\n        roundtrip007.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip07.json\")\n\n    def test_roundtrip008(self):\n        \"\"\"\n        roundtrip008.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip08.json\")\n\n    def test_roundtrip009(self):\n        \"\"\"\n        roundtrip009.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip09.json\")\n\n    def test_roundtrip010(self):\n        \"\"\"\n        roundtrip010.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip10.json\")\n\n    def test_roundtrip011(self):\n        \"\"\"\n        roundtrip011.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip11.json\")\n\n    def test_roundtrip012(self):\n        \"\"\"\n        roundtrip012.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip12.json\")\n\n    def test_roundtrip013(self):\n        \"\"\"\n        roundtrip013.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip13.json\")\n\n    def test_roundtrip014(self):\n        \"\"\"\n        roundtrip014.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip14.json\")\n\n    def test_roundtrip015(self):\n        \"\"\"\n        roundtrip015.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip15.json\")\n\n    def test_roundtrip016(self):\n        \"\"\"\n        roundtrip016.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip16.json\")\n\n    def test_roundtrip017(self):\n        \"\"\"\n        roundtrip017.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip17.json\")\n\n    def test_roundtrip018(self):\n        \"\"\"\n        roundtrip018.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip18.json\")\n\n    def test_roundtrip019(self):\n        \"\"\"\n        roundtrip019.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip19.json\")\n\n    def test_roundtrip020(self):\n        \"\"\"\n        roundtrip020.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip20.json\")\n\n    def test_roundtrip021(self):\n        \"\"\"\n        roundtrip021.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip21.json\")\n\n    def test_roundtrip022(self):\n        \"\"\"\n        roundtrip022.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip22.json\")\n\n    def test_roundtrip023(self):\n        \"\"\"\n        roundtrip023.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip23.json\")\n\n    def test_roundtrip024(self):\n        \"\"\"\n        roundtrip024.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip24.json\")\n\n    def test_roundtrip025(self):\n        \"\"\"\n        roundtrip025.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip25.json\")\n\n    def test_roundtrip026(self):\n        \"\"\"\n        roundtrip026.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip26.json\")\n\n    def test_roundtrip027(self):\n        \"\"\"\n        roundtrip027.json\n        \"\"\"\n        self._run_roundtrip_json(\"roundtrip27.json\", byte_exact=False)\n"
  },
  {
    "path": "test/test_sort_keys.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2020-2025)\n\nimport orjson\n\nfrom .util import needs_data, read_fixture_obj\n\n\n@needs_data\nclass TestDictSortKeys:\n    # citm_catalog is already sorted\n    def test_twitter_sorted(self):\n        \"\"\"\n        twitter.json sorted\n        \"\"\"\n        obj = read_fixture_obj(\"twitter.json.xz\")\n        assert list(obj.keys()) != sorted(list(obj.keys()))\n        serialized = orjson.dumps(obj, option=orjson.OPT_SORT_KEYS)\n        val = orjson.loads(serialized)\n        assert list(val.keys()) == sorted(list(val.keys()))\n\n    def test_canada_sorted(self):\n        \"\"\"\n        canada.json sorted\n        \"\"\"\n        obj = read_fixture_obj(\"canada.json.xz\")\n        assert list(obj.keys()) != sorted(list(obj.keys()))\n        serialized = orjson.dumps(obj, option=orjson.OPT_SORT_KEYS)\n        val = orjson.loads(serialized)\n        assert list(val.keys()) == sorted(list(val.keys()))\n\n    def test_github_sorted(self):\n        \"\"\"\n        github.json sorted\n        \"\"\"\n        obj = read_fixture_obj(\"github.json.xz\")\n        for each in obj:\n            assert list(each.keys()) != sorted(list(each.keys()))\n        serialized = orjson.dumps(obj, option=orjson.OPT_SORT_KEYS)\n        val = orjson.loads(serialized)\n        for each in val:\n            assert list(each.keys()) == sorted(list(each.keys()))\n\n    def test_utf8_sorted(self):\n        \"\"\"\n        UTF-8 sorted\n        \"\"\"\n        obj = {\"a\": 1, \"ä\": 2, \"A\": 3}\n        assert list(obj.keys()) != sorted(list(obj.keys()))\n        serialized = orjson.dumps(obj, option=orjson.OPT_SORT_KEYS)\n        val = orjson.loads(serialized)\n        assert list(val.keys()) == sorted(list(val.keys()))\n"
  },
  {
    "path": "test/test_subclass.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2018-2022)\n\nimport collections\nimport json\n\nimport pytest\n\nimport orjson\n\n\nclass SubStr(str):\n    pass\n\n\nclass SubInt(int):\n    pass\n\n\nclass SubDict(dict):\n    pass\n\n\nclass SubList(list):\n    pass\n\n\nclass SubFloat(float):\n    pass\n\n\nclass SubTuple(tuple):\n    pass\n\n\nclass TestSubclass:\n    def test_subclass_str(self):\n        assert orjson.dumps(SubStr(\"zxc\")) == b'\"zxc\"'\n\n    def test_subclass_str_invalid(self):\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(SubStr(\"\\ud800\"))\n\n    def test_subclass_int(self):\n        assert orjson.dumps(SubInt(1)) == b\"1\"\n\n    def test_subclass_int_64(self):\n        for val in (9223372036854775807, -9223372036854775807):\n            assert orjson.dumps(SubInt(val)) == str(val).encode(\"utf-8\")\n\n    def test_subclass_int_53(self):\n        for val in (9007199254740992, -9007199254740992):\n            with pytest.raises(orjson.JSONEncodeError):\n                orjson.dumps(SubInt(val), option=orjson.OPT_STRICT_INTEGER)\n\n    def test_subclass_dict(self):\n        assert orjson.dumps(SubDict({\"a\": \"b\"})) == b'{\"a\":\"b\"}'\n\n    def test_subclass_list(self):\n        assert orjson.dumps(SubList([\"a\", \"b\"])) == b'[\"a\",\"b\"]'\n        ref = [True] * 512\n        assert orjson.loads(orjson.dumps(SubList(ref))) == ref\n\n    def test_subclass_float(self):\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(SubFloat(1.1))\n        assert json.dumps(SubFloat(1.1)) == \"1.1\"\n\n    def test_subclass_tuple(self):\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(SubTuple((1, 2)))\n        assert json.dumps(SubTuple((1, 2))) == \"[1, 2]\"\n\n    def test_namedtuple(self):\n        Point = collections.namedtuple(\"Point\", [\"x\", \"y\"])\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(Point(1, 2))\n\n    def test_subclass_circular_dict(self):\n        obj = SubDict({})\n        obj[\"obj\"] = obj\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(obj)\n\n    def test_subclass_circular_list(self):\n        obj = SubList([])\n        obj.append(obj)\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(obj)\n\n    def test_subclass_circular_nested(self):\n        obj = SubDict({})\n        obj[\"list\"] = SubList([{\"obj\": obj}])\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(obj)\n\n\nclass TestSubclassPassthrough:\n    def test_subclass_str(self):\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(SubStr(\"zxc\"), option=orjson.OPT_PASSTHROUGH_SUBCLASS)\n\n    def test_subclass_int(self):\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(SubInt(1), option=orjson.OPT_PASSTHROUGH_SUBCLASS)\n\n    def test_subclass_dict(self):\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(SubDict({\"a\": \"b\"}), option=orjson.OPT_PASSTHROUGH_SUBCLASS)\n\n    def test_subclass_list(self):\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(SubList([\"a\", \"b\"]), option=orjson.OPT_PASSTHROUGH_SUBCLASS)\n"
  },
  {
    "path": "test/test_transform.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2019-2025)\n\nimport pytest\n\nimport orjson\n\nfrom .util import needs_data, read_fixture_bytes\n\n\ndef _read_file(filename):\n    return read_fixture_bytes(filename, \"transform\").strip(b\"\\n\").strip(b\"\\r\")\n\n\n@needs_data\nclass TestJSONTestSuiteTransform:\n    def _pass_transform(self, filename, reference=None):\n        data = _read_file(filename)\n        assert orjson.dumps(orjson.loads(data)) == (reference or data)\n\n    def _fail_transform(self, filename):\n        data = _read_file(filename)\n        with pytest.raises(orjson.JSONDecodeError):\n            orjson.loads(data)\n\n    def test_number_1(self):\n        \"\"\"\n        number_1.0.json\n        \"\"\"\n        self._pass_transform(\"number_1.0.json\")\n\n    def test_number_1e6(self):\n        \"\"\"\n        number_1e6.json\n        \"\"\"\n        self._pass_transform(\"number_1e6.json\", b\"[1000000.0]\")\n\n    def test_number_1e_999(self):\n        \"\"\"\n        number_1e-999.json\n        \"\"\"\n        self._pass_transform(\"number_1e-999.json\", b\"[0.0]\")\n\n    def test_number_10000000000000000999(self):\n        \"\"\"\n        number_10000000000000000999.json\n        \"\"\"\n        # cannot serialize due to range\n        assert orjson.loads(_read_file(\"number_10000000000000000999.json\")) == [\n            10000000000000000999,\n        ]\n\n    def test_number_1000000000000000(self):\n        \"\"\"\n        number_1000000000000000.json\n        \"\"\"\n        self._pass_transform(\"number_1000000000000000.json\")\n\n    def test_object_key_nfc_nfd(self):\n        \"\"\"\n        object_key_nfc_nfd.json\n        \"\"\"\n        self._pass_transform(\"object_key_nfc_nfd.json\")\n\n    def test_object_key_nfd_nfc(self):\n        \"\"\"\n        object_key_nfd_nfc.json\n        \"\"\"\n        self._pass_transform(\"object_key_nfd_nfc.json\")\n\n    def test_object_same_key_different_values(self):\n        \"\"\"\n        object_same_key_different_values.json\n        \"\"\"\n        self._pass_transform(\"object_same_key_different_values.json\", b'{\"a\":2}')\n\n    def test_object_same_key_same_value(self):\n        \"\"\"\n        object_same_key_same_value.json\n        \"\"\"\n        self._pass_transform(\"object_same_key_same_value.json\", b'{\"a\":1}')\n\n    def test_object_same_key_unclear_values(self):\n        \"\"\"\n        object_same_key_unclear_values.json\n        \"\"\"\n        data = _read_file(\"object_same_key_unclear_values.json\")\n        # varies by backend\n        assert data in (b'{\"a\":-0.0}', b'{\"a\":0, \"a\":-0}')\n\n    def test_string_1_escaped_invalid_codepoint(self):\n        \"\"\"\n        string_1_escaped_invalid_codepoint.json\n        \"\"\"\n        self._fail_transform(\"string_1_escaped_invalid_codepoint.json\")\n\n    def test_string_1_invalid_codepoint(self):\n        \"\"\"\n        string_1_invalid_codepoint.json\n        \"\"\"\n        self._fail_transform(\"string_1_invalid_codepoint.json\")\n\n    def test_string_2_escaped_invalid_codepoints(self):\n        \"\"\"\n        string_2_escaped_invalid_codepoints.json\n        \"\"\"\n        self._fail_transform(\"string_2_escaped_invalid_codepoints.json\")\n\n    def test_string_2_invalid_codepoints(self):\n        \"\"\"\n        string_2_invalid_codepoints.json\n        \"\"\"\n        self._fail_transform(\"string_2_invalid_codepoints.json\")\n\n    def test_string_3_escaped_invalid_codepoints(self):\n        \"\"\"\n        string_3_escaped_invalid_codepoints.json\n        \"\"\"\n        self._fail_transform(\"string_3_escaped_invalid_codepoints.json\")\n\n    def test_string_3_invalid_codepoints(self):\n        \"\"\"\n        string_3_invalid_codepoints.json\n        \"\"\"\n        self._fail_transform(\"string_3_invalid_codepoints.json\")\n\n    def test_string_with_escaped_NULL(self):\n        \"\"\"\n        string_with_escaped_NULL.json\n        \"\"\"\n        self._pass_transform(\"string_with_escaped_NULL.json\")\n"
  },
  {
    "path": "test/test_type.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2018-2026)\n\nimport io\nimport sys\n\nimport pytest\n\nimport orjson\n\nfrom .util import SUPPORTS_BYTEARRAY, SUPPORTS_MEMORYVIEW\n\n\nclass TestType:\n    def test_fragment(self):\n        \"\"\"\n        orjson.JSONDecodeError on fragments\n        \"\"\"\n        for val in (\"n\", \"{\", \"[\", \"t\"):\n            pytest.raises(orjson.JSONDecodeError, orjson.loads, val)\n\n    def test_invalid(self):\n        \"\"\"\n        orjson.JSONDecodeError on invalid\n        \"\"\"\n        for val in ('{\"age\", 44}', \"[31337,]\", \"[,31337]\", \"[]]\", \"[,]\"):\n            pytest.raises(orjson.JSONDecodeError, orjson.loads, val)\n\n    def test_str(self):\n        \"\"\"\n        str\n        \"\"\"\n        for obj, ref in ((\"blah\", b'\"blah\"'), (\"東京\", b'\"\\xe6\\x9d\\xb1\\xe4\\xba\\xac\"')):\n            assert orjson.dumps(obj) == ref\n            assert orjson.loads(ref) == obj\n\n    def test_str_latin1(self):\n        \"\"\"\n        str latin1\n        \"\"\"\n        assert orjson.loads(orjson.dumps(\"üýþÿ\")) == \"üýþÿ\"\n\n    def test_str_long(self):\n        \"\"\"\n        str long\n        \"\"\"\n        for obj in (\"aaaa\" * 1024, \"üýþÿ\" * 1024, \"好\" * 1024, \"�\" * 1024):\n            assert orjson.loads(orjson.dumps(obj)) == obj\n\n    def test_str_2mib(self):\n        ref = '🐈🐈🐈🐈🐈\"üýa0s9999🐈🐈🐈🐈🐈9\\0999\\\\9999' * 1024 * 50\n        assert orjson.loads(orjson.dumps(ref)) == ref\n\n    def test_str_very_long(self):\n        \"\"\"\n        str long enough to trigger overflow in bytecount\n        \"\"\"\n        for obj in (\"aaaa\" * 20000, \"üýþÿ\" * 20000, \"好\" * 20000, \"�\" * 20000):\n            assert orjson.loads(orjson.dumps(obj)) == obj\n\n    def test_str_replacement(self):\n        \"\"\"\n        str roundtrip �\n        \"\"\"\n        assert orjson.dumps(\"�\") == b'\"\\xef\\xbf\\xbd\"'\n        assert orjson.loads(b'\"\\xef\\xbf\\xbd\"') == \"�\"\n\n    def test_str_trailing_4_byte(self):\n        ref = \"うぞ〜😏🙌\"\n        assert orjson.loads(orjson.dumps(ref)) == ref\n\n    def test_str_ascii_control(self):\n        \"\"\"\n        worst case format_escaped_str_with_escapes() allocation\n        \"\"\"\n        ref = \"\\x01\\x1f\" * 1024 * 16\n        assert orjson.loads(orjson.dumps(ref)) == ref\n        assert orjson.loads(orjson.dumps(ref, option=orjson.OPT_INDENT_2)) == ref\n\n    def test_str_escape_quote_0(self):\n        assert orjson.dumps('\"aaaaaaabb') == b'\"\\\\\"aaaaaaabb\"'\n\n    def test_str_escape_quote_1(self):\n        assert orjson.dumps('a\"aaaaaabb') == b'\"a\\\\\"aaaaaabb\"'\n\n    def test_str_escape_quote_2(self):\n        assert orjson.dumps('aa\"aaaaabb') == b'\"aa\\\\\"aaaaabb\"'\n\n    def test_str_escape_quote_3(self):\n        assert orjson.dumps('aaa\"aaaabb') == b'\"aaa\\\\\"aaaabb\"'\n\n    def test_str_escape_quote_4(self):\n        assert orjson.dumps('aaaa\"aaabb') == b'\"aaaa\\\\\"aaabb\"'\n\n    def test_str_escape_quote_5(self):\n        assert orjson.dumps('aaaaa\"aabb') == b'\"aaaaa\\\\\"aabb\"'\n\n    def test_str_escape_quote_6(self):\n        assert orjson.dumps('aaaaaa\"abb') == b'\"aaaaaa\\\\\"abb\"'\n\n    def test_str_escape_quote_7(self):\n        assert orjson.dumps('aaaaaaa\"bb') == b'\"aaaaaaa\\\\\"bb\"'\n\n    def test_str_escape_quote_8(self):\n        assert orjson.dumps('aaaaaaaab\"') == b'\"aaaaaaaab\\\\\"\"'\n\n    def test_str_escape_quote_multi(self):\n        assert (\n            orjson.dumps('aa\"aaaaabbbbbbbbbbbbbbbbbbbb\"bb')\n            == b'\"aa\\\\\"aaaaabbbbbbbbbbbbbbbbbbbb\\\\\"bb\"'\n        )\n\n    def test_str_escape_quote_buffer(self):\n        orjson.dumps(['\"' * 4096] * 1024)\n\n    def test_str_escape_backslash_0(self):\n        assert orjson.dumps(\"\\\\aaaaaaabb\") == b'\"\\\\\\\\aaaaaaabb\"'\n\n    def test_str_escape_backslash_1(self):\n        assert orjson.dumps(\"a\\\\aaaaaabb\") == b'\"a\\\\\\\\aaaaaabb\"'\n\n    def test_str_escape_backslash_2(self):\n        assert orjson.dumps(\"aa\\\\aaaaabb\") == b'\"aa\\\\\\\\aaaaabb\"'\n\n    def test_str_escape_backslash_3(self):\n        assert orjson.dumps(\"aaa\\\\aaaabb\") == b'\"aaa\\\\\\\\aaaabb\"'\n\n    def test_str_escape_backslash_4(self):\n        assert orjson.dumps(\"aaaa\\\\aaabb\") == b'\"aaaa\\\\\\\\aaabb\"'\n\n    def test_str_escape_backslash_5(self):\n        assert orjson.dumps(\"aaaaa\\\\aabb\") == b'\"aaaaa\\\\\\\\aabb\"'\n\n    def test_str_escape_backslash_6(self):\n        assert orjson.dumps(\"aaaaaa\\\\abb\") == b'\"aaaaaa\\\\\\\\abb\"'\n\n    def test_str_escape_backslash_7(self):\n        assert orjson.dumps(\"aaaaaaa\\\\bb\") == b'\"aaaaaaa\\\\\\\\bb\"'\n\n    def test_str_escape_backslash_8(self):\n        assert orjson.dumps(\"aaaaaaaab\\\\\") == b'\"aaaaaaaab\\\\\\\\\"'\n\n    def test_str_escape_backslash_multi(self):\n        assert (\n            orjson.dumps(\"aa\\\\aaaaabbbbbbbbbbbbbbbbbbbb\\\\bb\")\n            == b'\"aa\\\\\\\\aaaaabbbbbbbbbbbbbbbbbbbb\\\\\\\\bb\"'\n        )\n\n    def test_str_escape_backslash_buffer(self):\n        orjson.dumps([\"\\\\\" * 4096] * 1024)\n\n    def test_str_escape_x32_0(self):\n        assert orjson.dumps(\"\\taaaaaaabb\") == b'\"\\\\taaaaaaabb\"'\n\n    def test_str_escape_x32_1(self):\n        assert orjson.dumps(\"a\\taaaaaabb\") == b'\"a\\\\taaaaaabb\"'\n\n    def test_str_escape_x32_2(self):\n        assert orjson.dumps(\"aa\\taaaaabb\") == b'\"aa\\\\taaaaabb\"'\n\n    def test_str_escape_x32_3(self):\n        assert orjson.dumps(\"aaa\\taaaabb\") == b'\"aaa\\\\taaaabb\"'\n\n    def test_str_escape_x32_4(self):\n        assert orjson.dumps(\"aaaa\\taaabb\") == b'\"aaaa\\\\taaabb\"'\n\n    def test_str_escape_x32_5(self):\n        assert orjson.dumps(\"aaaaa\\taabb\") == b'\"aaaaa\\\\taabb\"'\n\n    def test_str_escape_x32_6(self):\n        assert orjson.dumps(\"aaaaaa\\tabb\") == b'\"aaaaaa\\\\tabb\"'\n\n    def test_str_escape_x32_7(self):\n        assert orjson.dumps(\"aaaaaaa\\tbb\") == b'\"aaaaaaa\\\\tbb\"'\n\n    def test_str_escape_x32_8(self):\n        assert orjson.dumps(\"aaaaaaaab\\t\") == b'\"aaaaaaaab\\\\t\"'\n\n    def test_str_escape_x32_multi(self):\n        assert (\n            orjson.dumps(\"aa\\taaaaabbbbbbbbbbbbbbbbbbbb\\tbb\")\n            == b'\"aa\\\\taaaaabbbbbbbbbbbbbbbbbbbb\\\\tbb\"'\n        )\n\n    def test_str_escape_x32_buffer(self):\n        orjson.dumps([\"\\t\" * 4096] * 1024)\n\n    def test_str_emoji(self):\n        ref = \"®️\"\n        assert orjson.loads(orjson.dumps(ref)) == ref\n\n    def test_str_emoji_escape(self):\n        ref = '/\"®️/\"'\n        assert orjson.loads(orjson.dumps(ref)) == ref\n\n    def test_very_long_list(self):\n        orjson.dumps([[]] * 1024 * 16)\n\n    def test_very_long_list_pretty(self):\n        orjson.dumps([[]] * 1024 * 16, option=orjson.OPT_INDENT_2)\n\n    def test_very_long_dict(self):\n        orjson.dumps([{}] * 1024 * 16)\n\n    def test_very_long_dict_pretty(self):\n        orjson.dumps([{}] * 1024 * 16, option=orjson.OPT_INDENT_2)\n\n    def test_very_long_str_empty(self):\n        orjson.dumps([\"\"] * 1024 * 16)\n\n    def test_very_long_str_empty_pretty(self):\n        orjson.dumps([\"\"] * 1024 * 16, option=orjson.OPT_INDENT_2)\n\n    def test_very_long_str_not_empty(self):\n        orjson.dumps([\"a\"] * 1024 * 16)\n\n    def test_very_long_str_not_empty_pretty(self):\n        orjson.dumps([\"a\"] * 1024 * 16, option=orjson.OPT_INDENT_2)\n\n    def test_very_long_bool(self):\n        orjson.dumps([True] * 1024 * 16)\n\n    def test_very_long_bool_pretty(self):\n        orjson.dumps([True] * 1024 * 16, option=orjson.OPT_INDENT_2)\n\n    def test_very_long_int(self):\n        orjson.dumps([(2**64) - 1] * 1024 * 16)\n\n    def test_very_long_int_pretty(self):\n        orjson.dumps([(2**64) - 1] * 1024 * 16, option=orjson.OPT_INDENT_2)\n\n    def test_very_long_float(self):\n        orjson.dumps([sys.float_info.max] * 1024 * 16)\n\n    def test_very_long_float_pretty(self):\n        orjson.dumps([sys.float_info.max] * 1024 * 16, option=orjson.OPT_INDENT_2)\n\n    def test_str_surrogates_loads(self):\n        \"\"\"\n        str unicode surrogates loads()\n        \"\"\"\n        pytest.raises(orjson.JSONDecodeError, orjson.loads, '\"\\ud800\"')\n        pytest.raises(orjson.JSONDecodeError, orjson.loads, '\"\\ud83d\\ude80\"')\n        pytest.raises(orjson.JSONDecodeError, orjson.loads, '\"\\udcff\"')\n        pytest.raises(\n            orjson.JSONDecodeError,\n            orjson.loads,\n            b'\"\\xed\\xa0\\xbd\\xed\\xba\\x80\"',\n        )  # \\ud83d\\ude80\n\n    def test_str_surrogates_dumps(self):\n        \"\"\"\n        str unicode surrogates dumps()\n        \"\"\"\n        pytest.raises(orjson.JSONEncodeError, orjson.dumps, \"\\ud800\")\n        pytest.raises(orjson.JSONEncodeError, orjson.dumps, \"\\ud83d\\ude80\")\n        pytest.raises(orjson.JSONEncodeError, orjson.dumps, \"\\udcff\")\n        pytest.raises(orjson.JSONEncodeError, orjson.dumps, {\"\\ud83d\\ude80\": None})\n        pytest.raises(\n            orjson.JSONEncodeError,\n            orjson.dumps,\n            b\"\\xed\\xa0\\xbd\\xed\\xba\\x80\",\n        )  # \\ud83d\\ude80\n\n    def test_bytes_dumps(self):\n        \"\"\"\n        bytes dumps not supported\n        \"\"\"\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps([b\"a\"])\n\n    def test_bytes_loads(self):\n        \"\"\"\n        bytes loads\n        \"\"\"\n        assert orjson.loads(b\"[]\") == []\n\n    @pytest.mark.skipif(SUPPORTS_BYTEARRAY is False, reason=\"bytearray\")\n    def test_bytearray_loads(self):\n        \"\"\"\n        bytearray loads\n        \"\"\"\n        arr = bytearray()\n        arr.extend(b\"[]\")\n        assert orjson.loads(arr) == []\n\n    @pytest.mark.skipif(SUPPORTS_MEMORYVIEW is True, reason=\"memoryview\")\n    def test_memoryview_loads_supported(self):\n        \"\"\"\n        memoryview loads supported\n        \"\"\"\n        assert orjson.loads(memoryview(b\"[]\")) == []\n\n    @pytest.mark.skipif(SUPPORTS_MEMORYVIEW is False, reason=\"memoryview\")\n    def test_memoryview_loads_unsupported(self):\n        \"\"\"\n        memoryview loads unsupported\n        \"\"\"\n        with pytest.raises(orjson.JSONDecodeError):\n            orjson.loads(memoryview(b\"[]\"))\n\n    @pytest.mark.skipif(SUPPORTS_BYTEARRAY is False, reason=\"bytearray\")\n    def test_bytesio_loads_supported(self):\n        \"\"\"\n        BytesIO loads supported\n        \"\"\"\n        arr = io.BytesIO(b\"[]\")\n        assert orjson.loads(arr.getbuffer()) == []\n\n    @pytest.mark.skipif(SUPPORTS_BYTEARRAY is True, reason=\"bytearray\")\n    def test_bytesio_loads_unsupported(self):\n        \"\"\"\n        BytesIO loads unsupported\n        \"\"\"\n        arr = io.BytesIO(b\"[]\")\n        with pytest.raises(orjson.JSONDecodeError):\n            orjson.loads(arr.getbuffer())\n\n    def test_bool(self):\n        \"\"\"\n        bool\n        \"\"\"\n        for obj, ref in ((True, \"true\"), (False, \"false\")):\n            assert orjson.dumps(obj) == ref.encode(\"utf-8\")\n            assert orjson.loads(ref) == obj\n\n    def test_bool_true_array(self):\n        \"\"\"\n        bool true array\n        \"\"\"\n        obj = [True] * 256\n        ref = (\"[\" + (\"true,\" * 255) + \"true]\").encode(\"utf-8\")\n        assert orjson.dumps(obj) == ref\n        assert orjson.loads(ref) == obj\n\n    def test_bool_false_array(self):\n        \"\"\"\n        bool false array\n        \"\"\"\n        obj = [False] * 256\n        ref = (\"[\" + (\"false,\" * 255) + \"false]\").encode(\"utf-8\")\n        assert orjson.dumps(obj) == ref\n        assert orjson.loads(ref) == obj\n\n    def test_none(self):\n        \"\"\"\n        null\n        \"\"\"\n        obj = None\n        ref = \"null\"\n        assert orjson.dumps(obj) == ref.encode(\"utf-8\")\n        assert orjson.loads(ref) == obj\n\n    def test_int(self):\n        \"\"\"\n        int compact and non-compact\n        \"\"\"\n        obj = [-5000, -1000, -10, -5, -2, -1, 0, 1, 2, 5, 10, 1000, 50000]\n        ref = b\"[-5000,-1000,-10,-5,-2,-1,0,1,2,5,10,1000,50000]\"\n        assert orjson.dumps(obj) == ref\n        assert orjson.loads(ref) == obj\n\n    def test_null_array(self):\n        \"\"\"\n        null array\n        \"\"\"\n        obj = [None] * 256\n        ref = (\"[\" + (\"null,\" * 255) + \"null]\").encode(\"utf-8\")\n        assert orjson.dumps(obj) == ref\n        assert orjson.loads(ref) == obj\n\n    def test_nan_dumps(self):\n        \"\"\"\n        NaN serializes to null\n        \"\"\"\n        assert orjson.dumps(float(\"NaN\")) == b\"null\"\n\n    def test_nan_loads(self):\n        \"\"\"\n        NaN is not valid JSON\n        \"\"\"\n        with pytest.raises(orjson.JSONDecodeError):\n            orjson.loads(\"[NaN]\")\n        with pytest.raises(orjson.JSONDecodeError):\n            orjson.loads(\"[nan]\")\n\n    def test_infinity_dumps(self):\n        \"\"\"\n        Infinity serializes to null\n        \"\"\"\n        assert orjson.dumps(float(\"Infinity\")) == b\"null\"\n\n    def test_infinity_loads(self):\n        \"\"\"\n        Infinity, -Infinity is not valid JSON\n        \"\"\"\n        with pytest.raises(orjson.JSONDecodeError):\n            orjson.loads(\"[infinity]\")\n        with pytest.raises(orjson.JSONDecodeError):\n            orjson.loads(\"[Infinity]\")\n        with pytest.raises(orjson.JSONDecodeError):\n            orjson.loads(\"[-Infinity]\")\n        with pytest.raises(orjson.JSONDecodeError):\n            orjson.loads(\"[-infinity]\")\n\n    def test_int_53(self):\n        \"\"\"\n        int 53-bit\n        \"\"\"\n        for val in (9007199254740991, -9007199254740991):\n            assert orjson.loads(str(val)) == val\n            assert orjson.dumps(val, option=orjson.OPT_STRICT_INTEGER) == str(\n                val,\n            ).encode(\"utf-8\")\n\n    def test_int_53_exc(self):\n        \"\"\"\n        int 53-bit exception on 64-bit\n        \"\"\"\n        for val in (9007199254740992, -9007199254740992):\n            with pytest.raises(orjson.JSONEncodeError):\n                orjson.dumps(val, option=orjson.OPT_STRICT_INTEGER)\n\n    def test_int_53_exc_usize(self):\n        \"\"\"\n        int 53-bit exception on 64-bit usize\n        \"\"\"\n        for val in (9223372036854775808, 18446744073709551615):\n            with pytest.raises(orjson.JSONEncodeError):\n                orjson.dumps(val, option=orjson.OPT_STRICT_INTEGER)\n\n    def test_int_53_exc_128(self):\n        \"\"\"\n        int 53-bit exception on 128-bit\n        \"\"\"\n        val = 2**65\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(val, option=orjson.OPT_STRICT_INTEGER)\n\n    def test_int_64(self):\n        \"\"\"\n        int 64-bit\n        \"\"\"\n        for val in (9223372036854775807, -9223372036854775807):\n            assert orjson.loads(str(val)) == val\n            assert orjson.dumps(val) == str(val).encode(\"utf-8\")\n\n    def test_uint_64(self):\n        \"\"\"\n        uint 64-bit\n        \"\"\"\n        for val in (0, 9223372036854775808, 18446744073709551615):\n            assert orjson.loads(str(val)) == val\n            assert orjson.dumps(val) == str(val).encode(\"utf-8\")\n\n    def test_int_128(self):\n        \"\"\"\n        int 128-bit\n        \"\"\"\n        for val in (18446744073709551616, -9223372036854775809):\n            pytest.raises(orjson.JSONEncodeError, orjson.dumps, val)\n\n    def test_float(self):\n        \"\"\"\n        float\n        \"\"\"\n        assert -1.1234567893 == orjson.loads(\"-1.1234567893\")\n        assert -1.234567893 == orjson.loads(\"-1.234567893\")\n        assert -1.34567893 == orjson.loads(\"-1.34567893\")\n        assert -1.4567893 == orjson.loads(\"-1.4567893\")\n        assert -1.567893 == orjson.loads(\"-1.567893\")\n        assert -1.67893 == orjson.loads(\"-1.67893\")\n        assert -1.7893 == orjson.loads(\"-1.7893\")\n        assert -1.893 == orjson.loads(\"-1.893\")\n        assert -1.3 == orjson.loads(\"-1.3\")\n\n        assert 1.1234567893 == orjson.loads(\"1.1234567893\")\n        assert 1.234567893 == orjson.loads(\"1.234567893\")\n        assert 1.34567893 == orjson.loads(\"1.34567893\")\n        assert 1.4567893 == orjson.loads(\"1.4567893\")\n        assert 1.567893 == orjson.loads(\"1.567893\")\n        assert 1.67893 == orjson.loads(\"1.67893\")\n        assert 1.7893 == orjson.loads(\"1.7893\")\n        assert 1.893 == orjson.loads(\"1.893\")\n        assert 1.3 == orjson.loads(\"1.3\")\n\n    def test_float_precision_loads(self):\n        \"\"\"\n        float precision loads()\n        \"\"\"\n        assert orjson.loads(\"31.245270191439438\") == 31.245270191439438\n        assert orjson.loads(\"-31.245270191439438\") == -31.245270191439438\n        assert orjson.loads(\"121.48791951161945\") == 121.48791951161945\n        assert orjson.loads(\"-121.48791951161945\") == -121.48791951161945\n        assert orjson.loads(\"100.78399658203125\") == 100.78399658203125\n        assert orjson.loads(\"-100.78399658203125\") == -100.78399658203125\n\n    def test_float_precision_dumps(self):\n        \"\"\"\n        float precision dumps()\n        \"\"\"\n        assert orjson.dumps(31.245270191439438) == b\"31.245270191439438\"\n        assert orjson.dumps(-31.245270191439438) == b\"-31.245270191439438\"\n        assert orjson.dumps(121.48791951161945) == b\"121.48791951161945\"\n        assert orjson.dumps(-121.48791951161945) == b\"-121.48791951161945\"\n        assert orjson.dumps(100.78399658203125) == b\"100.78399658203125\"\n        assert orjson.dumps(-100.78399658203125) == b\"-100.78399658203125\"\n\n    def test_float_edge(self):\n        \"\"\"\n        float edge cases\n        \"\"\"\n        assert orjson.dumps(0.8701) == b\"0.8701\"\n\n        assert orjson.loads(\"0.8701\") == 0.8701\n        assert (\n            orjson.loads(\"0.0000000000000000000000000000000000000000000000000123e50\")\n            == 1.23\n        )\n        assert orjson.loads(\"0.4e5\") == 40000.0\n        assert orjson.loads(\"0.00e-00\") == 0.0\n        assert orjson.loads(\"0.4e-001\") == 0.04\n        assert orjson.loads(\"0.123456789e-12\") == 1.23456789e-13\n        assert orjson.loads(\"1.234567890E+34\") == 1.23456789e34\n        assert orjson.loads(\"23456789012E66\") == 2.3456789012e76\n\n    def test_float_notation(self):\n        \"\"\"\n        float notation\n        \"\"\"\n        for val in (\"1.337E40\", \"1.337e+40\", \"1337e40\", \"1.337E-4\"):\n            obj = orjson.loads(val)\n            assert obj == float(val)\n            assert orjson.dumps(val) == (f'\"{val}\"').encode(\"utf-8\")\n\n    def test_list(self):\n        \"\"\"\n        list\n        \"\"\"\n        obj = [\"a\", \"😊\", True, {\"b\": 1.1}, 2]\n        ref = '[\"a\",\"😊\",true,{\"b\":1.1},2]'\n        assert orjson.dumps(obj) == ref.encode(\"utf-8\")\n        assert orjson.loads(ref) == obj\n\n    def test_tuple(self):\n        \"\"\"\n        tuple\n        \"\"\"\n        obj = (\"a\", \"😊\", True, {\"b\": 1.1}, 2)\n        ref = '[\"a\",\"😊\",true,{\"b\":1.1},2]'\n        assert orjson.dumps(obj) == ref.encode(\"utf-8\")\n        assert orjson.loads(ref) == list(obj)\n\n    def test_object(self):\n        \"\"\"\n        object() dumps()\n        \"\"\"\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(object())\n"
  },
  {
    "path": "test/test_typeddict.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2019-2023)\n\nimport orjson\n\ntry:\n    from typing import TypedDict  # type: ignore\nexcept ImportError:\n    from typing_extensions import TypedDict\n\n\nclass TestTypedDict:\n    def test_typeddict(self):\n        \"\"\"\n        dumps() TypedDict\n        \"\"\"\n\n        class TypedDict1(TypedDict):\n            a: str\n            b: int\n\n        obj = TypedDict1(a=\"a\", b=1)\n        assert orjson.dumps(obj) == b'{\"a\":\"a\",\"b\":1}'\n"
  },
  {
    "path": "test/test_uuid.py",
    "content": "# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# Copyright ijl (2020-2025), Rami Chowdhury (2020)\n\nimport uuid\n\nimport pytest\n\nimport orjson\n\n\nclass TestUUID:\n    def test_uuid_immutable(self):\n        \"\"\"\n        UUID objects are immutable\n        \"\"\"\n        val = uuid.uuid4()\n        with pytest.raises(TypeError):\n            val.int = 1  # type: ignore\n        with pytest.raises(TypeError):\n            val.int = None  # type: ignore\n\n    def test_uuid_int(self):\n        \"\"\"\n        UUID.int is a 128-bit integer\n        \"\"\"\n        val = uuid.UUID(\"7202d115-7ff3-4c81-a7c1-2a1f067b1ece\")\n        assert isinstance(val.int, int)\n        assert val.int >= 2**64\n        assert val.int < 2**128\n        assert val.int == 151546616840194781678008611711208857294\n\n    def test_uuid_overflow(self):\n        \"\"\"\n        UUID.int can't trigger errors in _PyLong_AsByteArray\n        \"\"\"\n        with pytest.raises(ValueError):\n            uuid.UUID(int=2**128)\n        with pytest.raises(ValueError):\n            uuid.UUID(int=-1)\n\n    def test_uuid_subclass(self):\n        \"\"\"\n        UUID subclasses are not serialized\n        \"\"\"\n\n        class AUUID(uuid.UUID):\n            pass\n\n        with pytest.raises(orjson.JSONEncodeError):\n            orjson.dumps(AUUID(\"{12345678-1234-5678-1234-567812345678}\"))\n\n    def test_serializes_withopt(self):\n        \"\"\"\n        dumps() accepts deprecated OPT_SERIALIZE_UUID\n        \"\"\"\n        assert (\n            orjson.dumps(\n                uuid.UUID(\"7202d115-7ff3-4c81-a7c1-2a1f067b1ece\"),\n                option=orjson.OPT_SERIALIZE_UUID,\n            )\n            == b'\"7202d115-7ff3-4c81-a7c1-2a1f067b1ece\"'\n        )\n\n    def test_nil_uuid(self):\n        assert (\n            orjson.dumps(uuid.UUID(\"00000000-0000-0000-0000-000000000000\"))\n            == b'\"00000000-0000-0000-0000-000000000000\"'\n        )\n\n    def test_all_ways_to_create_uuid_behave_equivalently(self):\n        # Note that according to the docstring for the uuid.UUID class, all the\n        # forms below are equivalent -- they end up with the same value for\n        # `self.int`, which is all that really matters\n        uuids = [\n            uuid.UUID(\"{12345678-1234-5678-1234-567812345678}\"),\n            uuid.UUID(\"12345678123456781234567812345678\"),\n            uuid.UUID(\"urn:uuid:12345678-1234-5678-1234-567812345678\"),\n            uuid.UUID(bytes=b\"\\x12\\x34\\x56\\x78\" * 4),\n            uuid.UUID(\n                bytes_le=b\"\\x78\\x56\\x34\\x12\\x34\\x12\\x78\\x56\\x12\\x34\\x56\\x78\\x12\\x34\\x56\\x78\",\n            ),\n            uuid.UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678)),\n            uuid.UUID(int=0x12345678123456781234567812345678),\n        ]\n        result = orjson.dumps(uuids)\n        canonical_uuids = [f'\"{u!s}\"' for u in uuids]\n        serialized = (\"[{}]\".format(\",\".join(canonical_uuids))).encode(\"utf8\")\n        assert result == serialized\n\n    def test_serializes_correctly_with_leading_zeroes(self):\n        instance = uuid.UUID(int=0x00345678123456781234567812345678)\n        assert orjson.dumps(instance) == (f'\"{instance!s}\"').encode(\"utf-8\")\n\n    def test_all_uuid_creation_functions_create_serializable_uuids(self):\n        uuids = (\n            uuid.uuid1(),\n            uuid.uuid3(uuid.NAMESPACE_DNS, \"python.org\"),\n            uuid.uuid4(),\n            uuid.uuid5(uuid.NAMESPACE_DNS, \"python.org\"),\n        )\n        for val in uuids:\n            assert orjson.dumps(val) == f'\"{val}\"'.encode(\"utf-8\")\n"
  },
  {
    "path": "test/util.py",
    "content": "# SPDX-License-Identifier: MPL-2.0\n# Copyright ijl (2018-2026)\n\nimport lzma\nimport os\nimport sys\nimport sysconfig\nfrom pathlib import Path\nfrom typing import Any\n\nIS_FREETHREADING = sysconfig.get_config_var(\"Py_GIL_DISABLED\")\n\nSUPPORTS_MEMORYVIEW = sys.implementation == \"cpython\" and not IS_FREETHREADING\n\nSUPPORTS_BYTEARRAY = not IS_FREETHREADING\n\nSUPPORTS_GETREFCOUNT = sys.implementation == \"cpython\"\n\nnumpy = None  # type: ignore\nif not IS_FREETHREADING:\n    try:\n        import numpy  # type: ignore # noqa: F401\n    except ImportError:\n        pass\n\npandas = None  # type: ignore\nif not IS_FREETHREADING:\n    try:\n        import pandas  # type: ignore # noqa: F401\n    except ImportError:\n        pass\n\nimport pytest\n\nimport orjson\n\ndata_dir = os.path.join(os.path.dirname(__file__), \"../data\")\n\nSTR_CACHE: dict[str, str] = {}\n\nOBJ_CACHE: dict[str, Any] = {}\n\n\ndef read_fixture_bytes(filename, subdir=None):\n    if subdir is None:\n        path = Path(data_dir, filename)\n    else:\n        path = Path(data_dir, subdir, filename)\n    if path.suffix == \".xz\":\n        contents = lzma.decompress(path.read_bytes())\n    else:\n        contents = path.read_bytes()\n    return contents\n\n\ndef read_fixture_str(filename, subdir=None):\n    if filename not in STR_CACHE:\n        STR_CACHE[filename] = read_fixture_bytes(filename, subdir).decode(\"utf-8\")\n    return STR_CACHE[filename]\n\n\ndef read_fixture_obj(filename):\n    if filename not in OBJ_CACHE:\n        OBJ_CACHE[filename] = orjson.loads(read_fixture_str(filename))\n    return OBJ_CACHE[filename]\n\n\nneeds_data = pytest.mark.skipif(\n    not Path(data_dir).exists(),\n    reason=\"Test depends on ./data dir that contains fixtures\",\n)\n"
  }
]