Compare commits

...

41 Commits

Author SHA1 Message Date
Daniel Lemire bfd8856913 less terrible maybe 2026-02-05 20:06:38 -05:00
Daniel Lemire 39bee282da implementing the backslash-free string optimization 2026-01-22 16:30:05 -05:00
Daniel Lemire d9956d7b3b Merge branch 'master' into optimization-get_string 2026-01-22 10:44:04 -05:00
Daniel Lemire 8e7ddb3155 Merge branch 'master' into optimization-get_string 2026-01-22 10:43:29 -05:00
Daniel Lemire e532d61e16 when calling get_string with a mutable string parameter, we want to only use the string buffer (#2595)
as scratch space
2026-01-22 10:23:39 -05:00
Olaf Bernstein db93de2a21 add rvv-vls backend (#2593) 2026-01-21 10:13:50 -05:00
Francisco Geiman Thiesen fc57c09cf0 Add FracturedJson formatting support for DOM serialization (#2580)
* Add FracturedJson formatting support for DOM serialization

Implements FracturedJson formatting as requested in issue #2576.
FracturedJson produces human-readable yet compact JSON output by
intelligently choosing between different layout strategies based on
content complexity, length, and structure similarity.

Key features:
- Four layout modes: inline, compact multiline, table, and expanded
- Structure analysis pass to compute metrics before formatting
- Table formatting for arrays of similar objects with column alignment
- Configurable options for line length, indentation, padding, etc.

New files:
- fractured_json.h: Public API with fractured_json_options struct
- fractured_json-inl.h: Implementation (~1000 lines)
- json_structure_analyzer.h: Structure analysis for layout decisions
- fractured_formatter.h: Formatter class using CRTP pattern

Usage:
  dom::parser parser;
  element doc = parser.parse(json_string);
  std::cout << fractured_json(doc) << std::endl;

  // Or with custom options:
  fractured_json_options opts;
  opts.indent_spaces = 2;
  std::cout << fractured_json(doc, opts) << std::endl;

  // Or format any JSON string (useful with reflection API):
  auto formatted = fractured_json_string(minified_json);

Resolves #2576

* Add comprehensive tests for FracturedJson formatter

Adds 27 test cases covering all aspects of the FracturedJson formatter:

Core functionality tests (13):
- Roundtrip parsing verification
- Inline formatting for simple arrays and objects
- Expanded formatting for complex nested structures
- Compact multiline arrays with configurable items per line
- Table formatting for uniform arrays of objects
- Empty container handling
- All scalar types (string, int, uint, double, bool, null)
- String escaping (quotes, backslashes, control characters)
- Custom indentation options
- Deep nesting (10+ levels)
- Mixed type arrays

Edge case tests (11):
- Unicode strings (Chinese, emoji, Arabic, Russian, accented chars)
- Boundary numbers (INT64_MIN/MAX, UINT64_MAX, DBL_MIN/MAX)
- Nested arrays (arrays of arrays)
- Empty string values
- Keys with special characters (spaces, quotes, colons, etc.)
- Non-uniform arrays (should not trigger table mode)
- Very long strings (500+ chars)
- Large arrays (100 elements)
- Reflection API workflow simulation
- Control characters (tab, newline, CR, null)
- Single element containers

Option tests (3):
- Disable compact multiline mode
- Disable table format mode
- Disable all padding options

* Add FracturedJson integration with builder/reflection API

Extends FracturedJson to work seamlessly with the builder API, enabling
formatted output directly from C++ structs using static reflection.

New functions:
- to_fractured_json_string(obj, opts) - serialize struct to formatted JSON
- to_fractured_json(obj, output, opts) - same with output parameter
- extract_fractured_json<fields...>(obj, opts) - format only specific fields

These functions combine the builder's reflection-based serialization with
FracturedJson formatting in a single convenient call:

  struct User { int id; std::string name; bool active; };
  User user{1, "Alice", true};

  // Minified output (existing):
  auto minified = to_json_string(user);
  // {"id":1,"name":"Alice","active":true}

  // Formatted output (new):
  auto formatted = to_fractured_json_string(user);
  // { "id": 1, "name": "Alice", "active": true }

  // Partial extraction with formatting:
  auto partial = extract_fractured_json<"id", "name">(user);
  // { "id": 1, "name": "Alice" }

New files:
- generic/builder/fractured_json_builder.h - builder integration
- tests/builder/static_reflection_fractured_json_tests.cpp - 7 tests

* Fix INT64_MIN overflow and implement table_similarity_threshold

- Fix undefined behavior when negating INT64_MIN in estimate_number_length()
  and measure_value_length() by returning 20 (the exact length of the
  string representation) directly
- Actually use table_similarity_threshold in check_array_uniformity() by
  calling compute_object_similarity() to compare objects against the first
  object in the array

* Fix -Werror=effc++ member initialization warnings

Initialize all member variables in member initialization lists to
satisfy GCC's -Werror=effc++ flag:
- element_metrics::common_keys - add {} default initializer
- structure_analyzer - add default constructor with member init list
- fractured_formatter - add column_widths_{} to constructor
- fractured_string_builder - add analyzer_{} to constructor

* Add Rule of Five to structure_analyzer class

The class has a pointer member (current_opts_) which triggers
-Werror=effc++ requiring explicit copy/move operations. Delete
copy operations (class shouldn't be copied due to cache) and
default move operations.

* Fix Windows build: wrap std::max to avoid macro conflict

Windows.h defines max/min macros that interfere with std::max/std::min.
Wrapping in parentheses as (std::max)(...) prevents macro expansion.

* Fix GCC 15 false positive -Wfree-nonheap-object warning

GCC 15 on MINGW64 gives a false positive warning in parser_moving_parser()
when the std::vector<std::string> goes out of scope. Suppress this
specific warning with a pragma for GCC builds.

* Fix metrics cache key bug by passing metrics through recursion

The cache was using element addresses as keys, but dom::element objects
are lightweight wrappers that get copied during iteration, causing
different addresses between analysis and formatting phases. This resulted
in cache misses and fallback to empty metrics.

Solution: Store child metrics in the element_metrics struct and pass
them through recursive calls, eliminating the need for address-based
caching entirely.

Changes:
- Add children vector to element_metrics for hierarchical metrics
- Remove metrics_cache_ and related get_metrics/has_metrics methods
- Update all format functions to accept and pass child metrics
- Add public analyze_array/analyze_object overloads for standalone use

* Add ignore patterns for Node.js, Rust, and generated files

Add entries for node_modules, package-lock.json, Rust target
directories, local ablation artifacts, and generated documentation
files.

* Refactor: extract analyze_scalar helper to reduce code duplication

Extract common scalar type handling (STRING, INT64, UINT64, DOUBLE,
BOOL, NULL_VALUE) into a dedicated analyze_scalar method. Each scalar
type shares the same initialization pattern for complexity, child_count,
can_inline, and recommended_layout.

Also simplify boolean formatting in format_scalar to use ternary operator.

* Fix formatting and duplicate error message in amalgamate.py

Reformat cramped is_amalgamator condition to multi-line for readability.
Fix duplicate error message text in _included_filename_root and use
correct variable name (relative_root instead of root).

* Refactor: add count_newlines helper in fractured_json tests

Extract repeated newline counting loop into a reusable static helper
function, used by inline_array_test, inline_object_test, and
expanded_test.

* Revert "Add ignore patterns for Node.js, Rust, and generated files"

This reverts commit 4760ea7cd0.

* various minor changes

---------

Co-authored-by: Daniel Lemire <daniel@lemire.me>
2026-01-20 10:32:24 -05:00
Daniel Lemire 2058b47dfe adding padded string builder (#2592)
* adding padded string builder

* minor rename

* deleting copy constructor

* typo

* [no-ci] tuning documentation.
2026-01-18 20:18:19 -05:00
Daniel Lemire b0486c7fa2 saving. 2026-01-18 11:57:55 -05:00
Daniel Lemire feb1e7feb6 work on the ondemand iterators (#2590)
* work on the ondemand iterators

* guarding two SIMDJSON_ASSUME

* simplify following @jkeiser's comment

* adding safety rails to the iterators

* silencing a warning.

* updating the amalgamation files
2026-01-17 21:15:18 -05:00
Eve Silfanus 2c7fbc1538 Build Performance Optimization (#2588) 2026-01-16 11:42:39 -05:00
Daniel Lemire 8b69401d8a moving the builder files in their own directory (#2578) 2026-01-07 18:08:11 -05:00
Daniel Lemire f504e57e7a Add runtime dispatching for loongarch (#2575)
* loongarch runtime dispatching

* remove CMake config for Loongarch.

* make lasx available

* flipping

* moving...

* fixing minor logic error

* minor fixes

* flipping

* adding hackish header

* better comment and reordering

* adding dispatch
2026-01-02 14:28:23 -05:00
Arthur Chan 135c173053 oss-fuzz: Add unit testing build to oss-fuzz build script (#2574) 2026-01-02 14:28:01 -05:00
Daniel Lemire b4ed3a99a9 fixing typos (#2573) 2025-12-30 17:38:03 -05:00
Daniel Lemire d8e1b36c88 just new small tests. (#2571) 2025-12-23 11:14:09 -05:00
Daniel Lemire c249a1b456 Merge branch 'master' of github.com:simdjson/simdjson 2025-12-22 16:08:30 -05:00
Daniel Lemire 9c4b793c90 adding ref 2025-12-22 16:08:19 -05:00
Daniel Lemire dd92a8414c Add optimization option to pull request template 2025-12-19 23:30:13 -05:00
Dirk Stolle 835bdba123 adjust logo image file names (*_simdjason_* -> *_simdjson_*) (#2569) 2025-12-19 23:21:59 -05:00
Dirk Stolle ad3cd71ca2 fix a few typos (#2568) 2025-12-19 21:56:32 -05:00
Daniel Lemire 860f7e0458 Update logo in README.md 2025-12-17 20:36:08 -05:00
Daniel Lemire 980f2ad3af 4.2.4 2025-12-17 20:33:11 -05:00
Daniel Lemire 7ad9fe63a6 fixing issue 2549 (#2567)
* fixing issue 2549

* saving.
2025-12-17 20:32:36 -05:00
Daniel Lemire 7987418b1f adding the official simdjson logo files 2025-12-13 12:14:40 -05:00
Daniel Lemire 5e871f6724 improving slightly the documentation. 2025-12-12 19:04:34 -05:00
Daniel Lemire 5d16fd5f31 4.2.3 2025-12-12 17:51:39 -05:00
Jake S. Del Mastro 4e9ff03af5 Make it possible to provide custom serializers for range types ( (#2550)
If you provide a custom serializer for range types it is currently never used due to the requires clause for string_builder::append with ranges is overly broad
2025-12-12 17:50:52 -05:00
Daniel Lemire aa7489060a Fix typo in bug report template 2025-12-12 15:24:48 -05:00
Daniel Lemire ae32422891 a few additional tests and removing a bad remark in the documentation... 2025-12-03 19:35:18 -05:00
Liqiang TAO 667d0ed3c7 make code branchless (#2546) 2025-11-18 16:57:06 -05:00
Daniel Lemire b1c31b428d update 2025-11-11 14:21:04 -05:00
Daniel Lemire 56ac56ba32 Merge branch 'master' of github.com:simdjson/simdjson 2025-11-11 14:17:08 -05:00
Muhammad Rizal Nurromdhoni 19549c60ec string_builder range-based append fix (#2544)
* Use std::ranges::range_value_t on range

* Add ranges test
2025-11-11 14:15:00 -05:00
Daniel Lemire 16e99f229b Update iterate_many.md for clarity on JSON processing
Clarified the example JSON format and emphasized the need for efficient processing.
2025-11-10 13:49:13 -05:00
Liqiang TAO 21342a4142 Fix some wrong content in doc (#2542) 2025-11-10 11:24:38 -05:00
Daniel Lemire d0e841d3e9 Release Candidate 4.2.2 (#2539)
* adding documentation.

* release candidate
2025-11-06 12:00:21 -05:00
Daniel Lemire a962652ec3 adding documentation. 2025-11-05 11:42:38 -05:00
hiteshmk05 77d73b068a add: windows wstring support for padded_str (#2537)
* add: windows wstring support for padded_str

* add: padded_string::load for wstring windows

* fix: extra space

* change: file path
2025-11-05 11:29:30 -05:00
Daniel Lemire 19ff7a572d adding concept examples to the compile-time JSON. (#2538) 2025-11-04 15:06:40 -05:00
Carlos Sousa e0ef3e7cec optimize get_string 2024-07-11 01:30:27 -03:00
136 changed files with 33956 additions and 21380 deletions
+1 -1
View File
@@ -38,7 +38,7 @@ If we cannot reproduce the issue, then we cannot address it. Note that a stack t
It should be possible to trigger the bug by using solely simdjson with our default build setup. If you can only observe the bug within some specific context, with some other software, please reduce the issue first.
**simjson release**
**simdjson release**
Unless you plan to contribute to simdjson, you should only work from releases. Please be mindful that our main branch may have additional features, bugs and documentation items.
+1
View File
@@ -6,6 +6,7 @@ Description
Type of change
- [ ] Bug fix
- [ ] Optimization
- [ ] New feature
- [ ] Refactor / cleanup
- [ ] Documentation / tests
+5 -5
View File
@@ -19,11 +19,11 @@ jobs:
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)
CC=clang-18 CXX=clang++-18 CFLAGS="--target=riscv64-linux-gnu -march=rv64gcv_zvbb" CXXFLAGS="${CFLAGS}" \
cmake --toolchain=cmake/toolchains-ci/riscv64-linux-gnu.cmake -DSIMDJSON_DEVELOPER_MODE=ON -B build
cmake --build build/ -j$(nproc) --config Release
- 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"
QEMU_LD_PREFIX="/usr/riscv64-linux-gnu" \
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)
+3 -8
View File
@@ -19,11 +19,6 @@ jobs:
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)
CC=clang-17 CXX=clang++-17 CFLAGS="--target=riscv64-linux-gnu -march=rv64gcv" CXXFLAGS="${CFLAGS}" \
cmake --toolchain=cmake/toolchains-ci/riscv64-linux-gnu.cmake -DSIMDJSON_DEVELOPER_MODE=ON -B build
cmake --build build/ -j$(nproc) --config Release
+39
View File
@@ -0,0 +1,39 @@
name: Ubuntu rvv VLEN=128 (clang 20)
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-20
- name: Build
run: |
CC=clang-20 CXX=clang++-20 CFLAGS="--target=riscv64-linux-gnu -march=rv64gcv" CXXFLAGS="${CFLAGS}" \
cmake --toolchain=cmake/toolchains-ci/riscv64-linux-gnu.cmake -DSIMDJSON_DEVELOPER_MODE=ON -B build
cmake --build build/ -j$(nproc) --config Release
- name: Test VLEN=128
run: |
QEMU_LD_PREFIX="/usr/riscv64-linux-gnu" \
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)
- name: Build VLS
run: |
CC=clang-20 CXX=clang++-20 CFLAGS="--target=riscv64-linux-gnu -march=rv64gcv_zvl128b_zba_zbb_zbc -mrvv-vector-bits=zvl" CXXFLAGS="${CFLAGS}" \
cmake --toolchain=cmake/toolchains-ci/riscv64-linux-gnu.cmake -DSIMDJSON_DEVELOPER_MODE=ON -B build-vls
cmake --build build-vls/ -j$(nproc) --config Release
- name: Test VLEN=128 VLS
run: |
QEMU_LD_PREFIX="/usr/riscv64-linux-gnu" \
QEMU_CPU="rv64,v=on,zba=on,zbb=on,zbc=on,vlen=128,rvv_ta_all_1s=on,rvv_ma_all_1s=on" \
ctest --timeout 1800 --output-on-failure --test-dir build-vls -j $(nproc)
+15 -5
View File
@@ -19,11 +19,21 @@ jobs:
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)
CC=riscv64-linux-gnu-gcc-14 CXX=riscv64-linux-gnu-g++-14 CFLAGS=-march=rv64gcv CXXFLAGS="${CFLAGS}" \
cmake --toolchain=cmake/toolchains-ci/riscv64-linux-gnu.cmake -DSIMDJSON_DEVELOPER_MODE=ON -B build
cmake --build build/ -j$(nproc) --config Release
- 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"
QEMU_LD_PREFIX="/usr/riscv64-linux-gnu" \
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)
- name: Build VLS
run: |
CC=riscv64-linux-gnu-gcc-14 CXX=riscv64-linux-gnu-g++-14 CFLAGS="-march=rv64gcv_zvl256b -mrvv-vector-bits=zvl" CXXFLAGS="${CFLAGS}" \
cmake --toolchain=cmake/toolchains-ci/riscv64-linux-gnu.cmake -DSIMDJSON_DEVELOPER_MODE=ON -B build-vls
cmake --build build-vls/ -j$(nproc) --config Release
- name: Test VLEN=256 VLS
run: |
QEMU_LD_PREFIX="/usr/riscv64-linux-gnu" \
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-vls -j $(nproc)
+39
View File
@@ -0,0 +1,39 @@
name: Ubuntu rvv VLEN=512 (clang 19)
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-19
- name: Build
run: |
CC=clang-19 CXX=clang++-19 CFLAGS="--target=riscv64-linux-gnu -march=rv64gcv" CXXFLAGS="${CFLAGS}" \
cmake --toolchain=cmake/toolchains-ci/riscv64-linux-gnu.cmake -DSIMDJSON_DEVELOPER_MODE=ON -B build
cmake --build build/ -j$(nproc) --config Release
- name: Test VLEN=512
run: |
QEMU_LD_PREFIX="/usr/riscv64-linux-gnu" \
QEMU_CPU="rv64,v=on,vlen=512,rvv_ta_all_1s=on,rvv_ma_all_1s=on" \
ctest --timeout 1800 --output-on-failure --test-dir build -j $(nproc)
- name: Build VLS
run: |
CC=clang-19 CXX=clang++-19 CFLAGS="--target=riscv64-linux-gnu -march=rv64gcv_zvl512b_zba_zbb_zbc -mrvv-vector-bits=zvl" CXXFLAGS="${CFLAGS}" \
cmake --toolchain=cmake/toolchains-ci/riscv64-linux-gnu.cmake -DSIMDJSON_DEVELOPER_MODE=ON -B build-vls
cmake --build build-vls/ -j$(nproc) --config Release
- name: Test VLEN=512 VLS
run: |
QEMU_LD_PREFIX="/usr/riscv64-linux-gnu" \
QEMU_CPU="rv64,v=on,zba=on,zbb=on,zbc=on,vlen=512,rvv_ta_all_1s=on,rvv_ma_all_1s=on" \
ctest --timeout 1800 --output-on-failure --test-dir build-vls -j $(nproc)
+50 -20
View File
@@ -1,9 +1,18 @@
cmake_minimum_required(VERSION 3.14)
# Build performance optimizations
set(CMAKE_EXPORT_COMPILE_COMMANDS ON CACHE BOOL "Export compile commands for faster IDE integration")
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
# Enable parallel compilation on MSVC
if(MSVC)
add_compile_options(/MP)
endif()
project(
simdjson
# The version number is modified by tools/release.py
VERSION 4.2.1
VERSION 4.2.4
DESCRIPTION "Parsing gigabytes of JSON per second"
HOMEPAGE_URL "https://simdjson.org/"
LANGUAGES CXX C
@@ -83,10 +92,36 @@ add_library(simdjson ${SIMDJSON_SOURCES})
add_library(simdjson::simdjson ALIAS simdjson)
set(SIMDJSON_LIBRARIES simdjson)
# Enable precompiled headers for faster builds
if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.16")
target_precompile_headers(simdjson PRIVATE
<algorithm>
<array>
<atomic>
<bit>
<cassert>
<cctype>
<cerrno>
<cstddef>
<cstdint>
<cstdlib>
<cstring>
<memory>
<string>
<utility>
<vector>
)
endif()
if(SIMDJSON_BUILD_STATIC_LIB)
add_library(simdjson_static STATIC ${SIMDJSON_SOURCES})
add_library(simdjson::simdjson_static ALIAS simdjson_static)
list(APPEND SIMDJSON_LIBRARIES simdjson_static)
# Reuse precompiled headers for static library
if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.16")
target_precompile_headers(simdjson_static REUSE_FROM simdjson)
endif()
endif()
set_target_properties(
@@ -112,6 +147,14 @@ simdjson_add_props(
PRIVATE "$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/src>"
)
# Optimize linker settings for faster builds
if(MSVC)
target_link_options(simdjson PRIVATE /INCREMENTAL)
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
target_link_options(simdjson PRIVATE /DEBUG:FASTLINK)
endif()
endif()
if(SIMDJSON_STATIC_REFLECTION)
# We would like to require C++26, but no compiler supports that!
# This is a hack:
@@ -140,24 +183,6 @@ if(SIMDJSON_MINUS_ZERO_AS_FLOAT)
simdjson_add_props(target_compile_definitions PRIVATE SIMDJSON_MINUS_ZERO_AS_FLOAT=1)
endif(SIMDJSON_MINUS_ZERO_AS_FLOAT)
if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(loongarch64)$")
option(SIMDJSON_PREFER_LSX "Prefer LoongArch SX" ON)
include(CheckCXXCompilerFlag)
check_cxx_compiler_flag(-mlasx COMPILER_SUPPORTS_LASX)
check_cxx_compiler_flag(-mlsx COMPILER_SUPPORTS_LSX)
if(COMPILER_SUPPORTS_LASX AND NOT SIMDJSON_PREFER_LSX)
simdjson_add_props(
target_compile_options PRIVATE
-mlasx
)
elseif(COMPILER_SUPPORTS_LSX)
simdjson_add_props(
target_compile_options PRIVATE
-mlsx
)
endif()
endif()
# GCC and Clang have horrendous Debug builds when using SIMD.
# A common fix is to use '-Og' instead.
# bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54412
@@ -171,7 +196,12 @@ if(
target_compile_options PRIVATE
$<$<CONFIG:DEBUG>:-Og>
)
endif()
# We still want to enable development checks in Debug mode
simdjson_add_props(
target_compile_definitions PUBLIC
SIMDJSON_DEVELOPMENT_CHECKS
)
endif()
if(SIMDJSON_ENABLE_THREADS)
find_package(Threads REQUIRED)
+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.2.1"
PROJECT_NUMBER = "4.2.4"
# 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
+25
View File
@@ -110,6 +110,24 @@ workflows used by simdjson.
Directory Structure and Source
------------------------------
Before diving into the directory structure, here are key concepts used in the codebase:
- **Amalgamated File**: A file that is conditionally included in the amalgamation process. These are wrapped in `#ifndef SIMDJSON_CONDITIONAL_INCLUDE` blocks and are included based on the target implementation (e.g., ARM64, x86). They include implementation-specific files (e.g., `arm64.h`) and generic files (e.g., under `generic/`). Amalgamated files have associated dependency files (`dependencies.h`) to track includes.
- **Amalgamator File**: A file that orchestrates the inclusion of amalgamated files. Examples: `arm64.h`, `arm64/implementation.h`, `generic/amalgamated.h`. These are not themselves amalgamated but control conditional inclusions.
- **Free Dependency File**: A top-level header that is always included unconditionally. These do not have dependency files and represent the public API (e.g., main headers).
- **Implementation-Specific File**: A file tied to a specific CPU architecture or instruction set (e.g., `arm64/`, `haswell/`). These must be amalgamated.
- **Generic File**: A shared file (under `generic/` or `simdjson/generic/`) that contains common code included once per implementation.
- **Builtin File**: Special files under `simdjson/builtin/` that handle the builtin implementation, a fallback/default implementation used when no optimized implementation is available.
- **Conditional Include Block**: A section wrapped in `#ifndef SIMDJSON_CONDITIONAL_INCLUDE` for editor-only or implementation-specific content.
The script `singleheader/amalgation_helper.py` will generate an HTML report which you can use to visualize the status of each file.
simdjson's source structure, from the top level, looks like this:
* **CMakeLists.txt:** The main build system.
@@ -133,6 +151,12 @@ simdjson's source structure, from the top level, looks like this:
* simdjson/generic/ondemand/*.h: individual On-Demand classes, generically written.
* simdjson/generic/ondemand/dependencies.h: dependencies on common, non-implementation-specific simdjson classes. This will be included before including amalgamated.h.
* simdjson/generic/ondemand/amalgamated.h: all generic ondemand classes for an implementation.
* simdjson/builder.h: the `simdjson::builder` namespace. Includes all public builder classes.
* simdjson/builtin/builder.h: the `simdjson::builtin::builder` namespace.
* simdjson/arm64|fallback|haswell|icelake|ppc64|westmere/builder.h: the `simdjson::<implementation>::builder` namespace. Builder compiled for the specific implementation.
* simdjson/generic/builder/*.h: individual Builder classes, generically written.
* simdjson/generic/builder/dependencies.h: dependencies on common, non-implementation-specific simdjson classes. This will be included before including amalgamated.h.
* simdjson/generic/builder/amalgamated.h: all generic builder classes for an implementation.
* **src:** The source files for non-inlined functionality (e.g. the architecture-specific parser
implementations).
* simdjson.cpp: A "main source" that includes all implementation files from src/. This is
@@ -147,6 +171,7 @@ Other important files and directories:
* **.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). If you add a new implementation (e.g., rvv), you need to edit this file (IMPLEMENTATIONS).
* **singleheader/amalgation_helper.py:** Generates and `amalgamation_report.html` that helps you understand the status of each file.
* **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:
+17 -1
View File
@@ -6,7 +6,8 @@
simdjson : Parsing gigabytes of JSON per second
===============================================
<img src="images/logo.png" width="10%" style="float: right">
<img src="images/official_logo/logo_noir/SVG/logo_simdjson_noir.svg" width="40%" style="float: right">
JSON is everywhere on the Internet. Servers spend a *lot* of time parsing it. We need a fresh
approach. The simdjson library uses commonly available SIMD instructions and microparallel algorithms
to parse JSON 4x faster than RapidJSON and 25x faster than JSON for Modern C++.
@@ -212,6 +213,21 @@ For the video inclined, <br />
[![simdjson at QCon San Francisco 2019](http://img.youtube.com/vi/wlvKAT7SZIQ/0.jpg)](http://www.youtube.com/watch?v=wlvKAT7SZIQ)<br />
(It was the best voted talk, we're kinda proud of it.)
Citing this work
-----------------
If you use simdjson in published research, please cite the software library. A suitable BibTeX entry is:
```bibtex
@misc{simdjson,
title={{The simdjson library: Parsing Gigabytes of JSON per Second}},
author={Daniel Lemire and Geoff Langdale and John Keiser and Paul Dreik and Francisco Thiesen and others},
year={2019},
howpublished={Software library},
note={https://github.com/simdjson/simdjson}
}
```
Funding
-------
+3 -3
View File
@@ -245,7 +245,7 @@ static u32 (*kpc_get_counter_count)(u32 classes);
/// Get counter accumulations.
/// If `all_cpus` is true, the buffer count should not smaller than
/// (cpu_count * counter_count). Otherwize, the buffer count should not smaller
/// (cpu_count * counter_count). Otherwise, the buffer count should not smaller
/// than (counter_count).
/// @see kpc_get_counter_count(), kpc_cpu_count().
/// @param all_cpus true for all CPUs, false for current cpu.
@@ -374,7 +374,7 @@ static int kperf_lightweight_pet_set(u32 enabled) {
// These functions do not require root privileges.
// -----------------------------------------------------------------------------
// KPEP CPU archtecture constants.
// KPEP CPU architecture constants.
#define KPEP_ARCH_I386 0
#define KPEP_ARCH_X86_64 1
#define KPEP_ARCH_ARM 2
@@ -414,7 +414,7 @@ typedef struct kpep_db {
usize fixed_counter_count;
usize config_counter_count;
usize power_counter_count;
u32 archtecture; ///< see `KPEP CPU archtecture constants` above.
u32 architecture; ///< see `KPEP CPU architecture constants` above.
u32 fixed_counter_bits;
u32 config_counter_bits;
u32 power_counter_bits;
+24 -9
View File
@@ -169,8 +169,10 @@ For efficiency reasons, simdjson requires a string with a few bytes (`simdjson::
at the end, these bytes may be read but their content does not affect the parsing. In practice,
it means that the JSON inputs should be stored in a memory region with `simdjson::SIMDJSON_PADDING`
extra bytes at the end. You do not have to set these bytes to specific values though you may
want to if you want to avoid runtime warnings with some sanitizers. Advanced users may want to
read the section Free Padding in [our performance notes](performance.md).
want to if you want to avoid runtime warnings with some sanitizers. We expect the user
of the library to load the data (from disk or from the network) into a padded buffer. To make
this easy, we provide the `padded_string::load` function which loads files from disk in a padded buffer.
[You can similarly fetch a file from a URL to a padded string](https://github.com/simdjson/curltostring) using our `simdjson::padded_string_builder`. Advanced users may want to read the section Free Padding in [our performance notes](performance.md).
The simdjson library offers a tree-like [API](https://en.wikipedia.org/wiki/API), which you can
access by creating a `ondemand::parser` and calling the `iterate()` method. The iterate method
@@ -183,6 +185,9 @@ auto json = padded_string::load("twitter.json"); // load JSON file 'twitter.json
ondemand::document doc = parser.iterate(json); // position a pointer at the beginning of the JSON data
```
(Windows users compiling with C++17 or better may use `wchar_t` strings to support non-ASCII
filenames: `padded_string::load(L"twitter.json")`.)
If you prefer not to create your own `ondemand::parser` instance, you can access
a thread-local version by calling `ondemand::parser.get_parser()`.
@@ -351,7 +356,13 @@ 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
simdjson library runs additional (expensive) tests on your code to help ensure that you are
using the library in a safe manner.
using the library in a safe manner. We add asserts which may halt your program, helping
you find the bad programming pattern.
When `SIMDJSON_DEVELOPMENT_CHECKS`, some of our data structures contain extra data for
tracking explicitly potential programming mistakes. Thus you should not relying on the
size (`sizeof`) of our data structures to be constant: they may change depending on the
compiler settings.
Once your code has been tested, you can then run it in
Release mode: under Visual Studio, it means having the `_DEBUG` macro undefined, and, for other
@@ -434,8 +445,8 @@ support for users who avoid exceptions. See [the simdjson error handling documen
If you know the type of the value, you can cast it right there, too! `for (double value : array) { ... }`.
You may also use explicit iterators: `for(auto i = array.begin(); i != array.end(); i++) {}`. You can check that an array is empty with the condition `auto i = array.begin(); if (i == array.end()) {...}`.
* **Object Iteration:** You can iterate through an object's fields, as well: `for (auto field : object) { ... }`. You may also use explicit iterators : `for(auto i = object.begin(); i != object.end(); i++) { auto field = *i; .... }`. You can check that an object is empty with the condition `auto i = object.begin(); if (i == object.end()) {...}`.
You may also use explicit iterators: `for(auto i = array.begin(); i != array.end(); i++) {}`. You can check that an array is empty with the condition `auto i = array.begin(); if (i == array.end()) {...}`. You should derefence (`*i`) an iterator at most once before incrementing it (`i++`), when compiling in debug mode with development checks, we add asserts to help you identify such a mistake.
* **Object Iteration:** You can iterate through an object's fields, as well: `for (auto field : object) { ... }`.
- `field.unescaped_key()` will get you the unescaped key string as a `std::string_view` instance. E.g., the JSON string `"\u00e1"` becomes the Unicode string `á`. Optionally, you pass `true` as a parameter to the `unescaped_key` method if you want invalid escape sequences to be replaced by a default replacement character (e.g., `\ud800\ud801\ud811`): otherwise bad escape sequences lead to an immediate error.
- `field.escaped_key()` will get you the key string as as a `std::string_view` instance, but unlike `unescaped_key()`, the key is not processed, so no unescaping is done. E.g., the JSON string `"\u00e1"` becomes the Unicode string `\u00e1`. We expect that `escaped_key()` is faster than `field.unescaped_key()`.
- `field.value()` will get you the value, which you can then use all these other methods on.
@@ -448,8 +459,12 @@ support for users who avoid exceptions. See [the simdjson error handling documen
When you are iterating through an object, you are advancing through its keys and values. You should not also access the object or other objects. E.g. within a loop over `myobject`, you should not be accessing `myobject`. The following is an anti-pattern: `for(auto value: myobject) {myobject["mykey"]}`.
We discourage using the object iterators explicitly: `for(auto i = object.begin(); i != object.end(); i++) { auto field = *i; .... }`. In addition to the usual requirement to check against `end()` prior to dereferencing, you must also always dereference the pointer (`*it`) exactly once before you increment it (`it++`). You must also only deference the iterator once (never more than once). When compiling in
debug mode with development checks, we add asserts to help check whether you correctly
dereferenced the pointer before incrementing it.
You should never reset an object as you are iterating through it. The following is an anti-pattern: `for(auto value: myobject) {myobject.reset()}`.
* **Array Index:** Because it is forward-only, you cannot look up an array element by index by index. Instead,
* **Array Index:** Because it is forward-only, you cannot look up an array element by index. Instead,
you should iterate through the array and keep an index yourself. Exceptionally, if need a single value
out of the array, you may use an array access (e.g., `array[1]`). You should never reset an array as you are iterating through it. The following is an anti-pattern: `for(auto value: myarray) {myarray.reset()}`.
* **Field Access:** To get the value of the "foo" field in an object, use `object["foo"]`. This will
@@ -524,13 +539,13 @@ support for users who avoid exceptions. See [the simdjson error handling documen
> auto silly_json = R"( { "test": "result" } )"_padded;
> ondemand::document doc = parser.iterate(silly_json);
> std::cout << simdjson::to_json_string(doc["test"]) << std::endl; // Requires simdjson 1.0 or better
>````
> ```
> ```cpp
> // retrieves an unescaped string value as a string_view instance
> auto silly_json = R"( { "test": "result" } )"_padded;
> ondemand::document doc = parser.iterate(silly_json);
> std::cout << std::string_view(doc["test"]) << std::endl;
>````
> ```
You can use `to_json_string` to efficiently extract components of a JSON document to reconstruct a new JSON document, as in the following example:
> ```cpp
> auto cars_json = R"( [
@@ -559,7 +574,7 @@ support for users who avoid exceptions. See [the simdjson error handling documen
> oss << "]";
> auto json_string = oss.str();
> // json_string == "[[ 40.1, 39.9, 37.7, 40.4 ],[ 30.1, 31.0, 28.6, 28.7 ]]"
>````
> ```
* **Extracting Values (without exceptions):** You can use a variant usage of `get()` with error
codes to avoid exceptions. You first declare the variable of the appropriate type (`double`,
`uint64_t`, `int64_t`, `bool`, `ondemand::object` and `ondemand::array`) and pass it by reference
+49 -2
View File
@@ -14,6 +14,7 @@ speed and high convenience.
* [C++26 static reflection](#c--26-static-reflection)
+ [Without `string_buffer` instance](#without--string-buffer--instance)
+ [Without `string_buffer` instance but with explicit error handling](#without--string-buffer--instance-but-with-explicit-error-handling)
+ [Pretty formatted (fractured JSON)](#pretty-formatted-fractured-json)
Overview: string_builder
---------------------------
@@ -332,7 +333,7 @@ pattern:
### Customization
If you want to serialize a value in a custome way, you can do it with a
If you want to serialize a value in a custom way, you can do it with a
`tag_invoke` specialization like the following example which will map
the year attribute to a string.
@@ -363,4 +364,50 @@ void tag_invoke(serialize_tag, builder_type &builder, const Car& car) {
}
} // namespace simdjson
```
```
### Pretty formatted (fractured JSON)
In some instances, you may want your JSON to be more readable. For this pupose, we also
support the Fractured JSON standard.
```Cpp
TableTestData data{
{{1, "Alice", true}, {2, "Bob", false}, {3, "Carol", true}, {4, "Dave", false}}
};
fractured_json_options opts;
opts.enable_table_format = true;
opts.min_table_rows = 3;
std::string formatted = simdjson::to_fractured_json_string(data, opts);
```
The result might be as follows.
```json
{
"records": [
{ "active": true , "id": 1, "name": "Alice" },
{ "active": false, "id": 2, "name": "Bob" },
{ "active": true , "id": 3, "name": "Carol" },
{ "active": false, "id": 4, "name": "Dave" }
]
}
```
The `fractured_json_options` struct allows you to customize the formatting behavior. It includes the following options:
- `max_total_line_length` (default: 120): Maximum total characters per line. Content exceeding this will be expanded to multiple lines.
- `max_inline_length` (default: 80): Maximum length for inlined elements. Simple arrays/objects shorter than this may be rendered inline.
- `max_inline_complexity` (default: 2): Maximum nesting depth for inline rendering. Elements with complexity exceeding this will be expanded. Complexity 0 = scalar, 1 = flat array/object, 2 = one level of nesting.
- `max_compact_array_complexity` (default: 1): Maximum complexity for compact array formatting. Arrays with elements of this complexity or less may have multiple items per line.
- `indent_spaces` (default: 4): Number of spaces per indentation level.
- `enable_table_format` (default: true): Enable tabular formatting for arrays of similar objects. When enabled, arrays of objects with identical keys are formatted as aligned tables.
- `min_table_rows` (default: 3): Minimum number of rows to trigger table mode.
- `table_similarity_threshold` (default: 0.8): Similarity threshold for table detection. Objects must share at least this fraction of keys to be formatted as a table.
- `enable_compact_multiline` (default: true): Enable compact multiline arrays. When enabled, arrays of simple elements may have multiple items per line.
- `max_items_per_line` (default: 10): Maximum array items per line in compact mode.
- `simple_bracket_padding` (default: true): Add space inside brackets for simple containers. When true: `{ "key": "value" }`, when false: `{"key": "value"}`.
- `colon_padding` (default: true): Add space after colons. When true: `"key": "value"`, when false: `"key":"value"`.
- `comma_padding` (default: true): Add space after commas in inline content. When true: `[1, 2, 3]`, when false: `[1,2,3]`.
+63
View File
@@ -1,6 +1,7 @@
# Parse json at compile time
* [Introduction](#introduction)
* [Example](#example)
* [Concepts](#concepts)
* [Loading from disk](#loading-from-disk)
* [Limitations (compile-time errors)](#limitations-compile-time-errors)
@@ -106,6 +107,68 @@ static_assert(arr.size() == 3);
static_assert(arr[1] == 2);
```
## Concepts
Given that the parsed data is made of structures that depend on the JSON input, you might
want to check that it conforms to your expectation. You can do so with concepts.
Let us consider this example:
```cpp
constexpr auto config = R"(
[
{ "name": "Alice", "age": 30 },
{ "name": "Bob", "age": 25 },
{ "name": "Charlie", "age": 35 }
]
)"_json;
```
You might want to ensure that the result is an array of persons. You can define your
expectation with concepts like so:
```cpp
template <typename T>
concept person = requires(T p) {
std::string_view(p.name); // has name field convertible to string_view
p.age; // has age field
requires std::is_integral_v<decltype(p.age)>; // age is integral
};
/**
* Concept to validate that a type is an array of person objects
*/
template <typename T>
concept array_of_person = requires(T arr) {
arr.size(); // has size method
arr[0]; // can access elements with []
requires person<decltype(arr[0])>; // elements satisfy person concept
};
```
And then a simple static assert with `decltype` is sufficient to check that the expectation is met:
```cpp
constexpr auto config = R"(
[
{ "name": "Alice", "age": 30 },
{ "name": "Bob", "age": 25 },
{ "name": "Charlie", "age": 35 }
]
)"_json;
// Validate that the array satisfies the array_of_person concept
static_assert(array_of_person<decltype(config)>);
```
## Loading from disk
In practice, you may have a JSON file, say `json_data` that you want to parse
+19 -1
View File
@@ -54,6 +54,24 @@ dom::parser parser;
dom::element doc = parser.parse("[1,2,3]"_padded); // parse a string, the _padded suffix creates a simdjson::padded_string instance
```
You can also load a `padded_string` from a file.
```cpp
auto json = padded_string::load("twitter.json"); // load JSON file 'twitter.json'.
dom::element doc = parser.parse(json);
```
[You can similarly fetch a file from a URL to a padded string](https://github.com/simdjson/curltostring) using our `simdjson::padded_string_builder`.
(Windows users compiling with C++17 or better may use `wchar_t` strings to support non-ASCII
filenames: `padded_string::load(L"twitter.json")`.)
(Windows users compiling with C++17 or better may use `wchar_t` strings to support non-ASCII
filenames: `padded_string::load(L"twitter.json")`.)
You can copy your data directly on a `simdjson::padded_string` as follows:
```cpp
@@ -827,7 +845,7 @@ memcpy(padded_json_copy.get(), json, json_len);
memset(padded_json_copy.get() + json_len, 0, SIMDJSON_PADDING);
simdjson::dom::parser parser;
simdjson::dom::element element = parser.parse(padded_json_copy.get(), json_len, false);
````
```
Setting the `realloc_if_needed` parameter `false` in this manner may lead to better performance since copies are avoided, but it requires that the user takes more responsibilities: the simdjson library cannot verify that the input buffer was padded with SIMDJSON_PADDING extra bytes.
+2 -2
View File
@@ -8,7 +8,7 @@ library provides high-speed access to files or streams containing multiple small
{"text":"a"}
{"text":"b"}
{"text":"c"}
...
"..."
```
... you want to read the entries (individual JSON documents) as quickly and as conveniently as possible. Importantly, the input might span several gigabytes, but you want to use a small (fixed) amount of memory. Ideally, you'd also like the parallelize the processing (using more than one core) to speed up the process.
@@ -403,4 +403,4 @@ Otherwise you may use this longer version for explicit handling of errors:
}
cars.push_back(c);
}
```
```
+1 -1
View File
@@ -545,7 +545,7 @@ To help visualize the algorithm, we'll walk through the example C++ given at the
"statuses": [
{ "id": 1, "text": "first!", "user": { "screen_name": "lemire", "name": "Daniel" }, "retweet_count": 40 },
{ "id": 2, "text": "second!", "user": { "screen_name": "jkeiser2", "name": "John" }, "retweet_count": 3 }
^ (depth 3 - root > statuses > tweet)
^ (depth 4 - root > statuses > tweet > field)
],
"search_metadata": { "count": 2 }
}
+58
View File
@@ -297,4 +297,62 @@ int main() {
}
return EXIT_SUCCESS;
}
```
Further, whenever you allocate N bytes, memory allocators tend to allocate more memory, without you necessarily knowing about it. Under linux, you can use the `malloc_usable_size` function to see how much memory was actually allocated.
Under an Apple plateform, you can `malloc_size`. The following program illustrates the usage.
```cpp
#include <iostream>
#include <cstddef>
#include <memory>
#include <cstdlib>
#ifdef __APPLE__
#include <malloc/malloc.h> // for malloc_size on macOS
#endif
#ifdef __linux__
#include <malloc.h> // for malloc_usable_size on Linux
#endif
size_t get_usable_size(void* ptr) {
#ifdef __linux__
return malloc_usable_size(ptr);
#elif defined(__APPLE__)
return malloc_size(ptr);
#else
return 0; // Unsupported platform
#endif
}
int main() {
std::cout << "Demonstrating allocation overhead and rounding with operator new\n\n";
#ifdef __linux__
std::cout << "Platform: Linux\n";
#elif defined(__APPLE__)
std::cout << "Platform: macOS (using malloc_size)\n";
#else
std::cout << "Platform: Other/unsupported (usable size will show 0)\n";
#endif
std::cout << "Requested size | Actual usable size\n";
std::cout << "---------------|-------------------\n";
size_t total_requested = 0;
size_t total_usable = 0;
for (size_t requested = 1; requested <= 4096; requested++) {
total_requested += requested;
std::unique_ptr<char[]> ptr(new char[requested]); // Allocate
size_t usable = get_usable_size(ptr.get()); // Get usable size
total_usable += usable;
std::cout << requested << "\t | " << usable << "\n";
}
std::cout << "---------------|-------------------\n";
std::cout << "Total requested: " << total_requested << " bytes\n";
std::cout << "Total usable: " << total_usable << " bytes\n";
std::cout << "Total overhead: " << (total_usable - total_requested) << " bytes\n";
std::cout << "Percentage overhead: "
<< ((total_usable - total_requested) * 100.0 / total_requested) << " %\n";
return EXIT_SUCCESS;
}
```
+1 -6
View File
@@ -8,16 +8,11 @@
* Minifies by first parsing, then minifying.
*/
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
auto begin = as_chars(Data);
auto end = begin + Size;
std::string str(begin, end);
simdjson::padded_string str(reinterpret_cast<const char *>(Data), Size);
simdjson::dom::parser parser;
simdjson::dom::element elem;
auto error = parser.parse(str).get(elem);
if (error) { return 0; }
std::string minified = simdjson::minify(elem);
(void)minified;
return 0;
+1 -1
View File
@@ -35,7 +35,7 @@ cmake .. \
-DSIMDJSON_DISABLE_DEPRECATED_API=On \
-DSIMDJSON_FUZZ_LDFLAGS=$LIB_FUZZING_ENGINE
cmake --build . --target all_fuzzers
cmake --build . --target all_fuzzers all_tests
cp fuzz/fuzz_* $OUT
Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 226 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 256 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 258 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 136 KiB

+1
View File
@@ -52,6 +52,7 @@
#include "simdjson/padded_string_view-inl.h"
#include "simdjson/dom.h"
#include "simdjson/builder.h"
#include "simdjson/ondemand.h"
#include "simdjson/convert.h"
#include "simdjson/convert-inl.h"
+8
View File
@@ -0,0 +1,8 @@
#ifndef SIMDJSON_ARM64_BUILDER_H
#define SIMDJSON_ARM64_BUILDER_H
#include "simdjson/arm64/begin.h"
#include "simdjson/generic/builder/amalgamated.h"
#include "simdjson/arm64/end.h"
#endif // SIMDJSON_ARM64_BUILDER_H
+1
View File
@@ -428,6 +428,7 @@ namespace {
static constexpr int NUM_CHUNKS = 64 / sizeof(simd8<T>);
static_assert(NUM_CHUNKS == 4, "ARM kernel should use four registers per 64-byte block.");
const simd8<T> chunks[NUM_CHUNKS];
template<int idx> simd8<uint8_t> get() const { return idx < NUM_CHUNKS ? chunks[idx] : simd8<T>(); }
simd8x64(const simd8x64<T>& o) = delete; // no copy allowed
simd8x64<T>& operator=(const simd8<T>& other) = delete; // no assignment allowed
+14
View File
@@ -0,0 +1,14 @@
#ifndef SIMDJSON_BUILDER_H
#define SIMDJSON_BUILDER_H
#include "simdjson/builtin/builder.h"
namespace simdjson {
/**
* @copydoc simdjson::builtin::builder
*/
namespace builder = builtin::builder;
} // namespace simdjson
#endif // SIMDJSON_BUILDER_H
+4 -2
View File
@@ -20,10 +20,12 @@
#include "simdjson/ppc64.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(westmere)
#include "simdjson/westmere.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lsx)
#include "simdjson/lsx.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lasx)
#include "simdjson/lasx.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lsx)
#include "simdjson/lsx.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(rvv_vls)
#include "simdjson/rvv-vls.h"
#else
#error Unknown SIMDJSON_BUILTIN_IMPLEMENTATION
#endif
+2
View File
@@ -21,6 +21,8 @@ namespace simdjson {
namespace lsx {}
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lasx)
namespace lasx {}
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(rvv_vls)
namespace rvv_vls {}
#else
#error Unknown SIMDJSON_BUILTIN_IMPLEMENTATION
#endif
+42
View File
@@ -0,0 +1,42 @@
#ifndef SIMDJSON_BUILTIN_BUILDER_H
#define SIMDJSON_BUILTIN_BUILDER_H
#include "simdjson/builtin.h"
#include "simdjson/builtin/base.h"
#include "simdjson/generic/builder/dependencies.h"
#define SIMDJSON_CONDITIONAL_INCLUDE
#if SIMDJSON_BUILTIN_IMPLEMENTATION_IS(arm64)
#include "simdjson/arm64/builder.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(fallback)
#include "simdjson/fallback/builder.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(haswell)
#include "simdjson/haswell/builder.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(icelake)
#include "simdjson/icelake/builder.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(ppc64)
#include "simdjson/ppc64/builder.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(westmere)
#include "simdjson/westmere/builder.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lsx)
#include "simdjson/lsx/builder.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lasx)
#include "simdjson/lasx/builder.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(rvv_vls)
#include "simdjson/rvv-vls/builder.h"
#else
#error Unknown SIMDJSON_BUILTIN_IMPLEMENTATION
#endif
#undef SIMDJSON_CONDITIONAL_INCLUDE
namespace simdjson {
/**
* @copydoc simdjson::SIMDJSON_BUILTIN_IMPLEMENTATION::builder
*/
namespace builder = SIMDJSON_BUILTIN_IMPLEMENTATION::builder;
} // namespace simdjson
#endif // SIMDJSON_BUILTIN_BUILDER_H
+3 -1
View File
@@ -23,6 +23,8 @@
#include "simdjson/lsx/implementation.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lasx)
#include "simdjson/lasx/implementation.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(rvv_vls)
#include "simdjson/rvv-vls/implementation.h"
#else
#error Unknown SIMDJSON_BUILTIN_IMPLEMENTATION
#endif
@@ -39,4 +41,4 @@ namespace simdjson {
const implementation * builtin_implementation();
} // namespace simdjson
#endif // SIMDJSON_BUILTIN_IMPLEMENTATION_H
#endif // SIMDJSON_BUILTIN_IMPLEMENTATION_H
+3 -1
View File
@@ -24,6 +24,8 @@
#include "simdjson/lsx/ondemand.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lasx)
#include "simdjson/lasx/ondemand.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(rvv_vls)
#include "simdjson/rvv-vls/ondemand.h"
#else
#error Unknown SIMDJSON_BUILTIN_IMPLEMENTATION
#endif
@@ -37,4 +39,4 @@ namespace simdjson {
namespace ondemand = SIMDJSON_BUILTIN_IMPLEMENTATION::ondemand;
} // namespace simdjson
#endif // SIMDJSON_BUILTIN_ONDEMAND_H
#endif // SIMDJSON_BUILTIN_ONDEMAND_H
+3 -1
View File
@@ -289,7 +289,9 @@ namespace std {
// when the compiler is optimizing.
// We only set SIMDJSON_DEVELOPMENT_CHECKS if both __OPTIMIZE__
// and NDEBUG are not defined.
#if !defined(__OPTIMIZE__) && !defined(NDEBUG)
// We recognize _DEBUG as overriding __OPTIMIZE__ so that if both
// __OPTIMIZE__ and _DEBUG are defined, we still set SIMDJSON_DEVELOPMENT_CHECKS.
#if ((!defined(__OPTIMIZE__) || defined(_DEBUG)) && !defined(NDEBUG))
#define SIMDJSON_DEVELOPMENT_CHECKS 1
#endif // __OPTIMIZE__
#endif // _MSC_VER
+2
View File
@@ -9,6 +9,7 @@
#include "simdjson/dom/object.h"
#include "simdjson/dom/parser.h"
#include "simdjson/dom/serialization.h"
#include "simdjson/dom/fractured_json.h"
// Inline functions
#include "simdjson/dom/array-inl.h"
@@ -19,5 +20,6 @@
#include "simdjson/dom/parser-inl.h"
#include "simdjson/internal/tape_ref-inl.h"
#include "simdjson/dom/serialization-inl.h"
#include "simdjson/dom/fractured_json-inl.h"
#endif // SIMDJSON_DOM_H
File diff suppressed because it is too large Load Diff
+159
View File
@@ -0,0 +1,159 @@
#ifndef SIMDJSON_DOM_FRACTURED_JSON_H
#define SIMDJSON_DOM_FRACTURED_JSON_H
#include "simdjson/dom/base.h"
#include "simdjson/dom/element.h"
namespace simdjson {
/**
* Configuration options for FracturedJson formatting.
*
* FracturedJson intelligently chooses between different layout strategies
* (inline, compact multiline, table, expanded) based on content complexity,
* length, and structure similarity.
*/
struct fractured_json_options {
/**
* Maximum total characters per line (default: 120).
* Content exceeding this will be expanded to multiple lines.
*/
size_t max_total_line_length = 120;
/**
* Maximum length for inlined elements (default: 80).
* Simple arrays/objects shorter than this may be rendered inline.
*/
size_t max_inline_length = 80;
/**
* Maximum nesting depth for inline rendering (default: 2).
* Elements with complexity exceeding this will be expanded.
* Complexity 0 = scalar, 1 = flat array/object, 2 = one level of nesting.
*/
size_t max_inline_complexity = 2;
/**
* Maximum complexity for compact array formatting (default: 1).
* Arrays with elements of this complexity or less may have multiple
* items per line.
*/
size_t max_compact_array_complexity = 1;
/**
* Number of spaces per indentation level (default: 4).
*/
size_t indent_spaces = 4;
/**
* Enable tabular formatting for arrays of similar objects (default: true).
* When enabled, arrays of objects with identical keys are formatted
* as aligned tables.
*/
bool enable_table_format = true;
/**
* Minimum number of rows to trigger table mode (default: 3).
*/
size_t min_table_rows = 3;
/**
* Similarity threshold for table detection (default: 0.8).
* Objects must share at least this fraction of keys to be formatted
* as a table.
*/
double table_similarity_threshold = 0.8;
/**
* Enable compact multiline arrays (default: true).
* When enabled, arrays of simple elements may have multiple items
* per line.
*/
bool enable_compact_multiline = true;
/**
* Maximum array items per line in compact mode (default: 10).
*/
size_t max_items_per_line = 10;
/**
* Add space inside brackets for simple containers (default: true).
* When true: { "key": "value" }
* When false: {"key": "value"}
*/
bool simple_bracket_padding = true;
/**
* Add space after colons (default: true).
* When true: "key": "value"
* When false: "key":"value"
*/
bool colon_padding = true;
/**
* Add space after commas in inline content (default: true).
* When true: [1, 2, 3]
* When false: [1,2,3]
*/
bool comma_padding = true;
};
/**
* Format JSON using FracturedJson formatting with default options.
*
* FracturedJson produces human-readable yet compact output by intelligently
* choosing between inline, compact multiline, table, and expanded layouts.
*
* dom::parser parser;
* element doc = parser.parse(json_string);
* cout << fractured_json(doc) << endl;
*/
template <class T>
std::string fractured_json(T x);
/**
* Format JSON using FracturedJson formatting with custom options.
*
* dom::parser parser;
* element doc = parser.parse(json_string);
* fractured_json_options opts;
* opts.max_total_line_length = 80;
* cout << fractured_json(doc, opts) << endl;
*/
template <class T>
std::string fractured_json(T x, const fractured_json_options& options);
#if SIMDJSON_EXCEPTIONS
template <class T>
std::string fractured_json(simdjson_result<T> x);
template <class T>
std::string fractured_json(simdjson_result<T> x, const fractured_json_options& options);
#endif
/**
* Format a JSON string using FracturedJson formatting.
*
* This is useful for formatting output from the builder/static reflection API
* or any valid JSON string.
*
* // With static reflection
* MyStruct data = {...};
* auto minified = simdjson::to_json_string(data);
* auto formatted = simdjson::fractured_json_string(minified.value());
*
* // Or with any JSON string
* std::string json = R"({"key":"value"})";
* auto formatted = simdjson::fractured_json_string(json);
*/
inline std::string fractured_json_string(std::string_view json_str);
/**
* Format a JSON string using FracturedJson formatting with custom options.
*/
inline std::string fractured_json_string(std::string_view json_str,
const fractured_json_options& options);
} // namespace simdjson
#endif // SIMDJSON_DOM_FRACTURED_JSON_H
+2 -5
View File
@@ -204,10 +204,7 @@ public:
*
* ### std::string references
*
* If you pass a mutable std::string reference (std::string&), the parser will seek to extend
* its capacity to SIMDJSON_PADDING bytes beyond the end of the string.
*
* Whenever you pass an std::string reference, the parser will access the bytes beyond the end of
* Whenever you pass an std::string reference, the parser may access the bytes beyond the end of
* the string but before the end of the allocated memory (std::string::capacity()).
* If you are using a sanitizer that checks for reading uninitialized bytes or std::string's
* container-overflow checks, you may encounter sanitizer warnings.
@@ -239,7 +236,7 @@ public:
/** @overload parse(const uint8_t *buf, size_t len, bool realloc_if_needed) */
simdjson_inline simdjson_result<element> parse(const char *buf, size_t len, bool realloc_if_needed = true) & noexcept;
simdjson_inline simdjson_result<element> parse(const char *buf, size_t len, bool realloc_if_needed = true) && =delete;
/** @overload parse(const uint8_t *buf, size_t len, bool realloc_if_needed) */
/** @overload parse(const std::string &) */
simdjson_inline simdjson_result<element> parse(const std::string &s) & noexcept;
simdjson_inline simdjson_result<element> parse(const std::string &s) && =delete;
/** @overload parse(const uint8_t *buf, size_t len, bool realloc_if_needed) */
+1 -1
View File
@@ -8,7 +8,7 @@
namespace simdjson {
inline bool is_fatal(error_code error) noexcept {
return error == TAPE_ERROR || error == INCOMPLETE_ARRAY_OR_OBJECT;
return error == TAPE_ERROR || error == INCOMPLETE_ARRAY_OR_OBJECT || error == OUT_OF_ORDER_ITERATION || error == DEPTH_ERROR;
}
namespace internal {
+4
View File
@@ -265,6 +265,8 @@ struct simdjson_result_base : protected std::pair<T, error_code> {
*/
simdjson_inline T&& value_unsafe() && noexcept;
using value_type = T;
using error_type = error_code;
}; // struct simdjson_result_base
} // namespace internal
@@ -376,6 +378,8 @@ struct simdjson_result : public internal::simdjson_result_base<T> {
*/
simdjson_inline T&& value_unsafe() && noexcept;
using value_type = T;
using error_type = error_code;
}; // struct simdjson_result
#if SIMDJSON_EXCEPTIONS
+8
View File
@@ -0,0 +1,8 @@
#ifndef SIMDJSON_FALLBACK_BUILDER_H
#define SIMDJSON_FALLBACK_BUILDER_H
#include "simdjson/fallback/begin.h"
#include "simdjson/generic/builder/amalgamated.h"
#include "simdjson/fallback/end.h"
#endif // SIMDJSON_FALLBACK_BUILDER_H
+5 -3
View File
@@ -17,10 +17,12 @@
#include "simdjson/arm64/begin.h"
#elif SIMDJSON_IMPLEMENTATION_PPC64
#include "simdjson/ppc64/begin.h"
#elif SIMDJSON_IMPLEMENTATION_LSX
#include "simdjson/lsx/begin.h"
#elif SIMDJSON_IMPLEMENTATION_LASX
#include "simdjson/lasx/begin.h"
#elif SIMDJSON_IMPLEMENTATION_LSX
#include "simdjson/lsx/begin.h"
#elif SIMDJSON_IMPLEMENTATION_RVV_VLS
#include "simdjson/rvv-vls/begin.h"
#elif SIMDJSON_IMPLEMENTATION_FALLBACK
#include "simdjson/fallback/begin.h"
#else
@@ -48,4 +50,4 @@ enum class number_type {
} // namespace SIMDJSON_IMPLEMENTATION
} // namespace simdjson
#endif // SIMDJSON_GENERIC_BASE_H
#endif // SIMDJSON_GENERIC_BASE_H
@@ -0,0 +1,13 @@
#if defined(SIMDJSON_CONDITIONAL_INCLUDE) && !defined(SIMDJSON_GENERIC_BUILDER_DEPENDENCIES_H)
#error simdjson/generic/builder/dependencies.h must be included before simdjson/generic/builder/amalgamated.h!
#endif
#include "simdjson/generic/builder/json_string_builder.h"
#include "simdjson/generic/builder/json_builder.h"
#include "simdjson/generic/builder/fractured_json_builder.h"
// JSON builder inline definitions
#include "simdjson/generic/builder/json_string_builder-inl.h"
@@ -0,0 +1,14 @@
#ifdef SIMDJSON_CONDITIONAL_INCLUDE
#error simdjson/generic/builder/dependencies.h must be included before defining SIMDJSON_CONDITIONAL_INCLUDE!
#endif
#ifndef SIMDJSON_GENERIC_BUILDER_DEPENDENCIES_H
#define SIMDJSON_GENERIC_BUILDER_DEPENDENCIES_H
// Internal headers needed for builder generics.
// All includes not under simdjson/generic/builder must be here!
// Otherwise, amalgamation will fail.
#include "simdjson/concepts.h"
#include "simdjson/dom/fractured_json.h"
#endif // SIMDJSON_GENERIC_BUILDER_DEPENDENCIES_H
@@ -0,0 +1,117 @@
#ifndef SIMDJSON_GENERIC_FRACTURED_JSON_BUILDER_H
#define SIMDJSON_GENERIC_FRACTURED_JSON_BUILDER_H
#ifndef SIMDJSON_CONDITIONAL_INCLUDE
#include "simdjson/generic/builder/json_builder.h"
#include "simdjson/dom/fractured_json.h"
#endif // SIMDJSON_CONDITIONAL_INCLUDE
#if SIMDJSON_STATIC_REFLECTION
namespace simdjson {
namespace SIMDJSON_IMPLEMENTATION {
namespace builder {
/**
* Serialize an object to a FracturedJson-formatted string.
*
* FracturedJson produces human-readable yet compact JSON output by intelligently
* choosing between different layout strategies (inline, compact multiline, table,
* expanded) based on content complexity, length, and structure similarity.
*
* This function combines the builder's serialization with FracturedJson formatting:
* 1. Serializes the object to minified JSON using reflection
* 2. Parses and reformats using FracturedJson
*
* Example:
* struct User { int id; std::string name; bool active; };
* User user{1, "Alice", true};
* auto result = to_fractured_json_string(user);
* // result.value() == "{ \"id\": 1, \"name\": \"Alice\", \"active\": true }"
*
* @param obj The object to serialize (must be a reflectable type)
* @param opts FracturedJson formatting options
* @param initial_capacity Initial buffer capacity for serialization
* @return The formatted JSON string, or an error
*/
template <class T>
simdjson_warn_unused simdjson_result<std::string> to_fractured_json_string(
const T& obj,
const fractured_json_options& opts = {},
size_t initial_capacity = string_builder::DEFAULT_INITIAL_CAPACITY) {
// Step 1: Serialize to minified JSON
std::string formatted;
auto error = to_json_string(obj, initial_capacity).get(formatted);
if (error) {
return error;
}
// Step 2: Reformat with FracturedJson
return fractured_json_string(formatted, opts);
}
/**
* Extract specific fields from an object and format with FracturedJson.
*
* Example:
* struct User { int id; std::string name; std::string email; bool active; };
* User user{1, "Alice", "alice@example.com", true};
* auto result = extract_fractured_json<"id", "name">(user);
* // result.value() == "{ \"id\": 1, \"name\": \"Alice\" }"
*
* @param obj The object to serialize
* @param opts FracturedJson formatting options
* @param initial_capacity Initial buffer capacity for serialization
* @return The formatted JSON string containing only the specified fields
*/
template<constevalutil::fixed_string... FieldNames, typename T>
requires(std::is_class_v<T> && (sizeof...(FieldNames) > 0))
simdjson_warn_unused simdjson_result<std::string> extract_fractured_json(
const T& obj,
const fractured_json_options& opts = {},
size_t initial_capacity = string_builder::DEFAULT_INITIAL_CAPACITY) {
// Step 1: Extract fields to minified JSON
std::string formatted;
auto error = extract_from<FieldNames...>(obj, initial_capacity).get(formatted);
if (error) {
return error;
}
// Step 2: Reformat with FracturedJson
return fractured_json_string(formatted, opts);
}
} // namespace builder
} // namespace SIMDJSON_IMPLEMENTATION
// Global namespace convenience functions
/**
* Serialize an object to a FracturedJson-formatted string.
* Global namespace version for convenience.
*/
template <class T>
simdjson_warn_unused simdjson_result<std::string> to_fractured_json_string(
const T& obj,
const fractured_json_options& opts = {},
size_t initial_capacity = SIMDJSON_IMPLEMENTATION::builder::string_builder::DEFAULT_INITIAL_CAPACITY) {
return SIMDJSON_IMPLEMENTATION::builder::to_fractured_json_string(obj, opts, initial_capacity);
}
/**
* Extract specific fields from an object and format with FracturedJson.
* Global namespace version for convenience.
*/
template<constevalutil::fixed_string... FieldNames, typename T>
requires(std::is_class_v<T> && (sizeof...(FieldNames) > 0))
simdjson_warn_unused simdjson_result<std::string> extract_fractured_json(
const T& obj,
const fractured_json_options& opts = {},
size_t initial_capacity = SIMDJSON_IMPLEMENTATION::builder::string_builder::DEFAULT_INITIAL_CAPACITY) {
return SIMDJSON_IMPLEMENTATION::builder::extract_fractured_json<FieldNames...>(obj, opts, initial_capacity);
}
} // namespace simdjson
#endif // SIMDJSON_STATIC_REFLECTION
#endif // SIMDJSON_GENERIC_FRACTURED_JSON_BUILDER_H
@@ -1,7 +1,3 @@
/**
* This file is part of the builder API. It is temporarily in the ondemand directory
* but we will move it to a builder directory later.
*/
#ifndef SIMDJSON_GENERIC_BUILDER_H
#ifndef SIMDJSON_CONDITIONAL_INCLUDE
@@ -1,7 +1,3 @@
/**
* This file is part of the builder API. It is temporarily in the ondemand
* directory but we will move it to a builder directory later.
*/
#include <array>
#include <cstring>
#include <type_traits>
@@ -519,8 +515,8 @@ simdjson_inline void string_builder::append(const T &opt) {
template <typename T>
requires(require_custom_serialization<T>)
simdjson_inline void string_builder::append(const T &val) {
serialize(*this, val);
simdjson_inline void string_builder::append(T &&val) {
serialize(*this, std::forward<T>(val));
}
template <typename T>
@@ -534,11 +530,11 @@ simdjson_inline void string_builder::append(const T &value) {
#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS
// 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 && !require_custom_serialization<R>)
simdjson_inline void string_builder::append(const R &range) noexcept {
auto it = std::ranges::begin(range);
auto end = std::ranges::end(range);
if constexpr (concepts::is_pair<typename R::value_type>) {
if constexpr (concepts::is_pair<std::ranges::range_value_t<R>>) {
start_object();
if (it == end) {
@@ -1,7 +1,3 @@
/**
* This file is part of the builder API. It is temporarily in the ondemand directory
* but we will move it to a builder directory later.
*/
#ifndef SIMDJSON_GENERIC_STRING_BUILDER_H
#ifndef SIMDJSON_CONDITIONAL_INCLUDE
@@ -24,9 +20,8 @@ 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);
constexpr void operator()(SIMDJSON_IMPLEMENTATION::builder::string_builder& b, T&& obj) const{
return tag_invoke(*this, b, std::forward<T>(obj));
}
@@ -165,7 +160,7 @@ public:
template <typename T>
requires(require_custom_serialization<T>)
simdjson_inline void append(const T &val);
simdjson_inline void append(T &&val);
// Support for string-like types
template <typename T>
@@ -176,7 +171,7 @@ public:
#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS
// 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 && !require_custom_serialization<R>)
simdjson_inline void append(const R &range) noexcept;
#endif
/**
@@ -301,4 +296,4 @@ simdjson_warn_unused simdjson_error to_json(const Z &z, std::string &s, size_t i
} // namespace simdjson
#endif // SIMDJSON_GENERIC_STRING_BUILDER_H
#endif // SIMDJSON_GENERIC_STRING_BUILDER_H
@@ -138,6 +138,9 @@ struct implementation_simdjson_result_base {
*/
simdjson_inline T&& value_unsafe() && noexcept;
using value_type = T;
using error_type = error_code;
protected:
/** users should never directly access first and second. **/
T first{}; /** Users should never directly access 'first'. **/
@@ -1,4 +1,4 @@
#if defined(SIMDJSON_CONDITIONAL_INCLUDE) && !defined(SIMDJSON_GENERIC_ONDEMAND_DEPENDENCIES_H)
#if defined(SIMDJSON_CONDITIONAL_INCLUDE) && !defined(SIMDJSON_GENERIC_BUILDER_DEPENDENCIES_H)
#error simdjson/generic/ondemand/dependencies.h must be included before simdjson/generic/ondemand/amalgamated.h!
#endif
@@ -14,9 +14,6 @@
#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"
@@ -44,13 +41,9 @@
#include "simdjson/generic/ondemand/object_iterator-inl.h"
#include "simdjson/generic/ondemand/parser-inl.h"
#include "simdjson/generic/ondemand/raw_json_string-inl.h"
#include "simdjson/generic/ondemand/serialization-inl.h"
#include "simdjson/generic/ondemand/token_iterator-inl.h"
#include "simdjson/generic/ondemand/value_iterator-inl.h"
// JSON builder inline definitions
#include "simdjson/generic/ondemand/json_string_builder-inl.h"
#include "simdjson/generic/ondemand/json_builder.h"
#include "simdjson/generic/ondemand/serialization-inl.h"
// JSON path accessor (compile-time) - must be after inline definitions
#include "simdjson/generic/ondemand/compile_time_accessors.h"
@@ -17,6 +17,10 @@ simdjson_inline array_iterator::array_iterator(const value_iterator &_iter) noex
{}
simdjson_inline simdjson_result<value> array_iterator::operator*() noexcept {
#if SIMDJSON_DEVELOPMENT_CHECKS
SIMDJSON_ASSUME(!has_been_referenced);
has_been_referenced = true;
#endif
if (iter.error()) { iter.abandon(); return iter.error(); }
return value(iter.child());
}
@@ -27,6 +31,9 @@ simdjson_inline bool array_iterator::operator!=(const array_iterator &) const no
return iter.is_open();
}
simdjson_inline array_iterator &array_iterator::operator++() noexcept {
#if SIMDJSON_DEVELOPMENT_CHECKS
has_been_referenced = false;
#endif
error_code error;
// PERF NOTE this is a safety rail ... users should exit loops as soon as they receive an error, so we'll never get here.
// However, it does not seem to make a perf difference, so we add it out of an abundance of caution.
@@ -2,6 +2,7 @@
#ifndef SIMDJSON_CONDITIONAL_INCLUDE
#define SIMDJSON_GENERIC_ONDEMAND_ARRAY_ITERATOR_H
#include <iterator>
#include "simdjson/generic/implementation_simdjson_result_base.h"
#include "simdjson/generic/ondemand/base.h"
#include "simdjson/generic/ondemand/value_iterator.h"
@@ -17,11 +18,17 @@ namespace ondemand {
*
* This is an input_iterator, meaning:
* - It is forward-only
* - * must be called exactly once per element.
* - * must be called at most once per element.
* - ++ must be called exactly once in between each * (*, ++, *, ++, * ...)
*/
class array_iterator {
public:
using iterator_category = std::input_iterator_tag;
using value_type = simdjson_result<value>;
using difference_type = std::ptrdiff_t;
using pointer = void;
using reference = value_type;
/** Create a new, invalid array iterator. */
simdjson_inline array_iterator() noexcept = default;
@@ -65,6 +72,9 @@ public:
simdjson_warn_unused simdjson_inline bool at_end() const noexcept;
private:
#if SIMDJSON_DEVELOPMENT_CHECKS
bool has_been_referenced{false};
#endif
value_iterator iter{};
simdjson_inline array_iterator(const value_iterator &iter) noexcept;
@@ -82,6 +92,12 @@ namespace simdjson {
template<>
struct simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::array_iterator> : public SIMDJSON_IMPLEMENTATION::implementation_simdjson_result_base<SIMDJSON_IMPLEMENTATION::ondemand::array_iterator> {
using iterator_category = std::input_iterator_tag;
using value_type = simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::value>;
using difference_type = std::ptrdiff_t;
using pointer = void;
using reference = value_type;
simdjson_inline simdjson_result(SIMDJSON_IMPLEMENTATION::ondemand::array_iterator &&value) noexcept; ///< @private
simdjson_inline simdjson_result(error_code error) noexcept; ///< @private
simdjson_inline simdjson_result() noexcept = default;
@@ -8,7 +8,6 @@
// Internal headers needed for ondemand generics.
// All includes not under simdjson/generic/ondemand must be here!
// Otherwise, amalgamation will fail.
#include "simdjson/concepts.h"
#include "simdjson/dom/base.h" // for MINIMAL_DOCUMENT_CAPACITY
#include "simdjson/implementation.h"
#include "simdjson/padded_string.h"
+5 -2
View File
@@ -403,7 +403,9 @@ public:
simdjson_inline simdjson_result<array_iterator> end() & noexcept;
/**
* Look up a field by name on an object (order-sensitive).
* Look up a field by name on an object (order-sensitive). By order-sensitive, we mean that
* fields must be accessed in the order they appear in the JSON text (although you can
* skip fields). See find_field_unordered() and operator[] for an order-insensitive version.
*
* The following code reads z, then y, then x, and thus will not retrieve x or y if fed the
* JSON `{ "x": 1, "y": 2, "z": 3 }`:
@@ -447,7 +449,8 @@ public:
* missing case has a non-cache-friendly bump and lots of extra scanning, especially if the object
* in question is large. The fact that the extra code is there also bumps the executable size.
*
* It is the default, however, because it would be highly surprising (and hard to debug) if the
* We default operator[] on find_field_unordered() for convenience.
* It is the default because it would be highly surprising (and hard to debug) if the
* default behavior failed to look up a field just because it was in the wrong order--and many
* APIs assume this. Therefore, you must be explicit if you want to treat objects as out of order.
*
@@ -215,11 +215,10 @@ simdjson_inline void json_iterator::assert_more_tokens(uint32_t required_tokens)
}
simdjson_inline void json_iterator::assert_valid_position(token_position position) const noexcept {
(void)position; // Suppress unused parameter warning
#ifndef SIMDJSON_CLANG_VISUAL_STUDIO
SIMDJSON_ASSUME( position >= &parser->implementation->structural_indexes[0] );
SIMDJSON_ASSUME( position < &parser->implementation->structural_indexes[parser->implementation->n_structural_indexes] );
#else
(void)position; // Suppress unused parameter warning
#endif
}
@@ -358,7 +357,11 @@ simdjson_inline token_position json_iterator::position() const noexcept {
simdjson_inline simdjson_result<std::string_view> json_iterator::unescape(raw_json_string in, bool allow_replacement) noexcept {
#if SIMDJSON_DEVELOPMENT_CHECKS
auto result = parser->unescape(in, _string_buf_loc, allow_replacement);
#if !defined(SIMDJSON_VISUAL_STUDIO) && !defined(SIMDJSON_CLANG_VISUAL_STUDIO)
// Under Visual Studio, the next SIMDJSON_ASSUME fails with: the argument
// has side effects that will be discarded.
SIMDJSON_ASSUME(!parser->string_buffer_overflow(_string_buf_loc));
#endif // !defined(SIMDJSON_VISUAL_STUDIO) && !defined(SIMDJSON_CLANG_VISUAL_STUDIO)
return result;
#else
return parser->unescape(in, _string_buf_loc, allow_replacement);
@@ -368,7 +371,11 @@ simdjson_inline simdjson_result<std::string_view> json_iterator::unescape(raw_js
simdjson_inline simdjson_result<std::string_view> json_iterator::unescape_wobbly(raw_json_string in) noexcept {
#if SIMDJSON_DEVELOPMENT_CHECKS
auto result = parser->unescape_wobbly(in, _string_buf_loc);
#if !defined(SIMDJSON_VISUAL_STUDIO) && !defined(SIMDJSON_CLANG_VISUAL_STUDIO)
// Under Visual Studio, the next SIMDJSON_ASSUME fails with: the argument
// has side effects that will be discarded.
SIMDJSON_ASSUME(!parser->string_buffer_overflow(_string_buf_loc));
#endif // !defined(SIMDJSON_VISUAL_STUDIO) && !defined(SIMDJSON_CLANG_VISUAL_STUDIO)
return result;
#else
return parser->unescape_wobbly(in, _string_buf_loc);
+12 -2
View File
@@ -27,10 +27,19 @@ public:
*/
simdjson_inline object() noexcept = default;
/**
* Get an iterator to the start of the object. We recommend using a range-based for loop.
*
* Using the iterator directly is also possible but error-prone and discouraged. In particular,
* you must dereference the iterator exactly once per iteration (before calling '++').
* Doing otherwise is unsafe and may lead to errors. You are responsible for ensuring
*/
simdjson_inline simdjson_result<object_iterator> begin() noexcept;
simdjson_inline simdjson_result<object_iterator> end() noexcept;
/**
* Look up a field by name on an object (order-sensitive).
* Look up a field by name on an object (order-sensitive). By order-sensitive, we mean that
* fields must be accessed in the order they appear in the JSON text (although you can
* skip fields). See find_field_unordered() and operator[] for an order-insensitive version.
*
* The following code reads z, then y, then x, and thus will not retrieve x or y if fed the
* JSON `{ "x": 1, "y": 2, "z": 3 }`:
@@ -78,7 +87,8 @@ public:
* missing case has a non-cache-friendly bump and lots of extra scanning, especially if the object
* in question is large. The fact that the extra code is there also bumps the executable size.
*
* It is the default, however, because it would be highly surprising (and hard to debug) if the
* We default operator[] on find_field_unordered() for convenience.
* It is the default because it would be highly surprising (and hard to debug) if the
* default behavior failed to look up a field just because it was in the wrong order--and many
* APIs assume this. Therefore, you must be explicit if you want to treat objects as out of order.
*
@@ -21,6 +21,11 @@ simdjson_inline object_iterator::object_iterator(const value_iterator &_iter) no
{}
simdjson_inline simdjson_result<field> object_iterator::operator*() noexcept {
#if SIMDJSON_DEVELOPMENT_CHECKS
// We must call * once per iteration.
SIMDJSON_ASSUME(!has_been_referenced);
has_been_referenced = true;
#endif
error_code error = iter.error();
if (error) { iter.abandon(); return error; }
auto result = field::start(iter);
@@ -39,6 +44,11 @@ simdjson_inline bool object_iterator::operator!=(const object_iterator &) const
SIMDJSON_PUSH_DISABLE_WARNINGS
SIMDJSON_DISABLE_STRICT_OVERFLOW_WARNING
simdjson_inline object_iterator &object_iterator::operator++() noexcept {
#if SIMDJSON_DEVELOPMENT_CHECKS
// Before calling ++, we must have called *.
SIMDJSON_ASSUME(has_been_referenced);
has_been_referenced = false;
#endif
// TODO this is a safety rail ... users should exit loops as soon as they receive an error.
// Nonetheless, let's see if performance is OK with this if statement--the compiler may give it to us for free.
if (!iter.is_open()) { return *this; } // Iterator will be released if there is an error
@@ -32,9 +32,14 @@ public:
// Assumes it's being compared with the end. true if depth >= iter->depth.
simdjson_inline bool operator!=(const object_iterator &) const noexcept;
// Checks for ']' and ','
// YOU MUST NOT CALL THIS IF operator* YIELDED AN ERROR.
// YOU MUST NOT CALL THIS WITHOUT A CORRESPONDING operator* CALL.
simdjson_inline object_iterator &operator++() noexcept;
private:
#if SIMDJSON_DEVELOPMENT_CHECKS
bool has_been_referenced{false};
#endif
/**
* The underlying JSON iterator.
*
@@ -10,7 +10,7 @@
#include "simdjson/generic/ondemand/serialization.h"
#include "simdjson/generic/ondemand/value.h"
#if SIMDJSON_STATIC_REFLECTION
#include "simdjson/generic/ondemand/json_builder.h"
#include "simdjson/generic/builder/json_builder.h"
#endif
#endif // SIMDJSON_CONDITIONAL_INCLUDE
+15 -6
View File
@@ -198,14 +198,17 @@ public:
* simdjson::ondemand::document doc = parser.iterate(json);
* auto view = doc["deviceId"].get_string(true);
*
* @returns An UTF-8 string. The string is stored in the parser and will be invalidated the next
* time it parses a document or when it is destroyed.
* @returns An UTF-8 string. The string is stored in the parser when escaping was needed
* and will be invalidated the next
* time it parses a document or when it is destroyed. If no escaping was needed,
* the string_view points directly into the original JSON buffer.
* @returns INCORRECT_TYPE if the JSON value is not a string.
*/
simdjson_inline simdjson_result<std::string_view> get_string(bool allow_replacement = false) noexcept;
/**
* Attempts to fill the provided std::string reference with the parsed value of the current string.
* The data is stored into the provided std::string instance.
*
* The string is guaranteed to be valid UTF-8.
*
@@ -395,7 +398,9 @@ public:
*/
simdjson_inline simdjson_result<value> at(size_t index) noexcept;
/**
* Look up a field by name on an object (order-sensitive).
* Look up a field by name on an object (order-sensitive). By order-sensitive, we mean that
* fields must be accessed in the order they appear in the JSON text (although you can
* skip fields). See find_field_unordered() and operator[] for an order-insensitive version.
*
* The following code reads z, then y, then x, and thus will not retrieve x or y if fed the
* JSON `{ "x": 1, "y": 2, "z": 3 }`:
@@ -429,7 +434,8 @@ public:
* missing case has a non-cache-friendly bump and lots of extra scanning, especially if the object
* in question is large. The fact that the extra code is there also bumps the executable size.
*
* It is the default, however, because it would be highly surprising (and hard to debug) if the
* We default operator[] on find_field_unordered() for convenience.
* It is the default because it would be highly surprising (and hard to debug) if the
* default behavior failed to look up a field just because it was in the wrong order--and many
* APIs assume this. Therefore, you must be explicit if you want to treat objects as out of order.
*
@@ -776,7 +782,9 @@ public:
simdjson_inline simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::array_iterator> end() & noexcept;
/**
* Look up a field by name on an object (order-sensitive).
* Look up a field by name on an object (order-sensitive). By order-sensitive, we mean that
* fields must be accessed in the order they appear in the JSON text (although you can
* skip fields). See find_field_unordered() and operator[] for an order-insensitive version.
*
* The following code reads z, then y, then x, and thus will not retrieve x or y if fed the
* JSON `{ "x": 1, "y": 2, "z": 3 }`:
@@ -808,7 +816,8 @@ public:
* missing case has a non-cache-friendly bump and lots of extra scanning, especially if the object
* in question is large. The fact that the extra code is there also bumps the executable size.
*
* It is the default, however, because it would be highly surprising (and hard to debug) if the
* We default operator[] on find_field_unordered() for convenience.
* It is the default because it would be highly surprising (and hard to debug) if the
* default behavior failed to look up a field just because it was in the wrong order--and many
* APIs assume this. Therefore, you must be explicit if you want to treat objects as out of order.
*
@@ -94,7 +94,6 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::end_container()
simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_next_field() noexcept {
assert_at_next();
// It's illegal to call this unless there are more tokens: anything that ends in } or ] is
// obligated to verify there are more tokens if they are not the top level.
switch (*_json_iter->return_current_and_advance()) {
@@ -511,14 +510,49 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::parse
}
simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_string(bool allow_replacement) noexcept {
// Optimization strategy:
// We expect that most strings do not have escape characters, and most are short.
// So we can quickly check for backslashes and if there are none, we can just return a string_view
// into the original JSON buffer. There is no need to copy or unescape.
// Fast path: check for backslash in the string
// It may seem that this function is odd in that it scans the string even if a
// backslash is found early. However, we expect that in most strings there will be no backslash,
// so we optimize for that case. The compiler knows to expect a full scan and it can optimize for it.
auto has_backslash_fast = [](std::string_view s) noexcept {
for(const char c : s) {
if(c == '\\') {
return true;
}
}
return false;
};
std::string_view string_with_quotes(reinterpret_cast<const char*>(peek_start()), peek_start_length());
if(string_with_quotes.front() != '"') {
return incorrect_type_error("Not a string");
}
if(!has_backslash_fast(string_with_quotes)) {
// Find the ending quote
size_t len = string_with_quotes.size();
while(string_with_quotes[len - 1] != '"') {
len--;
}
// At this point len is 2 or more
return std::string_view(string_with_quotes.data() + 1, len - 2);
}
// Slow path: we have a backslash, so we need to unescape
return get_raw_json_string().unescape(json_iter(), allow_replacement);
}
template <typename string_type>
simdjson_warn_unused simdjson_inline error_code value_iterator::get_string(string_type& receiver, bool allow_replacement) noexcept {
std::string_view content;
auto err = get_string(allow_replacement).get(content);
if (err) { return err; }
// Save the string buffer location so that we can restore it after get_string
auto saved_string_buf_loc = _json_iter->string_buf_loc();
SIMDJSON_TRY(get_string(allow_replacement).get(content));
receiver = content;
// Restore the string buffer location, effectively discarding any temporary string storage
_json_iter->string_buf_loc() = saved_string_buf_loc;
return SUCCESS;
}
simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_wobbly_string() noexcept {
@@ -653,14 +687,19 @@ simdjson_inline simdjson_result<number> value_iterator::get_root_number(bool che
return num;
}
simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_root_string(bool check_trailing, bool allow_replacement) noexcept {
// We could optimize for the no-escape case here as well, but root strings
// are less common so we do the simple thing for now.
return get_root_raw_json_string(check_trailing).unescape(json_iter(), allow_replacement);
}
template <typename string_type>
simdjson_warn_unused simdjson_inline error_code value_iterator::get_root_string(string_type& receiver, bool check_trailing, bool allow_replacement) noexcept {
std::string_view content;
auto err = get_root_string(check_trailing, allow_replacement).get(content);
if (err) { return err; }
// Save the string buffer location so that we can restore it after get_string
auto saved_string_buf_loc = _json_iter->string_buf_loc();
SIMDJSON_TRY(get_root_string(check_trailing, allow_replacement).get(content));
receiver = content;
// Restore the string buffer location, effectively discarding any temporary string storage
_json_iter->string_buf_loc() = saved_string_buf_loc;
return SUCCESS;
}
simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_root_wobbly_string(bool check_trailing) noexcept {
@@ -967,6 +1006,9 @@ simdjson_inline bool value_iterator::is_at_key() const noexcept {
// Keys are at the same depth as the object.
// Note here that we could be safer and check that we are within an object,
// but we do not.
//
// As long as we are at the object's depth, in a valid document,
// we will only ever be at { , : or the actual string key: ".
return _depth == _json_iter->_depth && *_json_iter->peek() == '"';
}
@@ -472,6 +472,7 @@ protected:
friend class document;
friend class object;
friend class object_iterator;
friend class array;
friend class value;
friend class field;
+8
View File
@@ -0,0 +1,8 @@
#ifndef SIMDJSON_HASWELL_BUILDER_H
#define SIMDJSON_HASWELL_BUILDER_H
#include "simdjson/haswell/begin.h"
#include "simdjson/generic/builder/amalgamated.h"
#include "simdjson/haswell/end.h"
#endif // SIMDJSON_HASWELL_BUILDER_H
+1
View File
@@ -300,6 +300,7 @@ namespace simd {
static constexpr int NUM_CHUNKS = 64 / sizeof(simd8<T>);
static_assert(NUM_CHUNKS == 2, "Haswell kernel should use two registers per 64-byte block.");
const simd8<T> chunks[NUM_CHUNKS];
template<int idx> simd8<uint8_t> get() const { return idx < NUM_CHUNKS ? chunks[idx] : simd8<T>(); }
simd8x64(const simd8x64<T>& o) = delete; // no copy allowed
simd8x64<T>& operator=(const simd8<T>& other) = delete; // no assignment allowed
+8
View File
@@ -0,0 +1,8 @@
#ifndef SIMDJSON_ICELAKE_BUILDER_H
#define SIMDJSON_ICELAKE_BUILDER_H
#include "simdjson/icelake/begin.h"
#include "simdjson/generic/builder/amalgamated.h"
#include "simdjson/icelake/end.h"
#endif // SIMDJSON_ICELAKE_BUILDER_H
+1
View File
@@ -322,6 +322,7 @@ namespace simd {
static constexpr int NUM_CHUNKS = 64 / sizeof(simd8<T>);
static_assert(NUM_CHUNKS == 1, "Icelake kernel should use one register per 64-byte block.");
const simd8<T> chunks[NUM_CHUNKS];
template<int idx> simd8<uint8_t> get() const { return idx < NUM_CHUNKS ? chunks[idx] : simd8<T>(); }
simd8x64(const simd8x64<T>& o) = delete; // no copy allowed
simd8x64<T>& operator=(const simd8<T>& other) = delete; // no assignment allowed
+14 -5
View File
@@ -12,6 +12,8 @@
#define SIMDJSON_IMPLEMENTATION_ID_westmere 6
#define SIMDJSON_IMPLEMENTATION_ID_lsx 7
#define SIMDJSON_IMPLEMENTATION_ID_lasx 8
//#define SIMDJSON_IMPLEMENTATION_ID_rvv 9
#define SIMDJSON_IMPLEMENTATION_ID_rvv_vls 10
#define SIMDJSON_IMPLEMENTATION_ID_FOR(IMPL) SIMDJSON_CAT(SIMDJSON_IMPLEMENTATION_ID_, IMPL)
#define SIMDJSON_IMPLEMENTATION_ID SIMDJSON_IMPLEMENTATION_ID_FOR(SIMDJSON_IMPLEMENTATION)
@@ -113,22 +115,27 @@
#endif
#ifndef SIMDJSON_IMPLEMENTATION_LASX
#define SIMDJSON_IMPLEMENTATION_LASX (SIMDJSON_IS_LOONGARCH64 && __loongarch_asx)
#define SIMDJSON_IMPLEMENTATION_LASX (SIMDJSON_IS_LSX)
#endif
#define SIMDJSON_CAN_ALWAYS_RUN_LASX (SIMDJSON_IMPLEMENTATION_LASX)
#define SIMDJSON_CAN_ALWAYS_RUN_LASX (SIMDJSON_IS_LASX)
#ifndef SIMDJSON_IMPLEMENTATION_LSX
#if SIMDJSON_CAN_ALWAYS_RUN_LASX
#define SIMDJSON_IMPLEMENTATION_LSX 0
#else
#define SIMDJSON_IMPLEMENTATION_LSX (SIMDJSON_IS_LOONGARCH64 && __loongarch_sx)
#define SIMDJSON_IMPLEMENTATION_LSX (SIMDJSON_IS_LSX)
#endif
#endif
#define SIMDJSON_CAN_ALWAYS_RUN_LSX (SIMDJSON_IMPLEMENTATION_LSX)
#define SIMDJSON_CAN_ALWAYS_RUN_RVV_VLS SIMDJSON_IS_RVV_VLS
#ifndef SIMDJSON_IMPLEMENTATION_RVV_VLS
#define SIMDJSON_IMPLEMENTATION_RVV_VLS SIMDJSON_CAN_ALWAYS_RUN_RVV_VLS
#endif
// Default Fallback to on unless a builtin implementation has already been selected.
#ifndef SIMDJSON_IMPLEMENTATION_FALLBACK
#if SIMDJSON_CAN_ALWAYS_RUN_ARM64 || SIMDJSON_CAN_ALWAYS_RUN_ICELAKE || SIMDJSON_CAN_ALWAYS_RUN_HASWELL || SIMDJSON_CAN_ALWAYS_RUN_WESTMERE || SIMDJSON_CAN_ALWAYS_RUN_PPC64 || SIMDJSON_CAN_ALWAYS_RUN_LSX || SIMDJSON_CAN_ALWAYS_RUN_LASX
#if SIMDJSON_CAN_ALWAYS_RUN_ARM64 || SIMDJSON_CAN_ALWAYS_RUN_ICELAKE || SIMDJSON_CAN_ALWAYS_RUN_HASWELL || SIMDJSON_CAN_ALWAYS_RUN_WESTMERE || SIMDJSON_CAN_ALWAYS_RUN_PPC64 || SIMDJSON_CAN_ALWAYS_RUN_LSX || SIMDJSON_CAN_ALWAYS_RUN_LASX || SIMDJSON_CAN_ALWAYS_RUN_RVV_VLS
// if anything at all except fallback can always run, then disable fallback.
#define SIMDJSON_IMPLEMENTATION_FALLBACK 0
#else
@@ -154,6 +161,8 @@
#define SIMDJSON_BUILTIN_IMPLEMENTATION lsx
#elif SIMDJSON_CAN_ALWAYS_RUN_LASX
#define SIMDJSON_BUILTIN_IMPLEMENTATION lasx
#elif SIMDJSON_CAN_ALWAYS_RUN_RVV_VLS
#define SIMDJSON_BUILTIN_IMPLEMENTATION rvv_vls
#elif SIMDJSON_CAN_ALWAYS_RUN_FALLBACK
#define SIMDJSON_BUILTIN_IMPLEMENTATION fallback
#else
@@ -165,4 +174,4 @@
#define SIMDJSON_BUILTIN_IMPLEMENTATION_ID SIMDJSON_IMPLEMENTATION_ID_FOR(SIMDJSON_BUILTIN_IMPLEMENTATION)
#define SIMDJSON_BUILTIN_IMPLEMENTATION_IS(IMPL) SIMDJSON_BUILTIN_IMPLEMENTATION_ID == SIMDJSON_IMPLEMENTATION_ID_FOR(IMPL)
#endif // SIMDJSON_IMPLEMENTATION_DETECTION_H
#endif // SIMDJSON_IMPLEMENTATION_DETECTION_H
@@ -0,0 +1,161 @@
#ifndef SIMDJSON_INTERNAL_FRACTURED_FORMATTER_H
#define SIMDJSON_INTERNAL_FRACTURED_FORMATTER_H
#include "simdjson/dom/serialization.h"
#include "simdjson/dom/fractured_json.h"
#include "simdjson/internal/json_structure_analyzer.h"
namespace simdjson {
namespace internal {
/**
* Fractured JSON formatter using CRTP pattern.
*
* This formatter intelligently chooses between different layout modes
* (inline, compact multiline, table, expanded) based on pre-computed
* structure metrics.
*/
class fractured_formatter : public base_formatter<fractured_formatter> {
public:
explicit fractured_formatter(const fractured_json_options& opts = {});
/** CRTP hook: print newline (context-aware) */
simdjson_inline void print_newline();
/** CRTP hook: print indentation */
simdjson_inline void print_indents(size_t depth);
/** CRTP hook: print space (context-aware) */
simdjson_inline void print_space();
/** Set the current layout mode */
void set_layout_mode(layout_mode mode);
/** Get the current layout mode */
layout_mode get_layout_mode() const;
/** Set current depth for formatting decisions */
void set_depth(size_t depth);
/** Get current depth */
size_t get_depth() const;
/** Track current line length for compact multiline decisions */
void track_line_length(size_t chars);
/** Reset line length (after newline) */
void reset_line_length();
/** Get current line length */
size_t get_line_length() const;
/** Check if we should break to a new line in compact mode */
bool should_break_line(size_t upcoming_length) const;
/** Get the options */
const fractured_json_options& options() const;
// Table formatting support
/** Begin a table row */
void begin_table_row();
/** End a table row */
void end_table_row();
/** Set column widths for table alignment */
void set_column_widths(const std::vector<size_t>& widths);
/** Get current column index in table mode */
size_t get_column_index() const;
/** Advance to next column */
void next_column();
/** Add padding to align with column width */
void align_to_column_width(size_t actual_width);
private:
fractured_json_options options_;
layout_mode current_layout_ = layout_mode::EXPANDED;
size_t current_depth_ = 0;
size_t current_line_length_ = 0;
// Table state
bool in_table_mode_ = false;
std::vector<size_t> column_widths_;
size_t current_column_ = 0;
};
/**
* Specialized string builder for fractured JSON formatting.
*
* This builder performs two passes:
* 1. Analyze the structure to compute metrics
* 2. Format using the metrics to make layout decisions
*/
class fractured_string_builder {
public:
fractured_string_builder(const fractured_json_options& opts = {});
/** Append a DOM element with fractured formatting */
void append(const dom::element& value);
/** Append a DOM array with fractured formatting */
void append(const dom::array& value);
/** Append a DOM object with fractured formatting */
void append(const dom::object& value);
/** Clear the builder */
simdjson_inline void clear();
/** Get the formatted string */
simdjson_inline std::string_view str() const;
private:
fractured_formatter format_;
structure_analyzer analyzer_;
fractured_json_options options_;
/** Format an element using pre-computed metrics */
void format_element(const dom::element& elem, const element_metrics& metrics, size_t depth);
/** Format an array with the appropriate layout */
void format_array(const dom::array& arr, const element_metrics& metrics, size_t depth);
/** Format an array inline: [1, 2, 3] */
void format_array_inline(const dom::array& arr, const element_metrics& metrics);
/** Format an array with compact multiline: multiple items per line */
void format_array_compact_multiline(const dom::array& arr, const element_metrics& metrics, size_t depth);
/** Format an array as a table */
void format_array_as_table(const dom::array& arr, const element_metrics& metrics, size_t depth);
/** Format an array expanded: one item per line */
void format_array_expanded(const dom::array& arr, const element_metrics& metrics, size_t depth);
/** Format an object with the appropriate layout */
void format_object(const dom::object& obj, const element_metrics& metrics, size_t depth);
/** Format an object inline: {"a": 1, "b": 2} */
void format_object_inline(const dom::object& obj, const element_metrics& metrics);
/** Format an object expanded: one key per line */
void format_object_expanded(const dom::object& obj, const element_metrics& metrics, size_t depth);
/** Format a scalar value */
void format_scalar(const dom::element& elem);
/** Calculate column widths for table formatting */
std::vector<size_t> calculate_column_widths(const dom::array& arr,
const std::vector<std::string>& columns) const;
/** Measure the actual formatted length of a value (for alignment) */
size_t measure_value_length(const dom::element& elem) const;
};
} // namespace internal
} // namespace simdjson
#endif // SIMDJSON_INTERNAL_FRACTURED_FORMATTER_H
@@ -69,6 +69,8 @@ enum instruction_set {
AVX512VBMI2 = 0x10000,
LSX = 0x20000,
LASX = 0x40000,
//RVV = 0x80000,
RVV_VLS = 0x100000,
};
} // namespace internal
@@ -0,0 +1,169 @@
#ifndef SIMDJSON_INTERNAL_JSON_STRUCTURE_ANALYZER_H
#define SIMDJSON_INTERNAL_JSON_STRUCTURE_ANALYZER_H
#include "simdjson/dom/base.h"
#include "simdjson/dom/element.h"
#include "simdjson/dom/array.h"
#include "simdjson/dom/object.h"
#include "simdjson/dom/fractured_json.h"
#include "simdjson/internal/tape_type.h"
#include <vector>
#include <string>
#include <string_view>
#include <set>
namespace simdjson {
namespace internal {
/**
* Layout mode for fractured JSON formatting.
*/
enum class layout_mode {
INLINE, // Single line: [1, 2, 3] or {"a": 1}
COMPACT_MULTILINE, // Multiple items per line with breaks
TABLE, // Tabular format for arrays of similar objects
EXPANDED // Traditional multi-line with indentation
};
/**
* Metrics computed for a JSON element during structure analysis.
* These metrics drive layout decisions and contain child metrics for recursive formatting.
*/
struct element_metrics {
/** Nesting depth score (0 = scalar, 1 = flat container, etc.) */
size_t complexity = 0;
/** Estimated character length if rendered inline (minified + spaces) */
size_t estimated_inline_len = 0;
/** Number of direct children (0 for scalars) */
size_t child_count = 0;
/** Pre-computed: can this element be rendered inline? */
bool can_inline = false;
/** Is this an array where all elements have similar structure? */
bool is_uniform_array = false;
/** For uniform arrays of objects: the common keys */
std::vector<std::string> common_keys{};
/** Recommended layout mode based on analysis */
layout_mode recommended_layout = layout_mode::EXPANDED;
/** Child metrics for arrays and objects (in order of iteration) */
std::vector<element_metrics> children{};
};
/**
* Analyzes JSON structure to compute metrics for formatting decisions.
*
* The analyzer performs a single pass over the DOM to compute:
* - Complexity (nesting depth)
* - Estimated inline length
* - Array uniformity for table detection
*
* Metrics are stored hierarchically with child metrics embedded in parent metrics,
* enabling efficient lookup during formatting without address-based caching.
*/
class structure_analyzer {
public:
/** Default constructor */
structure_analyzer() : current_opts_(nullptr) {}
/** Copy constructor - deleted since class has pointer member */
structure_analyzer(const structure_analyzer&) = delete;
/** Copy assignment - deleted since class has pointer member */
structure_analyzer& operator=(const structure_analyzer&) = delete;
/** Move constructor */
structure_analyzer(structure_analyzer&&) = default;
/** Move assignment */
structure_analyzer& operator=(structure_analyzer&&) = default;
/**
* Analyze a DOM element and compute metrics.
* @param elem The element to analyze
* @param opts Formatting options that affect metric computation
* @return Metrics for the root element (with child metrics embedded)
*/
element_metrics analyze(const dom::element& elem,
const fractured_json_options& opts);
/**
* Clear state.
*/
void clear();
/**
* Analyze an array element directly (for standalone array formatting).
* @param arr The array to analyze
* @param opts Formatting options
* @return Metrics for the array
*/
element_metrics analyze_array(const dom::array& arr,
const fractured_json_options& opts);
/**
* Analyze an object element directly (for standalone object formatting).
* @param obj The object to analyze
* @param opts Formatting options
* @return Metrics for the object
*/
element_metrics analyze_object(const dom::object& obj,
const fractured_json_options& opts);
private:
const fractured_json_options* current_opts_ = nullptr;
/** Recursive analysis implementation */
element_metrics analyze_element(const dom::element& elem, size_t depth);
/** Analyze scalar values (strings, numbers, booleans, null) */
element_metrics analyze_scalar(const dom::element& elem);
/** Analyze an array element */
element_metrics analyze_array(const dom::array& arr, size_t depth);
/** Analyze an object element */
element_metrics analyze_object(const dom::object& obj, size_t depth);
/** Estimate inline length for a string (including quotes and escaping) */
size_t estimate_string_length(std::string_view s) const;
/** Estimate inline length for a number */
size_t estimate_number_length(double d) const;
size_t estimate_number_length(int64_t i) const;
size_t estimate_number_length(uint64_t u) const;
/**
* Check if an array contains uniform objects suitable for table formatting.
* @param arr The array to check
* @param common_keys Output: keys common to all objects
* @return true if the array is suitable for table formatting
*/
bool check_array_uniformity(const dom::array& arr,
std::vector<std::string>& common_keys) const;
/**
* Compute similarity between two objects.
* @return Fraction of keys that are common (0.0 to 1.0)
*/
double compute_object_similarity(const dom::object& a,
const dom::object& b) const;
/**
* Decide the recommended layout mode based on metrics and options.
*/
layout_mode decide_layout(const element_metrics& metrics,
size_t depth,
size_t available_width) const;
};
} // namespace internal
} // namespace simdjson
#endif // SIMDJSON_INTERNAL_JSON_STRUCTURE_ANALYZER_H
+9
View File
@@ -1,4 +1,11 @@
#define SIMDJSON_IMPLEMENTATION lasx
#include <lsxintrin.h> // This is a hack. We should not need to put this include here.
#if SIMDJSON_CAN_ALWAYS_RUN_LASX
// nothing needed.
#else
SIMDJSON_TARGET_REGION("lasx,lsx")
#endif
#include "simdjson/lasx/base.h"
#include "simdjson/lasx/intrinsics.h"
#include "simdjson/lasx/bitmanipulation.h"
@@ -8,3 +15,5 @@
#include "simdjson/lasx/stringparsing_defs.h"
#define SIMDJSON_SKIP_BACKSLASH_SHORT_CIRCUIT 1
+8
View File
@@ -0,0 +1,8 @@
#ifndef SIMDJSON_LASX_BUILDER_H
#define SIMDJSON_LASX_BUILDER_H
#include "simdjson/lasx/begin.h"
#include "simdjson/generic/builder/amalgamated.h"
#include "simdjson/lasx/end.h"
#endif // SIMDJSON_LASX_BUILDER_H
+7
View File
@@ -4,3 +4,10 @@
#undef SIMDJSON_SKIP_BACKSLASH_SHORT_CIRCUIT
#undef SIMDJSON_IMPLEMENTATION
#if SIMDJSON_CAN_ALWAYS_RUN_LASX
// nothing needed.
#else
SIMDJSON_UNTARGET_REGION
#endif
+1 -2
View File
@@ -5,8 +5,7 @@
#include "simdjson/lasx/base.h"
#endif // SIMDJSON_CONDITIONAL_INCLUDE
// This should be the correct header whether
// you use visual studio or other compilers.
#include <lsxintrin.h>
#include <lasxintrin.h>
static_assert(sizeof(__m256i) <= simdjson::SIMDJSON_PADDING, "insufficient padding for LoongArch ASX");
+1
View File
@@ -303,6 +303,7 @@ namespace simd {
static constexpr int NUM_CHUNKS = 64 / sizeof(simd8<T>);
static_assert(NUM_CHUNKS == 2, "LASX kernel should use two registers per 64-byte block.");
const simd8<T> chunks[NUM_CHUNKS];
template<int idx> simd8<uint8_t> get() const { return idx < NUM_CHUNKS ? chunks[idx] : simd8<T>(); }
simd8x64(const simd8x64<T>& o) = delete; // no copy allowed
simd8x64<T>& operator=(const simd8<T>& other) = delete; // no assignment allowed
+1 -1
View File
@@ -61,7 +61,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())
};
}
+8
View File
@@ -0,0 +1,8 @@
#ifndef SIMDJSON_LSX_BUILDER_H
#define SIMDJSON_LSX_BUILDER_H
#include "simdjson/lsx/begin.h"
#include "simdjson/generic/builder/amalgamated.h"
#include "simdjson/lsx/end.h"
#endif // SIMDJSON_LSX_BUILDER_H
-2
View File
@@ -5,8 +5,6 @@
#include "simdjson/lsx/base.h"
#endif // SIMDJSON_CONDITIONAL_INCLUDE
// This should be the correct header whether
// you use visual studio or other compilers.
#include <lsxintrin.h>
static_assert(sizeof(__m128i) <= simdjson::SIMDJSON_PADDING, "insufficient padding for LoongArch SX");
+1
View File
@@ -260,6 +260,7 @@ namespace simd {
static constexpr int NUM_CHUNKS = 64 / sizeof(simd8<T>);
static_assert(NUM_CHUNKS == 4, "LSX kernel should use four registers per 64-byte block.");
const simd8<T> chunks[NUM_CHUNKS];
template<int idx> simd8<uint8_t> get() const { return idx < NUM_CHUNKS ? chunks[idx] : simd8<T>(); }
simd8x64(const simd8x64<T>& o) = delete; // no copy allowed
simd8x64<T>& operator=(const simd8<T>& other) = delete; // no assignment allowed
+181
View File
@@ -8,6 +8,7 @@
#include "simdjson/padded_string_view-inl.h"
#include <climits>
#include <cwchar>
namespace simdjson {
namespace internal {
@@ -125,6 +126,33 @@ inline const char *padded_string::data() const noexcept { return data_ptr; }
inline char *padded_string::data() noexcept { return data_ptr; }
inline bool padded_string::append(const char *data, size_t length) noexcept {
if (length == 0) {
return true; // Nothing to append
}
size_t new_size = viable_size + length;
if (new_size < viable_size) {
// Overflow, cannot append
return false;
}
char *new_data_ptr = internal::allocate_padded_buffer(new_size);
if (new_data_ptr == nullptr) {
// Allocation failed, cannot append
return false;
}
// Copy existing data
if (viable_size > 0) {
std::memcpy(new_data_ptr, data_ptr, viable_size);
}
// Copy new data
std::memcpy(new_data_ptr + viable_size, data, length);
// Update
delete[] data_ptr;
data_ptr = new_data_ptr;
viable_size = new_size;
return true;
}
inline padded_string::operator std::string_view() const simdjson_lifetime_bound { return std::string_view(data(), length()); }
inline padded_string::operator padded_string_view() const noexcept simdjson_lifetime_bound {
@@ -185,6 +213,159 @@ inline simdjson_result<padded_string> padded_string::load(std::string_view filen
return s;
}
#if defined(_WIN32) && SIMDJSON_CPLUSPLUS17
inline simdjson_result<padded_string> padded_string::load(std::wstring_view filename) noexcept {
// Open the file using the wide characters
SIMDJSON_PUSH_DISABLE_WARNINGS
SIMDJSON_DISABLE_DEPRECATED_WARNING // Disable CRT_SECURE warning on MSVC: manually verified this is safe
std::FILE *fp = _wfopen(filename.data(), L"rb");
SIMDJSON_POP_DISABLE_WARNINGS
if (fp == nullptr) {
return IO_ERROR;
}
// Get the file size
int ret;
#if SIMDJSON_VISUAL_STUDIO && !SIMDJSON_IS_32BITS
ret = _fseeki64(fp, 0, SEEK_END);
#else
ret = std::fseek(fp, 0, SEEK_END);
#endif // _WIN64
if(ret < 0) {
std::fclose(fp);
return IO_ERROR;
}
#if SIMDJSON_VISUAL_STUDIO && !SIMDJSON_IS_32BITS
__int64 llen = _ftelli64(fp);
if(llen == -1L) {
std::fclose(fp);
return IO_ERROR;
}
#else
long llen = std::ftell(fp);
if((llen < 0) || (llen == LONG_MAX)) {
std::fclose(fp);
return IO_ERROR;
}
#endif
// Allocate the padded_string
size_t len = static_cast<size_t>(llen);
padded_string s(len);
if (s.data() == nullptr) {
std::fclose(fp);
return MEMALLOC;
}
// Read the padded_string
std::rewind(fp);
size_t bytes_read = std::fread(s.data(), 1, len, fp);
if (std::fclose(fp) != 0 || bytes_read != len) {
return IO_ERROR;
}
return s;
}
#endif
// padded_string_builder implementations
inline padded_string_builder::padded_string_builder() noexcept = default;
inline padded_string_builder::padded_string_builder(size_t new_capacity) noexcept {
if (new_capacity > 0) {
data = internal::allocate_padded_buffer(new_capacity);
if (data != nullptr) {
this->capacity = new_capacity;
}
}
}
inline padded_string_builder::padded_string_builder(padded_string_builder &&o) noexcept
: size(o.size), capacity(o.capacity), data(o.data) {
o.size = 0;
o.capacity = 0;
o.data = nullptr;
}
inline padded_string_builder &padded_string_builder::operator=(padded_string_builder &&o) noexcept {
if (this != &o) {
delete[] data;
size = o.size;
capacity = o.capacity;
data = o.data;
o.size = 0;
o.capacity = 0;
o.data = nullptr;
}
return *this;
}
inline padded_string_builder::~padded_string_builder() noexcept {
delete[] data;
}
inline bool padded_string_builder::append(const char *newdata, size_t length) noexcept {
if (length == 0) {
return true;
}
if (!reserve(length)) {
return false;
}
std::memcpy(data + size, newdata, length);
size += length;
return true;
}
inline bool padded_string_builder::append(std::string_view sv) noexcept {
return append(sv.data(), sv.size());
}
inline size_t padded_string_builder::length() const noexcept {
return size;
}
inline padded_string padded_string_builder::build() const noexcept {
return padded_string(data, size);
}
inline padded_string padded_string_builder::convert() noexcept {
padded_string result{};
result.data_ptr = data;
result.viable_size = size;
data = nullptr;
size = 0;
capacity = 0;
return result;
}
inline bool padded_string_builder::reserve(size_t additional) noexcept {
size_t needed = size + additional;
if (needed <= capacity) {
return true;
}
size_t new_capacity = needed;
// We are going to grow the capacity exponentially to avoid
// repeated allocations.
if (new_capacity < 4096) {
new_capacity *= 2;
} else {
new_capacity += new_capacity/2; // grow by 1.5x
}
char *new_data = internal::allocate_padded_buffer(new_capacity);
if (new_data == nullptr) {
return false; // Allocation failed
}
if (size > 0) {
std::memcpy(new_data, data, size);
}
delete[] data;
data = new_data;
capacity = new_capacity;
return true;
}
} // namespace simdjson
inline simdjson::padded_string operator ""_padded(const char *str, size_t len) {
+119
View File
@@ -98,6 +98,16 @@ struct padded_string final {
**/
char *data() noexcept;
/**
* Append data to the padded string. Return true on success, false on failure.
* The complexity is O(n) where n is the new size of the string. If you are
* doing multiple appends, consider using padded_string_builder for better performance.
*
* @param data the buffer to append
* @param length the number of bytes to append
*/
inline bool append(const char *data, size_t length) noexcept;
/**
* Create a std::string_view with the same content.
*/
@@ -127,7 +137,21 @@ struct padded_string final {
**/
inline static simdjson_result<padded_string> load(std::string_view path) noexcept;
#if defined(_WIN32) && SIMDJSON_CPLUSPLUS17
/**
* This function accepts a wide string path (UTF-16) and converts it to
* UTF-8 before loading the file. This allows windows users to work
* with unicode file paths without manually converting the paths every time.
*
* @return IO_ERROR on error, including conversion failures.
*
* @param path the path to the file as a wide string.
**/
inline static simdjson_result<padded_string> load(std::wstring_view path) noexcept;
#endif
private:
friend class padded_string_builder;
padded_string &operator=(const padded_string &o) = delete;
padded_string(const padded_string &o) = delete;
@@ -136,6 +160,101 @@ private:
}; // padded_string
/**
* Builder for constructing padded_string incrementally.
*
* This class allows efficient appending of data and then building a padded_string.
*/
class padded_string_builder {
public:
/**
* Create a new, empty padded string builder.
*/
inline padded_string_builder() noexcept;
/**
* Create a new padded string builder with initial capacity.
*
* @param capacity the initial capacity of the builder.
*/
inline padded_string_builder(size_t capacity) noexcept;
/**
* Move constructor.
*/
inline padded_string_builder(padded_string_builder &&o) noexcept;
/**
* Move assignment.
*/
inline padded_string_builder &operator=(padded_string_builder &&o) noexcept;
/**
* Copy constructor (deleted).
*/
padded_string_builder(const padded_string_builder &) = delete;
/**
* Copy assignment (deleted).
*/
padded_string_builder &operator=(const padded_string_builder &) = delete;
/**
* Destructor.
*/
inline ~padded_string_builder() noexcept;
/**
* Append data to the builder.
*
* @param newdata the buffer to append
* @param length the number of bytes to append
* @return true if the append succeeded, false if allocation failed
*/
inline bool append(const char *newdata, size_t length) noexcept;
/**
* Append a string view to the builder.
*
* @param sv the string view to append
* @return true if the append succeeded, false if allocation failed
*/
inline bool append(std::string_view sv) noexcept;
/**
* Get the current length of the built string.
*/
inline size_t length() const noexcept;
/**
* Build a padded_string from the current content. The builder's content
* is not modified. If you want to avoid the copy, use convert() instead.
*
* @return a padded_string containing a copy of the built content.
*/
inline padded_string build() const noexcept;
/**
* Convert the current content into a padded_string. The
* builder's content is emptied, the capacity is lost.
*
* @return a padded_string containing the built content.
*/
inline padded_string convert() noexcept;
private:
size_t size{0};
size_t capacity{0};
char *data{nullptr};
/**
* Ensure the builder has enough capacity.
*
* @param additional the additional capacity needed.
* @return true if the reservation succeeded, false if allocation failed
*/
inline bool reserve(size_t additional) noexcept;
};
/**
* Send padded_string instance to an output stream.
*
+20 -15
View File
@@ -45,24 +45,28 @@ 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
#if SIMDJSON_HAS_RVV_INTRINSICS && __riscv_vector && __riscv_v_min_vlen >= 128 && __riscv_v_elen >= 64
#define SIMDJSON_IS_RVV 1 // RISC-V V extension
#endif
// current toolchains don't support fixed-size SIMD types that don't match VLEN directly
#if __riscv_v_fixed_vlen >= 128 && __riscv_v_fixed_vlen <= 512
#define SIMDJSON_IS_RVV_VLS 1
#endif
#elif defined(__loongarch_lp64)
#define SIMDJSON_IS_LOONGARCH64 1
#if defined(__loongarch_sx) && defined(__loongarch_asx)
#define SIMDJSON_IS_LSX 1
#define SIMDJSON_IS_LASX 1 // We can always run both
#elif defined(__loongarch_sx)
#define SIMDJSON_IS_LSX 1
#endif
#elif defined(__PPC64__) || defined(_M_PPC64)
#define SIMDJSON_IS_PPC64 1
#if defined(__ALTIVEC__)
@@ -118,7 +122,7 @@ using std::size_t;
//
// We are going to use runtime dispatch.
#if SIMDJSON_IS_X86_64
#if defined(SIMDJSON_IS_X86_64) || defined(SIMDJSON_IS_LSX)
#ifdef __clang__
// clang does not have GCC push pop
// warning: clang attribute push can't be used within a namespace in clang up
@@ -135,7 +139,7 @@ using std::size_t;
#define SIMDJSON_UNTARGET_REGION _Pragma("GCC pop_options")
#endif // clang then gcc
#endif // x86
#endif // defined(SIMDJSON_IS_X86_64) || defined(SIMDJSON_IS_LSX)
// Default target region macros don't do anything.
#ifndef SIMDJSON_TARGET_REGION
@@ -204,7 +208,8 @@ using std::size_t;
#define simdjson_strncasecmp strncasecmp
#endif
#if defined(NDEBUG) || defined(__OPTIMIZE__) || (defined(_MSC_VER) && !defined(_DEBUG))
#if (defined(NDEBUG) || defined(__OPTIMIZE__) || (defined(_MSC_VER) && !defined(_DEBUG))) && !SIMDJSON_DEVELOPMENT_CHECKS
// If SIMDJSON_DEVELOPMENT_CHECKS is undefined or 0, we consider that we are in release mode.
// If NDEBUG is set, or __OPTIMIZE__ is set, or we are under MSVC in release mode,
// then do away with asserts and use __assume.
// We still recommend that our users set NDEBUG in release mode.
@@ -216,7 +221,7 @@ using std::size_t;
#define SIMDJSON_ASSUME(COND) do { if (!(COND)) __builtin_unreachable(); } while (0)
#endif
#else // defined(NDEBUG) || defined(__OPTIMIZE__) || (defined(_MSC_VER) && !defined(_DEBUG))
#else // defined(NDEBUG) || defined(__OPTIMIZE__) || (defined(_MSC_VER) && !defined(_DEBUG)) && !SIMDJSON_DEVELOPMENT_CHECKS
// This should only ever be enabled in debug mode.
#define SIMDJSON_UNREACHABLE() assert(0);
#define SIMDJSON_ASSUME(COND) assert(COND)
+8
View File
@@ -0,0 +1,8 @@
#ifndef SIMDJSON_PPC64_BUILDER_H
#define SIMDJSON_PPC64_BUILDER_H
#include "simdjson/ppc64/begin.h"
#include "simdjson/generic/builder/amalgamated.h"
#include "simdjson/ppc64/end.h"
#endif // SIMDJSON_PPC64_BUILDER_H
+1
View File
@@ -397,6 +397,7 @@ template <typename T> struct simd8x64 {
static_assert(NUM_CHUNKS == 4,
"PPC64 kernel should use four registers per 64-byte block.");
const simd8<T> chunks[NUM_CHUNKS];
template<int idx> simd8<uint8_t> get() const { return idx < NUM_CHUNKS ? chunks[idx] : simd8<T>(); }
simd8x64(const simd8x64<T> &o) = delete; // no copy allowed
simd8x64<T> &
+9
View File
@@ -0,0 +1,9 @@
#ifndef SIMDJSON_RVV_VLS_H
#define SIMDJSON_RVV_VLS_H
#include "simdjson/rvv-vls/begin.h"
#include "simdjson/generic/amalgamated.h"
#include "simdjson/rvv-vls/end.h"
#endif // SIMDJSON_RVV_VLS_H
+19
View File
@@ -0,0 +1,19 @@
#ifndef SIMDJSON_RVV_VLS_BASE_H
#define SIMDJSON_RVV_VLS_BASE_H
#ifndef SIMDJSON_CONDITIONAL_INCLUDE
#include "simdjson/base.h"
#endif // SIMDJSON_CONDITIONAL_INCLUDE
namespace simdjson {
/**
* RVV-VLS implementation.
*/
namespace rvv_vls {
class implementation;
} // namespace rvv_vls
} // namespace simdjson
#endif // SIMDJSON_RVV_VLS_BASE_H
+10
View File
@@ -0,0 +1,10 @@
#define SIMDJSON_IMPLEMENTATION rvv_vls
#include "simdjson/rvv-vls/base.h"
#include "simdjson/rvv-vls/intrinsics.h"
#include "simdjson/rvv-vls/bitmanipulation.h"
#include "simdjson/rvv-vls/bitmask.h"
#include "simdjson/rvv-vls/simd.h"
#include "simdjson/rvv-vls/stringparsing_defs.h"
#include "simdjson/rvv-vls/numberparsing_defs.h"
#define SIMDJSON_SKIP_BACKSLASH_SHORT_CIRCUIT 1
@@ -0,0 +1,48 @@
#ifndef SIMDJSON_RVV_VLS_BITMANIPULATION_H
#define SIMDJSON_RVV_VLS_BITMANIPULATION_H
#ifndef SIMDJSON_CONDITIONAL_INCLUDE
#include "simdjson/rvv-vls/base.h"
#endif // SIMDJSON_CONDITIONAL_INCLUDE
namespace simdjson {
namespace rvv_vls {
namespace {
// We sometimes call trailing_zero on inputs that are zero,
// but the algorithms do not end up using the returned value.
// Sadly, sanitizers are not smart enough to figure it out.
SIMDJSON_NO_SANITIZE_UNDEFINED
// This function can be used safely even if not all bytes have been
// initialized.
// See issue https://github.com/simdjson/simdjson/issues/1965
SIMDJSON_NO_SANITIZE_MEMORY
simdjson_inline int trailing_zeroes(uint64_t input_num) {
return __builtin_ctzll(input_num);
}
/* result might be undefined when input_num is zero */
simdjson_inline uint64_t clear_lowest_bit(uint64_t input_num) {
return input_num & (input_num-1);
}
/* result might be undefined when input_num is zero */
simdjson_inline int leading_zeroes(uint64_t input_num) {
return __builtin_clzll(input_num);
}
simdjson_inline long long int count_ones(uint64_t input_num) {
return __builtin_popcountll(input_num);
}
simdjson_inline bool add_overflow(uint64_t value1, uint64_t value2,
uint64_t *result) {
return __builtin_uaddll_overflow(value1, value2,
reinterpret_cast<unsigned long long *>(result));
}
} // unnamed namespace
} // namespace rvv_vls
} // namespace simdjson
#endif // SIMDJSON_RVV_VLS_BITMANIPULATION_H
+39
View File
@@ -0,0 +1,39 @@
#ifndef SIMDJSON_RVV_VLS_BITMASK_H
#define SIMDJSON_RVV_VLS_BITMASK_H
#ifndef SIMDJSON_CONDITIONAL_INCLUDE
#include "simdjson/rvv-vls/base.h"
#include "simdjson/rvv-vls/intrinsics.h"
#endif // SIMDJSON_CONDITIONAL_INCLUDE
namespace simdjson {
namespace rvv_vls {
namespace {
//
// Perform a "cumulative bitwise xor," flipping bits each time a 1 is encountered.
//
// For example, prefix_xor(00100100) == 00011100
//
simdjson_inline uint64_t prefix_xor(uint64_t bitmask) {
#if __riscv_zbc
return __riscv_clmul_64(bitmask, ~(uint64_t)0);
#elif __riscv_zvbc
return __riscv_vmv_x(__riscv_vclmul(__riscv_vmv_s_x_u64m1(bitmask, 1), ~(uint64_t)0, 1));
#else
bitmask ^= bitmask << 1;
bitmask ^= bitmask << 2;
bitmask ^= bitmask << 4;
bitmask ^= bitmask << 8;
bitmask ^= bitmask << 16;
bitmask ^= bitmask << 32;
#endif
return bitmask;
}
} // unnamed namespace
} // namespace rvv_vls
} // namespace simdjson
#endif // SIMDJSON_RVV_VLS_BITMASK_H

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