Compare commits
37 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8e85352df4 | |||
| fc57c09cf0 | |||
| 2058b47dfe | |||
| b0486c7fa2 | |||
| feb1e7feb6 | |||
| 2c7fbc1538 | |||
| 8b69401d8a | |||
| f504e57e7a | |||
| 135c173053 | |||
| b4ed3a99a9 | |||
| d8e1b36c88 | |||
| c249a1b456 | |||
| 9c4b793c90 | |||
| dd92a8414c | |||
| 835bdba123 | |||
| ad3cd71ca2 | |||
| 860f7e0458 | |||
| 980f2ad3af | |||
| 7ad9fe63a6 | |||
| 7987418b1f | |||
| 5e871f6724 | |||
| 5d16fd5f31 | |||
| 4e9ff03af5 | |||
| aa7489060a | |||
| ae32422891 | |||
| 667d0ed3c7 | |||
| b1c31b428d | |||
| 56ac56ba32 | |||
| 19549c60ec | |||
| 16e99f229b | |||
| 21342a4142 | |||
| d0e841d3e9 | |||
| a962652ec3 | |||
| 77d73b068a | |||
| 19ff7a572d | |||
| 403b8bfb91 | |||
| 76f45a0c4b |
@@ -38,7 +38,7 @@ If we cannot reproduce the issue, then we cannot address it. Note that a stack t
|
||||
|
||||
It should be possible to trigger the bug by using solely simdjson with our default build setup. If you can only observe the bug within some specific context, with some other software, please reduce the issue first.
|
||||
|
||||
**simjson release**
|
||||
**simdjson release**
|
||||
|
||||
Unless you plan to contribute to simdjson, you should only work from releases. Please be mindful that our main branch may have additional features, bugs and documentation items.
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ Description
|
||||
|
||||
Type of change
|
||||
- [ ] Bug fix
|
||||
- [ ] Optimization
|
||||
- [ ] New feature
|
||||
- [ ] Refactor / cleanup
|
||||
- [ ] Documentation / tests
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
cmake_minimum_required(VERSION 3.14)
|
||||
|
||||
# Build performance optimizations
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON CACHE BOOL "Export compile commands for faster IDE integration")
|
||||
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
|
||||
|
||||
# Enable parallel compilation on MSVC
|
||||
if(MSVC)
|
||||
add_compile_options(/MP)
|
||||
endif()
|
||||
|
||||
project(
|
||||
simdjson
|
||||
# The version number is modified by tools/release.py
|
||||
VERSION 4.2.1
|
||||
VERSION 4.2.4
|
||||
DESCRIPTION "Parsing gigabytes of JSON per second"
|
||||
HOMEPAGE_URL "https://simdjson.org/"
|
||||
LANGUAGES CXX C
|
||||
@@ -83,10 +92,36 @@ add_library(simdjson ${SIMDJSON_SOURCES})
|
||||
add_library(simdjson::simdjson ALIAS simdjson)
|
||||
set(SIMDJSON_LIBRARIES simdjson)
|
||||
|
||||
# Enable precompiled headers for faster builds
|
||||
if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.16")
|
||||
target_precompile_headers(simdjson PRIVATE
|
||||
<algorithm>
|
||||
<array>
|
||||
<atomic>
|
||||
<bit>
|
||||
<cassert>
|
||||
<cctype>
|
||||
<cerrno>
|
||||
<cstddef>
|
||||
<cstdint>
|
||||
<cstdlib>
|
||||
<cstring>
|
||||
<memory>
|
||||
<string>
|
||||
<utility>
|
||||
<vector>
|
||||
)
|
||||
endif()
|
||||
|
||||
if(SIMDJSON_BUILD_STATIC_LIB)
|
||||
add_library(simdjson_static STATIC ${SIMDJSON_SOURCES})
|
||||
add_library(simdjson::simdjson_static ALIAS simdjson_static)
|
||||
list(APPEND SIMDJSON_LIBRARIES simdjson_static)
|
||||
|
||||
# Reuse precompiled headers for static library
|
||||
if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.16")
|
||||
target_precompile_headers(simdjson_static REUSE_FROM simdjson)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
set_target_properties(
|
||||
@@ -112,6 +147,14 @@ simdjson_add_props(
|
||||
PRIVATE "$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/src>"
|
||||
)
|
||||
|
||||
# Optimize linker settings for faster builds
|
||||
if(MSVC)
|
||||
target_link_options(simdjson PRIVATE /INCREMENTAL)
|
||||
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
|
||||
target_link_options(simdjson PRIVATE /DEBUG:FASTLINK)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(SIMDJSON_STATIC_REFLECTION)
|
||||
# We would like to require C++26, but no compiler supports that!
|
||||
# This is a hack:
|
||||
@@ -140,24 +183,6 @@ if(SIMDJSON_MINUS_ZERO_AS_FLOAT)
|
||||
simdjson_add_props(target_compile_definitions PRIVATE SIMDJSON_MINUS_ZERO_AS_FLOAT=1)
|
||||
endif(SIMDJSON_MINUS_ZERO_AS_FLOAT)
|
||||
|
||||
if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(loongarch64)$")
|
||||
option(SIMDJSON_PREFER_LSX "Prefer LoongArch SX" ON)
|
||||
include(CheckCXXCompilerFlag)
|
||||
check_cxx_compiler_flag(-mlasx COMPILER_SUPPORTS_LASX)
|
||||
check_cxx_compiler_flag(-mlsx COMPILER_SUPPORTS_LSX)
|
||||
if(COMPILER_SUPPORTS_LASX AND NOT SIMDJSON_PREFER_LSX)
|
||||
simdjson_add_props(
|
||||
target_compile_options PRIVATE
|
||||
-mlasx
|
||||
)
|
||||
elseif(COMPILER_SUPPORTS_LSX)
|
||||
simdjson_add_props(
|
||||
target_compile_options PRIVATE
|
||||
-mlsx
|
||||
)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# GCC and Clang have horrendous Debug builds when using SIMD.
|
||||
# A common fix is to use '-Og' instead.
|
||||
# bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54412
|
||||
@@ -171,7 +196,12 @@ if(
|
||||
target_compile_options PRIVATE
|
||||
$<$<CONFIG:DEBUG>:-Og>
|
||||
)
|
||||
endif()
|
||||
# We still want to enable development checks in Debug mode
|
||||
simdjson_add_props(
|
||||
target_compile_definitions PUBLIC
|
||||
SIMDJSON_DEVELOPMENT_CHECKS
|
||||
)
|
||||
endif()
|
||||
|
||||
if(SIMDJSON_ENABLE_THREADS)
|
||||
find_package(Threads REQUIRED)
|
||||
|
||||
@@ -38,7 +38,7 @@ PROJECT_NAME = simdjson
|
||||
# could be handy for archiving the generated documentation or if some version
|
||||
# control system is used.
|
||||
|
||||
PROJECT_NUMBER = "4.2.1"
|
||||
PROJECT_NUMBER = "4.2.4"
|
||||
|
||||
# Using the PROJECT_BRIEF tag one can provide an optional one line description
|
||||
# for a project that appears at the top of each page and should give viewer a
|
||||
|
||||
@@ -110,6 +110,24 @@ workflows used by simdjson.
|
||||
Directory Structure and Source
|
||||
------------------------------
|
||||
|
||||
Before diving into the directory structure, here are key concepts used in the codebase:
|
||||
|
||||
- **Amalgamated File**: A file that is conditionally included in the amalgamation process. These are wrapped in `#ifndef SIMDJSON_CONDITIONAL_INCLUDE` blocks and are included based on the target implementation (e.g., ARM64, x86). They include implementation-specific files (e.g., `arm64.h`) and generic files (e.g., under `generic/`). Amalgamated files have associated dependency files (`dependencies.h`) to track includes.
|
||||
|
||||
- **Amalgamator File**: A file that orchestrates the inclusion of amalgamated files. Examples: `arm64.h`, `arm64/implementation.h`, `generic/amalgamated.h`. These are not themselves amalgamated but control conditional inclusions.
|
||||
|
||||
- **Free Dependency File**: A top-level header that is always included unconditionally. These do not have dependency files and represent the public API (e.g., main headers).
|
||||
|
||||
- **Implementation-Specific File**: A file tied to a specific CPU architecture or instruction set (e.g., `arm64/`, `haswell/`). These must be amalgamated.
|
||||
|
||||
- **Generic File**: A shared file (under `generic/` or `simdjson/generic/`) that contains common code included once per implementation.
|
||||
|
||||
- **Builtin File**: Special files under `simdjson/builtin/` that handle the builtin implementation, a fallback/default implementation used when no optimized implementation is available.
|
||||
|
||||
- **Conditional Include Block**: A section wrapped in `#ifndef SIMDJSON_CONDITIONAL_INCLUDE` for editor-only or implementation-specific content.
|
||||
|
||||
The script `singleheader/amalgation_helper.py` will generate an HTML report which you can use to visualize the status of each file.
|
||||
|
||||
simdjson's source structure, from the top level, looks like this:
|
||||
|
||||
* **CMakeLists.txt:** The main build system.
|
||||
@@ -133,6 +151,12 @@ simdjson's source structure, from the top level, looks like this:
|
||||
* simdjson/generic/ondemand/*.h: individual On-Demand classes, generically written.
|
||||
* simdjson/generic/ondemand/dependencies.h: dependencies on common, non-implementation-specific simdjson classes. This will be included before including amalgamated.h.
|
||||
* simdjson/generic/ondemand/amalgamated.h: all generic ondemand classes for an implementation.
|
||||
* simdjson/builder.h: the `simdjson::builder` namespace. Includes all public builder classes.
|
||||
* simdjson/builtin/builder.h: the `simdjson::builtin::builder` namespace.
|
||||
* simdjson/arm64|fallback|haswell|icelake|ppc64|westmere/builder.h: the `simdjson::<implementation>::builder` namespace. Builder compiled for the specific implementation.
|
||||
* simdjson/generic/builder/*.h: individual Builder classes, generically written.
|
||||
* simdjson/generic/builder/dependencies.h: dependencies on common, non-implementation-specific simdjson classes. This will be included before including amalgamated.h.
|
||||
* simdjson/generic/builder/amalgamated.h: all generic builder classes for an implementation.
|
||||
* **src:** The source files for non-inlined functionality (e.g. the architecture-specific parser
|
||||
implementations).
|
||||
* simdjson.cpp: A "main source" that includes all implementation files from src/. This is
|
||||
@@ -147,6 +171,7 @@ Other important files and directories:
|
||||
* **.github/workflows:** Definitions for GitHub Actions (CI).
|
||||
* **singleheader:** Contains generated `simdjson.h` and `simdjson.cpp` that we release. The files `singleheader/simdjson.h` and `singleheader/simdjson.cpp` should never be edited by hand.
|
||||
* **singleheader/amalgamate.py:** Generates `singleheader/simdjson.h` and `singleheader/simdjson.cpp` for release (python script). If you add a new implementation (e.g., rvv), you need to edit this file (IMPLEMENTATIONS).
|
||||
* **singleheader/amalgation_helper.py:** Generates and `amalgamation_report.html` that helps you understand the status of each file.
|
||||
* **benchmark:** This is where we do benchmarking. Benchmarking is core to every change we make; the
|
||||
cardinal rule is don't regress performance without knowing exactly why, and what you're trading
|
||||
for it. Many of our benchmarks are microbenchmarks. We are effectively doing controlled scientific experiments for the purpose of understanding what affects our performance. So we simplify as much as possible. We try to avoid irrelevant factors such as page faults, interrupts, unnecessary system calls. We recommend checking the performance as follows:
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
simdjson : Parsing gigabytes of JSON per second
|
||||
===============================================
|
||||
|
||||
<img src="images/logo.png" width="10%" style="float: right">
|
||||
<img src="images/official_logo/logo_noir/SVG/logo_simdjson_noir.svg" width="40%" style="float: right">
|
||||
|
||||
JSON is everywhere on the Internet. Servers spend a *lot* of time parsing it. We need a fresh
|
||||
approach. The simdjson library uses commonly available SIMD instructions and microparallel algorithms
|
||||
to parse JSON 4x faster than RapidJSON and 25x faster than JSON for Modern C++.
|
||||
@@ -212,6 +213,21 @@ For the video inclined, <br />
|
||||
[](http://www.youtube.com/watch?v=wlvKAT7SZIQ)<br />
|
||||
(It was the best voted talk, we're kinda proud of it.)
|
||||
|
||||
Citing this work
|
||||
-----------------
|
||||
|
||||
If you use simdjson in published research, please cite the software library. A suitable BibTeX entry is:
|
||||
|
||||
```bibtex
|
||||
@misc{simdjson,
|
||||
title={{The simdjson library: Parsing Gigabytes of JSON per Second}},
|
||||
author={Daniel Lemire and Geoff Langdale and John Keiser and Paul Dreik and Francisco Thiesen and others},
|
||||
year={2019},
|
||||
howpublished={Software library},
|
||||
note={https://github.com/simdjson/simdjson}
|
||||
}
|
||||
```
|
||||
|
||||
Funding
|
||||
-------
|
||||
|
||||
|
||||
@@ -245,7 +245,7 @@ static u32 (*kpc_get_counter_count)(u32 classes);
|
||||
|
||||
/// Get counter accumulations.
|
||||
/// If `all_cpus` is true, the buffer count should not smaller than
|
||||
/// (cpu_count * counter_count). Otherwize, the buffer count should not smaller
|
||||
/// (cpu_count * counter_count). Otherwise, the buffer count should not smaller
|
||||
/// than (counter_count).
|
||||
/// @see kpc_get_counter_count(), kpc_cpu_count().
|
||||
/// @param all_cpus true for all CPUs, false for current cpu.
|
||||
@@ -374,7 +374,7 @@ static int kperf_lightweight_pet_set(u32 enabled) {
|
||||
// These functions do not require root privileges.
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
// KPEP CPU archtecture constants.
|
||||
// KPEP CPU architecture constants.
|
||||
#define KPEP_ARCH_I386 0
|
||||
#define KPEP_ARCH_X86_64 1
|
||||
#define KPEP_ARCH_ARM 2
|
||||
@@ -414,7 +414,7 @@ typedef struct kpep_db {
|
||||
usize fixed_counter_count;
|
||||
usize config_counter_count;
|
||||
usize power_counter_count;
|
||||
u32 archtecture; ///< see `KPEP CPU archtecture constants` above.
|
||||
u32 architecture; ///< see `KPEP CPU architecture constants` above.
|
||||
u32 fixed_counter_bits;
|
||||
u32 config_counter_bits;
|
||||
u32 power_counter_bits;
|
||||
|
||||
@@ -169,8 +169,10 @@ For efficiency reasons, simdjson requires a string with a few bytes (`simdjson::
|
||||
at the end, these bytes may be read but their content does not affect the parsing. In practice,
|
||||
it means that the JSON inputs should be stored in a memory region with `simdjson::SIMDJSON_PADDING`
|
||||
extra bytes at the end. You do not have to set these bytes to specific values though you may
|
||||
want to if you want to avoid runtime warnings with some sanitizers. Advanced users may want to
|
||||
read the section Free Padding in [our performance notes](performance.md).
|
||||
want to if you want to avoid runtime warnings with some sanitizers. We expect the user
|
||||
of the library to load the data (from disk or from the network) into a padded buffer. To make
|
||||
this easy, we provide the `padded_string::load` function which loads files from disk in a padded buffer.
|
||||
[You can similarly fetch a file from a URL to a padded string](https://github.com/simdjson/curltostring) using our `simdjson::padded_string_builder`. Advanced users may want to read the section Free Padding in [our performance notes](performance.md).
|
||||
|
||||
The simdjson library offers a tree-like [API](https://en.wikipedia.org/wiki/API), which you can
|
||||
access by creating a `ondemand::parser` and calling the `iterate()` method. The iterate method
|
||||
@@ -183,6 +185,9 @@ auto json = padded_string::load("twitter.json"); // load JSON file 'twitter.json
|
||||
ondemand::document doc = parser.iterate(json); // position a pointer at the beginning of the JSON data
|
||||
```
|
||||
|
||||
(Windows users compiling with C++17 or better may use `wchar_t` strings to support non-ASCII
|
||||
filenames: `padded_string::load(L"twitter.json")`.)
|
||||
|
||||
If you prefer not to create your own `ondemand::parser` instance, you can access
|
||||
a thread-local version by calling `ondemand::parser.get_parser()`.
|
||||
|
||||
@@ -351,7 +356,13 @@ the macro `SIMDJSON_DEVELOPMENT_CHECKS` to 1 prior to including
|
||||
the `simdjson.h` header to enable these additional checks: just make sure you remove the
|
||||
definition once your code has been tested. When `SIMDJSON_DEVELOPMENT_CHECKS` is set to 1, the
|
||||
simdjson library runs additional (expensive) tests on your code to help ensure that you are
|
||||
using the library in a safe manner.
|
||||
using the library in a safe manner. We add asserts which may halt your program, helping
|
||||
you find the bad programming pattern.
|
||||
|
||||
When `SIMDJSON_DEVELOPMENT_CHECKS`, some of our data structures contain extra data for
|
||||
tracking explicitly potential programming mistakes. Thus you should not relying on the
|
||||
size (`sizeof`) of our data structures to be constant: they may change depending on the
|
||||
compiler settings.
|
||||
|
||||
Once your code has been tested, you can then run it in
|
||||
Release mode: under Visual Studio, it means having the `_DEBUG` macro undefined, and, for other
|
||||
@@ -434,8 +445,8 @@ support for users who avoid exceptions. See [the simdjson error handling documen
|
||||
|
||||
If you know the type of the value, you can cast it right there, too! `for (double value : array) { ... }`.
|
||||
|
||||
You may also use explicit iterators: `for(auto i = array.begin(); i != array.end(); i++) {}`. You can check that an array is empty with the condition `auto i = array.begin(); if (i == array.end()) {...}`.
|
||||
* **Object Iteration:** You can iterate through an object's fields, as well: `for (auto field : object) { ... }`. You may also use explicit iterators : `for(auto i = object.begin(); i != object.end(); i++) { auto field = *i; .... }`. You can check that an object is empty with the condition `auto i = object.begin(); if (i == object.end()) {...}`.
|
||||
You may also use explicit iterators: `for(auto i = array.begin(); i != array.end(); i++) {}`. You can check that an array is empty with the condition `auto i = array.begin(); if (i == array.end()) {...}`. You should derefence (`*i`) an iterator at most once before incrementing it (`i++`), when compiling in debug mode with development checks, we add asserts to help you identify such a mistake.
|
||||
* **Object Iteration:** You can iterate through an object's fields, as well: `for (auto field : object) { ... }`.
|
||||
- `field.unescaped_key()` will get you the unescaped key string as a `std::string_view` instance. E.g., the JSON string `"\u00e1"` becomes the Unicode string `á`. Optionally, you pass `true` as a parameter to the `unescaped_key` method if you want invalid escape sequences to be replaced by a default replacement character (e.g., `\ud800\ud801\ud811`): otherwise bad escape sequences lead to an immediate error.
|
||||
- `field.escaped_key()` will get you the key string as as a `std::string_view` instance, but unlike `unescaped_key()`, the key is not processed, so no unescaping is done. E.g., the JSON string `"\u00e1"` becomes the Unicode string `\u00e1`. We expect that `escaped_key()` is faster than `field.unescaped_key()`.
|
||||
- `field.value()` will get you the value, which you can then use all these other methods on.
|
||||
@@ -448,8 +459,12 @@ support for users who avoid exceptions. See [the simdjson error handling documen
|
||||
|
||||
When you are iterating through an object, you are advancing through its keys and values. You should not also access the object or other objects. E.g. within a loop over `myobject`, you should not be accessing `myobject`. The following is an anti-pattern: `for(auto value: myobject) {myobject["mykey"]}`.
|
||||
|
||||
We discourage using the object iterators explicitly: `for(auto i = object.begin(); i != object.end(); i++) { auto field = *i; .... }`. In addition to the usual requirement to check against `end()` prior to dereferencing, you must also always dereference the pointer (`*it`) exactly once before you increment it (`it++`). You must also only deference the iterator once (never more than once). When compiling in
|
||||
debug mode with development checks, we add asserts to help check whether you correctly
|
||||
dereferenced the pointer before incrementing it.
|
||||
|
||||
You should never reset an object as you are iterating through it. The following is an anti-pattern: `for(auto value: myobject) {myobject.reset()}`.
|
||||
* **Array Index:** Because it is forward-only, you cannot look up an array element by index by index. Instead,
|
||||
* **Array Index:** Because it is forward-only, you cannot look up an array element by index. Instead,
|
||||
you should iterate through the array and keep an index yourself. Exceptionally, if need a single value
|
||||
out of the array, you may use an array access (e.g., `array[1]`). You should never reset an array as you are iterating through it. The following is an anti-pattern: `for(auto value: myarray) {myarray.reset()}`.
|
||||
* **Field Access:** To get the value of the "foo" field in an object, use `object["foo"]`. This will
|
||||
@@ -524,13 +539,13 @@ support for users who avoid exceptions. See [the simdjson error handling documen
|
||||
> auto silly_json = R"( { "test": "result" } )"_padded;
|
||||
> ondemand::document doc = parser.iterate(silly_json);
|
||||
> std::cout << simdjson::to_json_string(doc["test"]) << std::endl; // Requires simdjson 1.0 or better
|
||||
>````
|
||||
> ```
|
||||
> ```cpp
|
||||
> // retrieves an unescaped string value as a string_view instance
|
||||
> auto silly_json = R"( { "test": "result" } )"_padded;
|
||||
> ondemand::document doc = parser.iterate(silly_json);
|
||||
> std::cout << std::string_view(doc["test"]) << std::endl;
|
||||
>````
|
||||
> ```
|
||||
You can use `to_json_string` to efficiently extract components of a JSON document to reconstruct a new JSON document, as in the following example:
|
||||
> ```cpp
|
||||
> auto cars_json = R"( [
|
||||
@@ -559,7 +574,7 @@ support for users who avoid exceptions. See [the simdjson error handling documen
|
||||
> oss << "]";
|
||||
> auto json_string = oss.str();
|
||||
> // json_string == "[[ 40.1, 39.9, 37.7, 40.4 ],[ 30.1, 31.0, 28.6, 28.7 ]]"
|
||||
>````
|
||||
> ```
|
||||
* **Extracting Values (without exceptions):** You can use a variant usage of `get()` with error
|
||||
codes to avoid exceptions. You first declare the variable of the appropriate type (`double`,
|
||||
`uint64_t`, `int64_t`, `bool`, `ondemand::object` and `ondemand::array`) and pass it by reference
|
||||
|
||||
@@ -14,6 +14,7 @@ speed and high convenience.
|
||||
* [C++26 static reflection](#c--26-static-reflection)
|
||||
+ [Without `string_buffer` instance](#without--string-buffer--instance)
|
||||
+ [Without `string_buffer` instance but with explicit error handling](#without--string-buffer--instance-but-with-explicit-error-handling)
|
||||
+ [Pretty formatted (fractured JSON)](#pretty-formatted-fractured-json)
|
||||
|
||||
Overview: string_builder
|
||||
---------------------------
|
||||
@@ -332,7 +333,7 @@ pattern:
|
||||
|
||||
### Customization
|
||||
|
||||
If you want to serialize a value in a custome way, you can do it with a
|
||||
If you want to serialize a value in a custom way, you can do it with a
|
||||
`tag_invoke` specialization like the following example which will map
|
||||
the year attribute to a string.
|
||||
|
||||
@@ -363,4 +364,50 @@ void tag_invoke(serialize_tag, builder_type &builder, const Car& car) {
|
||||
}
|
||||
|
||||
} // namespace simdjson
|
||||
```
|
||||
```
|
||||
|
||||
### Pretty formatted (fractured JSON)
|
||||
|
||||
In some instances, you may want your JSON to be more readable. For this pupose, we also
|
||||
support the Fractured JSON standard.
|
||||
|
||||
```Cpp
|
||||
TableTestData data{
|
||||
{{1, "Alice", true}, {2, "Bob", false}, {3, "Carol", true}, {4, "Dave", false}}
|
||||
};
|
||||
|
||||
fractured_json_options opts;
|
||||
opts.enable_table_format = true;
|
||||
opts.min_table_rows = 3;
|
||||
|
||||
std::string formatted = simdjson::to_fractured_json_string(data, opts);
|
||||
```
|
||||
|
||||
The result might be as follows.
|
||||
|
||||
```json
|
||||
{
|
||||
"records": [
|
||||
{ "active": true , "id": 1, "name": "Alice" },
|
||||
{ "active": false, "id": 2, "name": "Bob" },
|
||||
{ "active": true , "id": 3, "name": "Carol" },
|
||||
{ "active": false, "id": 4, "name": "Dave" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The `fractured_json_options` struct allows you to customize the formatting behavior. It includes the following options:
|
||||
|
||||
- `max_total_line_length` (default: 120): Maximum total characters per line. Content exceeding this will be expanded to multiple lines.
|
||||
- `max_inline_length` (default: 80): Maximum length for inlined elements. Simple arrays/objects shorter than this may be rendered inline.
|
||||
- `max_inline_complexity` (default: 2): Maximum nesting depth for inline rendering. Elements with complexity exceeding this will be expanded. Complexity 0 = scalar, 1 = flat array/object, 2 = one level of nesting.
|
||||
- `max_compact_array_complexity` (default: 1): Maximum complexity for compact array formatting. Arrays with elements of this complexity or less may have multiple items per line.
|
||||
- `indent_spaces` (default: 4): Number of spaces per indentation level.
|
||||
- `enable_table_format` (default: true): Enable tabular formatting for arrays of similar objects. When enabled, arrays of objects with identical keys are formatted as aligned tables.
|
||||
- `min_table_rows` (default: 3): Minimum number of rows to trigger table mode.
|
||||
- `table_similarity_threshold` (default: 0.8): Similarity threshold for table detection. Objects must share at least this fraction of keys to be formatted as a table.
|
||||
- `enable_compact_multiline` (default: true): Enable compact multiline arrays. When enabled, arrays of simple elements may have multiple items per line.
|
||||
- `max_items_per_line` (default: 10): Maximum array items per line in compact mode.
|
||||
- `simple_bracket_padding` (default: true): Add space inside brackets for simple containers. When true: `{ "key": "value" }`, when false: `{"key": "value"}`.
|
||||
- `colon_padding` (default: true): Add space after colons. When true: `"key": "value"`, when false: `"key":"value"`.
|
||||
- `comma_padding` (default: true): Add space after commas in inline content. When true: `[1, 2, 3]`, when false: `[1,2,3]`.
|
||||
@@ -1,6 +1,7 @@
|
||||
# Parse json at compile time
|
||||
* [Introduction](#introduction)
|
||||
* [Example](#example)
|
||||
* [Concepts](#concepts)
|
||||
* [Loading from disk](#loading-from-disk)
|
||||
* [Limitations (compile-time errors)](#limitations-compile-time-errors)
|
||||
|
||||
@@ -106,6 +107,68 @@ static_assert(arr.size() == 3);
|
||||
static_assert(arr[1] == 2);
|
||||
```
|
||||
|
||||
|
||||
## Concepts
|
||||
|
||||
Given that the parsed data is made of structures that depend on the JSON input, you might
|
||||
want to check that it conforms to your expectation. You can do so with concepts.
|
||||
|
||||
Let us consider this example:
|
||||
|
||||
```cpp
|
||||
constexpr auto config = R"(
|
||||
|
||||
[
|
||||
{ "name": "Alice", "age": 30 },
|
||||
{ "name": "Bob", "age": 25 },
|
||||
{ "name": "Charlie", "age": 35 }
|
||||
]
|
||||
|
||||
)"_json;
|
||||
```
|
||||
|
||||
You might want to ensure that the result is an array of persons. You can define your
|
||||
expectation with concepts like so:
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
concept person = requires(T p) {
|
||||
std::string_view(p.name); // has name field convertible to string_view
|
||||
p.age; // has age field
|
||||
requires std::is_integral_v<decltype(p.age)>; // age is integral
|
||||
};
|
||||
|
||||
/**
|
||||
* Concept to validate that a type is an array of person objects
|
||||
*/
|
||||
template <typename T>
|
||||
concept array_of_person = requires(T arr) {
|
||||
arr.size(); // has size method
|
||||
arr[0]; // can access elements with []
|
||||
requires person<decltype(arr[0])>; // elements satisfy person concept
|
||||
};
|
||||
```
|
||||
|
||||
And then a simple static assert with `decltype` is sufficient to check that the expectation is met:
|
||||
|
||||
```cpp
|
||||
constexpr auto config = R"(
|
||||
|
||||
[
|
||||
{ "name": "Alice", "age": 30 },
|
||||
{ "name": "Bob", "age": 25 },
|
||||
{ "name": "Charlie", "age": 35 }
|
||||
]
|
||||
|
||||
)"_json;
|
||||
|
||||
|
||||
// Validate that the array satisfies the array_of_person concept
|
||||
static_assert(array_of_person<decltype(config)>);
|
||||
```
|
||||
|
||||
|
||||
|
||||
## Loading from disk
|
||||
|
||||
In practice, you may have a JSON file, say `json_data` that you want to parse
|
||||
|
||||
@@ -54,6 +54,24 @@ dom::parser parser;
|
||||
dom::element doc = parser.parse("[1,2,3]"_padded); // parse a string, the _padded suffix creates a simdjson::padded_string instance
|
||||
```
|
||||
|
||||
You can also load a `padded_string` from a file.
|
||||
|
||||
|
||||
```cpp
|
||||
auto json = padded_string::load("twitter.json"); // load JSON file 'twitter.json'.
|
||||
dom::element doc = parser.parse(json);
|
||||
```
|
||||
|
||||
[You can similarly fetch a file from a URL to a padded string](https://github.com/simdjson/curltostring) using our `simdjson::padded_string_builder`.
|
||||
|
||||
(Windows users compiling with C++17 or better may use `wchar_t` strings to support non-ASCII
|
||||
filenames: `padded_string::load(L"twitter.json")`.)
|
||||
|
||||
|
||||
(Windows users compiling with C++17 or better may use `wchar_t` strings to support non-ASCII
|
||||
filenames: `padded_string::load(L"twitter.json")`.)
|
||||
|
||||
|
||||
You can copy your data directly on a `simdjson::padded_string` as follows:
|
||||
|
||||
```cpp
|
||||
@@ -827,7 +845,7 @@ memcpy(padded_json_copy.get(), json, json_len);
|
||||
memset(padded_json_copy.get() + json_len, 0, SIMDJSON_PADDING);
|
||||
simdjson::dom::parser parser;
|
||||
simdjson::dom::element element = parser.parse(padded_json_copy.get(), json_len, false);
|
||||
````
|
||||
```
|
||||
|
||||
Setting the `realloc_if_needed` parameter `false` in this manner may lead to better performance since copies are avoided, but it requires that the user takes more responsibilities: the simdjson library cannot verify that the input buffer was padded with SIMDJSON_PADDING extra bytes.
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ library provides high-speed access to files or streams containing multiple small
|
||||
{"text":"a"}
|
||||
{"text":"b"}
|
||||
{"text":"c"}
|
||||
...
|
||||
"..."
|
||||
```
|
||||
... you want to read the entries (individual JSON documents) as quickly and as conveniently as possible. Importantly, the input might span several gigabytes, but you want to use a small (fixed) amount of memory. Ideally, you'd also like the parallelize the processing (using more than one core) to speed up the process.
|
||||
|
||||
@@ -403,4 +403,4 @@ Otherwise you may use this longer version for explicit handling of errors:
|
||||
}
|
||||
cars.push_back(c);
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
@@ -545,7 +545,7 @@ To help visualize the algorithm, we'll walk through the example C++ given at the
|
||||
"statuses": [
|
||||
{ "id": 1, "text": "first!", "user": { "screen_name": "lemire", "name": "Daniel" }, "retweet_count": 40 },
|
||||
{ "id": 2, "text": "second!", "user": { "screen_name": "jkeiser2", "name": "John" }, "retweet_count": 3 }
|
||||
^ (depth 3 - root > statuses > tweet)
|
||||
^ (depth 4 - root > statuses > tweet > field)
|
||||
],
|
||||
"search_metadata": { "count": 2 }
|
||||
}
|
||||
|
||||
@@ -297,4 +297,62 @@ int main() {
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
```
|
||||
|
||||
Further, whenever you allocate N bytes, memory allocators tend to allocate more memory, without you necessarily knowing about it. Under linux, you can use the `malloc_usable_size` function to see how much memory was actually allocated.
|
||||
Under an Apple plateform, you can `malloc_size`. The following program illustrates the usage.
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
#include <cstddef>
|
||||
#include <memory>
|
||||
#include <cstdlib>
|
||||
#ifdef __APPLE__
|
||||
#include <malloc/malloc.h> // for malloc_size on macOS
|
||||
#endif
|
||||
#ifdef __linux__
|
||||
#include <malloc.h> // for malloc_usable_size on Linux
|
||||
#endif
|
||||
size_t get_usable_size(void* ptr) {
|
||||
#ifdef __linux__
|
||||
return malloc_usable_size(ptr);
|
||||
#elif defined(__APPLE__)
|
||||
return malloc_size(ptr);
|
||||
#else
|
||||
return 0; // Unsupported platform
|
||||
#endif
|
||||
}
|
||||
|
||||
int main() {
|
||||
std::cout << "Demonstrating allocation overhead and rounding with operator new\n\n";
|
||||
|
||||
#ifdef __linux__
|
||||
std::cout << "Platform: Linux\n";
|
||||
#elif defined(__APPLE__)
|
||||
std::cout << "Platform: macOS (using malloc_size)\n";
|
||||
#else
|
||||
std::cout << "Platform: Other/unsupported (usable size will show 0)\n";
|
||||
#endif
|
||||
|
||||
std::cout << "Requested size | Actual usable size\n";
|
||||
std::cout << "---------------|-------------------\n";
|
||||
size_t total_requested = 0;
|
||||
size_t total_usable = 0;
|
||||
for (size_t requested = 1; requested <= 4096; requested++) {
|
||||
total_requested += requested;
|
||||
std::unique_ptr<char[]> ptr(new char[requested]); // Allocate
|
||||
size_t usable = get_usable_size(ptr.get()); // Get usable size
|
||||
total_usable += usable;
|
||||
|
||||
std::cout << requested << "\t | " << usable << "\n";
|
||||
}
|
||||
std::cout << "---------------|-------------------\n";
|
||||
std::cout << "Total requested: " << total_requested << " bytes\n";
|
||||
std::cout << "Total usable: " << total_usable << " bytes\n";
|
||||
std::cout << "Total overhead: " << (total_usable - total_requested) << " bytes\n";
|
||||
std::cout << "Percentage overhead: "
|
||||
<< ((total_usable - total_requested) * 100.0 / total_requested) << " %\n";
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
```
|
||||
@@ -8,16 +8,11 @@
|
||||
* Minifies by first parsing, then minifying.
|
||||
*/
|
||||
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
|
||||
|
||||
auto begin = as_chars(Data);
|
||||
auto end = begin + Size;
|
||||
|
||||
std::string str(begin, end);
|
||||
simdjson::padded_string str(reinterpret_cast<const char *>(Data), Size);
|
||||
simdjson::dom::parser parser;
|
||||
simdjson::dom::element elem;
|
||||
auto error = parser.parse(str).get(elem);
|
||||
if (error) { return 0; }
|
||||
|
||||
std::string minified = simdjson::minify(elem);
|
||||
(void)minified;
|
||||
return 0;
|
||||
|
||||
@@ -35,7 +35,7 @@ cmake .. \
|
||||
-DSIMDJSON_DISABLE_DEPRECATED_API=On \
|
||||
-DSIMDJSON_FUZZ_LDFLAGS=$LIB_FUZZING_ENGINE
|
||||
|
||||
cmake --build . --target all_fuzzers
|
||||
cmake --build . --target all_fuzzers all_tests
|
||||
|
||||
cp fuzz/fuzz_* $OUT
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 226 KiB |
|
After Width: | Height: | Size: 136 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 108 KiB |
|
After Width: | Height: | Size: 256 KiB |
|
After Width: | Height: | Size: 136 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 109 KiB |
|
After Width: | Height: | Size: 258 KiB |
|
After Width: | Height: | Size: 136 KiB |
@@ -52,6 +52,7 @@
|
||||
#include "simdjson/padded_string_view-inl.h"
|
||||
|
||||
#include "simdjson/dom.h"
|
||||
#include "simdjson/builder.h"
|
||||
#include "simdjson/ondemand.h"
|
||||
#include "simdjson/convert.h"
|
||||
#include "simdjson/convert-inl.h"
|
||||
|
||||
@@ -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
|
||||
@@ -17,6 +17,7 @@ using namespace simd;
|
||||
struct backslash_and_quote {
|
||||
public:
|
||||
static constexpr uint32_t BYTES_PROCESSED = 32;
|
||||
// We only copy if dst is non-null.
|
||||
simdjson_inline backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
|
||||
|
||||
simdjson_inline bool has_quote_first() { return ((bs_bits - 1) & quote_bits) != 0; }
|
||||
@@ -34,8 +35,10 @@ simdjson_inline backslash_and_quote backslash_and_quote::copy_and_find(const uin
|
||||
static_assert(SIMDJSON_PADDING >= (BYTES_PROCESSED - 1), "backslash and quote finder must process fewer than SIMDJSON_PADDING bytes");
|
||||
simd8<uint8_t> v0(src);
|
||||
simd8<uint8_t> v1(src + sizeof(v0));
|
||||
v0.store(dst);
|
||||
v1.store(dst + sizeof(v0));
|
||||
if(dst != nullptr) {
|
||||
v0.store(dst);
|
||||
v1.store(dst + sizeof(v0));
|
||||
}
|
||||
|
||||
// Getting a 64-bit bitmask is much cheaper than multiple 16-bit bitmasks on ARM; therefore, we
|
||||
// smash them together into a 64-byte mask and get the bitmask from there.
|
||||
|
||||
@@ -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
|
||||
@@ -20,10 +20,10 @@
|
||||
#include "simdjson/ppc64.h"
|
||||
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(westmere)
|
||||
#include "simdjson/westmere.h"
|
||||
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lsx)
|
||||
#include "simdjson/lsx.h"
|
||||
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lasx)
|
||||
#include "simdjson/lasx.h"
|
||||
#elif SIMDJSON_BUILTIN_IMPLEMENTATION_IS(lsx)
|
||||
#include "simdjson/lsx.h"
|
||||
#else
|
||||
#error Unknown SIMDJSON_BUILTIN_IMPLEMENTATION
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
#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"
|
||||
#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
|
||||
@@ -289,7 +289,9 @@ namespace std {
|
||||
// when the compiler is optimizing.
|
||||
// We only set SIMDJSON_DEVELOPMENT_CHECKS if both __OPTIMIZE__
|
||||
// and NDEBUG are not defined.
|
||||
#if !defined(__OPTIMIZE__) && !defined(NDEBUG)
|
||||
// We recognize _DEBUG as overriding __OPTIMIZE__ so that if both
|
||||
// __OPTIMIZE__ and _DEBUG are defined, we still set SIMDJSON_DEVELOPMENT_CHECKS.
|
||||
#if ((!defined(__OPTIMIZE__) || defined(_DEBUG)) && !defined(NDEBUG))
|
||||
#define SIMDJSON_DEVELOPMENT_CHECKS 1
|
||||
#endif // __OPTIMIZE__
|
||||
#endif // _MSC_VER
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#include "simdjson/dom/object.h"
|
||||
#include "simdjson/dom/parser.h"
|
||||
#include "simdjson/dom/serialization.h"
|
||||
#include "simdjson/dom/fractured_json.h"
|
||||
|
||||
// Inline functions
|
||||
#include "simdjson/dom/array-inl.h"
|
||||
@@ -19,5 +20,6 @@
|
||||
#include "simdjson/dom/parser-inl.h"
|
||||
#include "simdjson/internal/tape_ref-inl.h"
|
||||
#include "simdjson/dom/serialization-inl.h"
|
||||
#include "simdjson/dom/fractured_json-inl.h"
|
||||
|
||||
#endif // SIMDJSON_DOM_H
|
||||
|
||||
@@ -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
|
||||
@@ -204,10 +204,7 @@ public:
|
||||
*
|
||||
* ### std::string references
|
||||
*
|
||||
* If you pass a mutable std::string reference (std::string&), the parser will seek to extend
|
||||
* its capacity to SIMDJSON_PADDING bytes beyond the end of the string.
|
||||
*
|
||||
* Whenever you pass an std::string reference, the parser will access the bytes beyond the end of
|
||||
* Whenever you pass an std::string reference, the parser may access the bytes beyond the end of
|
||||
* the string but before the end of the allocated memory (std::string::capacity()).
|
||||
* If you are using a sanitizer that checks for reading uninitialized bytes or std::string's
|
||||
* container-overflow checks, you may encounter sanitizer warnings.
|
||||
@@ -239,7 +236,7 @@ public:
|
||||
/** @overload parse(const uint8_t *buf, size_t len, bool realloc_if_needed) */
|
||||
simdjson_inline simdjson_result<element> parse(const char *buf, size_t len, bool realloc_if_needed = true) & noexcept;
|
||||
simdjson_inline simdjson_result<element> parse(const char *buf, size_t len, bool realloc_if_needed = true) && =delete;
|
||||
/** @overload parse(const uint8_t *buf, size_t len, bool realloc_if_needed) */
|
||||
/** @overload parse(const std::string &) */
|
||||
simdjson_inline simdjson_result<element> parse(const std::string &s) & noexcept;
|
||||
simdjson_inline simdjson_result<element> parse(const std::string &s) && =delete;
|
||||
/** @overload parse(const uint8_t *buf, size_t len, bool realloc_if_needed) */
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
namespace simdjson {
|
||||
|
||||
inline bool is_fatal(error_code error) noexcept {
|
||||
return error == TAPE_ERROR || error == INCOMPLETE_ARRAY_OR_OBJECT;
|
||||
return error == TAPE_ERROR || error == INCOMPLETE_ARRAY_OR_OBJECT || error == OUT_OF_ORDER_ITERATION || error == DEPTH_ERROR;
|
||||
}
|
||||
|
||||
namespace internal {
|
||||
|
||||
@@ -265,6 +265,8 @@ struct simdjson_result_base : protected std::pair<T, error_code> {
|
||||
*/
|
||||
simdjson_inline T&& value_unsafe() && noexcept;
|
||||
|
||||
using value_type = T;
|
||||
using error_type = error_code;
|
||||
}; // struct simdjson_result_base
|
||||
|
||||
} // namespace internal
|
||||
@@ -376,6 +378,8 @@ struct simdjson_result : public internal::simdjson_result_base<T> {
|
||||
*/
|
||||
simdjson_inline T&& value_unsafe() && noexcept;
|
||||
|
||||
using value_type = T;
|
||||
using error_type = error_code;
|
||||
}; // struct simdjson_result
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
|
||||
@@ -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
|
||||
@@ -13,6 +13,7 @@ namespace {
|
||||
struct backslash_and_quote {
|
||||
public:
|
||||
static constexpr uint32_t BYTES_PROCESSED = 1;
|
||||
// We only copy if dst is non-null.
|
||||
simdjson_inline backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
|
||||
|
||||
simdjson_inline bool has_quote_first() { return c == '"'; }
|
||||
@@ -25,7 +26,9 @@ public:
|
||||
|
||||
simdjson_inline backslash_and_quote backslash_and_quote::copy_and_find(const uint8_t *src, uint8_t *dst) {
|
||||
// store to dest unconditionally - we can overwrite the bits we don't like later
|
||||
dst[0] = src[0];
|
||||
if(dst != nullptr) {
|
||||
dst[0] = src[0];
|
||||
}
|
||||
return { src[0] };
|
||||
}
|
||||
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
#include "simdjson/arm64/begin.h"
|
||||
#elif SIMDJSON_IMPLEMENTATION_PPC64
|
||||
#include "simdjson/ppc64/begin.h"
|
||||
#elif SIMDJSON_IMPLEMENTATION_LSX
|
||||
#include "simdjson/lsx/begin.h"
|
||||
#elif SIMDJSON_IMPLEMENTATION_LASX
|
||||
#include "simdjson/lasx/begin.h"
|
||||
#elif SIMDJSON_IMPLEMENTATION_LSX
|
||||
#include "simdjson/lsx/begin.h"
|
||||
#elif SIMDJSON_IMPLEMENTATION_FALLBACK
|
||||
#include "simdjson/fallback/begin.h"
|
||||
#else
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
#if defined(SIMDJSON_CONDITIONAL_INCLUDE) && !defined(SIMDJSON_GENERIC_BUILDER_DEPENDENCIES_H)
|
||||
#error simdjson/generic/builder/dependencies.h must be included before simdjson/generic/builder/amalgamated.h!
|
||||
#endif
|
||||
|
||||
#include "simdjson/generic/builder/json_string_builder.h"
|
||||
#include "simdjson/generic/builder/json_builder.h"
|
||||
#include "simdjson/generic/builder/fractured_json_builder.h"
|
||||
|
||||
|
||||
|
||||
// JSON builder inline definitions
|
||||
#include "simdjson/generic/builder/json_string_builder-inl.h"
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
#ifdef SIMDJSON_CONDITIONAL_INCLUDE
|
||||
#error simdjson/generic/builder/dependencies.h must be included before defining SIMDJSON_CONDITIONAL_INCLUDE!
|
||||
#endif
|
||||
|
||||
#ifndef SIMDJSON_GENERIC_BUILDER_DEPENDENCIES_H
|
||||
#define SIMDJSON_GENERIC_BUILDER_DEPENDENCIES_H
|
||||
|
||||
// Internal headers needed for builder generics.
|
||||
// All includes not under simdjson/generic/builder must be here!
|
||||
// Otherwise, amalgamation will fail.
|
||||
#include "simdjson/concepts.h"
|
||||
#include "simdjson/dom/fractured_json.h"
|
||||
|
||||
#endif // SIMDJSON_GENERIC_BUILDER_DEPENDENCIES_H
|
||||
@@ -0,0 +1,117 @@
|
||||
#ifndef SIMDJSON_GENERIC_FRACTURED_JSON_BUILDER_H
|
||||
#define SIMDJSON_GENERIC_FRACTURED_JSON_BUILDER_H
|
||||
|
||||
#ifndef SIMDJSON_CONDITIONAL_INCLUDE
|
||||
#include "simdjson/generic/builder/json_builder.h"
|
||||
#include "simdjson/dom/fractured_json.h"
|
||||
#endif // SIMDJSON_CONDITIONAL_INCLUDE
|
||||
|
||||
#if SIMDJSON_STATIC_REFLECTION
|
||||
|
||||
namespace simdjson {
|
||||
namespace SIMDJSON_IMPLEMENTATION {
|
||||
namespace builder {
|
||||
|
||||
/**
|
||||
* Serialize an object to a FracturedJson-formatted string.
|
||||
*
|
||||
* FracturedJson produces human-readable yet compact JSON output by intelligently
|
||||
* choosing between different layout strategies (inline, compact multiline, table,
|
||||
* expanded) based on content complexity, length, and structure similarity.
|
||||
*
|
||||
* This function combines the builder's serialization with FracturedJson formatting:
|
||||
* 1. Serializes the object to minified JSON using reflection
|
||||
* 2. Parses and reformats using FracturedJson
|
||||
*
|
||||
* Example:
|
||||
* struct User { int id; std::string name; bool active; };
|
||||
* User user{1, "Alice", true};
|
||||
* auto result = to_fractured_json_string(user);
|
||||
* // result.value() == "{ \"id\": 1, \"name\": \"Alice\", \"active\": true }"
|
||||
*
|
||||
* @param obj The object to serialize (must be a reflectable type)
|
||||
* @param opts FracturedJson formatting options
|
||||
* @param initial_capacity Initial buffer capacity for serialization
|
||||
* @return The formatted JSON string, or an error
|
||||
*/
|
||||
template <class T>
|
||||
simdjson_warn_unused simdjson_result<std::string> to_fractured_json_string(
|
||||
const T& obj,
|
||||
const fractured_json_options& opts = {},
|
||||
size_t initial_capacity = string_builder::DEFAULT_INITIAL_CAPACITY) {
|
||||
// Step 1: Serialize to minified JSON
|
||||
std::string formatted;
|
||||
auto error = to_json_string(obj, initial_capacity).get(formatted);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
// Step 2: Reformat with FracturedJson
|
||||
return fractured_json_string(formatted, opts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract specific fields from an object and format with FracturedJson.
|
||||
*
|
||||
* Example:
|
||||
* struct User { int id; std::string name; std::string email; bool active; };
|
||||
* User user{1, "Alice", "alice@example.com", true};
|
||||
* auto result = extract_fractured_json<"id", "name">(user);
|
||||
* // result.value() == "{ \"id\": 1, \"name\": \"Alice\" }"
|
||||
*
|
||||
* @param obj The object to serialize
|
||||
* @param opts FracturedJson formatting options
|
||||
* @param initial_capacity Initial buffer capacity for serialization
|
||||
* @return The formatted JSON string containing only the specified fields
|
||||
*/
|
||||
template<constevalutil::fixed_string... FieldNames, typename T>
|
||||
requires(std::is_class_v<T> && (sizeof...(FieldNames) > 0))
|
||||
simdjson_warn_unused simdjson_result<std::string> extract_fractured_json(
|
||||
const T& obj,
|
||||
const fractured_json_options& opts = {},
|
||||
size_t initial_capacity = string_builder::DEFAULT_INITIAL_CAPACITY) {
|
||||
// Step 1: Extract fields to minified JSON
|
||||
std::string formatted;
|
||||
auto error = extract_from<FieldNames...>(obj, initial_capacity).get(formatted);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
// Step 2: Reformat with FracturedJson
|
||||
return fractured_json_string(formatted, opts);
|
||||
}
|
||||
|
||||
} // namespace builder
|
||||
} // namespace SIMDJSON_IMPLEMENTATION
|
||||
|
||||
// Global namespace convenience functions
|
||||
|
||||
/**
|
||||
* Serialize an object to a FracturedJson-formatted string.
|
||||
* Global namespace version for convenience.
|
||||
*/
|
||||
template <class T>
|
||||
simdjson_warn_unused simdjson_result<std::string> to_fractured_json_string(
|
||||
const T& obj,
|
||||
const fractured_json_options& opts = {},
|
||||
size_t initial_capacity = SIMDJSON_IMPLEMENTATION::builder::string_builder::DEFAULT_INITIAL_CAPACITY) {
|
||||
return SIMDJSON_IMPLEMENTATION::builder::to_fractured_json_string(obj, opts, initial_capacity);
|
||||
}
|
||||
/**
|
||||
* Extract specific fields from an object and format with FracturedJson.
|
||||
* Global namespace version for convenience.
|
||||
*/
|
||||
template<constevalutil::fixed_string... FieldNames, typename T>
|
||||
requires(std::is_class_v<T> && (sizeof...(FieldNames) > 0))
|
||||
simdjson_warn_unused simdjson_result<std::string> extract_fractured_json(
|
||||
const T& obj,
|
||||
const fractured_json_options& opts = {},
|
||||
size_t initial_capacity = SIMDJSON_IMPLEMENTATION::builder::string_builder::DEFAULT_INITIAL_CAPACITY) {
|
||||
return SIMDJSON_IMPLEMENTATION::builder::extract_fractured_json<FieldNames...>(obj, opts, initial_capacity);
|
||||
}
|
||||
|
||||
} // namespace simdjson
|
||||
|
||||
#endif // SIMDJSON_STATIC_REFLECTION
|
||||
|
||||
#endif // SIMDJSON_GENERIC_FRACTURED_JSON_BUILDER_H
|
||||
@@ -1,7 +1,3 @@
|
||||
/**
|
||||
* This file is part of the builder API. It is temporarily in the ondemand directory
|
||||
* but we will move it to a builder directory later.
|
||||
*/
|
||||
#ifndef SIMDJSON_GENERIC_BUILDER_H
|
||||
|
||||
#ifndef SIMDJSON_CONDITIONAL_INCLUDE
|
||||
@@ -1,7 +1,3 @@
|
||||
/**
|
||||
* This file is part of the builder API. It is temporarily in the ondemand
|
||||
* directory but we will move it to a builder directory later.
|
||||
*/
|
||||
#include <array>
|
||||
#include <cstring>
|
||||
#include <type_traits>
|
||||
@@ -519,8 +515,8 @@ simdjson_inline void string_builder::append(const T &opt) {
|
||||
|
||||
template <typename T>
|
||||
requires(require_custom_serialization<T>)
|
||||
simdjson_inline void string_builder::append(const T &val) {
|
||||
serialize(*this, val);
|
||||
simdjson_inline void string_builder::append(T &&val) {
|
||||
serialize(*this, std::forward<T>(val));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
@@ -534,11 +530,11 @@ simdjson_inline void string_builder::append(const T &value) {
|
||||
#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS
|
||||
// Support for range-based appending (std::ranges::view, etc.)
|
||||
template <std::ranges::range R>
|
||||
requires(!std::is_convertible<R, std::string_view>::value)
|
||||
requires(!std::is_convertible<R, std::string_view>::value && !require_custom_serialization<R>)
|
||||
simdjson_inline void string_builder::append(const R &range) noexcept {
|
||||
auto it = std::ranges::begin(range);
|
||||
auto end = std::ranges::end(range);
|
||||
if constexpr (concepts::is_pair<typename R::value_type>) {
|
||||
if constexpr (concepts::is_pair<std::ranges::range_value_t<R>>) {
|
||||
start_object();
|
||||
|
||||
if (it == end) {
|
||||
@@ -1,7 +1,3 @@
|
||||
/**
|
||||
* This file is part of the builder API. It is temporarily in the ondemand directory
|
||||
* but we will move it to a builder directory later.
|
||||
*/
|
||||
#ifndef SIMDJSON_GENERIC_STRING_BUILDER_H
|
||||
|
||||
#ifndef SIMDJSON_CONDITIONAL_INCLUDE
|
||||
@@ -24,9 +20,8 @@ struct has_custom_serialization : std::false_type {};
|
||||
|
||||
inline constexpr struct serialize_tag {
|
||||
template <typename T>
|
||||
requires custom_deserializable<T>
|
||||
constexpr void operator()(SIMDJSON_IMPLEMENTATION::builder::string_builder& b, T& obj) const{
|
||||
return tag_invoke(*this, b, obj);
|
||||
constexpr void operator()(SIMDJSON_IMPLEMENTATION::builder::string_builder& b, T&& obj) const{
|
||||
return tag_invoke(*this, b, std::forward<T>(obj));
|
||||
}
|
||||
|
||||
|
||||
@@ -165,7 +160,7 @@ public:
|
||||
|
||||
template <typename T>
|
||||
requires(require_custom_serialization<T>)
|
||||
simdjson_inline void append(const T &val);
|
||||
simdjson_inline void append(T &&val);
|
||||
|
||||
// Support for string-like types
|
||||
template <typename T>
|
||||
@@ -176,7 +171,7 @@ public:
|
||||
#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS
|
||||
// Support for range-based appending (std::ranges::view, etc.)
|
||||
template <std::ranges::range R>
|
||||
requires (!std::is_convertible<R, std::string_view>::value)
|
||||
requires (!std::is_convertible<R, std::string_view>::value && !require_custom_serialization<R>)
|
||||
simdjson_inline void append(const R &range) noexcept;
|
||||
#endif
|
||||
/**
|
||||
@@ -301,4 +296,4 @@ simdjson_warn_unused simdjson_error to_json(const Z &z, std::string &s, size_t i
|
||||
|
||||
} // namespace simdjson
|
||||
|
||||
#endif // SIMDJSON_GENERIC_STRING_BUILDER_H
|
||||
#endif // SIMDJSON_GENERIC_STRING_BUILDER_H
|
||||
@@ -40,6 +40,7 @@ public:
|
||||
simdjson_warn_unused error_code stage1(const uint8_t *buf, size_t len, stage1_mode partial) noexcept final;
|
||||
simdjson_warn_unused error_code stage2(dom::document &doc) noexcept final;
|
||||
simdjson_warn_unused error_code stage2_next(dom::document &doc) noexcept final;
|
||||
simdjson_warn_unused std::pair<const uint8_t *,bool> parse_string_if_needed(const uint8_t *src, uint8_t *dst, bool allow_replacement) const noexcept final;
|
||||
simdjson_warn_unused uint8_t *parse_string(const uint8_t *src, uint8_t *dst, bool allow_replacement) const noexcept final;
|
||||
simdjson_warn_unused uint8_t *parse_wobbly_string(const uint8_t *src, uint8_t *dst) const noexcept final;
|
||||
inline simdjson_warn_unused error_code set_capacity(size_t capacity) noexcept final;
|
||||
|
||||
@@ -138,6 +138,9 @@ struct implementation_simdjson_result_base {
|
||||
*/
|
||||
simdjson_inline T&& value_unsafe() && noexcept;
|
||||
|
||||
using value_type = T;
|
||||
using error_type = error_code;
|
||||
|
||||
protected:
|
||||
/** users should never directly access first and second. **/
|
||||
T first{}; /** Users should never directly access 'first'. **/
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#if defined(SIMDJSON_CONDITIONAL_INCLUDE) && !defined(SIMDJSON_GENERIC_ONDEMAND_DEPENDENCIES_H)
|
||||
#if defined(SIMDJSON_CONDITIONAL_INCLUDE) && !defined(SIMDJSON_GENERIC_BUILDER_DEPENDENCIES_H)
|
||||
#error simdjson/generic/ondemand/dependencies.h must be included before simdjson/generic/ondemand/amalgamated.h!
|
||||
#endif
|
||||
|
||||
@@ -14,9 +14,6 @@
|
||||
#include "simdjson/generic/ondemand/raw_json_string.h"
|
||||
#include "simdjson/generic/ondemand/parser.h"
|
||||
|
||||
// JSON builder - needed for extract_into functionality
|
||||
#include "simdjson/generic/ondemand/json_string_builder.h"
|
||||
|
||||
// All other declarations
|
||||
#include "simdjson/generic/ondemand/array.h"
|
||||
#include "simdjson/generic/ondemand/array_iterator.h"
|
||||
@@ -44,13 +41,9 @@
|
||||
#include "simdjson/generic/ondemand/object_iterator-inl.h"
|
||||
#include "simdjson/generic/ondemand/parser-inl.h"
|
||||
#include "simdjson/generic/ondemand/raw_json_string-inl.h"
|
||||
#include "simdjson/generic/ondemand/serialization-inl.h"
|
||||
#include "simdjson/generic/ondemand/token_iterator-inl.h"
|
||||
#include "simdjson/generic/ondemand/value_iterator-inl.h"
|
||||
|
||||
// JSON builder inline definitions
|
||||
#include "simdjson/generic/ondemand/json_string_builder-inl.h"
|
||||
#include "simdjson/generic/ondemand/json_builder.h"
|
||||
#include "simdjson/generic/ondemand/serialization-inl.h"
|
||||
|
||||
// JSON path accessor (compile-time) - must be after inline definitions
|
||||
#include "simdjson/generic/ondemand/compile_time_accessors.h"
|
||||
|
||||
@@ -17,6 +17,10 @@ simdjson_inline array_iterator::array_iterator(const value_iterator &_iter) noex
|
||||
{}
|
||||
|
||||
simdjson_inline simdjson_result<value> array_iterator::operator*() noexcept {
|
||||
#if SIMDJSON_DEVELOPMENT_CHECKS
|
||||
SIMDJSON_ASSUME(!has_been_referenced);
|
||||
has_been_referenced = true;
|
||||
#endif
|
||||
if (iter.error()) { iter.abandon(); return iter.error(); }
|
||||
return value(iter.child());
|
||||
}
|
||||
@@ -27,6 +31,9 @@ simdjson_inline bool array_iterator::operator!=(const array_iterator &) const no
|
||||
return iter.is_open();
|
||||
}
|
||||
simdjson_inline array_iterator &array_iterator::operator++() noexcept {
|
||||
#if SIMDJSON_DEVELOPMENT_CHECKS
|
||||
has_been_referenced = false;
|
||||
#endif
|
||||
error_code error;
|
||||
// PERF NOTE this is a safety rail ... users should exit loops as soon as they receive an error, so we'll never get here.
|
||||
// However, it does not seem to make a perf difference, so we add it out of an abundance of caution.
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#ifndef SIMDJSON_CONDITIONAL_INCLUDE
|
||||
#define SIMDJSON_GENERIC_ONDEMAND_ARRAY_ITERATOR_H
|
||||
#include <iterator>
|
||||
#include "simdjson/generic/implementation_simdjson_result_base.h"
|
||||
#include "simdjson/generic/ondemand/base.h"
|
||||
#include "simdjson/generic/ondemand/value_iterator.h"
|
||||
@@ -17,11 +18,17 @@ namespace ondemand {
|
||||
*
|
||||
* This is an input_iterator, meaning:
|
||||
* - It is forward-only
|
||||
* - * must be called exactly once per element.
|
||||
* - * must be called at most once per element.
|
||||
* - ++ must be called exactly once in between each * (*, ++, *, ++, * ...)
|
||||
*/
|
||||
class array_iterator {
|
||||
public:
|
||||
using iterator_category = std::input_iterator_tag;
|
||||
using value_type = simdjson_result<value>;
|
||||
using difference_type = std::ptrdiff_t;
|
||||
using pointer = void;
|
||||
using reference = value_type;
|
||||
|
||||
/** Create a new, invalid array iterator. */
|
||||
simdjson_inline array_iterator() noexcept = default;
|
||||
|
||||
@@ -65,6 +72,9 @@ public:
|
||||
simdjson_warn_unused simdjson_inline bool at_end() const noexcept;
|
||||
|
||||
private:
|
||||
#if SIMDJSON_DEVELOPMENT_CHECKS
|
||||
bool has_been_referenced{false};
|
||||
#endif
|
||||
value_iterator iter{};
|
||||
|
||||
simdjson_inline array_iterator(const value_iterator &iter) noexcept;
|
||||
@@ -82,6 +92,12 @@ namespace simdjson {
|
||||
|
||||
template<>
|
||||
struct simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::array_iterator> : public SIMDJSON_IMPLEMENTATION::implementation_simdjson_result_base<SIMDJSON_IMPLEMENTATION::ondemand::array_iterator> {
|
||||
using iterator_category = std::input_iterator_tag;
|
||||
using value_type = simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::value>;
|
||||
using difference_type = std::ptrdiff_t;
|
||||
using pointer = void;
|
||||
using reference = value_type;
|
||||
|
||||
simdjson_inline simdjson_result(SIMDJSON_IMPLEMENTATION::ondemand::array_iterator &&value) noexcept; ///< @private
|
||||
simdjson_inline simdjson_result(error_code error) noexcept; ///< @private
|
||||
simdjson_inline simdjson_result() noexcept = default;
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
// Internal headers needed for ondemand generics.
|
||||
// All includes not under simdjson/generic/ondemand must be here!
|
||||
// Otherwise, amalgamation will fail.
|
||||
#include "simdjson/concepts.h"
|
||||
#include "simdjson/dom/base.h" // for MINIMAL_DOCUMENT_CAPACITY
|
||||
#include "simdjson/implementation.h"
|
||||
#include "simdjson/padded_string.h"
|
||||
|
||||
@@ -403,7 +403,9 @@ public:
|
||||
simdjson_inline simdjson_result<array_iterator> end() & noexcept;
|
||||
|
||||
/**
|
||||
* Look up a field by name on an object (order-sensitive).
|
||||
* Look up a field by name on an object (order-sensitive). By order-sensitive, we mean that
|
||||
* fields must be accessed in the order they appear in the JSON text (although you can
|
||||
* skip fields). See find_field_unordered() and operator[] for an order-insensitive version.
|
||||
*
|
||||
* The following code reads z, then y, then x, and thus will not retrieve x or y if fed the
|
||||
* JSON `{ "x": 1, "y": 2, "z": 3 }`:
|
||||
@@ -447,7 +449,8 @@ public:
|
||||
* missing case has a non-cache-friendly bump and lots of extra scanning, especially if the object
|
||||
* in question is large. The fact that the extra code is there also bumps the executable size.
|
||||
*
|
||||
* It is the default, however, because it would be highly surprising (and hard to debug) if the
|
||||
* We default operator[] on find_field_unordered() for convenience.
|
||||
* It is the default because it would be highly surprising (and hard to debug) if the
|
||||
* default behavior failed to look up a field just because it was in the wrong order--and many
|
||||
* APIs assume this. Therefore, you must be explicit if you want to treat objects as out of order.
|
||||
*
|
||||
|
||||
@@ -215,11 +215,10 @@ simdjson_inline void json_iterator::assert_more_tokens(uint32_t required_tokens)
|
||||
}
|
||||
|
||||
simdjson_inline void json_iterator::assert_valid_position(token_position position) const noexcept {
|
||||
(void)position; // Suppress unused parameter warning
|
||||
#ifndef SIMDJSON_CLANG_VISUAL_STUDIO
|
||||
SIMDJSON_ASSUME( position >= &parser->implementation->structural_indexes[0] );
|
||||
SIMDJSON_ASSUME( position < &parser->implementation->structural_indexes[parser->implementation->n_structural_indexes] );
|
||||
#else
|
||||
(void)position; // Suppress unused parameter warning
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -358,17 +357,25 @@ simdjson_inline token_position json_iterator::position() const noexcept {
|
||||
simdjson_inline simdjson_result<std::string_view> json_iterator::unescape(raw_json_string in, bool allow_replacement) noexcept {
|
||||
#if SIMDJSON_DEVELOPMENT_CHECKS
|
||||
auto result = parser->unescape(in, _string_buf_loc, allow_replacement);
|
||||
#if !defined(SIMDJSON_VISUAL_STUDIO) && !defined(SIMDJSON_CLANG_VISUAL_STUDIO)
|
||||
// Under Visual Studio, the next SIMDJSON_ASSUME fails with: the argument
|
||||
// has side effects that will be discarded.
|
||||
SIMDJSON_ASSUME(!parser->string_buffer_overflow(_string_buf_loc));
|
||||
#endif // !defined(SIMDJSON_VISUAL_STUDIO) && !defined(SIMDJSON_CLANG_VISUAL_STUDIO)
|
||||
return result;
|
||||
#else
|
||||
return parser->unescape(in, _string_buf_loc, allow_replacement);
|
||||
return parser->unescape_maybe(in, _string_buf_loc, allow_replacement);
|
||||
#endif
|
||||
}
|
||||
|
||||
simdjson_inline simdjson_result<std::string_view> json_iterator::unescape_wobbly(raw_json_string in) noexcept {
|
||||
#if SIMDJSON_DEVELOPMENT_CHECKS
|
||||
auto result = parser->unescape_wobbly(in, _string_buf_loc);
|
||||
#if !defined(SIMDJSON_VISUAL_STUDIO) && !defined(SIMDJSON_CLANG_VISUAL_STUDIO)
|
||||
// Under Visual Studio, the next SIMDJSON_ASSUME fails with: the argument
|
||||
// has side effects that will be discarded.
|
||||
SIMDJSON_ASSUME(!parser->string_buffer_overflow(_string_buf_loc));
|
||||
#endif // !defined(SIMDJSON_VISUAL_STUDIO) && !defined(SIMDJSON_CLANG_VISUAL_STUDIO)
|
||||
return result;
|
||||
#else
|
||||
return parser->unescape_wobbly(in, _string_buf_loc);
|
||||
|
||||
@@ -27,10 +27,19 @@ public:
|
||||
*/
|
||||
simdjson_inline object() noexcept = default;
|
||||
|
||||
/**
|
||||
* Get an iterator to the start of the object. We recommend using a range-based for loop.
|
||||
*
|
||||
* Using the iterator directly is also possible but error-prone and discouraged. In particular,
|
||||
* you must dereference the iterator exactly once per iteration (before calling '++').
|
||||
* Doing otherwise is unsafe and may lead to errors. You are responsible for ensuring
|
||||
*/
|
||||
simdjson_inline simdjson_result<object_iterator> begin() noexcept;
|
||||
simdjson_inline simdjson_result<object_iterator> end() noexcept;
|
||||
/**
|
||||
* Look up a field by name on an object (order-sensitive).
|
||||
* Look up a field by name on an object (order-sensitive). By order-sensitive, we mean that
|
||||
* fields must be accessed in the order they appear in the JSON text (although you can
|
||||
* skip fields). See find_field_unordered() and operator[] for an order-insensitive version.
|
||||
*
|
||||
* The following code reads z, then y, then x, and thus will not retrieve x or y if fed the
|
||||
* JSON `{ "x": 1, "y": 2, "z": 3 }`:
|
||||
@@ -78,7 +87,8 @@ public:
|
||||
* missing case has a non-cache-friendly bump and lots of extra scanning, especially if the object
|
||||
* in question is large. The fact that the extra code is there also bumps the executable size.
|
||||
*
|
||||
* It is the default, however, because it would be highly surprising (and hard to debug) if the
|
||||
* We default operator[] on find_field_unordered() for convenience.
|
||||
* It is the default because it would be highly surprising (and hard to debug) if the
|
||||
* default behavior failed to look up a field just because it was in the wrong order--and many
|
||||
* APIs assume this. Therefore, you must be explicit if you want to treat objects as out of order.
|
||||
*
|
||||
|
||||
@@ -21,6 +21,11 @@ simdjson_inline object_iterator::object_iterator(const value_iterator &_iter) no
|
||||
{}
|
||||
|
||||
simdjson_inline simdjson_result<field> object_iterator::operator*() noexcept {
|
||||
#if SIMDJSON_DEVELOPMENT_CHECKS
|
||||
// We must call * once per iteration.
|
||||
SIMDJSON_ASSUME(!has_been_referenced);
|
||||
has_been_referenced = true;
|
||||
#endif
|
||||
error_code error = iter.error();
|
||||
if (error) { iter.abandon(); return error; }
|
||||
auto result = field::start(iter);
|
||||
@@ -39,6 +44,11 @@ simdjson_inline bool object_iterator::operator!=(const object_iterator &) const
|
||||
SIMDJSON_PUSH_DISABLE_WARNINGS
|
||||
SIMDJSON_DISABLE_STRICT_OVERFLOW_WARNING
|
||||
simdjson_inline object_iterator &object_iterator::operator++() noexcept {
|
||||
#if SIMDJSON_DEVELOPMENT_CHECKS
|
||||
// Before calling ++, we must have called *.
|
||||
SIMDJSON_ASSUME(has_been_referenced);
|
||||
has_been_referenced = false;
|
||||
#endif
|
||||
// TODO this is a safety rail ... users should exit loops as soon as they receive an error.
|
||||
// Nonetheless, let's see if performance is OK with this if statement--the compiler may give it to us for free.
|
||||
if (!iter.is_open()) { return *this; } // Iterator will be released if there is an error
|
||||
|
||||
@@ -32,9 +32,14 @@ public:
|
||||
// Assumes it's being compared with the end. true if depth >= iter->depth.
|
||||
simdjson_inline bool operator!=(const object_iterator &) const noexcept;
|
||||
// Checks for ']' and ','
|
||||
// YOU MUST NOT CALL THIS IF operator* YIELDED AN ERROR.
|
||||
// YOU MUST NOT CALL THIS WITHOUT A CORRESPONDING operator* CALL.
|
||||
simdjson_inline object_iterator &operator++() noexcept;
|
||||
|
||||
private:
|
||||
#if SIMDJSON_DEVELOPMENT_CHECKS
|
||||
bool has_been_referenced{false};
|
||||
#endif
|
||||
/**
|
||||
* The underlying JSON iterator.
|
||||
*
|
||||
|
||||
@@ -179,6 +179,20 @@ simdjson_inline void parser::set_max_capacity(size_t max_capacity) noexcept {
|
||||
}
|
||||
}
|
||||
|
||||
simdjson_inline simdjson_warn_unused simdjson_result<std::string_view> parser::unescape_maybe(raw_json_string in, uint8_t *&dst, bool allow_replacement) const noexcept {
|
||||
std::pair<const uint8_t *, bool> result = implementation->parse_string_if_needed(in.buf, dst, allow_replacement);
|
||||
const uint8_t *end = result.first;
|
||||
bool copied = result.second;
|
||||
if (!end) { return STRING_ERROR; }
|
||||
if(copied) {
|
||||
std::string_view strresult(reinterpret_cast<const char *>(dst), end-dst);
|
||||
dst = const_cast<uint8_t *>(end);
|
||||
return strresult;
|
||||
}
|
||||
// fast path, no copy was made!!!
|
||||
return std::string_view(reinterpret_cast<const char *>(in.buf), end-in.buf);
|
||||
}
|
||||
|
||||
simdjson_inline simdjson_warn_unused simdjson_result<std::string_view> parser::unescape(raw_json_string in, uint8_t *&dst, bool allow_replacement) const noexcept {
|
||||
uint8_t *end = implementation->parse_string(in.buf, dst, allow_replacement);
|
||||
if (!end) { return STRING_ERROR; }
|
||||
|
||||
@@ -334,6 +334,32 @@ public:
|
||||
*/
|
||||
simdjson_inline simdjson_result<std::string_view> unescape(raw_json_string in, uint8_t *&dst, bool allow_replacement = false) const noexcept;
|
||||
|
||||
/**
|
||||
* Unescape this JSON string, replacing \\ with \, \n with newline, etc. to a user-provided buffer if
|
||||
* needed. If no escaping is done, the string is returned as is and dst is not not changed.
|
||||
* The result must be valid UTF-8.
|
||||
* The provided pointer is advanced to the end of the string by reference if a copy is needed,
|
||||
* and a string_view instance
|
||||
* is returned. You can ensure that your buffer is large enough by allocating a block of memory at least
|
||||
* as large as the input JSON plus SIMDJSON_PADDING and then unescape all strings to this one buffer.
|
||||
*
|
||||
* This unescape_maybe function is a low-level function. If you want a more user-friendly approach, you should
|
||||
* avoid raw_json_string instances (e.g., by calling unescaped_key() instead of key() or get_string()
|
||||
* instead of get_raw_json_string()).
|
||||
*
|
||||
* ## IMPORTANT: string_view lifetime
|
||||
*
|
||||
* The string_view is only valid as long as the bytes in dst.
|
||||
*
|
||||
* @param raw_json_string input
|
||||
* @param dst A pointer to a buffer at least large enough to write this string as well as
|
||||
* an additional SIMDJSON_PADDING bytes.
|
||||
* @param allow_replacement Whether we allow a replacement if the input string contains unmatched surrogate pairs.
|
||||
* @return A string_view pointing at the unescaped string in dst
|
||||
* @error STRING_ERROR if escapes are incorrect.
|
||||
*/
|
||||
simdjson_inline simdjson_result<std::string_view> unescape_maybe(raw_json_string in, uint8_t *&dst, bool allow_replacement = false) const noexcept;
|
||||
|
||||
/**
|
||||
* Unescape this JSON string, replacing \\ with \, \n with newline, etc. to a user-provided buffer.
|
||||
* The result may not be valid UTF-8. See https://simonsapin.github.io/wtf-8/
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
#include "simdjson/generic/ondemand/serialization.h"
|
||||
#include "simdjson/generic/ondemand/value.h"
|
||||
#if SIMDJSON_STATIC_REFLECTION
|
||||
#include "simdjson/generic/ondemand/json_builder.h"
|
||||
#include "simdjson/generic/builder/json_builder.h"
|
||||
#endif
|
||||
#endif // SIMDJSON_CONDITIONAL_INCLUDE
|
||||
|
||||
|
||||
@@ -395,7 +395,9 @@ public:
|
||||
*/
|
||||
simdjson_inline simdjson_result<value> at(size_t index) noexcept;
|
||||
/**
|
||||
* Look up a field by name on an object (order-sensitive).
|
||||
* Look up a field by name on an object (order-sensitive). By order-sensitive, we mean that
|
||||
* fields must be accessed in the order they appear in the JSON text (although you can
|
||||
* skip fields). See find_field_unordered() and operator[] for an order-insensitive version.
|
||||
*
|
||||
* The following code reads z, then y, then x, and thus will not retrieve x or y if fed the
|
||||
* JSON `{ "x": 1, "y": 2, "z": 3 }`:
|
||||
@@ -429,7 +431,8 @@ public:
|
||||
* missing case has a non-cache-friendly bump and lots of extra scanning, especially if the object
|
||||
* in question is large. The fact that the extra code is there also bumps the executable size.
|
||||
*
|
||||
* It is the default, however, because it would be highly surprising (and hard to debug) if the
|
||||
* We default operator[] on find_field_unordered() for convenience.
|
||||
* It is the default because it would be highly surprising (and hard to debug) if the
|
||||
* default behavior failed to look up a field just because it was in the wrong order--and many
|
||||
* APIs assume this. Therefore, you must be explicit if you want to treat objects as out of order.
|
||||
*
|
||||
@@ -776,7 +779,9 @@ public:
|
||||
simdjson_inline simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::array_iterator> end() & noexcept;
|
||||
|
||||
/**
|
||||
* Look up a field by name on an object (order-sensitive).
|
||||
* Look up a field by name on an object (order-sensitive). By order-sensitive, we mean that
|
||||
* fields must be accessed in the order they appear in the JSON text (although you can
|
||||
* skip fields). See find_field_unordered() and operator[] for an order-insensitive version.
|
||||
*
|
||||
* The following code reads z, then y, then x, and thus will not retrieve x or y if fed the
|
||||
* JSON `{ "x": 1, "y": 2, "z": 3 }`:
|
||||
@@ -808,7 +813,8 @@ public:
|
||||
* missing case has a non-cache-friendly bump and lots of extra scanning, especially if the object
|
||||
* in question is large. The fact that the extra code is there also bumps the executable size.
|
||||
*
|
||||
* It is the default, however, because it would be highly surprising (and hard to debug) if the
|
||||
* We default operator[] on find_field_unordered() for convenience.
|
||||
* It is the default because it would be highly surprising (and hard to debug) if the
|
||||
* default behavior failed to look up a field just because it was in the wrong order--and many
|
||||
* APIs assume this. Therefore, you must be explicit if you want to treat objects as out of order.
|
||||
*
|
||||
|
||||
@@ -94,7 +94,6 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::end_container()
|
||||
|
||||
simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_next_field() noexcept {
|
||||
assert_at_next();
|
||||
|
||||
// It's illegal to call this unless there are more tokens: anything that ends in } or ] is
|
||||
// obligated to verify there are more tokens if they are not the top level.
|
||||
switch (*_json_iter->return_current_and_advance()) {
|
||||
@@ -967,6 +966,9 @@ simdjson_inline bool value_iterator::is_at_key() const noexcept {
|
||||
// Keys are at the same depth as the object.
|
||||
// Note here that we could be safer and check that we are within an object,
|
||||
// but we do not.
|
||||
//
|
||||
// As long as we are at the object's depth, in a valid document,
|
||||
// we will only ever be at { , : or the actual string key: ".
|
||||
return _depth == _json_iter->_depth && *_json_iter->peek() == '"';
|
||||
}
|
||||
|
||||
|
||||
@@ -472,6 +472,7 @@ protected:
|
||||
|
||||
friend class document;
|
||||
friend class object;
|
||||
friend class object_iterator;
|
||||
friend class array;
|
||||
friend class value;
|
||||
friend class field;
|
||||
|
||||
@@ -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
|
||||
@@ -17,6 +17,7 @@ using namespace simd;
|
||||
struct backslash_and_quote {
|
||||
public:
|
||||
static constexpr uint32_t BYTES_PROCESSED = 32;
|
||||
// We only copy if dst is non-null.
|
||||
simdjson_inline backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
|
||||
|
||||
simdjson_inline bool has_quote_first() { return ((bs_bits - 1) & quote_bits) != 0; }
|
||||
@@ -34,7 +35,9 @@ simdjson_inline backslash_and_quote backslash_and_quote::copy_and_find(const uin
|
||||
static_assert(SIMDJSON_PADDING >= (BYTES_PROCESSED - 1), "backslash and quote finder must process fewer than SIMDJSON_PADDING bytes");
|
||||
simd8<uint8_t> v(src);
|
||||
// store to dest unconditionally - we can overwrite the bits we don't like later
|
||||
v.store(dst);
|
||||
if(dst != nullptr) {
|
||||
v.store(dst);
|
||||
}
|
||||
return {
|
||||
static_cast<uint32_t>((v == '\\').to_bitmask()), // bs_bits
|
||||
static_cast<uint32_t>((v == '"').to_bitmask()), // quote_bits
|
||||
|
||||
@@ -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
|
||||
@@ -17,6 +17,7 @@ using namespace simd;
|
||||
struct backslash_and_quote {
|
||||
public:
|
||||
static constexpr uint32_t BYTES_PROCESSED = 64;
|
||||
// We only copy if dst is non-null.
|
||||
simdjson_inline backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
|
||||
|
||||
simdjson_inline bool has_quote_first() { return ((bs_bits - 1) & quote_bits) != 0; }
|
||||
@@ -34,7 +35,9 @@ simdjson_inline backslash_and_quote backslash_and_quote::copy_and_find(const uin
|
||||
static_assert(SIMDJSON_PADDING >= (BYTES_PROCESSED - 1), "backslash and quote finder must process fewer than SIMDJSON_PADDING bytes");
|
||||
simd8<uint8_t> v(src);
|
||||
// store to dest unconditionally - we can overwrite the bits we don't like later
|
||||
v.store(dst);
|
||||
if(dst != nullptr) {
|
||||
v.store(dst);
|
||||
}
|
||||
return {
|
||||
static_cast<uint64_t>(v == '\\'), // bs_bits
|
||||
static_cast<uint64_t>(v == '"'), // quote_bits
|
||||
|
||||
@@ -113,15 +113,15 @@
|
||||
#endif
|
||||
|
||||
#ifndef SIMDJSON_IMPLEMENTATION_LASX
|
||||
#define SIMDJSON_IMPLEMENTATION_LASX (SIMDJSON_IS_LOONGARCH64 && __loongarch_asx)
|
||||
#define SIMDJSON_IMPLEMENTATION_LASX (SIMDJSON_IS_LSX)
|
||||
#endif
|
||||
#define SIMDJSON_CAN_ALWAYS_RUN_LASX (SIMDJSON_IMPLEMENTATION_LASX)
|
||||
#define SIMDJSON_CAN_ALWAYS_RUN_LASX (SIMDJSON_IS_LASX)
|
||||
|
||||
#ifndef SIMDJSON_IMPLEMENTATION_LSX
|
||||
#if SIMDJSON_CAN_ALWAYS_RUN_LASX
|
||||
#define SIMDJSON_IMPLEMENTATION_LSX 0
|
||||
#else
|
||||
#define SIMDJSON_IMPLEMENTATION_LSX (SIMDJSON_IS_LOONGARCH64 && __loongarch_sx)
|
||||
#define SIMDJSON_IMPLEMENTATION_LSX (SIMDJSON_IS_LSX)
|
||||
#endif
|
||||
#endif
|
||||
#define SIMDJSON_CAN_ALWAYS_RUN_LSX (SIMDJSON_IMPLEMENTATION_LSX)
|
||||
@@ -165,4 +165,4 @@
|
||||
#define SIMDJSON_BUILTIN_IMPLEMENTATION_ID SIMDJSON_IMPLEMENTATION_ID_FOR(SIMDJSON_BUILTIN_IMPLEMENTATION)
|
||||
#define SIMDJSON_BUILTIN_IMPLEMENTATION_IS(IMPL) SIMDJSON_BUILTIN_IMPLEMENTATION_ID == SIMDJSON_IMPLEMENTATION_ID_FOR(IMPL)
|
||||
|
||||
#endif // SIMDJSON_IMPLEMENTATION_DETECTION_H
|
||||
#endif // SIMDJSON_IMPLEMENTATION_DETECTION_H
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "simdjson/base.h"
|
||||
#include "simdjson/error.h"
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
namespace simdjson {
|
||||
|
||||
@@ -102,6 +103,24 @@ public:
|
||||
*/
|
||||
simdjson_warn_unused virtual error_code stage2_next(dom::document &doc) noexcept = 0;
|
||||
|
||||
/**
|
||||
* Unescape a valid UTF-8 string from src to dst, stopping at a final unescaped quote. There
|
||||
* must be an unescaped quote terminating the string. It returns the final output
|
||||
* position as pointer. In case of error (e.g., the string has bad escaped codes),
|
||||
* then null_ptr is returned. If no escaping was required, then no copy is made.
|
||||
* It is assumed that the output buffer is large
|
||||
* enough to store the unescapedstring + SIMDJSON_PADDING bytes.
|
||||
*
|
||||
* Overridden by each implementation.
|
||||
*
|
||||
* @param str pointer to the beginning of a valid UTF-8 JSON string, must end with an unescaped quote.
|
||||
* @param dst pointer to a destination buffer, it must point a region in memory of sufficient size.
|
||||
* @param allow_replacement whether we allow a replacement character when the UTF-8 contains unmatched surrogate pairs.
|
||||
* @return end of the of the written region (exclusive) or nullptr in case of error coupled with a Boolean telling you if a copy was made
|
||||
*/
|
||||
simdjson_warn_unused virtual std::pair<const uint8_t *,bool> parse_string_if_needed(const uint8_t *src, uint8_t *dst, bool allow_replacement) const noexcept = 0;
|
||||
|
||||
|
||||
/**
|
||||
* Unescape a valid UTF-8 string from src to dst, stopping at a final unescaped quote. There
|
||||
* must be an unescaped quote terminating the string. It returns the final output
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -1,4 +1,11 @@
|
||||
#define SIMDJSON_IMPLEMENTATION lasx
|
||||
#include <lsxintrin.h> // This is a hack. We should not need to put this include here.
|
||||
#if SIMDJSON_CAN_ALWAYS_RUN_LASX
|
||||
// nothing needed.
|
||||
#else
|
||||
SIMDJSON_TARGET_REGION("lasx,lsx")
|
||||
#endif
|
||||
|
||||
#include "simdjson/lasx/base.h"
|
||||
#include "simdjson/lasx/intrinsics.h"
|
||||
#include "simdjson/lasx/bitmanipulation.h"
|
||||
@@ -8,3 +15,5 @@
|
||||
#include "simdjson/lasx/stringparsing_defs.h"
|
||||
|
||||
#define SIMDJSON_SKIP_BACKSLASH_SHORT_CIRCUIT 1
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -4,3 +4,10 @@
|
||||
|
||||
#undef SIMDJSON_SKIP_BACKSLASH_SHORT_CIRCUIT
|
||||
#undef SIMDJSON_IMPLEMENTATION
|
||||
|
||||
|
||||
#if SIMDJSON_CAN_ALWAYS_RUN_LASX
|
||||
// nothing needed.
|
||||
#else
|
||||
SIMDJSON_UNTARGET_REGION
|
||||
#endif
|
||||
@@ -5,8 +5,7 @@
|
||||
#include "simdjson/lasx/base.h"
|
||||
#endif // SIMDJSON_CONDITIONAL_INCLUDE
|
||||
|
||||
// This should be the correct header whether
|
||||
// you use visual studio or other compilers.
|
||||
#include <lsxintrin.h>
|
||||
#include <lasxintrin.h>
|
||||
|
||||
static_assert(sizeof(__m256i) <= simdjson::SIMDJSON_PADDING, "insufficient padding for LoongArch ASX");
|
||||
|
||||
@@ -17,6 +17,7 @@ using namespace simd;
|
||||
struct backslash_and_quote {
|
||||
public:
|
||||
static constexpr uint32_t BYTES_PROCESSED = 32;
|
||||
// We only copy if dst is non-null.
|
||||
simdjson_inline backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
|
||||
|
||||
simdjson_inline bool has_quote_first() { return ((bs_bits - 1) & quote_bits) != 0; }
|
||||
@@ -33,7 +34,9 @@ simdjson_inline backslash_and_quote backslash_and_quote::copy_and_find(const uin
|
||||
// SIMDJSON_PADDING of padding
|
||||
static_assert(SIMDJSON_PADDING >= (BYTES_PROCESSED - 1), "backslash and quote finder must process fewer than SIMDJSON_PADDING bytes");
|
||||
simd8<uint8_t> v(src);
|
||||
v.store(dst);
|
||||
if(dst != nullptr) {
|
||||
v.store(dst);
|
||||
}
|
||||
return {
|
||||
static_cast<uint32_t>((v == '\\').to_bitmask()), // bs_bits
|
||||
static_cast<uint32_t>((v == '"').to_bitmask()), // quote_bits
|
||||
@@ -61,7 +64,7 @@ simdjson_inline escaping escaping::copy_and_find(const uint8_t *src, uint8_t *ds
|
||||
simd8<bool> is_backslash = (v == '\\');
|
||||
simd8<bool> is_control = (v < 32);
|
||||
return {
|
||||
(is_backslash | is_quote | is_control).to_bitmask()
|
||||
static_cast<uint64_t>((is_backslash | is_quote | is_control).to_bitmask())
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -5,8 +5,6 @@
|
||||
#include "simdjson/lsx/base.h"
|
||||
#endif // SIMDJSON_CONDITIONAL_INCLUDE
|
||||
|
||||
// This should be the correct header whether
|
||||
// you use visual studio or other compilers.
|
||||
#include <lsxintrin.h>
|
||||
|
||||
static_assert(sizeof(__m128i) <= simdjson::SIMDJSON_PADDING, "insufficient padding for LoongArch SX");
|
||||
|
||||
@@ -17,6 +17,7 @@ using namespace simd;
|
||||
struct backslash_and_quote {
|
||||
public:
|
||||
static constexpr uint32_t BYTES_PROCESSED = 32;
|
||||
// We only copy if dst is non-null.
|
||||
simdjson_inline backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
|
||||
|
||||
simdjson_inline bool has_quote_first() { return ((bs_bits - 1) & quote_bits) != 0; }
|
||||
@@ -34,8 +35,10 @@ simdjson_inline backslash_and_quote backslash_and_quote::copy_and_find(const uin
|
||||
static_assert(SIMDJSON_PADDING >= (BYTES_PROCESSED - 1), "backslash and quote finder must process fewer than SIMDJSON_PADDING bytes");
|
||||
simd8<uint8_t> v0(src);
|
||||
simd8<uint8_t> v1(src + sizeof(v0));
|
||||
v0.store(dst);
|
||||
v1.store(dst + sizeof(v0));
|
||||
if(dst != nullptr) {
|
||||
v0.store(dst);
|
||||
v1.store(dst + sizeof(v0));
|
||||
}
|
||||
|
||||
// Getting a 64-bit bitmask is much cheaper than multiple 16-bit bitmasks on LSX; therefore, we
|
||||
// smash them together into a 64-byte mask and get the bitmask from there.
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#include "simdjson/padded_string_view-inl.h"
|
||||
|
||||
#include <climits>
|
||||
#include <cwchar>
|
||||
|
||||
namespace simdjson {
|
||||
namespace internal {
|
||||
@@ -125,6 +126,33 @@ inline const char *padded_string::data() const noexcept { return data_ptr; }
|
||||
|
||||
inline char *padded_string::data() noexcept { return data_ptr; }
|
||||
|
||||
inline bool padded_string::append(const char *data, size_t length) noexcept {
|
||||
if (length == 0) {
|
||||
return true; // Nothing to append
|
||||
}
|
||||
size_t new_size = viable_size + length;
|
||||
if (new_size < viable_size) {
|
||||
// Overflow, cannot append
|
||||
return false;
|
||||
}
|
||||
char *new_data_ptr = internal::allocate_padded_buffer(new_size);
|
||||
if (new_data_ptr == nullptr) {
|
||||
// Allocation failed, cannot append
|
||||
return false;
|
||||
}
|
||||
// Copy existing data
|
||||
if (viable_size > 0) {
|
||||
std::memcpy(new_data_ptr, data_ptr, viable_size);
|
||||
}
|
||||
// Copy new data
|
||||
std::memcpy(new_data_ptr + viable_size, data, length);
|
||||
// Update
|
||||
delete[] data_ptr;
|
||||
data_ptr = new_data_ptr;
|
||||
viable_size = new_size;
|
||||
return true;
|
||||
}
|
||||
|
||||
inline padded_string::operator std::string_view() const simdjson_lifetime_bound { return std::string_view(data(), length()); }
|
||||
|
||||
inline padded_string::operator padded_string_view() const noexcept simdjson_lifetime_bound {
|
||||
@@ -185,6 +213,159 @@ inline simdjson_result<padded_string> padded_string::load(std::string_view filen
|
||||
return s;
|
||||
}
|
||||
|
||||
#if defined(_WIN32) && SIMDJSON_CPLUSPLUS17
|
||||
inline simdjson_result<padded_string> padded_string::load(std::wstring_view filename) noexcept {
|
||||
// Open the file using the wide characters
|
||||
SIMDJSON_PUSH_DISABLE_WARNINGS
|
||||
SIMDJSON_DISABLE_DEPRECATED_WARNING // Disable CRT_SECURE warning on MSVC: manually verified this is safe
|
||||
std::FILE *fp = _wfopen(filename.data(), L"rb");
|
||||
SIMDJSON_POP_DISABLE_WARNINGS
|
||||
|
||||
if (fp == nullptr) {
|
||||
return IO_ERROR;
|
||||
}
|
||||
|
||||
// Get the file size
|
||||
int ret;
|
||||
#if SIMDJSON_VISUAL_STUDIO && !SIMDJSON_IS_32BITS
|
||||
ret = _fseeki64(fp, 0, SEEK_END);
|
||||
#else
|
||||
ret = std::fseek(fp, 0, SEEK_END);
|
||||
#endif // _WIN64
|
||||
if(ret < 0) {
|
||||
std::fclose(fp);
|
||||
return IO_ERROR;
|
||||
}
|
||||
#if SIMDJSON_VISUAL_STUDIO && !SIMDJSON_IS_32BITS
|
||||
__int64 llen = _ftelli64(fp);
|
||||
if(llen == -1L) {
|
||||
std::fclose(fp);
|
||||
return IO_ERROR;
|
||||
}
|
||||
#else
|
||||
long llen = std::ftell(fp);
|
||||
if((llen < 0) || (llen == LONG_MAX)) {
|
||||
std::fclose(fp);
|
||||
return IO_ERROR;
|
||||
}
|
||||
#endif
|
||||
|
||||
// Allocate the padded_string
|
||||
size_t len = static_cast<size_t>(llen);
|
||||
padded_string s(len);
|
||||
if (s.data() == nullptr) {
|
||||
std::fclose(fp);
|
||||
return MEMALLOC;
|
||||
}
|
||||
|
||||
// Read the padded_string
|
||||
std::rewind(fp);
|
||||
size_t bytes_read = std::fread(s.data(), 1, len, fp);
|
||||
if (std::fclose(fp) != 0 || bytes_read != len) {
|
||||
return IO_ERROR;
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
#endif
|
||||
|
||||
// padded_string_builder implementations
|
||||
|
||||
inline padded_string_builder::padded_string_builder() noexcept = default;
|
||||
|
||||
inline padded_string_builder::padded_string_builder(size_t new_capacity) noexcept {
|
||||
if (new_capacity > 0) {
|
||||
data = internal::allocate_padded_buffer(new_capacity);
|
||||
if (data != nullptr) {
|
||||
this->capacity = new_capacity;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline padded_string_builder::padded_string_builder(padded_string_builder &&o) noexcept
|
||||
: size(o.size), capacity(o.capacity), data(o.data) {
|
||||
o.size = 0;
|
||||
o.capacity = 0;
|
||||
o.data = nullptr;
|
||||
}
|
||||
|
||||
inline padded_string_builder &padded_string_builder::operator=(padded_string_builder &&o) noexcept {
|
||||
if (this != &o) {
|
||||
delete[] data;
|
||||
size = o.size;
|
||||
capacity = o.capacity;
|
||||
data = o.data;
|
||||
o.size = 0;
|
||||
o.capacity = 0;
|
||||
o.data = nullptr;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
inline padded_string_builder::~padded_string_builder() noexcept {
|
||||
delete[] data;
|
||||
}
|
||||
|
||||
inline bool padded_string_builder::append(const char *newdata, size_t length) noexcept {
|
||||
if (length == 0) {
|
||||
return true;
|
||||
}
|
||||
if (!reserve(length)) {
|
||||
return false;
|
||||
}
|
||||
std::memcpy(data + size, newdata, length);
|
||||
size += length;
|
||||
return true;
|
||||
}
|
||||
|
||||
inline bool padded_string_builder::append(std::string_view sv) noexcept {
|
||||
return append(sv.data(), sv.size());
|
||||
}
|
||||
|
||||
inline size_t padded_string_builder::length() const noexcept {
|
||||
return size;
|
||||
}
|
||||
|
||||
inline padded_string padded_string_builder::build() const noexcept {
|
||||
return padded_string(data, size);
|
||||
}
|
||||
|
||||
inline padded_string padded_string_builder::convert() noexcept {
|
||||
padded_string result{};
|
||||
result.data_ptr = data;
|
||||
result.viable_size = size;
|
||||
data = nullptr;
|
||||
size = 0;
|
||||
capacity = 0;
|
||||
return result;
|
||||
}
|
||||
|
||||
inline bool padded_string_builder::reserve(size_t additional) noexcept {
|
||||
size_t needed = size + additional;
|
||||
if (needed <= capacity) {
|
||||
return true;
|
||||
}
|
||||
size_t new_capacity = needed;
|
||||
// We are going to grow the capacity exponentially to avoid
|
||||
// repeated allocations.
|
||||
if (new_capacity < 4096) {
|
||||
new_capacity *= 2;
|
||||
} else {
|
||||
new_capacity += new_capacity/2; // grow by 1.5x
|
||||
}
|
||||
char *new_data = internal::allocate_padded_buffer(new_capacity);
|
||||
if (new_data == nullptr) {
|
||||
return false; // Allocation failed
|
||||
}
|
||||
if (size > 0) {
|
||||
std::memcpy(new_data, data, size);
|
||||
}
|
||||
delete[] data;
|
||||
data = new_data;
|
||||
capacity = new_capacity;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace simdjson
|
||||
|
||||
inline simdjson::padded_string operator ""_padded(const char *str, size_t len) {
|
||||
|
||||
@@ -98,6 +98,16 @@ struct padded_string final {
|
||||
**/
|
||||
char *data() noexcept;
|
||||
|
||||
/**
|
||||
* Append data to the padded string. Return true on success, false on failure.
|
||||
* The complexity is O(n) where n is the new size of the string. If you are
|
||||
* doing multiple appends, consider using padded_string_builder for better performance.
|
||||
*
|
||||
* @param data the buffer to append
|
||||
* @param length the number of bytes to append
|
||||
*/
|
||||
inline bool append(const char *data, size_t length) noexcept;
|
||||
|
||||
/**
|
||||
* Create a std::string_view with the same content.
|
||||
*/
|
||||
@@ -127,7 +137,21 @@ struct padded_string final {
|
||||
**/
|
||||
inline static simdjson_result<padded_string> load(std::string_view path) noexcept;
|
||||
|
||||
#if defined(_WIN32) && SIMDJSON_CPLUSPLUS17
|
||||
/**
|
||||
* This function accepts a wide string path (UTF-16) and converts it to
|
||||
* UTF-8 before loading the file. This allows windows users to work
|
||||
* with unicode file paths without manually converting the paths every time.
|
||||
*
|
||||
* @return IO_ERROR on error, including conversion failures.
|
||||
*
|
||||
* @param path the path to the file as a wide string.
|
||||
**/
|
||||
inline static simdjson_result<padded_string> load(std::wstring_view path) noexcept;
|
||||
#endif
|
||||
|
||||
private:
|
||||
friend class padded_string_builder;
|
||||
padded_string &operator=(const padded_string &o) = delete;
|
||||
padded_string(const padded_string &o) = delete;
|
||||
|
||||
@@ -136,6 +160,101 @@ private:
|
||||
|
||||
}; // padded_string
|
||||
|
||||
/**
|
||||
* Builder for constructing padded_string incrementally.
|
||||
*
|
||||
* This class allows efficient appending of data and then building a padded_string.
|
||||
*/
|
||||
class padded_string_builder {
|
||||
public:
|
||||
/**
|
||||
* Create a new, empty padded string builder.
|
||||
*/
|
||||
inline padded_string_builder() noexcept;
|
||||
|
||||
/**
|
||||
* Create a new padded string builder with initial capacity.
|
||||
*
|
||||
* @param capacity the initial capacity of the builder.
|
||||
*/
|
||||
inline padded_string_builder(size_t capacity) noexcept;
|
||||
|
||||
/**
|
||||
* Move constructor.
|
||||
*/
|
||||
inline padded_string_builder(padded_string_builder &&o) noexcept;
|
||||
|
||||
/**
|
||||
* Move assignment.
|
||||
*/
|
||||
inline padded_string_builder &operator=(padded_string_builder &&o) noexcept;
|
||||
|
||||
/**
|
||||
* Copy constructor (deleted).
|
||||
*/
|
||||
padded_string_builder(const padded_string_builder &) = delete;
|
||||
|
||||
/**
|
||||
* Copy assignment (deleted).
|
||||
*/
|
||||
padded_string_builder &operator=(const padded_string_builder &) = delete;
|
||||
|
||||
/**
|
||||
* Destructor.
|
||||
*/
|
||||
inline ~padded_string_builder() noexcept;
|
||||
|
||||
/**
|
||||
* Append data to the builder.
|
||||
*
|
||||
* @param newdata the buffer to append
|
||||
* @param length the number of bytes to append
|
||||
* @return true if the append succeeded, false if allocation failed
|
||||
*/
|
||||
inline bool append(const char *newdata, size_t length) noexcept;
|
||||
|
||||
/**
|
||||
* Append a string view to the builder.
|
||||
*
|
||||
* @param sv the string view to append
|
||||
* @return true if the append succeeded, false if allocation failed
|
||||
*/
|
||||
inline bool append(std::string_view sv) noexcept;
|
||||
|
||||
/**
|
||||
* Get the current length of the built string.
|
||||
*/
|
||||
inline size_t length() const noexcept;
|
||||
|
||||
/**
|
||||
* Build a padded_string from the current content. The builder's content
|
||||
* is not modified. If you want to avoid the copy, use convert() instead.
|
||||
*
|
||||
* @return a padded_string containing a copy of the built content.
|
||||
*/
|
||||
inline padded_string build() const noexcept;
|
||||
|
||||
/**
|
||||
* Convert the current content into a padded_string. The
|
||||
* builder's content is emptied, the capacity is lost.
|
||||
*
|
||||
* @return a padded_string containing the built content.
|
||||
*/
|
||||
inline padded_string convert() noexcept;
|
||||
private:
|
||||
size_t size{0};
|
||||
size_t capacity{0};
|
||||
char *data{nullptr};
|
||||
|
||||
/**
|
||||
* Ensure the builder has enough capacity.
|
||||
*
|
||||
* @param additional the additional capacity needed.
|
||||
* @return true if the reservation succeeded, false if allocation failed
|
||||
*/
|
||||
inline bool reserve(size_t additional) noexcept;
|
||||
};
|
||||
|
||||
/**
|
||||
* Send padded_string instance to an output stream.
|
||||
*
|
||||
|
||||
@@ -63,6 +63,12 @@ using std::size_t;
|
||||
#endif
|
||||
#elif defined(__loongarch_lp64)
|
||||
#define SIMDJSON_IS_LOONGARCH64 1
|
||||
#if defined(__loongarch_sx) && defined(__loongarch_asx)
|
||||
#define SIMDJSON_IS_LSX 1
|
||||
#define SIMDJSON_IS_LASX 1 // We can always run both
|
||||
#elif defined(__loongarch_sx)
|
||||
#define SIMDJSON_IS_LSX 1
|
||||
#endif
|
||||
#elif defined(__PPC64__) || defined(_M_PPC64)
|
||||
#define SIMDJSON_IS_PPC64 1
|
||||
#if defined(__ALTIVEC__)
|
||||
@@ -118,7 +124,7 @@ using std::size_t;
|
||||
//
|
||||
|
||||
// We are going to use runtime dispatch.
|
||||
#if SIMDJSON_IS_X86_64
|
||||
#if defined(SIMDJSON_IS_X86_64) || defined(SIMDJSON_IS_LSX)
|
||||
#ifdef __clang__
|
||||
// clang does not have GCC push pop
|
||||
// warning: clang attribute push can't be used within a namespace in clang up
|
||||
@@ -135,7 +141,7 @@ using std::size_t;
|
||||
#define SIMDJSON_UNTARGET_REGION _Pragma("GCC pop_options")
|
||||
#endif // clang then gcc
|
||||
|
||||
#endif // x86
|
||||
#endif // defined(SIMDJSON_IS_X86_64) || defined(SIMDJSON_IS_LSX)
|
||||
|
||||
// Default target region macros don't do anything.
|
||||
#ifndef SIMDJSON_TARGET_REGION
|
||||
@@ -204,7 +210,8 @@ using std::size_t;
|
||||
#define simdjson_strncasecmp strncasecmp
|
||||
#endif
|
||||
|
||||
#if defined(NDEBUG) || defined(__OPTIMIZE__) || (defined(_MSC_VER) && !defined(_DEBUG))
|
||||
#if (defined(NDEBUG) || defined(__OPTIMIZE__) || (defined(_MSC_VER) && !defined(_DEBUG))) && !SIMDJSON_DEVELOPMENT_CHECKS
|
||||
// If SIMDJSON_DEVELOPMENT_CHECKS is undefined or 0, we consider that we are in release mode.
|
||||
// If NDEBUG is set, or __OPTIMIZE__ is set, or we are under MSVC in release mode,
|
||||
// then do away with asserts and use __assume.
|
||||
// We still recommend that our users set NDEBUG in release mode.
|
||||
@@ -216,7 +223,7 @@ using std::size_t;
|
||||
#define SIMDJSON_ASSUME(COND) do { if (!(COND)) __builtin_unreachable(); } while (0)
|
||||
#endif
|
||||
|
||||
#else // defined(NDEBUG) || defined(__OPTIMIZE__) || (defined(_MSC_VER) && !defined(_DEBUG))
|
||||
#else // defined(NDEBUG) || defined(__OPTIMIZE__) || (defined(_MSC_VER) && !defined(_DEBUG)) && !SIMDJSON_DEVELOPMENT_CHECKS
|
||||
// This should only ever be enabled in debug mode.
|
||||
#define SIMDJSON_UNREACHABLE() assert(0);
|
||||
#define SIMDJSON_ASSUME(COND) assert(COND)
|
||||
|
||||
@@ -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
|
||||
@@ -17,6 +17,7 @@ using namespace simd;
|
||||
struct backslash_and_quote {
|
||||
public:
|
||||
static constexpr uint32_t BYTES_PROCESSED = 32;
|
||||
// We only copy if dst is non-null.
|
||||
simdjson_inline backslash_and_quote
|
||||
copy_and_find(const uint8_t *src, uint8_t *dst);
|
||||
|
||||
@@ -44,8 +45,10 @@ backslash_and_quote::copy_and_find(const uint8_t *src, uint8_t *dst) {
|
||||
"SIMDJSON_PADDING bytes");
|
||||
simd8<uint8_t> v0(src);
|
||||
simd8<uint8_t> v1(src + sizeof(v0));
|
||||
v0.store(dst);
|
||||
v1.store(dst + sizeof(v0));
|
||||
if(dst != nullptr) {
|
||||
v0.store(dst);
|
||||
v1.store(dst + sizeof(v0));
|
||||
}
|
||||
|
||||
// Getting a 64-bit bitmask is much cheaper than multiple 16-bit bitmasks on
|
||||
// PPC; therefore, we smash them together into a 64-byte mask and get the
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
#define SIMDJSON_SIMDJSON_VERSION_H
|
||||
|
||||
/** The version of simdjson being used (major.minor.revision) */
|
||||
#define SIMDJSON_VERSION "4.2.1"
|
||||
#define SIMDJSON_VERSION "4.2.4"
|
||||
|
||||
namespace simdjson {
|
||||
enum {
|
||||
@@ -19,7 +19,7 @@ enum {
|
||||
/**
|
||||
* The revision (major.minor.REVISION) of simdjson being used.
|
||||
*/
|
||||
SIMDJSON_VERSION_REVISION = 1
|
||||
SIMDJSON_VERSION_REVISION = 4
|
||||
};
|
||||
} // namespace simdjson
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
#ifndef SIMDJSON_WESTMERE_BUILDER_H
|
||||
#define SIMDJSON_WESTMERE_BUILDER_H
|
||||
|
||||
#include "simdjson/westmere/begin.h"
|
||||
#include "simdjson/generic/builder/amalgamated.h"
|
||||
#include "simdjson/westmere/end.h"
|
||||
|
||||
#endif // SIMDJSON_WESTMERE_BUILDER_H
|
||||
@@ -14,6 +14,7 @@ using namespace simd;
|
||||
struct backslash_and_quote {
|
||||
public:
|
||||
static constexpr uint32_t BYTES_PROCESSED = 32;
|
||||
// We only copy if dst is non-null.
|
||||
simdjson_inline backslash_and_quote copy_and_find(const uint8_t *src, uint8_t *dst);
|
||||
|
||||
simdjson_inline bool has_quote_first() { return ((bs_bits - 1) & quote_bits) != 0; }
|
||||
@@ -31,8 +32,10 @@ simdjson_inline backslash_and_quote backslash_and_quote::copy_and_find(const uin
|
||||
static_assert(SIMDJSON_PADDING >= (BYTES_PROCESSED - 1), "backslash and quote finder must process fewer than SIMDJSON_PADDING bytes");
|
||||
simd8<uint8_t> v0(src);
|
||||
simd8<uint8_t> v1(src + 16);
|
||||
v0.store(dst);
|
||||
v1.store(dst + 16);
|
||||
if(dst != nullptr) {
|
||||
v0.store(dst);
|
||||
v1.store(dst + 16);
|
||||
}
|
||||
uint64_t bs_and_quote = simd8x64<bool>(v0 == '\\', v1 == '\\', v0 == '"', v1 == '"').to_bitmask();
|
||||
return {
|
||||
uint32_t(bs_and_quote), // bs_bits
|
||||
|
||||
@@ -20,31 +20,68 @@ if sys.version_info < (3, 0):
|
||||
|
||||
rules = """
|
||||
|
||||
We refer your to the HACKING.md file for more information on how the project is organized.
|
||||
Amalgamation Rules for simdjson
|
||||
==============================
|
||||
|
||||
If you are trying to add a new implementation, you need to edit the amalgamate.py script
|
||||
to add your implementation to the IMPLEMENTATIONS list.
|
||||
This script creates a single compilation unit (amalgamation) from multiple source files,
|
||||
allowing the entire library to be compiled as one file while supporting multiple CPU
|
||||
architectures. Implementation-specific code is conditionally included at compile time.
|
||||
|
||||
To help understand the error, here are the rules for including files in simdjson:
|
||||
For more details, see HACKING.md.
|
||||
|
||||
All implementation-specific files, including arm64.h, arm64/implementation.h and
|
||||
arm64/ondemand.h, must be within SIMDJSON_CONDITIONAL_INCLUDE blocks.
|
||||
Key Concepts:
|
||||
- **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.
|
||||
|
||||
Top-level headers must not be included in any SIMDJSON_CONDITIONAL_INCLUDE block.
|
||||
- **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.
|
||||
|
||||
Generic files must be included only in amalgamator files (arm64.h,
|
||||
arm64/implementation.h, arm64/ondemand.h, generic/amalgamated.h).
|
||||
- **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).
|
||||
|
||||
We fail if an implementation-specific file is included more than once in the same block.
|
||||
We fail if a generic file is included more than once per implementation in the same block.
|
||||
- **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.
|
||||
|
||||
Tip: generally, "file" will search the including file's source directory first, then
|
||||
the search paths while <file> does it the other way around.
|
||||
We prefer to use <> in simdjson headers to avoid accidentally including a file from the
|
||||
wrong directory.
|
||||
- **Builtin File**: Special files under simdjson/builtin/ that handle the builtin
|
||||
implementation, a fallback/default implementation used when no optimized implementation
|
||||
is available.
|
||||
|
||||
The amalgamate.py script checks that all files are included.
|
||||
- **Conditional Include Block**: A section wrapped in #ifndef SIMDJSON_CONDITIONAL_INCLUDE
|
||||
for editor-only or implementation-specific content.
|
||||
|
||||
Use amalgation_helper.py to generate an HTML report to help you understand the status of each file.
|
||||
|
||||
Inclusion Rules:
|
||||
1. All implementation-specific files must be within SIMDJSON_CONDITIONAL_INCLUDE blocks.
|
||||
|
||||
2. Top-level headers (free dependency files) must not be included in any
|
||||
SIMDJSON_CONDITIONAL_INCLUDE block.
|
||||
|
||||
3. Generic files must be included only in amalgamator files.
|
||||
|
||||
4. Amalgamated files can only include other amalgamated files.
|
||||
|
||||
5. Free dependency files can only include amalgamator files or other free files,
|
||||
not amalgamated files directly.
|
||||
|
||||
6. We fail if an implementation-specific file is included more than once in the same block.
|
||||
|
||||
7. We fail if a generic file is included more than once per implementation in the same block.
|
||||
|
||||
8. Dependency files (dependencies.h) must list all editor-only includes for completeness.
|
||||
|
||||
Tips:
|
||||
- Use <> for includes to search system paths first, avoiding accidental local includes.
|
||||
- The script validates that all .h and .cpp files are included or deprecated.
|
||||
|
||||
If adding a new implementation, edit the IMPLEMENTATIONS list in this script.
|
||||
|
||||
"""
|
||||
|
||||
@@ -179,6 +216,8 @@ class SimdjsonFile:
|
||||
# simdjson/arm64/ondemand.h
|
||||
if self.filename == 'ondemand.h':
|
||||
return self.repository["simdjson/generic/ondemand/dependencies.h"]
|
||||
if self.filename == 'builder.h':
|
||||
return self.repository["simdjson/generic/builder/dependencies.h"]
|
||||
|
||||
# simdjson/arm64.h, simdjson/arm64/*.h
|
||||
else:
|
||||
@@ -192,7 +231,11 @@ class SimdjsonFile:
|
||||
@property
|
||||
def is_amalgamator(self):
|
||||
if self.implementation:
|
||||
return self.root == 'src' or self.include_dir == 'simdjson' or self.filename == 'ondemand.h' or self.filename == 'implementation.h'
|
||||
return (self.root == 'src' or
|
||||
self.include_dir == 'simdjson' or
|
||||
self.filename == 'ondemand.h' or
|
||||
self.filename == 'builder.h' or
|
||||
self.filename == 'implementation.h')
|
||||
else:
|
||||
return self.filename == 'amalgamated.h'
|
||||
|
||||
@@ -209,22 +252,23 @@ class SimdjsonFile:
|
||||
return self.filename == 'dependencies.h'
|
||||
|
||||
def add_include(self, include: 'SimdjsonFile'):
|
||||
print(f" Adding include: {self} includes {include}")
|
||||
if self.is_conditional_include:
|
||||
# If I have a dependency file, I can only include something that has a dependency file.
|
||||
assert include.is_conditional_include, f"{self} cannot include {include} without #ifndef SIMDJSON_CONDITIONAL_INCLUDE. {rules}"
|
||||
assert include.is_conditional_include, f"Error: Amalgamated file '{self}' is trying to include '{include}', but '{include}' is not an amalgamated file. Amalgamated files can only include other amalgamated files to maintain conditional inclusion structure. Check the inclusion rules in the script's 'rules' variable. {rules}"
|
||||
# TODO make sure we only include amalgamated files that are guaranteed to be included with us (or before us)
|
||||
# if include.amalgamator_file:
|
||||
# assert include.amalgamator_file == self, f"{self} cannot include {include}: it should be included from {include.amalgamator_file} instead."
|
||||
else:
|
||||
assert include.is_amalgamator or not include.is_conditional_include, f"{self} cannot include {include} because it is an amalgamated file. {rules}"
|
||||
assert include.is_amalgamator or not include.is_conditional_include, f"Error: Free dependency file '{self}' is trying to include '{include}', which is an amalgamated file. Free dependency files (top-level headers) can only include amalgamator files or other free files, not amalgamated files directly. This prevents improper layering. Move the include to an amalgamator or restructure dependencies. {rules}"
|
||||
|
||||
self.includes.append(include)
|
||||
include.included_from.add(self)
|
||||
|
||||
def add_editor_only_include(self, include: 'SimdjsonFile'):
|
||||
assert self.is_conditional_include, f"Cannot use #ifndef SIMDJSON_CONDITIONAL_INCLUDE in {self} because it is not an amalgamated file. {rules}"
|
||||
assert self.is_conditional_include, f"Error: File '{self}' uses '#ifndef SIMDJSON_CONDITIONAL_INCLUDE', but '{self}' is not an amalgamated file. Conditional include blocks are only allowed in amalgamated files (those with dependencies). Remove the conditional block or ensure the file is amalgamated. {rules}"
|
||||
if not include.is_conditional_include:
|
||||
assert self.dependency_file, f"{self} cannot include {include} without #ifndef SIMDJSON_CONDITIONAL_INCLUDE. {rules}"
|
||||
assert self.dependency_file, f"Error: In '{self}', editor-only include of '{include}' requires a dependency file, but '{self}' has none. Ensure '{self}' has an associated dependencies.h file. {rules}"
|
||||
# TODO make sure we only include amalgamated files that are guaranteed to be included with us (or before us)
|
||||
# elif include.amalgamator_file:
|
||||
# assert self.is_amalgamated_before(self.amalgamator_file), f"{self} cannot include {include}: it should be included from {include.amalgamator_file} instead."
|
||||
@@ -239,11 +283,11 @@ class SimdjsonFile:
|
||||
if file.dependency_file == self:
|
||||
for editor_only_include in file.editor_only_includes:
|
||||
if not editor_only_include.is_conditional_include:
|
||||
assert editor_only_include in self.includes, f"{file} includes {editor_only_include}, but it is not included from {self}. It must be added to {self}. {rules}"
|
||||
assert editor_only_include in self.includes, f"Error: Dependency file '{self}' is missing an include for '{editor_only_include}', which is editor-only included in '{file}'. Add '{editor_only_include}' to '{self}' to ensure completeness. {rules}"
|
||||
if editor_only_include in extra_include_set:
|
||||
extra_include_set.remove(editor_only_include)
|
||||
|
||||
assert len(extra_include_set) == 0, f"{self} unnecessarily includes {extra_include_set}. They are not included in the corresponding amalgamated files. {rules}"
|
||||
assert len(extra_include_set) == 0, f"Error: Dependency file '{self}' includes {extra_include_set}, which are not used in any amalgamated files. Remove these unnecessary includes to clean up dependencies. {rules}"
|
||||
|
||||
class SimdjsonRepository:
|
||||
def __init__(self, project_path: str, relative_roots: List[RelativeRoot]):
|
||||
@@ -279,12 +323,12 @@ class SimdjsonRepository:
|
||||
result = None
|
||||
for relative_root in self.relative_roots:
|
||||
if os.path.exists(os.path.join(self.project_path, relative_root, filename)):
|
||||
assert result is None, "{file} exists in both {result} and {root}!"
|
||||
assert result is None, f"Error: File '{filename}' exists in both '{result}' and '{relative_root}' directories. Files must be unique across roots to avoid ambiguity. Rename or move the duplicate file."
|
||||
result = relative_root
|
||||
return result
|
||||
|
||||
def validate_all_files_used(self, root: RelativeRoot):
|
||||
assert root in self.relative_roots
|
||||
assert root in self.relative_roots, f"Error: Root '{root}' is not a valid relative root. Valid roots are {self.relative_roots}. Check the root parameter passed to validate_all_files_used."
|
||||
absolute_root = os.path.join(self.project_path, root)
|
||||
all_files = set([
|
||||
os.path.relpath(os.path.join(dir, file).replace('\\', '/'), absolute_root)
|
||||
@@ -295,7 +339,7 @@ class SimdjsonRepository:
|
||||
used_files = set([file.include_path for file in self if file.root == root])
|
||||
all_files.difference_update(used_files)
|
||||
all_files.difference_update(DEPRECATED_FILES)
|
||||
assert len(all_files) == 0, f"Files not used: {sorted(all_files)}"
|
||||
assert len(all_files) == 0, f"Error: The following files in '{root}' are not used in the amalgamation: {sorted(all_files)}. All .h and .cpp files must be included or added to DEPRECATED_FILES. Check for missing includes or deprecate unused files."
|
||||
|
||||
class Amalgamator:
|
||||
@classmethod
|
||||
@@ -305,7 +349,7 @@ class Amalgamator:
|
||||
print(f"/* auto-generated on {timestamp}. version {version} Do not edit! */", file=fid)
|
||||
amalgamator = cls(fid, SimdjsonRepository(PROJECTPATH, roots))
|
||||
file = amalgamator.repository[filename]
|
||||
assert file, f"{filename} not found in {[os.path.join(PROJECTPATH, root) for root in roots]}!"
|
||||
assert file, f"Error: Starting file '{filename}' not found in paths {[os.path.join(PROJECTPATH, root) for root in roots]}. Ensure the file exists and the paths are correct."
|
||||
amalgamator.maybe_write_file(file, None, "")
|
||||
amalgamator.repository.validate_free_dependency_files()
|
||||
fid.close()
|
||||
@@ -327,8 +371,8 @@ class Amalgamator:
|
||||
if file.is_conditional_include:
|
||||
if file.is_generic:
|
||||
# Generic files get written out once per implementation in a well-defined order
|
||||
assert (file, self.implementation) not in self.found_generic_includes, f"generic file {file} included from {including_file} a second time for {self.implementation}!"
|
||||
assert self.implementation, file
|
||||
assert (file, self.implementation) not in self.found_generic_includes, f"Error: Generic file '{file}' is being included a second time for implementation '{self.implementation}' from '{including_file}'. Generic files should be included only once per implementation to avoid duplication."
|
||||
assert self.implementation, f"Error: Attempting to write generic file '{file}', but no implementation is currently set. Generic files require an active implementation context."
|
||||
self.found_generic_includes.append((file, self.implementation))
|
||||
else:
|
||||
# Other amalgamated files, on the other hand, may only be included once per *amalgamation*
|
||||
@@ -348,13 +392,13 @@ class Amalgamator:
|
||||
|
||||
def file_to_str(self, file: SimdjsonFile):
|
||||
if file.is_generic and file.is_conditional_include:
|
||||
assert self.implementation, file
|
||||
assert self.implementation, f"Error: In file_to_str for '{file}', implementation is not set. This is required for generic conditional files."
|
||||
return f"{file} for {self.implementation}"
|
||||
return file
|
||||
|
||||
def write_file(self, file: SimdjsonFile):
|
||||
# Detect cyclic dependencies
|
||||
assert file not in self.include_stack, f"Cyclic include: {self.include_stack} -> {file}"
|
||||
assert file not in self.include_stack, f"Error: Cyclic include detected: {self.include_stack} -> {file}. Remove the circular dependency by restructuring includes."
|
||||
self.include_stack.append(file)
|
||||
|
||||
file.processed = False
|
||||
@@ -362,14 +406,13 @@ class Amalgamator:
|
||||
self.write(f"/* begin file {self.file_to_str(file)} */")
|
||||
|
||||
if file == BUILTIN_BEGIN_H:
|
||||
assert self.implementation is None, self.implementation
|
||||
assert not self.builtin_implementation, self.builtin_implementation
|
||||
assert self.implementation is None, f"Error: Starting builtin implementation, but '{self.implementation}' is already set. Builtin should start with no prior implementation."
|
||||
assert not self.builtin_implementation, f"Error: Builtin implementation is already active ({self.builtin_implementation}). Cannot start again."
|
||||
self.builtin_implementation = True
|
||||
self.implementation = "SIMDJSON_BUILTIN_IMPLEMENTATION"
|
||||
|
||||
assert not self.editor_only_region
|
||||
assert not self.editor_only_region, f"Error: Already in an editor-only region when starting to write '{file}'. Ensure proper nesting of conditional blocks."
|
||||
with open(file.absolute_path, 'r') as fid2:
|
||||
print(f"including: {file}")
|
||||
for line in fid2:
|
||||
line = line.rstrip('\n')
|
||||
|
||||
@@ -379,9 +422,9 @@ class Amalgamator:
|
||||
|
||||
# Ignore lines inside #ifndef SIMDJSON_CONDITIONAL_INCLUDE
|
||||
if re.search(r'^#ifndef\s+SIMDJSON_CONDITIONAL_INCLUDE\s*$', line):
|
||||
assert file.is_conditional_include, f"{file} uses #ifndef SIMDJSON_CONDITIONAL_INCLUDE but is not an amalgamated file! {rules}"
|
||||
assert self.in_conditional_include_block, f"{file} uses #ifndef SIMDJSON_CONDITIONAL_INCLUDE without a prior #define SIMDJSON_CONDITIONAL_INCLUDE: {self.include_stack} {rules}"
|
||||
assert not self.editor_only_region, f"{file} uses #ifndef SIMDJSON_CONDITIONAL_INCLUDE twice in a row {rules}"
|
||||
assert file.is_conditional_include, f"Error: File '{file}' uses '#ifndef SIMDJSON_CONDITIONAL_INCLUDE', but it's not an amalgamated file. Conditional includes are only for amalgamated files. {rules}"
|
||||
assert self.in_conditional_include_block, f"Error: File '{file}' uses '#ifndef SIMDJSON_CONDITIONAL_INCLUDE' without a prior '#define SIMDJSON_CONDITIONAL_INCLUDE'. Ensure the define comes first. Stack: {self.include_stack}. {rules}"
|
||||
assert not self.editor_only_region, f"Error: File '{file}' uses '#ifndef SIMDJSON_CONDITIONAL_INCLUDE' twice in a row. Ensure conditional blocks are properly nested and closed. {rules}"
|
||||
self.editor_only_region = True
|
||||
|
||||
# Handle ignored lines (and ending ignore blocks)
|
||||
@@ -399,7 +442,7 @@ class Amalgamator:
|
||||
self.editor_only_region = False
|
||||
continue
|
||||
|
||||
assert not end_ignore, f"{file} has #endif // SIMDJSON_CONDITIONAL_INCLUDE without #ifndef SIMDJSON_CONDITIONAL_INCLUDE {rules}"
|
||||
assert not end_ignore, f"Error: File '{file}' has '#endif // SIMDJSON_CONDITIONAL_INCLUDE' without a matching '#ifndef'. Ensure proper conditional block structure. {rules}"
|
||||
|
||||
# Handle #include lines
|
||||
included = re.search(r'^#include\s+["<]([^">]*)[">]', line)
|
||||
@@ -426,36 +469,36 @@ class Amalgamator:
|
||||
self.implementation = None
|
||||
elif re.search(r'\bSIMDJSON_IMPLEMENTATION\b', line) and file.include_path != IMPLEMENTATION_DETECTION_H:
|
||||
# copy the line, with SIMDJSON_IMPLEMENTATION replace to what it is currently defined to
|
||||
assert self.implementation, f"Use of SIMDJSON_IMPLEMENTATION while not defined in {file}: {line}\n{rules}"
|
||||
assert self.implementation, f"Error: In '{file}', line '{line}' uses SIMDJSON_IMPLEMENTATION, but it's not defined. Ensure SIMDJSON_IMPLEMENTATION is set before use. {rules}"
|
||||
line = re.sub(r'\bSIMDJSON_IMPLEMENTATION\b',self.implementation,line)
|
||||
|
||||
# Handle defining and undefining SIMDJSON_CONDITIONAL_INCLUDE
|
||||
defined = re.search(r'^#define\s+SIMDJSON_CONDITIONAL_INCLUDE\s*$', line)
|
||||
if defined:
|
||||
assert not file.is_conditional_include, "SIMDJSON_CONDITIONAL_INCLUDE defined in amalgamated file {file}! Not allowed. {rules}"
|
||||
assert not self.in_conditional_include_block, f"{file} redefines SIMDJSON_CONDITIONAL_INCLUDE {rules}"
|
||||
assert not file.is_conditional_include, f"Error: Amalgamated file '{file}' defines SIMDJSON_CONDITIONAL_INCLUDE, which is not allowed. Only non-amalgamated files can define it. {rules}"
|
||||
assert not self.in_conditional_include_block, f"Error: File '{file}' redefines SIMDJSON_CONDITIONAL_INCLUDE while already in a conditional block. Avoid redefinition. {rules}"
|
||||
self.in_conditional_include_block = True
|
||||
self.found_includes_per_conditional_block.clear()
|
||||
self.write(f'/* defining SIMDJSON_CONDITIONAL_INCLUDE */')
|
||||
elif re.search(r'^#undef\s+SIMDJSON_CONDITIONAL_INCLUDE\s*$', line):
|
||||
assert not file.is_conditional_include, "SIMDJSON_CONDITIONAL_INCLUDE undefined in amalgamated file {file}! Not allowed. {rules}"
|
||||
assert self.in_conditional_include_block, f"{file} undefines SIMDJSON_CONDITIONAL_INCLUDE without defining it {rules}"
|
||||
assert not file.is_conditional_include, f"Error: Amalgamated file '{file}' undefines SIMDJSON_CONDITIONAL_INCLUDE, which is not allowed. Only non-amalgamated files can undefine it. {rules}"
|
||||
assert self.in_conditional_include_block, f"Error: File '{file}' undefines SIMDJSON_CONDITIONAL_INCLUDE without having defined it first. Ensure proper define/undefine pairing. {rules}"
|
||||
self.write(f'/* undefining SIMDJSON_CONDITIONAL_INCLUDE */')
|
||||
self.in_conditional_include_block = False
|
||||
|
||||
self.write(line)
|
||||
|
||||
assert not self.editor_only_region, f"{file} ended without #endif // SIMDJSON_CONDITIONAL_INCLUDE {rules}"
|
||||
assert not self.editor_only_region, f"Error: File '{file}' ended without closing the '#endif // SIMDJSON_CONDITIONAL_INCLUDE'. Ensure all conditional blocks are properly closed. {rules}"
|
||||
|
||||
self.write(f"/* end file {self.file_to_str(file)} */")
|
||||
|
||||
if file.include_path == BUILTIN_BEGIN_H:
|
||||
# begin.h redefined SIMDJSON_IMPLEMENTATION multiple times
|
||||
assert self.builtin_implementation
|
||||
assert self.builtin_implementation, f"Error: Processing BUILTIN_BEGIN_H, but builtin implementation is not active."
|
||||
self.implementation = "SIMDJSON_BUILTIN_IMPLEMENTATION"
|
||||
elif file.include_path == BUILTIN_END_H:
|
||||
assert self.implementation is None
|
||||
assert self.builtin_implementation
|
||||
assert self.implementation is None, f"Error: Processing BUILTIN_END_H, but implementation is still set to '{self.implementation}'. It should be None."
|
||||
assert self.builtin_implementation, f"Error: Processing BUILTIN_END_H, but builtin implementation is not active."
|
||||
self.implementation = None
|
||||
|
||||
file.processed = True
|
||||
|
||||
@@ -150,6 +150,10 @@ simdjson_warn_unused error_code dom_parser_implementation::stage2_next(dom::docu
|
||||
return stage2::tape_builder::parse_document<true>(*this, _doc);
|
||||
}
|
||||
|
||||
simdjson_warn_unused std::pair<const uint8_t *, bool> dom_parser_implementation::parse_string_if_needed(const uint8_t *src, uint8_t *dst, bool allow_replacement) const noexcept {
|
||||
return arm64::stringparsing::parse_string_if_needed(src, dst, allow_replacement);
|
||||
}
|
||||
|
||||
SIMDJSON_NO_SANITIZE_MEMORY
|
||||
simdjson_warn_unused uint8_t *dom_parser_implementation::parse_string(const uint8_t *src, uint8_t *dst, bool allow_replacement) const noexcept {
|
||||
return arm64::stringparsing::parse_string(src, dst, allow_replacement);
|
||||
|
||||
@@ -444,6 +444,10 @@ simdjson_warn_unused error_code dom_parser_implementation::stage2_next(dom::docu
|
||||
return stage2::tape_builder::parse_document<true>(*this, _doc);
|
||||
}
|
||||
|
||||
simdjson_warn_unused std::pair<const uint8_t *, bool> dom_parser_implementation::parse_string_if_needed(const uint8_t *src, uint8_t *dst, bool allow_replacement) const noexcept {
|
||||
return fallback::stringparsing::parse_string_if_needed(src, dst, allow_replacement);
|
||||
}
|
||||
|
||||
SIMDJSON_NO_SANITIZE_MEMORY
|
||||
simdjson_warn_unused uint8_t *dom_parser_implementation::parse_string(const uint8_t *src, uint8_t *dst, bool replacement_char) const noexcept {
|
||||
return fallback::stringparsing::parse_string(src, dst, replacement_char);
|
||||
|
||||