Compare commits

..

27 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
Carlos Sousa e0ef3e7cec optimize get_string 2024-07-11 01:30:27 -03:00
127 changed files with 33482 additions and 21326 deletions
+1
View File
@@ -6,6 +6,7 @@ Description
Type of change Type of change
- [ ] Bug fix - [ ] Bug fix
- [ ] Optimization
- [ ] New feature - [ ] New feature
- [ ] Refactor / cleanup - [ ] Refactor / cleanup
- [ ] Documentation / tests - [ ] 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 sudo apt-get install -y cmake make g++-riscv64-linux-gnu qemu-user-static clang-18
- name: Build - name: Build
run: | run: |
CXX=clang++-18 CXXFLAGS="--target=riscv64-linux-gnu -march=rv64gcv_zvbb" \ 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 -DCMAKE_BUILD_TYPE=Release -B build cmake --toolchain=cmake/toolchains-ci/riscv64-linux-gnu.cmake -DSIMDJSON_DEVELOPER_MODE=ON -B build
cmake --build build/ -j$(nproc) cmake --build build/ -j$(nproc) --config Release
- name: Test VLEN=1024 - name: Test VLEN=1024
run: | run: |
export QEMU_LD_PREFIX="/usr/riscv64-linux-gnu" 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_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) 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 sudo apt-get install -y cmake make g++-riscv64-linux-gnu qemu-user-static clang-17
- name: Build - name: Build
run: | run: |
CXX=clang++-17 CXXFLAGS="--target=riscv64-linux-gnu -march=rv64gcv" \ CC=clang-17 CXX=clang++-17 CFLAGS="--target=riscv64-linux-gnu -march=rv64gcv" CXXFLAGS="${CFLAGS}" \
cmake --toolchain=cmake/toolchains-ci/riscv64-linux-gnu.cmake -DCMAKE_BUILD_TYPE=Release -B build cmake --toolchain=cmake/toolchains-ci/riscv64-linux-gnu.cmake -DSIMDJSON_DEVELOPER_MODE=ON -B build
cmake --build build/ -j$(nproc) cmake --build build/ -j$(nproc) --config Release
- 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)
+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 sudo apt-get install -y cmake make g++-14-riscv64-linux-gnu qemu-user-static
- name: Build - name: Build
run: | run: |
CXX=riscv64-linux-gnu-g++-14 CXXFLAGS=-march=rv64gcv \ 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 -DCMAKE_BUILD_TYPE=Release -B build cmake --toolchain=cmake/toolchains-ci/riscv64-linux-gnu.cmake -DSIMDJSON_DEVELOPER_MODE=ON -B build
cmake --build build/ -j$(nproc) cmake --build build/ -j$(nproc) --config Release
- name: Test VLEN=256 - name: Test VLEN=256
run: | run: |
export QEMU_LD_PREFIX="/usr/riscv64-linux-gnu" 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_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) 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) 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( project(
simdjson simdjson
# The version number is modified by tools/release.py # The version number is modified by tools/release.py
VERSION 4.2.3 VERSION 4.2.4
DESCRIPTION "Parsing gigabytes of JSON per second" DESCRIPTION "Parsing gigabytes of JSON per second"
HOMEPAGE_URL "https://simdjson.org/" HOMEPAGE_URL "https://simdjson.org/"
LANGUAGES CXX C LANGUAGES CXX C
@@ -83,10 +92,36 @@ add_library(simdjson ${SIMDJSON_SOURCES})
add_library(simdjson::simdjson ALIAS simdjson) add_library(simdjson::simdjson ALIAS simdjson)
set(SIMDJSON_LIBRARIES 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) if(SIMDJSON_BUILD_STATIC_LIB)
add_library(simdjson_static STATIC ${SIMDJSON_SOURCES}) add_library(simdjson_static STATIC ${SIMDJSON_SOURCES})
add_library(simdjson::simdjson_static ALIAS simdjson_static) add_library(simdjson::simdjson_static ALIAS simdjson_static)
list(APPEND SIMDJSON_LIBRARIES 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() endif()
set_target_properties( set_target_properties(
@@ -112,6 +147,14 @@ simdjson_add_props(
PRIVATE "$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/src>" 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) if(SIMDJSON_STATIC_REFLECTION)
# We would like to require C++26, but no compiler supports that! # We would like to require C++26, but no compiler supports that!
# This is a hack: # 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) simdjson_add_props(target_compile_definitions PRIVATE SIMDJSON_MINUS_ZERO_AS_FLOAT=1)
endif(SIMDJSON_MINUS_ZERO_AS_FLOAT) 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. # GCC and Clang have horrendous Debug builds when using SIMD.
# A common fix is to use '-Og' instead. # A common fix is to use '-Og' instead.
# bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54412 # bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54412
@@ -171,7 +196,12 @@ if(
target_compile_options PRIVATE target_compile_options PRIVATE
$<$<CONFIG:DEBUG>:-Og> $<$<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) if(SIMDJSON_ENABLE_THREADS)
find_package(Threads REQUIRED) 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 # could be handy for archiving the generated documentation or if some version
# control system is used. # control system is used.
PROJECT_NUMBER = "4.2.3" PROJECT_NUMBER = "4.2.4"
# Using the PROJECT_BRIEF tag one can provide an optional one line description # 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 # 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 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: simdjson's source structure, from the top level, looks like this:
* **CMakeLists.txt:** The main build system. * **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/*.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/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/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 * **src:** The source files for non-inlined functionality (e.g. the architecture-specific parser
implementations). implementations).
* simdjson.cpp: A "main source" that includes all implementation files from src/. This is * 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). * **.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:** 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/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 * **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 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: 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 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 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 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++. 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 /> [![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.) (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 Funding
------- -------
+3 -3
View File
@@ -245,7 +245,7 @@ static u32 (*kpc_get_counter_count)(u32 classes);
/// Get counter accumulations. /// Get counter accumulations.
/// If `all_cpus` is true, the buffer count should not smaller than /// 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). /// than (counter_count).
/// @see kpc_get_counter_count(), kpc_cpu_count(). /// @see kpc_get_counter_count(), kpc_cpu_count().
/// @param all_cpus true for all CPUs, false for current cpu. /// @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. // These functions do not require root privileges.
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// KPEP CPU archtecture constants. // KPEP CPU architecture constants.
#define KPEP_ARCH_I386 0 #define KPEP_ARCH_I386 0
#define KPEP_ARCH_X86_64 1 #define KPEP_ARCH_X86_64 1
#define KPEP_ARCH_ARM 2 #define KPEP_ARCH_ARM 2
@@ -414,7 +414,7 @@ typedef struct kpep_db {
usize fixed_counter_count; usize fixed_counter_count;
usize config_counter_count; usize config_counter_count;
usize power_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 fixed_counter_bits;
u32 config_counter_bits; u32 config_counter_bits;
u32 power_counter_bits; u32 power_counter_bits;
+17 -5
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, 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` 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 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 want to if you want to avoid runtime warnings with some sanitizers. We expect the user
read the section Free Padding in [our performance notes](performance.md). 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 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 access by creating a `ondemand::parser` and calling the `iterate()` method. The iterate method
@@ -354,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 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 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 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 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 Release mode: under Visual Studio, it means having the `_DEBUG` macro undefined, and, for other
@@ -437,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) { ... }`. 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()) {...}`. 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) { ... }`. 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()) {...}`. * **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.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.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. - `field.value()` will get you the value, which you can then use all these other methods on.
@@ -451,6 +459,10 @@ 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"]}`. 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()}`. 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. 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 you should iterate through the array and keep an index yourself. Exceptionally, if need a single value
+49 -2
View File
@@ -14,6 +14,7 @@ speed and high convenience.
* [C++26 static reflection](#c--26-static-reflection) * [C++26 static reflection](#c--26-static-reflection)
+ [Without `string_buffer` instance](#without--string-buffer--instance) + [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) + [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 Overview: string_builder
--------------------------- ---------------------------
@@ -332,7 +333,7 @@ pattern:
### Customization ### 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 `tag_invoke` specialization like the following example which will map
the year attribute to a string. the year attribute to a string.
@@ -363,4 +364,50 @@ void tag_invoke(serialize_tag, builder_type &builder, const Car& car) {
} }
} // namespace simdjson } // 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]`.
+1 -1
View File
@@ -128,7 +128,7 @@ Let us consider this example:
``` ```
You might want to ensure that the result is an array of persons. You can define your You might want to ensure that the result is an array of persons. You can define your
expection with concepts like so: expectation with concepts like so:
```cpp ```cpp
template <typename T> template <typename T>
+2
View File
@@ -62,6 +62,8 @@ auto json = padded_string::load("twitter.json"); // load JSON file 'twitter.json
dom::element doc = parser.parse(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 (Windows users compiling with C++17 or better may use `wchar_t` strings to support non-ASCII
filenames: `padded_string::load(L"twitter.json")`.) filenames: `padded_string::load(L"twitter.json")`.)
+58
View File
@@ -297,4 +297,62 @@ int main() {
} }
return EXIT_SUCCESS; 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 -1
View File
@@ -35,7 +35,7 @@ cmake .. \
-DSIMDJSON_DISABLE_DEPRECATED_API=On \ -DSIMDJSON_DISABLE_DEPRECATED_API=On \
-DSIMDJSON_FUZZ_LDFLAGS=$LIB_FUZZING_ENGINE -DSIMDJSON_FUZZ_LDFLAGS=$LIB_FUZZING_ENGINE
cmake --build . --target all_fuzzers cmake --build . --target all_fuzzers all_tests
cp fuzz/fuzz_* $OUT 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/padded_string_view-inl.h"
#include "simdjson/dom.h" #include "simdjson/dom.h"
#include "simdjson/builder.h"
#include "simdjson/ondemand.h" #include "simdjson/ondemand.h"
#include "simdjson/convert.h" #include "simdjson/convert.h"
#include "simdjson/convert-inl.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 constexpr int NUM_CHUNKS = 64 / sizeof(simd8<T>);
static_assert(NUM_CHUNKS == 4, "ARM kernel should use four registers per 64-byte block."); static_assert(NUM_CHUNKS == 4, "ARM kernel should use four registers per 64-byte block.");
const simd8<T> chunks[NUM_CHUNKS]; 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(const simd8x64<T>& o) = delete; // no copy allowed
simd8x64<T>& operator=(const simd8<T>& other) = delete; // no assignment 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" #include "simdjson/ppc64.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(westmere) #elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(westmere)
#include "simdjson/westmere.h" #include "simdjson/westmere.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lsx)
#include "simdjson/lsx.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lasx) #elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lasx)
#include "simdjson/lasx.h" #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 #else
#error Unknown SIMDJSON_BUILTIN_IMPLEMENTATION #error Unknown SIMDJSON_BUILTIN_IMPLEMENTATION
#endif #endif
+2
View File
@@ -21,6 +21,8 @@ namespace simdjson {
namespace lsx {} namespace lsx {}
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lasx) #elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lasx)
namespace lasx {} namespace lasx {}
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(rvv_vls)
namespace rvv_vls {}
#else #else
#error Unknown SIMDJSON_BUILTIN_IMPLEMENTATION #error Unknown SIMDJSON_BUILTIN_IMPLEMENTATION
#endif #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" #include "simdjson/lsx/implementation.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lasx) #elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lasx)
#include "simdjson/lasx/implementation.h" #include "simdjson/lasx/implementation.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(rvv_vls)
#include "simdjson/rvv-vls/implementation.h"
#else #else
#error Unknown SIMDJSON_BUILTIN_IMPLEMENTATION #error Unknown SIMDJSON_BUILTIN_IMPLEMENTATION
#endif #endif
@@ -39,4 +41,4 @@ namespace simdjson {
const implementation * builtin_implementation(); const implementation * builtin_implementation();
} // namespace simdjson } // 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" #include "simdjson/lsx/ondemand.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lasx) #elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lasx)
#include "simdjson/lasx/ondemand.h" #include "simdjson/lasx/ondemand.h"
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(rvv_vls)
#include "simdjson/rvv-vls/ondemand.h"
#else #else
#error Unknown SIMDJSON_BUILTIN_IMPLEMENTATION #error Unknown SIMDJSON_BUILTIN_IMPLEMENTATION
#endif #endif
@@ -37,4 +39,4 @@ namespace simdjson {
namespace ondemand = SIMDJSON_BUILTIN_IMPLEMENTATION::ondemand; namespace ondemand = SIMDJSON_BUILTIN_IMPLEMENTATION::ondemand;
} // namespace simdjson } // 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. // when the compiler is optimizing.
// We only set SIMDJSON_DEVELOPMENT_CHECKS if both __OPTIMIZE__ // We only set SIMDJSON_DEVELOPMENT_CHECKS if both __OPTIMIZE__
// and NDEBUG are not defined. // 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 #define SIMDJSON_DEVELOPMENT_CHECKS 1
#endif // __OPTIMIZE__ #endif // __OPTIMIZE__
#endif // _MSC_VER #endif // _MSC_VER
+2
View File
@@ -9,6 +9,7 @@
#include "simdjson/dom/object.h" #include "simdjson/dom/object.h"
#include "simdjson/dom/parser.h" #include "simdjson/dom/parser.h"
#include "simdjson/dom/serialization.h" #include "simdjson/dom/serialization.h"
#include "simdjson/dom/fractured_json.h"
// Inline functions // Inline functions
#include "simdjson/dom/array-inl.h" #include "simdjson/dom/array-inl.h"
@@ -19,5 +20,6 @@
#include "simdjson/dom/parser-inl.h" #include "simdjson/dom/parser-inl.h"
#include "simdjson/internal/tape_ref-inl.h" #include "simdjson/internal/tape_ref-inl.h"
#include "simdjson/dom/serialization-inl.h" #include "simdjson/dom/serialization-inl.h"
#include "simdjson/dom/fractured_json-inl.h"
#endif // SIMDJSON_DOM_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
+1 -1
View File
@@ -8,7 +8,7 @@
namespace simdjson { namespace simdjson {
inline bool is_fatal(error_code error) noexcept { 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 { namespace internal {
+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" #include "simdjson/arm64/begin.h"
#elif SIMDJSON_IMPLEMENTATION_PPC64 #elif SIMDJSON_IMPLEMENTATION_PPC64
#include "simdjson/ppc64/begin.h" #include "simdjson/ppc64/begin.h"
#elif SIMDJSON_IMPLEMENTATION_LSX
#include "simdjson/lsx/begin.h"
#elif SIMDJSON_IMPLEMENTATION_LASX #elif SIMDJSON_IMPLEMENTATION_LASX
#include "simdjson/lasx/begin.h" #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 #elif SIMDJSON_IMPLEMENTATION_FALLBACK
#include "simdjson/fallback/begin.h" #include "simdjson/fallback/begin.h"
#else #else
@@ -48,4 +50,4 @@ enum class number_type {
} // namespace SIMDJSON_IMPLEMENTATION } // namespace SIMDJSON_IMPLEMENTATION
} // namespace simdjson } // 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_GENERIC_BUILDER_H
#ifndef SIMDJSON_CONDITIONAL_INCLUDE #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 <array>
#include <cstring> #include <cstring>
#include <type_traits> #include <type_traits>
@@ -519,8 +515,8 @@ simdjson_inline void string_builder::append(const T &opt) {
template <typename T> template <typename T>
requires(require_custom_serialization<T>) requires(require_custom_serialization<T>)
simdjson_inline void string_builder::append(const T &val) { simdjson_inline void string_builder::append(T &&val) {
serialize(*this, val); serialize(*this, std::forward<T>(val));
} }
template <typename T> template <typename T>
@@ -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_GENERIC_STRING_BUILDER_H
#ifndef SIMDJSON_CONDITIONAL_INCLUDE #ifndef SIMDJSON_CONDITIONAL_INCLUDE
@@ -24,9 +20,8 @@ struct has_custom_serialization : std::false_type {};
inline constexpr struct serialize_tag { inline constexpr struct serialize_tag {
template <typename T> template <typename T>
requires custom_deserializable<T> constexpr void operator()(SIMDJSON_IMPLEMENTATION::builder::string_builder& b, T&& obj) const{
constexpr void operator()(SIMDJSON_IMPLEMENTATION::builder::string_builder& b, T& obj) const{ return tag_invoke(*this, b, std::forward<T>(obj));
return tag_invoke(*this, b, obj);
} }
@@ -165,7 +160,7 @@ public:
template <typename T> template <typename T>
requires(require_custom_serialization<T>) requires(require_custom_serialization<T>)
simdjson_inline void append(const T &val); simdjson_inline void append(T &&val);
// Support for string-like types // Support for string-like types
template <typename T> template <typename T>
@@ -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! #error simdjson/generic/ondemand/dependencies.h must be included before simdjson/generic/ondemand/amalgamated.h!
#endif #endif
@@ -14,9 +14,6 @@
#include "simdjson/generic/ondemand/raw_json_string.h" #include "simdjson/generic/ondemand/raw_json_string.h"
#include "simdjson/generic/ondemand/parser.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 // All other declarations
#include "simdjson/generic/ondemand/array.h" #include "simdjson/generic/ondemand/array.h"
#include "simdjson/generic/ondemand/array_iterator.h" #include "simdjson/generic/ondemand/array_iterator.h"
@@ -44,13 +41,9 @@
#include "simdjson/generic/ondemand/object_iterator-inl.h" #include "simdjson/generic/ondemand/object_iterator-inl.h"
#include "simdjson/generic/ondemand/parser-inl.h" #include "simdjson/generic/ondemand/parser-inl.h"
#include "simdjson/generic/ondemand/raw_json_string-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/token_iterator-inl.h"
#include "simdjson/generic/ondemand/value_iterator-inl.h" #include "simdjson/generic/ondemand/value_iterator-inl.h"
#include "simdjson/generic/ondemand/serialization-inl.h"
// JSON builder inline definitions
#include "simdjson/generic/ondemand/json_string_builder-inl.h"
#include "simdjson/generic/ondemand/json_builder.h"
// JSON path accessor (compile-time) - must be after inline definitions // JSON path accessor (compile-time) - must be after inline definitions
#include "simdjson/generic/ondemand/compile_time_accessors.h" #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 { 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(); } if (iter.error()) { iter.abandon(); return iter.error(); }
return value(iter.child()); return value(iter.child());
} }
@@ -27,6 +31,9 @@ simdjson_inline bool array_iterator::operator!=(const array_iterator &) const no
return iter.is_open(); return iter.is_open();
} }
simdjson_inline array_iterator &array_iterator::operator++() noexcept { simdjson_inline array_iterator &array_iterator::operator++() noexcept {
#if SIMDJSON_DEVELOPMENT_CHECKS
has_been_referenced = false;
#endif
error_code error; 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. // 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. // 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 #ifndef SIMDJSON_CONDITIONAL_INCLUDE
#define SIMDJSON_GENERIC_ONDEMAND_ARRAY_ITERATOR_H #define SIMDJSON_GENERIC_ONDEMAND_ARRAY_ITERATOR_H
#include <iterator>
#include "simdjson/generic/implementation_simdjson_result_base.h" #include "simdjson/generic/implementation_simdjson_result_base.h"
#include "simdjson/generic/ondemand/base.h" #include "simdjson/generic/ondemand/base.h"
#include "simdjson/generic/ondemand/value_iterator.h" #include "simdjson/generic/ondemand/value_iterator.h"
@@ -17,11 +18,17 @@ namespace ondemand {
* *
* This is an input_iterator, meaning: * This is an input_iterator, meaning:
* - It is forward-only * - 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 * (*, ++, *, ++, * ...) * - ++ must be called exactly once in between each * (*, ++, *, ++, * ...)
*/ */
class array_iterator { class array_iterator {
public: 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. */ /** Create a new, invalid array iterator. */
simdjson_inline array_iterator() noexcept = default; simdjson_inline array_iterator() noexcept = default;
@@ -65,6 +72,9 @@ public:
simdjson_warn_unused simdjson_inline bool at_end() const noexcept; simdjson_warn_unused simdjson_inline bool at_end() const noexcept;
private: private:
#if SIMDJSON_DEVELOPMENT_CHECKS
bool has_been_referenced{false};
#endif
value_iterator iter{}; value_iterator iter{};
simdjson_inline array_iterator(const value_iterator &iter) noexcept; simdjson_inline array_iterator(const value_iterator &iter) noexcept;
@@ -82,6 +92,12 @@ namespace simdjson {
template<> template<>
struct simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::array_iterator> : public SIMDJSON_IMPLEMENTATION::implementation_simdjson_result_base<SIMDJSON_IMPLEMENTATION::ondemand::array_iterator> { 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(SIMDJSON_IMPLEMENTATION::ondemand::array_iterator &&value) noexcept; ///< @private
simdjson_inline simdjson_result(error_code error) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private
simdjson_inline simdjson_result() noexcept = default; simdjson_inline simdjson_result() noexcept = default;
@@ -8,7 +8,6 @@
// Internal headers needed for ondemand generics. // Internal headers needed for ondemand generics.
// All includes not under simdjson/generic/ondemand must be here! // All includes not under simdjson/generic/ondemand must be here!
// Otherwise, amalgamation will fail. // Otherwise, amalgamation will fail.
#include "simdjson/concepts.h"
#include "simdjson/dom/base.h" // for MINIMAL_DOCUMENT_CAPACITY #include "simdjson/dom/base.h" // for MINIMAL_DOCUMENT_CAPACITY
#include "simdjson/implementation.h" #include "simdjson/implementation.h"
#include "simdjson/padded_string.h" #include "simdjson/padded_string.h"
+5 -2
View File
@@ -403,7 +403,9 @@ public:
simdjson_inline simdjson_result<array_iterator> end() & noexcept; 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 * 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 }`: * 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 * 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. * 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 * 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. * 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 { simdjson_inline void json_iterator::assert_valid_position(token_position position) const noexcept {
(void)position; // Suppress unused parameter warning
#ifndef SIMDJSON_CLANG_VISUAL_STUDIO #ifndef SIMDJSON_CLANG_VISUAL_STUDIO
SIMDJSON_ASSUME( position >= &parser->implementation->structural_indexes[0] ); SIMDJSON_ASSUME( position >= &parser->implementation->structural_indexes[0] );
SIMDJSON_ASSUME( position < &parser->implementation->structural_indexes[parser->implementation->n_structural_indexes] ); SIMDJSON_ASSUME( position < &parser->implementation->structural_indexes[parser->implementation->n_structural_indexes] );
#else
(void)position; // Suppress unused parameter warning
#endif #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 { simdjson_inline simdjson_result<std::string_view> json_iterator::unescape(raw_json_string in, bool allow_replacement) noexcept {
#if SIMDJSON_DEVELOPMENT_CHECKS #if SIMDJSON_DEVELOPMENT_CHECKS
auto result = parser->unescape(in, _string_buf_loc, allow_replacement); 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)); SIMDJSON_ASSUME(!parser->string_buffer_overflow(_string_buf_loc));
#endif // !defined(SIMDJSON_VISUAL_STUDIO) && !defined(SIMDJSON_CLANG_VISUAL_STUDIO)
return result; return result;
#else #else
return parser->unescape(in, _string_buf_loc, allow_replacement); 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 { simdjson_inline simdjson_result<std::string_view> json_iterator::unescape_wobbly(raw_json_string in) noexcept {
#if SIMDJSON_DEVELOPMENT_CHECKS #if SIMDJSON_DEVELOPMENT_CHECKS
auto result = parser->unescape_wobbly(in, _string_buf_loc); 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)); SIMDJSON_ASSUME(!parser->string_buffer_overflow(_string_buf_loc));
#endif // !defined(SIMDJSON_VISUAL_STUDIO) && !defined(SIMDJSON_CLANG_VISUAL_STUDIO)
return result; return result;
#else #else
return parser->unescape_wobbly(in, _string_buf_loc); return parser->unescape_wobbly(in, _string_buf_loc);
+12 -2
View File
@@ -27,10 +27,19 @@ public:
*/ */
simdjson_inline object() noexcept = default; 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> begin() noexcept;
simdjson_inline simdjson_result<object_iterator> end() 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 * 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 }`: * 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 * 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. * 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 * 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. * 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 { 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(); error_code error = iter.error();
if (error) { iter.abandon(); return error; } if (error) { iter.abandon(); return error; }
auto result = field::start(iter); auto result = field::start(iter);
@@ -39,6 +44,11 @@ simdjson_inline bool object_iterator::operator!=(const object_iterator &) const
SIMDJSON_PUSH_DISABLE_WARNINGS SIMDJSON_PUSH_DISABLE_WARNINGS
SIMDJSON_DISABLE_STRICT_OVERFLOW_WARNING SIMDJSON_DISABLE_STRICT_OVERFLOW_WARNING
simdjson_inline object_iterator &object_iterator::operator++() noexcept { 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. // 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. // 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 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. // Assumes it's being compared with the end. true if depth >= iter->depth.
simdjson_inline bool operator!=(const object_iterator &) const noexcept; simdjson_inline bool operator!=(const object_iterator &) const noexcept;
// Checks for ']' and ',' // 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; simdjson_inline object_iterator &operator++() noexcept;
private: private:
#if SIMDJSON_DEVELOPMENT_CHECKS
bool has_been_referenced{false};
#endif
/** /**
* The underlying JSON iterator. * The underlying JSON iterator.
* *
@@ -10,7 +10,7 @@
#include "simdjson/generic/ondemand/serialization.h" #include "simdjson/generic/ondemand/serialization.h"
#include "simdjson/generic/ondemand/value.h" #include "simdjson/generic/ondemand/value.h"
#if SIMDJSON_STATIC_REFLECTION #if SIMDJSON_STATIC_REFLECTION
#include "simdjson/generic/ondemand/json_builder.h" #include "simdjson/generic/builder/json_builder.h"
#endif #endif
#endif // SIMDJSON_CONDITIONAL_INCLUDE #endif // SIMDJSON_CONDITIONAL_INCLUDE
+15 -6
View File
@@ -198,14 +198,17 @@ public:
* simdjson::ondemand::document doc = parser.iterate(json); * simdjson::ondemand::document doc = parser.iterate(json);
* auto view = doc["deviceId"].get_string(true); * 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 * @returns An UTF-8 string. The string is stored in the parser when escaping was needed
* time it parses a document or when it is destroyed. * 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. * @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; 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. * 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. * The string is guaranteed to be valid UTF-8.
* *
@@ -395,7 +398,9 @@ public:
*/ */
simdjson_inline simdjson_result<value> at(size_t index) noexcept; 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 * 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 }`: * 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 * 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. * 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 * 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. * 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; 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 * 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 }`: * 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 * 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. * 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 * 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. * 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 { simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_next_field() noexcept {
assert_at_next(); assert_at_next();
// It's illegal to call this unless there are more tokens: anything that ends in } or ] is // 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. // obligated to verify there are more tokens if they are not the top level.
switch (*_json_iter->return_current_and_advance()) { 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 { 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); return get_raw_json_string().unescape(json_iter(), allow_replacement);
} }
template <typename string_type> template <typename string_type>
simdjson_warn_unused simdjson_inline error_code value_iterator::get_string(string_type& receiver, bool allow_replacement) noexcept { simdjson_warn_unused simdjson_inline error_code value_iterator::get_string(string_type& receiver, bool allow_replacement) noexcept {
std::string_view content; std::string_view content;
auto err = get_string(allow_replacement).get(content); // Save the string buffer location so that we can restore it after get_string
if (err) { return err; } auto saved_string_buf_loc = _json_iter->string_buf_loc();
SIMDJSON_TRY(get_string(allow_replacement).get(content));
receiver = 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; return SUCCESS;
} }
simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_wobbly_string() noexcept { 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; return num;
} }
simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_root_string(bool check_trailing, bool allow_replacement) noexcept { 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); return get_root_raw_json_string(check_trailing).unescape(json_iter(), allow_replacement);
} }
template <typename string_type> 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 { 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; std::string_view content;
auto err = get_root_string(check_trailing, allow_replacement).get(content); // Save the string buffer location so that we can restore it after get_string
if (err) { return err; } auto saved_string_buf_loc = _json_iter->string_buf_loc();
SIMDJSON_TRY(get_root_string(check_trailing, allow_replacement).get(content));
receiver = 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; return SUCCESS;
} }
simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_root_wobbly_string(bool check_trailing) noexcept { 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. // Keys are at the same depth as the object.
// Note here that we could be safer and check that we are within an object, // Note here that we could be safer and check that we are within an object,
// but we do not. // 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() == '"'; return _depth == _json_iter->_depth && *_json_iter->peek() == '"';
} }
@@ -472,6 +472,7 @@ protected:
friend class document; friend class document;
friend class object; friend class object;
friend class object_iterator;
friend class array; friend class array;
friend class value; friend class value;
friend class field; 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 constexpr int NUM_CHUNKS = 64 / sizeof(simd8<T>);
static_assert(NUM_CHUNKS == 2, "Haswell kernel should use two registers per 64-byte block."); static_assert(NUM_CHUNKS == 2, "Haswell kernel should use two registers per 64-byte block.");
const simd8<T> chunks[NUM_CHUNKS]; 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(const simd8x64<T>& o) = delete; // no copy allowed
simd8x64<T>& operator=(const simd8<T>& other) = delete; // no assignment 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 constexpr int NUM_CHUNKS = 64 / sizeof(simd8<T>);
static_assert(NUM_CHUNKS == 1, "Icelake kernel should use one register per 64-byte block."); static_assert(NUM_CHUNKS == 1, "Icelake kernel should use one register per 64-byte block.");
const simd8<T> chunks[NUM_CHUNKS]; 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(const simd8x64<T>& o) = delete; // no copy allowed
simd8x64<T>& operator=(const simd8<T>& other) = delete; // no assignment 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_westmere 6
#define SIMDJSON_IMPLEMENTATION_ID_lsx 7 #define SIMDJSON_IMPLEMENTATION_ID_lsx 7
#define SIMDJSON_IMPLEMENTATION_ID_lasx 8 #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_FOR(IMPL) SIMDJSON_CAT(SIMDJSON_IMPLEMENTATION_ID_, IMPL)
#define SIMDJSON_IMPLEMENTATION_ID SIMDJSON_IMPLEMENTATION_ID_FOR(SIMDJSON_IMPLEMENTATION) #define SIMDJSON_IMPLEMENTATION_ID SIMDJSON_IMPLEMENTATION_ID_FOR(SIMDJSON_IMPLEMENTATION)
@@ -113,22 +115,27 @@
#endif #endif
#ifndef SIMDJSON_IMPLEMENTATION_LASX #ifndef SIMDJSON_IMPLEMENTATION_LASX
#define SIMDJSON_IMPLEMENTATION_LASX (SIMDJSON_IS_LOONGARCH64 && __loongarch_asx) #define SIMDJSON_IMPLEMENTATION_LASX (SIMDJSON_IS_LSX)
#endif #endif
#define SIMDJSON_CAN_ALWAYS_RUN_LASX (SIMDJSON_IMPLEMENTATION_LASX) #define SIMDJSON_CAN_ALWAYS_RUN_LASX (SIMDJSON_IS_LASX)
#ifndef SIMDJSON_IMPLEMENTATION_LSX #ifndef SIMDJSON_IMPLEMENTATION_LSX
#if SIMDJSON_CAN_ALWAYS_RUN_LASX #if SIMDJSON_CAN_ALWAYS_RUN_LASX
#define SIMDJSON_IMPLEMENTATION_LSX 0 #define SIMDJSON_IMPLEMENTATION_LSX 0
#else #else
#define SIMDJSON_IMPLEMENTATION_LSX (SIMDJSON_IS_LOONGARCH64 && __loongarch_sx) #define SIMDJSON_IMPLEMENTATION_LSX (SIMDJSON_IS_LSX)
#endif #endif
#endif #endif
#define SIMDJSON_CAN_ALWAYS_RUN_LSX (SIMDJSON_IMPLEMENTATION_LSX) #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. // Default Fallback to on unless a builtin implementation has already been selected.
#ifndef SIMDJSON_IMPLEMENTATION_FALLBACK #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. // if anything at all except fallback can always run, then disable fallback.
#define SIMDJSON_IMPLEMENTATION_FALLBACK 0 #define SIMDJSON_IMPLEMENTATION_FALLBACK 0
#else #else
@@ -154,6 +161,8 @@
#define SIMDJSON_BUILTIN_IMPLEMENTATION lsx #define SIMDJSON_BUILTIN_IMPLEMENTATION lsx
#elif SIMDJSON_CAN_ALWAYS_RUN_LASX #elif SIMDJSON_CAN_ALWAYS_RUN_LASX
#define SIMDJSON_BUILTIN_IMPLEMENTATION 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 #elif SIMDJSON_CAN_ALWAYS_RUN_FALLBACK
#define SIMDJSON_BUILTIN_IMPLEMENTATION fallback #define SIMDJSON_BUILTIN_IMPLEMENTATION fallback
#else #else
@@ -165,4 +174,4 @@
#define SIMDJSON_BUILTIN_IMPLEMENTATION_ID SIMDJSON_IMPLEMENTATION_ID_FOR(SIMDJSON_BUILTIN_IMPLEMENTATION) #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) #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, AVX512VBMI2 = 0x10000,
LSX = 0x20000, LSX = 0x20000,
LASX = 0x40000, LASX = 0x40000,
//RVV = 0x80000,
RVV_VLS = 0x100000,
}; };
} // namespace internal } // 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 #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/base.h"
#include "simdjson/lasx/intrinsics.h" #include "simdjson/lasx/intrinsics.h"
#include "simdjson/lasx/bitmanipulation.h" #include "simdjson/lasx/bitmanipulation.h"
@@ -8,3 +15,5 @@
#include "simdjson/lasx/stringparsing_defs.h" #include "simdjson/lasx/stringparsing_defs.h"
#define SIMDJSON_SKIP_BACKSLASH_SHORT_CIRCUIT 1 #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_SKIP_BACKSLASH_SHORT_CIRCUIT
#undef SIMDJSON_IMPLEMENTATION #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" #include "simdjson/lasx/base.h"
#endif // SIMDJSON_CONDITIONAL_INCLUDE #endif // SIMDJSON_CONDITIONAL_INCLUDE
// This should be the correct header whether #include <lsxintrin.h>
// you use visual studio or other compilers.
#include <lasxintrin.h> #include <lasxintrin.h>
static_assert(sizeof(__m256i) <= simdjson::SIMDJSON_PADDING, "insufficient padding for LoongArch ASX"); 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 constexpr int NUM_CHUNKS = 64 / sizeof(simd8<T>);
static_assert(NUM_CHUNKS == 2, "LASX kernel should use two registers per 64-byte block."); static_assert(NUM_CHUNKS == 2, "LASX kernel should use two registers per 64-byte block.");
const simd8<T> chunks[NUM_CHUNKS]; 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(const simd8x64<T>& o) = delete; // no copy allowed
simd8x64<T>& operator=(const simd8<T>& other) = delete; // no assignment 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_backslash = (v == '\\');
simd8<bool> is_control = (v < 32); simd8<bool> is_control = (v < 32);
return { 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" #include "simdjson/lsx/base.h"
#endif // SIMDJSON_CONDITIONAL_INCLUDE #endif // SIMDJSON_CONDITIONAL_INCLUDE
// This should be the correct header whether
// you use visual studio or other compilers.
#include <lsxintrin.h> #include <lsxintrin.h>
static_assert(sizeof(__m128i) <= simdjson::SIMDJSON_PADDING, "insufficient padding for LoongArch SX"); 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 constexpr int NUM_CHUNKS = 64 / sizeof(simd8<T>);
static_assert(NUM_CHUNKS == 4, "LSX kernel should use four registers per 64-byte block."); static_assert(NUM_CHUNKS == 4, "LSX kernel should use four registers per 64-byte block.");
const simd8<T> chunks[NUM_CHUNKS]; 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(const simd8x64<T>& o) = delete; // no copy allowed
simd8x64<T>& operator=(const simd8<T>& other) = delete; // no assignment allowed simd8x64<T>& operator=(const simd8<T>& other) = delete; // no assignment allowed
+124
View File
@@ -126,6 +126,33 @@ inline const char *padded_string::data() const noexcept { return data_ptr; }
inline char *padded_string::data() 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 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 { inline padded_string::operator padded_string_view() const noexcept simdjson_lifetime_bound {
@@ -242,6 +269,103 @@ inline simdjson_result<padded_string> padded_string::load(std::wstring_view file
} }
#endif #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 } // namespace simdjson
inline simdjson::padded_string operator ""_padded(const char *str, size_t len) { inline simdjson::padded_string operator ""_padded(const char *str, size_t len) {
+107 -1
View File
@@ -98,6 +98,16 @@ struct padded_string final {
**/ **/
char *data() noexcept; 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. * Create a std::string_view with the same content.
*/ */
@@ -131,7 +141,7 @@ struct padded_string final {
/** /**
* This function accepts a wide string path (UTF-16) and converts it to * 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 * UTF-8 before loading the file. This allows windows users to work
* with unicode file paths without manually converting the paths everytime. * with unicode file paths without manually converting the paths every time.
* *
* @return IO_ERROR on error, including conversion failures. * @return IO_ERROR on error, including conversion failures.
* *
@@ -141,6 +151,7 @@ struct padded_string final {
#endif #endif
private: private:
friend class padded_string_builder;
padded_string &operator=(const padded_string &o) = delete; padded_string &operator=(const padded_string &o) = delete;
padded_string(const padded_string &o) = delete; padded_string(const padded_string &o) = delete;
@@ -149,6 +160,101 @@ private:
}; // padded_string }; // 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. * 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 #define SIMDJSON_IS_ARM64 1
#elif defined(__riscv) && __riscv_xlen == 64 #elif defined(__riscv) && __riscv_xlen == 64
#define SIMDJSON_IS_RISCV64 1 #define SIMDJSON_IS_RISCV64 1
#if __riscv_v_intrinsic >= 11000 #if __riscv_v_intrinsic >= 11000
#define SIMDJSON_HAS_RVV_INTRINSICS 1 #define SIMDJSON_HAS_RVV_INTRINSICS 1
#endif #endif
#define SIMDJSON_HAS_ZVBB_INTRINSICS \ #if SIMDJSON_HAS_RVV_INTRINSICS && __riscv_vector && __riscv_v_min_vlen >= 128 && __riscv_v_elen >= 64
0 // there is currently no way to detect this #define SIMDJSON_IS_RVV 1 // RISC-V V extension
#if SIMDJSON_HAS_RVV_INTRINSICS && __riscv_vector && \
__riscv_v_min_vlen >= 128 && __riscv_v_elen >= 64
// RISC-V V extension
#define SIMDJSON_IS_RVV 1
#if SIMDJSON_HAS_ZVBB_INTRINSICS && __riscv_zvbb >= 1000000
// RISC-V Vector Basic Bit-manipulation
#define SIMDJSON_IS_ZVBB 1
#endif
#endif #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) #elif defined(__loongarch_lp64)
#define SIMDJSON_IS_LOONGARCH64 1 #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) #elif defined(__PPC64__) || defined(_M_PPC64)
#define SIMDJSON_IS_PPC64 1 #define SIMDJSON_IS_PPC64 1
#if defined(__ALTIVEC__) #if defined(__ALTIVEC__)
@@ -118,7 +122,7 @@ using std::size_t;
// //
// We are going to use runtime dispatch. // We are going to use runtime dispatch.
#if SIMDJSON_IS_X86_64 #if defined(SIMDJSON_IS_X86_64) || defined(SIMDJSON_IS_LSX)
#ifdef __clang__ #ifdef __clang__
// clang does not have GCC push pop // clang does not have GCC push pop
// warning: clang attribute push can't be used within a namespace in clang up // 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") #define SIMDJSON_UNTARGET_REGION _Pragma("GCC pop_options")
#endif // clang then gcc #endif // clang then gcc
#endif // x86 #endif // defined(SIMDJSON_IS_X86_64) || defined(SIMDJSON_IS_LSX)
// Default target region macros don't do anything. // Default target region macros don't do anything.
#ifndef SIMDJSON_TARGET_REGION #ifndef SIMDJSON_TARGET_REGION
@@ -204,7 +208,8 @@ using std::size_t;
#define simdjson_strncasecmp strncasecmp #define simdjson_strncasecmp strncasecmp
#endif #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, // If NDEBUG is set, or __OPTIMIZE__ is set, or we are under MSVC in release mode,
// then do away with asserts and use __assume. // then do away with asserts and use __assume.
// We still recommend that our users set NDEBUG in release mode. // 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) #define SIMDJSON_ASSUME(COND) do { if (!(COND)) __builtin_unreachable(); } while (0)
#endif #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. // This should only ever be enabled in debug mode.
#define SIMDJSON_UNREACHABLE() assert(0); #define SIMDJSON_UNREACHABLE() assert(0);
#define SIMDJSON_ASSUME(COND) assert(COND) #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, static_assert(NUM_CHUNKS == 4,
"PPC64 kernel should use four registers per 64-byte block."); "PPC64 kernel should use four registers per 64-byte block.");
const simd8<T> chunks[NUM_CHUNKS]; 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(const simd8x64<T> &o) = delete; // no copy allowed
simd8x64<T> & 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
+8
View File
@@ -0,0 +1,8 @@
#ifndef SIMDJSON_RVV_VLS_BUILDER_H
#define SIMDJSON_RVV_VLS_BUILDER_H
#include "simdjson/rvv-vls/begin.h"
#include "simdjson/generic/builder/amalgamated.h"
#include "simdjson/rvv-vls/end.h"
#endif // SIMDJSON_RVV_VLS_BUILDER_H
+5
View File
@@ -0,0 +1,5 @@
#ifndef SIMDJSON_CONDITIONAL_INCLUDE
#include "simdjson/rvv-vls/base.h"
#endif // SIMDJSON_CONDITIONAL_INCLUDE
#undef SIMDJSON_IMPLEMENTATION
+34
View File
@@ -0,0 +1,34 @@
#ifndef SIMDJSON_RVV_VLS_IMPLEMENTATION_H
#define SIMDJSON_RVV_VLS_IMPLEMENTATION_H
#ifndef SIMDJSON_CONDITIONAL_INCLUDE
#include "simdjson/rvv-vls/base.h"
#include "simdjson/implementation.h"
#endif // SIMDJSON_CONDITIONAL_INCLUDE
namespace simdjson {
namespace rvv_vls {
/**
* @private
*/
class implementation final : public simdjson::implementation {
public:
simdjson_inline implementation() : simdjson::implementation(
"rvv_vls",
"RISC-V V extension",
0
) {}
simdjson_warn_unused error_code create_dom_parser_implementation(
size_t capacity,
size_t max_length,
std::unique_ptr<simdjson::internal::dom_parser_implementation>& dst
) const noexcept final;
simdjson_warn_unused error_code minify(const uint8_t *buf, size_t len, uint8_t *dst, size_t &dst_len) const noexcept final;
simdjson_warn_unused bool validate_utf8(const char *buf, size_t len) const noexcept final;
};
} // namespace rvv_vls
} // namespace simdjson
#endif // SIMDJSON_RVV_VLS_IMPLEMENTATION_H
+32
View File
@@ -0,0 +1,32 @@
#ifndef SIMDJSON_RVV_VLS_INTRINSICS_H
#define SIMDJSON_RVV_VLS_INTRINSICS_H
#ifndef SIMDJSON_CONDITIONAL_INCLUDE
#include "simdjson/rvv-vls/base.h"
#endif // SIMDJSON_CONDITIONAL_INCLUDE
#include <riscv_vector.h>
#define simdutf_vrgather_u8m1x2(tbl, idx) \
__riscv_vcreate_v_u8m1_u8m2( \
__riscv_vrgather_vv_u8m1(tbl, __riscv_vget_v_u8m2_u8m1(idx, 0), \
__riscv_vsetvlmax_e8m1()), \
__riscv_vrgather_vv_u8m1(tbl, __riscv_vget_v_u8m2_u8m1(idx, 1), \
__riscv_vsetvlmax_e8m1()))
#define simdutf_vrgather_u8m1x4(tbl, idx) \
__riscv_vcreate_v_u8m1_u8m4( \
__riscv_vrgather_vv_u8m1(tbl, __riscv_vget_v_u8m4_u8m1(idx, 0), \
__riscv_vsetvlmax_e8m1()), \
__riscv_vrgather_vv_u8m1(tbl, __riscv_vget_v_u8m4_u8m1(idx, 1), \
__riscv_vsetvlmax_e8m1()), \
__riscv_vrgather_vv_u8m1(tbl, __riscv_vget_v_u8m4_u8m1(idx, 2), \
__riscv_vsetvlmax_e8m1()), \
__riscv_vrgather_vv_u8m1(tbl, __riscv_vget_v_u8m4_u8m1(idx, 3), \
__riscv_vsetvlmax_e8m1()))
#if __riscv_zbc
#include <riscv_bitmanip.h>
#endif
#endif // SIMDJSON_RVV_VLS_INTRINSICS_H
@@ -0,0 +1,56 @@
#ifndef SIMDJSON_RVV_VLS_NUMBERPARSING_DEFS_H
#define SIMDJSON_RVV_VLS_NUMBERPARSING_DEFS_H
#ifndef SIMDJSON_CONDITIONAL_INCLUDE
#include "simdjson/rvv-vls/base.h"
#include "simdjson/internal/numberparsing_tables.h"
#endif // SIMDJSON_CONDITIONAL_INCLUDE
#include <cstring>
#ifdef JSON_TEST_NUMBERS // for unit testing
void found_invalid_number(const uint8_t *buf);
void found_integer(int64_t result, const uint8_t *buf);
void found_unsigned_integer(uint64_t result, const uint8_t *buf);
void found_float(double result, const uint8_t *buf);
#endif
namespace simdjson {
namespace rvv_vls {
namespace numberparsing {
// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/
/** @private */
static simdjson_inline uint32_t parse_eight_digits_unrolled(const char *chars) {
uint64_t val;
#if __riscv_misaligned_fast
memcpy(&val, chars, sizeof(uint64_t));
#else
val = __riscv_vmv_x(__riscv_vreinterpret_u64m1(__riscv_vlmul_ext_u8m1(__riscv_vle8_v_u8mf2((uint8_t*)chars, 8))));
#endif
val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8;
val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16;
return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32);
}
/** @private */
static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) {
return parse_eight_digits_unrolled(reinterpret_cast<const char *>(chars));
}
/** @private */
simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t value2) {
internal::value128 answer;
__uint128_t r = (static_cast<__uint128_t>(value1)) * value2;
answer.low = uint64_t(r);
answer.high = uint64_t(r >> 64);
return answer;
}
} // namespace numberparsing
} // namespace rvv_vls
} // namespace simdjson
#define SIMDJSON_SWAR_NUMBER_PARSING 1
#endif // SIMDJSON_RVV_VLS_NUMBERPARSING_DEFS_H
+8
View File
@@ -0,0 +1,8 @@
#ifndef SIMDJSON_RVV_VLS_ONDEMAND_H
#define SIMDJSON_RVV_VLS_ONDEMAND_H
#include "simdjson/rvv-vls/begin.h"
#include "simdjson/generic/ondemand/amalgamated.h"
#include "simdjson/rvv-vls/end.h"
#endif // SIMDJSON_RVV_VLS_ONDEMAND_H
+370
View File
@@ -0,0 +1,370 @@
#ifndef SIMDJSON_RVV_VLS_SIMD_H
#define SIMDJSON_RVV_VLS_SIMD_H
#ifndef SIMDJSON_CONDITIONAL_INCLUDE
#include "simdjson/rvv-vls/base.h"
#include "simdjson/rvv-vls/bitmanipulation.h"
#include "simdjson/internal/simdprune_tables.h"
#endif // SIMDJSON_CONDITIONAL_INCLUDE
namespace simdjson {
namespace rvv_vls {
namespace {
namespace simd {
#if __riscv_v_fixed_vlen >= 512
static constexpr size_t VL8 = 512/8;
using vint8_t = vint8m1_t __attribute__((riscv_rvv_vector_bits(512)));
using vuint8_t = vuint8m1_t __attribute__((riscv_rvv_vector_bits(512)));
using vbool_t = vbool8_t __attribute__((riscv_rvv_vector_bits(512/8)));
using vbitmask_t = uint64_t;
#else
static constexpr size_t VL8 = __riscv_v_fixed_vlen/8;
using vint8_t = vint8m1_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen)));
using vuint8_t = vuint8m1_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen)));
using vbool_t = vbool8_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen/8)));
#if __riscv_v_fixed_vlen == 128
using vbitmask_t = uint16_t;
#elif __riscv_v_fixed_vlen == 256
using vbitmask_t = uint32_t;
#endif
#endif
#if __riscv_v_fixed_vlen == 128
using vuint8x64_t = vuint8m4_t __attribute__((riscv_rvv_vector_bits(512)));
using vboolx64_t = vbool2_t __attribute__((riscv_rvv_vector_bits(512/8)));
#elif __riscv_v_fixed_vlen == 256
using vuint8x64_t = vuint8m2_t __attribute__((riscv_rvv_vector_bits(512)));
using vboolx64_t = vbool4_t __attribute__((riscv_rvv_vector_bits(512/8)));
#else
using vuint8x64_t = vuint8m1_t __attribute__((riscv_rvv_vector_bits(512)));
using vboolx64_t = vbool8_t __attribute__((riscv_rvv_vector_bits(512/8)));
#endif
template<typename T>
struct simd8;
// SIMD byte mask type (returned by things like eq and gt)
template<>
struct simd8<bool> {
vbool_t value;
using bitmask_t = vbitmask_t;
static constexpr int SIZE = sizeof(value);
simdjson_inline simd8(const vbool_t _value) : value(_value) {}
simdjson_inline simd8() : simd8(__riscv_vmclr_m_b8(VL8)) {}
simdjson_inline simd8(bool _value) : simd8(splat(_value)) {}
simdjson_inline operator const vbool_t&() const { return value; }
simdjson_inline operator vbool_t&() { return value; }
static simdjson_inline simd8<bool> splat(bool _value) {
return __riscv_vreinterpret_b8(__riscv_vmv_v_x_u64m1(((uint64_t)!_value)-1, 1));
}
simdjson_inline vbitmask_t to_bitmask() const {
#if __riscv_v_fixed_vlen == 128
return __riscv_vmv_x(__riscv_vreinterpret_u16m1(value));
#elif __riscv_v_fixed_vlen == 256
return __riscv_vmv_x(__riscv_vreinterpret_u32m1(value));
#else
return __riscv_vmv_x(__riscv_vreinterpret_u64m1(value));
#endif
}
// Bit operations
simdjson_inline simd8<bool> operator|(const simd8<bool> other) const { return __riscv_vmor(*this, other, VL8); }
simdjson_inline simd8<bool> operator&(const simd8<bool> other) const { return __riscv_vmand(*this, other, VL8); }
simdjson_inline simd8<bool> operator^(const simd8<bool> other) const { return __riscv_vmxor(*this, other, VL8); }
simdjson_inline simd8<bool> bit_andnot(const simd8<bool> other) const { return __riscv_vmandn(other, *this, VL8); }
simdjson_inline simd8<bool> operator~() const { return __riscv_vmnot(*this, VL8); }
simdjson_inline simd8<bool>& operator|=(const simd8<bool> other) { auto this_cast = static_cast<simd8<bool>*>(this); *this_cast = *this_cast | other; return *this_cast; }
simdjson_inline simd8<bool>& operator&=(const simd8<bool> other) { auto this_cast = static_cast<simd8<bool>*>(this); *this_cast = *this_cast & other; return *this_cast; }
simdjson_inline simd8<bool>& operator^=(const simd8<bool> other) { auto this_cast = static_cast<simd8<bool>*>(this); *this_cast = *this_cast ^ other; return *this_cast; }
};
// Unsigned bytes
template<>
struct simd8<uint8_t> {
vuint8_t value;
static constexpr int SIZE = sizeof(value);
simdjson_inline simd8(const vuint8_t _value) : value(_value) {}
simdjson_inline simd8() : simd8(zero()) {}
simdjson_inline simd8(const uint8_t values[VL8]) : simd8(load(values)) {}
simdjson_inline simd8(uint8_t _value) : simd8(splat(_value)) {}
simdjson_inline simd8(simd8<bool> mask) : value(__riscv_vmerge_vxm_u8m1(zero(), -1, (vbool_t)mask, VL8)) {}
simdjson_inline operator const vuint8_t&() const { return this->value; }
simdjson_inline operator vuint8_t&() { return this->value; }
simdjson_inline simd8(
uint8_t v0, uint8_t v1, uint8_t v2, uint8_t v3, uint8_t v4, uint8_t v5, uint8_t v6, uint8_t v7,
uint8_t v8, uint8_t v9, uint8_t v10, uint8_t v11, uint8_t v12, uint8_t v13, uint8_t v14, uint8_t v15
) : simd8(vuint8_t{
v0, v1, v2, v3, v4, v5, v6, v7,
v8, v9, v10,v11,v12,v13,v14,v15
}) {}
// Repeat 16 values as many times as necessary (usually for lookup tables)
simdjson_inline static simd8<uint8_t> repeat_16(
uint8_t v0, uint8_t v1, uint8_t v2, uint8_t v3, uint8_t v4, uint8_t v5, uint8_t v6, uint8_t v7,
uint8_t v8, uint8_t v9, uint8_t v10, uint8_t v11, uint8_t v12, uint8_t v13, uint8_t v14, uint8_t v15
) {
return simd8<uint8_t>(
v0, v1, v2, v3, v4, v5, v6, v7,
v8, v9, v10,v11,v12,v13,v14,v15
);
}
static simdjson_inline vuint8_t splat(uint8_t _value) { return __riscv_vmv_v_x_u8m1(_value, VL8); }
static simdjson_inline vuint8_t zero() { return splat(0); }
static simdjson_inline vuint8_t load(const uint8_t values[VL8]) { return __riscv_vle8_v_u8m1(values, VL8); }
// Bit operations
simdjson_inline simd8<uint8_t> operator|(const simd8<uint8_t> other) const { return __riscv_vor_vv_u8m1( value, other, VL8); }
simdjson_inline simd8<uint8_t> operator&(const simd8<uint8_t> other) const { return __riscv_vand_vv_u8m1( value, other, VL8); }
simdjson_inline simd8<uint8_t> operator^(const simd8<uint8_t> other) const { return __riscv_vxor_vv_u8m1( value, other, VL8); }
simdjson_inline simd8<uint8_t> operator~() const { return __riscv_vnot_v_u8m1(value, VL8); }
#if __riscv_zvbb
simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return __riscv_vandn_vv_u8m1(other, value, VL8); }
#else
simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return other & ~*this; }
#endif
simdjson_inline simd8<uint8_t>& operator|=(const simd8<uint8_t> other) { value = *this | other; return *this; }
simdjson_inline simd8<uint8_t>& operator&=(const simd8<uint8_t> other) { value = *this & other; return *this; }
simdjson_inline simd8<uint8_t>& operator^=(const simd8<uint8_t> other) { value = *this ^ other; return *this; }
simdjson_inline simd8<bool> operator==(const simd8<uint8_t> other) const { return __riscv_vmseq(value, other, VL8); }
simdjson_inline simd8<bool> operator==(uint8_t other) const { return __riscv_vmseq(value, other, VL8); }
template<int N=1>
simdjson_inline simd8<uint8_t> prev(const simd8<uint8_t> prev_chunk) const {
return __riscv_vslideup(__riscv_vslidedown(prev_chunk, VL8-N, VL8), value, N, VL8);
}
// Store to array
simdjson_inline void store(uint8_t dst[VL8]) const { return __riscv_vse8(dst, value, VL8); }
// Saturated math
simdjson_inline simd8<uint8_t> saturating_add(const simd8<uint8_t> other) const { return __riscv_vsaddu(value, other, VL8); }
simdjson_inline simd8<uint8_t> saturating_sub(const simd8<uint8_t> other) const { return __riscv_vssubu(value, other, VL8); }
// Addition/subtraction are the same for signed and unsigned
simdjson_inline simd8<uint8_t> operator+(const simd8<uint8_t> other) const { return __riscv_vadd(value, other, VL8); }
simdjson_inline simd8<uint8_t> operator-(const simd8<uint8_t> other) const { return __riscv_vsub(value, other, VL8); }
simdjson_inline simd8<uint8_t>& operator+=(const simd8<uint8_t> other) { value = *this + other; return *this; }
simdjson_inline simd8<uint8_t>& operator-=(const simd8<uint8_t> other) { value = *this - other; return *this; }
// Order-specific operations
simdjson_inline simd8<bool> operator<=(const simd8<uint8_t> other) const { return __riscv_vmsleu(value, other, VL8); }
simdjson_inline simd8<bool> operator>=(const simd8<uint8_t> other) const { return __riscv_vmsgeu(value, other, VL8); }
simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return __riscv_vmsltu(value, other, VL8); }
simdjson_inline simd8<bool> operator>(const simd8<uint8_t> other) const { return __riscv_vmsgtu(value, other, VL8); }
// Same as >, but instead of guaranteeing all 1's == true, false = 0 and true = nonzero.
simdjson_inline simd8<uint8_t> gt_bits(const simd8<uint8_t> other) const { return simd8<uint8_t>(*this > other); }
// Same as <, but instead of guaranteeing all 1's == true, false = 0 and true = nonzero.
simdjson_inline simd8<uint8_t> lt_bits(const simd8<uint8_t> other) const { return simd8<uint8_t>(*this < other); }
// Bit-specific operations
simdjson_inline bool any_bits_set_anywhere() const {
return __riscv_vfirst(__riscv_vmsne(value, 0, VL8), VL8) >= 0;
}
simdjson_inline bool any_bits_set_anywhere(simd8<uint8_t> bits) const { return (*this & bits).any_bits_set_anywhere(); }
template<int N>
simdjson_inline simd8<uint8_t> shr() const { return __riscv_vsrl(value, N, VL8); }
template<int N>
simdjson_inline simd8<uint8_t> shl() const { return __riscv_vsll(value, N, VL8); }
// Perform a lookup assuming the value is between 0 and 16 (undefined behavior for out of range values)
template<typename L>
simdjson_inline simd8<L> lookup_16(simd8<L> lookup_table) const {
return __riscv_vrgather(lookup_table, value, VL8);
}
// compress inactive elements, to match AVX-512 behavior
template<typename L>
simdjson_inline void compress(vbitmask_t mask, L * output) const {
mask = (vbitmask_t)~mask;
#if __riscv_v_fixed_vlen == 128
vbool8_t m = __riscv_vreinterpret_b8(__riscv_vmv_s_x_u16m1(mask, 1));
#elif __riscv_v_fixed_vlen == 256
vbool8_t m = __riscv_vreinterpret_b8(__riscv_vmv_s_x_u32m1(mask, 1));
#else
vbool8_t m = __riscv_vreinterpret_b8(__riscv_vmv_s_x_u64m1(mask, 1));
#endif
__riscv_vse8_v_u8m1(output, __riscv_vcompress(value, m, VL8), count_ones(mask));
}
template<typename L>
simdjson_inline simd8<L> lookup_16(
L replace0, L replace1, L replace2, L replace3,
L replace4, L replace5, L replace6, L replace7,
L replace8, L replace9, L replace10, L replace11,
L replace12, L replace13, L replace14, L replace15) const {
return lookup_16(simd8<L>::repeat_16(
replace0, replace1, replace2, replace3,
replace4, replace5, replace6, replace7,
replace8, replace9, replace10, replace11,
replace12, replace13, replace14, replace15
));
}
};
// Signed bytes
template<>
struct simd8<int8_t> {
vint8_t value;
static constexpr int SIZE = sizeof(value);
simdjson_inline simd8(const vint8_t _value) : value(_value) {}
simdjson_inline simd8() : simd8(zero()) {}
simdjson_inline simd8(const int8_t values[VL8]) : simd8(load(values)) {}
simdjson_inline simd8(int8_t _value) : simd8(splat(_value)) {}
simdjson_inline operator const vint8_t&() const { return this->value; }
simdjson_inline operator vint8_t&() { return this->value; }
simdjson_inline simd8(
int8_t v0, int8_t v1, int8_t v2, int8_t v3, int8_t v4, int8_t v5, int8_t v6, int8_t v7,
int8_t v8, int8_t v9, int8_t v10, int8_t v11, int8_t v12, int8_t v13, int8_t v14, int8_t v15
) : simd8(vint8_t{
v0, v1, v2, v3, v4, v5, v6, v7,
v8, v9, v10,v11,v12,v13,v14,v15
}) {}
// Repeat 16 values as many times as necessary (usually for lookup tables)
simdjson_inline static simd8<int8_t> repeat_16(
int8_t v0, int8_t v1, int8_t v2, int8_t v3, int8_t v4, int8_t v5, int8_t v6, int8_t v7,
int8_t v8, int8_t v9, int8_t v10, int8_t v11, int8_t v12, int8_t v13, int8_t v14, int8_t v15
) {
return simd8<int8_t>(
v0, v1, v2, v3, v4, v5, v6, v7,
v8, v9, v10,v11,v12,v13,v14,v15
);
}
static simdjson_inline vint8_t splat(int8_t _value) { return __riscv_vmv_v_x_i8m1(_value, VL8); }
static simdjson_inline vint8_t zero() { return splat(0); }
static simdjson_inline vint8_t load(const int8_t values[VL8]) { return __riscv_vle8_v_i8m1(values, VL8); }
simdjson_inline void store(int8_t dst[VL8]) const { return __riscv_vse8(dst, value, VL8); }
// Explicit conversion to/from unsigned
simdjson_inline explicit simd8(const vuint8_t other): simd8(__riscv_vreinterpret_i8m1(other)) {}
simdjson_inline explicit operator simd8<uint8_t>() const { return __riscv_vreinterpret_u8m1(value); }
// Math
simdjson_inline simd8<int8_t> operator+(const simd8<int8_t> other) const { return __riscv_vadd(value, other, VL8); }
simdjson_inline simd8<int8_t> operator-(const simd8<int8_t> other) const { return __riscv_vsub(value, other, VL8); }
simdjson_inline simd8<int8_t>& operator+=(const simd8<int8_t> other) { value = *this + other; return *this; }
simdjson_inline simd8<int8_t>& operator-=(const simd8<int8_t> other) { value = *this - other; return *this; }
// Order-sensitive comparisons
simdjson_inline simd8<int8_t> max_val( const simd8<int8_t> other) const { return __riscv_vmax( value, other, VL8); }
simdjson_inline simd8<int8_t> min_val( const simd8<int8_t> other) const { return __riscv_vmin( value, other, VL8); }
simdjson_inline simd8<bool> operator>( const simd8<int8_t> other) const { return __riscv_vmsgt(value, other, VL8); }
simdjson_inline simd8<bool> operator<( const simd8<int8_t> other) const { return __riscv_vmslt(value, other, VL8); }
simdjson_inline simd8<bool> operator==(const simd8<int8_t> other) const { return __riscv_vmseq(value, other, VL8); }
template<int N=1>
simdjson_inline simd8<int8_t> prev(const simd8<int8_t> prev_chunk) const {
return __riscv_vslideup(__riscv_vslidedown(prev_chunk, VL8-N, VL8), value, N, VL8);
}
// Perform a lookup assuming no value is larger than 16
template<typename L>
simdjson_inline simd8<L> lookup_16(simd8<L> lookup_table) const {
return __riscv_vrgather(lookup_table, value, VL8);
}
template<typename L>
simdjson_inline simd8<L> lookup_16(
L replace0, L replace1, L replace2, L replace3,
L replace4, L replace5, L replace6, L replace7,
L replace8, L replace9, L replace10, L replace11,
L replace12, L replace13, L replace14, L replace15) const {
return lookup_16(simd8<L>::repeat_16(
replace0, replace1, replace2, replace3,
replace4, replace5, replace6, replace7,
replace8, replace9, replace10, replace11,
replace12, replace13, replace14, replace15
));
}
};
template<typename T>
struct simd8x64;
template<>
struct simd8x64<uint8_t> {
static constexpr int NUM_CHUNKS = 64 / sizeof(simd8<uint8_t>);
vuint8x64_t value;
#if __riscv_v_fixed_vlen >= 512
template<int idx> simd8<uint8_t> get() const { return value; }
#else
template<int idx> simd8<uint8_t> get() const { return __riscv_vget_u8m1(value, idx); }
#endif
simdjson_inline operator const vuint8x64_t&() const { return this->value; }
simdjson_inline operator vuint8x64_t&() { return this->value; }
simd8x64(const simd8x64<uint8_t>& o) = delete; // no copy allowed
simd8x64<uint8_t>& operator=(const simd8<uint8_t>& other) = delete; // no assignment allowed
simd8x64() = delete; // no default constructor allowed
#if __riscv_v_fixed_vlen == 128
simdjson_inline simd8x64(const uint8_t *ptr, size_t n = 64) : value(__riscv_vle8_v_u8m4(ptr, n)) {}
#elif __riscv_v_fixed_vlen == 256
simdjson_inline simd8x64(const uint8_t *ptr, size_t n = 64) : value(__riscv_vle8_v_u8m2(ptr, n)) {}
#else
simdjson_inline simd8x64(const uint8_t *ptr, size_t n = 64) : value(__riscv_vle8_v_u8m1(ptr, n)) {}
#endif
simdjson_inline void store(uint8_t ptr[64]) const {
__riscv_vse8(ptr, value, 64);
}
simdjson_inline bool is_ascii() const {
#if __riscv_v_fixed_vlen == 128
return __riscv_vfirst(__riscv_vmslt(__riscv_vreinterpret_i8m4(value), 0, 64), 64) < 0;
#elif __riscv_v_fixed_vlen == 256
return __riscv_vfirst(__riscv_vmslt(__riscv_vreinterpret_i8m2(value), 0, 64), 64) < 0;
#else
return __riscv_vfirst(__riscv_vmslt(__riscv_vreinterpret_i8m1(value), 0, 64), 64) < 0;
#endif
}
// compress inactive elements, to match AVX-512 behavior
simdjson_inline uint64_t compress(uint64_t mask, uint8_t * output) const {
mask = ~mask;
#if __riscv_v_fixed_vlen == 128
vboolx64_t m = __riscv_vreinterpret_b2(__riscv_vmv_s_x_u64m1(mask, 1));
#elif __riscv_v_fixed_vlen == 256
vboolx64_t m = __riscv_vreinterpret_b4(__riscv_vmv_s_x_u64m1(mask, 1));
#else
vboolx64_t m = __riscv_vreinterpret_b8(__riscv_vmv_s_x_u64m1(mask, 1));
#endif
size_t cnt = count_ones(mask);
__riscv_vse8(output, __riscv_vcompress(value, m, 64), cnt);
return cnt;
}
simdjson_inline uint64_t eq(const uint8_t m) const {
return __riscv_vmv_x(__riscv_vreinterpret_u64m1(__riscv_vmseq(value, m, 64)));
}
simdjson_inline uint64_t lteq(const uint8_t m) const {
return __riscv_vmv_x(__riscv_vreinterpret_u64m1(__riscv_vmsleu(value, m, 64)));
}
}; // struct simd8x64<uint8_t>
} // namespace simd
} // unnamed namespace
} // namespace rvv_vls
} // namespace simdjson
#endif // SIMDJSON_RVV_VLS_SIMD_H

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