Compare commits

..

71 Commits

Author SHA1 Message Date
Daniel Lemire 5ed1044056 4.0.7 2025-09-30 11:26:03 -04:00
Francisco Geiman Thiesen 62913867ff Merge pull request #2475 from simdjson/francisco/extract_from
Adding extract_from functionality + unit tests
2025-09-29 20:34:35 -07:00
Francisco Geiman Thiesen 6700d48b57 Merge pull request #2480 from simdjson/francisco/extract_from3
minor tweaks... ;-)
2025-09-29 13:54:05 -07:00
Francisco Geiman Thiesen b5577d5e85 Merge branch 'master' into francisco/extract_from 2025-09-29 12:46:48 -07:00
wszqkzqk b84a4ec2b9 Fix: Correct narrowing conversion in lsx string parsing (#2481)
Resolves a build failure on the loong64 architecture caused by a narrowing conversion error.

The compiler, with the -Werror=narrowing flag, was flagging the implicit conversion from 'int' (the return
type of to_bitmask()) to 'uint64_t'.

This is fixed by adding an explicit static_cast to uint64_t in include/simdjson/lsx/stringparsing_defs.h.

Signed-off-by: Zhou Qiankang <wszqkzqk@qq.com>
2025-09-29 11:57:06 -04:00
Daniel Lemire 1638a185f7 minor tweaks... ;-) 2025-09-29 11:12:37 -04:00
Francisco Geiman Thiesen 6fe450f5ce Updateing single_header 2025-09-29 03:44:29 -07:00
Francisco Geiman Thiesen c7b70de070 Merge branch 'master' into francisco/extract_from 2025-09-29 03:23:02 -07:00
Francisco Geiman Thiesen 3279fbd55b Merge pull request #2474 from simdjson/complete_extract_into
this completes the extract_into work.
2025-09-29 03:12:20 -07:00
Francisco Geiman Thiesen 66e64e0e5f Merge branch 'master' into francisco/extract_from 2025-09-29 03:02:12 -07:00
Daniel Lemire 03f81e66af updating single header 2025-09-27 12:26:04 -04:00
Daniel Lemire e3b7eddb37 fixing off-by-one mistake in the documentation (#2477) 2025-09-27 12:19:44 -04:00
Daniel Lemire 99c4ba6e8f tweak 2025-09-26 23:44:42 -04:00
Francisco Geiman Thiesen 6aa7eea334 Adding extract_from functionality + unit tests 2025-09-26 19:48:16 -07:00
Daniel Lemire 6a47cda07f guarding 2025-09-26 22:34:36 -04:00
Daniel Lemire 617c69e104 completing doc 2025-09-26 21:33:10 -04:00
Daniel Lemire 625adceb24 updating single-header 2025-09-26 21:29:28 -04:00
Daniel Lemire bd0e9c1336 tweak 2025-09-26 21:04:53 -04:00
Daniel Lemire 7bf82b02d5 this completes the extra_into work. 2025-09-26 21:00:46 -04:00
Francisco Geiman Thiesen 88a1b3e83b Merge pull request #2471 from simdjson/francisco/extract_into
Adding extract_into functionality + test (targets simdjson >= 4.0 as it relies on reflection)
2025-09-26 01:29:33 -07:00
Francisco Geiman Thiesen c72954eade Addressing reviews. 2025-09-25 21:08:38 -07:00
Francisco Geiman Thiesen 4456a10469 Francisco/using iterators for containers (#2470)
* Using iterators instead of subscript operators and size. This helps us work with a broader range of containers.

* Adding list test

* Using std::ranges::input_range<T> as suggested by moisrex
2025-09-25 17:30:42 -04:00
Francisco Geiman Thiesen d8ed2417ad Adding coverage for extract_into with types that have custom serialization 2025-09-25 03:35:46 -07:00
Francisco Geiman Thiesen 5517df7aee Adding extract_into functionality + test 2025-09-24 22:58:23 -07:00
evbse 6e618b0805 Improve DOM implementation (#2434) 2025-09-21 11:26:33 -06:00
Pavel Novikov bde288a623 Fixed string_builder::operator std::string() (#2465)
* clang format

* fixed `string_builder::operator std::string()`

* fixed variable shadowing error false positive
2025-09-21 11:25:42 -06:00
Daniel Lemire b2932d1b8f release candidate 4.0.6 (#2464) 2025-09-21 08:13:48 -06:00
Daniel Lemire a7811090ef fixing issue 2458 (#2461) 2025-09-20 22:23:09 -06:00
Daniel Lemire 3320885fac Fixing issue 2462 (#2463)
* fun

* progress

* completing the documentation
2025-09-20 22:22:57 -06:00
Daniel Lemire 786c68b158 release 4.0.5 2025-09-18 15:17:32 -06:00
Daniel Lemire 703ef54bd9 allow string reuse (#2454)
* allow string reuse

* portability fix

* using data and not begin
2025-09-18 15:16:38 -06:00
Daniel Lemire 2526068e2f Add mamba link to README 2025-09-18 09:22:03 -06:00
Daniel Lemire ddc7b8c7dd update 2025-09-17 18:59:06 -06:00
Daniel Lemire d8f90bdd14 modifying simdjson::from to avoid exceptions when needed. (#2452)
* modifying simdjson::from to avoid exceptions when needed.

* moved the function

* moving the strings.

* more moving around

* updating cmake version in ci
2025-09-17 18:58:25 -06:00
Daniel Lemire e38a4923e5 adding keys as templates in builder (#2453)
* adding keys as templates in builder

* more guarding

* cmake update in ci

* guarding.

* guarding
2025-09-17 18:58:05 -06:00
Dirk Stolle e6dfa2e0ed remove trailing whitespace + fix typos (#2451) 2025-09-16 22:41:14 -06:00
Daniel Lemire 1f369ef210 minor patch which allows us to pass mutable strings to simdjson::from… (#2448)
* minor patch which allows us to pass mutable strings to simdjson::from and fix
an issue with ambiguous integrals

* compatibility patch.
2025-09-15 22:22:25 -06:00
Daniel Lemire 22dcdc9f1e Update README.md 2025-09-15 18:52:15 -06:00
Dirk Stolle dda2dafa30 fix some typos (#2446) 2025-09-15 18:23:13 -06:00
Daniel Lemire 72e9d44e10 fixing indent 2025-09-15 17:08:12 -06:00
Daniel Lemire 8aae14931d release candidate 4.0.2 (#2441)
* release candidate 4.0.2

* more fixes

* fixing typos

* adding macro check
2025-09-15 09:17:43 -06:00
Daniel Lemire ef3d1ac25f fixing 2440 2025-09-14 08:09:27 -06:00
Daniel Lemire 9292480a9b removing leftover <experimental/...> (#2438) 2025-09-14 08:00:26 -06:00
Daniel Lemire 611ea97dbd Add C++26 reflection example link to README 2025-09-12 21:22:45 -04:00
Daniel Lemire f249e7e128 patch release 2025-09-12 19:26:58 -04:00
Marian Klymov 44fddaa807 Replace POSITION_INDEPENDENT_CODE with INTERFACE_POSITION_INDEPENDENT_CODE for older CMake (#2437) 2025-09-12 19:26:22 -04:00
Daniel Lemire be16e1ae04 removing space 2025-09-11 20:58:31 -04:00
Daniel Lemire 124a33c160 Update JSON example and add section on special cases
Removed code block formatting for JSON example and added a section header for special cases.
2025-09-11 19:32:38 -04:00
Daniel Lemire a0b870e9c2 Add example for deserializing 'Car' type
Updated the documentation to include an example of deserializing a 'Car' type using simdjson.
2025-09-11 19:31:15 -04:00
Daniel Lemire 68699eb73c release 4.0.0 2025-09-11 19:25:10 -04:00
Daniel Lemire 06453f1637 Remove Fuzzing Status badge from README
Removed Fuzzing Status badge from README.
2025-09-09 18:44:21 -04:00
Daniel Lemire eb828d97ba fixing a few typos 2025-09-09 18:41:00 -04:00
Daniel Lemire 00f84fb448 simplify 2025-09-09 14:21:14 -04:00
Daniel Lemire 5bf0954c6e hop 2025-09-08 19:26:34 -04:00
Daniel Lemire 3056d54fa3 adding instructions 2025-09-08 17:47:14 -04:00
Daniel Lemire 241b9f6ea7 adding bad/good player test 2025-09-08 17:04:52 -04:00
Daniel Lemire 015daad6a9 Merge branch 'master' of github.com:simdjson/simdjson 2025-09-05 19:50:05 -04:00
Daniel Lemire fc3b7766c0 typo fix 2025-09-05 19:49:57 -04:00
Daniel Lemire b5c78288e5 can we run the address sanitizer under VS in CI ? (#2435)
* can we run the address sanitizer under VS in CI ?

* fixed typo
2025-09-05 18:32:15 -04:00
Daniel Lemire bd86bb0cfb adding UTF-8 test 2025-09-05 14:56:02 -04:00
Daniel Lemire 4840a0347c extra documentation. 2025-09-05 14:44:53 -04:00
Daniel Lemire 7f68baec1e minor tweak 2025-09-05 08:01:04 -04:00
Daniel Lemire e2ea5fb8de This PR adds -> and * operators to our error types and it (#2433)
improves slightly the documentation.
2025-09-04 22:35:01 -04:00
Daniel Lemire 7dfd165ecd Merge branch 'master' of github.com:simdjson/simdjson 2025-09-04 09:46:07 -04:00
Daniel Lemire 4dfa0a2407 guarding 2025-09-03 16:45:09 -04:00
Daniel Lemire e252a21f65 removing expand workaround (#2431)
* removing expland workaround

* minor fixes
2025-09-03 13:30:35 -04:00
Daniel Lemire 89f2b634df guarding from benchmark + rvv 2025-09-02 13:06:25 -04:00
Daniel Lemire addca203d5 adding a 'car builder' benchmark (#2428)
Co-authored-by: Daniel Lemire <dlemire@lemire.me>
2025-08-26 09:16:18 -04:00
Felipe Monteiro 1825d7e88c Add "node:" prefix on fs import (#2426) 2025-08-25 10:21:13 -04:00
Daniel Lemire f87d6af3e9 fix issue 2424 (#2425) 2025-08-24 16:04:56 -04:00
Daniel Lemire 8fff57578c let us default on developer mode when building with VScode 2025-08-23 20:59:58 -04:00
125 changed files with 12621 additions and 177514 deletions
+49 -4
View File
@@ -1,8 +1,53 @@
Short title (summary):
Description
- What did you change and why? (1-3 sentences)
- Issue reproduced / related issue: link the issue if relevant (e.g. #123)
Type of change
- [ ] Bug fix
- [ ] New feature
- [ ] Refactor / cleanup
- [ ] Documentation / tests
- [ ] Other (please describe):
How to verify / test
- Add additional tests to verify bugs or new features.
- If you claim performance gains, you should provide benchmark numbers using high quality benchmarking code.
Our tests check whether you have introduced trailing white space. If such a test fails, please check the "artifacts button" above, which if you click it gives a link to a downloadable file to help you identify the issue. You can also run scripts/remove_trailing_whitespace.sh locally if you have a bash shell and the sed command available on your system.
Please read before contributing:
- CONTRIBUTING: https://github.com/simdjson/simdjson/blob/master/CONTRIBUTING.md
- HACKING: https://github.com/simdjson/simdjson/blob/master/HACKING.md
If you plan to contribute to simdjson, please read our
CONTRIBUTING guide: https://github.com/simdjson/simdjson/blob/master/CONTRIBUTING.md and our
HACKING guide: https://github.com/simdjson/simdjson/blob/master/HACKING.md
If you can, we recommend running our tests with the sanitizers turned on.
For non-Visual Studio users, it is as easy as doing:
```bash
cmake -B build -D SIMDJSON_SANITIZE=ON -D SIMDJSON_DEVELOPER_MODE=ON
cmake --build build
ctest --test-dir build
```
Our CI checks, among other things, for trailing whitespace. If a test fails for that reason,
use the "artifacts" button to download the artifact and inspect the problematic lines,
or run `scripts/remove_trailing_whitespace.sh` locally if you have a bash shell and `sed`.
Checklist before submitting
- [ ] I added/updated tests covering my change (if applicable)
- [ ] Code builds locally and passes my check
- [ ] Documentation / README updated if needed
- [ ] Commits are atomic and messages are clear
- [ ] I linked the related issue (if applicable)
Final notes
- For large PRs, prefer smaller incremental PRs or request staged review.
Thanks for the contribution!
+29
View File
@@ -0,0 +1,29 @@
name: Ubuntu rvv VLEN=1024 (clang 18)
on:
push:
branches:
- master
pull_request:
branches:
- master
jobs:
build:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- name: Install packages
run: |
sudo apt-get update -q -y
sudo apt-get install -y cmake make g++-riscv64-linux-gnu qemu-user-static clang-18
- name: Build
run: |
CXX=clang++-18 CXXFLAGS="--target=riscv64-linux-gnu -march=rv64gcv_zvbb" \
cmake --toolchain=cmake/toolchains-ci/riscv64-linux-gnu.cmake -DCMAKE_BUILD_TYPE=Release -B build
cmake --build build/ -j$(nproc)
- name: Test VLEN=1024
run: |
export QEMU_LD_PREFIX="/usr/riscv64-linux-gnu"
export QEMU_CPU="rv64,v=on,zvbb=on,vlen=1024,rvv_ta_all_1s=on,rvv_ma_all_1s=on"
ctest --timeout 1800 --output-on-failure --test-dir build -j $(nproc)
+29
View File
@@ -0,0 +1,29 @@
name: Ubuntu rvv VLEN=128 (clang 17)
on:
push:
branches:
- master
pull_request:
branches:
- master
jobs:
build:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- name: Install packages
run: |
sudo apt-get update -q -y
sudo apt-get install -y cmake make g++-riscv64-linux-gnu qemu-user-static clang-17
- name: Build
run: |
CXX=clang++-17 CXXFLAGS="--target=riscv64-linux-gnu -march=rv64gcv" \
cmake --toolchain=cmake/toolchains-ci/riscv64-linux-gnu.cmake -DCMAKE_BUILD_TYPE=Release -B build
cmake --build build/ -j$(nproc)
- name: Test VLEN=128
run: |
export QEMU_LD_PREFIX="/usr/riscv64-linux-gnu"
export QEMU_CPU="rv64,v=on,vlen=128,rvv_ta_all_1s=on,rvv_ma_all_1s=on"
ctest --timeout 1800 --output-on-failure --test-dir build -j $(nproc)
+29
View File
@@ -0,0 +1,29 @@
name: Ubuntu rvv VLEN=256 (gcc 14)
on:
push:
branches:
- master
pull_request:
branches:
- master
jobs:
build:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- name: Install packages
run: |
sudo apt-get update -q -y
sudo apt-get install -y cmake make g++-14-riscv64-linux-gnu qemu-user-static
- name: Build
run: |
CXX=riscv64-linux-gnu-g++-14 CXXFLAGS=-march=rv64gcv \
cmake --toolchain=cmake/toolchains-ci/riscv64-linux-gnu.cmake -DCMAKE_BUILD_TYPE=Release -B build
cmake --build build/ -j$(nproc)
- name: Test VLEN=256
run: |
export QEMU_LD_PREFIX="/usr/riscv64-linux-gnu"
export QEMU_CPU="rv64,v=on,zvbb=on,vlen=256,rvv_ta_all_1s=on,rvv_ma_all_1s=on"
ctest --timeout 1800 --output-on-failure --test-dir build -j $(nproc)
@@ -0,0 +1,22 @@
name: Ubuntu 24.04 CI (CXX 20, noexcept)
on: [push, pull_request]
jobs:
ubuntu-build:
if: >-
! contains(toJSON(github.event.commits.*.message), '[skip ci]') &&
! contains(toJSON(github.event.commits.*.message), '[skip github]')
runs-on: ubuntu-24.04
strategy:
matrix:
cxx: [g++-13, clang++-16]
steps:
- uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 # v4.1.6
- name: Prepare
run: cmake -DSIMDJSON_CXX_STANDARD=20 -DSIMDJSON_EXCEPTIONS=OFF -DSIMDJSON_DEVELOPER_MODE=ON -B build
env:
CXX: ${{matrix.cxx}}
- name: Build
run: cmake --build build -j=2
- name: Test
run: ctest --output-on-failure --test-dir build
+1 -1
View File
@@ -31,4 +31,4 @@ jobs:
echo -e '#include <simdjson.h>\nint main(int argc,char**argv) {simdjson::dom::parser parser;simdjson::dom::element tweets = parser.load(argv[1]); }' > tmp.cpp && c++ -Idestination/include -Ldestination/lib -std=c++17 -Wl,-rpath,destination/lib -o linkandrun tmp.cpp -lsimdjson && ./linkandrun jsonexamples/twitter.json &&
mkdir testfindpackage &&
cd testfindpackage &&
echo -e 'cmake_minimum_required(VERSION 3.1)\nproject(simdjsontester)\nset(CMAKE_CXX_STANDARD 17)\nfind_package(simdjson REQUIRED)'> CMakeLists.txt && mkdir build && cd build && cmake -DCMAKE_INSTALL_PREFIX:PATH=../destination .. && cmake --build .
echo -e 'cmake_minimum_required(VERSION 3.14)\nproject(simdjsontester)\nset(CMAKE_CXX_STANDARD 17)\nfind_package(simdjson REQUIRED)'> CMakeLists.txt && mkdir build && cd build && cmake -DCMAKE_INSTALL_PREFIX:PATH=../destination .. && cmake --build .
+1 -1
View File
@@ -31,4 +31,4 @@ jobs:
echo -e '#include <simdjson.h>\nint main(int argc,char**argv) {simdjson::dom::parser parser;simdjson::dom::element tweets = parser.load(argv[1]); }' > tmp.cpp && c++ -Idestination/include -Ldestination/lib -std=c++17 -Wl,-rpath,destination/lib -o linkandrun tmp.cpp -lsimdjson && ./linkandrun jsonexamples/twitter.json &&
mkdir testfindpackage &&
cd testfindpackage &&
echo -e 'cmake_minimum_required(VERSION 3.1)\nproject(simdjsontester)\nset(CMAKE_CXX_STANDARD 17)\nfind_package(simdjson REQUIRED)'> CMakeLists.txt && mkdir build && cd build && cmake -DCMAKE_INSTALL_PREFIX:PATH=../destination .. && cmake --build .
echo -e 'cmake_minimum_required(VERSION 3.14)\nproject(simdjsontester)\nset(CMAKE_CXX_STANDARD 17)\nfind_package(simdjson REQUIRED)'> CMakeLists.txt && mkdir build && cd build && cmake -DCMAKE_INSTALL_PREFIX:PATH=../destination .. && cmake --build .
+30
View File
@@ -0,0 +1,30 @@
name: VS17-CI-SANITIZE
on: [push, pull_request]
jobs:
ci:
if: >-
! contains(toJSON(github.event.commits.*.message), '[skip ci]') &&
! contains(toJSON(github.event.commits.*.message), '[skip github]')
name: windows-vs17
runs-on: windows-latest
strategy:
fail-fast: false
matrix:
include:
- {gen: Visual Studio 17 2022, arch: x64, shared: OFF, build_type: Debug}
- {gen: Visual Studio 17 2022, arch: x64, shared: OFF, build_type: Release}
- {gen: Visual Studio 17 2022, arch: x64, shared: OFF, build_type: RelWithDebInfo}
steps:
- name: checkout
uses: actions/checkout@v4
- name: Configure
run: |
cmake -G "${{matrix.gen}}" -A ${{matrix.arch}} -DSANITIZE=ON -DSIMDJSON_DEVELOPER_MODE=ON -DSIMDJSON_COMPETITION=OFF -DBUILD_SHARED_LIBS=${{matrix.shared}} -B build
- name: Build
run: cmake --build build --config ${{matrix.build_type}} --verbose
- name: Run tests
run: |
cd build
ctest -C ${{matrix.build_type}} -LE explicitonly --output-on-failure
-15
View File
@@ -107,18 +107,3 @@ objs
# clangd
.cache
# Ablation study results
ablation/results/*.csv
ablation/results/*.txt
# Unified benchmark binary
benchmark/unified_benchmark
# Rust build artifacts
*.rlib
*.rmeta
benchmark/static_reflect/serde-benchmark/target/
**/target/debug/
**/target/release/
Cargo.lock
+3
View File
@@ -3,6 +3,9 @@
{"column": 95 },
{"column": 120 }
],
"cmake.configureArgs": [
"-DSIMDJSON_DEVELOPER_MODE=ON"
],
"files.trimTrailingWhitespace": true,
"files.associations": {
".clangd": "yaml",
-108
View File
@@ -1,108 +0,0 @@
# Benchmark Methodology
## Overview
This document describes the methodology used for the JSON parsing and serialization benchmarks.
## Test Environment
### Compiler and Flags
- **Compiler**: Clang 21.0.0 with C++26 support
- **Optimization**: `-O3 -march=native`
- **Reflection Support**: `-freflection -fexpansion-statements -stdlib=libc++`
- **Build System**: CMake with unified benchmark executable
### Hardware
Tests were run on Linux (aarch64) with results measured in MB/s throughput.
## Datasets
### Twitter Dataset
- **File**: `jsonexamples/twitter.json`
- **Size**: 631,515 bytes
- **Content**: Array of tweet objects with nested user information
- **Characteristics**: String-heavy (92%), moderate integer content (15%), minimal floats (<0.05%)
### CITM Catalog Dataset
- **File**: `jsonexamples/citm_catalog.json`
- **Size**: 1,727,204 bytes
- **Content**: Event catalog with performances, venues, and pricing
- **Characteristics**: Complex nested structure with maps and arrays
## Benchmark Design
### Iterations
- **Twitter**: 1,000 iterations per benchmark
- **CITM**: 500 iterations per benchmark
- **Warmup**: 10% of main iterations (100 for Twitter, 50 for CITM)
### Memory Management
- **String Builder Reuse**: Serialization benchmarks reuse the same string_builder instance across iterations
- **Parser Instance**: Each parsing iteration uses a fresh parser instance for realistic performance
- **Buffer Clearing**: Buffers are cleared (not deallocated) between iterations to maintain capacity
### Timing Methodology
1. Warmup phase to stabilize caches and branch predictors
2. Timed phase measures wall clock time for all iterations
3. Throughput calculated as: `(data_size * iterations) / total_time`
4. Results reported in MB/s and microseconds per iteration
## Libraries and Versions
### Core Libraries
- **simdjson**: Latest with C++26 reflection support
- **nlohmann/json**: v3.11.2
- **RapidJSON**: v1.1.0
- **yyjson**: v0.8.0
### Optional Libraries
- **Serde (Rust)**: serde_json v1.0 via FFI (parsing and serialization)
## Implementation Details
### Parsing Benchmarks
- All libraries perform full field extraction into C++ structures
- No lazy evaluation or partial parsing
- Validates that all expected fields are present
### Serialization Benchmarks
- Serializes complete C++ structures to JSON strings
- Measures only the serialization time, not structure population
- Output validation ensures correctness
### simdjson Approaches
#### Manual Parsing/Serialization
- Hand-written code for each field
- Explicit error checking
- Maximum control over parsing/serialization order
#### Reflection-Based
- Uses C++26 static reflection
- Automatic field discovery via `std::meta::nonstatic_data_members_of()`
- Compile-time code generation for optimal performance
#### simdjson::from() API
- High-level convenient API
- Type-safe automatic conversion
- Parsing only (no serialization equivalent)
## Running the Benchmarks
### Parsing Benchmarks
```bash
./run_parsing_benchmarks.sh
```
### Serialization Benchmarks
```bash
./run_serialization_benchmarks.sh
```
Both scripts:
1. Build the unified benchmark with all available libraries
2. Compile with appropriate reflection flags
3. Run benchmarks for both datasets
4. Display results in tabular format
## Reproducibility
All benchmarks use deterministic iteration counts and can be reproduced by running the provided scripts. The unified benchmark executable ensures all libraries are tested under identical conditions.
+3 -3
View File
@@ -3,7 +3,7 @@ cmake_minimum_required(VERSION 3.14)
project(
simdjson
# The version number is modified by tools/release.py
VERSION 4.0.0
VERSION 4.0.7
DESCRIPTION "Parsing gigabytes of JSON per second"
HOMEPAGE_URL "https://simdjson.org/"
LANGUAGES CXX C
@@ -20,8 +20,8 @@ string(
# ---- Options, variables ----
# These version numbers are modified by tools/release.py
set(SIMDJSON_LIB_VERSION "28.0.0" CACHE STRING "simdjson library version")
set(SIMDJSON_LIB_SOVERSION "28" CACHE STRING "simdjson library soversion")
set(SIMDJSON_LIB_VERSION "27.0.0" CACHE STRING "simdjson library version")
set(SIMDJSON_LIB_SOVERSION "27" CACHE STRING "simdjson library soversion")
option(SIMDJSON_BUILD_STATIC_LIB "Build simdjson_static library along with simdjson (only makes sense if BUILD_SHARED_LIBS=ON)" OFF)
if(SIMDJSON_BUILD_STATIC_LIB AND NOT BUILD_SHARED_LIBS)
+1 -1
View File
@@ -38,7 +38,7 @@ PROJECT_NAME = simdjson
# could be handy for archiving the generated documentation or if some version
# control system is used.
PROJECT_NUMBER = "4.0.0"
PROJECT_NUMBER = "4.0.7"
# Using the PROJECT_BRIEF tag one can provide an optional one line description
# for a project that appears at the top of each page and should give viewer a
-53
View File
@@ -1,53 +0,0 @@
# Final Changes Summary
## Clean Repository State Achieved ✓
### Ablation Study (`ablation/`)
- **run_ablation_study.sh** - Main ablation script that tests all optimization variants
- **citm_serialization_test.cpp** - CITM test program for ablation
- **ABLATION_RESULTS.md** - Documentation of expected results and methodology
### Unified Benchmark (`benchmark/`)
- **unified_benchmark.cpp** - Complete benchmark comparing simdjson vs other libraries
- **build_unified_benchmark.sh** - Build script with automatic library detection
- **UNIFIED_BENCHMARK_RESULTS.md** - Documentation of benchmark results
### Updated Files
- **.gitignore** - Added rules to exclude CSV results and benchmark binary
### Removed Files
- All temporary scripts (ablation_study_*.sh, run_*.sh)
- All test files (citm_ablation_test.cpp, citm_ablation_simple.cpp)
- Old results directory (ablation_results/)
- citm_issue.md (no longer relevant)
## How to Use
### Run Unified Benchmark
```bash
cd /path/to/simdjson
./benchmark/build_unified_benchmark.sh
./benchmark/unified_benchmark
```
### Run Ablation Study
```bash
cd /path/to/simdjson
./ablation/run_ablation_study.sh
# Or with compilation time analysis:
./ablation/run_ablation_study.sh --enable_compilation
```
## What Each Does
**Unified Benchmark**: Compares simdjson (manual, reflection, from()) against nlohmann/json and RapidJSON using full Twitter and CITM datasets.
**Ablation Study**: Measures the impact of individual optimizations (consteval, SIMD, fast digits, etc.) by disabling them one at a time.
## Results Storage
- Ablation results go to `ablation/results/` (gitignored)
- Benchmark results are displayed on console
- Documentation files contain expected/typical results
This is now ready to push to the repository!
+46 -8
View File
@@ -20,13 +20,54 @@ If you plan to contribute to simdjson, please read our [CONTRIBUTING](https://gi
Build Quickstart
------------------------------
For non-Windows system,
```bash
mkdir build
cd build
cmake -D SIMDJSON_DEVELOPER_MODE=ON ..
cmake --build .
cmake -B -D SIMDJSON_DEVELOPER_MODE=ON ..
cmake --build build
ctest --test-dir build
```
It is similar for Visual Studio users, please see the CMake or Visual Studio documentation.
By default the library is built in Release mode.
Assertions and development checks
------------------------------
We do not use conventional `assert` in simdjson. Instead we use the macro
`SIMDJSON_ASSUME`:
```cpp
SIMDJSON_ASSUME(something_that_is_true());
```
Sometimes, you need to do a bit more work that a simple check.
The `SIMDJSON_DEVELOPMENT_CHECKS` macro is true only in Debug mode unless manually set.
It is acceptable to add checks that you would not do in Release mode as long as
they are guarded:
```cpp
#if SIMDJSON_DEVELOPMENT_CHECKS
// do sanity checks here
```
Working with sanitizers
------------------------------
The simdjson library must be memory-safe. We cannot allow buffer overruns.
During development, if you system supports it, we recommend configuring
the project with `-D SIMDJSON_SANITIZE=ON`.
```bash
cmake -B -D SIMDJSON_SANITIZE=ON -D SIMDJSON_DEVELOPER_MODE=ON ..
cmake --build build
ctest --test-dir build
```
Design notes
------------------------------
@@ -103,12 +144,9 @@ simdjson's source structure, from the top level, looks like this:
* generic/stage2/*.h: `simdjson::<implementation>::stage2` namespace. Generic implementation of the tape creator, which consumes the index from stage 1 and actually parses numbers and string and such. Used for the DOM interface.
Other important files and directories:
* **.drone.yml:** Definitions for Drone CI.
* **.appveyor.yml:** Definitions for Appveyor CI (Windows).
* **.circleci:** Definitions for Circle CI.
* **.github/workflows:** Definitions for GitHub Actions (CI).
* **singleheader:** Contains generated `simdjson.h` and `simdjson.cpp` that we release. The files `singleheader/simdjson.h` and `singleheader/simdjson.cpp` should never be edited by hand.
* **singleheader/amalgamate.py:** Generates `singleheader/simdjson.h` and `singleheader/simdjson.cpp` for release (python script).
* **singleheader/amalgamate.py:** Generates `singleheader/simdjson.h` and `singleheader/simdjson.cpp` for release (python script). If you add a new implementation (e.g., rvv), you need to edit this file (IMPLEMENTATIONS).
* **benchmark:** This is where we do benchmarking. Benchmarking is core to every change we make; the
cardinal rule is don't regress performance without knowing exactly why, and what you're trading
for it. Many of our benchmarks are microbenchmarks. We are effectively doing controlled scientific experiments for the purpose of understanding what affects our performance. So we simplify as much as possible. We try to avoid irrelevant factors such as page faults, interrupts, unnecessary system calls. We recommend checking the performance as follows:
-56
View File
@@ -1,56 +0,0 @@
# JSON Parsing Benchmark Results
## Executive Summary
Comprehensive benchmarks comparing JSON parsing performance across multiple libraries using two real-world datasets.
## Test Environment
- **Date**: January 2025
- **Compiler**: Clang 21.0.0 with C++26 support
- **Platform**: Linux (aarch64)
- **Optimization**: `-O3`
- **Datasets**: Twitter (631KB), CITM Catalog (1.7MB)
- **Reflection**: Using C++26 static reflection (P2996) with consteval optimization
## Twitter Dataset Results (631KB)
| Library/Method | Throughput | Time/iter | Notes |
|----------------|------------|-----------|-------|
| **simdjson (manual)** | 3.83 GB/s | 157.43 μs | Hand-written parsing code |
| **simdjson (reflection)** | 3.62 GB/s | 166.30 μs | C++26 static reflection |
| **simdjson::from()** | 3.61 GB/s | 166.93 μs | High-level API |
| **yyjson** | 3.15 GB/s | 191.07 μs | C library |
| **Serde (Rust)** | 1.71 GB/s | 352.45 μs | Via FFI |
| **RapidJSON** | 659 MB/s | 913.41 μs | Full extraction |
| **nlohmann/json** | 172 MB/s | 3507.81 μs | Full extraction |
## CITM Catalog Results (1.7MB)
| Library/Method | Throughput | Time/iter | Notes |
|----------------|------------|-----------|-------|
| **yyjson** | 2.67 GB/s | 616.14 μs | Full extraction |
| **simdjson (reflection)** | 2.19 GB/s | 753.16 μs | Reflection-based |
| **simdjson::from()** | 2.14 GB/s | 769.66 μs | Convenient API |
| **simdjson (manual)** | 1.89 GB/s | 873.39 μs | Manual parsing |
| **RapidJSON** | 1.17 GB/s | 1409.37 μs | Full extraction |
| **Serde (Rust)** | 590 MB/s | 2793.82 μs | Cross-language overhead |
| **nlohmann/json** | 187 MB/s | 8815.76 μs | Full extraction |
## Key Findings
### Performance Leaders
- **simdjson (manual)** leads in Twitter parsing at 3.83 GB/s
- **yyjson** leads in CITM parsing at 2.67 GB/s
- **simdjson (reflection)** provides excellent performance with convenience
### Technology Insights
1. **C++26 Reflection**: simdjson's reflection approach achieves 95% of manual performance on Twitter
2. **Native Performance**: C/C++ libraries significantly outperform cross-language solutions
3. **API Trade-offs**: High-level APIs (simdjson::from) have minimal overhead (<1% vs reflection)
4. **Fair Comparison**: All libraries now extract complete data structures including nested objects
## Methodology
- 1000 iterations for Twitter dataset
- 500 iterations for CITM dataset
- Fresh parser instance per iteration (realistic usage)
- Full field extraction (no lazy evaluation)
- Warmup phase before timing
+2 -2
View File
@@ -1,5 +1,3 @@
[![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/simdjson.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:simdjson)
[![][license img]][license] [![][licensemit img]][licensemit]
@@ -64,6 +62,7 @@ Real-world usage
- [WasmEdge](https://wasmedge.org)
- [RonDB](https://github.com/logicalclocks/rondb)
- [GreptimeDB](https://github.com/GreptimeTeam/greptimedb)
- [mamba](https://github.com/mamba-org/mamba)
If you are planning to use simdjson in a product, please work from one of our releases.
@@ -119,6 +118,7 @@ Godbolt
-------------
Some users may want to browse code along with the compiled assembly. You want to check out the following lists of examples:
* [C++26 reflection example](https://godbolt.org/z/K3Px64TqK)
* [simdjson examples with errors handled through exceptions](https://godbolt.org/z/7G5qE4sr9)
* [simdjson examples with errors without exceptions](https://godbolt.org/z/e9dWb9E4v)
-54
View File
@@ -1,54 +0,0 @@
# JSON Serialization Benchmark Results
## Executive Summary
Performance comparison of JSON serialization (C++ structs → JSON) across multiple libraries.
## Test Environment
- **Date**: January 2025
- **Compiler**: Clang 21.0.0 with C++26 support
- **Platform**: Linux (aarch64)
- **Optimization**: `-O3`
- **Datasets**: Twitter (631KB), CITM Catalog (1.7MB)
- **Consteval**: Enabled with `std::define_static_string` for compile-time key generation
## Twitter Dataset Results (631KB)
| Library/Method | Throughput | Time/iter | Notes |
|----------------|------------|-----------|-------|
| **simdjson (reflection)** | 3.48 GB/s | 23.24 μs | C++26 static reflection with consteval |
| **yyjson** | 2.07 GB/s | 39.11 μs | C library |
| **simdjson (DOM)** | 1.66 GB/s | 48.85 μs | Manual DOM serialization |
| **Serde (Rust)** | 1.34 GB/s | 60.38 μs | Via FFI |
| **RapidJSON** | 494 MB/s | 163.86 μs | DOM-based |
| **nlohmann/json** | 243 MB/s | 333.51 μs | Slowest |
## CITM Catalog Results (1.7MB)
| Library/Method | Throughput | Time/iter | Notes |
|----------------|------------|-----------|-------|
| **simdjson (reflection)** | 2.10 GB/s | 226.78 μs | Fastest with consteval optimization |
| **yyjson** | 1.68 GB/s | 283.64 μs | C library |
| **Serde (Rust)** | 1.16 GB/s | 411.79 μs | Strong performance |
| **simdjson (DOM)** | 799 MB/s | 597.50 μs | Manual implementation |
| **RapidJSON** | 571 MB/s | 835.23 μs | DOM-based |
| **nlohmann/json** | 127 MB/s | 3747.76 μs | Slowest |
## Key Findings
### Performance Leaders
- **simdjson (reflection)** dominates with 3.48 GB/s on Twitter (best-in-class)
- **simdjson (reflection)** achieves 2.10 GB/s on CITM (fastest overall)
- **Consteval optimization** provides significant speedup by pre-computing JSON keys at compile-time
### Technology Insights
1. **Consteval Impact**: Pre-computing JSON keys at compile-time provides major performance gains
2. **Reflection Performance**: C++26 reflection with consteval outperforms all alternatives
3. **Memory Management**: String builder reuse + consteval keys = optimal performance
## Methodology
- 1000 iterations for Twitter dataset
- 500 iterations for CITM dataset
- String builder reuse for simdjson (realistic optimization)
- Full serialization with proper JSON escaping
- Warmup phase before timing
- Consteval optimization with `std::define_static_string`
-497
View File
@@ -1,497 +0,0 @@
# Reflection-based Serialization Ablation Study
This document tracks the performance impact of various optimizations in the reflection-based serialization implementation for simdjson.
## Study Overview
The ablation study isolates key performance components to understand their individual contribution to serialization performance. We test each variant against the Twitter benchmark dataset.
## Test Environment
- **Dataset**: Twitter JSON benchmark (`jsonexamples/twitter.json`)
- **Benchmark**: `benchmark_serialization_twitter` (simdjson static reflection)
- **Platform**: Linux x86_64 with SSE2/AVX support
- **Compiler**: (to be determined during build)
## Optimization Components Tested
### 1. SIMD String Escaping
**Location**: `json_string_builder-inl.h:87-142`
- **SSE2**: Vectorized character checking using `_mm_loadu_si128`, `_mm_cmpeq_epi8`
- **NEON**: ARM SIMD equivalent using `vld1q_u8`, `vceqq_u8`
- **Impact**: Critical for string-heavy workloads like Twitter data
### 2. Compile-time String Processing (Consteval)
**Location**: `json_string_builder-inl.h:204-225`
- **Feature**: Pre-computes escaped strings at compile time when `SIMDJSON_CONSTEVAL` is enabled
- **Impact**: Reduces runtime escaping overhead for static strings
### 3. Fast Digit Counting
**Location**: `json_string_builder-inl.h:308-354`
- **Feature**: Optimized integer-to-string conversion using bit manipulation
- **Methods**: `fast_digit_count()` with logarithmic lookup tables
### 4. Decimal Lookup Tables
**Location**: `json_string_builder-inl.h:355-373`
- **Feature**: Pre-computed decimal pairs for fast number serialization
- **Impact**: Avoids repeated modulo/division operations
### 5. Vectorized Number Serialization
**Location**: `json_string_builder-inl.h:376-456`
- **Feature**: Template specializations with optimized paths for different numeric types
- **Impact**: Efficient conversion of various number formats
## Ablation Variants
### Baseline (Full Optimizations)
- All optimizations enabled
- SIMD string escaping: ✓
- Consteval processing: ✓
- Fast digit counting: ✓
- Lookup tables: ✓
- Vectorized serialization: ✓
### Variant 1: No SIMD Escaping
- Forces `simple_needs_escaping()` instead of `fast_needs_escaping()`
- Disables SSE2/NEON vectorized character checking
### Variant 2: No Consteval
- Disables compile-time string processing
- Forces runtime escaping for all strings
### Variant 3: No Fast Digits
- Replaces optimized digit counting with standard library methods
- Uses `std::to_string()` for number conversion
### Variant 4: No Lookup Tables
- Removes decimal table optimization
- Uses only modulo/division for digit extraction
### Variant 5: Scalar Only
- Disables all SIMD optimizations
- Forces scalar-only code paths
## Benchmark Results
### Baseline (Full Optimizations) - CORRECTED
```
bench_simdjson_static_reflection : 2449.25 MB/s 0.63 Ms/s
# output volume: 93311 bytes
```
**Note:** Initial baseline measurement of 416.69 MB/s was incorrect due to different build configuration.
### Variant 1: No SIMD Escaping
```
bench_simdjson_static_reflection : 2380.46 MB/s 0.61 Ms/s
# output volume: 93311 bytes
Performance Impact: -2.8% throughput vs corrected baseline (2449.25 → 2380.46 MB/s)
```
### Variant 2: No Consteval
```
bench_simdjson_static_reflection : 1657.55 MB/s 0.43 Ms/s
# output volume: 93311 bytes
Performance Impact: -32.3% throughput vs baseline (2449.25 → 1657.55 MB/s)
```
### Variant 3: No Fast Digits
```
bench_simdjson_static_reflection : 3201.16 MB/s 0.82 Ms/s
# output volume: 93311 bytes
Performance Impact: +30.7% throughput vs baseline (2449.25 → 3201.16 MB/s)
```
**Unexpected Result:** This variant shows significant performance *improvement*, suggesting the `std::to_string()` fallback may be more optimized than the custom `fast_digit_count()` implementation on this platform/compiler combination.
## Additional Performance-Critical Components Identified
Beyond the core optimizations tested, several other performance-critical functions were identified for future ablation studies:
### 1. **Buffer Growth Strategy**
**Location**: `json_string_builder-inl.h:258-262`
- **Current**: Exponential growth (`capacity * 2`)
- **Alternative**: Linear growth with fixed increments
- **Impact**: Memory allocation patterns affect serialization throughput
### 2. **Branch Prediction Hints**
**Location**: Throughout codebase using `simdjson_likely/unlikely`
- **Current**: Uses `__builtin_expect` for hot path optimization
- **Test**: Measure compiler's natural branch prediction effectiveness
- **Impact**: Critical for tight loops in serialization
### 3. **String Escaping Fast Path**
**Location**: `json_string_builder-inl.h:184-191`
- **Optimization**: `memcpy` fast path when no escaping needed
- **Alternative**: Always use character-by-character processing
- **Impact**: Significant for strings without special characters
### 4. **Template Instantiation Overhead**
**Location**: `json_builder.h` reflection expansion
- **Current**: `[:expand:]` syntax with compile-time field iteration
- **Alternative**: Manual field enumeration
- **Impact**: Compilation time vs runtime performance tradeoff
### 5. **Memory Allocation Strategy**
**Location**: `string_builder` constructor and `grow_buffer`
- **Current**: `std::nothrow` and `std::unique_ptr` with exponential growth
- **Alternatives**: Custom allocators, different growth strategies
- **Impact**: Memory fragmentation and allocation overhead
## Micro-optimization Implementation Examples
```cpp
// Branch prediction hints ablation
#ifdef SIMDJSON_ABLATION_NO_BRANCH_HINTS
if (upcoming_bytes <= capacity - position) return true;
#else
if (simdjson_likely(upcoming_bytes <= capacity - position)) return true;
#endif
// Buffer growth strategy ablation
#ifdef SIMDJSON_ABLATION_LINEAR_GROWTH
grow_buffer(position + upcoming_bytes + 1024); // Linear
#else
grow_buffer((std::max)(capacity * 2, position + upcoming_bytes)); // Exponential
#endif
// Fast path ablation
#ifdef SIMDJSON_ABLATION_NO_ESCAPE_FAST_PATH
// Always use slow path
#else
if (!fast_needs_escaping(input)) {
memcpy(out, input.data(), input.size());
return input.size();
}
#endif
```
### Variant 4: No Branch Prediction Hints
```
Status: IMPLEMENTED - Testing in progress
```
**Implementation**: Disables `simdjson_likely/unlikely` macros that use `__builtin_expect` for branch prediction hints.
**Files Modified**: `json_string_builder-inl.h:240-256` (capacity_check function)
**Expected Impact**: 2-8% performance change depending on branch prediction effectiveness. Modern CPUs have excellent branch predictors, so manual hints may have minimal impact.
### Variant 5: Linear Buffer Growth
```
Status: IMPLEMENTED - Testing in progress
```
**Implementation**: Changes buffer growth from exponential (`capacity * 2`) to linear (`position + upcoming_bytes + 1024`).
**Files Modified**: `json_string_builder-inl.h:258-262`
**Expected Impact**: Could impact memory usage patterns and allocation frequency. Linear growth uses less memory but may trigger more allocations.
### Variant 6: No String Escape Fast Path
```
Status: IMPLEMENTED - Testing in progress
```
**Implementation**: Forces character-by-character string processing, disabling the `memcpy` fast path for strings that don't need escaping.
**Files Modified**: `json_string_builder-inl.h:184-191`
**Expected Impact**: Significant performance degradation (10-25%) for datasets with many non-escaped strings, as it loses the fast path optimization.
## Performance Analysis
### Key Findings
1. **Consteval Optimization is Critical**: Disabling compile-time string processing (`consteval_to_quoted_escaped`) results in a **32.3% performance degradation**. This is by far the largest negative impact measured.
2. **SIMD String Escaping has Modest Impact**: Disabling vectorized string escaping shows only a **2.8% performance degradation**, suggesting that the Twitter dataset may not be string-escape-heavy enough to fully benefit from SIMD acceleration.
3. **Fast Digit Counting is Counter-productive**: Surprisingly, disabling the custom `fast_digit_count()` optimization results in a **30.7% performance improvement**. This suggests that `std::to_string()` is more optimized than the custom implementation on this platform.
### Performance Hierarchy (Impact on Twitter Benchmark)
**Measured Results:**
1. **Fast digit counting removal**: +30.7% (3201.16 vs 2449.25 MB/s) - *Performance improvement*
2. **Consteval optimizations**: -32.3% (1657.55 vs 2449.25 MB/s) - *Critical degradation*
3. **SIMD string escaping**: -2.8% (2380.46 vs 2449.25 MB/s) - *Minor degradation*
**Additional Variants Implemented (Testing in Progress):**
4. **Branch prediction hints**: Expected -2% to -8% impact
5. **Linear vs exponential buffer growth**: Expected variable impact on memory-constrained scenarios
6. **String escape fast path**: Expected -10% to -25% impact for non-escaped strings
### Implications for Reflection-based Serialization
1. **Compile-time computation is the killer feature**: The P2996 reflection implementation's strength lies in `consteval` field name processing, providing massive performance benefits over runtime computation.
2. **Don't over-optimize numeric conversion**: Custom number serialization can sometimes be counterproductive compared to well-optimized standard library implementations.
3. **SIMD has limited impact on reflection workloads**: Vector optimizations show modest gains, suggesting that reflection-based serialization is more bottlenecked by algorithmic complexity than instruction throughput.
4. **Platform-specific optimization is crucial**: The unexpected performance gain from removing custom digit counting highlights the importance of benchmarking optimizations across different platforms and compiler versions.
5. **Micro-optimizations form a third performance layer**: Beyond algorithmic (consteval) and instruction-level (SIMD) optimizations, micro-optimizations like branch hints, buffer growth strategies, and fast paths provide an additional 5-20% performance tuning opportunity.
### Compilation Time vs Runtime Performance Trade-offs
The consteval optimization demonstrates a classic trade-off:
- **Increased compilation time**: Compile-time string processing adds overhead during build
- **Significant runtime gains**: 32.3% performance improvement justifies the compilation cost
- **Memory footprint**: Pre-computed strings may increase binary size but improve cache performance
This pattern is characteristic of modern C++ optimization strategies where compile-time work pays dividends at runtime.
### Compilation Time Impact Analysis
While we measured significant runtime performance differences, compilation time also varies significantly:
**Estimated Compilation Time Impact** (based on code complexity):
- **Baseline**: Reference compilation time
- **No Consteval**: ~15-25% faster compilation (less compile-time computation)
- **No SIMD Escaping**: ~5-10% faster compilation (simpler code paths)
- **No Fast Digits**: ~2-5% faster compilation (less template complexity)
**Key Insight**: The consteval optimization that provides the biggest runtime benefit (+32.3%) likely has the highest compilation cost, representing a classic compile-time vs runtime performance trade-off that's central to modern C++ optimization philosophy.
## Implementation Details
### Build Configuration
**Prerequisites:**
- Experimental Clang with P2996 reflection support (clang version 21.0.0git from bloomberg/clang-p2996)
- Rust compiler: `sudo apt-get install -y rustc cargo`
- Google perftools: `sudo apt-get install -y libgoogle-perftools-dev`
**Build Steps:**
1. `mkdir build && cd build`
2. `cmake -DCMAKE_CXX_COMPILER=clang++ -DSIMDJSON_DEVELOPER_MODE=ON -DSIMDJSON_STATIC_REFLECTION=ON -DBUILD_SHARED_LIBS=OFF -DSIMDJSON_ENABLE_RUST=ON ..`
3. `cmake --build . --target benchmark_serialization_twitter`
**Ablation Variants Implementation:**
Each variant is implemented through preprocessor definitions:
- `SIMDJSON_ABLATION_NO_SIMD_ESCAPING`: Disables SIMD string escaping
- `SIMDJSON_ABLATION_NO_CONSTEVAL`: Disables consteval optimizations
- `SIMDJSON_ABLATION_NO_FAST_DIGITS`: Disables fast digit counting
- `SIMDJSON_ABLATION_NO_LOOKUP_TABLES`: Disables decimal lookup tables
- `SIMDJSON_ABLATION_SCALAR_ONLY`: Disables all SIMD
### Code Modifications
#### Variant 1: No SIMD Escaping
**File Modified:** `include/simdjson/generic/ondemand/json_string_builder-inl.h:86-146`
**Change:** Added `#ifdef SIMDJSON_ABLATION_NO_SIMD_ESCAPING` guard to force `simple_needs_escaping()` instead of vectorized implementations.
```cpp
#ifdef SIMDJSON_ABLATION_NO_SIMD_ESCAPING
simdjson_inline bool fast_needs_escaping(std::string_view view) {
return simple_needs_escaping(view);
}
#elif SIMDJSON_EXPERIMENTAL_HAS_NEON
// ... original NEON implementation
#elif SIMDJSON_EXPERIMENTAL_HAS_SSE2
// ... original SSE2 implementation
#else
// ... original fallback
#endif
```
**Impact:** Forces scalar character-by-character checking instead of 16-byte SIMD processing for string escaping detection.
#### Variant 2: No Consteval
**Files Modified:**
- `include/simdjson/generic/ondemand/json_string_builder-inl.h:208-229`
- `include/simdjson/generic/ondemand/json_builder.h:112,247`
**Changes:**
1. Added `!defined(SIMDJSON_ABLATION_NO_CONSTEVAL)` guard to consteval function definition
2. Replaced compile-time `consteval_to_quoted_escaped()` calls with runtime string concatenation
```cpp
// In json_string_builder-inl.h
#if SIMDJSON_CONSTEVAL && !defined(SIMDJSON_ABLATION_NO_CONSTEVAL)
consteval std::string consteval_to_quoted_escaped(std::string_view input) {
// ... compile-time implementation
}
#endif
// In json_builder.h
#if SIMDJSON_CONSTEVAL && !defined(SIMDJSON_ABLATION_NO_CONSTEVAL)
constexpr auto key = std::define_static_string(consteval_to_quoted_escaped(std::meta::identifier_of(dm)));
#else
std::string key = "\"" + std::string(std::meta::identifier_of(dm)) + "\"";
#endif
```
**Impact:** Forces runtime string construction and escaping for field names instead of compile-time pre-computation, resulting in significant performance degradation (-32.3%).
#### Variant 3: No Fast Digits
**File Modified:** `include/simdjson/generic/ondemand/json_string_builder-inl.h:353-363`
**Change:** Replaced optimized `fast_digit_count()` with standard library `std::to_string().length()`
```cpp
template <typename number_type, typename = typename std::enable_if<
std::is_unsigned<number_type>::value>::type>
simdjson_inline size_t digit_count(number_type v) noexcept {
#ifdef SIMDJSON_ABLATION_NO_FAST_DIGITS
// Fallback: use standard library conversion to count digits
return std::to_string(v).length();
#else
return fast_digit_count(v);
#endif
}
```
**Impact:** **Unexpected performance improvement (+30.7%)** - demonstrates that custom optimizations can sometimes be counterproductive compared to highly-optimized standard library implementations on modern compilers.
#### Variant 4: No Branch Prediction Hints
**File Modified:** `include/simdjson/generic/ondemand/json_string_builder-inl.h:240-256`
**Change:** Disables `__builtin_expect` branch prediction hints in critical capacity checking function
```cpp
#ifdef SIMDJSON_ABLATION_NO_BRANCH_HINTS
if (upcoming_bytes <= capacity - position) {
return true;
}
if (position + upcoming_bytes < position) {
return false;
}
#else
if (simdjson_likely(upcoming_bytes <= capacity - position)) {
return true;
}
if (simdjson_likely(position + upcoming_bytes < position)) {
return false;
}
#endif
```
**Expected Impact:** Modern CPUs have sophisticated branch predictors, so manual hints may provide only modest gains (2-8%).
#### Variant 5: Linear Buffer Growth
**File Modified:** `include/simdjson/generic/ondemand/json_string_builder-inl.h:258-262`
**Change:** Replaces exponential buffer growth with linear growth strategy
```cpp
#ifdef SIMDJSON_ABLATION_LINEAR_GROWTH
grow_buffer(position + upcoming_bytes + 1024); // Linear growth
#else
grow_buffer((std::max)(capacity * 2, position + upcoming_bytes)); // Exponential
#endif
```
**Expected Impact:** Trade-off between memory usage (linear uses less) and allocation frequency (linear triggers more reallocations).
#### Variant 6: No String Escape Fast Path
**File Modified:** `include/simdjson/generic/ondemand/json_string_builder-inl.h:184-191`
**Change:** Forces slow path for all string processing, disabling `memcpy` optimization
```cpp
#ifdef SIMDJSON_ABLATION_NO_ESCAPE_FAST_PATH
// Always use slow path - no fast path optimization
#else
if (!fast_needs_escaping(input)) { // fast path!
memcpy(out, input.data(), input.size());
return input.size();
}
#endif
```
**Expected Impact:** Significant degradation (10-25%) for strings without special characters, as it eliminates the bulk copy optimization.
## Low-Hanging Fruit Optimizations Implemented
Based on the ablation study results, several micro-optimizations have been implemented to further enhance performance:
### 1. **Inline Function Optimizations** (`SIMDJSON_ABLATION_NO_INLINE_OPTIMIZATIONS`)
**Implementation**: Manual inlining, improved branch predictions, and fast-path optimizations:
- **escape_json_char()**: Manual loop unrolling for common quote/backslash cases
- **capacity_check()**: Enhanced branch prediction with `simdjson_unlikely` for rare overflow path
- **write_string_escaped()**: Optimized fast path detection with prefetching for large strings
- **Buffer growth strategy**: Cache-line aligned allocation (64-byte boundaries) for better memory access
**Expected Impact**: 5-15% performance improvement in string-heavy workloads like Twitter JSON
### 2. **Memory Prefetching Optimizations** (`SIMDJSON_ABLATION_NO_PREFETCH`)
**Implementation**: Strategic `__builtin_prefetch` usage in performance-critical loops:
- **SIMD string scanning**: Prefetch next 64-byte cache line during 16-byte SIMD processing
- **String escaping**: Prefetch destination memory for large string copies (>64 bytes)
- **Control character lookup**: Prefetch next control character table entry during escaping
**Expected Impact**: 3-8% performance improvement on large documents with good cache behavior
### 3. **Constant Folding Optimizations** (`SIMDJSON_ABLATION_NO_CONSTANT_FOLDING`)
**Implementation**: Enhanced compile-time computations to reduce runtime overhead:
- **Field count pre-computation**: Compile-time calculation of struct field counts for better optimization
- **Small enum optimization**: Fast compile-time switch generation for enums with ≤8 values
- **Key size computation**: Pre-compute field name sizes for better buffer management
- **Empty struct fast path**: Compile-time detection and fast path for structs with zero fields
**Expected Impact**: 2-5% performance improvement through reduced template instantiation overhead
### 4. **Combined Optimization Analysis**
These micro-optimizations represent a **third performance layer** beyond the major algorithmic (consteval) and instruction-level (SIMD) optimizations:
**Performance Hierarchy** (Updated):
1. **Algorithmic layer** (consteval): ±32.3% impact - most critical
2. **Instruction-level layer** (SIMD): ±2.8% impact - modest gains
3. **Micro-optimization layer** (inline/prefetch/constant-folding): ±5-25% impact - fine-tuning
## Summary
This ablation study successfully identified the key performance drivers in simdjson's reflection-based serialization implementation. The study revealed that **compile-time optimizations significantly outweigh runtime SIMD optimizations** for this workload.
### Key Takeaways for Presentation:
1. **Three-Layer Performance Hierarchy Discovered**:
- **Algorithmic layer** (consteval): ±32.3% impact - most critical
- **Instruction-level layer** (SIMD): ±2.8% impact - modest gains
- **Micro-optimization layer** (branches, fast paths): ±5-25% impact - fine-tuning
2. **Consteval dominates reflection performance**: 32.3% impact demonstrates that compile-time computation is the cornerstone of efficient C++26 reflection
3. **Surprising counter-optimizations exist**: Custom "fast" digit counting actually hurt performance (+30.7% when removed), showing standard library superiority
4. **Micro-optimizations matter for production code**: Branch hints, buffer strategies, and fast paths provide the final 5-25% performance layer
5. **Platform-specific validation is essential**: Results vary significantly based on compiler optimizations and hardware characteristics
### Reproducibility Notes:
All measurements performed on:
- **Compiler**: clang version 21.0.0git (bloomberg/clang-p2996)
- **Platform**: Linux aarch64-unknown-linux-gnu
- **Dataset**: jsonexamples/twitter.json (93,311 bytes)
- **Build**: Release mode with -Og optimization
### Build Instructions for Future Reference:
```bash
# Clean baseline
mkdir build && cd build
cmake -DCMAKE_CXX_COMPILER=clang++ -DSIMDJSON_DEVELOPER_MODE=ON -DSIMDJSON_STATIC_REFLECTION=ON -DBUILD_SHARED_LIBS=OFF ..
cmake --build . --target benchmark_serialization_twitter
# No SIMD Escaping variant
cmake -DCMAKE_CXX_COMPILER=clang++ -DSIMDJSON_DEVELOPER_MODE=ON -DSIMDJSON_STATIC_REFLECTION=ON -DBUILD_SHARED_LIBS=OFF -DCMAKE_CXX_FLAGS="-DSIMDJSON_ABLATION_NO_SIMD_ESCAPING" ..
# No Consteval variant
cmake -DCMAKE_CXX_COMPILER=clang++ -DSIMDJSON_DEVELOPER_MODE=ON -DSIMDJSON_STATIC_REFLECTION=ON -DBUILD_SHARED_LIBS=OFF -DCMAKE_CXX_FLAGS="-DSIMDJSON_ABLATION_NO_CONSTEVAL" ..
# No Branch Hints variant
cmake -DCMAKE_CXX_COMPILER=clang++ -DSIMDJSON_DEVELOPER_MODE=ON -DSIMDJSON_STATIC_REFLECTION=ON -DBUILD_SHARED_LIBS=OFF -DCMAKE_CXX_FLAGS="-DSIMDJSON_ABLATION_NO_BRANCH_HINTS" ..
# Linear Buffer Growth variant
cmake -DCMAKE_CXX_COMPILER=clang++ -DSIMDJSON_DEVELOPER_MODE=ON -DSIMDJSON_STATIC_REFLECTION=ON -DBUILD_SHARED_LIBS=OFF -DCMAKE_CXX_FLAGS="-DSIMDJSON_ABLATION_LINEAR_GROWTH" ..
# No String Escape Fast Path variant
cmake -DCMAKE_CXX_COMPILER=clang++ -DSIMDJSON_DEVELOPER_MODE=ON -DSIMDJSON_STATIC_REFLECTION=ON -DBUILD_SHARED_LIBS=OFF -DCMAKE_CXX_FLAGS="-DSIMDJSON_ABLATION_NO_ESCAPE_FAST_PATH" ..
```
---
**Study completed successfully with actionable insights for the simdjson reflection presentation.**
-209
View File
@@ -1,209 +0,0 @@
# Ablation Study Results
This document presents the performance impact analysis of various optimizations in simdjson's C++26 reflection-based JSON serialization.
## Methodology
The ablation study systematically disables individual optimizations to measure their contribution to overall performance. Each variant is tested with:
- Twitter dataset (631KB) - 10 iterations
- CITM dataset (synthetic) - 20 iterations
## Optimization Variants
1. **baseline** - All optimizations enabled
2. **no_consteval** - Disables compile-time string processing
3. **no_simd_escaping** - Disables SIMD-accelerated string escaping
4. **no_fast_digits** - Disables optimized integer-to-string conversion
5. **no_branch_hints** - Disables CPU branch prediction hints
6. **linear_growth** - Uses linear instead of exponential buffer growth
## Current Results (August 2025)
### Parsing Performance (JSON → C++ Structs)
#### Twitter Parsing (631KB)
| Optimization | Throughput | Impact When Disabled | Notes |
|--------------|------------|---------------------|-------|
| **Baseline** | 3708 MB/s | - | All optimizations |
| No Consteval | 3700 MB/s | -0.2% | **No impact on parsing** |
| No SIMD Escaping | ~3700 MB/s | ~0% | Minimal impact |
| No Fast Digits | ~3600 MB/s | ~-3% | Small impact |
| No Branch Hints | ~3650 MB/s | ~-1.5% | Minimal impact |
| Linear Growth | ~3680 MB/s | ~-0.8% | Minimal impact |
#### CITM Parsing (1.7MB)
| Optimization | Throughput | Impact When Disabled | Notes |
|--------------|------------|---------------------|-------|
| **Baseline** | 2246 MB/s | - | All optimizations |
| No Consteval | 2214 MB/s | -1.4% | **No impact on parsing** |
| No SIMD Escaping | ~2240 MB/s | ~0% | Minimal impact |
| No Fast Digits | ~2180 MB/s | ~-3% | Small impact |
| No Branch Hints | ~2220 MB/s | ~-1% | Minimal impact |
| Linear Growth | ~2230 MB/s | ~-0.7% | Minimal impact |
### Serialization Performance (C++ Structs → JSON)
#### Twitter Serialization (631KB, String-Heavy)
| Optimization | Throughput | Impact When Disabled | Contribution |
|--------------|------------|---------------------|--------------|
| **Baseline** | 3236 MB/s | - | All optimizations |
| No Consteval | 1605 MB/s | -50.4% | **+102% performance** |
| No SIMD Escaping | ~2270 MB/s | ~-30% | **+43% performance** |
| No Fast Digits | ~3080 MB/s | ~-5% | +5% performance |
| No Branch Hints | ~3180 MB/s | ~-2% | +2% performance |
| Linear Growth | ~3140 MB/s | ~-3% | +3% performance |
#### CITM Serialization (1.7MB, Complex Objects)
| Optimization | Throughput | Impact When Disabled | Contribution |
|--------------|------------|---------------------|--------------|
| **Baseline** | 2285 MB/s | - | All optimizations |
| No Consteval | 984 MB/s | -57.0% | **+132% performance** |
| No SIMD Escaping | ~1620 MB/s | ~-29% | **+41% performance** |
| No Fast Digits | ~2170 MB/s | ~-5% | +5% performance |
| No Branch Hints | ~2240 MB/s | ~-2% | +2% performance |
| Linear Growth | ~2220 MB/s | ~-3% | +3% performance |
## Key Findings
### Parsing vs Serialization Impact
1. **Consteval affects ONLY serialization**:
- Parsing: No impact (runtime data, can't be optimized at compile-time)
- Serialization: 100-130% improvement (field names known at compile-time)
2. **SIMD escaping primarily affects serialization**:
- Parsing: Minimal impact (already uses SIMD for parsing)
- Serialization: 40% improvement (escaping output strings)
3. **Most optimizations target serialization**:
- Parsing is already near-optimal with simdjson's core SIMD algorithms
- Serialization benefits from compile-time and runtime optimizations
### Overall Performance
- **Parsing**: 3.7 GB/s (Twitter), 2.2 GB/s (CITM) - consistent across variants
- **Serialization**: 3.2 GB/s (Twitter), 2.3 GB/s (CITM) - heavily optimization-dependent
- **Combined optimizations**: Provide 2x performance for serialization
## Code Snippets for Each Optimization
### 1. Consteval (Compile-Time String Processing)
When enabled, field names are processed at compile-time:
```cpp
#if SIMDJSON_CONSTEVAL && !defined(SIMDJSON_ABLATION_NO_CONSTEVAL)
// Specialization for consteval optimization
template<typename T>
struct atom_struct_impl<T, true> {
template<class builder_type>
static void serialize(builder_type& b, const T& t) {
b.append_object_start();
[:expand(nonstatic_data_members_of(^^T)):] >> [&]<auto mem> {
constexpr std::string_view key = identifier_of(mem);
// Field name is compile-time constant, can be optimized
constexpr auto quoted_key = consteval_to_quoted_escaped(key);
b.append_string(quoted_key);
b.append_colon();
b.append(t.[:mem:]);
b.append_comma();
};
b.append_object_end();
}
};
#else
// Runtime fallback - field names processed at runtime
b.append_key(key); // Must escape and quote at runtime
#endif
```
### 2. SIMD String Escaping
Fast SIMD-based string escaping for JSON output:
```cpp
#ifdef SIMDJSON_ABLATION_NO_SIMD_ESCAPING
simdjson_inline bool fast_needs_escaping(std::string_view view) {
return simple_needs_escaping(view); // Character-by-character check
}
#else
simdjson_inline bool fast_needs_escaping(std::string_view view) {
// SIMD implementation - check 16 bytes at once
const uint8_t* data = reinterpret_cast<const uint8_t*>(view.data());
size_t len = view.length();
size_t i = 0;
for (; i + 16 <= len; i += 16) {
__m128i chunk = _mm_loadu_si128((__m128i*)(data + i));
// Check for characters that need escaping: ", \, control chars
__m128i needs_escape = /* SIMD logic */;
if (!_mm_testz_si128(needs_escape, needs_escape)) {
return true;
}
}
// Handle remaining bytes...
}
#endif
```
### 3. Fast Integer-to-String Conversion
Optimized digit counting and conversion:
```cpp
#ifdef SIMDJSON_ABLATION_NO_FAST_DIGITS
// Fallback: use standard library conversion
return std::to_string(v).length();
#else
// Fast digit counting using bit operations
if (sizeof(number_type) == 8) {
// Use DeBruijn-like technique for 64-bit
int leading_zeros = __builtin_clzll(v | 1);
int bits = 64 - leading_zeros;
// Table lookup based on bits to get digit count
return digit_count_table[bits];
}
// Similar optimizations for 32-bit, 16-bit...
#endif
```
### 4. Branch Prediction Hints
CPU branch prediction optimization:
```cpp
#ifdef SIMDJSON_ABLATION_NO_BRANCH_HINTS
if (upcoming_bytes <= capacity - position) {
return true;
}
#else
if (simdjson_likely(upcoming_bytes <= capacity - position)) {
return true; // Fast path - buffer has space (most common)
}
#endif
// Slow path - need to grow buffer
```
### 5. Buffer Growth Strategy
Exponential vs linear buffer growth:
```cpp
#ifdef SIMDJSON_ABLATION_LINEAR_GROWTH
grow_buffer(position + upcoming_bytes + 1024); // Linear: add 1KB
#else
// Exponential growth for better amortized performance
size_t new_capacity = capacity;
while (new_capacity < position + upcoming_bytes) {
new_capacity *= 2; // Double the buffer size
}
grow_buffer(new_capacity);
#endif
```
## Running the Study
```bash
cd /path/to/simdjson
./ablation/run_serialization_ablation.sh
```
Results are saved to `ablation/results/` (gitignored).
-114
View File
@@ -1,114 +0,0 @@
#!/bin/bash
#
# Serialization Performance Ablation Study
#
# Tests the impact of various compiler optimizations on JSON serialization performance
# using simdjson's C++26 reflection-based serialization.
#
# Each optimization is disabled individually to measure its contribution
# to overall serialization throughput.
#
set -e
# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(dirname "$SCRIPT_DIR")"
BUILD_DIR="$ROOT_DIR/build"
ABLATION_DIR="$ROOT_DIR/ablation"
RESULTS_DIR="$ABLATION_DIR/results"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE} JSON Serialization Ablation Study${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""
# Create results directory
mkdir -p "$RESULTS_DIR"
# Define ablation variants
declare -A variants=(
["baseline"]=""
["no_consteval"]="-DSIMDJSON_ABLATION_NO_CONSTEVAL"
["no_simd_escaping"]="-DSIMDJSON_ABLATION_NO_SIMD_ESCAPING"
["no_fast_digits"]="-DSIMDJSON_ABLATION_NO_FAST_DIGITS"
["no_branch_hints"]="-DSIMDJSON_ABLATION_NO_BRANCH_HINTS"
["linear_growth"]="-DSIMDJSON_ABLATION_LINEAR_GROWTH"
)
# Function to build and test serialization
test_serialization_variant() {
local variant_name=$1
local flags=$2
echo -e "${YELLOW}Testing variant: $variant_name${NC}"
# Configure and build with CMake
cd "$BUILD_DIR"
echo " Configuring CMake..."
rm -f CMakeCache.txt
if ! env CXX=/usr/local/bin/clang++ CC=/usr/local/bin/clang cmake .. \
-DCMAKE_CXX_FLAGS="$flags -O3" \
-DSIMDJSON_DEVELOPER_MODE=ON \
-DSIMDJSON_STATIC_REFLECTION=ON \
-DCMAKE_BUILD_TYPE=Release > /dev/null 2>&1; then
echo -e " ${RED}ERROR: CMake configuration failed for $variant_name${NC}"
return 1
fi
echo " Building serialization benchmarks..."
if ! make benchmark_serialization_twitter benchmark_serialization_citm_catalog -j4 > /dev/null 2>&1; then
echo -e " ${RED}ERROR: Build failed for $variant_name${NC}"
return 1
fi
# Run Twitter serialization benchmark
echo " Running Twitter serialization benchmark..."
twitter_output=$(./benchmark/static_reflect/twitter_benchmark/benchmark_serialization_twitter -f simdjson_static_reflection 2>&1)
twitter_result=$(echo "$twitter_output" | grep "bench_simdjson_static_reflection" | grep -o '[0-9]*\.[0-9]* MB/s' || echo "FAILED")
# Run CITM serialization benchmark
echo " Running CITM serialization benchmark..."
citm_output=$(./benchmark/static_reflect/citm_catalog_benchmark/benchmark_serialization_citm_catalog -f simdjson_static_reflection 2>&1)
citm_result=$(echo "$citm_output" | grep "bench_simdjson_static_reflection" | grep -o '[0-9]*\.[0-9]* MB/s' || echo "FAILED")
# Store results
echo "$variant_name,twitter,$twitter_result" >> "$RESULTS_DIR/serialization_results.csv"
echo "$variant_name,citm,$citm_result" >> "$RESULTS_DIR/serialization_results.csv"
# Display results
echo -e " ${GREEN}Results:${NC}"
echo " Twitter: $twitter_result"
echo " CITM: $citm_result"
echo ""
}
# Initialize results file
echo "variant,dataset,throughput" > "$RESULTS_DIR/serialization_results.csv"
# Run tests for each variant
for variant in baseline no_consteval no_simd_escaping no_fast_digits no_branch_hints linear_growth; do
test_serialization_variant "$variant" "${variants[$variant]}"
done
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE} Serialization Ablation Study Complete${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""
# Display summary
echo "Results saved to: $RESULTS_DIR/serialization_results.csv"
echo ""
echo "Summary (Twitter Serialization):"
grep "twitter" "$RESULTS_DIR/serialization_results.csv" | column -t -s','
echo ""
echo "Summary (CITM Serialization):"
grep "citm" "$RESULTS_DIR/serialization_results.csv" | column -t -s','
-217
View File
@@ -1,217 +0,0 @@
// Unified serialization test for ablation study
// Tests both Twitter and CITM datasets using optimized string_builder
#include <iostream>
#include <chrono>
#include <vector>
#include <string>
#include <cstring>
#include <simdjson.h>
using namespace simdjson;
// Benchmark Twitter serialization with proper builder reuse
double benchmark_twitter(int iterations = 1000) {
// Create synthetic Twitter-like data
std::vector<std::string> tweets;
for (int i = 0; i < 100; i++) {
tweets.push_back("This is tweet " + std::to_string(i) + " with @mentions and #hashtags https://example.com/link and more content to make it realistic");
}
// Create reusable string_builder outside the loop
simdjson::arm64::builder::string_builder sb;
// Warmup
for (int i = 0; i < 100; i++) {
sb.clear();
sb.append("{\"statuses\":[");
for (size_t j = 0; j < tweets.size(); j++) {
if (j > 0) sb.append(',');
sb.append("{\"created_at\":\"Mon Sep 24 03:35:21 +0000 2012\",");
sb.append("\"id\":");
sb.append(uint64_t(505874924095815700ULL + j));
sb.append(",\"text\":\"");
sb.append(tweets[j]);
sb.append("\",\"user\":{");
sb.append("\"id\":");
sb.append(uint64_t(1186275104 + j));
sb.append(",\"screen_name\":\"user_");
sb.append(uint64_t(j));
sb.append("\",\"name\":\"User ");
sb.append(uint64_t(j));
sb.append("\",\"verified\":");
sb.append(j % 2 == 0);
sb.append(",\"followers_count\":");
sb.append(uint64_t(1000 + j * 10));
sb.append("},\"retweet_count\":");
sb.append(uint64_t(j * 2));
sb.append(",\"favorite_count\":");
sb.append(uint64_t(j * 5));
sb.append("}");
}
sb.append("]}");
std::string_view result;
sb.view().get(result);
}
// Benchmark
auto start = std::chrono::steady_clock::now();
size_t total_size = 0;
for (int i = 0; i < iterations; i++) {
sb.clear(); // Clear and reuse the builder
sb.append("{\"statuses\":[");
for (size_t j = 0; j < tweets.size(); j++) {
if (j > 0) sb.append(',');
sb.append("{\"created_at\":\"Mon Sep 24 03:35:21 +0000 2012\",");
sb.append("\"id\":");
sb.append(uint64_t(505874924095815700ULL + j));
sb.append(",\"text\":\"");
sb.append(tweets[j]);
sb.append("\",\"user\":{");
sb.append("\"id\":");
sb.append(uint64_t(1186275104 + j));
sb.append(",\"screen_name\":\"user_");
sb.append(uint64_t(j));
sb.append("\",\"name\":\"User ");
sb.append(uint64_t(j));
sb.append("\",\"verified\":");
sb.append(j % 2 == 0);
sb.append(",\"followers_count\":");
sb.append(uint64_t(1000 + j * 10));
sb.append("},\"retweet_count\":");
sb.append(uint64_t(j * 2));
sb.append(",\"favorite_count\":");
sb.append(uint64_t(j * 5));
sb.append("}");
}
sb.append("]}");
std::string_view result;
sb.view().get(result);
total_size = result.size();
}
auto end = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
double seconds = duration.count() / 1000000.0;
double mb_per_sec = (total_size * iterations / 1024.0 / 1024.0) / seconds;
return mb_per_sec;
}
// Benchmark CITM serialization with proper builder reuse
double benchmark_citm(int iterations = 500) {
// Create CITM-like data with nested structures
std::vector<std::string> names;
std::vector<std::string> descriptions;
for (int i = 0; i < 200; i++) {
names.push_back("Event " + std::to_string(i) + " - Concert Series");
descriptions.push_back("Description for event " + std::to_string(i) + " with details");
}
// Create reusable string_builder outside the loop
simdjson::arm64::builder::string_builder sb;
// Warmup
for (int i = 0; i < 50; i++) {
sb.clear();
sb.append("{\"events\":[],\"performances\":[]}");
std::string_view result;
sb.view().get(result);
}
// Benchmark
auto start = std::chrono::steady_clock::now();
size_t total_size = 0;
for (int iter = 0; iter < iterations; iter++) {
sb.clear(); // Clear and reuse the builder
sb.append("{\"events\":[");
for (size_t i = 0; i < names.size(); i++) {
if (i > 0) sb.append(',');
sb.append("{\"id\":");
sb.append(uint64_t(138586341 + i));
sb.append(",\"name\":\"");
sb.append(names[i]);
sb.append("\",\"description\":\"");
sb.append(descriptions[i]);
sb.append("\",\"topicIds\":[");
sb.append(uint64_t(324846099 + i));
sb.append(",");
sb.append(uint64_t(107888604 + i));
sb.append("]}");
}
sb.append("],\"performances\":[");
for (int i = 0; i < 500; i++) {
if (i > 0) sb.append(',');
sb.append("{\"id\":");
sb.append(uint64_t(339420000 + i));
sb.append(",\"eventId\":");
sb.append(uint64_t(138586341 + (i % 200)));
sb.append(",\"start\":");
sb.append(uint64_t(1572892800 + i * 3600));
sb.append(",\"venueCode\":\"VENUE_");
sb.append(uint64_t(i % 10));
sb.append("\"}");
}
sb.append("],\"venues\":[");
for (int i = 0; i < 50; i++) {
if (i > 0) sb.append(',');
sb.append("{\"id\":");
sb.append(uint64_t(1000 + i));
sb.append(",\"name\":\"Venue ");
sb.append(uint64_t(i));
sb.append("\",\"capacity\":");
sb.append(uint64_t(5000 + i * 100));
sb.append("}");
}
sb.append("]}");
std::string_view result;
sb.view().get(result);
total_size = result.size();
}
auto end = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
double seconds = duration.count() / 1000000.0;
double mb_per_sec = (total_size * iterations / 1024.0 / 1024.0) / seconds;
return mb_per_sec;
}
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " <twitter|citm>" << std::endl;
return 1;
}
std::string test_type = argv[1];
if (test_type == "twitter") {
double mb_per_sec = benchmark_twitter();
std::cout << mb_per_sec << std::endl;
} else if (test_type == "citm") {
double mb_per_sec = benchmark_citm();
std::cout << mb_per_sec << std::endl;
} else {
std::cerr << "Unknown test type: " << test_type << std::endl;
return 1;
}
return 0;
}
-297
View File
@@ -1,297 +0,0 @@
# Ablation Study Guide - simdjson C++26 Reflection
This guide explains how to run and analyze ablation studies for the simdjson C++26 reflection-based JSON serialization implementation.
## Prerequisites
1. **Compiler**: Clang with C++26 reflection support (bloomberg/clang-p2996)
2. **Build Tools**: CMake 3.25+, Make
3. **Analysis Tools**: Python 3, bc (basic calculator)
4. **System**: Linux/macOS with sufficient memory for compilation
## Quick Start
### Running the Complete Ablation Study
```bash
# Run both benchmarks with defaults (10 runs Twitter, 20 runs CITM)
./ablation_study.sh
# Run only Twitter benchmark with custom runs
./ablation_study.sh -b twitter -r 20
# Run with compilation time measurement
./ablation_study.sh --compilation-time
# Analyze results
python3 calculate_stats.py
```
## Important: Baseline Performance Verification
**CRITICAL**: Before running any ablation study, verify that your baseline performance is approximately **3,200 MB/s** for the Twitter benchmark. If you see significantly lower numbers (e.g., ~1,600 MB/s), the consteval optimization may not be active.
### Verify Baseline Performance
```bash
cd build
cmake .. -DCMAKE_CXX_COMPILER=clang++ \
-DSIMDJSON_DEVELOPER_MODE=ON \
-DSIMDJSON_STATIC_REFLECTION=ON \
-DBUILD_SHARED_LIBS=OFF \
-DCMAKE_BUILD_TYPE=Release
make benchmark_serialization_twitter -j4
./benchmark/static_reflect/twitter_benchmark/benchmark_serialization_twitter -f simdjson_static_reflection
```
Expected output:
```
bench_simdjson_static_reflection : 3164.70 MB/s 0.79 Ms/s
```
If you see ~1,600 MB/s instead, try:
1. Clean rebuild: `rm -rf build/*`
2. Verify include files are correct in `json_builder.h`
3. Check that `SIMDJSON_CONSTEVAL` is defined
## Understanding the Ablation Study
### What It Measures
The ablation study systematically disables optimizations to measure their individual contributions:
1. **Baseline**: All optimizations enabled (reference)
2. **No Consteval**: Disables compile-time string processing
3. **No SIMD Escaping**: Disables vectorized string escaping
4. **No Fast Digits**: Disables optimized integer-to-string conversion
5. **No Branch Hints**: Disables CPU branch prediction hints
6. **Linear Growth**: Uses linear instead of exponential buffer growth
### Output Format
Results are saved in CSV format to the `ablation_results` directory:
- `twitter_ablation_results.csv`: Twitter benchmark results
- `citm_ablation_results.csv`: CITM benchmark results
- `ablation_summary.txt`: Human-readable summary
CSV format:
```
Variant,Mean_MB/s,StdDev,CV%,Runs,Impact%,CompileTime_s
baseline,3164.70,36.93,1.17,10,0,44.02
no_consteval,1571.96,26.00,1.65,10,-50.3,40.31
```
## Step-by-Step Process
### 1. Prepare the Environment
```bash
# Navigate to simdjson directory
cd /path/to/simdjson
# Ensure build directory exists
mkdir -p build
# Make scripts executable
chmod +x ablation_study.sh
chmod +x calculate_stats.py
```
### 2. Run the Ablation Study
```bash
# Basic run (both benchmarks with optimal runs)
./ablation_study.sh
# Advanced options
./ablation_study.sh --help
# Run only CITM with custom runs (due to high variance)
./ablation_study.sh -b citm -c 30
# Include compilation time measurements
./ablation_study.sh --compilation-time
# Verbose mode for debugging
./ablation_study.sh --verbose
```
#### Key Options
- `-b, --benchmark`: Choose twitter, citm, or both (default: both)
- `-r, --runs`: Number of runs for Twitter (default: 10)
- `-c, --citm-runs`: Number of runs for CITM (default: 20 due to higher variance)
- `--compilation-time`: Also measure compilation time for each variant
- `-o, --output`: Output directory for results (default: ablation_results)
### 3. Monitor Progress
The script will show progress for each variant:
```
=== Processing variant: baseline ===
Results: Twitter,baseline,3164.70,36.93,10,44.02s compilation
=== Processing variant: no_consteval ===
Results: Twitter,no_consteval,1571.96,26.00,10,40.31s compilation
```
### 4. Analyze Results
```bash
# Process results with statistics
python3 calculate_stats.py
# Or specify a custom results file
python3 calculate_stats.py my_ablation_results.txt
```
Output will show:
- Mean throughput for each variant
- Standard deviation and coefficient of variation
- Performance impact relative to baseline
- Compilation time differences
Example output:
```
================================================================================
Twitter Benchmark Results
================================================================================
Variant Mean (MB/s) StdDev CV (%) Impact Compile (s)
------------------------- ------------ ---------- -------- ------------ ------------
**Baseline** 3164.70 ±36.93 1.17 Reference 44.02
No Consteval 1571.96 ±26.00 1.65 -50.3% 40.31
No Simd Escaping 2285.77 ±33.34 1.46 -27.8% 41.51
```
## Troubleshooting
### Issue: Low Baseline Performance
If baseline is ~1,600 MB/s instead of ~3,200 MB/s:
1. **Clean rebuild**:
```bash
cd build
rm -rf *
cmake .. # with proper flags
make benchmark_serialization_twitter -j4
```
2. **Check consteval is working**:
```bash
# Look for SIMDJSON_CONSTEVAL in the output
cmake .. -DCMAKE_BUILD_TYPE=Release -DSIMDJSON_STATIC_REFLECTION=ON -DCMAKE_VERBOSE_MAKEFILE=ON
```
3. **Verify includes**: Check that `json_builder.h` includes `json_string_builder-inl.h`
### Issue: CITM Benchmark Fails
The CITM benchmark has been fixed using `std::define_static_string`. If you still encounter issues, check `citm_issue.md` for details.
### Issue: Script Permissions
```bash
chmod +x ablation_study.sh
chmod +x calculate_stats.py
```
### Issue: Missing Dependencies
```bash
# Install bc (basic calculator)
sudo apt-get install bc # Ubuntu/Debian
brew install bc # macOS
```
## Manual Testing
To test individual optimization variants manually:
```bash
cd build
# Test specific variant
cmake .. -DCMAKE_CXX_FLAGS="-DSIMDJSON_ABLATION_NO_CONSTEVAL" -DCMAKE_BUILD_TYPE=Release
make benchmark_serialization_twitter -j4
./benchmark/static_reflect/twitter_benchmark/benchmark_serialization_twitter -f simdjson_static_reflection
```
## Understanding Results
### Performance Tiers
1. **Critical Optimizations (>25% impact)**:
- Consteval: ~50% performance improvement
- SIMD Escaping: ~28% performance improvement
2. **Moderate Optimizations (5-10% impact)**:
- Fast Digits: ~7% performance improvement
3. **Minor Optimizations (<5% impact)**:
- Branch Hints: ~2% performance improvement
- Buffer Growth Strategy: ~2% performance improvement
### Compilation Time
Interestingly, optimizations generally *reduce* compilation time:
- Baseline: ~44 seconds
- With optimizations disabled: ~40-42 seconds
This suggests that compile-time computation (consteval) actually speeds up overall compilation.
## Advanced Usage
### Running Specific Variants Only
Modify the `ABLATION_VARIANTS` array in `ablation_study.sh`:
```bash
declare -A ABLATION_VARIANTS=(
["baseline"]=""
["no_consteval"]="-DSIMDJSON_ABLATION_NO_CONSTEVAL"
# Add or remove variants as needed
)
```
### Custom Benchmarks
To add a new benchmark:
1. Add benchmark path to the script
2. Update the benchmark selection logic
3. Ensure the benchmark follows the expected output format
### Integration with CI/CD
```yaml
# Example GitHub Actions workflow
- name: Run Ablation Study
run: |
./ablation_study.sh -r 5 -c 10 -o ci_results
python3 calculate_stats.py ci_results > ablation_summary.txt
- name: Upload Results
uses: actions/upload-artifact@v3
with:
name: ablation-results
path: |
ci_ablation_results.txt
ablation_summary.txt
```
## Best Practices
1. **Consistency**: Always run the same number of iterations for reliable comparisons
2. **Clean State**: Start with a clean build directory for each full study
3. **System Load**: Run on a quiet system to minimize variance
4. **Temperature**: Allow system to cool between runs if thermal throttling is a concern
5. **Documentation**: Record system specs and compiler versions with results
## Further Reading
- `ablation_results.md`: Detailed analysis of optimization impacts
- `citm_issue.md`: Technical details about CITM compilation issues and resolution
- `ablation_study.sh`: Unified script source code with inline documentation
- `calculate_stats.py`: Statistical analysis implementation
-406
View File
@@ -1,406 +0,0 @@
# Ablation Study Results - simdjson C++26 Reflection Serialization
## Methodology
This ablation study evaluates the performance impact of various optimizations in simdjson's C++26 reflection-based JSON serialization implementation. The study uses a systematic approach to disable individual optimizations and measure their contribution to overall performance.
### Test Environment
- **Compiler**: Clang 21.0.0 (bloomberg/clang-p2996) with C++26 reflection support
- **Platform**: aarch64-unknown-linux-gnu
- **Build Type**: Release with `-O3` optimization
- **Benchmarks**:
- Twitter JSON (93,311 bytes) - Complete Twitter API response
- CITM Catalog (41,631 bytes) - Event catalog with maps and nested objects
- **Methodology**: 10 runs for Twitter, 20 runs for CITM per variant with statistical analysis
- **Date**: July 31, 2025
### Measurement Approach
Each optimization variant is tested by:
1. Rebuilding the library with specific ablation flags
2. Running the benchmark 10 times to ensure statistical significance
3. Calculating mean, standard deviation, and confidence intervals
4. Measuring both runtime performance and compilation time impact
## Instructions to Reproduce
### Quick Start
```bash
# Run the complete ablation study for both benchmarks with compilation time measurement
./ablation_study.sh --compilation-time
# Analyze the results
python3 calculate_stats.py
# View the summary
cat ablation_results/ablation_summary.txt
```
### Detailed Instructions
1. **Prepare the environment**:
```bash
# Ensure you're in the simdjson root directory
cd /path/to/simdjson
# Make scripts executable
chmod +x ablation_study.sh
chmod +x calculate_stats.py
# Verify build directory exists
mkdir -p build
```
2. **Run the ablation study**:
```bash
# Full study with optimal settings (10 runs Twitter, 20 runs CITM, with compilation time)
./ablation_study.sh --compilation-time
# Alternative: Run only one benchmark
./ablation_study.sh -b twitter -r 15 # Twitter only with 15 runs
./ablation_study.sh -b citm -c 30 # CITM only with 30 runs
# Alternative: Skip compilation time measurement for faster results
./ablation_study.sh # Both benchmarks, no compilation time
```
3. **Analyze the results**:
```bash
# Generate statistical analysis
python3 calculate_stats.py
# Alternative: Analyze results from a custom directory
python3 calculate_stats.py /path/to/custom/results
```
4. **View the outputs**:
```bash
# Results are saved in the ablation_results directory:
ls ablation_results/
# twitter_ablation_results.csv - Raw Twitter benchmark data
# citm_ablation_results.csv - Raw CITM benchmark data
# ablation_summary.txt - Human-readable summary
# View the summary
cat ablation_results/ablation_summary.txt
```
### Prerequisites
1. **Compiler**: Clang with C++26 reflection support (bloomberg/clang-p2996)
2. **Build Tools**: CMake 3.25+, Make
3. **Runtime Tools**: Python 3, bc (calculator)
4. **Performance Check**: Ensure baseline Twitter performance is ~3,200 MB/s before starting
### Expected Runtime
- Twitter benchmark (10 runs × 6 variants): ~2 minutes
- CITM benchmark (20 runs × 6 variants): ~4 minutes
- Compilation time measurement adds: ~5 minutes
- **Total with compilation time**: ~11 minutes
### Manual Testing of Individual Variants
```bash
# Example: Test No SIMD Escaping variant manually
cd build
cmake .. -DCMAKE_CXX_FLAGS="-DSIMDJSON_ABLATION_NO_SIMD_ESCAPING" -DCMAKE_BUILD_TYPE=Release
make benchmark_serialization_twitter -j4
./benchmark/static_reflect/twitter_benchmark/benchmark_serialization_twitter -f simdjson_static_reflection
```
## Optimization Details
### 1. Consteval Optimization (`SIMDJSON_ABLATION_NO_CONSTEVAL`)
**Purpose**: Enables compile-time string processing for JSON field names using C++26 reflection and `std::define_static_string` from P3491R3.
**Location**: `include/simdjson/generic/ondemand/json_builder.h:83-106`
**Implementation**:
```cpp
#if SIMDJSON_CONSTEVAL && !defined(SIMDJSON_ABLATION_NO_CONSTEVAL)
template<typename T>
struct atom_struct_impl<T, true> {
static void serialize(string_builder &b, const T &t) {
b.append('{');
bool first = true;
[:expand(std::meta::nonstatic_data_members_of(^^T, std::meta::access_context::unchecked())):] >> [&]<auto dm>() {
if (!first)
b.append(',');
first = false;
// Create a compile-time string using define_static_string
constexpr auto escaped_name = consteval_to_quoted_escaped(std::meta::identifier_of(dm));
constexpr const char* static_key = std::define_static_string(escaped_name);
b.append_raw(static_key);
b.append(':');
atom(b, t.[:dm:]);
};
b.append('}');
}
};
#else
// Runtime fallback: string concatenation at runtime
std::string key = "\"" + std::string(std::meta::identifier_of(dm)) + "\"";
#endif
```
**What it does**: Pre-computes escaped JSON field names at compile time and promotes them to static storage using `std::define_static_string`, avoiding runtime string allocation and escaping overhead.
### 2. SIMD String Escaping (`SIMDJSON_ABLATION_NO_SIMD_ESCAPING`)
**Purpose**: Uses vectorized instructions to check if strings need escaping.
**Location**: `include/simdjson/generic/ondemand/json_string_builder-inl.h:86-120`
**Implementation**:
```cpp
#ifdef SIMDJSON_ABLATION_NO_SIMD_ESCAPING
simdjson_inline bool fast_needs_escaping(std::string_view view) {
return simple_needs_escaping(view); // Scalar fallback
}
#elif SIMDJSON_EXPERIMENTAL_HAS_SSE2
simdjson_inline bool fast_needs_escaping(std::string_view view) {
const char* p = view.data();
const char* end = p + view.size();
// Process 16 bytes at a time with SIMD
const __m128i quote_mask = _mm_set1_epi8('"');
const __m128i backslash_mask = _mm_set1_epi8('\\');
const __m128i below_32_mask = _mm_set1_epi8(32);
while (end - p >= 16) {
__m128i v = _mm_loadu_si128(reinterpret_cast<const __m128i*>(p));
__m128i quotes = _mm_cmpeq_epi8(v, quote_mask);
__m128i backslashes = _mm_cmpeq_epi8(v, backslash_mask);
__m128i below_32 = _mm_cmplt_epi8(v, below_32_mask);
__m128i needs_escape = _mm_or_si128(_mm_or_si128(quotes, backslashes), below_32);
if (_mm_movemask_epi8(needs_escape)) {
return true;
}
p += 16;
}
// Handle remaining bytes with scalar code
return simple_needs_escaping(std::string_view(p, end - p));
}
#endif
```
**What it does**: Processes 16 bytes at a time to check for characters that need JSON escaping (quotes, backslashes, control characters).
### 3. Fast Digit Counting (`SIMDJSON_ABLATION_NO_FAST_DIGITS`)
**Purpose**: Optimizes integer-to-string conversion by pre-computing digit counts.
**Location**: `include/simdjson/generic/ondemand/json_string_builder-inl.h:449-490`
**Implementation**:
```cpp
template <typename number_type>
simdjson_inline size_t digit_count(number_type v) noexcept {
#ifdef SIMDJSON_ABLATION_NO_FAST_DIGITS
// Fallback: use standard library conversion to count digits
return std::to_string(v).length();
#else
return fast_digit_count(v); // Optimized bit manipulation
#endif
}
// Fast implementation using logarithmic properties
simdjson_inline int fast_digit_count(uint32_t x) noexcept {
// Avoid 64-bit math as much as possible.
// Adapted from: https://johnnylee-sde.github.io/Fast-digit-counting/
static constexpr uint32_t table[] = {
9, 99, 999, 9999, 99999, 999999, 9999999,
99999999, 999999999
};
int log2 = 31 - __builtin_clz(x | 1);
uint32_t digits = (log2 + 1) * 1233 >> 12;
return digits + (x > table[digits - 1]);
}
```
**What it does**: Avoids expensive string allocation and formatting by using bit manipulation and lookup tables to count digits.
### 4. Branch Prediction Hints (`SIMDJSON_ABLATION_NO_BRANCH_HINTS`)
**Purpose**: Provides hints to the CPU's branch predictor for better instruction pipelining.
**Location**: `include/simdjson/generic/ondemand/json_string_builder-inl.h:309-317`
**Implementation**:
```cpp
#ifdef SIMDJSON_ABLATION_NO_BRANCH_HINTS
if (upcoming_bytes <= capacity - position) {
return true;
}
if (position + upcoming_bytes < position) { // Overflow check
return false;
}
#else
if (simdjson_likely(upcoming_bytes <= capacity - position)) {
return true; // Fast path: enough space
}
if (simdjson_unlikely(position + upcoming_bytes < position)) {
return false; // Overflow detected
}
#endif
// Where simdjson_likely/unlikely are defined as:
#define simdjson_likely(x) __builtin_expect(!!(x), 1)
#define simdjson_unlikely(x) __builtin_expect(!!(x), 0)
```
**What it does**: Helps CPU predict which branches are more likely, reducing pipeline stalls.
### 5. Buffer Growth Strategy (`SIMDJSON_ABLATION_LINEAR_GROWTH`)
**Purpose**: Controls memory allocation strategy for the output buffer.
**Location**: `include/simdjson/generic/ondemand/json_string_builder-inl.h:327-332`
**Implementation**:
```cpp
#ifdef SIMDJSON_ABLATION_LINEAR_GROWTH
// Linear growth: add fixed 1KB chunks
grow_buffer(position + upcoming_bytes + 1024);
#else
// Exponential growth: double the capacity
grow_buffer((std::max)(capacity * 2, position + upcoming_bytes));
#endif
```
**What it does**: Exponential growth reduces the number of reallocations for large outputs, trading memory for speed.
## Performance Results
### Twitter Benchmark Results (10 Runs)
| Optimization Variant | Mean (MB/s) | Std Dev | CV (%) | Runtime Impact | Compilation Time (s) | Compilation Impact |
|---------------------|-------------|---------|--------|----------------|---------------------|-------------------|
| **Baseline** | **3,235.16** | ±20.78 | 0.64 | **Reference** | 22.88 | **Reference** |
| No Consteval | 1,610.22 | ±19.22 | 1.19 | **-50.2%** | 23.06 | +0.8% |
| No SIMD Escaping | 2,280.01 | ±22.07 | 0.97 | **-29.5%** | 22.40 | -2.1% |
| No Fast Digits | 3,041.88 | ±42.60 | 1.40 | **-6.0%** | 23.31 | +1.9% |
| No Branch Hints | 3,223.95 | ±9.66 | 0.30 | **-0.3%** | 23.11 | +1.0% |
| Linear Buffer Growth | 3,183.68 | ±39.42 | 1.24 | **-1.6%** | 22.86 | -0.1% |
### Statistical Analysis
**Baseline Performance**:
- Twitter: 3,235.16 MB/s (±20.78, CV: 0.64%)
- CITM: 2,278.05 MB/s (±263.44, CV: 11.56%)
**Key Findings**:
1. Twitter shows excellent consistency (CV < 1%), while CITM has high variance (CV: 11.56%)
2. Consteval optimization provides ~50% impact for both benchmarks
3. SIMD optimization: 29.5% impact for Twitter, 19.8% for CITM
4. Fast digits: minimal impact on Twitter (6%), significant on CITM (24.3%)
5. Buffer growth: minimal impact on Twitter (1.6%), massive on CITM (40.6%)
6. Compilation time impact is minimal (±2% for all variants)
### Performance Hierarchy
**Twitter Optimizations by Impact**:
1. **Tier 1 - Critical (>25% impact)**:
- Consteval: 50.2% performance loss when disabled
- SIMD Escaping: 29.5% performance loss when disabled
2. **Tier 2 - Moderate (5-10% impact)**:
- Fast Digits: 6.0% performance loss when disabled
3. **Tier 3 - Minor (<5% impact)**:
- Linear Buffer Growth: 1.6% performance loss when enabled
- Branch Hints: 0.3% performance loss when disabled
**CITM Optimizations by Impact**:
1. **Tier 1 - Critical (>25% impact)**:
- Consteval: 51.0% performance loss when disabled
- Linear Buffer Growth: 40.6% performance loss when enabled
2. **Tier 2 - Significant (15-25% impact)**:
- Fast Digits: 24.3% performance loss when disabled
- SIMD Escaping: 19.8% performance loss when disabled
3. **Tier 3 - Moderate (5-15% impact)**:
- Branch Hints: 6.0% performance loss when disabled
## CITM Catalog Benchmark
### Status Update (July 31, 2025)
The CITM Catalog benchmark issue has been **resolved** by using `std::define_static_string` from P3491R3. The benchmark now compiles and runs successfully with full consteval optimization.
### CITM Performance Results (20 Runs)
Using a CITM-like benchmark with similar data structures (maps, nested objects, 41KB JSON output):
| Optimization Variant | Mean (MB/s) | Std Dev | CV (%) | Runtime Impact | Compilation Time (s) | Compilation Impact |
|---------------------|-------------|---------|--------|----------------|---------------------|-------------------|
| **Baseline** | **2,278.05** | ±263.44 | 11.56 | **Reference** | 22.88 | **Reference** |
| No Consteval | 1,115.10 | ±38.71 | 3.47 | **-51.0%** | 23.06 | +0.8% |
| No SIMD Escaping | 1,826.12 | ±26.48 | 1.45 | **-19.8%** | 22.40 | -2.1% |
| No Fast Digits | 1,723.83 | ±69.55 | 4.03 | **-24.3%** | 23.31 | +1.9% |
| No Branch Hints | 2,141.79 | ±294.10 | 13.73 | **-6.0%** | 23.11 | +1.0% |
| Linear Buffer Growth | 1,352.53 | ±52.48 | 3.88 | **-40.6%** | 22.86 | -0.1% |
### CITM vs Twitter Performance Comparison
| Aspect | Twitter | CITM | Difference |
|--------|---------|------|------------|
| **Baseline Performance** | 3,235.16 MB/s | 2,278.05 MB/s | CITM is 29.6% slower |
| **Consteval Impact** | -50.2% | -51.0% | Nearly identical |
| **SIMD Impact** | -29.5% | -19.8% | 1.5x smaller for CITM |
| **Fast Digits Impact** | -6.0% | -24.3% | 4x larger for CITM |
| **Branch Hints Impact** | -0.3% | -6.0% | 20x larger for CITM |
| **Linear Growth Impact** | -1.6% | -40.6% | 25x larger for CITM |
### Key Findings
1. **Consteval optimization remains critical**: ~50% performance improvement for both benchmarks
2. **Different optimization profiles**: CITM benefits differently from various optimizations:
- **Fast Digits** has 4x larger impact on CITM (24.3% vs 6.0%)
- **SIMD Escaping** has 1.5x smaller impact on CITM (19.8% vs 29.5%)
- **Branch Hints** has 20x larger impact on CITM (6.0% vs 0.3%)
- **Buffer Growth** strategy has 25x larger impact on CITM (40.6% vs 1.6%)
3. **Why the differences?**
- **Maps vs Arrays**: CITM uses std::map extensively, making integer-to-string conversion (for map keys) more critical
- **Complex nesting**: Deeper object hierarchies benefit more from proper buffer growth strategies
- **Different string patterns**: CITM has different string escaping patterns than Twitter
- **Branch patterns**: Map iteration has more predictable patterns than expected
4. **Statistical observations with 20 runs**:
- CITM variance reduced from 19.09% to 11.56% with more runs
- Twitter maintains excellent consistency (CV: 0.64%)
- Some optimizations (No SIMD, No Consteval) actually reduce CITM variance
- Branch hints show highest variance for CITM (CV: 13.73%)
**Resolution Details**: By using `std::define_static_string` to promote compile-time strings to static storage, we avoid the constant expression limitations that previously prevented compilation. The threshold workaround is no longer needed. See `citm_issue.md` for technical details.
## Conclusions
1. **Consteval optimization is universally dominant**: Provides ~50% performance improvement across both Twitter and CITM benchmarks through compile-time field name generation
2. **Optimization impact varies by data structure**:
- **Twitter (array-heavy)**: Benefits most from SIMD (28%) and consteval (50%)
- **CITM (map-heavy)**: Benefits most from consteval (48.5%), fast digits (32.7%), and buffer growth (33.4%)
3. **Key insights from the comparison**:
- **SIMD effectiveness depends on string patterns**: 28% impact for Twitter vs 7.8% for CITM
- **Integer optimization critical for maps**: Fast digit counting has 5x larger impact on CITM due to map key serialization
- **Buffer growth strategy matters for complex structures**: 33.4% impact for CITM's nested maps vs 1.8% for Twitter's arrays
- **Branch prediction can backfire**: CITM performs 9.1% *better* without branch hints, likely due to unpredictable map iteration patterns
4. **Compilation overhead is negligible**: All optimizations have ±2% compilation time impact, with no clear pattern. The measured ~23 second compilation time is consistent across all variants.
5. **Statistical considerations**:
- Twitter shows excellent consistency (CV: 0.64%)
- CITM shows higher variance (CV: 11.56% with 20 runs, down from 19.09% with 10 runs)
- 20-run methodology recommended for CITM due to higher variance
- 10-run methodology sufficient for Twitter benchmarks
The ablation study demonstrates that modern C++ optimizations must be carefully tuned for different data structures. While consteval optimization provides consistent benefits, other optimizations like SIMD, fast digit counting, and buffer growth strategies have dramatically different impacts depending on whether the JSON structure is array-dominated (Twitter) or map-dominated (CITM).
+10 -7
View File
@@ -35,13 +35,16 @@ if (TARGET benchmark::benchmark)
endif()
endif()
if(SIMDJSON_STATIC_REFLECTION)
add_subdirectory(static_reflect)
endif(SIMDJSON_STATIC_REFLECTION)
include(CheckCXXCompilerFlag)
check_cxx_compiler_flag("-std=c++20" SIMDJSON_COMPILER_SUPPORTS_CXX20)
if(SIMDJSON_EXCEPTIONS AND SIMDJSON_COMPILER_SUPPORTS_CXX20)
add_subdirectory(from)
endif()
if(SIMDJSON_STATIC_REFLECTION)
add_subdirectory(static_reflect)
else()
if(SIMDJSON_EXCEPTIONS AND SIMDJSON_COMPILER_SUPPORTS_CXX20)
add_subdirectory(from)
add_subdirectory(car_builder)
endif()
endif(SIMDJSON_STATIC_REFLECTION)
-134
View File
@@ -1,134 +0,0 @@
# Unified Benchmark Results - JSON Parsing Performance
## Overview
Comparison of simdjson's C++26 static reflection implementation against traditional JSON libraries for parsing performance (JSON → C++ structs).
## Test Environment
- **Compiler**: bloomberg/clang-p2996 (C++26 with reflection support)
- **Platform**: Linux aarch64
- **Build Type**: Release with -O3
- **Methodology**: Conservative approach - fresh parser instance per iteration
- **Date**: August 2025
## Parsing Performance Results
### Twitter Parsing Benchmark (631KB, String-Heavy)
| Library/Method | Throughput | Latency | Speedup vs nlohmann |
|----------------|------------|---------|-------------------|
| **simdjson (manual)** | 3879.9 MB/s | 155.23 μs | 22.7x |
| **simdjson (reflection)** | 3708.9 MB/s | 162.38 μs | 21.7x |
| **simdjson::from()** | 3708.8 MB/s | 162.38 μs | 21.7x |
| nlohmann (extraction) | 170.7 MB/s | 3528.11 μs | 1.0x (baseline) |
| RapidJSON (extraction) | 663.1 MB/s | 908.26 μs | 3.9x |
### CITM Catalog Parsing Benchmark (1.7MB, Complex Objects)
| Library/Method | Throughput | Latency | Speedup vs nlohmann |
|----------------|------------|---------|-------------------|
| **simdjson (manual)** | 2848.8 MB/s | 578.21 μs | 14.5x |
| **simdjson (reflection)** | 2183.4 MB/s | 754.42 μs | 11.1x |
| **simdjson::from()** | 2169.8 MB/s | 759.16 μs | 11.0x |
| nlohmann (extraction) | 197.1 MB/s | 8357.74 μs | 1.0x (baseline) |
| RapidJSON (extraction) | 1355.6 MB/s | 1215.13 μs | 6.9x |
## Key Findings
1. **Reflection performs excellently**: Only 4-25% slower than manual implementation
2. **Massive speedup over traditional libraries**: 10-22x faster than nlohmann::json
3. **Parser reuse is critical**: simdjson uses parser reuse pattern for optimal performance
4. **String-heavy workloads favor simdjson**: Twitter shows better relative performance
## Performance Characteristics
### simdjson Advantages
- **Manual implementation**: Fastest possible, hand-optimized
- **Reflection**: Near-manual performance with automatic code generation
- **from() API**: Convenient extraction API with minimal overhead
- **Parser reuse**: Amortizes allocation costs across iterations
### Library Comparison
- **simdjson**: 2.2-3.9 GB/s throughput (conservative approach)
- **RapidJSON**: 0.7-1.4 GB/s throughput (3-7x slower)
- **nlohmann**: 170-200 MB/s throughput (11-23x slower)
## Implementation Notes
- **Conservative approach**: Fresh parser instance per iteration (realistic usage)
- **Reflection implementation**: Uses C++26 static reflection (P2996)
- **Compilation**: Standalone with -O3 optimization
- **Results**: Median of 500-1000 iterations
### Performance Difference vs Ablation Study
The unified benchmark shows ~15% higher throughput (3.7 vs 3.2 GB/s) compared to the ablation study due to:
- Standalone compilation with explicit -O3 flags
- Different link-time optimization settings
- Potential inlining threshold differences
Both measurements are valid - unified shows optimized build performance, ablation shows CMake build performance.
## Conclusion
simdjson's C++26 static reflection provides:
- **Near-manual performance** (within 4-25%)
- **10-22x speedup** over nlohmann::json
- **3-7x speedup** over RapidJSON
- **Automatic code generation** with reflection
This demonstrates that C++26 reflection can provide zero-cost abstractions for JSON parsing.
## Running Benchmarks with Serde Comparison
### Serialization Benchmarks (Including Serde)
The repository includes benchmarks comparing simdjson with Serde (Rust's serialization framework).
#### Prerequisites
- Rust and Cargo installed (`curl https://sh.rustup.rs -sSf | sh`)
- C++26-capable compiler with reflection support
#### Running the Benchmarks
```bash
# Build the benchmarks with Rust/Serde support
cd /path/to/simdjson/build
cmake .. -DSIMDJSON_DEVELOPER_MODE=ON \
-DSIMDJSON_STATIC_REFLECTION=ON \
-DCMAKE_BUILD_TYPE=Release
make benchmark_serialization_twitter benchmark_serialization_citm_catalog -j4
# Run Twitter serialization benchmark (all libraries)
./benchmark/static_reflect/twitter_benchmark/benchmark_serialization_twitter
# Run CITM serialization benchmark (all libraries)
./benchmark/static_reflect/citm_catalog_benchmark/benchmark_serialization_citm_catalog
# Run specific library comparison (comma-separated filters now supported!)
./benchmark/static_reflect/twitter_benchmark/benchmark_serialization_twitter -f simdjson_static_reflection,simdjson_to,rust
# List available benchmarks
./benchmark/static_reflect/twitter_benchmark/benchmark_serialization_twitter -l
```
#### Expected Results
**Twitter Dataset (631KB)**
- simdjson (builder API): ~3.21 GB/s
- simdjson::to API: ~2.85 GB/s
- Serde (Rust): ~1.73 GB/s
- reflect-cpp: ~1.49 GB/s
- nlohmann: ~0.18 GB/s
**CITM Dataset (1.7MB)**
- simdjson (builder API): ~2.37 GB/s
- simdjson::to API: ~2.15 GB/s
- reflect-cpp: ~1.19 GB/s
- Serde (Rust): ~1.17 GB/s
- nlohmann: ~0.10 GB/s
**Key Finding**: simdjson with C++26 reflection achieves 1.8-1.9x faster serialization than Serde.
Note: The benchmark includes a warning that Serde may use different data structures, but the performance comparison remains valid for real-world serialization scenarios.
-95
View File
@@ -1,95 +0,0 @@
#!/bin/bash
# Build script for the unified benchmark
# Automatically detects available libraries and builds accordingly
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(dirname "$SCRIPT_DIR")"
BUILD_DIR="$ROOT_DIR/build"
echo "=== Building Unified JSON Benchmark ==="
echo ""
# Check for clang++ with C++26 support
if ! command -v /usr/local/bin/clang++ &> /dev/null; then
echo "Error: Clang++ with C++26 support not found at /usr/local/bin/clang++"
echo "Please install the bloomberg/clang-p2996 compiler"
exit 1
fi
# Detect available libraries
COMPILE_FLAGS="-std=c++26 -freflection -O3"
COMPILE_FLAGS="$COMPILE_FLAGS -DSIMDJSON_STATIC_REFLECTION=1"
COMPILE_FLAGS="$COMPILE_FLAGS -DSIMDJSON_EXCEPTIONS=1"
INCLUDES="-I$ROOT_DIR/include"
echo "Checking for optional libraries..."
# Check for nlohmann/json
if [ -d "$BUILD_DIR/_deps/nlohmann_json-src" ]; then
echo "✓ Found nlohmann/json"
COMPILE_FLAGS="$COMPILE_FLAGS -DHAS_NLOHMANN"
INCLUDES="$INCLUDES -I$BUILD_DIR/_deps/nlohmann_json-src/include"
elif [ -d "$BUILD_DIR/build20/_deps/nlohmann_json-src" ]; then
echo "✓ Found nlohmann/json (in build20)"
COMPILE_FLAGS="$COMPILE_FLAGS -DHAS_NLOHMANN"
INCLUDES="$INCLUDES -I$BUILD_DIR/build20/_deps/nlohmann_json-src/include"
else
echo "✗ nlohmann/json not found (will skip nlohmann benchmarks)"
fi
# Check for RapidJSON
if [ -d "$BUILD_DIR/_deps/rapidjson-src" ]; then
echo "✓ Found RapidJSON"
COMPILE_FLAGS="$COMPILE_FLAGS -DHAS_RAPIDJSON"
INCLUDES="$INCLUDES -I$BUILD_DIR/_deps/rapidjson-src/include"
elif [ -d "$BUILD_DIR/build20/_deps/rapidjson-src" ]; then
echo "✓ Found RapidJSON (in build20)"
COMPILE_FLAGS="$COMPILE_FLAGS -DHAS_RAPIDJSON"
INCLUDES="$INCLUDES -I$BUILD_DIR/build20/_deps/rapidjson-src/include"
else
echo "✗ RapidJSON not found (will skip RapidJSON benchmarks)"
fi
echo ""
echo "Compiling unified benchmark..."
# Compile the benchmark
/usr/local/bin/clang++ \
$COMPILE_FLAGS \
$INCLUDES \
"$SCRIPT_DIR/unified_benchmark.cpp" \
"$ROOT_DIR/singleheader/simdjson.cpp" \
-o "$SCRIPT_DIR/unified_benchmark"
if [ $? -eq 0 ]; then
echo ""
echo "✓ Build successful!"
echo ""
echo "Running benchmark..."
echo "==================="
echo ""
# Run the benchmark from the correct directory
cd "$ROOT_DIR"
"$SCRIPT_DIR/unified_benchmark"
if [ $? -eq 0 ]; then
echo ""
echo "✓ Benchmark completed successfully!"
else
echo ""
echo "✗ Benchmark execution failed"
echo ""
echo "Note: The benchmark expects to find JSON files in:"
echo " jsonexamples/twitter.json"
echo " jsonexamples/citm_catalog.json"
exit 1
fi
else
echo ""
echo "✗ Build failed"
exit 1
fi
+14
View File
@@ -0,0 +1,14 @@
# Executable
add_executable(benchmark_car_builder benchmark_car_builder.cpp)
# Compile for C++20.
target_compile_features(benchmark_car_builder PRIVATE cxx_std_20)
# Check if -march=native is supported
include(CheckCXXCompilerFlag)
check_cxx_compiler_flag("-march=native" SIMDJSON_SUPPORTS_MARCH_NATIVE)
if(SIMDJSON_SUPPORTS_MARCH_NATIVE)
target_compile_options(benchmark_car_builder PRIVATE -march=native)
endif()
target_include_directories(benchmark_car_builder PRIVATE ${CMAKE_CURRENT_LIST_DIR}/..)
@@ -0,0 +1,127 @@
#include "event_counter.h"
#include <random>
#include <vector>
#include <simdjson.h>
event_collector collector;
struct Car {
std::string make;
std::string model;
int64_t year; // We deliberately do not include the tire pressure.
};
std::vector<Car> generate_random_cars(size_t count) {
static const std::vector<std::string> makes = {"Toyota", "Honda", "Ford",
"BMW", "Mazda"};
static const std::vector<std::string> models = {"Camry", "Civic", "Focus",
"320i", "3"};
static thread_local std::mt19937 rng{std::random_device{}()};
std::uniform_int_distribution<int> make_dist(0, makes.size() - 1);
std::uniform_int_distribution<int> model_dist(0, models.size() - 1);
std::uniform_int_distribution<int64_t> year_dist(2000, 2025);
std::uniform_real_distribution<double> pressure_dist(30.0, 45.0);
std::vector<Car> cars;
cars.reserve(count);
for (size_t i = 0; i < count; ++i) {
Car car;
car.make = makes[make_dist(rng)];
car.model = models[model_dist(rng)];
car.year = year_dist(rng);
cars.push_back(std::move(car));
}
return cars;
}
std::string_view serialize(simdjson::builder::string_builder &sb,
const std::vector<Car> &cars) {
sb.clear();
sb.start_array();
for (const auto &car : cars) {
sb.start_object();
sb.append_key_value("make", car.make);
sb.append_comma();
sb.append_key_value("model", car.model);
sb.append_comma();
sb.append_key_value("year", car.year);
sb.end_object();
}
sb.end_array();
std::string_view result;
if (sb.view().get(result)) {
return ""; // unexpected (error)
}
return result;
}
double pretty_print(const std::string &name, size_t num_chars,
std::pair<event_aggregate, size_t> result) {
const auto &agg = result.first;
size_t N = result.second;
num_chars *= N;
printf("%-40s : %8.2f ns %8.2f GB/s", name.c_str(),
agg.elapsed_ns() / num_chars, num_chars / agg.elapsed_ns());
if (collector.has_events()) {
printf(" %8.2f GHz %8.2f cycles/char %8.2f ins./char %8.2f i/c",
agg.cycles() / agg.elapsed_ns(), agg.cycles() / num_chars,
agg.instructions() / num_chars, agg.instructions() / agg.cycles());
}
printf("\n");
return num_chars / agg.elapsed_ns();
}
template <class function_type>
std::pair<event_aggregate, size_t>
bench(const function_type &&function, size_t min_repeat = 100,
size_t min_time_ns = 40'000'000, size_t max_repeat = 10000000) {
size_t N = min_repeat;
if (N == 0) {
N = 1;
}
event_aggregate warm_aggregate{};
for (size_t i = 0; i < N; i++) {
std::atomic_thread_fence(std::memory_order_acquire);
collector.start();
function();
std::atomic_thread_fence(std::memory_order_release);
event_count allocate_count = collector.end();
warm_aggregate << allocate_count;
if ((i + 1 == N) && (warm_aggregate.total_elapsed_ns() < min_time_ns) &&
(N < max_repeat)) {
N *= 10;
}
}
event_aggregate aggregate{};
for (size_t i = 0; i < 10; i++) {
std::atomic_thread_fence(std::memory_order_acquire);
collector.start();
for (size_t i = 0; i < N; i++) {
function();
}
std::atomic_thread_fence(std::memory_order_release);
event_count allocate_count = collector.end();
aggregate << allocate_count;
}
return {aggregate, N};
}
void run_benchmarks() {
std::vector<Car> source = generate_random_cars(100000);
simdjson::builder::string_builder sb;
size_t volume = serialize(sb, source).size();
pretty_print("string_builder", volume, bench([&source, &sb]() -> size_t {
return serialize(sb, source).size();
}));
}
int main() {
for (size_t trial = 0; trial < 3; trial++) {
printf("Trial %zu:\n", trial + 1);
run_benchmarks();
printf("\n");
}
return EXIT_SUCCESS;
}
+34 -30
View File
@@ -6,38 +6,42 @@ CPMAddPackage(
EXCLUDE_FROM_ALL YES
)
option(SIMDJSON_USE_RUST "Build the static_reflect benchmark" OFF)
if(NOT WIN32)
# We want the check whether Rust is available before trying to build a crate.
CPMAddPackage(
NAME corrosion
GITHUB_REPOSITORY corrosion-rs/corrosion
VERSION 0.4.4
DOWNLOAD_ONLY ON
OPTIONS "Rust_FIND_QUIETLY OFF"
)
include("${corrosion_SOURCE_DIR}/cmake/FindRust.cmake")
endif()
if(RUST_FOUND)
message(STATUS "Rust found: " ${Rust_VERSION} )
add_subdirectory("${corrosion_SOURCE_DIR}" "${PROJECT_BINARY_DIR}/_deps/corrosion" EXCLUDE_FROM_ALL)
# Important: we want to build in release mode!
corrosion_import_crate(MANIFEST_PATH "serde-benchmark/Cargo.toml" NO_LINKER_OVERRIDE PROFILE release)
else()
message(STATUS "Rust/Cargo is unavailable." )
message(STATUS "We will not benchmark serde-benchmark." )
if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
message(STATUS "Under macOS, you may be able to install rust with")
message(STATUS "curl https://sh.rustup.rs -sSf | sh")
elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux")
message(STATUS "Under Linux, you may be able to install rust with a command such as")
message(STATUS "apt-get install cargo" )
message(STATUS "or" )
message(STATUS "curl https://sh.rustup.rs -sSf | sh")
if(SIMDJSON_USER_RUST)
if(NOT WIN32)
# We want the check whether Rust is available before trying to build a crate.
CPMAddPackage(
NAME corrosion
GITHUB_REPOSITORY corrosion-rs/corrosion
VERSION 0.4.4
DOWNLOAD_ONLY ON
OPTIONS "Rust_FIND_QUIETLY OFF"
)
include("${corrosion_SOURCE_DIR}/cmake/FindRust.cmake")
endif()
endif()
if(RUST_FOUND)
message(STATUS "Rust found: " ${Rust_VERSION} )
add_subdirectory("${corrosion_SOURCE_DIR}" "${PROJECT_BINARY_DIR}/_deps/corrosion" EXCLUDE_FROM_ALL)
# Important: we want to build in release mode!
corrosion_import_crate(MANIFEST_PATH "serde-benchmark/Cargo.toml" NO_LINKER_OVERRIDE PROFILE release)
else()
message(STATUS "Rust/Cargo is unavailable." )
message(STATUS "We will not benchmark serde-benchmark." )
if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
message(STATUS "Under macOS, you may be able to install rust with")
message(STATUS "curl https://sh.rustup.rs -sSf | sh")
elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux")
message(STATUS "Under Linux, you may be able to install rust with a command such as")
message(STATUS "apt-get install cargo" )
message(STATUS "or" )
message(STATUS "curl https://sh.rustup.rs -sSf | sh")
endif()
endif()
else(SIMDJSON_USER_RUST)
message(STATUS "We will not benchmark serde-benchmark." )
endif(SIMDJSON_USER_RUST)
# Add the benchmark executable targets
add_subdirectory(twitter_benchmark)
@@ -95,24 +95,6 @@ void bench_simdjson_static_reflection(CitmCatalog &data) {
}));
}
#if SIMDJSON_STATIC_REFLECTION
void bench_simdjson_to(CitmCatalog &data) {
std::string output = simdjson::to_json_string(data);
size_t output_volume = output.size();
printf("# output volume: %zu bytes\n", output_volume);
volatile size_t measured_volume = 0;
pretty_print(sizeof(data), output_volume, "bench_simdjson_to",
bench([&data, &measured_volume, &output_volume]() {
std::string output = simdjson::to_json_string(data);
measured_volume = output.size();
if (measured_volume != output_volume) {
printf("mismatch\n");
}
}));
}
#endif
std::string read_file(const std::string &file_path, size_t read_size = 65536) {
std::ifstream stream(file_path, std::ios::binary);
if(!stream) {
@@ -129,24 +111,9 @@ std::string read_file(const std::string &file_path, size_t read_size = 65536) {
return out;
}
// Function to check if benchmark name matches any of the comma-separated filters
// Function to check if benchmark name contains filter substring
bool matches_filter(const std::string& benchmark_name, const std::string& filter) {
if (filter.empty()) return true;
// Split filter by comma
size_t start = 0;
size_t end = filter.find(',');
while (end != std::string::npos) {
std::string token = filter.substr(start, end - start);
if (benchmark_name.find(token) != std::string::npos) {
return true;
}
start = end + 1;
end = filter.find(',', start);
}
// Check last token
std::string token = filter.substr(start);
return benchmark_name.find(token) != std::string::npos;
return filter.empty() || benchmark_name.find(filter) != std::string::npos;
}
int main(int argc, char* argv[]) {
@@ -186,14 +153,9 @@ int main(int argc, char* argv[]) {
if (matches_filter("simdjson_static_reflection", filter)) {
bench_simdjson_static_reflection(my_struct);
}
#if SIMDJSON_STATIC_REFLECTION
if (matches_filter("simdjson_to", filter)) {
bench_simdjson_to(my_struct);
}
#endif
#ifdef SIMDJSON_RUST_VERSION
if (matches_filter("rust", filter)) {
printf("# Note: Rust/Serde structures updated to closely match C++ (indices field remains as array).\n");
printf("# WARNING: The Rust benchmark may not be directly comparable since it does not use an equivalent data structure.\n");
// Create a Rust-compatible CitmCatalog structure from the JSON string
serde_benchmark::CitmCatalog* rust_data =
serde_benchmark::citm_from_str(json_str.c_str(), json_str.size());
@@ -4,65 +4,79 @@
#include <string>
#include <vector>
#include <map>
#include <optional>
#include <cstdint>
// Price structure with simpler field names to avoid reflection issues
struct CITMPrice {
uint64_t amount;
uint64_t audience; // was audienceSubCategoryId
uint64_t seat; // was seatCategoryId
bool operator==(const CITMPrice&) const = default;
struct Area {
int64_t id;
std::string name;
int64_t parent;
std::vector<int64_t> childAreas;
bool operator==(const Area &other) const = default;
};
struct CITMArea {
uint64_t areaId;
std::vector<uint64_t> blockIds;
bool operator==(const CITMArea&) const = default;
struct AudienceSubCategory {
int64_t id;
std::string name;
int64_t parent;
bool operator==(const AudienceSubCategory &other) const = default;
};
struct CITMSeatCategory {
std::vector<CITMArea> areas;
uint64_t seatCategoryId;
bool operator==(const CITMSeatCategory&) const = default;
struct Event {
int64_t id;
std::string name;
std::string description;
int64_t subTopic;
int64_t topic;
std::vector<int64_t> audience;
bool operator==(const Event &other) const = default;
};
struct CITMPerformance {
uint64_t id;
uint64_t eventId;
std::optional<std::string> logo;
std::optional<std::string> name;
std::vector<CITMPrice> prices;
std::vector<CITMSeatCategory> seatCategories;
std::optional<std::string> seatMapImage;
uint64_t start;
std::string venueCode;
bool operator==(const CITMPerformance&) const = default;
struct Performance {
int64_t id;
std::string name;
int64_t event;
std::string start;
int64_t venueCode;
bool operator==(const Performance &other) const = default;
};
struct CITMEvent {
uint64_t id;
std::string name;
std::optional<std::string> description;
std::optional<std::string> logo;
std::vector<uint64_t> subTopicIds;
std::optional<std::string> subjectCode;
std::optional<std::string> subtitle;
std::vector<uint64_t> topicIds;
bool operator==(const CITMEvent&) const = default;
struct SeatCategory {
int64_t id;
std::string name;
std::vector<int64_t> areas;
bool operator==(const SeatCategory &other) const = default;
};
struct SubTopic {
int64_t id;
std::string name;
int64_t parent;
bool operator==(const SubTopic &other) const = default;
};
struct Topic {
int64_t id;
std::string name;
bool operator==(const Topic &other) const = default;
};
struct Venue {
int64_t id;
std::string name;
int64_t address;
bool operator==(const Venue &other) const = default;
};
struct CitmCatalog {
std::map<std::string, CITMEvent> events;
std::vector<CITMPerformance> performances;
bool operator==(const CitmCatalog&) const = default;
std::map<std::string, Area> areas;
std::map<std::string, AudienceSubCategory> audienceSubCategory;
std::map<std::string, Event> events;
std::map<std::string, Performance> performances;
std::map<std::string, SeatCategory> seatCategory;
std::map<std::string, SubTopic> subTopic;
std::map<std::string, Topic> topic;
std::map<std::string, Venue> venue;
bool operator==(const CitmCatalog &other) const = default;
};
// Type aliases
using Event = CITMEvent;
using Performance = CITMPerformance;
using Price = CITMPrice;
using SeatArea = CITMArea;
using SeatCategoryInfo = CITMSeatCategory;
#endif
#endif
@@ -8,72 +8,164 @@
using json = nlohmann::json;
// ---- CITMPrice ----
inline void to_json(json &j, const CITMPrice &p) {
// ---- Area ----
inline void to_json(json &j, const Area &a) {
j = json{
{"amount", p.amount},
{"audienceSubCategoryId", p.audience},
{"seatCategoryId", p.seat}
{"id", a.id},
{"name", a.name},
{"parent", a.parent},
{"childAreas", a.childAreas}
};
}
// ---- CITMArea ----
inline void to_json(json &j, const CITMArea &a) {
j = json{
{"areaId", a.areaId},
{"blockIds", a.blockIds}
};
inline void from_json(const json &j, Area &a) {
j.at("id").get_to(a.id);
j.at("name").get_to(a.name);
j.at("parent").get_to(a.parent);
j.at("childAreas").get_to(a.childAreas);
}
// ---- CITMSeatCategory ----
inline void to_json(json &j, const CITMSeatCategory &s) {
// ---- AudienceSubCategory ----
inline void to_json(json &j, const AudienceSubCategory &asc) {
j = json{
{"areas", s.areas},
{"seatCategoryId", s.seatCategoryId}
{"id", asc.id},
{"name", asc.name},
{"parent", asc.parent}
};
}
// ---- CITMPerformance ----
inline void to_json(json &j, const CITMPerformance &p) {
j = json{
{"id", p.id},
{"eventId", p.eventId},
{"logo", p.logo},
{"name", p.name},
{"prices", p.prices},
{"seatCategories", p.seatCategories},
{"seatMapImage", p.seatMapImage},
{"start", p.start},
{"venueCode", p.venueCode}
};
inline void from_json(const json &j, AudienceSubCategory &asc) {
j.at("id").get_to(asc.id);
j.at("name").get_to(asc.name);
j.at("parent").get_to(asc.parent);
}
// ---- CITMEvent ----
inline void to_json(json &j, const CITMEvent &e) {
// ---- Event ----
inline void to_json(json &j, const Event &e) {
j = json{
{"id", e.id},
{"name", e.name},
{"description", e.description},
{"logo", e.logo},
{"subTopicIds", e.subTopicIds},
{"subjectCode", e.subjectCode},
{"subtitle", e.subtitle},
{"topicIds", e.topicIds}
{"subTopic", e.subTopic},
{"topic", e.topic},
{"audience", e.audience}
};
}
inline void from_json(const json &j, Event &e) {
j.at("id").get_to(e.id);
j.at("name").get_to(e.name);
j.at("description").get_to(e.description);
j.at("subTopic").get_to(e.subTopic);
j.at("topic").get_to(e.topic);
j.at("audience").get_to(e.audience);
}
// ---- Performance ----
inline void to_json(json &j, const Performance &p) {
j = json{
{"id", p.id},
{"name", p.name},
{"event", p.event},
{"start", p.start},
{"venueCode", p.venueCode}
};
}
inline void from_json(const json &j, Performance &p) {
j.at("id").get_to(p.id);
j.at("name").get_to(p.name);
j.at("event").get_to(p.event);
j.at("start").get_to(p.start);
j.at("venueCode").get_to(p.venueCode);
}
// ---- SeatCategory ----
inline void to_json(json &j, const SeatCategory &sc) {
j = json{
{"id", sc.id},
{"name", sc.name},
{"areas", sc.areas}
};
}
inline void from_json(const json &j, SeatCategory &sc) {
j.at("id").get_to(sc.id);
j.at("name").get_to(sc.name);
j.at("areas").get_to(sc.areas);
}
// ---- SubTopic ----
inline void to_json(json &j, const SubTopic &st) {
j = json{
{"id", st.id},
{"name", st.name},
{"parent", st.parent}
};
}
inline void from_json(const json &j, SubTopic &st) {
j.at("id").get_to(st.id);
j.at("name").get_to(st.name);
j.at("parent").get_to(st.parent);
}
// ---- Topic ----
inline void to_json(json &j, const Topic &t) {
j = json{
{"id", t.id},
{"name", t.name}
};
}
inline void from_json(const json &j, Topic &t) {
j.at("id").get_to(t.id);
j.at("name").get_to(t.name);
}
// ---- Venue ----
inline void to_json(json &j, const Venue &v) {
j = json{
{"id", v.id},
{"name", v.name},
{"address", v.address}
};
}
inline void from_json(const json &j, Venue &v) {
j.at("id").get_to(v.id);
j.at("name").get_to(v.name);
j.at("address").get_to(v.address);
}
// ---- CitmCatalog ----
inline void to_json(json &j, const CitmCatalog &c) {
j = json{
{"areas", c.areas},
{"audienceSubCategory", c.audienceSubCategory},
{"events", c.events},
{"performances", c.performances}
{"performances", c.performances},
{"seatCategory", c.seatCategory},
{"subTopic", c.subTopic},
{"topic", c.topic},
{"venue", c.venue}
};
}
inline void from_json(const json &j, CitmCatalog &c) {
j.at("areas").get_to(c.areas);
j.at("audienceSubCategory").get_to(c.audienceSubCategory);
j.at("events").get_to(c.events);
j.at("performances").get_to(c.performances);
j.at("seatCategory").get_to(c.seatCategory);
j.at("subTopic").get_to(c.subTopic);
j.at("topic").get_to(c.topic);
j.at("venue").get_to(c.venue);
}
// Serialization function
// Optional convenience functions for benchmarking
inline std::string nlohmann_serialize(const CitmCatalog &catalog) {
json j = catalog;
return j.dump();
}
inline bool nlohmann_deserialize(const std::string &json_in, CitmCatalog &catalog) {
try {
catalog = json::parse(json_in);
return false; // success
} catch(...) {
return true; // failure
}
}
#endif // NLOHMANN_CITM_CATALOG_DATA_H
@@ -14,12 +14,12 @@ use serde::de::{self, Deserializer};
/******************************************************/
/******************************************************/
// Removed - not in C++ structure
// #[derive(Serialize, Deserialize)]
// pub struct Metadata {
// result_type: String,
// iso_language_code: String,
// }
// This has no equivalent in C++:
#[derive(Serialize, Deserialize)]
pub struct Metadata {
result_type: String,
iso_language_code: String,
}
#[derive(Serialize, Deserialize)]
pub struct User {
@@ -29,16 +29,47 @@ pub struct User {
screen_name: String,
location: String,
description: String,
// C++ does not have those:
// url: Option<String>,
//protected: bool,
//listed_count: i64,
//created_at: String,
//favourites_count: i64,
//utc_offset: Option<i64>,
//time_zone: Option<String>,
//geo_enabled: bool,
verified: bool,
followers_count: i64,
friends_count: i64,
statuses_count: i64,
// C++ does not have those:
//lang: String,
//profile_background_color: String,
//profile_background_image_url: String,
//profile_background_image_url_https: String,
//profile_background_tile: bool,
//profile_image_url: String,
//profile_image_url_https: String,
//profile_banner_url: Option<String>,
//profile_link_color: String,
//profile_sidebar_border_color: String,
//profile_sidebar_fill_color: String,
//profile_text_color: String,
//profile_use_background_image: bool,
//default_profile: bool,
//default_profile_image: bool,
//following: bool,
//follow_request_sent: bool,
//notifications: bool,
}
#[derive(Serialize, Deserialize)]
pub struct Hashtag {
text: String,
indices: Vec<i64>, // Array in JSON, not separate fields
// C++ has those but D. Lemire does not know what they are, they don't appear in the JSON:
// int64_t indices_start;
// int64_t indices_end;
}
#[derive(Serialize, Deserialize)]
@@ -46,7 +77,9 @@ pub struct Url {
url: String,
expanded_url: String,
display_url: String,
indices: Vec<i64>, // Array in JSON, not separate fields
// C++ has those but D. Lemire does not know what they are, they don't appear in the JSON:
// int64_t indices_start;
// int64_t indices_end;
}
#[derive(Serialize, Deserialize)]
@@ -54,7 +87,12 @@ pub struct UserMention {
id: i64,
name: String,
screen_name: String,
indices: Vec<i64>, // Array in JSON, not separate fields
// Not in the C++ equivalent:
//id_str: String,
//indices: Vec<i64>,
// C++ has those but D. Lemire does not know what they are, they don't appear in the JSON:
// int64_t indices_start;
// int64_t indices_end;
}
#[derive(Serialize, Deserialize)]
@@ -74,24 +74,6 @@ template <class T> void bench_simdjson_static_reflection(T &data) {
}));
}
#if SIMDJSON_STATIC_REFLECTION
template <class T> void bench_simdjson_to(T &data) {
std::string output = simdjson::to_json_string(data);
size_t output_volume = output.size();
printf("# output volume: %zu bytes\n", output_volume);
volatile size_t measured_volume = 0;
pretty_print(sizeof(data), output_volume, "bench_simdjson_to",
bench([&data, &measured_volume, &output_volume]() {
std::string output = simdjson::to_json_string(data);
measured_volume = output.size();
if (measured_volume != output_volume) {
printf("mismatch\n");
}
}));
}
#endif
void bench_nlohmann(TwitterData &data) {
std::string output = nlohmann_serialize(data);
size_t output_volume = output.size();
@@ -127,24 +109,9 @@ std::string read_file(std::string filename) {
return out;
}
// Function to check if benchmark name matches any of the comma-separated filters
// Function to check if benchmark name contains filter substring
bool matches_filter(const std::string& benchmark_name, const std::string& filter) {
if (filter.empty()) return true;
// Split filter by comma
size_t start = 0;
size_t end = filter.find(',');
while (end != std::string::npos) {
std::string token = filter.substr(start, end - start);
if (benchmark_name.find(token) != std::string::npos) {
return true;
}
start = end + 1;
end = filter.find(',', start);
}
// Check last token
std::string token = filter.substr(start);
return benchmark_name.find(token) != std::string::npos;
return filter.empty() || benchmark_name.find(filter) != std::string::npos;
}
int main(int argc, char* argv[]) {
@@ -184,14 +151,9 @@ int main(int argc, char* argv[]) {
if (matches_filter("simdjson_static_reflection", filter)) {
bench_simdjson_static_reflection(my_struct);
}
#if SIMDJSON_STATIC_REFLECTION
if (matches_filter("simdjson_to", filter)) {
bench_simdjson_to(my_struct);
}
#endif
#ifdef SIMDJSON_RUST_VERSION
if (matches_filter("rust", filter)) {
printf("# Note: Rust/Serde structures updated to closely match C++ (indices field remains as array).\n");
printf("# WARNING: The Rust benchmark may not be directly comparable since it does not use an equivalent data structure.\n");
serde_benchmark::TwitterData * td = serde_benchmark::twitter_from_str(json_str.c_str(), json_str.size());
bench_rust(td);
serde_benchmark::free_twitter(td);
File diff suppressed because it is too large Load Diff
-32
View File
@@ -1,32 +0,0 @@
#!/bin/bash
# Clean build script for simdjson reflection benchmark
set -e
# Get the directory where this script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Navigate to simdjson root directory (where this script is located)
cd "$SCRIPT_DIR"
# Clean any existing build
rm -rf build
# Create new build directory
mkdir build
cd build
# Configure with the specified settings
cmake .. \
-DCMAKE_CXX_COMPILER=clang++ \
-DSIMDJSON_DEVELOPER_MODE=ON \
-DSIMDJSON_STATIC_REFLECTION=ON \
-DBUILD_SHARED_LIBS=OFF \
-DCMAKE_BUILD_TYPE=Release
# Build the specific target
make benchmark_serialization_twitter
echo "Build completed successfully!"
echo "To run the benchmark with simdjson static reflection filter, use:"
echo "./benchmark/static_reflect/twitter_benchmark/benchmark_serialization_twitter -f simdjson_static_reflection"
-113
View File
@@ -1,113 +0,0 @@
#!/bin/bash
# Build script for the unified JSON benchmark
# This compiles the benchmark with all available libraries
echo "Building Unified JSON Benchmark..."
# Check for dependencies directories
NLOHMANN_PATH=""
RAPIDJSON_PATH=""
SERDE_PATH=""
# Try multiple possible locations for dependencies
for dir in build build20 build26; do
if [ -d "$dir/_deps/nlohmann_json-src/include" ]; then
NLOHMANN_PATH="-I./$dir/_deps/nlohmann_json-src/include -DHAS_NLOHMANN"
echo "✓ Found nlohmann/json in $dir"
break
fi
done
if [ -z "$NLOHMANN_PATH" ]; then
echo "✗ nlohmann/json not found"
fi
for dir in build build20 build26; do
if [ -d "$dir/_deps/rapidjson-src/include" ]; then
RAPIDJSON_PATH="-I./$dir/_deps/rapidjson-src/include -DHAS_RAPIDJSON"
echo "✓ Found RapidJSON in $dir"
break
fi
done
if [ -z "$RAPIDJSON_PATH" ]; then
echo "✗ RapidJSON not found"
fi
# Check for Serde benchmark library (.so or .a)
if [ -f "benchmark/static_reflect/serde-benchmark/target/release/libserde_benchmark.so" ] || [ -f "benchmark/static_reflect/serde-benchmark/target/release/libserde_benchmark.a" ]; then
SERDE_PATH="-L./benchmark/static_reflect/serde-benchmark/target/release -lserde_benchmark -ldl -lpthread -DHAS_SERDE"
echo "✓ Found Serde benchmark library"
else
echo "✗ Serde benchmark library not found"
echo " To build it: cd benchmark/static_reflect/serde-benchmark && cargo build --release"
fi
# Check for yyjson
YYJSON_PATH=""
YYJSON_LIB=""
if [ -d "build/_deps/yyjson-src/src" ] || [ -f "build/dependencies/libyyjson.a" ]; then
if [ -f "build/dependencies/libyyjson.a" ]; then
YYJSON_PATH="-I./build/_deps/yyjson-src/src -DHAS_YYJSON"
YYJSON_LIB="build/dependencies/libyyjson.a"
echo "✓ Found yyjson library"
elif [ -f "build/_deps/yyjson-build/libyyjson.a" ]; then
YYJSON_PATH="-I./build/_deps/yyjson-src/src -DHAS_YYJSON"
YYJSON_LIB="build/_deps/yyjson-build/libyyjson.a"
echo "✓ Found yyjson library"
fi
else
echo "✗ yyjson not found"
fi
# Note: reflect-cpp disabled due to complex linking requirements
# REFLECTCPP_PATH=""
# Compile the benchmark
clang++ -std=c++26 \
-freflection \
-fexpansion-statements \
-stdlib=libc++ \
-DSIMDJSON_STATIC_REFLECTION=1 \
-DSIMDJSON_EXCEPTIONS=1 \
-I./include \
-I./benchmark/static_reflect/serde-benchmark \
$NLOHMANN_PATH \
$RAPIDJSON_PATH \
$YYJSON_PATH \
-O3 \
benchmark/unified_benchmark.cpp \
singleheader/simdjson.cpp \
$YYJSON_LIB \
$SERDE_PATH \
-o benchmark/unified_benchmark
if [ $? -eq 0 ]; then
echo ""
echo "Build successful! Run with: ./benchmark/unified_benchmark"
echo ""
echo "The benchmark will test:"
echo " - Twitter dataset (631KB)"
echo " - CITM Catalog dataset (1.7MB)"
echo ""
echo "With the following methods:"
echo " - simdjson manual parsing"
echo " - simdjson reflection parsing"
echo " - simdjson::from() API"
if [ ! -z "$NLOHMANN_PATH" ]; then
echo " - nlohmann/json"
fi
if [ ! -z "$RAPIDJSON_PATH" ]; then
echo " - RapidJSON"
fi
if [ ! -z "$SERDE_PATH" ]; then
echo " - Serde (Rust)"
fi
if [ ! -z "$REFLECTCPP_PATH" ]; then
echo " - reflect-cpp"
fi
else
echo "Build failed!"
exit 1
fi
-174
View File
@@ -1,174 +0,0 @@
#!/usr/bin/env python3
"""
Calculate statistics from ablation study results.
This script processes the CSV output from ablation_study.sh
and generates formatted statistical summaries.
"""
import sys
import csv
import os
from pathlib import Path
def read_csv_results(filename):
"""Read CSV results file and return data."""
results = []
try:
with open(filename, 'r') as f:
reader = csv.DictReader(f)
for row in reader:
results.append({
'variant': row['Variant'],
'mean': float(row['Mean_MB/s']),
'stdev': float(row['StdDev']),
'cv': float(row['CV%']),
'runs': int(row['Runs']),
'impact': float(row['Impact%']),
'compile_time': float(row['CompileTime_s'])
})
except FileNotFoundError:
return None
except Exception as e:
print(f"Error reading {filename}: {e}")
return None
return results
def print_results_table(title, results):
"""Print formatted results table."""
if not results:
return
print(f"\n{'='*80}")
print(f"{title}")
print(f"{'='*80}")
# Print header
print(f"\n{'Variant':<25} {'Mean (MB/s)':<12} {'Std Dev':<10} {'CV (%)':<8} {'Impact':<12} {'Compile (s)':<12}")
print(f"{'-'*25} {'-'*12} {'-'*10} {'-'*8} {'-'*12} {'-'*12}")
for result in results:
variant_display = result['variant'].replace('_', ' ').title()
if result['variant'] == 'baseline':
variant_display = "**Baseline**"
impact_str = "Reference"
else:
impact_str = f"{result['impact']:+.1f}%"
print(f"{variant_display:<25} {result['mean']:<12.2f} ±{result['stdev']:<8.2f} "
f"{result['cv']:<8.2f} {impact_str:<12} {result['compile_time']:<12.2f}")
def print_comparison_table(twitter_results, citm_results):
"""Print comparison table between Twitter and CITM results."""
if not twitter_results or not citm_results:
return
print(f"\n{'='*80}")
print("Performance Comparison: Twitter vs CITM")
print(f"{'='*80}")
print(f"\n{'Optimization':<25} {'Twitter Impact':<15} {'CITM Impact':<15} {'Difference':<20}")
print(f"{'-'*25} {'-'*15} {'-'*15} {'-'*20}")
# Create lookup dictionaries
twitter_dict = {r['variant']: r for r in twitter_results}
citm_dict = {r['variant']: r for r in citm_results}
for variant in ['no_consteval', 'no_simd_escaping', 'no_fast_digits', 'no_branch_hints', 'linear_growth']:
if variant in twitter_dict and variant in citm_dict:
twitter_impact = twitter_dict[variant]['impact']
citm_impact = citm_dict[variant]['impact']
variant_display = variant.replace('_', ' ').title()
diff_abs = abs(citm_impact - twitter_impact)
if abs(twitter_impact) > 0.1:
diff_factor = citm_impact / twitter_impact
diff_str = f"{diff_factor:.1f}x"
else:
diff_str = "Different direction"
print(f"{variant_display:<25} {twitter_impact:>+14.1f}% {citm_impact:>+14.1f}% {diff_str:<20}")
def print_summary_insights(twitter_results, citm_results):
"""Print summary insights from the ablation study."""
print(f"\n{'='*80}")
print("Key Insights")
print(f"{'='*80}\n")
if twitter_results and citm_results:
# Find baseline performance
twitter_baseline = next((r['mean'] for r in twitter_results if r['variant'] == 'baseline'), 0)
citm_baseline = next((r['mean'] for r in citm_results if r['variant'] == 'baseline'), 0)
print(f"1. Baseline Performance:")
print(f" - Twitter: {twitter_baseline:.2f} MB/s")
print(f" - CITM: {citm_baseline:.2f} MB/s")
print(f" - CITM is {((citm_baseline / twitter_baseline - 1) * 100):.1f}% slower than Twitter\n")
# Find most impactful optimizations
print(f"2. Most Impactful Optimizations:")
all_impacts = []
for r in twitter_results[1:]: # Skip baseline
all_impacts.append(('Twitter', r['variant'], r['impact']))
for r in citm_results[1:]: # Skip baseline
all_impacts.append(('CITM', r['variant'], r['impact']))
all_impacts.sort(key=lambda x: abs(x[2]), reverse=True)
for i, (bench, variant, impact) in enumerate(all_impacts[:5]):
variant_display = variant.replace('_', ' ').title()
print(f" {i+1}. {variant_display} on {bench}: {impact:+.1f}%")
print(f"\n3. Variance Analysis:")
twitter_cv = next((r['cv'] for r in twitter_results if r['variant'] == 'baseline'), 0)
citm_cv = next((r['cv'] for r in citm_results if r['variant'] == 'baseline'), 0)
print(f" - Twitter baseline CV: {twitter_cv:.2f}%")
print(f" - CITM baseline CV: {citm_cv:.2f}%")
print(f" - CITM shows {citm_cv / twitter_cv:.1f}x higher variance than Twitter")
def main():
# Default to ablation_results directory
results_dir = "ablation_results"
# Allow custom directory as argument
if len(sys.argv) > 1:
results_dir = sys.argv[1]
# Check if directory exists
if not os.path.exists(results_dir):
print(f"Error: Results directory '{results_dir}' not found.")
print("Please run ablation_study.sh first.")
sys.exit(1)
# Read results files
twitter_file = os.path.join(results_dir, "twitter_ablation_results.csv")
citm_file = os.path.join(results_dir, "citm_ablation_results.csv")
twitter_results = read_csv_results(twitter_file)
citm_results = read_csv_results(citm_file)
if not twitter_results and not citm_results:
print("No results found. Please run ablation_study.sh first.")
sys.exit(1)
# Print results
if twitter_results:
print_results_table("Twitter Benchmark Results", twitter_results)
if citm_results:
print_results_table("CITM Benchmark Results", citm_results)
if twitter_results and citm_results:
print_comparison_table(twitter_results, citm_results)
print_summary_insights(twitter_results, citm_results)
print(f"\n{'='*80}")
print("Statistical Analysis Complete")
print(f"{'='*80}")
if __name__ == "__main__":
main()
+8 -1
View File
@@ -4,7 +4,7 @@
add_library(simdjson-internal-flags INTERFACE)
if(NOT DEFINED CMAKE_POSITION_INDEPENDENT_CODE)
# We default to ON for all targets, so that we can use the library in shared libraries.
set_target_properties(simdjson-internal-flags PROPERTIES POSITION_INDEPENDENT_CODE ON)
set_target_properties(simdjson-internal-flags PROPERTIES INTERFACE_POSITION_INDEPENDENT_CODE ON)
endif(NOT DEFINED CMAKE_POSITION_INDEPENDENT_CODE)
option(SIMDJSON_CHECK_EOF "Check for the end of the input buffer. The setting is unnecessary since we require padding of the inputs. You should expect tests to fail with this option turned on." OFF)
@@ -32,6 +32,9 @@ undefined behavior.")
link_libraries(
-fsanitize=address -fno-omit-frame-pointer -fno-sanitize-recover=all
)
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
add_compile_options(-fsanitize=address)
link_libraries(-fsanitize=address)
else()
message(
STATUS
@@ -171,6 +174,10 @@ else()
-Werror -Wall -Wextra -Weffc++ -Wsign-compare -Wshadow -Wwrite-strings
-Wpointer-arith -Winit-self -Wconversion -Wno-sign-conversion
)
if(CMAKE_CXX_STANDARD VERSION_GREATER_EQUAL 20)
target_compile_options(simdjson-internal-flags INTERFACE -Wctad-maybe-unsupported)
endif()
endif()
option(SIMDJSON_GLIBCXX_ASSERTIONS "Set _GLIBCXX_ASSERTIONS" OFF)
@@ -0,0 +1,4 @@
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR riscv64)
set(CMAKE_CROSSCOMPILING_EMULATOR "qemu-riscv64-static")
-83
View File
@@ -1,83 +0,0 @@
#!/usr/bin/env python3
import sys
import json
def parse_perf_script(input_file, output_file):
"""Convert perf script output to Perfetto JSON format"""
samples = []
current_sample = None
with open(input_file, 'r') as f:
for line in f:
line = line.strip()
if not line:
continue
# New sample line
if 'cpu-clock:pppH:' in line:
if current_sample and current_sample['stack']:
samples.append(current_sample)
parts = line.split()
timestamp = float(parts[2].rstrip(':')) * 1000000 # Convert to microseconds
current_sample = {
'ts': timestamp,
'stack': [],
'name': 'cpu-clock'
}
# Stack frame
elif line.startswith('\t') and current_sample:
# Extract function name from the line
parts = line.strip().split()
if len(parts) >= 2:
func_info = parts[1]
# Clean up function name
if '+' in func_info:
func_name = func_info.split('+')[0]
else:
func_name = func_info
# Skip unknown symbols
if func_name != '[unknown]':
current_sample['stack'].append(func_name)
# Add last sample
if current_sample and current_sample['stack']:
samples.append(current_sample)
# Create Perfetto trace format
trace = {
'traceEvents': [],
'samples': [],
'stacks': {}
}
# Convert to Perfetto sampling profiler format
for i, sample in enumerate(samples):
if sample['stack']:
# Reverse stack for bottom-up view
stack = list(reversed(sample['stack']))
# Create a stack ID
stack_id = str(i)
trace['stacks'][stack_id] = stack
# Add sample event
trace['samples'].append({
'ts': sample['ts'],
'sf': stack_id, # Stack frame ID
'pid': 1,
'tid': 1,
'weight': 1
})
# Write JSON output
with open(output_file, 'w') as f:
json.dump(trace, f, indent=2)
print(f"Converted {len(samples)} samples to Perfetto format")
print(f"Output written to {output_file}")
if __name__ == "__main__":
parse_perf_script("perf_simdjson_serialization.txt", "perf_simdjson_perfetto.json")
+176 -21
View File
@@ -54,7 +54,7 @@ The simdjson library is widely deployed in popular systems such as the Node.js r
environment.
- A recent compiler (LLVM clang 6 or better, GNU GCC 7.4 or better, Xcode 11 or better) on POSIX systems such as macOS, FreeBSD or Linux. We require that the compiler supports the C++11 standard or better. We test the library on a big-endian system (IBM s390x with Linux).
- Visual Studio 2017 or better. We support the LLVM clang compiler under Visual Studio (clang-cl) as well as as the regular Visual Studio compiler. For better release performance (both compile time and execution time), we recommend Visual Studio users adopt LLVM (clang-cl). We discourage against using GCC under Windows: there [is a long-running bug with GCC under Windows](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54412).
- Visual Studio 2017 or better. We support the LLVM clang compiler under Visual Studio (clang-cl) as well as the regular Visual Studio compiler. For better release performance (both compile time and execution time), we recommend Visual Studio users adopt LLVM (clang-cl). We discourage using GCC under Windows: there [is a long-running bug with GCC under Windows](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54412).
Support for AVX-512 require a processor with AVX512-VBMI2 support (Ice Lake or better, AMD Zen 4 or better) under a 64-bit system and a recent compiler (LLVM clang 6 or better, GCC 8 or better, Visual Studio 2019 or better). You need a correspondingly recent assembler such as gas (2.30+) or nasm (2.14+): recent compilers usually come with recent assemblers. If you mix a recent compiler with an incompatible/old assembler (e.g., when using a recent compiler with an old Linux distribution), you may get errors at build time because the compiler produces instructions that the assembler does not recognize: you should update your assembler to match your compiler (e.g., upgrade binutils to version 2.30 or better under Linux) or use an older compiler matching the capabilities of your assembler.
@@ -78,14 +78,14 @@ c++ myproject.cpp simdjson.cpp
```
Note:
- We recommend that you use simdjson by copying the single-header `simdjson.h` file along with the source file `simdjson.cpp` directly in your project, as they are part of [every release](https://github.com/simdjson/simdjson/releases) as assets. In this manner, you only have to compile `simdjson.cpp` as any other source file: it works well in every development environment. However, you may also use simdjson as a git submodule ([example](https://github.com/simdjson/cmakedemo)), using FetchContent ([example](https://github.com/simdjson/cmake_demo_single_file)), with ExternalProject_Add ([example](https://github.com/simdjson/cmakedemo_externalproject)) or with CPM ([example](https://github.com/cpm-cmake/CPM.cmake/tree/master/examples/simdjson)).
- We recommend that you use simdjson by copying the single-header `simdjson.h` file along with the source file `simdjson.cpp` directly into your project, as they are part of [every release](https://github.com/simdjson/simdjson/releases) as assets. In this manner, you only have to compile `simdjson.cpp` as any other source file: it works well in every development environment. However, you may also use simdjson as a git submodule ([example](https://github.com/simdjson/cmakedemo)), using FetchContent ([example](https://github.com/simdjson/cmake_demo_single_file)), with ExternalProject_Add ([example](https://github.com/simdjson/cmakedemo_externalproject)) or with CPM ([example](https://github.com/cpm-cmake/CPM.cmake/tree/master/examples/simdjson)).
- Users on macOS and other platforms where default compilers do not provide C++11 compliant by default should request it with the appropriate flag (e.g., `c++ -std=c++11 myproject.cpp simdjson.cpp`).
- The library relies on [runtime CPU detection](implementation-selection.md): avoid specifying an architecture at compile time (e.g., `-march-native`) if you want your binaries to run everywhere.
Using simdjson with package managers
------------------
You can install the simdjson library on your system or in your project using multiple package managers such as MSYS2, the conan package manager, vcpkg, brew, the apt package manager (debian-based Linux systems), the FreeBSD package manager (FreeBSD), and so on. E.g., [we provide an complete example with vcpkg](https://github.com/simdjson/simdjson-vcpkg) that works under Windows. [Visit our wiki for more details](https://github.com/simdjson/simdjson/wiki/Installing-simdjson-with-a-package-manager).
You can install the simdjson library on your system or in your project using multiple package managers such as MSYS2, the conan package manager, vcpkg, brew, the apt package manager (debian-based Linux systems), the FreeBSD package manager (FreeBSD), and so on. E.g., [we provide a complete example with vcpkg](https://github.com/simdjson/simdjson-vcpkg) that works under Windows. [Visit our wiki for more details](https://github.com/simdjson/simdjson/wiki/Installing-simdjson-with-a-package-manager).
@@ -320,7 +320,7 @@ At the cost of some memory allocation, you may convert your `std::string_view` i
For convenience, we also allow [storing an escaped string directly into an existing string instance](#storing-directly-into-an-existing-string-instance).
The `std::string_view` class has become standard as part of C++17 but it is not always available
on compilers which only supports C++11. When we detect that `string_view` is natively
on compilers that only supports C++11. When we detect that `string_view` is natively
available, we define the macro `SIMDJSON_HAS_STRING_VIEW`.
When we detect that it is unavailable,
@@ -343,7 +343,7 @@ We recommend that you first compile and run your code in debug mode:
The simdjson code will set `SIMDJSON_DEVELOPMENT_CHECKS=1` in debug mode. Because
the C++ standard does not provide a direct way of checking for a debug build, and
because you may want the checks while building with otimizations, you can set
because you may want the checks while building with optimizations, you can set
the macro `SIMDJSON_DEVELOPMENT_CHECKS` to 1 prior to including
the `simdjson.h` header to enable these additional checks: just make sure you remove the
definition once your code has been tested. When `SIMDJSON_DEVELOPMENT_CHECKS` is set to 1, the
@@ -371,9 +371,8 @@ and arrays (`simdjson::ondemand::array`).
We also have a generic ephemeral type (`simdjson::ondemand::value`) which represents a potential
array or object, or scalar type (`double`, `uint64_t`, `int64_t`, `bool`, `null`, string) inside
an array or an object. Both generic types (`simdjson::ondemand::document` and
`simdjson::ondemand::value`) have a `type()` method returning a `json_type` value describing the
value (`json_type::array`, `json_type::object`, `json_type::number`, `json_type::string`,
`json_type::boolean`, `json_type::null`). The `type()` method does not consume nor validate the value: e.g., you must still call `is_null()` to check that the value is a `null` even if `json_type::null` is returned. Starting with simdjson 4.0, we return `json_type::unknown` for bad tokens such as the `NaN` token in `{"key":NaN}`. A `json_type::unknown` type value indicates an error in the JSON document but you might still be able to proceed, see [General direct access to the raw JSON string](#general-direct-access-to-the-raw-json-string). A generic value (`simdjson::ondemand::value`)
`simdjson::ondemand::value`) have a `type()` method returning a `json_type` value describing indicating the type (`json_type::array`, `json_type::object`, `json_type::number`, `json_type::string`,
`json_type::boolean`, `json_type::null`, and `json_type::unknown` for unrecognized types). The `type()` method does not consume nor validate the value: e.g., you must still call `is_null()` to check that the value is a `null` even if `json_type::null` is returned. Starting with simdjson 4.0, we return `json_type::unknown` for bad tokens such as the `NaN` token in `{"key":NaN}`. A `json_type::unknown` type value indicates an error in the JSON document but you might still be able to proceed, see [General direct access to the raw JSON string](#general-direct-access-to-the-raw-json-string). A generic value (`simdjson::ondemand::value`)
is only valid temporarily, as soon as you access other values, other keys in objects, etc.
it becomes invalid: you should therefore consume the value immediately by converting it to a
scalar type, an array or an object.
@@ -406,7 +405,7 @@ support for users who avoid exceptions. See [the simdjson error handling documen
ondemand::object and ondemand::array. We also have explicit methods such as `get_string()`, `get_double()`,
`get_uint64()`, `get_int64()`, `get_bool()`, `get_object()` and `get_array()`. After a cast or an explicit method,
the number, string or boolean will be parsed, or the initial `{` or `[` will be verified for `ondemand::object` and `ondemand::array`. An exception may be thrown if
the cast is not possible: there error code is `simdjson::INCORRECT_TYPE` (see [Error handling](#error-handling)). Importantly, when getting an ondemand::object or ondemand::array instance, its content is
the cast is not possible: the error code is `simdjson::INCORRECT_TYPE` (see [Error handling](#error-handling)). Importantly, when getting an ondemand::object or ondemand::array instance, its content is
not validated: you are only guaranteed that the corresponding initial character (`{` or `[`) is present. Thus,
for example, you could have an ondemand::object instance pointing at the invalid JSON `{ "this is not a valid object" }`: the validation occurs as you access the content.
The `get_string()` returns a valid UTF-8 string, after
@@ -453,7 +452,7 @@ support for users who avoid exceptions. See [the simdjson error handling documen
* **Field Access:** To get the value of the "foo" field in an object, use `object["foo"]`. This will
scan through the object looking for the field with the matching string, doing a character-by-character
comparison. It may generate the error `simdjson::NO_SUCH_FIELD` if there is no such key in the object, it may throw an exception (see [Error handling](#error-handling)). For efficiency reason, you should avoid looking up the same field repeatedly: e.g., do
not do `object["foo"]` followed by `object["foo"]` with the same `object` instance. For best performance, you should try to query the keys in the same order they appear in the document. If you need several keys and you cannot predict the order they will appear in, it is recommended to iterate through all keys `for(auto field : object) {...}`. Generally, you should not mix and match iterating through an object (`for(auto field : object) {...}`) and key accesses (`object["foo"]`): if you need to iterate through an object after a key access, you need to call `reset()` on the object. Whenever you call `reset()`, you need to keep in mind that though you can iterate over the array repeatedly, values should be consumedonly once (e.g., repeatedly calling `unescaped_key()` on the same key is forbidden). Keep in mind that On-Demand does not buffer or save the result of the parsing: if you repeatedly access `object["foo"]`, then it must repeatedly seek the key and parse the content. The library does not provide a distinct function to check if a key is present, instead we recommend you attempt to access the key: e.g., by doing `ondemand::value val{}; if (!object["foo"].get(val)) {...}`, you have that `val` contains the requested value inside the if clause. It is your responsibility as a user to temporarily keep a reference to the value (`auto v = object["foo"]`), or to consume the content and store it in your own data structures. If you consume an
not do `object["foo"]` followed by `object["foo"]` with the same `object` instance. Generally, you should not mix and match iterating through an object (`for(auto field : object) {...}`) and key accesses (`object["foo"]`): if you need to iterate through an object after a key access, you need to call `reset()` on the object. Whenever you call `reset()`, you need to keep in mind that though you can iterate over the array repeatedly, values should be consumedonly once (e.g., repeatedly calling `unescaped_key()` on the same key is forbidden). Keep in mind that On-Demand does not buffer or save the result of the parsing: if you repeatedly access `object["foo"]`, then it must repeatedly seek the key and parse the content. The library does not provide a distinct function to check if a key is present, instead we recommend you attempt to access the key: e.g., by doing `ondemand::value val{}; if (!object["foo"].get(val)) {...}`, you have that `val` contains the requested value inside the if clause. It is your responsibility as a user to temporarily keep a reference to the value (`auto v = object["foo"]`), or to consume the content and store it in your own data structures. If you consume an
object twice: `std::string_view(object["foo"]` followed by `std::string_view(object["foo"]` then your code
is in error. Furthermore, you can only consume one field at a time, on the same object. The
value instance you get from `content["bids"]` becomes invalid when you call `content["asks"]`.
@@ -516,7 +515,7 @@ support for users who avoid exceptions. See [the simdjson error handling documen
> double y = doc["y"]; // The cursor is now after the 2 (at })
> double x = doc["x"]; // Success: [] loops back around to find "x"
> ```
* **Output to strings:** Given a document, a value, an array or an object in a JSON document, you can output a JSON string version suitable to be parsed again as JSON content: `simdjson::to_json_string(element)`. A call to `to_json_string` consumes fully the element: if you apply it on a document, the JSON pointer is advanced to the end of the document. The `simdjson::to_json_string` does not allocate memory. The `to_json_string` function should not be confused with retrieving the value of a string instance which are escaped and represented using a lightweight `std::string_view` instance pointing at an internal string buffer inside the parser instance. To illustrate, the first of the following two code segments will print the unescaped string `"test"` complete with the quote whereas the second one will print the escaped content of the string (without the quotes).
* **Output to strings:** Given a document, a value, an array or an object in a JSON document, you can output a JSON string version suitable to be parsed again as JSON content: `simdjson::to_json_string(element)`. A call to `to_json_string` consumes fully the element: if you apply it on a document, the internal pointer is advanced to the end of the document. The `simdjson::to_json_string` does not allocate memory. The `to_json_string` function should not be confused with retrieving the value of a string instance which are escaped and represented using a lightweight `std::string_view` instance pointing at an internal string buffer inside the parser instance. To illustrate, the first of the following two code segments will print the unescaped string `"test"` complete with the quote whereas the second one will print the escaped content of the string (without the quotes).
> ```C++
> // serialize a JSON to an escaped std::string instance so that it can be parsed again as JSON
> auto silly_json = R"( { "test": "result" } )"_padded;
@@ -1376,7 +1375,16 @@ your code with the `SIMDJSON_STATIC_REFLECTION` macro set:
Then you can deserialize a type such as `Car` automatically:
```cpp
```C++
struct Car {
std::string make;
std::string model;
int year;
std::vector<float> tire_pressure;
};
std::string json = R"( { "make": "Toyota", "model": "Camry", "year": 2018,
"tire_pressure": [ 40.1, 39.9 ] } )";
simdjson::ondemand::parser parser;
@@ -1385,6 +1393,111 @@ Car c = doc.get<Car>();
```
We try to automate the parsing of any given structure or class
by looking at its non-static public members. At compile-time,
the library looks at a simple structure like `Car` and
maps it to parsing code. We call the default constructor,
and then assign values to the public members.
If a key is missing in the JSON document, an error is generated (`NO_SUCH_FIELD`),
except if the attribute is of a type like `std::optional` (`simdjson::concepts::optional_type`).
Sometimes you might want to only extract some attributes from the JSON. You can
achieve this result with the `extract_into` method supported by both `object` and
`document` instances. It returns an error code that evaluates to false when there
is no error.
Consider the following example where you only want to parse the make and the model
from the JSON:
```cpp
struct car_type {
std::string make;
std::string model;
uint64_t year;
std::vector<double> tire_pressure;
};
void f() {
auto json = R"( {
"make": "Toyota",
"model": "Camry",
"year": 2024,
"tire_pressure": [ 40.1, 39.9 ]
} )"_padded;
ondemand::parser parser;
ondemand::document doc = parser.iterate(json);
Car car{};
auto error = doc.extract_into<"make","model">(car);
if(error) { /** error handling */ }
// only car.make and car.
}
```
#### Special cases
However, there are instances where the construction cannot
be easily automated. Let us consider a class without any
public member.
```cpp
class MyDate {
public:
void assign(std::string_view str) {
date_str = str;
}
const std::string& to_string() const {
return date_str;
}
private:
std::string date_str;
};
```
This class has a default constructor, but it must be initialized
with the `assign` method. We need to help the library with
a `tag_invoke` function (just as in the C++20 case).
```cpp
namespace simdjson {
template <typename simdjson_value>
auto tag_invoke(deserialize_tag, simdjson_value &val, MyDate& date) {
std::string_view str;
auto error = val.get_string().get(str);
if(error) { return error; }
date.assign(str);
return simdjson::SUCCESS;
}
} // namespace simdjson
```
Once this is done, we can now automatically parse a custom type
like `complicated_weather_data` containing `MyDate` values.
```cpp
struct complicated_weather_data {
std::vector<MyDate> time;
std::vector<float> temperature;
};
```
The code might be as simple as the following.
```cpp
auto padded = R"({"time":["2023-03-15T12:00:00Z"],"temperature":[42]})"_padded;
simdjson::ondemand::parser parser;
simdjson::ondemand::document doc = parser.iterate(padded);
complicated_weather_data p = doc.get<complicated_weather_data>();
```
Thus you can combine C++26 static reflection with custom deserialization
functions.
You can also automatically serialize the `Car` instance to a JSON string, see
our [Builder documentation](builder.md).
@@ -1400,6 +1513,12 @@ type without a document instance like so:
Car car = simdjson::from(json);
```
You can also use the `simdjson::from` syntax without exceptions, like so:
```cpp
Car car;
simdjson::error_code err = simdjson::from(json_car).get(car);
```
You can also use the `simdjson::from` syntax to iterate over an array.
```cpp
@@ -1460,9 +1579,9 @@ If you find yourself needing only fast Unicode functions, consider using the sim
JSON Pointer
------------
The simdjson library also supports [JSON pointer](https://tools.ietf.org/html/rfc6901) through the `at_pointer()` method, letting you reach further down into the document in a single call. JSON pointer is supported by both the [DOM approach](https://github.com/simdjson/simdjson/blob/master/doc/dom.md#json-pointer) as well as the On-Demand approach.
The simdjson library also supports [JSON pointer](https://tools.ietf.org/html/rfc6901) through the `at_pointer()` method, letting you reach further down into the document in a single call. JSON Pointer is supported by both the [DOM approach](https://github.com/simdjson/simdjson/blob/master/doc/dom.md#json-pointer) as well as the On-Demand approach.
**Note:** The On-Demand implementation of JSON pointer relies on `find_field` which implies that it does not unescape keys when matching.
**Note:** The On-Demand implementation of JSON Pointer relies on `find_field` which implies that it does not unescape keys when matching.
Consider the following example:
@@ -1482,7 +1601,7 @@ index allows you to select the indexed node. Within objects, the string value of
select the value. If your keys contain the characters '/' or '~', they must be escaped as '~1' and
'~0' respectively. An empty JSON Pointer Path refers to the whole document.
For multiple JSON pointer queries on a document, one can call `at_pointer` multiple times.
For multiple JSON Pointer queries on a document, one can call `at_pointer` multiple times.
```c++
auto cars_json = R"( [
@@ -1637,7 +1756,7 @@ x = obj.at_path("$.d.foo2.a.2"); // 30
Error handling
--------------
Error handing with exception and a single try/catch clause makes the code simple, but it gives you little control over errors. For easier debugging or more robust error handling, you may want to consider our exception-free approach.
Error handling with exception and a single try/catch clause makes the code simple, but it gives you little control over errors. For easier debugging or more robust error handling, you may want to consider our exception-free approach.
The entire simdjson API is usable with and without exceptions. All simdjson APIs that can fail return `simdjson_result<T>`, which is a &lt;value, error_code&gt;
pair. You can retrieve the value with .get() without generating an exception, like so:
@@ -2688,15 +2807,16 @@ a parameter a reference to a `std::string`.
ondemand::parser parser;
ondemand::document doc = parser.iterate(json);
std::string name;
doc["name"].get_string(name);
auto error = doc["name"].get_string(name);
if(error) { /* handle error */ }
```
The same routine can be written without exceptions handling:
```C++
std::string name;
auto err = doc["name"].get_string(name);
if (err) { /* handle error */ }
auto error = doc["name"].get_string(name);
if (error) { /* handle error */ }
```
The `std::string` instance, once created, is independent. Unlike our `std::string_view` instances,
@@ -3099,10 +3219,45 @@ Performance tips
- The On-Demand front-end works best when doing a single pass over the input: avoid calling `count_elements`, `rewind`, `reset` and similar methods.
- If you are familiar with assembly language, you may use the online tool godbolt to explore the compiled code. The following example may work: [https://godbolt.org/z/xE4GWs573](https://godbolt.org/z/xE4GWs573).
- Given a field `field` in an object, calling `field.key()` is often faster than `field.unescaped_key()` so if you do not need an unescaped `std::string_view` instance, prefer `field.key()`. Similarly, we expect `field.escaped_key()` to be faster than `field.unescaped_key()` even though both return a `std::string_view` instance.
- For release builds, we recommend setting `NDEBUG` pre-processor directive when compiling the `simdjson` library. Importantly, using the optimization flags `-O2` or `-O3` under GCC and LLVM clang does not set the `NDEBUG` directive, you must set it manually (e.g., `-DNDEBUG`).
- For release builds, we recommend setting the `NDEBUG` pre-processor directive when compiling the `simdjson` library. Importantly, using the optimization flags `-O2` or `-O3` under GCC and LLVM clang does not set the `NDEBUG` directive, you must set it manually (e.g., `-DNDEBUG`).
- For long streams of JSON documents, consider [`iterate_many`](iterate_many.md) and [`parse_many`](parse_many.md) for better performance.
- Never seek to access a field twice (e.g., o["data"] and later again o["data"]). Instead capture once an ondemand::value and reuse it.
- If you must access several different keys in an object, it might be preferable to iterate through all the fields in the object instead, and branch on the field keys.
- If you must access several different keys in an object, it might be preferable to iterate through all the fields in the object instead, and branch on the field keys. Consider this example.
```cpp
auto json = R"({"price": 123.456789, "volume": 9999,
"timestamp": "2025-09-04T09:45:00Z",
"symbol": "XYZ", "currency": "USD", "change": 1.23,
"isActive": true})"_padded;
simdjson::ondemand::parser parser;
simdjson::ondemand::document doc = parser.iterate(json);
for(auto keyvalue : doc.get_object()) {
simdjson::ondemand::raw_json_string key = keyvalue.key();
switch(key[0]) {
case 'p': // price
if (key == "price") {
std::string_view price_str = keyvalue.value().raw_json();
std::cout << "Price: " << price_str << std::endl;
}
break;
case 'v': // volume
if (key == "volume") {
std::string_view volume_str = keyvalue.value().raw_json();
std::cout << "Volume: " << volume_str << std::endl;
}
break;
case 't': // timestamp
if (key == "timestamp") {
std::string_view timestamp = keyvalue.value();
std::cout << "Timestamp: " << timestamp << std::endl;
}
break;
default: break;
}
}
```
- If possible, refer to each object and array in your code once. For example, the following code repeatedly refers to the `"data"` key to create an object...
```C++
std::string_view make = o["data"]["make"];
+123 -13
View File
@@ -34,27 +34,28 @@ It has the following methods to add content to the string:
- `append_null()`: Appends the string "null" to the JSON buffer.
- `clear()`: Clears the contents of the JSON buffer, resetting the position to 0 while retaining the allocated capacity.
- `escape_and_append(std::string_view input)`: Appends a string view to the JSON buffer after escaping special characters (e.g., quotes, backslashes) as required by JSON.
- `escape_and_append_with_quotes(std::string_view input)` Appends a string view surrounded by double quotes (e.g., "input") to the JSON buffer after escaping special characters.
Parameters:
- `escape_and_append_with_quotes(std::string_view input)` Appends a string view surrounded by double quotes (e.g., "input") to the JSON buffer after escaping special characters. For constant strings, you may also do `escape_and_append_with_quotes<"mystring">()`.
- `escape_and_append_with_quotes(char input)`: Appends a single character surrounded by double quotes (e.g., "c") to the JSON buffer after escaping it if necessary.
- `append_raw(const char *c)`: Appends a null-terminated C string directly to the JSON buffer without escaping.
- `append_raw(std::string_view input)`: Appends a string view directly to the JSON buffer without escaping.
- `append_raw(const char *str, size_t len)`: Appends a specified number of characters from a C string directly to the JSON
- `append_key_value(key,value)`: Appends a key and a value (`"json":somevalue`)
- `append_key_value<"mykey">(value)`: Appends a key and a value (`"json":somevalue`), useful when the key is a compile-time constant (C++20).
After writting the content, if you have reasons to believe that the content might violate UTF-8 conventions, you can check it as follows:
After writing the content, if you have reasons to believe that the content might violate UTF-8 conventions, you can check it as follows:
- `validate_unicode()`: Checks if the content in the JSON buffer is valid UTF-8. Returns: true if the content is valid UTF-8, false otherwise.
You might need to do unicode validation if you have strings in your data structures containing
malformed UTF-8.
malformed UTF-8. Note that we do not automatically call `validate_unicode()`.
Once you are satisfied, you can recover the string as follows:
- `operator std::string()`: Converts the JSON buffer to an std::string. (Might throw if an error occurred.)
- `operator std::string_view()`: Converts the JSON buffer to an std::string_view. (Might throw if an error occurred.)
- `view()`: Returns a view of the written JSON buffer as a `simdjson_result<std::string_view>`.
- `view()`: Returns a view of the written JSON buffer as a `simdjson_result<std::string_view>` (C++20).
The later method (`view()`) is recommended.
The later method (`view()`) is recommended. For performance reasons, we expect you to explicitly call `validate_unicode()` as needed (e.g., prior to calling `view()`).
Example: string_builder
---------------------------
@@ -131,20 +132,20 @@ In all cases, the `std::string_view` instance depends the corresponding `string_
If you have C++20, you can simplify the code, as the `std::vector<double>` is automatically
supported.
If you have C++20, you can simplify the code, as the `std::vector<double>` is automatically supported. Further, we can pass the keys (which are compile-time
constant) as template parameter (for improved performance).
```cpp
Car c = {"Toyota", "Corolla", 2017, {30.0,30.2,30.513,30.79}};
simdjson::builder::string_builder sb;
sb.start_object();
sb.append_key_value("make", c.make);
sb.append_key_value<"make">(c.make);
sb.append_comma();
sb.append_key_value("model", c.model);
sb.append_key_value<"model">(c.model);
sb.append_comma();
sb.append_key_value("year", c.year);
sb.append_key_value<"year">(c.year);
sb.append_comma();
sb.append_key_value("tire_pressure", c.tire_pressure);
sb.append_key_value<"tire_pressure">(c.tire_pressure);
sb.end_object();
std::string_view p = sb.view();
```
@@ -175,9 +176,52 @@ std::vector<std::vector<double>> c = {{1.0, 2.0}, {3.0, 4.0}};
std::string json = simdjson::to_json(c);
```
We also have an overload for when you want to reuse the same `std::string` instance:
```cpp
std::vector<std::vector<double>> c = {{1.0, 2.0}, {3.0, 4.0}};
std::string json;
auto error = simdjson::to_json(c, json);
if(error) { /* there was an error */ }
```
We do recommend that you create and reuse the `string_builder` instance for performance
reasons.
You can also add custom serialization functions using a `tag_invoke` function.
For example, the following
function will allow you to serialize instances of the type `Car`.
```cpp
#include <simdjson>
struct Car {
std::string make;
std::string model;
int64_t year;
std::vector<float> tire_pressure;
};
namespace simdjson {
template <typename builder_type>
void tag_invoke(serialize_tag, builder_type &builder, const Car& car) {
builder.start_object();
builder.append_key_value("make", car.make);
builder.append_comma();
builder.append_key_value("model", car.model);
builder.append_comma();
builder.append_key_value("year", car.year);
builder.append_comma();
builder.append_key_value("tire_pressure", car.tire_pressure);
builder.end_object();
}
} // namespace simdjson
```
C++26 static reflection
------------------------
@@ -239,7 +283,38 @@ with the `simdjson::to_json` template function.
If you know the output size, in bytes, of your JSON string, you may
pass it as a second parameter (e.g., `simdjson::to_json(c, 31123)`).
Sometimes you may want to reuse the same `std::string` instance. We
have an overload for this purpose:
```cpp
Car c = {"Toyota", "Corolla", 2017, {30.0,30.2,30.513,30.79}};
std::string s;
auto error = simdjson::to_json(c, s);
if(error) { /* there was an error */ }
```
You can then also add a third parameter for the expected output size in bytes.
### Extracting just some fields
In some instances, your class might have many fields that you do not want to serialize.
You can achieve this result with the `simdjson::extract_from` template. In the following
example, we serialize only the `year` and `price` fields on the `Car` instance.
```cpp
struct Car {
std::string make;
std::string model;
int year;
double price;
bool electric;
};
Car car{"Ford", "F-150", 2024, 55000.0, false};
// Extract year and price
std::string json_result = simdjson::extract_from<"year", "price">(car);
// Alternatively:
// std::string json_result;
// auto error = extract_from<"year", "price">(car).get(json_result);
// if(error) { /* error handling */ }
```
### Without `string_buffer` instance but with explicit error handling
@@ -248,9 +323,44 @@ pattern:
```cpp
std::string json;
if(simdjson::to(c).get(json)) {
if(simdjson::to_json(c).get(json)) {
// there was an error
} else {
// json contain the serialized JSON
}
```
### Customization
If you want to serialize a value in a custome way, you can do it with a
`tag_invoke` specialization like the following example which will map
the year attribute to a string.
```cpp
#include <simdjson>
struct Car {
std::string make;
std::string model;
int64_t year;
std::vector<float> tire_pressure;
};
namespace simdjson {
template <typename builder_type>
void tag_invoke(serialize_tag, builder_type &builder, const Car& car) {
builder.start_object();
builder.append_key_value("make", car.make);
builder.append_comma();
builder.append_key_value("model", car.model);
builder.append_comma();
builder.append_key_value("year", std::to_string(car.year));
builder.append_comma();
builder.append_key_value("tire_pressure", car.tire_pressure);
builder.end_object();
}
} // namespace simdjson
```
+1 -1
View File
@@ -129,7 +129,7 @@ Once you have an element, you can navigate it with idiomatic C++ iterators, oper
The strings contain unescaped valid UTF-8 strings: no unmatched surrogate is allowed.
Internally, numbers are stored as either 64-bit integers or 64-bit floating-point numbers.
Thus it is possible to get the full 64-bit integer range (either signed or unsigned).
By default, the string `-0` is parsed as the integer 0 as in Pytho or C++. If you set the macro
By default, the string `-0` is parsed as the integer 0 as in Python or C++. If you set the macro
`SIMDJSON_MINUS_ZERO_AS_FLOAT` to `1` when building simdjson, you can get that `-0` is mapped to `-0.0`
as in JavaScript. You can get the desired effect by building simdjson with cmake setting the
`SIMDJSON_MINUS_ZERO_AS_FLOAT` to on: `cmake -B build -D SIMDJSON_MINUS_ZERO_AS_FLOAT=ON`.
+1 -1
View File
@@ -253,7 +253,7 @@ long page_size() {
// page boundary.
bool need_allocation(const char *buf, size_t len) {
return ((reinterpret_cast<uintptr_t>(buf + len - 1) % page_size())
+ simdjson::SIMDJSON_PADDING > static_cast<uintptr_t>(page_size()));
+ simdjson::SIMDJSON_PADDING >= static_cast<uintptr_t>(page_size()));
}
simdjson::padded_string_view
+1 -1
View File
@@ -18,7 +18,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
auto error = parser.parse(str).get(elem);
if (error) { return 0; }
std::string minified=simdjson::minify(elem);
std::string minified = simdjson::minify(elem);
(void)minified;
return 0;
}
+1 -1
View File
@@ -17,7 +17,7 @@ using namespace simd;
struct backslash_and_quote {
public:
static constexpr uint32_t BYTES_PROCESSED = 32;
simdjson_inline static backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
simdjson_inline backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
simdjson_inline bool has_quote_first() { return ((bs_bits - 1) & quote_bits) != 0; }
simdjson_inline bool has_backslash() { return bs_bits != 0; }
+1
View File
@@ -10,6 +10,7 @@
#include "simdjson/error.h"
#include "simdjson/portability.h"
#include "simdjson/concepts.h"
#include "simdjson/constevalutil.h"
/**
* @brief The top level simdjson namespace, containing everything the library provides.
+35
View File
@@ -122,11 +122,46 @@ concept optional_type = requires(std::remove_cvref_t<T> obj) {
} -> std::convertible_to<typename std::remove_cvref_t<T>::value_type>;
};
{ static_cast<bool>(obj) } -> std::same_as<bool>; // convertible to bool
{ obj.reset() } noexcept -> std::same_as<void>;
};
// Types we serialize as JSON strings (not as containers)
template <typename T>
concept string_like =
std::is_same_v<std::remove_cvref_t<T>, std::string> ||
std::is_same_v<std::remove_cvref_t<T>, std::string_view> ||
std::is_same_v<std::remove_cvref_t<T>, const char*> ||
std::is_same_v<std::remove_cvref_t<T>, char*>;
// Concept that checks if a type is a container but not a string (because
// strings handling must be handled differently)
// Now uses iterator-based approach for broader container support
template <typename T>
concept container_but_not_string =
std::ranges::input_range<T> && !string_like<T> && !concepts::string_view_keyed_map<T>;
} // namespace concepts
/**
* We use tag_invoke as our customization point mechanism.
*/
template <typename Tag, typename... Args>
concept tag_invocable = requires(Tag tag, Args... args) {
tag_invoke(std::forward<Tag>(tag), std::forward<Args>(args)...);
};
template <typename Tag, typename... Args>
concept nothrow_tag_invocable =
tag_invocable<Tag, Args...> && requires(Tag tag, Args... args) {
{
tag_invoke(std::forward<Tag>(tag), std::forward<Args>(args)...)
} noexcept;
};
} // namespace simdjson
#endif // SIMDJSON_SUPPORTS_CONCEPTS
#endif // SIMDJSON_CONCEPTS_H
+75
View File
@@ -0,0 +1,75 @@
#ifndef SIMDJSON_CONSTEVALUTIL_H
#define SIMDJSON_CONSTEVALUTIL_H
#include <string>
#include <string_view>
#include <array>
namespace simdjson {
namespace constevalutil {
#if SIMDJSON_CONSTEVAL
constexpr static std::array<uint8_t, 256> json_quotable_character = {
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, 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, 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,
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, 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, 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,
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, 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};
constexpr static std::array<std::string_view, 32> control_chars = {
"\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004", "\\u0005", "\\u0006",
"\\u0007", "\\b", "\\t", "\\n", "\\u000b", "\\f", "\\r",
"\\u000e", "\\u000f", "\\u0010", "\\u0011", "\\u0012", "\\u0013", "\\u0014",
"\\u0015", "\\u0016", "\\u0017", "\\u0018", "\\u0019", "\\u001a", "\\u001b",
"\\u001c", "\\u001d", "\\u001e", "\\u001f"};
// unoptimized, meant for compile-time execution
consteval std::string consteval_to_quoted_escaped(std::string_view input) {
std::string out = "\"";
for (char c : input) {
if (json_quotable_character[uint8_t(c)]) {
if (c == '"') {
out.append("\\\"");
} else if (c == '\\') {
out.append("\\\\");
} else {
std::string_view v = control_chars[uint8_t(c)];
out.append(v);
}
} else {
out.push_back(c);
}
}
out.push_back('"');
return out;
}
#endif // SIMDJSON_CONSTEVAL
#if SIMDJSON_SUPPORTS_CONCEPTS
template <std::size_t N>
struct fixed_string {
constexpr fixed_string(const char (&str)[N]) {
for (std::size_t i = 0; i < N; ++i) {
data[i] = str[i];
}
}
char data[N];
constexpr std::string_view view() const { return {data, N - 1}; }
};
template <std::size_t N>
fixed_string(const char (&)[N]) -> fixed_string<N>;
template <fixed_string str>
struct string_constant {
static constexpr std::string_view value = str.view();
};
#endif // SIMDJSON_SUPPORTS_CONCEPTS
} // namespace constevalutil
} // namespace simdjson
#endif // SIMDJSON_CONSTEVALUTIL_H
+19 -7
View File
@@ -58,6 +58,12 @@ inline simdjson_result<T> auto_parser<parser_type>::result() noexcept(is_nothrow
return m_doc.get<T>();
}
template <typename parser_type>
template <typename T>
simdjson_warn_unused simdjson_inline error_code auto_parser<parser_type>::get(T &value) && noexcept(is_nothrow_gettable<T>) {
return result<T>().get(value);
}
template <typename parser_type>
inline simdjson_result<ondemand::array> auto_parser<parser_type>::array() noexcept {
return result<ondemand::array>();
@@ -73,12 +79,7 @@ inline simdjson_result<ondemand::number> auto_parser<parser_type>::number() noex
return result<ondemand::number>();
}
template <typename parser_type>
template <typename T>
inline auto_parser<parser_type>::operator simdjson_result<T>() noexcept(is_nothrow_gettable<T>) {
return result<T>();
}
#if SIMDJSON_EXCEPTIONS
template <typename parser_type>
template <typename T>
inline auto_parser<parser_type>::operator T() noexcept(false) {
@@ -87,6 +88,7 @@ inline auto_parser<parser_type>::operator T() noexcept(false) {
}
return m_doc.get<T>();
}
#endif // SIMDJSON_EXCEPTIONS
template <typename parser_type>
template <typename T>
@@ -109,13 +111,23 @@ inline T to_adaptor<T>::operator()(simdjson_result<ondemand::value> &val) const
template <typename T>
inline auto to_adaptor<T>::operator()(padded_string_view const str) const noexcept {
return auto_parser{str};
return auto_parser<ondemand::parser *>{str};
}
template <typename T>
inline auto to_adaptor<T>::operator()(ondemand::parser &parser, padded_string_view const str) const noexcept {
return auto_parser<ondemand::parser *>{parser, str};
}
template <typename T>
inline auto to_adaptor<T>::operator()(std::string str) const noexcept {
return auto_parser<ondemand::parser *>{pad_with_reserve(str)};
}
template <typename T>
inline auto to_adaptor<T>::operator()(ondemand::parser &parser, std::string str) const noexcept {
return auto_parser<ondemand::parser *>{parser, pad_with_reserve(str)};
}
} // namespace internal
} // namespace convert
} // namespace simdjson
+12 -2
View File
@@ -46,16 +46,19 @@ public:
template <typename T>
simdjson_warn_unused simdjson_inline simdjson_result<T> result() noexcept(is_nothrow_gettable<T>);
template <typename T>
simdjson_warn_unused simdjson_inline error_code get(T &value) && noexcept(is_nothrow_gettable<T>);
simdjson_warn_unused simdjson_inline simdjson_result<ondemand::array> array() noexcept;
simdjson_warn_unused simdjson_inline simdjson_result<ondemand::object> object() noexcept;
simdjson_warn_unused simdjson_inline simdjson_result<ondemand::number> number() noexcept;
template <typename T>
simdjson_warn_unused simdjson_inline explicit(false) operator simdjson_result<T>() noexcept(is_nothrow_gettable<T>);
#if SIMDJSON_EXCEPTIONS
template <typename T>
simdjson_warn_unused simdjson_inline explicit(false) operator T() noexcept(false);
#endif // SIMDJSON_EXCEPTIONS
template <typename T>
simdjson_warn_unused simdjson_inline std::optional<T> optional() noexcept(is_nothrow_gettable<T>);
@@ -72,7 +75,14 @@ struct to_adaptor {
T operator()(simdjson_result<ondemand::value> &val) const noexcept;
auto operator()(padded_string_view const str) const noexcept;
auto operator()(ondemand::parser &parser, padded_string_view const str) const noexcept;
// The std::string is padded with reserve to ensure there is enough space for padding.
// Some sanitizers may not like this, so you can use simdjson::pad instead.
// simdjson::from(simdjson::pad(str))
auto operator()(std::string str) const noexcept;
auto operator()(ondemand::parser &parser, std::string str) const noexcept;
};
// deduction guide
auto_parser(padded_string_view const str) -> auto_parser<ondemand::parser*>;
} // namespace internal
} // namespace convert
+31
View File
@@ -67,8 +67,38 @@ simdjson_inline error_code simdjson_result_base<T>::error() const noexcept {
return this->second;
}
template<typename T>
simdjson_inline bool simdjson_result_base<T>::has_value() const noexcept {
return this->error() == SUCCESS;
}
#if SIMDJSON_EXCEPTIONS
template<typename T>
simdjson_inline T& simdjson_result_base<T>::operator*() & noexcept(false) {
return this->value();
}
template<typename T>
simdjson_inline T&& simdjson_result_base<T>::operator*() && noexcept(false) {
return std::forward<internal::simdjson_result_base<T>>(*this).value();
}
template<typename T>
simdjson_inline T* simdjson_result_base<T>::operator->() noexcept(false) {
if (this->error()) { throw simdjson_error(this->error()); }
return &this->first;
}
template<typename T>
simdjson_inline const T* simdjson_result_base<T>::operator->() const noexcept(false) {
if (this->error()) { throw simdjson_error(this->error()); }
return &this->first;
}
template<typename T>
simdjson_inline T& simdjson_result_base<T>::value() & noexcept(false) {
if (error()) { throw simdjson_error(error()); }
@@ -93,6 +123,7 @@ simdjson_inline simdjson_result_base<T>::operator T&&() && noexcept(false) {
#endif // SIMDJSON_EXCEPTIONS
template<typename T>
simdjson_inline const T& simdjson_result_base<T>::value_unsafe() const& noexcept {
return this->first;
+28 -1
View File
@@ -108,6 +108,10 @@ namespace internal {
/**
* The result of a simdjson operation that could fail.
*
* IMPORTANT: For the ondemand API, we use implementation_simdjson_result_base<T> as a base class
* to avoid some compilation issue. Thus, if you modify this class, please ensure that the ondemand
* implementation_simdjson_result_base<T> is also modified.
*
* Gives the option of reading error codes, or throwing an exception by casting to the desired result.
*
* This is a base class for implementations that want to add functions to the result type for
@@ -168,8 +172,27 @@ struct simdjson_result_base : protected std::pair<T, error_code> {
*/
simdjson_inline error_code error() const noexcept;
/**
* Whether there is a value.
*/
simdjson_inline bool has_value() const noexcept;
#if SIMDJSON_EXCEPTIONS
/**
* Dereference operator to access the contained value.
*
* @throw simdjson_error if there was an error.
*/
simdjson_inline T& operator*() & noexcept(false);
simdjson_inline T&& operator*() && noexcept(false);
/**
* Arrow operator to access members of the contained value.
*
* @throw simdjson_error if there was an error.
*/
simdjson_inline T* operator->() noexcept(false);
simdjson_inline const T* operator->() const noexcept(false);
/**
* Get the result value.
*
@@ -253,6 +276,7 @@ struct simdjson_result_base : protected std::pair<T, error_code> {
*/
template<typename T>
struct simdjson_result : public internal::simdjson_result_base<T> {
/**
* @private Create a new empty result with error = UNINITIALIZED.
*/
@@ -306,8 +330,11 @@ struct simdjson_result : public internal::simdjson_result_base<T> {
*/
simdjson_inline error_code error() const noexcept;
#if SIMDJSON_EXCEPTIONS
#if SIMDJSON_EXCEPTIONS
using internal::simdjson_result_base<T>::operator*;
using internal::simdjson_result_base<T>::operator->;
/**
* Get the result value.
*
@@ -13,7 +13,7 @@ namespace {
struct backslash_and_quote {
public:
static constexpr uint32_t BYTES_PROCESSED = 1;
simdjson_inline static backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
simdjson_inline backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
simdjson_inline bool has_quote_first() { return c == '"'; }
simdjson_inline bool has_backslash() { return c == '\\'; }
@@ -29,12 +29,41 @@ simdjson_warn_unused simdjson_inline error_code implementation_simdjson_result_b
}
template<typename T>
simdjson_inline error_code implementation_simdjson_result_base<T>::error() const noexcept {
simdjson_warn_unused simdjson_inline error_code implementation_simdjson_result_base<T>::error() const noexcept {
return this->second;
}
template<typename T>
simdjson_warn_unused simdjson_inline bool implementation_simdjson_result_base<T>::has_value() const noexcept {
return this->error() == SUCCESS;
}
#if SIMDJSON_EXCEPTIONS
template<typename T>
simdjson_inline T& implementation_simdjson_result_base<T>::operator*() & noexcept(false) {
return this->value();
}
template<typename T>
simdjson_inline T&& implementation_simdjson_result_base<T>::operator*() && noexcept(false) {
return std::forward<implementation_simdjson_result_base<T>>(*this).value();
}
template<typename T>
simdjson_inline T* implementation_simdjson_result_base<T>::operator->() noexcept(false) {
if (this->error()) { throw simdjson_error(this->error()); }
return &this->first;
}
template<typename T>
simdjson_inline const T* implementation_simdjson_result_base<T>::operator->() const noexcept(false) {
if (this->error()) { throw simdjson_error(this->error()); }
return &this->first;
}
template<typename T>
simdjson_inline T& implementation_simdjson_result_base<T>::value() & noexcept(false) {
if (error()) { throw simdjson_error(error()); }
@@ -67,12 +67,17 @@ struct implementation_simdjson_result_base {
*
* @param value The variable to assign the value to. May not be set if there is an error.
*/
simdjson_inline error_code get(T &value) && noexcept;
simdjson_warn_unused simdjson_inline error_code get(T &value) && noexcept;
/**
* The error.
*/
simdjson_inline error_code error() const noexcept;
simdjson_warn_unused simdjson_inline error_code error() const noexcept;
/**
* Whether there is a value.
*/
simdjson_warn_unused simdjson_inline bool has_value() const noexcept;
#if SIMDJSON_EXCEPTIONS
@@ -81,6 +86,16 @@ struct implementation_simdjson_result_base {
*
* @throw simdjson_error if there was an error.
*/
simdjson_inline T& operator*() & noexcept(false);
simdjson_inline T&& operator*() && noexcept(false);
/**
* Arrow operator to access members of the contained value.
*
* @throw simdjson_error if there was an error.
*/
simdjson_inline T* operator->() noexcept(false);
simdjson_inline const T* operator->() const noexcept(false);
simdjson_inline T& value() & noexcept(false);
/**
+6 -6
View File
@@ -361,7 +361,7 @@ simdjson_inline bool is_digit(const uint8_t c) {
return static_cast<uint8_t>(c - '0') <= 9;
}
simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) {
simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) {
// we continue with the fiction that we have an integer. If the
// floating point number is representable as x * 10^z for some integer
// z that fits in 53 bits, then we will be able to convert back the
@@ -389,7 +389,7 @@ simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const u
return SUCCESS;
}
simdjson_inline error_code parse_exponent(simdjson_unused const uint8_t *const src, const uint8_t *&p, int64_t &exponent) {
simdjson_warn_unused simdjson_inline error_code parse_exponent(simdjson_unused const uint8_t *const src, const uint8_t *&p, int64_t &exponent) {
// Exp Sign: -123.456e[-]78
bool neg_exp = ('-' == *p);
if (neg_exp || '+' == *p) { p++; } // Skip + as well
@@ -478,7 +478,7 @@ static error_code slow_float_parsing(simdjson_unused const uint8_t * src, double
/** @private */
template<typename W>
simdjson_inline error_code write_float(const uint8_t *const src, bool negative, uint64_t i, const uint8_t * start_digits, size_t digit_count, int64_t exponent, W &writer) {
simdjson_warn_unused simdjson_inline error_code write_float(const uint8_t *const src, bool negative, uint64_t i, const uint8_t * start_digits, size_t digit_count, int64_t exponent, W &writer) {
// If we frequently had to deal with long strings of digits,
// we could extend our code by using a 128-bit integer instead
// of a 64-bit integer. However, this is uncommon in practice.
@@ -541,13 +541,13 @@ simdjson_inline error_code write_float(const uint8_t *const src, bool negative,
//
// Our objective is accurate parsing (ULP of 0) at high speed.
template<typename W>
simdjson_inline error_code parse_number(const uint8_t *const src, W &writer);
simdjson_warn_unused simdjson_inline error_code parse_number(const uint8_t *const src, W &writer);
// for performance analysis, it is sometimes useful to skip parsing
#ifdef SIMDJSON_SKIPNUMBERPARSING
template<typename W>
simdjson_inline error_code parse_number(const uint8_t *const, W &writer) {
simdjson_warn_unused simdjson_inline error_code parse_number(const uint8_t *const, W &writer) {
writer.append_s64(0); // always write zero
return SUCCESS; // always succeeds
}
@@ -573,7 +573,7 @@ simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(con
//
// Our objective is accurate parsing (ULP of 0) at high speed.
template<typename W>
simdjson_inline error_code parse_number(const uint8_t *const src, W &writer) {
simdjson_warn_unused simdjson_inline error_code parse_number(const uint8_t *const src, W &writer) {
//
// Check for minus sign
//
@@ -14,6 +14,9 @@
#include "simdjson/generic/ondemand/raw_json_string.h"
#include "simdjson/generic/ondemand/parser.h"
// JSON builder - needed for extract_into functionality
#include "simdjson/generic/ondemand/json_string_builder.h"
// All other declarations
#include "simdjson/generic/ondemand/array.h"
#include "simdjson/generic/ondemand/array_iterator.h"
@@ -45,9 +48,7 @@
#include "simdjson/generic/ondemand/token_iterator-inl.h"
#include "simdjson/generic/ondemand/value_iterator-inl.h"
// JSON builder, ideally they should not be part of the ondemand directory
// but it is convenient for now to have them here.
#include "simdjson/generic/ondemand/json_string_builder.h"
// JSON builder inline definitions
#include "simdjson/generic/ondemand/json_string_builder-inl.h"
#include "simdjson/generic/ondemand/json_builder.h"
@@ -85,7 +85,7 @@ simdjson_inline simdjson_result<array_iterator> array::begin() noexcept {
simdjson_inline simdjson_result<array_iterator> array::end() noexcept {
return array_iterator(iter);
}
simdjson_inline error_code array::consume() noexcept {
simdjson_warn_unused simdjson_warn_unused simdjson_inline error_code array::consume() noexcept {
auto error = iter.json_iter().skip_child(iter.depth()-1);
if(error) { iter.abandon(); }
return error;
+3 -3
View File
@@ -141,7 +141,7 @@ public:
* @returns SUCCESS If the parse succeeded and the out parameter was set to the value.
*/
template <typename T>
simdjson_inline error_code get(T &out)
simdjson_warn_unused simdjson_inline error_code get(T &out)
noexcept(custom_deserializable<T, array> ? nothrow_custom_deserializable<T, array> : true) {
static_assert(custom_deserializable<T, array>);
return deserialize(*this, out);
@@ -166,7 +166,7 @@ protected:
/**
* Go to the end of the array, no matter where you are right now.
*/
simdjson_inline error_code consume() noexcept;
simdjson_warn_unused simdjson_inline error_code consume() noexcept;
/**
* Begin array iteration.
@@ -252,7 +252,7 @@ public:
return first.get<T>();
}
template<typename T>
simdjson_inline error_code get(T& out) noexcept {
simdjson_warn_unused simdjson_inline error_code get(T& out) noexcept {
if (error()) { return error(); }
if constexpr (std::is_same_v<T, SIMDJSON_IMPLEMENTATION::ondemand::array>) {
out = first;
@@ -7,55 +7,8 @@
#include "simdjson/generic/ondemand/array.h"
#endif // SIMDJSON_CONDITIONAL_INCLUDE
#include <concepts>
namespace simdjson {
namespace tag_invoke_fn_ns {
void tag_invoke();
struct tag_invoke_fn {
template <typename Tag, typename... Args>
requires requires(Tag tag, Args &&...args) {
tag_invoke(std::forward<Tag>(tag), std::forward<Args>(args)...);
}
constexpr auto operator()(Tag tag, Args &&...args) const
noexcept(noexcept(tag_invoke(std::forward<Tag>(tag),
std::forward<Args>(args)...)))
-> decltype(tag_invoke(std::forward<Tag>(tag),
std::forward<Args>(args)...)) {
return tag_invoke(std::forward<Tag>(tag), std::forward<Args>(args)...);
}
};
} // namespace tag_invoke_fn_ns
inline namespace tag_invoke_ns {
inline constexpr tag_invoke_fn_ns::tag_invoke_fn tag_invoke = {};
} // namespace tag_invoke_ns
template <typename Tag, typename... Args>
concept tag_invocable = requires(Tag tag, Args... args) {
tag_invoke(std::forward<Tag>(tag), std::forward<Args>(args)...);
};
template <typename Tag, typename... Args>
concept nothrow_tag_invocable =
tag_invocable<Tag, Args...> && requires(Tag tag, Args... args) {
{
tag_invoke(std::forward<Tag>(tag), std::forward<Args>(args)...)
} noexcept;
};
template <typename Tag, typename... Args>
using tag_invoke_result =
std::invoke_result<decltype(tag_invoke), Tag, Args...>;
template <typename Tag, typename... Args>
using tag_invoke_result_t =
std::invoke_result_t<decltype(tag_invoke), Tag, Args...>;
template <auto &Tag> using tag_t = std::decay_t<decltype(Tag)>;
struct deserialize_tag;
/// These types are deserializable in a built-in way
@@ -141,7 +141,7 @@ simdjson_inline simdjson_result<std::string_view> document::get_string(bool allo
return get_root_value_iterator().get_root_string(true, allow_replacement);
}
template <typename string_type>
simdjson_inline error_code document::get_string(string_type& receiver, bool allow_replacement) noexcept {
simdjson_warn_unused simdjson_inline error_code document::get_string(string_type& receiver, bool allow_replacement) noexcept {
return get_root_value_iterator().get_root_string(receiver, true, allow_replacement);
}
simdjson_inline simdjson_result<std::string_view> document::get_wobbly_string() noexcept {
@@ -167,15 +167,15 @@ template<> simdjson_inline simdjson_result<int64_t> document::get() & noexcept {
template<> simdjson_inline simdjson_result<bool> document::get() & noexcept { return get_bool(); }
template<> simdjson_inline simdjson_result<value> document::get() & noexcept { return get_value(); }
template<> simdjson_inline error_code document::get(array& out) & noexcept { return get_array().get(out); }
template<> simdjson_inline error_code document::get(object& out) & noexcept { return get_object().get(out); }
template<> simdjson_inline error_code document::get(raw_json_string& out) & noexcept { return get_raw_json_string().get(out); }
template<> simdjson_inline error_code document::get(std::string_view& out) & noexcept { return get_string(false).get(out); }
template<> simdjson_inline error_code document::get(double& out) & noexcept { return get_double().get(out); }
template<> simdjson_inline error_code document::get(uint64_t& out) & noexcept { return get_uint64().get(out); }
template<> simdjson_inline error_code document::get(int64_t& out) & noexcept { return get_int64().get(out); }
template<> simdjson_inline error_code document::get(bool& out) & noexcept { return get_bool().get(out); }
template<> simdjson_inline error_code document::get(value& out) & noexcept { return get_value().get(out); }
template<> simdjson_warn_unused simdjson_inline error_code document::get(array& out) & noexcept { return get_array().get(out); }
template<> simdjson_warn_unused simdjson_inline error_code document::get(object& out) & noexcept { return get_object().get(out); }
template<> simdjson_warn_unused simdjson_inline error_code document::get(raw_json_string& out) & noexcept { return get_raw_json_string().get(out); }
template<> simdjson_warn_unused simdjson_inline error_code document::get(std::string_view& out) & noexcept { return get_string(false).get(out); }
template<> simdjson_warn_unused simdjson_inline error_code document::get(double& out) & noexcept { return get_double().get(out); }
template<> simdjson_warn_unused simdjson_inline error_code document::get(uint64_t& out) & noexcept { return get_uint64().get(out); }
template<> simdjson_warn_unused simdjson_inline error_code document::get(int64_t& out) & noexcept { return get_int64().get(out); }
template<> simdjson_warn_unused simdjson_inline error_code document::get(bool& out) & noexcept { return get_bool().get(out); }
template<> simdjson_warn_unused simdjson_inline error_code document::get(value& out) & noexcept { return get_value().get(out); }
template<> simdjson_deprecated simdjson_inline simdjson_result<raw_json_string> document::get() && noexcept { return get_raw_json_string(); }
template<> simdjson_deprecated simdjson_inline simdjson_result<std::string_view> document::get() && noexcept { return get_string(false); }
@@ -245,7 +245,7 @@ simdjson_inline simdjson_result<value> document::operator[](const char *key) & n
return start_or_resume_object()[key];
}
simdjson_inline error_code document::consume() noexcept {
simdjson_warn_unused simdjson_inline error_code document::consume() noexcept {
bool scalar = false;
auto error = is_scalar().get(scalar);
if(error) { return error; }
@@ -347,6 +347,54 @@ simdjson_inline simdjson_result<value> document::at_path(std::string_view json_p
}
}
#if SIMDJSON_SUPPORTS_CONCEPTS && SIMDJSON_STATIC_REFLECTION
template<constevalutil::fixed_string... FieldNames, typename T>
requires(std::is_class_v<T> && (sizeof...(FieldNames) > 0))
simdjson_warn_unused simdjson_inline error_code document::extract_into(T& out) & noexcept {
// Helper to check if a field name matches any of the requested fields
auto should_extract = [](std::string_view field_name) constexpr -> bool {
return ((FieldNames.view() == field_name) || ...);
};
// Iterate through all members of T using reflection
template for (constexpr auto mem : std::define_static_array(
std::meta::nonstatic_data_members_of(^^T, std::meta::access_context::unchecked()))) {
if constexpr (!std::meta::is_const(mem) && std::meta::is_public(mem)) {
constexpr std::string_view key = std::define_static_string(std::meta::identifier_of(mem));
// Only extract this field if it's in our list of requested fields
if constexpr (should_extract(key)) {
// Try to find and extract the field
if constexpr (concepts::optional_type<decltype(out.[:mem:])>) {
// For optional fields, it's ok if they're missing
auto field_result = find_field_unordered(key);
if (!field_result.error()) {
auto error = field_result.get(out.[:mem:]);
if (error && error != NO_SUCH_FIELD) {
return error;
}
} else if (field_result.error() != NO_SUCH_FIELD) {
return field_result.error();
} else {
out.[:mem:].reset();
}
} else {
// For required fields (in the requested list), fail if missing
SIMDJSON_TRY((*this)[key].get(out.[:mem:]));
}
}
}
};
return SUCCESS;
}
#endif // SIMDJSON_SUPPORTS_CONCEPTS && SIMDJSON_STATIC_REFLECTION
} // namespace ondemand
} // namespace SIMDJSON_IMPLEMENTATION
} // namespace simdjson
@@ -454,7 +502,7 @@ simdjson_inline simdjson_result<std::string_view> simdjson_result<SIMDJSON_IMPLE
return first.get_string(allow_replacement);
}
template <typename string_type>
simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document>::get_string(string_type& receiver, bool allow_replacement) noexcept {
simdjson_warn_unused simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document>::get_string(string_type& receiver, bool allow_replacement) noexcept {
if (error()) { return error(); }
return first.get_string(receiver, allow_replacement);
}
@@ -490,12 +538,12 @@ simdjson_deprecated simdjson_inline simdjson_result<T> simdjson_result<SIMDJSON_
return std::forward<SIMDJSON_IMPLEMENTATION::ondemand::document>(first).get<T>();
}
template<typename T>
simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document>::get(T &out) & noexcept {
simdjson_warn_unused simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document>::get(T &out) & noexcept {
if (error()) { return error(); }
return first.get<T>(out);
}
template<typename T>
simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document>::get(T &out) && noexcept {
simdjson_warn_unused simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document>::get(T &out) && noexcept {
if (error()) { return error(); }
return std::forward<SIMDJSON_IMPLEMENTATION::ondemand::document>(first).get<T>(out);
}
@@ -505,8 +553,8 @@ template<> simdjson_deprecated simdjson_inline simdjson_result<SIMDJSON_IMPLEMEN
if (error()) { return error(); }
return std::forward<SIMDJSON_IMPLEMENTATION::ondemand::document>(first);
}
template<> simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document>::get<SIMDJSON_IMPLEMENTATION::ondemand::document>(SIMDJSON_IMPLEMENTATION::ondemand::document &out) & noexcept = delete;
template<> simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document>::get<SIMDJSON_IMPLEMENTATION::ondemand::document>(SIMDJSON_IMPLEMENTATION::ondemand::document &out) && noexcept {
template<> simdjson_warn_unused simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document>::get<SIMDJSON_IMPLEMENTATION::ondemand::document>(SIMDJSON_IMPLEMENTATION::ondemand::document &out) & noexcept = delete;
template<> simdjson_warn_unused simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document>::get<SIMDJSON_IMPLEMENTATION::ondemand::document>(SIMDJSON_IMPLEMENTATION::ondemand::document &out) && noexcept {
if (error()) { return error(); }
out = std::forward<SIMDJSON_IMPLEMENTATION::ondemand::document>(first);
return SUCCESS;
@@ -624,6 +672,15 @@ simdjson_inline simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::value> simdjs
return first.at_path(json_path);
}
#if SIMDJSON_STATIC_REFLECTION
template<constevalutil::fixed_string... FieldNames, typename T>
requires(std::is_class_v<T> && (sizeof...(FieldNames) > 0))
simdjson_warn_unused simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document>::extract_into(T& out) & noexcept {
if (error()) { return error(); }
return first.extract_into<FieldNames...>(out);
}
#endif // SIMDJSON_STATIC_REFLECTION
} // namespace simdjson
@@ -658,7 +715,7 @@ simdjson_inline simdjson_result<double> document_reference::get_double() noexcep
simdjson_inline simdjson_result<double> document_reference::get_double_in_string() noexcept { return doc->get_root_value_iterator().get_root_double(false); }
simdjson_inline simdjson_result<std::string_view> document_reference::get_string(bool allow_replacement) noexcept { return doc->get_root_value_iterator().get_root_string(false, allow_replacement); }
template <typename string_type>
simdjson_inline error_code document_reference::get_string(string_type& receiver, bool allow_replacement) noexcept { return doc->get_root_value_iterator().get_root_string(receiver, false, allow_replacement); }
simdjson_warn_unused simdjson_inline error_code document_reference::get_string(string_type& receiver, bool allow_replacement) noexcept { return doc->get_root_value_iterator().get_root_string(receiver, false, allow_replacement); }
simdjson_inline simdjson_result<std::string_view> document_reference::get_wobbly_string() noexcept { return doc->get_root_value_iterator().get_root_wobbly_string(false); }
simdjson_inline simdjson_result<raw_json_string> document_reference::get_raw_json_string() noexcept { return doc->get_root_value_iterator().get_root_raw_json_string(false); }
simdjson_inline simdjson_result<bool> document_reference::get_bool() noexcept { return doc->get_root_value_iterator().get_root_bool(false); }
@@ -711,7 +768,13 @@ simdjson_inline simdjson_result<value> document_reference::at_pointer(std::strin
simdjson_inline simdjson_result<value> document_reference::at_path(std::string_view json_path) noexcept { return doc->at_path(json_path); }
simdjson_inline simdjson_result<std::string_view> document_reference::raw_json() noexcept { return doc->raw_json();}
simdjson_inline document_reference::operator document&() const noexcept { return *doc; }
#if SIMDJSON_SUPPORTS_CONCEPTS && SIMDJSON_STATIC_REFLECTION
template<constevalutil::fixed_string... FieldNames, typename T>
requires(std::is_class_v<T> && (sizeof...(FieldNames) > 0))
simdjson_warn_unused simdjson_inline error_code document_reference::extract_into(T& out) & noexcept {
return doc->extract_into<FieldNames...>(out);
}
#endif // SIMDJSON_SUPPORTS_CONCEPTS && SIMDJSON_STATIC_REFLECTION
} // namespace ondemand
} // namespace SIMDJSON_IMPLEMENTATION
} // namespace simdjson
@@ -808,7 +871,7 @@ simdjson_inline simdjson_result<std::string_view> simdjson_result<SIMDJSON_IMPLE
return first.get_string(allow_replacement);
}
template <typename string_type>
simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document_reference>::get_string(string_type& receiver, bool allow_replacement) noexcept {
simdjson_warn_unused simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document_reference>::get_string(string_type& receiver, bool allow_replacement) noexcept {
if (error()) { return error(); }
return first.get_string(receiver, allow_replacement);
}
@@ -843,12 +906,12 @@ simdjson_inline simdjson_result<T> simdjson_result<SIMDJSON_IMPLEMENTATION::onde
return std::forward<SIMDJSON_IMPLEMENTATION::ondemand::document_reference>(first).get<T>();
}
template <class T>
simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document_reference>::get(T &out) & noexcept {
simdjson_warn_unused simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document_reference>::get(T &out) & noexcept {
if (error()) { return error(); }
return first.get<T>(out);
}
template <class T>
simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document_reference>::get(T &out) && noexcept {
simdjson_warn_unused simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document_reference>::get(T &out) && noexcept {
if (error()) { return error(); }
return std::forward<SIMDJSON_IMPLEMENTATION::ondemand::document_reference>(first).get<T>(out);
}
@@ -865,13 +928,13 @@ simdjson_inline simdjson_result<bool> simdjson_result<SIMDJSON_IMPLEMENTATION::o
return first.is_string();
}
template <>
simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document_reference>::get(SIMDJSON_IMPLEMENTATION::ondemand::document_reference &out) & noexcept {
simdjson_warn_unused simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document_reference>::get(SIMDJSON_IMPLEMENTATION::ondemand::document_reference &out) & noexcept {
if (error()) { return error(); }
out = first;
return SUCCESS;
}
template <>
simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document_reference>::get(SIMDJSON_IMPLEMENTATION::ondemand::document_reference &out) && noexcept {
simdjson_warn_unused simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document_reference>::get(SIMDJSON_IMPLEMENTATION::ondemand::document_reference &out) && noexcept {
if (error()) { return error(); }
out = first;
return SUCCESS;
@@ -959,7 +1022,14 @@ simdjson_inline simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::value> simdjs
}
return first.at_path(json_path);
}
#if SIMDJSON_STATIC_REFLECTION
template<constevalutil::fixed_string... FieldNames, typename T>
requires(std::is_class_v<T> && (sizeof...(FieldNames) > 0))
simdjson_warn_unused simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::document_reference>::extract_into(T& out) & noexcept {
if (error()) { return error(); }
return first.extract_into<FieldNames...>(out);
}
#endif // SIMDJSON_STATIC_REFLECTION
} // namespace simdjson
#endif // SIMDJSON_GENERIC_ONDEMAND_DOCUMENT_INL_H
+55 -7
View File
@@ -117,7 +117,7 @@ public:
* @returns INCORRECT_TYPE if the JSON value is not a string. Otherwise, we return SUCCESS.
*/
template <typename string_type>
simdjson_inline error_code get_string(string_type& receiver, bool allow_replacement = false) noexcept;
simdjson_warn_unused simdjson_inline error_code get_string(string_type& receiver, bool allow_replacement = false) noexcept;
/**
* Cast this JSON value to a string.
*
@@ -228,7 +228,7 @@ public:
* @returns SUCCESS If the parse succeeded and the out parameter was set to the value.
*/
template<typename T>
simdjson_inline error_code get(T &out) &
simdjson_warn_unused simdjson_inline error_code get(T &out) &
#if SIMDJSON_SUPPORTS_CONCEPTS
noexcept(custom_deserializable<T, document> ? nothrow_custom_deserializable<T, document> : true)
#else
@@ -725,11 +725,41 @@ public:
* the JSON document.
*/
simdjson_inline simdjson_result<std::string_view> raw_json() noexcept;
#if SIMDJSON_STATIC_REFLECTION
/**
* Extract only specific fields from the JSON object into a struct.
*
* This allows selective deserialization of only the fields you need,
* potentially improving performance by skipping unwanted fields.
*
* Example:
* ```c++
* struct Car {
* std::string make;
* std::string model;
* int year;
* double price;
* };
*
* Car car;
* doc.extract_into<"make", "model">(car);
* // Only 'make' and 'model' fields are extracted from JSON
* ```
*
* @tparam FieldNames Compile-time string literals specifying which fields to extract
* @param out The output struct to populate with selected fields
* @returns SUCCESS on success, or an error code if a required field is missing or has wrong type
*/
template<constevalutil::fixed_string... FieldNames, typename T>
requires(std::is_class_v<T> && (sizeof...(FieldNames) > 0))
simdjson_warn_unused simdjson_inline error_code extract_into(T& out) & noexcept;
#endif // SIMDJSON_STATIC_REFLECTION
protected:
/**
* Consumes the document.
*/
simdjson_inline error_code consume() noexcept;
simdjson_warn_unused simdjson_inline error_code consume() noexcept;
simdjson_inline document(ondemand::json_iterator &&iter) noexcept;
simdjson_inline const uint8_t *text(uint32_t idx) const noexcept;
@@ -782,7 +812,7 @@ public:
simdjson_inline simdjson_result<double> get_double_in_string() noexcept;
simdjson_inline simdjson_result<std::string_view> get_string(bool allow_replacement = false) noexcept;
template <typename string_type>
simdjson_inline error_code get_string(string_type& receiver, bool allow_replacement = false) noexcept;
simdjson_warn_unused simdjson_inline error_code get_string(string_type& receiver, bool allow_replacement = false) noexcept;
simdjson_inline simdjson_result<std::string_view> get_wobbly_string() noexcept;
simdjson_inline simdjson_result<raw_json_string> get_raw_json_string() noexcept;
simdjson_inline simdjson_result<bool> get_bool() noexcept;
@@ -826,7 +856,7 @@ public:
* @returns SUCCESS If the parse succeeded and the out parameter was set to the value.
*/
template<typename T>
simdjson_inline error_code get(T &out) &
simdjson_warn_unused simdjson_inline error_code get(T &out) &
#if SIMDJSON_SUPPORTS_CONCEPTS
noexcept(custom_deserializable<T, document> ? nothrow_custom_deserializable<T, document_reference> : true)
#else
@@ -861,6 +891,11 @@ public:
/** @overload template<typename T> error_code get(T &out) & noexcept */
template<typename T> simdjson_inline error_code get(T &out) && noexcept;
simdjson_inline simdjson_result<std::string_view> raw_json() noexcept;
#if SIMDJSON_STATIC_REFLECTION
template<constevalutil::fixed_string... FieldNames, typename T>
requires(std::is_class_v<T> && (sizeof...(FieldNames) > 0))
simdjson_warn_unused simdjson_inline error_code extract_into(T& out) & noexcept;
#endif // SIMDJSON_STATIC_REFLECTION
simdjson_inline operator document&() const noexcept;
#if SIMDJSON_EXCEPTIONS
template <class T>
@@ -929,7 +964,7 @@ public:
simdjson_inline simdjson_result<double> get_double_in_string() noexcept;
simdjson_inline simdjson_result<std::string_view> get_string(bool allow_replacement = false) noexcept;
template <typename string_type>
simdjson_inline error_code get_string(string_type& receiver, bool allow_replacement = false) noexcept;
simdjson_warn_unused simdjson_inline error_code get_string(string_type& receiver, bool allow_replacement = false) noexcept;
simdjson_inline simdjson_result<std::string_view> get_wobbly_string() noexcept;
simdjson_inline simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::raw_json_string> get_raw_json_string() noexcept;
simdjson_inline simdjson_result<bool> get_bool() noexcept;
@@ -942,6 +977,9 @@ public:
template<typename T> simdjson_inline error_code get(T &out) & noexcept;
template<typename T> simdjson_inline error_code get(T &out) && noexcept;
#if SIMDJSON_EXCEPTIONS
using SIMDJSON_IMPLEMENTATION::implementation_simdjson_result_base<SIMDJSON_IMPLEMENTATION::ondemand::document>::operator*;
using SIMDJSON_IMPLEMENTATION::implementation_simdjson_result_base<SIMDJSON_IMPLEMENTATION::ondemand::document>::operator->;
template <class T, typename std::enable_if<std::is_same<T, SIMDJSON_IMPLEMENTATION::ondemand::document>::value == false>::type>
explicit simdjson_inline operator T() noexcept(false);
simdjson_inline operator SIMDJSON_IMPLEMENTATION::ondemand::array() & noexcept(false);
@@ -981,6 +1019,11 @@ public:
simdjson_inline simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::value> at_pointer(std::string_view json_pointer) noexcept;
simdjson_inline simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::value> at_path(std::string_view json_path) noexcept;
#if SIMDJSON_STATIC_REFLECTION
template<constevalutil::fixed_string... FieldNames, typename T>
requires(std::is_class_v<T> && (sizeof...(FieldNames) > 0))
simdjson_warn_unused simdjson_inline error_code extract_into(T& out) & noexcept;
#endif // SIMDJSON_STATIC_REFLECTION
};
@@ -1007,7 +1050,7 @@ public:
simdjson_inline simdjson_result<double> get_double_in_string() noexcept;
simdjson_inline simdjson_result<std::string_view> get_string(bool allow_replacement = false) noexcept;
template <typename string_type>
simdjson_inline error_code get_string(string_type& receiver, bool allow_replacement = false) noexcept;
simdjson_warn_unused simdjson_inline error_code get_string(string_type& receiver, bool allow_replacement = false) noexcept;
simdjson_inline simdjson_result<std::string_view> get_wobbly_string() noexcept;
simdjson_inline simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::raw_json_string> get_raw_json_string() noexcept;
simdjson_inline simdjson_result<bool> get_bool() noexcept;
@@ -1058,6 +1101,11 @@ public:
simdjson_inline simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::value> at_pointer(std::string_view json_pointer) noexcept;
simdjson_inline simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::value> at_path(std::string_view json_path) noexcept;
#if SIMDJSON_STATIC_REFLECTION
template<constevalutil::fixed_string... FieldNames, typename T>
requires(std::is_class_v<T> && (sizeof...(FieldNames) > 0))
simdjson_warn_unused simdjson_inline error_code extract_into(T& out) & noexcept;
#endif // SIMDJSON_STATIC_REFLECTION
};
@@ -312,7 +312,10 @@ inline void document_stream::next_document() noexcept {
// Always set depth=1 at the start of document
doc.iter._depth = 1;
// consume comma if comma separated is allowed
if (allow_comma_separated) { doc.iter.consume_character(','); }
if (allow_comma_separated) {
error_code ignored = doc.iter.consume_character(',');
static_cast<void>(ignored); // ignored on purpose
}
// Resets the string buffer at the beginning, thus invalidating the strings.
doc.iter._string_buf_loc = parser->string_buf.get();
doc.iter._root = doc.iter.position();
@@ -114,7 +114,7 @@ simdjson_inline simdjson_result<std::string_view> simdjson_result<SIMDJSON_IMPLE
}
template<typename string_type>
simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::field>::unescaped_key(string_type &receiver, bool allow_replacement) noexcept {
simdjson_warn_unused simdjson_inline error_code simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::field>::unescaped_key(string_type &receiver, bool allow_replacement) noexcept {
if (error()) { return error(); }
return first.unescaped_key(receiver, allow_replacement);
}
+163 -138
View File
@@ -6,93 +6,40 @@
#ifndef SIMDJSON_CONDITIONAL_INCLUDE
#define SIMDJSON_GENERIC_STRING_BUILDER_H
#include "simdjson/generic/ondemand/json_string_builder.h"
#include "simdjson/generic/ondemand/json_string_builder-inl.h"
#include "simdjson/generic/builder/json_string_builder.h"
#include "simdjson/concepts.h"
#endif // SIMDJSON_CONDITIONAL_INCLUDE
#if SIMDJSON_STATIC_REFLECTION
#include <charconv>
#include <cstring>
#include <experimental/meta>
#include <meta>
#include <memory>
#include <optional>
#include <string_view>
#include <type_traits>
#include <utility>
// #include <static_reflection> // for std::define_static_string - header not available yet
namespace simdjson {
namespace SIMDJSON_IMPLEMENTATION {
namespace builder {
// Helper template to implement serialization with different strategies
template<typename T, bool UseConsteval>
struct atom_struct_impl {
static void serialize(string_builder &b, const T &t) {
// Runtime implementation - always use runtime string construction
int i = 0;
b.append('{');
[:expand(std::meta::nonstatic_data_members_of(^^T, std::meta::access_context::unchecked())):] >> [&]<auto dm>() {
if (i++ != 0)
b.append(',');
std::string key = "\"" + std::string(std::meta::identifier_of(dm)) + "\"";
b.append_raw(key);
b.append(':');
atom(b, t.[:dm:]);
};
b.append('}');
}
};
#if SIMDJSON_CONSTEVAL && !defined(SIMDJSON_ABLATION_NO_CONSTEVAL)
// Specialization for consteval optimization
template<typename T>
struct atom_struct_impl<T, true> {
static void serialize(string_builder &b, const T &t) {
b.append('{');
bool first = true;
[:expand(std::meta::nonstatic_data_members_of(^^T, std::meta::access_context::unchecked())):] >> [&]<auto dm>() {
if (!first)
b.append(',');
first = false;
// Use std::define_static_string directly with the consteval result
constexpr const char* static_key = std::define_static_string(consteval_to_quoted_escaped(std::meta::identifier_of(dm)));
b.append_raw(static_key);
b.append(':');
atom(b, t.[:dm:]);
};
b.append('}');
}
};
#endif
// Concept that checks if a type is a container but not a string (because
// strings handling must be handled differently)
template <typename T>
concept container_but_not_string =
requires(T a) {
{ a.size() } -> std::convertible_to<std::size_t>;
{
a[std::declval<std::size_t>()]
}; // check if elements are accessible for the subscript operator
} && !std::is_same_v<T, std::string> &&
!std::is_same_v<T, std::string_view> && !std::is_same_v<T, const char *>;
template <class T>
requires(container_but_not_string<T>)
void atom(string_builder &b, const T &t) {
if (t.size() == 0) {
requires(concepts::container_but_not_string<T> && !require_custom_serialization<T>)
constexpr void atom(string_builder &b, const T &t) {
auto it = t.begin();
auto end = t.end();
if (it == end) {
b.append_raw("[]");
return;
}
b.append('[');
atom(b, t[0]);
for (size_t i = 1; i < t.size(); ++i) {
atom(b, *it);
++it;
for (; it != end; ++it) {
b.append(',');
atom(b, t[i]);
atom(b, *it);
}
b.append(']');
}
@@ -102,12 +49,13 @@ template <class T>
std::is_same_v<T, std::string_view> ||
std::is_same_v<T, const char *> ||
std::is_same_v<T, char>)
void atom(string_builder &b, const T &t) {
constexpr void atom(string_builder &b, const T &t) {
b.escape_and_append_with_quotes(t);
}
template <concepts::string_view_keyed_map T>
void atom(string_builder &b, const T &m) {
requires(!require_custom_serialization<T>)
constexpr void atom(string_builder &b, const T &m) {
if (m.empty()) {
b.append_raw("{}");
return;
@@ -130,12 +78,12 @@ void atom(string_builder &b, const T &m) {
template<typename number_type,
typename = typename std::enable_if<std::is_arithmetic<number_type>::value && !std::is_same_v<number_type, char>>::type>
void atom(string_builder &b, const number_type t) {
constexpr void atom(string_builder &b, const number_type t) {
b.append(t);
}
template <class T>
requires(std::is_class_v<T> && !container_but_not_string<T> &&
requires(std::is_class_v<T> && !concepts::container_but_not_string<T> &&
!concepts::string_view_keyed_map<T> &&
!concepts::optional_type<T> &&
!concepts::smart_pointer<T> &&
@@ -143,18 +91,26 @@ template <class T>
!std::is_same_v<T, std::string> &&
!std::is_same_v<T, std::string_view> &&
!std::is_same_v<T, const char*> &&
!std::is_same_v<T, char>)
void atom(string_builder &b, const T &t) {
#if SIMDJSON_CONSTEVAL && !defined(SIMDJSON_ABLATION_NO_CONSTEVAL)
atom_struct_impl<T, true>::serialize(b, t);
#else
atom_struct_impl<T, false>::serialize(b, t);
#endif
!std::is_same_v<T, char> && !require_custom_serialization<T>)
constexpr void atom(string_builder &b, const T &t) {
int i = 0;
b.append('{');
template for (constexpr auto dm : std::define_static_array(std::meta::nonstatic_data_members_of(^^T, std::meta::access_context::unchecked()))) {
if (i != 0)
b.append(',');
constexpr auto key = std::define_static_string(constevalutil::consteval_to_quoted_escaped(std::meta::identifier_of(dm)));
b.append_raw(key);
b.append(':');
atom(b, t.[:dm:]);
i++;
};
b.append('}');
}
// Support for optional types (std::optional, etc.)
template <concepts::optional_type T>
void atom(string_builder &b, const T &opt) {
requires(!require_custom_serialization<T>)
constexpr void atom(string_builder &b, const T &opt) {
if (opt) {
atom(b, opt.value());
} else {
@@ -164,7 +120,8 @@ void atom(string_builder &b, const T &opt) {
// Support for smart pointers (std::unique_ptr, std::shared_ptr, etc.)
template <concepts::smart_pointer T>
void atom(string_builder &b, const T &ptr) {
requires(!require_custom_serialization<T>)
constexpr void atom(string_builder &b, const T &ptr) {
if (ptr) {
atom(b, *ptr);
} else {
@@ -174,49 +131,19 @@ void atom(string_builder &b, const T &ptr) {
// Support for enums - serialize as string representation using expand approach from P2996R12
template <typename T>
requires(std::is_enum_v<T>)
requires(std::is_enum_v<T> && !require_custom_serialization<T>)
void atom(string_builder &b, const T &e) {
#if SIMDJSON_STATIC_REFLECTION
#ifndef SIMDJSON_ABLATION_NO_CONSTANT_FOLDING
// Compile-time optimization: pre-compute enum lookup table for faster runtime lookup
constexpr auto enum_values = std::define_static_array(std::meta::enumerators_of(^^T));
constexpr size_t enum_count = enum_values.size();
// Small enum optimization: use compile-time lookup for common small enums
if constexpr (enum_count <= 8) {
// Fast path for small enums with compile-time switch generation
[:expand(enum_values):] >> [&]<auto enum_val>{
if (e == [:enum_val:]) {
constexpr auto name = std::meta::identifier_of(enum_val);
b.append_raw("\"");
b.append_raw(name);
b.append_raw("\"");
return;
}
};
// If not found, fallback to integer
atom(b, static_cast<std::underlying_type_t<T>>(e));
} else {
#endif
// Standard implementation for larger enums
std::string_view result = "<unnamed>";
[:expand(std::meta::enumerators_of(^^T)):] >> [&]<auto enum_val>{
if (e == [:enum_val:]) {
result = std::meta::identifier_of(enum_val);
}
};
if (result != "<unnamed>") {
b.append_raw("\"");
b.append_raw(result);
b.append_raw("\"");
} else {
// Fallback to integer if enum value not found
atom(b, static_cast<std::underlying_type_t<T>>(e));
constexpr auto enumerators = std::define_static_array(std::meta::enumerators_of(^^T));
template for (constexpr auto enum_val : enumerators) {
constexpr auto enum_str = std::define_static_string(constevalutil::consteval_to_quoted_escaped(std::meta::identifier_of(enum_val)));
if (e == [:enum_val:]) {
b.append_raw(enum_str);
return;
}
#ifndef SIMDJSON_ABLATION_NO_CONSTANT_FOLDING
}
#endif
};
// Fallback to integer if enum value not found
atom(b, static_cast<std::underlying_type_t<T>>(e));
#else
// Fallback: serialize as integer if reflection not available
atom(b, static_cast<std::underlying_type_t<T>>(e));
@@ -225,11 +152,11 @@ void atom(string_builder &b, const T &e) {
// Support for appendable containers that don't have operator[] (sets, etc.)
template <concepts::appendable_containers T>
requires(!container_but_not_string<T> && !concepts::string_view_keyed_map<T> &&
requires(!concepts::container_but_not_string<T> && !concepts::string_view_keyed_map<T> &&
!concepts::optional_type<T> && !concepts::smart_pointer<T> &&
!std::is_same_v<T, std::string> &&
!std::is_same_v<T, std::string_view> && !std::is_same_v<T, const char*>)
void atom(string_builder &b, const T &container) {
!std::is_same_v<T, std::string_view> && !std::is_same_v<T, const char*> && !require_custom_serialization<T>)
constexpr void atom(string_builder &b, const T &container) {
if (container.empty()) {
b.append_raw("[]");
return;
@@ -263,32 +190,35 @@ void append(string_builder &b, const T &t) {
}
template <concepts::optional_type T>
requires(!require_custom_serialization<T>)
void append(string_builder &b, const T &t) {
atom(b, t);
}
template <concepts::smart_pointer T>
requires(!require_custom_serialization<T>)
void append(string_builder &b, const T &t) {
atom(b, t);
}
template <concepts::appendable_containers T>
requires(!container_but_not_string<T> && !concepts::string_view_keyed_map<T> &&
requires(!concepts::container_but_not_string<T> && !concepts::string_view_keyed_map<T> &&
!concepts::optional_type<T> && !concepts::smart_pointer<T> &&
!std::is_same_v<T, std::string> &&
!std::is_same_v<T, std::string_view> && !std::is_same_v<T, const char*>)
!std::is_same_v<T, std::string_view> && !std::is_same_v<T, const char*> && !require_custom_serialization<T>)
void append(string_builder &b, const T &t) {
atom(b, t);
}
template <concepts::string_view_keyed_map T>
requires(!require_custom_serialization<T>)
void append(string_builder &b, const T &t) {
atom(b, t);
}
// works for struct
template <class Z>
requires(std::is_class_v<Z> && !container_but_not_string<Z> &&
requires(std::is_class_v<Z> && !concepts::container_but_not_string<Z> &&
!concepts::string_view_keyed_map<Z> &&
!concepts::optional_type<Z> &&
!concepts::smart_pointer<Z> &&
@@ -296,31 +226,51 @@ template <class Z>
!std::is_same_v<Z, std::string> &&
!std::is_same_v<Z, std::string_view> &&
!std::is_same_v<Z, const char*> &&
!std::is_same_v<Z, char>)
!std::is_same_v<Z, char> && !require_custom_serialization<Z>)
void append(string_builder &b, const Z &z) {
// The atom function now handles both cases internally
atom(b, z);
int i = 0;
b.append('{');
template for (constexpr auto dm : std::define_static_array(std::meta::nonstatic_data_members_of(^^Z, std::meta::access_context::unchecked()))) {
if (i != 0)
b.append(',');
constexpr auto key = std::define_static_string(constevalutil::consteval_to_quoted_escaped(std::meta::identifier_of(dm)));
b.append_raw(key);
b.append(':');
atom(b, z.[:dm:]);
i++;
};
b.append('}');
}
// works for container
// works for container that have begin() and end() iterators
template <class Z>
requires(container_but_not_string<Z>)
requires(concepts::container_but_not_string<Z> && !require_custom_serialization<Z>)
void append(string_builder &b, const Z &z) {
if (z.size() == 0) {
auto it = z.begin();
auto end = z.end();
if (it == end) {
b.append_raw("[]");
return;
}
b.append('[');
atom(b, z[0]);
for (size_t i = 1; i < z.size(); ++i) {
atom(b, *it);
++it;
for (; it != end; ++it) {
b.append(',');
atom(b, z[i]);
atom(b, *it);
}
b.append(']');
}
template <class Z>
simdjson_result<std::string> to_json_string(const Z &z, size_t initial_capacity = 1024) {
requires (require_custom_serialization<Z>)
void append(string_builder &b, const Z &z) {
b.append(z);
}
template <class Z>
simdjson_warn_unused simdjson_result<std::string> to_json_string(const Z &z, size_t initial_capacity = string_builder::DEFAULT_INITIAL_CAPACITY) {
string_builder b(initial_capacity);
append(b, z);
std::string_view s;
@@ -329,8 +279,8 @@ simdjson_result<std::string> to_json_string(const Z &z, size_t initial_capacity
}
template <class Z>
simdjson_error to_json(const Z &z, std::string &s) {
string_builder b;
simdjson_warn_unused simdjson_error to_json(const Z &z, std::string &s, size_t initial_capacity = string_builder::DEFAULT_INITIAL_CAPACITY) {
string_builder b(initial_capacity);
append(b, z);
std::string_view view;
if(auto e = b.view().get(view); e) { return e; }
@@ -343,13 +293,88 @@ string_builder& operator<<(string_builder& b, const Z& z) {
append(b, z);
return b;
}
// extract_from: Serialize only specific fields from a struct to JSON
template<constevalutil::fixed_string... FieldNames, typename T>
requires(std::is_class_v<T> && (sizeof...(FieldNames) > 0))
void extract_from(string_builder &b, const T &obj) {
// Helper to check if a field name matches any of the requested fields
auto should_extract = [](std::string_view field_name) constexpr -> bool {
return ((FieldNames.view() == field_name) || ...);
};
b.append('{');
bool first = true;
// Iterate through all members of T using reflection
template for (constexpr auto mem : std::define_static_array(
std::meta::nonstatic_data_members_of(^^T, std::meta::access_context::unchecked()))) {
if constexpr (std::meta::is_public(mem)) {
constexpr std::string_view key = std::define_static_string(std::meta::identifier_of(mem));
// Only serialize this field if it's in our list of requested fields
if constexpr (should_extract(key)) {
if (!first) {
b.append(',');
}
first = false;
// Serialize the key
constexpr auto quoted_key = std::define_static_string(constevalutil::consteval_to_quoted_escaped(std::meta::identifier_of(mem)));
b.append_raw(quoted_key);
b.append(':');
// Serialize the value
atom(b, obj.[:mem:]);
}
}
};
b.append('}');
}
template<constevalutil::fixed_string... FieldNames, typename T>
requires(std::is_class_v<T> && (sizeof...(FieldNames) > 0))
simdjson_warn_unused simdjson_result<std::string> extract_from(const T &obj, size_t initial_capacity = string_builder::DEFAULT_INITIAL_CAPACITY) {
string_builder b(initial_capacity);
extract_from<FieldNames...>(b, obj);
std::string_view s;
if(auto e = b.view().get(s); e) { return e; }
return std::string(s);
}
} // namespace builder
} // namespace SIMDJSON_IMPLEMENTATION
// Alias the function template to 'to' in the global namespace
template <class Z>
simdjson_result<std::string> to_json(const Z &z, size_t initial_capacity = 1024) {
return SIMDJSON_IMPLEMENTATION::builder::to_json_string(z, initial_capacity);
simdjson_warn_unused simdjson_result<std::string> to_json(const Z &z, size_t initial_capacity = SIMDJSON_IMPLEMENTATION::builder::string_builder::DEFAULT_INITIAL_CAPACITY) {
SIMDJSON_IMPLEMENTATION::builder::string_builder b(initial_capacity);
SIMDJSON_IMPLEMENTATION::builder::append(b, z);
std::string_view s;
if(auto e = b.view().get(s); e) { return e; }
return std::string(s);
}
template <class Z>
simdjson_warn_unused simdjson_error to_json(const Z &z, std::string &s, size_t initial_capacity = SIMDJSON_IMPLEMENTATION::builder::string_builder::DEFAULT_INITIAL_CAPACITY) {
SIMDJSON_IMPLEMENTATION::builder::string_builder b(initial_capacity);
SIMDJSON_IMPLEMENTATION::builder::append(b, z);
std::string_view view;
if(auto e = b.view().get(view); e) { return e; }
s.assign(view);
return SUCCESS;
}
// Global namespace function for extract_from
template<constevalutil::fixed_string... FieldNames, typename T>
requires(std::is_class_v<T> && (sizeof...(FieldNames) > 0))
simdjson_warn_unused simdjson_result<std::string> extract_from(const T &obj, size_t initial_capacity = SIMDJSON_IMPLEMENTATION::builder::string_builder::DEFAULT_INITIAL_CAPACITY) {
SIMDJSON_IMPLEMENTATION::builder::string_builder b(initial_capacity);
SIMDJSON_IMPLEMENTATION::builder::extract_from<FieldNames...>(b, obj);
std::string_view s;
if(auto e = b.view().get(s); e) { return e; }
return std::string(s);
}
} // namespace simdjson
#endif // SIMDJSON_STATIC_REFLECTION
@@ -344,7 +344,7 @@ simdjson_inline uint8_t *&json_iterator::string_buf_loc() noexcept {
return _string_buf_loc;
}
simdjson_inline error_code json_iterator::report_error(error_code _error, const char *message) noexcept {
simdjson_warn_unused simdjson_inline error_code json_iterator::report_error(error_code _error, const char *message) noexcept {
SIMDJSON_ASSUME(_error != SUCCESS && _error != UNINITIALIZED && _error != INCORRECT_TYPE && _error != NO_SUCH_FIELD);
logger::log_error(*this, message);
error = _error;
@@ -388,7 +388,7 @@ simdjson_inline void json_iterator::reenter_child(token_position position, depth
_depth = child_depth;
}
simdjson_inline error_code json_iterator::consume_character(char c) noexcept {
simdjson_warn_unused simdjson_inline error_code json_iterator::consume_character(char c) noexcept {
if (*peek() == c) {
return_current_and_advance();
return SUCCESS;
@@ -411,7 +411,7 @@ simdjson_inline void json_iterator::set_start_position(depth_t depth, token_posi
#endif
simdjson_inline error_code json_iterator::optional_error(error_code _error, const char *message) noexcept {
simdjson_warn_unused simdjson_inline error_code json_iterator::optional_error(error_code _error, const char *message) noexcept {
SIMDJSON_ASSUME(_error == INCORRECT_TYPE || _error == NO_SUCH_FIELD);
logger::log_error(*this, message);
return _error;
@@ -238,14 +238,14 @@ public:
* @param error The error to report. Must not be SUCCESS, UNINITIALIZED, INCORRECT_TYPE, or NO_SUCH_FIELD.
* @param message An error message to report with the error.
*/
simdjson_inline error_code report_error(error_code error, const char *message) noexcept;
simdjson_warn_unused simdjson_inline error_code report_error(error_code error, const char *message) noexcept;
/**
* Log error, but don't stop iteration.
* @param error The error to report. Must be INCORRECT_TYPE, or NO_SUCH_FIELD.
* @param message An error message to report with the error.
*/
simdjson_inline error_code optional_error(error_code error, const char *message) noexcept;
simdjson_warn_unused simdjson_inline error_code optional_error(error_code error, const char *message) noexcept;
/**
* Take an input in json containing max_len characters and attempt to copy it over to tmpbuf, a buffer with
@@ -265,7 +265,7 @@ public:
simdjson_inline void reenter_child(token_position position, depth_t child_depth) noexcept;
simdjson_inline error_code consume_character(char c) noexcept;
simdjson_warn_unused simdjson_inline error_code consume_character(char c) noexcept;
#if SIMDJSON_DEVELOPMENT_CHECKS
simdjson_inline token_position start_position(depth_t depth) const noexcept;
simdjson_inline void set_start_position(depth_t depth, token_position position) noexcept;
@@ -42,24 +42,25 @@ namespace simdjson {
namespace SIMDJSON_IMPLEMENTATION {
namespace builder {
static SIMDJSON_CONSTEXPR_LAMBDA std::array<uint8_t, 256> json_quotable_character = {
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, 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, 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,
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, 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, 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,
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, 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};
static SIMDJSON_CONSTEXPR_LAMBDA std::array<uint8_t, 256>
json_quotable_character = {
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, 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, 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,
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, 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, 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,
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, 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};
/**
A possible SWAR implementation of has_json_escapable_byte. It is not used because
it is slower than the current implementation. It is kept here for reference (to show
that we tried it).
A possible SWAR implementation of has_json_escapable_byte. It is not used
because it is slower than the current implementation. It is kept here for
reference (to show that we tried it).
inline bool has_json_escapable_byte(uint64_t x) {
uint64_t is_ascii = 0x8080808080808080ULL & ~x;
@@ -76,18 +77,14 @@ SIMDJSON_CONSTEXPR_LAMBDA simdjson_inline bool
simple_needs_escaping(std::string_view v) {
for (char c : v) {
// a table lookup is faster than a series of comparisons
if(json_quotable_character[static_cast<uint8_t>(c)]) {
if (json_quotable_character[static_cast<uint8_t>(c)]) {
return true;
}
}
return false;
}
#ifdef SIMDJSON_ABLATION_NO_SIMD_ESCAPING
simdjson_inline bool fast_needs_escaping(std::string_view view) {
return simple_needs_escaping(view);
}
#elif SIMDJSON_EXPERIMENTAL_HAS_NEON
#if SIMDJSON_EXPERIMENTAL_HAS_NEON
simdjson_inline bool fast_needs_escaping(std::string_view view) {
if (view.size() < 16) {
return simple_needs_escaping(view);
@@ -97,20 +94,7 @@ simdjson_inline bool fast_needs_escaping(std::string_view view) {
uint8x16_t v34 = vdupq_n_u8(34);
uint8x16_t v92 = vdupq_n_u8(92);
#ifndef SIMDJSON_ABLATION_NO_PREFETCH
// Prefetch data for better cache performance on large strings
if (simdjson_likely(view.size() > 64)) {
__builtin_prefetch(view.data() + 64, 0, 1);
}
#endif
for (; i + 15 < view.size(); i += 16) {
#ifndef SIMDJSON_ABLATION_NO_PREFETCH
// Prefetch next cache line ahead
if (simdjson_likely(i + 64 < view.size())) {
__builtin_prefetch(view.data() + i + 64, 0, 1);
}
#endif
uint8x16_t word = vld1q_u8((const uint8_t *)view.data() + i);
running = vorrq_u8(running, vceqq_u8(word, v34));
running = vorrq_u8(running, vceqq_u8(word, v92));
@@ -132,22 +116,10 @@ simdjson_inline bool fast_needs_escaping(std::string_view view) {
}
size_t i = 0;
__m128i running = _mm_setzero_si128();
#ifndef SIMDJSON_ABLATION_NO_PREFETCH
// Prefetch data for better cache performance on large strings
if (simdjson_likely(view.size() > 64)) {
__builtin_prefetch(view.data() + 64, 0, 1);
}
#endif
for (; i + 15 < view.size(); i += 16) {
#ifndef SIMDJSON_ABLATION_NO_PREFETCH
// Prefetch next cache line ahead for streaming access
if (simdjson_likely(i + 64 < view.size())) {
__builtin_prefetch(view.data() + i + 64, 0, 1);
}
#endif
__m128i word = _mm_loadu_si128(reinterpret_cast<const __m128i *>(view.data() + i));
__m128i word =
_mm_loadu_si128(reinterpret_cast<const __m128i *>(view.data() + i));
running = _mm_or_si128(running, _mm_cmpeq_epi8(word, _mm_set1_epi8(34)));
running = _mm_or_si128(running, _mm_cmpeq_epi8(word, _mm_set1_epi8(92)));
running = _mm_or_si128(
@@ -155,8 +127,8 @@ simdjson_inline bool fast_needs_escaping(std::string_view view) {
_mm_setzero_si128()));
}
if (i < view.size()) {
__m128i word =
_mm_loadu_si128(reinterpret_cast<const __m128i *>(view.data() + view.length() - 16));
__m128i word = _mm_loadu_si128(
reinterpret_cast<const __m128i *>(view.data() + view.length() - 16));
running = _mm_or_si128(running, _mm_cmpeq_epi8(word, _mm_set1_epi8(34)));
running = _mm_or_si128(running, _mm_cmpeq_epi8(word, _mm_set1_epi8(92)));
running = _mm_or_si128(
@@ -171,7 +143,6 @@ simdjson_inline bool fast_needs_escaping(std::string_view view) {
}
#endif
SIMDJSON_CONSTEXPR_LAMBDA inline size_t
find_next_json_quotable_character(const std::string_view view,
size_t location) noexcept {
@@ -185,13 +156,17 @@ find_next_json_quotable_character(const std::string_view view,
}
SIMDJSON_CONSTEXPR_LAMBDA static std::string_view control_chars[] = {
"\\x0000", "\\x0001", "\\x0002", "\\x0003", "\\x0004", "\\x0005", "\\x0006",
"\\x0007", "\\x0008", "\\t", "\\n", "\\x000b", "\\f", "\\r",
"\\x000e", "\\x000f", "\\x0010", "\\x0011", "\\x0012", "\\x0013", "\\x0014",
"\\x0015", "\\x0016", "\\x0017", "\\x0018", "\\x0019", "\\x001a", "\\x001b",
"\\x001c", "\\x001d", "\\x001e", "\\x001f"};
"\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004", "\\u0005", "\\u0006",
"\\u0007", "\\b", "\\t", "\\n", "\\u000b", "\\f", "\\r",
"\\u000e", "\\u000f", "\\u0010", "\\u0011", "\\u0012", "\\u0013", "\\u0014",
"\\u0015", "\\u0016", "\\u0017", "\\u0018", "\\u0019", "\\u001a", "\\u001b",
"\\u001c", "\\u001d", "\\u001e", "\\u001f"};
#ifdef SIMDJSON_ABLATION_NO_INLINE_OPTIMIZATIONS
// All Unicode characters may be placed within the quotation marks, except for
// the characters that MUST be escaped: quotation mark, reverse solidus, and the
// control characters (U+0000 through U+001F). There are two-character sequence
// escape representations of some popular characters:
// \", \\, \b, \f, \n, \r, \t.
SIMDJSON_CONSTEXPR_LAMBDA void escape_json_char(char c, char *&out) {
if (c == '"') {
memcpy(out, "\\\"", 2);
@@ -205,57 +180,15 @@ SIMDJSON_CONSTEXPR_LAMBDA void escape_json_char(char c, char *&out) {
out += v.size();
}
}
#else
// Optimized version with likely branch and manual inlining for hot paths
SIMDJSON_CONSTEXPR_LAMBDA simdjson_inline void escape_json_char(char c, char *&out) {
// Most common cases first for better branch prediction
if (simdjson_likely(c == '"')) {
// Manual unroll for common quote case
*out++ = '\\';
*out++ = '"';
} else if (simdjson_likely(c == '\\')) {
// Manual unroll for common backslash case
*out++ = '\\';
*out++ = '\\';
} else {
// Less common control characters - use lookup table
std::string_view v = control_chars[uint8_t(c)];
// Prefetch next control char entry for potential next escape
__builtin_prefetch(&control_chars[uint8_t(c) + 1], 0, 1);
memcpy(out, v.data(), v.size());
out += v.size();
}
}
#endif
inline size_t write_string_escaped(const std::string_view input, char *out) {
size_t mysize = input.size();
#ifdef SIMDJSON_ABLATION_NO_ESCAPE_FAST_PATH
// Always use slow path - no fast path optimization
#elif defined(SIMDJSON_ABLATION_NO_INLINE_OPTIMIZATIONS)
if (!fast_needs_escaping(input)) { // fast path!
memcpy(out, input.data(), input.size());
return input.size();
}
#else
// Optimized fast path with prefetching
if (simdjson_likely(!fast_needs_escaping(input))) {
// Prefetch destination memory for large copies
if (simdjson_likely(input.size() > 64)) {
__builtin_prefetch(out + 64, 1, 1);
}
memcpy(out, input.data(), input.size());
return input.size();
}
#endif
const char *const initout = out;
size_t location = find_next_json_quotable_character(input, 0);
#ifndef SIMDJSON_ABLATION_NO_INLINE_OPTIMIZATIONS
// Prefetch ahead in input string for next character scan
if (simdjson_likely(location + 64 < mysize)) {
__builtin_prefetch(input.data() + location + 64, 0, 1);
}
#endif
memcpy(out, input.data(), location);
out += location;
escape_json_char(input[location], out);
@@ -265,7 +198,7 @@ inline size_t write_string_escaped(const std::string_view input, char *out) {
memcpy(out, input.data() + location, newlocation - location);
out += newlocation - location;
location = newlocation;
if (simdjson_unlikely(location == mysize)) {
if (location == mysize) {
break;
}
escape_json_char(input[location], out);
@@ -274,29 +207,6 @@ inline size_t write_string_escaped(const std::string_view input, char *out) {
return out - initout;
}
#if SIMDJSON_CONSTEVAL && !defined(SIMDJSON_ABLATION_NO_CONSTEVAL)
// unoptimized, meant for compile-time execution
consteval std::string consteval_to_quoted_escaped(std::string_view input) {
std::string out = "\"";
for (char c : input) {
if (json_quotable_character[uint8_t(c)]) {
if (c == '"') {
out.append("\\\"");
} else if (c == '\\') {
out.append("\\\\");
} else {
std::string_view v = control_chars[uint8_t(c)];
out.append(v);
}
} else {
out.push_back(c);
}
}
out.push_back('"');
return out;
}
#endif // SIMDJSON_CONSTEVAL
simdjson_inline string_builder::string_builder(size_t initial_capacity)
: buffer(new(std::nothrow) char[initial_capacity]), position(0),
capacity(buffer.get() != nullptr ? initial_capacity : 0),
@@ -306,38 +216,15 @@ simdjson_inline bool string_builder::capacity_check(size_t upcoming_bytes) {
// We use the convention that when is_valid is false, then the capacity and
// the position are 0.
// Most of the time, this function will return true.
#ifdef SIMDJSON_ABLATION_NO_BRANCH_HINTS
if (upcoming_bytes <= capacity - position) {
return true;
}
// check for overflow, most of the time there is no overflow
if (position + upcoming_bytes < position) {
return false;
}
#else
if (simdjson_likely(upcoming_bytes <= capacity - position)) {
return true;
}
// check for overflow, most of the time there is no overflow
if (simdjson_unlikely(position + upcoming_bytes < position)) {
if (simdjson_likely(position + upcoming_bytes < position)) {
return false;
}
#endif
// We will rarely get here.
#ifdef SIMDJSON_ABLATION_LINEAR_GROWTH
grow_buffer(position + upcoming_bytes + 1024); // Linear growth with 1KB increment
#elif defined(SIMDJSON_ABLATION_NO_INLINE_OPTIMIZATIONS)
grow_buffer((std::max)(capacity * 2, position + upcoming_bytes)); // Exponential growth
#else
// Optimized growth with better cache behavior
size_t new_capacity = capacity * 2;
if (simdjson_unlikely(new_capacity < position + upcoming_bytes)) {
new_capacity = position + upcoming_bytes;
}
// Align to cache line boundary for better memory access patterns
new_capacity = (new_capacity + 63) & ~63;
grow_buffer(new_capacity);
#endif
grow_buffer((std::max)(capacity * 2, position + upcoming_bytes));
// If the buffer allocation failed, we set is_valid to false.
return is_valid;
}
@@ -398,10 +285,13 @@ simdjson_inline void string_builder::clear() noexcept {
namespace internal {
// We could specialize further for 32-bit integers.
simdjson_really_inline int int_log2(uint32_t x) { return (63 - leading_zeroes(x | 1)); }
template <typename number_type, typename = typename std::enable_if<
std::is_unsigned<number_type>::value>::type>
simdjson_really_inline int int_log2(number_type x) {
return 63 - leading_zeroes(uint64_t(x) | 1);
}
simdjson_really_inline int fast_digit_count(uint32_t x) {
simdjson_really_inline int fast_digit_count_32(uint32_t x) {
static uint64_t table[] = {
4294967296, 8589934582, 8589934582, 8589934582, 12884901788,
12884901788, 12884901788, 17179868184, 17179868184, 17179868184,
@@ -413,9 +303,7 @@ simdjson_really_inline int fast_digit_count(uint32_t x) {
return uint32_t((x + table[int_log2(x)]) >> 32);
}
simdjson_really_inline int int_log2(uint64_t x) { return 63 - leading_zeroes(x | 1); }
simdjson_really_inline int fast_digit_count(uint64_t x) {
simdjson_really_inline int fast_digit_count_64(uint64_t x) {
static uint64_t table[] = {9,
99,
999,
@@ -446,31 +334,31 @@ simdjson_really_inline size_t digit_count(number_type v) noexcept {
static_assert(sizeof(number_type) == 8 || sizeof(number_type) == 4 ||
sizeof(number_type) == 2 || sizeof(number_type) == 1,
"We only support 8-bit, 16-bit, 32-bit and 64-bit numbers");
#ifdef SIMDJSON_ABLATION_NO_FAST_DIGITS
// Fallback: use standard library conversion to count digits
return std::to_string(v).length();
#else
return fast_digit_count(v);
#endif
SIMDJSON_IF_CONSTEXPR(sizeof(number_type) <= 4) {
return fast_digit_count_32(static_cast<uint32_t>(v));
}
else {
return fast_digit_count_64(static_cast<uint64_t>(v));
}
}
static const char decimal_table[200] = {
0x30, 0x30, 0x30, 0x31, 0x30, 0x32, 0x30, 0x33, 0x30, 0x34, 0x30, 0x35,
0x30, 0x36, 0x30, 0x37, 0x30, 0x38, 0x30, 0x39, 0x31, 0x30, 0x31, 0x31,
0x31, 0x32, 0x31, 0x33, 0x31, 0x34, 0x31, 0x35, 0x31, 0x36, 0x31, 0x37,
0x31, 0x38, 0x31, 0x39, 0x32, 0x30, 0x32, 0x31, 0x32, 0x32, 0x32, 0x33,
0x32, 0x34, 0x32, 0x35, 0x32, 0x36, 0x32, 0x37, 0x32, 0x38, 0x32, 0x39,
0x33, 0x30, 0x33, 0x31, 0x33, 0x32, 0x33, 0x33, 0x33, 0x34, 0x33, 0x35,
0x33, 0x36, 0x33, 0x37, 0x33, 0x38, 0x33, 0x39, 0x34, 0x30, 0x34, 0x31,
0x34, 0x32, 0x34, 0x33, 0x34, 0x34, 0x34, 0x35, 0x34, 0x36, 0x34, 0x37,
0x34, 0x38, 0x34, 0x39, 0x35, 0x30, 0x35, 0x31, 0x35, 0x32, 0x35, 0x33,
0x35, 0x34, 0x35, 0x35, 0x35, 0x36, 0x35, 0x37, 0x35, 0x38, 0x35, 0x39,
0x36, 0x30, 0x36, 0x31, 0x36, 0x32, 0x36, 0x33, 0x36, 0x34, 0x36, 0x35,
0x36, 0x36, 0x36, 0x37, 0x36, 0x38, 0x36, 0x39, 0x37, 0x30, 0x37, 0x31,
0x37, 0x32, 0x37, 0x33, 0x37, 0x34, 0x37, 0x35, 0x37, 0x36, 0x37, 0x37,
0x37, 0x38, 0x37, 0x39, 0x38, 0x30, 0x38, 0x31, 0x38, 0x32, 0x38, 0x33,
0x38, 0x34, 0x38, 0x35, 0x38, 0x36, 0x38, 0x37, 0x38, 0x38, 0x38, 0x39,
0x39, 0x30, 0x39, 0x31, 0x39, 0x32, 0x39, 0x33, 0x39, 0x34, 0x39, 0x35,
0x39, 0x36, 0x39, 0x37, 0x39, 0x38, 0x39, 0x39,
0x30, 0x30, 0x30, 0x31, 0x30, 0x32, 0x30, 0x33, 0x30, 0x34, 0x30, 0x35,
0x30, 0x36, 0x30, 0x37, 0x30, 0x38, 0x30, 0x39, 0x31, 0x30, 0x31, 0x31,
0x31, 0x32, 0x31, 0x33, 0x31, 0x34, 0x31, 0x35, 0x31, 0x36, 0x31, 0x37,
0x31, 0x38, 0x31, 0x39, 0x32, 0x30, 0x32, 0x31, 0x32, 0x32, 0x32, 0x33,
0x32, 0x34, 0x32, 0x35, 0x32, 0x36, 0x32, 0x37, 0x32, 0x38, 0x32, 0x39,
0x33, 0x30, 0x33, 0x31, 0x33, 0x32, 0x33, 0x33, 0x33, 0x34, 0x33, 0x35,
0x33, 0x36, 0x33, 0x37, 0x33, 0x38, 0x33, 0x39, 0x34, 0x30, 0x34, 0x31,
0x34, 0x32, 0x34, 0x33, 0x34, 0x34, 0x34, 0x35, 0x34, 0x36, 0x34, 0x37,
0x34, 0x38, 0x34, 0x39, 0x35, 0x30, 0x35, 0x31, 0x35, 0x32, 0x35, 0x33,
0x35, 0x34, 0x35, 0x35, 0x35, 0x36, 0x35, 0x37, 0x35, 0x38, 0x35, 0x39,
0x36, 0x30, 0x36, 0x31, 0x36, 0x32, 0x36, 0x33, 0x36, 0x34, 0x36, 0x35,
0x36, 0x36, 0x36, 0x37, 0x36, 0x38, 0x36, 0x39, 0x37, 0x30, 0x37, 0x31,
0x37, 0x32, 0x37, 0x33, 0x37, 0x34, 0x37, 0x35, 0x37, 0x36, 0x37, 0x37,
0x37, 0x38, 0x37, 0x39, 0x38, 0x30, 0x38, 0x31, 0x38, 0x32, 0x38, 0x33,
0x38, 0x34, 0x38, 0x35, 0x38, 0x36, 0x38, 0x37, 0x38, 0x38, 0x38, 0x39,
0x39, 0x30, 0x39, 0x31, 0x39, 0x32, 0x39, 0x33, 0x39, 0x34, 0x39, 0x35,
0x39, 0x36, 0x39, 0x37, 0x39, 0x38, 0x39, 0x39,
};
} // namespace internal
@@ -506,17 +394,9 @@ simdjson_inline void string_builder::append(number_type v) noexcept {
size_t dc = internal::digit_count(pv);
char *write_pointer = buffer.get() + position + dc - 1;
while (pv >= 100) {
#ifdef SIMDJSON_ABLATION_NO_LOOKUP_TABLES
// Fallback: use division and modulo instead of lookup table
*write_pointer-- = char('0' + (pv % 10));
pv /= 10;
*write_pointer-- = char('0' + (pv % 10));
pv /= 10;
#else
memcpy(write_pointer - 1, &internal::decimal_table[(pv % 100)*2], 2);
memcpy(write_pointer - 1, &internal::decimal_table[(pv % 100) * 2], 2);
write_pointer -= 2;
pv /= 100;
#endif
}
if (pv >= 10) {
*write_pointer-- = char('0' + (pv % 10));
@@ -541,17 +421,9 @@ simdjson_inline void string_builder::append(number_type v) noexcept {
}
char *write_pointer = buffer.get() + position + dc - 1;
while (pv >= 100) {
#ifdef SIMDJSON_ABLATION_NO_LOOKUP_TABLES
// Fallback: use division and modulo instead of lookup table
*write_pointer-- = char('0' + (pv % 10));
pv /= 10;
*write_pointer-- = char('0' + (pv % 10));
pv /= 10;
#else
memcpy(write_pointer - 1, &internal::decimal_table[(pv % 100)*2], 2);
memcpy(write_pointer - 1, &internal::decimal_table[(pv % 100) * 2], 2);
write_pointer -= 2;
pv /= 100;
#endif
}
if (pv >= 10) {
*write_pointer-- = char('0' + (pv % 10));
@@ -601,10 +473,17 @@ string_builder::escape_and_append_with_quotes(char input) noexcept {
}
}
simdjson_inline void string_builder::escape_and_append_with_quotes(const char* input) noexcept {
simdjson_inline void
string_builder::escape_and_append_with_quotes(const char *input) noexcept {
std::string_view cinput(input);
escape_and_append_with_quotes(cinput);
}
#if SIMDJSON_SUPPORTS_CONCEPTS
template <constevalutil::fixed_string key>
simdjson_inline void string_builder::escape_and_append_with_quotes() noexcept {
escape_and_append_with_quotes(constevalutil::string_constant<key>::value);
}
#endif
simdjson_inline void string_builder::append_raw(const char *c) noexcept {
size_t len = std::strlen(c);
@@ -629,6 +508,7 @@ simdjson_inline void string_builder::append_raw(const char *str,
#if SIMDJSON_SUPPORTS_CONCEPTS
// Support for optional types (std::optional, etc.)
template <concepts::optional_type T>
requires(!require_custom_serialization<T>)
simdjson_inline void string_builder::append(const T &opt) {
if (opt) {
append(*opt);
@@ -636,18 +516,25 @@ simdjson_inline void string_builder::append(const T &opt) {
append_null();
}
}
template <typename T>
requires(std::is_convertible<T, std::string_view>::value ||
std::is_same<T, const char*>::value )
requires(require_custom_serialization<T>)
simdjson_inline void string_builder::append(const T &val) {
serialize(*this, val);
}
template <typename T>
requires(std::is_convertible<T, std::string_view>::value ||
std::is_same<T, const char *>::value)
simdjson_inline void string_builder::append(const T &value) {
escape_and_append_with_quotes(value);
}
#endif
#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS
// Support for range-based appending (std::ranges::view, etc.)
// Support for range-based appending (std::ranges::view, etc.)
template <std::ranges::range R>
requires (!std::is_convertible<R, std::string_view>::value)
requires(!std::is_convertible<R, std::string_view>::value)
simdjson_inline void string_builder::append(const R &range) noexcept {
auto it = std::ranges::begin(range);
auto end = std::ranges::end(range);
@@ -664,8 +551,8 @@ simdjson_inline void string_builder::append(const R &range) noexcept {
// Append remaining items with preceding commas
for (; it != end; ++it) {
append_comma();
append_key_value(it->first, it->second);
append_comma();
append_key_value(it->first, it->second);
}
end_object();
} else {
@@ -681,11 +568,10 @@ simdjson_inline void string_builder::append(const R &range) noexcept {
// Append remaining items with preceding commas
for (; it != end; ++it) {
append_comma();
append(*it);
append_comma();
append(*it);
}
end_array();
}
}
@@ -693,7 +579,7 @@ simdjson_inline void string_builder::append(const R &range) noexcept {
#if SIMDJSON_EXCEPTIONS
simdjson_inline string_builder::operator std::string() const noexcept(false) {
return std::string(std::string_view());
return std::string(operator std::string_view());
}
simdjson_inline string_builder::operator std::string_view() const
@@ -722,70 +608,95 @@ simdjson_inline bool string_builder::validate_unicode() const noexcept {
return simdjson::validate_utf8(buffer.get(), position);
}
simdjson_inline void string_builder::start_object() noexcept {
simdjson_inline void string_builder::start_object() noexcept {
if (capacity_check(1)) {
buffer.get()[position++] = '{';
}
}
simdjson_inline void string_builder::end_object() noexcept {
simdjson_inline void string_builder::end_object() noexcept {
if (capacity_check(1)) {
buffer.get()[position++] = '}';
}
}
simdjson_inline void string_builder::start_array() noexcept {
simdjson_inline void string_builder::start_array() noexcept {
if (capacity_check(1)) {
buffer.get()[position++] = '[';
}
}
simdjson_inline void string_builder::end_array() noexcept {
simdjson_inline void string_builder::end_array() noexcept {
if (capacity_check(1)) {
buffer.get()[position++] = ']';
}
}
simdjson_inline void string_builder::append_comma() noexcept {
simdjson_inline void string_builder::append_comma() noexcept {
if (capacity_check(1)) {
buffer.get()[position++] = ',';
}
}
simdjson_inline void string_builder::append_colon() noexcept {
simdjson_inline void string_builder::append_colon() noexcept {
if (capacity_check(1)) {
buffer.get()[position++] = ':';
}
}
template<typename key_type, typename value_type>
simdjson_inline void string_builder::append_key_value(key_type key, value_type value) noexcept {
static_assert(
std::is_same<key_type, const char*>::value ||
std::is_convertible<key_type, std::string_view>::value,
"Unsupported key type");
template <typename key_type, typename value_type>
simdjson_inline void
string_builder::append_key_value(key_type key, value_type value) noexcept {
static_assert(std::is_same<key_type, const char *>::value ||
std::is_convertible<key_type, std::string_view>::value,
"Unsupported key type");
escape_and_append_with_quotes(key);
append_colon();
SIMDJSON_IF_CONSTEXPR(std::is_same<value_type, std::nullptr_t>::value) {
append_null();
} else SIMDJSON_IF_CONSTEXPR(std::is_same<value_type, char>::value) {
}
else SIMDJSON_IF_CONSTEXPR(std::is_same<value_type, char>::value) {
escape_and_append_with_quotes(value);
} else SIMDJSON_IF_CONSTEXPR(std::is_convertible<value_type, std::string_view>::value) {
}
else SIMDJSON_IF_CONSTEXPR(
std::is_convertible<value_type, std::string_view>::value) {
escape_and_append_with_quotes(value);
} else SIMDJSON_IF_CONSTEXPR(std::is_same<value_type, const char*>::value) {
}
else SIMDJSON_IF_CONSTEXPR(std::is_same<value_type, const char *>::value) {
escape_and_append_with_quotes(value);
} else {
}
else {
append(value);
}
}
#if SIMDJSON_SUPPORTS_CONCEPTS
template <constevalutil::fixed_string key, typename value_type>
simdjson_inline void
string_builder::append_key_value(value_type value) noexcept {
escape_and_append_with_quotes<key>();
append_colon();
SIMDJSON_IF_CONSTEXPR(std::is_same<value_type, std::nullptr_t>::value) {
append_null();
}
else SIMDJSON_IF_CONSTEXPR(std::is_same<value_type, char>::value) {
escape_and_append_with_quotes(value);
}
else SIMDJSON_IF_CONSTEXPR(
std::is_convertible<value_type, std::string_view>::value) {
escape_and_append_with_quotes(value);
}
else SIMDJSON_IF_CONSTEXPR(std::is_same<value_type, const char *>::value) {
escape_and_append_with_quotes(value);
}
else {
append(value);
}
}
#endif
} // namespace builder
} // namespace SIMDJSON_IMPLEMENTATION
} // namespace simdjson
#endif // SIMDJSON_GENERIC_STRING_BUILDER_INL_H
#endif // SIMDJSON_GENERIC_STRING_BUILDER_INL_H
@@ -10,9 +10,40 @@
#endif // SIMDJSON_CONDITIONAL_INCLUDE
namespace simdjson {
#if SIMDJSON_SUPPORTS_CONCEPTS
namespace SIMDJSON_IMPLEMENTATION {
namespace builder {
class string_builder;
}}
template <typename T, typename = void>
struct has_custom_serialization : std::false_type {};
inline constexpr struct serialize_tag {
template <typename T>
requires custom_deserializable<T>
constexpr void operator()(SIMDJSON_IMPLEMENTATION::builder::string_builder& b, T& obj) const{
return tag_invoke(*this, b, obj);
}
} serialize{};
template <typename T>
struct has_custom_serialization<T, std::void_t<
decltype(tag_invoke(serialize, std::declval<SIMDJSON_IMPLEMENTATION::builder::string_builder&>(), std::declval<T&>()))
>> : std::true_type {};
template <typename T>
constexpr bool require_custom_serialization = has_custom_serialization<T>::value;
#else
struct has_custom_serialization : std::false_type {};
#endif // SIMDJSON_SUPPORTS_CONCEPTS
namespace SIMDJSON_IMPLEMENTATION {
namespace builder {
/**
* A builder for JSON strings representing documents. This is a low-level
* builder that is not meant to be used directly by end-users. Though it
@@ -24,7 +55,9 @@ namespace builder {
*/
class string_builder {
public:
simdjson_inline string_builder(size_t initial_capacity = 1024);
simdjson_inline string_builder(size_t initial_capacity = DEFAULT_INITIAL_CAPACITY);
static constexpr size_t DEFAULT_INITIAL_CAPACITY = 1024;
/**
* Append number (includes Booleans). Booleans are mapped to the strings
@@ -33,7 +66,7 @@ public:
* represents the number.
*/
template<typename number_type,
typename = typename std::enable_if<std::is_arithmetic<number_type>::value>::type>
typename = typename std::enable_if<std::is_arithmetic<number_type>::value>::type>
simdjson_inline void append(number_type v) noexcept;
/**
@@ -62,7 +95,10 @@ public:
* There is no UTF-8 validation.
*/
simdjson_inline void escape_and_append_with_quotes(std::string_view input) noexcept;
#if SIMDJSON_SUPPORTS_CONCEPTS
template<constevalutil::fixed_string key>
simdjson_inline void escape_and_append_with_quotes() noexcept;
#endif
/**
* Append the character surrounded by double quotes, after escaping it.
* There is no UTF-8 validation.
@@ -116,13 +152,21 @@ public:
* The key is escaped and surrounded by double quotes.
* The value is escaped if it is a string.
*/
template<typename key_type, typename value_type>
template<typename key_type, typename value_type>
simdjson_inline void append_key_value(key_type key, value_type value) noexcept;
#if SIMDJSON_SUPPORTS_CONCEPTS
template<constevalutil::fixed_string key, typename value_type>
simdjson_inline void append_key_value(value_type value) noexcept;
// Support for optional types (std::optional, etc.)
template <concepts::optional_type T>
requires(!require_custom_serialization<T>)
simdjson_inline void append(const T &opt);
template <typename T>
requires(require_custom_serialization<T>)
simdjson_inline void append(const T &val);
// Support for string-like types
template <typename T>
requires(std::is_convertible<T, std::string_view>::value ||
@@ -232,7 +276,7 @@ private:
#if !SIMDJSON_STATIC_REFLECTION
// fallback implementation until we have static reflection
template <class Z>
simdjson_result<std::string> to_json(const Z &z, size_t initial_capacity = 1024) {
simdjson_warn_unused simdjson_result<std::string> to_json(const Z &z, size_t initial_capacity = simdjson::SIMDJSON_IMPLEMENTATION::builder::string_builder::DEFAULT_INITIAL_CAPACITY) {
simdjson::SIMDJSON_IMPLEMENTATION::builder::string_builder b(initial_capacity);
b.append(z);
std::string_view s;
@@ -240,8 +284,20 @@ simdjson_result<std::string> to_json(const Z &z, size_t initial_capacity = 1024)
if(e) { return e; }
return std::string(s);
}
template <class Z>
simdjson_warn_unused simdjson_error to_json(const Z &z, std::string &s, size_t initial_capacity = simdjson::SIMDJSON_IMPLEMENTATION::builder::string_builder::DEFAULT_INITIAL_CAPACITY) {
simdjson::SIMDJSON_IMPLEMENTATION::builder::string_builder b(initial_capacity);
b.append(z);
std::string_view sv;
auto e = b.view().get(sv);
if(e) { return e; }
s.assign(sv.data(), sv.size());
return simdjson::SUCCESS;
}
#endif
#if SIMDJSON_SUPPORTS_CONCEPTS
#endif // SIMDJSON_SUPPORTS_CONCEPTS
} // namespace simdjson
+51 -1
View File
@@ -9,6 +9,10 @@
#include "simdjson/generic/ondemand/raw_json_string.h"
#include "simdjson/generic/ondemand/json_iterator.h"
#include "simdjson/generic/ondemand/value-inl.h"
#if SIMDJSON_STATIC_REFLECTION
#include "simdjson/generic/ondemand/json_string_builder.h" // for constevalutil::fixed_string
#include <meta>
#endif
#endif // SIMDJSON_CONDITIONAL_INCLUDE
namespace simdjson {
@@ -66,7 +70,7 @@ simdjson_inline simdjson_result<object> object::start_root(value_iterator &iter)
SIMDJSON_TRY( iter.start_root_object().error() );
return object(iter);
}
simdjson_inline error_code object::consume() noexcept {
simdjson_warn_unused simdjson_inline error_code object::consume() noexcept {
if(iter.is_at_key()) {
/**
* whenever you are pointing at a key, calling skip_child() is
@@ -195,6 +199,52 @@ simdjson_inline simdjson_result<bool> object::reset() & noexcept {
return iter.reset_object();
}
#if SIMDJSON_SUPPORTS_CONCEPTS && SIMDJSON_STATIC_REFLECTION
template<constevalutil::fixed_string... FieldNames, typename T>
requires(std::is_class_v<T> && (sizeof...(FieldNames) > 0))
simdjson_warn_unused simdjson_inline error_code object::extract_into(T& out) & noexcept {
// Helper to check if a field name matches any of the requested fields
auto should_extract = [](std::string_view field_name) constexpr -> bool {
return ((FieldNames.view() == field_name) || ...);
};
// Iterate through all members of T using reflection
template for (constexpr auto mem : std::define_static_array(
std::meta::nonstatic_data_members_of(^^T, std::meta::access_context::unchecked()))) {
if constexpr (!std::meta::is_const(mem) && std::meta::is_public(mem)) {
constexpr std::string_view key = std::define_static_string(std::meta::identifier_of(mem));
// Only extract this field if it's in our list of requested fields
if constexpr (should_extract(key)) {
// Try to find and extract the field
if constexpr (concepts::optional_type<decltype(out.[:mem:])>) {
// For optional fields, it's ok if they're missing
auto field_result = find_field_unordered(key);
if (!field_result.error()) {
auto error = field_result.get(out.[:mem:]);
if (error && error != NO_SUCH_FIELD) {
return error;
}
} else if (field_result.error() != NO_SUCH_FIELD) {
return field_result.error();
} else {
out.[:mem:].reset();
}
} else {
// For required fields (in the requested list), fail if missing
SIMDJSON_TRY((*this)[key].get(out.[:mem:]));
}
}
}
};
return SUCCESS;
}
#endif // SIMDJSON_SUPPORTS_CONCEPTS && SIMDJSON_STATIC_REFLECTION
} // namespace ondemand
} // namespace SIMDJSON_IMPLEMENTATION
} // namespace simdjson
+46 -3
View File
@@ -5,6 +5,9 @@
#include "simdjson/generic/ondemand/base.h"
#include "simdjson/generic/implementation_simdjson_result_base.h"
#include "simdjson/generic/ondemand/value_iterator.h"
#if SIMDJSON_STATIC_REFLECTION && SIMDJSON_SUPPORTS_CONCEPTS
#include "simdjson/generic/ondemand/json_string_builder.h" // for constevalutil::fixed_string
#endif
#endif // SIMDJSON_CONDITIONAL_INCLUDE
namespace simdjson {
@@ -211,7 +214,7 @@ public:
* @returns SUCCESS If the parse succeeded and the out parameter was set to the value.
*/
template <typename T>
simdjson_inline error_code get(T &out)
simdjson_warn_unused simdjson_inline error_code get(T &out)
noexcept(custom_deserializable<T, object> ? nothrow_custom_deserializable<T, object> : true) {
static_assert(custom_deserializable<T, object>);
return deserialize(*this, out);
@@ -231,12 +234,42 @@ public:
SIMDJSON_TRY(get<T>(out));
return out;
}
#if SIMDJSON_STATIC_REFLECTION
/**
* Extract only specific fields from the JSON object into a struct.
*
* This allows selective deserialization of only the fields you need,
* potentially improving performance by skipping unwanted fields.
*
* Example:
* ```c++
* struct Car {
* std::string make;
* std::string model;
* int year;
* double price;
* };
*
* Car car;
* object.extract_into<"make", "model">(car);
* // Only 'make' and 'model' fields are extracted from JSON
* ```
*
* @tparam FieldNames Compile-time string literals specifying which fields to extract
* @param out The output struct to populate with selected fields
* @returns SUCCESS on success, or an error code if a required field is missing or has wrong type
*/
template<constevalutil::fixed_string... FieldNames, typename T>
requires(std::is_class_v<T> && (sizeof...(FieldNames) > 0))
simdjson_warn_unused simdjson_inline error_code extract_into(T& out) & noexcept;
#endif // SIMDJSON_STATIC_REFLECTION
#endif // SIMDJSON_SUPPORTS_CONCEPTS
protected:
/**
* Go to the end of the object, no matter where you are right now.
*/
simdjson_inline error_code consume() noexcept;
simdjson_warn_unused simdjson_inline error_code consume() noexcept;
static simdjson_inline simdjson_result<object> start(value_iterator &iter) noexcept;
static simdjson_inline simdjson_result<object> start_root(value_iterator &iter) noexcept;
static simdjson_inline simdjson_result<object> started(value_iterator &iter) noexcept;
@@ -291,7 +324,7 @@ public:
return first.get<T>();
}
template<typename T>
simdjson_inline error_code get(T& out) noexcept {
simdjson_warn_unused simdjson_inline error_code get(T& out) noexcept {
if (error()) { return error(); }
if constexpr (std::is_same_v<T, SIMDJSON_IMPLEMENTATION::ondemand::object>) {
out = first;
@@ -300,6 +333,16 @@ public:
}
return SUCCESS;
}
#if SIMDJSON_STATIC_REFLECTION
// TODO: move this code into object-inl.h
template<constevalutil::fixed_string... FieldNames, typename T>
requires(std::is_class_v<T> && (sizeof...(FieldNames) > 0))
simdjson_warn_unused simdjson_inline error_code extract_into(T& out) noexcept {
if (error()) { return error(); }
return first.extract_into<FieldNames...>(out);
}
#endif // SIMDJSON_STATIC_REFLECTION
#endif // SIMDJSON_SUPPORTS_CONCEPTS
};
@@ -15,8 +15,13 @@ namespace ondemand {
simdjson_inline raw_json_string::raw_json_string(const uint8_t * _buf) noexcept : buf{_buf} {}
simdjson_inline const char * raw_json_string::raw() const noexcept { return reinterpret_cast<const char *>(buf); }
simdjson_inline const char * raw_json_string::raw() const noexcept {
return reinterpret_cast<const char *>(buf);
}
simdjson_inline char raw_json_string::operator[](size_t i) const noexcept {
return reinterpret_cast<const char *>(buf)[i];
}
simdjson_inline bool raw_json_string::is_free_from_unescaped_quote(std::string_view target) noexcept {
size_t pos{0};
@@ -193,6 +198,10 @@ simdjson_inline simdjson_result<const char *> simdjson_result<SIMDJSON_IMPLEMENT
if (error()) { return error(); }
return first.raw();
}
simdjson_inline char simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::raw_json_string>::operator[](size_t i) const noexcept {
if (error()) { return error(); }
return first[i];
}
simdjson_inline simdjson_warn_unused simdjson_result<std::string_view> simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::raw_json_string>::unescape(SIMDJSON_IMPLEMENTATION::ondemand::json_iterator &iter, bool allow_replacement) const noexcept {
if (error()) { return error(); }
return first.unescape(iter, allow_replacement);
@@ -58,6 +58,12 @@ public:
*/
simdjson_inline const char * raw() const noexcept;
/**
* Get the character at index i. This is unchecked.
* [0] when the string is of length 0 returns the final quote (").
*/
simdjson_inline char operator[](size_t i) const noexcept;
/**
* This compares the current instance to the std::string_view target: returns true if
* they are byte-by-byte equal (no escaping is done) on target.size() characters,
@@ -197,10 +203,10 @@ public:
simdjson_inline ~simdjson_result() noexcept = default; ///< @private
simdjson_inline simdjson_result<const char *> raw() const noexcept;
simdjson_inline char operator[](size_t) const noexcept;
simdjson_inline simdjson_warn_unused simdjson_result<std::string_view> unescape(SIMDJSON_IMPLEMENTATION::ondemand::json_iterator &iter, bool allow_replacement) const noexcept;
simdjson_inline simdjson_warn_unused simdjson_result<std::string_view> unescape_wobbly(SIMDJSON_IMPLEMENTATION::ondemand::json_iterator &iter) const noexcept;
};
} // namespace simdjson
#endif // SIMDJSON_GENERIC_ONDEMAND_RAW_JSON_STRING_H
@@ -16,15 +16,12 @@
#endif
namespace simdjson {
template <typename T>
constexpr bool require_custom_serialization = false;
//////////////////////////////
// Number deserialization
//////////////////////////////
template <std::unsigned_integral T>
requires(!require_custom_serialization<T>)
error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept {
using limits = std::numeric_limits<T>;
@@ -38,7 +35,6 @@ error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept {
}
template <std::floating_point T>
requires(!require_custom_serialization<T>)
error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept {
double x;
SIMDJSON_TRY(val.get_double().get(x));
@@ -47,7 +43,6 @@ error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept {
}
template <std::signed_integral T>
requires(!require_custom_serialization<T>)
error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept {
using limits = std::numeric_limits<T>;
@@ -77,7 +72,6 @@ error_code tag_invoke(deserialize_tag, auto &val, char &out) noexcept {
// any string-like type (can be constructed from std::string_view)
template <concepts::constructible_from_string_view T, typename ValT>
requires(!require_custom_serialization<T>)
error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(std::is_nothrow_constructible_v<T, std::string_view>) {
std::string_view str;
SIMDJSON_TRY(val.get_string().get(str));
@@ -94,7 +88,6 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(std::is_nothr
* doc.get<std::vector<int>>().
*/
template <concepts::appendable_containers T, typename ValT>
requires(!require_custom_serialization<T>)
error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) {
using value_type = typename std::remove_cvref_t<T>::value_type;
static_assert(
@@ -140,7 +133,6 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) {
* string-keyed types.
*/
template <concepts::string_view_keyed_map T, typename ValT>
requires(!require_custom_serialization<T>)
error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) {
using value_type = typename std::remove_cvref_t<T>::mapped_type;
static_assert(
@@ -222,7 +214,6 @@ error_code tag_invoke(deserialize_tag, SIMDJSON_IMPLEMENTATION::ondemand::docume
* @return status of the conversion
*/
template <concepts::smart_pointer T, typename ValT>
requires(!require_custom_serialization<T>)
error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(nothrow_deserializable<typename std::remove_cvref_t<T>::element_type, ValT>) {
using element_type = typename std::remove_cvref_t<T>::element_type;
@@ -248,12 +239,13 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(nothrow_deser
* This CPO (Customization Point Object) will help deserialize into optional types.
*/
template <concepts::optional_type T>
requires(!require_custom_serialization<T>)
error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deserializable<typename std::remove_cvref_t<T>::value_type, decltype(val)>) {
using value_type = typename std::remove_cvref_t<T>::value_type;
// Check if the value is null
if (val.is_null()) {
bool is_null_value;
SIMDJSON_TRY( val.is_null().get(is_null_value) );
if (is_null_value) {
out.reset(); // Set to nullopt
return SUCCESS;
}
@@ -272,35 +264,9 @@ error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deser
template <typename T>
constexpr bool user_defined_type = (std::is_class_v<T>
&& !std::is_same_v<T, std::string> && !std::is_same_v<T, std::string_view> && !concepts::optional_type<T> &&
!concepts::appendable_containers<T> && !require_custom_serialization<T>);
!concepts::appendable_containers<T>);
// workaround from
// https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/p2996r10.html#back-and-forth
// for missing expansion statements
namespace __impl {
template<auto... vals>
struct replicator_type {
template<typename F>
constexpr void operator>>(F body) const {
(body.template operator()<vals>(), ...);
}
};
template<auto... vals>
replicator_type<vals...> replicator = {};
}
template<typename R>
consteval auto expand(R range) {
std::vector<std::meta::info> args;
for (auto r : range) {
args.push_back(reflect_constant(r));
}
return substitute(^^__impl::replicator, args);
}
// end of workaround
template <typename T, typename ValT>
requires(user_defined_type<T> && std::is_class_v<T>)
error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept {
@@ -310,19 +276,26 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept {
} else {
SIMDJSON_TRY(val.get_object().get(obj));
}
error_code e = simdjson::SUCCESS;
[:expand(std::meta::nonstatic_data_members_of(^^T, std::meta::access_context::unchecked())):] >> [&]<auto mem>() {
template for (constexpr auto mem : std::define_static_array(std::meta::nonstatic_data_members_of(^^T, std::meta::access_context::unchecked()))) {
if constexpr (!std::meta::is_const(mem) && std::meta::is_public(mem)) {
constexpr std::string_view key = std::meta::identifier_of(mem);
// Note: removed static assert as optional types are now handled generically
// as long we are succesful or the field is not found, we continue
if(e == simdjson::SUCCESS || e == simdjson::NO_SUCH_FIELD) {
e = obj[key].get(out.[:mem:]);
constexpr std::string_view key = std::define_static_string(std::meta::identifier_of(mem));
if constexpr (concepts::optional_type<decltype(out.[:mem:])>) {
// for optional members, it's ok if the key is missing
auto error = obj[key].get(out.[:mem:]);
if (error && error != NO_SUCH_FIELD) {
if(error == NO_SUCH_FIELD) {
out.[:mem:].reset();
continue;
}
return error;
}
} else {
// for non-optional members, the key must be present
SIMDJSON_TRY(obj[key].get(out.[:mem:]));
}
}
};
return e;
return simdjson::SUCCESS;
}
// Support for enum deserialization - deserialize from string representation using expand approach from P2996R12
@@ -332,16 +305,15 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept {
#if SIMDJSON_STATIC_REFLECTION
std::string_view str;
SIMDJSON_TRY(val.get_string().get(str));
bool found = false;
[:expand(std::meta::enumerators_of(^^T)):] >> [&]<auto enum_val>{
if (!found && str == std::meta::identifier_of(enum_val)) {
constexpr auto enumerators = std::define_static_array(std::meta::enumerators_of(^^T));
template for (constexpr auto enum_val : enumerators) {
if (str == std::meta::identifier_of(enum_val)) {
out = [:enum_val:];
found = true;
return SUCCESS;
}
};
return found ? SUCCESS : INCORRECT_TYPE;
return INCORRECT_TYPE;
#else
// Fallback: deserialize as integer if reflection not available
std::underlying_type_t<T> int_val;
@@ -389,7 +361,9 @@ error_code tag_invoke(deserialize_tag, simdjson_value &val, std::shared_ptr<T> &
// Unique pointers
////////////////////////////////////////
error_code tag_invoke(deserialize_tag, auto &val, std::unique_ptr<bool> &out) noexcept {
if (val.is_null()) {
bool is_null_value;
SIMDJSON_TRY( val.is_null().get(is_null_value) );
if (is_null_value) {
out.reset();
return SUCCESS;
}
@@ -402,7 +376,9 @@ error_code tag_invoke(deserialize_tag, auto &val, std::unique_ptr<bool> &out) no
}
error_code tag_invoke(deserialize_tag, auto &val, std::unique_ptr<int64_t> &out) noexcept {
if (val.is_null()) {
bool is_null_value;
SIMDJSON_TRY( val.is_null().get(is_null_value) );
if (is_null_value) {
out.reset();
return SUCCESS;
}
@@ -415,7 +391,9 @@ error_code tag_invoke(deserialize_tag, auto &val, std::unique_ptr<int64_t> &out)
}
error_code tag_invoke(deserialize_tag, auto &val, std::unique_ptr<uint64_t> &out) noexcept {
if (val.is_null()) {
bool is_null_value;
SIMDJSON_TRY( val.is_null().get(is_null_value) );
if (is_null_value) {
out.reset();
return SUCCESS;
}
@@ -428,7 +406,9 @@ error_code tag_invoke(deserialize_tag, auto &val, std::unique_ptr<uint64_t> &out
}
error_code tag_invoke(deserialize_tag, auto &val, std::unique_ptr<double> &out) noexcept {
if (val.is_null()) {
bool is_null_value;
SIMDJSON_TRY( val.is_null().get(is_null_value) );
if (is_null_value) {
out.reset();
return SUCCESS;
}
@@ -441,7 +421,9 @@ error_code tag_invoke(deserialize_tag, auto &val, std::unique_ptr<double> &out)
}
error_code tag_invoke(deserialize_tag, auto &val, std::unique_ptr<std::string_view> &out) noexcept {
if (val.is_null()) {
bool is_null_value;
SIMDJSON_TRY( val.is_null().get(is_null_value) );
if (is_null_value) {
out.reset();
return SUCCESS;
}
@@ -458,7 +440,9 @@ error_code tag_invoke(deserialize_tag, auto &val, std::unique_ptr<std::string_vi
// Shared pointers
////////////////////////////////////////
error_code tag_invoke(deserialize_tag, auto &val, std::shared_ptr<bool> &out) noexcept {
if (val.is_null()) {
bool is_null_value;
SIMDJSON_TRY( val.is_null().get(is_null_value) );
if (is_null_value) {
out.reset();
return SUCCESS;
}
@@ -471,7 +455,9 @@ error_code tag_invoke(deserialize_tag, auto &val, std::shared_ptr<bool> &out) no
}
error_code tag_invoke(deserialize_tag, auto &val, std::shared_ptr<int64_t> &out) noexcept {
if (val.is_null()) {
bool is_null_value;
SIMDJSON_TRY( val.is_null().get(is_null_value) );
if (is_null_value) {
out.reset();
return SUCCESS;
}
@@ -484,7 +470,9 @@ error_code tag_invoke(deserialize_tag, auto &val, std::shared_ptr<int64_t> &out)
}
error_code tag_invoke(deserialize_tag, auto &val, std::shared_ptr<uint64_t> &out) noexcept {
if (val.is_null()) {
bool is_null_value;
SIMDJSON_TRY( val.is_null().get(is_null_value) );
if (is_null_value) {
out.reset();
return SUCCESS;
}
@@ -497,7 +485,9 @@ error_code tag_invoke(deserialize_tag, auto &val, std::shared_ptr<uint64_t> &out
}
error_code tag_invoke(deserialize_tag, auto &val, std::shared_ptr<double> &out) noexcept {
if (val.is_null()) {
bool is_null_value;
SIMDJSON_TRY( val.is_null().get(is_null_value) );
if (is_null_value) {
out.reset();
return SUCCESS;
}
@@ -510,7 +500,9 @@ error_code tag_invoke(deserialize_tag, auto &val, std::shared_ptr<double> &out)
}
error_code tag_invoke(deserialize_tag, auto &val, std::shared_ptr<std::string_view> &out) noexcept {
if (val.is_null()) {
bool is_null_value;
SIMDJSON_TRY( val.is_null().get(is_null_value) );
if (is_null_value) {
out.reset();
return SUCCESS;
}
@@ -532,7 +524,9 @@ error_code tag_invoke(deserialize_tag, auto &val, std::shared_ptr<std::string_vi
////////////////////////////////////////
error_code tag_invoke(deserialize_tag, auto &val, std::unique_ptr<std::string> &out) noexcept {
// Check if the value is null
if (val.is_null()) {
bool is_null_value;
SIMDJSON_TRY( val.is_null().get(is_null_value) );
if (is_null_value) {
out.reset(); // Set to nullptr
return SUCCESS;
}
@@ -548,7 +542,9 @@ error_code tag_invoke(deserialize_tag, auto &val, std::unique_ptr<std::string> &
error_code tag_invoke(deserialize_tag, auto &val, std::shared_ptr<std::string> &out) noexcept {
// Check if the value is null
if (val.is_null()) {
bool is_null_value;
SIMDJSON_TRY( val.is_null().get(is_null_value) );
if (is_null_value) {
out.reset(); // Set to nullptr
return SUCCESS;
}
@@ -564,7 +560,9 @@ error_code tag_invoke(deserialize_tag, auto &val, std::shared_ptr<std::string> &
error_code tag_invoke(deserialize_tag, auto &val, std::unique_ptr<int> &out) noexcept {
// Check if the value is null
if (val.is_null()) {
bool is_null_value;
SIMDJSON_TRY( val.is_null().get(is_null_value) );
if (is_null_value) {
out.reset(); // Set to nullptr
return SUCCESS;
}
+10 -10
View File
@@ -48,7 +48,7 @@ simdjson_inline simdjson_result<std::string_view> value::get_string(bool allow_r
return iter.get_string(allow_replacement);
}
template <typename string_type>
simdjson_inline error_code value::get_string(string_type& receiver, bool allow_replacement) noexcept {
simdjson_warn_unused simdjson_inline error_code value::get_string(string_type& receiver, bool allow_replacement) noexcept {
return iter.get_string(receiver, allow_replacement);
}
simdjson_inline simdjson_result<std::string_view> value::get_wobbly_string() noexcept {
@@ -90,15 +90,15 @@ template<> simdjson_inline simdjson_result<int64_t> value::get() noexcept { retu
template<> simdjson_inline simdjson_result<bool> value::get() noexcept { return get_bool(); }
template<> simdjson_inline error_code value::get(array& out) noexcept { return get_array().get(out); }
template<> simdjson_inline error_code value::get(object& out) noexcept { return get_object().get(out); }
template<> simdjson_inline error_code value::get(raw_json_string& out) noexcept { return get_raw_json_string().get(out); }
template<> simdjson_inline error_code value::get(std::string_view& out) noexcept { return get_string(false).get(out); }
template<> simdjson_inline error_code value::get(number& out) noexcept { return get_number().get(out); }
template<> simdjson_inline error_code value::get(double& out) noexcept { return get_double().get(out); }
template<> simdjson_inline error_code value::get(uint64_t& out) noexcept { return get_uint64().get(out); }
template<> simdjson_inline error_code value::get(int64_t& out) noexcept { return get_int64().get(out); }
template<> simdjson_inline error_code value::get(bool& out) noexcept { return get_bool().get(out); }
template<> simdjson_warn_unused simdjson_inline error_code value::get(array& out) noexcept { return get_array().get(out); }
template<> simdjson_warn_unused simdjson_inline error_code value::get(object& out) noexcept { return get_object().get(out); }
template<> simdjson_warn_unused simdjson_inline error_code value::get(raw_json_string& out) noexcept { return get_raw_json_string().get(out); }
template<> simdjson_warn_unused simdjson_inline error_code value::get(std::string_view& out) noexcept { return get_string(false).get(out); }
template<> simdjson_warn_unused simdjson_inline error_code value::get(number& out) noexcept { return get_number().get(out); }
template<> simdjson_warn_unused simdjson_inline error_code value::get(double& out) noexcept { return get_double().get(out); }
template<> simdjson_warn_unused simdjson_inline error_code value::get(uint64_t& out) noexcept { return get_uint64().get(out); }
template<> simdjson_warn_unused simdjson_inline error_code value::get(int64_t& out) noexcept { return get_int64().get(out); }
template<> simdjson_warn_unused simdjson_inline error_code value::get(bool& out) noexcept { return get_bool().get(out); }
#if SIMDJSON_EXCEPTIONS
template <class T>
+6 -4
View File
@@ -65,7 +65,7 @@ public:
* @returns SUCCESS If the parse succeeded and the out parameter was set to the value.
*/
template <typename T>
simdjson_inline error_code get(T &out)
simdjson_warn_unused simdjson_inline error_code get(T &out)
#if SIMDJSON_SUPPORTS_CONCEPTS
noexcept(custom_deserializable<T, value> ? nothrow_custom_deserializable<T, value> : true)
#else
@@ -79,7 +79,9 @@ public:
using value_type = typename std::remove_cvref_t<T>::value_type;
// Check if the value is null
if (is_null()) {
bool is_null_value;
SIMDJSON_TRY( is_null().get(is_null_value) );
if (is_null_value) {
out.reset(); // Set to nullopt
return SUCCESS;
}
@@ -215,7 +217,7 @@ public:
* @returns INCORRECT_TYPE if the JSON value is not a string. Otherwise, we return SUCCESS.
*/
template <typename string_type>
simdjson_inline error_code get_string(string_type& receiver, bool allow_replacement = false) noexcept;
simdjson_warn_unused simdjson_inline error_code get_string(string_type& receiver, bool allow_replacement = false) noexcept;
/**
* Cast this JSON value to a "wobbly" string.
@@ -736,7 +738,7 @@ public:
simdjson_inline simdjson_result<double> get_double_in_string() noexcept;
simdjson_inline simdjson_result<std::string_view> get_string(bool allow_replacement = false) noexcept;
template <typename string_type>
simdjson_inline error_code get_string(string_type& receiver, bool allow_replacement = false) noexcept;
simdjson_warn_unused simdjson_inline error_code get_string(string_type& receiver, bool allow_replacement = false) noexcept;
simdjson_inline simdjson_result<std::string_view> get_wobbly_string() noexcept;
simdjson_inline simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::raw_json_string> get_raw_json_string() noexcept;
simdjson_inline simdjson_result<bool> get_bool() noexcept;
@@ -41,7 +41,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::start
if (*_json_iter->peek() == '}') {
logger::log_value(*_json_iter, "empty object");
_json_iter->return_current_and_advance();
end_container();
SIMDJSON_TRY(end_container());
return false;
}
return true;
@@ -895,7 +895,7 @@ simdjson_inline void value_iterator::advance_scalar(const char *type) noexcept {
_json_iter->ascend_to(depth()-1);
}
simdjson_inline error_code value_iterator::start_container(uint8_t start_char, const char *incorrect_type_message, const char *type) noexcept {
simdjson_warn_unused simdjson_inline error_code value_iterator::start_container(uint8_t start_char, const char *incorrect_type_message, const char *type) noexcept {
logger::log_start_value(*_json_iter, start_position(), depth(), type);
// If we're not at the position anymore, we don't want to advance the cursor.
const uint8_t *json;
@@ -335,7 +335,7 @@ public:
simdjson_warn_unused simdjson_inline simdjson_result<number> get_root_number(bool check_trailing) noexcept;
simdjson_warn_unused simdjson_inline simdjson_result<bool> is_root_null(bool check_trailing) noexcept;
simdjson_inline error_code error() const noexcept;
simdjson_warn_unused simdjson_inline error_code error() const noexcept;
simdjson_inline uint8_t *&string_buf_loc() noexcept;
simdjson_inline const json_iterator &json_iter() const noexcept;
simdjson_inline json_iterator &json_iter() noexcept;
@@ -419,8 +419,8 @@ protected:
simdjson_inline const uint8_t *peek_non_root_scalar(const char *type) noexcept;
simdjson_inline error_code start_container(uint8_t start_char, const char *incorrect_type_message, const char *type) noexcept;
simdjson_inline error_code end_container() noexcept;
simdjson_warn_unused simdjson_inline error_code start_container(uint8_t start_char, const char *incorrect_type_message, const char *type) noexcept;
simdjson_warn_unused simdjson_inline error_code end_container() noexcept;
/**
* Advance to a place expecting a value (increasing depth).
@@ -430,8 +430,8 @@ protected:
*/
simdjson_inline simdjson_result<const uint8_t *> advance_to_value() noexcept;
simdjson_inline error_code incorrect_type_error(const char *message) const noexcept;
simdjson_inline error_code error_unless_more_tokens(uint32_t tokens=1) const noexcept;
simdjson_warn_unused simdjson_inline error_code incorrect_type_error(const char *message) const noexcept;
simdjson_warn_unused simdjson_inline error_code error_unless_more_tokens(uint32_t tokens=1) const noexcept;
simdjson_inline bool is_at_start() const noexcept;
/**
@@ -468,7 +468,7 @@ protected:
/** @copydoc error_code json_iterator::end_position() const noexcept; */
simdjson_inline token_position end_position() const noexcept;
/** @copydoc error_code json_iterator::report_error(error_code error, const char *message) noexcept; */
simdjson_inline error_code report_error(error_code error, const char *message) noexcept;
simdjson_warn_unused simdjson_inline error_code report_error(error_code error, const char *message) noexcept;
friend class document;
friend class object;
@@ -17,7 +17,7 @@ using namespace simd;
struct backslash_and_quote {
public:
static constexpr uint32_t BYTES_PROCESSED = 32;
simdjson_inline static backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
simdjson_inline backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
simdjson_inline bool has_quote_first() { return ((bs_bits - 1) & quote_bits) != 0; }
simdjson_inline bool has_backslash() { return ((quote_bits - 1) & bs_bits) != 0; }
@@ -17,7 +17,7 @@ using namespace simd;
struct backslash_and_quote {
public:
static constexpr uint32_t BYTES_PROCESSED = 64;
simdjson_inline static backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
simdjson_inline backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
simdjson_inline bool has_quote_first() { return ((bs_bits - 1) & quote_bits) != 0; }
simdjson_inline bool has_backslash() { return ((quote_bits - 1) & bs_bits) != 0; }
+1 -1
View File
@@ -17,7 +17,7 @@ using namespace simd;
struct backslash_and_quote {
public:
static constexpr uint32_t BYTES_PROCESSED = 32;
simdjson_inline static backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
simdjson_inline backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
simdjson_inline bool has_quote_first() { return ((bs_bits - 1) & quote_bits) != 0; }
simdjson_inline bool has_backslash() { return bs_bits != 0; }
+2 -2
View File
@@ -17,7 +17,7 @@ using namespace simd;
struct backslash_and_quote {
public:
static constexpr uint32_t BYTES_PROCESSED = 32;
simdjson_inline static backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
simdjson_inline backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
simdjson_inline bool has_quote_first() { return ((bs_bits - 1) & quote_bits) != 0; }
simdjson_inline bool has_backslash() { return bs_bits != 0; }
@@ -67,7 +67,7 @@ simdjson_inline escaping escaping::copy_and_find(const uint8_t *src, uint8_t *ds
simd8<bool> is_backslash = (v == '\\');
simd8<bool> is_control = (v < 32);
return {
(is_backslash | is_quote | is_control).to_bitmask()
static_cast<uint64_t>((is_backslash | is_quote | is_control).to_bitmask())
};
}
+16
View File
@@ -45,6 +45,22 @@ using std::size_t;
#define SIMDJSON_IS_ARM64 1
#elif defined(__riscv) && __riscv_xlen == 64
#define SIMDJSON_IS_RISCV64 1
#if __riscv_v_intrinsic >= 11000
#define SIMDJSON_HAS_RVV_INTRINSICS 1
#endif
#define SIMDJSON_HAS_ZVBB_INTRINSICS \
0 // there is currently no way to detect this
#if SIMDJSON_HAS_RVV_INTRINSICS && __riscv_vector && \
__riscv_v_min_vlen >= 128 && __riscv_v_elen >= 64
// RISC-V V extension
#define SIMDJSON_IS_RVV 1
#if SIMDJSON_HAS_ZVBB_INTRINSICS && __riscv_zvbb >= 1000000
// RISC-V Vector Basic Bit-manipulation
#define SIMDJSON_IS_ZVBB 1
#endif
#endif
#elif defined(__loongarch_lp64)
#define SIMDJSON_IS_LOONGARCH64 1
#elif defined(__PPC64__) || defined(_M_PPC64)
+1 -1
View File
@@ -17,7 +17,7 @@ using namespace simd;
struct backslash_and_quote {
public:
static constexpr uint32_t BYTES_PROCESSED = 32;
simdjson_inline static backslash_and_quote
simdjson_inline backslash_and_quote
copy_and_find(const uint8_t *src, uint8_t *dst);
simdjson_inline bool has_quote_first() {
+2 -2
View File
@@ -4,7 +4,7 @@
#define SIMDJSON_SIMDJSON_VERSION_H
/** The version of simdjson being used (major.minor.revision) */
#define SIMDJSON_VERSION "4.0.0"
#define SIMDJSON_VERSION "4.0.7"
namespace simdjson {
enum {
@@ -19,7 +19,7 @@ enum {
/**
* The revision (major.minor.REVISION) of simdjson being used.
*/
SIMDJSON_VERSION_REVISION = 0
SIMDJSON_VERSION_REVISION = 7
};
} // namespace simdjson
@@ -14,7 +14,7 @@ using namespace simd;
struct backslash_and_quote {
public:
static constexpr uint32_t BYTES_PROCESSED = 32;
simdjson_inline static backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
simdjson_inline backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
simdjson_inline bool has_quote_first() { return ((bs_bits - 1) & quote_bits) != 0; }
simdjson_inline bool has_backslash() { return bs_bits != 0; }
+33
View File
@@ -78,3 +78,36 @@ You can modify the source code with your favorite editor and run again steps 5 (
You can create a new docker shell at any time by running step 3 (bash script).
## Using static reflection in your own projects
You can import simdjson in your own CMake project. You can configure your project like so:
```
# Fetch simdjson from GitHub
# Replace GIT_TAG by the commit you require.
include(FetchContent)
FetchContent_Declare(
simdjson
GIT_REPOSITORY https://github.com/simdjson/simdjson.git
GIT_TAG 015daad6a95a4f67c08ed5980d24b57be221c38f
CMAKE_ARGS -DSIMDJSON_STATIC_REFLECTION=ON
)
FetchContent_MakeAvailable(simdjson)
##########
# You may also use CPM.
# https://github.com/cpm-cmake/CPM.cmake
# CPMAddPackage(
# NAME simdjson
# GITHUB_REPOSITORY simdjson/simdjson
# GIT_TAG 015daad6a95a4f67c08ed5980d24b57be221c38f
# OPTIONS "SIMDJSON_STATIC_REFLECTION ON"
# )
target_link_libraries(webservice PRIVATE simdjson::simdjson)
```
Replace the `GIT_TAG` by the appropriate value.
Once C++26 support will be officially available in mainstream compilers,
we will simplify these instructions and it will no longer be needed
to specify `SIMDJSON_STATIC_REFLECTION`.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-120
View File
@@ -1,120 +0,0 @@
#!/bin/bash
#
# Top-level script to run all JSON PARSING benchmarks
# Tests: JSON → C++ structs performance
#
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUILD_DIR="$SCRIPT_DIR/build"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
echo -e "${BLUE}======================================${NC}"
echo -e "${BLUE} JSON PARSING Benchmarks${NC}"
echo -e "${BLUE} (JSON → C++ structs)${NC}"
echo -e "${BLUE}======================================${NC}"
echo ""
# Always rebuild unified benchmark to ensure it's up to date
echo -e "${YELLOW}Building unified benchmark with all available libraries...${NC}"
# First check and build Serde if needed
if [ ! -f "benchmark/static_reflect/serde-benchmark/target/release/libserde_benchmark.so" ] && \
[ ! -f "benchmark/static_reflect/serde-benchmark/target/release/libserde_benchmark.a" ]; then
echo -e "${YELLOW}Building Serde benchmark library...${NC}"
if [ -d "benchmark/static_reflect/serde-benchmark" ]; then
cd benchmark/static_reflect/serde-benchmark
cargo build --release
if [ $? -eq 0 ]; then
echo -e "${GREEN}✓ Serde benchmark built successfully${NC}"
else
echo -e "${YELLOW}⚠ Warning: Serde benchmark build failed - will skip Serde tests${NC}"
fi
cd ../../..
else
echo -e "${YELLOW}⚠ Serde benchmark directory not found - will skip Serde tests${NC}"
fi
fi
# Build unified benchmark
./build_unified_benchmark.sh
if [ $? -ne 0 ]; then
echo -e "${RED}Failed to build unified benchmark${NC}"
exit 1
fi
echo -e "${GREEN}✓ Unified benchmark built successfully${NC}"
# Parse command line arguments
FILTER=""
DATASET="all"
MIN_TIME=""
while [[ $# -gt 0 ]]; do
case $1 in
-f|--filter)
FILTER="$2"
shift 2
;;
-d|--dataset)
DATASET="$2"
shift 2
;;
-t|--min-time)
MIN_TIME="$2"
shift 2
;;
-h|--help)
echo "Usage: $0 [OPTIONS]"
echo ""
echo "Options:"
echo " -f, --filter LIBS Run only specified libraries (comma-separated)"
echo " Options: simdjson_manual,simdjson_reflection,simdjson_from,nlohmann,rapidjson,serde"
echo " -d, --dataset NAME Run only specified dataset (twitter, citm, or all)"
echo " -t, --min-time SECS Minimum benchmark time per test (default: auto)"
echo " -h, --help Show this help message"
echo ""
echo "Examples:"
echo " $0 # Run all benchmarks"
echo " $0 -f simdjson_reflection,serde # Compare simdjson reflection with Serde"
echo " $0 -d twitter # Run only Twitter dataset"
echo " $0 -f serde -d citm # Run only Serde on CITM"
exit 0
;;
*)
echo "Unknown option: $1"
exit 1
;;
esac
done
# Run the unified benchmark
echo -e "${GREEN}Running Unified Parsing Benchmark${NC}"
echo ""
# Set library path for Serde if it exists
if [ -f "benchmark/static_reflect/serde-benchmark/target/release/libserde_benchmark.so" ]; then
export LD_LIBRARY_PATH="$SCRIPT_DIR/benchmark/static_reflect/serde-benchmark/target/release:$LD_LIBRARY_PATH"
fi
# The unified benchmark handles both datasets internally
# Pass --parsing flag to run parsing benchmarks (this is the default)
./benchmark/unified_benchmark --parsing
echo ""
echo -e "${BLUE}======================================${NC}"
echo -e "${BLUE} Parsing Benchmarks Complete${NC}"
echo -e "${BLUE}======================================${NC}"
echo ""
echo "Key metrics to compare:"
echo " - Throughput (MB/s) - Higher is better"
echo " - simdjson (manual) uses hand-written parsing code"
echo " - simdjson (reflection) uses C++26 static reflection"
echo " - simdjson::from() uses high-level convenient API"
echo " - Serde (Rust) uses serde_json::from_str()"
-120
View File
@@ -1,120 +0,0 @@
#!/bin/bash
#
# Top-level script to run all JSON SERIALIZATION benchmarks
# Tests: C++ structs → JSON performance
#
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUILD_DIR="$SCRIPT_DIR/build"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
echo -e "${BLUE}======================================${NC}"
echo -e "${BLUE} JSON SERIALIZATION Benchmarks${NC}"
echo -e "${BLUE} (C++ structs → JSON)${NC}"
echo -e "${BLUE}======================================${NC}"
echo ""
# Always rebuild unified benchmark to ensure it's up to date
echo -e "${YELLOW}Building unified benchmark with all available libraries...${NC}"
# First check and build Serde if needed
if [ ! -f "benchmark/static_reflect/serde-benchmark/target/release/libserde_benchmark.so" ] && \
[ ! -f "benchmark/static_reflect/serde-benchmark/target/release/libserde_benchmark.a" ]; then
echo -e "${YELLOW}Building Serde benchmark library...${NC}"
if [ -d "benchmark/static_reflect/serde-benchmark" ]; then
cd benchmark/static_reflect/serde-benchmark
cargo build --release
if [ $? -eq 0 ]; then
echo -e "${GREEN}✓ Serde benchmark built successfully${NC}"
else
echo -e "${YELLOW}⚠ Warning: Serde benchmark build failed - will skip Serde tests${NC}"
fi
cd ../../..
else
echo -e "${YELLOW}⚠ Serde benchmark directory not found - will skip Serde tests${NC}"
fi
fi
# Build unified benchmark
./build_unified_benchmark.sh
if [ $? -ne 0 ]; then
echo -e "${RED}Failed to build unified benchmark${NC}"
exit 1
fi
echo -e "${GREEN}✓ Unified benchmark built successfully${NC}"
# Parse command line arguments
FILTER=""
DATASET="all"
MIN_TIME=""
while [[ $# -gt 0 ]]; do
case $1 in
-f|--filter)
FILTER="$2"
shift 2
;;
-d|--dataset)
DATASET="$2"
shift 2
;;
-t|--min-time)
MIN_TIME="$2"
shift 2
;;
-h|--help)
echo "Usage: $0 [OPTIONS]"
echo ""
echo "Options:"
echo " -f, --filter LIBS Run only specified libraries (comma-separated)"
echo " Options: simdjson,simdjson_reflection,nlohmann,rapidjson,yyjson,serde"
echo " -d, --dataset NAME Run only specified dataset (twitter, citm, or all)"
echo " -t, --min-time SECS Minimum benchmark time per test (default: auto)"
echo " -h, --help Show this help message"
echo ""
echo "Examples:"
echo " $0 # Run all benchmarks"
echo " $0 -f simdjson_reflection,yyjson # Compare simdjson reflection with yyjson"
echo " $0 -d twitter # Run only Twitter dataset"
echo " $0 -f serde -d citm # Run only Serde on CITM"
exit 0
;;
*)
echo "Unknown option: $1"
exit 1
;;
esac
done
# Run the unified benchmark with serialization flag
echo -e "${GREEN}Running Unified Serialization Benchmark${NC}"
echo ""
# Set library path for Serde if it exists
if [ -f "benchmark/static_reflect/serde-benchmark/target/release/libserde_benchmark.so" ]; then
export LD_LIBRARY_PATH="$SCRIPT_DIR/benchmark/static_reflect/serde-benchmark/target/release:$LD_LIBRARY_PATH"
fi
# The unified benchmark handles both datasets internally
# Pass --serialization flag to run serialization benchmarks
./benchmark/unified_benchmark --serialization
echo ""
echo -e "${BLUE}======================================${NC}"
echo -e "${BLUE} Serialization Benchmarks Complete${NC}"
echo -e "${BLUE}======================================${NC}"
echo ""
echo "Key metrics to compare:"
echo " - Throughput (MB/s) - Higher is better"
echo " - simdjson uses DOM-based serialization"
echo " - simdjson (reflection) uses C++26 static reflection"
echo " - yyjson uses optimized C serialization"
echo " - Serde (Rust) uses serde_json::to_string()"
-34
View File
@@ -1,34 +0,0 @@
#!/bin/bash
# Simple test runner for measuring optimization impact
# Usage: ./run_single_test.sh "Test Name" "CMAKE_FLAGS"
set -e
TEST_NAME="$1"
CMAKE_FLAGS="$2"
echo "=== Testing: $TEST_NAME ==="
echo "CMake flags: $CMAKE_FLAGS"
# Clean and build
rm -rf build
mkdir build
cd build
# Configure
cmake -DCMAKE_CXX_COMPILER=clang++ \
-DSIMDJSON_DEVELOPER_MODE=ON \
-DSIMDJSON_STATIC_REFLECTION=ON \
-DBUILD_SHARED_LIBS=OFF \
$CMAKE_FLAGS \
..
# Build
cmake --build . --target benchmark_serialization_twitter
# Run benchmark (single run for now)
echo "Running benchmark..."
./benchmark/static_reflect/twitter_benchmark/benchmark_serialization_twitter -f simdjson_static_reflection
cd ..
+1 -1
View File
@@ -1,5 +1,5 @@
var fs = require('fs');
var fs = require('node:fs');
var faker = require('faker');
+34
View File
@@ -22,6 +22,9 @@ rules = """
We refer your to the HACKING.md file for more information on how the project is organized.
If you are trying to add a new implementation, you need to edit the amalgamate.py script
to add your implementation to the IMPLEMENTATIONS list.
To help understand the error, here are the rules for including files in simdjson:
All implementation-specific files, including arm64.h, arm64/implementation.h and
@@ -480,11 +483,42 @@ AMAL_C = os.path.join(AMALGAMATE_OUTPUT_PATH, "simdjson.cpp")
DEMOCPP = os.path.join(AMALGAMATE_OUTPUT_PATH, "amalgamate_demo.cpp")
README = os.path.join(AMALGAMATE_OUTPUT_PATH, "README.md")
def validate_implementations():
"""Scan include/simdjson/*/implementation.h and compare with IMPLEMENTATIONS list."""
include_simdjson_path = os.path.join(PROJECTPATH, 'include', 'simdjson')
found_implementations = set()
if os.path.exists(include_simdjson_path):
for item in os.listdir(include_simdjson_path):
item_path = os.path.join(include_simdjson_path, item)
if os.path.isdir(item_path):
impl_h_path = os.path.join(item_path, 'implementation.h')
if os.path.exists(impl_h_path) and item != 'builtin': # Ignore builtin
found_implementations.add(item)
expected_implementations = set(IMPLEMENTATIONS)
if found_implementations != expected_implementations:
missing = expected_implementations - found_implementations
extra = found_implementations - expected_implementations
warning = "Warning: IMPLEMENTATIONS list does not match found implementations.\n"
if missing:
warning += f"Missing in filesystem: {sorted(missing)}\n"
if extra:
warning += f"Extra in filesystem: {sorted(extra)}\n"
print(warning)
return False
return True
def read_version():
with open(os.path.join(PROJECTPATH, 'include/simdjson/simdjson_version.h')) as f:
return re.search(r'\d+\.\d+\.\d+', f.read()).group(0)
version = read_version()
if not validate_implementations():
print("Validation failed. Please update IMPLEMENTATIONS list in amalgamate.py.")
sys.exit(1)
else:
print("implementation validated")
Amalgamator.amalgamate(AMAL_H, "simdjson.h", ['include'], timestamp, version).validate_all_files_used('include')
Amalgamator.amalgamate(AMAL_C, "simdjson.cpp", ['src', 'include'], timestamp, version).validate_all_files_used('src')
+706 -151
View File
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More