mirror of
https://github.com/simdjson/simdjson
synced 2026-06-08 17:27:07 +00:00
Compare commits
507 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 88374a416f | |||
| 74870a8189 | |||
| 0ef4d90ad0 | |||
| 1a1e7edb02 | |||
| 51b835f71b | |||
| e38fe3d361 | |||
| cc042c9936 | |||
| 599e3bc937 | |||
| 1fa0d940bc | |||
| 7dc4a9525b | |||
| b6f1f4ef64 | |||
| 3faae67663 | |||
| ccc94c9b05 | |||
| 1fd30db726 | |||
| 0ba76ac066 | |||
| 8b661fe556 | |||
| 077907b7c3 | |||
| 172d669780 | |||
| 6b85b9a416 | |||
| 5d3001279c | |||
| 4582a13360 | |||
| 3a064535ae | |||
| 444ec4ad27 | |||
| 94e910586d | |||
| bb5ce007e6 | |||
| deaa74d378 | |||
| 13e1794e91 | |||
| 67b3595008 | |||
| 6c33f518a8 | |||
| 88da62ba09 | |||
| b6997a56df | |||
| 74178fd1c2 | |||
| 34c59bfa90 | |||
| 2956bce047 | |||
| 41f33ecbb9 | |||
| 86241e2871 | |||
| 1e32897d3e | |||
| 1b63a9a9b5 | |||
| 4c9f11b78a | |||
| 32348c2b0b | |||
| 5e690c5d04 | |||
| 4ec56484a1 | |||
| 8f2a5649fe | |||
| c3b25e12a5 | |||
| 6d3e33d440 | |||
| c11f7ce54f | |||
| 84806cc174 | |||
| 16f12f7d59 | |||
| 8609b8e589 | |||
| 29e744fdbb | |||
| 515b87bcbe | |||
| 5fa9faca20 | |||
| a4ebdfd47c | |||
| 188d8d4b64 | |||
| ce5581d428 | |||
| 5b4acf14ea | |||
| 5fc6cb15b8 | |||
| f6e9a8eee4 | |||
| 6c0950cb2e | |||
| cb8a9ef2c0 | |||
| 470cbbe9ff | |||
| e01f1434fb | |||
| 187084ce46 | |||
| b6f9382b5b | |||
| 57f68381ed | |||
| 3e35729eb6 | |||
| 544fa57641 | |||
| 7e94309046 | |||
| 21eff5b825 | |||
| b408d7c95e | |||
| d9929edbc1 | |||
| 843b73dedb | |||
| 02a8145b18 | |||
| cfcb315b14 | |||
| c8a70a0a73 | |||
| b84a3a0230 | |||
| 49d70232f8 | |||
| 8cc9f496ee | |||
| 1547f2ec80 | |||
| 42a8b40de0 | |||
| b4b968ff44 | |||
| 52e3c063c5 | |||
| 257089884f | |||
| c650ea9765 | |||
| e369d45b9c | |||
| 2d84b6f6d9 | |||
| eef1171944 | |||
| 12ccdcf858 | |||
| f1a03bfb04 | |||
| 696b0e29e4 | |||
| 5eb748ae17 | |||
| aa4340ef5c | |||
| 0062e54e93 | |||
| dada5090b0 | |||
| 1c4593c648 | |||
| e7004cef76 | |||
| 2bb101bd19 | |||
| 26baf70912 | |||
| 89c2582376 | |||
| 33e003616d | |||
| bf03d77ab9 | |||
| a6cbf1f922 | |||
| d6f056f266 | |||
| 69a247d500 | |||
| a76c67c19f | |||
| b836164a38 | |||
| 058507badf | |||
| ad40e90790 | |||
| 0c9dc11550 | |||
| 1ff55c2729 | |||
| 066269153e | |||
| 38bb08778a | |||
| 5dbcdf1484 | |||
| f03a6ab5a4 | |||
| 6fa5abcd7e | |||
| 5dc07ed295 | |||
| 064d4255d5 | |||
| 04139eb82e | |||
| 1b1a122b1f | |||
| ccb132320c | |||
| c0e7f824df | |||
| 05bba71eaf | |||
| 7ebe5c4bcf | |||
| ae1bd891e7 | |||
| 9899e5021d | |||
| 94440e0170 | |||
| c25928e44f | |||
| a7fc7d4ffb | |||
| f336103f63 | |||
| 56e2b38048 | |||
| a5ccff720a | |||
| 1d8c2d6c22 | |||
| 0b8c357eff | |||
| efc168f473 | |||
| d8428f98d9 | |||
| 60f17d26a3 | |||
| 05bc664c11 | |||
| 2cc84b6e51 | |||
| 5ccdbef7d5 | |||
| c13c2650a2 | |||
| ec6c998a3a | |||
| 2f6091419f | |||
| 2022dd7d74 | |||
| b8202dab3b | |||
| ef688a74fe | |||
| f632e7c043 | |||
| 04a19f9813 | |||
| 2cbc591c9d | |||
| 3f00e79bcb | |||
| 3586fc4910 | |||
| c9a6bbeb64 | |||
| 0655a135e6 | |||
| d3e8bb1889 | |||
| 14ceacac73 | |||
| e4f33b5970 | |||
| 4474f8ef18 | |||
| 76c9f4f5a6 | |||
| 942ef3b7f2 | |||
| 0b9df6d8c4 | |||
| b5ea504ad2 | |||
| 803b0c4bdb | |||
| 6537d0dc76 | |||
| f8f36c085c | |||
| 7339f67dd7 | |||
| 0d4e501239 | |||
| 8d609607e2 | |||
| 71a889ed73 | |||
| 27a75a9085 | |||
| 954d6c326d | |||
| 7ea05d038e | |||
| 33930ff046 | |||
| 16f41ea059 | |||
| 0a7270fc29 | |||
| 23fbd9d004 | |||
| 610c79fbf3 | |||
| fd44c2a2ff | |||
| a86a82b39c | |||
| 89b059b1ea | |||
| bd2d0f769f | |||
| d830422489 | |||
| d1a54249e7 | |||
| 4dfbf98e4e | |||
| 1b6258ec8c | |||
| be707dbb6f | |||
| 664b03bb13 | |||
| 7c6723d912 | |||
| 1febf2ec83 | |||
| fe69928764 | |||
| bbd61eb13f | |||
| e15e1e253d | |||
| 45e2178ada | |||
| a6e4933d93 | |||
| 98599e0972 | |||
| b4837f2e2f | |||
| ea08e7d192 | |||
| d178e089a6 | |||
| 5f00b37e21 | |||
| 8a8792d47f | |||
| 59d9bc9e48 | |||
| 8793dd3ceb | |||
| 48062380fa | |||
| 3636aa5522 | |||
| a1aea4588f | |||
| 1d4fffb799 | |||
| 6f90f5dc5f | |||
| 9dd6972d26 | |||
| d731a7d52c | |||
| 059468b74e | |||
| 5e69fb782a | |||
| a5beffda78 | |||
| 7de7ce5fdc | |||
| 383e8c7f68 | |||
| 0dbda65e44 | |||
| fe01da077e | |||
| d43a4e9df9 | |||
| 3e226795f0 | |||
| c4a0fe1606 | |||
| ef63a84a3e | |||
| 8c16ba372e | |||
| 9be4a17687 | |||
| 89332e1696 | |||
| 8a56129def | |||
| ed0c815735 | |||
| 7a69da16e4 | |||
| 351717414d | |||
| 52f44de257 | |||
| ae6dddfff4 | |||
| 539f555e23 | |||
| b75fa26dc1 | |||
| 3d22a2d845 | |||
| 1aab4752e2 | |||
| 86f8a4a9d2 | |||
| db2cb061cb | |||
| 6a71b24495 | |||
| 84712a8bbc | |||
| b86fb95306 | |||
| a3a9bde83e | |||
| 2fe2dd170b | |||
| f772bf4fbc | |||
| ac0c3093f4 | |||
| 12150baa5e | |||
| 219b02c1e5 | |||
| 4551e60f8b | |||
| ea842e78af | |||
| 5651fbedc4 | |||
| 2f87dfd4a9 | |||
| 332dd76867 | |||
| d2c9ea8a9a | |||
| 40d57da83c | |||
| 561813eb2a | |||
| e6c9dfbd91 | |||
| 603b6596af | |||
| 64abc3e86c | |||
| fac42fa3e8 | |||
| 7ad4020829 | |||
| 72ab0d11ff | |||
| 4ea866f050 | |||
| a476531524 | |||
| e7e6ac5bb3 | |||
| f346362b00 | |||
| d9ba455695 | |||
| 8927a0561f | |||
| e03c5e9f23 | |||
| 1f79200db8 | |||
| c009e4a57d | |||
| c615d52cf4 | |||
| dbb3316511 | |||
| cd6f204c77 | |||
| 269131ed21 | |||
| 65d784e88e | |||
| 35afb6cae0 | |||
| 27bce09be8 | |||
| 4f25b6ac0c | |||
| 3d5ed1a7e3 | |||
| a03115a4a6 | |||
| 7219d28a31 | |||
| 0875bce68f | |||
| 54fe302907 | |||
| edaa8f811f | |||
| 2c8fd109de | |||
| 07fe7ad1a2 | |||
| 16d88cc095 | |||
| 2a6e6b3dbd | |||
| 0c19848230 | |||
| 3c3a4db54e | |||
| 0e6bd2224f | |||
| a64d2f4673 | |||
| 1e8a54af0b | |||
| aa53d8708e | |||
| 8c600ca553 | |||
| 25fe6d7dde | |||
| afb369950c | |||
| d7f133c24c | |||
| 5312fd30e5 | |||
| 23dd0bdaa1 | |||
| 1d06624d38 | |||
| d40069a018 | |||
| 73e27bdd48 | |||
| 064eb0b24f | |||
| af968c5b44 | |||
| f93dbe51e2 | |||
| 1c34707925 | |||
| deaca58504 | |||
| 1d519aa9cb | |||
| 191faeae70 | |||
| 1153aaf55b | |||
| 292cb5a5af | |||
| 1e9488d4a6 | |||
| ff1d77ead9 | |||
| 977e1a94b2 | |||
| 60ee5fc844 | |||
| 940c8fcb5e | |||
| 71e0148eb4 | |||
| 293c104cc4 | |||
| 5a3035bb72 | |||
| e04cbd71d0 | |||
| fa4ce6a8bc | |||
| 9863f62321 | |||
| 7cd1f7dbd5 | |||
| 8c45a18524 | |||
| 8cb383ed45 | |||
| 7d1305b169 | |||
| 24ab1f32e4 | |||
| 073ad0dada | |||
| f43b6a0675 | |||
| fc1ddcd2f8 | |||
| e7f774f964 | |||
| cb49af1ea5 | |||
| 73d7d704c1 | |||
| 8b89232f12 | |||
| c3dec1a5ea | |||
| 44b06d70e8 | |||
| eee07e6cfd | |||
| 5051c27c3d | |||
| 76f3506ac5 | |||
| 5d7a84fad7 | |||
| dec161ed26 | |||
| 0f9dbf84b7 | |||
| f0d5337818 | |||
| 4cd9de5c37 | |||
| 76b0bfa7f5 | |||
| 32d6b0eed4 | |||
| 127d962271 | |||
| 92d7af0881 | |||
| af12066f77 | |||
| 2a1f8fa8f1 | |||
| 04e47bde84 | |||
| 49da7e74cd | |||
| 6ac47734c0 | |||
| 0e6ea76e88 | |||
| 0514588175 | |||
| 59d1212039 | |||
| d61cca6720 | |||
| 8c74e88f16 | |||
| 46cf512032 | |||
| 24a185d26b | |||
| b99a7344c9 | |||
| c6a4fb1e13 | |||
| e2718fe845 | |||
| 76314280cb | |||
| d6716218bd | |||
| 9371a92122 | |||
| e8b030ad17 | |||
| e0180b4849 | |||
| 3901bbb401 | |||
| 76bebfd798 | |||
| 3013166d8d | |||
| 8596e702ac | |||
| 414bf4a296 | |||
| 0daa01edef | |||
| 98abd96075 | |||
| 8e3fc826e2 | |||
| c750095241 | |||
| 2a0c0c0ad2 | |||
| 92f3bb89c3 | |||
| ac0e6c5e6e | |||
| f397b6fedf | |||
| 1d069e5077 | |||
| c5684a6278 | |||
| f3ac0be0e6 | |||
| 18c9468af5 | |||
| 32bc0da362 | |||
| c9a3800ce7 | |||
| d4239aaa8f | |||
| 4f72d5cfac | |||
| 66acab4130 | |||
| 9e9e3373e0 | |||
| 502fee1b45 | |||
| 4d0c7d706d | |||
| 6cd418b60a | |||
| a3b39dfd1a | |||
| 74da47e286 | |||
| 587ba9bec0 | |||
| 382392e03b | |||
| 409948a0f9 | |||
| 34919ca394 | |||
| 0d1c574cb1 | |||
| c564815931 | |||
| f6fb667ac1 | |||
| 832bbe734d | |||
| 7a2fda891c | |||
| e50c239a2e | |||
| cc7c8d92da | |||
| 87acab0846 | |||
| f43459d476 | |||
| e030f02776 | |||
| 10f2d01e7f | |||
| 80dbf9a32a | |||
| 185274e70f | |||
| f0ac55ec0c | |||
| 44544635dd | |||
| 3c594b1037 | |||
| ea7100e8c4 | |||
| a198abc485 | |||
| d4a37f6ef5 | |||
| a5c9c31231 | |||
| e3ec78a832 | |||
| a116e68a47 | |||
| e7084de166 | |||
| 398eda6365 | |||
| 349abf5ee6 | |||
| 4ce40b1975 | |||
| 536fe28f8f | |||
| 3e9e14f4d6 | |||
| c8140068ad | |||
| db314bc381 | |||
| 499a26b152 | |||
| a9cdb5be50 | |||
| 5f04208dbd | |||
| ffaa292006 | |||
| d3e44b1108 | |||
| fbf274a42b | |||
| d94cd65dfd | |||
| 3c1b403c4e | |||
| 75564453b3 | |||
| 3091e2dc0e | |||
| fc50a36cc5 | |||
| 9bf9fba2ec | |||
| 121615da70 | |||
| 53d28a713c | |||
| cf37704193 | |||
| 38289fe381 | |||
| f9337a1111 | |||
| 6d059b479f | |||
| b6e23b2d3e | |||
| e5e6a46c37 | |||
| 22b9a53bef | |||
| 3be81e3206 | |||
| ff09b6c824 | |||
| a8e892ba90 | |||
| 289cc3e7a0 | |||
| 7480b87e07 | |||
| befa6423be | |||
| fd418f568c | |||
| 09cf18a646 | |||
| 326c175dcb | |||
| 6d7c77ddc1 | |||
| efd706528b | |||
| b523c43927 | |||
| 75545ff70d | |||
| 3c6ef83046 | |||
| b9ac0a79f1 | |||
| 8539896f3d | |||
| a3b508ceff | |||
| 334a486737 | |||
| d7370cc916 | |||
| 92c34f7f38 | |||
| 93328c8d6d | |||
| 5710ec13d4 | |||
| fa637fcecb | |||
| 4af7d6f108 | |||
| 0fd159dadb | |||
| 1ff22c78b3 | |||
| ceb1def55c | |||
| 893a1d8306 | |||
| 3c91690e55 | |||
| 6835dd73bc | |||
| 7317fe1440 | |||
| 7b58fea911 | |||
| c1ff74c9a6 | |||
| 6dabfa176a | |||
| 0714f5fc67 | |||
| 3b1b1bfd48 | |||
| 218c867f46 | |||
| 2bc12f9730 | |||
| 5e564a8e0c | |||
| beaa6a9a7a | |||
| a9c8224f40 | |||
| 3dcc188d93 | |||
| 10b7556a37 | |||
| 54b7291c34 | |||
| 1e30b6e334 | |||
| 406240bae3 | |||
| 74d9b41b7d | |||
| ff0b0c54b7 | |||
| 6eec2d6b4f | |||
| 5731c5437a | |||
| 04f14ec026 | |||
| 12ed6336b1 | |||
| 3cb79e6977 | |||
| c5e21a2469 | |||
| 13aee51011 | |||
| 53fca1b5e6 | |||
| 7dad9fca0f | |||
| b249d7c76c | |||
| 4060f64232 | |||
| 5b2f7d3374 |
+40
-21
@@ -1,29 +1,48 @@
|
||||
version: '{build}'
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
image:
|
||||
- Visual Studio 2017
|
||||
clone_folder: c:\projects\simdjson
|
||||
|
||||
platform:
|
||||
- x64
|
||||
branches: { only: [ master ] }
|
||||
configuration: Release
|
||||
image: Visual Studio 2019
|
||||
platform: x64
|
||||
|
||||
environment:
|
||||
matrix:
|
||||
- SIMDJSON_BUILD_STATIC: "OFF"
|
||||
THREADS: "ON"
|
||||
- SIMDJSON_BUILD_STATIC: "OFF"
|
||||
THREADS: "OFF"
|
||||
- SIMDJSON_BUILD_STATIC: "ON"
|
||||
THREADS: "ON"
|
||||
# - SIMDJSON_BUILD_STATIC: "ON"
|
||||
# THREADS: "OFF"
|
||||
|
||||
- job_name: VS2019
|
||||
CMAKE_ARGS: -A %Platform%
|
||||
- job_name: VS2019CLANG
|
||||
CMAKE_ARGS: -A %Platform% -T ClangCL
|
||||
- job_name: VS2019ARM
|
||||
CMAKE_ARGS: -A ARM64 -DCMAKE_CROSSCOMPILING=1 -D SIMDJSON_GOOGLE_BENCHMARKS=OFF # Does Google Benchmark builds under VS ARM?
|
||||
- job_name: VS2017 (Static, No Threads)
|
||||
image: Visual Studio 2017
|
||||
CMAKE_ARGS: -A %Platform% -DSIMDJSON_BUILD_STATIC=ON -DSIMDJSON_ENABLE_THREADS=OFF
|
||||
CTEST_ARGS: -E checkperf
|
||||
- job_name: VS2019 (Win32)
|
||||
platform: Win32
|
||||
CMAKE_ARGS: -A %Platform% -DSIMDJSON_BUILD_STATIC=OFF -DSIMDJSON_ENABLE_THREADS=ON # This should be the default. Testing anyway.
|
||||
CTEST_ARGS: -E checkperf
|
||||
- job_name: VS2015
|
||||
image: Visual Studio 2015
|
||||
CMAKE_ARGS: -A %Platform% -DSIMDJSON_BUILD_STATIC=ON -DSIMDJSON_ENABLE_THREADS=OFF
|
||||
CTEST_ARGS: -E checkperf
|
||||
|
||||
build_script:
|
||||
- mkdir build
|
||||
- cd build
|
||||
- ps: cmake -DSIMDJSON_BUILD_STATIC="$env:SIMDJSON_BUILD_STATIC" -DSIMDJSON_ENABLE_THREADS="$env:THREADS" -DCMAKE_BUILD_TYPE=Release -DCMAKE_GENERATOR_PLATFORM=x64 -DSIMDJSON_GOOGLE_BENCHMARKS=OFF ..
|
||||
- cmake --build .
|
||||
- ctest --verbose --output-on-failure
|
||||
- cmake --version
|
||||
- cmake %CMAKE_ARGS% --parallel ..
|
||||
- cmake -LH ..
|
||||
- cmake --build . --config %Configuration% --verbose --parallel
|
||||
|
||||
for:
|
||||
-
|
||||
matrix:
|
||||
except:
|
||||
- job_name: VS2019ARM
|
||||
|
||||
test_script:
|
||||
- ctest --output-on-failure -C %Configuration% --verbose %CTEST_ARGS% --parallel
|
||||
|
||||
clone_folder: c:\projects\simdjson
|
||||
|
||||
matrix:
|
||||
fast_finish: true
|
||||
|
||||
+205
-172
@@ -7,210 +7,243 @@ executors:
|
||||
- image: gcc:7
|
||||
environment:
|
||||
CXX: g++
|
||||
CC: gcc
|
||||
BUILD_FLAGS: -j
|
||||
CTEST_FLAGS: -j4 --output-on-failure
|
||||
|
||||
gcc8:
|
||||
docker:
|
||||
- image: gcc:8
|
||||
- image: conanio/gcc8
|
||||
environment:
|
||||
CXX: g++
|
||||
CXX: g++-8
|
||||
CC: gcc-8
|
||||
BUILD_FLAGS: -j
|
||||
CTEST_FLAGS: -j4 --output-on-failure
|
||||
|
||||
gcc9:
|
||||
docker:
|
||||
- image: gcc:9
|
||||
- image: conanio/gcc9
|
||||
environment:
|
||||
CXX: g++
|
||||
CXX: g++-9
|
||||
CC: gcc-9
|
||||
BUILD_FLAGS: -j
|
||||
CTEST_FLAGS: -j4 --output-on-failure
|
||||
|
||||
gcc10:
|
||||
docker:
|
||||
- image: conanio/gcc10
|
||||
environment:
|
||||
CXX: g++-10
|
||||
CC: gcc-10
|
||||
BUILD_FLAGS: -j
|
||||
CTEST_FLAGS: -j4 --output-on-failure
|
||||
|
||||
clang10:
|
||||
docker:
|
||||
- image: conanio/clang10
|
||||
environment:
|
||||
CXX: clang++-10
|
||||
CC: clang-10
|
||||
BUILD_FLAGS: -j
|
||||
CTEST_FLAGS: -j4 --output-on-failure
|
||||
|
||||
clang9:
|
||||
docker:
|
||||
- image: conanio/clang9
|
||||
environment:
|
||||
CXX: clang++-9
|
||||
CC: clang-9
|
||||
BUILD_FLAGS: -j
|
||||
CTEST_FLAGS: -j4 --output-on-failure
|
||||
|
||||
clang6:
|
||||
docker:
|
||||
- image: ubuntu:18.04
|
||||
- image: conanio/clang60
|
||||
environment:
|
||||
CXX: clang++-6.0
|
||||
CC: clang-6.0
|
||||
BUILD_FLAGS: -j
|
||||
CTEST_FLAGS: -j4 --output-on-failure
|
||||
|
||||
# Reusable test commands (and initializer for clang 6)
|
||||
commands:
|
||||
init_clang6:
|
||||
steps:
|
||||
- run: apt-get update -qq
|
||||
- run: apt-get install -y clang build-essential git
|
||||
make_test:
|
||||
steps:
|
||||
- checkout
|
||||
- run: make
|
||||
- run: make amalgamate
|
||||
- run: ARCHFLAGS=-march=haswell make amalgamate # some users do this: https://github.com/lemire/simdjson/issues/444
|
||||
- run: make test
|
||||
- run: make checkperf
|
||||
- run: make clean
|
||||
- run: ARCHFLAGS=-march=haswell make test # this breaks runtime dispatch, but see https://github.com/lemire/simdjson/issues/444... this is a code robustness test
|
||||
- run: make clean
|
||||
- run: EXTRAFLAGS=-DSIMDJSON_NO_COMPUTED_GOTO=true make test # this should run tests with computed gotos disabled
|
||||
make_test_strict:
|
||||
steps:
|
||||
- checkout
|
||||
- run: EXTRAFLAGS=-Werror make
|
||||
- run: EXTRAFLAGS=-Werror make amalgamate
|
||||
- run: ARCHFLAGS=-march=haswell make amalgamate # some users do this: https://github.com/lemire/simdjson/issues/444
|
||||
- run: EXTRAFLAGS=-Werror make quicktests
|
||||
- run: make clean
|
||||
|
||||
cmake_test:
|
||||
install_cmake:
|
||||
steps:
|
||||
- run: apt-get update -qq
|
||||
- run: apt-get install -y cmake
|
||||
|
||||
cmake_prep:
|
||||
steps:
|
||||
- checkout
|
||||
- run: cmake $CMAKE_TEST_FLAGS
|
||||
- run: make
|
||||
- run: make test
|
||||
- run: mkdir -p build
|
||||
|
||||
cmake_build:
|
||||
steps:
|
||||
- cmake_prep
|
||||
- run: |
|
||||
cd build &&
|
||||
cmake $CMAKE_FLAGS -DCMAKE_INSTALL_PREFIX:PATH=destination .. &&
|
||||
make $BUILD_FLAGS all
|
||||
|
||||
cmake_test:
|
||||
steps:
|
||||
- cmake_build
|
||||
- run: |
|
||||
cd build && tools/json2json -h &&
|
||||
ctest $CTEST_FLAGS -L acceptance &&
|
||||
ctest $CTEST_FLAGS -LE acceptance -E checkperf
|
||||
|
||||
cmake_test_all:
|
||||
steps:
|
||||
- cmake_build
|
||||
- run: |
|
||||
cd build && tools/json2json -h &&
|
||||
ctest $CTEST_FLAGS -L acceptance -LE per_implementation &&
|
||||
SIMDJSON_FORCE_IMPLEMENTATION=haswell ctest $CTEST_FLAGS -L per_implementation &&
|
||||
SIMDJSON_FORCE_IMPLEMENTATION=westmere ctest $CTEST_FLAGS -L per_implementation &&SIMDJSON_FORCE_IMPLEMENTATION=fallback ctest $CTEST_FLAGS -L per_implementation &&
|
||||
ctest $CTEST_FLAGS -LE "acceptance|per_implementation" # Everything we haven't run yet, run now.
|
||||
|
||||
|
||||
# we not only want cmake to build and run tests, but we want also a successful installation from which we can build, link and run programs
|
||||
cmake_install_test: # this version builds, install, test and then verify from the installation
|
||||
steps:
|
||||
- run: cd build && make install
|
||||
- run: echo -e '#include <simdjson.h>\nint main(int argc,char**argv) {simdjson::dom::parser parser;simdjson::dom::element tweets = parser.load(argv[1]); }' > tmp.cpp && c++ -Ibuild/destination/include -Lbuild/destination/lib -std=c++17 -Wl,-rpath,build/destination/lib -o linkandrun tmp.cpp -lsimdjson && ./linkandrun jsonexamples/twitter.json
|
||||
|
||||
jobs:
|
||||
|
||||
gcc-avx-unthreaded:
|
||||
description: Build, run tests and check performance on GCC 7 and AVX 2 *without* threads
|
||||
# static
|
||||
gcc7:
|
||||
description: Build and run tests on GCC 7 and AVX 2 with a cmake static build
|
||||
executor: gcc7
|
||||
environment: { CMAKE_TEST_FLAGS: -DSIMDJSON_ENABLE_THREADS=OFF }
|
||||
environment: { CMAKE_FLAGS: -DSIMDJSON_GOOGLE_BENCHMARKS=ON -DSIMDJSON_BUILD_STATIC=ON }
|
||||
steps: [ install_cmake, cmake_test, cmake_install_test ]
|
||||
justlib-gcc10:
|
||||
description: Build just the library, install it and do a basic test
|
||||
executor: gcc10
|
||||
environment: { CMAKE_FLAGS: -DSIMDJSON_JUST_LIBRARY=ON }
|
||||
steps: [ cmake_build, cmake_install_test ]
|
||||
gcc10:
|
||||
description: Build and run tests on GCC 10 and AVX 2 with a cmake static build, this test performance regression
|
||||
executor: gcc10
|
||||
environment: { CMAKE_FLAGS: -DSIMDJSON_GOOGLE_BENCHMARKS=ON -DSIMDJSON_BUILD_STATIC=ON }
|
||||
steps: [ cmake_test_all, cmake_install_test ]
|
||||
clang6:
|
||||
description: Build and run tests on clang 6 and AVX 2 with a cmake static build
|
||||
executor: clang6
|
||||
environment: { CMAKE_FLAGS: -DSIMDJSON_GOOGLE_BENCHMARKS=ON -DSIMDJSON_BUILD_STATIC=ON }
|
||||
steps: [ cmake_test, cmake_install_test ]
|
||||
clang10:
|
||||
description: Build and run tests on clang 10 and AVX 2 with a cmake static build
|
||||
executor: clang10
|
||||
environment: { CMAKE_FLAGS: -DSIMDJSON_GOOGLE_BENCHMARKS=ON -DSIMDJSON_BUILD_STATIC=ON }
|
||||
steps: [ cmake_test, cmake_install_test ]
|
||||
# libcpp
|
||||
libcpp-clang10:
|
||||
description: Build and run tests on clang 10 and AVX 2 with a cmake static build and libc++
|
||||
executor: clang10
|
||||
environment: { CMAKE_FLAGS: -DSIMDJSON_USE_LIBCPP=ON -DSIMDJSON_BUILD_STATIC=ON }
|
||||
steps: [ cmake_test, cmake_install_test ]
|
||||
# sanitize
|
||||
sanitize-gcc10:
|
||||
description: Build and run tests on GCC 10 and AVX 2 with a cmake sanitize build
|
||||
executor: gcc10
|
||||
environment: { CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF -DSIMDJSON_SANITIZE=ON, BUILD_FLAGS: "", CTEST_FLAGS: -j4 --output-on-failure -E checkperf }
|
||||
steps: [ cmake_test ]
|
||||
gcc-avx-threaded:
|
||||
description: Build, run tests and check performance on GCC 7 and AVX 2 with threads
|
||||
executor: gcc7
|
||||
environment: { CMAKE_TEST_FLAGS: -DSIMDJSON_ENABLE_THREADS=ON }
|
||||
sanitize-clang10:
|
||||
description: Build and run tests on clang 10 and AVX 2 with a cmake sanitize build
|
||||
executor: clang10
|
||||
environment: { CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF -DSIMDJSON_SANITIZE=ON, CTEST_FLAGS: -j4 --output-on-failure -E checkperf }
|
||||
steps: [ cmake_test ]
|
||||
|
||||
clang-avx-unthreaded:
|
||||
description: Build, run tests and check performance on Clang 6 and AVX 2 *without* threads
|
||||
executor: clang6
|
||||
environment: { CMAKE_TEST_FLAGS: -DSIMDJSON_ENABLE_THREADS=OFF }
|
||||
steps: [ init_clang6, cmake_test ]
|
||||
clang-avx-threaded:
|
||||
description: Build, run tests and check performance on Clang 6 and AVX 2 with threads
|
||||
executor: clang6
|
||||
environment: { CMAKE_TEST_FLAGS: -DSIMDJSON_ENABLE_THREADS=ON }
|
||||
steps: [ init_clang6, cmake_test ]
|
||||
# dynamic
|
||||
dynamic-gcc10:
|
||||
description: Build and run tests on GCC 10 and AVX 2 with a cmake dynamic build
|
||||
executor: gcc10
|
||||
environment: { CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF }
|
||||
steps: [ cmake_test, cmake_install_test ]
|
||||
dynamic-clang10:
|
||||
description: Build and run tests on clang 10 and AVX 2 with a cmake dynamic build
|
||||
executor: clang10
|
||||
environment: { CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF }
|
||||
steps: [ cmake_test, cmake_install_test ]
|
||||
|
||||
gcc9-avx:
|
||||
description: Build, run tests and check performance on GCC 9 and AVX 2
|
||||
executor: gcc9
|
||||
steps: [ make_test_strict ]
|
||||
gcc8-avx:
|
||||
description: Build, run tests and check performance on GCC 8 and AVX 2
|
||||
executor: gcc9
|
||||
steps: [ make_test_strict ]
|
||||
gcc-avx:
|
||||
description: Build, run tests and check performance on GCC 7 and AVX 2
|
||||
executor: gcc7
|
||||
steps: [ make_test ]
|
||||
gcc-avx-dynamic:
|
||||
description: Build, run tests and check performance on GCC 7 and AVX 2 with a cmake dynamic build
|
||||
executor: gcc7
|
||||
environment: { CMAKE_TEST_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF }
|
||||
steps: [ cmake_test ]
|
||||
gcc-avx-static:
|
||||
description: Build, run tests and check performance on GCC 7 and AVX 2 with a cmake static build
|
||||
executor: gcc7
|
||||
environment: { CMAKE_TEST_FLAGS: -DSIMDJSON_BUILD_STATIC=ON }
|
||||
steps: [ cmake_test ]
|
||||
gcc-avx-google-benchmarks:
|
||||
description: Build, run tests and check performance on GCC 7 with google benchmarks enabled
|
||||
executor: gcc7
|
||||
environment: { CMAKE_TEST_FLAGS: -DSIMDJSON_GOOGLE_BENCHMARKS=ON }
|
||||
steps: [ cmake_test ]
|
||||
gcc-avx-sanitize:
|
||||
description: Build, run tests and check performance on GCC 7 and AVX 2 with a cmake sanitize build
|
||||
executor: gcc7
|
||||
environment: { CMAKE_TEST_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF -DSIMDJSON_SANITIZE=ON }
|
||||
steps: [ cmake_test ]
|
||||
# unthreaded
|
||||
unthreaded-gcc10:
|
||||
description: Build and run tests on GCC 10 and AVX 2 *without* threads
|
||||
executor: gcc10
|
||||
environment: { CMAKE_FLAGS: -DSIMDJSON_ENABLE_THREADS=OFF }
|
||||
steps: [ cmake_test, cmake_install_test ]
|
||||
unthreaded-clang10:
|
||||
description: Build and run tests on Clang 10 and AVX 2 *without* threads
|
||||
executor: clang10
|
||||
environment: { CMAKE_FLAGS: -DSIMDJSON_ENABLE_THREADS=OFF }
|
||||
steps: [ cmake_test, cmake_install_test ]
|
||||
|
||||
gcc-sse:
|
||||
description: Build, run tests and check performance on GCC 7 and SSE 4.2
|
||||
executor: gcc7
|
||||
environment: { ARCHFLAGS: -march=nehalem }
|
||||
steps: [ make_test ]
|
||||
gcc-sse-dynamic:
|
||||
description: Build, run tests and check performance on GCC 7 and SSE 4.2 with a cmake dynamic build
|
||||
executor: gcc7
|
||||
environment: { CMAKE_TEST_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF }
|
||||
steps: [ cmake_test ]
|
||||
gcc-sse-static:
|
||||
description: Build, run tests and check performance on GCC 7 and SSE 4.2 with a cmake static build
|
||||
executor: gcc7
|
||||
environment: { CMAKE_TEST_FLAGS: -DSIMDJSON_BUILD_STATIC=ON }
|
||||
steps: [ cmake_test ]
|
||||
gcc-sse-sanitize:
|
||||
description: Build, run tests and check performance on GCC 7 and SSE 4.2 with a cmake sanitize build
|
||||
executor: gcc7
|
||||
environment: { CMAKE_TEST_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF -DSIMDJSON_SANITIZE=ON }
|
||||
steps: [ cmake_test ]
|
||||
# noexcept
|
||||
noexcept-gcc10:
|
||||
description: Build and run tests on GCC 10 and AVX 2 with exceptions off
|
||||
executor: gcc10
|
||||
environment: { CMAKE_FLAGS: -DSIMDJSON_EXCEPTIONS=OFF }
|
||||
steps: [ cmake_test, cmake_install_test ]
|
||||
noexcept-clang10:
|
||||
description: Build and run tests on Clang 10 and AVX 2 with exceptions off
|
||||
executor: clang10
|
||||
environment: { CMAKE_FLAGS: -DSIMDJSON_EXCEPTIONS=OFF }
|
||||
steps: [ cmake_test, cmake_install_test ]
|
||||
|
||||
clang-avx:
|
||||
description: Build, run tests and check performance on clang 6 and AVX 2
|
||||
executor: clang6
|
||||
steps: [ init_clang6, make_test ]
|
||||
clang-avx-dynamic:
|
||||
description: Build, run tests and check performance on clang 6 and AVX 2 with a cmake dynamic build
|
||||
executor: clang6
|
||||
environment: { CMAKE_TEST_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF }
|
||||
steps: [ init_clang6, cmake_test ]
|
||||
clang-avx-static:
|
||||
description: Build, run tests and check performance on clang 6 and AVX 2 with a cmake static build
|
||||
executor: clang6
|
||||
environment: { CMAKE_TEST_FLAGS: -DSIMDJSON_BUILD_STATIC=ON }
|
||||
steps: [ init_clang6, cmake_test ]
|
||||
clang-avx-google-benchmarks:
|
||||
description: Build, run tests and check performance on clang 6 with google benchmarks enabled
|
||||
executor: clang6
|
||||
environment: { CMAKE_TEST_FLAGS: -DSIMDJSON_GOOGLE_BENCHMARKS=ON }
|
||||
steps: [ init_clang6, cmake_test ]
|
||||
clang-avx-sanitize:
|
||||
description: Build, run tests and check performance on clang 6 and AVX 2 with a cmake sanitize build
|
||||
executor: clang6
|
||||
environment: { CMAKE_TEST_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF -DSIMDJSON_SANITIZE=ON }
|
||||
steps: [ init_clang6, cmake_test ]
|
||||
#
|
||||
# Misc.
|
||||
#
|
||||
|
||||
clang-sse:
|
||||
description: Build, run tests and check performance on Clang 6 and SSE 4.2
|
||||
executor: clang6
|
||||
environment: { ARCHFLAGS: -march=nehalem }
|
||||
steps: [ init_clang6, make_test ]
|
||||
clang-sse-dynamic:
|
||||
description: Build, run tests and check performance on Clang 6 and SSE 4.2 with a cmake dynamic build
|
||||
executor: clang6
|
||||
environment: { CMAKE_TEST_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF }
|
||||
steps: [ init_clang6, cmake_test ]
|
||||
clang-sse-static:
|
||||
description: Build, run tests and check performance on Clang 6 and SSE 4.2 with a cmake static build
|
||||
executor: clang6
|
||||
environment: { CMAKE_TEST_FLAGS: -DSIMDJSON_BUILD_STATIC=ON }
|
||||
steps: [ init_clang6, cmake_test ]
|
||||
clang-sse-sanitize:
|
||||
description: Build, run tests and check performance on Clang 6 and SSE 4.2 with a cmake sanitize build
|
||||
executor: clang6
|
||||
environment: { CMAKE_TEST_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF -DSIMDJSON_SANITIZE=ON }
|
||||
steps: [ init_clang6, cmake_test ]
|
||||
# make (test and checkperf)
|
||||
arch-haswell-gcc10:
|
||||
description: Build, run tests and check performance on GCC 7 with -march=haswell
|
||||
executor: gcc10
|
||||
environment: { CXXFLAGS: -march=haswell }
|
||||
steps: [ cmake_test ]
|
||||
arch-nehalem-gcc10:
|
||||
description: Build, run tests and check performance on GCC 7 with -march=nehalem
|
||||
executor: gcc10
|
||||
environment: { CXXFLAGS: -march=nehalem }
|
||||
steps: [ cmake_test ]
|
||||
no-computed-goto-gcc10:
|
||||
description: Build, run tests and check performance on GCC 7 with -DSIMDJSON_NO_COMPUTED_GOTO=true
|
||||
executor: gcc10
|
||||
environment: { CXXFLAGS: -DSIMDJSON_NO_COMPUTED_GOTO=true }
|
||||
steps: [ cmake_test ]
|
||||
|
||||
workflows:
|
||||
version: 2.1
|
||||
build_and_test:
|
||||
jobs:
|
||||
- gcc9-avx
|
||||
- gcc8-avx
|
||||
- gcc-avx
|
||||
- gcc-avx-dynamic
|
||||
- gcc-avx-static
|
||||
- gcc-avx-google-benchmarks
|
||||
- gcc-avx-sanitize
|
||||
- gcc-sse
|
||||
- gcc-sse-dynamic
|
||||
- gcc-sse-static
|
||||
- gcc-sse-sanitize
|
||||
- clang-avx
|
||||
- clang-avx-dynamic
|
||||
- clang-avx-static
|
||||
- clang-avx-google-benchmarks
|
||||
- clang-avx-sanitize
|
||||
- clang-sse
|
||||
- clang-sse-dynamic
|
||||
- clang-sse-static
|
||||
- clang-sse-sanitize
|
||||
- gcc-avx-threaded
|
||||
- gcc-avx-unthreaded
|
||||
- clang-avx-threaded
|
||||
- clang-avx-unthreaded
|
||||
# full multi-implementation tests
|
||||
- gcc7
|
||||
- gcc10 # do not delete this as it tests our performance
|
||||
- clang6
|
||||
#- clang10 # this gets tested a lot below
|
||||
|
||||
# libc++
|
||||
- libcpp-clang10
|
||||
|
||||
# full single-implementation tests
|
||||
- sanitize-gcc10
|
||||
- sanitize-clang10
|
||||
- dynamic-gcc10
|
||||
- dynamic-clang10
|
||||
- unthreaded-gcc10
|
||||
- unthreaded-clang10
|
||||
|
||||
# no exceptions
|
||||
- noexcept-gcc10
|
||||
- noexcept-clang10
|
||||
|
||||
# quicker make single-implementation tests
|
||||
- arch-haswell-gcc10
|
||||
- arch-nehalem-gcc10
|
||||
- no-computed-goto-gcc10
|
||||
|
||||
# testing "just the library"
|
||||
- justlib-gcc10
|
||||
|
||||
# TODO add windows: https://circleci.com/docs/2.0/configuration-reference/#windows
|
||||
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
task:
|
||||
timeout_in: 120m
|
||||
freebsd_instance:
|
||||
matrix:
|
||||
- image_family: freebsd-13-0-snap
|
||||
|
||||
env:
|
||||
ASSUME_ALWAYS_YES: YES
|
||||
setup_script:
|
||||
- pkg update -f
|
||||
- pkg install bash
|
||||
- pkg install cmake
|
||||
- pkg install git
|
||||
build_script:
|
||||
- mkdir build
|
||||
- cd build
|
||||
- cmake ..
|
||||
- make -j4
|
||||
test_script:
|
||||
- cd build
|
||||
- ctest -j4 --output-on-failure -E checkperf
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
*
|
||||
!.git
|
||||
!Makefile
|
||||
!amalgamation.sh
|
||||
!amalgamate.sh
|
||||
!benchmark
|
||||
!dependencies
|
||||
!include
|
||||
|
||||
+343
-508
@@ -1,207 +1,389 @@
|
||||
kind: pipeline
|
||||
name: x64-quicktests-libc
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
name: i386-gcc # we do not support 32-bit systems, but we run tests
|
||||
platform: { os: linux, arch: amd64 }
|
||||
steps:
|
||||
- name: quicktests
|
||||
image: conanio/clang8
|
||||
- name: Build and Test
|
||||
image: i386/ubuntu
|
||||
environment:
|
||||
CC: gcc
|
||||
CXX: g++
|
||||
BUILD_FLAGS: -- -j
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=ON
|
||||
CTEST_FLAGS: -j4 --output-on-failure -E checkperf
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y g++ cmake gcc
|
||||
- mkdir build
|
||||
- cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- cmake --build . $BUILD_FLAGS
|
||||
- ctest $CTEST_FLAGS
|
||||
---
|
||||
kind: pipeline
|
||||
name: i386-clang # we do not support 32-bit systems, but we run tests
|
||||
platform: { os: linux, arch: amd64 }
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: i386/ubuntu
|
||||
environment:
|
||||
CC: clang-6.0
|
||||
CXX: clang++-6.0
|
||||
BUILD_FLAGS: -- -j
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=ON
|
||||
CTEST_FLAGS: -j4 --output-on-failure -E checkperf
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y clang++-6.0 cmake
|
||||
- mkdir build
|
||||
- cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- cmake --build . $BUILD_FLAGS
|
||||
- ctest $CTEST_FLAGS
|
||||
---
|
||||
kind: pipeline
|
||||
name: gcc9
|
||||
platform: { os: linux, arch: amd64 }
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: gcc:9
|
||||
environment:
|
||||
CC: gcc
|
||||
CXX: g++
|
||||
BUILD_FLAGS: -- -j
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=ON
|
||||
CTEST_FLAGS: -j4 --output-on-failure -E checkperf
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y cmake
|
||||
- mkdir build
|
||||
- cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- cmake --build . $BUILD_FLAGS
|
||||
- ctest $CTEST_FLAGS -L acceptance -LE per_implementation
|
||||
- SIMDJSON_FORCE_IMPLEMENTATION=haswell ctest $CTEST_FLAGS -L per_implementation
|
||||
- SIMDJSON_FORCE_IMPLEMENTATION=westmere ctest $CTEST_FLAGS -L per_implementation
|
||||
- SIMDJSON_FORCE_IMPLEMENTATION=fallback ctest $CTEST_FLAGS -L per_implementation
|
||||
- ctest $CTEST_FLAGS -LE "acceptance|per_implementation" # Everything we haven't run yet, run now.
|
||||
---
|
||||
kind: pipeline
|
||||
name: clang6
|
||||
platform: { os: linux, arch: amd64 }
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: conanio/clang60
|
||||
user: root
|
||||
commands: [ EXTRAFLAGS=-stdlib=libc++ make quicktests ]
|
||||
environment:
|
||||
CC: clang-6.0
|
||||
CXX: clang++-6.0
|
||||
BUILD_FLAGS: -- -j
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=ON
|
||||
CTEST_FLAGS: -j4 --output-on-failure -E checkperf
|
||||
commands:
|
||||
- mkdir build
|
||||
- cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- cmake --build . $BUILD_FLAGS
|
||||
- ctest $CTEST_FLAGS -L acceptance -LE per_implementation
|
||||
- SIMDJSON_FORCE_IMPLEMENTATION=haswell ctest $CTEST_FLAGS -L per_implementation
|
||||
- SIMDJSON_FORCE_IMPLEMENTATION=westmere ctest $CTEST_FLAGS -L per_implementation
|
||||
- SIMDJSON_FORCE_IMPLEMENTATION=fallback ctest $CTEST_FLAGS -L per_implementation
|
||||
- ctest $CTEST_FLAGS -LE "acceptance|per_implementation" # Everything we haven't run yet, run now.
|
||||
---
|
||||
kind: pipeline
|
||||
name: x64-quicktests
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
name: dynamic-gcc9
|
||||
platform: { os: linux, arch: amd64 }
|
||||
steps:
|
||||
- name: quicktests
|
||||
image: gcc:8
|
||||
commands: [ make quicktests ]
|
||||
- name: Build and Test
|
||||
image: gcc:9
|
||||
environment:
|
||||
CC: gcc
|
||||
CXX: g++
|
||||
BUILD_FLAGS: -- -j
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF
|
||||
CTEST_FLAGS: -j4 --output-on-failure -E checkperf
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y cmake
|
||||
- mkdir build
|
||||
- cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- cmake --build . $BUILD_FLAGS
|
||||
- ctest $CTEST_FLAGS
|
||||
---
|
||||
kind: pipeline
|
||||
name: x64-checkperf
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
name: dynamic-clang9
|
||||
platform: { os: linux, arch: amd64 }
|
||||
steps:
|
||||
- name: checkperf
|
||||
- name: Build and Test
|
||||
image: conanio/clang9
|
||||
user: root
|
||||
environment:
|
||||
CC: clang-9
|
||||
CXX: clang++-9
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF
|
||||
BUILD_FLAGS: -- -j
|
||||
CTEST_FLAGS: -j4 --output-on-failure -E checkperf
|
||||
commands:
|
||||
- mkdir build
|
||||
- cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- cmake --build . $BUILD_FLAGS
|
||||
- ctest $CTEST_FLAGS
|
||||
---
|
||||
kind: pipeline
|
||||
name: sanitize-gcc9
|
||||
platform: { os: linux, arch: amd64 }
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: gcc:9
|
||||
environment:
|
||||
CC: gcc
|
||||
CXX: g++
|
||||
BUILD_FLAGS: -- -j
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=ON
|
||||
CTEST_FLAGS: -j4 --output-on-failure -E checkperf
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y cmake
|
||||
- mkdir build
|
||||
- cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- cmake --build . $BUILD_FLAGS
|
||||
- ASAN_OPTIONS="detect_leaks=0" ctest $CTEST_FLAGS -L acceptance -LE per_implementation
|
||||
- SIMDJSON_FORCE_IMPLEMENTATION=haswell ASAN_OPTIONS="detect_leaks=0" ctest $CTEST_FLAGS -L per_implementation
|
||||
- SIMDJSON_FORCE_IMPLEMENTATION=westmere ASAN_OPTIONS="detect_leaks=0" ctest $CTEST_FLAGS -L per_implementation
|
||||
- SIMDJSON_FORCE_IMPLEMENTATION=fallback ASAN_OPTIONS="detect_leaks=0" ctest $CTEST_FLAGS -L per_implementation
|
||||
- ASAN_OPTIONS="detect_leaks=0" ctest $CTEST_FLAGS -LE "acceptance|per_implementation" # Everything we haven't run yet, run now.
|
||||
---
|
||||
kind: pipeline
|
||||
name: sanitize-clang9
|
||||
platform: { os: linux, arch: amd64 }
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: conanio/clang9
|
||||
user: root
|
||||
environment:
|
||||
CC: clang-9
|
||||
CXX: clang++-9
|
||||
CMAKE_FLAGS: -DSIMDJSON_SANITIZE=ON
|
||||
BUILD_FLAGS: -- -j
|
||||
CTEST_FLAGS: -j4 --output-on-failure -E checkperf
|
||||
commands:
|
||||
- mkdir build
|
||||
- cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- cmake --build . $BUILD_FLAGS
|
||||
- ASAN_OPTIONS="detect_leaks=0" ctest $CTEST_FLAGS -L acceptance -LE per_implementation
|
||||
- SIMDJSON_FORCE_IMPLEMENTATION=haswell ASAN_OPTIONS="detect_leaks=0" ctest $CTEST_FLAGS -L per_implementation
|
||||
- SIMDJSON_FORCE_IMPLEMENTATION=westmere ASAN_OPTIONS="detect_leaks=0" ctest $CTEST_FLAGS -L per_implementation
|
||||
- SIMDJSON_FORCE_IMPLEMENTATION=fallback ASAN_OPTIONS="detect_leaks=0" ctest $CTEST_FLAGS -L per_implementation
|
||||
- ASAN_OPTIONS="detect_leaks=0" ctest $CTEST_FLAGS -LE "acceptance|per_implementation" # Everything we haven't run yet, run now.
|
||||
---
|
||||
kind: pipeline
|
||||
name: arm64-gcc8
|
||||
platform: { os: linux, arch: arm64 }
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: gcc:8
|
||||
environment:
|
||||
CHECKPERF_REPOSITORY: https://github.com/lemire/simdjson
|
||||
commands: [ sed '/^$/Q' /proc/cpuinfo, make checkperf ]
|
||||
CC: gcc
|
||||
CXX: g++
|
||||
BUILD_FLAGS: -- -j
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=ON
|
||||
CTEST_FLAGS: -j4 --output-on-failure -E checkperf
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y cmake
|
||||
- mkdir build
|
||||
- cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- cmake --build . $BUILD_FLAGS
|
||||
- ctest $CTEST_FLAGS -L acceptance -LE per_implementation
|
||||
- SIMDJSON_FORCE_IMPLEMENTATION=arm64 ctest $CTEST_FLAGS -L per_implementation
|
||||
- SIMDJSON_FORCE_IMPLEMENTATION=fallback ctest $CTEST_FLAGS -L per_implementation
|
||||
- ctest $CTEST_FLAGS -LE "acceptance|per_implementation" # Everything we haven't run yet, run now.
|
||||
---
|
||||
kind: pipeline
|
||||
name: x64-build
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
name: arm64-clang6
|
||||
platform: { os: linux, arch: arm64 }
|
||||
steps:
|
||||
- name: build
|
||||
image: gcc:8
|
||||
commands: [ make, make amalgamate ]
|
||||
- name: Build and Test
|
||||
image: ubuntu:18.04
|
||||
environment:
|
||||
CC: clang-6.0
|
||||
CXX: clang++-6.0
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF
|
||||
BUILD_FLAGS: -- -j
|
||||
CTEST_FLAGS: -j4 --output-on-failure -E checkperf
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y clang cmake git
|
||||
- mkdir build
|
||||
- cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- cmake --build . $BUILD_FLAGS
|
||||
- ctest $CTEST_FLAGS
|
||||
---
|
||||
kind: pipeline
|
||||
name: x64-slowtests
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
name: arm64-dynamic-gcc8
|
||||
platform: { os: linux, arch: arm64 }
|
||||
steps:
|
||||
- name: slowtests
|
||||
image: gcc:8
|
||||
commands: [ make slowtests ]
|
||||
---
|
||||
kind: pipeline
|
||||
name: x64-noexceptions-quicktests
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
steps:
|
||||
- name: quicktests
|
||||
- name: Build and Test
|
||||
image: gcc:8
|
||||
environment:
|
||||
EXTRA_FLAGS: -fno-exceptions
|
||||
commands: [ make quicktests ]
|
||||
CC: gcc
|
||||
CXX: g++
|
||||
BUILD_FLAGS: -- -j
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF
|
||||
CTEST_FLAGS: -j4 --output-on-failure -E checkperf
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y cmake
|
||||
- mkdir build
|
||||
- cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- cmake --build . $BUILD_FLAGS
|
||||
- ctest $CTEST_FLAGS
|
||||
---
|
||||
kind: pipeline
|
||||
name: x64-noexceptions-build
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
name: arm64-dynamic-clang6
|
||||
platform: { os: linux, arch: arm64 }
|
||||
steps:
|
||||
- name: build
|
||||
- name: Build and Test
|
||||
image: ubuntu:18.04
|
||||
environment:
|
||||
CC: clang-6.0
|
||||
CXX: clang++-6.0
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF
|
||||
BUILD_FLAGS: -- -j
|
||||
CTEST_FLAGS: -j4 --output-on-failure -E checkperf
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y clang cmake git
|
||||
- mkdir build
|
||||
- cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- cmake --build . $BUILD_FLAGS
|
||||
- ctest $CTEST_FLAGS
|
||||
---
|
||||
kind: pipeline
|
||||
name: arm64-sanitize-gcc8
|
||||
platform: { os: linux, arch: arm64 }
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: gcc:8
|
||||
environment:
|
||||
EXTRA_FLAGS: -fno-exceptions
|
||||
commands: [ make, make amalgamate ]
|
||||
BUILD_FLAGS: -- -j
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=ON
|
||||
CTEST_FLAGS: -j4 --output-on-failure -E checkperf
|
||||
CC: gcc
|
||||
CXX: g++
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y cmake libstdc++6
|
||||
- mkdir build
|
||||
- cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- cmake --build . $BUILD_FLAGS
|
||||
- ASAN_OPTIONS="detect_leaks=0" ctest $CTEST_FLAGS -L acceptance -LE per_implementation
|
||||
- SIMDJSON_FORCE_IMPLEMENTATION=arm64 ASAN_OPTIONS="detect_leaks=0" ctest $CTEST_FLAGS -L per_implementation
|
||||
- SIMDJSON_FORCE_IMPLEMENTATION=fallback ASAN_OPTIONS="detect_leaks=0" ctest $CTEST_FLAGS -L per_implementation
|
||||
- ASAN_OPTIONS="detect_leaks=0" ctest $CTEST_FLAGS -LE "acceptance|per_implementation" # Everything we haven't run yet, run now.
|
||||
---
|
||||
kind: pipeline
|
||||
name: x64-noexceptions-slowtests
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
name: arm64-sanitize-clang6
|
||||
platform: { os: linux, arch: arm64 }
|
||||
steps:
|
||||
- name: slowtests
|
||||
image: gcc:8
|
||||
- name: Build and Test
|
||||
image: ubuntu:18.04
|
||||
environment:
|
||||
EXTRA_FLAGS: -fno-exceptions
|
||||
commands: [ make slowtests ]
|
||||
CC: clang-6.0
|
||||
CXX: clang++-6.0
|
||||
CMAKE_FLAGS: -DSIMDJSON_SANITIZE=ON
|
||||
BUILD_FLAGS: -- -j
|
||||
CTEST_FLAGS: -j4 --output-on-failure -E checkperf
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y clang cmake git
|
||||
- mkdir build
|
||||
- cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- cmake --build . $BUILD_FLAGS
|
||||
- ASAN_OPTIONS="detect_leaks=0" ctest $CTEST_FLAGS -L acceptance -LE per_implementation
|
||||
- SIMDJSON_FORCE_IMPLEMENTATION=arm64 ASAN_OPTIONS="detect_leaks=0" ctest $CTEST_FLAGS -L per_implementation
|
||||
- SIMDJSON_FORCE_IMPLEMENTATION=fallback ASAN_OPTIONS="detect_leaks=0" ctest $CTEST_FLAGS -L per_implementation
|
||||
- ASAN_OPTIONS="detect_leaks=0" ctest $CTEST_FLAGS -LE "acceptance|per_implementation" # Everything we haven't run yet, run now.
|
||||
---
|
||||
kind: pipeline
|
||||
name: arm64-quicktests
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: arm64
|
||||
|
||||
name: ninja-clang9
|
||||
platform: { os: linux, arch: amd64 }
|
||||
steps:
|
||||
- name: quicktests
|
||||
image: gcc:8
|
||||
commands: [ make quicktests ]
|
||||
---
|
||||
kind: pipeline
|
||||
name: arm64-checkperf
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: arm64
|
||||
|
||||
steps:
|
||||
- name: checkperf
|
||||
image: gcc:8
|
||||
- name: Build and Test
|
||||
image: conanio/clang9
|
||||
user: root
|
||||
environment:
|
||||
CHECKPERF_REPOSITORY: https://github.com/lemire/simdjson
|
||||
commands: [ cat /proc/cpuinfo, make checkperf ]
|
||||
CC: clang-9
|
||||
CXX: clang++-9
|
||||
BUILD_FLAGS: -- -j 4
|
||||
CMAKE_FLAGS: -GNinja -DSIMDJSON_BUILD_STATIC=ON
|
||||
CTEST_FLAGS: -j4 --output-on-failure
|
||||
CXXFLAGS: -stdlib=libc++
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y cmake
|
||||
- mkdir build
|
||||
- cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- cmake --build . $BUILD_FLAGS
|
||||
- ctest $CTEST_FLAGS
|
||||
---
|
||||
kind: pipeline
|
||||
name: arm64-build
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: arm64
|
||||
|
||||
name: libcpp-clang9
|
||||
platform: { os: linux, arch: amd64 }
|
||||
steps:
|
||||
- name: build
|
||||
image: gcc:8
|
||||
commands: [ make, make amalgamate ]
|
||||
---
|
||||
kind: pipeline
|
||||
name: arm64-slowtests
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: arm64
|
||||
|
||||
steps:
|
||||
- name: slowtests
|
||||
image: gcc:8
|
||||
commands: [ make slowtests ]
|
||||
---
|
||||
kind: pipeline
|
||||
name: x64-amalgamated-build
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
steps:
|
||||
- name: build
|
||||
image: gcc:8
|
||||
- name: Build and Test
|
||||
image: conanio/clang9
|
||||
user: root
|
||||
environment:
|
||||
SIMDJSON_TEST_AMALGAMATED_HEADERS: 1
|
||||
commands: [ make amalgamate, make ]
|
||||
CC: clang-9
|
||||
CXX: clang++-9
|
||||
BUILD_FLAGS: -- -j
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=ON
|
||||
CTEST_FLAGS: -j4 --output-on-failure -E checkperf
|
||||
CXXFLAGS: -stdlib=libc++
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y cmake
|
||||
- mkdir build
|
||||
- cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- cmake --build . $BUILD_FLAGS
|
||||
- ctest $CTEST_FLAGS
|
||||
---
|
||||
kind: pipeline
|
||||
name: x64-amalgamated-quicktests
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
name: noexceptions-gcc9
|
||||
platform: { os: linux, arch: amd64 }
|
||||
steps:
|
||||
- name: quicktests
|
||||
image: gcc:8
|
||||
- name: Build and Test
|
||||
image: gcc:9
|
||||
environment:
|
||||
SIMDJSON_TEST_AMALGAMATED_HEADERS: 1
|
||||
commands: [ make amalgamate, make quicktests ]
|
||||
---
|
||||
kind: pipeline
|
||||
name: x64-amalgamated-slowtests
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
steps:
|
||||
- name: slowtests
|
||||
image: gcc:8
|
||||
environment:
|
||||
SIMDJSON_TEST_AMALGAMATED_HEADERS: 1
|
||||
commands: [ make amalgamate, make slowtests ]
|
||||
CC: gcc
|
||||
CXX: g++
|
||||
BUILD_FLAGS: -- -j
|
||||
CMAKE_FLAGS: -DSIMDJSON_EXCEPTIONS=OFF
|
||||
CTEST_FLAGS: -j4 --output-on-failure -E checkperf
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y cmake
|
||||
- mkdir build
|
||||
- cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- cmake --build . $BUILD_FLAGS
|
||||
- ctest $CTEST_FLAGS
|
||||
---
|
||||
kind: pipeline
|
||||
name: stylecheck
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
platform: { os: linux, arch: amd64 }
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: ubuntu:18.04
|
||||
@@ -209,350 +391,3 @@ steps:
|
||||
- apt-get update -y
|
||||
- apt-get install -y python clang-format
|
||||
- ./style/run-clang-format.py -r include/ benchmark/ src/ tests/
|
||||
---
|
||||
kind: pipeline
|
||||
name: amd64_clang_cmake_dynamic
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: ubuntu:18.04
|
||||
environment:
|
||||
CC: clang
|
||||
CXX: clang++
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y clang make cmake
|
||||
- $CC --version
|
||||
- mkdir build && cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- make -j
|
||||
- ctest --output-on-failure
|
||||
---
|
||||
kind: pipeline
|
||||
name: amd64_clang_cmake_no_exceptions
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: ubuntu:18.04
|
||||
environment:
|
||||
CC: clang
|
||||
CXX: clang++
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y clang make cmake
|
||||
- $CC --version
|
||||
- mkdir build && cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- make -j
|
||||
- ctest --output-on-failure
|
||||
kind: pipeline
|
||||
name: amd64_clang_cmake_static
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: ubuntu:18.04
|
||||
environment:
|
||||
CC: clang
|
||||
CXX: clang++
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=ON
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y clang make cmake
|
||||
- $CC --version
|
||||
- mkdir build && cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- make -j
|
||||
- ctest --output-on-failure
|
||||
---
|
||||
kind: pipeline
|
||||
name: amd64_gcc_cmake_static
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: gcc:8
|
||||
environment:
|
||||
CC: gcc
|
||||
CXX: g++
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=ON
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y cmake
|
||||
- $CC --version
|
||||
- mkdir build && cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- make -j
|
||||
- ctest --output-on-failure
|
||||
---
|
||||
kind: pipeline
|
||||
name: amd64_gcc_cmake_dynamic
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: gcc:8
|
||||
environment:
|
||||
CC: gcc
|
||||
CXX: g++
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y cmake
|
||||
- $CC --version
|
||||
- mkdir build && cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- make -j
|
||||
- ctest --output-on-failure
|
||||
---
|
||||
kind: pipeline
|
||||
name: arm64_clang_cmake_dynamic
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: arm64
|
||||
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: ubuntu:18.04
|
||||
environment:
|
||||
CC: clang
|
||||
CXX: clang++
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y clang make cmake
|
||||
- $CC --version
|
||||
- mkdir build && cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- make -j
|
||||
- ctest --output-on-failure
|
||||
---
|
||||
kind: pipeline
|
||||
name: arm64_gcc_cmake_dynamic
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: arm64
|
||||
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: gcc:8
|
||||
environment:
|
||||
CC: gcc
|
||||
CXX: g++
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=OFF
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y cmake
|
||||
- $CC --version
|
||||
- mkdir build && cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- make -j
|
||||
- ctest --output-on-failure
|
||||
---
|
||||
kind: pipeline
|
||||
name: arm64_clang_cmake_static
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: arm64
|
||||
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: ubuntu:18.04
|
||||
environment:
|
||||
CC: clang
|
||||
CXX: clang++
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=ON
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y clang make cmake
|
||||
- $CC --version
|
||||
- mkdir build && cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- make -j
|
||||
- ctest --output-on-failure
|
||||
---
|
||||
kind: pipeline
|
||||
name: arm64_gcc_cmake_static
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: arm64
|
||||
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: gcc:8
|
||||
environment:
|
||||
CC: gcc
|
||||
CXX: g++
|
||||
CMAKE_FLAGS: -DSIMDJSON_BUILD_STATIC=ON
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y cmake
|
||||
- $CC --version
|
||||
- mkdir build && cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- make -j
|
||||
- ctest --output-on-failure
|
||||
|
||||
---
|
||||
kind: pipeline
|
||||
name: arm64_clang_cmake_sanitize
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: arm64
|
||||
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: ubuntu:18.04
|
||||
environment:
|
||||
CC: clang
|
||||
CXX: clang++
|
||||
CMAKE_FLAGS: -DSIMDJSON_SANITIZE=ON
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y clang make cmake
|
||||
- $CC --version
|
||||
- mkdir build && cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- make -j
|
||||
- ASAN_OPTIONS="detect_leaks=0" ctest --output-on-failure
|
||||
---
|
||||
kind: pipeline
|
||||
name: arm64_gcc_cmake_sanitize
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: arm64
|
||||
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: gcc:8
|
||||
environment:
|
||||
CC: gcc
|
||||
CXX: g++
|
||||
CMAKE_FLAGS: -DSIMDJSON_SANITIZE=ON
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y cmake
|
||||
- $CC --version
|
||||
- mkdir build && cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- make -j
|
||||
- ASAN_OPTIONS="detect_leaks=0" ctest --output-on-failure
|
||||
|
||||
---
|
||||
kind: pipeline
|
||||
name: amd64_clang_cmake_sanitize
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: ubuntu:18.04
|
||||
environment:
|
||||
CC: clang
|
||||
CXX: clang++
|
||||
CMAKE_FLAGS: -DSIMDJSON_SANITIZE=ON
|
||||
commands:
|
||||
- apt-get update -y
|
||||
- apt-get install -y make $CC g++ cmake
|
||||
- $CC --version
|
||||
- mkdir build && cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- make -j
|
||||
- ASAN_OPTIONS="detect_leaks=0" ctest --output-on-failure
|
||||
---
|
||||
kind: pipeline
|
||||
name: amd64_gcc_cmake_sanitize
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: gcc:8
|
||||
environment:
|
||||
CC: gcc
|
||||
CXX: g++
|
||||
CMAKE_FLAGS: -DSIMDJSON_SANITIZE=ON
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y cmake
|
||||
- $CC --version
|
||||
- mkdir build && cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- make -j
|
||||
- ASAN_OPTIONS="detect_leaks=0" ctest --output-on-failure
|
||||
|
||||
---
|
||||
kind: pipeline
|
||||
name: amd64_clang_cmake_sanitize_noavx
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: ubuntu:18.04
|
||||
environment:
|
||||
CC: clang
|
||||
CXX: clang++
|
||||
CMAKE_FLAGS: -DSIMDJSON_SANITIZE=ON -DSIMDJSON_IMPLEMENTATION_HASWELL=OFF
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y clang make cmake
|
||||
- $CC --version
|
||||
- mkdir build && cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- make -j
|
||||
- ASAN_OPTIONS="detect_leaks=0" ctest --output-on-failure
|
||||
---
|
||||
kind: pipeline
|
||||
name: amd64_gcc_cmake_sanitize_noavx
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
steps:
|
||||
- name: Build and Test
|
||||
image: gcc:8
|
||||
environment:
|
||||
CC: gcc
|
||||
CXX: g++
|
||||
CMAKE_FLAGS: -DSIMDJSON_SANITIZE=ON -DSIMDJSON_IMPLEMENTATION_HASWELL=OFF
|
||||
commands:
|
||||
- apt-get update -qq
|
||||
- apt-get install -y cmake
|
||||
- $CC --version
|
||||
- mkdir build && cd build
|
||||
- cmake $CMAKE_FLAGS ..
|
||||
- make -j
|
||||
- ASAN_OPTIONS="detect_leaks=0" ctest --output-on-failure
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
Before submitting an issue, please ensure that you have read the documentation:
|
||||
|
||||
* Basics is an overview of how to use simdjson and its APIs: https://github.com/simdjson/simdjson/blob/master/doc/basics.md
|
||||
* Performance shows some more advanced scenarios and how to tune for them: https://github.com/simdjson/simdjson/blob/master/doc/performance.md
|
||||
* Contributing: https://github.com/simdjson/simdjson/blob/master/CONTRIBUTING.md
|
||||
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behaviour: provide a code sample if possible.
|
||||
|
||||
**Configuration (please complete the following information if relevant):**
|
||||
- OS: [e.g. Ubuntu 16.04.6 LTS]
|
||||
- Compiler [e.g. Apple clang version 11.0.3 (clang-1103.0.32.59) x86_64-apple-darwin19.4.0]
|
||||
- Version [e.g. 22]
|
||||
|
||||
|
||||
**Indicate whether you are willing or able to provide a bug fix as a pull request**
|
||||
|
||||
If you plan to contribute to simdjson, please read our
|
||||
* CONTRIBUTING guide: https://github.com/simdjson/simdjson/blob/master/CONTRIBUTING.md and our
|
||||
* HACKING guide: https://github.com/simdjson/simdjson/blob/master/HACKING.md
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: feature request
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
Before submitting an issue, please ensure that you have read the documentation:
|
||||
|
||||
* Basics is an overview of how to use simdjson and its APIs: https://github.com/simdjson/simdjson/blob/master/doc/basics.md
|
||||
* Performance shows some more advanced scenarios and how to tune for them: https://github.com/simdjson/simdjson/blob/master/doc/performance.md
|
||||
* Contributing: https://github.com/simdjson/simdjson/blob/master/CONTRIBUTING.md
|
||||
|
||||
We do not make changes to simdjson without clearly identifiable benefits, which typically means either performance improvements, bug fixes or new features. Avoid bike-shedding: we all have opinions about how to write code, but we want to focus on what makes simdjson objectively better.
|
||||
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
Please provide a clear rationale for the feature. Be advised that simdjson is a community-based project: you should consider providing help.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
|
||||
** Are you willing to contribute code or documentation toward this new feature? **
|
||||
If you plan to contribute to simdjson, please read our
|
||||
* CONTRIBUTING guide: https://github.com/simdjson/simdjson/blob/master/CONTRIBUTING.md and our
|
||||
* HACKING guide: https://github.com/simdjson/simdjson/blob/master/HACKING.md
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
name: Standard issue template
|
||||
about: Issue
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
Before submitting an issue, please ensure that you have read the documentation:
|
||||
|
||||
* Basics is an overview of how to use simdjson and its APIs: https://github.com/simdjson/simdjson/blob/master/doc/basics.md
|
||||
* Performance shows some more advanced scenarios and how to tune for them: https://github.com/simdjson/simdjson/blob/master/doc/performance.md
|
||||
* Contributing: https://github.com/simdjson/simdjson/blob/master/CONTRIBUTING.md
|
||||
|
||||
We do not make changes to simdjson without clearly identifiable benefits, which typically means either performance improvements, bug fixes or new features. Avoid bike-shedding: we all have opinions about how to write code, but we want to focus on what makes simdjson objectively better.
|
||||
|
||||
Is your issue:
|
||||
|
||||
1. A bug report? If so, please point at a reproducible test. Indicate whether you are willing or able to provide a bug fix as a pull request.
|
||||
|
||||
2. A build issue? If so, provide all possible details regarding your system configuration. If we cannot reproduce your issue, we cannot fix it.
|
||||
|
||||
3. A feature request? Please provide a clear rationale for the feature. Be advised that simdjson is a community-based project: you should consider providing help.
|
||||
|
||||
4. A documentation issue? Can you suggest an improvement?
|
||||
|
||||
|
||||
If you plan to contribute to simdjson, please read our
|
||||
* CONTRIBUTING guide: https://github.com/simdjson/simdjson/blob/master/CONTRIBUTING.md and our
|
||||
* HACKING guide: https://github.com/simdjson/simdjson/blob/master/HACKING.md
|
||||
@@ -23,7 +23,7 @@ jobs:
|
||||
sudo apt-get install --quiet ninja-build valgrind zip unzip
|
||||
wget https://apt.llvm.org/llvm.sh
|
||||
chmod +x llvm.sh
|
||||
sudo ./llvm.sh 8
|
||||
sudo ./llvm.sh 9
|
||||
|
||||
- uses: actions/checkout@v1
|
||||
- name: Create and prepare the initial seed corpus
|
||||
@@ -55,7 +55,7 @@ jobs:
|
||||
run: |
|
||||
for fuzzer in $allfuzzers; do
|
||||
mkdir -p out/$fuzzer # in case this is a new fuzzer, or corpus.tar is broken
|
||||
build-ossfuzz-fast8/fuzz/fuzz_$fuzzer out/$fuzzer -max_total_time=30 $artifactsprefix || touch failed
|
||||
build-ossfuzz-fast9/fuzz/fuzz_$fuzzer out/$fuzzer -max_total_time=30 $artifactsprefix || touch failed
|
||||
# make sure the failing output is visible in the log
|
||||
if [ -e failed ] ; then
|
||||
ls fuzzfailure/* |xargs -n1 base64
|
||||
@@ -68,22 +68,22 @@ jobs:
|
||||
for fuzzer in $allfuzzers; do
|
||||
build-ossfuzz-withavx/fuzz/fuzz_$fuzzer out/$fuzzer -max_total_time=20 $artifactsprefix || touch failed
|
||||
build-ossfuzz-noavx/fuzz/fuzz_$fuzzer out/$fuzzer -max_total_time=10 $artifactsprefix || touch failed
|
||||
build-ossfuzz-noavx8/fuzz/fuzz_$fuzzer out/$fuzzer -max_total_time=10 $artifactsprefix || touch failed
|
||||
build-ossfuzz-noavx9/fuzz/fuzz_$fuzzer out/$fuzzer -max_total_time=10 $artifactsprefix || touch failed
|
||||
if [ -e failed ] ; then
|
||||
# make sure the failing output is visible in the log
|
||||
ls fuzzfailure/* |xargs -n1 base64
|
||||
exit 1
|
||||
fi
|
||||
echo disable msan runs, it fails inside the fuzzing engine and not the fuzzed code!
|
||||
echo build-ossfuzz-msan-noavx8/fuzz/fuzz_$fuzzer out/$fuzzer -max_total_time=10 -reload=0 $artifactsprefix
|
||||
echo build-ossfuzz-msan-withavx8/fuzz/fuzz_$fuzzer out/$fuzzer -max_total_time=10 -reload=0 $artifactsprefix
|
||||
echo build-ossfuzz-msan-noavx9/fuzz/fuzz_$fuzzer out/$fuzzer -max_total_time=10 -reload=0 $artifactsprefix
|
||||
echo build-ossfuzz-msan-withavx9/fuzz/fuzz_$fuzzer out/$fuzzer -max_total_time=10 -reload=0 $artifactsprefix
|
||||
echo now have $(ls out/$fuzzer |wc -l) files in corpus
|
||||
done
|
||||
- name: Minimize the corpus with the fast fuzzer
|
||||
run: |
|
||||
for fuzzer in $allfuzzers; do
|
||||
mkdir -p out/cmin/$fuzzer
|
||||
build-ossfuzz-fast8/fuzz/fuzz_$fuzzer -merge=1 out/cmin/$fuzzer out/$fuzzer
|
||||
build-ossfuzz-fast9/fuzz/fuzz_$fuzzer -merge=1 out/cmin/$fuzzer out/$fuzzer
|
||||
rm -rf out/$fuzzer
|
||||
mv out/cmin/$fuzzer out/$fuzzer
|
||||
done
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
name: MinGW32-CI
|
||||
|
||||
on: push
|
||||
|
||||
|
||||
# Important: scoop will either install 32-bit GCC or 64-bit GCC, not both.
|
||||
|
||||
# It is important to build static libraries because cmake is not smart enough under Windows/mingw to take care of the path. So
|
||||
# with a dynamic library, you could get failures due to the fact that the EXE can't find its DLL.
|
||||
|
||||
jobs:
|
||||
ci:
|
||||
name: windows-gcc
|
||||
runs-on: windows-2016
|
||||
|
||||
env:
|
||||
CMAKE_GENERATOR: Ninja # This is critical, try ' cmake -GNinja-DSIMDJSON_BUILD_STATIC=ON .. ' if using the command line
|
||||
CC: gcc
|
||||
CXX: g++
|
||||
|
||||
steps: # To reproduce what is below, start a powershell with administrative rights, using scoop *is* a good idea
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- uses: actions/cache@v2 # we cache the scoop setup with 32-bit GCC
|
||||
id: cache
|
||||
with:
|
||||
path: |
|
||||
C:\ProgramData\scoop
|
||||
key: scoop32 # static key: should be good forever
|
||||
- name: Setup Windows # This should almost never run if the cache works.
|
||||
if: steps.cache.outputs.cache-hit != 'true'
|
||||
shell: powershell
|
||||
run: |
|
||||
Invoke-Expression (New-Object System.Net.WebClient).DownloadString('https://get.scoop.sh')
|
||||
scoop install sudo --global
|
||||
sudo scoop install git --global
|
||||
sudo scoop install ninja --global
|
||||
sudo scoop install cmake --global
|
||||
sudo scoop install gcc --arch 32bit --global
|
||||
$env:path
|
||||
Write-Host 'Everything has been installed, you are good!'
|
||||
- name: Build and Test 32-bit x86
|
||||
shell: powershell
|
||||
run: |
|
||||
$ENV:PATH="C:\ProgramData\scoop\shims;C:\ProgramData\scoop\apps\gcc\current\bin;C:\ProgramData\scoop\apps\ninja\current;$ENV:PATH"
|
||||
g++ --version
|
||||
cmake --version
|
||||
ninja --version
|
||||
git --version
|
||||
mkdir build32
|
||||
cd build32
|
||||
cmake -DSIMDJSON_BUILD_STATIC=ON -DSIMDJSON_COMPETITION=OFF -DSIMDJSON_GOOGLE_BENCHMARKS=OFF -DSIMDJSON_ENABLE_THREADS=OFF ..
|
||||
cmake --build . --target basictests numberparsingcheck stringparsingcheck errortests integer_tests pointercheck --verbose
|
||||
ctest . -R stringparsingcheck --output-on-failure
|
||||
ctest . -R numberparsingcheck --output-on-failure
|
||||
ctest . -R errortests --output-on-failure
|
||||
ctest . -R integer_tests --output-on-failure
|
||||
ctest . -R pointercheck --output-on-failure
|
||||
@@ -0,0 +1,60 @@
|
||||
name: MinGW64-CI
|
||||
|
||||
on: push
|
||||
|
||||
|
||||
# Important: scoop will either install 32-bit GCC or 64-bit GCC, not both.
|
||||
|
||||
# It is important to build static libraries because cmake is not smart enough under Windows/mingw to take care of the path. So
|
||||
# with a dynamic library, you could get failures due to the fact that the EXE can't find its DLL.
|
||||
|
||||
jobs:
|
||||
ci:
|
||||
name: windows-gcc
|
||||
runs-on: windows-2016
|
||||
|
||||
env:
|
||||
CMAKE_GENERATOR: Ninja # This is critical, try ' cmake -GNinja-DSIMDJSON_BUILD_STATIC=ON .. ' if using the command line
|
||||
CC: gcc
|
||||
CXX: g++
|
||||
|
||||
steps: # To reproduce what is below, start a powershell with administrative rights, using scoop *is* a good idea
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
|
||||
- uses: actions/cache@v2 # we cache the scoop setup with 64-bit GCC
|
||||
id: cache
|
||||
with:
|
||||
path: |
|
||||
C:\ProgramData\scoop
|
||||
key: scoop64 # static key: should be good forever
|
||||
- name: Setup Windows # This should almost never run if the cache works.
|
||||
if: steps.cache.outputs.cache-hit != 'true'
|
||||
shell: powershell
|
||||
run: |
|
||||
Invoke-Expression (New-Object System.Net.WebClient).DownloadString('https://get.scoop.sh')
|
||||
scoop install sudo --global
|
||||
sudo scoop install git --global
|
||||
sudo scoop install ninja --global
|
||||
sudo scoop install cmake --global
|
||||
sudo scoop install gcc --arch 64bit --global
|
||||
$env:path
|
||||
Write-Host 'Everything has been installed, you are good!'
|
||||
- name: Build and Test 64-bit x64
|
||||
shell: powershell
|
||||
run: |
|
||||
$ENV:PATH="C:\ProgramData\scoop\shims;C:\ProgramData\scoop\apps\gcc\current\bin;C:\ProgramData\scoop\apps\ninja\current;$ENV:PATH"
|
||||
g++ --version
|
||||
cmake --version
|
||||
ninja --version
|
||||
git --version
|
||||
mkdir build64
|
||||
cd build64
|
||||
cmake -DSIMDJSON_BUILD_STATIC=ON -DSIMDJSON_COMPETITION=OFF -DSIMDJSON_GOOGLE_BENCHMARKS=OFF -DSIMDJSON_ENABLE_THREADS=OFF ..
|
||||
cmake --build . --target basictests numberparsingcheck stringparsingcheck errortests integer_tests pointercheck --verbose
|
||||
ctest . -R stringparsingcheck --output-on-failure
|
||||
ctest . -R numberparsingcheck --output-on-failure
|
||||
ctest . -R errortests --output-on-failure
|
||||
ctest . -R integer_tests --output-on-failure
|
||||
ctest . -R pointercheck --output-on-failure
|
||||
|
||||
+11
-102
@@ -1,8 +1,3 @@
|
||||
visual_studio
|
||||
|
||||
/benchbranch/
|
||||
/submodules/
|
||||
|
||||
# eclipse project files
|
||||
.cproject
|
||||
.project
|
||||
@@ -52,85 +47,6 @@ gens
|
||||
libs
|
||||
objs
|
||||
|
||||
# Build outputs (TODO build to a subdir so we can exclude that instead)
|
||||
/allparserscheckfile
|
||||
/allparsingcompetition
|
||||
/basictests
|
||||
/benchfeatures
|
||||
/benchmark/bench_dom_api
|
||||
/benchmark/bench_parse_call
|
||||
/benchmark/get_corpus_benchmark
|
||||
/benchmark/parse
|
||||
/benchmark/parse_stream
|
||||
/benchmark/perfdiff
|
||||
/benchmark/statisticalmodel
|
||||
/build/
|
||||
/build-ossfuzz-*/
|
||||
/build-plain-*/
|
||||
/corpus.zip
|
||||
/distinctuseridcompetition
|
||||
/errortests
|
||||
/examples/quickstart/quickstart
|
||||
/examples/quickstart/simdjson.cpp
|
||||
/examples/quickstart/simdjson.h
|
||||
/examples/quickstart/twitter.json
|
||||
/fuzz/fuzz_dump
|
||||
/fuzz/fuzz_dump_raw_tape
|
||||
/fuzz/fuzz_parser
|
||||
/fuzz/fuzz_print_json
|
||||
/get_corpus_benchmark
|
||||
/json2json
|
||||
/jsoncheck
|
||||
/jsoncheck_westmere
|
||||
/jsoncheck_fallback
|
||||
/jsonpointer
|
||||
/jsonstats
|
||||
/integer_tests
|
||||
/libsimdjson.so*
|
||||
/minifiercompetition
|
||||
/minify
|
||||
/numberparsingcheck
|
||||
/ossfuzz-out
|
||||
/out
|
||||
/parse
|
||||
/parse_many_test
|
||||
/parse_nonumberparsing
|
||||
/parse_nostringparsing
|
||||
/parse_noutf8validation
|
||||
/parse_stream
|
||||
/parseandstatcompetition
|
||||
/parsingcompetition
|
||||
/perfdiff
|
||||
/pointercheck
|
||||
/readme_examples
|
||||
/readme_examples_noexceptions
|
||||
/statisticalmodel
|
||||
/stringparsingcheck
|
||||
/submodules
|
||||
/ujdecode.o
|
||||
/amalgamation_demo.cpp
|
||||
/simdjson.cpp
|
||||
/simdjson.h
|
||||
/singleheader/amalgamation_demo
|
||||
/singleheader/demo
|
||||
/tests/basictests
|
||||
/tests/errortests
|
||||
/tests/jsoncheck
|
||||
/tests/pointercheck
|
||||
/tests/integer_tests
|
||||
/tests/parse_many_test
|
||||
/tests/readme_examples
|
||||
/tests/readme_examples_noexceptions
|
||||
/tools/json2json
|
||||
/tools/jsonstats
|
||||
/tools/minify
|
||||
|
||||
# Don't check in generated API docs
|
||||
/doc/api
|
||||
|
||||
# Don't check in generated examples
|
||||
/jsonexamples/generated
|
||||
|
||||
# C++ ignore from https://github.com/github/gitignore/blob/master/C%2B%2B.gitignore
|
||||
|
||||
# Prerequisites
|
||||
@@ -167,23 +83,16 @@ objs
|
||||
*.app
|
||||
|
||||
|
||||
### https://raw.github.com/github/gitignore/e92f8db7a027af8cc25da2dc0758317e39697684/CMake.gitignore
|
||||
|
||||
CMakeLists.txt.user
|
||||
CMakeCache.txt
|
||||
CMakeFiles
|
||||
CMakeScripts
|
||||
Testing
|
||||
Makefile
|
||||
cmake_install.cmake
|
||||
install_manifest.txt
|
||||
compile_commands.json
|
||||
CTestTestfile.cmake
|
||||
_deps
|
||||
|
||||
# CMake files that may be specific to our installation
|
||||
/CPackConfig.cmake
|
||||
/CPackSourceConfig.cmake
|
||||
# We check in a custom version of root Makefile that is not generated by CMake
|
||||
!/Makefile
|
||||
|
||||
# Build outputs
|
||||
/build*/
|
||||
/visual_studio/
|
||||
|
||||
# Fuzzer outputs generated by instructions in fuzz/Fuzzing.md
|
||||
/corpus.zip
|
||||
/ossfuzz-out/
|
||||
/out/
|
||||
|
||||
# Generated docs
|
||||
/doc/api
|
||||
|
||||
@@ -31,3 +31,6 @@
|
||||
[submodule "dependencies/benchmark"]
|
||||
path = dependencies/benchmark
|
||||
url = https://github.com/google/benchmark.git
|
||||
[submodule "dependencies/cxxopts"]
|
||||
path = dependencies/cxxopts
|
||||
url = https://github.com/jarro2783/cxxopts
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# List of authors for copyright purposes
|
||||
# List of authors for copyright purposes, in no particular order
|
||||
Daniel Lemire
|
||||
Geoff Langdale
|
||||
John Keiser
|
||||
|
||||
+61
-68
@@ -1,86 +1,81 @@
|
||||
cmake_minimum_required(VERSION 3.9) # CMP0069 NEW
|
||||
|
||||
if (NOT CMAKE_BUILD_TYPE)
|
||||
message(STATUS "No build type selected, default to Release")
|
||||
set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE)
|
||||
endif()
|
||||
|
||||
project(simdjson
|
||||
DESCRIPTION "Parsing gigabytes of JSON per second"
|
||||
LANGUAGES CXX
|
||||
LANGUAGES CXX C
|
||||
)
|
||||
|
||||
# LTO seems to create all sorts of fun problems. Let us
|
||||
# disable temporarily.
|
||||
#include(CheckIPOSupported)
|
||||
#check_ipo_supported(RESULT ltoresult)
|
||||
#if(ltoresult)
|
||||
# set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
|
||||
#endif()
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_MACOSX_RPATH OFF)
|
||||
set(CMAKE_THREAD_PREFER_PTHREAD ON)
|
||||
set(THREADS_PREFER_PTHREAD_FLAG ON)
|
||||
|
||||
set(SIMDJSON_LIB_NAME simdjson)
|
||||
set(PROJECT_VERSION_MAJOR 0)
|
||||
set(PROJECT_VERSION_MINOR 3)
|
||||
set(PROJECT_VERSION_PATCH 0)
|
||||
set(SIMDJSON_LIB_VERSION "0.3.0" CACHE STRING "simdjson library version")
|
||||
set(SIMDJSON_LIB_SOVERSION "0" CACHE STRING "simdjson library soversion")
|
||||
set(PROJECT_VERSION_MINOR 4)
|
||||
set(PROJECT_VERSION_PATCH 7)
|
||||
set(SIMDJSON_SEMANTIC_VERSION "0.4.7" CACHE STRING "simdjson semantic version")
|
||||
set(SIMDJSON_LIB_VERSION "2.0.0" CACHE STRING "simdjson library version")
|
||||
set(SIMDJSON_LIB_SOVERSION "2" CACHE STRING "simdjson library soversion")
|
||||
set(SIMDJSON_GITHUB_REPOSITORY https://github.com/simdjson/simdjson)
|
||||
|
||||
option(SIMDJSON_IMPLEMENTATION_HASWELL "Include the haswell implementation" ON)
|
||||
option(SIMDJSON_IMPLEMENTATION_WESTMERE "Include the westmere implementation" ON)
|
||||
option(SIMDJSON_IMPLEMENTATION_ARM64 "Include the arm64 implementation" ON)
|
||||
option(SIMDJSON_IMPLEMENTATION_FALLBACK "Include the fallback implementation" ON)
|
||||
if(NOT MSVC)
|
||||
option(SIMDJSON_BUILD_STATIC "Build a static library" OFF) # turning it on disables the production of a dynamic library
|
||||
else()
|
||||
option(SIMDJSON_BUILD_STATIC "Build a static library" ON) # turning it on disables the production of a dynamic library
|
||||
include(GNUInstallDirs)
|
||||
include(cmake/simdjson-flags.cmake)
|
||||
include(cmake/simdjson-user-cmakecache.cmake)
|
||||
|
||||
|
||||
|
||||
if(SIMDJSON_JUST_LIBRARY)
|
||||
message( STATUS "Building just the library, omitting all tests, tools and benchmarks." )
|
||||
endif()
|
||||
option(SIMDJSON_SANITIZE "Sanitize addresses" OFF)
|
||||
option(SIMDJSON_GOOGLE_BENCHMARKS "compile the Google Benchmark benchmarks" OFF)
|
||||
option(SIMDJSON_ENABLE_THREADS "enable threaded operation" ON)
|
||||
option(SIMDJSON_EXCEPTIONS "Enable simdjson's exception-throwing interface" ON)
|
||||
|
||||
set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/tools/cmake")
|
||||
#
|
||||
# Set up test data
|
||||
#
|
||||
if(NOT(SIMDJSON_JUST_LIBRARY))
|
||||
enable_testing()
|
||||
add_subdirectory(jsonchecker)
|
||||
add_subdirectory(jsonexamples)
|
||||
add_library(test-data INTERFACE)
|
||||
target_link_libraries(test-data INTERFACE jsonchecker-data jsonexamples-data)
|
||||
endif()
|
||||
|
||||
find_package(CTargets)
|
||||
find_package(Options)
|
||||
|
||||
install(DIRECTORY include/${SIMDJSON_LIB_NAME} DESTINATION include)
|
||||
set (TEST_DATA_DIR "${CMAKE_CURRENT_SOURCE_DIR}/jsonchecker/")
|
||||
set (BENCHMARK_DATA_DIR "${CMAKE_CURRENT_SOURCE_DIR}/jsonexamples/")
|
||||
add_definitions(-DSIMDJSON_TEST_DATA_DIR="${TEST_DATA_DIR}")
|
||||
add_definitions(-DSIMDJSON_BENCHMARK_DATA_DIR="${TEST_DATA_DIR}")
|
||||
enable_testing()
|
||||
include(include/CMakeLists.txt)
|
||||
#
|
||||
# Create the top level simdjson library (must be done at this level to use both src/ and include/
|
||||
# directories) and tools
|
||||
#
|
||||
add_subdirectory(include)
|
||||
add_subdirectory(src)
|
||||
add_subdirectory(tools)
|
||||
add_subdirectory(tests)
|
||||
add_subdirectory(benchmark)
|
||||
|
||||
if (SIMDJSON_GOOGLE_BENCHMARKS)
|
||||
if(NOT EXISTS dependencies/benchmark/CMakeLists.txt)
|
||||
# message(STATUS "Unable to find dependencies/benchmark/CMakeLists.txt")
|
||||
execute_process(COMMAND git submodule update --init -- dependencies/benchmark
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
endif()
|
||||
option(BENCHMARK_ENABLE_TESTING OFF)
|
||||
set(BENCHMARK_ENABLE_TESTING OFF)
|
||||
option(BENCHMARK_ENABLE_INSTALL OFF)
|
||||
set(BENCHMARK_ENABLE_INSTALL OFF)
|
||||
add_subdirectory(dependencies/benchmark)
|
||||
add_subdirectory(windows)
|
||||
if(NOT(SIMDJSON_JUST_LIBRARY))
|
||||
add_subdirectory(dependencies) ## This needs to be before tools because of cxxopts
|
||||
add_subdirectory(tools) ## This needs to be before tests because of cxxopts
|
||||
add_subdirectory(singleheader)
|
||||
endif()
|
||||
install(FILES singleheader/simdjson.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
|
||||
|
||||
# for fuzzing, read the comments in the fuzz/CMakeLists.txt file
|
||||
option(ENABLE_FUZZING "enable building the fuzzers" ON)
|
||||
if(ENABLE_FUZZING)
|
||||
#
|
||||
# Compile tools / tests / benchmarks
|
||||
#
|
||||
if(NOT(SIMDJSON_JUST_LIBRARY))
|
||||
add_subdirectory(tests)
|
||||
add_subdirectory(examples)
|
||||
add_subdirectory(benchmark)
|
||||
add_subdirectory(fuzz)
|
||||
endif()
|
||||
|
||||
#
|
||||
# Source files should be just ASCII
|
||||
#
|
||||
find_program(FIND find)
|
||||
find_program(FILE file)
|
||||
find_program(GREP grep)
|
||||
if((FIND) AND (FILE) AND (GREP))
|
||||
add_test(
|
||||
NAME "just_ascii"
|
||||
COMMAND sh -c "${FIND} include src windows tools singleheader tests examples benchmark -path benchmark/checkperf-reference -prune -name '*.h' -o -name '*.cpp' -type f -exec ${FILE} '{}' \; |${GREP} -v ASCII || exit 0 && exit 1"
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||
)
|
||||
endif()
|
||||
|
||||
|
||||
#
|
||||
# CPack
|
||||
#
|
||||
set(CPACK_PACKAGE_VENDOR "Daniel Lemire")
|
||||
set(CPACK_PACKAGE_CONTACT "lemire@gmail.com")
|
||||
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Parsing gigabytes of JSON per second")
|
||||
@@ -95,5 +90,3 @@ set(CPACK_RPM_PACKAGE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE")
|
||||
set(CPACK_SOURCE_GENERATOR "TGZ;ZIP")
|
||||
|
||||
include(CPack)
|
||||
|
||||
|
||||
|
||||
+39
-3
@@ -5,7 +5,7 @@ The simdjson library is an open project written in C++. Contributions are invite
|
||||
agree to the project's license.
|
||||
|
||||
We have an extensive list of issues, and contributions toward any of these issues is invited.
|
||||
Contributions can take the form of code samples, better documentation or design ideas.
|
||||
Contributions can take the form of code samples, better documentation or design ideas.
|
||||
|
||||
In particular, the following contributions are invited:
|
||||
|
||||
@@ -32,7 +32,19 @@ We discourage the following types of contributions:
|
||||
|
||||
In short, most code changes should either bring new features or better performance. We want to avoid unmotivated code changes.
|
||||
|
||||
Guidelines
|
||||
|
||||
Specific rules
|
||||
----------
|
||||
|
||||
We have few hard rules, but we have some:
|
||||
|
||||
- Printing to standard output or standard error (`stderr`, `stdout`, `std::cerr`, `std::cout`) in the core library is forbidden. This follows from the [Writing R Extensions](https://cran.r-project.org/doc/manuals/R-exts.html) manual which states that "Compiled code should not write to stdout or stderr".
|
||||
- Calls to `abort()` are forbidden in the core library. This follows from the [Writing R Extensions](https://cran.r-project.org/doc/manuals/R-exts.html) manual which states that "Under no circumstances should your compiled code ever call abort or exit".
|
||||
- All source code files (.h, .cpp) must be ASCII.
|
||||
|
||||
Tools, tests and benchmarks are not held to these same strict rules.
|
||||
|
||||
General Guidelines
|
||||
----------
|
||||
|
||||
Contributors are encouraged to :
|
||||
@@ -43,11 +55,35 @@ Contributors are encouraged to :
|
||||
- Tools may report "problems" with the code, but we never delegate programming to tools: if there is a problem with the code, we need to understand it. Thus we will not "fix" code merely to please a static analyzer if we do not understand.
|
||||
- Provide tests for any new feature. We will not merge a new feature without tests.
|
||||
|
||||
Pull Requests
|
||||
--------------
|
||||
|
||||
Pull requests are always invited. However, we ask that you follow these guidelines:
|
||||
|
||||
- It is wiser to discuss your ideas first as part of an issue before you start coding. If you omit this step and code first, be prepare to have your code receive scrutiny and be dropped.
|
||||
- Users should provide a rationale for their changes. Does it improve performance? Does it add a feature? Does it improve maintainability? Does fix a bug? This must be explicitly stated as part of the pull request. Do not propose changes based on taste or intuition. We do not delegate programming to tools: that some tool suggested a code change is not reason enough to change the code.
|
||||
1. When your code improves performance, please document the gains with a benchmark using hard numbers.
|
||||
2. If your code fixes a bug, please be either fix a failing test, or propose a new test.
|
||||
3. Other types of changes must be clearly motivated. We openly discourage changes with no identifiable benefits.
|
||||
- Changes should be focused and minimal. You should change as few lines of code as possible. Please do not reformat or touch files needlessly.
|
||||
- New features must be accompanied of new tests, in general.
|
||||
- Your code should pass our continuous-integration tests. It is your responsability to ensure that your proposal pass the tests. We do not merge pull requests that would break our build.
|
||||
|
||||
If the benefits of your proposed code remain unclear, we may choose to discard your code: that is not an insult, we frequently discard our own code. We may also consider various alternatives and choose another path. Again, that is not an insult or a sign that you have wasted your time.
|
||||
|
||||
Code of Conduct
|
||||
---------------
|
||||
|
||||
Though we do not have a formal code of conduct, we will not tolerate bullying, bigotry or
|
||||
intimidation. Everyone is welcome to contribute.
|
||||
intimidation. Everyone is welcome to contribute. If you have concerns, you can raise them privately with the core team members (e.g., D. Lemire, J. Keiser).
|
||||
|
||||
We welcome contributions from women and less represented groups. If you need help, please reach out.
|
||||
|
||||
Consider the following points when engaging with the project:
|
||||
|
||||
- We discourage arguments from authority: ideas are discusssed on their own merits and not based on who stated it.
|
||||
- Be mindful that what you may view as an aggression is maybe merely a difference of opinion or a misunderstanding.
|
||||
- Be mindful that a collection of small aggressions, even if mild in isolation, can become harmful.
|
||||
|
||||
Getting Started Hacking
|
||||
-----------------------
|
||||
|
||||
@@ -31,5 +31,9 @@ Paul Dreik
|
||||
Jeremie Piotte
|
||||
Matthew Wilson
|
||||
Dušan Jovanović
|
||||
Matjaž Ostroveršnik
|
||||
Nong Li
|
||||
Furkan Taşkale
|
||||
Brendan Knapp
|
||||
# if you have contributed to the project and your name does not
|
||||
# appear in this list, please let us know!
|
||||
|
||||
+88
-10
@@ -1,10 +1,88 @@
|
||||
# docker build -t simdjson . && docker run --privileged -t simdjson
|
||||
FROM gcc:8.3
|
||||
COPY . /usr/src/
|
||||
WORKDIR /usr/src/
|
||||
RUN make clean
|
||||
RUN make amalgamate
|
||||
RUN make
|
||||
RUN make test
|
||||
RUN make parsingcompetition
|
||||
CMD ["bash", "scripts/selectparser.sh"]
|
||||
###
|
||||
#
|
||||
# Though simdjson requires only commonly available compilers and tools, it can
|
||||
# be convenient to build it and test it inside a docker container: it makes it
|
||||
# possible to test and benchmark simdjson under even relatively out-of-date
|
||||
# Linux servers. It should also work under macOS and Windows, though not
|
||||
# at native speeds, maybe.
|
||||
#
|
||||
# Assuming that you have a working docker server, this file
|
||||
# allows you to build, test and benchmark simdjson.
|
||||
#
|
||||
# We build the library and associated files in the dockerbuild subdirectory.
|
||||
# It may be necessary to delete it before creating the image:
|
||||
#
|
||||
# rm -r -f dockerbuild
|
||||
#
|
||||
# The need to delete the directory has nothing to do with docker per se: it is
|
||||
# simply cleaner in CMake to start from a fresh directory. This is important: if you
|
||||
# reuse the same directory with different configurations, you may get broken builds.
|
||||
#
|
||||
#
|
||||
# Then you can build the image as follows:
|
||||
#
|
||||
# docker build -t simdjson --build-arg USER_ID=$(id -u) --build-arg GROUP_ID=$(id -g) .
|
||||
#
|
||||
# Please note that the image does not contain a copy of the code. However, the image will contain the
|
||||
# the compiler and the build system. This means that if you change the source code, after you have built
|
||||
# the image, you won't need to rebuild the image. In fact, unless you want to try a different compiler, you
|
||||
# do not need to ever rebuild the image, even if you do a lot of work on the source code.
|
||||
#
|
||||
# We specify the users to avoid having files owned by a privileged user (root) in our directory. Some
|
||||
# people like to run their machine as the "root" user. We do not think it is cool.
|
||||
#
|
||||
# Then you need to build the project:
|
||||
#
|
||||
# docker run -v $(pwd):/project:Z simdjson
|
||||
#
|
||||
# Should you change a source file, you may need to call this command again. Because the output
|
||||
# files are persistent between calls to this command (they reside in the dockerbuild directory),
|
||||
# this command can be fast.
|
||||
#
|
||||
# Next you can test it as follows:
|
||||
#
|
||||
# docker run -it -v $(pwd):/project:Z simdjson sh -c "cd dockerbuild && ctest . --output-on-failure -E checkperf"
|
||||
#
|
||||
# The run the complete tests requires you to have built all of simdjson.
|
||||
#
|
||||
# Building all of simdjson takes a long time. Instead, you can build just one target:
|
||||
#
|
||||
# docker run -it -v $(pwd):/project:Z simdjson sh -c "[ -d dockerbuild ] || mkdir dockerbuild && cd dockerbuild && cmake .. && cmake --build . --target parse"
|
||||
#
|
||||
# Note that it is safe to remove dockerbuild before call the previous command, as the repository gets rebuild. It is also possible, by changing the command, to use a different directory name.
|
||||
#
|
||||
# You can run performance tests:
|
||||
#
|
||||
# docker run -it --privileged -v $(pwd):/project:Z simdjson sh -c "cd dockerbuild && for i in ../jsonexamples/*.json; do echo \$i; ./benchmark/parse \$i; done"
|
||||
#
|
||||
# The "--privileged" is recommended so you can get performance counters under Linux.
|
||||
#
|
||||
# You can also grab a fresh copy of simdjson and rebuild it, to make comparisons:
|
||||
#
|
||||
# docker run -it -v $(pwd):/project:Z simdjson sh -c "git clone https://github.com/simdjson/simdjson.git && cd simdjson && mkdir build && cd build && cmake .. && cmake --build . --target parse "
|
||||
#
|
||||
# Then you can run comparisons:
|
||||
#
|
||||
# docker run -it --privileged -v $(pwd):/project:Z simdjson sh -c "for i in jsonexamples/*.json; do echo \$i; dockerbuild/benchmark/parse \$i| grep GB| head -n 1; simdjson/build/benchmark/parse \$i | grep GB |head -n 1; done"
|
||||
#
|
||||
####
|
||||
FROM ubuntu:20.10
|
||||
################
|
||||
# We would prefer to use the conan io images but they do not support 64-bit ARM? The small gcc images appear to
|
||||
# be broken on ARM.
|
||||
# Furthermore, we would not expect users to frequently rebuild the container, so using ubuntu is probably fine.
|
||||
###############
|
||||
ARG USER_ID
|
||||
ARG GROUP_ID
|
||||
RUN apt-get update -qq
|
||||
RUN DEBIAN_FRONTEND="noninteractive" apt-get -y install tzdata
|
||||
RUN apt-get install -y cmake g++ git
|
||||
RUN mkdir project
|
||||
|
||||
RUN addgroup --gid $GROUP_ID user; exit 0
|
||||
RUN adduser --disabled-password --gecos '' --uid $USER_ID --gid $GROUP_ID user; exit 0
|
||||
USER user
|
||||
RUN gcc --version
|
||||
WORKDIR /project
|
||||
|
||||
CMD ["sh","-c","[ -d dockerbuild ] || mkdir dockerbuild && cd dockerbuild && cmake .. && cmake --build . "]
|
||||
|
||||
@@ -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 =
|
||||
PROJECT_NUMBER = "0.4.7"
|
||||
|
||||
# Using the PROJECT_BRIEF tag one can provide an optional one line description
|
||||
# for a project that appears at the top of each page and should give viewer a
|
||||
@@ -51,7 +51,7 @@ PROJECT_BRIEF = "Ridiculously Fast JSON"
|
||||
# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy
|
||||
# the logo to the output directory.
|
||||
|
||||
PROJECT_LOGO =
|
||||
PROJECT_LOGO = images/logotiny.png
|
||||
|
||||
# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
|
||||
# into which the generated documentation will be written. If a relative path is
|
||||
@@ -829,7 +829,7 @@ WARN_LOGFILE =
|
||||
# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING
|
||||
# Note: If this tag is empty the current directory is searched.
|
||||
|
||||
INPUT = include
|
||||
INPUT = doc include
|
||||
|
||||
# This tag can be used to specify the character encoding of the source files
|
||||
# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
|
||||
@@ -1026,7 +1026,7 @@ FILTER_SOURCE_PATTERNS =
|
||||
# (index.html). This can be useful if you have a project on for instance GitHub
|
||||
# and want to reuse the introduction page also for the doxygen output.
|
||||
|
||||
USE_MDFILE_AS_MAINPAGE =
|
||||
USE_MDFILE_AS_MAINPAGE = doc/basics_doxygen.md
|
||||
|
||||
#---------------------------------------------------------------------------
|
||||
# Configuration options related to source browsing
|
||||
|
||||
+334
-83
@@ -4,13 +4,14 @@ Hacking simdjson
|
||||
Here is wisdom about how to build, test and run simdjson from within the repository. *Users* of
|
||||
simdjson should use the released simdjson.h and simdjson.cpp files.
|
||||
|
||||
If you plan to contribute to simdjson, please read our [CONTRIBUTING](https://github.com/simdjson/simdjson/blob/master/CONTRIBUTING.md) guide.
|
||||
|
||||
Directory Structure and Source
|
||||
------------------------------
|
||||
|
||||
simdjson's source structure, from the top level, looks like this:
|
||||
|
||||
* **Makefile:** The main Makefile for Linux. This is not the same as CMakeLists.txt.
|
||||
* **CMakeLists.txt:** A Makefile generator for non-default cases and options.
|
||||
* **CMakeLists.txt:** The main build system.
|
||||
* **include:** User-facing declarations and inline definitions (most user-facing functions are inlined).
|
||||
* simdjson.h: A "master include" that includes files from include/simdjson/. This is equivalent to
|
||||
the distributed simdjson.h.
|
||||
@@ -20,14 +21,16 @@ simdjson's source structure, from the top level, looks like this:
|
||||
implementations).
|
||||
* simdjson.cpp: A "master source" that includes all implementation files from src/. This is
|
||||
equivalent to the distributed simdjson.cpp.
|
||||
* arm64/|fallback/|haswell/|westmere/: Architecture-specific implementations. All functions are
|
||||
* arm64/|fallback/|haswell/|westmere/: Architecture-specific implementations. All functions are
|
||||
Each architecture defines its own namespace, e.g. simdjson::haswell.
|
||||
* generic/: Generic implementations of the simdjson parser. These files may be included and
|
||||
compiled multiple times, from whichever architectures use them. They assume they are already
|
||||
enclosed in a namespace, e.g.:
|
||||
```c++
|
||||
namespace simdjson::haswell {
|
||||
#include "generic/stage1_find_marks.h"
|
||||
namespace simdjson {
|
||||
namespace haswell {
|
||||
#include "generic/stage1/json_structural_indexer.h"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -35,13 +38,27 @@ Other important files and directories:
|
||||
* **.drone.yml:** Definitions for Drone CI.
|
||||
* **.appveyor.yml:** Definitions for Appveyor CI (Windows).
|
||||
* **.circleci:** Definitions for Circle CI.
|
||||
* **amalgamation.sh:** Generates singleheader/simdjson.h and singleheader/simdjson.cpp for release.
|
||||
* **amalgamate.sh:** Generates singleheader/simdjson.h and singleheader/simdjson.cpp for release.
|
||||
* **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. If you're not sure what else to do to check your performance, this is always a good start:
|
||||
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, unnnecessary system calls. We recommend checking the performance as follows:
|
||||
```bash
|
||||
make parse && ./parse jsonexamples/twitter.json
|
||||
mkdir build
|
||||
cd build
|
||||
cmake ..
|
||||
cmake --build . --config Release
|
||||
benchmark/parse ../jsonexamples/twitter.json
|
||||
```
|
||||
The last line becomes `./benchmark/Release/parse.exe ../jsonexample/twitter.json` under Windows. You may also use Google Benchmark:
|
||||
```bash
|
||||
mkdir build
|
||||
cd build
|
||||
cmake ..
|
||||
cmake --build . --target bench_parse_call --config Release
|
||||
./benchmark/bench_parse_call
|
||||
```
|
||||
The last line becomes `./benchmark/Release/bench_parse_call.exe` under Windows. Under Windows, you can also build with the clang compiler by adding `-T ClangCL` to the call to `cmake ..`: `cmake .. - TClangCL`.
|
||||
* **fuzz:** The source for fuzz testing. This lets us explore important edge and middle cases
|
||||
* **fuzz:** The source for fuzz testing. This lets us explore important edge and middle cases
|
||||
automatically, and is run in CI.
|
||||
* **jsonchecker:** A set of JSON files used to check different functionality of the parser.
|
||||
@@ -52,15 +69,61 @@ Other important files and directories:
|
||||
* **singleheader:** Contains generated simdjson.h and simdjson.cpp that we release.
|
||||
* **test:** The tests are here. basictests.cpp and errortests.cpp are the primary ones.
|
||||
* **tools:** Source for executables that can be distributed with simdjson
|
||||
|
||||
> **Don't modify the files in singleheader/ directly; these are automatically generated.**
|
||||
>
|
||||
>
|
||||
> While we distribute those files on release, we *maintain* the files under include/ and src/.
|
||||
|
||||
While simdjson distributes just two files from the singleheader/ directory, we *maintain* the code in
|
||||
multiple files under include/ and src/. include/simdjson.h and src/simdjson.cpp are the "spine" for
|
||||
these, and you can include
|
||||
|
||||
|
||||
|
||||
Runtime Dispatching
|
||||
--------------------
|
||||
|
||||
A key feature of simdjson is the ability to compile different processing kernels, optimized for specific instruction sets, and to select
|
||||
the most appropriate kernel at runtime. This ensures that users get the very best performance while still enabling simdjson to run everywhere.
|
||||
This technique is frequently called runtime dispatching. The simdjson achieves runtime dispatching entirely in C++: we do not assume
|
||||
that the user is building the code using CMake, for example.
|
||||
|
||||
To make runtime dispatching work, it is critical that the code be compiled for the lowest supported processor. In particular, you should
|
||||
not use flags such as -mavx2, /arch:AVX2 and so forth while compiling simdjson. When you do so, you allow the compiler to use advanced
|
||||
instructions. In turn, these advanced instructions present in the code may cause a runtime failure if the runtime processor does not
|
||||
support them. Even a simple loop, compiled with these flags, might generate binary code that only run on advanced processors.
|
||||
|
||||
So we compile simdjson for a generic processor. Our users should do the same if they want simdjson's runtime dispatch to work. It is important
|
||||
to understand that if runtime dispatching does not work, then simdjson will cause crashes on older processors. Of course, if a user chooses
|
||||
to compile their code for a specific instruction set (e.g., AVX2), they are responsible for the failures if they later run their code
|
||||
on a processor that does not support AVX2. Yet, if we were to entice these users to do so, we would share the blame: thus we carefully instruct
|
||||
users to compile their code in a generic way without doing anything to enable advanced instructions.
|
||||
|
||||
|
||||
We only use runtime dispatching on x64 (AMD/Intel) platforms, at the moment. On ARM processors, we would need a standard way to query, at runtime,
|
||||
the processor for its supported features. We do not know how to do so on ARM systems in general. Thankfully it is not yet a concern: 64-bit ARM
|
||||
processors are fairly uniform as far as the instruction sets they support.
|
||||
|
||||
|
||||
In all cases, simdjson uses advanced instructions by relying on "intrinsic functions": we do not write assembly code. The intrinsic functions
|
||||
are special functions that the compiler might recognize and translate into fast code. To make runtime dispatching work, we rely on the fact that
|
||||
the header providing these instructions
|
||||
(intrin.h under Visual Studio, x86intrin.h elsewhere) defines all of the intrinsic functions, including those that are not supported
|
||||
processor.
|
||||
|
||||
At this point, we are require to use one of two main strategies.
|
||||
|
||||
1. On POSIX systems, the main compilers (LLVM clang, GNU gcc) allow us to use any intrinsic function after including the header, but they fail to inline the resulting instruction if the target processor does not support them. Because we compile for a generic processor, we would not be able to use most intrinsic functions. Thankfully, more recent versions of these compilers allow us to flag a region of code with a specific target, so that we can compile only some of the code with support for advanced instructions. Thus in our C++, one might notice macros like `TARGET_HASWELL`. It is then our responsability, at runtime, to only run the regions of code (that we call kernels) matching the properties of the runtime processor. The benefit of this approach is that the compiler not only let us use intrinsic functions, but it can also optimize the rest of the code in the kernel with advanced instructions we enabled.
|
||||
|
||||
2. Under Visual Studio, the problem is somewhat simpler. Visual Studio will not only provide the intrinsic functions, but it will also allow us to use them. They will compile just fine. It is at runtime that they may cause a crash. So we do not need to mark regions of code for compilation toward advanced processors (e.g., with `TARGET_HASWELL` macros). The downside of the Visual Studio approach is that the compiler is not allowed to use advanced instructions others than those we specify. In principle, this means that Visual Studio has weaker optimization opportunities.
|
||||
|
||||
|
||||
|
||||
We also handle the special case where a user is compiling using LLVM clang under Windows, [using the Visual Studio toolchain](https://devblogs.microsoft.com/cppblog/clang-llvm-support-in-visual-studio/). If you compile with LLVM clang under Visual Studio, then the header files (intrin.h or x86intrin.h) no longer provides the intrinsic functions that are unsupported by the processor. This appears to be deliberate on the part of the LLVM engineers. With a few lines of code, we handle this scenario just like LLVM clang under a POSIX system, but forcing the inclusion of the specific headers, and rolling our own intrinsic function as needed.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Regenerating Single Headers From Master
|
||||
---------------------------------------
|
||||
|
||||
@@ -68,58 +131,40 @@ simdjson.h and simdjson.cpp are not always up to date in master. To ensure you h
|
||||
you can regenerate them by running this at the top level:
|
||||
|
||||
```bash
|
||||
make amalgamate
|
||||
mkdir build
|
||||
cd build
|
||||
cmake ..
|
||||
cmake --build . --target amalgamate
|
||||
```
|
||||
|
||||
The amalgamator is at `amalgamation.sh` at the top level. It generates singleheader/simdjson.h by
|
||||
The amalgamator is at `amalgamate.sh` at the top level. It generates singleheader/simdjson.h by
|
||||
reading through include/simdjson.h, copy/pasting each header file into the amalgamated file at the
|
||||
point it gets included (but only once per header). singleheader/simdjson.cpp is generated from
|
||||
src/simdjson.cpp the same way, except files under generic/ may be included and copy/pasted multiple
|
||||
times.
|
||||
|
||||
### Usage (old-school Makefile on platforms like Linux or macOS)
|
||||
### Usage (CMake on 64-bit platforms like Linux, freeBSD or macOS)
|
||||
|
||||
Requirements: recent clang or gcc, and make. We recommend at least GNU GCC/G++ 7 or LLVM clang 6. A 64-bit system like Linux or macOS is expected.
|
||||
|
||||
To test:
|
||||
|
||||
```
|
||||
make
|
||||
make test
|
||||
```
|
||||
|
||||
To run benchmarks:
|
||||
|
||||
```
|
||||
make parse
|
||||
./parse jsonexamples/twitter.json
|
||||
```
|
||||
|
||||
Under Linux, the `parse` command gives a detailed analysis of the performance counters.
|
||||
|
||||
To run comparative benchmarks (with other parsers):
|
||||
|
||||
```
|
||||
make benchmark
|
||||
```
|
||||
|
||||
### Usage (CMake on 64-bit platforms like Linux or macOS)
|
||||
|
||||
Requirements: We require a recent version of cmake. On macOS, the easiest way to install cmake might be to use [brew](https://brew.sh) and then type
|
||||
Requirements: In addition to git, we require a recent version of CMake as well as bash.
|
||||
|
||||
1. On macOS, the easiest way to install cmake might be to use [brew](https://brew.sh) and then type
|
||||
```
|
||||
brew install cmake
|
||||
```
|
||||
|
||||
There is an [equivalent brew on Linux which works the same way as well](https://linuxbrew.sh).
|
||||
|
||||
You need a recent compiler like clang or gcc. We recommend at least GNU GCC/G++ 7 or LLVM clang 6. For example, you can install a recent compiler with brew:
|
||||
|
||||
2. Under Linux, you might be able to install CMake as follows:
|
||||
```
|
||||
brew install gcc@8
|
||||
apt-get update -qq
|
||||
apt-get install -y cmake
|
||||
```
|
||||
3. On freeBSD, you might be able to install bash and CMake as follows:
|
||||
```
|
||||
pkg update -f
|
||||
pkg install bash
|
||||
pkg install cmake
|
||||
```
|
||||
|
||||
Optional: You need to tell cmake which compiler you wish to use by setting the CC and CXX variables. Under bash, you can do so with commands such as `export CC=gcc-7` and `export CXX=g++-7`.
|
||||
You need a recent compiler like clang or gcc. We recommend at least GNU GCC/G++ 7 or LLVM clang 6.
|
||||
|
||||
|
||||
Building: While in the project repository, do the following:
|
||||
|
||||
@@ -127,8 +172,8 @@ Building: While in the project repository, do the following:
|
||||
mkdir build
|
||||
cd build
|
||||
cmake ..
|
||||
make
|
||||
make test
|
||||
cmake --build .
|
||||
ctest
|
||||
```
|
||||
|
||||
CMake will build a library. By default, it builds a shared library (e.g., libsimdjson.so on Linux).
|
||||
@@ -139,11 +184,11 @@ You can build a static library:
|
||||
mkdir buildstatic
|
||||
cd buildstatic
|
||||
cmake -DSIMDJSON_BUILD_STATIC=ON ..
|
||||
make
|
||||
make test
|
||||
cmake --build .
|
||||
ctest
|
||||
```
|
||||
|
||||
In some cases, you may want to specify your compiler, especially if the default compiler on your system is too old. You may proceed as follows:
|
||||
In some cases, you may want to specify your compiler, especially if the default compiler on your system is too old. You need to tell cmake which compiler you wish to use by setting the CC and CXX variables. Under bash, you can do so with commands such as `export CC=gcc-7` and `export CXX=g++-7`. You can also do it as part of the `cmake` command: `cmake .. -DCMAKE_CXX_COMPILER=g++`. You may proceed as follows:
|
||||
|
||||
```
|
||||
brew install gcc@8
|
||||
@@ -151,21 +196,45 @@ mkdir build
|
||||
cd build
|
||||
export CXX=g++-8 CC=gcc-8
|
||||
cmake ..
|
||||
make
|
||||
make test
|
||||
cmake --build .
|
||||
ctest
|
||||
```
|
||||
|
||||
If your compiler does not default on C++11 support or better you may get failing tests. If so, you may be able to exclude the failing tests by replacing `ctest` with `ctest -E "^quickstart$"`.
|
||||
|
||||
Note that the name of directory (`build`) is arbitrary, you can name it as you want (e.g., `buildgcc`) and you can have as many different such directories as you would like (one per configuration).
|
||||
|
||||
|
||||
|
||||
### Usage (CMake on 64-bit Windows using Visual Studio)
|
||||
|
||||
We assume you have a common 64-bit Windows PC with at least Visual Studio 2017 and an x64 processor with AVX2 support (2013 Intel Haswell or later) or SSE 4.2 + CLMUL (2010 Westmere or later).
|
||||
|
||||
- Grab the simdjson code from GitHub, e.g., by cloning it using [GitHub Desktop](https://desktop.github.com/).
|
||||
- Install [CMake](https://cmake.org/download/). When you install it, make sure to ask that `cmake` be made available from the command line. Please choose a recent version of cmake.
|
||||
- Create a subdirectory within simdjson, such as `VisualStudio`.
|
||||
- Using a shell, go to this newly created directory.
|
||||
- Type `cmake -DCMAKE_GENERATOR_PLATFORM=x64 ..` in the shell while in the `VisualStudio` repository. (Alternatively, if you want to build a DLL, you may use the command line `cmake -DCMAKE_GENERATOR_PLATFORM=x64 -DSIMDJSON_BUILD_STATIC=OFF ..`.)
|
||||
- Create a subdirectory within simdjson, such as `build`.
|
||||
- Using a shell, go to this newly created directory. You can start a shell directly from GitHub Desktop (Repository > Open in Command Prompt).
|
||||
- Type `cmake -DCMAKE_GENERATOR_PLATFORM=x64 ..` in the shell while in the `build` repository. (Alternatively, if you want to build a DLL, you may use the command line `cmake -DCMAKE_GENERATOR_PLATFORM=x64 -DSIMDJSON_BUILD_STATIC=OFF ..`.)
|
||||
- This last command (`cmake ...`) created a Visual Studio solution file in the newly created directory (e.g., `simdjson.sln`). Open this file in Visual Studio. You should now be able to build the project and run the tests. For example, in the `Solution Explorer` window (available from the `View` menu), right-click `ALL_BUILD` and select `Build`. To test the code, still in the `Solution Explorer` window, select `RUN_TESTS` and select `Build`.
|
||||
|
||||
|
||||
Though having Visual Studio installed is necessary, one can build simdjson using only cmake commands:
|
||||
|
||||
- `mkdir build`
|
||||
- `cd build`
|
||||
- `cmake ..`
|
||||
- `cmake --build . -config Release`
|
||||
|
||||
|
||||
Furthermore, if you have installed LLVM clang on Windows, for example as a component of Visual Studio 2019, you can configure and build simdjson using LLVM clang on Windows using cmake:
|
||||
|
||||
|
||||
- `mkdir build`
|
||||
- `cd build`
|
||||
- `cmake .. -T ClangCL`
|
||||
- `cmake --build . -config Release`
|
||||
|
||||
|
||||
### Usage (Using `vcpkg` on 64-bit Windows, Linux and macOS)
|
||||
|
||||
[vcpkg](https://github.com/Microsoft/vcpkg) users on Windows, Linux and macOS can download and install `simdjson` with one single command from their favorite shell.
|
||||
@@ -187,7 +256,7 @@ On Windows (64-bit):
|
||||
will build and install `simdjson` as a shared library.
|
||||
|
||||
```
|
||||
.\vcpkg.exe install simdjson:x64-windows-static
|
||||
.\vcpkg.exe install simdjson:x64-windows-static
|
||||
```
|
||||
|
||||
will build and install `simdjson` as a static library.
|
||||
@@ -300,6 +369,213 @@ This helps as we redefine some new characters as pseudo-structural such as the c
|
||||
|
||||
> { "foo" : 1.5, "bar" : 1.5 GEOFF_IS_A_DUMMY bla bla , "baz", null }
|
||||
|
||||
|
||||
|
||||
### UTF-8 validation (lookup2)
|
||||
|
||||
The simdjson library relies on the lookup2 algorithm for UTF-8 validation on x64 platforms.
|
||||
|
||||
This algorithm validate the length of multibyte characters (that each multibyte character has the right number of continuation characters, and that all continuation characters are part of a multibyte character).
|
||||
|
||||
#### Algorithm
|
||||
|
||||
This algorithm compares *expected* continuation characters with *actual* continuation bytes, and emits an error anytime there is a mismatch.
|
||||
|
||||
For example, in the string "𝄞₿֏ab", which has a 4-, 3-, 2- and 1-byte
|
||||
characters, the file will look like this:
|
||||
|
||||
| Character | 𝄞 | | | | ₿ | | | ֏ | | a | b |
|
||||
|-----------------------|----|----|----|----|----|----|----|----|----|----|----|
|
||||
| Character Length | 4 | | | | 3 | | | 2 | | 1 | 1 |
|
||||
| Byte | F0 | 9D | 84 | 9E | E2 | 82 | BF | D6 | 8F | 61 | 62 |
|
||||
| is_second_byte | | X | | | | X | | | X | | |
|
||||
| is_third_byte | | | X | | | | X | | | | |
|
||||
| is_fourth_byte | | | | X | | | | | | | |
|
||||
| expected_continuation | | X | X | X | | X | X | | X | | |
|
||||
| is_continuation | | X | X | X | | X | X | | X | | |
|
||||
|
||||
The errors here are basically (Second Byte OR Third Byte OR Fourth Byte == Continuation):
|
||||
|
||||
- **Extra Continuations:** Any continuation that is not a second, third or fourth byte is not
|
||||
part of a valid 2-, 3- or 4-byte character and is thus an error. It could be that it's just
|
||||
floating around extra outside of any character, or that there is an illegal 5-byte character,
|
||||
or maybe it's at the beginning of the file before any characters have started; but it's an
|
||||
error in all these cases.
|
||||
- **Missing Continuations:** Any second, third or fourth byte that *isn't* a continuation is an error, because that means
|
||||
we started a new character before we were finished with the current one.
|
||||
|
||||
#### Getting the Previous Bytes
|
||||
|
||||
Because we want to know if a byte is the *second* (or third, or fourth) byte of a multibyte
|
||||
character, we need to "shift the bytes" to find that out. This is what they mean:
|
||||
|
||||
- `is_continuation`: if the current byte is a continuation.
|
||||
- `is_second_byte`: if 1 byte back is the start of a 2-, 3- or 4-byte character.
|
||||
- `is_third_byte`: if 2 bytes back is the start of a 3- or 4-byte character.
|
||||
- `is_fourth_byte`: if 3 bytes back is the start of a 4-byte character.
|
||||
|
||||
We use shuffles to go n bytes back, selecting part of the current `input` and part of the
|
||||
`prev_input` (search for `.prev<1>`, `.prev<2>`, etc.). These are passed in by the caller
|
||||
function, because the 1-byte-back data is used by other checks as well.
|
||||
|
||||
#### Getting the Continuation Mask
|
||||
|
||||
Once we have the right bytes, we have to get the masks. To do this, we treat UTF-8 bytes as
|
||||
numbers, using signed `<` and `>` operations to check if they are continuations or leads.
|
||||
In fact, we treat the numbers as *signed*, partly because it helps us, and partly because
|
||||
Intel's SIMD presently only offers signed `<` and `>` operations (not unsigned ones).
|
||||
|
||||
In UTF-8, bytes that start with the bits 110, 1110 and 11110 are 2-, 3- and 4-byte "leads,"
|
||||
respectively, meaning they expect to have 1, 2 and 3 "continuation bytes" after them.
|
||||
Continuation bytes start with 10, and ASCII (1-byte characters) starts with 0.
|
||||
|
||||
When treated as signed numbers, they look like this:
|
||||
|
||||
| Type | High Bits | Binary Range | Signed |
|
||||
|--------------|------------|--------------|--------|
|
||||
| ASCII | `0` | `01111111` | 127 |
|
||||
| | | `00000000` | 0 |
|
||||
| 4+-Byte Lead | `1111` | `11111111` | -1 |
|
||||
| | | `11110000 | -16 |
|
||||
| 3-Byte Lead | `1110` | `11101111` | -17 |
|
||||
| | | `11100000 | -32 |
|
||||
| 2-Byte Lead | `110` | `11011111` | -33 |
|
||||
| | | `11000000 | -64 |
|
||||
| Continuation | `10` | `10111111` | -65 |
|
||||
| | | `10000000 | -128 |
|
||||
|
||||
This makes it pretty easy to get the continuation mask! It's just a single comparison:
|
||||
|
||||
```
|
||||
is_continuation = input < -64`
|
||||
```
|
||||
|
||||
We can do something similar for the others, but it takes two comparisons instead of one: "is
|
||||
the start of a 4-byte character" is `< -32` and `> -65`, for example. And 2+ bytes is `< 0` and
|
||||
`> -64`. Surely we can do better, they're right next to each other!
|
||||
|
||||
#### Getting the is_xxx Masks: Shifting the Range
|
||||
|
||||
Notice *why* continuations were a single comparison. The actual *range* would require two
|
||||
comparisons--`< -64` and `> -129`--but all characters are always greater than -128, so we get
|
||||
that for free. In fact, if we had *unsigned* comparisons, 2+, 3+ and 4+ comparisons would be
|
||||
just as easy: 4+ would be `> 239`, 3+ would be `> 223`, and 2+ would be `> 191`.
|
||||
|
||||
Instead, we add 128 to each byte, shifting the range up to make comparison easy. This wraps
|
||||
ASCII down into the negative, and puts 4+-Byte Lead at the top:
|
||||
|
||||
| Type | High Bits | Binary Range | Signed |
|
||||
|----------------------|------------|--------------|-------|
|
||||
| 4+-Byte Lead (+ 127) | `0111` | `01111111` | 127 |
|
||||
| | | `01110000 | 112 |
|
||||
|----------------------|------------|--------------|-------|
|
||||
| 3-Byte Lead (+ 127) | `0110` | `01101111` | 111 |
|
||||
| | | `01100000 | 96 |
|
||||
|----------------------|------------|--------------|-------|
|
||||
| 2-Byte Lead (+ 127) | `010` | `01011111` | 95 |
|
||||
| | | `01000000 | 64 |
|
||||
|----------------------|------------|--------------|-------|
|
||||
| Continuation (+ 127) | `00` | `00111111` | 63 |
|
||||
| | | `00000000 | 0 |
|
||||
|----------------------|------------|--------------|-------|
|
||||
| ASCII (+ 127) | `1` | `11111111` | -1 |
|
||||
| | | `10000000` | -128 |
|
||||
|----------------------|------------|--------------|-------|
|
||||
|
||||
*Now* we can use signed `>` on all of them:
|
||||
|
||||
```
|
||||
prev1 = input.prev<1>
|
||||
prev2 = input.prev<2>
|
||||
prev3 = input.prev<3>
|
||||
prev1_flipped = input.prev<1>(prev_input) ^ 0x80; // Same as `+ 128`
|
||||
prev2_flipped = input.prev<2>(prev_input) ^ 0x80; // Same as `+ 128`
|
||||
prev3_flipped = input.prev<3>(prev_input) ^ 0x80; // Same as `+ 128`
|
||||
is_second_byte = prev1_flipped > 63;2+-byte lead
|
||||
is_third_byte = prev2_flipped > 95;3+-byte lead
|
||||
is_fourth_byte = prev3_flipped > 111; // 4+-byte lead
|
||||
```
|
||||
|
||||
NOTE: we use `^ 0x80` instead of `+ 128` in the code, which accomplishes the same thing, and even takes the same number
|
||||
of cycles as `+`, but on many Intel architectures can be parallelized better (you can do 3
|
||||
`^`'s at a time on Haswell, but only 2 `+`'s).
|
||||
|
||||
That doesn't look like it saved us any instructions, did it? Well, because we're adding the
|
||||
same number to all of them, we can save one of those `+ 128` operations by assembling
|
||||
`prev2_flipped` out of prev 1 and prev 3 instead of assembling it from input and adding 128
|
||||
to it. One more instruction saved!
|
||||
|
||||
```
|
||||
prev1 = input.prev<1>
|
||||
prev3 = input.prev<3>
|
||||
prev1_flipped = prev1 ^ 0x80; // Same as `+ 128`
|
||||
prev3_flipped = prev3 ^ 0x80; // Same as `+ 128`
|
||||
prev2_flipped = prev1_flipped.concat<2>(prev3_flipped): // <shuffle: take the first 2 bytes from prev1 and the rest from prev3
|
||||
```
|
||||
|
||||
#### Bringing It All Together: Detecting the Errors
|
||||
|
||||
At this point, we have `is_continuation`, `is_first_byte`, `is_second_byte` and `is_third_byte`.
|
||||
All we have left to do is check if they match!
|
||||
|
||||
```
|
||||
return (is_second_byte | is_third_byte | is_fourth_byte) ^ is_continuation;
|
||||
```
|
||||
|
||||
But wait--there's more. The above statement is only 3 operations, but they *cannot be done in
|
||||
parallel*. You have to do 2 `|`'s and then 1 `&`. Haswell, at least, has 3 ports that can do
|
||||
bitwise operations, and we're only using 1!
|
||||
|
||||
#### Epilogue: Addition For Booleans
|
||||
|
||||
There is one big case the above code doesn't explicitly talk about--what if is_second_byte
|
||||
and is_third_byte are BOTH true? That means there is a 3-byte and 2-byte character right next
|
||||
to each other (or any combination), and the continuation could be part of either of them!
|
||||
Our algorithm using `&` and `|` won't detect that the continuation byte is problematic.
|
||||
|
||||
Never fear, though. If that situation occurs, we'll already have detected that the second
|
||||
leading byte was an error, because it was supposed to be a part of the preceding multibyte
|
||||
character, but it *wasn't a continuation*.
|
||||
|
||||
We could stop here, but it turns out that we can fix it using `+` and `-` instead of `|` and
|
||||
`&`, which is both interesting and possibly useful (even though we're not using it here). It
|
||||
exploits the fact that in SIMD, a *true* value is -1, and a *false* value is 0. So those
|
||||
comparisons were giving us numbers!
|
||||
|
||||
Given that, if you do `is_second_byte + is_third_byte + is_fourth_byte`, under normal
|
||||
circumstances you will either get 0 (0 + 0 + 0) or -1 (-1 + 0 + 0, etc.). Thus,
|
||||
`(is_second_byte + is_third_byte + is_fourth_byte) - is_continuation` will yield 0 only if
|
||||
*both* or *neither* are 0 (0-0 or -1 - -1). You'll get 1 or -1 if they are different. Because
|
||||
*any* nonzero value is treated as an error (not just -1), we're just fine here :)
|
||||
|
||||
Further, if *more than one* multibyte character overlaps,
|
||||
`is_second_byte + is_third_byte + is_fourth_byte` will be -2 or -3! Subtracting `is_continuation`
|
||||
from *that* is guaranteed to give you a nonzero value (-1, -2 or -3). So it'll always be
|
||||
considered an error.
|
||||
|
||||
One reason you might want to do this is parallelism. ^ and | are not associative, so
|
||||
(A | B | C) ^ D will always be three operations in a row: either you do A | B -> | C -> ^ D, or
|
||||
you do B | C -> | A -> ^ D. But addition and subtraction *are* associative: (A + B + C) - D can
|
||||
be written as `(A + B) + (C - D)`. This means you can do A + B and C - D at the same time, and
|
||||
then adds the result together. Same number of operations, but if the processor can run
|
||||
independent things in parallel (which most can), it runs faster.
|
||||
|
||||
This doesn't help us on Intel, but might help us elsewhere: on Haswell, at least, | and ^ have
|
||||
a super nice advantage in that more of them can be run at the same time (they can run on 3
|
||||
ports, while + and - can run on 2)! This means that we can do A | B while we're still doing C,
|
||||
saving us the cycle we would have earned by using +. Even more, using an instruction with a
|
||||
wider array of ports can help *other* code run ahead, too, since these instructions can "get
|
||||
out of the way," running on a port other instructions can't.
|
||||
|
||||
#### Epilogue II: One More Trick
|
||||
|
||||
There's one more relevant trick up our sleeve, it turns out: it turns out on Intel we can "pay
|
||||
for" the (prev<1> + 128) instruction, because it can be used to save an instruction in
|
||||
check_special_cases()--but we'll talk about that there :)
|
||||
|
||||
|
||||
|
||||
|
||||
## About the Project
|
||||
|
||||
### Bindings and Ports of simdjson
|
||||
@@ -325,31 +601,6 @@ We distinguish between "bindings" (which just wrap the C++ code) and a port to a
|
||||
- `minify mydoc.json` minifies the JSON document, outputting the result to standard output. Minifying means to remove the unneeded white space characters.
|
||||
- `jsonpointer mydoc.json <jsonpath> <jsonpath> ... <jsonpath>` parses the document, constructs a model and then processes a series of [JSON Pointer paths](https://tools.ietf.org/html/rfc6901). The result is itself a JSON document.
|
||||
|
||||
### In-depth comparisons
|
||||
|
||||
If you want to see how a wide range of parsers validate a given JSON file:
|
||||
|
||||
```
|
||||
make allparserscheckfile
|
||||
./allparserscheckfile myfile.json
|
||||
```
|
||||
|
||||
For performance comparisons:
|
||||
|
||||
```
|
||||
make parsingcompetition
|
||||
./parsingcompetition myfile.json
|
||||
```
|
||||
|
||||
For broader comparisons:
|
||||
|
||||
```
|
||||
make allparsingcompetition
|
||||
./allparsingcompetition myfile.json
|
||||
```
|
||||
|
||||
Both the `parsingcompetition` and `allparsingcompetition` tools take a `-t` flag which produces
|
||||
a table-oriented output that can be conveniently parsed by other tools.
|
||||
|
||||
### Various References
|
||||
|
||||
|
||||
@@ -1,301 +0,0 @@
|
||||
REFERENCE_VERSION = master
|
||||
|
||||
.SUFFIXES:
|
||||
#
|
||||
.SUFFIXES: .cpp .o .c .h
|
||||
|
||||
|
||||
.PHONY: clean cleandist
|
||||
COREDEPSINCLUDE = -Idependencies/json/single_include -Idependencies/rapidjson/include -Idependencies/sajson/include -Idependencies/cJSON -Idependencies/jsmn
|
||||
EXTRADEPSINCLUDE = -Idependencies/jsoncppdist -Idependencies/json11 -Idependencies/fastjson/src -Idependencies/fastjson/include -Idependencies/gason/src -Idependencies/ujson4c/3rdparty -Idependencies/ujson4c/src
|
||||
# users can provide their own additional flags with make EXTRAFLAGS=something
|
||||
architecture:=$(shell arch)
|
||||
|
||||
####
|
||||
# If you want to specify your own target architecture,
|
||||
# then define ARCHFLAGS. Otherwise, we set good default.
|
||||
# E.g., type ' ARCHFLAGS="-march=westmere" make parse '
|
||||
###
|
||||
|
||||
CXXFLAGS = $(ARCHFLAGS) -std=c++17 -pthread -Wall -Wextra -Wshadow -Ibenchmark/linux
|
||||
CFLAGS = $(ARCHFLAGS) -Idependencies/ujson4c/3rdparty -Idependencies/ujson4c/src $(EXTRAFLAGS)
|
||||
|
||||
# This is a convenience flag
|
||||
ifdef SANITIZEGOLD
|
||||
SANITIZE = 1
|
||||
LINKER = gold
|
||||
endif
|
||||
|
||||
ifdef LINKER
|
||||
CXXFLAGS += -fuse-ld=$(LINKER)
|
||||
CFLAGS += -fuse-ld=$(LINKER)
|
||||
endif
|
||||
|
||||
|
||||
# SANITIZE *implies* DEBUG
|
||||
ifeq ($(MEMSANITIZE),1)
|
||||
CXXFLAGS += -g3 -O0 -fsanitize=memory -fno-omit-frame-pointer -fsanitize=undefined
|
||||
CFLAGS += -g3 -O0 -fsanitize=memory -fno-omit-frame-pointer -fsanitize=undefined
|
||||
else
|
||||
ifeq ($(SANITIZE),1)
|
||||
CXXFLAGS += -g3 -O0 -fsanitize=address -fno-omit-frame-pointer -fsanitize=undefined
|
||||
CFLAGS += -g3 -O0 -fsanitize=address -fno-omit-frame-pointer -fsanitize=undefined
|
||||
else
|
||||
ifeq ($(DEBUG),1)
|
||||
CXXFLAGS += -g3 -O0
|
||||
CFLAGS += -g3 -O0
|
||||
else
|
||||
# we opt for -O3 for regular builds
|
||||
CXXFLAGS += -O3
|
||||
CFLAGS += -O3
|
||||
endif # ifeq ($(DEBUG),1)
|
||||
endif # ifeq ($(SANITIZE),1)
|
||||
endif # ifeq ($(MEMSANITIZE),1)
|
||||
|
||||
# Headers and sources
|
||||
SRCHEADERS_GENERIC=src/generic/atomparsing.h src/generic/numberparsing.h src/generic/json_scanner.h src/generic/json_string_scanner.h src/generic/json_structural_indexer.h src/generic/json_minifier.h src/generic/buf_block_reader.h src/generic/stage2_build_tape.h src/generic/stringparsing.h src/generic/stage2_streaming_build_tape.h src/generic/utf8_fastvalidate_algorithm.h src/generic/utf8_lookup_algorithm.h src/generic/utf8_lookup2_algorithm.h src/generic/utf8_range_algorithm.h src/generic/utf8_zwegner_algorithm.h
|
||||
SRCHEADERS_ARM64= src/arm64/bitmanipulation.h src/arm64/bitmask.h src/arm64/intrinsics.h src/arm64/numberparsing.h src/arm64/simd.h src/arm64/stage1_find_marks.h src/arm64/stage2_build_tape.h src/arm64/stringparsing.h
|
||||
SRCHEADERS_HASWELL= src/haswell/bitmanipulation.h src/haswell/bitmask.h src/haswell/intrinsics.h src/haswell/numberparsing.h src/haswell/simd.h src/haswell/stage1_find_marks.h src/haswell/stage2_build_tape.h src/haswell/stringparsing.h
|
||||
SRCHEADERS_FALLBACK= src/fallback/bitmanipulation.h src/fallback/implementation.h src/fallback/numberparsing.h src/fallback/stage1_find_marks.h src/fallback/stage2_build_tape.h src/fallback/stringparsing.h
|
||||
SRCHEADERS_WESTMERE=src/westmere/bitmanipulation.h src/westmere/bitmask.h src/westmere/intrinsics.h src/westmere/numberparsing.h src/westmere/simd.h src/westmere/stage1_find_marks.h src/westmere/stage2_build_tape.h src/westmere/stringparsing.h
|
||||
SRCHEADERS_SRC=src/isadetection.h src/jsoncharutils.h src/simdprune_tables.h src/implementation.cpp src/stage1_find_marks.cpp src/stage2_build_tape.cpp src/document_parser_callbacks.h
|
||||
SRCHEADERS=$(SRCHEADERS_SRC) $(SRCHEADERS_GENERIC) $(SRCHEADERS_ARM64) $(SRCHEADERS_HASWELL) $(SRCHEADERS_WESTMERE) $(SRCHEADERS_FALLBACK)
|
||||
|
||||
INCLUDEHEADERS=include/simdjson.h include/simdjson/common_defs.h include/simdjson/internal/jsonformatutils.h include/simdjson/jsonioutil.h include/simdjson/jsonparser.h include/simdjson/padded_string.h include/simdjson/inline/padded_string.h include/simdjson/document.h include/simdjson/inline/document.h include/simdjson/parsedjson_iterator.h include/simdjson/inline/parsedjson_iterator.h include/simdjson/document_stream.h include/simdjson/inline/document_stream.h include/simdjson/implementation.h include/simdjson/parsedjson.h include/simdjson/portability.h include/simdjson/error.h include/simdjson/inline/error.h include/simdjson/simdjson.h include/simdjson/simdjson_version.h
|
||||
|
||||
ifeq ($(SIMDJSON_TEST_AMALGAMATED_HEADERS),1)
|
||||
HEADERS=singleheader/simdjson.h
|
||||
LIBFILES=singleheader/simdjson.cpp
|
||||
CXXFLAGS += -Isingleheader
|
||||
else
|
||||
HEADERS=$(INCLUDEHEADERS) $(SRCHEADERS)
|
||||
LIBFILES=src/simdjson.cpp
|
||||
CXXFLAGS += -Isrc -Iinclude
|
||||
endif
|
||||
|
||||
# We put EXTRAFLAGS after all other CXXFLAGS so they can override if necessary
|
||||
CXXFLAGS += $(EXTRAFLAGS)
|
||||
|
||||
FEATURE_JSON_FILES=jsonexamples/generated/0-structurals-full.json jsonexamples/generated/0-structurals-miss.json jsonexamples/generated/0-structurals.json jsonexamples/generated/15-structurals-full.json jsonexamples/generated/15-structurals-miss.json jsonexamples/generated/15-structurals.json jsonexamples/generated/23-structurals-full.json jsonexamples/generated/23-structurals-miss.json jsonexamples/generated/23-structurals.json jsonexamples/generated/7-structurals-full.json jsonexamples/generated/7-structurals-miss.json jsonexamples/generated/7-structurals.json jsonexamples/generated/escape-full.json jsonexamples/generated/escape-miss.json jsonexamples/generated/escape.json jsonexamples/generated/utf-8-full.json jsonexamples/generated/utf-8-miss.json jsonexamples/generated/utf-8.json
|
||||
|
||||
RAPIDJSON_INCLUDE:=dependencies/rapidjson/include
|
||||
SAJSON_INCLUDE:=dependencies/sajson/include
|
||||
JSON11_INCLUDE:=dependencies/json11/json11.hpp
|
||||
FASTJSON_INCLUDE:=dependencies/include/fastjson/fastjson.h
|
||||
GASON_INCLUDE:=dependencies/gason/src/gason.h
|
||||
UJSON4C_INCLUDE:=dependencies/ujson4c/src/ujdecode.c
|
||||
CJSON_INCLUDE:=dependencies/cJSON/cJSON.h
|
||||
JSMN_INCLUDE:=dependencies/jsmn/jsmn.h
|
||||
JSON_INCLUDE:=dependencies/json/single_include/nlohmann/json.hpp
|
||||
|
||||
EXTRAOBJECTS=ujdecode.o
|
||||
|
||||
MAINEXECUTABLES=parse minify json2json jsonstats statisticalmodel jsonpointer get_corpus_benchmark
|
||||
TESTEXECUTABLES=jsoncheck jsoncheck_westmere jsoncheck_fallback integer_tests numberparsingcheck stringparsingcheck pointercheck parse_many_test basictests errortests readme_examples readme_examples_noexceptions
|
||||
COMPARISONEXECUTABLES=minifiercompetition parsingcompetition parseandstatcompetition distinctuseridcompetition allparserscheckfile allparsingcompetition
|
||||
SUPPLEMENTARYEXECUTABLES=parse_noutf8validation parse_nonumberparsing parse_nostringparsing
|
||||
|
||||
all: $(MAINEXECUTABLES)
|
||||
|
||||
competition: $(COMPARISONEXECUTABLES)
|
||||
|
||||
.PHONY: benchmark test
|
||||
|
||||
benchmark:
|
||||
bash ./scripts/parser.sh
|
||||
bash ./scripts/parseandstat.sh
|
||||
|
||||
run_basictests: basictests
|
||||
./basictests
|
||||
|
||||
run_errortests: errortests
|
||||
./errortests
|
||||
|
||||
run_numberparsingcheck: numberparsingcheck
|
||||
./numberparsingcheck
|
||||
|
||||
run_integer_tests: integer_tests
|
||||
./integer_tests
|
||||
|
||||
run_stringparsingcheck: stringparsingcheck
|
||||
./stringparsingcheck
|
||||
|
||||
run_jsoncheck: jsoncheck
|
||||
./jsoncheck
|
||||
|
||||
run_parse_many_test: parse_many_test
|
||||
./parse_many_test
|
||||
|
||||
run_jsoncheck_westmere: jsoncheck_westmere
|
||||
./jsoncheck_westmere
|
||||
|
||||
run_jsoncheck_fallback: jsoncheck_fallback
|
||||
./jsoncheck_fallback
|
||||
|
||||
run_pointercheck: pointercheck
|
||||
./pointercheck
|
||||
|
||||
run_issue150_sh: allparserscheckfile
|
||||
./scripts/issue150.sh
|
||||
|
||||
quickstart:
|
||||
cd examples/quickstart && make quickstart
|
||||
|
||||
run_quickstart:
|
||||
cd examples/quickstart && make test
|
||||
|
||||
run_testjson2json_sh: minify json2json
|
||||
./scripts/testjson2json.sh
|
||||
|
||||
$(FEATURE_JSON_FILES): benchmark/genfeaturejson.rb
|
||||
ruby ./benchmark/genfeaturejson.rb
|
||||
|
||||
run_benchfeatures: benchfeatures $(FEATURE_JSON_FILES)
|
||||
./benchfeatures -n 1000
|
||||
|
||||
test: quicktests slowtests
|
||||
@echo "It looks like the code is good!"
|
||||
|
||||
quiettest: quicktests slowtests
|
||||
|
||||
quicktests: run_basictests run_quickstart readme_examples readme_examples_noexceptions run_jsoncheck run_numberparsingcheck run_integer_tests run_stringparsingcheck run_jsoncheck run_parse_many_test run_pointercheck run_jsoncheck_westmere run_jsoncheck_fallback
|
||||
|
||||
slowtests: run_testjson2json_sh run_issue150_sh
|
||||
|
||||
amalgamate:
|
||||
./amalgamation.sh
|
||||
|
||||
singleheader/simdjson.h singleheader/simdjson.cpp singleheader/amalgamation_demo.cpp: amalgamation.sh src/simdjson.cpp $(SRCHEADERS) $(INCLUDEHEADERS)
|
||||
./amalgamation.sh
|
||||
|
||||
singleheader/demo: singleheader/simdjson.h singleheader/simdjson.cpp singleheader/amalgamation_demo.cpp
|
||||
$(CXX) $(CXXFLAGS) -o singleheader/demo singleheader/amalgamation_demo.cpp -Isingleheader
|
||||
|
||||
submodules:
|
||||
-git submodule update --init --recursive
|
||||
-touch submodules
|
||||
|
||||
$(JSON_INCLUDE) $(SAJSON_INCLUDE) $(RAPIDJSON_INCLUDE) $(JSON11_INCLUDE) $(FASTJSON_INCLUDE) $(GASON_INCLUDE) $(UJSON4C_INCLUDE) $(CJSON_INCLUDE) $(JSMN_INCLUDE) : submodules
|
||||
|
||||
parse: benchmark/parse.cpp benchmark/event_counter.h benchmark/benchmarker.h $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o parse benchmark/parse.cpp $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
get_corpus_benchmark: benchmark/get_corpus_benchmark.cpp $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o get_corpus_benchmark benchmark/get_corpus_benchmark.cpp $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
parse_stream: benchmark/parse_stream.cpp benchmark/event_counter.h benchmark/benchmarker.h $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o parse_stream benchmark/parse_stream.cpp $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
benchfeatures: benchmark/benchfeatures.cpp benchmark/event_counter.h benchmark/benchmarker.h $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o benchfeatures benchmark/benchfeatures.cpp $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
perfdiff: benchmark/perfdiff.cpp
|
||||
$(CXX) $(CXXFLAGS) -o perfdiff benchmark/perfdiff.cpp $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
checkperf:
|
||||
bash ./scripts/checkperf.sh $(REFERENCE_VERSION)
|
||||
|
||||
statisticalmodel: benchmark/statisticalmodel.cpp $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o statisticalmodel benchmark/statisticalmodel.cpp $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
|
||||
parse_noutf8validation: benchmark/parse.cpp $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o parse_noutf8validation -DSIMDJSON_SKIPUTF8VALIDATION benchmark/parse.cpp $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
parse_nonumberparsing: benchmark/parse.cpp $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o parse_nonumberparsing -DSIMDJSON_SKIPNUMBERPARSING benchmark/parse.cpp $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
parse_nostringparsing: benchmark/parse.cpp $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o parse_nostringparsing -DSIMDJSON_SKIPSTRINGPARSING benchmark/parse.cpp $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
|
||||
jsoncheck:tests/jsoncheck.cpp $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o jsoncheck tests/jsoncheck.cpp -I. $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
parse_many_test:tests/parse_many_test.cpp $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o parse_many_test tests/parse_many_test.cpp -I. $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
|
||||
jsoncheck_westmere:tests/jsoncheck.cpp $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o jsoncheck_westmere tests/jsoncheck.cpp -I. $(LIBFILES) $(LIBFLAGS) -DSIMDJSON_IMPLEMENTATION_HASWELL=0
|
||||
|
||||
jsoncheck_fallback:tests/jsoncheck.cpp $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o jsoncheck_fallback tests/jsoncheck.cpp -I. $(LIBFILES) $(LIBFLAGS) -DSIMDJSON_IMPLEMENTATION_HASWELL=0 -DSIMDJSON_IMPLEMENTATION_WESTMERE=0 -DSIMDJSON_IMPLEMENTATION_ARM64=0
|
||||
|
||||
basictests:tests/basictests.cpp $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o basictests tests/basictests.cpp -I. $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
errortests:tests/errortests.cpp $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o errortests tests/errortests.cpp -I. $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
readme_examples: tests/readme_examples.cpp $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o readme_examples tests/readme_examples.cpp -I. $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
readme_examples_noexceptions: tests/readme_examples_noexceptions.cpp $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o readme_examples_noexceptions tests/readme_examples_noexceptions.cpp -I. $(LIBFILES) $(LIBFLAGS) -fno-exceptions
|
||||
|
||||
numberparsingcheck: tests/numberparsingcheck.cpp $(HEADERS) src/simdjson.cpp
|
||||
$(CXX) $(CXXFLAGS) -o numberparsingcheck tests/numberparsingcheck.cpp -I. $(LIBFLAGS) -DJSON_TEST_NUMBERS
|
||||
|
||||
integer_tests:tests/integer_tests.cpp $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o integer_tests tests/integer_tests.cpp -I. $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
|
||||
|
||||
stringparsingcheck: tests/stringparsingcheck.cpp $(HEADERS) src/simdjson.cpp
|
||||
$(CXX) $(CXXFLAGS) -o stringparsingcheck tests/stringparsingcheck.cpp -I. $(LIBFLAGS) -DJSON_TEST_STRINGS
|
||||
|
||||
pointercheck:tests/pointercheck.cpp $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o pointercheck tests/pointercheck.cpp -I. $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
minifiercompetition: benchmark/minifiercompetition.cpp submodules $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o minifiercompetition benchmark/minifiercompetition.cpp -I. $(LIBFILES) $(LIBFLAGS) $(COREDEPSINCLUDE)
|
||||
|
||||
minify: tools/minify.cpp $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o minify tools/minify.cpp -I. $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
json2json: tools/json2json.cpp $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o json2json $ tools/json2json.cpp -I. $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
jsonpointer: tools/jsonpointer.cpp $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o jsonpointer $ tools/jsonpointer.cpp -I. $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
jsonstats: tools/jsonstats.cpp $(HEADERS) $(LIBFILES)
|
||||
$(CXX) $(CXXFLAGS) -o jsonstats $ tools/jsonstats.cpp -I. $(LIBFILES) $(LIBFLAGS)
|
||||
|
||||
ujdecode.o: $(UJSON4C_INCLUDE)
|
||||
$(CC) $(CFLAGS) -c dependencies/ujson4c/src/ujdecode.c
|
||||
|
||||
parseandstatcompetition: benchmark/parseandstatcompetition.cpp $(HEADERS) $(LIBFILES) submodules
|
||||
$(CXX) $(CXXFLAGS) -o parseandstatcompetition benchmark/parseandstatcompetition.cpp -I. $(LIBFILES) $(LIBFLAGS) $(COREDEPSINCLUDE)
|
||||
|
||||
distinctuseridcompetition: benchmark/distinctuseridcompetition.cpp $(HEADERS) $(LIBFILES) submodules
|
||||
$(CXX) $(CXXFLAGS) -o distinctuseridcompetition benchmark/distinctuseridcompetition.cpp -I. $(LIBFILES) $(LIBFLAGS) $(COREDEPSINCLUDE)
|
||||
|
||||
parsingcompetition: benchmark/parsingcompetition.cpp $(HEADERS) $(LIBFILES) submodules
|
||||
@echo "In case of build error due to missing files, try 'make clean'"
|
||||
$(CXX) $(CXXFLAGS) -o parsingcompetition benchmark/parsingcompetition.cpp -I. $(LIBFILES) $(LIBFLAGS) $(COREDEPSINCLUDE)
|
||||
|
||||
allparsingcompetition: benchmark/parsingcompetition.cpp $(HEADERS) $(LIBFILES) $(EXTRAOBJECTS) submodules
|
||||
$(CXX) $(CXXFLAGS) -o allparsingcompetition benchmark/parsingcompetition.cpp $(EXTRAOBJECTS) -I. $(LIBFILES) $(LIBFLAGS) $(COREDEPSINCLUDE) $(EXTRADEPSINCLUDE) -DALLPARSER
|
||||
|
||||
|
||||
allparserscheckfile: tests/allparserscheckfile.cpp $(HEADERS) $(LIBFILES) $(EXTRAOBJECTS) submodules
|
||||
$(CXX) $(CXXFLAGS) -o allparserscheckfile tests/allparserscheckfile.cpp $(EXTRAOBJECTS) -I. $(LIBFILES) $(LIBFLAGS) $(COREDEPSINCLUDE) $(EXTRADEPSINCLUDE)
|
||||
|
||||
.PHONY: clean cppcheck cleandist
|
||||
|
||||
cppcheck:
|
||||
cppcheck --enable=all src/*.cpp benchmarks/*.cpp tests/*.cpp -Iinclude -I. -Ibenchmark/linux
|
||||
|
||||
everything: $(MAINEXECUTABLES) $(EXTRA_EXECUTABLES) $(TESTEXECUTABLES) $(COMPARISONEXECUTABLES) $(SUPPLEMENTARYEXECUTABLES) quickstart
|
||||
|
||||
clean:
|
||||
rm -f submodules $(EXTRAOBJECTS) $(MAINEXECUTABLES) $(EXTRA_EXECUTABLES) $(TESTEXECUTABLES) $(COMPARISONEXECUTABLES) $(SUPPLEMENTARYEXECUTABLES)
|
||||
cd examples/quickstart && make clean
|
||||
|
||||
cleandist:
|
||||
rm -f submodules $(EXTRAOBJECTS) $(MAINEXECUTABLES) $(EXTRA_EXECUTABLES) $(TESTEXECUTABLES) $(COMPARISONEXECUTABLES) $(SUPPLEMENTARYEXECUTABLES)
|
||||
|
||||
doc/api: Doxyfile $(HEADERS)
|
||||
doxygen
|
||||
@@ -1,8 +1,10 @@
|
||||
[](https://cloud.drone.io/simdjson/simdjson)
|
||||
[](https://circleci.com/gh/simdjson/simdjson)
|
||||
[](https://cloud.drone.io/simdjson/simdjson)
|
||||
[](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&q=proj%3Asimdjson&can=2)
|
||||
[](https://ci.appveyor.com/project/lemire/simdjson-jmmti/branch/master)
|
||||
[![][license img]][license]
|
||||
[](https://circleci.com/gh/simdjson/simdjson)
|
||||
[](https://cirrus-ci.com/github/simdjson/simdjson)
|
||||

|
||||
[![][license img]][license] [](https://simdjson.org/api/0.4.0/index.html)
|
||||
|
||||
simdjson : Parsing gigabytes of JSON per second
|
||||
===============================================
|
||||
@@ -39,7 +41,7 @@ Quick Start
|
||||
|
||||
The simdjson library is easily consumable with a single .h and .cpp file.
|
||||
|
||||
0. Prerequisites: `g++` (version 7 or better) or `clang++` (version 6 or better), and a 64-bit system.
|
||||
0. Prerequisites: `g++` (version 7 or better) or `clang++` (version 6 or better), and a 64-bit system with a command-line shell (e.g., Linux, macOS, freeBSD). We also support programming environnements like Visual Studio and Xcode, but different steps are needed.
|
||||
1. Pull [simdjson.h](singleheader/simdjson.h) and [simdjson.cpp](singleheader/simdjson.cpp) into a directory, along with the sample file [twitter.json](jsonexamples/twitter.json).
|
||||
```
|
||||
wget https://raw.githubusercontent.com/simdjson/simdjson/master/singleheader/simdjson.h https://raw.githubusercontent.com/simdjson/simdjson/master/singleheader/simdjson.cpp https://raw.githubusercontent.com/simdjson/simdjson/master/jsonexamples/twitter.json
|
||||
@@ -54,7 +56,7 @@ The simdjson library is easily consumable with a single .h and .cpp file.
|
||||
std::cout << tweets["search_metadata"]["count"] << " results." << std::endl;
|
||||
}
|
||||
```
|
||||
3. `c++ -o quickstart quickstart.cpp simdjson.cpp -std=c++17`
|
||||
3. `c++ -o quickstart quickstart.cpp simdjson.cpp`
|
||||
4. `./quickstart`
|
||||
```
|
||||
100 results.
|
||||
@@ -69,20 +71,19 @@ Usage documentation is available:
|
||||
* [Performance](doc/performance.md) shows some more advanced scenarios and how to tune for them.
|
||||
* [Implementation Selection](doc/implementation-selection.md) describes runtime CPU detection and
|
||||
how you can work with it.
|
||||
* [API](https://simdjson.org/api/0.3.0/annotated.html) contains the automatically generated API documentation.
|
||||
* [API](https://simdjson.org/api/0.3.1/annotated.html) contains the automatically generated API documentation.
|
||||
|
||||
Performance results
|
||||
-------------------
|
||||
|
||||
The simdjson library uses three-quarters less instructions than state-of-the-art parser RapidJSON and
|
||||
The simdjson library uses three-quarters less instructions than state-of-the-art parser [RapidJSON](https://rapidjson.org) and
|
||||
fifty percent less than sajson. To our knowledge, simdjson is the first fully-validating JSON parser
|
||||
to run at gigabytes per second on commodity processors. It can parse millions of JSON documents
|
||||
per second on a single core.
|
||||
to run at [gigabytes per second](https://en.wikipedia.org/wiki/Gigabyte) (GB/s) on commodity processors. It can parse millions of JSON documents per second on a single core.
|
||||
|
||||
The following figure represents parsing speed in GB/s for parsing various files
|
||||
on an Intel Skylake processor (3.4 GHz) using the GNU GCC 9 compiler (with the -O3 flag).
|
||||
We compare against the best and fastest C++ libraries.
|
||||
The simdjson library offers full unicode (UTF-8) validation and exact
|
||||
The simdjson library offers full unicode ([UTF-8](https://en.wikipedia.org/wiki/UTF-8)) validation and exact
|
||||
number parsing. The RapidJSON library is tested in two modes: fast and
|
||||
exact number parsing. The sajson library offers fast (but not exact)
|
||||
number parsing and partial unicode validation. In this data set, the file
|
||||
@@ -167,7 +168,8 @@ For the video inclined, <br />
|
||||
Funding
|
||||
-------
|
||||
|
||||
The work is supported by the Natural Sciences and Engineering Research Council of Canada under grant number RGPIN-2017-03910.
|
||||
The work is supported by the Natural Sciences and Engineering Research Council of Canada under grant
|
||||
number RGPIN-2017-03910.
|
||||
|
||||
[license]: LICENSE
|
||||
[license img]: https://img.shields.io/badge/License-Apache%202-blue.svg
|
||||
@@ -181,6 +183,8 @@ Head over to [CONTRIBUTING.md](CONTRIBUTING.md) for information on contributing
|
||||
License
|
||||
-------
|
||||
|
||||
This code is made available under the Apache License 2.0.
|
||||
This code is made available under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0.html).
|
||||
|
||||
Under Windows, we build some tools using the windows/dirent_portable.h file (which is outside our library code): it under the liberal (business-friendly) MIT license.
|
||||
|
||||
For compilers that do not support [C++17](https://en.wikipedia.org/wiki/C%2B%2B17), we bundle the string-view library which is published under the Boost license (http://www.boost.org/LICENSE_1_0.txt). Like the Apache license, the Boost license is a permissive license allowing commercial redistribution.
|
||||
|
||||
+17
@@ -2,6 +2,23 @@
|
||||
|
||||
## Highlights
|
||||
|
||||
- Test coverage has been greatly improved and we have resolved many static-analysis warnings on different systems.
|
||||
- We added a fast (8GB/s) minifier that works directly on JSON strings.
|
||||
- We added fast (10GB/s) UTF-8 validator that works directly on strings (any strings, including non-JSON).
|
||||
- The array and object elements have a constant-time size() method.
|
||||
- Performance improvements to the API (type(), get<>()).
|
||||
- The parse_many function (ndjson) has been entirely reworked. It now uses a single secondary thread instead of several new threads.
|
||||
- We have introduced a faster UTF-8 validation algorithm (lookup3) for all kernels (ARM, x64 SSE, x64 AVX).
|
||||
- C++11 support for older compilers and systems.
|
||||
- FreeBSD support (and tests).
|
||||
- We support the clang front-end compiler (clangcl) under Visual Studio.
|
||||
- It is now possible to target ARM platforms under Visual Studio.
|
||||
- The simdjson library will never abort or print to standard output/error.
|
||||
|
||||
# 0.3
|
||||
|
||||
## Highlights
|
||||
|
||||
- **Multi-Document Parsing:** Read a bundle of JSON documents (ndjson) 2-4x faster than doing it
|
||||
individually. [API docs](https://github.com/simdjson/simdjson/blob/master/doc/basics.md#newline-delimited-json-ndjson-and-json-lines) / [Design Details](https://github.com/simdjson/simdjson/blob/master/doc/parse_many.md)
|
||||
- **Simplified API:** The API has been completely revamped for ease of use, including a new JSON
|
||||
|
||||
+34
-18
@@ -1,21 +1,37 @@
|
||||
target_include_directories(${SIMDJSON_LIB_NAME}
|
||||
INTERFACE
|
||||
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/benchmark>
|
||||
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/benchmark/linux>
|
||||
)
|
||||
|
||||
add_cpp_benchmark(parse)
|
||||
add_cpp_benchmark(statisticalmodel)
|
||||
add_cpp_benchmark(parse_stream)
|
||||
add_cpp_benchmark(get_corpus_benchmark)
|
||||
include_directories( . linux )
|
||||
link_libraries(simdjson simdjson-flags simdjson-windows-headers test-data)
|
||||
add_executable(benchfeatures benchfeatures.cpp)
|
||||
add_executable(get_corpus_benchmark get_corpus_benchmark.cpp)
|
||||
add_executable(perfdiff perfdiff.cpp)
|
||||
add_executable(parse parse.cpp)
|
||||
add_executable(parse_stream parse_stream.cpp)
|
||||
add_executable(statisticalmodel statisticalmodel.cpp)
|
||||
|
||||
# Google Benchmarks
|
||||
if (SIMDJSON_GOOGLE_BENCHMARKS)
|
||||
add_cpp_benchmark(bench_parse_call)
|
||||
target_link_libraries(bench_parse_call benchmark::benchmark)
|
||||
add_executable(parse_noutf8validation parse.cpp)
|
||||
target_compile_definitions(parse_noutf8validation PRIVATE SIMDJSON_SKIPUTF8VALIDATION)
|
||||
add_executable(parse_nonumberparsing parse.cpp)
|
||||
target_compile_definitions(parse_nonumberparsing PRIVATE SIMDJSON_SKIPNUMBERPARSING)
|
||||
add_executable(parse_nostringparsing parse.cpp)
|
||||
target_compile_definitions(parse_nostringparsing PRIVATE SIMDJSON_SKIPSTRINGPARSING)
|
||||
|
||||
add_cpp_benchmark(bench_dom_api)
|
||||
target_link_libraries(bench_dom_api benchmark::benchmark)
|
||||
target_compile_definitions(bench_dom_api PRIVATE JSON_TEST_PATH="${PROJECT_SOURCE_DIR}/jsonexamples/twitter.json")
|
||||
endif()
|
||||
if (TARGET benchmark::benchmark)
|
||||
link_libraries(benchmark::benchmark)
|
||||
add_executable(bench_parse_call bench_parse_call.cpp)
|
||||
add_executable(bench_dom_api bench_dom_api.cpp)
|
||||
endif()
|
||||
|
||||
if (TARGET competition-all)
|
||||
add_executable(distinctuseridcompetition distinctuseridcompetition.cpp)
|
||||
target_link_libraries(distinctuseridcompetition competition-core)
|
||||
add_executable(minifiercompetition minifiercompetition.cpp)
|
||||
target_link_libraries(minifiercompetition competition-core)
|
||||
add_executable(parseandstatcompetition parseandstatcompetition.cpp)
|
||||
target_link_libraries(parseandstatcompetition competition-core)
|
||||
add_executable(parsingcompetition parsingcompetition.cpp)
|
||||
target_link_libraries(parsingcompetition competition-core)
|
||||
add_executable(allparsingcompetition parsingcompetition.cpp)
|
||||
target_link_libraries(allparsingcompetition competition-all)
|
||||
target_compile_definitions(allparsingcompetition PRIVATE ALLPARSER)
|
||||
endif()
|
||||
|
||||
include(checkperf.cmake)
|
||||
|
||||
+341
-57
@@ -6,19 +6,286 @@ using namespace simdjson;
|
||||
using namespace benchmark;
|
||||
using namespace std;
|
||||
|
||||
#ifndef JSON_TEST_PATH
|
||||
#define JSON_TEST_PATH "jsonexamples/twitter.json"
|
||||
#endif
|
||||
|
||||
const padded_string EMPTY_ARRAY("[]", 2);
|
||||
|
||||
const char *TWITTER_JSON = SIMDJSON_BENCHMARK_DATA_DIR "twitter.json";
|
||||
const char *NUMBERS_JSON = SIMDJSON_BENCHMARK_DATA_DIR "numbers.json";
|
||||
|
||||
|
||||
|
||||
static void numbers_scan(State& state) {
|
||||
// Prints the number of results in twitter.json
|
||||
dom::parser parser;
|
||||
dom::array arr;
|
||||
simdjson::error_code error;
|
||||
if ((error = parser.load(NUMBERS_JSON).get(arr))) {
|
||||
cerr << "could not read " << NUMBERS_JSON << " as an array: " << error << endl;
|
||||
return;
|
||||
}
|
||||
for (UNUSED auto _ : state) {
|
||||
std::vector<double> container;
|
||||
for (auto e : arr) {
|
||||
double x;
|
||||
if ((error = e.get(x))) { cerr << "found a node that is not an number: " << error << endl; break;}
|
||||
container.push_back(x);
|
||||
}
|
||||
benchmark::DoNotOptimize(container.data());
|
||||
benchmark::ClobberMemory();
|
||||
}
|
||||
}
|
||||
BENCHMARK(numbers_scan);
|
||||
|
||||
static void numbers_size_scan(State& state) {
|
||||
// Prints the number of results in twitter.json
|
||||
dom::parser parser;
|
||||
dom::array arr;
|
||||
simdjson::error_code error;
|
||||
if ((error = parser.load(NUMBERS_JSON).get(arr))) {
|
||||
cerr << "could not read " << NUMBERS_JSON << " as an array: " << error << endl;
|
||||
return;
|
||||
}
|
||||
for (UNUSED auto _ : state) {
|
||||
std::vector<double> container;
|
||||
container.resize(arr.size());
|
||||
size_t pos = 0;
|
||||
for (auto e : arr) {
|
||||
double x;
|
||||
if ((error = e.get(x))) { cerr << "found a node that is not an number: " << error << endl; break;}
|
||||
container[pos++] = x;
|
||||
}
|
||||
if(pos != container.size()) { cerr << "bad count" << endl; }
|
||||
benchmark::DoNotOptimize(container.data());
|
||||
benchmark::ClobberMemory();
|
||||
}
|
||||
}
|
||||
BENCHMARK(numbers_size_scan);
|
||||
|
||||
|
||||
static void numbers_type_scan(State& state) {
|
||||
// Prints the number of results in twitter.json
|
||||
dom::parser parser;
|
||||
dom::array arr;
|
||||
simdjson::error_code error;
|
||||
if ((error = parser.load(NUMBERS_JSON).get(arr))) {
|
||||
cerr << "could not read " << NUMBERS_JSON << " as an array" << endl;
|
||||
return;
|
||||
}
|
||||
for (UNUSED auto _ : state) {
|
||||
std::vector<double> container;
|
||||
for (auto e : arr) {
|
||||
dom::element_type actual_type = e.type();
|
||||
if(actual_type != dom::element_type::DOUBLE) {
|
||||
cerr << "found a node that is not an number?" << endl; break;
|
||||
}
|
||||
double x;
|
||||
error = e.get(x);
|
||||
container.push_back(x);
|
||||
}
|
||||
benchmark::DoNotOptimize(container.data());
|
||||
benchmark::ClobberMemory();
|
||||
}
|
||||
}
|
||||
BENCHMARK(numbers_type_scan);
|
||||
|
||||
static void numbers_type_size_scan(State& state) {
|
||||
// Prints the number of results in twitter.json
|
||||
dom::parser parser;
|
||||
dom::array arr;
|
||||
simdjson::error_code error;
|
||||
if ((error = parser.load(NUMBERS_JSON).get(arr))) {
|
||||
cerr << "could not read " << NUMBERS_JSON << " as an array: " << error << endl;
|
||||
return;
|
||||
}
|
||||
for (UNUSED auto _ : state) {
|
||||
std::vector<double> container;
|
||||
container.resize(arr.size());
|
||||
size_t pos = 0;
|
||||
for (auto e : arr) {
|
||||
dom::element_type actual_type = e.type();
|
||||
if(actual_type != dom::element_type::DOUBLE) {
|
||||
cerr << "found a node that is not an number?" << endl; break;
|
||||
}
|
||||
double x;
|
||||
error = e.get(x);
|
||||
container[pos++] = x;
|
||||
}
|
||||
if(pos != container.size()) { cerr << "bad count" << endl; }
|
||||
benchmark::DoNotOptimize(container.data());
|
||||
benchmark::ClobberMemory();
|
||||
}
|
||||
}
|
||||
BENCHMARK(numbers_type_size_scan);
|
||||
|
||||
static void numbers_load_scan(State& state) {
|
||||
// Prints the number of results in twitter.json
|
||||
dom::parser parser;
|
||||
dom::array arr;
|
||||
simdjson::error_code error;
|
||||
for (UNUSED auto _ : state) {
|
||||
// this may hit the disk, but probably just once
|
||||
if ((error = parser.load(NUMBERS_JSON).get(arr))) {
|
||||
cerr << "could not read " << NUMBERS_JSON << " as an array: " << error << endl;
|
||||
break;
|
||||
}
|
||||
std::vector<double> container;
|
||||
for (auto e : arr) {
|
||||
double x;
|
||||
if ((error = e.get(x))) { cerr << "found a node that is not an number: " << error << endl; break;}
|
||||
container.push_back(x);
|
||||
}
|
||||
benchmark::DoNotOptimize(container.data());
|
||||
benchmark::ClobberMemory();
|
||||
}
|
||||
}
|
||||
BENCHMARK(numbers_load_scan);
|
||||
|
||||
static void numbers_load_size_scan(State& state) {
|
||||
// Prints the number of results in twitter.json
|
||||
dom::parser parser;
|
||||
dom::array arr;
|
||||
simdjson::error_code error;
|
||||
for (UNUSED auto _ : state) {
|
||||
// this may hit the disk, but probably just once
|
||||
if ((error = parser.load(NUMBERS_JSON).get(arr))) {
|
||||
cerr << "could not read " << NUMBERS_JSON << " as an array" << endl;
|
||||
break;
|
||||
}
|
||||
std::vector<double> container;
|
||||
container.resize(arr.size());
|
||||
size_t pos = 0;
|
||||
for (auto e : arr) {
|
||||
double x;
|
||||
if ((error = e.get(x))) { cerr << "found a node that is not an number?" << endl; break;}
|
||||
container[pos++] = x;
|
||||
}
|
||||
if(pos != container.size()) { cerr << "bad count" << endl; }
|
||||
benchmark::DoNotOptimize(container.data());
|
||||
benchmark::ClobberMemory();
|
||||
}
|
||||
}
|
||||
BENCHMARK(numbers_load_size_scan);
|
||||
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
|
||||
|
||||
static void numbers_exceptions_scan(State& state) {
|
||||
// Prints the number of results in twitter.json
|
||||
dom::parser parser;
|
||||
dom::array arr = parser.load(NUMBERS_JSON);
|
||||
for (UNUSED auto _ : state) {
|
||||
std::vector<double> container;
|
||||
for (double x : arr) {
|
||||
container.push_back(x);
|
||||
}
|
||||
benchmark::DoNotOptimize(container.data());
|
||||
benchmark::ClobberMemory();
|
||||
}
|
||||
}
|
||||
BENCHMARK(numbers_exceptions_scan);
|
||||
|
||||
static void numbers_exceptions_size_scan(State& state) {
|
||||
// Prints the number of results in twitter.json
|
||||
dom::parser parser;
|
||||
dom::array arr = parser.load(NUMBERS_JSON);
|
||||
for (UNUSED auto _ : state) {
|
||||
std::vector<double> container;
|
||||
container.resize(arr.size());
|
||||
size_t pos = 0;
|
||||
for (auto e : arr) {
|
||||
container[pos++] = double(e);
|
||||
}
|
||||
if(pos != container.size()) { cerr << "bad count" << endl; }
|
||||
benchmark::DoNotOptimize(container.data());
|
||||
benchmark::ClobberMemory();
|
||||
}
|
||||
}
|
||||
BENCHMARK(numbers_exceptions_size_scan);
|
||||
|
||||
|
||||
|
||||
static void numbers_type_exceptions_scan(State& state) {
|
||||
// Prints the number of results in twitter.json
|
||||
dom::parser parser;
|
||||
dom::array arr = parser.load(NUMBERS_JSON);
|
||||
for (UNUSED auto _ : state) {
|
||||
std::vector<double> container;
|
||||
for (auto e : arr) {
|
||||
dom::element_type actual_type = e.type();
|
||||
if(actual_type != dom::element_type::DOUBLE) {
|
||||
cerr << "found a node that is not an number?" << endl; break;
|
||||
}
|
||||
container.push_back(double(e));
|
||||
}
|
||||
benchmark::DoNotOptimize(container.data());
|
||||
benchmark::ClobberMemory();
|
||||
}
|
||||
}
|
||||
BENCHMARK(numbers_type_exceptions_scan);
|
||||
|
||||
static void numbers_type_exceptions_size_scan(State& state) {
|
||||
// Prints the number of results in twitter.json
|
||||
dom::parser parser;
|
||||
dom::array arr = parser.load(NUMBERS_JSON);
|
||||
for (UNUSED auto _ : state) {
|
||||
std::vector<double> container;
|
||||
container.resize(arr.size());
|
||||
size_t pos = 0;
|
||||
for (auto e : arr) {
|
||||
dom::element_type actual_type = e.type();
|
||||
if(actual_type != dom::element_type::DOUBLE) {
|
||||
cerr << "found a node that is not an number?" << endl; break;
|
||||
}
|
||||
container[pos++] = double(e);
|
||||
}
|
||||
if(pos != container.size()) { cerr << "bad count" << endl; }
|
||||
benchmark::DoNotOptimize(container.data());
|
||||
benchmark::ClobberMemory();
|
||||
}
|
||||
}
|
||||
BENCHMARK(numbers_type_exceptions_size_scan);
|
||||
|
||||
static void numbers_exceptions_load_scan(State& state) {
|
||||
// Prints the number of results in twitter.json
|
||||
dom::parser parser;
|
||||
for (UNUSED auto _ : state) {
|
||||
// this may hit the disk, but probably just once
|
||||
dom::array arr = parser.load(NUMBERS_JSON);
|
||||
std::vector<double> container;
|
||||
for (double x : arr) {
|
||||
container.push_back(x);
|
||||
}
|
||||
benchmark::DoNotOptimize(container.data());
|
||||
benchmark::ClobberMemory();
|
||||
}
|
||||
}
|
||||
BENCHMARK(numbers_exceptions_load_scan);
|
||||
|
||||
static void numbers_exceptions_load_size_scan(State& state) {
|
||||
// Prints the number of results in twitter.json
|
||||
dom::parser parser;
|
||||
for (UNUSED auto _ : state) {
|
||||
// this may hit the disk, but probably just once
|
||||
dom::array arr = parser.load(NUMBERS_JSON);
|
||||
std::vector<double> container;
|
||||
container.resize(arr.size());
|
||||
size_t pos = 0;
|
||||
for (double x : arr) {
|
||||
container[pos++] = x;
|
||||
}
|
||||
if(pos != container.size()) { cerr << "bad count" << endl; }
|
||||
benchmark::DoNotOptimize(container.data());
|
||||
benchmark::ClobberMemory();
|
||||
}
|
||||
}
|
||||
BENCHMARK(numbers_exceptions_load_size_scan);
|
||||
|
||||
|
||||
static void twitter_count(State& state) {
|
||||
// Prints the number of results in twitter.json
|
||||
dom::parser parser;
|
||||
dom::element doc = parser.load(JSON_TEST_PATH);
|
||||
for (auto _ : state) {
|
||||
dom::element doc = parser.load(TWITTER_JSON);
|
||||
for (UNUSED auto _ : state) {
|
||||
uint64_t result_count = doc["search_metadata"]["count"];
|
||||
if (result_count != 100) { return; }
|
||||
}
|
||||
@@ -29,9 +296,9 @@ SIMDJSON_PUSH_DISABLE_WARNINGS
|
||||
SIMDJSON_DISABLE_DEPRECATED_WARNING
|
||||
static void iterator_twitter_count(State& state) {
|
||||
// Prints the number of results in twitter.json
|
||||
padded_string json = padded_string::load(JSON_TEST_PATH);
|
||||
padded_string json = padded_string::load(TWITTER_JSON);
|
||||
ParsedJson pj = build_parsed_json(json);
|
||||
for (auto _ : state) {
|
||||
for (UNUSED auto _ : state) {
|
||||
ParsedJson::Iterator iter(pj);
|
||||
// uint64_t result_count = doc["search_metadata"]["count"];
|
||||
if (!iter.move_to_key("search_metadata")) { return; }
|
||||
@@ -48,10 +315,10 @@ SIMDJSON_POP_DISABLE_WARNINGS
|
||||
static void twitter_default_profile(State& state) {
|
||||
// Count unique users with a default profile.
|
||||
dom::parser parser;
|
||||
dom::element doc = parser.load(JSON_TEST_PATH);
|
||||
for (auto _ : state) {
|
||||
dom::element doc = parser.load(TWITTER_JSON);
|
||||
for (UNUSED auto _ : state) {
|
||||
set<string_view> default_users;
|
||||
for (dom::object tweet : doc["statuses"].get<dom::array>()) {
|
||||
for (dom::object tweet : doc["statuses"]) {
|
||||
dom::object user = tweet["user"];
|
||||
if (user["default_profile"]) {
|
||||
default_users.insert(user["screen_name"]);
|
||||
@@ -65,15 +332,16 @@ BENCHMARK(twitter_default_profile);
|
||||
static void twitter_image_sizes(State& state) {
|
||||
// Count unique image sizes
|
||||
dom::parser parser;
|
||||
dom::element doc = parser.load(JSON_TEST_PATH);
|
||||
for (auto _ : state) {
|
||||
dom::element doc = parser.load(TWITTER_JSON);
|
||||
simdjson::error_code error;
|
||||
for (UNUSED auto _ : state) {
|
||||
set<tuple<uint64_t, uint64_t>> image_sizes;
|
||||
for (dom::object tweet : doc["statuses"].get<dom::array>()) {
|
||||
auto [media, not_found] = tweet["entities"]["media"];
|
||||
if (!not_found) {
|
||||
for (dom::object image : media.get<dom::array>()) {
|
||||
for (auto [key, size] : image["sizes"].get<dom::object>()) {
|
||||
image_sizes.insert({ size["w"], size["h"] });
|
||||
for (dom::object tweet : doc["statuses"]) {
|
||||
dom::array media;
|
||||
if (not (error = tweet["entities"]["media"].get(media))) {
|
||||
for (dom::object image : media) {
|
||||
for (auto size : image["sizes"].get<dom::object>()) {
|
||||
image_sizes.insert({ size.value["w"], size.value["h"] });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -88,10 +356,12 @@ BENCHMARK(twitter_image_sizes);
|
||||
static void error_code_twitter_count(State& state) noexcept {
|
||||
// Prints the number of results in twitter.json
|
||||
dom::parser parser;
|
||||
dom::element doc = parser.load(JSON_TEST_PATH);
|
||||
for (auto _ : state) {
|
||||
auto [value, error] = doc["search_metadata"]["count"].get<uint64_t>();
|
||||
if (error) { return; }
|
||||
simdjson::error_code error;
|
||||
dom::element doc;
|
||||
if ((error = parser.load(TWITTER_JSON).get(doc))) { return; }
|
||||
for (UNUSED auto _ : state) {
|
||||
uint64_t value;
|
||||
if ((error = doc["search_metadata"]["count"].get(value))) { return; }
|
||||
if (value != 100) { return; }
|
||||
}
|
||||
}
|
||||
@@ -100,20 +370,22 @@ BENCHMARK(error_code_twitter_count);
|
||||
static void error_code_twitter_default_profile(State& state) noexcept {
|
||||
// Count unique users with a default profile.
|
||||
dom::parser parser;
|
||||
dom::element doc = parser.load(JSON_TEST_PATH);
|
||||
for (auto _ : state) {
|
||||
simdjson::error_code error;
|
||||
dom::element doc;
|
||||
if ((error = parser.load(TWITTER_JSON).get(doc))) { std::cerr << error << std::endl; return; }
|
||||
for (UNUSED auto _ : state) {
|
||||
set<string_view> default_users;
|
||||
|
||||
auto [tweets, error] = doc["statuses"].get<dom::array>();
|
||||
if (error) { return; }
|
||||
dom::array tweets;
|
||||
if ((error = doc["statuses"].get(tweets))) { return; }
|
||||
for (dom::element tweet : tweets) {
|
||||
auto [user, error2] = tweet["user"].get<dom::object>();
|
||||
if (error2) { return; }
|
||||
auto [default_profile, error3] = user["default_profile"].get<bool>();
|
||||
if (error3) { return; }
|
||||
dom::object user;
|
||||
if ((error = tweet["user"].get(user))) { return; }
|
||||
bool default_profile;
|
||||
if ((error = user["default_profile"].get(default_profile))) { return; }
|
||||
if (default_profile) {
|
||||
auto [screen_name, error4] = user["screen_name"].get<std::string_view>();
|
||||
if (error4) { return; }
|
||||
std::string_view screen_name;
|
||||
if ((error = user["screen_name"].get(screen_name))) { return; }
|
||||
default_users.insert(screen_name);
|
||||
}
|
||||
}
|
||||
@@ -127,13 +399,15 @@ SIMDJSON_PUSH_DISABLE_WARNINGS
|
||||
SIMDJSON_DISABLE_DEPRECATED_WARNING
|
||||
static void iterator_twitter_default_profile(State& state) {
|
||||
// Count unique users with a default profile.
|
||||
padded_string json = padded_string::load(JSON_TEST_PATH);
|
||||
padded_string json;
|
||||
auto error = padded_string::load(TWITTER_JSON).get(json);
|
||||
if (error) { std::cerr << error << std::endl; return; }
|
||||
ParsedJson pj = build_parsed_json(json);
|
||||
for (auto _ : state) {
|
||||
for (UNUSED auto _ : state) {
|
||||
set<string_view> default_users;
|
||||
ParsedJson::Iterator iter(pj);
|
||||
|
||||
// for (dom::object tweet : doc["statuses"].get<dom::array>()) {
|
||||
// for (dom::object tweet : doc["statuses"]) {
|
||||
if (!(iter.move_to_key("statuses") && iter.is_array())) { return; }
|
||||
if (iter.down()) { // first status
|
||||
do {
|
||||
@@ -167,21 +441,23 @@ BENCHMARK(iterator_twitter_default_profile);
|
||||
static void error_code_twitter_image_sizes(State& state) noexcept {
|
||||
// Count unique image sizes
|
||||
dom::parser parser;
|
||||
dom::element doc = parser.load(JSON_TEST_PATH);
|
||||
for (auto _ : state) {
|
||||
simdjson::error_code error;
|
||||
dom::element doc;
|
||||
if ((error = parser.load(TWITTER_JSON).get(doc))) { std::cerr << error << std::endl; return; }
|
||||
for (UNUSED auto _ : state) {
|
||||
set<tuple<uint64_t, uint64_t>> image_sizes;
|
||||
auto [statuses, error] = doc["statuses"].get<dom::array>();
|
||||
if (error) { return; }
|
||||
dom::array statuses;
|
||||
if ((error = doc["statuses"].get(statuses))) { return; }
|
||||
for (dom::element tweet : statuses) {
|
||||
auto [images, not_found] = tweet["entities"]["media"].get<dom::array>();
|
||||
if (!not_found) {
|
||||
dom::array images;
|
||||
if (not (error = tweet["entities"]["media"].get(images))) {
|
||||
for (dom::element image : images) {
|
||||
auto [sizes, error2] = image["sizes"].get<dom::object>();
|
||||
if (error2) { return; }
|
||||
for (auto [key, size] : sizes) {
|
||||
auto [width, error3] = size["w"].get<uint64_t>();
|
||||
auto [height, error4] = size["h"].get<uint64_t>();
|
||||
if (error3 || error4) { return; }
|
||||
dom::object sizes;
|
||||
if ((error = image["sizes"].get(sizes))) { return; }
|
||||
for (auto size : sizes) {
|
||||
uint64_t width, height;
|
||||
if ((error = size.value["w"].get(width))) { return; }
|
||||
if ((error = size.value["h"].get(height))) { return; }
|
||||
image_sizes.insert({ width, height });
|
||||
}
|
||||
}
|
||||
@@ -196,29 +472,32 @@ SIMDJSON_PUSH_DISABLE_WARNINGS
|
||||
SIMDJSON_DISABLE_DEPRECATED_WARNING
|
||||
static void iterator_twitter_image_sizes(State& state) {
|
||||
// Count unique image sizes
|
||||
padded_string json = padded_string::load(JSON_TEST_PATH);
|
||||
padded_string json;
|
||||
auto error = padded_string::load(TWITTER_JSON).get(json);
|
||||
if (error) { std::cerr << error << std::endl; return; }
|
||||
ParsedJson pj = build_parsed_json(json);
|
||||
for (auto _ : state) {
|
||||
for (UNUSED auto _ : state) {
|
||||
set<tuple<uint64_t, uint64_t>> image_sizes;
|
||||
ParsedJson::Iterator iter(pj);
|
||||
|
||||
// for (dom::object tweet : doc["statuses"].get<dom::array>()) {
|
||||
// for (dom::object tweet : doc["statuses"]) {
|
||||
if (!(iter.move_to_key("statuses") && iter.is_array())) { return; }
|
||||
if (iter.down()) { // first status
|
||||
do {
|
||||
|
||||
// auto [media, not_found] = tweet["entities"]["media"];
|
||||
// dom::object media;
|
||||
// not_found = tweet["entities"]["media"].get(media);
|
||||
// if (!not_found) {
|
||||
if (iter.move_to_key("entities")) {
|
||||
if (!iter.is_object()) { return; }
|
||||
if (iter.move_to_key("media")) {
|
||||
if (!iter.is_array()) { return; }
|
||||
|
||||
// for (dom::object image : media.get<dom::array>()) {
|
||||
// for (dom::object image : media) {
|
||||
if (iter.down()) { // first media
|
||||
do {
|
||||
|
||||
// for (auto [key, size] : image["sizes"].get<dom::object>()) {
|
||||
// for (auto [key, size] : dom::object(image["sizes"])) {
|
||||
if (!(iter.move_to_key("sizes") && iter.is_object())) { return; }
|
||||
if (iter.down()) { // first size
|
||||
do {
|
||||
@@ -254,10 +533,15 @@ BENCHMARK(iterator_twitter_image_sizes);
|
||||
|
||||
static void print_json(State& state) noexcept {
|
||||
// Prints the number of results in twitter.json
|
||||
padded_string json = get_corpus(JSON_TEST_PATH);
|
||||
dom::parser parser;
|
||||
if (int error = json_parse(json, parser); error != SUCCESS) { cerr << error_message(error) << endl; return; }
|
||||
for (auto _ : state) {
|
||||
|
||||
padded_string json;
|
||||
auto error = padded_string::load(TWITTER_JSON).get(json);
|
||||
if (error) { std::cerr << error << std::endl; return; }
|
||||
|
||||
int code = json_parse(json, parser);
|
||||
if (code) { cerr << error_message(code) << endl; return; }
|
||||
for (UNUSED auto _ : state) {
|
||||
std::stringstream s;
|
||||
if (!parser.print_json(s)) { cerr << "print_json failed" << endl; return; }
|
||||
}
|
||||
|
||||
@@ -5,13 +5,89 @@ using namespace benchmark;
|
||||
using namespace std;
|
||||
|
||||
const padded_string EMPTY_ARRAY("[]", 2);
|
||||
const char *TWITTER_JSON = SIMDJSON_BENCHMARK_DATA_DIR "twitter.json";
|
||||
const char *GSOC_JSON = SIMDJSON_BENCHMARK_DATA_DIR "gsoc-2018.json";
|
||||
|
||||
|
||||
|
||||
static void parse_twitter(State& state) {
|
||||
dom::parser parser;
|
||||
padded_string docdata;
|
||||
auto error = padded_string::load(TWITTER_JSON).get(docdata);
|
||||
if(error) {
|
||||
cerr << "could not parse twitter.json" << error << endl;
|
||||
return;
|
||||
}
|
||||
// we do not want mem. alloc. in the loop.
|
||||
error = parser.allocate(docdata.size());
|
||||
if(error) {
|
||||
cout << error << endl;
|
||||
return;
|
||||
}
|
||||
size_t bytes = 0;
|
||||
for (UNUSED auto _ : state) {
|
||||
dom::element doc;
|
||||
bytes += docdata.size();
|
||||
;
|
||||
if ((error = parser.parse(docdata).get(doc))) {
|
||||
cerr << "could not parse twitter.json" << error << endl;
|
||||
return;
|
||||
}
|
||||
benchmark::DoNotOptimize(doc);
|
||||
}
|
||||
// Gigabyte: https://en.wikipedia.org/wiki/Gigabyte
|
||||
state.counters["Gigabytes"] = benchmark::Counter(
|
||||
double(bytes), benchmark::Counter::kIsRate,
|
||||
benchmark::Counter::OneK::kIs1000); // For GiB : kIs1024
|
||||
state.counters["docs"] = Counter(double(state.iterations()), benchmark::Counter::kIsRate);
|
||||
}
|
||||
BENCHMARK(parse_twitter)->Repetitions(10)->ComputeStatistics("max", [](const std::vector<double>& v) -> double {
|
||||
return *(std::max_element(std::begin(v), std::end(v)));
|
||||
})->DisplayAggregatesOnly(true);
|
||||
|
||||
|
||||
static void parse_gsoc(State& state) {
|
||||
dom::parser parser;
|
||||
padded_string docdata;
|
||||
auto error = padded_string::load(GSOC_JSON).get(docdata);
|
||||
if(error) {
|
||||
cerr << "could not parse gsoc-2018.json" << error << endl;
|
||||
return;
|
||||
}
|
||||
// we do not want mem. alloc. in the loop.
|
||||
error = parser.allocate(docdata.size());
|
||||
if(error) {
|
||||
cout << error << endl;
|
||||
return;
|
||||
}
|
||||
size_t bytes = 0;
|
||||
for (UNUSED auto _ : state) {
|
||||
bytes += docdata.size();
|
||||
dom::element doc;
|
||||
if ((error = parser.parse(docdata).get(doc))) {
|
||||
cerr << "could not parse gsoc-2018.json" << error << endl;
|
||||
return;
|
||||
}
|
||||
benchmark::DoNotOptimize(doc);
|
||||
}
|
||||
// Gigabyte: https://en.wikipedia.org/wiki/Gigabyte
|
||||
state.counters["Gigabytes"] = benchmark::Counter(
|
||||
double(bytes), benchmark::Counter::kIsRate,
|
||||
benchmark::Counter::OneK::kIs1000); // For GiB : kIs1024
|
||||
state.counters["docs"] = Counter(double(state.iterations()), benchmark::Counter::kIsRate);
|
||||
}
|
||||
BENCHMARK(parse_gsoc)->Repetitions(10)->ComputeStatistics("max", [](const std::vector<double>& v) -> double {
|
||||
return *(std::max_element(std::begin(v), std::end(v)));
|
||||
})->DisplayAggregatesOnly(true);
|
||||
|
||||
|
||||
|
||||
SIMDJSON_PUSH_DISABLE_WARNINGS
|
||||
SIMDJSON_DISABLE_DEPRECATED_WARNING
|
||||
static void json_parse(State& state) {
|
||||
ParsedJson pj;
|
||||
if (!pj.allocate_capacity(EMPTY_ARRAY.length())) { return; }
|
||||
for (auto _ : state) {
|
||||
for (UNUSED auto _ : state) {
|
||||
auto error = json_parse(EMPTY_ARRAY, pj);
|
||||
if (error) { return; }
|
||||
}
|
||||
@@ -21,53 +97,66 @@ BENCHMARK(json_parse);
|
||||
static void parser_parse_error_code(State& state) {
|
||||
dom::parser parser;
|
||||
if (parser.allocate(EMPTY_ARRAY.length())) { return; }
|
||||
for (auto _ : state) {
|
||||
auto [doc, error] = parser.parse(EMPTY_ARRAY);
|
||||
for (UNUSED auto _ : state) {
|
||||
auto error = parser.parse(EMPTY_ARRAY).error();
|
||||
if (error) { return; }
|
||||
}
|
||||
}
|
||||
BENCHMARK(parser_parse_error_code);
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
|
||||
static void parser_parse_exception(State& state) {
|
||||
dom::parser parser;
|
||||
if (parser.allocate(EMPTY_ARRAY.length())) { return; }
|
||||
for (auto _ : state) {
|
||||
for (UNUSED auto _ : state) {
|
||||
try {
|
||||
UNUSED dom::element doc = parser.parse(EMPTY_ARRAY);
|
||||
} catch(simdjson_error &j) {
|
||||
cout << j.what() << endl;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
BENCHMARK(parser_parse_exception);
|
||||
|
||||
#endif // SIMDJSON_EXCEPTIONS
|
||||
|
||||
SIMDJSON_PUSH_DISABLE_WARNINGS
|
||||
SIMDJSON_DISABLE_DEPRECATED_WARNING
|
||||
static void build_parsed_json(State& state) {
|
||||
for (auto _ : state) {
|
||||
for (UNUSED auto _ : state) {
|
||||
dom::parser parser = simdjson::build_parsed_json(EMPTY_ARRAY);
|
||||
if (!parser.valid) { return; }
|
||||
}
|
||||
}
|
||||
SIMDJSON_POP_DISABLE_WARNINGS
|
||||
|
||||
BENCHMARK(build_parsed_json);
|
||||
static void document_parse_error_code(State& state) {
|
||||
for (auto _ : state) {
|
||||
for (UNUSED auto _ : state) {
|
||||
dom::parser parser;
|
||||
auto [doc, error] = parser.parse(EMPTY_ARRAY);
|
||||
auto error = parser.parse(EMPTY_ARRAY).error();
|
||||
if (error) { return; }
|
||||
}
|
||||
}
|
||||
BENCHMARK(document_parse_error_code);
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
|
||||
static void document_parse_exception(State& state) {
|
||||
for (auto _ : state) {
|
||||
for (UNUSED auto _ : state) {
|
||||
try {
|
||||
dom::parser parser;
|
||||
UNUSED dom::element doc = parser.parse(EMPTY_ARRAY);
|
||||
} catch(simdjson_error &j) {
|
||||
cout << j.what() << endl;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
BENCHMARK(document_parse_exception);
|
||||
|
||||
BENCHMARK_MAIN();
|
||||
#endif // SIMDJSON_EXCEPTIONS
|
||||
|
||||
BENCHMARK_MAIN();
|
||||
|
||||
+74
-88
@@ -4,8 +4,8 @@
|
||||
#include <cctype>
|
||||
#ifndef _MSC_VER
|
||||
#include <dirent.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
#include <unistd.h>
|
||||
#include <cinttypes>
|
||||
#include <initializer_list>
|
||||
|
||||
@@ -75,7 +75,6 @@ void exit_usage(string message) {
|
||||
}
|
||||
|
||||
struct option_struct {
|
||||
architecture arch = architecture::UNSUPPORTED;
|
||||
bool stage1_only = false;
|
||||
|
||||
int32_t iterations = 400;
|
||||
@@ -84,48 +83,35 @@ struct option_struct {
|
||||
bool verbose = false;
|
||||
|
||||
option_struct(int argc, char **argv) {
|
||||
#ifndef _MSC_VER
|
||||
int c;
|
||||
int c;
|
||||
|
||||
while ((c = getopt(argc, argv, "vtn:i:a:s:")) != -1) {
|
||||
switch (c) {
|
||||
case 'n':
|
||||
iterations = atoi(optarg);
|
||||
break;
|
||||
case 'i':
|
||||
iteration_step = atoi(optarg);
|
||||
break;
|
||||
case 'v':
|
||||
verbose = true;
|
||||
break;
|
||||
case 'a':
|
||||
arch = parse_architecture(optarg);
|
||||
if (arch == architecture::UNSUPPORTED) {
|
||||
exit_usage(string("Unsupported option value -a ") + optarg + ": expected -a HASWELL, WESTMERE or ARM64");
|
||||
}
|
||||
break;
|
||||
case 's':
|
||||
if (!strcmp(optarg, "stage1")) {
|
||||
stage1_only = true;
|
||||
} else if (!strcmp(optarg, "all")) {
|
||||
stage1_only = false;
|
||||
} else {
|
||||
exit_usage(string("Unsupported option value -s ") + optarg + ": expected -s stage1 or all");
|
||||
}
|
||||
break;
|
||||
default:
|
||||
exit_error("Unexpected argument " + c);
|
||||
while ((c = getopt(argc, argv, "vtn:i:a:s:")) != -1) {
|
||||
switch (c) {
|
||||
case 'n':
|
||||
iterations = atoi(optarg);
|
||||
break;
|
||||
case 'i':
|
||||
iteration_step = atoi(optarg);
|
||||
break;
|
||||
case 'v':
|
||||
verbose = true;
|
||||
break;
|
||||
case 'a':
|
||||
simdjson::active_implementation = simdjson::available_implementations[optarg];
|
||||
break;
|
||||
case 's':
|
||||
if (!strcmp(optarg, "stage1")) {
|
||||
stage1_only = true;
|
||||
} else if (!strcmp(optarg, "all")) {
|
||||
stage1_only = false;
|
||||
} else {
|
||||
exit_usage(string("Unsupported option value -s ") + optarg + ": expected -s stage1 or all");
|
||||
}
|
||||
break;
|
||||
default:
|
||||
exit_error(string("Unexpected argument ") + std::string(1,static_cast<char>(c)));
|
||||
}
|
||||
#else
|
||||
int optind = 1;
|
||||
#endif
|
||||
|
||||
// If architecture is not specified, pick the best supported architecture by default
|
||||
if (arch == architecture::UNSUPPORTED) {
|
||||
arch = find_best_supported_architecture();
|
||||
}
|
||||
dom::parser::use_implementation(arch);
|
||||
}
|
||||
|
||||
template<typename F>
|
||||
@@ -154,20 +140,20 @@ struct feature_benchmarker {
|
||||
benchmarker struct23;
|
||||
benchmarker struct23_miss;
|
||||
|
||||
feature_benchmarker(const simdjson::implementation &parser, event_collector& collector) :
|
||||
utf8 ("jsonexamples/generated/utf-8.json", parser, collector),
|
||||
utf8_miss ("jsonexamples/generated/utf-8-miss.json", parser, collector),
|
||||
escape ("jsonexamples/generated/escape.json", parser, collector),
|
||||
escape_miss ("jsonexamples/generated/escape-miss.json", parser, collector),
|
||||
empty ("jsonexamples/generated/0-structurals.json", parser, collector),
|
||||
empty_miss ("jsonexamples/generated/0-structurals-miss.json", parser, collector),
|
||||
struct7 ("jsonexamples/generated/7-structurals.json", parser, collector),
|
||||
struct7_miss ("jsonexamples/generated/7-structurals-miss.json", parser, collector),
|
||||
struct7_full ("jsonexamples/generated/7-structurals-full.json", parser, collector),
|
||||
struct15 ("jsonexamples/generated/15-structurals.json", parser, collector),
|
||||
struct15_miss("jsonexamples/generated/15-structurals-miss.json", parser, collector),
|
||||
struct23 ("jsonexamples/generated/23-structurals.json", parser, collector),
|
||||
struct23_miss("jsonexamples/generated/23-structurals-miss.json", parser, collector)
|
||||
feature_benchmarker(event_collector& collector) :
|
||||
utf8 (SIMDJSON_BENCHMARK_DATA_DIR "generated/utf-8.json", collector),
|
||||
utf8_miss (SIMDJSON_BENCHMARK_DATA_DIR "generated/utf-8-miss.json", collector),
|
||||
escape (SIMDJSON_BENCHMARK_DATA_DIR "generated/escape.json", collector),
|
||||
escape_miss (SIMDJSON_BENCHMARK_DATA_DIR "generated/escape-miss.json", collector),
|
||||
empty (SIMDJSON_BENCHMARK_DATA_DIR "generated/0-structurals.json", collector),
|
||||
empty_miss (SIMDJSON_BENCHMARK_DATA_DIR "generated/0-structurals-miss.json", collector),
|
||||
struct7 (SIMDJSON_BENCHMARK_DATA_DIR "generated/7-structurals.json", collector),
|
||||
struct7_miss (SIMDJSON_BENCHMARK_DATA_DIR "generated/7-structurals-miss.json", collector),
|
||||
struct7_full (SIMDJSON_BENCHMARK_DATA_DIR "generated/7-structurals-full.json", collector),
|
||||
struct15 (SIMDJSON_BENCHMARK_DATA_DIR "generated/15-structurals.json", collector),
|
||||
struct15_miss(SIMDJSON_BENCHMARK_DATA_DIR "generated/15-structurals-miss.json", collector),
|
||||
struct23 (SIMDJSON_BENCHMARK_DATA_DIR "generated/23-structurals.json", collector),
|
||||
struct23_miss(SIMDJSON_BENCHMARK_DATA_DIR "generated/23-structurals-miss.json", collector)
|
||||
{
|
||||
|
||||
}
|
||||
@@ -189,7 +175,7 @@ struct feature_benchmarker {
|
||||
}
|
||||
|
||||
double cost_per_block(BenchmarkStage stage, const benchmarker& feature, size_t feature_blocks, const benchmarker& base) const {
|
||||
return (feature[stage].best.elapsed_ns() - base[stage].best.elapsed_ns()) / feature_blocks;
|
||||
return (feature[stage].best.elapsed_ns() - base[stage].best.elapsed_ns()) / double(feature_blocks);
|
||||
}
|
||||
|
||||
// Whether we're recording cache miss and branch miss events
|
||||
@@ -199,7 +185,7 @@ struct feature_benchmarker {
|
||||
|
||||
// Base cost of any block (including empty ones)
|
||||
double base_cost(BenchmarkStage stage) const {
|
||||
return (empty[stage].best.elapsed_ns() / empty.stats->blocks);
|
||||
return (empty[stage].best.elapsed_ns() / double(empty.stats->blocks));
|
||||
}
|
||||
|
||||
// Extra cost of a 1-7 structural block over an empty block
|
||||
@@ -213,7 +199,7 @@ struct feature_benchmarker {
|
||||
// Rate of 1-7-structural misses per 8-structural flip
|
||||
double struct1_7_miss_rate(BenchmarkStage stage) const {
|
||||
if (!has_events()) { return 1; }
|
||||
return double(struct7_miss[stage].best.branch_misses() - struct7[stage].best.branch_misses()) / struct7_miss.stats->blocks_with_1_structural_flipped;
|
||||
return struct7_miss[stage].best.branch_misses() - struct7[stage].best.branch_misses() / double(struct7_miss.stats->blocks_with_1_structural_flipped);
|
||||
}
|
||||
|
||||
// Extra cost of an 8-15 structural block over a 1-7 structural block
|
||||
@@ -227,7 +213,7 @@ struct feature_benchmarker {
|
||||
// Rate of 8-15-structural misses per 8-structural flip
|
||||
double struct8_15_miss_rate(BenchmarkStage stage) const {
|
||||
if (!has_events()) { return 1; }
|
||||
return double(struct15_miss[stage].best.branch_misses() - struct15[stage].best.branch_misses()) / struct15_miss.stats->blocks_with_8_structurals_flipped;
|
||||
return double(struct15_miss[stage].best.branch_misses() - struct15[stage].best.branch_misses()) / double(struct15_miss.stats->blocks_with_8_structurals_flipped);
|
||||
}
|
||||
|
||||
// Extra cost of a 16+-structural block over an 8-15 structural block (actual varies based on # of structurals!)
|
||||
@@ -241,7 +227,7 @@ struct feature_benchmarker {
|
||||
// Rate of 16-structural misses per 16-structural flip
|
||||
double struct16_miss_rate(BenchmarkStage stage) const {
|
||||
if (!has_events()) { return 1; }
|
||||
return double(struct23_miss[stage].best.branch_misses() - struct23[stage].best.branch_misses()) / struct23_miss.stats->blocks_with_16_structurals_flipped;
|
||||
return double(struct23_miss[stage].best.branch_misses() - struct23[stage].best.branch_misses()) / double(struct23_miss.stats->blocks_with_16_structurals_flipped);
|
||||
}
|
||||
|
||||
// Extra cost of having UTF-8 in a block
|
||||
@@ -255,7 +241,7 @@ struct feature_benchmarker {
|
||||
// Rate of UTF-8 misses per UTF-8 flip
|
||||
double utf8_miss_rate(BenchmarkStage stage) const {
|
||||
if (!has_events()) { return 1; }
|
||||
return double(utf8_miss[stage].best.branch_misses() - utf8[stage].best.branch_misses()) / utf8_miss.stats->blocks_with_utf8_flipped;
|
||||
return double(utf8_miss[stage].best.branch_misses() - utf8[stage].best.branch_misses()) / double(utf8_miss.stats->blocks_with_utf8_flipped);
|
||||
}
|
||||
|
||||
// Extra cost of having escapes in a block
|
||||
@@ -269,39 +255,39 @@ struct feature_benchmarker {
|
||||
// Rate of escape misses per escape flip
|
||||
double escape_miss_rate(BenchmarkStage stage) const {
|
||||
if (!has_events()) { return 1; }
|
||||
return double(escape_miss[stage].best.branch_misses() - escape[stage].best.branch_misses()) / escape_miss.stats->blocks_with_escapes_flipped;
|
||||
return double(escape_miss[stage].best.branch_misses() - escape[stage].best.branch_misses()) / double(escape_miss.stats->blocks_with_escapes_flipped);
|
||||
}
|
||||
|
||||
double calc_expected_feature_cost(BenchmarkStage stage, const benchmarker& file) const {
|
||||
// Expected base ns/block (empty)
|
||||
json_stats& stats = *file.stats;
|
||||
double expected = base_cost(stage) * stats.blocks;
|
||||
expected += struct1_7_cost(stage) * stats.blocks_with_1_structural;
|
||||
expected += utf8_cost(stage) * stats.blocks_with_utf8;
|
||||
expected += escape_cost(stage) * stats.blocks_with_escapes;
|
||||
expected += struct8_15_cost(stage) * stats.blocks_with_8_structurals;
|
||||
expected += struct16_cost(stage) * stats.blocks_with_16_structurals;
|
||||
return expected / stats.blocks;
|
||||
double expected = base_cost(stage) * double(stats.blocks);
|
||||
expected += struct1_7_cost(stage) * double(stats.blocks_with_1_structural);
|
||||
expected += utf8_cost(stage) * double(stats.blocks_with_utf8);
|
||||
expected += escape_cost(stage) * double(stats.blocks_with_escapes);
|
||||
expected += struct8_15_cost(stage) * double(stats.blocks_with_8_structurals);
|
||||
expected += struct16_cost(stage) * double(stats.blocks_with_16_structurals);
|
||||
return expected / double(stats.blocks);
|
||||
}
|
||||
|
||||
double calc_expected_miss_cost(BenchmarkStage stage, const benchmarker& file) const {
|
||||
// Expected base ns/block (empty)
|
||||
json_stats& stats = *file.stats;
|
||||
double expected = struct1_7_miss_cost(stage) * stats.blocks_with_1_structural_flipped * struct1_7_miss_rate(stage);
|
||||
expected += utf8_miss_cost(stage) * stats.blocks_with_utf8_flipped * utf8_miss_rate(stage);
|
||||
expected += escape_miss_cost(stage) * stats.blocks_with_escapes_flipped * escape_miss_rate(stage);
|
||||
expected += struct8_15_miss_cost(stage) * stats.blocks_with_8_structurals_flipped * struct8_15_miss_rate(stage);
|
||||
expected += struct16_miss_cost(stage) * stats.blocks_with_16_structurals_flipped * struct16_miss_rate(stage);
|
||||
return expected / stats.blocks;
|
||||
double expected = struct1_7_miss_cost(stage) * double(stats.blocks_with_1_structural_flipped) * struct1_7_miss_rate(stage);
|
||||
expected += utf8_miss_cost(stage) * double(stats.blocks_with_utf8_flipped) * utf8_miss_rate(stage);
|
||||
expected += escape_miss_cost(stage) * double(stats.blocks_with_escapes_flipped) * escape_miss_rate(stage);
|
||||
expected += struct8_15_miss_cost(stage) * double(stats.blocks_with_8_structurals_flipped) * struct8_15_miss_rate(stage);
|
||||
expected += struct16_miss_cost(stage) * double(stats.blocks_with_16_structurals_flipped) * struct16_miss_rate(stage);
|
||||
return expected / double(stats.blocks);
|
||||
}
|
||||
|
||||
double calc_expected_misses(BenchmarkStage stage, const benchmarker& file) const {
|
||||
json_stats& stats = *file.stats;
|
||||
double expected = stats.blocks_with_1_structural_flipped * struct1_7_miss_rate(stage);
|
||||
expected += stats.blocks_with_utf8_flipped * utf8_miss_rate(stage);
|
||||
expected += stats.blocks_with_escapes_flipped * escape_miss_rate(stage);
|
||||
expected += stats.blocks_with_8_structurals_flipped * struct8_15_miss_rate(stage);
|
||||
expected += stats.blocks_with_16_structurals_flipped * struct16_miss_rate(stage);
|
||||
double expected = double(stats.blocks_with_1_structural_flipped) * struct1_7_miss_rate(stage);
|
||||
expected += double(stats.blocks_with_utf8_flipped) * utf8_miss_rate(stage);
|
||||
expected += double(stats.blocks_with_escapes_flipped) * escape_miss_rate(stage);
|
||||
expected += double(stats.blocks_with_8_structurals_flipped) * struct8_15_miss_rate(stage);
|
||||
expected += double(stats.blocks_with_16_structurals_flipped) * struct16_miss_rate(stage);
|
||||
return expected;
|
||||
}
|
||||
|
||||
@@ -368,10 +354,10 @@ struct feature_benchmarker {
|
||||
};
|
||||
|
||||
void print_file_effectiveness(BenchmarkStage stage, const char* filename, const benchmarker& results, const feature_benchmarker& features) {
|
||||
double actual = results[stage].best.elapsed_ns() / results.stats->blocks;
|
||||
double actual = results[stage].best.elapsed_ns() / double(results.stats->blocks);
|
||||
double calc = features.calc_expected(stage, results);
|
||||
uint64_t actual_misses = results[stage].best.branch_misses();
|
||||
uint64_t calc_misses = uint64_t(features.calc_expected_misses(stage, results));
|
||||
double actual_misses = results[stage].best.branch_misses();
|
||||
double calc_misses = features.calc_expected_misses(stage, results);
|
||||
double calc_miss_cost = features.calc_expected_miss_cost(stage, results);
|
||||
printf(" | %-8s ", benchmark_stage_name(stage));
|
||||
printf("| %-15s ", filename);
|
||||
@@ -380,10 +366,10 @@ void print_file_effectiveness(BenchmarkStage stage, const char* filename, const
|
||||
printf("| %8.3g ", calc);
|
||||
printf("| %8.3g ", actual);
|
||||
printf("| %+8.3g ", actual - calc);
|
||||
printf("| %13lu ", calc_misses);
|
||||
printf("| %13llu ", (long long unsigned)(calc_misses));
|
||||
if (features.has_events()) {
|
||||
printf("| %13lu ", actual_misses);
|
||||
printf("| %+13ld ", int64_t(actual_misses - calc_misses));
|
||||
printf("| %13llu ", (long long unsigned)(actual_misses));
|
||||
printf("| %+13lld ", (long long int)(actual_misses - calc_misses));
|
||||
double miss_adjustment = calc_miss_cost * (double(int64_t(actual_misses - calc_misses)) / calc_misses);
|
||||
printf("| %8.3g ", calc_miss_cost + miss_adjustment);
|
||||
printf("| %+8.3g ", actual - (calc + miss_adjustment));
|
||||
@@ -405,9 +391,9 @@ int main(int argc, char *argv[]) {
|
||||
|
||||
// Set up benchmarkers by reading all files
|
||||
feature_benchmarker features(collector);
|
||||
benchmarker gsoc_2018("jsonexamples/gsoc-2018.json", collector);
|
||||
benchmarker twitter("jsonexamples/twitter.json", collector);
|
||||
benchmarker random("jsonexamples/random.json", collector);
|
||||
benchmarker gsoc_2018(SIMDJSON_BENCHMARK_DATA_DIR "gsoc-2018.json", collector);
|
||||
benchmarker twitter(SIMDJSON_BENCHMARK_DATA_DIR "twitter.json", collector);
|
||||
benchmarker random(SIMDJSON_BENCHMARK_DATA_DIR "random.json", collector);
|
||||
|
||||
// Run the benchmarks
|
||||
progress_bar progress(options.iterations, 100);
|
||||
|
||||
+62
-183
@@ -1,82 +1,7 @@
|
||||
#ifndef _BENCHMARK_H_
|
||||
#define _BENCHMARK_H_
|
||||
#include <float.h>
|
||||
#include <stdint.h>
|
||||
#include <time.h>
|
||||
#ifdef __x86_64__
|
||||
|
||||
const char *unitname = "cycles";
|
||||
|
||||
#define RDTSC_START(cycles) \
|
||||
do { \
|
||||
uint32_t cyc_high, cyc_low; \
|
||||
__asm volatile("cpuid\n" \
|
||||
"rdtsc\n" \
|
||||
"mov %%edx, %0\n" \
|
||||
"mov %%eax, %1" \
|
||||
: "=r"(cyc_high), "=r"(cyc_low) \
|
||||
: \
|
||||
: /* no read only */ \
|
||||
"%rax", "%rbx", "%rcx", "%rdx" /* clobbers */ \
|
||||
); \
|
||||
(cycles) = ((uint64_t)cyc_high << 32) | cyc_low; \
|
||||
} while (0)
|
||||
|
||||
#define RDTSC_STOP(cycles) \
|
||||
do { \
|
||||
uint32_t cyc_high, cyc_low; \
|
||||
__asm volatile("rdtscp\n" \
|
||||
"mov %%edx, %0\n" \
|
||||
"mov %%eax, %1\n" \
|
||||
"cpuid" \
|
||||
: "=r"(cyc_high), "=r"(cyc_low) \
|
||||
: /* no read only registers */ \
|
||||
: "%rax", "%rbx", "%rcx", "%rdx" /* clobbers */ \
|
||||
); \
|
||||
(cycles) = ((uint64_t)cyc_high << 32) | cyc_low; \
|
||||
} while (0)
|
||||
|
||||
#else
|
||||
const char *unitname = " (clock units) ";
|
||||
|
||||
#define RDTSC_START(cycles) \
|
||||
do { \
|
||||
cycles = clock(); \
|
||||
} while (0)
|
||||
|
||||
#define RDTSC_STOP(cycles) \
|
||||
do { \
|
||||
cycles = clock(); \
|
||||
} while (0)
|
||||
#endif
|
||||
|
||||
static __attribute__((noinline)) uint64_t rdtsc_overhead_func(uint64_t dummy) {
|
||||
return dummy;
|
||||
}
|
||||
|
||||
uint64_t global_rdtsc_overhead = (uint64_t)UINT64_MAX;
|
||||
|
||||
#define RDTSC_SET_OVERHEAD(test, repeat) \
|
||||
do { \
|
||||
uint64_t cycles_start, cycles_final, cycles_diff; \
|
||||
uint64_t min_diff = UINT64_MAX; \
|
||||
for (int i = 0; i < repeat; i++) { \
|
||||
__asm volatile("" ::: /* pretend to clobber */ "memory"); \
|
||||
RDTSC_START(cycles_start); \
|
||||
test; \
|
||||
RDTSC_STOP(cycles_final); \
|
||||
cycles_diff = (cycles_final - cycles_start); \
|
||||
if (cycles_diff < min_diff) \
|
||||
min_diff = cycles_diff; \
|
||||
} \
|
||||
global_rdtsc_overhead = min_diff; \
|
||||
} while (0)
|
||||
|
||||
double diff(timespec start, timespec end) {
|
||||
return ((end.tv_nsec + 1000000000 * end.tv_sec) -
|
||||
(start.tv_nsec + 1000000000 * start.tv_sec)) /
|
||||
1000000000.0;
|
||||
}
|
||||
#include "event_counter.h"
|
||||
|
||||
/*
|
||||
* Prints the best number of operations per cycle where
|
||||
@@ -86,62 +11,48 @@ double diff(timespec start, timespec end) {
|
||||
*/
|
||||
#define BEST_TIME(name, test, expected, pre, repeat, size, verbose) \
|
||||
do { \
|
||||
if (global_rdtsc_overhead == UINT64_MAX) { \
|
||||
RDTSC_SET_OVERHEAD(rdtsc_overhead_func(1), repeat); \
|
||||
} \
|
||||
if (verbose) \
|
||||
printf("%-40s\t: ", name); \
|
||||
else \
|
||||
printf("\"%-40s\"", name); \
|
||||
fflush(NULL); \
|
||||
uint64_t cycles_start, cycles_final, cycles_diff; \
|
||||
uint64_t min_diff = (uint64_t)-1; \
|
||||
double min_sumclockdiff = DBL_MAX; \
|
||||
uint64_t sum_diff = 0; \
|
||||
double sumclockdiff = 0; \
|
||||
struct timespec time1, time2; \
|
||||
for (int i = 0; i < repeat; i++) { \
|
||||
event_collector collector; \
|
||||
event_aggregate aggregate{}; \
|
||||
for (decltype(repeat) i = 0; i < repeat; i++) { \
|
||||
pre; \
|
||||
__asm volatile("" ::: /* pretend to clobber */ "memory"); \
|
||||
clock_gettime(CLOCK_REALTIME, &time1); \
|
||||
RDTSC_START(cycles_start); \
|
||||
std::atomic_thread_fence(std::memory_order_acquire); \
|
||||
collector.start(); \
|
||||
if (test != expected) { \
|
||||
fprintf(stderr, "not expected (%d , %d )", (int)test, (int)expected); \
|
||||
break; \
|
||||
} \
|
||||
RDTSC_STOP(cycles_final); \
|
||||
clock_gettime(CLOCK_REALTIME, &time2); \
|
||||
double thistiming = diff(time1, time2); \
|
||||
sumclockdiff += thistiming; \
|
||||
if (thistiming < min_sumclockdiff) \
|
||||
min_sumclockdiff = thistiming; \
|
||||
cycles_diff = (cycles_final - cycles_start - global_rdtsc_overhead); \
|
||||
if (cycles_diff < min_diff) \
|
||||
min_diff = cycles_diff; \
|
||||
sum_diff += cycles_diff; \
|
||||
std::atomic_thread_fence(std::memory_order_release); \
|
||||
event_count allocate_count = collector.end(); \
|
||||
aggregate << allocate_count; \
|
||||
} \
|
||||
uint64_t S = size; \
|
||||
float cycle_per_op = (min_diff) / (double)S; \
|
||||
float avg_cycle_per_op = (sum_diff) / ((double)S * repeat); \
|
||||
double avg_gb_per_s = \
|
||||
((double)S * repeat) / ((sumclockdiff)*1000.0 * 1000.0 * 1000.0); \
|
||||
double max_gb_per_s = \
|
||||
((double)S) / ((min_sumclockdiff)*1000.0 * 1000.0 * 1000.0); \
|
||||
if (verbose) \
|
||||
printf(" %7.3f %s per input byte (best) ", cycle_per_op, unitname); \
|
||||
if (verbose) \
|
||||
printf(" %7.3f %s (avg) ", avg_cycle_per_op, unitname); \
|
||||
if (verbose) \
|
||||
printf(" %7.3f GB/s (error margin: %5.3f GB/s)", max_gb_per_s, \
|
||||
-avg_gb_per_s + max_gb_per_s); \
|
||||
if (verbose) \
|
||||
printf(" %13.0f documents/s (best)", 1.0/min_sumclockdiff); \
|
||||
if (verbose) \
|
||||
printf(" %13.0f documents/s (avg)", 1.0/(sumclockdiff/repeat)); \
|
||||
if (!verbose) \
|
||||
printf(" %20.3f %20.3f %20.3f %20.3f", cycle_per_op, \
|
||||
avg_cycle_per_op - cycle_per_op, max_gb_per_s, \
|
||||
-avg_gb_per_s + max_gb_per_s); \
|
||||
if (collector.has_events()) { \
|
||||
printf("%7.3f", aggregate.best.cycles() / static_cast<double>(size)); \
|
||||
if (verbose) { \
|
||||
printf(" cycles/byte "); \
|
||||
} \
|
||||
printf("\t"); \
|
||||
printf("%7.3f", \
|
||||
aggregate.best.instructions() / static_cast<double>(size)); \
|
||||
if (verbose) { \
|
||||
printf(" instructions/byte "); \
|
||||
} \
|
||||
printf("\t"); \
|
||||
} \
|
||||
double gb = static_cast<double>(size) / 1000000000.0; \
|
||||
printf("%7.3f", gb / aggregate.best.elapsed_sec()); \
|
||||
if (verbose) { \
|
||||
printf(" GB/s "); \
|
||||
} \
|
||||
printf("%7.3f", 1.0 / aggregate.best.elapsed_sec()); \
|
||||
if (verbose) { \
|
||||
printf(" documents/s "); \
|
||||
} \
|
||||
printf("\n"); \
|
||||
fflush(NULL); \
|
||||
} while (0)
|
||||
@@ -149,78 +60,46 @@ double diff(timespec start, timespec end) {
|
||||
// like BEST_TIME, but no check
|
||||
#define BEST_TIME_NOCHECK(name, test, pre, repeat, size, verbose) \
|
||||
do { \
|
||||
if (global_rdtsc_overhead == UINT64_MAX) { \
|
||||
RDTSC_SET_OVERHEAD(rdtsc_overhead_func(1), repeat); \
|
||||
} \
|
||||
if (verbose) \
|
||||
printf("%-40s\t: ", name); \
|
||||
else \
|
||||
printf("\"%-40s\"", name); \
|
||||
fflush(NULL); \
|
||||
uint64_t cycles_start, cycles_final, cycles_diff; \
|
||||
uint64_t min_diff = (uint64_t)-1; \
|
||||
uint64_t sum_diff = 0; \
|
||||
for (int i = 0; i < repeat; i++) { \
|
||||
event_collector collector; \
|
||||
event_aggregate aggregate{}; \
|
||||
for (decltype(repeat) i = 0; i < repeat; i++) { \
|
||||
pre; \
|
||||
__asm volatile("" ::: /* pretend to clobber */ "memory"); \
|
||||
RDTSC_START(cycles_start); \
|
||||
std::atomic_thread_fence(std::memory_order_acquire); \
|
||||
collector.start(); \
|
||||
test; \
|
||||
RDTSC_STOP(cycles_final); \
|
||||
cycles_diff = (cycles_final - cycles_start - global_rdtsc_overhead); \
|
||||
if (cycles_diff < min_diff) \
|
||||
min_diff = cycles_diff; \
|
||||
sum_diff += cycles_diff; \
|
||||
std::atomic_thread_fence(std::memory_order_release); \
|
||||
event_count allocate_count = collector.end(); \
|
||||
aggregate << allocate_count; \
|
||||
} \
|
||||
uint64_t S = size; \
|
||||
float cycle_per_op = (min_diff) / (double)S; \
|
||||
float avg_cycle_per_op = (sum_diff) / ((double)S * repeat); \
|
||||
if (verbose) \
|
||||
printf(" %.3f %s per input byte (best) ", cycle_per_op, unitname); \
|
||||
if (verbose) \
|
||||
printf(" %.3f %s per input byte (avg) ", avg_cycle_per_op, unitname); \
|
||||
if (verbose) \
|
||||
printf("\n"); \
|
||||
if (!verbose) \
|
||||
printf(" %.3f ", cycle_per_op); \
|
||||
fflush(NULL); \
|
||||
} while (0)
|
||||
|
||||
// like BEST_TIME except that we run a function to check the result
|
||||
#define BEST_TIME_CHECK(test, check, pre, repeat, size, verbose) \
|
||||
do { \
|
||||
if (global_rdtsc_overhead == UINT64_MAX) { \
|
||||
RDTSC_SET_OVERHEAD(rdtsc_overhead_func(1), repeat); \
|
||||
} \
|
||||
if (verbose) \
|
||||
printf("%-60s\t:\n", #test); \
|
||||
fflush(NULL); \
|
||||
uint64_t cycles_start, cycles_final, cycles_diff; \
|
||||
uint64_t min_diff = (uint64_t)-1; \
|
||||
uint64_t sum_diff = 0; \
|
||||
for (int i = 0; i < repeat; i++) { \
|
||||
pre; \
|
||||
__asm volatile("" ::: /* pretend to clobber */ "memory"); \
|
||||
RDTSC_START(cycles_start); \
|
||||
test; \
|
||||
RDTSC_STOP(cycles_final); \
|
||||
if (!check) { \
|
||||
printf("error"); \
|
||||
break; \
|
||||
if (collector.has_events()) { \
|
||||
printf("%7.3f", aggregate.best.cycles() / static_cast<double>(size)); \
|
||||
if (verbose) { \
|
||||
printf(" cycles/byte "); \
|
||||
} \
|
||||
cycles_diff = (cycles_final - cycles_start - global_rdtsc_overhead); \
|
||||
if (cycles_diff < min_diff) \
|
||||
min_diff = cycles_diff; \
|
||||
sum_diff += cycles_diff; \
|
||||
printf("\t"); \
|
||||
printf("%7.3f", \
|
||||
aggregate.best.instructions() / static_cast<double>(size)); \
|
||||
if (verbose) { \
|
||||
printf(" instructions/byte "); \
|
||||
} \
|
||||
printf("\t"); \
|
||||
} \
|
||||
uint64_t S = size; \
|
||||
float cycle_per_op = (min_diff) / (double)S; \
|
||||
float avg_cycle_per_op = (sum_diff) / ((double)S * repeat); \
|
||||
if (verbose) \
|
||||
printf(" %.3f cycles per operation (best) ", cycle_per_op); \
|
||||
if (verbose) \
|
||||
printf("\t%.3f cycles per operation (avg) ", avg_cycle_per_op); \
|
||||
if (verbose) \
|
||||
printf("\n"); \
|
||||
if (!verbose) \
|
||||
printf(" %.3f ", cycle_per_op); \
|
||||
double gb = static_cast<double>(size) / 1000000000.0; \
|
||||
printf("%7.3f", gb / aggregate.best.elapsed_sec()); \
|
||||
if (verbose) { \
|
||||
printf(" GB/s "); \
|
||||
} \
|
||||
printf("%7.3f", 1.0 / aggregate.best.elapsed_sec()); \
|
||||
if (verbose) { \
|
||||
printf(" documents/s "); \
|
||||
} \
|
||||
printf("\n"); \
|
||||
fflush(NULL); \
|
||||
} while (0)
|
||||
|
||||
|
||||
+71
-54
@@ -2,13 +2,14 @@
|
||||
#define __BENCHMARKER_H
|
||||
|
||||
#include "event_counter.h"
|
||||
#include "simdjson.h" // For SIMDJSON_DISABLE_DEPRECATED_WARNINGS
|
||||
|
||||
#include <cassert>
|
||||
#include <cctype>
|
||||
#ifndef _MSC_VER
|
||||
#include <dirent.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
#include <unistd.h>
|
||||
#include <cinttypes>
|
||||
|
||||
#include <cstdio>
|
||||
@@ -45,6 +46,8 @@ using std::vector;
|
||||
using std::ostream;
|
||||
using std::ofstream;
|
||||
using std::exception;
|
||||
using std::min;
|
||||
using std::max;
|
||||
|
||||
// Initialize "verbose" to go nowhere. We'll read options in main() and set to cout if verbose is true.
|
||||
std::ofstream dev_null;
|
||||
@@ -81,7 +84,7 @@ struct json_stats {
|
||||
bytes = json.size();
|
||||
blocks = bytes / BYTES_PER_BLOCK;
|
||||
if (bytes % BYTES_PER_BLOCK > 0) { blocks++; } // Account for remainder block
|
||||
structurals = parser.n_structural_indexes-1;
|
||||
structurals = parser.implementation->n_structural_indexes-1;
|
||||
|
||||
// Calculate stats on blocks that will trigger utf-8 if statements / mispredictions
|
||||
bool last_block_has_utf8 = false;
|
||||
@@ -138,7 +141,7 @@ struct json_stats {
|
||||
for (size_t block=0; block<blocks; block++) {
|
||||
// Count structurals in the block
|
||||
int block_structurals=0;
|
||||
while (structural < parser.n_structural_indexes && parser.structural_indexes[structural] < (block+1)*BYTES_PER_BLOCK) {
|
||||
while (structural < parser.implementation->n_structural_indexes && parser.implementation->structural_indexes[structural] < (block+1)*BYTES_PER_BLOCK) {
|
||||
block_structurals++;
|
||||
structural++;
|
||||
}
|
||||
@@ -241,7 +244,7 @@ const char* benchmark_stage_name(BenchmarkStage stage) {
|
||||
|
||||
struct benchmarker {
|
||||
// JSON text from loading the file. Owns the memory.
|
||||
padded_string json;
|
||||
padded_string json{};
|
||||
// JSON filename
|
||||
const char *filename;
|
||||
// Event collector that can be turned on to measure cycles, missed branches, etc.
|
||||
@@ -250,22 +253,21 @@ struct benchmarker {
|
||||
// Statistics about the JSON file independent of its speed (amount of utf-8, structurals, etc.).
|
||||
// Loaded on first parse.
|
||||
json_stats* stats;
|
||||
// Speed and event summary for full parse (not including allocation)
|
||||
event_aggregate all_stages;
|
||||
// Speed and event summary for full parse (including allocation, stage 1 and stage 2)
|
||||
event_aggregate all_stages{};
|
||||
// Speed and event summary for stage 1
|
||||
event_aggregate stage1;
|
||||
event_aggregate stage1{};
|
||||
// Speed and event summary for stage 2
|
||||
event_aggregate stage2;
|
||||
event_aggregate stage2{};
|
||||
// Speed and event summary for allocation
|
||||
event_aggregate allocate_stage;
|
||||
event_aggregate allocate_stage{};
|
||||
// Speed and event summary for the repeatly-parsing mode
|
||||
event_aggregate loop;
|
||||
event_aggregate loop{};
|
||||
|
||||
benchmarker(const char *_filename, event_collector& _collector)
|
||||
: filename(_filename), collector(_collector), stats(NULL) {
|
||||
verbose() << "[verbose] loading " << filename << endl;
|
||||
simdjson::error_code error;
|
||||
padded_string::load(filename).tie(this->json, error);
|
||||
auto error = padded_string::load(filename).get(json);
|
||||
if (error) {
|
||||
exit_error(string("Could not load the file ") + filename);
|
||||
}
|
||||
@@ -278,6 +280,9 @@ struct benchmarker {
|
||||
}
|
||||
}
|
||||
|
||||
benchmarker(const benchmarker&) = delete;
|
||||
benchmarker& operator=(const benchmarker&) = delete;
|
||||
|
||||
const event_aggregate& operator[](BenchmarkStage stage) const {
|
||||
switch (stage) {
|
||||
case BenchmarkStage::ALL: return this->all_stages;
|
||||
@@ -314,7 +319,7 @@ struct benchmarker {
|
||||
|
||||
// Stage 1 (find structurals)
|
||||
collector.start();
|
||||
error = active_implementation->stage1((const uint8_t *)json.data(), json.size(), parser, false);
|
||||
error = parser.implementation->stage1((const uint8_t *)json.data(), json.size(), false);
|
||||
event_count stage1_count = collector.end();
|
||||
stage1 << stage1_count;
|
||||
if (error) {
|
||||
@@ -328,7 +333,7 @@ struct benchmarker {
|
||||
} else {
|
||||
event_count stage2_count;
|
||||
collector.start();
|
||||
error = active_implementation->stage2((const uint8_t *)json.data(), json.size(), parser);
|
||||
error = parser.implementation->stage2(parser.doc);
|
||||
if (error) {
|
||||
exit_error(string("Failed to parse ") + filename + " during stage 2 parsing " + error_message(error));
|
||||
}
|
||||
@@ -339,7 +344,7 @@ struct benchmarker {
|
||||
// Calculate stats the first time we parse
|
||||
if (stats == NULL) {
|
||||
if (stage1_only) { // we need stage 2 once
|
||||
error = active_implementation->stage2((const uint8_t *)json.data(), json.size(), parser);
|
||||
error = parser.implementation->stage2(parser.doc);
|
||||
if (error) {
|
||||
printf("Warning: failed to parse during stage 2. Unable to acquire statistics.\n");
|
||||
}
|
||||
@@ -374,36 +379,37 @@ struct benchmarker {
|
||||
run_loop(iterations);
|
||||
}
|
||||
|
||||
// Gigabyte: https://en.wikipedia.org/wiki/Gigabyte
|
||||
template<typename T>
|
||||
void print_aggregate(const char* prefix, const T& stage) const {
|
||||
printf("%s%-13s: %8.4f ns per block (%6.2f%%) - %8.4f ns per byte - %8.4f ns per structural - %8.3f GB/s\n",
|
||||
printf("%s%-13s: %8.4f ns per block (%6.2f%%) - %8.4f ns per byte - %8.4f ns per structural - %8.4f GB/s\n",
|
||||
prefix,
|
||||
"Speed",
|
||||
stage.elapsed_ns() / stats->blocks, // per block
|
||||
100.0 * stage.elapsed_sec() / all_stages.elapsed_sec(), // %
|
||||
stage.elapsed_ns() / stats->bytes, // per byte
|
||||
stage.elapsed_ns() / stats->structurals, // per structural
|
||||
(json.size() / 1000000000.0) / stage.elapsed_sec() // GB/s
|
||||
stage.elapsed_ns() / static_cast<double>(stats->blocks), // per block
|
||||
percent(stage.elapsed_sec(), all_stages.elapsed_sec()), // %
|
||||
stage.elapsed_ns() / static_cast<double>(stats->bytes), // per byte
|
||||
stage.elapsed_ns() / static_cast<double>(stats->structurals), // per structural
|
||||
(static_cast<double>(json.size()) / 1000000000.0) / stage.elapsed_sec() // GB/s
|
||||
);
|
||||
|
||||
if (collector.has_events()) {
|
||||
printf("%s%-13s: %8.4f per block (%6.2f%%) - %8.4f per byte - %8.4f per structural - %8.3f GHz est. frequency\n",
|
||||
prefix,
|
||||
"Cycles",
|
||||
stage.cycles() / stats->blocks,
|
||||
100.0 * stage.cycles() / all_stages.cycles(),
|
||||
stage.cycles() / stats->bytes,
|
||||
stage.cycles() / stats->structurals,
|
||||
stage.cycles() / static_cast<double>(stats->blocks),
|
||||
percent(stage.cycles(), all_stages.cycles()),
|
||||
stage.cycles() / static_cast<double>(stats->bytes),
|
||||
stage.cycles() / static_cast<double>(stats->structurals),
|
||||
(stage.cycles() / stage.elapsed_sec()) / 1000000000.0
|
||||
);
|
||||
printf("%s%-13s: %8.4f per block (%6.2f%%) - %8.4f per byte - %8.4f per structural - %8.3f per cycle\n",
|
||||
prefix,
|
||||
"Instructions",
|
||||
stage.instructions() / stats->blocks,
|
||||
100.0 * stage.instructions() / all_stages.instructions(),
|
||||
stage.instructions() / stats->bytes,
|
||||
stage.instructions() / stats->structurals,
|
||||
stage.instructions() / stage.cycles()
|
||||
stage.instructions() / static_cast<double>(stats->blocks),
|
||||
percent(stage.instructions(), all_stages.instructions()),
|
||||
stage.instructions() / static_cast<double>(stats->bytes),
|
||||
stage.instructions() / static_cast<double>(stats->structurals),
|
||||
stage.instructions() / static_cast<double>(stage.cycles())
|
||||
);
|
||||
|
||||
// NOTE: removed cycles/miss because it is a somewhat misleading stat
|
||||
@@ -411,18 +417,29 @@ struct benchmarker {
|
||||
prefix,
|
||||
"Misses",
|
||||
stage.branch_misses(),
|
||||
100.0 * stage.branch_misses() / all_stages.branch_misses(),
|
||||
percent(stage.branch_misses(), all_stages.branch_misses()),
|
||||
stage.cache_misses(),
|
||||
100.0 * stage.cache_misses() / all_stages.cache_misses(),
|
||||
percent(stage.cache_misses(), all_stages.cache_misses()),
|
||||
stage.cache_references()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void print(bool tabbed_output, size_t iterations) const {
|
||||
static double percent(size_t a, size_t b) {
|
||||
return 100.0 * static_cast<double>(a) / static_cast<double>(b);
|
||||
}
|
||||
static double percent(double a, double b) {
|
||||
return 100.0 * a / b;
|
||||
}
|
||||
|
||||
void print(bool tabbed_output) const {
|
||||
if (tabbed_output) {
|
||||
char* filename_copy = (char*)malloc(strlen(filename)+1);
|
||||
SIMDJSON_PUSH_DISABLE_WARNINGS
|
||||
SIMDJSON_DISABLE_DEPRECATED_WARNING // Validated CRT_SECURE safe here
|
||||
strcpy(filename_copy, filename);
|
||||
SIMDJSON_POP_DISABLE_WARNINGS
|
||||
|
||||
#if defined(__linux__)
|
||||
char* base = ::basename(filename_copy);
|
||||
#else
|
||||
@@ -432,14 +449,14 @@ struct benchmarker {
|
||||
base[strlen(base)-5] = '\0';
|
||||
}
|
||||
|
||||
double gb = json.size() / 1000000000.0;
|
||||
double gb = static_cast<double>(json.size()) / 1000000000.0;
|
||||
if (collector.has_events()) {
|
||||
printf("\"%s\"\t%f\t%f\t%f\t%f\t%f\t%f\t%f\n",
|
||||
base,
|
||||
allocate_stage.best.cycles() / json.size(),
|
||||
stage1.best.cycles() / json.size(),
|
||||
stage2.best.cycles() / json.size(),
|
||||
all_stages.best.cycles() / json.size(),
|
||||
allocate_stage.best.cycles() / static_cast<double>(json.size()),
|
||||
stage1.best.cycles() / static_cast<double>(json.size()),
|
||||
stage2.best.cycles() / static_cast<double>(json.size()),
|
||||
all_stages.best.cycles() / static_cast<double>(json.size()),
|
||||
gb / all_stages.best.elapsed_sec(),
|
||||
gb / stage1.best.elapsed_sec(),
|
||||
gb / stage2.best.elapsed_sec());
|
||||
@@ -455,22 +472,22 @@ struct benchmarker {
|
||||
printf("\n");
|
||||
printf("%s\n", filename);
|
||||
printf("%s\n", string(strlen(filename), '=').c_str());
|
||||
printf("%9zu blocks - %10zu bytes - %5zu structurals (%5.1f %%)\n", stats->bytes / BYTES_PER_BLOCK, stats->bytes, stats->structurals, 100.0 * stats->structurals / stats->bytes);
|
||||
printf("%9zu blocks - %10zu bytes - %5zu structurals (%5.1f %%)\n", stats->bytes / BYTES_PER_BLOCK, stats->bytes, stats->structurals, percent(stats->structurals, stats->bytes));
|
||||
if (stats) {
|
||||
printf("special blocks with: utf8 %9zu (%5.1f %%) - escape %9zu (%5.1f %%) - 0 structurals %9zu (%5.1f %%) - 1+ structurals %9zu (%5.1f %%) - 8+ structurals %9zu (%5.1f %%) - 16+ structurals %9zu (%5.1f %%)\n",
|
||||
stats->blocks_with_utf8, 100.0 * stats->blocks_with_utf8 / stats->blocks,
|
||||
stats->blocks_with_escapes, 100.0 * stats->blocks_with_escapes / stats->blocks,
|
||||
stats->blocks_with_0_structurals, 100.0 * stats->blocks_with_0_structurals / stats->blocks,
|
||||
stats->blocks_with_1_structural, 100.0 * stats->blocks_with_1_structural / stats->blocks,
|
||||
stats->blocks_with_8_structurals, 100.0 * stats->blocks_with_8_structurals / stats->blocks,
|
||||
stats->blocks_with_16_structurals, 100.0 * stats->blocks_with_16_structurals / stats->blocks);
|
||||
stats->blocks_with_utf8, percent(stats->blocks_with_utf8, stats->blocks),
|
||||
stats->blocks_with_escapes, percent(stats->blocks_with_escapes, stats->blocks),
|
||||
stats->blocks_with_0_structurals, percent(stats->blocks_with_0_structurals, stats->blocks),
|
||||
stats->blocks_with_1_structural, percent(stats->blocks_with_1_structural, stats->blocks),
|
||||
stats->blocks_with_8_structurals, percent(stats->blocks_with_8_structurals, stats->blocks),
|
||||
stats->blocks_with_16_structurals, percent(stats->blocks_with_16_structurals, stats->blocks));
|
||||
printf("special block flips: utf8 %9zu (%5.1f %%) - escape %9zu (%5.1f %%) - 0 structurals %9zu (%5.1f %%) - 1+ structurals %9zu (%5.1f %%) - 8+ structurals %9zu (%5.1f %%) - 16+ structurals %9zu (%5.1f %%)\n",
|
||||
stats->blocks_with_utf8_flipped, 100.0 * stats->blocks_with_utf8_flipped / stats->blocks,
|
||||
stats->blocks_with_escapes_flipped, 100.0 * stats->blocks_with_escapes_flipped / stats->blocks,
|
||||
stats->blocks_with_0_structurals_flipped, 100.0 * stats->blocks_with_0_structurals_flipped / stats->blocks,
|
||||
stats->blocks_with_1_structural_flipped, 100.0 * stats->blocks_with_1_structural_flipped / stats->blocks,
|
||||
stats->blocks_with_8_structurals_flipped, 100.0 * stats->blocks_with_8_structurals_flipped / stats->blocks,
|
||||
stats->blocks_with_16_structurals_flipped, 100.0 * stats->blocks_with_16_structurals_flipped / stats->blocks);
|
||||
stats->blocks_with_utf8_flipped, percent(stats->blocks_with_utf8_flipped, stats->blocks),
|
||||
stats->blocks_with_escapes_flipped, percent(stats->blocks_with_escapes_flipped, stats->blocks),
|
||||
stats->blocks_with_0_structurals_flipped, percent(stats->blocks_with_0_structurals_flipped, stats->blocks),
|
||||
stats->blocks_with_1_structural_flipped, percent(stats->blocks_with_1_structural_flipped, stats->blocks),
|
||||
stats->blocks_with_8_structurals_flipped, percent(stats->blocks_with_8_structurals_flipped, stats->blocks),
|
||||
stats->blocks_with_16_structurals_flipped, percent(stats->blocks_with_16_structurals_flipped, stats->blocks));
|
||||
}
|
||||
printf("\n");
|
||||
printf("All Stages\n");
|
||||
@@ -488,8 +505,8 @@ struct benchmarker {
|
||||
double freq1 = (stage1.best.cycles() / stage1.best.elapsed_sec()) / 1000000000.0;
|
||||
double freq2 = (stage2.best.cycles() / stage2.best.elapsed_sec()) / 1000000000.0;
|
||||
double freqall = (all_stages.best.cycles() / all_stages.best.elapsed_sec()) / 1000000000.0;
|
||||
double freqmin = std::min(freq1, freq2);
|
||||
double freqmax = std::max(freq1, freq2);
|
||||
double freqmin = min(freq1, freq2);
|
||||
double freqmax = max(freq1, freq2);
|
||||
if((freqall < 0.95 * freqmin) or (freqall > 1.05 * freqmax)) {
|
||||
printf("\nWarning: The processor frequency fluctuates in an expected way!!!\n"
|
||||
"Expect the overall speed not to match stage 1 and stage 2 speeds.\n"
|
||||
@@ -497,7 +514,7 @@ struct benchmarker {
|
||||
freqmin, freqmax, freqall);
|
||||
}
|
||||
}
|
||||
printf("\n%.1f documents parsed per second\n", iterations/loop.best.elapsed_sec());
|
||||
printf("\n%.1f documents parsed per second (best)\n", 1.0/static_cast<double>(all_stages.best.elapsed_sec()));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
# Relevant targets:
|
||||
# checkperf-parse: builds the reference checkperf-parse, syncing reference repository if needed
|
||||
# checkperf: builds the targets needed for checkperf (parse, perfdiff, checkperf-parse)
|
||||
# update-checkperf-repo: updates the reference repository we're checking performance against
|
||||
# checkperf-repo: initialize and sync reference repository (first time only)
|
||||
# TEST checkperf: runs the actual checkperf test
|
||||
|
||||
# Clone the repository if it's not there
|
||||
find_package(Git QUIET)
|
||||
if (SIMDJSON_IS_UNDER_GIT AND Git_FOUND AND (GIT_VERSION_STRING VERSION_GREATER "2.1.4") AND (NOT CMAKE_GENERATOR MATCHES Ninja) ) # We use "-C" which requires a recent git
|
||||
message(STATUS "Git is available and it is recent. We are enabling checkperf targets.")
|
||||
# sync_git_repository(myrepo ...) creates two targets:
|
||||
# myrepo - if the repo does not exist, creates and syncs it against the origin branch
|
||||
# update_myrepo - will update the repo against the origin branch (and create if needed)
|
||||
function(sync_git_repository name dir remote branch url)
|
||||
# This conditionally creates the git repository
|
||||
add_custom_command(
|
||||
OUTPUT ${dir}/.git/config
|
||||
COMMAND ${GIT_EXECUTABLE} init ${dir}
|
||||
COMMAND ${GIT_EXECUTABLE} -C ${dir} remote add ${remote} ${url}
|
||||
)
|
||||
add_custom_target(init-${name} DEPENDS ${dir}/.git/config)
|
||||
# This conditionally syncs the git repository, first time only
|
||||
add_custom_command(
|
||||
OUTPUT ${dir}/.git/FETCH_HEAD
|
||||
COMMAND ${GIT_EXECUTABLE} remote set-url ${remote} ${url}
|
||||
COMMAND ${GIT_EXECUTABLE} fetch --depth=1 ${remote} ${branch}
|
||||
COMMAND ${GIT_EXECUTABLE} reset --hard ${remote}/${branch}
|
||||
WORKING_DIRECTORY ${dir}
|
||||
DEPENDS init-${name}
|
||||
)
|
||||
# This is the ${name} target, which will create and sync the repo first time only
|
||||
add_custom_target(${name} DEPENDS ${dir}/.git/FETCH_HEAD)
|
||||
# This is the update-${name} target, which will sync the repo (creating it if needed)
|
||||
add_custom_target(
|
||||
update-${name}
|
||||
COMMAND ${GIT_EXECUTABLE} remote set-url ${remote} ${url}
|
||||
COMMAND ${GIT_EXECUTABLE} fetch --depth=1 ${remote} ${branch}
|
||||
COMMAND ${GIT_EXECUTABLE} reset --hard ${remote}/${branch}
|
||||
WORKING_DIRECTORY ${dir}
|
||||
DEPENDS init-${name}
|
||||
)
|
||||
endfunction(sync_git_repository)
|
||||
|
||||
set(SIMDJSON_CHECKPERF_REMOTE origin CACHE STRING "Remote repository to compare performance against")
|
||||
set(SIMDJSON_CHECKPERF_BRANCH master CACHE STRING "Branch to compare performance against")
|
||||
set(SIMDJSON_CHECKPERF_DIR ${CMAKE_CURRENT_BINARY_DIR}/checkperf-reference/${SIMDJSON_CHECKPERF_BRANCH} CACHE STRING "Location to put checkperf performance comparison repository")
|
||||
set(SIMDJSON_CHECKPERF_ARGS ${EXAMPLE_JSON} CACHE STRING "Arguments to pass to parse during checkperf")
|
||||
sync_git_repository(checkperf-repo ${SIMDJSON_CHECKPERF_DIR} ${SIMDJSON_CHECKPERF_REMOTE} ${SIMDJSON_CHECKPERF_BRANCH} ${SIMDJSON_GITHUB_REPOSITORY})
|
||||
|
||||
# Commands to cause cmake on benchmark/checkperf-master/build/
|
||||
# - first, copy CMakeCache.txt
|
||||
add_custom_command(
|
||||
OUTPUT ${SIMDJSON_CHECKPERF_DIR}/build/CMakeCache.txt
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory ${SIMDJSON_CHECKPERF_DIR}/build
|
||||
COMMAND ${CMAKE_COMMAND} -E copy ${SIMDJSON_USER_CMAKECACHE} ${SIMDJSON_CHECKPERF_DIR}/build/CMakeCache.txt
|
||||
DEPENDS checkperf-repo simdjson-user-cmakecache
|
||||
)
|
||||
# - second, cmake ..
|
||||
add_custom_command(
|
||||
OUTPUT ${SIMDJSON_CHECKPERF_DIR}/build/cmake_install.cmake # We make many things but this seems the most cross-platform one we can depend on
|
||||
COMMAND
|
||||
${CMAKE_COMMAND} -E env CXX=${CMAKE_CXX_COMPILER} CC=${CMAKE_C_COMPILER}
|
||||
${CMAKE_COMMAND} -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} -DSIMDJSON_GOOGLE_BENCHMARKS=OFF -DSIMDJSON_COMPETITION=OFF -G ${CMAKE_GENERATOR} ..
|
||||
WORKING_DIRECTORY ${SIMDJSON_CHECKPERF_DIR}/build
|
||||
DEPENDS ${SIMDJSON_CHECKPERF_DIR}/build/CMakeCache.txt
|
||||
)
|
||||
|
||||
# - third, build parse.
|
||||
if (CMAKE_CONFIGURATION_TYPES)
|
||||
set(CHECKPERF_PARSE ${SIMDJSON_CHECKPERF_DIR}/build/benchmark/$<CONFIGURATION>/parse)
|
||||
else()
|
||||
set(CHECKPERF_PARSE ${SIMDJSON_CHECKPERF_DIR}/build/benchmark/parse)
|
||||
endif()
|
||||
add_custom_target(
|
||||
checkperf-parse ALL # TODO is ALL necessary?
|
||||
# Build parse
|
||||
COMMAND ${CMAKE_COMMAND} --build . --target parse --config $<CONFIGURATION>
|
||||
WORKING_DIRECTORY ${SIMDJSON_CHECKPERF_DIR}/build
|
||||
DEPENDS ${SIMDJSON_CHECKPERF_DIR}/build/cmake_install.cmake # We make many things but this seems the most cross-platform one we can depend on
|
||||
)
|
||||
|
||||
# Target to build everything needed for the checkperf test
|
||||
add_custom_target(checkperf DEPENDS parse perfdiff checkperf-parse)
|
||||
|
||||
# Add the actual checkperf test
|
||||
add_test(
|
||||
NAME checkperf
|
||||
# COMMAND ECHO $<TARGET_FILE:perfdiff> \"$<TARGET_FILE:parse> -t ${SIMDJSON_CHECKPERF_ARGS}\" \"${CHECKPERF_PARSE} -t ${SIMDJSON_CHECKPERF_ARGS}\" }
|
||||
COMMAND $<TARGET_FILE:perfdiff> $<TARGET_FILE:parse> ${CHECKPERF_PARSE} -H -t ${SIMDJSON_CHECKPERF_ARGS}
|
||||
)
|
||||
set_property(TEST checkperf APPEND PROPERTY LABELS per_implementation)
|
||||
set_property(TEST checkperf APPEND PROPERTY DEPENDS parse perfdiff ${SIMDJSON_USER_CMAKECACHE})
|
||||
set_property(TEST checkperf PROPERTY RUN_SERIAL TRUE)
|
||||
else()
|
||||
if (CMAKE_GENERATOR MATCHES Ninja)
|
||||
message(STATUS "We disable the checkperf targets under Ninja.")
|
||||
else()
|
||||
message(STATUS "Either git is unavailable or else it is too old. We are disabling checkperf targets.")
|
||||
endif()
|
||||
endif ()
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "simdjson.h"
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <unistd.h>
|
||||
#include <vector>
|
||||
|
||||
@@ -39,17 +40,18 @@ void print_vec(const std::vector<int64_t> &v) {
|
||||
|
||||
// simdjson_recurse below come be implemented like so but it is slow:
|
||||
/*void simdjson_recurse(std::vector<int64_t> & v, simdjson::dom::element element) {
|
||||
if (element.is<simdjson::dom::array>()) {
|
||||
auto [array, array_error] = element.get<simdjson::dom::array>();
|
||||
error_code error;
|
||||
if (element.is_array()) {
|
||||
dom::array array;
|
||||
error = element.get(array);
|
||||
for (auto child : array) {
|
||||
if (child.is<simdjson::dom::array>() || child.is<simdjson::dom::object>()) {
|
||||
simdjson_recurse(v, child);
|
||||
}
|
||||
}
|
||||
} else if (element.is<simdjson::dom::object>()) {
|
||||
auto [object, error] = element.get<simdjson::dom::object>();
|
||||
} else if (element.is_object()) {
|
||||
int64_t id;
|
||||
object["user"]["id"].get<int64_t>().tie(id,error);
|
||||
error = element["user"]["id"].get(id);
|
||||
if(!error) {
|
||||
v.push_back(id);
|
||||
}
|
||||
@@ -63,43 +65,50 @@ void print_vec(const std::vector<int64_t> &v) {
|
||||
// clang-format on
|
||||
|
||||
|
||||
void simdjson_recurse(std::vector<int64_t> & v, simdjson::dom::element element) {
|
||||
if (element.is<simdjson::dom::array>()) {
|
||||
auto array = element.get<simdjson::dom::array>();
|
||||
for (auto child : array) {
|
||||
if (child.is<simdjson::dom::array>() || child.is<simdjson::dom::object>()) {
|
||||
simdjson_recurse(v, child);
|
||||
}
|
||||
}
|
||||
} else if (element.is<simdjson::dom::object>()) {
|
||||
auto object = element.get<simdjson::dom::object>();
|
||||
for (auto [key, value] : object) {
|
||||
if((key.size() == 4) && (memcmp(key.data(), "user", 4) == 0)) {
|
||||
// we are in an object under the key "user"
|
||||
if(value.is<simdjson::dom::object>()) {
|
||||
auto child_object = value.get<simdjson::dom::object>();
|
||||
for (auto [child_key, child_value] : child_object) {
|
||||
if((child_key.size() == 2) && (memcmp(child_key.data(), "id", 2) == 0)) {
|
||||
if(child_value.is<int64_t>()) {
|
||||
v.push_back(child_value.get<int64_t>());
|
||||
}
|
||||
really_inline void simdjson_recurse(std::vector<int64_t> & v, simdjson::dom::element element);
|
||||
void simdjson_recurse(std::vector<int64_t> & v, simdjson::dom::array array) {
|
||||
for (auto child : array) {
|
||||
simdjson_recurse(v, child);
|
||||
}
|
||||
}
|
||||
void simdjson_recurse(std::vector<int64_t> & v, simdjson::dom::object object) {
|
||||
for (auto [key, value] : object) {
|
||||
if((key.size() == 4) && (memcmp(key.data(), "user", 4) == 0)) {
|
||||
// we are in an object under the key "user"
|
||||
simdjson::error_code error;
|
||||
simdjson::dom::object child_object;
|
||||
simdjson::dom::object child_array;
|
||||
if (not (error = value.get(child_object))) {
|
||||
for (auto [child_key, child_value] : child_object) {
|
||||
if((child_key.size() == 2) && (memcmp(child_key.data(), "id", 2) == 0)) {
|
||||
int64_t x;
|
||||
if (not (error = child_value.get(x))) {
|
||||
v.push_back(x);
|
||||
}
|
||||
if (child_value.is<simdjson::dom::array>() || child_value.is<simdjson::dom::object>()) {
|
||||
simdjson_recurse(v, child_value);
|
||||
}
|
||||
}
|
||||
} else if (value.is<simdjson::dom::array>()) {
|
||||
simdjson_recurse(v, value);
|
||||
simdjson_recurse(v, child_value);
|
||||
}
|
||||
// end of: we are in an object under the key "user"
|
||||
} else if (value.is<simdjson::dom::array>() || value.is<simdjson::dom::object>()) {
|
||||
simdjson_recurse(v, value);
|
||||
} else if (not (error = value.get(child_array))) {
|
||||
simdjson_recurse(v, child_array);
|
||||
}
|
||||
// end of: we are in an object under the key "user"
|
||||
} else {
|
||||
simdjson_recurse(v, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
really_inline void simdjson_recurse(std::vector<int64_t> & v, simdjson::dom::element element) {
|
||||
UNUSED simdjson::error_code error;
|
||||
simdjson::dom::array array;
|
||||
simdjson::dom::object object;
|
||||
if (not (error = element.get(array))) {
|
||||
simdjson_recurse(v, array);
|
||||
} else if (not (error = element.get(object))) {
|
||||
simdjson_recurse(v, object);
|
||||
}
|
||||
}
|
||||
|
||||
__attribute__((noinline)) std::vector<int64_t>
|
||||
really_inline std::vector<int64_t>
|
||||
simdjson_just_dom(simdjson::dom::element doc) {
|
||||
std::vector<int64_t> answer;
|
||||
simdjson_recurse(answer, doc);
|
||||
@@ -107,17 +116,20 @@ simdjson_just_dom(simdjson::dom::element doc) {
|
||||
return answer;
|
||||
}
|
||||
|
||||
__attribute__((noinline)) std::vector<int64_t>
|
||||
really_inline std::vector<int64_t>
|
||||
simdjson_compute_stats(const simdjson::padded_string &p) {
|
||||
std::vector<int64_t> answer;
|
||||
simdjson::dom::parser parser;
|
||||
simdjson::dom::element doc = parser.parse(p);
|
||||
simdjson_recurse(answer, doc);
|
||||
remove_duplicates(answer);
|
||||
simdjson::dom::element doc;
|
||||
auto error = parser.parse(p).get(doc);
|
||||
if (!error) {
|
||||
simdjson_recurse(answer, doc);
|
||||
remove_duplicates(answer);
|
||||
}
|
||||
return answer;
|
||||
}
|
||||
|
||||
__attribute__((noinline)) simdjson::error_code
|
||||
really_inline simdjson::error_code
|
||||
simdjson_just_parse(const simdjson::padded_string &p) {
|
||||
simdjson::dom::parser parser;
|
||||
return parser.parse(p).error();
|
||||
@@ -175,7 +187,7 @@ void sajson_traverse(std::vector<int64_t> &answer, const sajson::value &node) {
|
||||
}
|
||||
}
|
||||
|
||||
__attribute__((noinline)) std::vector<int64_t>
|
||||
really_inline std::vector<int64_t>
|
||||
sasjon_just_dom(sajson::document &d) {
|
||||
std::vector<int64_t> answer;
|
||||
sajson_traverse(answer, d.get_root());
|
||||
@@ -183,7 +195,7 @@ sasjon_just_dom(sajson::document &d) {
|
||||
return answer;
|
||||
}
|
||||
|
||||
__attribute__((noinline)) std::vector<int64_t>
|
||||
really_inline std::vector<int64_t>
|
||||
sasjon_compute_stats(const simdjson::padded_string &p) {
|
||||
std::vector<int64_t> answer;
|
||||
char *buffer = (char *)malloc(p.size());
|
||||
@@ -200,7 +212,7 @@ sasjon_compute_stats(const simdjson::padded_string &p) {
|
||||
return answer;
|
||||
}
|
||||
|
||||
__attribute__((noinline)) bool
|
||||
really_inline bool
|
||||
sasjon_just_parse(const simdjson::padded_string &p) {
|
||||
char *buffer = (char *)malloc(p.size());
|
||||
memcpy(buffer, p.data(), p.size());
|
||||
@@ -251,7 +263,7 @@ void rapid_traverse(std::vector<int64_t> &answer, const rapidjson::Value &v) {
|
||||
}
|
||||
}
|
||||
|
||||
__attribute__((noinline)) std::vector<int64_t>
|
||||
really_inline std::vector<int64_t>
|
||||
rapid_just_dom(rapidjson::Document &d) {
|
||||
std::vector<int64_t> answer;
|
||||
rapid_traverse(answer, d);
|
||||
@@ -259,7 +271,7 @@ rapid_just_dom(rapidjson::Document &d) {
|
||||
return answer;
|
||||
}
|
||||
|
||||
__attribute__((noinline)) std::vector<int64_t>
|
||||
really_inline std::vector<int64_t>
|
||||
rapid_compute_stats(const simdjson::padded_string &p) {
|
||||
std::vector<int64_t> answer;
|
||||
char *buffer = (char *)malloc(p.size() + 1);
|
||||
@@ -277,7 +289,7 @@ rapid_compute_stats(const simdjson::padded_string &p) {
|
||||
return answer;
|
||||
}
|
||||
|
||||
__attribute__((noinline)) bool
|
||||
really_inline bool
|
||||
rapid_just_parse(const simdjson::padded_string &p) {
|
||||
char *buffer = (char *)malloc(p.size() + 1);
|
||||
memcpy(buffer, p.data(), p.size());
|
||||
@@ -319,18 +331,19 @@ int main(int argc, char *argv[]) {
|
||||
std::cerr << "warning: ignoring everything after " << argv[optind + 1]
|
||||
<< std::endl;
|
||||
}
|
||||
auto [p, error] = simdjson::padded_string::load(filename);
|
||||
simdjson::padded_string p;
|
||||
auto error = simdjson::padded_string::load(filename).get(p);
|
||||
if (error) {
|
||||
std::cerr << "Could not load the file " << filename << std::endl;
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
// Gigabyte: https://en.wikipedia.org/wiki/Gigabyte
|
||||
if (verbose) {
|
||||
std::cout << "Input has ";
|
||||
if (p.size() > 1024 * 1024)
|
||||
std::cout << p.size() / (1024 * 1024) << " MB ";
|
||||
else if (p.size() > 1024)
|
||||
std::cout << p.size() / 1024 << " KB ";
|
||||
if (p.size() > 1000 * 1000)
|
||||
std::cout << p.size() / (1000 * 1000) << " MB ";
|
||||
else if (p.size() > 1000)
|
||||
std::cout << p.size() / 1000 << " KB ";
|
||||
else
|
||||
std::cout << p.size() << " B ";
|
||||
std::cout << std::endl;
|
||||
@@ -355,7 +368,7 @@ int main(int argc, char *argv[]) {
|
||||
size_t size = s1.size();
|
||||
|
||||
int repeat = 500;
|
||||
int volume = p.size();
|
||||
size_t volume = p.size();
|
||||
if (just_data) {
|
||||
printf(
|
||||
"name cycles_per_byte cycles_per_byte_err gb_per_s gb_per_s_err \n");
|
||||
@@ -373,7 +386,8 @@ int main(int argc, char *argv[]) {
|
||||
BEST_TIME("sasjon (just parse) ", sasjon_just_parse(p), false, , repeat,
|
||||
volume, !just_data);
|
||||
simdjson::dom::parser parser;
|
||||
simdjson::dom::element doc = parser.parse(p);
|
||||
simdjson::dom::element doc;
|
||||
error = parser.parse(p).get(doc);
|
||||
BEST_TIME("simdjson (just dom) ", simdjson_just_dom(doc).size(), size,
|
||||
, repeat, volume, !just_data);
|
||||
char *buffer = (char *)malloc(p.size() + 1);
|
||||
|
||||
+12
-12
@@ -5,8 +5,8 @@
|
||||
#include <cctype>
|
||||
#ifndef _MSC_VER
|
||||
#include <dirent.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
#include <unistd.h>
|
||||
#include <cinttypes>
|
||||
|
||||
#include <cstdio>
|
||||
@@ -56,11 +56,11 @@ struct event_count {
|
||||
|
||||
double elapsed_sec() const { return duration<double>(elapsed).count(); }
|
||||
double elapsed_ns() const { return duration<double, std::nano>(elapsed).count(); }
|
||||
double cycles() const { return event_counts[CPU_CYCLES]; }
|
||||
double instructions() const { return event_counts[INSTRUCTIONS]; }
|
||||
double branch_misses() const { return event_counts[BRANCH_MISSES]; }
|
||||
double cache_references() const { return event_counts[CACHE_REFERENCES]; }
|
||||
double cache_misses() const { return event_counts[CACHE_MISSES]; }
|
||||
double cycles() const { return static_cast<double>(event_counts[CPU_CYCLES]); }
|
||||
double instructions() const { return static_cast<double>(event_counts[INSTRUCTIONS]); }
|
||||
double branch_misses() const { return static_cast<double>(event_counts[BRANCH_MISSES]); }
|
||||
double cache_references() const { return static_cast<double>(event_counts[CACHE_REFERENCES]); }
|
||||
double cache_misses() const { return static_cast<double>(event_counts[CACHE_MISSES]); }
|
||||
|
||||
event_count& operator=(const event_count& other) {
|
||||
this->elapsed = other.elapsed;
|
||||
@@ -84,9 +84,9 @@ struct event_count {
|
||||
|
||||
struct event_aggregate {
|
||||
int iterations = 0;
|
||||
event_count total;
|
||||
event_count best;
|
||||
event_count worst;
|
||||
event_count total{};
|
||||
event_count best{};
|
||||
event_count worst{};
|
||||
|
||||
event_aggregate() {}
|
||||
|
||||
@@ -111,8 +111,8 @@ struct event_aggregate {
|
||||
};
|
||||
|
||||
struct event_collector {
|
||||
event_count count;
|
||||
time_point<steady_clock> start_clock;
|
||||
event_count count{};
|
||||
time_point<steady_clock> start_clock{};
|
||||
|
||||
#if defined(__linux__)
|
||||
LinuxEvents<PERF_TYPE_HARDWARE> linux_events;
|
||||
@@ -149,4 +149,4 @@ struct event_collector {
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
|
||||
// Gigabyte: https://en.wikipedia.org/wiki/Gigabyte
|
||||
never_inline
|
||||
double bench(std::string filename, simdjson::padded_string& p) {
|
||||
std::chrono::time_point<std::chrono::steady_clock> start_clock =
|
||||
@@ -12,7 +13,7 @@ double bench(std::string filename, simdjson::padded_string& p) {
|
||||
std::chrono::time_point<std::chrono::steady_clock> end_clock =
|
||||
std::chrono::steady_clock::now();
|
||||
std::chrono::duration<double> elapsed = end_clock - start_clock;
|
||||
return (p.size() / (1024. * 1024 * 1024.)) / elapsed.count();
|
||||
return (static_cast<double>(p.size()) / (1000000000.)) / elapsed.count();
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
@@ -32,8 +33,8 @@ int main(int argc, char *argv[]) {
|
||||
double meanval = 0;
|
||||
double maxval = 0;
|
||||
double minval = 10000;
|
||||
std::cout << "file size: "<< (p.size() / (1024. * 1024 * 1024.)) << " GB" <<std::endl;
|
||||
size_t times = p.size() > 1024*1024*1024 ? 5 : 50;
|
||||
std::cout << "file size: "<< (static_cast<double>(p.size()) / (1000000000.)) << " GB" <<std::endl;
|
||||
size_t times = p.size() > 1000000000 ? 5 : 50;
|
||||
#if __cpp_exceptions
|
||||
try {
|
||||
#endif
|
||||
@@ -49,7 +50,7 @@ std::cout << "file size: "<< (p.size() / (1024. * 1024 * 1024.)) << " GB" <<std
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
#endif
|
||||
std::cout << "average speed: " << meanval / times << " GB/s"<< std::endl;
|
||||
std::cout << "average speed: " << meanval / static_cast<double>(times) << " GB/s"<< std::endl;
|
||||
std::cout << "min speed : " << minval << " GB/s" << std::endl;
|
||||
std::cout << "max speed : " << maxval << " GB/s" << std::endl;
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
template <int TYPE = PERF_TYPE_HARDWARE> class LinuxEvents {
|
||||
int fd;
|
||||
bool working;
|
||||
perf_event_attr attribs;
|
||||
int num_events;
|
||||
std::vector<uint64_t> temp_result_vec;
|
||||
std::vector<uint64_t> ids;
|
||||
perf_event_attr attribs{};
|
||||
size_t num_events{};
|
||||
std::vector<uint64_t> temp_result_vec{};
|
||||
std::vector<uint64_t> ids{};
|
||||
|
||||
public:
|
||||
explicit LinuxEvents(std::vector<int> config_vec) : fd(0), working(true) {
|
||||
@@ -43,7 +43,7 @@ public:
|
||||
uint32_t i = 0;
|
||||
for (auto config : config_vec) {
|
||||
attribs.config = config;
|
||||
fd = syscall(__NR_perf_event_open, &attribs, pid, cpu, group, flags);
|
||||
fd = static_cast<int>(syscall(__NR_perf_event_open, &attribs, pid, cpu, group, flags));
|
||||
if (fd == -1) {
|
||||
report_error("perf_event_open");
|
||||
}
|
||||
|
||||
@@ -45,6 +45,14 @@ std::string rapid_stringme(char *json) {
|
||||
return buffer.GetString();
|
||||
}
|
||||
|
||||
std::string simdjson_stringme(simdjson::padded_string & json) {
|
||||
std::stringstream ss;
|
||||
dom::parser parser;
|
||||
dom::element doc = parser.parse(json);
|
||||
ss << simdjson::minify(doc);
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
int c;
|
||||
@@ -67,17 +75,19 @@ int main(int argc, char *argv[]) {
|
||||
exit(1);
|
||||
}
|
||||
const char *filename = argv[optind];
|
||||
auto [p, error] = simdjson::padded_string::load(filename);
|
||||
simdjson::padded_string p;
|
||||
auto error = simdjson::padded_string::load(filename).get(p);
|
||||
if (error) {
|
||||
std::cerr << "Could not load the file " << filename << std::endl;
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
// Gigabyte: https://en.wikipedia.org/wiki/Gigabyte
|
||||
if (verbose) {
|
||||
std::cout << "Input has ";
|
||||
if (p.size() > 1024 * 1024)
|
||||
std::cout << p.size() / (1024 * 1024) << " MB ";
|
||||
else if (p.size() > 1024)
|
||||
std::cout << p.size() / 1024 << " KB ";
|
||||
if (p.size() > 1000 * 1000)
|
||||
std::cout << p.size() / (1000 * 1000) << " MB ";
|
||||
else if (p.size() > 1000)
|
||||
std::cout << p.size() / 1000 << " KB ";
|
||||
else
|
||||
std::cout << p.size() << " B ";
|
||||
std::cout << std::endl;
|
||||
@@ -87,7 +97,7 @@ int main(int argc, char *argv[]) {
|
||||
buffer[p.size()] = '\0';
|
||||
|
||||
int repeat = 50;
|
||||
int volume = p.size();
|
||||
size_t volume = p.size();
|
||||
if (just_data) {
|
||||
printf(
|
||||
"name cycles_per_byte cycles_per_byte_err gb_per_s gb_per_s_err \n");
|
||||
@@ -102,18 +112,23 @@ int main(int argc, char *argv[]) {
|
||||
BEST_TIME_NOCHECK(
|
||||
"despacing with RapidJSON Insitu", rapid_stringme_insitu((char *)buffer),
|
||||
memcpy(buffer, p.data(), p.size()), repeat, volume, !just_data);
|
||||
|
||||
BEST_TIME_NOCHECK(
|
||||
"despacing with std::minify", simdjson_stringme(p),, repeat, volume, !just_data);
|
||||
|
||||
|
||||
memcpy(buffer, p.data(), p.size());
|
||||
size_t outlength;
|
||||
uint8_t *cbuffer = (uint8_t *)buffer;
|
||||
for (auto imple : simdjson::available_implementations) {
|
||||
BEST_TIME((std::string("simdjson->minify+")+imple->name()).c_str(), (imple->minify(cbuffer, p.size(), cbuffer, outlength) ? outlength : -1),
|
||||
BEST_TIME((std::string("simdjson->minify+")+imple->name()).c_str(), (imple->minify(cbuffer, p.size(), cbuffer, outlength) == simdjson::SUCCESS ? outlength : -1),
|
||||
outlength, memcpy(buffer, p.data(), p.size()), repeat, volume,
|
||||
!just_data);
|
||||
}
|
||||
|
||||
printf("minisize = %zu, original size = %zu (minified down to %.2f percent "
|
||||
"of original) \n",
|
||||
outlength, p.size(), outlength * 100.0 / p.size());
|
||||
outlength, p.size(), static_cast<double>(outlength) * 100.0 / static_cast<double>(p.size()));
|
||||
|
||||
/***
|
||||
* Is it worth it to minify before parsing?
|
||||
@@ -125,8 +140,7 @@ int main(int argc, char *argv[]) {
|
||||
|
||||
char *mini_buffer = simdjson::internal::allocate_padded_buffer(p.size() + 1);
|
||||
size_t minisize;
|
||||
auto minierror = simdjson::active_implementation->minify((const uint8_t *)p.data(), p.size(),
|
||||
(uint8_t *)mini_buffer, minisize);
|
||||
auto minierror = minify(p.data(), p.size(),mini_buffer, minisize);
|
||||
if (!minierror) { std::cerr << minierror << std::endl; exit(1); }
|
||||
mini_buffer[minisize] = '\0';
|
||||
|
||||
|
||||
+67
-65
@@ -4,8 +4,8 @@
|
||||
#include <cctype>
|
||||
#ifndef _MSC_VER
|
||||
#include <dirent.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
#include <unistd.h>
|
||||
#include <cinttypes>
|
||||
|
||||
#include <cstdio>
|
||||
@@ -62,7 +62,8 @@ void print_usage(ostream& out) {
|
||||
out << "-v - Verbose output." << endl;
|
||||
out << "-s stage1 - Stop after find_structural_bits." << endl;
|
||||
out << "-s all - Run all stages." << endl;
|
||||
out << "-H - Make the buffers hot (reduce page allocation during parsing)" << endl;
|
||||
out << "-C - Leave the buffers cold (includes page allocation and related OS tasks during parsing, speed tied to OS performance)" << endl;
|
||||
out << "-H - Make the buffers hot (reduce page allocation and related OS tasks during parsing) [default]" << endl;
|
||||
out << "-a IMPL - Use the given parser implementation. By default, detects the most advanced" << endl;
|
||||
out << " implementation supported on the host machine." << endl;
|
||||
for (auto impl : simdjson::available_implementations) {
|
||||
@@ -78,69 +79,81 @@ void exit_usage(string message) {
|
||||
}
|
||||
|
||||
struct option_struct {
|
||||
vector<char*> files;
|
||||
vector<char*> files{};
|
||||
bool stage1_only = false;
|
||||
|
||||
int32_t iterations = 200;
|
||||
int32_t iteration_step = 50;
|
||||
int32_t iteration_step = -1;
|
||||
|
||||
bool verbose = false;
|
||||
bool tabbed_output = false;
|
||||
bool hotbuffers = false;
|
||||
/**
|
||||
* Benchmarking on a cold parser instance means that the parsing may include
|
||||
* memory allocation at the OS level. This may lead to apparently odd results
|
||||
* such that higher speed under the Windows Subsystem for Linux than under the
|
||||
* regular Windows, for the same machine. It is arguably misleading to benchmark
|
||||
* how the OS allocates memory, when we really want to just benchmark simdjson.
|
||||
*/
|
||||
bool hotbuffers = true;
|
||||
|
||||
option_struct(int argc, char **argv) {
|
||||
#ifndef _MSC_VER
|
||||
int c;
|
||||
int c;
|
||||
|
||||
while ((c = getopt(argc, argv, "vtn:i:a:s:H")) != -1) {
|
||||
switch (c) {
|
||||
case 'n':
|
||||
iterations = atoi(optarg);
|
||||
break;
|
||||
case 'i':
|
||||
iteration_step = atoi(optarg);
|
||||
break;
|
||||
case 't':
|
||||
tabbed_output = true;
|
||||
break;
|
||||
case 'v':
|
||||
verbose = true;
|
||||
break;
|
||||
case 'a': {
|
||||
const implementation *impl = simdjson::available_implementations[optarg];
|
||||
if (!impl) {
|
||||
std::string exit_message = string("Unsupported option value -a ") + optarg + ": expected -a with one of ";
|
||||
for (auto imple : simdjson::available_implementations) {
|
||||
exit_message += imple->name();
|
||||
exit_message += " ";
|
||||
}
|
||||
exit_usage(exit_message);
|
||||
while ((c = getopt(argc, argv, "vtn:i:a:s:HC")) != -1) {
|
||||
switch (c) {
|
||||
case 'n':
|
||||
iterations = atoi(optarg);
|
||||
break;
|
||||
case 'i':
|
||||
iteration_step = atoi(optarg);
|
||||
break;
|
||||
case 't':
|
||||
tabbed_output = true;
|
||||
break;
|
||||
case 'v':
|
||||
verbose = true;
|
||||
break;
|
||||
case 'a': {
|
||||
const implementation *impl = simdjson::available_implementations[optarg];
|
||||
if (!impl) {
|
||||
std::string exit_message = string("Unsupported option value -a ") + optarg + ": expected -a with one of ";
|
||||
for (auto imple : simdjson::available_implementations) {
|
||||
exit_message += imple->name();
|
||||
exit_message += " ";
|
||||
}
|
||||
simdjson::active_implementation = impl;
|
||||
break;
|
||||
}
|
||||
case 'H':
|
||||
hotbuffers = true;
|
||||
break;
|
||||
case 's':
|
||||
if (!strcmp(optarg, "stage1")) {
|
||||
stage1_only = true;
|
||||
} else if (!strcmp(optarg, "all")) {
|
||||
stage1_only = false;
|
||||
} else {
|
||||
exit_usage(string("Unsupported option value -s ") + optarg + ": expected -s stage1 or all");
|
||||
}
|
||||
break;
|
||||
default:
|
||||
// reaching here means an argument was given to getopt() which did not have a case label
|
||||
exit_usage("Unexpected argument - missing case for option "+
|
||||
std::string(1,static_cast<char>(c))+
|
||||
" (programming error)");
|
||||
exit_usage(exit_message);
|
||||
}
|
||||
simdjson::active_implementation = impl;
|
||||
break;
|
||||
}
|
||||
#else
|
||||
int optind = 1;
|
||||
#endif
|
||||
case 'C':
|
||||
hotbuffers = false;
|
||||
break;
|
||||
case 'H':
|
||||
hotbuffers = true;
|
||||
break;
|
||||
case 's':
|
||||
if (!strcmp(optarg, "stage1")) {
|
||||
stage1_only = true;
|
||||
} else if (!strcmp(optarg, "all")) {
|
||||
stage1_only = false;
|
||||
} else {
|
||||
exit_usage(string("Unsupported option value -s ") + optarg + ": expected -s stage1 or all");
|
||||
}
|
||||
break;
|
||||
default:
|
||||
// reaching here means an argument was given to getopt() which did not have a case label
|
||||
exit_usage("Unexpected argument - missing case for option "+
|
||||
std::string(1,static_cast<char>(c))+
|
||||
" (programming error)");
|
||||
}
|
||||
}
|
||||
|
||||
if (iteration_step == -1) {
|
||||
iteration_step = iterations / 50;
|
||||
if (iteration_step < 200) { iteration_step = 200; }
|
||||
if (iteration_step > iterations) { iteration_step = iterations; }
|
||||
}
|
||||
|
||||
// All remaining arguments are considered to be files
|
||||
for (int i=optind; i<argc; i++) {
|
||||
@@ -149,17 +162,6 @@ struct option_struct {
|
||||
if (files.empty()) {
|
||||
exit_usage("No files specified");
|
||||
}
|
||||
|
||||
// Keeps the numbers the same for CI (old ./parse didn't have a two-stage loop)
|
||||
if (files.size() == 1) {
|
||||
iteration_step = iterations;
|
||||
}
|
||||
|
||||
#if !defined(__linux__)
|
||||
if (tabbed_output) {
|
||||
exit_error("tabbed_output (-t) flag only works under linux.\n");
|
||||
}
|
||||
#endif
|
||||
}
|
||||
};
|
||||
|
||||
@@ -212,7 +214,7 @@ int main(int argc, char *argv[]) {
|
||||
if (!options.verbose) { progress.erase(); }
|
||||
|
||||
for (size_t i=0; i<options.files.size(); i++) {
|
||||
benchmarkers[i]->print(options.tabbed_output, options.iterations);
|
||||
benchmarkers[i]->print(options.tabbed_output);
|
||||
delete benchmarkers[i];
|
||||
}
|
||||
|
||||
|
||||
Executable → Regular
+164
-122
@@ -1,149 +1,191 @@
|
||||
#include <iostream>
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
|
||||
#include "simdjson.h"
|
||||
|
||||
#define NB_ITERATION 5
|
||||
#define MIN_BATCH_SIZE 200000
|
||||
#define NB_ITERATION 20
|
||||
#define MIN_BATCH_SIZE 10000
|
||||
#define MAX_BATCH_SIZE 10000000
|
||||
|
||||
bool test_baseline = false;
|
||||
bool test_per_batch = true;
|
||||
bool test_best_batch = true;
|
||||
bool test_best_batch = false;
|
||||
|
||||
bool compare(std::pair<size_t, double> i, std::pair<size_t, double> j){
|
||||
return i.second > j.second;
|
||||
bool compare(std::pair<size_t, double> i, std::pair<size_t, double> j) {
|
||||
return i.second > j.second;
|
||||
}
|
||||
|
||||
int main (int argc, char *argv[]){
|
||||
int main(int argc, char *argv[]) {
|
||||
|
||||
if (argc <= 1) {
|
||||
std::cerr << "Usage: " << argv[0] << " <jsonfile>" << std::endl;
|
||||
exit(1);
|
||||
}
|
||||
const char *filename = argv[1];
|
||||
auto [p, err] = simdjson::padded_string::load(filename);
|
||||
if (err) {
|
||||
std::cerr << "Could not load the file " << filename << std::endl;
|
||||
if (argc <= 1) {
|
||||
std::cerr << "Usage: " << argv[0] << " <jsonfile>" << std::endl;
|
||||
exit(1);
|
||||
}
|
||||
const char *filename = argv[1];
|
||||
auto[p, err] = simdjson::padded_string::load(filename);
|
||||
if (err) {
|
||||
std::cerr << "Could not load the file " << filename << std::endl;
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
if (test_baseline) {
|
||||
std::wclog << "Baseline: Getline + normal parse... " << std::endl;
|
||||
std::cout << "Gigabytes/second\t"
|
||||
<< "Nb of documents parsed" << std::endl;
|
||||
for (auto i = 0; i < 3; i++) {
|
||||
// Actual test
|
||||
simdjson::dom::parser parser;
|
||||
simdjson::error_code alloc_error = parser.allocate(p.size());
|
||||
if (alloc_error) {
|
||||
std::cerr << alloc_error << std::endl;
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
std::istringstream ss(std::string(p.data(), p.size()));
|
||||
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
int count = 0;
|
||||
std::string line;
|
||||
int parse_res = simdjson::SUCCESS;
|
||||
while (getline(ss, line)) {
|
||||
// TODO we're likely triggering simdjson's padding reallocation here. Is
|
||||
// that intentional?
|
||||
parser.parse(line);
|
||||
count++;
|
||||
}
|
||||
|
||||
auto end = std::chrono::steady_clock::now();
|
||||
|
||||
std::chrono::duration<double> secs = end - start;
|
||||
double speedinGBs = static_cast<double>(p.size()) /
|
||||
(static_cast<double>(secs.count()) * 1000000000.0);
|
||||
std::cout << speedinGBs << "\t\t\t\t" << count << std::endl;
|
||||
|
||||
if (parse_res != simdjson::SUCCESS) {
|
||||
std::cerr << "Parsing failed" << std::endl;
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
if (test_baseline) {
|
||||
std::wclog << "Baseline: Getline + normal parse... " << std::endl;
|
||||
std::cout << "Gigabytes/second\t" << "Nb of documents parsed" << std::endl;
|
||||
for (auto i = 0; i < 3; i++) {
|
||||
//Actual test
|
||||
simdjson::dom::parser parser;
|
||||
simdjson::error_code alloc_error = parser.allocate(p.size());
|
||||
if (alloc_error) {
|
||||
std::cerr << alloc_error << std::endl;
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
std::istringstream ss(std::string(p.data(), p.size()));
|
||||
}
|
||||
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
int count = 0;
|
||||
std::string line;
|
||||
int parse_res = simdjson::SUCCESS;
|
||||
while (getline(ss, line)) {
|
||||
// TODO we're likely triggering simdjson's padding reallocation here. Is that intentional?
|
||||
parser.parse(line);
|
||||
count++;
|
||||
}
|
||||
std::map<size_t, double> batch_size_res;
|
||||
if (test_per_batch) {
|
||||
std::wclog << "parse_many: Speed per batch_size... from " << MIN_BATCH_SIZE
|
||||
<< " bytes to " << MAX_BATCH_SIZE << " bytes..." << std::endl;
|
||||
std::cout << "Batch Size\t"
|
||||
<< "Gigabytes/second\t"
|
||||
<< "Nb of documents parsed" << std::endl;
|
||||
for (size_t i = MIN_BATCH_SIZE; i <= MAX_BATCH_SIZE;
|
||||
i += (MAX_BATCH_SIZE - MIN_BATCH_SIZE) / 100) {
|
||||
batch_size_res.insert(std::pair<size_t, double>(i, 0));
|
||||
int count;
|
||||
for (size_t j = 0; j < 5; j++) {
|
||||
// Actual test
|
||||
simdjson::dom::parser parser;
|
||||
simdjson::error_code error;
|
||||
|
||||
auto end = std::chrono::steady_clock::now();
|
||||
|
||||
std::chrono::duration<double> secs = end - start;
|
||||
double speedinGBs = (p.size()) / (secs.count() * 1000000000.0);
|
||||
std::cout << speedinGBs << "\t\t\t\t" << count << std::endl;
|
||||
|
||||
if (parse_res != simdjson::SUCCESS) {
|
||||
std::cerr << "Parsing failed" << std::endl;
|
||||
exit(1);
|
||||
}
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
count = 0;
|
||||
simdjson::dom::document_stream docs;
|
||||
if ((error = parser.parse_many(p, i).get(docs))) {
|
||||
std::wcerr << "Parsing failed with: " << error << std::endl;
|
||||
exit(1);
|
||||
}
|
||||
for (auto result : docs) {
|
||||
error = result.error();
|
||||
if (error) {
|
||||
std::wcerr << "Parsing failed with: " << error << std::endl;
|
||||
exit(1);
|
||||
}
|
||||
count++;
|
||||
}
|
||||
auto end = std::chrono::steady_clock::now();
|
||||
|
||||
std::chrono::duration<double> secs = end - start;
|
||||
double speedinGBs = static_cast<double>(p.size()) /
|
||||
(static_cast<double>(secs.count()) * 1000000000.0);
|
||||
if (speedinGBs > batch_size_res.at(i))
|
||||
batch_size_res[i] = speedinGBs;
|
||||
}
|
||||
std::cout << i << "\t\t" << std::fixed << std::setprecision(3)
|
||||
<< batch_size_res.at(i) << "\t\t\t\t" << count << std::endl;
|
||||
}
|
||||
}
|
||||
size_t optimal_batch_size{};
|
||||
double best_speed{};
|
||||
if (test_per_batch) {
|
||||
std::pair<size_t, double> best_results;
|
||||
best_results =
|
||||
(*min_element(batch_size_res.begin(), batch_size_res.end(), compare));
|
||||
optimal_batch_size = best_results.first;
|
||||
best_speed = best_results.second;
|
||||
} else {
|
||||
optimal_batch_size = MIN_BATCH_SIZE;
|
||||
}
|
||||
std::wclog << "Seemingly optimal batch_size: " << optimal_batch_size << "..."
|
||||
<< std::endl;
|
||||
std::wclog << "Best speed: " << best_speed << "..." << std::endl;
|
||||
|
||||
if (test_best_batch) {
|
||||
std::wclog << "Starting speed test... Best of " << NB_ITERATION
|
||||
<< " iterations..." << std::endl;
|
||||
std::vector<double> res;
|
||||
for (int i = 0; i < NB_ITERATION; i++) {
|
||||
|
||||
// Actual test
|
||||
simdjson::dom::parser parser;
|
||||
simdjson::error_code error;
|
||||
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
// This includes allocation of the parser
|
||||
simdjson::dom::document_stream docs;
|
||||
if ((error = parser.parse_many(p, optimal_batch_size).get(docs))) {
|
||||
std::wcerr << "Parsing failed with: " << error << std::endl;
|
||||
exit(1);
|
||||
}
|
||||
for (auto result : docs) {
|
||||
error = result.error();
|
||||
if (error) {
|
||||
std::wcerr << "Parsing failed with: " << error << std::endl;
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
auto end = std::chrono::steady_clock::now();
|
||||
|
||||
std::chrono::duration<double> secs = end - start;
|
||||
res.push_back(secs.count());
|
||||
}
|
||||
|
||||
std::map<size_t, double> batch_size_res;
|
||||
if(test_per_batch) {
|
||||
std::wclog << "parse_many: Speed per batch_size... from " << MIN_BATCH_SIZE
|
||||
<< " bytes to " << MAX_BATCH_SIZE << " bytes..." << std::endl;
|
||||
std::cout << "Batch Size\t" << "Gigabytes/second\t" << "Nb of documents parsed" << std::endl;
|
||||
for (size_t i = MIN_BATCH_SIZE; i <= MAX_BATCH_SIZE; i += (MAX_BATCH_SIZE - MIN_BATCH_SIZE) / 50) {
|
||||
batch_size_res.insert(std::pair<size_t, double>(i, 0));
|
||||
int count;
|
||||
for (size_t j = 0; j < 5; j++) {
|
||||
//Actual test
|
||||
simdjson::dom::parser parser;
|
||||
simdjson::error_code error;
|
||||
double min_result = *min_element(res.begin(), res.end());
|
||||
double speedinGBs =
|
||||
static_cast<double>(p.size()) / (min_result * 1000000000.0);
|
||||
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
count = 0;
|
||||
for (auto result : parser.parse_many(p, 4000000)) {
|
||||
error = result.error();
|
||||
count++;
|
||||
}
|
||||
auto end = std::chrono::steady_clock::now();
|
||||
std::cout << "Min: " << min_result << " bytes read: " << p.size()
|
||||
<< " Gigabytes/second: " << speedinGBs << std::endl;
|
||||
}
|
||||
#ifdef SIMDJSON_THREADS_ENABLED
|
||||
// Multithreading probably does not help matters for small files (less than 10
|
||||
// MB).
|
||||
if (p.size() < 10000000) {
|
||||
std::cout << std::endl;
|
||||
|
||||
std::chrono::duration<double> secs = end - start;
|
||||
double speedinGBs = (p.size()) / (secs.count() * 1000000000.0);
|
||||
if (speedinGBs > batch_size_res.at(i))
|
||||
batch_size_res[i] = speedinGBs;
|
||||
std::cout << "Warning: your file is small and the performance results are "
|
||||
"probably meaningless"
|
||||
<< std::endl;
|
||||
std::cout << "as far as multithreaded performance goes." << std::endl;
|
||||
|
||||
if (error != simdjson::SUCCESS) {
|
||||
std::wcerr << "Parsing failed with: " << error << std::endl;
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
std::cout << i << "\t\t" << std::fixed << std::setprecision(3) << batch_size_res.at(i) << "\t\t\t\t" << count << std::endl;
|
||||
std::cout << std::endl;
|
||||
|
||||
}
|
||||
}
|
||||
std::cout
|
||||
<< "Try to concatenate the file with itself to generate a large one."
|
||||
<< std::endl;
|
||||
std::cout << "In bash: " << std::endl;
|
||||
std::cout << "for i in {1..1000}; do cat '" << filename
|
||||
<< "' >> bar.ndjson; done" << std::endl;
|
||||
std::cout << argv[0] << " bar.ndjson" << std::endl;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (test_best_batch) {
|
||||
size_t optimal_batch_size;
|
||||
if (test_per_batch) {
|
||||
optimal_batch_size = (*min_element(batch_size_res.begin(), batch_size_res.end(), compare)).first;
|
||||
} else {
|
||||
optimal_batch_size = MIN_BATCH_SIZE;
|
||||
}
|
||||
std::wclog << "Starting speed test... Best of " << NB_ITERATION << " iterations..." << std::endl;
|
||||
std::wclog << "Seemingly optimal batch_size: " << optimal_batch_size << "..." << std::endl;
|
||||
std::vector<double> res;
|
||||
for (int i = 0; i < NB_ITERATION; i++) {
|
||||
|
||||
// Actual test
|
||||
simdjson::dom::parser parser;
|
||||
simdjson::error_code error;
|
||||
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
// TODO this includes allocation of the parser; is that intentional?
|
||||
for (auto result : parser.parse_many(p, 4000000)) {
|
||||
error = result.error();
|
||||
}
|
||||
auto end = std::chrono::steady_clock::now();
|
||||
|
||||
std::chrono::duration<double> secs = end - start;
|
||||
res.push_back(secs.count());
|
||||
|
||||
if (error != simdjson::SUCCESS) {
|
||||
std::wcerr << "Parsing failed with: " << error << std::endl;
|
||||
exit(1);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
std::min(res.begin(), res.end());
|
||||
|
||||
double min_result = *min_element(res.begin(), res.end());
|
||||
double speedinGBs = (p.size()) / (min_result * 1000000000.0);
|
||||
|
||||
|
||||
std::cout << "Min: " << min_result << " bytes read: " << p.size()
|
||||
<< " Gigabytes/second: " << speedinGBs << std::endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -48,13 +48,14 @@ void print_stat(const stat_t &s) {
|
||||
s.true_count, s.false_count);
|
||||
}
|
||||
|
||||
|
||||
really_inline void simdjson_process_atom(stat_t &s,
|
||||
simdjson::dom::element element) {
|
||||
if (element.is<double>()) {
|
||||
s.number_count++;
|
||||
} else if (element.is<bool>()) {
|
||||
if (element.get<bool>()) {
|
||||
simdjson::error_code error;
|
||||
bool v;
|
||||
if (not (error = element.get(v)) && v) {
|
||||
s.true_count++;
|
||||
} else {
|
||||
s.false_count++;
|
||||
@@ -65,11 +66,17 @@ really_inline void simdjson_process_atom(stat_t &s,
|
||||
}
|
||||
|
||||
void simdjson_recurse(stat_t &s, simdjson::dom::element element) {
|
||||
error_code error;
|
||||
if (element.is<simdjson::dom::array>()) {
|
||||
s.array_count++;
|
||||
auto [array, array_error] = element.get<simdjson::dom::array>();
|
||||
dom::array array;
|
||||
if ((error = element.get(array))) {
|
||||
std::cerr << error << std::endl;
|
||||
abort();
|
||||
}
|
||||
for (auto child : array) {
|
||||
if (child.is<simdjson::dom::array>() || child.is<simdjson::dom::object>()) {
|
||||
if (child.is<simdjson::dom::array>() ||
|
||||
child.is<simdjson::dom::object>()) {
|
||||
simdjson_recurse(s, child);
|
||||
} else {
|
||||
simdjson_process_atom(s, child);
|
||||
@@ -77,12 +84,17 @@ void simdjson_recurse(stat_t &s, simdjson::dom::element element) {
|
||||
}
|
||||
} else if (element.is<simdjson::dom::object>()) {
|
||||
s.object_count++;
|
||||
auto [object, object_error] = element.get<simdjson::dom::object>();
|
||||
for (auto [key, value] : object) {
|
||||
if (value.is<simdjson::dom::array>() || value.is<simdjson::dom::object>()) {
|
||||
simdjson_recurse(s, value);
|
||||
dom::object object;
|
||||
if ((error = element.get(object))) {
|
||||
std::cerr << error << std::endl;
|
||||
abort();
|
||||
}
|
||||
for (auto field : object) {
|
||||
if (field.value.is<simdjson::dom::array>() ||
|
||||
field.value.is<simdjson::dom::object>()) {
|
||||
simdjson_recurse(s, field.value);
|
||||
} else {
|
||||
simdjson_process_atom(s, value);
|
||||
simdjson_process_atom(s, field.value);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -90,11 +102,11 @@ void simdjson_recurse(stat_t &s, simdjson::dom::element element) {
|
||||
}
|
||||
}
|
||||
|
||||
__attribute__((noinline)) stat_t
|
||||
simdjson_compute_stats(const simdjson::padded_string &p) {
|
||||
never_inline stat_t simdjson_compute_stats(const simdjson::padded_string &p) {
|
||||
stat_t s{};
|
||||
simdjson::dom::parser parser;
|
||||
auto [doc, error] = parser.parse(p);
|
||||
simdjson::dom::element doc;
|
||||
auto error = parser.parse(p).get(doc);
|
||||
if (error) {
|
||||
s.valid = false;
|
||||
return s;
|
||||
@@ -104,6 +116,114 @@ simdjson_compute_stats(const simdjson::padded_string &p) {
|
||||
return s;
|
||||
}
|
||||
|
||||
///
|
||||
struct Stat {
|
||||
size_t objectCount;
|
||||
size_t arrayCount;
|
||||
size_t numberCount;
|
||||
size_t stringCount;
|
||||
size_t trueCount;
|
||||
size_t falseCount;
|
||||
size_t nullCount;
|
||||
|
||||
size_t memberCount; // Number of members in all objects
|
||||
size_t elementCount; // Number of elements in all arrays
|
||||
size_t stringLength; // Number of code units in all strings
|
||||
};
|
||||
|
||||
static void GenStatPlus(Stat &stat, const dom::element &v) {
|
||||
switch (v.type()) {
|
||||
case dom::element_type::ARRAY:
|
||||
for (dom::element child : dom::array(v)) {
|
||||
GenStatPlus(stat, child);
|
||||
stat.elementCount++;
|
||||
}
|
||||
stat.arrayCount++;
|
||||
break;
|
||||
case dom::element_type::OBJECT:
|
||||
for (dom::key_value_pair kv : dom::object(v)) {
|
||||
GenStatPlus(stat, dom::element(kv.value));
|
||||
stat.memberCount++;
|
||||
stat.stringCount++;
|
||||
}
|
||||
stat.objectCount++;
|
||||
break;
|
||||
case dom::element_type::INT64:
|
||||
case dom::element_type::UINT64:
|
||||
case dom::element_type::DOUBLE:
|
||||
stat.numberCount++;
|
||||
break;
|
||||
case dom::element_type::STRING: {
|
||||
stat.stringCount++;
|
||||
auto sv = std::string_view(v);
|
||||
stat.stringLength += sv.size();
|
||||
} break;
|
||||
case dom::element_type::BOOL:
|
||||
if (bool(v)) {
|
||||
stat.trueCount++;
|
||||
} else {
|
||||
stat.falseCount++;
|
||||
}
|
||||
break;
|
||||
case dom::element_type::NULL_VALUE:
|
||||
++stat.nullCount;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static void RapidGenStat(Stat &stat, const rapidjson::Value &v) {
|
||||
switch (v.GetType()) {
|
||||
case kNullType:
|
||||
stat.nullCount++;
|
||||
break;
|
||||
case kFalseType:
|
||||
stat.falseCount++;
|
||||
break;
|
||||
case kTrueType:
|
||||
stat.trueCount++;
|
||||
break;
|
||||
|
||||
case kObjectType:
|
||||
for (Value::ConstMemberIterator m = v.MemberBegin(); m != v.MemberEnd();
|
||||
++m) {
|
||||
stat.stringLength += m->name.GetStringLength();
|
||||
RapidGenStat(stat, m->value);
|
||||
}
|
||||
stat.objectCount++;
|
||||
stat.memberCount += (v.MemberEnd() - v.MemberBegin());
|
||||
stat.stringCount += (v.MemberEnd() - v.MemberBegin()); // Key
|
||||
break;
|
||||
|
||||
case kArrayType:
|
||||
for (Value::ConstValueIterator i = v.Begin(); i != v.End(); ++i)
|
||||
RapidGenStat(stat, *i);
|
||||
stat.arrayCount++;
|
||||
stat.elementCount += v.Size();
|
||||
break;
|
||||
|
||||
case kStringType:
|
||||
stat.stringCount++;
|
||||
stat.stringLength += v.GetStringLength();
|
||||
break;
|
||||
|
||||
case kNumberType:
|
||||
stat.numberCount++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
never_inline Stat rapidjson_compute_stats_ref(const rapidjson::Value &doc) {
|
||||
Stat s{};
|
||||
RapidGenStat(s, doc);
|
||||
return s;
|
||||
}
|
||||
|
||||
never_inline Stat
|
||||
simdjson_compute_stats_refplus(const simdjson::dom::element &doc) {
|
||||
Stat s{};
|
||||
GenStatPlus(s, doc);
|
||||
return s;
|
||||
}
|
||||
|
||||
// see
|
||||
// https://github.com/miloyip/nativejson-benchmark/blob/master/src/tests/sajsontest.cpp
|
||||
void sajson_traverse(stat_t &stats, const sajson::value &node) {
|
||||
@@ -147,9 +267,8 @@ void sajson_traverse(stat_t &stats, const sajson::value &node) {
|
||||
}
|
||||
}
|
||||
|
||||
__attribute__((noinline)) stat_t
|
||||
sasjon_compute_stats(const simdjson::padded_string &p) {
|
||||
stat_t answer;
|
||||
never_inline stat_t sasjon_compute_stats(const simdjson::padded_string &p) {
|
||||
stat_t answer{};
|
||||
char *buffer = (char *)malloc(p.size());
|
||||
if (buffer == nullptr) {
|
||||
return answer;
|
||||
@@ -209,9 +328,8 @@ void rapid_traverse(stat_t &stats, const rapidjson::Value &v) {
|
||||
}
|
||||
}
|
||||
|
||||
__attribute__((noinline)) stat_t
|
||||
rapid_compute_stats(const simdjson::padded_string &p) {
|
||||
stat_t answer;
|
||||
never_inline stat_t rapid_compute_stats(const simdjson::padded_string &p) {
|
||||
stat_t answer{};
|
||||
char *buffer = (char *)malloc(p.size() + 1);
|
||||
if (buffer == nullptr) {
|
||||
return answer;
|
||||
@@ -236,9 +354,9 @@ rapid_compute_stats(const simdjson::padded_string &p) {
|
||||
return answer;
|
||||
}
|
||||
|
||||
__attribute__((noinline)) stat_t
|
||||
never_inline stat_t
|
||||
rapid_accurate_compute_stats(const simdjson::padded_string &p) {
|
||||
stat_t answer;
|
||||
stat_t answer{};
|
||||
char *buffer = (char *)malloc(p.size() + 1);
|
||||
if (buffer == nullptr) {
|
||||
return answer;
|
||||
@@ -292,18 +410,19 @@ int main(int argc, char *argv[]) {
|
||||
std::cerr << "warning: ignoring everything after " << argv[optind + 1]
|
||||
<< std::endl;
|
||||
}
|
||||
auto [p, error] = simdjson::padded_string::load(filename);
|
||||
simdjson::padded_string p;
|
||||
auto error = simdjson::padded_string::load(filename).get(p);
|
||||
if (error) {
|
||||
std::cerr << "Could not load the file " << filename << std::endl;
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
// Gigabyte: https://en.wikipedia.org/wiki/Gigabyte
|
||||
if (verbose) {
|
||||
std::cout << "Input has ";
|
||||
if (p.size() > 1024 * 1024)
|
||||
std::cout << p.size() / (1024 * 1024) << " MB ";
|
||||
else if (p.size() > 1024)
|
||||
std::cout << p.size() / 1024 << " KB ";
|
||||
if (p.size() > 1000 * 1000)
|
||||
std::cout << p.size() / (1000 * 1000) << " MB ";
|
||||
else if (p.size() > 1000)
|
||||
std::cout << p.size() / 1000 << " KB ";
|
||||
else
|
||||
std::cout << p.size() << " B ";
|
||||
std::cout << std::endl;
|
||||
@@ -331,7 +450,7 @@ int main(int argc, char *argv[]) {
|
||||
assert(stat_equal(s1, s2));
|
||||
assert(stat_equal(s1, s3));
|
||||
int repeat = 50;
|
||||
int volume = p.size();
|
||||
size_t volume = p.size();
|
||||
if (just_data) {
|
||||
printf("name cycles_per_byte cycles_per_byte_err gb_per_s gb_per_s_err \n");
|
||||
}
|
||||
@@ -339,8 +458,31 @@ int main(int argc, char *argv[]) {
|
||||
repeat, volume, !just_data);
|
||||
BEST_TIME("RapidJSON ", rapid_compute_stats(p).valid, true, ,
|
||||
repeat, volume, !just_data);
|
||||
BEST_TIME("RapidJSON (precise) ", rapid_accurate_compute_stats(p).valid, true, ,
|
||||
repeat, volume, !just_data);
|
||||
BEST_TIME("RapidJSON (precise) ", rapid_accurate_compute_stats(p).valid, true,
|
||||
, repeat, volume, !just_data);
|
||||
BEST_TIME("sasjon ", sasjon_compute_stats(p).valid, true, ,
|
||||
repeat, volume, !just_data);
|
||||
if (!just_data) {
|
||||
printf("API traversal tests\n");
|
||||
printf("Based on https://github.com/miloyip/nativejson-benchmark\n");
|
||||
simdjson::dom::parser parser;
|
||||
simdjson::dom::element doc;
|
||||
auto error = parser.parse(p).get(doc);
|
||||
if (error) {
|
||||
std::cerr << error << std::endl;
|
||||
}
|
||||
size_t refval = simdjson_compute_stats_refplus(doc).objectCount;
|
||||
|
||||
BEST_TIME("simdjson ",
|
||||
simdjson_compute_stats_refplus(doc).objectCount, refval, , repeat,
|
||||
volume, !just_data);
|
||||
char *buffer = (char *)malloc(p.size() + 1);
|
||||
memcpy(buffer, p.data(), p.size());
|
||||
buffer[p.size()] = '\0';
|
||||
rapidjson::Document d;
|
||||
d.ParseInsitu<kParseValidateEncodingFlag>(buffer);
|
||||
BEST_TIME("rapid ", rapidjson_compute_stats_ref(d).objectCount,
|
||||
refval, , repeat, volume, !just_data);
|
||||
free(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#include "simdjson.h"
|
||||
|
||||
#include <unistd.h>
|
||||
#ifndef _MSC_VER
|
||||
#include "linux-perf-events.h"
|
||||
#include <unistd.h>
|
||||
#ifdef __linux__
|
||||
#include <libgen.h>
|
||||
#endif //__linux__
|
||||
@@ -65,52 +65,65 @@ bool fastjson_parse(const char *input) {
|
||||
// end of fastjson stuff
|
||||
#endif
|
||||
|
||||
never_inline size_t sum_line_lengths(char * data, size_t length) {
|
||||
std::stringstream is;
|
||||
is.rdbuf()->pubsetbuf(data, length);
|
||||
never_inline size_t sum_line_lengths(std::stringstream & is) {
|
||||
std::string line;
|
||||
size_t sumofalllinelengths{0};
|
||||
while(getline(is, line)) {
|
||||
while(std::getline(is, line)) {
|
||||
sumofalllinelengths += line.size();
|
||||
}
|
||||
return sumofalllinelengths;
|
||||
}
|
||||
|
||||
inline void reset_stream(std::stringstream & is) {
|
||||
is.clear();
|
||||
is.seekg(0,std::ios::beg);
|
||||
}
|
||||
|
||||
bool bench(const char *filename, bool verbose, bool just_data, int repeat_multiplier) {
|
||||
auto [p, err] = simdjson::padded_string::load(filename);
|
||||
if (err) {
|
||||
std::cerr << "Could not load the file " << filename << std::endl;
|
||||
|
||||
|
||||
bool bench(const char *filename, bool verbose, bool just_data, double repeat_multiplier) {
|
||||
simdjson::padded_string p;
|
||||
auto error = simdjson::padded_string::load(filename).get(p);
|
||||
if (error) {
|
||||
std::cerr << "Could not load the file " << filename << ": " << error << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
int repeat = (50000000 * repeat_multiplier) / p.size();
|
||||
int repeat = static_cast<int>((50000000 * repeat_multiplier) / static_cast<double>(p.size()));
|
||||
if (repeat < 10) { repeat = 10; }
|
||||
|
||||
// Gigabyte: https://en.wikipedia.org/wiki/Gigabyte
|
||||
if (verbose) {
|
||||
std::cout << "Input " << filename << " has ";
|
||||
if (p.size() > 1024 * 1024)
|
||||
std::cout << p.size() / (1024 * 1024) << " MB";
|
||||
else if (p.size() > 1024)
|
||||
std::cout << p.size() / 1024 << " KB";
|
||||
if (p.size() > 1000 * 1000)
|
||||
std::cout << p.size() / (1000 * 1000) << " MB";
|
||||
else if (p.size() > 1000)
|
||||
std::cout << p.size() / 1000 << " KB";
|
||||
else
|
||||
std::cout << p.size() << " B";
|
||||
std::cout << ": will run " << repeat << " iterations." << std::endl;
|
||||
}
|
||||
int volume = p.size();
|
||||
size_t volume = p.size();
|
||||
if (just_data) {
|
||||
printf("%-42s %20s %20s %20s %20s \n", "name", "cycles_per_byte",
|
||||
"cycles_per_byte_err", "gb_per_s", "gb_per_s_err");
|
||||
}
|
||||
if (!just_data) {
|
||||
size_t lc = sum_line_lengths(p.data(), p.size());
|
||||
BEST_TIME("getline ",sum_line_lengths(p.data(), p.size()) , lc, ,
|
||||
const std::string inputcopy(p.data(), p.data()+p.size());
|
||||
std::stringstream is;
|
||||
is.str(inputcopy);
|
||||
const size_t lc = sum_line_lengths(is);
|
||||
BEST_TIME("getline ",sum_line_lengths(is) , lc, reset_stream(is),
|
||||
repeat, volume, !just_data);
|
||||
}
|
||||
|
||||
if (!just_data)
|
||||
BEST_TIME("simdjson (dynamic mem) ", simdjson::dom::parser().parse(p).error(), simdjson::SUCCESS,
|
||||
if (!just_data) {
|
||||
auto parse_dynamic=[](auto& str){
|
||||
simdjson::dom::parser parser;
|
||||
return parser.parse(str).error();
|
||||
};
|
||||
BEST_TIME("simdjson (dynamic mem) ", parse_dynamic(p), simdjson::SUCCESS,
|
||||
, repeat, volume, !just_data);
|
||||
}
|
||||
// (static alloc)
|
||||
simdjson::dom::parser parser;
|
||||
BEST_TIME("simdjson ", parser.parse(p).error(), simdjson::SUCCESS, , repeat, volume,
|
||||
@@ -209,7 +222,7 @@ bool bench(const char *filename, bool verbose, bool just_data, int repeat_multip
|
||||
buffer[p.size()] = '\0';
|
||||
BEST_TIME(
|
||||
"jsmn ",
|
||||
(jsmn_parse(&jparser, buffer, p.size(), tokens.get(), p.size()) > 0),
|
||||
(jsmn_parse(&jparser, buffer, p.size(), tokens.get(), static_cast<unsigned int>(p.size())) > 0),
|
||||
true, jsmn_init(&jparser), repeat, volume, !just_data);
|
||||
}
|
||||
memcpy(buffer, p.data(), p.size());
|
||||
@@ -248,9 +261,9 @@ bool bench(const char *filename, bool verbose, bool just_data, int repeat_multip
|
||||
results.resize(evts.size());
|
||||
stats.resize(evts.size());
|
||||
std::fill(stats.begin(), stats.end(), 0); // unnecessary
|
||||
for (int i = 0; i < repeat; i++) {
|
||||
for (decltype(repeat) i = 0; i < repeat; i++) {
|
||||
unified.start();
|
||||
auto [doc, parse_error] = parser.parse(p);
|
||||
auto parse_error = parser.parse(p).error();
|
||||
if (parse_error)
|
||||
printf("bug\n");
|
||||
unified.end(results);
|
||||
@@ -260,13 +273,13 @@ bool bench(const char *filename, bool verbose, bool just_data, int repeat_multip
|
||||
printf("simdjson : cycles %10.0f instructions %10.0f branchmisses %10.0f "
|
||||
"cacheref %10.0f cachemisses %10.0f bytespercachemiss %10.0f "
|
||||
"inspercycle %10.1f insperbyte %10.1f\n",
|
||||
stats[0] * 1.0 / repeat, stats[1] * 1.0 / repeat,
|
||||
stats[2] * 1.0 / repeat, stats[3] * 1.0 / repeat,
|
||||
stats[4] * 1.0 / repeat, volume * repeat * 1.0 / stats[2],
|
||||
stats[1] * 1.0 / stats[0], stats[1] * 1.0 / (volume * repeat));
|
||||
static_cast<double>(stats[0]) / static_cast<double>(repeat), static_cast<double>(stats[1]) / static_cast<double>(repeat),
|
||||
static_cast<double>(stats[2]) / static_cast<double>(repeat), static_cast<double>(stats[3]) / static_cast<double>(repeat),
|
||||
static_cast<double>(stats[4]) / static_cast<double>(repeat), static_cast<double>(volume) * static_cast<double>(repeat) / static_cast<double>(stats[2]),
|
||||
static_cast<double>(stats[1]) / static_cast<double>(stats[0]), static_cast<double>(stats[1]) / (static_cast<double>(volume) * static_cast<double>(repeat)));
|
||||
|
||||
std::fill(stats.begin(), stats.end(), 0);
|
||||
for (int i = 0; i < repeat; i++) {
|
||||
for (decltype(repeat) i = 0; i < repeat; i++) {
|
||||
memcpy(buffer, p.data(), p.size());
|
||||
buffer[p.size()] = '\0';
|
||||
unified.start();
|
||||
@@ -280,13 +293,13 @@ bool bench(const char *filename, bool verbose, bool just_data, int repeat_multip
|
||||
printf("RapidJSON: cycles %10.0f instructions %10.0f branchmisses %10.0f "
|
||||
"cacheref %10.0f cachemisses %10.0f bytespercachemiss %10.0f "
|
||||
"inspercycle %10.1f insperbyte %10.1f\n",
|
||||
stats[0] * 1.0 / repeat, stats[1] * 1.0 / repeat,
|
||||
stats[2] * 1.0 / repeat, stats[3] * 1.0 / repeat,
|
||||
stats[4] * 1.0 / repeat, volume * repeat * 1.0 / stats[2],
|
||||
stats[1] * 1.0 / stats[0], stats[1] * 1.0 / (volume * repeat));
|
||||
static_cast<double>(stats[0]) / static_cast<double>(repeat), static_cast<double>(stats[1]) / static_cast<double>(repeat),
|
||||
static_cast<double>(stats[2]) / static_cast<double>(repeat), static_cast<double>(stats[3]) / static_cast<double>(repeat),
|
||||
static_cast<double>(stats[4]) / static_cast<double>(repeat), static_cast<double>(volume) * static_cast<double>(repeat) / static_cast<double>(stats[2]),
|
||||
static_cast<double>(stats[1]) / static_cast<double>(stats[0]), static_cast<double>(stats[1]) / (static_cast<double>(volume) * static_cast<double>(repeat)));
|
||||
|
||||
std::fill(stats.begin(), stats.end(), 0); // unnecessary
|
||||
for (int i = 0; i < repeat; i++) {
|
||||
for (decltype(repeat) i = 0; i < repeat; i++) {
|
||||
memcpy(buffer, p.data(), p.size());
|
||||
unified.start();
|
||||
if (sajson::parse(sajson::bounded_allocation(ast_buffer, ast_buffer_size),
|
||||
@@ -300,10 +313,10 @@ bool bench(const char *filename, bool verbose, bool just_data, int repeat_multip
|
||||
printf("sajson : cycles %10.0f instructions %10.0f branchmisses %10.0f "
|
||||
"cacheref %10.0f cachemisses %10.0f bytespercachemiss %10.0f "
|
||||
"inspercycle %10.1f insperbyte %10.1f\n",
|
||||
stats[0] * 1.0 / repeat, stats[1] * 1.0 / repeat,
|
||||
stats[2] * 1.0 / repeat, stats[3] * 1.0 / repeat,
|
||||
stats[4] * 1.0 / repeat, volume * repeat * 1.0 / stats[2],
|
||||
stats[1] * 1.0 / stats[0], stats[1] * 1.0 / (volume * repeat));
|
||||
static_cast<double>(stats[0]) / static_cast<double>(repeat), static_cast<double>(stats[1]) / static_cast<double>(repeat),
|
||||
static_cast<double>(stats[2]) / static_cast<double>(repeat), static_cast<double>(stats[3]) / static_cast<double>(repeat),
|
||||
static_cast<double>(stats[4]) / static_cast<double>(repeat), static_cast<double>(volume) * static_cast<double>(repeat) / static_cast<double>(stats[2]),
|
||||
static_cast<double>(stats[1]) / static_cast<double>(stats[0]), static_cast<double>(stats[1]) / (static_cast<double>(volume) * static_cast<double>(repeat)));
|
||||
|
||||
}
|
||||
#endif // __linux__
|
||||
|
||||
+20
-9
@@ -29,9 +29,10 @@ std::string exec(const char* cmd) {
|
||||
std::string result;
|
||||
std::unique_ptr<FILE, decltype(&closepipe)> pipe(popen(cmd, "r"), closepipe);
|
||||
if (!pipe) {
|
||||
throw std::runtime_error("popen() failed!");
|
||||
std::cerr << "popen() failed!" << std::endl;
|
||||
abort();
|
||||
}
|
||||
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
|
||||
while (fgets(buffer.data(), int(buffer.size()), pipe.get()) != nullptr) {
|
||||
result += buffer.data();
|
||||
}
|
||||
return result;
|
||||
@@ -43,10 +44,10 @@ double readThroughput(std::string parseOutput) {
|
||||
double result = 0;
|
||||
int numResults = 0;
|
||||
while (std::getline(output, line)) {
|
||||
int pos = 0;
|
||||
std::string::size_type pos = 0;
|
||||
for (int i=0; i<5; i++) {
|
||||
pos = line.find('\t', pos);
|
||||
if (pos < 0) {
|
||||
if (pos == std::string::npos) {
|
||||
std::cerr << "Command printed out a line with less than 5 fields in it:\n" << line << std::endl;
|
||||
}
|
||||
pos++;
|
||||
@@ -63,23 +64,33 @@ double readThroughput(std::string parseOutput) {
|
||||
|
||||
const double INTERLEAVED_ATTEMPTS = 7;
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
if (argc != 3) {
|
||||
std::cerr << "Usage: " << argv[0] << " <new parse cmd> <reference parse cmd>" << std::endl;
|
||||
int main(int argc, const char *argv[]) {
|
||||
if (argc < 3) {
|
||||
std::cerr << "Usage: " << argv[0] << " <old parse exe> <new parse exe> [<parse arguments>]" << std::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
std::string newCommand = argv[1];
|
||||
std::string refCommand = argv[2];
|
||||
for (int i=3; i<argc; i++) {
|
||||
newCommand += " ";
|
||||
newCommand += argv[i];
|
||||
refCommand += " ";
|
||||
refCommand += argv[i];
|
||||
}
|
||||
|
||||
std::vector<double> ref;
|
||||
std::vector<double> newcode;
|
||||
for (int attempt=0; attempt < INTERLEAVED_ATTEMPTS; attempt++) {
|
||||
std::cout << "Attempt #" << (attempt+1) << " of " << INTERLEAVED_ATTEMPTS << std::endl;
|
||||
|
||||
// Read new throughput
|
||||
double newThroughput = readThroughput(exec(argv[1]));
|
||||
double newThroughput = readThroughput(exec(newCommand.c_str()));
|
||||
std::cout << "New throughput: " << newThroughput << std::endl;
|
||||
newcode.push_back(newThroughput);
|
||||
|
||||
// Read reference throughput
|
||||
double referenceThroughput = readThroughput(exec(argv[2]));
|
||||
double referenceThroughput = readThroughput(exec(refCommand.c_str()));
|
||||
std::cout << "Ref throughput: " << referenceThroughput << std::endl;
|
||||
ref.push_back(referenceThroughput);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
#include <iostream>
|
||||
#ifndef _MSC_VER
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
#include "simdjson.h"
|
||||
#ifdef __linux__
|
||||
#include "linux-perf-events.h"
|
||||
@@ -52,7 +50,10 @@ really_inline void simdjson_process_atom(stat_t &s,
|
||||
} else if(element.is<double>()) {
|
||||
s.float_count++;
|
||||
} else if (element.is<bool>()) {
|
||||
if (element.get<bool>()) {
|
||||
simdjson::error_code err;
|
||||
bool v;
|
||||
err = element.get(v);
|
||||
if (v) {
|
||||
s.true_count++;
|
||||
} else {
|
||||
s.false_count++;
|
||||
@@ -63,9 +64,11 @@ really_inline void simdjson_process_atom(stat_t &s,
|
||||
}
|
||||
|
||||
void simdjson_recurse(stat_t &s, simdjson::dom::element element) {
|
||||
simdjson::error_code error;
|
||||
if (element.is<simdjson::dom::array>()) {
|
||||
s.array_count++;
|
||||
auto [array, array_error] = element.get<simdjson::dom::array>();
|
||||
simdjson::dom::array array;
|
||||
if ((error = element.get(array))) { std::cerr << error << std::endl; abort(); }
|
||||
for (auto child : array) {
|
||||
if (child.is<simdjson::dom::array>() || child.is<simdjson::dom::object>()) {
|
||||
simdjson_recurse(s, child);
|
||||
@@ -75,13 +78,14 @@ void simdjson_recurse(stat_t &s, simdjson::dom::element element) {
|
||||
}
|
||||
} else if (element.is<simdjson::dom::object>()) {
|
||||
s.object_count++;
|
||||
auto [object, object_error] = element.get<simdjson::dom::object>();
|
||||
for (auto [key, value] : object) {
|
||||
simdjson::dom::object object;
|
||||
if ((error = element.get(object))) { std::cerr << error << std::endl; abort(); }
|
||||
for (auto field : object) {
|
||||
s.string_count++; // for key
|
||||
if (value.is<simdjson::dom::array>() || value.is<simdjson::dom::object>()) {
|
||||
simdjson_recurse(s, value);
|
||||
if (field.value.is<simdjson::dom::array>() || field.value.is<simdjson::dom::object>()) {
|
||||
simdjson_recurse(s, field.value);
|
||||
} else {
|
||||
simdjson_process_atom(s, value);
|
||||
simdjson_process_atom(s, field.value);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -92,7 +96,8 @@ void simdjson_recurse(stat_t &s, simdjson::dom::element element) {
|
||||
stat_t simdjson_compute_stats(const simdjson::padded_string &p) {
|
||||
stat_t answer{};
|
||||
simdjson::dom::parser parser;
|
||||
auto [doc, error] = parser.parse(p);
|
||||
simdjson::dom::element doc;
|
||||
auto error = parser.parse(p).get(doc);
|
||||
if (error) {
|
||||
answer.valid = false;
|
||||
return answer;
|
||||
@@ -103,7 +108,7 @@ stat_t simdjson_compute_stats(const simdjson::padded_string &p) {
|
||||
answer.non_ascii_byte_count = count_nonasciibytes(
|
||||
reinterpret_cast<const uint8_t *>(p.data()), p.size());
|
||||
answer.byte_count = p.size();
|
||||
answer.structural_indexes_count = parser.n_structural_indexes;
|
||||
answer.structural_indexes_count = parser.implementation->n_structural_indexes;
|
||||
simdjson_recurse(answer, doc);
|
||||
return answer;
|
||||
}
|
||||
@@ -132,7 +137,8 @@ int main(int argc, char *argv[]) {
|
||||
std::cerr << "warning: ignoring everything after " << argv[optind + 1]
|
||||
<< std::endl;
|
||||
}
|
||||
auto [p, error] = simdjson::padded_string::load(filename);
|
||||
simdjson::padded_string p;
|
||||
auto error = simdjson::padded_string::load(filename).get(p);
|
||||
if (error) {
|
||||
std::cerr << "Could not load the file " << filename << std::endl;
|
||||
return EXIT_FAILURE;
|
||||
@@ -160,7 +166,6 @@ int main(int argc, char *argv[]) {
|
||||
s.true_count, s.false_count, s.byte_count, s.structural_indexes_count);
|
||||
#ifdef __linux__
|
||||
simdjson::dom::parser parser;
|
||||
const simdjson::implementation &stage_parser = *simdjson::active_implementation;
|
||||
simdjson::error_code alloc_error = parser.allocate(p.size());
|
||||
if (alloc_error) {
|
||||
std::cerr << alloc_error << std::endl;
|
||||
@@ -178,14 +183,14 @@ int main(int argc, char *argv[]) {
|
||||
for (uint32_t i = 0; i < iterations; i++) {
|
||||
unified.start();
|
||||
// The default template is simdjson::architecture::NATIVE.
|
||||
bool isok = (stage_parser.stage1((const uint8_t *)p.data(), p.size(), parser, false) == simdjson::SUCCESS);
|
||||
bool isok = (parser.implementation->stage1((const uint8_t *)p.data(), p.size(), false) == simdjson::SUCCESS);
|
||||
unified.end(results);
|
||||
|
||||
cy1 += results[0];
|
||||
cl1 += results[1];
|
||||
|
||||
unified.start();
|
||||
isok = isok && (stage_parser.stage2((const uint8_t *)p.data(), p.size(), parser) == simdjson::SUCCESS);
|
||||
isok = isok && (parser.implementation->stage2(parser.doc) == simdjson::SUCCESS);
|
||||
unified.end(results);
|
||||
|
||||
cy2 += results[0];
|
||||
@@ -194,8 +199,8 @@ int main(int argc, char *argv[]) {
|
||||
std::cerr << "failure?" << std::endl;
|
||||
}
|
||||
}
|
||||
printf("%f %f %f %f ", cy1 * 1.0 / iterations, cl1 * 1.0 / iterations,
|
||||
cy2 * 1.0 / iterations, cl2 * 1.0 / iterations);
|
||||
printf("%f %f %f %f ", static_cast<double>(cy1) / static_cast<double>(iterations), static_cast<double>(cl1) / static_cast<double>(iterations),
|
||||
static_cast<double>(cy2) / static_cast<double>(iterations), static_cast<double>(cl2) / static_cast<double>(iterations));
|
||||
#endif // __linux__
|
||||
printf("\n");
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# Helper so we don't have to repeat ourselves so much
|
||||
# Usage: add_cpp_test(testname [COMPILE_ONLY] [SOURCES a.cpp b.cpp ...] [LABELS acceptance per_implementation ...])
|
||||
# SOURCES defaults to testname.cpp if not specified.
|
||||
function(add_cpp_test TEST_NAME)
|
||||
# Parse arguments
|
||||
cmake_parse_arguments(PARSE_ARGV 1 ARGS "COMPILE_ONLY;LIBRARY;WILL_FAIL" "" "SOURCES;LABELS")
|
||||
if (NOT ARGS_SOURCES)
|
||||
list(APPEND ARGS_SOURCES ${TEST_NAME}.cpp)
|
||||
endif()
|
||||
if (ARGS_COMPILE_ONLY)
|
||||
list(APPEND ${ARGS_LABELS} compile)
|
||||
endif()
|
||||
|
||||
# Add the compile target
|
||||
if (ARGS_LIBRARY)
|
||||
add_library(${TEST_NAME} STATIC ${ARGS_SOURCES})
|
||||
else(ARGS_LIBRARY)
|
||||
add_executable(${TEST_NAME} ${ARGS_SOURCES})
|
||||
endif(ARGS_LIBRARY)
|
||||
|
||||
# Add test
|
||||
if (ARGS_COMPILE_ONLY OR ARGS_LIBRARY)
|
||||
add_test(
|
||||
NAME ${TEST_NAME}
|
||||
COMMAND ${CMAKE_COMMAND} --build . --target ${TEST_NAME} --config $<CONFIGURATION>
|
||||
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
|
||||
)
|
||||
set_target_properties(${TEST_NAME} PROPERTIES EXCLUDE_FROM_ALL TRUE EXCLUDE_FROM_DEFAULT_BUILD TRUE)
|
||||
else()
|
||||
add_test(${TEST_NAME} ${TEST_NAME})
|
||||
endif()
|
||||
|
||||
if (ARGS_LABELS)
|
||||
set_property(TEST ${TEST_NAME} APPEND PROPERTY LABELS ${ARGS_LABELS})
|
||||
endif()
|
||||
|
||||
if (ARGS_WILL_FAIL)
|
||||
set_property(TEST ${TEST_NAME} PROPERTY WILL_FAIL TRUE)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
function(add_compile_only_test TEST_NAME)
|
||||
add_test(
|
||||
NAME ${TEST_NAME}
|
||||
COMMAND ${CMAKE_COMMAND} --build . --target ${TEST_NAME} --config $<CONFIGURATION>
|
||||
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
|
||||
)
|
||||
set_target_properties(${TEST_NAME} PROPERTIES EXCLUDE_FROM_ALL TRUE EXCLUDE_FROM_DEFAULT_BUILD TRUE)
|
||||
endfunction()
|
||||
@@ -0,0 +1,155 @@
|
||||
|
||||
if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
|
||||
message (STATUS "The simdjson repository appears to be standalone.")
|
||||
option(SIMDJSON_JUST_LIBRARY "Build just the library, omit tests, tools and benchmarks" OFF)
|
||||
message (STATUS "By default, we attempt to build everything.")
|
||||
else()
|
||||
message (STATUS "The simdjson repository appears to be used as a subdirectory.")
|
||||
option(SIMDJSON_JUST_LIBRARY "Build just the library, omit tests, tools and benchmarks" ON)
|
||||
message (STATUS "By default, we just build the library.")
|
||||
endif()
|
||||
|
||||
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.git)
|
||||
set(SIMDJSON_IS_UNDER_GIT ON CACHE BOOL "Whether cmake is under git control")
|
||||
message( STATUS "The simdjson repository appears to be under git." )
|
||||
else()
|
||||
set(SIMDJSON_IS_UNDER_GIT OFF CACHE BOOL "Whether cmake is under git control")
|
||||
message( STATUS "The simdjson repository does not appear to be under git." )
|
||||
endif()
|
||||
|
||||
#
|
||||
# Flags used by exes and by the simdjson library (project-wide flags)
|
||||
#
|
||||
add_library(simdjson-flags INTERFACE)
|
||||
add_library(simdjson-internal-flags INTERFACE)
|
||||
target_link_libraries(simdjson-internal-flags INTERFACE simdjson-flags)
|
||||
|
||||
option(SIMDJSON_SANITIZE "Sanitize addresses" OFF)
|
||||
if(SIMDJSON_SANITIZE)
|
||||
target_compile_options(simdjson-flags INTERFACE -fsanitize=address -fno-omit-frame-pointer -fsanitize=undefined -fno-sanitize-recover=all)
|
||||
target_link_libraries(simdjson-flags INTERFACE -fsanitize=address -fno-omit-frame-pointer -fsanitize=undefined -fno-sanitize-recover=all)
|
||||
|
||||
# Ubuntu bug for GCC 5.0+ (safe for all versions)
|
||||
if (CMAKE_COMPILER_IS_GNUCC)
|
||||
target_link_libraries(simdjson-flags INTERFACE -fuse-ld=gold)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
|
||||
if (NOT CMAKE_BUILD_TYPE)
|
||||
message(STATUS "No build type selected, default to Release")
|
||||
set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE)
|
||||
if(SIMDJSON_SANITIZE)
|
||||
message(WARNING "No build type selected and you have enabled the sanitizer. Consider setting CMAKE_BUILD_TYPE to Debug to help identify the eventual problems.")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(MSVC)
|
||||
option(SIMDJSON_BUILD_STATIC "Build a static library" ON) # turning it on disables the production of a dynamic library
|
||||
else()
|
||||
option(SIMDJSON_BUILD_STATIC "Build a static library" OFF) # turning it on disables the production of a dynamic library
|
||||
option(SIMDJSON_USE_LIBCPP "Use the libc++ library" OFF)
|
||||
endif()
|
||||
option(SIMDJSON_COMPETITION "Compile competitive benchmarks" ON)
|
||||
|
||||
option(SIMDJSON_GOOGLE_BENCHMARKS "compile the Google Benchmark benchmarks" ON)
|
||||
if(SIMDJSON_COMPETITION)
|
||||
message(STATUS "Using SIMDJSON_GOOGLE_BENCHMARKS")
|
||||
endif()
|
||||
|
||||
set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/tools/cmake")
|
||||
|
||||
# We compile tools, tests, etc. with C++ 17. Override yourself if you need on a target.
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
set(CMAKE_MACOSX_RPATH OFF)
|
||||
set(CMAKE_THREAD_PREFER_PTHREAD ON)
|
||||
set(THREADS_PREFER_PTHREAD_FLAG ON)
|
||||
|
||||
# LTO seems to create all sorts of fun problems. Let us
|
||||
# disable temporarily.
|
||||
#include(CheckIPOSupported)
|
||||
#check_ipo_supported(RESULT ltoresult)
|
||||
#if(ltoresult)
|
||||
# set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
|
||||
#endif()
|
||||
|
||||
|
||||
if(MSVC)
|
||||
if("${MSVC_TOOLSET_VERSION}" STREQUAL "140")
|
||||
# Visual Studio 2015 issues warnings and we tolerate it, cmake -G"Visual Studio 14" ..
|
||||
target_compile_options(simdjson-internal-flags INTERFACE /W0 /sdl)
|
||||
else()
|
||||
# Recent version of Visual Studio expected (2017, 2019...). Prior versions are unsupported.
|
||||
target_compile_options(simdjson-internal-flags INTERFACE /WX /W3 /sdl)
|
||||
endif()
|
||||
else()
|
||||
target_compile_options(simdjson-internal-flags INTERFACE -fPIC)
|
||||
target_compile_options(simdjson-internal-flags INTERFACE -Werror -Wall -Wextra -Weffc++)
|
||||
target_compile_options(simdjson-internal-flags INTERFACE -Wsign-compare -Wshadow -Wwrite-strings -Wpointer-arith -Winit-self -Wconversion -Wno-sign-conversion)
|
||||
endif()
|
||||
|
||||
# Optional flags
|
||||
option(SIMDJSON_IMPLEMENTATION_HASWELL "Include the haswell implementation" ON)
|
||||
if(NOT SIMDJSON_IMPLEMENTATION_HASWELL)
|
||||
target_compile_definitions(simdjson-internal-flags INTERFACE SIMDJSON_IMPLEMENTATION_HASWELL=0)
|
||||
endif()
|
||||
option(SIMDJSON_IMPLEMENTATION_WESTMERE "Include the westmere implementation" ON)
|
||||
if(NOT SIMDJSON_IMPLEMENTATION_WESTMERE)
|
||||
target_compile_definitions(simdjson-internal-flags INTERFACE SIMDJSON_IMPLEMENTATION_WESTMERE=0)
|
||||
endif()
|
||||
option(SIMDJSON_IMPLEMENTATION_ARM64 "Include the arm64 implementation" ON)
|
||||
if(NOT SIMDJSON_IMPLEMENTATION_ARM64)
|
||||
target_compile_definitions(simdjson-internal-flags INTERFACE SIMDJSON_IMPLEMENTATION_ARM64=0)
|
||||
endif()
|
||||
option(SIMDJSON_IMPLEMENTATION_FALLBACK "Include the fallback implementation" ON)
|
||||
if(NOT SIMDJSON_IMPLEMENTATION_FALLBACK)
|
||||
target_compile_definitions(simdjson-internal-flags INTERFACE SIMDJSON_IMPLEMENTATION_FALLBACK=0)
|
||||
endif()
|
||||
|
||||
option(SIMDJSON_EXCEPTIONS "Enable simdjson's exception-throwing interface" ON)
|
||||
if(NOT SIMDJSON_EXCEPTIONS)
|
||||
message(STATUS "simdjson exception interface turned off. Code that does not check error codes will not compile.")
|
||||
target_compile_definitions(simdjson-internal-flags INTERFACE SIMDJSON_EXCEPTIONS=0)
|
||||
endif()
|
||||
|
||||
option(SIMDJSON_ENABLE_THREADS "Link with thread support" ON)
|
||||
if(SIMDJSON_ENABLE_THREADS)
|
||||
set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
|
||||
set(THREADS_PREFER_PTHREAD_FLAG TRUE)
|
||||
find_package(Threads REQUIRED)
|
||||
target_link_libraries(simdjson-flags INTERFACE Threads::Threads)
|
||||
target_link_libraries(simdjson-flags INTERFACE ${CMAKE_THREAD_LIBS_INIT})
|
||||
target_compile_options(simdjson-flags INTERFACE ${CMAKE_THREAD_LIBS_INIT})
|
||||
target_compile_definitions(simdjson-flags INTERFACE SIMDJSON_THREADS_ENABLED=1) # This will be set in the code automatically.
|
||||
endif()
|
||||
|
||||
# Some users compile simdjson with thread support but still do not want simdjson to use threads.
|
||||
#
|
||||
# Important : Expect this option to disappear in the future.
|
||||
#
|
||||
option(SIMDJSON_DO_NOT_USE_THREADS_NO_MATTER_WHAT "Whether we enabled thread support or not (SIMDJSON_ENABLE_THREADS), do not use threads.\
|
||||
This option does nothing when thread support is not enabled. We reserve the right to remove this option in a future release in\
|
||||
favor of a runtime approach." OFF)
|
||||
if(SIMDJSON_DO_NOT_USE_THREADS_NO_MATTER_WHAT)
|
||||
target_compile_definitions(simdjson-flags INTERFACE SIMDJSON_DO_NOT_USE_THREADS_NO_MATTER_WHAT=1)
|
||||
endif()
|
||||
|
||||
if(SIMDJSON_USE_LIBCPP)
|
||||
target_link_libraries(simdjson-flags INTERFACE -stdlib=libc++ -lc++abi)
|
||||
# instead of the above line, we could have used
|
||||
# set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -stdlib=libc++ -lc++abi")
|
||||
# The next line is needed empirically.
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++")
|
||||
# we update CMAKE_SHARED_LINKER_FLAGS, this gets updated later as well
|
||||
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -lc++abi")
|
||||
endif(SIMDJSON_USE_LIBCPP)
|
||||
|
||||
# prevent shared libraries from depending on Intel provided libraries
|
||||
if(${CMAKE_C_COMPILER_ID} MATCHES "Intel") # icc / icpc
|
||||
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -static-intel")
|
||||
endif()
|
||||
|
||||
install(TARGETS simdjson-flags EXPORT simdjson-config)
|
||||
install(TARGETS simdjson-internal-flags EXPORT simdjson-config)
|
||||
@@ -0,0 +1,24 @@
|
||||
#
|
||||
# ${SIMDJSON_USER_CMAKECACHE} contains the *user-specified* simdjson options so you can call cmake on
|
||||
# another branch or repository with the same options.
|
||||
#
|
||||
# Not supported on Windows at present, because the only thing that uses it is checkperf, which we
|
||||
# don't run on Windows.
|
||||
#
|
||||
set(SIMDJSON_USER_CMAKECACHE ${CMAKE_CURRENT_BINARY_DIR}/.simdjson-user-CMakeCache.txt)
|
||||
if (MSVC)
|
||||
add_custom_command(
|
||||
OUTPUT ${SIMDJSON_USER_CMAKECACHE}
|
||||
COMMAND findstr SIMDJSON_ ${PROJECT_BINARY_DIR}/CMakeCache.txt > ${SIMDJSON_USER_CMAKECACHE}.tmp
|
||||
COMMAND findstr /v SIMDJSON_LIB_ ${SIMDJSON_USER_CMAKECACHE}.tmp > ${SIMDJSON_USER_CMAKECACHE}
|
||||
VERBATIM # Makes it not do weird escaping with the command
|
||||
)
|
||||
else()
|
||||
add_custom_command(
|
||||
OUTPUT ${SIMDJSON_USER_CMAKECACHE}
|
||||
COMMAND grep SIMDJSON_ ${PROJECT_BINARY_DIR}/CMakeCache.txt > ${SIMDJSON_USER_CMAKECACHE}.tmp
|
||||
COMMAND grep -v SIMDJSON_LIB_ ${SIMDJSON_USER_CMAKECACHE}.tmp > ${SIMDJSON_USER_CMAKECACHE}
|
||||
VERBATIM # Makes it not do weird escaping with the command
|
||||
)
|
||||
endif()
|
||||
add_custom_target(simdjson-user-cmakecache DEPENDS ${SIMDJSON_USER_CMAKECACHE})
|
||||
Vendored
+89
@@ -0,0 +1,89 @@
|
||||
# Initializes a git submodule if it hasn't been initialized before
|
||||
|
||||
|
||||
find_package(Git QUIET) # We want the library to build even if git is missing
|
||||
if ((Git_FOUND) AND (SIMDJSON_IS_UNDER_GIT))
|
||||
message(STATUS "Git is available.")
|
||||
# Does NOT attempt to update or otherwise modify git submodules that are already initialized.
|
||||
function(initialize_submodule DIRECTORY)
|
||||
if(NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${DIRECTORY}/.git)
|
||||
message(STATUS "${CMAKE_CURRENT_SOURCE_DIR}/${DIRECTORY}/.git does not exist. Initializing ${DIRECTORY} submodule ...")
|
||||
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init ${CMAKE_CURRENT_SOURCE_DIR}/${DIRECTORY}
|
||||
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
|
||||
RESULT_VARIABLE GIT_EXIT_CODE)
|
||||
if(NOT GIT_EXIT_CODE EQUAL "0")
|
||||
message(FATAL_ERROR "${GIT_EXECUTABLE} submodule update --init dependencies/${DIRECTORY} failed with exit code ${GIT_EXIT_CODE}, please checkout submodules")
|
||||
endif()
|
||||
endif()
|
||||
endfunction(initialize_submodule)
|
||||
|
||||
if (SIMDJSON_GOOGLE_BENCHMARKS)
|
||||
message (STATUS "'SIMDJSON_GOOGLE_BENCHMARKS' is requested, configuring..." )
|
||||
option(BENCHMARK_ENABLE_TESTING OFF)
|
||||
set(BENCHMARK_ENABLE_TESTING OFF)
|
||||
option(BENCHMARK_ENABLE_INSTALL OFF)
|
||||
set(BENCHMARK_ENABLE_INSTALL OFF)
|
||||
initialize_submodule(benchmark)
|
||||
add_subdirectory(benchmark)
|
||||
endif()
|
||||
|
||||
if (SIMDJSON_COMPETITION)
|
||||
initialize_submodule(cJSON)
|
||||
add_library(competition-cJSON INTERFACE)
|
||||
target_include_directories(competition-cJSON INTERFACE cJSON)
|
||||
|
||||
initialize_submodule(fastjson)
|
||||
add_library(competition-fastjson INTERFACE)
|
||||
target_include_directories(competition-fastjson INTERFACE fastjson/src fastjson/include)
|
||||
|
||||
initialize_submodule(gason)
|
||||
add_library(competition-gason INTERFACE)
|
||||
target_include_directories(competition-gason INTERFACE gason/src)
|
||||
|
||||
initialize_submodule(jsmn)
|
||||
add_library(competition-jsmn INTERFACE)
|
||||
target_include_directories(competition-jsmn INTERFACE jsmn)
|
||||
|
||||
initialize_submodule(json)
|
||||
add_library(competition-json INTERFACE)
|
||||
target_include_directories(competition-json INTERFACE json/single_include)
|
||||
|
||||
initialize_submodule(json11)
|
||||
add_library(competition-json11 INTERFACE)
|
||||
target_include_directories(competition-json11 INTERFACE json11)
|
||||
|
||||
add_library(competition-jsoncppdist INTERFACE)
|
||||
target_include_directories(competition-jsoncppdist INTERFACE jsoncppdist)
|
||||
|
||||
initialize_submodule(rapidjson)
|
||||
add_library(competition-rapidjson INTERFACE)
|
||||
target_include_directories(competition-rapidjson INTERFACE rapidjson/include)
|
||||
|
||||
initialize_submodule(sajson)
|
||||
add_library(competition-sajson INTERFACE)
|
||||
target_include_directories(competition-sajson INTERFACE sajson/include)
|
||||
|
||||
initialize_submodule(ujson4c)
|
||||
add_library(competition-ujson4c ujson4c/src/ujdecode.c)
|
||||
target_include_directories(competition-ujson4c PUBLIC ujson4c/3rdparty ujson4c/src)
|
||||
|
||||
add_library(competition-core INTERFACE)
|
||||
target_link_libraries(competition-core INTERFACE competition-json competition-rapidjson competition-sajson competition-cJSON competition-jsmn)
|
||||
|
||||
add_library(competition-all INTERFACE)
|
||||
target_link_libraries(competition-all INTERFACE competition-core competition-jsoncppdist competition-json11 competition-fastjson competition-gason competition-ujson4c)
|
||||
endif()
|
||||
|
||||
initialize_submodule(cxxopts)
|
||||
message(STATUS "We acquired cxxopts and we are adding it as a library and target.")
|
||||
add_library(cxxopts INTERFACE)
|
||||
target_include_directories(cxxopts INTERFACE cxxopts/include)
|
||||
else()
|
||||
message(STATUS "Git is unavailable.")
|
||||
if(SIMDJSON_COMPETITION)
|
||||
message (STATUS "'SIMDJSON_COMPETITION' is requested, but we cannot download the remote repositories." )
|
||||
endif()
|
||||
if(SIMDJSON_GOOGLE_BENCHMARKS)
|
||||
message (STATUS "'SIMDJSON_GOOGLE_BENCHMARKS' is requested, but we cannot download the remote repositories." )
|
||||
endif()
|
||||
endif()
|
||||
+1
Submodule dependencies/cxxopts added at 794c975287
+388
-66
@@ -3,20 +3,34 @@ The Basics
|
||||
|
||||
An overview of what you need to know to use simdjson, with examples.
|
||||
|
||||
* [Requirements](#requirements)
|
||||
* [Including simdjson](#including-simdjson)
|
||||
* [Using simdjson as a CMake dependency](#using-simdjson-as-a-cmake-dependency)
|
||||
* [The Basics: Loading and Parsing JSON Documents](#the-basics-loading-and-parsing-json-documents)
|
||||
* [Using the Parsed JSON](#using-the-parsed-json)
|
||||
* [C++11 Support and string_view](#c++11-support-and-string_view)
|
||||
* [C++17 Support](#c++17-support)
|
||||
* [Minifying JSON strings without parsing](#minifying-json-strings-without-parsing)
|
||||
* [UTF-8 validation (alone)](#utf-8-validation-alone)
|
||||
* [JSON Pointer](#json-pointer)
|
||||
* [Error Handling](#error-handling)
|
||||
* [Error Handling Example](#error-handling-example)
|
||||
* [Exceptions](#exceptions)
|
||||
* [Error Handling Example](#error-handling-example)
|
||||
* [Exceptions](#exceptions)
|
||||
* [Tree Walking and JSON Element Types](#tree-walking-and-json-element-types)
|
||||
* [Newline-Delimited JSON (ndjson) and JSON lines](#newline-delimited-json-ndjson-and-json-lines)
|
||||
* [Thread Safety](#thread-safety)
|
||||
|
||||
|
||||
Requirements
|
||||
------------------
|
||||
|
||||
- A recent compiler (LLVM clang6 or better, GNU GCC 7 or better) on a 64-bit (ARM or x64 Intel/AMD) POSIX systems such as macOS, freeBSD or Linux. We require that the compiler supports the C++11 standard or better.
|
||||
- Visual Studio 2017 or better under 64-bit Windows. Users should target a 64-bit build (x64) instead of a 32-bit build (x86). We support the LLVM clang compiler under Visual Studio (clangcl) as well as as the regular Visual Studio compiler. We also support MinGW 64-bit under Windows.
|
||||
|
||||
Including simdjson
|
||||
------------------
|
||||
|
||||
To include simdjson, copy [simdjson.h](singleheader/simdjson.h) and [simdjson.cpp](singleheader/simdjson.cpp)
|
||||
To include simdjson, copy [simdjson.h](/singleheader/simdjson.h) and [simdjson.cpp](/singleheader/simdjson.cpp)
|
||||
into your project. Then include it in your project with:
|
||||
|
||||
```c++
|
||||
@@ -27,9 +41,33 @@ using namespace simdjson; // optional
|
||||
You can compile with:
|
||||
|
||||
```
|
||||
c++ myproject.cpp simdjson.cpp --std=c++17
|
||||
c++ myproject.cpp simdjson.cpp
|
||||
```
|
||||
|
||||
Note:
|
||||
- Users on macOS and other platforms were default compilers do not provide C++11 compliant by default should request it with the appropriate flag (e.g., `c++ myproject.cpp simdjson.cpp`).
|
||||
- Visual Studio users should compile with the `_CRT_SECURE_NO_WARNINGS` flag to avoid warnings with respect to our use of standard C functions such as `fopen`.
|
||||
|
||||
Using simdjson as a CMake dependency
|
||||
------------------
|
||||
|
||||
You can include the simdjson repository as a folder in your CMake project. In the parent
|
||||
`CMakeLists.txt`, include the following lines:
|
||||
|
||||
```
|
||||
set(SIMDJSON_JUST_LIBRARY ON CACHE STRING "Build just the library, nothing else." FORCE)
|
||||
add_subdirectory(simdjson EXCLUDE_FROM_ALL)
|
||||
```
|
||||
|
||||
Elsewhere in your project, you can declare dependencies on simdjson with lines such as these:
|
||||
|
||||
```
|
||||
add_executable(myprogram myprogram.cpp)
|
||||
target_link_libraries(myprogram simdjson)
|
||||
```
|
||||
|
||||
See [our CMake demonstration](https://github.com/simdjson/cmakedemo).
|
||||
|
||||
The Basics: Loading and Parsing JSON Documents
|
||||
----------------------------------------------
|
||||
|
||||
@@ -49,16 +87,32 @@ dom::parser parser;
|
||||
dom::element doc = parser.parse("[1,2,3]"_padded); // parse a string
|
||||
```
|
||||
|
||||
The parsed document resulting from the `parser.load` and `parser.parse` calls depends on the `parser` instance. Thus the `parser` instance must remain in scope. Furthermore, you must have at most one parsed document in play per `parser` instance.
|
||||
|
||||
During the`load` or `parse` calls, neither the input file nor the input string are ever modified. After calling `load` or `parse`, the source (either a file or a string) can be safely discarded. All of the JSON data is stored in the `parser` instance. The parsed document is also immutable in simdjson: you do not modify it by accessing it.
|
||||
|
||||
For best performance, a `parser` instance should be reused over several files: otherwise you will needlessly reallocate memory, an expensive process. It is also possible to avoid entirely memory allocations during parsing when using simdjson. [See our performance notes for details](performance.md).
|
||||
|
||||
|
||||
Using the Parsed JSON
|
||||
---------------------
|
||||
|
||||
Once you have an element, you can navigate it with idiomatic C++ iterators, operators and casts.
|
||||
|
||||
* **Extracting Values:** You can cast a JSON element to a native type: `double(element)` or
|
||||
* **Extracting Values (with exceptions):** You can cast a JSON element to a native type: `double(element)` or
|
||||
`double x = json_element`. This works for double, uint64_t, int64_t, bool,
|
||||
dom::object and dom::array. You can also use is_*typename*()` to test if it is a
|
||||
given type, and as_*typename*() to do the cast and return an error code on failure instead of an
|
||||
exception.
|
||||
dom::object and dom::array. An exception is thrown if the cast is not possible.
|
||||
* **Extracting Values (without expceptions):** 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`,
|
||||
`dom::object` and `dom::array`) and pass it by reference to `get()` which gives you back an error code: e.g.,
|
||||
```c++
|
||||
simdjson::error_code error;
|
||||
simdjson::padded_string numberstring = "1.2"_padded; // our JSON input ("1.2")
|
||||
simdjson::dom::parser parser;
|
||||
double value; // variable where we store the value to be parsed
|
||||
error = parser.parse(numberstring).get(value);
|
||||
if (error) { std::cerr << error << std::endl; return EXIT_FAILURE; }
|
||||
std::cout << "I parsed " << value << " from " << numberstring.data() << std::endl;
|
||||
```
|
||||
* **Field Access:** To get the value of the "foo" field in an object, use `object["foo"]`.
|
||||
* **Array Iteration:** To iterate through an array, use `for (auto value : array) { ... }`. If you
|
||||
know the type of the value, you can cast it right there, too! `for (double value : array) { ... }`
|
||||
@@ -66,7 +120,13 @@ Once you have an element, you can navigate it with idiomatic C++ iterators, oper
|
||||
* **Array Index:** To get at an array value by index, use the at() method: `array.at(0)` gets the
|
||||
first element.
|
||||
> Note that array[0] does not compile, because implementing [] gives the impression indexing is a
|
||||
> O(1) operation, which it is not presently in simdjson.
|
||||
> O(1) operation, which it is not presently in simdjson. Instead, you should iterate over the elements
|
||||
> using a for-loop, as in our examples.
|
||||
* **Array and Object size** Given an array or an object, you can get its size (number of elements or keys)
|
||||
with the `size()` method.
|
||||
* **Checking an Element Type:** You can check an element's type with `element.type()`. It
|
||||
returns an `element_type`.
|
||||
|
||||
|
||||
Here are some examples of all of the above:
|
||||
|
||||
@@ -77,10 +137,9 @@ auto cars_json = R"( [
|
||||
{ "make": "Toyota", "model": "Tercel", "year": 1999, "tire_pressure": [ 29.8, 30.0, 30.2, 30.5 ] }
|
||||
] )"_padded;
|
||||
dom::parser parser;
|
||||
dom::array cars = parser.parse(cars_json).get<dom::array>();
|
||||
|
||||
// Iterating through an array of objects
|
||||
for (dom::object car : cars) {
|
||||
for (dom::object car : parser.parse(cars_json)) {
|
||||
// Accessing a field by name
|
||||
cout << "Make/Model: " << car["make"] << "/" << car["model"] << endl;
|
||||
|
||||
@@ -96,12 +155,131 @@ for (dom::object car : cars) {
|
||||
cout << "- Average tire pressure: " << (total_tire_pressure / 4) << endl;
|
||||
|
||||
// Writing out all the information about the car
|
||||
for (auto [key, value] : car) {
|
||||
cout << "- " << key << ": " << value << endl;
|
||||
for (auto field : car) {
|
||||
cout << "- " << field.key << ": " << field.value << endl;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Here is a different example illustrating the same ideas:
|
||||
|
||||
```C++
|
||||
auto abstract_json = R"( [
|
||||
{ "12345" : {"a":12.34, "b":56.78, "c": 9998877} },
|
||||
{ "12545" : {"a":11.44, "b":12.78, "c": 11111111} }
|
||||
] )"_padded;
|
||||
dom::parser parser;
|
||||
|
||||
// Parse and iterate through an array of objects
|
||||
for (dom::object obj : parser.parse(abstract_json)) {
|
||||
for(const auto& key_value : obj) {
|
||||
cout << "key: " << key_value.key << " : ";
|
||||
dom::object innerobj = key_value.value;
|
||||
cout << "a: " << double(innerobj["a"]) << ", ";
|
||||
cout << "b: " << double(innerobj["b"]) << ", ";
|
||||
cout << "c: " << int64_t(innerobj["c"]) << endl;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And another one:
|
||||
|
||||
|
||||
```C++
|
||||
auto abstract_json = R"(
|
||||
{ "str" : { "123" : {"abc" : 3.14 } } } )"_padded;
|
||||
dom::parser parser;
|
||||
double v = parser.parse(abstract_json)["str"]["123"]["abc"];
|
||||
cout << "number: " << v << endl;
|
||||
```
|
||||
|
||||
|
||||
C++11 Support and string_view
|
||||
-------------
|
||||
|
||||
The simdjson library builds on compilers supporting the [C++11 standard](https://en.wikipedia.org/wiki/C%2B%2B11). It is also a strict requirement: we have no plan to support older C++ compilers.
|
||||
|
||||
We represent parsed strings in simdjson using the `std::string_view` class. It avoids
|
||||
the need to copy the data, as would be necessary with the `std::string` class. It also
|
||||
avoids the pitfalls of null-terminated C strings.
|
||||
|
||||
The `std::string_view` class has become standard as part of C++17 but it is not always available
|
||||
on compilers which only supports C++11. When we detect that `string_view` is natively
|
||||
available, we define the macro `SIMDJSON_HAS_STRING_VIEW`.
|
||||
|
||||
When we detect that it is unavailable,
|
||||
we use [string-view-lite](https://github.com/martinmoene/string-view-lite) as a
|
||||
substitute. In such cases, we use the type alias `using string_view = nonstd::string_view;` to
|
||||
offer the same API, irrespective of the compiler and standard library. The macro
|
||||
`SIMDJSON_HAS_STRING_VIEW` will be *undefined* to indicate that we emulate `string_view`.
|
||||
|
||||
|
||||
C++17 Support
|
||||
-------------
|
||||
|
||||
While the simdjson library can be used in any project using C++ 11 and above, field iteration has special support C++ 17's destructuring syntax. For example:
|
||||
|
||||
```c++
|
||||
padded_string json = R"( { "foo": 1, "bar": 2 } )"_padded;
|
||||
dom::parser parser;
|
||||
dom::object object;
|
||||
auto error = parser.parse(json).get(object);
|
||||
if (error) { cerr << error << endl; return; }
|
||||
for (auto [key, value] : object) {
|
||||
cout << key << " = " << value << endl;
|
||||
}
|
||||
```
|
||||
|
||||
For comparison, here is the C++ 11 version of the same code:
|
||||
|
||||
```c++
|
||||
// C++ 11 version for comparison
|
||||
padded_string json = R"( { "foo": 1, "bar": 2 } )"_padded;
|
||||
dom::parser parser;
|
||||
dom::object object;
|
||||
auto error = parser.parse(json).get(object);
|
||||
if (!error) { cerr << error << endl; return; }
|
||||
for (dom::key_value_pair field : object) {
|
||||
cout << field.key << " = " << field.value << endl;
|
||||
}
|
||||
```
|
||||
|
||||
Minifying JSON strings without parsing
|
||||
----------------------
|
||||
|
||||
In some cases, you may have valid JSON strings that you do not wish to parse but that you wish to minify. That is, you wish to remove all unnecessary spaces. We have a fast function for this purpose (`minify`). This function does not validate your content, and it does not parse it. Instead, it assumes that your string is valid UTF-8. It is much faster than parsing the string and re-serializing it in minified form. Usage is relatively simple. You must pass an input pointer with a length parameter, as well as an output pointer and an output length parameter (by reference). The output length parameter is not read, but written to. The output pointer should point to a valid memory region that is slightly overallocated (by `simdjson::SIMDJSON_PADDING`) compared to the original string length. The input pointer and input length are read, but not written to.
|
||||
|
||||
```C++
|
||||
// Starts with a valid JSON document as a string.
|
||||
// It does not have to be null-terminated.
|
||||
const char * some_string = "[ 1, 2, 3, 4] ";
|
||||
size_t length = strlen(some_string);
|
||||
// Create a buffer to receive the minified string. Make sure that there is enough room,
|
||||
// including some padding (simdjson::SIMDJSON_PADDING).
|
||||
std::unique_ptr<char[]> buffer{new(std::nothrow) char[length + simdjson::SIMDJSON_PADDING]};
|
||||
size_t new_length{}; // It will receive the minified length.
|
||||
auto error = simdjson::minify(some_string, length, buffer.get(), new_length);
|
||||
// The buffer variable now has "[1,2,3,4]" and new_length has value 9.
|
||||
```
|
||||
|
||||
Though it does not validate the JSON input, it will detect when the document ends with an unterminated string. E.g., it would refuse to minify the string `"this string is not terminated` because of the missing final quote.
|
||||
|
||||
|
||||
UTF-8 validation (alone)
|
||||
----------------------
|
||||
|
||||
The simdjson library has fast functions to validate UTF-8 strings. They are many times faster than most functions commonly found in libraries. You can use our fast functions, even if you do not care about JSON.
|
||||
|
||||
```C++
|
||||
const char * some_string = "[ 1, 2, 3, 4] ";
|
||||
size_t length = strlen(some_string);
|
||||
bool is_ok = simdjson::validate_utf8(some_string, length);
|
||||
```
|
||||
|
||||
The UTF-8 validation function merely checks that the input is valid UTF-8: it works with strings in general, not just JSON strings.
|
||||
|
||||
Your input string does not need any padding. Any string will do. The `validate_utf8` function does not do any memory allocation on the heap, and it does not throw exceptions.
|
||||
|
||||
JSON Pointer
|
||||
------------
|
||||
|
||||
@@ -123,28 +301,38 @@ Error Handling
|
||||
--------------
|
||||
|
||||
All simdjson APIs that can fail return `simdjson_result<T>`, which is a <value, error_code>
|
||||
pair. The error codes and values can be accessed directly, reading the error like so:
|
||||
pair. You can retrieve the value with .get(), like so:
|
||||
|
||||
```c++
|
||||
auto [doc, error] = parser.parse(json); // doc is a dom::element
|
||||
dom::element doc;
|
||||
auto error = parser.parse(json).get(doc);
|
||||
if (error) { cerr << error << endl; exit(1); }
|
||||
// Use document here now that we've checked for the error
|
||||
```
|
||||
|
||||
When you use the code this way, it is your responsibility to check for error before using the
|
||||
result: if there is an error, the result value will not be valid and using it will caused undefined
|
||||
behavior.
|
||||
|
||||
> Note: because of the way `auto [x, y]` works in C++, you have to define new variables each time you
|
||||
> use it. If your project treats aliased, this means you can't use the same names in `auto [x, error]`
|
||||
> without triggering warnings or error (and particularly can't use the word "error" every time). To
|
||||
> circumvent this, you can use this instead:
|
||||
>
|
||||
> ```c++
|
||||
> dom::element doc;
|
||||
> simdjson::error_code error;
|
||||
> parser.parse(json).tie(doc, error); // <-- Assigns to doc and error just like "auto [doc, error]"
|
||||
> ```
|
||||
We can write a "quick start" example where we attempt to parse a file and access some data, without triggering exceptions:
|
||||
|
||||
```C++
|
||||
#include "simdjson.h"
|
||||
|
||||
int main(void) {
|
||||
simdjson::dom::parser parser;
|
||||
|
||||
simdjson::dom::element tweets;
|
||||
auto error = parser.load("twitter.json").get(tweets);
|
||||
if (error) { std::cerr << error << std::endl; return EXIT_FAILURE; }
|
||||
|
||||
simdjson::dom::element res;
|
||||
if ((error = tweets["search_metadata"]["count"].get(res))) {
|
||||
std::cerr << "could not access keys" << std::endl;
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
std::cout << res << " results." << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
### Error Handling Example
|
||||
|
||||
@@ -152,50 +340,117 @@ This is how the example in "Using the Parsed JSON" could be written using only e
|
||||
|
||||
```c++
|
||||
auto cars_json = R"( [
|
||||
{ "make": "Toyota", "model": "Camry", "year": 2018, "tire_pressure": [ 40.1, 39.9, 37.7, 40.4 ] },
|
||||
{ "make": "Kia", "model": "Soul", "year": 2012, "tire_pressure": [ 30.1, 31.0, 28.6, 28.7 ] },
|
||||
{ "make": "Toyota", "model": "Tercel", "year": 1999, "tire_pressure": [ 29.8, 30.0, 30.2, 30.5 ] }
|
||||
{ "make": "Toyota", "model": "Camry", "year": 2018, "tire_pressure": [ 40.1, 39.9, 37.7, 40.4 ] },
|
||||
{ "make": "Kia", "model": "Soul", "year": 2012, "tire_pressure": [ 30.1, 31.0, 28.6, 28.7 ] },
|
||||
{ "make": "Toyota", "model": "Tercel", "year": 1999, "tire_pressure": [ 29.8, 30.0, 30.2, 30.5 ] }
|
||||
] )"_padded;
|
||||
dom::parser parser;
|
||||
auto [cars, error] = parser.parse(cars_json).get<dom::array>();
|
||||
dom::array cars;
|
||||
auto error = parser.parse(cars_json).get(cars);
|
||||
if (error) { cerr << error << endl; exit(1); }
|
||||
|
||||
// Iterating through an array of objects
|
||||
for (dom::element car_element : cars) {
|
||||
dom::object car;
|
||||
car_element.get<dom::object>().tie(car, error);
|
||||
if (error) { cerr << error << endl; exit(1); }
|
||||
dom::object car;
|
||||
if ((error = car_element.get(car))) { cerr << error << endl; exit(1); }
|
||||
|
||||
// Accessing a field by name
|
||||
dom::element make, model;
|
||||
car["make"].tie(make, error);
|
||||
if (error) { cerr << error << endl; exit(1); }
|
||||
car["model"].tie(model, error);
|
||||
if (error) { cerr << error << endl; exit(1); }
|
||||
cout << "Make/Model: " << make << "/" << model << endl;
|
||||
// Accessing a field by name
|
||||
std::string_view make, model;
|
||||
if ((error = car["make"].get(make))) { cerr << error << endl; exit(1); }
|
||||
if ((error = car["model"].get(model))) { cerr << error << endl; exit(1); }
|
||||
cout << "Make/Model: " << make << "/" << model << endl;
|
||||
|
||||
// Casting a JSON element to an integer
|
||||
uint64_t year;
|
||||
car["year"].get<uint64_t>().tie(year, error);
|
||||
if (error) { cerr << error << endl; exit(1); }
|
||||
cout << "- This car is " << 2020 - year << "years old." << endl;
|
||||
// Casting a JSON element to an integer
|
||||
uint64_t year;
|
||||
if ((error = car["year"].get(year))) { cerr << error << endl; exit(1); }
|
||||
cout << "- This car is " << 2020 - year << "years old." << endl;
|
||||
|
||||
// Iterating through an array of floats
|
||||
double total_tire_pressure = 0;
|
||||
dom::array tire_pressure_array;
|
||||
car["tire_pressure"].get<dom::array>().tie(tire_pressure_array, error);
|
||||
if (error) { cerr << error << endl; exit(1); }
|
||||
for (dom::element tire_pressure_element : tire_pressure_array) {
|
||||
double tire_pressure;
|
||||
tire_pressure_element.get<double>().tie(tire_pressure, error);
|
||||
if (error) { cerr << error << endl; exit(1); }
|
||||
total_tire_pressure += tire_pressure;
|
||||
// Iterating through an array of floats
|
||||
double total_tire_pressure = 0;
|
||||
dom::array tire_pressure_array;
|
||||
if ((error = car["tire_pressure"].get(tire_pressure_array))) { cerr << error << endl; exit(1); }
|
||||
for (dom::element tire_pressure_element : tire_pressure_array) {
|
||||
double tire_pressure;
|
||||
if ((error = tire_pressure_element.get(tire_pressure))) { cerr << error << endl; exit(1); }
|
||||
total_tire_pressure += tire_pressure;
|
||||
}
|
||||
cout << "- Average tire pressure: " << (total_tire_pressure / 4) << endl;
|
||||
|
||||
// Writing out all the information about the car
|
||||
for (auto field : car) {
|
||||
cout << "- " << field.key << ": " << field.value << endl;
|
||||
}
|
||||
}
|
||||
cout << "- Average tire pressure: " << (total_tire_pressure / 4) << endl;
|
||||
```
|
||||
|
||||
// Writing out all the information about the car
|
||||
for (auto [key, value] : car) {
|
||||
cout << "- " << key << ": " << value << endl;
|
||||
Here is another example:
|
||||
|
||||
```C++
|
||||
auto abstract_json = R"( [
|
||||
{ "12345" : {"a":12.34, "b":56.78, "c": 9998877} },
|
||||
{ "12545" : {"a":11.44, "b":12.78, "c": 11111111} }
|
||||
] )"_padded;
|
||||
dom::parser parser;
|
||||
dom::array array;
|
||||
auto error = parser.parse(abstract_json).get(array);
|
||||
if (error) { cerr << error << endl; exit(1); }
|
||||
// Iterate through an array of objects
|
||||
for (dom::element elem : array) {
|
||||
dom::object obj;
|
||||
if ((error = elem.get(obj))) { cerr << error << endl; exit(1); }
|
||||
for (auto & key_value : obj) {
|
||||
cout << "key: " << key_value.key << " : ";
|
||||
dom::object innerobj;
|
||||
if ((error = key_value.value.get(innerobj))) { cerr << error << endl; exit(1); }
|
||||
|
||||
double va, vb;
|
||||
if ((error = innerobj["a"].get(va))) { cerr << error << endl; exit(1); }
|
||||
cout << "a: " << va << ", ";
|
||||
if ((error = innerobj["b"].get(vc))) { cerr << error << endl; exit(1); }
|
||||
cout << "b: " << vb << ", ";
|
||||
|
||||
int64_t vc;
|
||||
if ((error = innerobj["c"].get(vc))) { cerr << error << endl; exit(1); }
|
||||
cout << "c: " << vc << endl;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And another one:
|
||||
|
||||
```C++
|
||||
auto abstract_json = R"(
|
||||
{ "str" : { "123" : {"abc" : 3.14 } } } )"_padded;
|
||||
dom::parser parser;
|
||||
double v;
|
||||
auto error = parser.parse(abstract_json)["str"]["123"]["abc"].get(v);
|
||||
if (error) { cerr << error << endl; exit(1); }
|
||||
cout << "number: " << v << endl;
|
||||
```
|
||||
|
||||
Notice how we can string several operations (`parser.parse(abstract_json)["str"]["123"]["abc"].get(v)`) and only check for the error once, a strategy we call *error chaining*.
|
||||
|
||||
The next two functions will take as input a JSON document containing an array with a single element, either a string or a number. They return true upon success.
|
||||
|
||||
```C++
|
||||
simdjson::dom::parser parser{};
|
||||
|
||||
bool parse_double(const char *j, double &d) {
|
||||
auto error = parser.parse(j, std::strlen(j))
|
||||
.at(0)
|
||||
.get(d, error);
|
||||
if (error) { return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
bool parse_string(const char *j, std::string &s) {
|
||||
std::string_view answer;
|
||||
auto error = parser.parse(j,strlen(j))
|
||||
.at(0)
|
||||
.get(answer, error);
|
||||
if (error) { return false; }
|
||||
s.assign(answer.data(), answer.size());
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
@@ -210,6 +465,60 @@ dom::element doc = parser.parse(json); // Throws an exception if there was an er
|
||||
When used this way, a `simdjson_error` exception will be thrown if an error occurs, preventing the
|
||||
program from continuing if there was an error.
|
||||
|
||||
Tree Walking and JSON Element Types
|
||||
-----------------------------------
|
||||
|
||||
Sometimes you don't necessarily have a document with a known type, and are trying to generically
|
||||
inspect or walk over JSON elements. To do that, you can use iterators and the type() method. For
|
||||
example, here's a quick and dirty recursive function that verbosely prints the JSON document as JSON
|
||||
(* ignoring nuances like trailing commas and escaping strings, for brevity's sake):
|
||||
|
||||
```c++
|
||||
void print_json(dom::element element) {
|
||||
switch (element.type()) {
|
||||
case dom::element_type::ARRAY:
|
||||
cout << "[";
|
||||
for (dom::element child : dom::array(element)) {
|
||||
print_json(child);
|
||||
cout << ",";
|
||||
}
|
||||
cout << "]";
|
||||
break;
|
||||
case dom::element_type::OBJECT:
|
||||
cout << "{";
|
||||
for (dom::key_value_pair field : dom::object(element)) {
|
||||
cout << "\"" << field.key << "\": ";
|
||||
print_json(field.value);
|
||||
}
|
||||
cout << "}";
|
||||
break;
|
||||
case dom::element_type::INT64:
|
||||
cout << int64_t(element) << endl;
|
||||
break;
|
||||
case dom::element_type::UINT64:
|
||||
cout << uint64_t(element) << endl;
|
||||
break;
|
||||
case dom::element_type::DOUBLE:
|
||||
cout << double(element) << endl;
|
||||
break;
|
||||
case dom::element_type::STRING:
|
||||
cout << std::string_view(element) << endl;
|
||||
break;
|
||||
case dom::element_type::BOOL:
|
||||
cout << bool(element) << endl;
|
||||
break;
|
||||
case dom::element_type::NULL_VALUE:
|
||||
cout << "null" << endl;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void basics_treewalk_1() {
|
||||
dom::parser parser;
|
||||
print_json(parser.load("twitter.json"));
|
||||
}
|
||||
```
|
||||
|
||||
Newline-Delimited JSON (ndjson) and JSON lines
|
||||
----------------------------------------------
|
||||
|
||||
@@ -217,7 +526,7 @@ The simdjson library also support multithreaded JSON streaming through a large f
|
||||
smaller JSON documents in either [ndjson](http://ndjson.org) or [JSON lines](http://jsonlines.org)
|
||||
format. If your JSON documents all contain arrays or objects, we even support direct file
|
||||
concatenation without whitespace. The concatenated file has no size restrictions (including larger
|
||||
than 4GB), though each individual document must be less than 4GB.
|
||||
than 4GB), though each individual document must be no larger than 4 GB.
|
||||
|
||||
Here is a simple example, given "x.json" with this content:
|
||||
|
||||
@@ -229,7 +538,8 @@ Here is a simple example, given "x.json" with this content:
|
||||
|
||||
```c++
|
||||
dom::parser parser;
|
||||
for (dom::element doc : parser.load_many(filename)) {
|
||||
dom::document_stream docs = parser.load_many(filename);
|
||||
for (dom::element doc : docs) {
|
||||
cout << doc["foo"] << endl;
|
||||
}
|
||||
// Prints 1 2 3
|
||||
@@ -237,16 +547,28 @@ for (dom::element doc : parser.load_many(filename)) {
|
||||
|
||||
In-memory ndjson strings can be parsed as well, with `parser.parse_many(string)`.
|
||||
|
||||
Both `load_many` and `parse_many` take an optional parameter `size_t batch_size` which defines the window processing size. It is set by default to a large value (`1000000` corresponding to 1 MB). None of your JSON documents should exceed this window size, or else you will get the error `simdjson::CAPACITY`. You cannot set this window size larger than 4 GB: you will get the error `simdjson::CAPACITY`. The smaller the window size is, the less memory the function will use. Setting the window size too small (e.g., less than 100 kB) may also impact performance negatively. Leaving it to 1 MB is expected to be a good choice, unless you have some larger documents.
|
||||
|
||||
See [parse_many.md](parse_many.md) for detailed information and design.
|
||||
|
||||
Thread Safety
|
||||
-------------
|
||||
|
||||
The simdjson library is mostly single-threaded. Thread safety is the responsibility of the caller:
|
||||
it is unsafe to reuse a dom::parser object between different threads.
|
||||
We built simdjson with thread safety in mind.
|
||||
|
||||
simdjson's CPU detection, which runs the first time parsing is attempted and switches to the fastest
|
||||
The simdjson library is single-threaded except for [`parse_many`](parse_many.md) which may use secondary threads under its control when the library is compiled with thread support.
|
||||
|
||||
|
||||
We recommend using one `dom::parser` object per thread in which case the library is thread-safe.
|
||||
It is unsafe to reuse a `dom::parser` object between different threads.
|
||||
The parsed results (`dom::document`, `dom::element`, `array`, `object`) depend on the `dom::parser`, etc. therefore it is also potentially unsafe to use the result of the parsing between different threads.
|
||||
|
||||
The CPU detection, which runs the first time parsing is attempted and switches to the fastest
|
||||
parser for your CPU, is transparent and thread-safe.
|
||||
|
||||
The json stream parser is threaded, using a second thread under its own control. Like the single
|
||||
document parser
|
||||
Backwards Compatibility
|
||||
-----------------------
|
||||
|
||||
The only header file supported by simdjson is `simdjson.h`. Older versions of simdjson published a
|
||||
number of other include files such as `document.h` or `ParsedJson.h` alongside `simdjson.h`; these headers
|
||||
may be moved or removed in future versions.
|
||||
|
||||
@@ -0,0 +1,556 @@
|
||||
The Basics
|
||||
==========
|
||||
|
||||
An overview of what you need to know to use simdjson, with examples.
|
||||
|
||||
|
||||
Requirements
|
||||
------------------
|
||||
|
||||
- A recent compiler (LLVM clang6 or better, GNU GCC 7 or better) on a 64-bit (ARM or x64 Intel/AMD) POSIX systems such as macOS, freeBSD or Linux. We require that the compiler supports the C++11 standard or better.
|
||||
- Visual Studio 2017 or better under 64-bit Windows. Users should target a 64-bit build (x64) instead of a 32-bit build (x86). We support the LLVM clang compiler under Visual Studio (clangcl) as well as as the regular Visual Studio compiler.
|
||||
|
||||
Including simdjson
|
||||
------------------
|
||||
|
||||
To include simdjson, copy the simdjson.h and simdjson.cpp files from the singleheader directory
|
||||
into your project. Then include the header file in your project with:
|
||||
|
||||
```
|
||||
#include "simdjson.h"
|
||||
using namespace simdjson; // optional
|
||||
```
|
||||
|
||||
You can compile with:
|
||||
|
||||
```
|
||||
c++ myproject.cpp simdjson.cpp
|
||||
```
|
||||
|
||||
Note:
|
||||
- Users on macOS and other platforms were default compilers do not provide C++11 compliant by default should request it with the appropriate flag (e.g., `c++ myproject.cpp simdjson.cpp`).
|
||||
- Visual Studio users should compile with the `_CRT_SECURE_NO_WARNINGS` flag to avoid warnings with respect to our use of standard C functions such as `fopen`.
|
||||
|
||||
Using simdjson as a CMake dependency
|
||||
------------------
|
||||
|
||||
You can include the simdjson repository as a folder in your CMake project. In the parent
|
||||
`CMakeLists.txt`, include the following lines:
|
||||
|
||||
```
|
||||
set(SIMDJSON_JUST_LIBRARY ON CACHE STRING "Build just the library, nothing else." FORCE)
|
||||
add_subdirectory(simdjson EXCLUDE_FROM_ALL)
|
||||
```
|
||||
|
||||
Elsewhere in your project, you can declare dependencies on simdjson with lines such as these:
|
||||
|
||||
```
|
||||
add_executable(myprogram myprogram.cpp)
|
||||
target_link_libraries(myprogram simdjson)
|
||||
```
|
||||
|
||||
See [our CMake demonstration](https://github.com/simdjson/cmakedemo).
|
||||
|
||||
The Basics: Loading and Parsing JSON Documents
|
||||
----------------------------------------------
|
||||
|
||||
The simdjson library offers a simple DOM tree API, which you can access by creating a
|
||||
`dom::parser` and calling the `load()` method:
|
||||
|
||||
```
|
||||
dom::parser parser;
|
||||
dom::element doc = parser.load(filename); // load and parse a file
|
||||
```
|
||||
|
||||
Or by creating a padded string (for efficiency reasons, simdjson requires a string with
|
||||
SIMDJSON_PADDING bytes at the end) and calling `parse()`:
|
||||
|
||||
```
|
||||
dom::parser parser;
|
||||
dom::element doc = parser.parse("[1,2,3]"_padded); // parse a string
|
||||
```
|
||||
|
||||
The parsed document resulting from the `parser.load` and `parser.parse` calls depends on the `parser` instance. Thus the `parser` instance must remain in scope. Furthermore, you must have at most one parsed document in play per `parser` instance.
|
||||
|
||||
During the`load` or `parse` calls, neither the input file nor the input string are ever modified. After calling `load` or `parse`, the source (either a file or a string) can be safely discarded. All of the JSON data is stored in the `parser` instance. The parsed document is also immutable in simdjson: you do not modify it by accessing it.
|
||||
|
||||
For best performance, a `parser` instance should be reused over several files: otherwise you will needlessly reallocate memory, an expensive process. It is also possible to avoid entirely memory allocations during parsing when using simdjson.
|
||||
|
||||
|
||||
Using the Parsed JSON
|
||||
---------------------
|
||||
|
||||
Once you have an element, you can navigate it with idiomatic C++ iterators, operators and casts.
|
||||
|
||||
* **Extracting Values (with exceptions):** You can cast a JSON element to a native type: `double(element)` or
|
||||
`double x = json_element`. This works for double, uint64_t, int64_t, bool,
|
||||
dom::object and dom::array. An exception is thrown if the cast is not possible.
|
||||
* **Extracting Values (without expceptions):** 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`,
|
||||
`dom::object` and `dom::array`) and pass it by reference to `get()` which gives you back an error code: e.g.,
|
||||
```
|
||||
simdjson::error_code error;
|
||||
simdjson::padded_string numberstring = "1.2"_padded; // our JSON input ("1.2")
|
||||
simdjson::dom::parser parser;
|
||||
double value; // variable where we store the value to be parsed
|
||||
error = parser.parse(numberstring).get(value);
|
||||
if (error) { std::cerr << error << std::endl; return EXIT_FAILURE; }
|
||||
std::cout << "I parsed " << value << " from " << numberstring.data() << std::endl;
|
||||
```
|
||||
* **Field Access:** To get the value of the "foo" field in an object, use `object["foo"]`.
|
||||
* **Array Iteration:** To iterate through an array, use `for (auto value : array) { ... }`. If you
|
||||
know the type of the value, you can cast it right there, too! `for (double value : array) { ... }`
|
||||
* **Object Iteration:** You can iterate through an object's fields, too: `for (auto [key, value] : object)`
|
||||
* **Array Index:** To get at an array value by index, use the at() method: `array.at(0)` gets the
|
||||
first element.
|
||||
> Note that array[0] does not compile, because implementing [] gives the impression indexing is a
|
||||
> O(1) operation, which it is not presently in simdjson. Instead, you should iterate over the elements
|
||||
> using a for-loop, as in our examples.
|
||||
* **Array and Object size** Given an array or an object, you can get its size (number of elements or keys)
|
||||
with the `size()` method.
|
||||
* **Checking an Element Type:** You can check an element's type with `element.type()`. It
|
||||
returns an `element_type`.
|
||||
|
||||
|
||||
Here are some examples of all of the above:
|
||||
|
||||
```
|
||||
auto cars_json = R"( [
|
||||
{ "make": "Toyota", "model": "Camry", "year": 2018, "tire_pressure": [ 40.1, 39.9, 37.7, 40.4 ] },
|
||||
{ "make": "Kia", "model": "Soul", "year": 2012, "tire_pressure": [ 30.1, 31.0, 28.6, 28.7 ] },
|
||||
{ "make": "Toyota", "model": "Tercel", "year": 1999, "tire_pressure": [ 29.8, 30.0, 30.2, 30.5 ] }
|
||||
] )"_padded;
|
||||
dom::parser parser;
|
||||
|
||||
// Iterating through an array of objects
|
||||
for (dom::object car : parser.parse(cars_json)) {
|
||||
// Accessing a field by name
|
||||
cout << "Make/Model: " << car["make"] << "/" << car["model"] << endl;
|
||||
|
||||
// Casting a JSON element to an integer
|
||||
uint64_t year = car["year"];
|
||||
cout << "- This car is " << 2020 - year << "years old." << endl;
|
||||
|
||||
// Iterating through an array of floats
|
||||
double total_tire_pressure = 0;
|
||||
for (double tire_pressure : car["tire_pressure"]) {
|
||||
total_tire_pressure += tire_pressure;
|
||||
}
|
||||
cout << "- Average tire pressure: " << (total_tire_pressure / 4) << endl;
|
||||
|
||||
// Writing out all the information about the car
|
||||
for (auto field : car) {
|
||||
cout << "- " << field.key << ": " << field.value << endl;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Here is a different example illustrating the same ideas:
|
||||
|
||||
```
|
||||
auto abstract_json = R"( [
|
||||
{ "12345" : {"a":12.34, "b":56.78, "c": 9998877} },
|
||||
{ "12545" : {"a":11.44, "b":12.78, "c": 11111111} }
|
||||
] )"_padded;
|
||||
dom::parser parser;
|
||||
|
||||
// Parse and iterate through an array of objects
|
||||
for (dom::object obj : parser.parse(abstract_json)) {
|
||||
for(const auto& key_value : obj) {
|
||||
cout << "key: " << key_value.key << " : ";
|
||||
dom::object innerobj = key_value.value;
|
||||
cout << "a: " << double(innerobj["a"]) << ", ";
|
||||
cout << "b: " << double(innerobj["b"]) << ", ";
|
||||
cout << "c: " << int64_t(innerobj["c"]) << endl;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And another one:
|
||||
|
||||
|
||||
```
|
||||
auto abstract_json = R"(
|
||||
{ "str" : { "123" : {"abc" : 3.14 } } } )"_padded;
|
||||
dom::parser parser;
|
||||
double v = parser.parse(abstract_json)["str"]["123"]["abc"];
|
||||
cout << "number: " << v << endl;
|
||||
```
|
||||
|
||||
|
||||
C++11 Support and string_view
|
||||
-------------
|
||||
|
||||
The simdjson library builds on compilers supporting the [C++11 standard](https://en.wikipedia.org/wiki/C%2B%2B11). It is also a strict requirement: we have no plan to support older C++ compilers.
|
||||
|
||||
We represent parsed strings in simdjson using the `std::string_view` class. It avoids
|
||||
the need to copy the data, as would be necessary with the `std::string` class. It also
|
||||
avoids the pitfalls of null-terminated C strings.
|
||||
|
||||
The `std::string_view` class has become standard as part of C++17 but it is not always available
|
||||
on compilers which only supports C++11. When we detect that `string_view` is natively
|
||||
available, we define the macro `SIMDJSON_HAS_STRING_VIEW`.
|
||||
|
||||
When we detect that it is unavailable,
|
||||
we use [string-view-lite](https://github.com/martinmoene/string-view-lite) as a
|
||||
substitute. In such cases, we use the type alias `using string_view = nonstd::string_view;` to
|
||||
offer the same API, irrespective of the compiler and standard library. The macro
|
||||
`SIMDJSON_HAS_STRING_VIEW` will be *undefined* to indicate that we emulate `string_view`.
|
||||
|
||||
|
||||
C++17 Support
|
||||
-------------
|
||||
|
||||
While the simdjson library can be used in any project using C++ 11 and above, field iteration has special support C++ 17's destructuring syntax. For example:
|
||||
|
||||
```
|
||||
padded_string json = R"( { "foo": 1, "bar": 2 } )"_padded;
|
||||
dom::parser parser;
|
||||
dom::object object;
|
||||
auto error = parser.parse(json).get(object);
|
||||
if (error) { cerr << error << endl; return; }
|
||||
for (auto [key, value] : object) {
|
||||
cout << key << " = " << value << endl;
|
||||
}
|
||||
```
|
||||
|
||||
For comparison, here is the C++ 11 version of the same code:
|
||||
|
||||
```
|
||||
// C++ 11 version for comparison
|
||||
padded_string json = R"( { "foo": 1, "bar": 2 } )"_padded;
|
||||
dom::parser parser;
|
||||
dom::object object;
|
||||
auto error = parser.parse(json).get(object);
|
||||
if (!error) { cerr << error << endl; return; }
|
||||
for (dom::key_value_pair field : object) {
|
||||
cout << field.key << " = " << field.value << endl;
|
||||
}
|
||||
```
|
||||
|
||||
Minifying JSON strings without parsing
|
||||
----------------------
|
||||
|
||||
In some cases, you may have valid JSON strings that you do not wish to parse but that you wish to minify. That is, you wish to remove all unnecessary spaces. We have a fast function for this purpose (`minify`). This function does not validate your content, and it does not parse it. Instead, it assumes that your string is valid UTF-8. It is much faster than parsing the string and re-serializing it in minified form. Usage is relatively simple. You must pass an input pointer with a length parameter, as well as an output pointer and an output length parameter (by reference). The output length parameter is not read, but written to. The output pointer should point to a valid memory region that is slightly overallocated (by `simdjson::SIMDJSON_PADDING`) compared to the original string length. The input pointer and input length are read, but not written to.
|
||||
|
||||
```
|
||||
// Starts with a valid JSON document as a string.
|
||||
// It does not have to be null-terminated.
|
||||
const char * some_string = "[ 1, 2, 3, 4] ";
|
||||
size_t length = strlen(some_string);
|
||||
// Create a buffer to receive the minified string. Make sure that there is enough room,
|
||||
// including some padding (simdjson::SIMDJSON_PADDING).
|
||||
std::unique_ptr<char[]> buffer{new(std::nothrow) char[length + simdjson::SIMDJSON_PADDING]};
|
||||
size_t new_length{}; // It will receive the minified length.
|
||||
auto error = simdjson::minify(some_string, length, buffer.get(), new_length);
|
||||
// The buffer variable now has "[1,2,3,4]" and new_length has value 9.
|
||||
```
|
||||
|
||||
Though it does not validate the JSON input, it will detect when the document ends with an unterminated string. E.g., it would refuse to minify the string `"this string is not terminated` because of the missing final quote.
|
||||
|
||||
|
||||
UTF-8 validation (alone)
|
||||
----------------------
|
||||
|
||||
The simdjson library has fast functions to validate UTF-8 strings. They are many times faster than most functions commonly found in libraries. You can use our fast functions, even if you do not care about JSON.
|
||||
|
||||
```
|
||||
const char * some_string = "[ 1, 2, 3, 4] ";
|
||||
size_t length = strlen(some_string);
|
||||
bool is_ok = simdjson::validate_utf8(some_string, length);
|
||||
```
|
||||
|
||||
The UTF-8 validation function merely checks that the input is valid UTF-8: it works with strings in general, not just JSON strings.
|
||||
|
||||
Your input string does not need any padding. Any string will do. The `validate_utf8` function does not do any memory allocation on the heap, and it does not throw exceptions.
|
||||
|
||||
JSON Pointer
|
||||
------------
|
||||
|
||||
The simdjson library also supports [JSON pointer](https://tools.ietf.org/html/rfc6901) through the
|
||||
at() method, letting you reach further down into the document in a single call:
|
||||
|
||||
```
|
||||
auto cars_json = R"( [
|
||||
{ "make": "Toyota", "model": "Camry", "year": 2018, "tire_pressure": [ 40.1, 39.9, 37.7, 40.4 ] },
|
||||
{ "make": "Kia", "model": "Soul", "year": 2012, "tire_pressure": [ 30.1, 31.0, 28.6, 28.7 ] },
|
||||
{ "make": "Toyota", "model": "Tercel", "year": 1999, "tire_pressure": [ 29.8, 30.0, 30.2, 30.5 ] }
|
||||
] )"_padded;
|
||||
dom::parser parser;
|
||||
dom::element cars = parser.parse(cars_json);
|
||||
cout << cars.at("0/tire_pressure/1") << endl; // Prints 39.9
|
||||
```
|
||||
|
||||
Error Handling
|
||||
--------------
|
||||
|
||||
All simdjson APIs that can fail return `simdjson_result<T>`, which is a <value, error_code>
|
||||
pair. You can retrieve the value with .get(), like so:
|
||||
|
||||
```
|
||||
dom::element doc;
|
||||
auto error = parser.parse(json).get(doc);
|
||||
if (error) { cerr << error << endl; exit(1); }
|
||||
```
|
||||
|
||||
When you use the code this way, it is your responsibility to check for error before using the
|
||||
result: if there is an error, the result value will not be valid and using it will caused undefined
|
||||
behavior.
|
||||
|
||||
We can write a "quick start" example where we attempt to parse a file and access some data, without triggering exceptions:
|
||||
|
||||
```
|
||||
#include "simdjson.h"
|
||||
|
||||
int main(void) {
|
||||
simdjson::dom::parser parser;
|
||||
|
||||
simdjson::dom::element tweets;
|
||||
auto error = parser.load("twitter.json").get(tweets);
|
||||
if (error) { std::cerr << error << std::endl; return EXIT_FAILURE; }
|
||||
|
||||
simdjson::dom::element res;
|
||||
if ((error = tweets["search_metadata"]["count"].get(res))) {
|
||||
std::cerr << "could not access keys" << std::endl;
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
std::cout << res << " results." << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
### Error Handling Example
|
||||
|
||||
This is how the example in "Using the Parsed JSON" could be written using only error code checking:
|
||||
|
||||
```
|
||||
auto cars_json = R"( [
|
||||
{ "make": "Toyota", "model": "Camry", "year": 2018, "tire_pressure": [ 40.1, 39.9, 37.7, 40.4 ] },
|
||||
{ "make": "Kia", "model": "Soul", "year": 2012, "tire_pressure": [ 30.1, 31.0, 28.6, 28.7 ] },
|
||||
{ "make": "Toyota", "model": "Tercel", "year": 1999, "tire_pressure": [ 29.8, 30.0, 30.2, 30.5 ] }
|
||||
] )"_padded;
|
||||
dom::parser parser;
|
||||
dom::array cars;
|
||||
auto error = parser.parse(cars_json).get(cars);
|
||||
if (error) { cerr << error << endl; exit(1); }
|
||||
|
||||
// Iterating through an array of objects
|
||||
for (dom::element car_element : cars) {
|
||||
dom::object car;
|
||||
if ((error = car_element.get(car))) { cerr << error << endl; exit(1); }
|
||||
|
||||
// Accessing a field by name
|
||||
std::string_view make, model;
|
||||
if ((error = car["make"].get(make))) { cerr << error << endl; exit(1); }
|
||||
if ((error = car["model"].get(model))) { cerr << error << endl; exit(1); }
|
||||
cout << "Make/Model: " << make << "/" << model << endl;
|
||||
|
||||
// Casting a JSON element to an integer
|
||||
uint64_t year;
|
||||
if ((error = car["year"].get(year))) { cerr << error << endl; exit(1); }
|
||||
cout << "- This car is " << 2020 - year << "years old." << endl;
|
||||
|
||||
// Iterating through an array of floats
|
||||
double total_tire_pressure = 0;
|
||||
dom::array tire_pressure_array;
|
||||
if ((error = car["tire_pressure"].get(tire_pressure_array))) { cerr << error << endl; exit(1); }
|
||||
for (dom::element tire_pressure_element : tire_pressure_array) {
|
||||
double tire_pressure;
|
||||
if ((error = tire_pressure_element.get(tire_pressure))) { cerr << error << endl; exit(1); }
|
||||
total_tire_pressure += tire_pressure;
|
||||
}
|
||||
cout << "- Average tire pressure: " << (total_tire_pressure / 4) << endl;
|
||||
|
||||
// Writing out all the information about the car
|
||||
for (auto field : car) {
|
||||
cout << "- " << field.key << ": " << field.value << endl;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Here is another example:
|
||||
|
||||
```
|
||||
auto abstract_json = R"( [
|
||||
{ "12345" : {"a":12.34, "b":56.78, "c": 9998877} },
|
||||
{ "12545" : {"a":11.44, "b":12.78, "c": 11111111} }
|
||||
] )"_padded;
|
||||
dom::parser parser;
|
||||
dom::array array;
|
||||
auto error = parser.parse(abstract_json).get(array);
|
||||
if (error) { cerr << error << endl; exit(1); }
|
||||
// Iterate through an array of objects
|
||||
for (dom::element elem : array) {
|
||||
dom::object obj;
|
||||
if ((error = elem.get(obj))) { cerr << error << endl; exit(1); }
|
||||
for (auto & key_value : obj) {
|
||||
cout << "key: " << key_value.key << " : ";
|
||||
dom::object innerobj;
|
||||
if ((error = key_value.value.get(innerobj))) { cerr << error << endl; exit(1); }
|
||||
|
||||
double va, vb;
|
||||
if ((error = innerobj["a"].get(va))) { cerr << error << endl; exit(1); }
|
||||
cout << "a: " << va << ", ";
|
||||
if ((error = innerobj["b"].get(vc))) { cerr << error << endl; exit(1); }
|
||||
cout << "b: " << vb << ", ";
|
||||
|
||||
int64_t vc;
|
||||
if ((error = innerobj["c"].get(vc))) { cerr << error << endl; exit(1); }
|
||||
cout << "c: " << vc << endl;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And another one:
|
||||
|
||||
```
|
||||
auto abstract_json = R"(
|
||||
{ "str" : { "123" : {"abc" : 3.14 } } } )"_padded;
|
||||
dom::parser parser;
|
||||
double v;
|
||||
auto error = parser.parse(abstract_json)["str"]["123"]["abc"].get(v);
|
||||
if (error) { cerr << error << endl; exit(1); }
|
||||
cout << "number: " << v << endl;
|
||||
```
|
||||
|
||||
Notice how we can string several operations (`parser.parse(abstract_json)["str"]["123"]["abc"].get(v)`) and only check for the error once, a strategy we call *error chaining*.
|
||||
|
||||
The next two functions will take as input a JSON document containing an array with a single element, either a string or a number. They return true upon success.
|
||||
|
||||
```
|
||||
simdjson::dom::parser parser{};
|
||||
|
||||
bool parse_double(const char *j, double &d) {
|
||||
auto error = parser.parse(j, std::strlen(j))
|
||||
.at(0)
|
||||
.get(d, error);
|
||||
if (error) { return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
bool parse_string(const char *j, std::string &s) {
|
||||
std::string_view answer;
|
||||
auto error = parser.parse(j,strlen(j))
|
||||
.at(0)
|
||||
.get(answer, error);
|
||||
if (error) { return false; }
|
||||
s.assign(answer.data(), answer.size());
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
### Exceptions
|
||||
|
||||
Users more comfortable with an exception flow may choose to directly cast the `simdjson_result<T>` to the desired type:
|
||||
|
||||
```
|
||||
dom::element doc = parser.parse(json); // Throws an exception if there was an error!
|
||||
```
|
||||
|
||||
When used this way, a `simdjson_error` exception will be thrown if an error occurs, preventing the
|
||||
program from continuing if there was an error.
|
||||
|
||||
Tree Walking and JSON Element Types
|
||||
-----------------------------------
|
||||
|
||||
Sometimes you don't necessarily have a document with a known type, and are trying to generically
|
||||
inspect or walk over JSON elements. To do that, you can use iterators and the type() method. For
|
||||
example, here's a quick and dirty recursive function that verbosely prints the JSON document as JSON
|
||||
(* ignoring nuances like trailing commas and escaping strings, for brevity's sake):
|
||||
|
||||
```
|
||||
void print_json(dom::element element) {
|
||||
switch (element.type()) {
|
||||
case dom::element_type::ARRAY:
|
||||
cout << "[";
|
||||
for (dom::element child : dom::array(element)) {
|
||||
print_json(child);
|
||||
cout << ",";
|
||||
}
|
||||
cout << "]";
|
||||
break;
|
||||
case dom::element_type::OBJECT:
|
||||
cout << "{";
|
||||
for (dom::key_value_pair field : dom::object(element)) {
|
||||
cout << "\"" << field.key << "\": ";
|
||||
print_json(field.value);
|
||||
}
|
||||
cout << "}";
|
||||
break;
|
||||
case dom::element_type::INT64:
|
||||
cout << int64_t(element) << endl;
|
||||
break;
|
||||
case dom::element_type::UINT64:
|
||||
cout << uint64_t(element) << endl;
|
||||
break;
|
||||
case dom::element_type::DOUBLE:
|
||||
cout << double(element) << endl;
|
||||
break;
|
||||
case dom::element_type::STRING:
|
||||
cout << std::string_view(element) << endl;
|
||||
break;
|
||||
case dom::element_type::BOOL:
|
||||
cout << bool(element) << endl;
|
||||
break;
|
||||
case dom::element_type::NULL_VALUE:
|
||||
cout << "null" << endl;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void basics_treewalk_1() {
|
||||
dom::parser parser;
|
||||
print_json(parser.load("twitter.json"));
|
||||
}
|
||||
```
|
||||
|
||||
Newline-Delimited JSON (ndjson) and JSON lines
|
||||
----------------------------------------------
|
||||
|
||||
The simdjson library also support multithreaded JSON streaming through a large file containing many
|
||||
smaller JSON documents in either [ndjson](http://ndjson.org) or [JSON lines](http://jsonlines.org)
|
||||
format. If your JSON documents all contain arrays or objects, we even support direct file
|
||||
concatenation without whitespace. The concatenated file has no size restrictions (including larger
|
||||
than 4GB), though each individual document must be no larger than 4 GB.
|
||||
|
||||
Here is a simple example, given "x.json" with this content:
|
||||
|
||||
```json
|
||||
{ "foo": 1 }
|
||||
{ "foo": 2 }
|
||||
{ "foo": 3 }
|
||||
```
|
||||
|
||||
```
|
||||
dom::parser parser;
|
||||
dom::document_stream docs = parser.load_many(filename);
|
||||
for (dom::element doc : docs) {
|
||||
cout << doc["foo"] << endl;
|
||||
}
|
||||
// Prints 1 2 3
|
||||
```
|
||||
|
||||
In-memory ndjson strings can be parsed as well, with `parser.parse_many(string)`.
|
||||
|
||||
Both `load_many` and `parse_many` take an optional parameter `size_t batch_size` which defines the window processing size. It is set by default to a large value (`1000000` corresponding to 1 MB). None of your JSON documents should exceed this window size, or else you will get the error `simdjson::CAPACITY`. You cannot set this window size larger than 4 GB: you will get the error `simdjson::CAPACITY`. The smaller the window size is, the less memory the function will use. Setting the window size too small (e.g., less than 100 kB) may also impact performance negatively. Leaving it to 1 MB is expected to be a good choice, unless you have some larger documents.
|
||||
|
||||
|
||||
Thread Safety
|
||||
-------------
|
||||
|
||||
We built simdjson with thread safety in mind.
|
||||
|
||||
The simdjson library is single-threaded except for `parse_many` which may use secondary threads under its control when the library is compiled with thread support.
|
||||
|
||||
|
||||
We recommend using one `dom::parser` object per thread in which case the library is thread-safe.
|
||||
It is unsafe to reuse a `dom::parser` object between different threads.
|
||||
The parsed results (`dom::document`, `dom::element`, `array`, `object`) depend on the `dom::parser`, etc. therefore it is also potentially unsafe to use the result of the parsing between different threads.
|
||||
|
||||
The CPU detection, which runs the first time parsing is attempted and switches to the fastest
|
||||
parser for your CPU, is transparent and thread-safe.
|
||||
|
||||
Backwards Compatibility
|
||||
-----------------------
|
||||
|
||||
The only header file supported by simdjson is `simdjson.h`. Older versions of simdjson published a
|
||||
number of other include files such as `document.h` or `ParsedJson.h` alongside `simdjson.h`; these headers
|
||||
may be moved or removed in future versions.
|
||||
@@ -47,7 +47,7 @@ Inspecting the Detected Implementation
|
||||
You can check what implementation is running with `active_implementation`:
|
||||
|
||||
```c++
|
||||
cout << "simdjson v" << #SIMDJSON_VERSION << endl;
|
||||
cout << "simdjson v" << STRINGIFY(SIMDJSON_VERSION) << endl;
|
||||
cout << "Detected the best implementation for your machine: " << simdjson::active_implementation->name();
|
||||
cout << "(" << simdjson::active_implementation->description() << ")" << endl;
|
||||
```
|
||||
|
||||
+20
-15
@@ -1,7 +1,7 @@
|
||||
parse_many
|
||||
==========
|
||||
|
||||
An interface providing features to work with files or streams containing multiple JSON documents.
|
||||
An interface providing features to work with files or streams containing multiple JSON documents.
|
||||
As fast and convenient as possible.
|
||||
|
||||
Contents
|
||||
@@ -12,8 +12,6 @@ Contents
|
||||
- [How it works](#how-it-works)
|
||||
- [Support](#support)
|
||||
- [API](#api)
|
||||
- [Concurrency mode](#concurrency-mode)
|
||||
- [Example](#example)
|
||||
- [Use cases](#use-cases)
|
||||
|
||||
Motivations
|
||||
@@ -28,7 +26,7 @@ values as an array, or a possibly indeterminate-length or never-
|
||||
ending sequence of values, JSON becomes difficult to work with.
|
||||
|
||||
Consider a sequence of one million values, each possibly one kilobyte
|
||||
when encoded -- roughly one gigabyte. It is often desirable to process such a dataset incrementally
|
||||
when encoded -- roughly one gigabyte. It is often desirable to process such a dataset incrementally
|
||||
without having to first read all of it before beginning to produce results.
|
||||
|
||||
Performance
|
||||
@@ -88,14 +86,21 @@ sweet spot for now.
|
||||
|
||||
### Threads
|
||||
|
||||
But how can we make use of threads? We found a pretty cool algorithm that allows us to quickly
|
||||
But how can we make use of threads if they are available? We found a pretty cool algorithm that allows us to quickly
|
||||
identify the position of the last JSON document in a given batch. Knowing exactly where the end of
|
||||
the batch is, we no longer need for stage 2 to finish in order to load a new batch. We already know
|
||||
where to start the next batch. Therefore, we can run stage 1 on the next batch concurrently while
|
||||
the main thread is going through stage 2. Now, running stage 1 in a different thread can, in best
|
||||
cases, remove almost entirely it's cost and replaces it by the overhead of a thread, which is orders
|
||||
the main thread is going through stage 2. Running stage 1 in a different thread can, in best
|
||||
cases, remove almost entirely its cost and replaces it by the overhead of a thread, which is orders
|
||||
of magnitude cheaper. Ain't that awesome!
|
||||
|
||||
Thread support is only active if thread supported is detected in which case the macro
|
||||
SIMDJSON_THREADS_ENABLED is set. Otherwise the library runs in single-thread mode.
|
||||
|
||||
A `document_stream` instance uses at most two threads: there is a main thread and a worker thread.
|
||||
You should expect the main thread to be fully occupied while the worker thread is partially busy
|
||||
(e.g., 80% of the time).
|
||||
|
||||
Support
|
||||
-------
|
||||
|
||||
@@ -104,7 +109,7 @@ format, we support any file that contains any amount of valid JSON document, **s
|
||||
or more character that is considered whitespace** by the JSON spec. Anything that is
|
||||
not whitespace will be parsed as a JSON document and could lead to failure.
|
||||
|
||||
Whitespace Characters:
|
||||
Whitespace Characters:
|
||||
- **Space**
|
||||
- **Linefeed**
|
||||
- **Carriage return**
|
||||
@@ -132,16 +137,16 @@ From [jsonlines.org](http://jsonlines.org/examples/):
|
||||
["Gilbert", "2013", 24, true]
|
||||
["Alexa", "2013", 29, true]
|
||||
["May", "2012B", 14, false]
|
||||
["Deloise", "2012A", 19, true]
|
||||
["Deloise", "2012A", 19, true]
|
||||
```
|
||||
CSV seems so easy that many programmers have written code to generate it themselves, and almost every implementation is
|
||||
different. Handling broken CSV files is a common and frustrating task. CSV has no standard encoding, no standard column
|
||||
CSV seems so easy that many programmers have written code to generate it themselves, and almost every implementation is
|
||||
different. Handling broken CSV files is a common and frustrating task. CSV has no standard encoding, no standard column
|
||||
separator and multiple character escaping standards. String is the only type supported for cell values, so some programs
|
||||
attempt to guess the correct types.
|
||||
|
||||
|
||||
JSON Lines handles tabular data cleanly and without ambiguity. Cells may use the standard JSON types.
|
||||
|
||||
The biggest missing piece is an import/export filter for popular spreadsheet programs so that non-programmers can use
|
||||
|
||||
The biggest missing piece is an import/export filter for popular spreadsheet programs so that non-programmers can use
|
||||
this format.
|
||||
|
||||
- **Easy Nested Data**
|
||||
@@ -151,5 +156,5 @@ From [jsonlines.org](http://jsonlines.org/examples/):
|
||||
{"name": "May", "wins": []}
|
||||
{"name": "Deloise", "wins": [["three of a kind", "5♣"]]}
|
||||
```
|
||||
JSON Lines' biggest strength is in handling lots of similar nested data structures. One .jsonl file is easier to
|
||||
JSON Lines' biggest strength is in handling lots of similar nested data structures. One .jsonl file is easier to
|
||||
work with than a directory full of XML files.
|
||||
|
||||
+37
-7
@@ -9,13 +9,18 @@ are still some scenarios where tuning can enhance performance.
|
||||
* [Server Loops: Long-Running Processes and Memory Capacity](#server-loops-long-running-processes-and-memory-capacity)
|
||||
* [Large files and huge page support](#large-files-and-huge-page-support)
|
||||
* [Computed GOTOs](#computed-gotos)
|
||||
* [Number parsing](#number-parsing)
|
||||
* [Visual Studio](#visual-studio)
|
||||
* [Downclocking](#downclocking)
|
||||
|
||||
|
||||
Reusing the parser for maximum efficiency
|
||||
-----------------------------------------
|
||||
|
||||
If you're using simdjson to parse multiple documents, or in a loop, you should make a parser once
|
||||
and reuse it. The simdjson library will allocate and retain internal buffers between parses, keeping
|
||||
buffers hot in cache and keeping memory allocation and initialization to a minimum.
|
||||
buffers hot in cache and keeping memory allocation and initialization to a minimum. In this manner,
|
||||
you can parse terabytes of JSON data without doing any new allocation.
|
||||
|
||||
```c++
|
||||
dom::parser parser;
|
||||
@@ -35,7 +40,7 @@ cout << doc << endl;
|
||||
cout << doc2 << endl;
|
||||
```
|
||||
|
||||
It's not just internal buffers though. The simdjson library reuses the document itself. dom::element, dom::object and dom::array are *references* to the internal document.
|
||||
It's not just internal buffers though. The simdjson library reuses the document itself. The dom::element, dom::object and dom::array instances are *references* to the internal document.
|
||||
You are only *borrowing* the document from simdjson, which purposely reuses and overwrites it each
|
||||
time you call parse. This prevent wasteful and unnecessary memory allocation in 99% of cases where
|
||||
JSON is just read, used, and converted to native values or thrown away.
|
||||
@@ -61,9 +66,10 @@ without bound:
|
||||
* You can set a *max capacity* when constructing a parser:
|
||||
|
||||
```c++
|
||||
dom::parser parser(1024*1024); // Never grow past documents > 1MB
|
||||
dom::parser parser(1000*1000); // Never grow past documents > 1MB
|
||||
for (web_request request : listen()) {
|
||||
auto [doc, error] = parser.parse(request.body);
|
||||
dom::element doc;
|
||||
auto error = parser.parse(request.body).get(doc);
|
||||
// If the document was above our limit, emit 413 = payload too large
|
||||
if (error == CAPACITY) { request.respond(413); continue; }
|
||||
// ...
|
||||
@@ -77,11 +83,12 @@ without bound:
|
||||
|
||||
```c++
|
||||
dom::parser parser(0); // This parser will refuse to automatically grow capacity
|
||||
simdjson::error_code allocate_error = parser.allocate(1024*1024); // This allocates enough capacity to handle documents <= 1MB
|
||||
if (allocate_error) { cerr << allocate_error << endl; exit(1); }
|
||||
auto error = parser.allocate(1000*1000); // This allocates enough capacity to handle documents <= 1MB
|
||||
if (error) { cerr << error << endl; exit(1); }
|
||||
|
||||
for (web_request request : listen()) {
|
||||
auto [doc, error] = parser.parse(request.body);
|
||||
dom::element doc;
|
||||
error = parser.parse(request.body).get(doc);
|
||||
// If the document was above our limit, emit 413 = payload too large
|
||||
if (error == CAPACITY) { request.respond(413); continue; }
|
||||
// ...
|
||||
@@ -140,3 +147,26 @@ few hundred megabytes per second if your JSON documents are densely packed with
|
||||
- When possible, you should favor integer values written without a decimal point, as it simpler and faster to parse decimal integer values.
|
||||
- When serializing numbers, you should not use more digits than necessary: 17 digits is all that is needed to exactly represent double-precision floating-point numbers. Using many more digits than necessary will make your files larger and slower to parse.
|
||||
- When benchmarking parsing speeds, always report whether your JSON documents are made mostly of floating-point numbers when it is the case, since number parsing can then dominate the parsing time.
|
||||
|
||||
|
||||
Visual Studio
|
||||
--------------
|
||||
|
||||
On Intel and AMD Windows platforms, Microsoft Visual Studio enables programmers to build either 32-bit (x86) or 64-bit (x64) binaries. We urge you to always use 64-bit mode. Visual Studio 2019 should default on 64-bit builds when you have a 64-bit version of Windows, which we recommend.
|
||||
|
||||
We do not recommend that you compile simdjson with architecture-specific flags such as `arch:AVX2`. The simdjson library automatically selects the best execution kernel at runtime.
|
||||
|
||||
Recent versions of Microsoft Visual Studio on Windows provides support for the LLVM Clang compiler. You only need to install the "Clang compiler" optional component. You may also get a copy of the 64-bit LLVM CLang compiler for [Windows directly from LLVM](https://releases.llvm.org/download.html). The simdjson library fully supports the LLVM Clang compiler under Windows. In fact, you may get better performance out of simdjson with the LLVM Clang compiler than with the regular Visual Studio compiler.
|
||||
|
||||
|
||||
Downclocking
|
||||
--------------
|
||||
|
||||
You should not expect the simdjson library to cause downclocking of your recent Intel CPU cores.
|
||||
|
||||
On some Intel processors, using SIMD instructions in a sustained manner on the same CPU core may result in a phenomenon called downclocking whereas the processor initially runs these instructions at a slow speed before reducing the frequency of the core for a short time (milliseconds). Intel refers to these states as licenses. On some current Intel processors, it occurs under two scenarios:
|
||||
|
||||
- [Whenever 512-bit AVX-512 instructions are used](https://lemire.me/blog/2018/09/07/avx-512-when-and-how-to-use-these-new-instructions/).
|
||||
- Whenever heavy 256-bit or wider instructions are used. Heavy instructions are those involving floating point operations or integer multiplications (since these execute on the floating point unit).
|
||||
|
||||
The simdjson library does not currently support AVX-512 instructions and it does not make use of heavy 256-bit instructions. Thus there should be no downclocking due to simdjson on recent processors. You may still be worried about which SIMD instruction set is used by simdjson. Thankfully, [you can always determine and change which architecture-specific implementation is used](implementation-selection.md). Thus even if your CPU supports AVX2, you do not need to use AVX2. You are in control.
|
||||
|
||||
@@ -134,4 +134,3 @@ In-between these two tape elements, we alternate between key (which must be stri
|
||||
All the content of the object is located between these two tape elements, including arrays and objects.
|
||||
|
||||
Performance consideration: We can skip the content of an object entirely by accessing the first 64-bit tape element, reading the payload and moving to the corresponding index on the tape.
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
add_subdirectory(quickstart)
|
||||
@@ -0,0 +1,60 @@
|
||||
#
|
||||
# Quickstart compile tests don't require any flags
|
||||
#
|
||||
|
||||
# TODO haven't quite decided the right way to run quickstart on Windows. Needs README update.
|
||||
#
|
||||
# Note: on macOS and other platforms, the 'command' described below may not work even if the cmake builds.
|
||||
# For example, it may be necessary to specify the sysroot, which CMake does, but the 'command' does not
|
||||
# handle such niceties. On a case-by-case basis it is fixable but it requires work that CMake knows how
|
||||
# to do but that is not trivial.
|
||||
#
|
||||
IF(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
|
||||
# TODO run amalgamate first!
|
||||
function(add_quickstart_test TEST_NAME SOURCE_FILE)
|
||||
# Second argument is C++ standard name
|
||||
if (MSVC)
|
||||
if (ARGV2)
|
||||
set(QUICKSTART_FLAGS /std:${ARGV2})
|
||||
else()
|
||||
set(QUICKSTART_FLAGS /WX)
|
||||
endif()
|
||||
set(QUICKSTART_INCLUDE /I${PROJECT_SOURCE_DIR}/include /I${PROJECT_SOURCE_DIR}/src ${PROJECT_SOURCE_DIR}/src/simdjson.cpp)
|
||||
else()
|
||||
if (ARGV2)
|
||||
set(QUICKSTART_FLAGS -Werror -std=${ARGV2})
|
||||
else()
|
||||
set(QUICKSTART_FLAGS -Werror)
|
||||
endif()
|
||||
set(QUICKSTART_INCLUDE -I${PROJECT_SOURCE_DIR}/include -I${PROJECT_SOURCE_DIR}/src ${PROJECT_SOURCE_DIR}/src/simdjson.cpp)
|
||||
endif()
|
||||
|
||||
# Third argument tells whether to compile with -fno-exceptions
|
||||
if (ARGV3)
|
||||
if (NOT MSVC)
|
||||
set(QUICKSTART_FLAGS ${QUICKSTART_FLAGS} -fno-exceptions)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
add_test(
|
||||
NAME ${TEST_NAME}
|
||||
COMMAND ${CMAKE_CXX_COMPILER} ${QUICKSTART_FLAGS} -I${PROJECT_SOURCE_DIR}/include -I${PROJECT_SOURCE_DIR}/src ${PROJECT_SOURCE_DIR}/src/simdjson.cpp ${SOURCE_FILE}
|
||||
WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/examples/quickstart
|
||||
)
|
||||
set_property(
|
||||
TEST ${TEST_NAME}
|
||||
APPEND PROPERTY DEPENDS simdjson-source ${PROJECT_SOURCE_DIR}/examples/quickstart/${SOURCE_FILE}
|
||||
)
|
||||
endfunction(add_quickstart_test)
|
||||
|
||||
if (SIMDJSON_EXCEPTIONS)
|
||||
add_quickstart_test(quickstart quickstart.cpp)
|
||||
add_quickstart_test(quickstart11 quickstart.cpp c++11)
|
||||
add_quickstart_test(quickstart14 quickstart.cpp c++14)
|
||||
set_property( TEST quickstart quickstart11 APPEND PROPERTY LABELS acceptance compiletests )
|
||||
endif()
|
||||
|
||||
add_quickstart_test(quickstart_noexceptions quickstart_noexceptions.cpp "" true)
|
||||
add_quickstart_test(quickstart_noexceptions11 quickstart_noexceptions.cpp c++11 true)
|
||||
set_property( TEST quickstart_noexceptions APPEND PROPERTY LABELS acceptance compile )
|
||||
endif()
|
||||
@@ -4,13 +4,29 @@ JSONEXAMPLES=$(ROOT)/jsonexamples
|
||||
|
||||
test: quickstart twitter.json
|
||||
./quickstart
|
||||
quickstart: quickstart.cpp simdjson.cpp simdjson.h
|
||||
c++ -o ./quickstart quickstart.cpp simdjson.cpp
|
||||
clean:
|
||||
rm -f simdjson.cpp simdjson.h twitter.json quickstart quickstart11 quickstart14
|
||||
simdjson.cpp: $(SINGLEHEADER)/simdjson.cpp
|
||||
cp $(SINGLEHEADER)/simdjson.cpp .
|
||||
simdjson.h: $(SINGLEHEADER)/simdjson.h
|
||||
cp $(SINGLEHEADER)/simdjson.h .
|
||||
twitter.json: $(JSONEXAMPLES)/twitter.json
|
||||
cp $(JSONEXAMPLES)/twitter.json .
|
||||
quickstart: quickstart.cpp simdjson.cpp simdjson.h
|
||||
c++ -o ./quickstart quickstart.cpp simdjson.cpp -std=c++17
|
||||
clean:
|
||||
rm -f simdjson.cpp simdjson.h twitter.json quickstart
|
||||
|
||||
quickstart11: $(ROOT)/src/**.h $(ROOT)/src/**.cpp $(ROOT)/include/**.h $(ROOT)/src/**.cpp
|
||||
rm -f simdjson.h simdjson.cpp
|
||||
c++ -o ./quickstart11 quickstart.cpp $(ROOT)/src/simdjson.cpp -I$(ROOT)/src -I$(ROOT)/include -std=c++11
|
||||
test11: quickstart11 twitter.json
|
||||
./quickstart11
|
||||
quickstart14: $(ROOT)/src/**.h $(ROOT)/src/**.cpp $(ROOT)/include/**.h $(ROOT)/src/**.cpp
|
||||
rm -f simdjson.h simdjson.cpp
|
||||
c++ -o ./quickstart14 quickstart.cpp $(ROOT)/src/simdjson.cpp -I$(ROOT)/src -I$(ROOT)/include -std=c++14
|
||||
test14: quickstart14 twitter.json
|
||||
./quickstart14
|
||||
quickstart17: $(ROOT)/src/**.h $(ROOT)/src/**.cpp $(ROOT)/include/**.h $(ROOT)/src/**.cpp
|
||||
rm -f simdjson.h simdjson.cpp
|
||||
c++ -o ./quickstart17 quickstart.cpp $(ROOT)/src/simdjson.cpp -I$(ROOT)/src -I$(ROOT)/include -std=c++17
|
||||
test17: quickstart17 twitter.json
|
||||
./quickstart17
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "simdjson.h"
|
||||
|
||||
int main(void) {
|
||||
simdjson::dom::parser parser;
|
||||
simdjson::dom::element tweets = parser.load("twitter.json");
|
||||
std::cout << tweets["search_metadata"]["count"] << " results." << std::endl;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#include "simdjson.h"
|
||||
|
||||
int main(void) {
|
||||
simdjson::dom::parser parser;
|
||||
simdjson::dom::element tweets;
|
||||
auto error = parser.load("twitter.json").get(tweets);
|
||||
if (error) { std::cerr << error << std::endl; return EXIT_FAILURE; }
|
||||
simdjson::dom::element res;
|
||||
|
||||
if ((error = tweets["search_metadata"]["count"].get(res))) {
|
||||
std::cerr << "could not access keys" << std::endl;
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
std::cout << res << " results." << std::endl;
|
||||
}
|
||||
|
||||
+52
-45
@@ -1,56 +1,63 @@
|
||||
# First attempt at a fuzzer, using libFuzzer.
|
||||
#
|
||||
# compile like this:
|
||||
# mkdir build-fuzzer
|
||||
# cd build-fuzzer
|
||||
# export LDFLAGS="-fsanitize=address,undefined"
|
||||
# export CXXFLAGS="-fsanitize=fuzzer-no-link,address,undefined"
|
||||
# export CFLAGS="-fsanitize=fuzzer-no-link,address,undefined"
|
||||
# export CXX=clang++
|
||||
# export CC=clang++
|
||||
# cmake .. -GNinja -DCMAKE_BUILD_TYPE=Debug -DENABLE_FUZZING=On -DSIMDJSON_FUZZ_LINKMAIN=Off -DSIMDJSON_FUZZ_LDFLAGS=-fsanitize=fuzzer
|
||||
# ninja
|
||||
option(ENABLE_FUZZING "enable building the fuzzers" ON)
|
||||
|
||||
if(ENABLE_FUZZING)
|
||||
|
||||
# settings this links in a main. useful for reproducing,
|
||||
# kcov, gdb, afl, valgrind.
|
||||
# (note that libFuzzer can also reproduce, just pass it the files)
|
||||
#
|
||||
# Using this by default, means the fuzzers will be built as a part of the normal
|
||||
# workflow, meaning they wont bitrot and will participate in refactoring etc.
|
||||
#
|
||||
option(SIMDJSON_FUZZ_LINKMAIN "links a main into fuzz targets for building reproducers" On)
|
||||
# First attempt at a fuzzer, using libFuzzer.
|
||||
#
|
||||
# compile like this:
|
||||
# mkdir build-fuzzer
|
||||
# cd build-fuzzer
|
||||
# export LDFLAGS="-fsanitize=address,undefined"
|
||||
# export CXXFLAGS="-fsanitize=fuzzer-no-link,address,undefined"
|
||||
# export CFLAGS="-fsanitize=fuzzer-no-link,address,undefined"
|
||||
# export CXX=clang++
|
||||
# export CC=clang++
|
||||
# cmake .. -GNinja -DCMAKE_BUILD_TYPE=Debug -DENABLE_FUZZING=On -DSIMDJSON_FUZZ_LINKMAIN=Off -DSIMDJSON_FUZZ_LDFLAGS=-fsanitize=fuzzer
|
||||
# ninja
|
||||
|
||||
# For oss-fuzz - insert $LIB_FUZZING_ENGINE into the link flags, but only for
|
||||
# the fuzz targets, otherwise the cmake configuration step fails.
|
||||
set(SIMDJSON_FUZZ_LDFLAGS "" CACHE STRING "LDFLAGS for the fuzz targets")
|
||||
# settings this links in a main. useful for reproducing,
|
||||
# kcov, gdb, afl, valgrind.
|
||||
# (note that libFuzzer can also reproduce, just pass it the files)
|
||||
#
|
||||
# Using this by default, means the fuzzers will be built as a part of the normal
|
||||
# workflow, meaning they wont bitrot and will participate in refactoring etc.
|
||||
#
|
||||
option(SIMDJSON_FUZZ_LINKMAIN "links a main into fuzz targets for building reproducers" On)
|
||||
|
||||
set(SOURCES
|
||||
fuzz_parser.cpp
|
||||
# fuzz_minify.cpp # <--- does not pass the build check test on oss-fuzz, says "partially instrumented". help needed!
|
||||
fuzz_dump.cpp
|
||||
fuzz_print_json.cpp
|
||||
fuzz_dump_raw_tape.cpp
|
||||
)
|
||||
# For oss-fuzz - insert $LIB_FUZZING_ENGINE into the link flags, but only for
|
||||
# the fuzz targets, otherwise the cmake configuration step fails.
|
||||
set(SIMDJSON_FUZZ_LDFLAGS "" CACHE STRING "LDFLAGS for the fuzz targets")
|
||||
|
||||
add_custom_target(print_all_fuzz_targets
|
||||
add_custom_target(print_all_fuzz_targets
|
||||
COMMAND ${CMAKE_COMMAND} -E echo ${SOURCES}
|
||||
)
|
||||
)
|
||||
|
||||
macro(implement_fuzzer sourcefile)
|
||||
get_filename_component(basename ${sourcefile} NAME_WE)
|
||||
set(name ${basename})
|
||||
add_executable(${name} ${sourcefile})
|
||||
# Fuzzer build flags and libraries
|
||||
add_library(simdjson-fuzzer INTERFACE)
|
||||
if (SIMDJSON_FUZZ_LINKMAIN)
|
||||
target_sources(${name} PRIVATE main.cpp)
|
||||
target_link_libraries(simdjson-fuzzer INTERFACE simdjson-source)
|
||||
target_sources(simdjson-fuzzer INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>/main.cpp)
|
||||
else ()
|
||||
target_link_libraries(simdjson-fuzzer INTERFACE simdjson)
|
||||
endif ()
|
||||
target_link_libraries(${name} PRIVATE ${SIMDJSON_LIB_NAME})
|
||||
if (SIMDJSON_FUZZ_LDFLAGS)
|
||||
target_link_libraries(${name} PRIVATE ${SIMDJSON_FUZZ_LDFLAGS})
|
||||
endif ()
|
||||
endmacro ()
|
||||
target_link_libraries(simdjson-fuzzer INTERFACE simdjson-internal-flags)
|
||||
target_link_libraries(simdjson-fuzzer INTERFACE ${SIMDJSON_FUZZ_LDFLAGS})
|
||||
|
||||
foreach (X IN ITEMS ${SOURCES})
|
||||
implement_fuzzer(${X})
|
||||
endforeach ()
|
||||
# Define the fuzzers
|
||||
add_custom_target(all_fuzzers)
|
||||
|
||||
function(implement_fuzzer name)
|
||||
add_executable(${name} ${name}.cpp)
|
||||
target_link_libraries(${name} PRIVATE simdjson-fuzzer)
|
||||
add_dependencies(all_fuzzers ${name})
|
||||
add_test(${name} ${name})
|
||||
set_property(TEST ${name} APPEND PROPERTY LABELS fuzz)
|
||||
endfunction()
|
||||
|
||||
implement_fuzzer(fuzz_parser)
|
||||
implement_fuzzer(fuzz_minify)
|
||||
implement_fuzzer(fuzz_dump)
|
||||
implement_fuzzer(fuzz_print_json)
|
||||
implement_fuzzer(fuzz_dump_raw_tape)
|
||||
|
||||
endif()
|
||||
|
||||
+23
-10
@@ -2,19 +2,30 @@
|
||||
|
||||
[Fuzzing](https://en.wikipedia.org/wiki/Fuzzing) is efficient for finding bugs. Here are a few bugs in simdjson found by fuzzing:
|
||||
|
||||
- https://github.com/lemire/simdjson/issues/353
|
||||
- https://github.com/lemire/simdjson/issues/351
|
||||
- https://github.com/lemire/simdjson/issues/345
|
||||
- [#353](https://github.com/simdjson/simdjson/issues/353)
|
||||
- [#351](https://github.com/simdjson/simdjson/issues/351)
|
||||
- [#345](https://github.com/simdjson/simdjson/issues/345)
|
||||
- [oss-fuzz 18714](https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=18714&sort=-opened&q=proj%3Asimdjson&can=1)
|
||||
|
||||
The simdjson library tries to follow [fuzzing best practises](https://google.github.io/oss-fuzz/advanced-topics/ideal-integration/#summary).
|
||||
|
||||
The simdjson library is continuously fuzzed on [oss-fuzz](https://github.com/google/oss-fuzz).
|
||||
The simdjson library is continuously fuzzed on [oss-fuzz](https://github.com/google/oss-fuzz). In case a bug is found, the offending input is minimized and tested for reproducibility. A report with the details is automatically filed, and the contact persons at simdjson are notified via email. An issue is opened at the oss-fuzz bugtracker with restricted view access. When the bug is fixed, the issue is automatically closed.
|
||||
|
||||
Bugs are automatically made visible to the public after a period of time. An example of a bug that was found, fixed and closed can be seen here: [oss-fuzz 18714](https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=18714).
|
||||
|
||||
|
||||
## Currently open bugs
|
||||
|
||||
|
||||
You can find the currently opened bugs, if any at [bugs.chromium.org](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&q=proj%3Asimdjson&can=2): make sure not to miss the "Open Issues" selector. Bugs that are fixed by follow-up commits are automatically closed.
|
||||
|
||||
## Integration with oss-fuzz
|
||||
|
||||
Changes to the integration with oss-fuzz are made by making pull requests against the oss-fuzz github repo. An example can be seen at [oss-fuzz pull request 3013](https://github.com/google/oss-fuzz/pull/3013).
|
||||
|
||||
As little code as possible is kept at oss-fuzz since it is inconvenient to change. The [oss-fuzz build script](https://github.com/google/oss-fuzz/blob/b96dd54183f727a5d90c786e0fb01ec986c74d30/projects/simdjson/build.sh#L18) invokes [the script from the simdjson repo](https://github.com/simdjson/simdjson/blob/master/fuzz/ossfuzz.sh).
|
||||
|
||||
|
||||
|
||||
## Fuzzing as a CI job
|
||||
|
||||
@@ -29,24 +40,26 @@ The CI job does the following
|
||||
- minimizes the corpus and upload it (if on the master branch)
|
||||
- store the corpus and valgrind output as artifacts
|
||||
|
||||
The job is available under the actions tab, here is a [direct link](https://github.com/lemire/simdjson/actions?query=workflow%3A%22Run+fuzzers+on+stored+corpus+and+test+it+with+valgrind%22).
|
||||
The job is available under the actions tab, here is a [direct link](https://github.com/simdjson/simdjson/actions?query=workflow%3A%22Run+fuzzers+on+stored+corpus+and+test+it+with+valgrind%22).
|
||||
|
||||
The corpus will grow over time and easy to find bugs will be detected already during the pull request stage. Also, it will keep the fuzzer builds from bit rot.
|
||||
The corpus will grow over time and easy to find bugs will be detected already during the pull request stage. Also, it will keep the fuzzer builds from bit rot.
|
||||
|
||||
## Corpus
|
||||
|
||||
The simdjson library does not benefit from a corpus as much as other projects, because the library is very fast and explores the input space very well. With that said, it is still beneficial to have one. The CI job stores the corpus on bintray between runs, and is available here: https://dl.bintray.com/pauldreik/simdjson-fuzz-corpus/corpus/corpus.tar
|
||||
The simdjson library does not benefit from a corpus as much as other projects, because the library is very fast and explores the input space very well. With that said, it is still beneficial to have one. The CI job stores the corpus on bintray between runs, and is available at [bintray](https://dl.bintray.com/pauldreik/simdjson-fuzz-corpus/corpus/corpus.tar).
|
||||
|
||||
One can also grab the corpus as an artifact from the github actions job. Pick a run, then go to artifacts and download.
|
||||
|
||||
## Fuzzing coverage
|
||||
|
||||
The code coverage from fuzzing is most easily viewed on the [oss-fuzz status panel](https://oss-fuzz.com/fuzzer-stats). Viewing the coverage does not require login, but the direct link is publicly accessible. Substitute the date in the URL to get a more recent link:
|
||||
https://storage.googleapis.com/oss-fuzz-coverage/simdjson/reports/20191112/linux/src/simdjson/report.html
|
||||
The code coverage from fuzzing is most easily viewed on the [oss-fuzz status panel](https://oss-fuzz.com/fuzzer-stats). Viewing the coverage does not require login, but the direct link is not easy to find. Substitute the date in the URL to get a more recent link:
|
||||
[https://storage.googleapis.com/oss-fuzz-coverage/simdjson/reports/20200411/linux/src/simdjson/report.html](https://storage.googleapis.com/oss-fuzz-coverage/simdjson/reports/20200411/linux/src/simdjson/report.html)
|
||||
|
||||
|
||||
## Running the fuzzers locally
|
||||
|
||||
This has only been tested on Linux (Debian and Ubuntu are known to work).
|
||||
|
||||
Make sure you have clang and cmake installed.
|
||||
The easiest way to get started is to run the following, standing in the root of the checked out repo:
|
||||
```
|
||||
@@ -64,7 +77,7 @@ You can also use the more extensive fuzzer build script to get a variation of bu
|
||||
fuzz/build_fuzzer_variants.sh
|
||||
```
|
||||
|
||||
It is also possible to run the full oss-fuzz setup by following [these oss-fuzz instructions](https://google.github.io/oss-fuzz/getting-started/new-project-guide/#testing-locally) with PROJECT_NAME set to simdjson.
|
||||
It is also possible to run the full oss-fuzz setup by following [these oss-fuzz instructions](https://google.github.io/oss-fuzz/getting-started/new-project-guide/#testing-locally) with PROJECT_NAME set to simdjson. You will need rights to run docker.
|
||||
|
||||
## Reproducing
|
||||
To reproduce a test case, build the fuzzers, then invoke it with the testcase as a command line argument:
|
||||
|
||||
@@ -24,10 +24,12 @@ if [ ! -d build-$variant ] ; then
|
||||
-DCMAKE_BUILD_TYPE=Debug \
|
||||
-DSIMDJSON_BUILD_STATIC=On \
|
||||
-DENABLE_FUZZING=On \
|
||||
-DSIMDJSON_COMPETITION=OFF \
|
||||
-DSIMDJSON_GOOGLE_BENCHMARKS=OFF \
|
||||
-DSIMDJSON_FUZZ_LINKMAIN=On \
|
||||
-DSIMDJSON_IMPLEMENTATION_HASWELL=0
|
||||
|
||||
ninja
|
||||
ninja all_fuzzers
|
||||
cd ..
|
||||
fi
|
||||
|
||||
@@ -43,9 +45,11 @@ if [ ! -d build-$variant ] ; then
|
||||
-DCMAKE_BUILD_TYPE=Debug \
|
||||
-DSIMDJSON_BUILD_STATIC=On \
|
||||
-DENABLE_FUZZING=On \
|
||||
-DSIMDJSON_COMPETITION=OFF \
|
||||
-DSIMDJSON_GOOGLE_BENCHMARKS=OFF \
|
||||
-DSIMDJSON_FUZZ_LINKMAIN=On
|
||||
|
||||
ninja
|
||||
ninja all_fuzzers
|
||||
cd ..
|
||||
fi
|
||||
|
||||
@@ -67,22 +71,24 @@ if [ ! -d build-$variant ] ; then
|
||||
-DCMAKE_BUILD_TYPE=Debug \
|
||||
-DSIMDJSON_BUILD_STATIC=On \
|
||||
-DENABLE_FUZZING=On \
|
||||
-DSIMDJSON_COMPETITION=OFF \
|
||||
-DSIMDJSON_GOOGLE_BENCHMARKS=OFF \
|
||||
-DSIMDJSON_FUZZ_LINKMAIN=Off \
|
||||
-DSIMDJSON_FUZZ_LDFLAGS=$LIB_FUZZING_ENGINE \
|
||||
-DSIMDJSON_IMPLEMENTATION_HASWELL=0
|
||||
|
||||
ninja
|
||||
ninja all_fuzzers
|
||||
cd ..
|
||||
fi
|
||||
|
||||
|
||||
# a fuzzer with sanitizers, built with avx disabled.
|
||||
variant=ossfuzz-noavx8
|
||||
if which clang++-8 >/dev/null 2>&1 ; then
|
||||
variant=ossfuzz-noavx9
|
||||
if which clang++-9 >/dev/null 2>&1 ; then
|
||||
if [ ! -d build-$variant ] ; then
|
||||
|
||||
export CC=clang-8
|
||||
export CXX="clang++-8"
|
||||
export CC=clang-9
|
||||
export CXX="clang++-9"
|
||||
export CFLAGS="-fsanitize=fuzzer-no-link,address,undefined -fno-sanitize-recover=undefined -mno-avx2 -mno-avx "
|
||||
export CXXFLAGS="-fsanitize=fuzzer-no-link,address,undefined -fno-sanitize-recover=undefined -mno-avx2 -mno-avx"
|
||||
export LIB_FUZZING_ENGINE="-fsanitize=fuzzer"
|
||||
@@ -95,15 +101,17 @@ if which clang++-8 >/dev/null 2>&1 ; then
|
||||
-DCMAKE_BUILD_TYPE=Debug \
|
||||
-DSIMDJSON_BUILD_STATIC=On \
|
||||
-DENABLE_FUZZING=On \
|
||||
-DSIMDJSON_COMPETITION=OFF \
|
||||
-DSIMDJSON_GOOGLE_BENCHMARKS=OFF \
|
||||
-DSIMDJSON_FUZZ_LINKMAIN=Off \
|
||||
-DSIMDJSON_FUZZ_LDFLAGS=$LIB_FUZZING_ENGINE \
|
||||
-DSIMDJSON_IMPLEMENTATION_HASWELL=0
|
||||
|
||||
ninja
|
||||
ninja all_fuzzers
|
||||
cd ..
|
||||
fi
|
||||
else
|
||||
echo "$me: WARNING clang++-8 not found, please install it to build $variant"
|
||||
echo "$me: WARNING clang++-9 not found, please install it to build $variant"
|
||||
fi
|
||||
|
||||
# a fuzzer with sanitizers, default built
|
||||
@@ -124,19 +132,21 @@ if [ ! -d build-$variant ] ; then
|
||||
-DCMAKE_BUILD_TYPE=Debug \
|
||||
-DSIMDJSON_BUILD_STATIC=On \
|
||||
-DENABLE_FUZZING=On \
|
||||
-DSIMDJSON_COMPETITION=OFF \
|
||||
-DSIMDJSON_GOOGLE_BENCHMARKS=OFF \
|
||||
-DSIMDJSON_FUZZ_LINKMAIN=Off \
|
||||
-DSIMDJSON_FUZZ_LDFLAGS=$LIB_FUZZING_ENGINE
|
||||
|
||||
ninja
|
||||
ninja all_fuzzers
|
||||
cd ..
|
||||
fi
|
||||
|
||||
# a fast fuzzer, for fast exploration
|
||||
variant=ossfuzz-fast8
|
||||
if which clang++-8 >/dev/null 2>&1 ; then
|
||||
variant=ossfuzz-fast9
|
||||
if which clang++-9 >/dev/null 2>&1 ; then
|
||||
if [ ! -d build-$variant ] ; then
|
||||
export CC=clang-8
|
||||
export CXX="clang++-8"
|
||||
export CC=clang-9
|
||||
export CXX="clang++-9"
|
||||
export CFLAGS="-fsanitize=fuzzer-no-link -O3 -g"
|
||||
export CXXFLAGS="-fsanitize=fuzzer-no-link -O3 -g"
|
||||
export LIB_FUZZING_ENGINE="-fsanitize=fuzzer"
|
||||
@@ -149,14 +159,16 @@ if which clang++-8 >/dev/null 2>&1 ; then
|
||||
-DCMAKE_BUILD_TYPE= \
|
||||
-DSIMDJSON_BUILD_STATIC=On \
|
||||
-DENABLE_FUZZING=On \
|
||||
-DSIMDJSON_COMPETITION=OFF \
|
||||
-DSIMDJSON_GOOGLE_BENCHMARKS=OFF \
|
||||
-DSIMDJSON_FUZZ_LINKMAIN=Off \
|
||||
-DSIMDJSON_FUZZ_LDFLAGS=$LIB_FUZZING_ENGINE
|
||||
|
||||
ninja
|
||||
ninja all_fuzzers
|
||||
|
||||
cd ..
|
||||
fi
|
||||
else
|
||||
echo "$me: WARNING clang++-8 not found, please install it to build $variant"
|
||||
echo "$me: WARNING clang++-9 not found, please install it to build $variant"
|
||||
fi
|
||||
|
||||
|
||||
+43
-43
@@ -3,58 +3,58 @@
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
#include "NullBuffer.h"
|
||||
|
||||
// from the README on the front page
|
||||
void compute_dump(simdjson::ParsedJson::Iterator &pjh) {
|
||||
NulOStream os;
|
||||
|
||||
if (pjh.is_object()) {
|
||||
os << "{";
|
||||
if (pjh.down()) {
|
||||
pjh.print(os); // must be a string
|
||||
os << ":";
|
||||
pjh.next();
|
||||
compute_dump(pjh); // let us recurse
|
||||
while (pjh.next()) {
|
||||
os << ",";
|
||||
pjh.print(os);
|
||||
os << ":";
|
||||
pjh.next();
|
||||
compute_dump(pjh); // let us recurse
|
||||
}
|
||||
pjh.up();
|
||||
}
|
||||
os << "}";
|
||||
} else if (pjh.is_array()) {
|
||||
// example from doc/basics.md#tree-walking-and-json-element-types
|
||||
static void print_json(std::ostream& os, simdjson::dom::element element) {
|
||||
const char endl='\n';
|
||||
switch (element.type()) {
|
||||
case simdjson::dom::element_type::ARRAY:
|
||||
os << "[";
|
||||
if (pjh.down()) {
|
||||
compute_dump(pjh); // let us recurse
|
||||
while (pjh.next()) {
|
||||
os << ",";
|
||||
compute_dump(pjh); // let us recurse
|
||||
}
|
||||
pjh.up();
|
||||
for (simdjson::dom::element child : element.get<simdjson::dom::array>().first) {
|
||||
print_json(os, child);
|
||||
os << ",";
|
||||
}
|
||||
os << "]";
|
||||
} else {
|
||||
pjh.print(os); // just print the lone value
|
||||
break;
|
||||
case simdjson::dom::element_type::OBJECT:
|
||||
os << "{";
|
||||
for (simdjson::dom::key_value_pair field : element.get<simdjson::dom::object>().first) {
|
||||
os << "\"" << field.key << "\": ";
|
||||
print_json(os, field.value);
|
||||
}
|
||||
os << "}";
|
||||
break;
|
||||
case simdjson::dom::element_type::INT64:
|
||||
os << element.get<int64_t>().first << endl;
|
||||
break;
|
||||
case simdjson::dom::element_type::UINT64:
|
||||
os << element.get<uint64_t>().first << endl;
|
||||
break;
|
||||
case simdjson::dom::element_type::DOUBLE:
|
||||
os << element.get<double>().first << endl;
|
||||
break;
|
||||
case simdjson::dom::element_type::STRING:
|
||||
os << element.get<std::string_view>().first << endl;
|
||||
break;
|
||||
case simdjson::dom::element_type::BOOL:
|
||||
os << element.get<bool>().first << endl;
|
||||
break;
|
||||
case simdjson::dom::element_type::NULL_VALUE:
|
||||
os << "null" << endl;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
|
||||
simdjson::dom::parser parser;
|
||||
simdjson::dom::element elem;
|
||||
auto error = parser.parse(Data, Size).get(elem);
|
||||
|
||||
try {
|
||||
auto pj = simdjson::build_parsed_json(Data, Size);
|
||||
if (!pj.is_valid()) {
|
||||
throw 1;
|
||||
}
|
||||
simdjson::ParsedJson::Iterator pjh(pj);
|
||||
if (pjh.is_ok()) {
|
||||
compute_dump(pjh);
|
||||
}
|
||||
} catch (...) {
|
||||
}
|
||||
if (error) { return 1; }
|
||||
NulOStream os;
|
||||
//std::ostream& os(std::cout);
|
||||
print_json(os,elem);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -7,12 +7,12 @@
|
||||
#include "NullBuffer.h"
|
||||
|
||||
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
|
||||
simdjson::dom::parser parser;
|
||||
simdjson::dom::element elem;
|
||||
auto error = parser.parse(Data, Size).get(elem);
|
||||
if (error) { return 1; }
|
||||
|
||||
try {
|
||||
auto pj = simdjson::build_parsed_json(Data, Size);
|
||||
NulOStream os;
|
||||
UNUSED bool ignored=pj.dump_raw_tape(os);
|
||||
} catch (...) {
|
||||
}
|
||||
return 0;
|
||||
UNUSED auto dumpstatus = elem.dump_raw_tape(os);
|
||||
return 0;
|
||||
}
|
||||
|
||||
+10
-5
@@ -4,11 +4,16 @@
|
||||
#include <string>
|
||||
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
|
||||
|
||||
auto begin = (const char *)Data;
|
||||
auto end = begin + Size;
|
||||
auto begin = (const char *)Data;
|
||||
auto end = begin + Size;
|
||||
|
||||
std::string str(begin, end);
|
||||
std::string str(begin, end);
|
||||
simdjson::dom::parser parser;
|
||||
simdjson::dom::element elem;
|
||||
auto error = parser.parse(str).get(elem);
|
||||
if (error) { return 1; }
|
||||
|
||||
simdjson::json_minify(str.data(), str.size(), str.data());
|
||||
return 0;
|
||||
std::string minified=simdjson::minify(elem);
|
||||
(void)minified;
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
|
||||
|
||||
auto ignored = simdjson::build_parsed_json(Data, Size);
|
||||
|
||||
simdjson::dom::parser parser;
|
||||
UNUSED simdjson::dom::element elem;
|
||||
UNUSED auto error = parser.parse(Data, Size).get(elem);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -7,13 +7,12 @@
|
||||
|
||||
|
||||
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
|
||||
|
||||
try {
|
||||
auto pj = simdjson::build_parsed_json(Data, Size);
|
||||
simdjson::dom::parser parser;
|
||||
simdjson::dom::element elem;
|
||||
auto error = parser.parse(Data, Size).get(elem);
|
||||
if (!error) {
|
||||
NulOStream os;
|
||||
bool ignored=pj.print_json(os);
|
||||
(void)ignored;
|
||||
} catch (...) {
|
||||
os<<elem;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ if [ ! -d $bdir ] ; then
|
||||
-DSIMDJSON_BUILD_STATIC=On \
|
||||
-DENABLE_FUZZING=On \
|
||||
-DSIMDJSON_FUZZ_LINKMAIN=On
|
||||
ninja
|
||||
ninja all_fuzzers
|
||||
cd ..
|
||||
fi
|
||||
|
||||
|
||||
+3
-2
@@ -30,14 +30,15 @@ cmake .. \
|
||||
-DCMAKE_BUILD_TYPE=Debug \
|
||||
-DSIMDJSON_BUILD_STATIC=On \
|
||||
-DENABLE_FUZZING=On \
|
||||
-DSIMDJSON_COMPETITION=Off \
|
||||
-DSIMDJSON_FUZZ_LINKMAIN=Off \
|
||||
-DSIMDJSON_FUZZ_LDFLAGS=$LIB_FUZZING_ENGINE
|
||||
|
||||
cmake --build .
|
||||
cmake --build . --target all_fuzzers
|
||||
|
||||
cp fuzz/fuzz_* $OUT
|
||||
|
||||
# all corpora are equal, they all take json as input
|
||||
for f in $OUT/fuzz* ; do
|
||||
for f in $(ls $OUT/fuzz* |grep -v '.zip$') ; do
|
||||
cp ../corpus.zip $OUT/$(basename $f).zip
|
||||
done
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
+13
-24
@@ -1,24 +1,13 @@
|
||||
set(SIMDJSON_INCLUDE_DIR ${PROJECT_SOURCE_DIR}/include)
|
||||
set(SIMDJSON_INCLUDE
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/common_defs.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/compiler_check.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/document_stream.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/document.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/error.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/implementation.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/inline/document_stream.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/inline/document.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/inline/error.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/inline/padded_string.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/inline/parsedjson_iterator.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/internal/jsonformatutils.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/jsonioutil.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/jsonparser.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/padded_string.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/parsedjson.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/parsedjson_iterator.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/portability.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/simdjson_version.h
|
||||
${SIMDJSON_INCLUDE_DIR}/simdjson/simdjson.h
|
||||
)
|
||||
#
|
||||
# Provides the simdjson headers.
|
||||
#
|
||||
# target_link_libraries(my-project simdjson-headers) grants the headers. It does not provide the
|
||||
# source, libraries or any compiler flags.
|
||||
#
|
||||
add_library(simdjson-headers INTERFACE)
|
||||
target_compile_features(simdjson-headers INTERFACE cxx_std_11) # headers require at least C++11
|
||||
target_include_directories(simdjson-headers INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>
|
||||
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCDIR}>)
|
||||
|
||||
install(TARGETS simdjson-headers EXPORT simdjson-config INCLUDES DESTINATION include)
|
||||
|
||||
+21
-6
@@ -8,25 +8,40 @@
|
||||
*/
|
||||
|
||||
#include "simdjson/compiler_check.h"
|
||||
#include "simdjson/common_defs.h"
|
||||
|
||||
SIMDJSON_PUSH_DISABLE_WARNINGS
|
||||
SIMDJSON_DISABLE_UNDESIRED_WARNINGS
|
||||
|
||||
// Public API
|
||||
#include "simdjson/simdjson_version.h"
|
||||
#include "simdjson/error.h"
|
||||
#include "simdjson/padded_string.h"
|
||||
#include "simdjson/implementation.h"
|
||||
#include "simdjson/document.h"
|
||||
#include "simdjson/document_stream.h"
|
||||
#include "simdjson/dom/array.h"
|
||||
#include "simdjson/dom/document_stream.h"
|
||||
#include "simdjson/dom/document.h"
|
||||
#include "simdjson/dom/element.h"
|
||||
#include "simdjson/dom/object.h"
|
||||
#include "simdjson/dom/parser.h"
|
||||
|
||||
// Deprecated API
|
||||
#include "simdjson/jsonparser.h"
|
||||
#include "simdjson/parsedjson.h"
|
||||
#include "simdjson/parsedjson_iterator.h"
|
||||
#include "simdjson/dom/jsonparser.h"
|
||||
#include "simdjson/dom/parsedjson.h"
|
||||
#include "simdjson/dom/parsedjson_iterator.h"
|
||||
|
||||
// Inline functions
|
||||
#include "simdjson/inline/document.h"
|
||||
#include "simdjson/inline/array.h"
|
||||
#include "simdjson/inline/document_stream.h"
|
||||
#include "simdjson/inline/document.h"
|
||||
#include "simdjson/inline/element.h"
|
||||
#include "simdjson/inline/error.h"
|
||||
#include "simdjson/inline/object.h"
|
||||
#include "simdjson/inline/padded_string.h"
|
||||
#include "simdjson/inline/parsedjson_iterator.h"
|
||||
#include "simdjson/inline/parser.h"
|
||||
#include "simdjson/inline/tape_ref.h"
|
||||
|
||||
SIMDJSON_POP_DISABLE_WARNINGS
|
||||
|
||||
#endif // SIMDJSON_H
|
||||
|
||||
+148
-53
@@ -37,20 +37,23 @@ constexpr size_t DEFAULT_MAX_DEPTH = 1024;
|
||||
} // namespace simdjson
|
||||
|
||||
#if defined(__GNUC__)
|
||||
// Marks a block with a name so that MCA analysis can see it.
|
||||
#define BEGIN_DEBUG_BLOCK(name) __asm volatile("# LLVM-MCA-BEGIN " #name);
|
||||
#define END_DEBUG_BLOCK(name) __asm volatile("# LLVM-MCA-END " #name);
|
||||
#define DEBUG_BLOCK(name, block) BEGIN_DEBUG_BLOCK(name); block; END_DEBUG_BLOCK(name);
|
||||
// Marks a block with a name so that MCA analysis can see it.
|
||||
#define BEGIN_DEBUG_BLOCK(name) __asm volatile("# LLVM-MCA-BEGIN " #name);
|
||||
#define END_DEBUG_BLOCK(name) __asm volatile("# LLVM-MCA-END " #name);
|
||||
#define DEBUG_BLOCK(name, block) BEGIN_DEBUG_BLOCK(name); block; END_DEBUG_BLOCK(name);
|
||||
#else
|
||||
#define BEGIN_DEBUG_BLOCK(name)
|
||||
#define END_DEBUG_BLOCK(name)
|
||||
#define DEBUG_BLOCK(name, block)
|
||||
#define BEGIN_DEBUG_BLOCK(name)
|
||||
#define END_DEBUG_BLOCK(name)
|
||||
#define DEBUG_BLOCK(name, block)
|
||||
#endif
|
||||
|
||||
#if !defined(_MSC_VER) && !defined(SIMDJSON_NO_COMPUTED_GOTO)
|
||||
// Implemented using Labels as Values which works in GCC and CLANG (and maybe
|
||||
// also in Intel's compiler), but won't work in MSVC.
|
||||
#define SIMDJSON_USE_COMPUTED_GOTO
|
||||
#if !defined(SIMDJSON_REGULAR_VISUAL_STUDIO) && !defined(SIMDJSON_NO_COMPUTED_GOTO)
|
||||
// We assume here that *only* regular visual studio
|
||||
// does not support computed gotos.
|
||||
// Implemented using Labels as Values which works in GCC and CLANG (and maybe
|
||||
// also in Intel's compiler), but won't work in MSVC.
|
||||
// Compute gotos are good for performance, enable them if you can.
|
||||
#define SIMDJSON_USE_COMPUTED_GOTO
|
||||
#endif
|
||||
|
||||
// Align to N-byte boundary
|
||||
@@ -59,55 +62,147 @@ constexpr size_t DEFAULT_MAX_DEPTH = 1024;
|
||||
|
||||
#define ISALIGNED_N(ptr, n) (((uintptr_t)(ptr) & ((n)-1)) == 0)
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#define really_inline __forceinline
|
||||
#define never_inline __declspec(noinline)
|
||||
#if defined(SIMDJSON_REGULAR_VISUAL_STUDIO)
|
||||
|
||||
#define UNUSED
|
||||
#define WARN_UNUSED
|
||||
#define really_inline __forceinline
|
||||
#define never_inline __declspec(noinline)
|
||||
|
||||
#ifndef likely
|
||||
#define likely(x) x
|
||||
#endif
|
||||
#ifndef unlikely
|
||||
#define unlikely(x) x
|
||||
#endif
|
||||
#define UNUSED
|
||||
#define WARN_UNUSED
|
||||
|
||||
#define SIMDJSON_PUSH_DISABLE_WARNINGS __pragma(warning( push ))
|
||||
#define SIMDJSON_PUSH_DISABLE_ALL_WARNINGS __pragma(warning( push, 0 ))
|
||||
#define SIMDJSON_DISABLE_VS_WARNING(WARNING_NUMBER) __pragma(warning( disable : WARNING_NUMBER ))
|
||||
#define SIMDJSON_DISABLE_DEPRECATED_WARNING SIMDJSON_DISABLE_VS_WARNING(4996)
|
||||
#define SIMDJSON_POP_DISABLE_WARNINGS __pragma(warning( pop ))
|
||||
#ifndef likely
|
||||
#define likely(x) x
|
||||
#endif
|
||||
#ifndef unlikely
|
||||
#define unlikely(x) x
|
||||
#endif
|
||||
|
||||
#else // MSC_VER
|
||||
#define SIMDJSON_PUSH_DISABLE_WARNINGS __pragma(warning( push ))
|
||||
#define SIMDJSON_PUSH_DISABLE_ALL_WARNINGS __pragma(warning( push, 0 ))
|
||||
#define SIMDJSON_DISABLE_VS_WARNING(WARNING_NUMBER) __pragma(warning( disable : WARNING_NUMBER ))
|
||||
// Get rid of Intellisense-only warnings (Code Analysis)
|
||||
// Though __has_include is C++17, it is supported in Visual Studio 2017 or better (_MSC_VER>=1910).
|
||||
#if defined(_MSC_VER) && (_MSC_VER>=1910)
|
||||
#if __has_include(<CppCoreCheck\Warnings.h>)
|
||||
#include <CppCoreCheck\Warnings.h>
|
||||
#define SIMDJSON_DISABLE_UNDESIRED_WARNINGS SIMDJSON_DISABLE_VS_WARNING(ALL_CPPCORECHECK_WARNINGS)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef SIMDJSON_DISABLE_UNDESIRED_WARNINGS
|
||||
#define SIMDJSON_DISABLE_UNDESIRED_WARNINGS
|
||||
#endif
|
||||
|
||||
#define SIMDJSON_DISABLE_DEPRECATED_WARNING SIMDJSON_DISABLE_VS_WARNING(4996)
|
||||
#define SIMDJSON_POP_DISABLE_WARNINGS __pragma(warning( pop ))
|
||||
|
||||
#else // SIMDJSON_REGULAR_VISUAL_STUDIO
|
||||
|
||||
#define really_inline inline __attribute__((always_inline, unused))
|
||||
#define never_inline inline __attribute__((noinline, unused))
|
||||
|
||||
#define UNUSED __attribute__((unused))
|
||||
#define WARN_UNUSED __attribute__((warn_unused_result))
|
||||
|
||||
#ifndef likely
|
||||
#define likely(x) __builtin_expect(!!(x), 1)
|
||||
#endif
|
||||
#ifndef unlikely
|
||||
#define unlikely(x) __builtin_expect(!!(x), 0)
|
||||
#endif
|
||||
|
||||
#define SIMDJSON_PUSH_DISABLE_WARNINGS _Pragma("GCC diagnostic push")
|
||||
// gcc doesn't seem to disable all warnings with all and extra, add warnings here as necessary
|
||||
#define SIMDJSON_PUSH_DISABLE_ALL_WARNINGS SIMDJSON_PUSH_DISABLE_WARNINGS \
|
||||
SIMDJSON_DISABLE_GCC_WARNING(-Weffc++) \
|
||||
SIMDJSON_DISABLE_GCC_WARNING(-Wall) \
|
||||
SIMDJSON_DISABLE_GCC_WARNING(-Wconversion) \
|
||||
SIMDJSON_DISABLE_GCC_WARNING(-Wextra) \
|
||||
SIMDJSON_DISABLE_GCC_WARNING(-Wattributes) \
|
||||
SIMDJSON_DISABLE_GCC_WARNING(-Wimplicit-fallthrough) \
|
||||
SIMDJSON_DISABLE_GCC_WARNING(-Wnon-virtual-dtor) \
|
||||
SIMDJSON_DISABLE_GCC_WARNING(-Wreturn-type) \
|
||||
SIMDJSON_DISABLE_GCC_WARNING(-Wshadow) \
|
||||
SIMDJSON_DISABLE_GCC_WARNING(-Wunused-parameter) \
|
||||
SIMDJSON_DISABLE_GCC_WARNING(-Wunused-variable)
|
||||
#define SIMDJSON_PRAGMA(P) _Pragma(#P)
|
||||
#define SIMDJSON_DISABLE_GCC_WARNING(WARNING) SIMDJSON_PRAGMA(GCC diagnostic ignored #WARNING)
|
||||
#if defined(SIMDJSON_CLANG_VISUAL_STUDIO)
|
||||
#define SIMDJSON_DISABLE_UNDESIRED_WARNINGS SIMDJSON_DISABLE_GCC_WARNING(-Wmicrosoft-include)
|
||||
#else
|
||||
#define SIMDJSON_DISABLE_UNDESIRED_WARNINGS
|
||||
#endif
|
||||
#define SIMDJSON_DISABLE_DEPRECATED_WARNING SIMDJSON_DISABLE_GCC_WARNING(-Wdeprecated-declarations)
|
||||
#define SIMDJSON_POP_DISABLE_WARNINGS _Pragma("GCC diagnostic pop")
|
||||
|
||||
|
||||
#define really_inline inline __attribute__((always_inline, unused))
|
||||
#define never_inline inline __attribute__((noinline, unused))
|
||||
|
||||
#define UNUSED __attribute__((unused))
|
||||
#define WARN_UNUSED __attribute__((warn_unused_result))
|
||||
|
||||
#ifndef likely
|
||||
#define likely(x) __builtin_expect(!!(x), 1)
|
||||
#endif
|
||||
#ifndef unlikely
|
||||
#define unlikely(x) __builtin_expect(!!(x), 0)
|
||||
#endif
|
||||
|
||||
#define SIMDJSON_PUSH_DISABLE_WARNINGS _Pragma("GCC diagnostic push")
|
||||
// gcc doesn't seem to disable all warnings with all and extra, add warnings here as necessary
|
||||
#define SIMDJSON_PUSH_DISABLE_ALL_WARNINGS SIMDJSON_PUSH_DISABLE_WARNINGS \
|
||||
SIMDJSON_DISABLE_GCC_WARNING(-Wall) \
|
||||
SIMDJSON_DISABLE_GCC_WARNING(-Wextra) \
|
||||
SIMDJSON_DISABLE_GCC_WARNING(-Wshadow) \
|
||||
SIMDJSON_DISABLE_GCC_WARNING(-Wunused-parameter) \
|
||||
SIMDJSON_DISABLE_GCC_WARNING(-Wimplicit-fallthrough)
|
||||
#define SIMDJSON_PRAGMA(P) _Pragma(#P)
|
||||
#define SIMDJSON_DISABLE_GCC_WARNING(WARNING) SIMDJSON_PRAGMA(GCC diagnostic ignored #WARNING)
|
||||
#define SIMDJSON_DISABLE_DEPRECATED_WARNING SIMDJSON_DISABLE_GCC_WARNING(-Wdeprecated-declarations)
|
||||
#define SIMDJSON_POP_DISABLE_WARNINGS _Pragma("GCC diagnostic pop")
|
||||
|
||||
#endif // MSC_VER
|
||||
|
||||
#if defined(SIMDJSON_VISUAL_STUDIO)
|
||||
/**
|
||||
* It does not matter here whether you are using
|
||||
* the regular visual studio or clang under visual
|
||||
* studio.
|
||||
*/
|
||||
#if SIMDJSON_USING_LIBRARY
|
||||
#define SIMDJSON_DLLIMPORTEXPORT __declspec(dllimport)
|
||||
#else
|
||||
#define SIMDJSON_DLLIMPORTEXPORT __declspec(dllexport)
|
||||
#endif
|
||||
#else
|
||||
#define SIMDJSON_DLLIMPORTEXPORT
|
||||
#endif
|
||||
|
||||
// C++17 requires string_view.
|
||||
#if SIMDJSON_CPLUSPLUS17
|
||||
#define SIMDJSON_HAS_STRING_VIEW
|
||||
#endif
|
||||
|
||||
// This macro (__cpp_lib_string_view) has to be defined
|
||||
// for C++17 and better, but if it is otherwise defined,
|
||||
// we are going to assume that string_view is available
|
||||
// even if we do not have C++17 support.
|
||||
#ifdef __cpp_lib_string_view
|
||||
#define SIMDJSON_HAS_STRING_VIEW
|
||||
#endif
|
||||
|
||||
// Some systems have string_view even if we do not have C++17 support,
|
||||
// and even if __cpp_lib_string_view is undefined, it is the case
|
||||
// with Apple clang version 11.
|
||||
// We must handle it. *This is important.*
|
||||
#ifndef SIMDJSON_HAS_STRING_VIEW
|
||||
#if defined __has_include
|
||||
// do not combine the next #if with the previous one (unsafe)
|
||||
#if __has_include (<string_view>)
|
||||
// now it is safe to trigger the include
|
||||
#include <string_view> // though the file is there, it does not follow that we got the implementation
|
||||
#if defined(_LIBCPP_STRING_VIEW)
|
||||
// Ah! So we under libc++ which under its Library Fundamentals Technical Specification, which preceeded C++17,
|
||||
// included string_view.
|
||||
// This means that we have string_view *even though* we may not have C++17.
|
||||
#define SIMDJSON_HAS_STRING_VIEW
|
||||
#endif // _LIBCPP_STRING_VIEW
|
||||
#endif // __has_include (<string_view>)
|
||||
#endif // defined __has_include
|
||||
#endif // def SIMDJSON_HAS_STRING_VIEW
|
||||
// end of complicated but important routine to try to detect string_view.
|
||||
|
||||
//
|
||||
// Backfill std::string_view using nonstd::string_view on systems where
|
||||
// we expect that string_view is missing. Important: if we get this wrong,
|
||||
// we will end up with two string_view definitions and potential trouble.
|
||||
// That is why we work so hard above to avoid it.
|
||||
//
|
||||
#ifndef SIMDJSON_HAS_STRING_VIEW
|
||||
SIMDJSON_PUSH_DISABLE_ALL_WARNINGS
|
||||
#include "simdjson/nonstd/string_view.hpp"
|
||||
SIMDJSON_POP_DISABLE_WARNINGS
|
||||
|
||||
namespace std {
|
||||
using string_view = nonstd::string_view;
|
||||
}
|
||||
#endif // SIMDJSON_HAS_STRING_VIEW
|
||||
#undef SIMDJSON_HAS_STRING_VIEW // We are not going to need this macro anymore.
|
||||
|
||||
#endif // SIMDJSON_COMMON_DEFS_H
|
||||
|
||||
@@ -13,8 +13,23 @@
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if (SIMDJSON_CPLUSPLUS < 201703L)
|
||||
#error simdjson requires a compiler compliant with the C++17 standard
|
||||
// C++ 17
|
||||
#if !defined(SIMDJSON_CPLUSPLUS17) && (SIMDJSON_CPLUSPLUS >= 201703L)
|
||||
#define SIMDJSON_CPLUSPLUS17 1
|
||||
#endif
|
||||
|
||||
// C++ 14
|
||||
#if !defined(SIMDJSON_CPLUSPLUS14) && (SIMDJSON_CPLUSPLUS >= 201402L)
|
||||
#define SIMDJSON_CPLUSPLUS14 1
|
||||
#endif
|
||||
|
||||
// C++ 11
|
||||
#if !defined(SIMDJSON_CPLUSPLUS11) && (SIMDJSON_CPLUSPLUS >= 201103L)
|
||||
#define SIMDJSON_CPLUSPLUS11 1
|
||||
#endif
|
||||
|
||||
#ifndef SIMDJSON_CPLUSPLUS11
|
||||
#error simdjson requires a compiler compliant with the C++11 standard
|
||||
#endif
|
||||
|
||||
#endif // SIMDJSON_COMPILER_CHECK_H
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,143 +0,0 @@
|
||||
#ifndef SIMDJSON_DOCUMENT_STREAM_H
|
||||
#define SIMDJSON_DOCUMENT_STREAM_H
|
||||
|
||||
#include <thread>
|
||||
#include "simdjson/document.h"
|
||||
|
||||
namespace simdjson::dom {
|
||||
|
||||
/**
|
||||
* A forward-only stream of documents.
|
||||
*
|
||||
* Produced by parser::parse_many.
|
||||
*
|
||||
*/
|
||||
class document_stream {
|
||||
public:
|
||||
really_inline ~document_stream() noexcept;
|
||||
|
||||
/**
|
||||
* An iterator through a forward-only stream of documents.
|
||||
*/
|
||||
class iterator {
|
||||
public:
|
||||
/**
|
||||
* Get the current document (or error).
|
||||
*/
|
||||
really_inline simdjson_result<element> operator*() noexcept;
|
||||
/**
|
||||
* Advance to the next document.
|
||||
*/
|
||||
inline iterator& operator++() noexcept;
|
||||
/**
|
||||
* Check if we're at the end yet.
|
||||
* @param other the end iterator to compare to.
|
||||
*/
|
||||
really_inline bool operator!=(const iterator &other) const noexcept;
|
||||
|
||||
private:
|
||||
iterator(document_stream& stream, bool finished) noexcept;
|
||||
/** The document_stream we're iterating through. */
|
||||
document_stream& stream;
|
||||
/** Whether we're finished or not. */
|
||||
bool finished;
|
||||
friend class document_stream;
|
||||
};
|
||||
|
||||
/**
|
||||
* Start iterating the documents in the stream.
|
||||
*/
|
||||
really_inline iterator begin() noexcept;
|
||||
/**
|
||||
* The end of the stream, for iterator comparison purposes.
|
||||
*/
|
||||
really_inline iterator end() noexcept;
|
||||
|
||||
private:
|
||||
|
||||
document_stream &operator=(const document_stream &) = delete; // Disallow copying
|
||||
|
||||
document_stream(document_stream &other) = delete; // Disallow copying
|
||||
|
||||
really_inline document_stream(dom::parser &parser, const uint8_t *buf, size_t len, size_t batch_size, error_code error = SUCCESS) noexcept;
|
||||
|
||||
/**
|
||||
* Parse the next document found in the buffer previously given to document_stream.
|
||||
*
|
||||
* The content should be a valid JSON document encoded as UTF-8. If there is a
|
||||
* UTF-8 BOM, the caller is responsible for omitting it, UTF-8 BOM are
|
||||
* discouraged.
|
||||
*
|
||||
* You do NOT need to pre-allocate a parser. This function takes care of
|
||||
* pre-allocating a capacity defined by the batch_size defined when creating the
|
||||
* document_stream object.
|
||||
*
|
||||
* The function returns simdjson::SUCCESS_AND_HAS_MORE (an integer = 1) in case
|
||||
* of success and indicates that the buffer still contains more data to be parsed,
|
||||
* meaning this function can be called again to return the next JSON document
|
||||
* after this one.
|
||||
*
|
||||
* The function returns simdjson::SUCCESS (as integer = 0) in case of success
|
||||
* and indicates that the buffer has successfully been parsed to the end.
|
||||
* Every document it contained has been parsed without error.
|
||||
*
|
||||
* The function returns an error code from simdjson/simdjson.h in case of failure
|
||||
* such as simdjson::CAPACITY, simdjson::MEMALLOC, simdjson::DEPTH_ERROR and so forth;
|
||||
* the simdjson::error_message function converts these error codes into a string).
|
||||
*
|
||||
* You can also check validity by calling parser.is_valid(). The same parser can
|
||||
* and should be reused for the other documents in the buffer. */
|
||||
inline error_code json_parse() noexcept;
|
||||
|
||||
/**
|
||||
* Returns the location (index) of where the next document should be in the
|
||||
* buffer.
|
||||
* Can be used for debugging, it tells the user the position of the end of the
|
||||
* last
|
||||
* valid JSON document parsed
|
||||
*/
|
||||
inline size_t get_current_buffer_loc() const { return current_buffer_loc; }
|
||||
|
||||
/**
|
||||
* Returns the total amount of complete documents parsed by the document_stream,
|
||||
* in the current buffer, at the given time.
|
||||
*/
|
||||
inline size_t get_n_parsed_docs() const { return n_parsed_docs; }
|
||||
|
||||
/**
|
||||
* Returns the total amount of data (in bytes) parsed by the document_stream,
|
||||
* in the current buffer, at the given time.
|
||||
*/
|
||||
inline size_t get_n_bytes_parsed() const { return n_bytes_parsed; }
|
||||
|
||||
inline const uint8_t *buf() const { return _buf + buf_start; }
|
||||
|
||||
inline void advance(size_t offset) { buf_start += offset; }
|
||||
|
||||
inline size_t remaining() const { return _len - buf_start; }
|
||||
|
||||
dom::parser &parser;
|
||||
const uint8_t *_buf;
|
||||
const size_t _len;
|
||||
size_t _batch_size; // this is actually variable!
|
||||
size_t buf_start{0};
|
||||
size_t next_json{0};
|
||||
bool load_next_batch{true};
|
||||
size_t current_buffer_loc{0};
|
||||
#ifdef SIMDJSON_THREADS_ENABLED
|
||||
size_t last_json_buffer_loc{0};
|
||||
#endif
|
||||
size_t n_parsed_docs{0};
|
||||
size_t n_bytes_parsed{0};
|
||||
error_code error{SUCCESS_AND_HAS_MORE};
|
||||
#ifdef SIMDJSON_THREADS_ENABLED
|
||||
error_code stage1_is_ok_thread{SUCCESS};
|
||||
std::thread stage_1_thread;
|
||||
dom::parser parser_thread;
|
||||
#endif
|
||||
friend class dom::parser;
|
||||
}; // class document_stream
|
||||
|
||||
} // end of namespace simdjson::dom
|
||||
|
||||
#endif // SIMDJSON_DOCUMENT_STREAM_H
|
||||
@@ -0,0 +1,158 @@
|
||||
#ifndef SIMDJSON_DOM_ARRAY_H
|
||||
#define SIMDJSON_DOM_ARRAY_H
|
||||
|
||||
#include "simdjson/common_defs.h"
|
||||
#include "simdjson/error.h"
|
||||
#include "simdjson/internal/tape_ref.h"
|
||||
#include "simdjson/minify.h"
|
||||
#include <ostream>
|
||||
|
||||
namespace simdjson {
|
||||
namespace dom {
|
||||
|
||||
class document;
|
||||
class element;
|
||||
|
||||
/**
|
||||
* JSON array.
|
||||
*/
|
||||
class array {
|
||||
public:
|
||||
/** Create a new, invalid array */
|
||||
really_inline array() noexcept;
|
||||
|
||||
class iterator {
|
||||
public:
|
||||
/**
|
||||
* Get the actual value
|
||||
*/
|
||||
inline element operator*() const noexcept;
|
||||
/**
|
||||
* Get the next value.
|
||||
*
|
||||
* Part of the std::iterator interface.
|
||||
*
|
||||
*/
|
||||
inline iterator& operator++() noexcept;
|
||||
/**
|
||||
* Check if these values come from the same place in the JSON.
|
||||
*
|
||||
* Part of the std::iterator interface.
|
||||
*/
|
||||
inline bool operator!=(const iterator& other) const noexcept;
|
||||
private:
|
||||
really_inline iterator(const internal::tape_ref &tape) noexcept;
|
||||
internal::tape_ref tape;
|
||||
friend class array;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the first array element.
|
||||
*
|
||||
* Part of the std::iterable interface.
|
||||
*/
|
||||
inline iterator begin() const noexcept;
|
||||
/**
|
||||
* One past the last array element.
|
||||
*
|
||||
* Part of the std::iterable interface.
|
||||
*/
|
||||
inline iterator end() const noexcept;
|
||||
/**
|
||||
* Get the size of the array (number of immediate children).
|
||||
* It is a saturated value with a maximum of 0xFFFFFF: if the value
|
||||
* is 0xFFFFFF then the size is 0xFFFFFF or greater.
|
||||
*/
|
||||
inline size_t size() const noexcept;
|
||||
/**
|
||||
* Get the value associated with the given JSON pointer.
|
||||
*
|
||||
* dom::parser parser;
|
||||
* array a = parser.parse(R"([ { "foo": { "a": [ 10, 20, 30 ] }} ])"_padded);
|
||||
* a.at("0/foo/a/1") == 20
|
||||
* a.at("0")["foo"]["a"].at(1) == 20
|
||||
*
|
||||
* @return The value associated with the given JSON pointer, or:
|
||||
* - NO_SUCH_FIELD if a field does not exist in an object
|
||||
* - INDEX_OUT_OF_BOUNDS if an array index is larger than an array length
|
||||
* - INCORRECT_TYPE if a non-integer is used to access an array
|
||||
* - INVALID_JSON_POINTER if the JSON pointer is invalid and cannot be parsed
|
||||
*/
|
||||
inline simdjson_result<element> at(const std::string_view &json_pointer) const noexcept;
|
||||
|
||||
/**
|
||||
* Get the value at the given index. This function has linear-time complexity and
|
||||
* is equivalent to the following:
|
||||
*
|
||||
* size_t i=0;
|
||||
* for (auto element : *this) {
|
||||
* if (i == index) { return element; }
|
||||
* i++;
|
||||
* }
|
||||
* return INDEX_OUT_OF_BOUNDS;
|
||||
*
|
||||
* Avoid calling the at() function repeatedly.
|
||||
*
|
||||
* @return The value at the given index, or:
|
||||
* - INDEX_OUT_OF_BOUNDS if the array index is larger than an array length
|
||||
*/
|
||||
inline simdjson_result<element> at(size_t index) const noexcept;
|
||||
|
||||
private:
|
||||
really_inline array(const internal::tape_ref &tape) noexcept;
|
||||
internal::tape_ref tape;
|
||||
friend class element;
|
||||
friend struct simdjson_result<element>;
|
||||
template<typename T>
|
||||
friend class simdjson::minifier;
|
||||
};
|
||||
|
||||
/**
|
||||
* Print JSON to an output stream.
|
||||
*
|
||||
* By default, the value will be printed minified.
|
||||
*
|
||||
* @param out The output stream.
|
||||
* @param value The value to print.
|
||||
* @throw if there is an error with the underlying output stream. simdjson itself will not throw.
|
||||
*/
|
||||
inline std::ostream& operator<<(std::ostream& out, const array &value);
|
||||
|
||||
} // namespace dom
|
||||
|
||||
/** The result of a JSON conversion that may fail. */
|
||||
template<>
|
||||
struct simdjson_result<dom::array> : public internal::simdjson_result_base<dom::array> {
|
||||
public:
|
||||
really_inline simdjson_result() noexcept; ///< @private
|
||||
really_inline simdjson_result(dom::array value) noexcept; ///< @private
|
||||
really_inline simdjson_result(error_code error) noexcept; ///< @private
|
||||
|
||||
inline simdjson_result<dom::element> at(const std::string_view &json_pointer) const noexcept;
|
||||
inline simdjson_result<dom::element> at(size_t index) const noexcept;
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
inline dom::array::iterator begin() const noexcept(false);
|
||||
inline dom::array::iterator end() const noexcept(false);
|
||||
inline size_t size() const noexcept(false);
|
||||
#endif // SIMDJSON_EXCEPTIONS
|
||||
};
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
/**
|
||||
* Print JSON to an output stream.
|
||||
*
|
||||
* By default, the value will be printed minified.
|
||||
*
|
||||
* @param out The output stream.
|
||||
* @param value The value to print.
|
||||
* @throw simdjson_error if the result being printed has an error. If there is an error with the
|
||||
* underlying output stream, that error will be propagated (simdjson_error will not be
|
||||
* thrown).
|
||||
*/
|
||||
inline std::ostream& operator<<(std::ostream& out, const simdjson_result<dom::array> &value) noexcept(false);
|
||||
#endif
|
||||
|
||||
} // namespace simdjson
|
||||
|
||||
#endif // SIMDJSON_DOM_ARRAY_H
|
||||
@@ -0,0 +1,78 @@
|
||||
#ifndef SIMDJSON_DOM_DOCUMENT_H
|
||||
#define SIMDJSON_DOM_DOCUMENT_H
|
||||
|
||||
#include "simdjson/common_defs.h"
|
||||
#include "simdjson/minify.h"
|
||||
#include <memory>
|
||||
#include <ostream>
|
||||
|
||||
namespace simdjson {
|
||||
namespace dom {
|
||||
|
||||
class element;
|
||||
|
||||
/**
|
||||
* A parsed JSON document.
|
||||
*
|
||||
* This class cannot be copied, only moved, to avoid unintended allocations.
|
||||
*/
|
||||
class document {
|
||||
public:
|
||||
/**
|
||||
* Create a document container with zero capacity.
|
||||
*
|
||||
* The parser will allocate capacity as needed.
|
||||
*/
|
||||
document() noexcept = default;
|
||||
~document() noexcept = default;
|
||||
|
||||
/**
|
||||
* Take another document's buffers.
|
||||
*
|
||||
* @param other The document to take. Its capacity is zeroed and it is invalidated.
|
||||
*/
|
||||
document(document &&other) noexcept = default;
|
||||
/** @private */
|
||||
document(const document &) = delete; // Disallow copying
|
||||
/**
|
||||
* Take another document's buffers.
|
||||
*
|
||||
* @param other The document to take. Its capacity is zeroed.
|
||||
*/
|
||||
document &operator=(document &&other) noexcept = default;
|
||||
/** @private */
|
||||
document &operator=(const document &) = delete; // Disallow copying
|
||||
|
||||
/**
|
||||
* Get the root element of this document as a JSON array.
|
||||
*/
|
||||
element root() const noexcept;
|
||||
|
||||
/**
|
||||
* @private Dump the raw tape for debugging.
|
||||
*
|
||||
* @param os the stream to output to.
|
||||
* @return false if the tape is likely wrong (e.g., you did not parse a valid JSON).
|
||||
*/
|
||||
bool dump_raw_tape(std::ostream &os) const noexcept;
|
||||
|
||||
/** @private Structural values. */
|
||||
std::unique_ptr<uint64_t[]> tape{};
|
||||
|
||||
/** @private String values.
|
||||
*
|
||||
* Should be at least byte_capacity.
|
||||
*/
|
||||
std::unique_ptr<uint8_t[]> string_buf{};
|
||||
|
||||
private:
|
||||
inline error_code allocate(size_t len) noexcept;
|
||||
template<typename T>
|
||||
friend class simdjson::minifier;
|
||||
friend class parser;
|
||||
}; // class document
|
||||
|
||||
} // namespace dom
|
||||
} // namespace simdjson
|
||||
|
||||
#endif // SIMDJSON_DOM_DOCUMENT_H
|
||||
@@ -0,0 +1,261 @@
|
||||
#ifndef SIMDJSON_DOCUMENT_STREAM_H
|
||||
#define SIMDJSON_DOCUMENT_STREAM_H
|
||||
|
||||
#include "simdjson/common_defs.h"
|
||||
#include "simdjson/dom/parser.h"
|
||||
#include "simdjson/error.h"
|
||||
#ifdef SIMDJSON_THREADS_ENABLED
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
#include <condition_variable>
|
||||
#endif
|
||||
|
||||
namespace simdjson {
|
||||
namespace dom {
|
||||
|
||||
|
||||
#ifdef SIMDJSON_THREADS_ENABLED
|
||||
/** @private Custom worker class **/
|
||||
struct stage1_worker {
|
||||
stage1_worker() noexcept = default;
|
||||
stage1_worker(const stage1_worker&) = delete;
|
||||
stage1_worker(stage1_worker&&) = delete;
|
||||
stage1_worker operator=(const stage1_worker&) = delete;
|
||||
~stage1_worker();
|
||||
/**
|
||||
* We only start the thread when it is needed, not at object construction, this may throw.
|
||||
* You should only call this once.
|
||||
**/
|
||||
void start_thread();
|
||||
/**
|
||||
* Start a stage 1 job. You should first call 'run', then 'finish'.
|
||||
* You must call start_thread once before.
|
||||
*/
|
||||
void run(document_stream * ds, dom::parser * stage1, size_t next_batch_start);
|
||||
/** Wait for the run to finish (blocking). You should first call 'run', then 'finish'. **/
|
||||
void finish();
|
||||
|
||||
private:
|
||||
|
||||
/**
|
||||
* Normally, we would never stop the thread. But we do in the destructor.
|
||||
* This function is only safe assuming that you are not waiting for results. You
|
||||
* should have called run, then finish, and be done.
|
||||
**/
|
||||
void stop_thread();
|
||||
|
||||
std::thread thread{};
|
||||
/** These three variables define the work done by the thread. **/
|
||||
dom::parser * stage1_thread_parser{};
|
||||
size_t _next_batch_start{};
|
||||
document_stream * owner{};
|
||||
/**
|
||||
* We have two state variables. This could be streamlined to one variable in the future but
|
||||
* we use two for clarity.
|
||||
*/
|
||||
bool has_work{false};
|
||||
bool can_work{true};
|
||||
|
||||
/**
|
||||
* We lock using a mutex.
|
||||
*/
|
||||
std::mutex locking_mutex{};
|
||||
std::condition_variable cond_var{};
|
||||
};
|
||||
#endif
|
||||
|
||||
/**
|
||||
* A forward-only stream of documents.
|
||||
*
|
||||
* Produced by parser::parse_many.
|
||||
*
|
||||
*/
|
||||
class document_stream {
|
||||
public:
|
||||
/**
|
||||
* Construct an uninitialized document_stream.
|
||||
*
|
||||
* ```c++
|
||||
* document_stream docs;
|
||||
* error = parser.parse_many(json).get(docs);
|
||||
* ```
|
||||
*/
|
||||
really_inline document_stream() noexcept;
|
||||
/** Move one document_stream to another. */
|
||||
really_inline document_stream(document_stream &&other) noexcept = default;
|
||||
/** Move one document_stream to another. */
|
||||
really_inline document_stream &operator=(document_stream &&other) noexcept = default;
|
||||
|
||||
really_inline ~document_stream() noexcept;
|
||||
|
||||
/**
|
||||
* An iterator through a forward-only stream of documents.
|
||||
*/
|
||||
class iterator {
|
||||
public:
|
||||
/**
|
||||
* Get the current document (or error).
|
||||
*/
|
||||
really_inline simdjson_result<element> operator*() noexcept;
|
||||
/**
|
||||
* Advance to the next document.
|
||||
*/
|
||||
inline iterator& operator++() noexcept;
|
||||
/**
|
||||
* Check if we're at the end yet.
|
||||
* @param other the end iterator to compare to.
|
||||
*/
|
||||
really_inline bool operator!=(const iterator &other) const noexcept;
|
||||
/**
|
||||
* @private
|
||||
*
|
||||
* Gives the current index in the input document in bytes.
|
||||
*
|
||||
* document_stream stream = parser.parse_many(json,window);
|
||||
* for(auto i = stream.begin(); i != stream.end(); ++i) {
|
||||
* auto doc = *i;
|
||||
* size_t index = i.current_index();
|
||||
* }
|
||||
*
|
||||
* This function (current_index()) is experimental and the usage
|
||||
* may change in future versions of simdjson: we find the API somewhat
|
||||
* awkward and we would like to offer something friendlier.
|
||||
*/
|
||||
really_inline size_t current_index() noexcept;
|
||||
private:
|
||||
really_inline iterator(document_stream &s, bool finished) noexcept;
|
||||
/** The document_stream we're iterating through. */
|
||||
document_stream& stream;
|
||||
/** Whether we're finished or not. */
|
||||
bool finished;
|
||||
friend class document_stream;
|
||||
};
|
||||
|
||||
/**
|
||||
* Start iterating the documents in the stream.
|
||||
*/
|
||||
really_inline iterator begin() noexcept;
|
||||
/**
|
||||
* The end of the stream, for iterator comparison purposes.
|
||||
*/
|
||||
really_inline iterator end() noexcept;
|
||||
|
||||
private:
|
||||
|
||||
document_stream &operator=(const document_stream &) = delete; // Disallow copying
|
||||
document_stream(const document_stream &other) = delete; // Disallow copying
|
||||
|
||||
/**
|
||||
* Construct a document_stream. Does not allocate or parse anything until the iterator is
|
||||
* used.
|
||||
*/
|
||||
really_inline document_stream(
|
||||
dom::parser &parser,
|
||||
const uint8_t *buf,
|
||||
size_t len,
|
||||
size_t batch_size
|
||||
) noexcept;
|
||||
|
||||
/**
|
||||
* Parse the first document in the buffer. Used by begin(), to handle allocation and
|
||||
* initialization.
|
||||
*/
|
||||
inline void start() noexcept;
|
||||
|
||||
/**
|
||||
* Parse the next document found in the buffer previously given to document_stream.
|
||||
*
|
||||
* The content should be a valid JSON document encoded as UTF-8. If there is a
|
||||
* UTF-8 BOM, the caller is responsible for omitting it, UTF-8 BOM are
|
||||
* discouraged.
|
||||
*
|
||||
* You do NOT need to pre-allocate a parser. This function takes care of
|
||||
* pre-allocating a capacity defined by the batch_size defined when creating the
|
||||
* document_stream object.
|
||||
*
|
||||
* The function returns simdjson::EMPTY if there is no more data to be parsed.
|
||||
*
|
||||
* The function returns simdjson::SUCCESS (as integer = 0) in case of success
|
||||
* and indicates that the buffer has successfully been parsed to the end.
|
||||
* Every document it contained has been parsed without error.
|
||||
*
|
||||
* The function returns an error code from simdjson/simdjson.h in case of failure
|
||||
* such as simdjson::CAPACITY, simdjson::MEMALLOC, simdjson::DEPTH_ERROR and so forth;
|
||||
* the simdjson::error_message function converts these error codes into a string).
|
||||
*
|
||||
* You can also check validity by calling parser.is_valid(). The same parser can
|
||||
* and should be reused for the other documents in the buffer.
|
||||
*/
|
||||
inline void next() noexcept;
|
||||
|
||||
/**
|
||||
* Pass the next batch through stage 1 and return when finished.
|
||||
* When threads are enabled, this may wait for the stage 1 thread to finish.
|
||||
*/
|
||||
inline void load_batch() noexcept;
|
||||
|
||||
/** Get the next document index. */
|
||||
inline size_t next_batch_start() const noexcept;
|
||||
|
||||
/** Pass the next batch through stage 1 with the given parser. */
|
||||
inline error_code run_stage1(dom::parser &p, size_t batch_start) noexcept;
|
||||
|
||||
dom::parser *parser;
|
||||
const uint8_t *buf;
|
||||
size_t len;
|
||||
size_t batch_size;
|
||||
/** The error (or lack thereof) from the current document. */
|
||||
error_code error;
|
||||
size_t batch_start{0};
|
||||
size_t doc_index{};
|
||||
|
||||
#ifdef SIMDJSON_THREADS_ENABLED
|
||||
inline void load_from_stage1_thread() noexcept;
|
||||
|
||||
/** Start a thread to run stage 1 on the next batch. */
|
||||
inline void start_stage1_thread() noexcept;
|
||||
|
||||
/** Wait for the stage 1 thread to finish and capture the results. */
|
||||
inline void finish_stage1_thread() noexcept;
|
||||
|
||||
/** The error returned from the stage 1 thread. */
|
||||
error_code stage1_thread_error{UNINITIALIZED};
|
||||
/** The thread used to run stage 1 against the next batch in the background. */
|
||||
friend struct stage1_worker;
|
||||
std::unique_ptr<stage1_worker> worker{new(std::nothrow) stage1_worker()};
|
||||
/**
|
||||
* The parser used to run stage 1 in the background. Will be swapped
|
||||
* with the regular parser when finished.
|
||||
*/
|
||||
dom::parser stage1_thread_parser{};
|
||||
#endif // SIMDJSON_THREADS_ENABLED
|
||||
|
||||
friend class dom::parser;
|
||||
friend struct simdjson_result<dom::document_stream>;
|
||||
friend struct internal::simdjson_result_base<dom::document_stream>;
|
||||
|
||||
}; // class document_stream
|
||||
|
||||
} // namespace dom
|
||||
|
||||
template<>
|
||||
struct simdjson_result<dom::document_stream> : public internal::simdjson_result_base<dom::document_stream> {
|
||||
public:
|
||||
really_inline simdjson_result() noexcept; ///< @private
|
||||
really_inline simdjson_result(error_code error) noexcept; ///< @private
|
||||
really_inline simdjson_result(dom::document_stream &&value) noexcept; ///< @private
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
really_inline dom::document_stream::iterator begin() noexcept(false);
|
||||
really_inline dom::document_stream::iterator end() noexcept(false);
|
||||
#else // SIMDJSON_EXCEPTIONS
|
||||
[[deprecated("parse_many() and load_many() may return errors. Use document_stream stream; error = parser.parse_many().get(doc); instead.")]]
|
||||
really_inline dom::document_stream::iterator begin() noexcept;
|
||||
[[deprecated("parse_many() and load_many() may return errors. Use document_stream stream; error = parser.parse_many().get(doc); instead.")]]
|
||||
really_inline dom::document_stream::iterator end() noexcept;
|
||||
#endif // SIMDJSON_EXCEPTIONS
|
||||
}; // struct simdjson_result<dom::document_stream>
|
||||
|
||||
} // namespace simdjson
|
||||
|
||||
#endif // SIMDJSON_DOCUMENT_STREAM_H
|
||||
@@ -0,0 +1,545 @@
|
||||
#ifndef SIMDJSON_DOM_ELEMENT_H
|
||||
#define SIMDJSON_DOM_ELEMENT_H
|
||||
|
||||
#include "simdjson/common_defs.h"
|
||||
#include "simdjson/error.h"
|
||||
#include "simdjson/internal/tape_ref.h"
|
||||
#include "simdjson/minify.h"
|
||||
#include <ostream>
|
||||
|
||||
namespace simdjson {
|
||||
namespace dom {
|
||||
|
||||
class array;
|
||||
class document;
|
||||
class object;
|
||||
|
||||
/**
|
||||
* The actual concrete type of a JSON element
|
||||
* This is the type it is most easily cast to with get<>.
|
||||
*/
|
||||
enum class element_type {
|
||||
ARRAY = '[', ///< dom::array
|
||||
OBJECT = '{', ///< dom::object
|
||||
INT64 = 'l', ///< int64_t
|
||||
UINT64 = 'u', ///< uint64_t: any integer that fits in uint64_t but *not* int64_t
|
||||
DOUBLE = 'd', ///< double: Any number with a "." or "e" that fits in double.
|
||||
STRING = '"', ///< std::string_view
|
||||
BOOL = 't', ///< bool
|
||||
NULL_VALUE = 'n' ///< null
|
||||
};
|
||||
|
||||
/**
|
||||
* A JSON element.
|
||||
*
|
||||
* References an element in a JSON document, representing a JSON null, boolean, string, number,
|
||||
* array or object.
|
||||
*/
|
||||
class element {
|
||||
public:
|
||||
/** Create a new, invalid element. */
|
||||
really_inline element() noexcept;
|
||||
|
||||
/** The type of this element. */
|
||||
really_inline element_type type() const noexcept;
|
||||
|
||||
/**
|
||||
* Cast this element to an array.
|
||||
*
|
||||
* Equivalent to get<array>().
|
||||
*
|
||||
* @returns An object that can be used to iterate the array, or:
|
||||
* INCORRECT_TYPE if the JSON element is not an array.
|
||||
*/
|
||||
inline simdjson_result<array> get_array() const noexcept;
|
||||
/**
|
||||
* Cast this element to an object.
|
||||
*
|
||||
* Equivalent to get<object>().
|
||||
*
|
||||
* @returns An object that can be used to look up or iterate the object's fields, or:
|
||||
* INCORRECT_TYPE if the JSON element is not an object.
|
||||
*/
|
||||
inline simdjson_result<object> get_object() const noexcept;
|
||||
/**
|
||||
* Cast this element to a null-terminated C string.
|
||||
*
|
||||
* The string is guaranteed to be valid UTF-8.
|
||||
*
|
||||
* The get_c_str() function is equivalent to get<const char *>().
|
||||
*
|
||||
* The length of the string is given by get_string_length(). Because JSON strings
|
||||
* may contain null characters, it may be incorrect to use strlen to determine the
|
||||
* string length.
|
||||
*
|
||||
* It is possible to get a single string_view instance which represents both the string
|
||||
* content and its length: see get_string().
|
||||
*
|
||||
* @returns A pointer to a null-terminated UTF-8 string. This string is stored in the parser and will
|
||||
* be invalidated the next time it parses a document or when it is destroyed.
|
||||
* Returns INCORRECT_TYPE if the JSON element is not a string.
|
||||
*/
|
||||
inline simdjson_result<const char *> get_c_str() const noexcept;
|
||||
/**
|
||||
* Gives the length in bytes of the string.
|
||||
*
|
||||
* It is possible to get a single string_view instance which represents both the string
|
||||
* content and its length: see get_string().
|
||||
*
|
||||
* @returns A string length in bytes.
|
||||
* Returns INCORRECT_TYPE if the JSON element is not a string.
|
||||
*/
|
||||
inline simdjson_result<size_t> get_string_length() const noexcept;
|
||||
/**
|
||||
* Cast this element to a string.
|
||||
*
|
||||
* The string is guaranteed to be valid UTF-8.
|
||||
*
|
||||
* Equivalent to get<std::string_view>().
|
||||
*
|
||||
* @returns An UTF-8 string. The string is stored in the parser and will be invalidated the next time it
|
||||
* parses a document or when it is destroyed.
|
||||
* Returns INCORRECT_TYPE if the JSON element is not a string.
|
||||
*/
|
||||
inline simdjson_result<std::string_view> get_string() const noexcept;
|
||||
/**
|
||||
* Cast this element to a signed integer.
|
||||
*
|
||||
* Equivalent to get<int64_t>().
|
||||
*
|
||||
* @returns A signed 64-bit integer.
|
||||
* Returns INCORRECT_TYPE if the JSON element is not an integer, or NUMBER_OUT_OF_RANGE
|
||||
* if it is negative.
|
||||
*/
|
||||
inline simdjson_result<int64_t> get_int64() const noexcept;
|
||||
/**
|
||||
* Cast this element to an unsigned integer.
|
||||
*
|
||||
* Equivalent to get<uint64_t>().
|
||||
*
|
||||
* @returns An unsigned 64-bit integer.
|
||||
* Returns INCORRECT_TYPE if the JSON element is not an integer, or NUMBER_OUT_OF_RANGE
|
||||
* if it is too large.
|
||||
*/
|
||||
inline simdjson_result<uint64_t> get_uint64() const noexcept;
|
||||
/**
|
||||
* Cast this element to an double floating-point.
|
||||
*
|
||||
* Equivalent to get<double>().
|
||||
*
|
||||
* @returns A double value.
|
||||
* Returns INCORRECT_TYPE if the JSON element is not a number.
|
||||
*/
|
||||
inline simdjson_result<double> get_double() const noexcept;
|
||||
/**
|
||||
* Cast this element to a bool.
|
||||
*
|
||||
* Equivalent to get<bool>().
|
||||
*
|
||||
* @returns A bool value.
|
||||
* Returns INCORRECT_TYPE if the JSON element is not a boolean.
|
||||
*/
|
||||
inline simdjson_result<bool> get_bool() const noexcept;
|
||||
|
||||
/**
|
||||
* Whether this element is a json array.
|
||||
*
|
||||
* Equivalent to is<array>().
|
||||
*/
|
||||
inline bool is_array() const noexcept;
|
||||
/**
|
||||
* Whether this element is a json object.
|
||||
*
|
||||
* Equivalent to is<object>().
|
||||
*/
|
||||
inline bool is_object() const noexcept;
|
||||
/**
|
||||
* Whether this element is a json string.
|
||||
*
|
||||
* Equivalent to is<std::string_view>() or is<const char *>().
|
||||
*/
|
||||
inline bool is_string() const noexcept;
|
||||
/**
|
||||
* Whether this element is a json number that fits in a signed 64-bit integer.
|
||||
*
|
||||
* Equivalent to is<int64_t>().
|
||||
*/
|
||||
inline bool is_int64() const noexcept;
|
||||
/**
|
||||
* Whether this element is a json number that fits in an unsigned 64-bit integer.
|
||||
*
|
||||
* Equivalent to is<uint64_t>().
|
||||
*/
|
||||
inline bool is_uint64() const noexcept;
|
||||
/**
|
||||
* Whether this element is a json number that fits in a double.
|
||||
*
|
||||
* Equivalent to is<double>().
|
||||
*/
|
||||
inline bool is_double() const noexcept;
|
||||
/**
|
||||
* Whether this element is a json number.
|
||||
*
|
||||
* Both integers and floating points will return true.
|
||||
*/
|
||||
inline bool is_number() const noexcept;
|
||||
/**
|
||||
* Whether this element is a json `true` or `false`.
|
||||
*
|
||||
* Equivalent to is<bool>().
|
||||
*/
|
||||
inline bool is_bool() const noexcept;
|
||||
/**
|
||||
* Whether this element is a json `null`.
|
||||
*/
|
||||
inline bool is_null() const noexcept;
|
||||
|
||||
/**
|
||||
* Tell whether the value can be cast to provided type (T).
|
||||
*
|
||||
* Supported types:
|
||||
* - Boolean: bool
|
||||
* - Number: double, uint64_t, int64_t
|
||||
* - String: std::string_view, const char *
|
||||
* - Array: dom::array
|
||||
* - Object: dom::object
|
||||
*
|
||||
* @tparam T bool, double, uint64_t, int64_t, std::string_view, const char *, dom::array, dom::object
|
||||
*/
|
||||
template<typename T>
|
||||
really_inline bool is() const noexcept;
|
||||
|
||||
/**
|
||||
* Get the value as the provided type (T).
|
||||
*
|
||||
* Supported types:
|
||||
* - Boolean: bool
|
||||
* - Number: double, uint64_t, int64_t
|
||||
* - String: std::string_view, const char *
|
||||
* - Array: dom::array
|
||||
* - Object: dom::object
|
||||
*
|
||||
* @tparam T bool, double, uint64_t, int64_t, std::string_view, const char *, dom::array, dom::object
|
||||
*
|
||||
* @returns The value cast to the given type, or:
|
||||
* INCORRECT_TYPE if the value cannot be cast to the given type.
|
||||
*/
|
||||
template<typename T>
|
||||
inline simdjson_result<T> get() const noexcept;
|
||||
|
||||
/**
|
||||
* Get the value as the provided type (T).
|
||||
*
|
||||
* Supported types:
|
||||
* - Boolean: bool
|
||||
* - Number: double, uint64_t, int64_t
|
||||
* - String: std::string_view, const char *
|
||||
* - Array: dom::array
|
||||
* - Object: dom::object
|
||||
*
|
||||
* @tparam T bool, double, uint64_t, int64_t, std::string_view, const char *, dom::array, dom::object
|
||||
*
|
||||
* @param value The variable to set to the value. May not be set if there is an error.
|
||||
*
|
||||
* @returns The error that occurred, or SUCCESS if there was no error.
|
||||
*/
|
||||
template<typename T>
|
||||
WARN_UNUSED really_inline error_code get(T &value) const noexcept;
|
||||
|
||||
/**
|
||||
* Get the value as the provided type (T), setting error if it's not the given type.
|
||||
*
|
||||
* Supported types:
|
||||
* - Boolean: bool
|
||||
* - Number: double, uint64_t, int64_t
|
||||
* - String: std::string_view, const char *
|
||||
* - Array: dom::array
|
||||
* - Object: dom::object
|
||||
*
|
||||
* @tparam T bool, double, uint64_t, int64_t, std::string_view, const char *, dom::array, dom::object
|
||||
*
|
||||
* @param value The variable to set to the given type. value is undefined if there is an error.
|
||||
* @param error The variable to store the error. error is set to error_code::SUCCEED if there is an error.
|
||||
*/
|
||||
template<typename T>
|
||||
inline void tie(T &value, error_code &error) && noexcept;
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
/**
|
||||
* Read this element as a boolean.
|
||||
*
|
||||
* @return The boolean value
|
||||
* @exception simdjson_error(INCORRECT_TYPE) if the JSON element is not a boolean.
|
||||
*/
|
||||
inline operator bool() const noexcept(false);
|
||||
|
||||
/**
|
||||
* Read this element as a null-terminated UTF-8 string.
|
||||
*
|
||||
* Be mindful that JSON allows strings to contain null characters.
|
||||
*
|
||||
* Does *not* convert other types to a string; requires that the JSON type of the element was
|
||||
* an actual string.
|
||||
*
|
||||
* @return The string value.
|
||||
* @exception simdjson_error(INCORRECT_TYPE) if the JSON element is not a string.
|
||||
*/
|
||||
inline explicit operator const char*() const noexcept(false);
|
||||
|
||||
/**
|
||||
* Read this element as a null-terminated UTF-8 string.
|
||||
*
|
||||
* Does *not* convert other types to a string; requires that the JSON type of the element was
|
||||
* an actual string.
|
||||
*
|
||||
* @return The string value.
|
||||
* @exception simdjson_error(INCORRECT_TYPE) if the JSON element is not a string.
|
||||
*/
|
||||
inline operator std::string_view() const noexcept(false);
|
||||
|
||||
/**
|
||||
* Read this element as an unsigned integer.
|
||||
*
|
||||
* @return The integer value.
|
||||
* @exception simdjson_error(INCORRECT_TYPE) if the JSON element is not an integer
|
||||
* @exception simdjson_error(NUMBER_OUT_OF_RANGE) if the integer doesn't fit in 64 bits or is negative
|
||||
*/
|
||||
inline operator uint64_t() const noexcept(false);
|
||||
/**
|
||||
* Read this element as an signed integer.
|
||||
*
|
||||
* @return The integer value.
|
||||
* @exception simdjson_error(INCORRECT_TYPE) if the JSON element is not an integer
|
||||
* @exception simdjson_error(NUMBER_OUT_OF_RANGE) if the integer doesn't fit in 64 bits
|
||||
*/
|
||||
inline operator int64_t() const noexcept(false);
|
||||
/**
|
||||
* Read this element as an double.
|
||||
*
|
||||
* @return The double value.
|
||||
* @exception simdjson_error(INCORRECT_TYPE) if the JSON element is not a number
|
||||
* @exception simdjson_error(NUMBER_OUT_OF_RANGE) if the integer doesn't fit in 64 bits or is negative
|
||||
*/
|
||||
inline operator double() const noexcept(false);
|
||||
/**
|
||||
* Read this element as a JSON array.
|
||||
*
|
||||
* @return The JSON array.
|
||||
* @exception simdjson_error(INCORRECT_TYPE) if the JSON element is not an array
|
||||
*/
|
||||
inline operator array() const noexcept(false);
|
||||
/**
|
||||
* Read this element as a JSON object (key/value pairs).
|
||||
*
|
||||
* @return The JSON object.
|
||||
* @exception simdjson_error(INCORRECT_TYPE) if the JSON element is not an object
|
||||
*/
|
||||
inline operator object() const noexcept(false);
|
||||
|
||||
/**
|
||||
* Iterate over each element in this array.
|
||||
*
|
||||
* @return The beginning of the iteration.
|
||||
* @exception simdjson_error(INCORRECT_TYPE) if the JSON element is not an array
|
||||
*/
|
||||
inline dom::array::iterator begin() const noexcept(false);
|
||||
|
||||
/**
|
||||
* Iterate over each element in this array.
|
||||
*
|
||||
* @return The end of the iteration.
|
||||
* @exception simdjson_error(INCORRECT_TYPE) if the JSON element is not an array
|
||||
*/
|
||||
inline dom::array::iterator end() const noexcept(false);
|
||||
#endif // SIMDJSON_EXCEPTIONS
|
||||
|
||||
/**
|
||||
* Get the value associated with the given key.
|
||||
*
|
||||
* The key will be matched against **unescaped** JSON:
|
||||
*
|
||||
* dom::parser parser;
|
||||
* parser.parse(R"({ "a\n": 1 })"_padded)["a\n"].get<uint64_t>().first == 1
|
||||
* parser.parse(R"({ "a\n": 1 })"_padded)["a\\n"].get<uint64_t>().error() == NO_SUCH_FIELD
|
||||
*
|
||||
* @return The value associated with this field, or:
|
||||
* - NO_SUCH_FIELD if the field does not exist in the object
|
||||
* - INCORRECT_TYPE if this is not an object
|
||||
*/
|
||||
inline simdjson_result<element> operator[](const std::string_view &key) const noexcept;
|
||||
|
||||
/**
|
||||
* Get the value associated with the given key.
|
||||
*
|
||||
* The key will be matched against **unescaped** JSON:
|
||||
*
|
||||
* dom::parser parser;
|
||||
* parser.parse(R"({ "a\n": 1 })"_padded)["a\n"].get<uint64_t>().first == 1
|
||||
* parser.parse(R"({ "a\n": 1 })"_padded)["a\\n"].get<uint64_t>().error() == NO_SUCH_FIELD
|
||||
*
|
||||
* @return The value associated with this field, or:
|
||||
* - NO_SUCH_FIELD if the field does not exist in the object
|
||||
* - INCORRECT_TYPE if this is not an object
|
||||
*/
|
||||
inline simdjson_result<element> operator[](const char *key) const noexcept;
|
||||
|
||||
/**
|
||||
* Get the value associated with the given JSON pointer.
|
||||
*
|
||||
* dom::parser parser;
|
||||
* element doc = parser.parse(R"({ "foo": { "a": [ 10, 20, 30 ] }})"_padded);
|
||||
* doc.at("/foo/a/1") == 20
|
||||
* doc.at("/")["foo"]["a"].at(1) == 20
|
||||
* doc.at("")["foo"]["a"].at(1) == 20
|
||||
*
|
||||
* @return The value associated with the given JSON pointer, or:
|
||||
* - NO_SUCH_FIELD if a field does not exist in an object
|
||||
* - INDEX_OUT_OF_BOUNDS if an array index is larger than an array length
|
||||
* - INCORRECT_TYPE if a non-integer is used to access an array
|
||||
* - INVALID_JSON_POINTER if the JSON pointer is invalid and cannot be parsed
|
||||
*/
|
||||
inline simdjson_result<element> at(const std::string_view &json_pointer) const noexcept;
|
||||
|
||||
/**
|
||||
* Get the value at the given index.
|
||||
*
|
||||
* @return The value at the given index, or:
|
||||
* - INDEX_OUT_OF_BOUNDS if the array index is larger than an array length
|
||||
*/
|
||||
inline simdjson_result<element> at(size_t index) const noexcept;
|
||||
|
||||
/**
|
||||
* Get the value associated with the given key.
|
||||
*
|
||||
* The key will be matched against **unescaped** JSON:
|
||||
*
|
||||
* dom::parser parser;
|
||||
* parser.parse(R"({ "a\n": 1 })"_padded)["a\n"].get<uint64_t>().first == 1
|
||||
* parser.parse(R"({ "a\n": 1 })"_padded)["a\\n"].get<uint64_t>().error() == NO_SUCH_FIELD
|
||||
*
|
||||
* @return The value associated with this field, or:
|
||||
* - NO_SUCH_FIELD if the field does not exist in the object
|
||||
*/
|
||||
inline simdjson_result<element> at_key(const std::string_view &key) const noexcept;
|
||||
|
||||
/**
|
||||
* Get the value associated with the given key in a case-insensitive manner.
|
||||
*
|
||||
* Note: The key will be matched against **unescaped** JSON.
|
||||
*
|
||||
* @return The value associated with this field, or:
|
||||
* - NO_SUCH_FIELD if the field does not exist in the object
|
||||
*/
|
||||
inline simdjson_result<element> at_key_case_insensitive(const std::string_view &key) const noexcept;
|
||||
|
||||
/** @private for debugging. Prints out the root element. */
|
||||
inline bool dump_raw_tape(std::ostream &out) const noexcept;
|
||||
|
||||
private:
|
||||
really_inline element(const internal::tape_ref &tape) noexcept;
|
||||
internal::tape_ref tape;
|
||||
friend class document;
|
||||
friend class object;
|
||||
friend class array;
|
||||
friend struct simdjson_result<element>;
|
||||
template<typename T>
|
||||
friend class simdjson::minifier;
|
||||
};
|
||||
|
||||
/**
|
||||
* Print JSON to an output stream.
|
||||
*
|
||||
* By default, the value will be printed minified.
|
||||
*
|
||||
* @param out The output stream.
|
||||
* @param value The value to print.
|
||||
* @throw if there is an error with the underlying output stream. simdjson itself will not throw.
|
||||
*/
|
||||
inline std::ostream& operator<<(std::ostream& out, const element &value);
|
||||
|
||||
/**
|
||||
* Print element type to an output stream.
|
||||
*
|
||||
* @param out The output stream.
|
||||
* @param value The value to print.
|
||||
* @throw if there is an error with the underlying output stream. simdjson itself will not throw.
|
||||
*/
|
||||
inline std::ostream& operator<<(std::ostream& out, element_type type);
|
||||
|
||||
} // namespace dom
|
||||
|
||||
/** The result of a JSON navigation that may fail. */
|
||||
template<>
|
||||
struct simdjson_result<dom::element> : public internal::simdjson_result_base<dom::element> {
|
||||
public:
|
||||
really_inline simdjson_result() noexcept; ///< @private
|
||||
really_inline simdjson_result(dom::element &&value) noexcept; ///< @private
|
||||
really_inline simdjson_result(error_code error) noexcept; ///< @private
|
||||
|
||||
really_inline simdjson_result<dom::element_type> type() const noexcept;
|
||||
template<typename T>
|
||||
really_inline bool is() const noexcept;
|
||||
template<typename T>
|
||||
really_inline simdjson_result<T> get() const noexcept;
|
||||
template<typename T>
|
||||
WARN_UNUSED really_inline error_code get(T &value) const noexcept;
|
||||
|
||||
really_inline simdjson_result<dom::array> get_array() const noexcept;
|
||||
really_inline simdjson_result<dom::object> get_object() const noexcept;
|
||||
really_inline simdjson_result<const char *> get_c_str() const noexcept;
|
||||
really_inline simdjson_result<size_t> get_string_length() const noexcept;
|
||||
really_inline simdjson_result<std::string_view> get_string() const noexcept;
|
||||
really_inline simdjson_result<int64_t> get_int64() const noexcept;
|
||||
really_inline simdjson_result<uint64_t> get_uint64() const noexcept;
|
||||
really_inline simdjson_result<double> get_double() const noexcept;
|
||||
really_inline simdjson_result<bool> get_bool() const noexcept;
|
||||
|
||||
really_inline bool is_array() const noexcept;
|
||||
really_inline bool is_object() const noexcept;
|
||||
really_inline bool is_string() const noexcept;
|
||||
really_inline bool is_int64() const noexcept;
|
||||
really_inline bool is_uint64() const noexcept;
|
||||
really_inline bool is_double() const noexcept;
|
||||
really_inline bool is_bool() const noexcept;
|
||||
really_inline bool is_null() const noexcept;
|
||||
|
||||
really_inline simdjson_result<dom::element> operator[](const std::string_view &key) const noexcept;
|
||||
really_inline simdjson_result<dom::element> operator[](const char *key) const noexcept;
|
||||
really_inline simdjson_result<dom::element> at(const std::string_view &json_pointer) const noexcept;
|
||||
really_inline simdjson_result<dom::element> at(size_t index) const noexcept;
|
||||
really_inline simdjson_result<dom::element> at_key(const std::string_view &key) const noexcept;
|
||||
really_inline simdjson_result<dom::element> at_key_case_insensitive(const std::string_view &key) const noexcept;
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
really_inline operator bool() const noexcept(false);
|
||||
really_inline explicit operator const char*() const noexcept(false);
|
||||
really_inline operator std::string_view() const noexcept(false);
|
||||
really_inline operator uint64_t() const noexcept(false);
|
||||
really_inline operator int64_t() const noexcept(false);
|
||||
really_inline operator double() const noexcept(false);
|
||||
really_inline operator dom::array() const noexcept(false);
|
||||
really_inline operator dom::object() const noexcept(false);
|
||||
|
||||
really_inline dom::array::iterator begin() const noexcept(false);
|
||||
really_inline dom::array::iterator end() const noexcept(false);
|
||||
#endif // SIMDJSON_EXCEPTIONS
|
||||
};
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
/**
|
||||
* Print JSON to an output stream.
|
||||
*
|
||||
* By default, the value will be printed minified.
|
||||
*
|
||||
* @param out The output stream.
|
||||
* @param value The value to print.
|
||||
* @throw simdjson_error if the result being printed has an error. If there is an error with the
|
||||
* underlying output stream, that error will be propagated (simdjson_error will not be
|
||||
* thrown).
|
||||
*/
|
||||
really_inline std::ostream& operator<<(std::ostream& out, const simdjson_result<dom::element> &value) noexcept(false);
|
||||
#endif
|
||||
|
||||
} // namespace simdjson
|
||||
|
||||
#endif // SIMDJSON_DOM_DOCUMENT_H
|
||||
@@ -1,10 +1,10 @@
|
||||
// TODO Remove this -- deprecated API and files
|
||||
|
||||
#ifndef SIMDJSON_JSONPARSER_H
|
||||
#define SIMDJSON_JSONPARSER_H
|
||||
#ifndef SIMDJSON_DOM_JSONPARSER_H
|
||||
#define SIMDJSON_DOM_JSONPARSER_H
|
||||
|
||||
#include "simdjson/document.h"
|
||||
#include "simdjson/parsedjson.h"
|
||||
#include "simdjson/dom/document.h"
|
||||
#include "simdjson/dom/parsedjson.h"
|
||||
#include "simdjson/jsonioutil.h"
|
||||
|
||||
namespace simdjson {
|
||||
@@ -114,4 +114,4 @@ dom::parser build_parsed_json(const char *buf) noexcept = delete;
|
||||
|
||||
} // namespace simdjson
|
||||
|
||||
#endif
|
||||
#endif // SIMDJSON_DOM_JSONPARSER_H
|
||||
@@ -0,0 +1,264 @@
|
||||
#ifndef SIMDJSON_DOM_OBJECT_H
|
||||
#define SIMDJSON_DOM_OBJECT_H
|
||||
|
||||
#include "simdjson/common_defs.h"
|
||||
#include "simdjson/error.h"
|
||||
#include "simdjson/internal/tape_ref.h"
|
||||
#include "simdjson/minify.h"
|
||||
#include <ostream>
|
||||
|
||||
namespace simdjson {
|
||||
namespace dom {
|
||||
|
||||
class document;
|
||||
class element;
|
||||
class key_value_pair;
|
||||
|
||||
/**
|
||||
* JSON object.
|
||||
*/
|
||||
class object {
|
||||
public:
|
||||
/** Create a new, invalid object */
|
||||
really_inline object() noexcept;
|
||||
|
||||
class iterator {
|
||||
public:
|
||||
/**
|
||||
* Get the actual key/value pair
|
||||
*/
|
||||
inline const key_value_pair operator*() const noexcept;
|
||||
/**
|
||||
* Get the next key/value pair.
|
||||
*
|
||||
* Part of the std::iterator interface.
|
||||
*
|
||||
*/
|
||||
inline iterator& operator++() noexcept;
|
||||
/**
|
||||
* Check if these key value pairs come from the same place in the JSON.
|
||||
*
|
||||
* Part of the std::iterator interface.
|
||||
*/
|
||||
inline bool operator!=(const iterator& other) const noexcept;
|
||||
/**
|
||||
* Get the key of this key/value pair.
|
||||
*/
|
||||
inline std::string_view key() const noexcept;
|
||||
/**
|
||||
* Get the length (in bytes) of the key in this key/value pair.
|
||||
* You should expect this function to be faster than key().size().
|
||||
*/
|
||||
inline uint32_t key_length() const noexcept;
|
||||
/**
|
||||
* Returns true if the key in this key/value pair is equal
|
||||
* to the provided string_view.
|
||||
*/
|
||||
inline bool key_equals(const std::string_view & o) const noexcept;
|
||||
/**
|
||||
* Returns true if the key in this key/value pair is equal
|
||||
* to the provided string_view in a case-insensitive manner.
|
||||
* Case comparisons may only be handled correctly for ASCII strings.
|
||||
*/
|
||||
inline bool key_equals_case_insensitive(const std::string_view & o) const noexcept;
|
||||
/**
|
||||
* Get the key of this key/value pair.
|
||||
*/
|
||||
inline const char *key_c_str() const noexcept;
|
||||
/**
|
||||
* Get the value of this key/value pair.
|
||||
*/
|
||||
inline element value() const noexcept;
|
||||
private:
|
||||
really_inline iterator(const internal::tape_ref &tape) noexcept;
|
||||
|
||||
internal::tape_ref tape;
|
||||
|
||||
friend class object;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the first key/value pair.
|
||||
*
|
||||
* Part of the std::iterable interface.
|
||||
*/
|
||||
inline iterator begin() const noexcept;
|
||||
/**
|
||||
* One past the last key/value pair.
|
||||
*
|
||||
* Part of the std::iterable interface.
|
||||
*/
|
||||
inline iterator end() const noexcept;
|
||||
/**
|
||||
* Get the size of the object (number of keys).
|
||||
* It is a saturated value with a maximum of 0xFFFFFF: if the value
|
||||
* is 0xFFFFFF then the size is 0xFFFFFF or greater.
|
||||
*/
|
||||
inline size_t size() const noexcept;
|
||||
/**
|
||||
* Get the value associated with the given key.
|
||||
*
|
||||
* The key will be matched against **unescaped** JSON:
|
||||
*
|
||||
* dom::parser parser;
|
||||
* parser.parse(R"({ "a\n": 1 })"_padded)["a\n"].get<uint64_t>().first == 1
|
||||
* parser.parse(R"({ "a\n": 1 })"_padded)["a\\n"].get<uint64_t>().error() == NO_SUCH_FIELD
|
||||
*
|
||||
* This function has linear-time complexity: the keys are checked one by one.
|
||||
*
|
||||
* @return The value associated with this field, or:
|
||||
* - NO_SUCH_FIELD if the field does not exist in the object
|
||||
* - INCORRECT_TYPE if this is not an object
|
||||
*/
|
||||
inline simdjson_result<element> operator[](const std::string_view &key) const noexcept;
|
||||
|
||||
/**
|
||||
* Get the value associated with the given key.
|
||||
*
|
||||
* The key will be matched against **unescaped** JSON:
|
||||
*
|
||||
* dom::parser parser;
|
||||
* parser.parse(R"({ "a\n": 1 })"_padded)["a\n"].get<uint64_t>().first == 1
|
||||
* parser.parse(R"({ "a\n": 1 })"_padded)["a\\n"].get<uint64_t>().error() == NO_SUCH_FIELD
|
||||
*
|
||||
* This function has linear-time complexity: the keys are checked one by one.
|
||||
*
|
||||
* @return The value associated with this field, or:
|
||||
* - NO_SUCH_FIELD if the field does not exist in the object
|
||||
* - INCORRECT_TYPE if this is not an object
|
||||
*/
|
||||
inline simdjson_result<element> operator[](const char *key) const noexcept;
|
||||
|
||||
/**
|
||||
* Get the value associated with the given JSON pointer.
|
||||
*
|
||||
* dom::parser parser;
|
||||
* object obj = parser.parse(R"({ "foo": { "a": [ 10, 20, 30 ] }})"_padded);
|
||||
* obj.at("foo/a/1") == 20
|
||||
* obj.at("foo")["a"].at(1) == 20
|
||||
*
|
||||
* @return The value associated with the given JSON pointer, or:
|
||||
* - NO_SUCH_FIELD if a field does not exist in an object
|
||||
* - INDEX_OUT_OF_BOUNDS if an array index is larger than an array length
|
||||
* - INCORRECT_TYPE if a non-integer is used to access an array
|
||||
* - INVALID_JSON_POINTER if the JSON pointer is invalid and cannot be parsed
|
||||
*/
|
||||
inline simdjson_result<element> at(const std::string_view &json_pointer) const noexcept;
|
||||
|
||||
/**
|
||||
* Get the value associated with the given key.
|
||||
*
|
||||
* The key will be matched against **unescaped** JSON:
|
||||
*
|
||||
* dom::parser parser;
|
||||
* parser.parse(R"({ "a\n": 1 })"_padded)["a\n"].get<uint64_t>().first == 1
|
||||
* parser.parse(R"({ "a\n": 1 })"_padded)["a\\n"].get<uint64_t>().error() == NO_SUCH_FIELD
|
||||
*
|
||||
* This function has linear-time complexity: the keys are checked one by one.
|
||||
*
|
||||
* @return The value associated with this field, or:
|
||||
* - NO_SUCH_FIELD if the field does not exist in the object
|
||||
*/
|
||||
inline simdjson_result<element> at_key(const std::string_view &key) const noexcept;
|
||||
|
||||
/**
|
||||
* Get the value associated with the given key in a case-insensitive manner.
|
||||
* It is only guaranteed to work over ASCII inputs.
|
||||
*
|
||||
* Note: The key will be matched against **unescaped** JSON.
|
||||
*
|
||||
* This function has linear-time complexity: the keys are checked one by one.
|
||||
*
|
||||
* @return The value associated with this field, or:
|
||||
* - NO_SUCH_FIELD if the field does not exist in the object
|
||||
*/
|
||||
inline simdjson_result<element> at_key_case_insensitive(const std::string_view &key) const noexcept;
|
||||
|
||||
private:
|
||||
really_inline object(const internal::tape_ref &tape) noexcept;
|
||||
|
||||
internal::tape_ref tape;
|
||||
|
||||
friend class element;
|
||||
friend struct simdjson_result<element>;
|
||||
template<typename T>
|
||||
friend class simdjson::minifier;
|
||||
};
|
||||
|
||||
/**
|
||||
* Key/value pair in an object.
|
||||
*/
|
||||
class key_value_pair {
|
||||
public:
|
||||
/** key in the key-value pair **/
|
||||
std::string_view key;
|
||||
/** value in the key-value pair **/
|
||||
element value;
|
||||
|
||||
private:
|
||||
really_inline key_value_pair(const std::string_view &_key, element _value) noexcept;
|
||||
friend class object;
|
||||
};
|
||||
|
||||
/**
|
||||
* Print JSON to an output stream.
|
||||
*
|
||||
* By default, the value will be printed minified.
|
||||
*
|
||||
* @param out The output stream.
|
||||
* @param value The value to print.
|
||||
* @throw if there is an error with the underlying output stream. simdjson itself will not throw.
|
||||
*/
|
||||
inline std::ostream& operator<<(std::ostream& out, const object &value);
|
||||
/**
|
||||
* Print JSON to an output stream.
|
||||
*
|
||||
* By default, the value will be printed minified.
|
||||
*
|
||||
* @param out The output stream.
|
||||
* @param value The value to print.
|
||||
* @throw if there is an error with the underlying output stream. simdjson itself will not throw.
|
||||
*/
|
||||
inline std::ostream& operator<<(std::ostream& out, const key_value_pair &value);
|
||||
|
||||
} // namespace dom
|
||||
|
||||
/** The result of a JSON conversion that may fail. */
|
||||
template<>
|
||||
struct simdjson_result<dom::object> : public internal::simdjson_result_base<dom::object> {
|
||||
public:
|
||||
really_inline simdjson_result() noexcept; ///< @private
|
||||
really_inline simdjson_result(dom::object value) noexcept; ///< @private
|
||||
really_inline simdjson_result(error_code error) noexcept; ///< @private
|
||||
|
||||
inline simdjson_result<dom::element> operator[](const std::string_view &key) const noexcept;
|
||||
inline simdjson_result<dom::element> operator[](const char *key) const noexcept;
|
||||
inline simdjson_result<dom::element> at(const std::string_view &json_pointer) const noexcept;
|
||||
inline simdjson_result<dom::element> at_key(const std::string_view &key) const noexcept;
|
||||
inline simdjson_result<dom::element> at_key_case_insensitive(const std::string_view &key) const noexcept;
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
inline dom::object::iterator begin() const noexcept(false);
|
||||
inline dom::object::iterator end() const noexcept(false);
|
||||
inline size_t size() const noexcept(false);
|
||||
#endif // SIMDJSON_EXCEPTIONS
|
||||
};
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
/**
|
||||
* Print JSON to an output stream.
|
||||
*
|
||||
* By default, the value will be printed minified.
|
||||
*
|
||||
* @param out The output stream.
|
||||
* @param value The value to print.
|
||||
* @throw simdjson_error if the result being printed has an error. If there is an error with the
|
||||
* underlying output stream, that error will be propagated (simdjson_error will not be
|
||||
* thrown).
|
||||
*/
|
||||
inline std::ostream& operator<<(std::ostream& out, const simdjson_result<dom::object> &value) noexcept(false);
|
||||
#endif // SIMDJSON_EXCEPTIONS
|
||||
|
||||
} // namespace simdjson
|
||||
|
||||
#endif // SIMDJSON_DOM_OBJECT_H
|
||||
@@ -1,9 +1,9 @@
|
||||
// TODO Remove this -- deprecated API and files
|
||||
|
||||
#ifndef SIMDJSON_PARSEDJSON_H
|
||||
#define SIMDJSON_PARSEDJSON_H
|
||||
#ifndef SIMDJSON_DOM_PARSEDJSON_H
|
||||
#define SIMDJSON_DOM_PARSEDJSON_H
|
||||
|
||||
#include "simdjson/document.h"
|
||||
#include "simdjson/dom/document.h"
|
||||
|
||||
namespace simdjson {
|
||||
|
||||
@@ -13,4 +13,5 @@ namespace simdjson {
|
||||
using ParsedJson [[deprecated("Use dom::parser instead")]] = dom::parser;
|
||||
|
||||
} // namespace simdjson
|
||||
#endif
|
||||
|
||||
#endif // SIMDJSON_DOM_PARSEDJSON_H
|
||||
+29
-26
@@ -1,7 +1,7 @@
|
||||
// TODO Remove this -- deprecated API and files
|
||||
|
||||
#ifndef SIMDJSON_PARSEDJSON_ITERATOR_H
|
||||
#define SIMDJSON_PARSEDJSON_ITERATOR_H
|
||||
#ifndef SIMDJSON_DOM_PARSEDJSON_ITERATOR_H
|
||||
#define SIMDJSON_DOM_PARSEDJSON_ITERATOR_H
|
||||
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
@@ -10,18 +10,21 @@
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
|
||||
#include "simdjson/document.h"
|
||||
#include "simdjson/parsedjson.h"
|
||||
#include "simdjson/dom/document.h"
|
||||
#include "simdjson/dom/parsedjson.h"
|
||||
#include "simdjson/internal/jsonformatutils.h"
|
||||
|
||||
namespace simdjson {
|
||||
|
||||
class [[deprecated("Use the new DOM navigation API instead (see doc/usage.md)")]] dom::parser::Iterator {
|
||||
/** @private **/
|
||||
class [[deprecated("Use the new DOM navigation API instead (see doc/basics.md)")]] dom::parser::Iterator {
|
||||
public:
|
||||
inline Iterator(const dom::parser &parser) noexcept(false);
|
||||
inline Iterator(const Iterator &o) noexcept;
|
||||
inline ~Iterator() noexcept;
|
||||
|
||||
inline Iterator& operator=(const Iterator&) = delete;
|
||||
|
||||
inline bool is_ok() const;
|
||||
|
||||
// useful for debugging purposes
|
||||
@@ -102,11 +105,11 @@ public:
|
||||
|
||||
inline bool is_string() const { return get_type() == '"'; }
|
||||
|
||||
// Returns true if the current type of node is an signed integer.
|
||||
// Returns true if the current type of the node is an signed integer.
|
||||
// You can get its value with `get_integer()`.
|
||||
inline bool is_integer() const { return get_type() == 'l'; }
|
||||
|
||||
// Returns true if the current type of node is an unsigned integer.
|
||||
// Returns true if the current type of the node is an unsigned integer.
|
||||
// You can get its value with `get_unsigned_integer()`.
|
||||
//
|
||||
// NOTE:
|
||||
@@ -115,19 +118,19 @@ public:
|
||||
// positive integer, such as 1, 42, or 1000000, is as a signed node.
|
||||
// Be aware this function returns false for a signed node.
|
||||
inline bool is_unsigned_integer() const { return get_type() == 'u'; }
|
||||
|
||||
// Returns true if the current type of the node is a double floating-point number.
|
||||
inline bool is_double() const { return get_type() == 'd'; }
|
||||
|
||||
// Returns true if the current type of the node is a number (integer or floating-point).
|
||||
inline bool is_number() const {
|
||||
return is_integer() || is_unsigned_integer() || is_double();
|
||||
}
|
||||
|
||||
// Returns true if the current type of the node is a bool with true value.
|
||||
inline bool is_true() const { return get_type() == 't'; }
|
||||
|
||||
// Returns true if the current type of the node is a bool with false value.
|
||||
inline bool is_false() const { return get_type() == 'f'; }
|
||||
|
||||
// Returns true if the current type of the node is null.
|
||||
inline bool is_null() const { return get_type() == 'n'; }
|
||||
|
||||
// Returns true if the type byte represents an object of an array
|
||||
static bool is_object_or_array(uint8_t type) {
|
||||
return ((type == '[') || (type == '{'));
|
||||
}
|
||||
@@ -187,7 +190,7 @@ public:
|
||||
// is referenced is undefined, and evaluation fails". Here we just return
|
||||
// the first corresponding value.
|
||||
inline bool move_to(const std::string &pointer) {
|
||||
return move_to(pointer.c_str(), pointer.length());
|
||||
return move_to(pointer.c_str(), uint32_t(pointer.length()));
|
||||
}
|
||||
|
||||
private:
|
||||
@@ -241,27 +244,27 @@ public:
|
||||
;
|
||||
}
|
||||
|
||||
// void to_end_scope(); // move us to
|
||||
// the start of our current scope; always succeeds
|
||||
|
||||
|
||||
// print the node we are currently pointing at
|
||||
inline bool print(std::ostream &os, bool escape_strings = true) const;
|
||||
|
||||
private:
|
||||
const document &doc;
|
||||
size_t max_depth{};
|
||||
size_t depth{};
|
||||
size_t location{}; // our current location on a tape
|
||||
size_t tape_length{};
|
||||
uint8_t current_type{};
|
||||
uint64_t current_val{};
|
||||
typedef struct {
|
||||
size_t start_of_scope;
|
||||
uint8_t scope_type;
|
||||
} scopeindex_t;
|
||||
|
||||
private:
|
||||
const document &doc;
|
||||
size_t max_depth;
|
||||
size_t depth;
|
||||
size_t location; // our current location on a tape
|
||||
size_t tape_length;
|
||||
uint8_t current_type;
|
||||
uint64_t current_val;
|
||||
scopeindex_t *depth_index;
|
||||
scopeindex_t *depth_index{};
|
||||
};
|
||||
|
||||
} // namespace simdjson
|
||||
|
||||
#endif
|
||||
#endif // SIMDJSON_DOM_PARSEDJSON_ITERATOR_H
|
||||
@@ -0,0 +1,434 @@
|
||||
#ifndef SIMDJSON_DOM_PARSER_H
|
||||
#define SIMDJSON_DOM_PARSER_H
|
||||
|
||||
#include "simdjson/common_defs.h"
|
||||
#include "simdjson/dom/document.h"
|
||||
#include "simdjson/error.h"
|
||||
#include "simdjson/internal/dom_parser_implementation.h"
|
||||
#include "simdjson/internal/tape_ref.h"
|
||||
#include "simdjson/minify.h"
|
||||
#include "simdjson/padded_string.h"
|
||||
#include "simdjson/portability.h"
|
||||
#include <memory>
|
||||
#include <ostream>
|
||||
#include <string>
|
||||
|
||||
namespace simdjson {
|
||||
|
||||
namespace dom {
|
||||
|
||||
class document_stream;
|
||||
class element;
|
||||
|
||||
/** The default batch size for parser.parse_many() and parser.load_many() */
|
||||
static constexpr size_t DEFAULT_BATCH_SIZE = 1000000;
|
||||
|
||||
/**
|
||||
* A persistent document parser.
|
||||
*
|
||||
* The parser is designed to be reused, holding the internal buffers necessary to do parsing,
|
||||
* as well as memory for a single document. The parsed document is overwritten on each parse.
|
||||
*
|
||||
* This class cannot be copied, only moved, to avoid unintended allocations.
|
||||
*
|
||||
* @note This is not thread safe: one parser cannot produce two documents at the same time!
|
||||
*/
|
||||
class parser {
|
||||
public:
|
||||
/**
|
||||
* Create a JSON parser.
|
||||
*
|
||||
* The new parser will have zero capacity.
|
||||
*
|
||||
* @param max_capacity The maximum document length the parser can automatically handle. The parser
|
||||
* will allocate more capacity on an as needed basis (when it sees documents too big to handle)
|
||||
* up to this amount. The parser still starts with zero capacity no matter what this number is:
|
||||
* to allocate an initial capacity, call allocate() after constructing the parser.
|
||||
* Defaults to SIMDJSON_MAXSIZE_BYTES (the largest single document simdjson can process).
|
||||
*/
|
||||
really_inline explicit parser(size_t max_capacity = SIMDJSON_MAXSIZE_BYTES) noexcept;
|
||||
/**
|
||||
* Take another parser's buffers and state.
|
||||
*
|
||||
* @param other The parser to take. Its capacity is zeroed.
|
||||
*/
|
||||
really_inline parser(parser &&other) noexcept;
|
||||
parser(const parser &) = delete; ///< @private Disallow copying
|
||||
/**
|
||||
* Take another parser's buffers and state.
|
||||
*
|
||||
* @param other The parser to take. Its capacity is zeroed.
|
||||
*/
|
||||
really_inline parser &operator=(parser &&other) noexcept;
|
||||
parser &operator=(const parser &) = delete; ///< @private Disallow copying
|
||||
|
||||
/** Deallocate the JSON parser. */
|
||||
~parser()=default;
|
||||
|
||||
/**
|
||||
* Load a JSON document from a file and return a reference to it.
|
||||
*
|
||||
* dom::parser parser;
|
||||
* const element doc = parser.load("jsonexamples/twitter.json");
|
||||
*
|
||||
* ### IMPORTANT: Document Lifetime
|
||||
*
|
||||
* The JSON document still lives in the parser: this is the most efficient way to parse JSON
|
||||
* documents because it reuses the same buffers, but you *must* use the document before you
|
||||
* destroy the parser or call parse() again.
|
||||
*
|
||||
* ### Parser Capacity
|
||||
*
|
||||
* If the parser's current capacity is less than the file length, it will allocate enough capacity
|
||||
* to handle it (up to max_capacity).
|
||||
*
|
||||
* @param path The path to load.
|
||||
* @return The document, or an error:
|
||||
* - IO_ERROR if there was an error opening or reading the file.
|
||||
* - MEMALLOC if the parser does not have enough capacity and memory allocation fails.
|
||||
* - CAPACITY if the parser does not have enough capacity and len > max_capacity.
|
||||
* - other json errors if parsing fails.
|
||||
*/
|
||||
inline simdjson_result<element> load(const std::string &path) & noexcept;
|
||||
inline simdjson_result<element> load(const std::string &path) && = delete ;
|
||||
/**
|
||||
* Parse a JSON document and return a temporary reference to it.
|
||||
*
|
||||
* dom::parser parser;
|
||||
* element doc = parser.parse(buf, len);
|
||||
*
|
||||
* ### IMPORTANT: Document Lifetime
|
||||
*
|
||||
* The JSON document still lives in the parser: this is the most efficient way to parse JSON
|
||||
* documents because it reuses the same buffers, but you *must* use the document before you
|
||||
* destroy the parser or call parse() again.
|
||||
*
|
||||
* ### REQUIRED: Buffer Padding
|
||||
*
|
||||
* The buffer must have at least SIMDJSON_PADDING extra allocated bytes. It does not matter what
|
||||
* those bytes are initialized to, as long as they are allocated.
|
||||
*
|
||||
* If realloc_if_needed is true, it is assumed that the buffer does *not* have enough padding,
|
||||
* and it is copied into an enlarged temporary buffer before parsing.
|
||||
*
|
||||
* ### Parser Capacity
|
||||
*
|
||||
* If the parser's current capacity is less than len, it will allocate enough capacity
|
||||
* to handle it (up to max_capacity).
|
||||
*
|
||||
* @param buf The JSON to parse. Must have at least len + SIMDJSON_PADDING allocated bytes, unless
|
||||
* realloc_if_needed is true.
|
||||
* @param len The length of the JSON.
|
||||
* @param realloc_if_needed Whether to reallocate and enlarge the JSON buffer to add padding.
|
||||
* @return The document, or an error:
|
||||
* - MEMALLOC if realloc_if_needed is true or the parser does not have enough capacity,
|
||||
* and memory allocation fails.
|
||||
* - CAPACITY if the parser does not have enough capacity and len > max_capacity.
|
||||
* - other json errors if parsing fails.
|
||||
*/
|
||||
inline simdjson_result<element> parse(const uint8_t *buf, size_t len, bool realloc_if_needed = true) & noexcept;
|
||||
inline simdjson_result<element> parse(const uint8_t *buf, size_t len, bool realloc_if_needed = true) && =delete;
|
||||
/** @overload parse(const uint8_t *buf, size_t len, bool realloc_if_needed) */
|
||||
really_inline simdjson_result<element> parse(const char *buf, size_t len, bool realloc_if_needed = true) & noexcept;
|
||||
really_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) */
|
||||
really_inline simdjson_result<element> parse(const std::string &s) & noexcept;
|
||||
really_inline simdjson_result<element> parse(const std::string &s) && =delete;
|
||||
/** @overload parse(const uint8_t *buf, size_t len, bool realloc_if_needed) */
|
||||
really_inline simdjson_result<element> parse(const padded_string &s) & noexcept;
|
||||
really_inline simdjson_result<element> parse(const padded_string &s) && =delete;
|
||||
|
||||
/** @private We do not want to allow implicit conversion from C string to std::string. */
|
||||
really_inline simdjson_result<element> parse(const char *buf) noexcept = delete;
|
||||
|
||||
/**
|
||||
* Load a file containing many JSON documents.
|
||||
*
|
||||
* dom::parser parser;
|
||||
* for (const element doc : parser.load_many(path)) {
|
||||
* cout << std::string(doc["title"]) << endl;
|
||||
* }
|
||||
*
|
||||
* ### Format
|
||||
*
|
||||
* The file must contain a series of one or more JSON documents, concatenated into a single
|
||||
* buffer, separated by whitespace. It effectively parses until it has a fully valid document,
|
||||
* then starts parsing the next document at that point. (It does this with more parallelism and
|
||||
* lookahead than you might think, though.)
|
||||
*
|
||||
* documents that consist of an object or array may omit the whitespace between them, concatenating
|
||||
* with no separator. documents that consist of a single primitive (i.e. documents that are not
|
||||
* arrays or objects) MUST be separated with whitespace.
|
||||
*
|
||||
* The documents must not exceed batch_size bytes (by default 1MB) or they will fail to parse.
|
||||
* Setting batch_size to excessively large or excesively small values may impact negatively the
|
||||
* performance.
|
||||
*
|
||||
* ### Error Handling
|
||||
*
|
||||
* All errors are returned during iteration: if there is a global error such as memory allocation,
|
||||
* it will be yielded as the first result. Iteration always stops after the first error.
|
||||
*
|
||||
* As with all other simdjson methods, non-exception error handling is readily available through
|
||||
* the same interface, requiring you to check the error before using the document:
|
||||
*
|
||||
* dom::parser parser;
|
||||
* dom::document_stream docs;
|
||||
* auto error = parser.load_many(path).get(docs);
|
||||
* if (error) { cerr << error << endl; exit(1); }
|
||||
* for (auto doc : docs) {
|
||||
* std::string_view title;
|
||||
* if ((error = doc["title"].get(title)) { cerr << error << endl; exit(1); }
|
||||
* cout << title << endl;
|
||||
* }
|
||||
*
|
||||
* ### Threads
|
||||
*
|
||||
* When compiled with SIMDJSON_THREADS_ENABLED, this method will use a single thread under the
|
||||
* hood to do some lookahead.
|
||||
*
|
||||
* ### Parser Capacity
|
||||
*
|
||||
* If the parser's current capacity is less than batch_size, it will allocate enough capacity
|
||||
* to handle it (up to max_capacity).
|
||||
*
|
||||
* @param path File name pointing at the concatenated JSON to parse.
|
||||
* @param batch_size The batch size to use. MUST be larger than the largest document. The sweet
|
||||
* spot is cache-related: small enough to fit in cache, yet big enough to
|
||||
* parse as many documents as possible in one tight loop.
|
||||
* Defaults to 10MB, which has been a reasonable sweet spot in our tests.
|
||||
* @return The stream, or an error. An empty input will yield 0 documents rather than an EMPTY error. Errors:
|
||||
* - IO_ERROR if there was an error opening or reading the file.
|
||||
* - MEMALLOC if the parser does not have enough capacity and memory allocation fails.
|
||||
* - CAPACITY if the parser does not have enough capacity and batch_size > max_capacity.
|
||||
* - other json errors if parsing fails.
|
||||
*/
|
||||
inline simdjson_result<document_stream> load_many(const std::string &path, size_t batch_size = DEFAULT_BATCH_SIZE) noexcept;
|
||||
|
||||
/**
|
||||
* Parse a buffer containing many JSON documents.
|
||||
*
|
||||
* dom::parser parser;
|
||||
* for (element doc : parser.parse_many(buf, len)) {
|
||||
* cout << std::string(doc["title"]) << endl;
|
||||
* }
|
||||
*
|
||||
* ### Format
|
||||
*
|
||||
* The buffer must contain a series of one or more JSON documents, concatenated into a single
|
||||
* buffer, separated by whitespace. It effectively parses until it has a fully valid document,
|
||||
* then starts parsing the next document at that point. (It does this with more parallelism and
|
||||
* lookahead than you might think, though.)
|
||||
*
|
||||
* documents that consist of an object or array may omit the whitespace between them, concatenating
|
||||
* with no separator. documents that consist of a single primitive (i.e. documents that are not
|
||||
* arrays or objects) MUST be separated with whitespace.
|
||||
*
|
||||
* The documents must not exceed batch_size bytes (by default 1MB) or they will fail to parse.
|
||||
* Setting batch_size to excessively large or excesively small values may impact negatively the
|
||||
* performance.
|
||||
*
|
||||
* ### Error Handling
|
||||
*
|
||||
* All errors are returned during iteration: if there is a global error such as memory allocation,
|
||||
* it will be yielded as the first result. Iteration always stops after the first error.
|
||||
*
|
||||
* As with all other simdjson methods, non-exception error handling is readily available through
|
||||
* the same interface, requiring you to check the error before using the document:
|
||||
*
|
||||
* dom::parser parser;
|
||||
* dom::document_stream docs;
|
||||
* auto error = parser.load_many(path).get(docs);
|
||||
* if (error) { cerr << error << endl; exit(1); }
|
||||
* for (auto doc : docs) {
|
||||
* std::string_view title;
|
||||
* if ((error = doc["title"].get(title)) { cerr << error << endl; exit(1); }
|
||||
* cout << title << endl;
|
||||
* }
|
||||
*
|
||||
* ### REQUIRED: Buffer Padding
|
||||
*
|
||||
* The buffer must have at least SIMDJSON_PADDING extra allocated bytes. It does not matter what
|
||||
* those bytes are initialized to, as long as they are allocated.
|
||||
*
|
||||
* ### Threads
|
||||
*
|
||||
* When compiled with SIMDJSON_THREADS_ENABLED, this method will use a single thread under the
|
||||
* hood to do some lookahead.
|
||||
*
|
||||
* ### Parser Capacity
|
||||
*
|
||||
* If the parser's current capacity is less than batch_size, it will allocate enough capacity
|
||||
* to handle it (up to max_capacity).
|
||||
*
|
||||
* @param buf The concatenated JSON to parse. Must have at least len + SIMDJSON_PADDING allocated bytes.
|
||||
* @param len The length of the concatenated JSON.
|
||||
* @param batch_size The batch size to use. MUST be larger than the largest document. The sweet
|
||||
* spot is cache-related: small enough to fit in cache, yet big enough to
|
||||
* parse as many documents as possible in one tight loop.
|
||||
* Defaults to 10MB, which has been a reasonable sweet spot in our tests.
|
||||
* @return The stream, or an error. An empty input will yield 0 documents rather than an EMPTY error. Errors:
|
||||
* - MEMALLOC if the parser does not have enough capacity and memory allocation fails
|
||||
* - CAPACITY if the parser does not have enough capacity and batch_size > max_capacity.
|
||||
* - other json errors if parsing fails.
|
||||
*/
|
||||
inline simdjson_result<document_stream> parse_many(const uint8_t *buf, size_t len, size_t batch_size = DEFAULT_BATCH_SIZE) noexcept;
|
||||
/** @overload parse_many(const uint8_t *buf, size_t len, size_t batch_size) */
|
||||
inline simdjson_result<document_stream> parse_many(const char *buf, size_t len, size_t batch_size = DEFAULT_BATCH_SIZE) noexcept;
|
||||
/** @overload parse_many(const uint8_t *buf, size_t len, size_t batch_size) */
|
||||
inline simdjson_result<document_stream> parse_many(const std::string &s, size_t batch_size = DEFAULT_BATCH_SIZE) noexcept;
|
||||
/** @overload parse_many(const uint8_t *buf, size_t len, size_t batch_size) */
|
||||
inline simdjson_result<document_stream> parse_many(const padded_string &s, size_t batch_size = DEFAULT_BATCH_SIZE) noexcept;
|
||||
|
||||
/** @private We do not want to allow implicit conversion from C string to std::string. */
|
||||
simdjson_result<document_stream> parse_many(const char *buf, size_t batch_size = DEFAULT_BATCH_SIZE) noexcept = delete;
|
||||
|
||||
/**
|
||||
* Ensure this parser has enough memory to process JSON documents up to `capacity` bytes in length
|
||||
* and `max_depth` depth.
|
||||
*
|
||||
* @param capacity The new capacity.
|
||||
* @param max_depth The new max_depth. Defaults to DEFAULT_MAX_DEPTH.
|
||||
* @return The error, if there is one.
|
||||
*/
|
||||
WARN_UNUSED inline error_code allocate(size_t capacity, size_t max_depth = DEFAULT_MAX_DEPTH) noexcept;
|
||||
|
||||
/**
|
||||
* @private deprecated because it returns bool instead of error_code, which is our standard for
|
||||
* failures. Use allocate() instead.
|
||||
*
|
||||
* Ensure this parser has enough memory to process JSON documents up to `capacity` bytes in length
|
||||
* and `max_depth` depth.
|
||||
*
|
||||
* @param capacity The new capacity.
|
||||
* @param max_depth The new max_depth. Defaults to DEFAULT_MAX_DEPTH.
|
||||
* @return true if successful, false if allocation failed.
|
||||
*/
|
||||
[[deprecated("Use allocate() instead.")]]
|
||||
WARN_UNUSED inline bool allocate_capacity(size_t capacity, size_t max_depth = DEFAULT_MAX_DEPTH) noexcept;
|
||||
|
||||
/**
|
||||
* The largest document this parser can support without reallocating.
|
||||
*
|
||||
* @return Current capacity, in bytes.
|
||||
*/
|
||||
really_inline size_t capacity() const noexcept;
|
||||
|
||||
/**
|
||||
* The largest document this parser can automatically support.
|
||||
*
|
||||
* The parser may reallocate internal buffers as needed up to this amount.
|
||||
*
|
||||
* @return Maximum capacity, in bytes.
|
||||
*/
|
||||
really_inline size_t max_capacity() const noexcept;
|
||||
|
||||
/**
|
||||
* The maximum level of nested object and arrays supported by this parser.
|
||||
*
|
||||
* @return Maximum depth, in bytes.
|
||||
*/
|
||||
really_inline size_t max_depth() const noexcept;
|
||||
|
||||
/**
|
||||
* Set max_capacity. This is the largest document this parser can automatically support.
|
||||
*
|
||||
* The parser may reallocate internal buffers as needed up to this amount as documents are passed
|
||||
* to it.
|
||||
*
|
||||
* This call will not allocate or deallocate, even if capacity is currently above max_capacity.
|
||||
*
|
||||
* @param max_capacity The new maximum capacity, in bytes.
|
||||
*/
|
||||
really_inline void set_max_capacity(size_t max_capacity) noexcept;
|
||||
|
||||
/** @private Use the new DOM API instead */
|
||||
class Iterator;
|
||||
/** @private Use simdjson_error instead */
|
||||
using InvalidJSON [[deprecated("Use simdjson_error instead")]] = simdjson_error;
|
||||
|
||||
/** @private [for benchmarking access] The implementation to use */
|
||||
std::unique_ptr<internal::dom_parser_implementation> implementation{};
|
||||
|
||||
/** @private Use `if (parser.parse(...).error())` instead */
|
||||
bool valid{false};
|
||||
/** @private Use `parser.parse(...).error()` instead */
|
||||
error_code error{UNINITIALIZED};
|
||||
|
||||
/** @private Use `parser.parse(...).value()` instead */
|
||||
document doc{};
|
||||
|
||||
/** @private returns true if the document parsed was valid */
|
||||
[[deprecated("Use the result of parser.parse() instead")]]
|
||||
inline bool is_valid() const noexcept;
|
||||
|
||||
/**
|
||||
* @private return an error code corresponding to the last parsing attempt, see
|
||||
* simdjson.h will return UNITIALIZED if no parsing was attempted
|
||||
*/
|
||||
[[deprecated("Use the result of parser.parse() instead")]]
|
||||
inline int get_error_code() const noexcept;
|
||||
|
||||
/** @private return the string equivalent of "get_error_code" */
|
||||
[[deprecated("Use error_message() on the result of parser.parse() instead, or cout << error")]]
|
||||
inline std::string get_error_message() const noexcept;
|
||||
|
||||
/** @private */
|
||||
[[deprecated("Use cout << on the result of parser.parse() instead")]]
|
||||
inline bool print_json(std::ostream &os) const noexcept;
|
||||
|
||||
/** @private Private and deprecated: use `parser.parse(...).doc.dump_raw_tape()` instead */
|
||||
inline bool dump_raw_tape(std::ostream &os) const noexcept;
|
||||
|
||||
private:
|
||||
/**
|
||||
* The maximum document length this parser will automatically support.
|
||||
*
|
||||
* The parser will not be automatically allocated above this amount.
|
||||
*/
|
||||
size_t _max_capacity;
|
||||
|
||||
/**
|
||||
* The loaded buffer (reused each time load() is called)
|
||||
*/
|
||||
#if defined(_MSC_VER) && _MSC_VER < 1910
|
||||
// older versions of Visual Studio lack proper support for unique_ptr.
|
||||
std::unique_ptr<char[]> loaded_bytes;
|
||||
#else
|
||||
std::unique_ptr<char[], decltype(&aligned_free_char)> loaded_bytes;
|
||||
#endif
|
||||
|
||||
/** Capacity of loaded_bytes buffer. */
|
||||
size_t _loaded_bytes_capacity{0};
|
||||
|
||||
// all nodes are stored on the doc.tape using a 64-bit word.
|
||||
//
|
||||
// strings, double and ints are stored as
|
||||
// a 64-bit word with a pointer to the actual value
|
||||
//
|
||||
//
|
||||
//
|
||||
// for objects or arrays, store [ or { at the beginning and } and ] at the
|
||||
// end. For the openings ([ or {), we annotate them with a reference to the
|
||||
// location on the doc.tape of the end, and for then closings (} and ]), we
|
||||
// annotate them with a reference to the location of the opening
|
||||
//
|
||||
//
|
||||
|
||||
/**
|
||||
* Ensure we have enough capacity to handle at least desired_capacity bytes,
|
||||
* and auto-allocate if not.
|
||||
*/
|
||||
inline error_code ensure_capacity(size_t desired_capacity) noexcept;
|
||||
|
||||
/** Read the file into loaded_bytes */
|
||||
inline simdjson_result<size_t> read_file(const std::string &path) noexcept;
|
||||
|
||||
friend class parser::Iterator;
|
||||
friend class document_stream;
|
||||
}; // class parser
|
||||
|
||||
} // namespace dom
|
||||
} // namespace simdjson
|
||||
|
||||
#endif // SIMDJSON_DOM_PARSER_H
|
||||
@@ -3,7 +3,6 @@
|
||||
|
||||
#include "simdjson/common_defs.h"
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace simdjson {
|
||||
|
||||
@@ -12,7 +11,6 @@ namespace simdjson {
|
||||
*/
|
||||
enum error_code {
|
||||
SUCCESS = 0, ///< No error
|
||||
SUCCESS_AND_HAS_MORE, ///< @private No error and buffer still has more data
|
||||
CAPACITY, ///< This parser can't support a document that big
|
||||
MEMALLOC, ///< Error allocating memory, most likely out of memory
|
||||
TAPE_ERROR, ///< Something went wrong while writing to the tape (stage 2), this is a generic error
|
||||
@@ -44,7 +42,8 @@ enum error_code {
|
||||
* Get the error message for the given error code.
|
||||
*
|
||||
* dom::parser parser;
|
||||
* auto [doc, error] = parser.parse("foo");
|
||||
* dom::element doc;
|
||||
* auto error = parser.parse("foo").get(doc);
|
||||
* if (error) { printf("Error: %s\n", error_message(error)); }
|
||||
*
|
||||
* @return The error message.
|
||||
@@ -121,9 +120,19 @@ struct simdjson_result_base : public std::pair<T, error_code> {
|
||||
|
||||
/**
|
||||
* Move the value and the error to the provided variables.
|
||||
*
|
||||
* @param value The variable to assign the value to. May not be set if there is an error.
|
||||
* @param error The variable to assign the error to. Set to SUCCESS if there is no error.
|
||||
*/
|
||||
really_inline void tie(T &value, error_code &error) && noexcept;
|
||||
|
||||
/**
|
||||
* Move the value to the provided variable.
|
||||
*
|
||||
* @param value The variable to assign the value to. May not be set if there is an error.
|
||||
*/
|
||||
really_inline error_code get(T &value) && noexcept;
|
||||
|
||||
/**
|
||||
* The error.
|
||||
*/
|
||||
@@ -183,8 +192,18 @@ struct simdjson_result : public internal::simdjson_result_base<T> {
|
||||
|
||||
/**
|
||||
* Move the value and the error to the provided variables.
|
||||
*
|
||||
* @param value The variable to assign the value to. May not be set if there is an error.
|
||||
* @param error The variable to assign the error to. Set to SUCCESS if there is no error.
|
||||
*/
|
||||
really_inline void tie(T& t, error_code & e) && noexcept;
|
||||
really_inline void tie(T &value, error_code &error) && noexcept;
|
||||
|
||||
/**
|
||||
* Move the value to the provided variable.
|
||||
*
|
||||
* @param value The variable to assign the value to. May not be set if there is an error.
|
||||
*/
|
||||
WARN_UNUSED really_inline error_code get(T &value) && noexcept;
|
||||
|
||||
/**
|
||||
* The error.
|
||||
|
||||
@@ -1,14 +1,48 @@
|
||||
#ifndef SIMDJSON_IMPLEMENTATION_H
|
||||
#define SIMDJSON_IMPLEMENTATION_H
|
||||
|
||||
#include <optional>
|
||||
#include "simdjson/common_defs.h"
|
||||
#include "simdjson/internal/dom_parser_implementation.h"
|
||||
#include <string>
|
||||
#include <atomic>
|
||||
#include <vector>
|
||||
#include "simdjson/document.h"
|
||||
|
||||
namespace simdjson {
|
||||
|
||||
/**
|
||||
* Validate the UTF-8 string.
|
||||
*
|
||||
* @param buf the string to validate.
|
||||
* @param len the length of the string in bytes.
|
||||
* @return true if the string is valid UTF-8.
|
||||
*/
|
||||
WARN_UNUSED bool validate_utf8(const char * buf, size_t len) noexcept;
|
||||
|
||||
|
||||
/**
|
||||
* Validate the UTF-8 string.
|
||||
*
|
||||
* @param sv the string_view to validate.
|
||||
* @return true if the string is valid UTF-8.
|
||||
*/
|
||||
really_inline WARN_UNUSED bool validate_utf8(const std::string_view sv) noexcept {
|
||||
return validate_utf8(sv.data(), sv.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the UTF-8 string.
|
||||
*
|
||||
* @param p the string to validate.
|
||||
* @return true if the string is valid UTF-8.
|
||||
*/
|
||||
really_inline WARN_UNUSED bool validate_utf8(const std::string& s) noexcept {
|
||||
return validate_utf8(s.data(), s.size());
|
||||
}
|
||||
|
||||
namespace dom {
|
||||
class document;
|
||||
} // namespace dom
|
||||
|
||||
/**
|
||||
* An implementation of simdjson for a particular CPU architecture.
|
||||
*
|
||||
@@ -17,6 +51,7 @@ namespace simdjson {
|
||||
*/
|
||||
class implementation {
|
||||
public:
|
||||
|
||||
/**
|
||||
* The name of this implementation.
|
||||
*
|
||||
@@ -49,75 +84,46 @@ public:
|
||||
/**
|
||||
* @private For internal implementation use
|
||||
*
|
||||
* Run a full document parse (ensure_capacity, stage1 and stage2).
|
||||
* const implementation *impl = simdjson::active_implementation;
|
||||
* cout << "simdjson is optimized for " << impl->name() << "(" << impl->description() << ")" << endl;
|
||||
*
|
||||
* Overridden by each implementation.
|
||||
*
|
||||
* @param buf the json document to parse. *MUST* be allocated up to len + SIMDJSON_PADDING bytes.
|
||||
* @param len the length of the json document.
|
||||
* @param parser the parser with the buffers to use. *MUST* have allocated up to at least len capacity.
|
||||
* @return the error code, or SUCCESS if there was no error.
|
||||
* @param capacity The largest document that will be passed to the parser.
|
||||
* @param max_depth The maximum JSON object/array nesting this parser is expected to handle.
|
||||
* @param dst The place to put the resulting parser implementation.
|
||||
* @return the name of the implementation, e.g. "haswell", "westmere", "arm64"
|
||||
*/
|
||||
WARN_UNUSED virtual error_code parse(const uint8_t *buf, size_t len, dom::parser &parser) const noexcept = 0;
|
||||
virtual error_code create_dom_parser_implementation(
|
||||
size_t capacity,
|
||||
size_t max_depth,
|
||||
std::unique_ptr<internal::dom_parser_implementation> &dst
|
||||
) const noexcept = 0;
|
||||
|
||||
/**
|
||||
* @private For internal implementation use
|
||||
*
|
||||
* Run a full document parse (ensure_capacity, stage1 and stage2).
|
||||
* Minify the input string assuming that it represents a JSON string, does not parse or validate.
|
||||
*
|
||||
* Overridden by each implementation.
|
||||
*
|
||||
* @param buf the json document to parse. *MUST* be allocated up to len + SIMDJSON_PADDING bytes.
|
||||
* @param buf the json document to minify.
|
||||
* @param len the length of the json document.
|
||||
* @param dst the buffer to write the minified document to. *MUST* be allocated up to len + SIMDJSON_PADDING bytes.
|
||||
* @param dst_len the number of bytes written. Output only.
|
||||
* @return the error code, or SUCCESS if there was no error.
|
||||
*/
|
||||
WARN_UNUSED virtual error_code minify(const uint8_t *buf, size_t len, uint8_t *dst, size_t &dst_len) const noexcept = 0;
|
||||
|
||||
/**
|
||||
* @private For internal implementation use
|
||||
*
|
||||
* Stage 1 of the document parser.
|
||||
|
||||
|
||||
/**
|
||||
* Validate the UTF-8 string.
|
||||
*
|
||||
* Overridden by each implementation.
|
||||
*
|
||||
* @param buf the json document to parse. *MUST* be allocated up to len + SIMDJSON_PADDING bytes.
|
||||
* @param len the length of the json document.
|
||||
* @param parser the parser with the buffers to use. *MUST* have allocated up to at least len capacity.
|
||||
* @param streaming whether this is being called by parser::parse_many.
|
||||
* @return the error code, or SUCCESS if there was no error.
|
||||
* @param buf the string to validate.
|
||||
* @param len the length of the string in bytes.
|
||||
* @return true if and only if the string is valid UTF-8.
|
||||
*/
|
||||
WARN_UNUSED virtual error_code stage1(const uint8_t *buf, size_t len, dom::parser &parser, bool streaming) const noexcept = 0;
|
||||
|
||||
/**
|
||||
* @private For internal implementation use
|
||||
*
|
||||
* Stage 2 of the document parser.
|
||||
*
|
||||
* Overridden by each implementation.
|
||||
*
|
||||
* @param buf the json document to parse. *MUST* be allocated up to len + SIMDJSON_PADDING bytes.
|
||||
* @param len the length of the json document.
|
||||
* @param parser the parser with the buffers to use. *MUST* have allocated up to at least len capacity.
|
||||
* @return the error code, or SUCCESS if there was no error.
|
||||
*/
|
||||
WARN_UNUSED virtual error_code stage2(const uint8_t *buf, size_t len, dom::parser &parser) const noexcept = 0;
|
||||
|
||||
/**
|
||||
* @private For internal implementation use
|
||||
*
|
||||
* Stage 2 of the document parser for parser::parse_many.
|
||||
*
|
||||
* Overridden by each implementation.
|
||||
*
|
||||
* @param buf the json document to parse. *MUST* be allocated up to len + SIMDJSON_PADDING bytes.
|
||||
* @param len the length of the json document.
|
||||
* @param parser the parser with the buffers to use. *MUST* have allocated up to at least len capacity.
|
||||
* @param next_json the next structural index. Start this at 0 the first time, and it will be updated to the next value to pass each time.
|
||||
* @return the error code, SUCCESS if there was no error, or SUCCESS_AND_HAS_MORE if there was no error and stage2 can be called again.
|
||||
*/
|
||||
WARN_UNUSED virtual error_code stage2(const uint8_t *buf, size_t len, dom::parser &parser, size_t &next_json) const noexcept = 0;
|
||||
WARN_UNUSED virtual bool validate_utf8(const char *buf, size_t len) const noexcept = 0;
|
||||
|
||||
protected:
|
||||
/** @private Construct an implementation with the given name and description. For subclasses. */
|
||||
@@ -131,6 +137,7 @@ protected:
|
||||
_required_instruction_sets(required_instruction_sets)
|
||||
{
|
||||
}
|
||||
virtual ~implementation()=default;
|
||||
|
||||
private:
|
||||
/**
|
||||
@@ -200,37 +207,6 @@ public:
|
||||
const implementation *detect_best_supported() const noexcept;
|
||||
};
|
||||
|
||||
/**
|
||||
* @private Detects best supported implementation on first use, and sets it
|
||||
*/
|
||||
class detect_best_supported_implementation_on_first_use final : public implementation {
|
||||
public:
|
||||
const std::string &name() const noexcept final { return set_best()->name(); }
|
||||
const std::string &description() const noexcept final { return set_best()->description(); }
|
||||
uint32_t required_instruction_sets() const noexcept final { return set_best()->required_instruction_sets(); }
|
||||
WARN_UNUSED error_code parse(const uint8_t *buf, size_t len, dom::parser &parser) const noexcept final {
|
||||
return set_best()->parse(buf, len, parser);
|
||||
}
|
||||
WARN_UNUSED error_code minify(const uint8_t *buf, size_t len, uint8_t *dst, size_t &dst_len) const noexcept final {
|
||||
return set_best()->minify(buf, len, dst, dst_len);
|
||||
}
|
||||
WARN_UNUSED error_code stage1(const uint8_t *buf, size_t len, dom::parser &parser, bool streaming) const noexcept final {
|
||||
return set_best()->stage1(buf, len, parser, streaming);
|
||||
}
|
||||
WARN_UNUSED error_code stage2(const uint8_t *buf, size_t len, dom::parser &parser) const noexcept final {
|
||||
return set_best()->stage2(buf, len, parser);
|
||||
}
|
||||
WARN_UNUSED error_code stage2(const uint8_t *buf, size_t len, dom::parser &parser, size_t &next_json) const noexcept final {
|
||||
return set_best()->stage2(buf, len, parser, next_json);
|
||||
}
|
||||
|
||||
really_inline detect_best_supported_implementation_on_first_use() noexcept : implementation("best_supported_detector", "Detects the best supported implementation and sets it", 0) {}
|
||||
private:
|
||||
const implementation *set_best() const noexcept;
|
||||
};
|
||||
|
||||
inline const detect_best_supported_implementation_on_first_use detect_best_supported_implementation_on_first_use_singleton;
|
||||
|
||||
template<typename T>
|
||||
class atomic_ptr {
|
||||
public:
|
||||
@@ -243,27 +219,25 @@ public:
|
||||
operator T*() { return ptr.load(); }
|
||||
T& operator*() { return *ptr; }
|
||||
T* operator->() { return ptr.load(); }
|
||||
T* operator=(T *_ptr) { return ptr = _ptr; }
|
||||
atomic_ptr& operator=(T *_ptr) { ptr = _ptr; return *this; }
|
||||
|
||||
private:
|
||||
std::atomic<T*> ptr;
|
||||
};
|
||||
|
||||
} // namespace [simdjson::]internal
|
||||
} // namespace internal
|
||||
|
||||
/**
|
||||
* The list of available implementations compiled into simdjson.
|
||||
*/
|
||||
inline const internal::available_implementation_list available_implementations;
|
||||
extern SIMDJSON_DLLIMPORTEXPORT const internal::available_implementation_list available_implementations;
|
||||
|
||||
/**
|
||||
* The active implementation.
|
||||
*
|
||||
* Automatically initialized on first use to the most advanced implementation supported by this hardware.
|
||||
*
|
||||
* @hideinitializer
|
||||
*/
|
||||
inline internal::atomic_ptr<const implementation> active_implementation = &internal::detect_best_supported_implementation_on_first_use_singleton;
|
||||
extern SIMDJSON_DLLIMPORTEXPORT internal::atomic_ptr<const implementation> active_implementation;
|
||||
|
||||
} // namespace simdjson
|
||||
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
#ifndef SIMDJSON_INLINE_ARRAY_H
|
||||
#define SIMDJSON_INLINE_ARRAY_H
|
||||
|
||||
// Inline implementations go in here.
|
||||
|
||||
#include "simdjson/dom/array.h"
|
||||
#include "simdjson/dom/element.h"
|
||||
#include <utility>
|
||||
|
||||
namespace simdjson {
|
||||
|
||||
//
|
||||
// simdjson_result<dom::array> inline implementation
|
||||
//
|
||||
really_inline simdjson_result<dom::array>::simdjson_result() noexcept
|
||||
: internal::simdjson_result_base<dom::array>() {}
|
||||
really_inline simdjson_result<dom::array>::simdjson_result(dom::array value) noexcept
|
||||
: internal::simdjson_result_base<dom::array>(std::forward<dom::array>(value)) {}
|
||||
really_inline simdjson_result<dom::array>::simdjson_result(error_code error) noexcept
|
||||
: internal::simdjson_result_base<dom::array>(error) {}
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
|
||||
inline dom::array::iterator simdjson_result<dom::array>::begin() const noexcept(false) {
|
||||
if (error()) { throw simdjson_error(error()); }
|
||||
return first.begin();
|
||||
}
|
||||
inline dom::array::iterator simdjson_result<dom::array>::end() const noexcept(false) {
|
||||
if (error()) { throw simdjson_error(error()); }
|
||||
return first.end();
|
||||
}
|
||||
inline size_t simdjson_result<dom::array>::size() const noexcept(false) {
|
||||
if (error()) { throw simdjson_error(error()); }
|
||||
return first.size();
|
||||
}
|
||||
|
||||
#endif // SIMDJSON_EXCEPTIONS
|
||||
|
||||
inline simdjson_result<dom::element> simdjson_result<dom::array>::at(const std::string_view &json_pointer) const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.at(json_pointer);
|
||||
}
|
||||
inline simdjson_result<dom::element> simdjson_result<dom::array>::at(size_t index) const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.at(index);
|
||||
}
|
||||
|
||||
namespace dom {
|
||||
|
||||
//
|
||||
// array inline implementation
|
||||
//
|
||||
really_inline array::array() noexcept : tape{} {}
|
||||
really_inline array::array(const internal::tape_ref &_tape) noexcept : tape{_tape} {}
|
||||
inline array::iterator array::begin() const noexcept {
|
||||
return internal::tape_ref(tape.doc, tape.json_index + 1);
|
||||
}
|
||||
inline array::iterator array::end() const noexcept {
|
||||
return internal::tape_ref(tape.doc, tape.after_element() - 1);
|
||||
}
|
||||
inline size_t array::size() const noexcept {
|
||||
return tape.scope_count();
|
||||
}
|
||||
inline simdjson_result<element> array::at(const std::string_view &json_pointer) const noexcept {
|
||||
// - means "the append position" or "the element after the end of the array"
|
||||
// We don't support this, because we're returning a real element, not a position.
|
||||
if (json_pointer == "-") { return INDEX_OUT_OF_BOUNDS; }
|
||||
|
||||
// Read the array index
|
||||
size_t array_index = 0;
|
||||
size_t i;
|
||||
for (i = 0; i < json_pointer.length() && json_pointer[i] != '/'; i++) {
|
||||
uint8_t digit = uint8_t(json_pointer[i] - '0');
|
||||
// Check for non-digit in array index. If it's there, we're trying to get a field in an object
|
||||
if (digit > 9) { return INCORRECT_TYPE; }
|
||||
array_index = array_index*10 + digit;
|
||||
}
|
||||
|
||||
// 0 followed by other digits is invalid
|
||||
if (i > 1 && json_pointer[0] == '0') { return INVALID_JSON_POINTER; } // "JSON pointer array index has other characters after 0"
|
||||
|
||||
// Empty string is invalid; so is a "/" with no digits before it
|
||||
if (i == 0) { return INVALID_JSON_POINTER; } // "Empty string in JSON pointer array index"
|
||||
|
||||
// Get the child
|
||||
auto child = array(tape).at(array_index);
|
||||
// If there is a /, we're not done yet, call recursively.
|
||||
if (i < json_pointer.length()) {
|
||||
child = child.at(json_pointer.substr(i+1));
|
||||
}
|
||||
return child;
|
||||
}
|
||||
inline simdjson_result<element> array::at(size_t index) const noexcept {
|
||||
size_t i=0;
|
||||
for (auto element : *this) {
|
||||
if (i == index) { return element; }
|
||||
i++;
|
||||
}
|
||||
return INDEX_OUT_OF_BOUNDS;
|
||||
}
|
||||
|
||||
//
|
||||
// array::iterator inline implementation
|
||||
//
|
||||
really_inline array::iterator::iterator(const internal::tape_ref &_tape) noexcept : tape{_tape} { }
|
||||
inline element array::iterator::operator*() const noexcept {
|
||||
return element(tape);
|
||||
}
|
||||
inline bool array::iterator::operator!=(const array::iterator& other) const noexcept {
|
||||
return tape.json_index != other.tape.json_index;
|
||||
}
|
||||
inline array::iterator& array::iterator::operator++() noexcept {
|
||||
tape.json_index = tape.after_element();
|
||||
return *this;
|
||||
}
|
||||
|
||||
inline std::ostream& operator<<(std::ostream& out, const array &value) {
|
||||
return out << minify<array>(value);
|
||||
}
|
||||
|
||||
} // namespace dom
|
||||
|
||||
template<>
|
||||
inline std::ostream& minifier<dom::array>::print(std::ostream& out) {
|
||||
out << '[';
|
||||
auto iter = value.begin();
|
||||
auto end = value.end();
|
||||
if (iter != end) {
|
||||
out << minify<dom::element>(*iter);
|
||||
for (++iter; iter != end; ++iter) {
|
||||
out << "," << minify<dom::element>(*iter);
|
||||
}
|
||||
}
|
||||
return out << ']';
|
||||
}
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
|
||||
template<>
|
||||
inline std::ostream& minifier<simdjson_result<dom::array>>::print(std::ostream& out) {
|
||||
if (value.error()) { throw simdjson_error(value.error()); }
|
||||
return out << minify<dom::array>(value.first);
|
||||
}
|
||||
|
||||
inline std::ostream& operator<<(std::ostream& out, const simdjson_result<dom::array> &value) noexcept(false) {
|
||||
return out << minify<simdjson_result<dom::array>>(value);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace simdjson
|
||||
|
||||
#endif // SIMDJSON_INLINE_ARRAY_H
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,122 +1,103 @@
|
||||
#ifndef SIMDJSON_INLINE_DOCUMENT_STREAM_H
|
||||
#define SIMDJSON_INLINE_DOCUMENT_STREAM_H
|
||||
|
||||
#include "simdjson/document_stream.h"
|
||||
#include "simdjson/dom/document_stream.h"
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
namespace simdjson {
|
||||
namespace dom {
|
||||
|
||||
namespace simdjson::internal {
|
||||
|
||||
/**
|
||||
* This algorithm is used to quickly identify the buffer position of
|
||||
* the last JSON document inside the current batch.
|
||||
*
|
||||
* It does its work by finding the last pair of structural characters
|
||||
* that represent the end followed by the start of a document.
|
||||
*
|
||||
* Simply put, we iterate over the structural characters, starting from
|
||||
* the end. We consider that we found the end of a JSON document when the
|
||||
* first element of the pair is NOT one of these characters: '{' '[' ';' ','
|
||||
* and when the second element is NOT one of these characters: '}' '}' ';' ','.
|
||||
*
|
||||
* This simple comparison works most of the time, but it does not cover cases
|
||||
* where the batch's structural indexes contain a perfect amount of documents.
|
||||
* In such a case, we do not have access to the structural index which follows
|
||||
* the last document, therefore, we do not have access to the second element in
|
||||
* the pair, and means that we cannot identify the last document. To fix this
|
||||
* issue, we keep a count of the open and closed curly/square braces we found
|
||||
* while searching for the pair. When we find a pair AND the count of open and
|
||||
* closed curly/square braces is the same, we know that we just passed a
|
||||
* complete
|
||||
* document, therefore the last json buffer location is the end of the batch
|
||||
* */
|
||||
inline size_t find_last_json_buf_idx(const uint8_t *buf, size_t size, const dom::parser &parser) {
|
||||
// this function can be generally useful
|
||||
if (parser.n_structural_indexes == 0)
|
||||
return 0;
|
||||
auto last_i = parser.n_structural_indexes - 1;
|
||||
if (parser.structural_indexes[last_i] == size) {
|
||||
if (last_i == 0)
|
||||
return 0;
|
||||
last_i = parser.n_structural_indexes - 2;
|
||||
}
|
||||
auto arr_cnt = 0;
|
||||
auto obj_cnt = 0;
|
||||
for (auto i = last_i; i > 0; i--) {
|
||||
auto idxb = parser.structural_indexes[i];
|
||||
switch (buf[idxb]) {
|
||||
case ':':
|
||||
case ',':
|
||||
continue;
|
||||
case '}':
|
||||
obj_cnt--;
|
||||
continue;
|
||||
case ']':
|
||||
arr_cnt--;
|
||||
continue;
|
||||
case '{':
|
||||
obj_cnt++;
|
||||
break;
|
||||
case '[':
|
||||
arr_cnt++;
|
||||
break;
|
||||
}
|
||||
auto idxa = parser.structural_indexes[i - 1];
|
||||
switch (buf[idxa]) {
|
||||
case '{':
|
||||
case '[':
|
||||
case ':':
|
||||
case ',':
|
||||
continue;
|
||||
}
|
||||
if (!arr_cnt && !obj_cnt) {
|
||||
return last_i + 1;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
return 0;
|
||||
#ifdef SIMDJSON_THREADS_ENABLED
|
||||
inline void stage1_worker::finish() {
|
||||
std::unique_lock<std::mutex> lock(locking_mutex);
|
||||
cond_var.wait(lock, [this]{return has_work == false;});
|
||||
}
|
||||
|
||||
// returns true if the provided byte value is an ASCII character
|
||||
static inline bool is_ascii(char c) {
|
||||
return ((unsigned char)c) <= 127;
|
||||
inline stage1_worker::~stage1_worker() {
|
||||
stop_thread();
|
||||
}
|
||||
|
||||
// if the string ends with UTF-8 values, backtrack
|
||||
// up to the first ASCII character. May return 0.
|
||||
static inline size_t trimmed_length_safe_utf8(const char * c, size_t len) {
|
||||
while ((len > 0) and (not is_ascii(c[len - 1]))) {
|
||||
len--;
|
||||
inline void stage1_worker::start_thread() {
|
||||
std::unique_lock<std::mutex> lock(locking_mutex);
|
||||
if(thread.joinable()) {
|
||||
return; // This should never happen but we never want to create more than one thread.
|
||||
}
|
||||
return len;
|
||||
thread = std::thread([this]{
|
||||
while(can_work) {
|
||||
std::unique_lock<std::mutex> thread_lock(locking_mutex);
|
||||
cond_var.wait(thread_lock, [this]{return has_work || !can_work;});
|
||||
if(!can_work) {
|
||||
break;
|
||||
}
|
||||
this->owner->stage1_thread_error = this->owner->run_stage1(*this->stage1_thread_parser,
|
||||
this->_next_batch_start);
|
||||
this->has_work = false;
|
||||
thread_lock.unlock();
|
||||
cond_var.notify_one(); // will notify "finish"
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
} // namespace simdjson::internal
|
||||
|
||||
namespace simdjson::dom {
|
||||
inline void stage1_worker::stop_thread() {
|
||||
std::unique_lock<std::mutex> lock(locking_mutex);
|
||||
// We have to make sure that all locks can be released.
|
||||
can_work = false;
|
||||
has_work = false;
|
||||
lock.unlock();
|
||||
cond_var.notify_all();
|
||||
if(thread.joinable()) {
|
||||
thread.join();
|
||||
}
|
||||
}
|
||||
|
||||
inline void stage1_worker::run(document_stream * ds, dom::parser * stage1, size_t next_batch_start) {
|
||||
std::unique_lock<std::mutex> lock(locking_mutex);
|
||||
owner = ds;
|
||||
_next_batch_start = next_batch_start;
|
||||
stage1_thread_parser = stage1;
|
||||
has_work = true;
|
||||
lock.unlock();
|
||||
cond_var.notify_one();// will notify the thread lock
|
||||
}
|
||||
#endif
|
||||
|
||||
really_inline document_stream::document_stream(
|
||||
dom::parser &_parser,
|
||||
const uint8_t *buf,
|
||||
size_t len,
|
||||
size_t batch_size,
|
||||
error_code _error
|
||||
) noexcept : parser{_parser}, _buf{buf}, _len{len}, _batch_size(batch_size), error{_error} {
|
||||
if (!error) { error = json_parse(); }
|
||||
}
|
||||
|
||||
inline document_stream::~document_stream() noexcept {
|
||||
const uint8_t *_buf,
|
||||
size_t _len,
|
||||
size_t _batch_size
|
||||
) noexcept
|
||||
: parser{&_parser},
|
||||
buf{_buf},
|
||||
len{_len},
|
||||
batch_size{_batch_size},
|
||||
error{SUCCESS}
|
||||
{
|
||||
#ifdef SIMDJSON_THREADS_ENABLED
|
||||
if (stage_1_thread.joinable()) {
|
||||
stage_1_thread.join();
|
||||
if(worker.get() == nullptr) {
|
||||
error = MEMALLOC;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
really_inline document_stream::document_stream() noexcept
|
||||
: parser{nullptr},
|
||||
buf{nullptr},
|
||||
len{0},
|
||||
batch_size{0},
|
||||
error{UNINITIALIZED} {
|
||||
}
|
||||
|
||||
really_inline document_stream::~document_stream() noexcept {
|
||||
}
|
||||
|
||||
really_inline document_stream::iterator document_stream::begin() noexcept {
|
||||
return iterator(*this, false);
|
||||
start();
|
||||
// If there are no documents, we're finished.
|
||||
return iterator(*this, error == EMPTY);
|
||||
}
|
||||
|
||||
really_inline document_stream::iterator document_stream::end() noexcept {
|
||||
@@ -128,17 +109,15 @@ really_inline document_stream::iterator::iterator(document_stream& _stream, bool
|
||||
}
|
||||
|
||||
really_inline simdjson_result<element> document_stream::iterator::operator*() noexcept {
|
||||
error_code err = stream.error == SUCCESS_AND_HAS_MORE ? SUCCESS : stream.error;
|
||||
if (err) { return err; }
|
||||
return stream.parser.doc.root();
|
||||
// Once we have yielded any errors, we're finished.
|
||||
if (stream.error) { finished = true; return stream.error; }
|
||||
return stream.parser->doc.root();
|
||||
}
|
||||
|
||||
really_inline document_stream::iterator& document_stream::iterator::operator++() noexcept {
|
||||
if (stream.error == SUCCESS_AND_HAS_MORE) {
|
||||
stream.error = stream.json_parse();
|
||||
} else {
|
||||
finished = true;
|
||||
}
|
||||
stream.next();
|
||||
// If that was the last document, we're finished.
|
||||
if (stream.error == EMPTY) { finished = true; }
|
||||
return *this;
|
||||
}
|
||||
|
||||
@@ -146,131 +125,131 @@ really_inline bool document_stream::iterator::operator!=(const document_stream::
|
||||
return finished != other.finished;
|
||||
}
|
||||
|
||||
inline void document_stream::start() noexcept {
|
||||
if (error) { return; }
|
||||
|
||||
error = parser->ensure_capacity(batch_size);
|
||||
if (error) { return; }
|
||||
|
||||
// Always run the first stage 1 parse immediately
|
||||
batch_start = 0;
|
||||
error = run_stage1(*parser, batch_start);
|
||||
if (error) { return; }
|
||||
|
||||
#ifdef SIMDJSON_THREADS_ENABLED
|
||||
|
||||
// threaded version of json_parse
|
||||
// todo: simplify this code further
|
||||
inline error_code document_stream::json_parse() noexcept {
|
||||
error = parser.ensure_capacity(_batch_size);
|
||||
if (error) { return error; }
|
||||
error = parser_thread.ensure_capacity(_batch_size);
|
||||
if (error) { return error; }
|
||||
|
||||
if (unlikely(load_next_batch)) {
|
||||
// First time loading
|
||||
if (!stage_1_thread.joinable()) {
|
||||
_batch_size = (std::min)(_batch_size, remaining());
|
||||
_batch_size = internal::trimmed_length_safe_utf8((const char *)buf(), _batch_size);
|
||||
if (_batch_size == 0) {
|
||||
return simdjson::UTF8_ERROR;
|
||||
}
|
||||
auto stage1_is_ok = error_code(simdjson::active_implementation->stage1(buf(), _batch_size, parser, true));
|
||||
if (stage1_is_ok != simdjson::SUCCESS) {
|
||||
return stage1_is_ok;
|
||||
}
|
||||
size_t last_index = internal::find_last_json_buf_idx(buf(), _batch_size, parser);
|
||||
if (last_index == 0) {
|
||||
if (parser.n_structural_indexes == 0) {
|
||||
return simdjson::EMPTY;
|
||||
}
|
||||
} else {
|
||||
parser.n_structural_indexes = last_index + 1;
|
||||
}
|
||||
}
|
||||
// the second thread is running or done.
|
||||
else {
|
||||
stage_1_thread.join();
|
||||
if (stage1_is_ok_thread != simdjson::SUCCESS) {
|
||||
return stage1_is_ok_thread;
|
||||
}
|
||||
std::swap(parser.structural_indexes, parser_thread.structural_indexes);
|
||||
parser.n_structural_indexes = parser_thread.n_structural_indexes;
|
||||
advance(last_json_buffer_loc);
|
||||
n_bytes_parsed += last_json_buffer_loc;
|
||||
}
|
||||
// let us decide whether we will start a new thread
|
||||
if (remaining() - _batch_size > 0) {
|
||||
last_json_buffer_loc =
|
||||
parser.structural_indexes[internal::find_last_json_buf_idx(buf(), _batch_size, parser)];
|
||||
_batch_size = (std::min)(_batch_size, remaining() - last_json_buffer_loc);
|
||||
if (_batch_size > 0) {
|
||||
_batch_size = internal::trimmed_length_safe_utf8(
|
||||
(const char *)(buf() + last_json_buffer_loc), _batch_size);
|
||||
if (_batch_size == 0) {
|
||||
return simdjson::UTF8_ERROR;
|
||||
}
|
||||
// let us capture read-only variables
|
||||
const uint8_t *const b = buf() + last_json_buffer_loc;
|
||||
const size_t bs = _batch_size;
|
||||
// we call the thread on a lambda that will update
|
||||
// this->stage1_is_ok_thread
|
||||
// there is only one thread that may write to this value
|
||||
stage_1_thread = std::thread([this, b, bs] {
|
||||
this->stage1_is_ok_thread = error_code(simdjson::active_implementation->stage1(b, bs, this->parser_thread, true));
|
||||
});
|
||||
}
|
||||
}
|
||||
next_json = 0;
|
||||
load_next_batch = false;
|
||||
} // load_next_batch
|
||||
error_code res = simdjson::active_implementation->stage2(buf(), remaining(), parser, next_json);
|
||||
if (res == simdjson::SUCCESS_AND_HAS_MORE) {
|
||||
n_parsed_docs++;
|
||||
current_buffer_loc = parser.structural_indexes[next_json];
|
||||
load_next_batch = (current_buffer_loc == last_json_buffer_loc);
|
||||
} else if (res == simdjson::SUCCESS) {
|
||||
n_parsed_docs++;
|
||||
if (remaining() > _batch_size) {
|
||||
current_buffer_loc = parser.structural_indexes[next_json - 1];
|
||||
load_next_batch = true;
|
||||
res = simdjson::SUCCESS_AND_HAS_MORE;
|
||||
}
|
||||
if (next_batch_start() < len) {
|
||||
// Kick off the first thread if needed
|
||||
error = stage1_thread_parser.ensure_capacity(batch_size);
|
||||
if (error) { return; }
|
||||
worker->start_thread();
|
||||
start_stage1_thread();
|
||||
if (error) { return; }
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
#else // SIMDJSON_THREADS_ENABLED
|
||||
|
||||
// single-threaded version of json_parse
|
||||
inline error_code document_stream::json_parse() noexcept {
|
||||
error = parser.ensure_capacity(_batch_size);
|
||||
if (error) { return error; }
|
||||
|
||||
if (unlikely(load_next_batch)) {
|
||||
advance(current_buffer_loc);
|
||||
n_bytes_parsed += current_buffer_loc;
|
||||
_batch_size = (std::min)(_batch_size, remaining());
|
||||
_batch_size = internal::trimmed_length_safe_utf8((const char *)buf(), _batch_size);
|
||||
auto stage1_is_ok = (error_code)simdjson::active_implementation->stage1(buf(), _batch_size, parser, true);
|
||||
if (stage1_is_ok != simdjson::SUCCESS) {
|
||||
return stage1_is_ok;
|
||||
}
|
||||
size_t last_index = internal::find_last_json_buf_idx(buf(), _batch_size, parser);
|
||||
if (last_index == 0) {
|
||||
if (parser.n_structural_indexes == 0) {
|
||||
return EMPTY;
|
||||
}
|
||||
} else {
|
||||
parser.n_structural_indexes = last_index + 1;
|
||||
}
|
||||
load_next_batch = false;
|
||||
} // load_next_batch
|
||||
error_code res = simdjson::active_implementation->stage2(buf(), remaining(), parser, next_json);
|
||||
if (likely(res == simdjson::SUCCESS_AND_HAS_MORE)) {
|
||||
n_parsed_docs++;
|
||||
current_buffer_loc = parser.structural_indexes[next_json];
|
||||
} else if (res == simdjson::SUCCESS) {
|
||||
n_parsed_docs++;
|
||||
if (remaining() > _batch_size) {
|
||||
current_buffer_loc = parser.structural_indexes[next_json - 1];
|
||||
next_json = 1;
|
||||
load_next_batch = true;
|
||||
res = simdjson::SUCCESS_AND_HAS_MORE;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
#endif // SIMDJSON_THREADS_ENABLED
|
||||
|
||||
} // namespace simdjson::dom
|
||||
next();
|
||||
}
|
||||
|
||||
really_inline size_t document_stream::iterator::current_index() noexcept {
|
||||
return stream.doc_index;
|
||||
}
|
||||
inline void document_stream::next() noexcept {
|
||||
if (error) { return; }
|
||||
|
||||
// Load the next document from the batch
|
||||
doc_index = batch_start + parser->implementation->structural_indexes[parser->implementation->next_structural_index];
|
||||
error = parser->implementation->stage2_next(parser->doc);
|
||||
// If that was the last document in the batch, load another batch (if available)
|
||||
while (error == EMPTY) {
|
||||
batch_start = next_batch_start();
|
||||
if (batch_start >= len) { break; }
|
||||
|
||||
#ifdef SIMDJSON_THREADS_ENABLED
|
||||
load_from_stage1_thread();
|
||||
#else
|
||||
error = run_stage1(*parser, batch_start);
|
||||
#endif
|
||||
if (error) { continue; } // If the error was EMPTY, we may want to load another batch.
|
||||
// Run stage 2 on the first document in the batch
|
||||
doc_index = batch_start + parser->implementation->structural_indexes[parser->implementation->next_structural_index];
|
||||
error = parser->implementation->stage2_next(parser->doc);
|
||||
}
|
||||
}
|
||||
|
||||
inline size_t document_stream::next_batch_start() const noexcept {
|
||||
return batch_start + parser->implementation->structural_indexes[parser->implementation->n_structural_indexes];
|
||||
}
|
||||
|
||||
inline error_code document_stream::run_stage1(dom::parser &p, size_t _batch_start) noexcept {
|
||||
// If this is the final batch, pass partial = false
|
||||
size_t remaining = len - _batch_start;
|
||||
if (remaining <= batch_size) {
|
||||
return p.implementation->stage1(&buf[_batch_start], remaining, false);
|
||||
} else {
|
||||
return p.implementation->stage1(&buf[_batch_start], batch_size, true);
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef SIMDJSON_THREADS_ENABLED
|
||||
|
||||
inline void document_stream::load_from_stage1_thread() noexcept {
|
||||
worker->finish();
|
||||
// Swap to the parser that was loaded up in the thread. Make sure the parser has
|
||||
// enough memory to swap to, as well.
|
||||
std::swap(*parser, stage1_thread_parser);
|
||||
error = stage1_thread_error;
|
||||
if (error) { return; }
|
||||
|
||||
// If there's anything left, start the stage 1 thread!
|
||||
if (next_batch_start() < len) {
|
||||
start_stage1_thread();
|
||||
}
|
||||
}
|
||||
|
||||
inline void document_stream::start_stage1_thread() noexcept {
|
||||
// we call the thread on a lambda that will update
|
||||
// this->stage1_thread_error
|
||||
// there is only one thread that may write to this value
|
||||
// TODO this is NOT exception-safe.
|
||||
this->stage1_thread_error = UNINITIALIZED; // In case something goes wrong, make sure it's an error
|
||||
size_t _next_batch_start = this->next_batch_start();
|
||||
|
||||
worker->run(this, & this->stage1_thread_parser, _next_batch_start);
|
||||
}
|
||||
|
||||
#endif // SIMDJSON_THREADS_ENABLED
|
||||
|
||||
} // namespace dom
|
||||
|
||||
really_inline simdjson_result<dom::document_stream>::simdjson_result() noexcept
|
||||
: simdjson_result_base() {
|
||||
}
|
||||
really_inline simdjson_result<dom::document_stream>::simdjson_result(error_code error) noexcept
|
||||
: simdjson_result_base(error) {
|
||||
}
|
||||
really_inline simdjson_result<dom::document_stream>::simdjson_result(dom::document_stream &&value) noexcept
|
||||
: simdjson_result_base(std::forward<dom::document_stream>(value)) {
|
||||
}
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
really_inline dom::document_stream::iterator simdjson_result<dom::document_stream>::begin() noexcept(false) {
|
||||
if (error()) { throw simdjson_error(error()); }
|
||||
return first.begin();
|
||||
}
|
||||
really_inline dom::document_stream::iterator simdjson_result<dom::document_stream>::end() noexcept(false) {
|
||||
if (error()) { throw simdjson_error(error()); }
|
||||
return first.end();
|
||||
}
|
||||
#else // SIMDJSON_EXCEPTIONS
|
||||
really_inline dom::document_stream::iterator simdjson_result<dom::document_stream>::begin() noexcept {
|
||||
first.error = error();
|
||||
return first.begin();
|
||||
}
|
||||
really_inline dom::document_stream::iterator simdjson_result<dom::document_stream>::end() noexcept {
|
||||
first.error = error();
|
||||
return first.end();
|
||||
}
|
||||
#endif // SIMDJSON_EXCEPTIONS
|
||||
|
||||
} // namespace simdjson
|
||||
#endif // SIMDJSON_INLINE_DOCUMENT_STREAM_H
|
||||
|
||||
@@ -0,0 +1,535 @@
|
||||
#ifndef SIMDJSON_INLINE_ELEMENT_H
|
||||
#define SIMDJSON_INLINE_ELEMENT_H
|
||||
|
||||
#include "simdjson/dom/array.h"
|
||||
#include "simdjson/dom/element.h"
|
||||
#include "simdjson/dom/object.h"
|
||||
#include <cstring>
|
||||
#include <utility>
|
||||
|
||||
namespace simdjson {
|
||||
|
||||
//
|
||||
// simdjson_result<dom::element> inline implementation
|
||||
//
|
||||
really_inline simdjson_result<dom::element>::simdjson_result() noexcept
|
||||
: internal::simdjson_result_base<dom::element>() {}
|
||||
really_inline simdjson_result<dom::element>::simdjson_result(dom::element &&value) noexcept
|
||||
: internal::simdjson_result_base<dom::element>(std::forward<dom::element>(value)) {}
|
||||
really_inline simdjson_result<dom::element>::simdjson_result(error_code error) noexcept
|
||||
: internal::simdjson_result_base<dom::element>(error) {}
|
||||
inline simdjson_result<dom::element_type> simdjson_result<dom::element>::type() const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.type();
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
really_inline bool simdjson_result<dom::element>::is() const noexcept {
|
||||
return !error() && first.is<T>();
|
||||
}
|
||||
template<typename T>
|
||||
really_inline simdjson_result<T> simdjson_result<dom::element>::get() const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.get<T>();
|
||||
}
|
||||
template<typename T>
|
||||
WARN_UNUSED really_inline error_code simdjson_result<dom::element>::get(T &value) const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.get<T>(value);
|
||||
}
|
||||
|
||||
really_inline simdjson_result<dom::array> simdjson_result<dom::element>::get_array() const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.get_array();
|
||||
}
|
||||
really_inline simdjson_result<dom::object> simdjson_result<dom::element>::get_object() const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.get_object();
|
||||
}
|
||||
really_inline simdjson_result<const char *> simdjson_result<dom::element>::get_c_str() const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.get_c_str();
|
||||
}
|
||||
really_inline simdjson_result<size_t> simdjson_result<dom::element>::get_string_length() const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.get_string_length();
|
||||
}
|
||||
really_inline simdjson_result<std::string_view> simdjson_result<dom::element>::get_string() const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.get_string();
|
||||
}
|
||||
really_inline simdjson_result<int64_t> simdjson_result<dom::element>::get_int64() const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.get_int64();
|
||||
}
|
||||
really_inline simdjson_result<uint64_t> simdjson_result<dom::element>::get_uint64() const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.get_uint64();
|
||||
}
|
||||
really_inline simdjson_result<double> simdjson_result<dom::element>::get_double() const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.get_double();
|
||||
}
|
||||
really_inline simdjson_result<bool> simdjson_result<dom::element>::get_bool() const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.get_bool();
|
||||
}
|
||||
|
||||
really_inline bool simdjson_result<dom::element>::is_array() const noexcept {
|
||||
return !error() && first.is_array();
|
||||
}
|
||||
really_inline bool simdjson_result<dom::element>::is_object() const noexcept {
|
||||
return !error() && first.is_object();
|
||||
}
|
||||
really_inline bool simdjson_result<dom::element>::is_string() const noexcept {
|
||||
return !error() && first.is_string();
|
||||
}
|
||||
really_inline bool simdjson_result<dom::element>::is_int64() const noexcept {
|
||||
return !error() && first.is_int64();
|
||||
}
|
||||
really_inline bool simdjson_result<dom::element>::is_uint64() const noexcept {
|
||||
return !error() && first.is_uint64();
|
||||
}
|
||||
really_inline bool simdjson_result<dom::element>::is_double() const noexcept {
|
||||
return !error() && first.is_double();
|
||||
}
|
||||
really_inline bool simdjson_result<dom::element>::is_bool() const noexcept {
|
||||
return !error() && first.is_bool();
|
||||
}
|
||||
|
||||
really_inline bool simdjson_result<dom::element>::is_null() const noexcept {
|
||||
return !error() && first.is_null();
|
||||
}
|
||||
|
||||
really_inline simdjson_result<dom::element> simdjson_result<dom::element>::operator[](const std::string_view &key) const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first[key];
|
||||
}
|
||||
really_inline simdjson_result<dom::element> simdjson_result<dom::element>::operator[](const char *key) const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first[key];
|
||||
}
|
||||
really_inline simdjson_result<dom::element> simdjson_result<dom::element>::at(const std::string_view &json_pointer) const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.at(json_pointer);
|
||||
}
|
||||
really_inline simdjson_result<dom::element> simdjson_result<dom::element>::at(size_t index) const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.at(index);
|
||||
}
|
||||
really_inline simdjson_result<dom::element> simdjson_result<dom::element>::at_key(const std::string_view &key) const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.at_key(key);
|
||||
}
|
||||
really_inline simdjson_result<dom::element> simdjson_result<dom::element>::at_key_case_insensitive(const std::string_view &key) const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.at_key_case_insensitive(key);
|
||||
}
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
|
||||
really_inline simdjson_result<dom::element>::operator bool() const noexcept(false) {
|
||||
return get<bool>();
|
||||
}
|
||||
really_inline simdjson_result<dom::element>::operator const char *() const noexcept(false) {
|
||||
return get<const char *>();
|
||||
}
|
||||
really_inline simdjson_result<dom::element>::operator std::string_view() const noexcept(false) {
|
||||
return get<std::string_view>();
|
||||
}
|
||||
really_inline simdjson_result<dom::element>::operator uint64_t() const noexcept(false) {
|
||||
return get<uint64_t>();
|
||||
}
|
||||
really_inline simdjson_result<dom::element>::operator int64_t() const noexcept(false) {
|
||||
return get<int64_t>();
|
||||
}
|
||||
really_inline simdjson_result<dom::element>::operator double() const noexcept(false) {
|
||||
return get<double>();
|
||||
}
|
||||
really_inline simdjson_result<dom::element>::operator dom::array() const noexcept(false) {
|
||||
return get<dom::array>();
|
||||
}
|
||||
really_inline simdjson_result<dom::element>::operator dom::object() const noexcept(false) {
|
||||
return get<dom::object>();
|
||||
}
|
||||
|
||||
really_inline dom::array::iterator simdjson_result<dom::element>::begin() const noexcept(false) {
|
||||
if (error()) { throw simdjson_error(error()); }
|
||||
return first.begin();
|
||||
}
|
||||
really_inline dom::array::iterator simdjson_result<dom::element>::end() const noexcept(false) {
|
||||
if (error()) { throw simdjson_error(error()); }
|
||||
return first.end();
|
||||
}
|
||||
|
||||
#endif // SIMDJSON_EXCEPTIONS
|
||||
|
||||
namespace dom {
|
||||
|
||||
//
|
||||
// element inline implementation
|
||||
//
|
||||
really_inline element::element() noexcept : tape{} {}
|
||||
really_inline element::element(const internal::tape_ref &_tape) noexcept : tape{_tape} { }
|
||||
|
||||
inline element_type element::type() const noexcept {
|
||||
auto tape_type = tape.tape_ref_type();
|
||||
return tape_type == internal::tape_type::FALSE_VALUE ? element_type::BOOL : static_cast<element_type>(tape_type);
|
||||
}
|
||||
|
||||
inline simdjson_result<bool> element::get_bool() const noexcept {
|
||||
if(tape.is_true()) {
|
||||
return true;
|
||||
} else if(tape.is_false()) {
|
||||
return false;
|
||||
}
|
||||
return INCORRECT_TYPE;
|
||||
}
|
||||
inline simdjson_result<const char *> element::get_c_str() const noexcept {
|
||||
switch (tape.tape_ref_type()) {
|
||||
case internal::tape_type::STRING: {
|
||||
return tape.get_c_str();
|
||||
}
|
||||
default:
|
||||
return INCORRECT_TYPE;
|
||||
}
|
||||
}
|
||||
inline simdjson_result<size_t> element::get_string_length() const noexcept {
|
||||
switch (tape.tape_ref_type()) {
|
||||
case internal::tape_type::STRING: {
|
||||
return tape.get_string_length();
|
||||
}
|
||||
default:
|
||||
return INCORRECT_TYPE;
|
||||
}
|
||||
}
|
||||
inline simdjson_result<std::string_view> element::get_string() const noexcept {
|
||||
switch (tape.tape_ref_type()) {
|
||||
case internal::tape_type::STRING:
|
||||
return tape.get_string_view();
|
||||
default:
|
||||
return INCORRECT_TYPE;
|
||||
}
|
||||
}
|
||||
inline simdjson_result<uint64_t> element::get_uint64() const noexcept {
|
||||
if(unlikely(!tape.is_uint64())) { // branch rarely taken
|
||||
if(tape.is_int64()) {
|
||||
int64_t result = tape.next_tape_value<int64_t>();
|
||||
if (result < 0) {
|
||||
return NUMBER_OUT_OF_RANGE;
|
||||
}
|
||||
return uint64_t(result);
|
||||
}
|
||||
return INCORRECT_TYPE;
|
||||
}
|
||||
return tape.next_tape_value<int64_t>();
|
||||
}
|
||||
inline simdjson_result<int64_t> element::get_int64() const noexcept {
|
||||
if(unlikely(!tape.is_int64())) { // branch rarely taken
|
||||
if(tape.is_uint64()) {
|
||||
uint64_t result = tape.next_tape_value<uint64_t>();
|
||||
// Wrapping max in parens to handle Windows issue: https://stackoverflow.com/questions/11544073/how-do-i-deal-with-the-max-macro-in-windows-h-colliding-with-max-in-std
|
||||
if (result > uint64_t((std::numeric_limits<int64_t>::max)())) {
|
||||
return NUMBER_OUT_OF_RANGE;
|
||||
}
|
||||
return static_cast<int64_t>(result);
|
||||
}
|
||||
return INCORRECT_TYPE;
|
||||
}
|
||||
return tape.next_tape_value<int64_t>();
|
||||
}
|
||||
inline simdjson_result<double> element::get_double() const noexcept {
|
||||
// Performance considerations:
|
||||
// 1. Querying tape_ref_type() implies doing a shift, it is fast to just do a straight
|
||||
// comparison.
|
||||
// 2. Using a switch-case relies on the compiler guessing what kind of code generation
|
||||
// we want... But the compiler cannot know that we expect the type to be "double"
|
||||
// most of the time.
|
||||
// We can expect get<double> to refer to a double type almost all the time.
|
||||
// It is important to craft the code accordingly so that the compiler can use this
|
||||
// information. (This could also be solved with profile-guided optimization.)
|
||||
if(unlikely(!tape.is_double())) { // branch rarely taken
|
||||
if(tape.is_uint64()) {
|
||||
return double(tape.next_tape_value<uint64_t>());
|
||||
} else if(tape.is_int64()) {
|
||||
return double(tape.next_tape_value<int64_t>());
|
||||
}
|
||||
return INCORRECT_TYPE;
|
||||
}
|
||||
// this is common:
|
||||
return tape.next_tape_value<double>();
|
||||
}
|
||||
inline simdjson_result<array> element::get_array() const noexcept {
|
||||
switch (tape.tape_ref_type()) {
|
||||
case internal::tape_type::START_ARRAY:
|
||||
return array(tape);
|
||||
default:
|
||||
return INCORRECT_TYPE;
|
||||
}
|
||||
}
|
||||
inline simdjson_result<object> element::get_object() const noexcept {
|
||||
switch (tape.tape_ref_type()) {
|
||||
case internal::tape_type::START_OBJECT:
|
||||
return object(tape);
|
||||
default:
|
||||
return INCORRECT_TYPE;
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
WARN_UNUSED really_inline error_code element::get(T &value) const noexcept {
|
||||
return get<T>().get(value);
|
||||
}
|
||||
// An element-specific version prevents recursion with simdjson_result::get<element>(value)
|
||||
template<>
|
||||
WARN_UNUSED really_inline error_code element::get<element>(element &value) const noexcept {
|
||||
value = element(tape);
|
||||
return SUCCESS;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
really_inline bool element::is() const noexcept {
|
||||
auto result = get<T>();
|
||||
return !result.error();
|
||||
}
|
||||
|
||||
template<> inline simdjson_result<array> element::get<array>() const noexcept { return get_array(); }
|
||||
template<> inline simdjson_result<object> element::get<object>() const noexcept { return get_object(); }
|
||||
template<> inline simdjson_result<const char *> element::get<const char *>() const noexcept { return get_c_str(); }
|
||||
template<> inline simdjson_result<std::string_view> element::get<std::string_view>() const noexcept { return get_string(); }
|
||||
template<> inline simdjson_result<int64_t> element::get<int64_t>() const noexcept { return get_int64(); }
|
||||
template<> inline simdjson_result<uint64_t> element::get<uint64_t>() const noexcept { return get_uint64(); }
|
||||
template<> inline simdjson_result<double> element::get<double>() const noexcept { return get_double(); }
|
||||
template<> inline simdjson_result<bool> element::get<bool>() const noexcept { return get_bool(); }
|
||||
|
||||
inline bool element::is_array() const noexcept { return is<array>(); }
|
||||
inline bool element::is_object() const noexcept { return is<object>(); }
|
||||
inline bool element::is_string() const noexcept { return is<std::string_view>(); }
|
||||
inline bool element::is_int64() const noexcept { return is<int64_t>(); }
|
||||
inline bool element::is_uint64() const noexcept { return is<uint64_t>(); }
|
||||
inline bool element::is_double() const noexcept { return is<double>(); }
|
||||
inline bool element::is_bool() const noexcept { return is<bool>(); }
|
||||
|
||||
inline bool element::is_null() const noexcept {
|
||||
return tape.is_null_on_tape();
|
||||
}
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
|
||||
inline element::operator bool() const noexcept(false) { return get<bool>(); }
|
||||
inline element::operator const char*() const noexcept(false) { return get<const char *>(); }
|
||||
inline element::operator std::string_view() const noexcept(false) { return get<std::string_view>(); }
|
||||
inline element::operator uint64_t() const noexcept(false) { return get<uint64_t>(); }
|
||||
inline element::operator int64_t() const noexcept(false) { return get<int64_t>(); }
|
||||
inline element::operator double() const noexcept(false) { return get<double>(); }
|
||||
inline element::operator array() const noexcept(false) { return get<array>(); }
|
||||
inline element::operator object() const noexcept(false) { return get<object>(); }
|
||||
|
||||
inline array::iterator element::begin() const noexcept(false) {
|
||||
return get<array>().begin();
|
||||
}
|
||||
inline array::iterator element::end() const noexcept(false) {
|
||||
return get<array>().end();
|
||||
}
|
||||
|
||||
#endif // SIMDJSON_EXCEPTIONS
|
||||
|
||||
inline simdjson_result<element> element::operator[](const std::string_view &key) const noexcept {
|
||||
return at_key(key);
|
||||
}
|
||||
inline simdjson_result<element> element::operator[](const char *key) const noexcept {
|
||||
return at_key(key);
|
||||
}
|
||||
inline simdjson_result<element> element::at(const std::string_view &json_pointer) const noexcept {
|
||||
switch (tape.tape_ref_type()) {
|
||||
case internal::tape_type::START_OBJECT:
|
||||
return object(tape).at(json_pointer);
|
||||
case internal::tape_type::START_ARRAY:
|
||||
return array(tape).at(json_pointer);
|
||||
default:
|
||||
return INCORRECT_TYPE;
|
||||
}
|
||||
}
|
||||
inline simdjson_result<element> element::at(size_t index) const noexcept {
|
||||
return get<array>().at(index);
|
||||
}
|
||||
inline simdjson_result<element> element::at_key(const std::string_view &key) const noexcept {
|
||||
return get<object>().at_key(key);
|
||||
}
|
||||
inline simdjson_result<element> element::at_key_case_insensitive(const std::string_view &key) const noexcept {
|
||||
return get<object>().at_key_case_insensitive(key);
|
||||
}
|
||||
|
||||
inline bool element::dump_raw_tape(std::ostream &out) const noexcept {
|
||||
return tape.doc->dump_raw_tape(out);
|
||||
}
|
||||
|
||||
inline std::ostream& operator<<(std::ostream& out, const element &value) {
|
||||
return out << minify<element>(value);
|
||||
}
|
||||
|
||||
inline std::ostream& operator<<(std::ostream& out, element_type type) {
|
||||
switch (type) {
|
||||
case element_type::ARRAY:
|
||||
return out << "array";
|
||||
case element_type::OBJECT:
|
||||
return out << "object";
|
||||
case element_type::INT64:
|
||||
return out << "int64_t";
|
||||
case element_type::UINT64:
|
||||
return out << "uint64_t";
|
||||
case element_type::DOUBLE:
|
||||
return out << "double";
|
||||
case element_type::STRING:
|
||||
return out << "string";
|
||||
case element_type::BOOL:
|
||||
return out << "bool";
|
||||
case element_type::NULL_VALUE:
|
||||
return out << "null";
|
||||
default:
|
||||
return out << "unexpected content!!!"; // abort() usage is forbidden in the library
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace dom
|
||||
|
||||
template<>
|
||||
inline std::ostream& minifier<dom::element>::print(std::ostream& out) {
|
||||
using tape_type=internal::tape_type;
|
||||
size_t depth = 0;
|
||||
constexpr size_t MAX_DEPTH = 16;
|
||||
bool is_object[MAX_DEPTH];
|
||||
is_object[0] = false;
|
||||
bool after_value = false;
|
||||
|
||||
internal::tape_ref iter(value.tape);
|
||||
do {
|
||||
// print commas after each value
|
||||
if (after_value) {
|
||||
out << ",";
|
||||
}
|
||||
// If we are in an object, print the next key and :, and skip to the next value.
|
||||
if (is_object[depth]) {
|
||||
out << '"' << internal::escape_json_string(iter.get_string_view()) << "\":";
|
||||
iter.json_index++;
|
||||
}
|
||||
switch (iter.tape_ref_type()) {
|
||||
|
||||
// Arrays
|
||||
case tape_type::START_ARRAY: {
|
||||
// If we're too deep, we need to recurse to go deeper.
|
||||
depth++;
|
||||
if (unlikely(depth >= MAX_DEPTH)) {
|
||||
out << minify<dom::array>(dom::array(iter));
|
||||
iter.json_index = iter.matching_brace_index() - 1; // Jump to the ]
|
||||
depth--;
|
||||
break;
|
||||
}
|
||||
|
||||
// Output start [
|
||||
out << '[';
|
||||
iter.json_index++;
|
||||
|
||||
// Handle empty [] (we don't want to come back around and print commas)
|
||||
if (iter.tape_ref_type() == tape_type::END_ARRAY) {
|
||||
out << ']';
|
||||
depth--;
|
||||
break;
|
||||
}
|
||||
|
||||
is_object[depth] = false;
|
||||
after_value = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Objects
|
||||
case tape_type::START_OBJECT: {
|
||||
// If we're too deep, we need to recurse to go deeper.
|
||||
depth++;
|
||||
if (unlikely(depth >= MAX_DEPTH)) {
|
||||
out << minify<dom::object>(dom::object(iter));
|
||||
iter.json_index = iter.matching_brace_index() - 1; // Jump to the }
|
||||
depth--;
|
||||
break;
|
||||
}
|
||||
|
||||
// Output start {
|
||||
out << '{';
|
||||
iter.json_index++;
|
||||
|
||||
// Handle empty {} (we don't want to come back around and print commas)
|
||||
if (iter.tape_ref_type() == tape_type::END_OBJECT) {
|
||||
out << '}';
|
||||
depth--;
|
||||
break;
|
||||
}
|
||||
|
||||
is_object[depth] = true;
|
||||
after_value = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Scalars
|
||||
case tape_type::STRING:
|
||||
out << '"' << internal::escape_json_string(iter.get_string_view()) << '"';
|
||||
break;
|
||||
case tape_type::INT64:
|
||||
out << iter.next_tape_value<int64_t>();
|
||||
iter.json_index++; // numbers take up 2 spots, so we need to increment extra
|
||||
break;
|
||||
case tape_type::UINT64:
|
||||
out << iter.next_tape_value<uint64_t>();
|
||||
iter.json_index++; // numbers take up 2 spots, so we need to increment extra
|
||||
break;
|
||||
case tape_type::DOUBLE:
|
||||
out << iter.next_tape_value<double>();
|
||||
iter.json_index++; // numbers take up 2 spots, so we need to increment extra
|
||||
break;
|
||||
case tape_type::TRUE_VALUE:
|
||||
out << "true";
|
||||
break;
|
||||
case tape_type::FALSE_VALUE:
|
||||
out << "false";
|
||||
break;
|
||||
case tape_type::NULL_VALUE:
|
||||
out << "null";
|
||||
break;
|
||||
|
||||
// These are impossible
|
||||
case tape_type::END_ARRAY:
|
||||
case tape_type::END_OBJECT:
|
||||
case tape_type::ROOT:
|
||||
out << "unexpected content!!!"; // abort() usage is forbidden in the library
|
||||
}
|
||||
iter.json_index++;
|
||||
after_value = true;
|
||||
|
||||
// Handle multiple ends in a row
|
||||
while (depth != 0 && (iter.tape_ref_type() == tape_type::END_ARRAY || iter.tape_ref_type() == tape_type::END_OBJECT)) {
|
||||
out << char(iter.tape_ref_type());
|
||||
depth--;
|
||||
iter.json_index++;
|
||||
}
|
||||
|
||||
// Stop when we're at depth 0
|
||||
} while (depth != 0);
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
|
||||
template<>
|
||||
really_inline std::ostream& minifier<simdjson_result<dom::element>>::print(std::ostream& out) {
|
||||
if (value.error()) { throw simdjson_error(value.error()); }
|
||||
return out << minify<dom::element>(value.first);
|
||||
}
|
||||
|
||||
really_inline std::ostream& operator<<(std::ostream& out, const simdjson_result<dom::element> &value) noexcept(false) {
|
||||
return out << minify<simdjson_result<dom::element>>(value);
|
||||
}
|
||||
#endif
|
||||
|
||||
} // namespace simdjson
|
||||
|
||||
#endif // SIMDJSON_INLINE_ELEMENT_H
|
||||
@@ -1,46 +1,22 @@
|
||||
#ifndef SIMDJSON_INLINE_ERROR_H
|
||||
#define SIMDJSON_INLINE_ERROR_H
|
||||
|
||||
#include "simdjson/error.h"
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include "simdjson/error.h"
|
||||
|
||||
namespace simdjson::internal {
|
||||
namespace simdjson {
|
||||
namespace internal {
|
||||
// We store the error code so we can validate the error message is associated with the right code
|
||||
struct error_code_info {
|
||||
error_code code;
|
||||
std::string message;
|
||||
};
|
||||
// These MUST match the codes in error_code. We check this constraint in basictests.
|
||||
inline const error_code_info error_codes[] {
|
||||
{ SUCCESS, "No error" },
|
||||
{ SUCCESS_AND_HAS_MORE, "No error and buffer still has more data" },
|
||||
{ CAPACITY, "This parser can't support a document that big" },
|
||||
{ MEMALLOC, "Error allocating memory, we're most likely out of memory" },
|
||||
{ TAPE_ERROR, "Something went wrong while writing to the tape" },
|
||||
{ DEPTH_ERROR, "The JSON document was too deep (too many nested objects and arrays)" },
|
||||
{ STRING_ERROR, "Problem while parsing a string" },
|
||||
{ T_ATOM_ERROR, "Problem while parsing an atom starting with the letter 't'" },
|
||||
{ F_ATOM_ERROR, "Problem while parsing an atom starting with the letter 'f'" },
|
||||
{ N_ATOM_ERROR, "Problem while parsing an atom starting with the letter 'n'" },
|
||||
{ NUMBER_ERROR, "Problem while parsing a number" },
|
||||
{ UTF8_ERROR, "The input is not valid UTF-8" },
|
||||
{ UNINITIALIZED, "Uninitialized" },
|
||||
{ EMPTY, "Empty: no JSON found" },
|
||||
{ UNESCAPED_CHARS, "Within strings, some characters must be escaped, we found unescaped characters" },
|
||||
{ UNCLOSED_STRING, "A string is opened, but never closed." },
|
||||
{ UNSUPPORTED_ARCHITECTURE, "simdjson does not have an implementation supported by this CPU architecture (perhaps it's a non-SIMD CPU?)." },
|
||||
{ INCORRECT_TYPE, "The JSON element does not have the requested type." },
|
||||
{ NUMBER_OUT_OF_RANGE, "The JSON number is too large or too small to fit within the requested type." },
|
||||
{ INDEX_OUT_OF_BOUNDS, "Attempted to access an element of a JSON array that is beyond its length." },
|
||||
{ NO_SUCH_FIELD, "The JSON field referenced does not exist in this object." },
|
||||
{ IO_ERROR, "Error reading the file." },
|
||||
{ INVALID_JSON_POINTER, "Invalid JSON pointer syntax." },
|
||||
{ INVALID_URI_FRAGMENT, "Invalid URI fragment syntax." },
|
||||
{ UNEXPECTED_ERROR, "Unexpected error, consider reporting this problem as you may have found a bug in simdjson" }
|
||||
}; // error_messages[]
|
||||
} // namespace simdjson::internal
|
||||
extern SIMDJSON_DLLIMPORTEXPORT const error_code_info error_codes[];
|
||||
} // namespace internal
|
||||
|
||||
namespace simdjson {
|
||||
|
||||
inline const char *error_message(error_code error) noexcept {
|
||||
// If you're using error_code, we're trusting you got it from the enum.
|
||||
@@ -69,8 +45,17 @@ really_inline void simdjson_result_base<T>::tie(T &value, error_code &error) &&
|
||||
// on the clang compiler that comes with current macOS (Apple clang version 11.0.0),
|
||||
// tie(width, error) = size["w"].get<uint64_t>();
|
||||
// fails with "error: no viable overloaded '='""
|
||||
value = std::forward<simdjson_result_base<T>>(*this).first;
|
||||
error = this->second;
|
||||
if (!error) {
|
||||
value = std::forward<simdjson_result_base<T>>(*this).first;
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
WARN_UNUSED really_inline error_code simdjson_result_base<T>::get(T &value) && noexcept {
|
||||
error_code error;
|
||||
std::forward<simdjson_result_base<T>>(*this).tie(value, error);
|
||||
return error;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
@@ -84,13 +69,13 @@ template<typename T>
|
||||
really_inline T& simdjson_result_base<T>::value() noexcept(false) {
|
||||
if (error()) { throw simdjson_error(error()); }
|
||||
return this->first;
|
||||
};
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
really_inline T&& simdjson_result_base<T>::take_value() && noexcept(false) {
|
||||
if (error()) { throw simdjson_error(error()); }
|
||||
return std::forward<T>(this->first);
|
||||
};
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
really_inline simdjson_result_base<T>::operator T&&() && noexcept(false) {
|
||||
@@ -123,6 +108,11 @@ really_inline void simdjson_result<T>::tie(T &value, error_code &error) && noexc
|
||||
std::forward<internal::simdjson_result_base<T>>(*this).tie(value, error);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
WARN_UNUSED really_inline error_code simdjson_result<T>::get(T &value) && noexcept {
|
||||
return std::forward<internal::simdjson_result_base<T>>(*this).get(value);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
really_inline error_code simdjson_result<T>::error() const noexcept {
|
||||
return internal::simdjson_result_base<T>::error();
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
#ifndef SIMDJSON_INLINE_OBJECT_H
|
||||
#define SIMDJSON_INLINE_OBJECT_H
|
||||
|
||||
#include "simdjson/dom/element.h"
|
||||
#include "simdjson/dom/object.h"
|
||||
#include "simdjson/portability.h"
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
namespace simdjson {
|
||||
|
||||
//
|
||||
// simdjson_result<dom::object> inline implementation
|
||||
//
|
||||
really_inline simdjson_result<dom::object>::simdjson_result() noexcept
|
||||
: internal::simdjson_result_base<dom::object>() {}
|
||||
really_inline simdjson_result<dom::object>::simdjson_result(dom::object value) noexcept
|
||||
: internal::simdjson_result_base<dom::object>(std::forward<dom::object>(value)) {}
|
||||
really_inline simdjson_result<dom::object>::simdjson_result(error_code error) noexcept
|
||||
: internal::simdjson_result_base<dom::object>(error) {}
|
||||
|
||||
inline simdjson_result<dom::element> simdjson_result<dom::object>::operator[](const std::string_view &key) const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first[key];
|
||||
}
|
||||
inline simdjson_result<dom::element> simdjson_result<dom::object>::operator[](const char *key) const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first[key];
|
||||
}
|
||||
inline simdjson_result<dom::element> simdjson_result<dom::object>::at(const std::string_view &json_pointer) const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.at(json_pointer);
|
||||
}
|
||||
inline simdjson_result<dom::element> simdjson_result<dom::object>::at_key(const std::string_view &key) const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.at_key(key);
|
||||
}
|
||||
inline simdjson_result<dom::element> simdjson_result<dom::object>::at_key_case_insensitive(const std::string_view &key) const noexcept {
|
||||
if (error()) { return error(); }
|
||||
return first.at_key_case_insensitive(key);
|
||||
}
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
|
||||
inline dom::object::iterator simdjson_result<dom::object>::begin() const noexcept(false) {
|
||||
if (error()) { throw simdjson_error(error()); }
|
||||
return first.begin();
|
||||
}
|
||||
inline dom::object::iterator simdjson_result<dom::object>::end() const noexcept(false) {
|
||||
if (error()) { throw simdjson_error(error()); }
|
||||
return first.end();
|
||||
}
|
||||
inline size_t simdjson_result<dom::object>::size() const noexcept(false) {
|
||||
if (error()) { throw simdjson_error(error()); }
|
||||
return first.size();
|
||||
}
|
||||
|
||||
#endif // SIMDJSON_EXCEPTIONS
|
||||
|
||||
namespace dom {
|
||||
|
||||
//
|
||||
// object inline implementation
|
||||
//
|
||||
really_inline object::object() noexcept : tape{} {}
|
||||
really_inline object::object(const internal::tape_ref &_tape) noexcept : tape{_tape} { }
|
||||
inline object::iterator object::begin() const noexcept {
|
||||
return internal::tape_ref(tape.doc, tape.json_index + 1);
|
||||
}
|
||||
inline object::iterator object::end() const noexcept {
|
||||
return internal::tape_ref(tape.doc, tape.after_element() - 1);
|
||||
}
|
||||
inline size_t object::size() const noexcept {
|
||||
return tape.scope_count();
|
||||
}
|
||||
|
||||
inline simdjson_result<element> object::operator[](const std::string_view &key) const noexcept {
|
||||
return at_key(key);
|
||||
}
|
||||
inline simdjson_result<element> object::operator[](const char *key) const noexcept {
|
||||
return at_key(key);
|
||||
}
|
||||
inline simdjson_result<element> object::at(const std::string_view &json_pointer) const noexcept {
|
||||
size_t slash = json_pointer.find('/');
|
||||
std::string_view key = json_pointer.substr(0, slash);
|
||||
|
||||
// Grab the child with the given key
|
||||
simdjson_result<element> child;
|
||||
|
||||
// If there is an escape character in the key, unescape it and then get the child.
|
||||
size_t escape = key.find('~');
|
||||
if (escape != std::string_view::npos) {
|
||||
// Unescape the key
|
||||
std::string unescaped(key);
|
||||
do {
|
||||
switch (unescaped[escape+1]) {
|
||||
case '0':
|
||||
unescaped.replace(escape, 2, "~");
|
||||
break;
|
||||
case '1':
|
||||
unescaped.replace(escape, 2, "/");
|
||||
break;
|
||||
default:
|
||||
return INVALID_JSON_POINTER; // "Unexpected ~ escape character in JSON pointer");
|
||||
}
|
||||
escape = unescaped.find('~', escape+1);
|
||||
} while (escape != std::string::npos);
|
||||
child = at_key(unescaped);
|
||||
} else {
|
||||
child = at_key(key);
|
||||
}
|
||||
|
||||
// If there is a /, we have to recurse and look up more of the path
|
||||
if (slash != std::string_view::npos) {
|
||||
child = child.at(json_pointer.substr(slash+1));
|
||||
}
|
||||
|
||||
return child;
|
||||
}
|
||||
inline simdjson_result<element> object::at_key(const std::string_view &key) const noexcept {
|
||||
iterator end_field = end();
|
||||
for (iterator field = begin(); field != end_field; ++field) {
|
||||
if (field.key_equals(key)) {
|
||||
return field.value();
|
||||
}
|
||||
}
|
||||
return NO_SUCH_FIELD;
|
||||
}
|
||||
// In case you wonder why we need this, please see
|
||||
// https://github.com/simdjson/simdjson/issues/323
|
||||
// People do seek keys in a case-insensitive manner.
|
||||
inline simdjson_result<element> object::at_key_case_insensitive(const std::string_view &key) const noexcept {
|
||||
iterator end_field = end();
|
||||
for (iterator field = begin(); field != end_field; ++field) {
|
||||
if (field.key_equals_case_insensitive(key)) {
|
||||
return field.value();
|
||||
}
|
||||
}
|
||||
return NO_SUCH_FIELD;
|
||||
}
|
||||
|
||||
//
|
||||
// object::iterator inline implementation
|
||||
//
|
||||
really_inline object::iterator::iterator(const internal::tape_ref &_tape) noexcept : tape{_tape} { }
|
||||
inline const key_value_pair object::iterator::operator*() const noexcept {
|
||||
return key_value_pair(key(), value());
|
||||
}
|
||||
inline bool object::iterator::operator!=(const object::iterator& other) const noexcept {
|
||||
return tape.json_index != other.tape.json_index;
|
||||
}
|
||||
inline object::iterator& object::iterator::operator++() noexcept {
|
||||
tape.json_index++;
|
||||
tape.json_index = tape.after_element();
|
||||
return *this;
|
||||
}
|
||||
inline std::string_view object::iterator::key() const noexcept {
|
||||
return tape.get_string_view();
|
||||
}
|
||||
inline uint32_t object::iterator::key_length() const noexcept {
|
||||
return tape.get_string_length();
|
||||
}
|
||||
inline const char* object::iterator::key_c_str() const noexcept {
|
||||
return reinterpret_cast<const char *>(&tape.doc->string_buf[size_t(tape.tape_value()) + sizeof(uint32_t)]);
|
||||
}
|
||||
inline element object::iterator::value() const noexcept {
|
||||
return element(internal::tape_ref(tape.doc, tape.json_index + 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* Design notes:
|
||||
* Instead of constructing a string_view and then comparing it with a
|
||||
* user-provided strings, it is probably more performant to have dedicated
|
||||
* functions taking as a parameter the string we want to compare against
|
||||
* and return true when they are equal. That avoids the creation of a temporary
|
||||
* std::string_view. Though it is possible for the compiler to avoid entirely
|
||||
* any overhead due to string_view, relying too much on compiler magic is
|
||||
* problematic: compiler magic sometimes fail, and then what do you do?
|
||||
* Also, enticing users to rely on high-performance function is probably better
|
||||
* on the long run.
|
||||
*/
|
||||
|
||||
inline bool object::iterator::key_equals(const std::string_view & o) const noexcept {
|
||||
// We use the fact that the key length can be computed quickly
|
||||
// without access to the string buffer.
|
||||
const uint32_t len = key_length();
|
||||
if(o.size() == len) {
|
||||
// We avoid construction of a temporary string_view instance.
|
||||
return (memcmp(o.data(), key_c_str(), len) == 0);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
inline bool object::iterator::key_equals_case_insensitive(const std::string_view & o) const noexcept {
|
||||
// We use the fact that the key length can be computed quickly
|
||||
// without access to the string buffer.
|
||||
const uint32_t len = key_length();
|
||||
if(o.size() == len) {
|
||||
// See For case-insensitive string comparisons, avoid char-by-char functions
|
||||
// https://lemire.me/blog/2020/04/30/for-case-insensitive-string-comparisons-avoid-char-by-char-functions/
|
||||
// Note that it might be worth rolling our own strncasecmp function, with vectorization.
|
||||
return (simdjson_strncasecmp(o.data(), key_c_str(), len) == 0);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
//
|
||||
// key_value_pair inline implementation
|
||||
//
|
||||
inline key_value_pair::key_value_pair(const std::string_view &_key, element _value) noexcept :
|
||||
key(_key), value(_value) {}
|
||||
|
||||
inline std::ostream& operator<<(std::ostream& out, const object &value) {
|
||||
return out << minify<object>(value);
|
||||
}
|
||||
inline std::ostream& operator<<(std::ostream& out, const key_value_pair &value) {
|
||||
return out << minify<key_value_pair>(value);
|
||||
}
|
||||
|
||||
} // namespace dom
|
||||
|
||||
template<>
|
||||
inline std::ostream& minifier<dom::object>::print(std::ostream& out) {
|
||||
out << '{';
|
||||
auto pair = value.begin();
|
||||
auto end = value.end();
|
||||
if (pair != end) {
|
||||
out << minify<dom::key_value_pair>(*pair);
|
||||
for (++pair; pair != end; ++pair) {
|
||||
out << "," << minify<dom::key_value_pair>(*pair);
|
||||
}
|
||||
}
|
||||
return out << '}';
|
||||
}
|
||||
|
||||
template<>
|
||||
inline std::ostream& minifier<dom::key_value_pair>::print(std::ostream& out) {
|
||||
return out << '"' << internal::escape_json_string(value.key) << "\":" << value.value;
|
||||
}
|
||||
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
|
||||
template<>
|
||||
inline std::ostream& minifier<simdjson_result<dom::object>>::print(std::ostream& out) {
|
||||
if (value.error()) { throw simdjson_error(value.error()); }
|
||||
return out << minify<dom::object>(value.first);
|
||||
}
|
||||
|
||||
inline std::ostream& operator<<(std::ostream& out, const simdjson_result<dom::object> &value) noexcept(false) {
|
||||
return out << minify<simdjson_result<dom::object>>(value);
|
||||
}
|
||||
#endif // SIMDJSON_EXCEPTIONS
|
||||
|
||||
} // namespace simdjson
|
||||
|
||||
#endif // SIMDJSON_INLINE_OBJECT_H
|
||||
@@ -9,7 +9,8 @@
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace simdjson::internal {
|
||||
namespace simdjson {
|
||||
namespace internal {
|
||||
|
||||
// low-level function to allocate memory with padding so we can read past the
|
||||
// "length" bytes safely. if you must provide a pointer to some data, create it
|
||||
@@ -20,7 +21,12 @@ inline char *allocate_padded_buffer(size_t length) noexcept {
|
||||
// return (char *) malloc(length + SIMDJSON_PADDING);
|
||||
// However, we might as well align to cache lines...
|
||||
size_t totalpaddedlength = length + SIMDJSON_PADDING;
|
||||
#if defined(_MSC_VER) && _MSC_VER < 1910
|
||||
// For legacy Visual Studio 2015 since it does not have proper C++11 support
|
||||
char *padded_buffer = new[totalpaddedlength];
|
||||
#else
|
||||
char *padded_buffer = aligned_malloc_char(64, totalpaddedlength);
|
||||
#endif
|
||||
#ifndef NDEBUG
|
||||
if (padded_buffer == nullptr) {
|
||||
return nullptr;
|
||||
@@ -30,11 +36,10 @@ inline char *allocate_padded_buffer(size_t length) noexcept {
|
||||
return padded_buffer;
|
||||
} // allocate_padded_buffer()
|
||||
|
||||
} // namespace simdjson::internal
|
||||
} // namespace internal
|
||||
|
||||
namespace simdjson {
|
||||
|
||||
inline padded_string::padded_string() noexcept : viable_size(0), data_ptr(nullptr) {}
|
||||
inline padded_string::padded_string() noexcept {}
|
||||
inline padded_string::padded_string(size_t length) noexcept
|
||||
: viable_size(length), data_ptr(internal::allocate_padded_buffer(length)) {
|
||||
if (data_ptr != nullptr)
|
||||
@@ -102,7 +107,11 @@ inline padded_string::operator std::string_view() const { return std::string_vie
|
||||
|
||||
inline simdjson_result<padded_string> padded_string::load(const std::string &filename) noexcept {
|
||||
// Open the file
|
||||
SIMDJSON_PUSH_DISABLE_WARNINGS
|
||||
SIMDJSON_DISABLE_DEPRECATED_WARNING // Disable CRT_SECURE warning on MSVC: manually verified this is safe
|
||||
std::FILE *fp = std::fopen(filename.c_str(), "rb");
|
||||
SIMDJSON_POP_DISABLE_WARNINGS
|
||||
|
||||
if (fp == nullptr) {
|
||||
return IO_ERROR;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
#ifndef SIMDJSON_INLINE_PARSEDJSON_ITERATOR_H
|
||||
#define SIMDJSON_INLINE_PARSEDJSON_ITERATOR_H
|
||||
|
||||
#include "simdjson/parsedjson_iterator.h"
|
||||
#include "simdjson/dom/parsedjson_iterator.h"
|
||||
#include "simdjson/portability.h"
|
||||
#include <cstring>
|
||||
|
||||
namespace simdjson {
|
||||
|
||||
// VS2017 reports deprecated warnings when you define a deprecated class's methods.
|
||||
SIMDJSON_PUSH_DISABLE_WARNINGS
|
||||
SIMDJSON_DISABLE_DEPRECATED_WARNING
|
||||
|
||||
// Because of template weirdness, the actual class definition is inline in the document class
|
||||
|
||||
WARN_UNUSED bool dom::parser::Iterator::is_ok() const {
|
||||
@@ -54,7 +60,7 @@ bool dom::parser::Iterator::move_forward() {
|
||||
|
||||
location += 1;
|
||||
current_val = doc.tape[location];
|
||||
current_type = (current_val >> 56);
|
||||
current_type = uint8_t(current_val >> 56);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -62,7 +68,7 @@ void dom::parser::Iterator::move_to_value() {
|
||||
// assume that we are on a key, so move by 1.
|
||||
location += 1;
|
||||
current_val = doc.tape[location];
|
||||
current_type = (current_val >> 56);
|
||||
current_type = uint8_t(current_val >> 56);
|
||||
}
|
||||
|
||||
bool dom::parser::Iterator::move_to_key(const char *key) {
|
||||
@@ -139,14 +145,14 @@ bool dom::parser::Iterator::prev() {
|
||||
oldnpos = npos;
|
||||
if ((current_type == '[') || (current_type == '{')) {
|
||||
// we need to jump
|
||||
npos = (current_val & internal::JSON_VALUE_MASK);
|
||||
npos = uint32_t(current_val);
|
||||
} else {
|
||||
npos = npos + ((current_type == 'd' || current_type == 'l') ? 2 : 1);
|
||||
}
|
||||
} while (npos < target_location);
|
||||
location = oldnpos;
|
||||
current_val = doc.tape[location];
|
||||
current_type = current_val >> 56;
|
||||
current_type = uint8_t(current_val >> 56);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -159,7 +165,7 @@ bool dom::parser::Iterator::up() {
|
||||
depth--;
|
||||
location -= 1;
|
||||
current_val = doc.tape[location];
|
||||
current_type = (current_val >> 56);
|
||||
current_type = uint8_t(current_val >> 56);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -168,7 +174,7 @@ bool dom::parser::Iterator::down() {
|
||||
return false;
|
||||
}
|
||||
if ((current_type == '[') || (current_type == '{')) {
|
||||
size_t npos = (current_val & internal::JSON_VALUE_MASK);
|
||||
size_t npos = uint32_t(current_val);
|
||||
if (npos == location + 2) {
|
||||
return false; // we have an empty scope
|
||||
}
|
||||
@@ -178,7 +184,7 @@ bool dom::parser::Iterator::down() {
|
||||
depth_index[depth].start_of_scope = location;
|
||||
depth_index[depth].scope_type = current_type;
|
||||
current_val = doc.tape[location];
|
||||
current_type = (current_val >> 56);
|
||||
current_type = uint8_t(current_val >> 56);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -187,19 +193,19 @@ bool dom::parser::Iterator::down() {
|
||||
void dom::parser::Iterator::to_start_scope() {
|
||||
location = depth_index[depth].start_of_scope;
|
||||
current_val = doc.tape[location];
|
||||
current_type = (current_val >> 56);
|
||||
current_type = uint8_t(current_val >> 56);
|
||||
}
|
||||
|
||||
bool dom::parser::Iterator::next() {
|
||||
size_t npos;
|
||||
if ((current_type == '[') || (current_type == '{')) {
|
||||
// we need to jump
|
||||
npos = (current_val & internal::JSON_VALUE_MASK);
|
||||
npos = uint32_t(current_val);
|
||||
} else {
|
||||
npos = location + (is_number() ? 2 : 1);
|
||||
}
|
||||
uint64_t next_val = doc.tape[npos];
|
||||
uint8_t next_type = (next_val >> 56);
|
||||
uint8_t next_type = uint8_t(next_val >> 56);
|
||||
if ((next_type == ']') || (next_type == '}')) {
|
||||
return false; // we reached the end of the scope
|
||||
}
|
||||
@@ -208,39 +214,43 @@ bool dom::parser::Iterator::next() {
|
||||
current_type = next_type;
|
||||
return true;
|
||||
}
|
||||
|
||||
dom::parser::Iterator::Iterator(const dom::parser &pj) noexcept(false)
|
||||
: doc(pj.doc), depth(0), location(0), tape_length(0) {
|
||||
: doc(pj.doc)
|
||||
{
|
||||
#if SIMDJSON_EXCEPTIONS
|
||||
if (!pj.valid) { throw simdjson_error(pj.error); }
|
||||
#else
|
||||
if (!pj.valid) { abort(); }
|
||||
if (!pj.valid) { return; } // abort() usage is forbidden in the library
|
||||
#endif
|
||||
|
||||
max_depth = pj.max_depth();
|
||||
depth_index = new scopeindex_t[max_depth + 1];
|
||||
depth_index[0].start_of_scope = location;
|
||||
current_val = doc.tape[location++];
|
||||
current_type = (current_val >> 56);
|
||||
current_type = uint8_t(current_val >> 56);
|
||||
depth_index[0].scope_type = current_type;
|
||||
tape_length = current_val & internal::JSON_VALUE_MASK;
|
||||
tape_length = size_t(current_val & internal::JSON_VALUE_MASK);
|
||||
if (location < tape_length) {
|
||||
// If we make it here, then depth_capacity must >=2, but the compiler
|
||||
// may not know this.
|
||||
current_val = doc.tape[location];
|
||||
current_type = (current_val >> 56);
|
||||
current_type = uint8_t(current_val >> 56);
|
||||
depth++;
|
||||
assert(depth < max_depth);
|
||||
depth_index[depth].start_of_scope = location;
|
||||
depth_index[depth].scope_type = current_type;
|
||||
}
|
||||
}
|
||||
|
||||
dom::parser::Iterator::Iterator(
|
||||
const dom::parser::Iterator &o) noexcept
|
||||
: doc(o.doc), max_depth(o.depth), depth(o.depth), location(o.location),
|
||||
tape_length(o.tape_length), current_type(o.current_type),
|
||||
current_val(o.current_val) {
|
||||
: doc(o.doc),
|
||||
max_depth(o.depth),
|
||||
depth(o.depth),
|
||||
location(o.location),
|
||||
tape_length(o.tape_length),
|
||||
current_type(o.current_type),
|
||||
current_val(o.current_val)
|
||||
{
|
||||
depth_index = new scopeindex_t[max_depth+1];
|
||||
memcpy(depth_index, o.depth_index, (depth + 1) * sizeof(depth_index[0]));
|
||||
}
|
||||
@@ -287,7 +297,7 @@ bool dom::parser::Iterator::print(std::ostream &os, bool escape_strings) const {
|
||||
case '}': // we end an object
|
||||
case '[': // we start an array
|
||||
case ']': // we end an array
|
||||
os << static_cast<char>(current_type);
|
||||
os << char(current_type);
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
@@ -314,7 +324,7 @@ bool dom::parser::Iterator::move_to(const char *pointer,
|
||||
new_pointer[new_length] = '\\';
|
||||
new_length++;
|
||||
}
|
||||
new_pointer[new_length] = fragment;
|
||||
new_pointer[new_length] = char(fragment);
|
||||
i += 3;
|
||||
#if __cpp_exceptions
|
||||
} catch (std::invalid_argument &) {
|
||||
@@ -427,7 +437,7 @@ bool dom::parser::Iterator::relative_move_to(const char *pointer,
|
||||
|
||||
bool found = false;
|
||||
if (is_object()) {
|
||||
if (move_to_key(key_or_index.c_str(), key_or_index.length())) {
|
||||
if (move_to_key(key_or_index.c_str(), uint32_t(key_or_index.length()))) {
|
||||
found = relative_move_to(pointer + offset, length - offset);
|
||||
}
|
||||
} else if (is_array()) {
|
||||
@@ -439,14 +449,14 @@ bool dom::parser::Iterator::relative_move_to(const char *pointer,
|
||||
size_t npos;
|
||||
if ((current_type == '[') || (current_type == '{')) {
|
||||
// we need to jump
|
||||
npos = (current_val & internal::JSON_VALUE_MASK);
|
||||
npos = uint32_t(current_val);
|
||||
} else {
|
||||
npos =
|
||||
location + ((current_type == 'd' || current_type == 'l') ? 2 : 1);
|
||||
}
|
||||
location = npos;
|
||||
current_val = doc.tape[npos];
|
||||
current_type = (current_val >> 56);
|
||||
current_type = uint8_t(current_val >> 56);
|
||||
return true; // how could it fail ?
|
||||
}
|
||||
} else { // regular numeric index
|
||||
@@ -469,6 +479,8 @@ bool dom::parser::Iterator::relative_move_to(const char *pointer,
|
||||
return found;
|
||||
}
|
||||
|
||||
SIMDJSON_POP_DISABLE_WARNINGS
|
||||
|
||||
} // namespace simdjson
|
||||
|
||||
#endif // SIMDJSON_INLINE_PARSEDJSON_ITERATOR_H
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
#ifndef SIMDJSON_INLINE_PARSER_H
|
||||
#define SIMDJSON_INLINE_PARSER_H
|
||||
|
||||
#include "simdjson/dom/document_stream.h"
|
||||
#include "simdjson/dom/parser.h"
|
||||
#include "simdjson/implementation.h"
|
||||
#include "simdjson/internal/jsonformatutils.h"
|
||||
#include "simdjson/portability.h"
|
||||
#include <cstdio>
|
||||
#include <climits>
|
||||
|
||||
namespace simdjson {
|
||||
namespace dom {
|
||||
|
||||
//
|
||||
// parser inline implementation
|
||||
//
|
||||
#if defined(_MSC_VER) && _MSC_VER < 1910
|
||||
// older versions of Visual Studio lack proper support for unique_ptr.
|
||||
really_inline parser::parser(size_t max_capacity) noexcept
|
||||
: _max_capacity{max_capacity},
|
||||
loaded_bytes(nullptr) {
|
||||
}
|
||||
#else
|
||||
really_inline parser::parser(size_t max_capacity) noexcept
|
||||
: _max_capacity{max_capacity},
|
||||
loaded_bytes(nullptr, &aligned_free_char) {
|
||||
}
|
||||
#endif
|
||||
really_inline parser::parser(parser &&other) noexcept = default;
|
||||
really_inline parser &parser::operator=(parser &&other) noexcept = default;
|
||||
|
||||
inline bool parser::is_valid() const noexcept { return valid; }
|
||||
inline int parser::get_error_code() const noexcept { return error; }
|
||||
inline std::string parser::get_error_message() const noexcept { return error_message(error); }
|
||||
inline bool parser::print_json(std::ostream &os) const noexcept {
|
||||
if (!valid) { return false; }
|
||||
os << doc.root();
|
||||
return true;
|
||||
}
|
||||
inline bool parser::dump_raw_tape(std::ostream &os) const noexcept {
|
||||
return valid ? doc.dump_raw_tape(os) : false;
|
||||
}
|
||||
|
||||
inline simdjson_result<size_t> parser::read_file(const std::string &path) noexcept {
|
||||
// Open the file
|
||||
SIMDJSON_PUSH_DISABLE_WARNINGS
|
||||
SIMDJSON_DISABLE_DEPRECATED_WARNING // Disable CRT_SECURE warning on MSVC: manually verified this is safe
|
||||
std::FILE *fp = std::fopen(path.c_str(), "rb");
|
||||
SIMDJSON_POP_DISABLE_WARNINGS
|
||||
|
||||
if (fp == nullptr) {
|
||||
return IO_ERROR;
|
||||
}
|
||||
|
||||
// Get the file size
|
||||
if(std::fseek(fp, 0, SEEK_END) < 0) {
|
||||
std::fclose(fp);
|
||||
return IO_ERROR;
|
||||
}
|
||||
long len = std::ftell(fp);
|
||||
if((len < 0) || (len == LONG_MAX)) {
|
||||
std::fclose(fp);
|
||||
return IO_ERROR;
|
||||
}
|
||||
|
||||
// Make sure we have enough capacity to load the file
|
||||
if (_loaded_bytes_capacity < size_t(len)) {
|
||||
loaded_bytes.reset( internal::allocate_padded_buffer(len) );
|
||||
if (!loaded_bytes) {
|
||||
std::fclose(fp);
|
||||
return MEMALLOC;
|
||||
}
|
||||
_loaded_bytes_capacity = len;
|
||||
}
|
||||
|
||||
// Read the string
|
||||
std::rewind(fp);
|
||||
size_t bytes_read = std::fread(loaded_bytes.get(), 1, len, fp);
|
||||
if (std::fclose(fp) != 0 || bytes_read != size_t(len)) {
|
||||
return IO_ERROR;
|
||||
}
|
||||
|
||||
return bytes_read;
|
||||
}
|
||||
|
||||
inline simdjson_result<element> parser::load(const std::string &path) & noexcept {
|
||||
size_t len;
|
||||
auto _error = read_file(path).get(len);
|
||||
if (_error) { return _error; }
|
||||
return parse(loaded_bytes.get(), len, false);
|
||||
}
|
||||
|
||||
inline simdjson_result<document_stream> parser::load_many(const std::string &path, size_t batch_size) noexcept {
|
||||
size_t len;
|
||||
auto _error = read_file(path).get(len);
|
||||
if (_error) { return _error; }
|
||||
return document_stream(*this, (const uint8_t*)loaded_bytes.get(), len, batch_size);
|
||||
}
|
||||
|
||||
inline simdjson_result<element> parser::parse(const uint8_t *buf, size_t len, bool realloc_if_needed) & noexcept {
|
||||
error_code _error = ensure_capacity(len);
|
||||
if (_error) { return _error; }
|
||||
|
||||
if (realloc_if_needed) {
|
||||
const uint8_t *tmp_buf = buf;
|
||||
buf = (uint8_t *)internal::allocate_padded_buffer(len);
|
||||
if (buf == nullptr)
|
||||
return MEMALLOC;
|
||||
memcpy((void *)buf, tmp_buf, len);
|
||||
}
|
||||
|
||||
_error = implementation->parse(buf, len, doc);
|
||||
if (realloc_if_needed) {
|
||||
aligned_free((void *)buf); // must free before we exit
|
||||
}
|
||||
if (_error) { return _error; }
|
||||
|
||||
return doc.root();
|
||||
}
|
||||
really_inline simdjson_result<element> parser::parse(const char *buf, size_t len, bool realloc_if_needed) & noexcept {
|
||||
return parse((const uint8_t *)buf, len, realloc_if_needed);
|
||||
}
|
||||
really_inline simdjson_result<element> parser::parse(const std::string &s) & noexcept {
|
||||
return parse(s.data(), s.length(), s.capacity() - s.length() < SIMDJSON_PADDING);
|
||||
}
|
||||
really_inline simdjson_result<element> parser::parse(const padded_string &s) & noexcept {
|
||||
return parse(s.data(), s.length(), false);
|
||||
}
|
||||
|
||||
inline simdjson_result<document_stream> parser::parse_many(const uint8_t *buf, size_t len, size_t batch_size) noexcept {
|
||||
return document_stream(*this, buf, len, batch_size);
|
||||
}
|
||||
inline simdjson_result<document_stream> parser::parse_many(const char *buf, size_t len, size_t batch_size) noexcept {
|
||||
return parse_many((const uint8_t *)buf, len, batch_size);
|
||||
}
|
||||
inline simdjson_result<document_stream> parser::parse_many(const std::string &s, size_t batch_size) noexcept {
|
||||
return parse_many(s.data(), s.length(), batch_size);
|
||||
}
|
||||
inline simdjson_result<document_stream> parser::parse_many(const padded_string &s, size_t batch_size) noexcept {
|
||||
return parse_many(s.data(), s.length(), batch_size);
|
||||
}
|
||||
|
||||
really_inline size_t parser::capacity() const noexcept {
|
||||
return implementation ? implementation->capacity() : 0;
|
||||
}
|
||||
really_inline size_t parser::max_capacity() const noexcept {
|
||||
return _max_capacity;
|
||||
}
|
||||
really_inline size_t parser::max_depth() const noexcept {
|
||||
return implementation ? implementation->max_depth() : DEFAULT_MAX_DEPTH;
|
||||
}
|
||||
|
||||
WARN_UNUSED
|
||||
inline error_code parser::allocate(size_t capacity, size_t max_depth) noexcept {
|
||||
//
|
||||
// Reallocate implementation and document if needed
|
||||
//
|
||||
error_code err;
|
||||
//
|
||||
// It is possible that we change max_depth without touching capacity, in
|
||||
// which case, we do not want to reallocate the document buffers.
|
||||
//
|
||||
bool need_doc_allocation{false};
|
||||
if (implementation) {
|
||||
need_doc_allocation = implementation->capacity() != capacity || !doc.tape;
|
||||
err = implementation->allocate(capacity, max_depth);
|
||||
} else {
|
||||
need_doc_allocation = true;
|
||||
err = simdjson::active_implementation->create_dom_parser_implementation(capacity, max_depth, implementation);
|
||||
}
|
||||
if (err) { return err; }
|
||||
if (need_doc_allocation) {
|
||||
err = doc.allocate(capacity);
|
||||
if (err) { return err; }
|
||||
}
|
||||
return SUCCESS;
|
||||
}
|
||||
|
||||
WARN_UNUSED
|
||||
inline bool parser::allocate_capacity(size_t capacity, size_t max_depth) noexcept {
|
||||
return !allocate(capacity, max_depth);
|
||||
}
|
||||
|
||||
inline error_code parser::ensure_capacity(size_t desired_capacity) noexcept {
|
||||
// If we don't have enough capacity, (try to) automatically bump it.
|
||||
// If the document was taken, reallocate that too.
|
||||
// Both in one if statement to minimize unlikely branching.
|
||||
if (unlikely(capacity() < desired_capacity || !doc.tape)) {
|
||||
if (desired_capacity > max_capacity()) {
|
||||
return error = CAPACITY;
|
||||
}
|
||||
return allocate(desired_capacity, max_depth());
|
||||
}
|
||||
|
||||
return SUCCESS;
|
||||
}
|
||||
|
||||
really_inline void parser::set_max_capacity(size_t max_capacity) noexcept {
|
||||
_max_capacity = max_capacity;
|
||||
}
|
||||
|
||||
} // namespace dom
|
||||
} // namespace simdjson
|
||||
|
||||
#endif // SIMDJSON_INLINE_PARSER_H
|
||||
@@ -0,0 +1,105 @@
|
||||
#ifndef SIMDJSON_INLINE_TAPE_REF_H
|
||||
#define SIMDJSON_INLINE_TAPE_REF_H
|
||||
|
||||
#include "simdjson/internal/tape_ref.h"
|
||||
#include <cstring>
|
||||
|
||||
namespace simdjson {
|
||||
namespace internal {
|
||||
|
||||
//
|
||||
// tape_ref inline implementation
|
||||
//
|
||||
really_inline tape_ref::tape_ref() noexcept : doc{nullptr}, json_index{0} {}
|
||||
really_inline tape_ref::tape_ref(const dom::document *_doc, size_t _json_index) noexcept : doc{_doc}, json_index{_json_index} {}
|
||||
|
||||
// Some value types have a specific on-tape word value. It can be faster
|
||||
// to check the type by doing a word-to-word comparison instead of extracting the
|
||||
// most significant 8 bits.
|
||||
|
||||
really_inline bool tape_ref::is_double() const noexcept {
|
||||
constexpr uint64_t tape_double = uint64_t(tape_type::DOUBLE)<<56;
|
||||
return doc->tape[json_index] == tape_double;
|
||||
}
|
||||
really_inline bool tape_ref::is_int64() const noexcept {
|
||||
constexpr uint64_t tape_int64 = uint64_t(tape_type::INT64)<<56;
|
||||
return doc->tape[json_index] == tape_int64;
|
||||
}
|
||||
really_inline bool tape_ref::is_uint64() const noexcept {
|
||||
constexpr uint64_t tape_uint64 = uint64_t(tape_type::UINT64)<<56;
|
||||
return doc->tape[json_index] == tape_uint64;
|
||||
}
|
||||
really_inline bool tape_ref::is_false() const noexcept {
|
||||
constexpr uint64_t tape_false = uint64_t(tape_type::FALSE_VALUE)<<56;
|
||||
return doc->tape[json_index] == tape_false;
|
||||
}
|
||||
really_inline bool tape_ref::is_true() const noexcept {
|
||||
constexpr uint64_t tape_true = uint64_t(tape_type::TRUE_VALUE)<<56;
|
||||
return doc->tape[json_index] == tape_true;
|
||||
}
|
||||
really_inline bool tape_ref::is_null_on_tape() const noexcept {
|
||||
constexpr uint64_t tape_null = uint64_t(tape_type::NULL_VALUE)<<56;
|
||||
return doc->tape[json_index] == tape_null;
|
||||
}
|
||||
|
||||
inline size_t tape_ref::after_element() const noexcept {
|
||||
switch (tape_ref_type()) {
|
||||
case tape_type::START_ARRAY:
|
||||
case tape_type::START_OBJECT:
|
||||
return matching_brace_index();
|
||||
case tape_type::UINT64:
|
||||
case tape_type::INT64:
|
||||
case tape_type::DOUBLE:
|
||||
return json_index + 2;
|
||||
default:
|
||||
return json_index + 1;
|
||||
}
|
||||
}
|
||||
really_inline tape_type tape_ref::tape_ref_type() const noexcept {
|
||||
return static_cast<tape_type>(doc->tape[json_index] >> 56);
|
||||
}
|
||||
really_inline uint64_t internal::tape_ref::tape_value() const noexcept {
|
||||
return doc->tape[json_index] & internal::JSON_VALUE_MASK;
|
||||
}
|
||||
really_inline uint32_t internal::tape_ref::matching_brace_index() const noexcept {
|
||||
return uint32_t(doc->tape[json_index]);
|
||||
}
|
||||
really_inline uint32_t internal::tape_ref::scope_count() const noexcept {
|
||||
return uint32_t((doc->tape[json_index] >> 32) & internal::JSON_COUNT_MASK);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
really_inline T tape_ref::next_tape_value() const noexcept {
|
||||
static_assert(sizeof(T) == sizeof(uint64_t), "next_tape_value() template parameter must be 64-bit");
|
||||
// Though the following is tempting...
|
||||
// return *reinterpret_cast<const T*>(&doc->tape[json_index + 1]);
|
||||
// It is not generally safe. It is safer, and often faster to rely
|
||||
// on memcpy. Yes, it is uglier, but it is also encapsulated.
|
||||
T x;
|
||||
memcpy(&x,&doc->tape[json_index + 1],sizeof(uint64_t));
|
||||
return x;
|
||||
}
|
||||
|
||||
really_inline uint32_t internal::tape_ref::get_string_length() const noexcept {
|
||||
size_t string_buf_index = size_t(tape_value());
|
||||
uint32_t len;
|
||||
memcpy(&len, &doc->string_buf[string_buf_index], sizeof(len));
|
||||
return len;
|
||||
}
|
||||
|
||||
really_inline const char * internal::tape_ref::get_c_str() const noexcept {
|
||||
size_t string_buf_index = size_t(tape_value());
|
||||
return reinterpret_cast<const char *>(&doc->string_buf[string_buf_index + sizeof(uint32_t)]);
|
||||
}
|
||||
|
||||
inline std::string_view internal::tape_ref::get_string_view() const noexcept {
|
||||
return std::string_view(
|
||||
get_c_str(),
|
||||
get_string_length()
|
||||
);
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
} // namespace simdjson
|
||||
|
||||
#endif // SIMDJSON_INLINE_TAPE_REF_H
|
||||
@@ -0,0 +1,181 @@
|
||||
#ifndef SIMDJSON_INTERNAL_DOM_PARSER_IMPLEMENTATION_H
|
||||
#define SIMDJSON_INTERNAL_DOM_PARSER_IMPLEMENTATION_H
|
||||
|
||||
#include "simdjson/common_defs.h"
|
||||
#include "simdjson/error.h"
|
||||
#include <memory>
|
||||
|
||||
namespace simdjson {
|
||||
|
||||
namespace dom {
|
||||
class document;
|
||||
} // namespace dom
|
||||
|
||||
namespace internal {
|
||||
|
||||
/**
|
||||
* An implementation of simdjson's DOM parser for a particular CPU architecture.
|
||||
*
|
||||
* This class is expected to be accessed only by pointer, and never move in memory (though the
|
||||
* pointer can move).
|
||||
*/
|
||||
class dom_parser_implementation {
|
||||
public:
|
||||
|
||||
/**
|
||||
* @private For internal implementation use
|
||||
*
|
||||
* Run a full JSON parse on a single document (stage1 + stage2).
|
||||
*
|
||||
* Guaranteed only to be called when capacity > document length.
|
||||
*
|
||||
* Overridden by each implementation.
|
||||
*
|
||||
* @param buf The json document to parse. *MUST* be allocated up to len + SIMDJSON_PADDING bytes.
|
||||
* @param len The length of the json document.
|
||||
* @return The error code, or SUCCESS if there was no error.
|
||||
*/
|
||||
WARN_UNUSED virtual error_code parse(const uint8_t *buf, size_t len, dom::document &doc) noexcept = 0;
|
||||
|
||||
/**
|
||||
* @private For internal implementation use
|
||||
*
|
||||
* Stage 1 of the document parser.
|
||||
*
|
||||
* Guaranteed only to be called when capacity > document length.
|
||||
*
|
||||
* Overridden by each implementation.
|
||||
*
|
||||
* @param buf The json document to parse.
|
||||
* @param len The length of the json document.
|
||||
* @param streaming Whether this is being called by parser::parse_many.
|
||||
* @return The error code, or SUCCESS if there was no error.
|
||||
*/
|
||||
WARN_UNUSED virtual error_code stage1(const uint8_t *buf, size_t len, bool streaming) noexcept = 0;
|
||||
|
||||
/**
|
||||
* @private For internal implementation use
|
||||
*
|
||||
* Stage 2 of the document parser.
|
||||
*
|
||||
* Called after stage1().
|
||||
*
|
||||
* Overridden by each implementation.
|
||||
*
|
||||
* @param doc The document to output to.
|
||||
* @return The error code, or SUCCESS if there was no error.
|
||||
*/
|
||||
WARN_UNUSED virtual error_code stage2(dom::document &doc) noexcept = 0;
|
||||
|
||||
/**
|
||||
* @private For internal implementation use
|
||||
*
|
||||
* Stage 2 of the document parser for parser::parse_many.
|
||||
*
|
||||
* Guaranteed only to be called after stage1().
|
||||
* Overridden by each implementation.
|
||||
*
|
||||
* @param doc The document to output to.
|
||||
* @return The error code, SUCCESS if there was no error, or EMPTY if all documents have been parsed.
|
||||
*/
|
||||
WARN_UNUSED virtual error_code stage2_next(dom::document &doc) noexcept = 0;
|
||||
|
||||
/**
|
||||
* Change the capacity of this parser.
|
||||
*
|
||||
* Generally used for reallocation.
|
||||
*
|
||||
* @param capacity The new capacity.
|
||||
* @param max_depth The new max_depth.
|
||||
* @return The error code, or SUCCESS if there was no error.
|
||||
*/
|
||||
virtual error_code set_capacity(size_t capacity) noexcept = 0;
|
||||
|
||||
/**
|
||||
* Change the max depth of this parser.
|
||||
*
|
||||
* Generally used for reallocation.
|
||||
*
|
||||
* @param capacity The new capacity.
|
||||
* @param max_depth The new max_depth.
|
||||
* @return The error code, or SUCCESS if there was no error.
|
||||
*/
|
||||
virtual error_code set_max_depth(size_t max_depth) noexcept = 0;
|
||||
|
||||
/**
|
||||
* Deallocate this parser.
|
||||
*/
|
||||
virtual ~dom_parser_implementation() = default;
|
||||
|
||||
/** Number of structural indices passed from stage 1 to stage 2 */
|
||||
uint32_t n_structural_indexes{0};
|
||||
/** Structural indices passed from stage 1 to stage 2 */
|
||||
std::unique_ptr<uint32_t[]> structural_indexes{};
|
||||
/** Next structural index to parse */
|
||||
uint32_t next_structural_index{0};
|
||||
|
||||
/**
|
||||
* The largest document this parser can support without reallocating.
|
||||
*
|
||||
* @return Current capacity, in bytes.
|
||||
*/
|
||||
really_inline size_t capacity() const noexcept;
|
||||
|
||||
/**
|
||||
* The maximum level of nested object and arrays supported by this parser.
|
||||
*
|
||||
* @return Maximum depth, in bytes.
|
||||
*/
|
||||
really_inline size_t max_depth() const noexcept;
|
||||
|
||||
/**
|
||||
* Ensure this parser has enough memory to process JSON documents up to `capacity` bytes in length
|
||||
* and `max_depth` depth.
|
||||
*
|
||||
* @param capacity The new capacity.
|
||||
* @param max_depth The new max_depth. Defaults to DEFAULT_MAX_DEPTH.
|
||||
* @return The error, if there is one.
|
||||
*/
|
||||
WARN_UNUSED inline error_code allocate(size_t capacity, size_t max_depth) noexcept;
|
||||
|
||||
protected:
|
||||
/**
|
||||
* The maximum document length this parser supports.
|
||||
*
|
||||
* Buffers are large enough to handle any document up to this length.
|
||||
*/
|
||||
size_t _capacity{0};
|
||||
|
||||
/**
|
||||
* The maximum depth (number of nested objects and arrays) supported by this parser.
|
||||
*
|
||||
* Defaults to DEFAULT_MAX_DEPTH.
|
||||
*/
|
||||
size_t _max_depth{0};
|
||||
}; // class dom_parser_implementation
|
||||
|
||||
really_inline size_t dom_parser_implementation::capacity() const noexcept {
|
||||
return _capacity;
|
||||
}
|
||||
|
||||
really_inline size_t dom_parser_implementation::max_depth() const noexcept {
|
||||
return _max_depth;
|
||||
}
|
||||
|
||||
WARN_UNUSED
|
||||
inline error_code dom_parser_implementation::allocate(size_t capacity, size_t max_depth) noexcept {
|
||||
if (this->max_depth() != max_depth) {
|
||||
error_code err = set_max_depth(max_depth);
|
||||
if (err) { return err; }
|
||||
}
|
||||
if (_capacity != capacity) {
|
||||
error_code err = set_capacity(capacity);
|
||||
if (err) { return err; }
|
||||
}
|
||||
return SUCCESS;
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
} // namespace simdjson
|
||||
|
||||
#endif // SIMDJSON_INTERNAL_DOM_PARSER_IMPLEMENTATION_H
|
||||
@@ -5,7 +5,8 @@
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
|
||||
namespace simdjson::internal {
|
||||
namespace simdjson {
|
||||
namespace internal {
|
||||
|
||||
class escape_json_string;
|
||||
|
||||
@@ -48,7 +49,7 @@ inline std::ostream& operator<<(std::ostream& out, const escape_json_string &une
|
||||
if ((unsigned char)unescaped.str[i] <= 0x1F) {
|
||||
// TODO can this be done once at the beginning, or will it mess up << char?
|
||||
std::ios::fmtflags f(out.flags());
|
||||
out << "\\u" << std::hex << std::setw(4) << std::setfill('0') << static_cast<int>(unescaped.str[i]);
|
||||
out << "\\u" << std::hex << std::setw(4) << std::setfill('0') << int(unescaped.str[i]);
|
||||
out.flags(f);
|
||||
} else {
|
||||
out << unescaped.str[i];
|
||||
@@ -58,6 +59,7 @@ inline std::ostream& operator<<(std::ostream& out, const escape_json_string &une
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace simdjson::internal
|
||||
} // namespace internal
|
||||
} // namespace simdjson
|
||||
|
||||
#endif // SIMDJSON_INTERNAL_JSONFORMATUTILS_H
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
#ifndef SIMDJSON_INTERNAL_TAPE_REF_H
|
||||
#define SIMDJSON_INTERNAL_TAPE_REF_H
|
||||
|
||||
#include "simdjson/internal/tape_type.h"
|
||||
|
||||
namespace simdjson {
|
||||
|
||||
namespace dom {
|
||||
class document;
|
||||
}
|
||||
|
||||
namespace internal {
|
||||
|
||||
constexpr const uint64_t JSON_VALUE_MASK = 0x00FFFFFFFFFFFFFF;
|
||||
constexpr const uint32_t JSON_COUNT_MASK = 0xFFFFFF;
|
||||
|
||||
/**
|
||||
* A reference to an element on the tape. Internal only.
|
||||
*/
|
||||
class tape_ref {
|
||||
public:
|
||||
really_inline tape_ref() noexcept;
|
||||
really_inline tape_ref(const dom::document *doc, size_t json_index) noexcept;
|
||||
inline size_t after_element() const noexcept;
|
||||
really_inline tape_type tape_ref_type() const noexcept;
|
||||
really_inline uint64_t tape_value() const noexcept;
|
||||
really_inline bool is_double() const noexcept;
|
||||
really_inline bool is_int64() const noexcept;
|
||||
really_inline bool is_uint64() const noexcept;
|
||||
really_inline bool is_false() const noexcept;
|
||||
really_inline bool is_true() const noexcept;
|
||||
really_inline bool is_null_on_tape() const noexcept;// different name to avoid clash with is_null.
|
||||
really_inline uint32_t matching_brace_index() const noexcept;
|
||||
really_inline uint32_t scope_count() const noexcept;
|
||||
template<typename T>
|
||||
really_inline T next_tape_value() const noexcept;
|
||||
really_inline uint32_t get_string_length() const noexcept;
|
||||
really_inline const char * get_c_str() const noexcept;
|
||||
inline std::string_view get_string_view() const noexcept;
|
||||
|
||||
/** The document this element references. */
|
||||
const dom::document *doc;
|
||||
|
||||
/** The index of this element on `doc.tape[]` */
|
||||
size_t json_index;
|
||||
};
|
||||
|
||||
} // namespace internal
|
||||
} // namespace simdjson
|
||||
|
||||
#endif // SIMDJSON_INTERNAL_TAPE_REF_H
|
||||
@@ -0,0 +1,28 @@
|
||||
#ifndef SIMDJSON_INTERNAL_TAPE_TYPE_H
|
||||
#define SIMDJSON_INTERNAL_TAPE_TYPE_H
|
||||
|
||||
namespace simdjson {
|
||||
namespace internal {
|
||||
|
||||
/**
|
||||
* The possible types in the tape.
|
||||
*/
|
||||
enum class tape_type {
|
||||
ROOT = 'r',
|
||||
START_ARRAY = '[',
|
||||
START_OBJECT = '{',
|
||||
END_ARRAY = ']',
|
||||
END_OBJECT = '}',
|
||||
STRING = '"',
|
||||
INT64 = 'l',
|
||||
UINT64 = 'u',
|
||||
DOUBLE = 'd',
|
||||
TRUE_VALUE = 't',
|
||||
FALSE_VALUE = 'f',
|
||||
NULL_VALUE = 'n'
|
||||
}; // enum class tape_type
|
||||
|
||||
} // namespace internal
|
||||
} // namespace simdjson
|
||||
|
||||
#endif // SIMDJSON_INTERNAL_TAPE_TYPE_H
|
||||
@@ -1,13 +1,6 @@
|
||||
#ifndef SIMDJSON_JSONIOUTIL_H
|
||||
#define SIMDJSON_JSONIOUTIL_H
|
||||
|
||||
#include <exception>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#include "simdjson/common_defs.h"
|
||||
#include "simdjson/padded_string.h"
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user